text:
package net.runelite.client.plugins.questlist;

import com.google.common.collect.ImmutableList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.List;
import java.util.stream.Collectors;
import javax.inject.Inject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import net.runelite.api.Client;
import net.runelite.api.GameState;
import net.runelite.api.ScriptID;
import net.runelite.api.SoundEffectID;
import net.runelite.api.SpriteID;
import net.runelite.api.VarClientInt;
import net.runelite.api.Varbits;
import net.runelite.api.events.GameStateChanged;
import net.runelite.api.events.VarClientIntChanged;
import net.runelite.api.events.VarbitChanged;
import net.runelite.api.events.WidgetLoaded;
import net.runelite.api.widgets.JavaScriptCallback;
import net.runelite.api.widgets.Widget;
import net.runelite.api.widgets.WidgetID;
import net.runelite.api.widgets.WidgetInfo;
import net.runelite.api.widgets.WidgetPositionMode;
import net.runelite.api.widgets.WidgetType;
import net.runelite.client.callback.ClientThread;
import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.game.chatbox.ChatboxPanelManager;
import net.runelite.client.game.chatbox.ChatboxTextInput;
import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.util.Text;

@PluginDescriptor(
	name = "Quest List",
	description = "Adds searching and filtering to the quest list"
)
public class QuestListPlugin extends Plugin
{
	private static final int ENTRY_PADDING = 8;
	private static final List<String> QUEST_HEADERS = ImmutableList.of("Free Quests", "Members' Quests", "Miniquests");

	private static final int SPRITE_SHOW_COMPLETED = SpriteID.OPTIONS_ZOOM_SLIDER_THUMB;
	private static final int SPRITE_HIDE_COMPLETED = SpriteID.SQUARE_CHECK_BOX;

	private static final String MENU_OPEN = "Open";
	private static final String MENU_CLOSE = "Close";

	private static final String MENU_SHOW = "Show";
	private static final String MENU_HIDE = "Hide";

	private static final String MENU_SEARCH = "Search";
	private static final String MENU_COMPLETED = "Completed Quests";

	@Inject
	private Client client;

	@Inject
	private ChatboxPanelManager chatboxPanelManager;

	@Inject
	private ClientThread clientThread;

	private ChatboxTextInput searchInput;
	private Widget questSearchButton;
	private Widget questHideCompletedButton;

	private EnumMap<QuestContainer, Collection<QuestWidget>> questSet;

	private boolean hideCompleted;

	@Subscribe
	public void onGameStateChanged(GameStateChanged e)
	{
		if (e.getGameState() == GameState.LOGGING_IN)
		{
			hideCompleted = false;
		}
	}

	@Subscribe
	public void onWidgetLoaded(WidgetLoaded widgetLoaded)
	{
		if (widgetLoaded.getGroupId() == WidgetID.QUESTLIST_GROUP_ID)
		{
			Widget header = client.getWidget(WidgetInfo.QUESTLIST_BOX);
			if (header != null)
			{
				questSearchButton = header.createChild(-1, WidgetType.GRAPHIC);
				questSearchButton.setSpriteId(SpriteID.GE_SEARCH);
				questSearchButton.setOriginalWidth(18);
				questSearchButton.setOriginalHeight(17);
				questSearchButton.setXPositionMode(WidgetPositionMode.ABSOLUTE_RIGHT);
				questSearchButton.setOriginalX(5);
				questSearchButton.setOriginalY(0);
				questSearchButton.setHasListener(true);
				questSearchButton.setAction(1, MENU_OPEN);
				questSearchButton.setOnOpListener((JavaScriptCallback) e -> openSearch());
				questSearchButton.setName(MENU_SEARCH);
				questSearchButton.revalidate();

				questHideCompletedButton = header.createChild(-1, WidgetType.GRAPHIC);
				redrawHideCompletedButton();

				questHideCompletedButton.setOriginalWidth(18);
				questHideCompletedButton.setOriginalHeight(17);
				questHideCompletedButton.setXPositionMode(WidgetPositionMode.ABSOLUTE_RIGHT);
				questHideCompletedButton.setOriginalX(25);
				questHideCompletedButton.setOriginalY(0);
				questHideCompletedButton.setHasListener(true);
				questHideCompletedButton.setOnOpListener((JavaScriptCallback) e -> toggleHideCompleted());
				questHideCompletedButton.setName(MENU_COMPLETED);

				questHideCompletedButton.revalidate();

				questSet = new EnumMap<>(QuestContainer.class);

				if (!header.isHidden())
				{
					updateFilter();
				}
			}
		}
	}

	@Subscribe
	public void onVarbitChanged(VarbitChanged varbitChanged)
	{
		if (isChatboxOpen() && !isOnQuestTab())
		{
			chatboxPanelManager.close();
		}
	}

	@Subscribe
	public void onVarClientIntChanged(VarClientIntChanged varClientIntChanged)
	{
		if (varClientIntChanged.getIndex() == VarClientInt.INVENTORY_TAB.getIndex())
		{
			if (isChatboxOpen() && !isOnQuestTab())
			{
				chatboxPanelManager.close();
			}
		}
	}

	private void toggleHideCompleted()
	{
		hideCompleted = !hideCompleted;
		redrawHideCompletedButton();

		updateFilter();
		client.playSoundEffect(SoundEffectID.UI_BOOP);
	}

	private void redrawHideCompletedButton()
	{
		questHideCompletedButton.setSpriteId(hideCompleted ? SPRITE_HIDE_COMPLETED : SPRITE_SHOW_COMPLETED);
		questHideCompletedButton.setAction(1, hideCompleted ? MENU_SHOW : MENU_HIDE);
	}

	private boolean isOnQuestTab()
	{
		return client.getVar(Varbits.QUEST_TAB) == 0 && client.getVar(VarClientInt.INVENTORY_TAB) == 2;
	}

	private boolean isChatboxOpen()
	{
		return searchInput != null && chatboxPanelManager.getCurrentInput() == searchInput;
	}

	private void closeSearch()
	{
		updateFilter("");
		chatboxPanelManager.close();
		client.playSoundEffect(SoundEffectID.UI_BOOP);
	}

	private void openSearch()
	{
		updateFilter("");
		client.playSoundEffect(SoundEffectID.UI_BOOP);
		questSearchButton.setAction(1, MENU_CLOSE);
		questSearchButton.setOnOpListener((JavaScriptCallback) e -> closeSearch());
		searchInput = chatboxPanelManager.openTextInput("Search quest list")
			.onChanged(s -> clientThread.invokeLater(() -> updateFilter(s)))
			.onClose(() ->
			{
				clientThread.invokeLater(() -> updateFilter(""));
				questSearchButton.setOnOpListener((JavaScriptCallback) e -> openSearch());
				questSearchButton.setAction(1, MENU_OPEN);
			})
			.build();
	}

	private void updateFilter()
	{
		String filter = "";
		if (isChatboxOpen())
		{
			filter = searchInput.getValue();
		}

		updateFilter(filter);
	}

	private void updateFilter(String filter)
	{
		filter = filter.toLowerCase();
		final Widget container = client.getWidget(WidgetInfo.QUESTLIST_CONTAINER);

		final Widget freeList = client.getWidget(QuestContainer.FREE_QUESTS.widgetInfo);
		final Widget memberList = client.getWidget(QuestContainer.MEMBER_QUESTS.widgetInfo);
		final Widget miniList = client.getWidget(QuestContainer.MINI_QUESTS.widgetInfo);

		if (container == null || freeList == null || memberList == null || miniList == null)
		{
			return;
		}

		updateList(QuestContainer.FREE_QUESTS, filter);
		updateList(QuestContainer.MEMBER_QUESTS, filter);
		updateList(QuestContainer.MINI_QUESTS, filter);

		memberList.setOriginalY(freeList.getOriginalY() + freeList.getOriginalHeight() + ENTRY_PADDING);
		miniList.setOriginalY(memberList.getOriginalY() + memberList.getOriginalHeight() + ENTRY_PADDING);

		// originalHeight is changed within updateList so revalidate all lists
		freeList.revalidate();
		memberList.revalidate();
		miniList.revalidate();

		int y = miniList.getRelativeY() + miniList.getHeight() + 10;

		int newHeight = 0;
		if (container.getScrollHeight() > 0)
		{
			newHeight = (container.getScrollY() * y) / container.getScrollHeight();
		}

		container.setScrollHeight(y);
		container.revalidateScroll();

		client.runScript(
			ScriptID.UPDATE_SCROLLBAR,
			WidgetInfo.QUESTLIST_SCROLLBAR.getId(),
			WidgetInfo.QUESTLIST_CONTAINER.getId(),
			newHeight
		);
	}

	private void updateList(QuestContainer questContainer, String filter)
	{
		Widget list = client.getWidget(questContainer.widgetInfo);
		if (list == null)
		{
			return;
		}

		Collection<QuestWidget> quests = questSet.get(questContainer);

		if (quests != null)
		{
			// Check to make sure the list hasn't been rebuild since we were last her
			// Do this by making sure the list's dynamic children are the same as when we last saw them
			if (quests.stream().noneMatch(w ->
			{
				Widget codeWidget = w.getQuest();
				if (codeWidget == null)
				{
					return false;
				}
				return list.getChild(codeWidget.getIndex()) == codeWidget;
			}))
			{
				quests = null;
			}
		}

		if (quests == null)
		{
			// Find all of the widgets that we care about, sorting by their Y value
			quests = Arrays.stream(list.getDynamicChildren())
				.sorted(Comparator.comparing(Widget::getRelativeY))
				.filter(w -> !w.isSelfHidden() && !QUEST_HEADERS.contains(w.getText()))
				.map(w -> new QuestWidget(w, Text.removeTags(w.getText()).toLowerCase()))
				.collect(Collectors.toList());
			questSet.put(questContainer, quests);
		}

		// offset because of header
		int y = 20;
		for (QuestWidget questInfo : quests)
		{
			Widget quest = questInfo.getQuest();
			QuestState questState = QuestState.getByColor(quest.getTextColor());

			boolean hidden = !(filter.isEmpty()
				|| questInfo.getTitle().contains(filter))
				|| (filter.isEmpty() && hideCompleted && questState == QuestState.COMPLETE);

			quest.setHidden(hidden);
			quest.setOriginalY(y);
			quest.revalidate();

			if (!hidden)
			{
				y += quest.getHeight();
			}
		}

		list.setOriginalHeight(y);
	}

	@AllArgsConstructor
	@Getter
	private enum QuestContainer
	{
		FREE_QUESTS(WidgetInfo.QUESTLIST_FREE_CONTAINER),
		MEMBER_QUESTS(WidgetInfo.QUESTLIST_MEMBERS_CONTAINER),
		MINI_QUESTS(WidgetInfo.QUESTLIST_MINIQUEST_CONTAINER);

		private final WidgetInfo widgetInfo;
	}

	@AllArgsConstructor
	@Getter
	private enum QuestState
	{
		NOT_STARTED(0xff0000), IN_PROGRESS(0xffff00), COMPLETE(0xdc10d);

		private final int color;

		static QuestState getByColor(int color)
		{
			for (QuestState value : values())
			{
				if (value.getColor() == color)
				{
					return value;
				}
			}

			return null;
		}
	}

	@Data
	@AllArgsConstructor
	private static class QuestWidget
	{
		private Widget quest;
		private String title;
	}
}


text:
<?php

namespace MicrosoftAzure\Storage\Tests\Functional\Table;

use MicrosoftAzure\Storage\Tests\Functional\Table\Enums\MutatePivot;
use MicrosoftAzure\Storage\Common\Internal\Utilities;
use MicrosoftAzure\Storage\Table\Models\EdmType;
use MicrosoftAzure\Storage\Table\Models\Entity;
use MicrosoftAzure\Storage\Table\Models\Property;
use MicrosoftAzure\Storage\Table\Models\Filters\BinaryFilter;
use MicrosoftAzure\Storage\Table\Models\Filters\ConstantFilter;
use MicrosoftAzure\Storage\Table\Models\Filters\Filter;
use MicrosoftAzure\Storage\Table\Models\Filters\PropertyNameFilter;
use MicrosoftAzure\Storage\Table\Models\Filters\QueryStringFilter;
use MicrosoftAzure\Storage\Table\Models\Filters\UnaryFilter;

class TableServiceFunctionalTestUtils
{
    static function isEqNotInTopLevel($filter)
    {
        return self::isEqNotInTopLevelWorker($filter, 0);
    }

    private static function isEqNotInTopLevelWorker($filter, $depth)
    {
        if (is_null($filter)) {
            return false;
        } else if ($filter instanceof UnaryFilter) {
            return self::isEqNotInTopLevelWorker($filter->getOperand(), $depth + 1);
        } else if ($filter instanceof BinaryFilter) {
            $binaryFilter = $filter;
            if ($binaryFilter->getOperator() == ('eq') && $depth != 0) {
                return true;
            }

            $left = self::isEqNotInTopLevelWorker($binaryFilter->getLeft(), $depth + 1);
            $right = self::isEqNotInTopLevelWorker($binaryFilter->getRight(), $depth + 1);
            return $left || $right;
        } else {
            return false;
        }
    }

    static function cloneRemoveEqNotInTopLevel($filter)
    {
        return self::cloneRemoveEqNotInTopLevelWorker($filter, 0);
    }

    private static function cloneRemoveEqNotInTopLevelWorker($filter, $depth)
    {
        if ($filter instanceof PropertyNameFilter) {
            $ret = new PropertyNameFilter($filter->getPropertyName());
            return $ret;
        } else if ($filter instanceof ConstantFilter) {
            $ret = new ConstantFilter($filter->getEdmType(), $filter->getValue());
            return $ret;
        } else if ($filter instanceof UnaryFilter) {
            $operand = self::cloneRemoveEqNotInTopLevelWorker($filter->getOperand(), $depth + 1);
            $ret = new UnaryFilter($filter->getOperator(), $operand);
            return $ret;
        } else if ($filter instanceof BinaryFilter) {
            if ($filter->getOperator() == ('eq') && $depth != 0) {
                return Filter::applyConstant(false);
            }
            $left = self::cloneRemoveEqNotInTopLevelWorker($filter->getLeft(), $depth + 1);
            $right = self::cloneRemoveEqNotInTopLevelWorker($filter->getRight(), $depth + 1);
            $ret = new BinaryFilter($left, $filter->getOperator(), $right);
            return $ret;
        } else if ($filter instanceof QueryStringFilter) {
            $ret = new QueryStringFilter($filter->getQueryString());
            return $ret;
        } else {
            throw new \Exception();
        }
    }

    public static function filterList($filter, $input)
    {
        $output = array();
        foreach($input as $i)  {
            if (self::filterInterperter($filter, $i)) {
                array_push($output, $i);
            }
        }
        return $output;
    }

    public static function filterEntityList($filter, $input)
    {
        $output = array();
        foreach($input as $i)  {
            $result = self::filterInterperter($filter, $i);
            if (!is_null($result) && $result) {
                array_push($output, $i);
            }
        }
        return $output;
    }

    static function cloneEntity($initialEnt)
    {
        $ret = new Entity();
        $initialProps = $initialEnt->getProperties();
        $retProps = array();
        foreach($initialProps as $propName => $initialProp)  {
            // Don't mess with the timestamp.
            if ($propName == ('Timestamp')) {
                continue;
            }

            $retProp = new Property();
            $retProp->setEdmType($initialProp->getEdmType());
            $retProp->setValue($initialProp->getValue());
            $retProps[$propName] = $retProp;
        }
        $ret->setProperties($retProps);
        $ret->setETag($initialEnt->getETag());
        return $ret;
    }

    static function mutateEntity($ent, $pivot)
    {
        if ($pivot == MutatePivot::CHANGE_VALUES) {
            self::mutateEntityChangeValues($ent);
        } else if ($pivot == MutatePivot::ADD_PROPERTY) {
            $ent->addProperty('BOOLEAN' . TableServiceFunctionalTestData::getNewKey(), EdmType::BOOLEAN, true);
            $ent->addProperty('DATETIME' . TableServiceFunctionalTestData::getNewKey(), EdmType::DATETIME, Utilities::convertToDateTime('2012-01-26T18:26:19.0000473Z'));
            $ent->addProperty('DOUBLE' . TableServiceFunctionalTestData::getNewKey(), EdmType::DOUBLE, 12345678901);
            $ent->addProperty('GUID' . TableServiceFunctionalTestData::getNewKey(), EdmType::GUID, '90ab64d6-d3f8-49ec-b837-b8b5b6367b74');
            $ent->addProperty('INT32' . TableServiceFunctionalTestData::getNewKey(), EdmType::INT32, 23);
            $ent->addProperty('INT64' . TableServiceFunctionalTestData::getNewKey(), EdmType::INT64, '-1');
            $ent->addProperty('STRING' . TableServiceFunctionalTestData::getNewKey(), EdmType::STRING, 'this is a test!');
        } else if ($pivot == MutatePivot::REMOVE_PROPERTY) {
            $propToRemove = null;
            foreach($ent->getProperties() as $propName => $propValue)  {
                // Don't mess with the keys.
                if ($propName == ('PartitionKey') || $propName == ('RowKey') || $propName == ('Timestamp')) {
                    continue;
                }
                $propToRemove = $propName;
                break;
            }

            $props = $ent->getProperties();
            unset($props[$propToRemove]);
        } else if ($pivot == MutatePivot::NULL_PROPERTY) {
            foreach($ent->getProperties() as $propName => $propValue)  {
                // Don't mess with the keys.
                if ($propName == ('PartitionKey') || $propName == ('RowKey') || $propName == ('Timestamp')) {
                    continue;
                }
                $propValue->setValue(null);
            }
        }
    }

    private static function mutateEntityChangeValues($ent)
    {
        foreach($ent->getProperties() as $propName => $initialProp)  {
            // Don't mess with the keys.
            if ($propName == ('PartitionKey') || $propName == ('RowKey') || $propName == ('Timestamp')) {
                continue;
            }

            $ptype = $initialProp->getEdmType();
            if (is_null($ptype)) {
                $eff = $initialProp->getValue();
                $initialProp->setValue($eff . 'AndMore');
            } else if ($ptype == (EdmType::DATETIME)) {
                $value = $initialProp->getValue();
                if (is_null($value)) {
                    $value = new \DateTime("1/26/1692");
                }
                $value->modify('+1 day');
                $initialProp->setValue($value);
            } else if ($ptype == (EdmType::BINARY)) {
                $eff = $initialProp->getValue();
                $initialProp->setValue($eff . 'x');
            } else if ($ptype == (EdmType::BOOLEAN)) {
                $eff = $initialProp->getValue();
                $initialProp->setValue(!$eff);
            } else if ($ptype == (EdmType::DOUBLE)) {
                $eff = $initialProp->getValue();
                $initialProp->setValue($eff + 1);
            } else if ($ptype == (EdmType::GUID)) {
                $initialProp->setValue(Utilities::getGuid());
            } else if ($ptype == (EdmType::INT32)) {
                $eff = $initialProp->getValue();
                $eff = ($eff > 10 ? 0 : $eff + 1);
                $initialProp->setValue($eff);
            } else if ($ptype == (EdmType::INT64)) {
                $eff = $initialProp->getValue();
                $eff = ($eff > 10 ? 0 : $eff + 1);
                $initialProp->setValue(strval($eff));
            } else if ($ptype == (EdmType::STRING)) {
                $eff = $initialProp->getValue();
                $initialProp->setValue($eff . 'AndMore');
            }
        }
    }

    public static function filterToString($filter, $pad = '  ')
    {
        if (is_null($filter)) {
            return $pad . 'filter <null>' . "\n";
        } else if ($filter instanceof PropertyNameFilter) {
            return $pad . 'entity.' . $filter->getPropertyName() . "\n";
        } else if ($filter instanceof ConstantFilter) {
           $ret = $pad;
           if (is_null($filter->getValue())) {
               $ret .= 'constant <null>';
           } else if (is_bool ($filter->getValue())) {
               $ret .= ($filter->getValue() ? 'true' : 'false');
           }  else {
               $ret .=  '\'' . FunctionalTestBase::tmptostring($filter->getValue()) . '\'';
           }
           return $ret . "\n";
        } else if ($filter instanceof UnaryFilter) {
            $ret = $pad . $filter->getOperator() . "\n";
            $ret .= self::filterToString($filter->getOperand(), $pad . '  ');
            return $ret;
        } else if ($filter instanceof BinaryFilter) {
            $ret = self::filterToString($filter->getLeft(), $pad . '  ');
            $ret .= $pad . $filter->getOperator() . "\n";
            $ret .= self::filterToString($filter->getRight(), $pad . '  ');
            return $ret;
        }
    }

    private static function filterInterperter($filter, $obj)
    {
        if (is_null($filter)) {
            return true;
        } else if (is_null($obj)) {
            return false;
        } else if ($filter instanceof PropertyNameFilter) {
            $name = $filter->getPropertyName();
            $value = ($obj instanceof Entity ? $obj->getPropertyValue($name) : $obj->{$name});
            return $value;
        } else if ($filter instanceof ConstantFilter) {
            $value = $filter->getValue();
            return $value;
        } else if ($filter instanceof UnaryFilter) {
            $ret = null;
            if ($filter->getOperator() == ('not')) {
                $op = self::filterInterperter($filter->getOperand(), $obj);
                if (is_null($op)) {
                    // http://msdn.microsoft/com/en-us/library/ms191504.aspx
                    // Not (null) -> null
                    $ret = null;
                } else {
                    $ret = !$op;
                }

                return $ret;
            }
        } else if ($filter instanceof BinaryFilter) {
            $left = self::filterInterperter($filter->getLeft(), $obj);
            $right = self::filterInterperter($filter->getRight(), $obj);

            $ret = null;
            if ($filter->getOperator() == ('and')) {
                $ret = self::nullPropAnd($left, $right);
            } else if ($filter->getOperator() == ('or')) {
                $ret = self::nullPropOr($left, $right);
            } else if ($filter->getOperator() == ('eq')) {
                $ret = self::nullPropEq($left, $right);
            } else if ($filter->getOperator() == ('ne')) {
                $ret = self::nullPropNe($left, $right);
            } else if ($filter->getOperator() == ('ge')) {
                $ret = self::nullPropGe($left, $right);
            } else if ($filter->getOperator() == ('gt')) {
                $ret = self::nullPropGt($left, $right);
            } else if ($filter->getOperator() == ('lt')) {
                $ret = self::nullPropLt($left, $right);
            } else if ($filter->getOperator() == ('le')) {
                $ret = self::nullPropLe($left, $right);
            }

            return $ret;
        }

        throw new \Exception();
    }

    private static function nullPropAnd($left, $right)
    {
        // http://msdn.microsoft.com/en-us/library/ms191504.aspx
        if (is_null($left) && is_null($right)) {
            return null;
        } else if (is_null($left)) {
            return ($right ? null : false);
        } else if (is_null($right)) {
            return ($left ? null : false);
        } else {
            return $left && $right;
        }
    }

    private static function nullPropOr($left, $right)
    {
        // http://msdn.microsoft.com/en-us/library/ms191504.aspx
        if (is_null($left) && is_null($right)) {
            return null;
        } else if (is_null($left)) {
            return ($right ? true : null);
        } else if (is_null($right)) {
            return ($left ? true : null);
        } else {
            return $left || $right;
        }
    }

    private static function nullPropEq($left, $right)
    {
        if (is_null($left) || is_null($right)) {
            return null;
        } else if (is_string($left) || is_string($right)) {
            return ('' . $left) == ('' . $right);
        }
        return $left == $right;
    }

    private static function nullPropNe($left, $right)
    {
        if (is_null($left) || is_null($right)) {
            return null;
        } else if (is_string($left) || is_string($right)) {
            return ('' . $left) != ('' . $right);
        }
        return $left != $right;
    }

    private static function nullPropGt($left, $right)
    {
        if (is_null($left) || is_null($right)) {
            return null;
        } else if (is_string($left) || is_string($right)) {
            return ('' . $left) > ('' . $right);
        }
        return $left > $right;
    }

    private static function nullPropGe($left, $right)
    {
        if (is_null($left) || is_null($right)) {
            return null;
        } else if (is_string($left) || is_string($right)) {
            return ('' . $left) >= ('' . $right);
        }
        return $left >= $right;
    }

    private static function nullPropLt($left, $right)
    {
        if (is_null($left) || is_null($right)) {
            return null;
        } else if (is_string($left) || is_string($right)) {
            return ('' . $left) < ('' . $right);
        }
        return $left < $right;
    }

    private static function nullPropLe($left, $right)
    {
        if (is_null($left) || is_null($right)) {
            return null;
        } else if (is_string($left) || is_string($right)) {
            return ('' . $left) <= ('' . $right);
        }
        return $left <= $right;
    }

    public static function showEntityListDiff($actualData, $expectedData)
    {
        $ret = '';
        if (count($expectedData) != count($actualData)) {
            $ret .= 'VVV actual VVV' . "\n";
            for ($i = 0; $i < count($actualData); $i++) {
                $e = $actualData[$i];
                $ret .= $e->getPartitionKey() . '/' . $e->getRowKey() . "\n";
            }
            $ret .= '-----------------' . "\n";

            for ($i = 0; $i < count($expectedData); $i++) {
                $e = $expectedData[$i];
                $ret .= $e->getPartitionKey() . '/' . $e->getRowKey() . "\n";
            }
            $ret .= '^^^ expected ^^^' . "\n";

            for ($i = 0; $i < count($actualData); $i++) {
                $in = false;
                $ei = $actualData[$i];
                for ($j = 0; $j < count($expectedData); $j++) {
                    $ej = $expectedData[$j];
                    if ($ei->getPartitionKey() == $ej->getPartitionKey() && $ei->getRowKey() == $ej->getRowKey()) {
                        $in = true;
                    }
                }
                if (!$in) {
                    $ret .= 'returned ' . $this->tmptostring($ei). "\n";
                }
            }

            for ($j = 0; $j < count($expectedData); $j++) {
                $in = false;
                $ej = $expectedData[$j];
                for ($i = 0; $i < count($actualData); $i++) {
                    $ei = $actualData[$i];
                    if ($ei->getPartitionKey() == $ej->getPartitionKey() && $ei->getRowKey() == $ej->getRowKey()) {
                        $in = true;
                    }
                }
                if (!$in) {
                    $ret .= 'expected ' . $this->tmptostring($ej). "\n";
                }
            }
        }
    return $ret;
    }
}

redpajama_set_name: RedPajamaGithub


text:
FROM postgres

ADD create.sql /docker-entrypoint-initdb.d


text:
import React from 'react'

const CryptoDropdown = ({ label, cryptos, action }) => (

    {label}

      <select className="form-control" onChange={
          (e) => action(e.target.value)}>
        <option value="" selected disabled>Select Account</option>
        {cryptos.map(crypto =>
          <option key={crypto.id}>{crypto.symbol}</option>
          )
        }
      </select>

)

export default CryptoDropdown


text:
using BulletMLLib;
using Microsoft.Xna.Framework;

namespace BulletMLSample
{
	public class Mover : Bullet
	{
		#region Members

		public Vector2 pos;

		#endregion //Members

		#region Properties

		public override float X
		{
			get { return pos.X; }
			set { pos.X = value; }
		}

		public override float Y
		{
			get { return pos.Y; }
			set { pos.Y = value; }
		}

		public bool Used { get; set; }

		#endregion //Properties

		#region Methods

		/// <summary>
		/// Initializes a new instance of the <see cref="BulletMLSample.Mover"/> class.
		/// </summary>
		/// <param name="myBulletManager">My bullet manager.</param>
		public Mover(IBulletManager myBulletManager) : base(myBulletManager)
		{
		}

		public void Init()
		{
			Used = true;
		}

		public override void PostUpdate()
		{
			if (X < 0 || X > Game1.graphics.PreferredBackBufferWidth || Y < 0 || Y > Game1.graphics.PreferredBackBufferHeight)
			{
				Used = false;
			}
		}

		#endregion //Methods
	}
}


text:
<!--

    Copyright 2016 SEARCH-The National Consortium for Justice Information and Statistics

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

	<modelVersion>4.0.0</modelVersion>

	<artifactId>nibrs-staging-data-common</artifactId>

	<parent>
	  <groupId>org.search.nibrs</groupId>
	  <artifactId>nibrs-tools-aggregate</artifactId>
	  <version>1.0.0</version>
	</parent>

	<properties>
		<owner>SEARCH-The National Consortium for Justice Information and Statistics</owner>
    <nibrs-common-version>[1.0.0,)</nibrs-common-version>
	</properties>

 	<dependencyManagement>
		<dependencies>
      <dependency>
          <groupId>org.apache.logging.log4j</groupId>
          <artifactId>log4j-bom</artifactId>
          <version>2.17.2</version>
          <type>pom</type>
          <scope>import</scope>
      </dependency>
			<dependency>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-dependencies</artifactId>
				<version>2.6.2</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
 		</dependencies>
	</dependencyManagement>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.search.nibrs</groupId>
			<artifactId>nibrs-common</artifactId>
			<version>${nibrs-common-version}</version>
		</dependency>
		<dependency>
		    <groupId>org.hibernate</groupId>
		    <artifactId>hibernate-core</artifactId>
	    </dependency>
		<dependency>
		    <groupId>com.fasterxml.jackson.datatype</groupId>
		    <artifactId>jackson-datatype-jsr310</artifactId>
		</dependency>
		<dependency>
		    <groupId>commons-logging</groupId>
		    <artifactId>commons-logging</artifactId>
		    <version>1.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-collections4</artifactId>
			<version>4.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
		</dependency>
		<dependency>
		    <groupId>org.apache.commons</groupId>
		    <artifactId>commons-lang3</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>


text:
RSpec.describe RuboCop::CommentConfig do
  subject(:comment_config) { described_class.new(parse_source(source)) }

  describe '#cop_enabled_at_line?' do
    let(:source) do
      # rubocop:disable Lint/EmptyExpression, Lint/EmptyInterpolation
      <<~RUBY
        # rubocop:disable Metrics/MethodLength with a comment why
        def some_method
          puts 'foo'                                                        # 03
        end
        # rubocop:enable Metrics/MethodLength

        # rubocop:disable all
        some_method                                                         # 08
        # rubocop:enable all

        code = 'This is evil.'
        eval(code) # rubocop:disable Security/Eval
        puts 'This is not evil.'                                            # 12

        def some_method
          puts 'Disabling indented single line' # rubocop:disable Layout/LineLength
        end
                                                                            # 18
        string = <<~END
        This is a string not a real comment # rubocop:disable Style/Loop
        END

        foo # rubocop:disable Style/MethodCallWithoutArgsParentheses        # 23

        # rubocop:enable Lint/Void

        # rubocop:disable Style/For, Style/Not,Layout/IndentationStyle
        foo                                                                 # 28

        class One
          # rubocop:disable Style/ClassVars
          @@class_var = 1
        end                                                                 # 33

        class Two
          # rubocop:disable Style/ClassVars
          @@class_var = 2
        end                                                                 # 38
        # rubocop:enable Style/Not,Layout/IndentationStyle
        # rubocop:disable Style/Send, Lint/RandOne some comment why
        # rubocop:disable Layout/BlockAlignment some comment why
        # rubocop:enable Style/Send, Layout/BlockAlignment but why?
        # rubocop:enable Lint/RandOne foo bar!                              # 43
        # rubocop:disable Lint/EmptyInterpolation
        "result is #{}"
        # rubocop:enable Lint/EmptyInterpolation
        # rubocop:disable RSpec/Example
        # rubocop:disable Custom2/Number9                                   # 48

        #=SomeDslDirective # rubocop:disable Layout/LeadingCommentSpace
        # rubocop:disable RSpec/Rails/HttpStatus
        it { is_expected.to have_http_status 200 }                          # 52
        # rubocop:enable RSpec/Rails/HttpStatus
      RUBY
      # rubocop:enable Lint/EmptyExpression, Lint/EmptyInterpolation
    end

    def disabled_lines_of_cop(cop)
      (1..source.size).each_with_object([]) do |line_number, disabled_lines|
        enabled = comment_config.cop_enabled_at_line?(cop, line_number)
        disabled_lines << line_number unless enabled
      end
    end

    it 'supports disabling multiple lines with a pair of directive' do
      method_length_disabled_lines = disabled_lines_of_cop('Metrics/MethodLength')
      expected_part = (1..4).to_a
      expect(method_length_disabled_lines & expected_part).to eq(expected_part)
    end

    it 'supports enabling/disabling multiple cops in a single directive' do
      not_disabled_lines = disabled_lines_of_cop('Style/Not')
      tab_disabled_lines = disabled_lines_of_cop('Layout/IndentationStyle')

      expect(not_disabled_lines).to eq(tab_disabled_lines)
      expected_part = (27..39).to_a
      expect(not_disabled_lines & expected_part).to eq(expected_part)
    end

    it 'supports enabling/disabling multiple cops along with a comment' do
      {
        'Style/Send' => 40..42,
        'Lint/RandOne' => 40..43,
        'Layout/BlockAlignment' => 41..42
      }.each do |cop_name, expected|
        actual = disabled_lines_of_cop(cop_name)
        expect(actual & expected.to_a).to eq(expected.to_a)
      end
    end

    it 'supports disabling cops with multiple levels in department name' do
      disabled_lines = disabled_lines_of_cop('RSpec/Rails/HttpStatus')
      expected_part = (51..53).to_a
      expect(disabled_lines & expected_part).to eq(expected_part)
    end

    it 'supports enabling/disabling cops without a prefix' do
      empty_interpolation_disabled_lines = disabled_lines_of_cop('Lint/EmptyInterpolation')

      expected = (44..46).to_a

      expect(empty_interpolation_disabled_lines & expected).to eq(expected)
    end

    it 'supports disabling all lines after a directive' do
      for_disabled_lines = disabled_lines_of_cop('Style/For')
      expected_part = (27..source.size).to_a
      expect(for_disabled_lines & expected_part).to eq(expected_part)
    end

    it 'just ignores unpaired enabling directives' do
      void_disabled_lines = disabled_lines_of_cop('Lint/Void')
      expected_part = (25..source.size).to_a
      expect((void_disabled_lines & expected_part).empty?).to be(true)
    end

    it 'supports disabling single line with a directive at end of line' do
      eval_disabled_lines = disabled_lines_of_cop('Security/Eval')
      expect(eval_disabled_lines).to include(12)
      expect(eval_disabled_lines).not_to include(13)
    end

    it 'handles indented single line' do
      line_length_disabled_lines = disabled_lines_of_cop('Layout/LineLength')
      expect(line_length_disabled_lines).to include(16)
      expect(line_length_disabled_lines).not_to include(18)
    end

    it 'does not confuse a comment directive embedded in a string literal with a real comment' do
      loop_disabled_lines = disabled_lines_of_cop('Loop')
      expect(loop_disabled_lines).not_to include(20)
    end

    it 'supports disabling all cops except Lint/RedundantCopDisableDirective with keyword all' do
      expected_part = (7..8).to_a

      cops = RuboCop::Cop::Registry.all.reject do |klass|
        klass == RuboCop::Cop::Lint::RedundantCopDisableDirective
      end

      cops.each do |cop|
        disabled_lines = disabled_lines_of_cop(cop)
        expect(disabled_lines & expected_part).to eq(expected_part)
      end
    end

    it 'does not confuse a cop name including "all" with all cops' do
      alias_disabled_lines = disabled_lines_of_cop('Alias')
      expect(alias_disabled_lines).not_to include(23)
    end

    it 'can handle double disable of one cop' do
      expect(disabled_lines_of_cop('Style/ClassVars')).to eq([7, 8, 9] + (31..source.size).to_a)
    end

    it 'supports disabling cops with multiple uppercase letters' do
      expect(disabled_lines_of_cop('RSpec/Example')).to include(47)
    end

    it 'supports disabling cops with numbers in their name' do
      expect(disabled_lines_of_cop('Custom2/Number9')).to include(48)
    end

    it 'supports disabling cops on a comment line with an EOL comment' do
      expect(disabled_lines_of_cop('Layout/LeadingCommentSpace')).to eq([7, 8, 9, 50])
    end
  end

  describe '#cop_disabled_line_ranges' do
    subject(:range) { comment_config.cop_disabled_line_ranges }

    let(:source) do
      <<~RUBY
        # rubocop:disable Metrics/MethodLength with a comment why
        def some_method
          puts 'foo'
        end
        # rubocop:enable Metrics/MethodLength

        code = 'This is evil.'
        eval(code) # rubocop:disable Security/Eval
        puts 'This is not evil.'
      RUBY
    end

    it 'collects line ranges by disabled cops' do
      expect(range).to eq({ 'Metrics/MethodLength' => [1..5], 'Security/Eval' => [8..8] })
    end
  end

  describe '#extra_enabled_comments' do
    subject(:extra) { comment_config.extra_enabled_comments }

    let(:source) do
      <<~RUBY
        # rubocop:enable Metrics/MethodLength, Security/Eval
        def some_method
          puts 'foo'
        end
      RUBY
    end

    it 'has keys as instances of Parser::Source::Comment for extra enabled comments' do
      key = extra.keys.first

      expect(key.is_a?(Parser::Source::Comment)).to be true
      expect(key.text).to eq '# rubocop:enable Metrics/MethodLength, Security/Eval'
    end

    it 'has values as arrays of extra enabled cops' do
      expect(extra.values.first).to eq ['Metrics/MethodLength', 'Security/Eval']
    end
  end

  describe 'comment_only_line?' do
    let(:source) do
      <<~RUBY
        # rubocop:disable Metrics/MethodLength                                01
        def some_method
          puts 'foo'
        end
        # rubocop:enable Metrics/MethodLength                                 05

        code = 'This is evil.'
        eval(code) # rubocop:disable Security/Eval
      RUBY
    end

    context 'when line contains only comment' do
      [1, 5].each do |line_number|
        it 'returns true' do
          expect(comment_config.comment_only_line?(line_number)).to be true
        end
      end
    end

    context 'when line is empty' do
      [6].each do |line_number|
        it 'returns true' do
          expect(comment_config.comment_only_line?(line_number)).to be true
        end
      end
    end

    context 'when line contains only code' do
      [2, 3, 4, 7].each do |line_number|
        it 'returns false' do
          expect(comment_config.comment_only_line?(line_number)).to be false
        end
      end
    end

    context 'when line contains code and comment' do
      [8].each do |line_number|
        it 'returns false' do
          expect(comment_config.comment_only_line?(line_number)).to be false
        end
      end
    end
  end
end


text:
@Version("1.0")
@Export(optional = "provide:=true")
package org.apache.jackrabbit.oak.plugins.segment.http;

import aQute.bnd.annotation.Export;
import aQute.bnd.annotation.Version;


text:
package edu.cmu.ml.rtw.generic.task.classify.meta;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import edu.cmu.ml.rtw.generic.data.annotation.DataSet;
import edu.cmu.ml.rtw.generic.data.annotation.DatumContext;
import edu.cmu.ml.rtw.generic.parse.AssignmentList;
import edu.cmu.ml.rtw.generic.parse.Obj;
import edu.cmu.ml.rtw.generic.task.classify.EvaluationClassificationMeasure;
import edu.cmu.ml.rtw.generic.task.classify.MethodClassification;
import edu.cmu.ml.rtw.generic.task.classify.Trainable;
import edu.cmu.ml.rtw.generic.util.Pair;

public class MethodClassificationMetaEvaluation extends MethodClassification<PredictionClassificationDatum<Boolean>, Boolean> {
	private List<EvaluationClassificationMeasure<?, ?>> evaluations;
	private List<Integer> evaluationRanks;
	private boolean weightByScores = false;
	private boolean partialByScores = false;
	private String[] parameterNames = { "evaluations", "weightByScores", "partialByScores" };

	public MethodClassificationMetaEvaluation() {
		this(null);
	}

	public MethodClassificationMetaEvaluation(DatumContext<PredictionClassificationDatum<Boolean>, Boolean> context) {
		super(context);
	}

	@Override
	public String[] getParameterNames() {
		return this.parameterNames;
	}

	@Override
	public Obj getParameterValue(String parameter) {
		if (parameter.equals("evaluations")) {
			if (this.evaluations == null)
				return null;
			Obj.Array array = Obj.array();
			for (EvaluationClassificationMeasure<?, ?> measure : this.evaluations)
				array.add(Obj.curlyBracedValue(measure.getReferenceName()));
			return array;
		} else if (parameter.equals("weightByScores")) {
			return Obj.stringValue(String.valueOf(this.weightByScores));
		} else if (parameter.equals("partialByScores")) {
			return Obj.stringValue(String.valueOf(this.partialByScores));
		} else
			return null;
	}

	@Override
	public boolean setParameterValue(String parameter, Obj parameterValue) {
		if (parameter.equals("evaluations")) {
			if (parameterValue != null) {
				this.evaluations = new ArrayList<EvaluationClassificationMeasure<?, ?>>();
				Obj.Array array = (Obj.Array)parameterValue;
				for (int i = 0; i < array.size(); i++)
					this.evaluations.add((EvaluationClassificationMeasure<?, ?>)this.context.getAssignedMatches(array.get(i)).get(0));

				this.evaluationRanks = new ArrayList<>();
				for (int i = 0; i < this.evaluations.size(); i++)
					this.evaluationRanks.add(i);
				this.evaluationRanks.sort(new Comparator<Integer>() {
					@Override
					public int compare(Integer o1, Integer o2) {
						return Double.compare(evaluations.get(o1).compute(), evaluations.get(o2).compute());
					}
				});

			}
		} else if (parameter.equals("weightByScores")) {
			this.weightByScores = Boolean.valueOf(this.context.getMatchValue(parameterValue));
		} else if (parameter.equals("partialByScores")) {
			this.partialByScores = Boolean.valueOf(this.context.getMatchValue(parameterValue));
		} else
			return false;

		return true;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private Double getScoreForDatum(PredictionClassificationDatum<Boolean> datum) {
		int i = 0;
		for (EvaluationClassificationMeasure<?, ?> measure : this.evaluations) {
			if (measure.getMethod().equals(datum.getPrediction().getMethod())) {
				double score = measure.compute();
				if (this.weightByScores)
					score *= ((MethodClassification)datum.getPrediction().getMethod()).score(datum.getPrediction().getDatum(), datum.getPrediction().getLabel());
				else if (this.partialByScores) {
					double weight = ((MethodClassification)datum.getPrediction().getMethod()).score(datum.getPrediction().getDatum(), datum.getPrediction().getLabel());
					score = (this.evaluationRanks.indexOf(i)+weight)/(double)this.evaluations.size();
				}
				return score;
			}

			i++;
		}

		return null;
	}

	@Override
	public Map<PredictionClassificationDatum<Boolean>, Boolean> classify(DataSet<PredictionClassificationDatum<Boolean>, Boolean> data) {
		Map<PredictionClassificationDatum<Boolean>, Boolean> map = new HashMap<PredictionClassificationDatum<Boolean>, Boolean>();

		for (PredictionClassificationDatum<Boolean> datum : data) {
			map.put(datum, true);
		}

		return map;
	}

	@Override
	public Map<PredictionClassificationDatum<Boolean>, Pair<Boolean, Double>> classifyWithScore(DataSet<PredictionClassificationDatum<Boolean>, Boolean> data) {
		Map<PredictionClassificationDatum<Boolean>, Pair<Boolean, Double>> map = new HashMap<PredictionClassificationDatum<Boolean>, Pair<Boolean, Double>>();

		for (PredictionClassificationDatum<Boolean> datum : data) {
			map.put(datum, new Pair<Boolean, Double>(true, getScoreForDatum(datum)));
		}

		return map;
	}

	@Override
	public boolean init(DataSet<PredictionClassificationDatum<Boolean>, Boolean> testData) {
		return true;
	}

	@Override
	protected boolean fromParseInternal(AssignmentList internalAssignments) {
		return true;
	}

	@Override
	protected AssignmentList toParseInternal() {
		return null;
	}

	@Override
	public String getGenericName() {
		return "MetaEvaluation";
	}

	@Override
	public MethodClassification<PredictionClassificationDatum<Boolean>, Boolean> clone(String referenceName) {
		MethodClassificationMetaEvaluation clone = new MethodClassificationMetaEvaluation(this.context);
		if (!clone.fromParse(this.getModifiers(), referenceName, toParse()))
			return null;
		return clone;
	}

	@Override
	public MethodClassification<PredictionClassificationDatum<Boolean>, Boolean> makeInstance(DatumContext<PredictionClassificationDatum<Boolean>, Boolean> context) {
		return new MethodClassificationMetaEvaluation(context);
	}

	@Override
	public boolean hasTrainable() {
		return false;
	}

	@Override
	public Trainable<PredictionClassificationDatum<Boolean>, Boolean> getTrainable() {
		return null;
	}

	@Override
	public Boolean classify(PredictionClassificationDatum<Boolean> datum) {
		return true;
	}

	@Override
	public Pair<Boolean, Double> classifyWithScore(PredictionClassificationDatum<Boolean> datum) {
		return new Pair<Boolean, Double>(true, getScoreForDatum(datum));
	}

	@Override
	public Map<PredictionClassificationDatum<Boolean>, Double> score(DataSet<PredictionClassificationDatum<Boolean>, Boolean> data, Boolean label) {
		Map<PredictionClassificationDatum<Boolean>, Double> map = new HashMap<>();

		for (PredictionClassificationDatum<Boolean> datum : data) {
			map.put(datum, score(datum, label));
		}

		return map;
	}

	@Override
	public double score(PredictionClassificationDatum<Boolean> datum, Boolean label) {
		if (label)
			return getScoreForDatum(datum);
		else
			return 1.0 - getScoreForDatum(datum);
	}

}


text:
class AddStatusToArticles < ActiveRecord::Migration
  def self.up
    remove_column :documents, :date
    add_column :documents, :status, :string
    add_column :documents, :published_at, :datetime
  end

  def self.down
    remove_column :documents, :status
    remove_column :documents, :published_at
    add_column :documents, :date, :datetime
  end
end


text:
//
//  HeadReosurce.h
//  MGLoveFreshBeen
//
//  Created by ming on 16/7/17.
//  Copyright © 2016年 ming. All rights reserved.
//

#import <Foundation/Foundation.h>
@class HeadData;

#pragma mark - HeadReosurce
@interface HeadReosurce : NSObject

@property (nonatomic,copy) NSString *String;
@property (nonatomic,copy) NSString *reqid;
/** HeadData */
@property (nonatomic,strong) HeadData *data;

@end
#pragma mark - HeadData

@interface HeadData : NSObject

@property (nonatomic,copy) NSArray *focus;
@property (nonatomic,copy) NSArray *icons;
@property (nonatomic,copy) NSArray *activities;

@end

#pragma mark - Activities

@interface Activities : NSObject

@property (nonatomic,copy) NSString *id;
@property (nonatomic,copy) NSString *name;
@property (nonatomic,copy) NSString *img;
@property (nonatomic,copy) NSString *topimg;
@property (nonatomic,copy) NSString *jptype;
@property (nonatomic,copy) NSString *trackid;
@property (nonatomic,copy) NSString *mimg;
@property (nonatomic,copy) NSString *customURL;

@end


text:
export default function pagerConfig(uibPagerConfig, paginationConstants) {
    "ngInject";
    uibPagerConfig.itemsPerPage = paginationConstants.itemsPerPage;
    uibPagerConfig.previousText = '«';
    uibPagerConfig.nextText = '»';
};


text:
Create or replace FUNCTION __temp_fix_bool_fence_agents_options()
RETURNS VOID
   AS $procedure$
   DECLARE
   v_agents varchar[] := array['inet4-only', 'inet6-only', 'lanplus', 'missing-as-off', 'notls', 'snmp-priv-passwd-script',
                               'ssh', 'ssl-insecure', 'ssl-secure', 'ssl', 'use-sudo', 'verbose', 'version'];
   v_temp_option_name varchar(50);
   v_option_true_val varchar(50);
   v_option_one_val varchar(50);

BEGIN
    for i in 1 .. array_upper(v_agents, 1)
    loop
        v_temp_option_name := 'temp__' || upper(v_agents[i]) || '__expr';
        v_option_true_val := v_agents[i] || '=' || 'true';
        v_option_one_val := v_agents[i] || '=' || '1';
        update fence_agents set options =  replace(options, v_option_one_val, v_temp_option_name) where not encrypt_options;
        update fence_agents set options =  replace(options, v_option_true_val, v_temp_option_name) where not encrypt_options;
        update fence_agents set options =  replace(options, v_agents[i], v_option_one_val) where not encrypt_options;
        update fence_agents set options =  replace(options, v_temp_option_name, v_option_one_val) where not encrypt_options;
    end loop;
    --fix options
    -- in case we have options that one is substring of the other we will get '=1-' expressions that
    -- should be replaced with '-' (for example 'ssl-insecure', 'ssl-secure', 'ssl')
    update fence_agents set options =  replace(options,'=1-','-') where not encrypt_options;
END; $procedure$
LANGUAGE plpgsql;

SELECT __temp_fix_bool_fence_agents_options();
DROP function __temp_fix_bool_fence_agents_options();


text:
require_relative '../spec_helper'

describe 'UDPSocket#inspect' do
  before do
    @socket = UDPSocket.new
    @socket.bind('127.0.0.1', 0)
  end

  after do
    @socket.close
  end

  it 'returns a String with the fd, family, address and port' do
    port = @socket.addr[1]
    @socket.inspect.should == "#<UDPSocket:fd #{@socket.fileno}, AF_INET, 127.0.0.1, #{port}>"
  end
end


text:
'''This runs a bunch of the ReQL tests against the `rethinkdb._debug_scratch` artificial table to check that `artificial_table_t` works properly.'''

import os, subprocess, sys

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'common')))
import driver, scenario_common, utils, vcoptparse

op = vcoptparse.OptParser()
scenario_common.prepare_option_parser_mode_flags(op)
_, command_prefix, serve_options = scenario_common.parse_mode_flags(op.parse(sys.argv))

r = utils.import_python_driver()

utils.print_with_time("Spinning up a server")
with driver.Process(name='.', command_prefix=command_prefix, extra_options=serve_options) as server:
    server.check()

    conn = r.connect(host=server.host, port=server.driver_port)

    # note: these tests are impicitly run in sequence because of the --table option

    command_line = [
        os.path.join(os.path.dirname(os.path.abspath(__file__)), os.path.pardir, 'rql_test', 'test-runner'),
        '--driver-port', '%s:%d' % (server.host, server.driver_port),
        '--table', 'rethinkdb._debug_scratch']
    command_line.extend('polyglot/' + name for name in [
        'control', 'joins', 'match',
        'mutation/atomic_get_set', 'mutation/delete', 'mutation/insert',
        'mutation/replace', 'mutation/update', 'polymorphism'])
    command_line.extend('polyglot/regression/%s' % issue_number for issue_number in [
        309, 453, '522.py', 545, 568, 678, 1155, 1179, 1468, 2399, 2697,
        2709, 2838, 2930])

    utils.print_with_time('Ensuring that db "test" exists for secondary table')
    if 'test' not in r.db_list().run(conn):
        r.db_create('test').run(conn)

    utils.print_with_time("Command line:", " ".join(command_line))
    utils.print_with_time("Running the QL test")

    utils.print_with_time('==== Start test-runner Output ====')
    subprocess.check_call(command_line)
    utils.print_with_time('==== End test-runner Output ====')

    utils.print_with_time("Cleaning up")
utils.print_with_time("Done.")


text:
/*
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * License: GNU Lesser General Public License (LGPL), version 2.1 or later
 * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
 */

package org.hibernate.orm.persister.common.spi;

import java.util.Optional;
import javax.persistence.AttributeConverter;

/**
 * Specialization of a DomainReference whose values may have a JPA
 * {@link AttributeConverter} applied.
 *
 * @author Steve Ebersole
 */
public interface ConvertibleOrmNavigable extends OrmNavigable {
	Optional<AttributeConverter> getAttributeConverter();
}


text:
<?php

/**
 *
 * @author Hudhaifa Shatnawi <hudhaifa.shatnawi@gmail.com>
 * @version 1.0, Nov 11, 2016 - 7:31:49 AM
 */
class AnniversaryFilter
        extends DateFilter {

    protected function applyOneDate(DataQuery $query) {
        $this->model = $query->applyRelation($this->relation);

        $dayClause = 'DAY(' . $this->getDbName() . ')';
        $monthClause = 'MONTH(' . $this->getDbName() . ')';

        $date = $this->getDate();
        return $query->where(array(
                    $dayClause => $date['d'],
                    $monthClause => $date['m'],
        ));
    }

}


text:
import FolderIcon from '@mui/icons-material/Folder';
import Breadcrumbs from '@mui/joy/Breadcrumbs';
import Button from '@mui/joy/Button';
import Link from '@mui/joy/Link';
import Typography from '@mui/joy/Typography';
import * as React from 'react';

export default function CollapsedBreadcrumbs() {
  const [collapsed, setCollapsed] = React.useState<boolean>(true);
  const [navigationItems, setNavigationItems] = React.useState<string[]>([
    'Programs',
    'Files',
    'Services',
  ]);

  return (
    <Breadcrumbs separator="›" aria-label="breadcrumbs">
      {collapsed ? (
        <Button
          size="sm"
          onClick={() => {
            setNavigationItems((prev) => ['Root', 'Home', ...prev]);
            setCollapsed(false);
          }}
          variant="plain"
          color="info"
        >
          •••
        </Button>
      ) : null}
      {navigationItems.map((item: string) => (
        <Link
          // The `preventDefault` is for demonstration purposes, generally, you don't need it in your application
          onClick={(event) => event.preventDefault()}
          underline="hover"
          color="info"
          href="/"
          fontSize="inherit"
        >
          <FolderIcon sx={{ mr: 0.5 }} fontSize="inherit" color="inherit" />
          {item}
        </Link>
      ))}
      <Typography fontSize="inherit" sx={{ display: 'flex', alignItems: 'center' }}>
        <FolderIcon sx={{ mr: 0.5 }} fontSize="inherit" />
        bablo.txt
      </Typography>
    </Breadcrumbs>
  );
}


text:
<?php

namespace ChatBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class ChatBundle extends Bundle
{
}


text:
using QIP.Domain;
using QIP.Public;
using QIP.Authorization;
using QIP.Authorization.Extensions;
using QIP.Authorization.Resources;
using QIP.IODomain.Extensions;
using QIP.IODomain.Input;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
using System.Threading.Tasks;
using QIP.WebSockets.Extensions;
using QIP.WebSockets.Models;
using QIP.WebSockets.StringWebSockets;

namespace QIP.WebSockets.Operations {
    public class PointerOperation {
        private static readonly JsonSerializerSettings serializerSettings;

        private readonly IAuthorizationService _authorizationService;
        private readonly ILogger<PointerOperation> _logger;

        static PointerOperation() {
            serializerSettings = new JsonSerializerSettings() {
                Converters = { new StringEnumConverter() }
            };
        }

        public PointerOperation(IAuthorizationService authorizationService, ILogger<PointerOperation> logger) {
            _authorizationService = authorizationService;
            _logger = logger;
        }

        public async Task PointTo(StringWebSocket stringWebSocket, IStringWebSocketSession session, JObject payload) {
            ClaimsPrincipal user = stringWebSocket.User;
            long boardId = session.Id;

            if(!await _authorizationService.AuthorizeAsync(user, new BoardRequest(boardId), Policies.WriteBoadPolicy)) {
                _logger.LogWarning(LoggingEvents.PointToNotAuthorized, "PointTo (Board {boardId}) NOT AUTHORIZED {userId}", boardId, user.GetNameIdentifier());
                return;
            }

            InPoint inPoint = payload.ToObject<InPoint>();

            var validationResults = new List<ValidationResult>();
            if(!Validator.TryValidateObject(inPoint, new ValidationContext(inPoint), validationResults, true)) {
                _logger.LogDebug(LoggingEvents.PointToInvalidModel, "PointTo (Board {boardId}) INVALID MODEL", boardId);
                return;
            }

            Point point = new Point().In(inPoint);

            _logger.LogInformation(LoggingEvents.PointTo, "Pointing To");

            await session.BroadcastAsync(
               new {
                   type = OperationType.POINT_TO,
                   payload = new { point = point.Out() }
               },
               serializerSettings
            );
        }
    }
}


text:
Rails.application.routes.draw do
    # brand new controller example
    #match '/mycontroller' => 'general#mycontroller'
    # Additional help page example
    #match '/help/help_out' => 'help#help_out'
end


text:
require 'brainclusterfuck/loop_error'

shared_examples 'a loop opcode' do
  it 'has num_operations' do
    op = described_class.new(3)

    expect(op.num_operations).to eq(3)
  end

  it 'uses equality' do
    expect(described_class.new(1)).to eq(described_class.new(1))
    expect(described_class.new(1)).not_to eq(described_class.new(2))
  end

  it 'can unresolve' do
    expect(described_class.new(1).unresolve_loop).to be_a(placeholder_class)
  end

  it 'raises on resolve' do
    expect { described_class.new(1).resolve_loop }.to raise_error(Brainclusterfuck::LoopError)
  end
end


text:
globals in global scope
--INI--
variables_order="egpcs"
--FILE--
<?php

var_dump(isset($_SERVER));
var_dump(empty($_SERVER));
var_dump(gettype($_SERVER));
var_dump(count($_SERVER));

var_dump($_SERVER['PHP_SELF']);
unset($_SERVER['PHP_SELF']);
var_dump($_SERVER['PHP_SELF']);

unset($_SERVER);
var_dump($_SERVER);

echo "Done\n";
?>
--EXPECTF--
bool(true)
bool(false)
string(5) "array"
int(%d)
string(%d) "%s"

Notice: Undefined index: PHP_SELF in %s on line %d
NULL

Notice: Undefined variable: _SERVER in %s on line %d
NULL
Done


text:
<?php

namespace Werkstatt\Bundle\FootBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 */
class NotTwoSameTeams extends Constraint
{
    public $message = 'Vous ne pouvez pas sélectionner 2 fois la même équipe. ';
}


text:
class CalendarItem < ApplicationRecord
  validates_presence_of :start_time, :end_time
end


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (C) 2022 The Android Open Source Project
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~      http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
-->
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
  <string name="material_timepicker_pm">PM</string>
  <string name="material_timepicker_am">AM</string>
  <string name="material_timepicker_select_time">Aja valimine</string>
  <string name="material_timepicker_minute">Minut</string>
  <string name="material_timepicker_hour">Tunnid</string>
  <string name="material_hour_suffix">Kell %1$s</string>
  <string name="material_hour_24h_suffix">%1$s tundi</string>
  <string name="material_minute_suffix">%1$s minutit</string>
  <string name="material_hour_selection">Valige tund</string>
  <string name="material_minute_selection">Minutite valimine</string>
  <string name="material_clock_toggle_content_description">Valige AM või PM</string>
  <string name="mtrl_timepicker_confirm">OK</string>
  <string name="mtrl_timepicker_cancel">Tühista</string>
  <string name="material_timepicker_text_input_mode_description">Aktiveerige kellaaja sisestamiseks tekstisisestusrežiim.</string>
  <string name="material_timepicker_clock_mode_description">Aktiveerige kellaaja sisestamiseks kellarežiim.</string>
</resources>


text:
package com.example;

import com.code_intelligence.jazzer.api.FuzzerSecurityIssueLow;
import com.code_intelligence.jazzer.api.HookType;
import com.code_intelligence.jazzer.api.MethodHook;
import java.lang.invoke.MethodHandle;
import java.lang.reflect.Field;
import java.util.regex.Pattern;

public class HookDependenciesFuzzerHooks {
  private static final Field PATTERN_ROOT;

  static {
    Field root;
    try {
      root = Pattern.class.getDeclaredField("root");
    } catch (NoSuchFieldException e) {
      root = null;
    }
    PATTERN_ROOT = root;
  }

  @MethodHook(type = HookType.AFTER, targetClassName = "java.util.regex.Matcher",
      targetMethod = "matches", targetMethodDescriptor = "()Z",
      additionalClassesToHook = {"java.util.regex.Pattern"})
  public static void
  matcherMatchesHook(MethodHandle method, Object alwaysNull, Object[] alwaysEmpty, int hookId,
      Boolean returnValue) {
    if (PATTERN_ROOT != null) {
      throw new FuzzerSecurityIssueLow("Hook applied even though it depends on the class to hook");
    }
  }
}


text:
const fs = require('fs')
const path = require('path')
const puppeteer = require('puppeteer')
const mock = require('../test/server')

const unmock = mock({
  '/md/info/site': {
    locale: 'en'
  }
})

if (!fs.existsSync(path.resolve(process.env.CIRCLE_ARTIFACTS, 'screenshots'))) {
  fs.mkdirSync(path.resolve(process.env.CIRCLE_ARTIFACTS, 'screenshots'))
}

function artifactsPath (...depths) {
  return path.resolve(process.env.CIRCLE_ARTIFACTS, 'screenshots', ...depths)
}

async function gotoPage (url, browser) {
  try {
    const page = await browser.newPage()
    await page.setViewport({ width: 1920, height: 1080 })
    await page.goto(url)
    return page
  } catch (e) {
    console.log(e)
  }
}

;(async () => {
  const browser = await puppeteer.launch()
  let page = await gotoPage('http://localhost:3000', browser)
  await page.screenshot({ path: artifactsPath('User_Index.png') })
  await page.close()

  page = await gotoPage('http://localhost:3000/#/user/closet', browser)
  await page.screenshot({ path: artifactsPath('User_Closet.png') })
  await page.close()

  page = await gotoPage('http://localhost:3000/#/user/player', browser)
  await page.screenshot({ path: artifactsPath('User_Player.png') })
  await page.close()

  page = await gotoPage('http://localhost:3000/#/user/profile', browser)
  await page.screenshot({ path: artifactsPath('User_Profile.png') })
  await page.close()

  browser.close()
  unmock()
})()


text:
package com.facebook.buck.rules.modern.builders;

import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.rules.BuildRuleStrategy;
import com.facebook.buck.rules.Cell;
import com.facebook.buck.rules.CellPathResolver;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.step.StepFailedException;
import com.facebook.buck.util.function.ThrowingFunction;
import com.google.common.hash.HashCode;
import java.io.Closeable;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Set;

/**
 * Interface used to implement various isolated execution strategies. In these strategies,
 * buildrules are run in isolation (i.e. outside of the real build root, in a different directory,
 * on a different machine, etc).
 */
public interface IsolatedExecution extends Closeable {
  void build(
      ExecutionContext executionContext,
      InputsDigestBuilder inputsBuilder,
      Set<Path> outputs,
      Path projectRoot,
      HashCode hash,
      BuildTarget buildTarget,
      Path cellPrefixRoot)
      throws IOException, StepFailedException, InterruptedException;

  /** Creates a BuildRuleStrategy for a particular */
  static BuildRuleStrategy createIsolatedExecutionStrategy(
      IsolatedExecution executionStrategy,
      SourcePathRuleFinder ruleFinder,
      CellPathResolver cellResolver,
      Cell rootCell,
      ThrowingFunction<Path, HashCode, IOException> fileHasher) {
    return new IsolatedExecutionStrategy(
        executionStrategy, ruleFinder, cellResolver, rootCell, fileHasher);
  }
}


text:
// This file was generated by Mendix Business Modeler.
//
// WARNING: Code you write here will be lost the next time you deploy the project.

package testsuite.proxies;

/**
 *
 */
public class Color extends system.proxies.FileDocument
{
	/**
	 * Internal name of this entity
	 */
	public static final java.lang.String entityName = "TestSuite.Color";

	/**
	 * Enum describing members of this entity
	 */
	public enum MemberNames
	{
		ColorName("ColorName"),
		RAL("RAL"),
		IsPrimary("IsPrimary"),
		ColorCode("ColorCode"),
		FileID("FileID"),
		Name("Name"),
		DeleteAfterDownload("DeleteAfterDownload"),
		Contents("Contents"),
		HasContents("HasContents");

		private java.lang.String metaName;

		MemberNames(java.lang.String s)
		{
			metaName = s;
		}

		@Override
		public java.lang.String toString()
		{
			return metaName;
		}
	}

	public Color(com.mendix.systemwideinterfaces.core.IContext context)
	{
		this(context, com.mendix.core.Core.instantiate(context, "TestSuite.Color"));
	}

	protected Color(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixObject colorMendixObject)
	{
		super(context, colorMendixObject);
		if (!com.mendix.core.Core.isSubClassOf("TestSuite.Color", colorMendixObject.getType()))
			throw new java.lang.IllegalArgumentException("The given object is not a TestSuite.Color");
	}

	/**
	 * @deprecated Use 'Color.load(IContext, IMendixIdentifier)' instead.
	 */
	@Deprecated
	public static testsuite.proxies.Color initialize(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixIdentifier mendixIdentifier) throws com.mendix.core.CoreException
	{
		return testsuite.proxies.Color.load(context, mendixIdentifier);
	}

	/**
	 * Initialize a proxy using context (recommended). This context will be used for security checking when the get- and set-methods without context parameters are called.
	 * The get- and set-methods with context parameter should be used when for instance sudo access is necessary (IContext.getSudoContext() can be used to obtain sudo access).
	 */
	public static testsuite.proxies.Color initialize(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixObject mendixObject)
	{
		return new testsuite.proxies.Color(context, mendixObject);
	}

	public static testsuite.proxies.Color load(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixIdentifier mendixIdentifier) throws com.mendix.core.CoreException
	{
		com.mendix.systemwideinterfaces.core.IMendixObject mendixObject = com.mendix.core.Core.retrieveId(context, mendixIdentifier);
		return testsuite.proxies.Color.initialize(context, mendixObject);
	}

	public static java.util.List<testsuite.proxies.Color> load(com.mendix.systemwideinterfaces.core.IContext context, java.lang.String xpathConstraint) throws com.mendix.core.CoreException
	{
		java.util.List<testsuite.proxies.Color> result = new java.util.ArrayList<testsuite.proxies.Color>();
		for (com.mendix.systemwideinterfaces.core.IMendixObject obj : com.mendix.core.Core.retrieveXPathQuery(context, "//TestSuite.Color" + xpathConstraint))
			result.add(testsuite.proxies.Color.initialize(context, obj));
		return result;
	}

	/**
	 * @return value of ColorName
	 */
	public final String getColorName()
	{
		return getColorName(getContext());
	}

	/**
	 * @param context
	 * @return value of ColorName
	 */
	public final String getColorName(com.mendix.systemwideinterfaces.core.IContext context)
	{
		return (String) getMendixObject().getValue(context, MemberNames.ColorName.toString());
	}

	/**
	 * Set value of ColorName
	 * @param colorname
	 */
	public final void setColorName(String colorname)
	{
		setColorName(getContext(), colorname);
	}

	/**
	 * Set value of ColorName
	 * @param context
	 * @param colorname
	 */
	public final void setColorName(com.mendix.systemwideinterfaces.core.IContext context, String colorname)
	{
		getMendixObject().setValue(context, MemberNames.ColorName.toString(), colorname);
	}

	/**
	 * @return value of RAL
	 */
	public final Integer getRAL()
	{
		return getRAL(getContext());
	}

	/**
	 * @param context
	 * @return value of RAL
	 */
	public final Integer getRAL(com.mendix.systemwideinterfaces.core.IContext context)
	{
		return (Integer) getMendixObject().getValue(context, MemberNames.RAL.toString());
	}

	/**
	 * Set value of RAL
	 * @param ral
	 */
	public final void setRAL(Integer ral)
	{
		setRAL(getContext(), ral);
	}

	/**
	 * Set value of RAL
	 * @param context
	 * @param ral
	 */
	public final void setRAL(com.mendix.systemwideinterfaces.core.IContext context, Integer ral)
	{
		getMendixObject().setValue(context, MemberNames.RAL.toString(), ral);
	}

	/**
	 * @return value of IsPrimary
	 */
	public final Boolean getIsPrimary()
	{
		return getIsPrimary(getContext());
	}

	/**
	 * @param context
	 * @return value of IsPrimary
	 */
	public final Boolean getIsPrimary(com.mendix.systemwideinterfaces.core.IContext context)
	{
		return (Boolean) getMendixObject().getValue(context, MemberNames.IsPrimary.toString());
	}

	/**
	 * Set value of IsPrimary
	 * @param isprimary
	 */
	public final void setIsPrimary(Boolean isprimary)
	{
		setIsPrimary(getContext(), isprimary);
	}

	/**
	 * Set value of IsPrimary
	 * @param context
	 * @param isprimary
	 */
	public final void setIsPrimary(com.mendix.systemwideinterfaces.core.IContext context, Boolean isprimary)
	{
		getMendixObject().setValue(context, MemberNames.IsPrimary.toString(), isprimary);
	}

	/**
	 * @return value of ColorCode
	 */
	public final String getColorCode()
	{
		return getColorCode(getContext());
	}

	/**
	 * @param context
	 * @return value of ColorCode
	 */
	public final String getColorCode(com.mendix.systemwideinterfaces.core.IContext context)
	{
		return (String) getMendixObject().getValue(context, MemberNames.ColorCode.toString());
	}

	/**
	 * Set value of ColorCode
	 * @param colorcode
	 */
	public final void setColorCode(String colorcode)
	{
		setColorCode(getContext(), colorcode);
	}

	/**
	 * Set value of ColorCode
	 * @param context
	 * @param colorcode
	 */
	public final void setColorCode(com.mendix.systemwideinterfaces.core.IContext context, String colorcode)
	{
		getMendixObject().setValue(context, MemberNames.ColorCode.toString(), colorcode);
	}

	@Override
	public boolean equals(Object obj)
	{
		if (obj == this)
			return true;

		if (obj != null && getClass().equals(obj.getClass()))
		{
			final testsuite.proxies.Color that = (testsuite.proxies.Color) obj;
			return getMendixObject().equals(that.getMendixObject());
		}
		return false;
	}

	@Override
	public int hashCode()
	{
		return getMendixObject().hashCode();
	}

	/**
	 * @return String name of this class
	 */
	public static java.lang.String getType()
	{
		return "TestSuite.Color";
	}

	/**
	 * @return String GUID from this object, format: ID_0000000000
	 * @deprecated Use getMendixObject().getId().toLong() to get a unique identifier for this object.
	 */
	@Override
	@Deprecated
	public java.lang.String getGUID()
	{
		return "ID_" + getMendixObject().getId().toLong();
	}
}


text:
class CommandHistory(object):
    def __init__(self):
        self._entries = [""]
        self.index = 0

    def add_entry(self, entry):
        if not entry:
            return
        if entry in self._entries:
            self._entries.remove(entry)
        self._entries.insert(1, entry)
        if len(self._entries) > 20:
            self._entries.pop()

        self.index = 0

    def entries(self):
        return self._entries

    def get_entries_with(self, text):
        return [e.rstrip("\r") for e in self._entries if text in e]

    def has_previous(self):
        return self.index > 0

    def get_previous(self):
        if self.has_previous():
            self.index -= 1
            return self._entries[self.index]

    def has_next(self):
        return self.index < (len(self._entries) - 1)

    def get_next(self):
        if self.has_next():
            self.index += 1
            return self._entries[self.index]


text:
from p5 import P5

class P5Button(P5):

    def __init__(self):
        P5.__init__(self)
        self.noloop()
        self._butts = []
        self._buttonPressed = False

    def button_press(self, widget, event):
        P5.button_press(self, widget, event)

        #iterate through the buttons to see if you've pressed any down
        bp = False
        for i in range ( 0, len(self._butts) ):
            if (self._butts[i]._enabled):
                contains = self._butts[i].contains(event.x, event.y)
                self._butts[i]._pressed = contains
                if (contains):
                    bp = True

        self._buttonPressed = bp
        self.redraw()

    def button_release(self, widget, event):
        P5.button_release(self, widget, event)
        self._buttonPressed = False

        pressed = []
        #iterate through the buttons to see if you've released on any
        for i in range ( 0, len(self._butts) ):
            if (self._butts[i]._enabled):
                if (self._butts[i]._pressed):
                    if (self._butts[i].contains(event.x, event.y)):
                        pressed.append( self._butts[i] )

                    if (self._butts[i]._toggle):
                        self._butts[i]._pressed = not self._butts[i]._pressed
                    else:
                        self._butts[i]._pressed = False

        for i in range( 0, len(pressed) ):
            pressed[i].doPressed()

        self.redraw()

class Polygon:

    def __init__( self, xs, ys ):
        self.setPoints( xs, ys )

    def setPoints( self, xs, ys ):
        self._xs = xs
        self._ys = ys

        self._boundingX = self._xs[0]
        self._boundingY = self._ys[0]
        self._boundingW = self._xs[0]
        self._boundingH = self._ys[0]

        for i in range ( 1, len(self._xs) ):
            if (self._xs[i] > self._boundingW):
                self._boundingW = self._xs[i]
            if (self._ys[i] > self._boundingH):
                self._boundingH = self._ys[i]
            if (self._xs[i] < self._boundingX):
                self._boundingX = self._xs[i]
            if (self._ys[i] < self._boundingY):
                self._boundingY = self._ys[i]

    def contains( self, mx, my ):
        if (not self.bbox_contains(mx, my)):
            return False

        #insert simple path tracing check on the polygon here

        return True

    def bbox_contains( self, mx, my ):
        if ( not((mx>=self._boundingX) and (my>=self._boundingY) and (mx<self._boundingW) and (my<self._boundingH)) ):
            return False
        else:
            return True

class Button:

    def __init__(self, poly, offX, offY):
        self._poly = poly
        self._offX = offX
        self._offY = offY

        self._enabled = True
        self._pressed = False
        self._toggle = False

        self._listeners = []

        self._actionCommand = None

        self._img = None

    def setOffsets(self, offs):
        self._offX = offs[0]
        self._offY = offs[1]

    def addActionListener(self, listen):
        self._listeners.append(listen)

    def removeActionListener(self, listen):
        try:
            self._listeners.remove(listen)
        except ValueError:
            pass

    def setActionCommand(self, command):
        self._actionCommand = command

    def getActionCommand(self):
        return self._actionCommand

    def setImage(self, img):
        self._img = img

    def contains( self, mx, my ):
        x = mx - self._offX
        y = my - self._offY

        contains = self._poly.contains( x, y )
        return contains

    def doPressed( self ):
        for i in range ( 0, len(self._listeners) ):
            self._listeners[i].fireButton( self._actionCommand )

    def isImg( self ):
        return self._img != None


text:
package peer

import (
	"github.com/gravitational/trace"
	"github.com/prometheus/client_golang/prometheus"

	"github.com/gravitational/teleport/lib/observability/metrics"
)

// serverMetrics represents a collection of grpcMetrics for a proxy peer server
type serverMetrics struct {
	connections     *prometheus.GaugeVec
	rpcs            *prometheus.GaugeVec
	rpcTotal        *prometheus.CounterVec
	rpcDuration     *prometheus.HistogramVec
	messageSent     *prometheus.HistogramVec
	messageReceived *prometheus.HistogramVec
}

// newServerMetrics inits and registers client grpcMetrics prometheus collectors.
func newServerMetrics() (*serverMetrics, error) {
	sm := &serverMetrics{
		connections: prometheus.NewGaugeVec(
			prometheus.GaugeOpts{
				Namespace: "proxy_peer",
				Subsystem: "server",
				Name:      "connections",
				Help:      "Number of currently opened connection to proxy peer clients.",
			},
			[]string{"local_id", "remote_id", "state"},
		),

		rpcs: prometheus.NewGaugeVec(
			prometheus.GaugeOpts{
				Namespace: "proxy_peer",
				Subsystem: "server",
				Name:      "rpc",
				Help:      "Number of current server RPC requests.",
			},
			[]string{"service", "method"},
		),

		rpcTotal: prometheus.NewCounterVec(
			prometheus.CounterOpts{
				Namespace: "proxy_peer",
				Subsystem: "server",
				Name:      "rpc_total",
				Help:      "Total number of server RPC requests.",
			},
			[]string{"service", "method", "code"},
		),

		rpcDuration: prometheus.NewHistogramVec(
			prometheus.HistogramOpts{
				Namespace: "proxy_peer",
				Subsystem: "server",
				Name:      "rpc_duration_seconds",
				Help:      "Duration in seconds of RPCs sent by the server.",
			},
			[]string{"service", "handler", "code"},
		),

		messageSent: prometheus.NewHistogramVec(
			prometheus.HistogramOpts{
				Namespace: "proxy_peer",
				Subsystem: "server",
				Name:      "message_sent_size",
				Help:      "Size of messages sent by the server.",
				Buckets:   messageByteBuckets,
			},
			[]string{"service", "handler"},
		),

		messageReceived: prometheus.NewHistogramVec(
			prometheus.HistogramOpts{
				Namespace: "proxy_peer",
				Subsystem: "server",
				Name:      "message_received_size",
				Help:      "Size of messages received by the server.",
				Buckets:   messageByteBuckets,
			},
			[]string{"service", "handler"},
		),
	}

	if err := metrics.RegisterPrometheusCollectors(
		sm.connections,
		sm.rpcs,
		sm.rpcTotal,
		sm.rpcDuration,
		sm.messageSent,
		sm.messageReceived,
	); err != nil {
		return nil, trace.Wrap(err)
	}

	return sm, nil
}

// getConnectionGauge is a getter for the connectionCounter collector.
func (s *serverMetrics) getConnectionGauge() *prometheus.GaugeVec {
	return s.connections
}

// getRPCGauge is a getter for the rpcs collector.
func (s *serverMetrics) getRPCGauge() *prometheus.GaugeVec {
	return s.rpcs
}

// getRPCCounter is a getter for the rpcTotal collector.
func (s *serverMetrics) getRPCCounter() *prometheus.CounterVec {
	return s.rpcTotal
}

// getRPCDuration is a getter for the rpcDuration collector.
func (s *serverMetrics) getRPCDuration() *prometheus.HistogramVec {
	return s.rpcDuration
}

// getMessageSent is a getter for the messageSent collector.
func (s *serverMetrics) getMessageSent() *prometheus.HistogramVec {
	return s.messageSent
}

// getMessageReceived is a getter for the messageReceived collector.
func (s *serverMetrics) getMessageReceived() *prometheus.HistogramVec {
	return s.messageReceived
}


text:
import contextlib
import mock

from nova import test
from nova.virt.vmwareapi import ds_util
from nova.virt.vmwareapi import error_util
from nova.virt.vmwareapi import fake

class fake_session(object):
    def __init__(self, ret=None):
        self.ret = ret

    def _get_vim(self):
        return fake.FakeVim()

    def _call_method(self, module, method, *args, **kwargs):
        return self.ret

    def _wait_for_task(self, task_ref):
        task_info = self._call_method('module', "get_dynamic_property",
                        task_ref, "Task", "info")
        task_name = task_info.name
        if task_info.state == 'success':
            return task_info
        else:
            error_info = 'fake error'
            error = task_info.error
            name = error.fault.__class__.__name__
            raise error_util.get_fault_class(name)(error_info)

class DsUtilTestCase(test.NoDBTestCase):
    def setUp(self):
        super(DsUtilTestCase, self).setUp()
        self.session = fake_session()
        self.flags(api_retry_count=1, group='vmware')
        fake.reset()

    def tearDown(self):
        super(DsUtilTestCase, self).tearDown()
        fake.reset()

    def test_build_datastore_path(self):
        path = ds_util.build_datastore_path('ds', 'folder')
        self.assertEqual('[ds] folder', path)
        path = ds_util.build_datastore_path('ds', 'folder/file')
        self.assertEqual('[ds] folder/file', path)

    def test_split_datastore_path(self):
        ds, path = ds_util.split_datastore_path('[ds]')
        self.assertEqual('ds', ds)
        self.assertEqual('', path)
        ds, path = ds_util.split_datastore_path('[ds] folder')
        self.assertEqual('ds', ds)
        self.assertEqual('folder', path)
        ds, path = ds_util.split_datastore_path('[ds] folder/file')
        self.assertEqual('ds', ds)
        self.assertEqual('folder/file', path)
        self.assertRaises(IndexError,
                          ds_util.split_datastore_path,
                          'split bad path')

    def test_file_delete(self):
        def fake_call_method(module, method, *args, **kwargs):
            self.assertEqual('DeleteDatastoreFile_Task', method)
            name = kwargs.get('name')
            self.assertEqual('fake-datastore-path', name)
            datacenter = kwargs.get('datacenter')
            self.assertEqual('fake-dc-ref', datacenter)
            return 'fake_delete_task'

        with contextlib.nested(
            mock.patch.object(self.session, '_wait_for_task'),
            mock.patch.object(self.session, '_call_method',
                              fake_call_method)
        ) as (_wait_for_task, _call_method):
            ds_util.file_delete(self.session,
                                'fake-datastore-path', 'fake-dc-ref')
            _wait_for_task.assert_has_calls([
                   mock.call('fake_delete_task')])

    def test_file_move(self):
        def fake_call_method(module, method, *args, **kwargs):
            self.assertEqual('MoveDatastoreFile_Task', method)
            sourceName = kwargs.get('sourceName')
            self.assertEqual('[ds] tmp/src', sourceName)
            destinationName = kwargs.get('destinationName')
            self.assertEqual('[ds] base/dst', destinationName)
            sourceDatacenter = kwargs.get('sourceDatacenter')
            self.assertEqual('fake-dc-ref', sourceDatacenter)
            destinationDatacenter = kwargs.get('destinationDatacenter')
            self.assertEqual('fake-dc-ref', destinationDatacenter)
            return 'fake_move_task'

        with contextlib.nested(
            mock.patch.object(self.session, '_wait_for_task'),
            mock.patch.object(self.session, '_call_method',
                              fake_call_method)
        ) as (_wait_for_task, _call_method):
            ds_util.file_move(self.session,
                              'fake-dc-ref', '[ds] tmp/src', '[ds] base/dst')
            _wait_for_task.assert_has_calls([
                   mock.call('fake_move_task')])

    def test_mkdir(self):
        def fake_call_method(module, method, *args, **kwargs):
            self.assertEqual('MakeDirectory', method)
            name = kwargs.get('name')
            self.assertEqual('fake-path', name)
            datacenter = kwargs.get('datacenter')
            self.assertEqual('fake-dc-ref', datacenter)
            createParentDirectories = kwargs.get('createParentDirectories')
            self.assertTrue(createParentDirectories)

        with mock.patch.object(self.session, '_call_method',
                               fake_call_method):
            ds_util.mkdir(self.session, 'fake-path', 'fake-dc-ref')

    def test_file_exists(self):
        def fake_call_method(module, method, *args, **kwargs):
            if method == 'SearchDatastore_Task':
                ds_browser = args[0]
                self.assertEqual('fake-browser', ds_browser)
                datastorePath = kwargs.get('datastorePath')
                self.assertEqual('fake-path', datastorePath)
                return 'fake_exists_task'
            elif method == 'get_dynamic_property':
                info = fake.DataObject()
                info.name = 'search_task'
                info.state = 'success'
                result = fake.DataObject()
                result.path = 'fake-path'
                matched = fake.DataObject()
                matched.path = 'fake-file'
                result.file = [matched]
                info.result = result
                return info
            # Should never get here
            self.fail()

        with mock.patch.object(self.session, '_call_method',
                               fake_call_method):
            file_exists = ds_util.file_exists(self.session,
                    'fake-browser', 'fake-path', 'fake-file')
            self.assertTrue(file_exists)

    def test_file_exists_fails(self):
        def fake_call_method(module, method, *args, **kwargs):
            if method == 'SearchDatastore_Task':
                return 'fake_exists_task'
            elif method == 'get_dynamic_property':
                info = fake.DataObject()
                info.name = 'search_task'
                info.state = 'error'
                error = fake.DataObject()
                error.localizedMessage = "Error message"
                error.fault = fake.FileNotFound()
                info.error = error
                return info
            # Should never get here
            self.fail()

        with mock.patch.object(self.session, '_call_method',
                               fake_call_method):
            file_exists = ds_util.file_exists(self.session,
                    'fake-browser', 'fake-path', 'fake-file')
            self.assertFalse(file_exists)


text:
using System;
using System.Collections.Generic;
using System.Windows;
using BudgetManager.Core.Configuration;
using BudgetManager.Data.Entities;
using BudgetManager.DbUpdater;
using BudgetManager.Domain;
using BudgetManager.Services;
using BudgetManager.Services.Mappings;
using Caliburn.Micro;
using Microsoft.Practices.Unity;

namespace BudgetManager
{
    public class UnityBootstrapper : BootstrapperBase
    {
        private IUnityContainer _container;

        public UnityBootstrapper()
        {
            Initialize();
        }

        protected override void BuildUp(object instance)
        {
            instance = _container.BuildUp(instance);
            base.BuildUp(instance);
        }

        protected override void Configure()
        {
            _container = new UnityContainer();
            _container.RegisterType<IWindowManager, WindowManager>(new ContainerControlledLifetimeManager());
            _container.RegisterType<IEventAggregator, EventAggregator>(new ContainerControlledLifetimeManager());

            _container.RegisterType<IMapper<Account, AccountEntity>, AccountMapper>();
            _container.RegisterType<IMapper<Category, CategoryEntity>, CategoryMapper>();
            _container.RegisterType<IMapper<Transaction, TransactionEntity>, TransactionMapper>();

            _container.RegisterType<IAccountService, AccountService>();
            _container.RegisterType<ICategoryService, CategoryService>();
            _container.RegisterType<ITransactionService, TransactionService>();

            Updater updater = new Updater(AppConfig.Config.ConnectionString);
            updater.Update();

            base.Configure();
        }

        protected override IEnumerable<object> GetAllInstances(Type service)
        {
            return _container.ResolveAll(service);
        }

        protected override object GetInstance(Type service, string key)
        {
            object result = default(object);
            if (key != null)
            {
                result = _container.Resolve(service, key);
            }
            else
            {
                result = _container.Resolve(service);
            }

            return result;
        }

        protected override void OnStartup(object sender, StartupEventArgs e)
        {
            DisplayRootViewFor<ShellViewModel>();
        }
    }
}


text:
using LolHandbook.DataDragon;
using System;

namespace LolHandbook.ViewModels
{
    public class ChampionPassiveViewModel : ISpellViewModel
    {
        private readonly ChampionPassive championPassive;

        public ChampionPassiveViewModel(ChampionPassive championPassive)
        {
            this.championPassive = championPassive;
        }

        public Uri ImageUri => championPassive.ImageUri;
        public string Name => championPassive.Name;
        public string Description => championPassive.Description;
        public string Cost => "Passive";
        public string Cooldown => null;
    }
}


text:
using UnityEngine;

#if UNITY_EDITOR
using UnityEditor;

namespace Destructible2D
{
	[CanEditMultipleObjects]
	[CustomEditor(typeof(D2dThrower))]
	public class D2dThrower_Editor : D2dEditor<D2dThrower>
	{
		protected override void OnInspector()
		{
			BeginError(Any(t => t.DelayMin < 0.0f || (t.DelayMin > t.DelayMax)));
				DrawDefault("DelayMin");
			EndError();
			BeginError(Any(t => t.DelayMax < 0.0f || (t.DelayMin > t.DelayMax)));
				DrawDefault("DelayMax");
			EndError();
			BeginError(Any(t => t.SpeedMin < 0.0f || (t.SpeedMin > t.SpeedMax)));
				DrawDefault("SpeedMin");
			EndError();
			BeginError(Any(t => t.SpeedMax < 0.0f || (t.SpeedMin > t.SpeedMax)));
				DrawDefault("SpeedMax");
			EndError();
			BeginError(Any(t => t.Spread < 0.0f));
				DrawDefault("Spread");
			EndError();
			BeginError(Any(t => t.ThrowPrefabs == null || t.ThrowPrefabs.Length > 0));
				DrawDefault("ThrowPrefabs");
			EndError();
		}
	}
}
#endif

namespace Destructible2D
{
	// This component throws random prefabs upwards
	[AddComponentMenu(D2dHelper.ComponentMenuPrefix + "Thrower")]
	public class D2dThrower : MonoBehaviour
	{
		[Tooltip("The minimum delay between throws in seconds")]
		public float DelayMin = 0.5f;

		[Tooltip("The maximum delay between throws in seconds")]
		public float DelayMax = 2.0f;

		[Tooltip("The minimum speed of the thrown object")]
		public float SpeedMin = 10.0f;

		[Tooltip("The maximum speed of the thrown object")]
		public float SpeedMax = 20.0f;

		[Tooltip("Maximum degrees spread when throwing")]
		public float Spread = 10.0f;

		[Tooltip("The prefabs that can be thrown")]
		public GameObject[] ThrowPrefabs;

		// Seconds until next spawn
		[SerializeField]
		private float cooldown;

		protected virtual void Update()
		{
			cooldown -= Time.deltaTime;

			if (cooldown <= 0.0f)
			{
				cooldown = Random.Range(DelayMin, DelayMax);

				if (ThrowPrefabs != null && ThrowPrefabs.Length > 0)
				{
					var index     = Random.Range(0, ThrowPrefabs.Length);
					var prefab    = ThrowPrefabs[index];
					var instance  = Instantiate(prefab);
					var rigidbody = instance.GetComponent<Rigidbody2D>();

					instance.transform.position = transform.position;

					if (rigidbody != null)
					{
						var angle = Random.Range(-0.5f, 0.5f) * Spread * Mathf.Deg2Rad;
						var speed = Random.Range(SpeedMin, SpeedMax);

						rigidbody.velocity        = new Vector2(Mathf.Sin(angle) * speed, Mathf.Cos(angle) * speed);
						rigidbody.angularVelocity = Random.Range(-180.0f, 180.0f);
					}
				}
			}
		}
	}
}


text:
/**
 * @file
 * @brief Gearman Declarations
 */

#pragma once

/* This seems to be required for older compilers @note http://stackoverflow.com/questions/8132399/how-to-printf-uint64-t  */
#ifndef __STDC_FORMAT_MACROS
#  define __STDC_FORMAT_MACROS
#endif

#ifdef __cplusplus
#  include <cinttypes>
#  include <cstddef>
#  include <cstdlib>
#  include <ctime>
#else
#  include <inttypes.h>
#  include <stdbool.h>
#  include <stddef.h>
#  include <stdlib.h>
#  include <time.h>
#endif

#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <poll.h>
#include <sys/uio.h>

#include <libgearman-1.0/visibility.h>
#include <libgearman-1.0/version.h>
#include <libgearman-1.0/constants.h>
#include <libgearman-1.0/signal.h>
#include <libgearman-1.0/kill.h>
#include <libgearman-1.0/job_handle.h>
#include <libgearman-1.0/client_callbacks.h>
#include <libgearman-1.0/strerror.h>
#include <libgearman-1.0/function.h>
#include <libgearman-1.0/string.h>

#include <libgearman-1.0/actions.h>
#include <libgearman-1.0/string.h>

#include <libgearman-1.0/aggregator.h>

// Everything above this line must be in the order specified.
#include <libgearman-1.0/argument.h>
#include <libgearman-1.0/task_attr.h>
#include <libgearman-1.0/core.h>
#include <libgearman-1.0/task.h>
#include <libgearman-1.0/job.h>
#include <libgearman-1.0/string.h>
#include <libgearman-1.0/result.h>
#include <libgearman-1.0/execute.h>
#include <libgearman-1.0/util.h>
#include <libgearman-1.0/interface/status.h>
#include <libgearman-1.0/status.h>

#include <libgearman-1.0/worker.h>
#include <libgearman-1.0/client.h>
#include <libgearman-1.0/connection.h>
#include <libgearman-1.0/parse.h>
#include <libgearman-1.0/cancel.h>


text:
package eu.ydp.empiria.player.client.module.connection.presenter.translation;

import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import eu.ydp.empiria.player.client.module.connection.item.ConnectionItem;
import eu.ydp.empiria.player.client.module.connection.presenter.ConnectionItems;

import javax.annotation.Nullable;
import java.util.Collection;

public class SurfacesOffsetsExtractor {
    public Collection<Integer> extractLeftOffsets(ConnectionItems items) {
        return Collections2.transform(items.getAllItems(), new Function<ConnectionItem, Integer>() {

            @Override
            @Nullable
            public Integer apply(@Nullable ConnectionItem ci) {
                return ci.getOffsetLeft();
            }
        });
    }

    public Collection<Integer> extractTopOffsets(ConnectionItems items) {
        return Collections2.transform(items.getAllItems(), new Function<ConnectionItem, Integer>() {

            @Override
            @Nullable
            public Integer apply(@Nullable ConnectionItem ci) {
                return ci.getOffsetTop();
            }
        });
    }

    public Collection<Integer> extractBottomOffsets(ConnectionItems items) {
        return Collections2.transform(items.getAllItems(), new Function<ConnectionItem, Integer>() {

            @Override
            @Nullable
            public Integer apply(@Nullable ConnectionItem ci) {
                return ci.getOffsetTop() + ci.getHeight();
            }
        });
    }

    public Collection<Integer> extractRightOffsets(ConnectionItems items) {
        return Collections2.transform(items.getAllItems(), new Function<ConnectionItem, Integer>() {

            @Override
            @Nullable
            public Integer apply(@Nullable ConnectionItem ci) {
                return ci.getOffsetLeft() + ci.getWidth();
            }
        });
    }
}