text:
using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;

namespace Bvs.Common.Utility
{
    internal class VirtualizingTilePanel : VirtualizingPanel, IScrollInfo
    {
        // Dependency property that controls the size of the child elements
        public static readonly DependencyProperty ChildSizeProperty
            = DependencyProperty.RegisterAttached("ChildSize", typeof(double), typeof(VirtualizingTilePanel),
                new FrameworkPropertyMetadata(200.0d, FrameworkPropertyMetadataOptions.AffectsMeasure |
                                                      FrameworkPropertyMetadataOptions.AffectsArrange));

        public static readonly DependencyProperty VerticalOffsetLineProperty = DependencyProperty.Register(
            "VerticalOffsetLine", typeof(int), typeof(VirtualizingTilePanel), new PropertyMetadata(10));

        public VirtualizingTilePanel()
        {
            // For use in the IScrollInfo implementation
            RenderTransform = _trans;
        }

        public int VerticalOffsetLine
        {
            get { return (int) GetValue(VerticalOffsetLineProperty); }
            set { SetValue(VerticalOffsetLineProperty, value); }
        }

        // Accessor for the child size dependency property
        public double ChildSize
        {
            get { return (double) GetValue(ChildSizeProperty); }
            set { SetValue(ChildSizeProperty, value); }
        }

        /// <summary>
        ///     Measure the children
        /// </summary>
        /// <param name="availableSize">Size available</param>
        /// <returns>Size desired</returns>
        protected override Size MeasureOverride(Size availableSize)
        {
            UpdateScrollInfo(availableSize);

            // Figure out range that's visible based on layout algorithm
            int firstVisibleItemIndex, lastVisibleItemIndex;
            GetVisibleRange(out firstVisibleItemIndex, out lastVisibleItemIndex);

            // We need to access InternalChildren before the generator to work around a bug
            var children = InternalChildren;
            var generator = ItemContainerGenerator;

            // Get the generator position of the first visible data item
            var startPos = generator.GeneratorPositionFromIndex(firstVisibleItemIndex);

            // Get index where we'd insert the child for this position. If the item is realized
            // (position.Offset == 0), it's just position.Index, otherwise we have to add one to
            // insert after the corresponding child
            var childIndex = startPos.Offset == 0 ? startPos.Index : startPos.Index + 1;

            using (generator.StartAt(startPos, GeneratorDirection.Forward, true))
            {
                for (var itemIndex = firstVisibleItemIndex;
                    itemIndex <= lastVisibleItemIndex;
                    ++itemIndex, ++childIndex)
                {
                    bool newlyRealized;

                    // Get or create the child
                    var child = generator.GenerateNext(out newlyRealized) as UIElement;
                    if (newlyRealized)
                    {
                        // Figure out if we need to insert the child at the end or somewhere in the middle
                        if (childIndex >= children.Count)
                            AddInternalChild(child);
                        else
                            InsertInternalChild(childIndex, child);
                        generator.PrepareItemContainer(child);
                    }
                    else
                    {
                        // The child has already been created, let's be sure it's in the right spot
                        Debug.Assert(child == children[childIndex], "Wrong child was generated");
                    }

                    // Measurements will depend on layout algorithm
                    child.Measure(GetChildSize());
                }
            }

            // Note: this could be deferred to idle time for efficiency
            CleanUpItems(firstVisibleItemIndex, lastVisibleItemIndex);

            return availableSize;
        }

        /// <summary>
        ///     Arrange the children
        /// </summary>
        /// <param name="finalSize">Size available</param>
        /// <returns>Size used</returns>
        protected override Size ArrangeOverride(Size finalSize)
        {
            var generator = ItemContainerGenerator;

            UpdateScrollInfo(finalSize);

            for (var i = 0; i < Children.Count; i++)
            {
                var child = Children[i];

                // Map the child offset to an item offset
                var itemIndex = generator.IndexFromGeneratorPosition(new GeneratorPosition(i, 0));

                ArrangeChild(itemIndex, child, finalSize);
            }

            return finalSize;
        }

        /// <summary>
        ///     Revirtualize items that are no longer visible
        /// </summary>
        /// <param name="minDesiredGenerated">first item index that should be visible</param>
        /// <param name="maxDesiredGenerated">last item index that should be visible</param>
        private void CleanUpItems(int minDesiredGenerated, int maxDesiredGenerated)
        {
            var children = InternalChildren;
            var generator = ItemContainerGenerator;

            for (var i = children.Count - 1; i >= 0; i--)
            {
                var childGeneratorPos = new GeneratorPosition(i, 0);
                var itemIndex = generator.IndexFromGeneratorPosition(childGeneratorPos);
                if (itemIndex < minDesiredGenerated || itemIndex > maxDesiredGenerated)
                {
                    generator.Remove(childGeneratorPos, 1);
                    RemoveInternalChildRange(i, 1);
                }
            }
        }

        /// <summary>
        ///     When items are removed, remove the corresponding UI if necessary
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        protected override void OnItemsChanged(object sender, ItemsChangedEventArgs args)
        {
            switch (args.Action)
            {
                case NotifyCollectionChangedAction.Remove:
                case NotifyCollectionChangedAction.Replace:
                case NotifyCollectionChangedAction.Move:
                    RemoveInternalChildRange(args.Position.Index, args.ItemUICount);
                    break;
            }
        }

        #region Layout specific code

        // I've isolated the layout specific code to this region. If you want to do something other than tiling, this is
        // where you'll make your changes

        /// <summary>
        ///     Calculate the extent of the view based on the available size
        /// </summary>
        /// <param name="availableSize">available size</param>
        /// <param name="itemCount">number of data items</param>
        /// <returns></returns>
        private Size CalculateExtent(Size availableSize, int itemCount)
        {
            var childrenPerRow = CalculateChildrenPerRow(availableSize);

            // See how big we are
            return new Size(childrenPerRow * ChildSize,
                ChildSize * Math.Ceiling((double) itemCount / childrenPerRow));
        }

        /// <summary>
        ///     Get the range of children that are visible
        /// </summary>
        /// <param name="firstVisibleItemIndex">The item index of the first visible item</param>
        /// <param name="lastVisibleItemIndex">The item index of the last visible item</param>
        private void GetVisibleRange(out int firstVisibleItemIndex, out int lastVisibleItemIndex)
        {
            var childrenPerRow = CalculateChildrenPerRow(_extent);

            firstVisibleItemIndex = (int) Math.Floor(_offset.Y / ChildSize) * childrenPerRow;
            lastVisibleItemIndex = (int) Math.Ceiling((_offset.Y + _viewport.Height) / ChildSize) * childrenPerRow - 1;

            var itemsControl = ItemsControl.GetItemsOwner(this);
            var itemCount = itemsControl.HasItems ? itemsControl.Items.Count : 0;
            if (lastVisibleItemIndex >= itemCount)
                lastVisibleItemIndex = itemCount - 1;
        }

        /// <summary>
        ///     Get the size of the children. We assume they are all the same
        /// </summary>
        /// <returns>The size</returns>
        private Size GetChildSize()
        {
            return new Size(ChildSize, ChildSize);
        }

        /// <summary>
        ///     Position a child
        /// </summary>
        /// <param name="itemIndex">The data item index of the child</param>
        /// <param name="child">The element to position</param>
        /// <param name="finalSize">The size of the panel</param>
        private void ArrangeChild(int itemIndex, UIElement child, Size finalSize)
        {
            var childrenPerRow = CalculateChildrenPerRow(finalSize);

            var row = itemIndex / childrenPerRow;
            var column = itemIndex % childrenPerRow;

            child.Arrange(new Rect(column * ChildSize, row * ChildSize, ChildSize, ChildSize));
        }

        /// <summary>
        ///     Helper function for tiling layout
        /// </summary>
        /// <param name="availableSize">Size available</param>
        /// <returns></returns>
        private int CalculateChildrenPerRow(Size availableSize)
        {
            // Figure out how many children fit on each row
            int childrenPerRow;
            if (availableSize.Width == double.PositiveInfinity)
                childrenPerRow = Children.Count;
            else
                childrenPerRow = Math.Max(1, (int) Math.Floor(availableSize.Width / ChildSize));
            return childrenPerRow;
        }

        #endregion

        #region IScrollInfo implementation

        // See Ben Constable's series of posts at http://blogs.msdn.com/bencon/

        private void UpdateScrollInfo(Size availableSize)
        {
            // See how many items there are
            var itemsControl = ItemsControl.GetItemsOwner(this);
            var itemCount = itemsControl.HasItems ? itemsControl.Items.Count : 0;

            var extent = CalculateExtent(availableSize, itemCount);
            // Update extent
            if (extent != _extent)
            {
                _extent = extent;
                if (ScrollOwner != null)
                    ScrollOwner.InvalidateScrollInfo();
            }

            // Update viewport
            if (availableSize != _viewport)
            {
                _viewport = availableSize;
                if (ScrollOwner != null)
                    ScrollOwner.InvalidateScrollInfo();
            }
        }

        public ScrollViewer ScrollOwner { get; set; }

        public bool CanHorizontallyScroll { get; set; } = false;

        public bool CanVerticallyScroll { get; set; } = false;

        public double HorizontalOffset
        {
            get { return _offset.X; }
        }

        public double VerticalOffset
        {
            get { return _offset.Y; }
        }

        public double ExtentHeight
        {
            get { return _extent.Height; }
        }

        public double ExtentWidth
        {
            get { return _extent.Width; }
        }

        public double ViewportHeight
        {
            get { return _viewport.Height; }
        }

        public double ViewportWidth
        {
            get { return _viewport.Width; }
        }

        public void LineUp()
        {
            SetVerticalOffset(VerticalOffset - VerticalOffsetLine);
        }

        public void LineDown()
        {
            SetVerticalOffset(VerticalOffset + VerticalOffsetLine);
        }

        public void PageUp()
        {
            SetVerticalOffset(VerticalOffset - _viewport.Height);
        }

        public void PageDown()
        {
            SetVerticalOffset(VerticalOffset + _viewport.Height);
        }

        public void MouseWheelUp()
        {
            SetVerticalOffset(VerticalOffset - VerticalOffsetLine);
        }

        public void MouseWheelDown()
        {
            SetVerticalOffset(VerticalOffset + VerticalOffsetLine);
        }

        public void LineLeft()
        {
            throw new InvalidOperationException();
        }

        public void LineRight()
        {
            throw new InvalidOperationException();
        }

        public Rect MakeVisible(Visual visual, Rect rectangle)
        {
            return new Rect();
        }

        public void MouseWheelLeft()
        {
            throw new InvalidOperationException();
        }

        public void MouseWheelRight()
        {
            throw new InvalidOperationException();
        }

        public void PageLeft()
        {
            throw new InvalidOperationException();
        }

        public void PageRight()
        {
            throw new InvalidOperationException();
        }

        public void SetHorizontalOffset(double offset)
        {
            throw new InvalidOperationException();
        }

        public void SetVerticalOffset(double offset)
        {
            if (offset < 0 || _viewport.Height >= _extent.Height)
            {
                offset = 0;
            }
            else
            {
                if (offset + _viewport.Height >= _extent.Height)
                    offset = _extent.Height - _viewport.Height;
            }

            _offset.Y = offset;

            if (ScrollOwner != null)
                ScrollOwner.InvalidateScrollInfo();

            _trans.Y = -offset;

            // Force us to realize the correct children
            InvalidateMeasure();
        }

        private readonly TranslateTransform _trans = new TranslateTransform();
        private Size _extent = new Size(0, 0);
        private Size _viewport = new Size(0, 0);
        private Point _offset;

        #endregion
    }
}


text:
define(function () {

    'use strict';

    var env = {};

    env.getEnvironment = function (callback) {
        // FIXME: we assume this code runs on the same thread as the
        // javascript executed from sugar-toolkit-gtk3 (python)

        if (env.isStandalone()) {
            setTimeout(function () {
                callback(null, {});
            }, 0);
        } else {
            var environmentCallback = function () {
                callback(null, window.top.sugar.environment);
            };

            if (window.top.sugar) {
                setTimeout(function () {
                    environmentCallback();
                }, 0);
            } else {
                window.top.sugar = {};
                window.top.sugar.onEnvironmentSet = function () {
                    environmentCallback();
                };
            }
        }
    };

    env.getObjectId = function (callback) {
        var objectId;
        env.getEnvironment(function (error, environment) {
            objectId = environment.objectId;
            callback(objectId);
        });
    };

    env.getURLScheme = function () {
        return window.location.protocol;
    };

    env.isStandalone = function () {
        var webActivityURLScheme = "activity:";
        var currentURLScheme = env.getURLScheme();

        return currentURLScheme !== webActivityURLScheme;
    };

    return env;
});

redpajama_set_name: RedPajamaGithub


text:
package testutil

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
	"os/exec"
	"strings"
	"text/template"
	"unicode"
)

// dedent is a helper function that trims repeated, leading spaces from several
// lines of text. This is useful for long, inline commands that are indented to
// match the surrounding code but should be interpreted without the space:
// e.g.:
// func() {
//   BashCmd(`
//     cat <<EOF
//     This is a test
//     EOF
//   `)
// }
// Should evaluate:
// $ cat <<EOF
// > This is a test
// > EOF
// not:
// $      cat <<EOF
// >      This is a test
// >      EOF  # doesn't terminate heredoc b/c of space
// such that the heredoc doesn't end properly
func dedent(cmd string) string {
	notSpace := func(r rune) bool {
		return !unicode.IsSpace(r)
	}

	prefix := "-" // non-space character indicates no prefix has been established
	s := bufio.NewScanner(strings.NewReader(cmd))
	var dedentedCmd bytes.Buffer
	for s.Scan() {
		i := strings.IndexFunc(s.Text(), notSpace)
		if i == -1 {
			continue // blank line (or spaces-only line)--ignore completely
		} else if prefix == "-" {
			prefix = s.Text()[:i] // first non-blank line, set prefix
			dedentedCmd.WriteString(s.Text()[i:])
			dedentedCmd.WriteRune('\n')
		} else if strings.HasPrefix(s.Text(), prefix) {
			dedentedCmd.WriteString(s.Text()[len(prefix):]) // remove prefix
			dedentedCmd.WriteRune('\n')
		} else {
			fmt.Fprintf(os.Stderr,
				"\nWARNING: the line\n  %q\ncannot be dedented as missing the prefix %q\n",
				s.Text(), prefix)
			return cmd // no common prefix--break early
		}
	}
	return dedentedCmd.String()
}

// Cmd is a convenience function that replaces exec.Command. It's both shorter
// and it uses the current process's stderr as output for the command, which
// makes debugging failures much easier (i.e. you get an error message
// rather than "exit status 1")
func Cmd(name string, args ...string) *exec.Cmd {
	cmd := exec.Command(name, args...)
	cmd.Stderr = os.Stderr
	// for convenience, simulate hitting "enter" after any prompt. This can easily
	// be replaced
	cmd.Stdin = strings.NewReader("\n")
	cmd.Env = os.Environ()
	return cmd
}

// BashCmd is a convenience function that:
// 1. Performs a Go template substitution on 'cmd' using the strings in 'subs'
// 2. Returns a command that runs the result string from 1 as a Bash script
func BashCmd(cmd string, subs ...string) *exec.Cmd {
	if len(subs)%2 == 1 {
		panic("some variable does not have a corresponding value")
	}

	// copy 'subs' into a map
	subsMap := make(map[string]string)
	for i := 0; i < len(subs); i += 2 {
		subsMap[subs[i]] = subs[i+1]
	}

	// Warn users that they must install 'match' if they want to run tests with
	// this library, and enable 'pipefail' so that if any 'match' in a chain
	// fails, the whole command fails.
	buf := &bytes.Buffer{}
	buf.WriteString(`
set -e -o pipefail

# Try to ignore pipefail errors (encountered when writing to a closed pipe).
# Processes like 'yes' are essentially guaranteed to hit this, and because of
# -e -o pipefail they will crash the whole script. We need these options,
# though, for 'match' to work, so for now we work around pipefail errors on a
# cmd-by-cmd basis. See "The Infamous SIGPIPE Signal"
# http://www.tldp.org/LDP/lpg/node20.html
pipeerr=141 # typical error code returned by unix utils when SIGPIPE is raised
function yes {
	/usr/bin/yes || test "$?" -eq "${pipeerr}"
}
export -f yes # use in subshells too

which match >/dev/null || {
	echo "You must have 'match' installed to run these tests. Please run:" >&2
	echo "  go install ./src/testing/match" >&2
	exit 1
}`)
	buf.WriteRune('\n')

	// do the substitution
	template.Must(template.New("").Parse(dedent(cmd))).Execute(buf, subsMap)
	res := exec.Command("/bin/bash")
	res.Stderr = os.Stderr
	// useful for debugging, but makes logs too noisy:
	// res.Stdout = os.Stdout
	res.Stdin = buf
	res.Env = os.Environ()
	return res
}


text:
package command

import (
	"flag"
	"fmt"
	"strings"

	"github.com/hashicorp/vault/api"
	"github.com/hashicorp/vault/meta"
)

// UnwrapCommand is a Command that behaves like ReadCommand but specifically
// for unwrapping cubbyhole-wrapped secrets
type UnwrapCommand struct {
	meta.Meta
}

func (c *UnwrapCommand) Run(args []string) int {
	var format string
	var field string
	var err error
	var secret *api.Secret
	var flags *flag.FlagSet
	flags = c.Meta.FlagSet("unwrap", meta.FlagSetDefault)
	flags.StringVar(&format, "format", "table", "")
	flags.StringVar(&field, "field", "", "")
	flags.Usage = func() { c.Ui.Error(c.Help()) }
	if err := flags.Parse(args); err != nil {
		return 1
	}

	var tokenID string

	args = flags.Args()
	switch len(args) {
	case 0:
	case 1:
		tokenID = args[0]
	default:
		c.Ui.Error("unwrap expects zero or one argument (the ID of the wrapping token)")
		flags.Usage()
		return 1
	}

	client, err := c.Client()
	if err != nil {
		c.Ui.Error(fmt.Sprintf(
			"Error initializing client: %s", err))
		return 2
	}

	secret, err = client.Logical().Unwrap(tokenID)
	if err != nil {
		c.Ui.Error(err.Error())
		return 1
	}
	if secret == nil {
		c.Ui.Error("Server gave empty response or secret returned was empty")
		return 1
	}

	// Handle single field output
	if field != "" {
		return PrintRawField(c.Ui, secret, field)
	}

	// Check if the original was a list response and format as a list if so
	if secret.Data != nil &&
		len(secret.Data) == 1 &&
		secret.Data["keys"] != nil {
		_, ok := secret.Data["keys"].([]interface{})
		if ok {
			return OutputList(c.Ui, format, secret)
		}
	}
	return OutputSecret(c.Ui, format, secret)
}

func (c *UnwrapCommand) Synopsis() string {
	return "Unwrap a wrapped secret"
}

func (c *UnwrapCommand) Help() string {
	helpText := `
Usage: vault unwrap [options] <wrapping token ID>

  Unwrap a wrapped secret.

  Unwraps the data wrapped by the given token ID. The returned result is the
  same as a 'read' operation on a non-wrapped secret.

General Options:
` + meta.GeneralOptionsUsage() + `
Read Options:

  -format=table           The format for output. By default it is a whitespace-
                          delimited table. This can also be json or yaml.

  -field=field            If included, the raw value of the specified field
                          will be output raw to stdout.

`
	return strings.TrimSpace(helpText)
}


text:
import {createSelector} from 'reselect';

/**
 * Direct selector to the languageToggle state domain
 */
const selectLanguage = (state) => state.get('language');

/**
 * Select the language locale
 */

const makeSelectLocale = () => createSelector(
    selectLanguage,
    (languageState) => languageState.get('locale')
);

export {
    selectLanguage,
    makeSelectLocale
};


text:
$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "")
Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan
. "$PSScriptRoot\constants.ps1"

Describe "$CommandName Unit Tests" -Tag 'UnitTests' {
    Context "Validate parameters" {
        [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')}
        [object[]]$knownParameters = 'SqlInstance','SqlCredential','InputObject','AgentLogLevel','AgentMailType','AgentShutdownWaitTime','DatabaseMailProfile','ErrorLogFile','IdleCpuDuration','IdleCpuPercentage','CpuPolling','LocalHostAlias','LoginTimeout','MaximumHistoryRows','MaximumJobHistoryRows','NetSendRecipient','ReplaceAlertTokens','SaveInSentFolder','SqlAgentAutoStart','SqlAgentMailProfile','SqlAgentRestart','SqlServerRestart','WriteOemErrorLog','EnableException'
        $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters
        It "Should only contain our specific parameters" {
            (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0
        }
    }
}
Describe "$CommandName Integration Tests" -Tag "IntegrationTests" {
    $results = Set-DbaAgentServer -SqlInstance $script:instance2 -MaximumHistoryRows 10000 -MaximumJobHistoryRows 100
    It "changes agent server job history properties to 10000 / 100" {
        $results.MaximumHistoryRows | Should Be 10000
        $results.MaximumJobHistoryRows | Should Be 100
    }

    $results = Set-DbaAgentServer -SqlInstance $script:instance2 -CpuPolling Enabled
    It "changes agent server CPU Polling to true" {
        $results.IsCpuPollingEnabled | Should Be $true
    }

    $results = Set-DbaAgentServer -SqlInstance $script:instance2 -CpuPolling Disabled
    It "changes agent server CPU Polling to false" {
        $results.IsCpuPollingEnabled | Should Be $false
    }
}


text:
title: Dinner & After Party!
author: Philippe
twitter: pcreux
layout: post
published: true
---

Hey Folks!

We are very happy to invite you to the Rulu After Party & Dinner on Friday 22nd
at 18h00.

The party will be held 15 minutes away walking from the
conference venue in a Gourmet Restaurant & Pub called "[Le
Koodeta](http://goo.gl/maps/5Qdi)"
featuring a large patio with olive trees and an outdoor bar.

The [Lyon Ruby Brigade](http://lyonrb.fr) is sponsoring the dinner! Here is the menu (fr):

## Rulu 2012 Dinner Menu

### ENTREE

* verrine minestrone de tomate au basilic
* verrine de mousse de chèvre et ricotta aus asperges vertes
* club sandwich aux thon
* club sandwich aux oeufs mimosa et jambon cru
* cake aux olives verte
* cake provençale

### CHAUD

* brochette de canard aux pruneaux
* petit boudin noir, blanc et volaille
* rôti de porc aux pleurottes et moutarde au miel
* beignets de calamars sauce tartare
* accompagnements: ratatouille et riz pilaf

### DESSERT

* soupe d'ananas menthe poivré
* fondant au chocolat
* mousse de fruits rouges

And wine.

Please note that while the dinner comes with your Rulu 2012 ticket, you'll have to pay for drinks.

A good party requires good music, so we've just created the
[collaborative playlist Rulu 2012](http://open.spotify.com/user/pcreux/playlist/6AxDMjyQCCU6WIwfzdA3b0) on Spotify. Go add music you'd like people to
listen to during Rulu breaks, lunch, dinner & party! :)

See you in about a week!


text:
.mblDomButtonBlackLeftArrow16 {
	position: relative;
	width: 16px;
	height: 16px;
}
.mblDomButtonBlackLeftArrow16 > div {
	position: absolute;
	left: 0px;
	clip: rect(0px 12px 16px 4px);
}
.mblDomButtonBlackLeftArrow16 > div > div {
	position: absolute;
	top: 3px;
	left: 6px;
	width: 10px;
	height: 10px;
	margin: 0px;
	font-size: 1px;
	background-color: black;
	-webkit-transform: scaleY(0.5) rotate(45deg);
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>Saltr iOS SDK: <SLTBoardLayerDelegate> Protocol Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Saltr iOS SDK
    1.0

Main Page

Related Pages

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

Instance Methods |
List of all members

<SLTBoardLayerDelegate> Protocol Reference

Protocol.
 More...

#import <SLTBoardLayer.h>

Inheritance diagram for <SLTBoardLayerDelegate>:

  <map id="<SLTBoardLayerDelegate>_map" name="<SLTBoardLayerDelegate>_map">
<area href="interface_s_l_t_board_layer.html" title="The SLTBoardLayer class represents the game board's layer. " alt="SLTBoardLayer" shape="rect" coords="175,112,340,136"/>
<area href="interface_s_l_t2_d_board_layer.html" title="The SLT2DBoardLayer class represents the game 2D board's layer. " alt="SLT2DBoardLayer" shape="rect" coords="0,168,165,192"/>
<area href="interface_s_l_t2_d_board_layer.html" title="The SLT2DBoardLayer class represents the game 2D board's layer. " alt="SLT2DBoardLayer" shape="rect" coords="175,168,340,192"/>
<area href="interface_s_l_t_matching_board_layer.html" title="The SLTMatchingBoardLayer class represents the matching board. " alt="SLTMatchingBoardLayer" shape="rect" coords="350,168,515,192"/>
</map>

Instance Methods

(void) 	- regenerate

Detailed Description

Protocol.

The documentation for this protocol was generated from the following file:

build/bin/Saltr.v.1.3.1/include/SLTBoardLayer.h

<address class="footer">
Generated on Wed Feb 4 2015 11:13:42 for Saltr iOS SDK by

 1.8.9.1
</address>


text:
using ES5.Script.EcmaScript.Bindings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ES5.Script.EcmaScript.Objects
{
    /**
    * Да се пренапишат всички операции по итерация върху масива като ...
    */
    public partial class GlobalObject : EcmaScriptObject
    {
        public EcmaScriptFunctionObject DefaultCompareInstance { get; set; }

        public EcmaScriptObject CreateArray()
        {
            var result = Get("Array") as EcmaScriptObject;
            if (result != null) return result;

            result = new EcmaScriptArrayObjectObject(this) { Class = "Function" };
            result.Prototype = FunctionPrototype;
            Values.Add("Array", PropertyValue.NotEnum(result));

            ArrayPrototype = new EcmaScriptObject(this) { Class = "Array" };
            ArrayPrototype.Prototype = ObjectPrototype;

            result.Values["prototype"] = PropertyValue.NotAllFlags(ArrayPrototype);
            result.Values.Add("isArray", PropertyValue.NotEnum(new EcmaScriptFunctionObject(this, "isArray", ArrayIsArray, 1)));

            DefaultCompareInstance = new EcmaScriptFunctionObject(this, "defaultCompare", DefaultCompare, 2);
            ArrayPrototype.Values["constructor"] = PropertyValue.NotEnum(result);
            //ArrayPrototype.Values["length"] = PropertyValue.NotAllFlags(0);
            ArrayPrototype.Values.Add("toString", PropertyValue.NotEnum(new EcmaScriptFunctionObject(this, "toString", ArrayToString, 0, false, true)));
            ArrayPrototype.Values.Add("toLocaleString", PropertyValue.NotEnum(new EcmaScriptFunctionObject(this, "toLocaleString", ArrayToLocaleString, 0, false, true)));
            ArrayPrototype.Values.Add("concat", PropertyValue.NotEnum(new EcmaScriptFunctionObject(this, "concat", ArrayConcat, 1, false, true)));
            ArrayPrototype.Values.Add("join", PropertyValue.NotEnum(new EcmaScriptFunctionObject(this, "join", ArrayJoin, 1, false, true)));
            ArrayPrototype.Values.Add("pop", PropertyValue.NotEnum(new EcmaScriptFunctionObject(this, "pop", ArrayPop, 0, false, true)));
            ArrayPrototype.Values.Add("push", PropertyValue.NotEnum(new EcmaScriptFunctionObject(this, "push", ArrayPush, 1, false, true)));
            ArrayPrototype.Values.Add("reverse", PropertyValue.NotEnum(new EcmaScriptFunctionObject(this, "reverse", ArrayReverse, 0, false, true)));
            ArrayPrototype.Values.Add("shift", PropertyValue.NotEnum(new EcmaScriptFunctionObject(this, "shift", ArrayShift, 0, false, true)));
            ArrayPrototype.Values.Add("slice", PropertyValue.NotEnum(new EcmaScriptFunctionObject(this, "slice", ArraySlice, 2, false, true)));
            ArrayPrototype.Values.Add("sort", PropertyValue.NotEnum(new EcmaScriptFunctionObject(this, "sort", ArraySort, 1, false, true)));
            ArrayPrototype.Values.Add("splice", PropertyValue.NotEnum(new EcmaScriptFunctionObject(this, "splice", ArraySplice, 2, false, true)));
            ArrayPrototype.Values.Add("unshift", PropertyValue.NotEnum(new EcmaScriptFunctionObject(this, "unshift", ArrayUnshift, 1, false, true)));

            ArrayPrototype.Values.Add("indexOf", PropertyValue.NotEnum(new EcmaScriptFunctionObject(this, "indexOf", ArrayIndexOf, 1, false, true)));
            ArrayPrototype.Values.Add("lastIndexOf", PropertyValue.NotEnum(new EcmaScriptFunctionObject(this, "lastIndexOf", ArrayLastIndexOf, 1, false, true)));
            ArrayPrototype.Values.Add("every", PropertyValue.NotEnum(new EcmaScriptFunctionObject(this, "every", ArrayEvery, 1, false, true)));
            ArrayPrototype.Values.Add("some", PropertyValue.NotEnum(new EcmaScriptFunctionObject(this, "some", ArraySome, 1, false, true)));
            ArrayPrototype.Values.Add("forEach", PropertyValue.NotEnum(new EcmaScriptFunctionObject(this, "forEach", ArrayForeach, 1, false, true)));
            ArrayPrototype.Values.Add("map", PropertyValue.NotEnum(new EcmaScriptFunctionObject(this, "map", ArrayMap, 1, false, true)));
            ArrayPrototype.Values.Add("filter", PropertyValue.NotEnum(new EcmaScriptFunctionObject(this, "filter", ArrayFilter, 1, false, true)));
            ArrayPrototype.Values.Add("reduce", PropertyValue.NotEnum(new EcmaScriptFunctionObject(this, "reduce", ArrayReduce, 1, false, true)));
            ArrayPrototype.Values.Add("reduceRight", PropertyValue.NotEnum(new EcmaScriptFunctionObject(this, "reduceRight", ArrayReduceRight, 1, false, true)));

            return result;
        }

        public object ArrayCtor(ExecutionContext aCaller, object aSelf, params object[] args)
        {
            if ((args.Length == 1) && ((args[0] is Int32) || (args[0] is Double)))
                return (new EcmaScriptArrayObject(this, args[0])); // create a new array of length arg

            return (new EcmaScriptArrayObject(this, 0).AddValues(args));
        }

        public object ArrayToString(ExecutionContext aCaller, object aSelf, params object[] args)
        {
            var lSelf = Utilities.ToObject(aCaller, aSelf);
            var lJoin = lSelf.Get("join") as EcmaScriptBaseFunctionObject;
            if (lJoin == null)
                return ObjectToString(aCaller, aSelf);

            return lJoin.CallEx(aCaller, aSelf);
        }

        public object ArrayConcat(ExecutionContext aCaller, object aSelf, params object[] args)
        {
            var lSelf = Utilities.ToObject(aCaller, aSelf);
            EcmaScriptArrayObject lRes;
            var lLen = Utilities.GetObjAsInteger(lSelf.Get("length"), aCaller);
            lRes = new EcmaScriptArrayObject(this, 0);
            for (var i = 0; i < lLen; i++)
            {
                lRes.AddValue(lSelf.Get(i.ToString(), aCaller, 3));
            }

            foreach (var el in args)
            {
                if (el is EcmaScriptArrayObject)
                {
                    var a = (EcmaScriptArrayObject)el;
                    for (uint i = 0, l = a.Length; i < l; i++)
                    {
                        var lVal = a.GetOwnProperty(i.ToString());
                        if (lVal != null)
                            lRes.AddValue(lVal.Value);
                    }
                }
                else
                    lRes.AddValue(el);
            }
            return lRes;
        }

        public object ArrayJoin(ExecutionContext aCaller, object aSelf, params object[] args)
        {
            var lSep = args.Length == 0 ? null : Utilities.GetArgAsString(args, 0, aCaller);
            if (lSep == null) lSep = ",";
            var lSelf = Utilities.ToObject(aCaller, aSelf);
            var lRes = new StringBuilder();
            for (int i = 0, l = Utilities.GetObjAsInteger(lSelf.Get("length"), aCaller); i < l; i++) {
                if (i != 0)
                    lRes.Append(lSep);

                var member = lSelf.Get(i.ToString(), aCaller, 3);
                var lItem = member == lSelf ? null : Utilities.GetObjAsString(member, aCaller);
                if (lItem == null)
                    lItem = "";

                lRes.Append(lItem);
            }
            return lRes.ToString();
        }

        public object ArrayPop(ExecutionContext aCaller, object aSelf, params object[] args)
        {
            var lSelf = Utilities.ToObject(aCaller, aSelf);
            var lLen = Utilities.GetObjAsCardinal(lSelf.Get("length", aCaller), aCaller);
            if (lLen == 0)
            {
                lSelf.Put("length", 0, aCaller, 1);
                return Undefined.Instance;
            }
            var indx = (lLen - 1).ToString();
            var el = lSelf.Get(indx, aCaller);
            lSelf.Delete(indx, true);
            lLen = (lLen - 1);
            lSelf.Put("length", indx, aCaller);
            return el;
        }

        public object ArrayPush(ExecutionContext aCaller, object aSelf, params object[] args)
        {
            var lSelf = Utilities.ToObject(aCaller, aSelf);
            var lLen = Utilities.GetObjAsCardinal(lSelf.Get("length", aCaller), aCaller);
            foreach (var el in args) {
                lSelf.Put(lLen.ToString(), el, aCaller);
                ++lLen;
            }
            var length = lLen < (uint)Int32.MaxValue ? (int)lLen : (double)lLen;
            return Put("length", length, aCaller);
        }

        public object ArrayReverse(ExecutionContext aCaller, object aSelf, params object[] args)
        {
            var lSelf = Utilities.ToObject(aCaller, aSelf);
            var lLen = Utilities.GetObjAsCardinal(lSelf.Get("length", aCaller), aCaller);
            var lMid = lLen / 2;
            var lLow = 0;
            while (lLow != lMid) {
                var lUp = lLen - lLow - 1;
                var lUpP = lUp.ToString();
                var lLowP = lLow.ToString();
                var lLowVal = lSelf.Get(lLowP, aCaller);
                var lUpVal = lSelf.Get(lUpP, aCaller);
                var lLowerExists = lSelf.HasProperty(lLowP);
                var lUpperExists = lSelf.HasProperty(lUpP);
                if (lLowerExists && lUpperExists) {
                    lSelf.Put(lLowP, lUpVal, aCaller, 1);
                    lSelf.Put(lUpP, lLowVal, aCaller, 1);
                } else if (!lLowerExists && lUpperExists) {
                    lSelf.Put(lLowP, lUpVal, aCaller, 1);
                    lSelf.Delete(lUpP, true);
                } else if (!lLowerExists && !lUpperExists) {
                    lSelf.Delete(lLowP, true);
                    lSelf.Put(lUpP, lLowVal, aCaller, 1);
                };

                lLow++;
            }
            return lSelf;
        }

        public object ArrayShift(ExecutionContext aCaller, object aSelf, params object[] args)
        {
            var lSelf = Utilities.ToObject(aCaller, aSelf);
            var lLen = Utilities.GetObjAsCardinal(lSelf.Get("length", aCaller), aCaller);

            if (lLen == 0) {
                lSelf.Put("length", 0, aCaller, 1);
                return (Undefined.Instance);
            }

            var first = lSelf.Get("0", aCaller);
            var k = (uint)1;
            while (k < lLen) {
                var lFrom = k.ToString();
                var lTo = (k - 1).ToString();
                if (lSelf.HasProperty(lFrom))
                    lSelf.Put(lTo, lSelf.Get(lFrom, aCaller), aCaller);
                else
                    lSelf.Delete(lTo, true);
                ++k;
            }

            var lNewLen = (lLen - 1).ToString();
            lSelf.Delete(lNewLen, true);
            lSelf.Put("length", lNewLen, aCaller);

            return (first);
        }

        public object ArraySlice(ExecutionContext aCaller, object aSelf, params object[] args)
        {
            var lSelf = Utilities.ToObject(aCaller, aSelf);
            var lLen = Utilities.GetObjAsCardinal(lSelf.Get("length", aCaller), aCaller);

            var lRelStart = Utilities.GetArgAsDouble(args, 0, aCaller);
            var k = (uint)0;
            if (lRelStart < 0)
                k = (uint)((Int64)(Math.Max((double)(lLen + lRelStart), 0)));
            else
                k = (uint)((Int64)(Math.Min(lRelStart, (Double)((Int64)lLen))));

            var lRelEnd = ((args.Length < 2) || (args[1] == Undefined.Instance)) ? lLen : Utilities.GetArgAsDouble(args, 1, aCaller);

            var lFinal = lRelEnd < 0 ? (uint)(Math.Max(lLen + (int)lRelEnd, 0)) : (uint)((Int64)(Math.Min(lRelEnd, (Double)lLen)));
            var a = new EcmaScriptArrayObject(Root, 0);
            var n = 0;
            while (k < lFinal)
            {
                var pk = k.ToString();
                if (lSelf.HasProperty(pk))
                {
                    a.Put(n.ToString(), lSelf.Get(pk, aCaller), aCaller, 0);
                }

                ++(n);
                ++(k);
            }

            return a;
        }

        public object ArraySort(ExecutionContext aCaller, object aSelf, params object[] args)
        {
            var lSelf = Utilities.ToObject(aCaller, aSelf);
            var lLen = Utilities.GetObjAsCardinal(lSelf.Get("length", aCaller), aCaller);

            var lFunc = Utilities.GetArg(args, 0) as EcmaScriptBaseFunctionObject;
            if (lFunc == null)
                lFunc = DefaultCompareInstance;

            Sort(lSelf, 0, (int)(lLen - 1),
              (EcmaScriptObject aList, int L, int R) => {
                  if (L != R) this.Swap(this.ExecutionContext, aList, L, R);
              },
              (EcmaScriptObject aList, int L, int R) =>
              {
                  var jString = L.ToString();
                  var kString = R.ToString();
                  var hasJ = aList.HasProperty(jString);
                  var hasK = aList.HasProperty(kString);
                  if (!hasJ && !hasK) return 0;
                  if (!hasJ) return 1;
                  if (!hasK) return -1;
                  var x = aList.Get(jString, aCaller, 0);
                  var y = aList.Get(kString, aCaller, 0);
                  if ((x == Undefined.Instance) && (y == Undefined.Instance)) return 0;
                  if (x == Undefined.Instance) return 1;
                  if (y == Undefined.Instance) return -1;
                  return Utilities.GetObjAsInteger(lFunc.CallEx(aCaller, aList, x, y), aCaller);
              });
            return lSelf;
        }

        public object ArraySplice(ExecutionContext aCaller, object aSelf, params object[] args)
        {
            var lSelf = Utilities.ToObject(aCaller, aSelf);
            var A = new EcmaScriptArrayObject(this, 0);
            var lLen = Utilities.GetObjAsCardinal(lSelf.Get("length", aCaller, 0), aCaller);

            var lRelativeStart = Utilities.GetArgAsInteger(args, 0, aCaller);
            var lActualStart = lRelativeStart < 0 ? Math.Max(lLen + lRelativeStart, 0) : Math.Min(lRelativeStart, (int)lLen);

            var lActualDeleteCount = Math.Min(Math.Max(Utilities.GetArgAsInteger(args, 1, aCaller), 0), lLen - lActualStart);
            var k = 0L;
            while (k < lActualDeleteCount) {
                var lFrom = (lRelativeStart + k).ToString();
                if (lSelf.HasProperty(lFrom)) {
                    A.Put(k.ToString(), lSelf.Get(lFrom, aCaller), aCaller);
                };
                ++(k);
            }

            if ((args.Length - 2) < lActualDeleteCount) {
                k = lActualStart;
                while (k < (lLen - lActualDeleteCount))
                {
                    var lFrom = (k + lActualDeleteCount).ToString();
                    var lTo = (k + args.Length - 2).ToString();
                    if (lSelf.HasProperty(lFrom))
                        lSelf.Put(lTo, lSelf.Get(lFrom, aCaller), aCaller);
                    else
                        lSelf.Delete(lTo, true);
                    ++(k);
                }
            } else if ((args.Length - 2) > lActualDeleteCount) {
                k = lLen - lActualDeleteCount;
                while (k > lActualStart)
                {
                    var lFrom = (k + lActualDeleteCount - 1).ToString();
                    var lTo = (k + args.Length - 3).ToString();
                    if (lSelf.HasProperty(lFrom))
                        lSelf.Put(lTo, lSelf.Get(lFrom, aCaller), aCaller);
                    else
                        lSelf.Delete(lTo, true);
                    --(k);
                }
            }
            k = lActualStart;

            for (int i = 2, l = args.Length; i < l; i++)
            {
                lSelf.Put(k.ToString(), args[i], aCaller);
                ++k;
            }

            lSelf.Put("length", (int)(lLen - lActualDeleteCount + (args.Length - 2)), aCaller);

            return (A);
        }

        public object ArrayUnshift(ExecutionContext aCaller, object aSelf, params object[] args)
        {
            var lSelf = Utilities.ToObject(aCaller, aSelf);
            var lLen = Utilities.GetObjAsCardinal(lSelf.Get("length", aCaller), aCaller);
            var lArgCount = args.Length;
            var k = lLen;
            while (k > 0) {
                var lFrom = (k - 1).ToString();
                var lTo = (k + lArgCount - 1).ToString();
                if (lSelf.HasProperty(lFrom)) {
                    lSelf.Put(lTo, lSelf.Get(lFrom, aCaller), aCaller);
                } else
                    lSelf.Delete(lTo, true);
                --(k);
            }

            for (int j = 0, l = args.Length; j < l; j++)
                lSelf.Put(j.ToString(), args[j], aCaller, 1);

            lSelf.Put("length", ((int)lLen) + lArgCount, aCaller);

            return (lSelf);
        }

        public object DefaultCompare(ExecutionContext aCaller, object aSelf, params object[] args)
        {
            var lLeft = args[0];
            var lRight = args[1];
            if (lLeft == lRight) return 0;
            if (lLeft == Undefined.Instance) return 1;
            if (lRight == Undefined.Instance) return -1;
            if (lLeft == null) return 1;
            if (lRight == null) return -1;

            if ((lLeft is String) || (lRight is String))
                return String.Compare(Utilities.GetObjAsString(lLeft, aCaller),
                                      Utilities.GetObjAsString(lRight, aCaller),
                                      StringComparison.Ordinal);

            if (lLeft is EcmaScriptObject)
                return (lRight is EcmaScriptObject ? 1 : 0);
            if (lRight is EcmaScriptObject)
                return -1;

            return Utilities.GetObjAsDouble(lLeft, aCaller).CompareTo(Utilities.GetObjAsDouble(lRight, aCaller));
        }

        public object ArrayToLocaleString(ExecutionContext aCaller, object aSelf, params object[] args)
        {
            var lObj = Utilities.ToObject(aCaller, aSelf);
            if (lObj == null)
                RaiseNativeError(NativeErrorType.ReferenceError, "Object type expected");

            var lLen = Utilities.GetObjAsInteger(lObj.Get("length", aCaller, 0), aCaller);
            var lRes = new StringBuilder();
            for (int i = 0; i < lLen; i++)
            {
                var lVal = Utilities.ToObject(aCaller, lObj.Get(i.ToString(), aCaller, 2));
                string lData;
                if (lVal == null)
                {
                    lData = String.Empty;
                }
                else
                {
                    var lLocale = lVal.Get("toLocaleString") as EcmaScriptFunctionObject;

                    if (lLocale == null)
                        RaiseNativeError(NativeErrorType.ReferenceError, "element " + i + " in array does not have a callable toLocaleString");

                    lData = Utilities.GetObjAsString(lLocale.CallEx(aCaller, lVal), aCaller);
                };

                if (i != 0)
                    lRes.Append(",");

                lRes.Append(lData);
            }

            return (lRes.ToString());
        }

        public bool Sort<T>(T aList, int aStart, int aEnd, Action<T, int, int> aSwap, Func<T, int, int, int> aCompare)
        {
            int I; bool result = false;
            do {
                I = aStart;
                var J = aEnd;
                var P = (aStart + aEnd) >> 1;

                do {
                    while (aCompare(aList, I, P) < 0) ++I;

                    while (aCompare(aList, J, P) > 0) --J;

                    if (I <= J)
                    {
                        result = true;
                        aSwap(aList, I, J);

                        if (P == I)
                            P = J;
                        else if (P == J)
                            P = I;

                        ++(I);
                        --(J);
                    }
                } while (!(I > J));

                if (aStart < J)
                    result = Sort<T>(aList, aStart, J, aSwap, aCompare) || result;

                aStart = I;
            } while (!(I >= aEnd));

            return result;
        }

        public object ArrayIsArray(ExecutionContext aCaller, object aSelf, params object[] args)
        {
            var obj = Utilities.GetArg(args, 0) as EcmaScriptObject;
            if (obj != null)
            {
                if (obj is EcmaScriptArrayObject)
                {
                    return true;
                }
                return obj == ArrayPrototype;
            }
            return false;
        }

        public object ArrayIndexOf(ExecutionContext aCaller, object aSelf, params object[] args)
        {
            var lObj = Utilities.ToObject(aCaller, aSelf);
            var lLen = Utilities.GetObjAsCardinal(lObj.Get("length"), aCaller);
            var lElement = Utilities.GetArg(args, 0);
            var lStart = Utilities.GetArgAsInt64(args, 1, aCaller);

            if (lStart >= lLen)
                return (-1);

            if (lStart < 0)
                lStart = lLen + lStart;

            while (lStart < lLen) {
                var lIndex = lStart.ToString();
                if (lObj.HasProperty(lIndex))
                    if ((bool)(Operators.StrictEqual(lObj.Get(lIndex, aCaller, 2), lElement, aCaller)))
                        return (lStart);
                lStart = lStart + 1;
            }

            return (-1);
        }

        public object ArrayEvery(ExecutionContext aCaller, object aSelf, params object[] args)
        {
            var lObj = Utilities.ToObject(aCaller, aSelf);
            var lLen = Utilities.GetObjAsCardinal(lObj.Get("length"), aCaller);
            var lCallback = Utilities.GetArg(args, 0) as EcmaScriptBaseFunctionObject;
            var lCallbackThis = Utilities.GetArg(args, 1) ?? Undefined.Instance;
            if (lCallback == null)
                RaiseNativeError(NativeErrorType.TypeError, "Delegate expected");

            var ticks = GetTicks(lObj); PropertyValue value;
            for (uint i = 0; i < lLen; i++)
            {
                if (lObj.Deleted)
                    break;

                var lIndex = i.ToString();
                if (null != (value = lObj.GetProperty(lIndex)) && value.Ticks <= ticks[value.Owner])
                    if (!Utilities.GetObjAsBoolean(lCallback.CallEx(aCaller, lCallbackThis, lObj.Get(value, aCaller, 2), i, lObj), aCaller))
                        return false;
            }
            return true;
        }

        public object ArrayLastIndexOf(ExecutionContext aCaller, object aSelf, params object[] args)
        {
            var lObj = Utilities.ToObject(aCaller, aSelf);
            var lLen = Utilities.GetObjAsCardinal(lObj.Get("length"), aCaller);
            var lElement = Utilities.GetArg(args, 0);
            var lStart = (args.Length >= 2) ? Utilities.GetArgAsInt64(args, 1, aCaller) : lLen;
            if (lLen == 0) return -1;
            if (lStart >= lLen) lStart = lLen - 1;
            if (lStart < 0) lStart = lLen + lStart;
            while (lStart >= 0) {
                var lIndex = lStart.ToString();
                if (lObj.HasProperty(lIndex))
                    if ((bool)Operators.StrictEqual(lObj.Get(lIndex, aCaller, 2), lElement, aCaller))
                        return lStart;
                lStart = lStart - 1;
            }
            return -1;
        }

        public object ArraySome(ExecutionContext aCaller, object aSelf, params object[] args)
        {
            var lObj = Utilities.ToObject(aCaller, aSelf);
            var lLen = (uint)0;
            // some strange behaviours
            var lArrayLen = lObj.Get("length") as EcmaScriptArrayObject;
            if (lArrayLen != null)
            {
                lLen = lArrayLen.Length;
                if (lLen == 0)
                {
                    return false;
                }
                else
                {
                    lLen = Utilities.GetObjAsCardinal(lArrayLen, aCaller);// TODO: Try if it cant be converted, tihs always return 0
                    if (0 == lLen)
                    {
                        return -1;
                    }
                }
            }
            else
            {
                lLen = Utilities.GetObjAsCardinal(lObj.Get("length"), aCaller);
            }
            //if (lLen == 0)
            //    return true;

            var lCallback = Utilities.GetArg(args, 0) as EcmaScriptBaseFunctionObject;
            var lCallbackThis = Utilities.GetArg(args, 1) ?? Undefined.Instance;
            if (lCallback == null)
                RaiseNativeError(NativeErrorType.TypeError, "Delegate expected");

            var ticks = GetTicks(lObj); PropertyValue value;
            for (uint i = 0; i < lLen; i++)
            {
                if (lObj.Deleted)
                    break;

                var lIndex = i.ToString();
                if (null != (value = lObj.GetProperty(lIndex)) && value.Ticks <= ticks[value.Owner])
                    if (Utilities.GetObjAsBoolean(lCallback.CallEx(aCaller, lCallbackThis, lObj.Get(value, aCaller, 2), i, lObj), aCaller))
                        return true;
            }
            return false;
        }

        public object ArrayMap(ExecutionContext aCaller, object aSelf, params object[] args)
        {
            var lObj = Utilities.ToObject(aCaller, aSelf);
            var lLen = Utilities.GetObjAsCardinal(lObj.Get("length"), aCaller);
            var lCallback = Utilities.GetArg(args, 0) as EcmaScriptBaseFunctionObject;
            var lCallbackThis = Utilities.GetArg(args, 1) ?? Undefined.Instance;
            if (lCallback == null)
                RaiseNativeError(NativeErrorType.TypeError, "Delegate expected");
            var ticks = GetTicks(lObj); PropertyValue value;

            var lRes = new EcmaScriptArrayObject(lLen, this);
            for (uint i = 0; i < lLen; i++)
            {
                if (lObj.Deleted)
                {
                    lRes.AddValue(Undefined.Instance);
                    break;
                }

                var lIndex = i.ToString();
                if (null != (value = lObj.GetProperty(lIndex)) && value.Ticks <= ticks[value.Owner])
                {
                    lRes.AddValue(lCallback.CallEx(aCaller, lCallbackThis, lObj.Get(value, aCaller, 2), i, lObj));
                }
            }

            //chapter15/15.4/15.4.4/15.4.4.19/15.4.4.19-8-7.js
            //chapter15\15.4\15.4.4\15.4.4.19\15.4.4.19-8-b-1.js
            lRes.Put("length", lLen);

            return lRes;
        }

        public object ArrayForeach(ExecutionContext aCaller, object aSelf, params object[] args)
        {
            var lObj = Utilities.ToObject(aCaller, aSelf);
            var lLen = Utilities.GetObjAsCardinal(lObj.Get("length"), aCaller);
            var lCallback = Utilities.GetArg(args, 0) as EcmaScriptBaseFunctionObject;
            var lCallbackThis = Utilities.GetArg(args, 1) ?? Undefined.Instance;
            if (lCallback == null)
                RaiseNativeError(NativeErrorType.TypeError, "Delegate expected");

            PropertyValue value;
            for (uint i = 0; i < lLen; i++) {
                if (lObj.Deleted)
                    break;

                var lIndex = i.ToString();
                if (null != (value = lObj.GetProperty(lIndex)))
                    lCallback.CallEx(aCaller, lCallbackThis, lObj.Get(value, aCaller, 2), i, lObj);
            }
            return Undefined.Instance;
        }

        public object ArrayFilter(ExecutionContext aCaller, object aSelf, params object[] args)
        {
            var lObj = Utilities.ToObject(aCaller, aSelf);
            var lLen = Utilities.GetObjAsCardinal(lObj.Get("length"), aCaller);
            var lCallback = Utilities.GetArg(args, 0) as EcmaScriptBaseFunctionObject;
            var lCallbackThis = Utilities.GetArg(args, 1) ?? Undefined.Instance;
            if (lCallback == null) RaiseNativeError(NativeErrorType.TypeError, "Delegate expected");
            var lRes = new EcmaScriptArrayObject(lLen, this); PropertyValue value;
            var ticks = GetTicks(lObj);

            for (uint i = 0; i < lLen; i++) {
                if (lObj.Deleted)
                    break;

                var lIndex = i.ToString();
                if (null != (value = lObj.GetProperty(lIndex)) && value.Ticks <= ticks[value.Owner]) {
                    var lGet = lObj.Get(value, aCaller, 2);
                    if (Utilities.GetObjAsBoolean(lCallback.CallEx(aCaller, lCallbackThis, lGet, i, lObj), aCaller))
                        lRes.AddValue(lGet);
                };
            };
            return lRes;
        }

        public object ArrayReduce(ExecutionContext aCaller, object aSelf, params object[] args)
        {
            var lObj = Utilities.ToObject(aCaller, aSelf);
            var lLen = Utilities.GetObjAsCardinal(lObj.Get("length"), aCaller);
            var lCallback = Utilities.GetArg(args, 0) as EcmaScriptBaseFunctionObject;
            if (lCallback == null)
                RaiseNativeError(NativeErrorType.TypeError, "Delegate expected");

            var lInitialValue = Utilities.GetArg(args, 1);
            var lGotInitial = false;
            if (args.Length >= 2)
                lGotInitial = true;

            var k = 0; PropertyValue value; string lKey;
            if (!lGotInitial)
            {
                while (k < lLen) {
                    lKey = k.ToString();
                    ++(k);
                    if (null != (value = lObj.GetProperty(lKey))) {
                        lGotInitial = true;
                        lInitialValue = lObj.Get(value, aCaller, 2);
                        break;
                    }
                }
            }

            if (k == lLen)
            {
                if (lGotInitial)
                {
                    return lInitialValue;
                }
                else
                {
                    RaiseNativeError(NativeErrorType.TypeError, "Empty array.");
                }
            }

            var ticks = GetTicks(lObj);
            while (k < lLen)
            {
                if (lObj.Deleted)
                {
                    break;
                }

                lKey = k.ToString();
                if (null != (value = lObj.GetProperty(lKey)) && value.Ticks <= ticks[value.Owner])
                {
                    lInitialValue = lCallback.CallEx(aCaller, Undefined.Instance, lInitialValue, lObj.Get(value, aCaller, 2), k, lObj);
                }
                ++(k);
            }
            return lInitialValue;
        }

        Dictionary<EcmaScriptObject, ulong> GetTicks(EcmaScriptObject obj)
        {
            var ticks = new Dictionary<EcmaScriptObject, ulong>();
            while (obj != null)
            {
                ticks[obj] = obj.Ticks;
                obj = obj.Prototype;
            }
            return ticks;
        }

        public object ArrayReduceRight(ExecutionContext aCaller, object aSelf, params object[] args)
        {
            var lObj = Utilities.ToObject(aCaller, aSelf);
            var lLen = Utilities.GetObjAsCardinal(lObj.Get("length"), aCaller);
            var lCallback = Utilities.GetArg(args, 0) as EcmaScriptBaseFunctionObject;
            if (lCallback == null)
                RaiseNativeError(NativeErrorType.TypeError, "Delegate expected");

            var lInitialValue = Utilities.GetArg(args, 1);
            var lGotInitial = false;
            if (args.Length >= 2)
                lGotInitial = true;

            var k = lLen; PropertyValue value; string lKey;
            if (!lGotInitial && k != 0)
            {
                do
                {
                    --k;
                    lKey = k.ToString();
                    if (null != (value = lObj.GetProperty(lKey)))
                    {
                        lGotInitial = true;
                        lInitialValue = lObj.Get(value, aCaller, 2);
                        break;
                    }
                }
                while (k != 0);
            }

            if (0 == k)
            {
                if (lGotInitial)
                {
                    return lInitialValue;
                }
                else
                {
                    RaiseNativeError(NativeErrorType.TypeError, "Empty array.");
                }
            }

            var ticks = GetTicks(lObj);
            do
            {
                if (lObj.Deleted)
                {
                    break;
                }

                --k;
                lKey = k.ToString();
                if (null != (value = lObj.GetProperty(lKey)) && value.Ticks <= ticks[value.Owner])
                {
                    lInitialValue = lCallback.CallEx(aCaller, Undefined.Instance, lInitialValue, lObj.Get(value, aCaller, 2), k, lObj);
                }
            }
            while (k != 0);

            return lInitialValue;
        }

        void Swap(ExecutionContext ec, EcmaScriptObject aSelf, Int32 L, Int32 R)
        {
            var LStr = L.ToString();
            var LVal = aSelf.Get(LStr, ec);
            var RStr = R.ToString();
            var RVal = aSelf.Get(RStr, ec);

            var lHasL = aSelf.HasProperty(LStr);
            var lHasR = aSelf.HasProperty(RStr);

            if (lHasL && lHasR) {
                aSelf.Put(LStr, RVal, ec, 1);
                aSelf.Put(RStr, LVal, ec, 1);
                return;
            }

            if (!lHasL && lHasR) {
                aSelf.Put(LStr, RVal, ec, 1);
                aSelf.Delete(RStr, true);
                return;
            }

            if (!lHasL && !lHasR)
            {
                aSelf.Delete(LStr, true);
                aSelf.Put( RStr, LVal, ec, 1);
            }
        }
    }
}


text:
package com.gemstone.gemfire.cache.query.internal.parse;

import antlr.Token;

import com.gemstone.gemfire.cache.query.QueryInvalidException;
import com.gemstone.gemfire.cache.query.internal.CompiledValue;
import com.gemstone.gemfire.cache.query.internal.QCompiler;

/**
 *
 * @author ashahid
 *
 */
public class ASTAggregateFunc extends GemFireAST {
  private static final long serialVersionUID = 8713004765228379685L;
  private int  aggFunctionType;
  private boolean  distinctOnly = false;

  public ASTAggregateFunc() {

  }

  public ASTAggregateFunc(Token t) {
    super(t);
  }

  public void setAggregateFunctionType(int type) {
    this.aggFunctionType = type;
  }

  public void setDistinctOnly(boolean distinctOnly) {
    this.distinctOnly = distinctOnly;
  }

  @Override
  public void compile(QCompiler compiler) {
    super.compile(compiler);
    Object expr = compiler.pop();
    if(expr instanceof String) {
      if(((String)expr).equals("*")) {
        expr = null;
      }else {
        throw new QueryInvalidException("invalid parameter to aggregate function");
      }
    }
    compiler.aggregateFunction((CompiledValue)expr, this.aggFunctionType, this.distinctOnly);
  }
}


text:
Troubleshooting
===============

Occasionally, the API can stop working for whatever reason. If it was working previously and it stopped working on the same version, it means that either we screwed code up or there's been a change to the Discord API. You can try asking around in the `discord.js channel in the API server`_. You could also `make an issue`_ if one relating to a similar issue doesn't exist. Please post a stacktrace if there is one, and be as detailed as possible - *"the API isn't working"* doesn't help at all.

If there is already an issue, feel free to comment that you're also experiencing the same thing. This helps to see how widespread the bug is.

You can try reconnecting before submitting an issue, as sometimes some of the servers may be slightly different.

.. _discord.js channel in the API server : https://discord.gg/0SBTUU1wZTYcFtmP
.. _make an issue : https://github.com/hydrabolt/discord.js/issues


text:
import datetime
import re
import uuid

from django.conf import settings
from django.core.exceptions import ValidationError
from django.db.transaction import atomic
from django.utils.translation import gettext as _

from couchdbkit import ResourceNotFound
from memoized import memoized

from dimagi.utils.modules import to_function
from dimagi.utils.parsing import json_format_datetime

from corehq.apps.hqcase.utils import submit_case_block_from_template
from corehq.apps.translations.models import SMSTranslations
from corehq.apps.users.models import CouchUser
from corehq.form_processor.exceptions import CaseNotFound
from corehq.form_processor.models import CommCareCase
from corehq.toggles import IS_CONTRACTOR
from corehq.util.quickcache import quickcache

class DateFormat(object):
    def __init__(self, human_readable_format, c_standard_format, validate_regex):
        self.human_readable_format = human_readable_format
        self.c_standard_format = c_standard_format
        self.validate_regex = validate_regex

    def parse(self, value):
        return datetime.datetime.strptime(value, self.c_standard_format)

    def is_valid(self, value):
        return re.match(self.validate_regex, value) is not None

# A project can specify the expected format of answers to date questions
# in SMS Surveys. These are the available choices.
ALLOWED_SURVEY_DATE_FORMATS = (
    DateFormat('YYYYMMDD', '%Y%m%d', r'^\d{8}$'),
    DateFormat('MMDDYYYY', '%m%d%Y', r'^\d{8}$'),
    DateFormat('DDMMYYYY', '%d%m%Y', r'^\d{8}$'),
)

SURVEY_DATE_FORMAT_LOOKUP = {df.human_readable_format: df for df in ALLOWED_SURVEY_DATE_FORMATS}

phone_number_plus_re = re.compile(r"^\+{0,1}\d+$")

class ContactNotFoundException(Exception):
    pass

def get_date_format(human_readable_format):
    return SURVEY_DATE_FORMAT_LOOKUP.get(human_readable_format, ALLOWED_SURVEY_DATE_FORMATS[0])

def strip_plus(phone_number):
    if (isinstance(phone_number, str) and len(phone_number) > 0
            and phone_number[0] == "+"):
        return phone_number[1:]
    else:
        return phone_number

def clean_phone_number(text):
    """
    strip non-numeric characters and add '%2B' at the front
    """
    non_decimal = re.compile(r'[^\d.]+')
    plus = '+'
    cleaned_text = "%s%s" % (plus, non_decimal.sub('', text))
    return cleaned_text

def validate_phone_number(phone_number, error_message=None):
    if (
        not isinstance(phone_number, str)
        or not phone_number_plus_re.match(phone_number)
    ):
        error_message = error_message or _("Invalid phone number format.")
        raise ValidationError(error_message)

def format_message_list(message_list):
    """
    question = message_list[-1]
    if len(question) > 160:
        return question[0:157] + "..."
    else:
        extra_space = 160 - len(question)
        message_start = ""
        if extra_space > 3:
            for msg in message_list[0:-1]:
                message_start += msg + ". "
            if len(message_start) > extra_space:
                message_start = message_start[0:extra_space-3] + "..."
        return message_start + question
    """
    # Some gateways (yo) allow a longer message to be sent and handle splitting
    # it up on their end, so for now just join all messages together
    return " ".join(message_list)

def register_sms_contact(domain, case_type, case_name, user_id,
        contact_phone_number, contact_phone_number_is_verified="1",
        contact_backend_id=None, language_code=None, time_zone=None,
        owner_id=None, contact_ivr_backend_id=None):
    """
    Creates a messaging case contact by submitting system-generated casexml
    """
    utcnow = str(datetime.datetime.utcnow())
    case_id = str(uuid.uuid3(uuid.NAMESPACE_URL, utcnow))
    if owner_id is None:
        owner_id = user_id
    context = {
        "case_id": case_id,
        "date_modified": json_format_datetime(datetime.datetime.utcnow()),
        "case_type": case_type,
        "case_name": case_name,
        "owner_id": owner_id,
        "user_id": user_id,
        "contact_phone_number": contact_phone_number,
        "contact_phone_number_is_verified": contact_phone_number_is_verified,
        "contact_backend_id": contact_backend_id,
        "language_code": language_code,
        "time_zone": time_zone,
        "contact_ivr_backend_id": contact_ivr_backend_id,
    }
    submit_case_block_from_template(domain, "sms/xml/register_contact.xml", context, user_id=user_id)
    return case_id

def update_contact(domain, case_id, user_id, contact_phone_number=None,
        contact_phone_number_is_verified=None, contact_backend_id=None,
        language_code=None, time_zone=None):
    context = {
        "case_id": case_id,
        "date_modified": json_format_datetime(datetime.datetime.utcnow()),
        "user_id": user_id,
        "contact_phone_number": contact_phone_number,
        "contact_phone_number_is_verified": contact_phone_number_is_verified,
        "contact_backend_id": contact_backend_id,
        "language_code": language_code,
        "time_zone": time_zone
    }
    submit_case_block_from_template(domain, "sms/xml/update_contact.xml", context, user_id=user_id)

def _get_backend_classes(backend_list):
    """
    Returns a dictionary of {api id: class} for all installed SMS backends.
    """
    from corehq.apps.sms.mixin import BadSMSConfigException
    result = {}

    for backend_class in backend_list:
        cls = to_function(backend_class)
        api_id = cls.get_api_id()
        if api_id in result:
            raise BadSMSConfigException("Cannot have more than one backend with the same "
                                        "api id. Duplicate found for: %s" % api_id)
        result[api_id] = cls
    return result

@memoized
def get_sms_backend_classes():
    return _get_backend_classes(settings.SMS_LOADED_SQL_BACKENDS)

CLEAN_TEXT_REPLACEMENTS = (
    # Common emoticon replacements
    (":o", ": o"),
    (":O", ": O"),
    (":x", ": x"),
    (":X", ": X"),
    (":D", ": D"),
    (":p", ": p"),
    (":P", ": P"),
    # Special punctuation ascii conversion
    ("\u2013", "-"),  # Dash
    ("\u201c", '"'),  # Open double quote
    ("\u201d", '"'),  # Close double quote
    ("\u2018", "'"),  # Open single quote
    ("\u2019", "'"),  # Close single quote
    ("\u2026", "..."),  # Ellipsis
)

def clean_text(text):
    """
    Performs the replacements in CLEAN_TEXT_REPLACEMENTS on text.
    """
    for a, b in CLEAN_TEXT_REPLACEMENTS:
        text = text.replace(a, b)
    return text

def get_contact(domain, contact_id):
    contact = None
    try:
        contact = CommCareCase.objects.get_case(contact_id, domain)
    except (ResourceNotFound, CaseNotFound):
        pass

    if contact and contact.doc_type == 'CommCareCase' and contact.domain == domain:
        return contact

    contact = None
    try:
        contact = CouchUser.get_by_user_id(contact_id, domain=domain)
    except CouchUser.AccountTypeError:
        pass

    if not contact:
        raise ContactNotFoundException("Contact not found")

    return contact

def touchforms_error_is_config_error(domain, touchforms_error):
    """
    Returns True if the given TouchformsError is the result of a
    form configuration error.
    """
    # Unfortunately there isn't a better way to do this.
    # What we want to do is try and pick out the types of exceptions
    # that are configuration errors such as an xpath reference error
    # or misconfigured case sharing settings.
    exception_text = touchforms_error.response_data.get('exception') or ''
    exception_text = exception_text.lower()
    return any(s in exception_text for s in (
        'case sharing settings',
        'error in calculation',
        'problem with display condition',
    ))

def get_formplayer_exception(domain, touchforms_error):
    return touchforms_error.response_data.get('exception')

@quickcache(['backend_id'], timeout=5 * 60)
def get_backend_name(backend_id):
    """
    Returns None if the backend is not found, otherwise
    returns the backend's name.
    """
    if not backend_id:
        return None

    from corehq.apps.sms.models import SQLMobileBackend
    try:
        return SQLMobileBackend.load(backend_id, is_couch_id=True).name
    except Exception:
        return None

def set_domain_default_backend_to_test_backend(domain):
    """
    Pass in the name of the domain to set the domain's default
    sms backend to be the test backend.
    """
    from corehq.apps.sms.models import SQLMobileBackend, SQLMobileBackendMapping
    test_backend = SQLMobileBackend.get_global_backend_by_name(
        SQLMobileBackend.SMS,
        'MOBILE_BACKEND_TEST'
    )
    if not test_backend:
        raise Exception("Expected MOBILE_BACKEND_TEST to be created")
    SQLMobileBackendMapping.set_default_domain_backend(
        domain,
        test_backend
    )

@quickcache(['domain', 'case_id'], timeout=60 * 60)
def is_case_contact_active(domain, case_id):
    try:
        case = CommCareCase.objects.get_case(case_id, domain)
    except (ResourceNotFound, CaseNotFound):
        return False

    return not (case.closed or case.is_deleted)

@quickcache(['domain', 'user_id'], timeout=60 * 60)
def is_user_contact_active(domain, user_id):
    try:
        user = CouchUser.get_by_user_id(user_id, domain=domain)
    except KeyError:
        return False

    if not user:
        return False

    return user.is_active

def is_contact_active(domain, contact_doc_type, contact_id):
    if contact_doc_type == 'CommCareCase':
        return is_case_contact_active(domain, contact_id)
    elif contact_doc_type in ('CommCareUser', 'WebUser'):
        return is_user_contact_active(domain, contact_id)
    else:
        # We can't tie the contact to a document so since we can't say whether
        # it's inactive, we count it as active
        return True

@atomic
def get_or_create_sms_translations(domain):
    (translations, created) = SMSTranslations.objects.get_or_create(domain=domain, defaults={
        "langs": ["en"],
        "translations": {
            "en": {}
        },
    })
    return translations

def get_language_list(domain):
    sms_translations = get_or_create_sms_translations(domain)
    result = set(sms_translations.langs)
    result.discard('*')
    return list(result)

def is_superuser_or_contractor(user: CouchUser):
    return IS_CONTRACTOR.enabled(user.username) or user.is_superuser


text:
using System;
using Xwt.Backends;

namespace Xwt.GtkBackend
{
	public class ListBoxBackend: ListViewBackend, IListBoxBackend
	{
		Gtk.TreeViewColumn theColumn;

		public ListBoxBackend ()
		{
		}

		public new bool GridLinesVisible {
			get {
				return (base.GridLinesVisible == Xwt.GridLines.Horizontal || base.GridLinesVisible == Xwt.GridLines.Both);
			}
			set {
				base.GridLinesVisible = value ?  Xwt.GridLines.Horizontal : Xwt.GridLines.None;
			}
		}

		protected new IListBoxEventSink EventSink {
			get { return (IListBoxEventSink)((WidgetBackend)this).EventSink; }
		}

		public override void Initialize ()
		{
			base.Initialize ();
			Widget.HeadersVisible = false;

			theColumn = new Gtk.TreeViewColumn ();
			Widget.AppendColumn (theColumn);

			var cr = new Gtk.CellRendererText ();
			theColumn.PackStart (cr, false);
			theColumn.AddAttribute (cr, "text", 0);
		}

		public void SetViews (CellViewCollection views)
		{
			theColumn.Clear ();
			foreach (var v in views)
				CellUtil.CreateCellRenderer (ApplicationContext, Frontend, this, theColumn, v);
		}
	}
}


text:
import { GlSprintf, GlIcon, GlDeprecatedDropdown, GlDeprecatedDropdownItem } from '@gitlab/ui';
import { shallowMount } from '@vue/test-utils';
import EnvironmentLogs from '~/logs/components/environment_logs.vue';

import { createStore } from '~/logs/stores';
import { scrollDown } from '~/lib/utils/scroll_utils';
import {
  mockEnvName,
  mockEnvironments,
  mockPods,
  mockLogsResult,
  mockTrace,
  mockEnvironmentsEndpoint,
  mockDocumentationPath,
  mockManagedAppsEndpoint,
} from '../mock_data';

jest.mock('~/lib/utils/scroll_utils');

const module = 'environmentLogs';

jest.mock('lodash/throttle', () =>
  jest.fn(func => {
    return func;
  }),
);

describe('EnvironmentLogs', () => {
  let store;
  let dispatch;
  let wrapper;
  let state;

  const propsData = {
    environmentName: mockEnvName,
    environmentsPath: mockEnvironmentsEndpoint,
    clusterApplicationsDocumentationPath: mockDocumentationPath,
    clustersPath: mockManagedAppsEndpoint,
  };

  const updateControlBtnsMock = jest.fn();

  const findEnvironmentsDropdown = () => wrapper.find('.js-environments-dropdown');

  const findSimpleFilters = () => wrapper.find({ ref: 'log-simple-filters' });
  const findAdvancedFilters = () => wrapper.find({ ref: 'log-advanced-filters' });
  const findElasticsearchNotice = () => wrapper.find({ ref: 'elasticsearchNotice' });
  const findLogControlButtons = () => wrapper.find({ name: 'log-control-buttons-stub' });

  const findInfiniteScroll = () => wrapper.find({ ref: 'infiniteScroll' });
  const findLogTrace = () => wrapper.find({ ref: 'logTrace' });
  const findLogFooter = () => wrapper.find({ ref: 'logFooter' });
  const getInfiniteScrollAttr = attr => parseInt(findInfiniteScroll().attributes(attr), 10);

  const mockSetInitData = () => {
    state.pods.options = mockPods;
    state.environments.current = mockEnvName;
    [state.pods.current] = state.pods.options;

    state.logs.lines = [];
  };

  const mockShowPodLogs = () => {
    state.pods.options = mockPods;
    [state.pods.current] = mockPods;

    state.logs.lines = mockLogsResult;
  };

  const mockFetchEnvs = () => {
    state.environments.options = mockEnvironments;
  };

  const initWrapper = () => {
    wrapper = shallowMount(EnvironmentLogs, {
      propsData,
      store,
      stubs: {
        LogControlButtons: {
          name: 'log-control-buttons-stub',
          template: '<div/>',
          methods: {
            update: updateControlBtnsMock,
          },
          props: {
            scrollDownButtonDisabled: false,
          },
        },
        GlInfiniteScroll: {
          name: 'gl-infinite-scroll',
          template: `
          <div>
            <slot name="header"></slot>
            <slot name="items"></slot>
            <slot></slot>
          </div>
          `,
        },
        GlSprintf,
      },
    });
  };

  beforeEach(() => {
    store = createStore();
    state = store.state.environmentLogs;

    jest.spyOn(store, 'dispatch').mockResolvedValue();

    dispatch = store.dispatch;
  });

  afterEach(() => {
    store.dispatch.mockReset();

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

  it('displays UI elements', () => {
    initWrapper();

    expect(wrapper.isVueInstance()).toBe(true);

    expect(findEnvironmentsDropdown().is(GlDeprecatedDropdown)).toBe(true);
    expect(findSimpleFilters().exists()).toBe(true);
    expect(findLogControlButtons().exists()).toBe(true);

    expect(findInfiniteScroll().exists()).toBe(true);
    expect(findLogTrace().exists()).toBe(true);
  });

  it('mounted inits data', () => {
    initWrapper();

    expect(dispatch).toHaveBeenCalledWith(`${module}/setInitData`, {
      timeRange: expect.objectContaining({
        default: true,
      }),
      environmentName: mockEnvName,
      podName: null,
    });

    expect(dispatch).toHaveBeenCalledWith(`${module}/fetchEnvironments`, mockEnvironmentsEndpoint);
  });

  describe('loading state', () => {
    beforeEach(() => {
      state.pods.options = [];

      state.logs.lines = [];
      state.logs.isLoading = true;

      state.environments = {
        options: [],
        isLoading: true,
      };

      initWrapper();
    });

    it('does not display an alert to upgrade to ES', () => {
      expect(findElasticsearchNotice().exists()).toBe(false);
    });

    it('displays a disabled environments dropdown', () => {
      expect(findEnvironmentsDropdown().attributes('disabled')).toBe('true');
      expect(findEnvironmentsDropdown().findAll(GlDeprecatedDropdownItem).length).toBe(0);
    });

    it('does not update buttons state', () => {
      expect(updateControlBtnsMock).not.toHaveBeenCalled();
    });

    it('shows an infinite scroll with no content', () => {
      expect(getInfiniteScrollAttr('fetched-items')).toBe(0);
    });

    it('shows an infinite scroll container with no set max-height ', () => {
      expect(findInfiniteScroll().attributes('max-list-height')).toBeUndefined();
    });

    it('shows a logs trace', () => {
      expect(findLogTrace().text()).toBe('');
      expect(
        findLogTrace()
          .find('.js-build-loader-animation')
          .isVisible(),
      ).toBe(true);
    });
  });

  describe('k8s environment', () => {
    beforeEach(() => {
      state.pods.options = [];

      state.logs.lines = [];
      state.logs.isLoading = false;

      state.environments = {
        options: mockEnvironments,
        current: 'staging',
        isLoading: false,
      };

      initWrapper();
    });

    it('displays an alert to upgrade to ES', () => {
      expect(findElasticsearchNotice().exists()).toBe(true);
    });

    it('displays simple filters for kubernetes logs API', () => {
      expect(findSimpleFilters().exists()).toBe(true);
      expect(findAdvancedFilters().exists()).toBe(false);
    });
  });

  describe('state with data', () => {
    beforeEach(() => {
      dispatch.mockImplementation(actionName => {
        if (actionName === `${module}/setInitData`) {
          mockSetInitData();
        } else if (actionName === `${module}/showPodLogs`) {
          mockShowPodLogs();
        } else if (actionName === `${module}/fetchEnvironments`) {
          mockFetchEnvs();
          mockShowPodLogs();
        }
      });

      initWrapper();
    });

    afterEach(() => {
      scrollDown.mockReset();
      updateControlBtnsMock.mockReset();
    });

    it('does not display an alert to upgrade to ES', () => {
      expect(findElasticsearchNotice().exists()).toBe(false);
    });

    it('populates environments dropdown', () => {
      const items = findEnvironmentsDropdown().findAll(GlDeprecatedDropdownItem);
      expect(findEnvironmentsDropdown().props('text')).toBe(mockEnvName);
      expect(items.length).toBe(mockEnvironments.length);
      mockEnvironments.forEach((env, i) => {
        const item = items.at(i);
        expect(item.text()).toBe(env.name);
      });
    });

    it('dropdown has one environment selected', () => {
      const items = findEnvironmentsDropdown().findAll(GlDeprecatedDropdownItem);
      mockEnvironments.forEach((env, i) => {
        const item = items.at(i);

        if (item.text() !== mockEnvName) {
          expect(item.find(GlIcon).classes('invisible')).toBe(true);
        } else {
          expect(item.find(GlIcon).classes('invisible')).toBe(false);
        }
      });
    });

    it('displays advanced filters for elasticsearch logs API', () => {
      expect(findSimpleFilters().exists()).toBe(false);
      expect(findAdvancedFilters().exists()).toBe(true);
    });

    it('shows infinite scroll with content', () => {
      expect(getInfiniteScrollAttr('fetched-items')).toBe(mockTrace.length);
    });

    it('populates logs trace', () => {
      const trace = findLogTrace();
      expect(trace.text().split('\n').length).toBe(mockTrace.length);
      expect(trace.text().split('\n')).toEqual(mockTrace);
    });

    it('populates footer', () => {
      const footer = findLogFooter().text();

      expect(footer).toContain(`${mockLogsResult.length} results`);
    });

    describe('when user clicks', () => {
      it('environment name, trace is refreshed', () => {
        const items = findEnvironmentsDropdown().findAll(GlDeprecatedDropdownItem);
        const index = 1; // any env

        expect(dispatch).not.toHaveBeenCalledWith(`${module}/showEnvironment`, expect.anything());

        items.at(index).vm.$emit('click');

        expect(dispatch).toHaveBeenCalledWith(
          `${module}/showEnvironment`,
          mockEnvironments[index].name,
        );
      });

      it('refresh button, trace is refreshed', () => {
        expect(dispatch).not.toHaveBeenCalledWith(`${module}/refreshPodLogs`, undefined);

        findLogControlButtons().vm.$emit('refresh');

        expect(dispatch).toHaveBeenCalledWith(`${module}/refreshPodLogs`, undefined);
      });
    });
  });

  describe('listeners', () => {
    beforeEach(() => {
      initWrapper();
    });

    it('attaches listeners in components', () => {
      expect(findInfiniteScroll().vm.$listeners).toEqual({
        topReached: expect.any(Function),
        scroll: expect.any(Function),
      });
    });

    it('`topReached` when not loading', () => {
      expect(store.dispatch).not.toHaveBeenCalledWith(`${module}/fetchMoreLogsPrepend`, undefined);

      findInfiniteScroll().vm.$emit('topReached');

      expect(store.dispatch).toHaveBeenCalledWith(`${module}/fetchMoreLogsPrepend`, undefined);
    });

    it('`topReached` does not fetches more logs when already loading', () => {
      state.logs.isLoading = true;
      findInfiniteScroll().vm.$emit('topReached');

      expect(store.dispatch).not.toHaveBeenCalledWith(`${module}/fetchMoreLogsPrepend`, undefined);
    });

    it('`topReached` fetches more logs', () => {
      state.logs.isLoading = true;
      findInfiniteScroll().vm.$emit('topReached');

      expect(store.dispatch).not.toHaveBeenCalledWith(`${module}/fetchMoreLogsPrepend`, undefined);
    });

    it('`scroll` on a scrollable target results in enabled scroll buttons', () => {
      const target = { scrollTop: 10, clientHeight: 10, scrollHeight: 21 };

      state.logs.isLoading = true;
      findInfiniteScroll().vm.$emit('scroll', { target });

      return wrapper.vm.$nextTick(() => {
        expect(findLogControlButtons().props('scrollDownButtonDisabled')).toEqual(false);
      });
    });

    it('`scroll` on a non-scrollable target in disabled scroll buttons', () => {
      const target = { scrollTop: 10, clientHeight: 10, scrollHeight: 20 };

      state.logs.isLoading = true;
      findInfiniteScroll().vm.$emit('scroll', { target });

      return wrapper.vm.$nextTick(() => {
        expect(findLogControlButtons().props('scrollDownButtonDisabled')).toEqual(true);
      });
    });

    it('`scroll` on no target results in disabled scroll buttons', () => {
      state.logs.isLoading = true;
      findInfiniteScroll().vm.$emit('scroll', { target: undefined });

      return wrapper.vm.$nextTick(() => {
        expect(findLogControlButtons().props('scrollDownButtonDisabled')).toEqual(true);
      });
    });
  });
});


text:
package ca.cmpt213.as3.UI.GUI;

import javax.swing.*;
import java.awt.*;

/**
 * Created by Nova on 13/03/2017.
 */
public class StatusBoxPanel extends JPanel {
    private static JLabel statusBox = new JLabel("Status", SwingConstants.CENTER);

    /*
    public StatusBoxPanel() {
        statusBox = new JLabel("Status", SwingConstants.CENTER);
    }
*/

    public static Component getStatusBoxPanel() {
        statusBox.setBorder(BorderFactory.createLineBorder(Color.BLACK, 3));
        statusBox.setSize(new Dimension(50,10));
        statusBox.setBackground(Color.WHITE);
        return statusBox;
    }

    public static void setStatusBoxText(String text) {
        statusBox.setText(text);
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Employee',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=200)),
                ('availability', models.BooleanField(default=True)),
                ('profile_pic', models.ImageField(upload_to=b'')),
            ],
        ),
        migrations.CreateModel(
            name='Pair',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('employee_one', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='employee_one', to='pairs.Employee')),
                ('employee_two', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='employee_two', to='pairs.Employee')),
            ],
        ),
        migrations.CreateModel(
            name='PairCall',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('is_done', models.BooleanField(default=False)),
                ('date', models.DateField()),
                ('picture', models.ImageField(upload_to=b'')),
                ('caption', models.CharField(max_length=400)),
                ('pair', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='pairs.Pair')),
            ],
        ),
        migrations.CreateModel(
            name='Team',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=200)),
            ],
        ),
        migrations.AddField(
            model_name='employee',
            name='team',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='pairs.Team'),
        ),
    ]


text:
package com.palantir.remoting3.jaxrs.feignimpl;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Lists;
import feign.Contract;
import feign.MethodMetadata;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;

/**
 * Decorates a {@link Contract} and uses {@link GuavaNullOptionalExpander} for any {@link QueryParam} parameters,
 * {@link GuavaEmptyOptionalExpander} for any {@link HeaderParam} parameters, and throws a {@link RuntimeException}
 * at first encounter of an {@link Optional} typed {@link PathParam}.
 * <p>
 * {@link PathParam}s require a value, and so we explicitly disallow use with {@link Optional}.
 */
public final class GuavaOptionalAwareContract extends AbstractDelegatingContract {

    public GuavaOptionalAwareContract(Contract delegate) {
        super(delegate);
    }

    @Override
    protected void processMetadata(Class<?> targetType, Method method, MethodMetadata metadata) {
        Class<?>[] parameterTypes = method.getParameterTypes();
        Annotation[][] annotations = method.getParameterAnnotations();
        for (int i = 0; i < parameterTypes.length; i++) {
            Class<?> cls = parameterTypes[i];
            if (cls.equals(Optional.class)) {
                FluentIterable<Class<?>> paramAnnotations =
                        FluentIterable.from(Lists.newArrayList(annotations[i])).transform(EXTRACT_CLASS);
                if (paramAnnotations.contains(HeaderParam.class)) {
                    metadata.indexToExpanderClass().put(i, GuavaEmptyOptionalExpander.class);
                } else if (paramAnnotations.contains(QueryParam.class)) {
                    metadata.indexToExpanderClass().put(i, GuavaNullOptionalExpander.class);
                } else if (paramAnnotations.contains(PathParam.class)) {
                    throw new RuntimeException(String.format(
                            "Cannot use Guava Optionals with PathParams. (Class: %s, Method: %s, Param: arg%d)",
                            targetType.getName(), method.getName(), i));
                }
            }
        }
    }

    private static final Function<Annotation, Class<?>> EXTRACT_CLASS = input -> input.annotationType();
}