text:
<?php
namespace Stockbase\Integration\Model\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\Data\OrderItemInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Stockbase\Integration\StockbaseApi\Client\StockbaseClientFactory;
use Stockbase\Integration\Model\Config\StockbaseConfiguration;
use Stockbase\Integration\Model\Inventory\StockbaseStockManagement;
use Stockbase\Integration\Model\OrderedItem as StockbaseOrderedItem;
use Stockbase\Integration\Model\StockItemReserve;

/**
 * Class OrderPaymentPayObserver
 */
class OrderPaymentPayObserver implements ObserverInterface
{
    /**
     * @var StockbaseConfiguration
     */
    private $stockbaseConfiguration;

    /**
     * @var StockbaseClientFactory
     */
    private $stockbaseClientFactory;

    /**
     * @var StockbaseStockManagement
     */
    private $stockbaseStockManagement;

    /**
     * @var ObjectManagerInterface
     */
    private $objectManager;

    /**
     * OrderPaymentPayObserver constructor.
     * @param StockbaseConfiguration   $stockbaseConfiguration
     * @param StockbaseStockManagement $stockbaseStockManagement
     * @param StockbaseClientFactory   $stockbaseClientFactory
     * @param ObjectManagerInterface   $objectManager
     */
    public function __construct(
        StockbaseConfiguration $stockbaseConfiguration,
        StockbaseStockManagement $stockbaseStockManagement,
        StockbaseClientFactory $stockbaseClientFactory,
        ObjectManagerInterface $objectManager
    ) {
        $this->stockbaseConfiguration = $stockbaseConfiguration;
        $this->stockbaseClientFactory = $stockbaseClientFactory;
        $this->stockbaseStockManagement = $stockbaseStockManagement;
        $this->objectManager = $objectManager;
    }

    /**
     * {@inheritdoc}
     */
    public function execute(Observer $observer)
    {
        if (!$this->stockbaseConfiguration->isModuleEnabled()) {
            return $this;
        }

        /** @var \Magento\Sales\Api\Data\InvoiceInterface $invoice */
        $invoice = $observer->getData('invoice');

        // since InvoiceInterface doesn't explicitly define getOrder(), we have to do this...
        if (\method_exists($invoice, 'getOrder')) {
            /** @var \Magento\Sales\Api\Data\OrderInterface $order */
            $order = $invoice->getOrder();
        } else {
            /** @var OrderRepositoryInterface $repository */
            $repository = $this->objectManager->get(OrderRepositoryInterface::class);
            $order = $repository->get($invoice->getOrderId());
        }

        $quoteItemIds = \array_map(function (OrderItemInterface $item) {
            return $item->getQuoteItemId();
        }, (array) $order->getAllItems());

        /** @var StockItemReserve[] $reservedStockbaseItems */
        $reservedStockbaseItems = $this->stockbaseStockManagement->getReserveForQuoteItem($quoteItemIds);

        if (empty($reservedStockbaseItems)) {
            return $this;
        }

        $client = $this->stockbaseClientFactory->create();
        $result = $client->createOrder($order, $reservedStockbaseItems);

        foreach ($reservedStockbaseItems as $reserve) {
            $this->addStatusHistoryComment($order, __(
                'Item with EAN "%1" (%2 pc.) has been ordered from Stockbase.',
                $reserve->getEan(),
                $reserve->getAmount()
            ));
            //$order->save();

            /** @var StockbaseOrderedItem $stockbaseOrderedItem */
            $stockbaseOrderedItem = $this->objectManager->create(StockbaseOrderedItem::class);
            $stockbaseOrderedItem->setOrderId($order->getId());
            $stockbaseOrderedItem->setOrderItemId($reserve->getOrderItemId());
            $stockbaseOrderedItem->setProductId($reserve->getProductId());
            $stockbaseOrderedItem->setEan($reserve->getEan());
            $stockbaseOrderedItem->setAmount($reserve->getAmount());
            $stockbaseOrderedItem->setCreatedAt((new \DateTime())->format('Y-m-d H:i:s'));
            $stockbaseOrderedItem->save();

            // Decrement local Stockbase stock amount
            $this->stockbaseStockManagement->updateStockAmount($reserve->getEan(), $reserve->getAmount(), '-');

            // Release the reserve
            $this->stockbaseStockManagement->releaseReserve($reserve);

            $this->addStatusHistoryComment($order, __(
                'Local Stockbase stock index for item with EAN "%1" has been updated.',
                $reserve->getEan()
            ));
            //$order->save();
        }

        return $this;
    }

    /**
     * Safe add status history comment.
     *
     * @param OrderInterface $order
     * @param string $comment
     * @param $status
     * @return void
     */
    private function addStatusHistoryComment(OrderInterface $order, string $comment, $status = false)
    {
        if (!$order instanceof \Magento\Sales\Model\Order) {
            return;
        }

        $order->addStatusHistoryComment($comment, $status);
    }
}


text:
package org.apache.bookkeeper.tools.cli.commands.autorecovery;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;

import java.util.ArrayList;
import java.util.Vector;
import java.util.function.Function;
import org.apache.bookkeeper.conf.ServerConfiguration;
import org.apache.bookkeeper.meta.LedgerManagerFactory;
import org.apache.bookkeeper.meta.LedgerUnderreplicationManager;
import org.apache.bookkeeper.meta.MetadataDrivers;
import org.apache.bookkeeper.meta.UnderreplicatedLedger;
import org.apache.bookkeeper.replication.ReplicationException;
import org.apache.bookkeeper.tools.cli.helpers.BookieCommandTestBase;
import org.apache.zookeeper.KeeperException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

/**
 * Unit test for {@link ListUnderReplicatedCommand}.
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest({ListUnderReplicatedCommand.class, MetadataDrivers.class, UnderreplicatedLedger.class })
public class ListUnderReplicatedCommandTest extends BookieCommandTestBase {

    private UnderreplicatedLedger ledger;
    private LedgerManagerFactory factory;
    private LedgerUnderreplicationManager underreplicationManager;

    public ListUnderReplicatedCommandTest() {
        super(3, 0);
    }

    @Override
    public void setup() throws Exception {
        super.setup();

        PowerMockito.whenNew(ServerConfiguration.class).withNoArguments().thenReturn(conf);

        PowerMockito.mockStatic(MetadataDrivers.class);
        factory = mock(LedgerManagerFactory.class);
        PowerMockito.doAnswer(invocationOnMock -> {
            Function<LedgerManagerFactory, ?> function = invocationOnMock.getArgument(1);
            function.apply(factory);
            return true;
        }).when(MetadataDrivers.class, "runFunctionWithLedgerManagerFactory", any(ServerConfiguration.class),
                any(Function.class));

        underreplicationManager = mock(LedgerUnderreplicationManager.class);
        when(factory.newLedgerUnderreplicationManager()).thenReturn(underreplicationManager);

        ledger = mock(UnderreplicatedLedger.class);
        when(ledger.getLedgerId()).thenReturn(1L);
        when(ledger.getCtime()).thenReturn(1L);

        Vector<UnderreplicatedLedger> ledgers = new Vector<>();
        ledgers.add(ledger);

        when(underreplicationManager.listLedgersToRereplicate(any())).thenReturn(ledgers.iterator());

    }

    @Test
    public void testWithoutArgs()
        throws InterruptedException, ReplicationException.CompatibilityException, KeeperException {
        testCommand("");
        verify(factory, times(1)).newLedgerUnderreplicationManager();
        verify(underreplicationManager, times(1)).listLedgersToRereplicate(any());
        verify(ledger, times(1)).getLedgerId();
        verify(ledger, times(1)).getCtime();
    }

    @Test
    public void testMissingReplica()
        throws InterruptedException, ReplicationException.CompatibilityException, KeeperException {
        testCommand("-mr", "");
        verify(factory, times(1)).newLedgerUnderreplicationManager();
        verify(underreplicationManager, times(1)).listLedgersToRereplicate(any());
        verify(ledger, times(1)).getLedgerId();
        verify(ledger, times(1)).getCtime();
    }

    @Test
    public void testExcludingMissingReplica()
        throws InterruptedException, ReplicationException.CompatibilityException, KeeperException {
        testCommand("-emr", "");
        verify(factory, times(1)).newLedgerUnderreplicationManager();
        verify(underreplicationManager, times(1)).listLedgersToRereplicate(any());
        verify(ledger, times(1)).getLedgerId();
        verify(ledger, times(1)).getCtime();
    }

    @Test
    public void testPrintMissingReplica()
        throws InterruptedException, ReplicationException.CompatibilityException, KeeperException {

        ArrayList<String> list = new ArrayList<>();
        list.add("replica");

        when(ledger.getReplicaList()).thenReturn(list);
        testCommand("-pmr");
        verify(factory, times(1)).newLedgerUnderreplicationManager();
        verify(underreplicationManager, times(1)).listLedgersToRereplicate(any());
        verify(ledger, times(1)).getLedgerId();
        verify(ledger, times(1)).getCtime();
        verify(ledger, times(1)).getReplicaList();
    }

    @Test
    public void testPrintReplicationWorkerId() throws ReplicationException.UnavailableException, InterruptedException,
                                                      ReplicationException.CompatibilityException, KeeperException {
        when(underreplicationManager.getReplicationWorkerIdRereplicatingLedger(1L)).thenReturn("test");

        testCommand("-prw");
        verify(factory, times(1)).newLedgerUnderreplicationManager();
        verify(underreplicationManager, times(1)).listLedgersToRereplicate(any());
        verify(ledger, times(1)).getLedgerId();
        verify(ledger, times(1)).getCtime();
        verify(underreplicationManager, times(1)).getReplicationWorkerIdRereplicatingLedger(1L);
    }

    @Test
    public void testCommand1() {
        ListUnderReplicatedCommand cmd = new ListUnderReplicatedCommand();
        cmd.apply(bkFlags, new String[] { "" });
    }

    private void testCommand(String... args) {
        ListUnderReplicatedCommand cmd = new ListUnderReplicatedCommand();
        Assert.assertTrue(cmd.apply(bkFlags, args));
    }

}

redpajama_set_name: RedPajamaGithub


text:
% function d = eval_fabric_distribution_function(F, theta, phi)
%
% Integrate given fabric tensor F the distribution probability in the
% angular intervals given by theta and phi.
%
% The fabric tensor of the second kind in sqrt2 notation
% theta: The angle interval with the vertical axis, typically between [0, pi)
% phi: The angle interval in the horizontal plane with the x-axis in [0, 2*pi)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright (C) 2011, Maarten Moesen                                      %
% All rights reserved.                                                    %
%                                                                         %
% Author(s): Maarten Moesen                                               %
% E-mail: moesen.maarten@gmail.com                                        %
%                                                                         %
% This file is part of MMTensor.                                          %                                                                        %
%                                                                         %
% Redistribution and use in source and binary forms, with or without      %
% modification, are permitted provided that the following conditions are  %
% met:                                                                    %
%    * Redistributions of source code must retain the above copyright     %
%      notice, this list of conditions and the following disclaimer.      %
%    * Redistributions in binary form must reproduce the above copyright  %
%      notice, this list of conditions and the following disclaimer in    %
%      the documentation and/or other materials provided with the         %
%      distribution.                                                      %
%    * Neither the name of the Katholieke Universiteit Leuven nor the     %
%      names of its contributors may be used to endorse or promote        %
%      products derived from this software without specific prior written %
%      permission.                                                        %
%                                                                         %
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS     %
% "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT       %
% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A %
% PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KATHOLIEKE         %
% UNIVERSITEIT LEUVEN BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,     %
% SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED %
% TO, PROCUREMENT OF SUBSTITUTE GOODS ORSERVICES; LOSS OF USE, DATA, OR   %
% PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF  %
% LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING    %
% NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS      %
% SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.            %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function d = eval_fabric_distribution_function(F, theta, phi)

fun = @(a,b) 1;

%% If F is a second order tensor
if size(F, 2) == 1
  fun = @(a, b) eval_integral_fun_S2(F,a,b);
elseif size(F,2) == 6
  fun = @(a, b) eval_integral_fun_S4(F,a,b);
end

d = dblquad(fun, theta(1), theta(2), phi(1), phi(2));
d = d/(4*pi);

end

function i = eval_integral_fun_S2(F, a, b)

sa = sin(a);
ca = cos(a);
sb = sin(b);
cb = cos(b);

n = [sa.*cb; sa.*sb; ones(size(a)).*ca];
fun_value = contractS2ToScalar(F, n);

i = fun_value.*sa;

end

function i = eval_integral_fun_S4(F, a, b)

sa = sin(a);
ca = cos(a);
sb = sin(b);
cb = cos(b);

n = [sa.*cb; sa.*sb; ones(size(a)).*ca];
N = makeS2FromVector(n);

fun_value = zeros(size(a));
for ai = 1:numel(a)
  fun_value(ai) = N(:,ai)'*F*N(:,ai);
end

i = fun_value.*sa;

end


text:
module.exports = Reference;

var ServerError = require('./server_error');

// Reference
// {
//      group:      <Group>,
//      type:       "global" | "local",
//      subclass:   "{class name}",
//      globalID:   "{global object id}",
//      localID:    "{local object id}",
//      token:      "{client token}",
//      registered: bool
// }

function Reference(group, type, subclass, id, token)
{
    this.group = group;
    this.type = type;
    this.subclass = subclass;
    this.registered = false;
    switch (type) {
        case Reference.localType:
            this.localID = id;
            this.token = token;
            break;
        case Reference.globalType:
            this.globalID = id;
            break;
        case Reference.nullType:
            break;
        default:
            throw "bad object type";
    }
}

Reference.prototype.register = function(object)
{
    if (this.registered)
        throw new ServerError("Reference.register: inconsistent state");
    this.registered = true;

    if (this.type & Reference.localType)
        this.group.localObjects.set(this.subclass+this.token+this.localID, object);
    if (this.type & Reference.globalType)
        this.group.globalObjects.set(this.subclass+this.globalID, object);
};

Reference.prototype.unregister = function()
{
    if (!this.registered)
        throw new ServerError("Reference.register: inconsistent state");
    this.registered = false;

    if (this.type & Reference.localType)
        this.group.localObjects.delete(this.subclass+this.token+this.localID);
    if (this.type & Reference.globalType)
        this.group.globalObjects.delete(this.subclass+this.globalID);
};

Reference.prototype.isRegistered = function()
{
    if (this.type & Reference.localType)
        return this.group.localObjects.has(this.subclass+this.token+this.localID);
    if (this.type & Reference.globalType)
        return this.group.globalObjects.has(this.subclass+this.globalID);
};

Reference.prototype.getObject = function()
{
    var     object;

    if (this.type & Reference.localType)
        object = this.group.localObjects.get(this.subclass+this.token+this.localID);
    if (this.type & Reference.globalType)
        object = this.group.globalObjects.get(this.subclass+this.globalID);
    return (object === undefined ? null : object);
};

Reference.prototype.getValidObject = function()
{
    var     object;

    object = this.getObject();
    if ((object === null) || !object.loaded.set || (object.error !== null))
        return null;
    return object;
};

Reference.prototype.validate = function(client, sequence, fix)
{
    var     object;

    object = this.getValidObject();
    if ((object === null) || !object.doesExist(sequence)) {
        fix();
        return null;
    }
    return object.retain();
};

Reference.prototype.makeGlobal = function(id, object)
{
    this.type |= Reference.globalType;
    this.globalID = id;
    if (this.registered)
        this.group.globalObjects.set(this.subclass+this.globalID, object);
};

Reference.prototype.isNull = function()
{
    return ((this.type & Reference.nullType) !== 0);
};

Reference.prototype.isGlobal = function()
{
    return ((this.type & Reference.globalType) !== 0);
};

// static function functions

Reference.isReference = function(value)
{
    return (value instanceof Reference);
};

Reference.localType = 1;
Reference.globalType = 2;
Reference.nullType = 4;

Reference.nullReference = new Reference(null, Reference.nullType, null, null);


text:
package com.lqg.service.impl;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lqg.base.DaoSupportImpl;
import com.lqg.model.Admin;
import com.lqg.model.Comment;
import com.lqg.service.AdminService;
import com.lqg.service.CommentService;

@Service(value = "commentService")
@Transactional
public class CommentServiceImpl extends DaoSupportImpl<Comment> implements CommentService{

}


text:
from robot.parsing.settings import Timeout, Tags, Fixture, Template
from robot.utils.asserts import assert_equals
import robotide
import unittest

class Test(unittest.TestCase):

    def test_timeout_patch(self):
        timeout = Timeout('Timeout')
        assert_equals(timeout.as_list(),['Timeout'])
        timeout.message='boo'
        assert_equals(timeout.as_list(),['Timeout', '', 'boo'])
        timeout.message=''
        timeout.value='1 second'
        assert_equals(timeout.as_list(),['Timeout', '1 second'])
        timeout.message='boo'
        assert_equals(timeout.as_list(),['Timeout', '1 second', 'boo'])

    def test_settings_patch(self):
        tags = Tags('Tags')
        assert_equals(tags.as_list(),['Tags'])
        tags.value = ['tag1','tag2']
        assert_equals(tags.as_list(),['Tags', 'tag1', 'tag2'])

    def test_fixture_patch(self):
        fixture = Fixture('Teardown')
        assert_equals(fixture.as_list(), ['Teardown'])
        fixture.name = 'Keyword'
        assert_equals(fixture.as_list(), ['Teardown', 'Keyword'])
        fixture.args = ['arg1', 'arg2']
        assert_equals(fixture.as_list(), ['Teardown', 'Keyword', 'arg1', 'arg2'])
        fixture.name = ''
        assert_equals(fixture.as_list(), ['Teardown', '', 'arg1', 'arg2'])

    def test_template_patch(self):
        template = Template('Template')
        assert_equals(template.as_list(),['Template'])
        template.value = 'value'
        assert_equals(template.as_list(),['Template', 'value'])

if __name__ == "__main__":
    unittest.main()


text:
package org.xtreemfs.babudb.log;

/**
 *
 * @author bjko
 */
public class LogEntryException extends Exception {

    private static final long serialVersionUID = 2911195875170424834L;

    public LogEntryException(String message) {
        super(message);
    }

}


text:
@implementation YYNewsResponseResult

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             xmlns:app="http://schemas.android.com/apk/res-auto"
             android:background="@android:color/white"
             android:clickable="true"
             android:focusable="true">

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/srl_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv_main_list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:nestedScrollingEnabled="true"/>

    </android.support.v4.widget.SwipeRefreshLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab_stop"
        android:layout_width="@dimen/fab_00"
        android:layout_height="@dimen/fab_00"
        android:layout_gravity="bottom|end"
        android:layout_marginBottom="@dimen/fab_00_m_b"
        android:layout_marginEnd="@dimen/fab_m"
        android:layout_marginRight="@dimen/fab_m"
        android:scaleType="center"
        android:src="@drawable/pause_selector"
        app:backgroundTint="@color/colorPrimary"
        app:fabSize="normal"/>
</FrameLayout>


text:
package guitests;

import org.junit.Test;

import guitests.guihandles.TaskCardHandle;
import seedu.task.model.task.ReadOnlyTask;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;

public class SelectCommandTest extends TaskManagerGuiTest {

    @Test
    public void selectTask_nonEmptyList() {
        assertSelectionInvalid(10); //invalid index
        assertNoTaskSelected();

        assertSelectionSuccess(1); //first task in the list

        int taskCount = td.getTypicalTasks().length;
        assertSelectionSuccess(taskCount); //last task in the list
        assertTaskNotSelected(1); // assert that previous selection is not selected

        int middleIndex = taskCount / 2;
        assertSelectionSuccess(middleIndex); // a task in the middle of the list
        assertTaskNotSelected(taskCount); // assert that previous selection is not selected

        assertSelectionInvalid(taskCount + 1); //invalid index
        assertTaskSelected(middleIndex); //assert previous selection remains

        /* Testing other invalid indexes such as -1 should be done when testing the SelectCommand */
    }

    @Test
    public void selectTask_emptyList(){
        commandBox.runCommand("clear");
        assertListSize(0);
        assertSelectionInvalid(1); //invalid index
    }

    private void assertSelectionInvalid(int index) {
        commandBox.runCommand("select " + index);
        assertResultMessage("The task index provided is invalid");
    }

    private void assertSelectionSuccess(int index) {
        commandBox.runCommand("select " + index);
        assertResultMessage("Selected Task: "+index);
        assertTaskSelected(index);
    }

    private void assertTaskSelected(int index) {
        assertEquals(taskListPanel.getSelectedTasks().size(), 1);
        ReadOnlyTask selectedTask = taskListPanel.getSelectedTasks().get(0);
        assertEquals(taskListPanel.getTask(index-1), selectedTask);

        TaskCardHandle selectedCard = taskListPanel.getTaskCardHandle(index - 1);
        assertTrue(selectedCard.isDetailsShown());
    }

    private void assertTaskNotSelected(int index) {
        assertEquals(taskListPanel.getSelectedTasks().size(), 1);
        ReadOnlyTask selectedTask = taskListPanel.getSelectedTasks().get(0);
        assertNotEquals(taskListPanel.getTask(index - 1), selectedTask);

        TaskCardHandle selectedCard = taskListPanel.getTaskCardHandle(index - 1);
        assertFalse(selectedCard.isDetailsShown());
    }

    private void assertNoTaskSelected() {
        assertEquals(taskListPanel.getSelectedTasks().size(), 0);
    }
}


text:
"""Gradients for operators defined in nn_ops.py."""

from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.ops import gen_nn_ops

@ops.RegisterGradient("Conv2DBackpropInput")
def _DeConv2DGrad(op, grad):
  """The derivatives for deconvolution.

  Args:
    op: the Deconvolution op.
    grad: the tensor representing the gradient w.r.t. the output

  Returns:
    the gradients w.r.t. the input and the filter
  """
  return [None,
          nn_ops.conv2d_backprop_filter(grad,
                                      array_ops.shape(op.inputs[1]),
                                      op.inputs[2],
                                      op.get_attr("strides"),
                                      op.get_attr("padding")),
          nn_ops.conv2d(grad,
                        op.inputs[1],
                        op.get_attr("strides"),
                        op.get_attr("padding"))]

@ops.RegisterGradient("Softmax")
def _SoftmaxGrad(op, grad_softmax):
  """The derivative of the softmax nonlinearity.

  We assume that probs is of shape [batch_size * dim]
  The formula for dsoftmax / dx = (diag(softmax) - softmax * softmax').
  This matrix is diagonal minus a rank one matrix, so it is easy to implement
  as follows:

    grad_x = grad_softmax * softmax - sum(grad_softmax * softmax) * softmax

  Args:
     op: the Softmax op.
     grad_softmax:  the tensor representing the gradient w.r.t. the
       softmax output.

  Returns:
     gradient w.r.t the input to the softmax

  """
  # TODO(ilyasu): assert that the tensor has two dimensions at
  # graph-construction time?  Alternatively: do different things
  # depending on the dimensionality of the input tensors.
  softmax = op.outputs[0]
  grad_x = ((grad_softmax -
             array_ops.reshape(math_ops.reduce_sum(grad_softmax * softmax, [1]),
                               [-1, 1]))
            * softmax)
  return grad_x

@ops.RegisterGradient("BiasAdd")
def _BiasAddGrad(unused_bias_op, received_grad):
  """Return the gradients for the 2 inputs of bias_op.

  The first input of unused_bias_op is the tensor t, and its gradient is
  just the gradient the unused_bias_op received.

  The second input of unused_bias_op is the bias vector which has one fewer
  dimension than "received_grad" (the batch dimension.)  Its gradient is the
  received gradient Summed on the batch dimension, which is the first dimension.

  Args:
    unused_bias_op: The BiasOp for which we need to generate gradients.
    received_grad: Tensor.  The gradients passed to the BiasOp.

  Returns:
    Two tensors, the first one for the "tensor" input of the BiasOp,
    the second one for the "bias" input of the BiasOp.
  """
  reduction_dim_tensor = math_ops.range(0, array_ops.rank(received_grad) - 1)
  return (received_grad, math_ops.reduce_sum(received_grad, reduction_dim_tensor))

def _VerifyTensor(t, name, msg):
  """Assert that the tensor does not contain any NaN's.

  Args:
    t: Tensor
    name: name
    msg: message to log
  Returns:
    Tensor, but verified
  """
  with ops.name_scope(name):
    with ops.device(t.device or ops.get_default_graph().get_default_device()):
      verify_input = array_ops.check_numerics(t, message=msg)
      out = control_flow_ops.with_dependencies([verify_input], t)
  return out

@ops.RegisterGradient("Relu")
def _ReluGrad(op, grad):
  t = _VerifyTensor(op.inputs[0], op.name, "ReluGrad input is not finite.")
  return gen_nn_ops._relu_grad(grad, t)

@ops.RegisterGradient("Relu6")
def _Relu6Grad(op, grad):
  return gen_nn_ops._relu6_grad(grad, op.inputs[0])

@ops.RegisterGradient("Softplus")
def _SoftplusGrad(op, grad):
  return gen_nn_ops._softplus_grad(grad, op.inputs[0])

@ops.RegisterGradient("ReluGrad")
def _ReluGradGrad(op, grad):
  x = op.inputs[1]
  return (gen_nn_ops._relu_grad(grad, x),
          array_ops.zeros(shape=array_ops.shape(x), dtype=x.dtype))

def _BroadcastMul(vec, mat):
  """Multiply after broadcasting vec to match dimensions of mat.

  Args:
    vec: A 1-D tensor of dimension [D0]
    mat: A 2-D tensor of dimension [D0, D1]

  Returns:
    A tensor of dimension [D0, D1], the result of vec * mat
  """
  # Reshape vec to [D0, 1]
  vec = array_ops.expand_dims(vec, -1)
  return vec * mat

@ops.RegisterGradient("SoftmaxCrossEntropyWithLogits")
def _SoftmaxCrossEntropyWithLogitsGrad(op, grad_0, _):
  # grad_0 is the backprop for cost, and we multiply it with the gradients
  # (which is output[1])
  # There is no gradient for the labels
  return _BroadcastMul(grad_0, op.outputs[1]), None

@ops.RegisterGradient("Conv2D")
def _Conv2DGrad(op, grad):
  return [nn_ops.conv2d_backprop_input(array_ops.shape(op.inputs[0]),
                                       op.inputs[1],
                                       grad,
                                       op.get_attr("strides"),
                                       op.get_attr("padding")),
          nn_ops.conv2d_backprop_filter(op.inputs[0],
                                        array_ops.shape(op.inputs[1]),
                                        grad,
                                        op.get_attr("strides"),
                                        op.get_attr("padding"))]

@ops.RegisterGradient("LRN")
def _LRNGrad(op, grad):
  depth_radius = op.get_attr("depth_radius")
  bias = op.get_attr("bias")
  alpha = op.get_attr("alpha")
  beta = op.get_attr("beta")
  return [gen_nn_ops._lrn_grad(grad, op.inputs[0], op.outputs[0],
                               depth_radius, bias, alpha, beta)]

@ops.RegisterGradient("AvgPool")
def _AvgPoolGrad(op, grad):
  return gen_nn_ops._avg_pool_grad(array_ops.shape(op.inputs[0]), grad,
                                   op.get_attr("ksize"),
                                   op.get_attr("strides"),
                                   op.get_attr("padding"))

@ops.RegisterGradient("MaxPool")
def _MaxPoolGrad(op, grad):
  return gen_nn_ops._max_pool_grad(op.inputs[0], op.outputs[0], grad,
                                   op.get_attr("ksize"),
                                   op.get_attr("strides"),
                                   padding=op.get_attr("padding"))

@ops.RegisterGradient("BatchNormWithGlobalNormalization")
def _BatchNormWithGlobalNormalizationGrad(op, grad):
  """Return the gradients for the 5 inputs of BatchNormWithGlobalNormalization.

  We do not backprop anything for the mean and var intentionally as they are
  not being trained with backprop in the operation.

  Args:
    op: The BatchNormOp for which we need to generate gradients.
    grad: Tensor.  The gradients passed to the BatchNormOp.

  Returns:
    dx: Backprop for input, which is (grad * (g * rsqrt(v + epsilon)))
    dm: Backprop for mean, which is
        sum_over_rest(grad * g) * (-1 / rsqrt(v + epsilon))
    dv: Backprop for variance, which is
        sum_over_rest(grad * g * (x - m)) * (-1/2) * (v + epsilon) ^ (-3/2)
    db: Backprop for beta, which is grad reduced in all except the
        last dimension.
    dg: Backprop for gamma, which is (grad * ((x - m) * rsqrt(v + epsilon)))
  """
  dx, dm, dv, db, dg = gen_nn_ops._batch_norm_with_global_normalization_grad(
      op.inputs[0], op.inputs[1], op.inputs[2], op.inputs[4], grad,
      op.get_attr("variance_epsilon"), op.get_attr("scale_after_normalization"))
  return dx, dm, dv, db, dg

@ops.RegisterGradient("L2Loss")
def _L2LossGrad(op, grad):
  """Return the gradients for L2Loss.

  Args:
    op: The L2LossOp for which we need to generate gradients.
    grad: Tensor containing a single number.

  Returns:
    The gradient, which is (x * grad).
  """
  return op.inputs[0] * grad


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

namespace CaixaEletronico
{
  class Banco
  {
    private Conta[] contas = new Conta[10];
    private int quantidade;

    public void Adiciona(Conta conta)
    {
      this.contas[this.quantidade] = conta;
      this.quantidade++;
    }
  }
}


text:
using System.IO;
using Castle.Facilities.Logging;
using Castle.Windsor;
using Abp.Castle.Logging.Log4Net;
using Castle.Core.Logging;
using Abp.IO;
using Shouldly;
using Xunit;

namespace Abp.Castle.Log4Net.Tests
{
    public class Castle_Log4Net_Tests
    {
        [Fact]
        public void Should_Write_Logs_To_Text_File()
        {
            //Arrange
            var logFilePath = Path.Combine(Directory.GetCurrentDirectory(), "AbpCastleLog4NetTests-Logs.txt");
            FileHelper.DeleteIfExists(logFilePath); //Clean old file

            //Act
            var container = new WindsorContainer();
            container.AddFacility<LoggingFacility>(facility =>
            {
                facility.UseAbpLog4Net().WithConfig("log4net.config");
            });

            var logger = container.Resolve<ILoggerFactory>().Create(typeof(Castle_Log4Net_Tests));
            logger.Info("Should_Write_Logs_To_Text_File works!");

            //Assert
            File.Exists(logFilePath).ShouldBeTrue();
        }
    }
}


text:
namespace ash {
namespace mus {

namespace {

// TODO(jamescook): After ShellDelegate is ported to ash/common use
// ShellDelegate::CreateSessionStateDelegate() to construct the mus version
// of SessionStateDelegate.
class SessionStateDelegateStub : public SessionStateDelegate {
 public:
  SessionStateDelegateStub()
      : screen_locked_(false), user_info_(new user_manager::UserInfoImpl()) {}

  ~SessionStateDelegateStub() override {}

  // SessionStateDelegate:
  int GetMaximumNumberOfLoggedInUsers() const override { return 3; }
  int NumberOfLoggedInUsers() const override {
    // ash_shell has 2 users.
    return 2;
  }
  bool IsActiveUserSessionStarted() const override { return true; }
  bool CanLockScreen() const override { return true; }
  bool IsScreenLocked() const override { return screen_locked_; }
  bool ShouldLockScreenBeforeSuspending() const override { return false; }
  void LockScreen() override {
    screen_locked_ = true;
    NOTIMPLEMENTED();
  }
  void UnlockScreen() override {
    NOTIMPLEMENTED();
    screen_locked_ = false;
  }
  bool IsUserSessionBlocked() const override { return false; }
  SessionState GetSessionState() const override { return SESSION_STATE_ACTIVE; }
  const user_manager::UserInfo* GetUserInfo(UserIndex index) const override {
    return user_info_.get();
  }
  bool ShouldShowAvatar(WmWindow* window) const override {
    NOTIMPLEMENTED();
    return !user_info_->GetImage().isNull();
  }
  gfx::ImageSkia GetAvatarImageForWindow(WmWindow* window) const override {
    NOTIMPLEMENTED();
    return gfx::ImageSkia();
  }
  void SwitchActiveUser(const AccountId& account_id) override {}
  void CycleActiveUser(CycleUser cycle_user) override {}
  bool IsMultiProfileAllowedByPrimaryUserPolicy() const override {
    return true;
  }
  void AddSessionStateObserver(ash::SessionStateObserver* observer) override {}
  void RemoveSessionStateObserver(
      ash::SessionStateObserver* observer) override {}

 private:
  bool screen_locked_;

  // A pseudo user info.
  std::unique_ptr<user_manager::UserInfo> user_info_;

  DISALLOW_COPY_AND_ASSIGN(SessionStateDelegateStub);
};

}  // namespace

WmShellMus::WmShellMus(std::unique_ptr<ShellDelegate> shell_delegate,
                       WindowManager* window_manager)
    : WmShell(std::move(shell_delegate)),
      window_manager_(window_manager),
      session_state_delegate_(new SessionStateDelegateStub) {
  window_tree_client()->AddObserver(this);
  WmShell::Set(this);

  uint16_t accelerator_namespace_id = 0u;
  const bool add_result =
      window_manager->GetNextAcceleratorNamespaceId(&accelerator_namespace_id);
  // WmShellMus is created early on, so that this should always succeed.
  DCHECK(add_result);
  accelerator_controller_delegate_.reset(new AcceleratorControllerDelegateMus);
  accelerator_controller_registrar_.reset(new AcceleratorControllerRegistrar(
      window_manager_, accelerator_namespace_id));
  SetAcceleratorController(base::MakeUnique<AcceleratorController>(
      accelerator_controller_delegate_.get(),
      accelerator_controller_registrar_.get()));

  CreateMaximizeModeController();

  CreateMruWindowTracker();

  SetSystemTrayDelegate(base::WrapUnique(new DefaultSystemTrayDelegate));

  // TODO(jamescook): Port ash::sysui::KeyboardUIMus and use it here.
  SetKeyboardUI(KeyboardUI::Create());
}

WmShellMus::~WmShellMus() {
  // This order mirrors that of Shell.

  // Destroy maximize mode controller early on since it has some observers which
  // need to be removed.
  DeleteMaximizeModeController();
  DeleteToastManager();
  DeleteSystemTrayDelegate();
  // Has to happen before ~MruWindowTracker.
  DeleteWindowCycleController();
  DeleteWindowSelectorController();
  DeleteMruWindowTracker();
  if (window_tree_client())
    window_tree_client()->RemoveObserver(this);
  WmShell::Set(nullptr);
}

// static
WmShellMus* WmShellMus::Get() {
  return static_cast<WmShellMus*>(WmShell::Get());
}

void WmShellMus::AddRootWindowController(
    WmRootWindowControllerMus* controller) {
  root_window_controllers_.push_back(controller);
  // The first root window will be the initial root for new windows.
  if (!GetRootWindowForNewWindows())
    set_root_window_for_new_windows(controller->GetWindow());
}

void WmShellMus::RemoveRootWindowController(
    WmRootWindowControllerMus* controller) {
  auto iter = std::find(root_window_controllers_.begin(),
                        root_window_controllers_.end(), controller);
  DCHECK(iter != root_window_controllers_.end());
  root_window_controllers_.erase(iter);
}

// static
WmWindowMus* WmShellMus::GetToplevelAncestor(ui::Window* window) {
  while (window) {
    if (IsActivationParent(window->parent()))
      return WmWindowMus::Get(window);
    window = window->parent();
  }
  return nullptr;
}

WmRootWindowControllerMus* WmShellMus::GetRootWindowControllerWithDisplayId(
    int64_t id) {
  for (WmRootWindowControllerMus* root_window_controller :
       root_window_controllers_) {
    if (root_window_controller->GetDisplay().id() == id)
      return root_window_controller;
  }
  NOTREACHED();
  return nullptr;
}

WmWindow* WmShellMus::NewContainerWindow() {
  return WmWindowMus::Get(window_tree_client()->NewWindow());
}

WmWindow* WmShellMus::GetFocusedWindow() {
  return WmWindowMus::Get(window_tree_client()->GetFocusedWindow());
}

WmWindow* WmShellMus::GetActiveWindow() {
  return GetToplevelAncestor(window_tree_client()->GetFocusedWindow());
}

WmWindow* WmShellMus::GetPrimaryRootWindow() {
  return root_window_controllers_[0]->GetWindow();
}

WmWindow* WmShellMus::GetRootWindowForDisplayId(int64_t display_id) {
  return GetRootWindowControllerWithDisplayId(display_id)->GetWindow();
}

const DisplayInfo& WmShellMus::GetDisplayInfo(int64_t display_id) const {
  // TODO(mash): implement http://crbug.com/622480.
  NOTIMPLEMENTED();
  static DisplayInfo fake_info;
  return fake_info;
}

bool WmShellMus::IsActiveDisplayId(int64_t display_id) const {
  // TODO(mash): implement http://crbug.com/622480.
  NOTIMPLEMENTED();
  return true;
}

display::Display WmShellMus::GetFirstDisplay() const {
  // TODO(mash): implement http://crbug.com/622480.
  NOTIMPLEMENTED();
  return display::Screen::GetScreen()->GetPrimaryDisplay();
}

bool WmShellMus::IsInUnifiedMode() const {
  // TODO(mash): implement http://crbug.com/622480.
  return false;
}

bool WmShellMus::IsForceMaximizeOnFirstRun() {
  NOTIMPLEMENTED();
  return false;
}

void WmShellMus::SetDisplayWorkAreaInsets(WmWindow* window,
                                          const gfx::Insets& insets) {
  NOTIMPLEMENTED();
}

bool WmShellMus::IsPinned() {
  NOTIMPLEMENTED();
  return false;
}

void WmShellMus::SetPinnedWindow(WmWindow* window) {
  NOTIMPLEMENTED();
}

bool WmShellMus::CanShowWindowForUser(WmWindow* window) {
  NOTIMPLEMENTED();
  return true;
}

void WmShellMus::LockCursor() {
  NOTIMPLEMENTED();
}

void WmShellMus::UnlockCursor() {
  NOTIMPLEMENTED();
}

std::vector<WmWindow*> WmShellMus::GetAllRootWindows() {
  std::vector<WmWindow*> wm_windows(root_window_controllers_.size());
  for (size_t i = 0; i < root_window_controllers_.size(); ++i)
    wm_windows[i] = root_window_controllers_[i]->GetWindow();
  return wm_windows;
}

void WmShellMus::RecordGestureAction(GestureActionType action) {
  // TODO: http://crbug.com/616581.
  NOTIMPLEMENTED();
}

void WmShellMus::RecordUserMetricsAction(UserMetricsAction action) {
  // TODO: http://crbug.com/616581.
  NOTIMPLEMENTED();
}

void WmShellMus::RecordTaskSwitchMetric(TaskSwitchSource source) {
  // TODO: http://crbug.com/616581.
  NOTIMPLEMENTED();
}

void WmShellMus::ShowContextMenu(const gfx::Point& location_in_screen,
                                 ui::MenuSourceType source_type) {
  NOTIMPLEMENTED();
}

std::unique_ptr<WindowResizer> WmShellMus::CreateDragWindowResizer(
    std::unique_ptr<WindowResizer> next_window_resizer,
    wm::WindowState* window_state) {
  return base::WrapUnique(
      new DragWindowResizer(std::move(next_window_resizer), window_state));
}

std::unique_ptr<WindowCycleEventFilter>
WmShellMus::CreateWindowCycleEventFilter() {
  // TODO: implement me, http://crbug.com/629191.
  return nullptr;
}

std::unique_ptr<wm::MaximizeModeEventHandler>
WmShellMus::CreateMaximizeModeEventHandler() {
  // TODO: need support for window manager to get events before client:
  // http://crbug.com/624157.
  NOTIMPLEMENTED();
  return nullptr;
}

std::unique_ptr<ScopedDisableInternalMouseAndKeyboard>
WmShellMus::CreateScopedDisableInternalMouseAndKeyboard() {
  // TODO: needs implementation for mus, http://crbug.com/624967.
  NOTIMPLEMENTED();
  return nullptr;
}

std::unique_ptr<WmImmersiveFullscreenController>
WmShellMus::CreateImmersiveFullscreenController() {
  // TODO(sky): port ImmersiveFullscreenController, http://crbug.com/548435.
  return nullptr;
}

void WmShellMus::OnOverviewModeStarting() {
  FOR_EACH_OBSERVER(ShellObserver, *shell_observers(),
                    OnOverviewModeStarting());
}

void WmShellMus::OnOverviewModeEnded() {
  FOR_EACH_OBSERVER(ShellObserver, *shell_observers(), OnOverviewModeEnded());
}

SessionStateDelegate* WmShellMus::GetSessionStateDelegate() {
  return session_state_delegate_.get();
}

void WmShellMus::AddActivationObserver(WmActivationObserver* observer) {
  activation_observers_.AddObserver(observer);
}

void WmShellMus::RemoveActivationObserver(WmActivationObserver* observer) {
  activation_observers_.RemoveObserver(observer);
}

void WmShellMus::AddDisplayObserver(WmDisplayObserver* observer) {
  NOTIMPLEMENTED();
}

void WmShellMus::RemoveDisplayObserver(WmDisplayObserver* observer) {
  NOTIMPLEMENTED();
}

void WmShellMus::AddPointerWatcher(views::PointerWatcher* watcher) {
  // TODO(jamescook): Move PointerWatcherDelegateMus to //ash/mus and use here.
  NOTIMPLEMENTED();
}

void WmShellMus::RemovePointerWatcher(views::PointerWatcher* watcher) {
  NOTIMPLEMENTED();
}

bool WmShellMus::IsTouchDown() {
  // TODO: implement me, http://crbug.com/634967.
  NOTIMPLEMENTED();
  return false;
}

#if defined(OS_CHROMEOS)
void WmShellMus::ToggleIgnoreExternalKeyboard() {
  NOTIMPLEMENTED();
}
#endif  // defined(OS_CHROMEOS)

ui::WindowTreeClient* WmShellMus::window_tree_client() {
  return window_manager_->window_tree_client();
}

// static
bool WmShellMus::IsActivationParent(ui::Window* window) {
  return window && IsActivatableShellWindowId(
                       WmWindowMus::Get(window)->GetShellWindowId());
}

// TODO: support OnAttemptToReactivateWindow, http://crbug.com/615114.
void WmShellMus::OnWindowTreeFocusChanged(ui::Window* gained_focus,
                                          ui::Window* lost_focus) {
  WmWindow* gained_active = GetToplevelAncestor(gained_focus);
  if (gained_active)
    set_root_window_for_new_windows(gained_active->GetRootWindow());

  WmWindow* lost_active = GetToplevelAncestor(gained_focus);
  if (gained_active == lost_active)
    return;

  FOR_EACH_OBSERVER(WmActivationObserver, activation_observers_,
                    OnWindowActivated(gained_active, lost_active));
}

void WmShellMus::OnDidDestroyClient(ui::WindowTreeClient* client) {
  DCHECK_EQ(window_tree_client(), client);
  client->RemoveObserver(this);
}

}  // namespace mus
}  // namespace ash


text:
package component

import "sort"

const defaultPriority = 0

type initFunc func(c *Component) error
type initFuncs map[int][]initFunc

func (i initFuncs) add(f initFunc) {
	i.addAt(defaultPriority, f)
}

func (i initFuncs) addAt(priority int, f initFunc) {
	if _, ok := i[priority]; !ok {
		i[priority] = make([]initFunc, 0)
	}
	i[priority] = append(i[priority], f)
}

func (i initFuncs) run(c *Component) error {
	var keys []int
	for key := range i {
		keys = append(keys, key)
	}
	sort.Ints(keys)
	for _, key := range keys {
		for _, init := range i[key] {
			if err := init(c); err != nil {
				return err
			}
		}
	}
	return nil
}

var _initFuncs initFuncs = make(map[int][]initFunc)

// OnInitialize registers a function that is called when any Component is initialized
func OnInitialize(fun initFunc) {
	_initFuncs.add(fun)
}

func (c *Component) initialize() error {
	return _initFuncs.run(c)
}


text:
'use strict';

/*!
 * Module dependencies
 */

const obj2Str = require('./obj2Str');
const noop = require('./noop');
const cloneArray = require('./cloneArray');
const parseArg = require('./parseArg');
const isString = require('./isString');
const isFunction = require('./isFunction');
const isObject = require('./isObject');
const isLocale = require('./isLocale');
const assert = require('./assert');
const isRef = require('./isRef');
const Method = require('../method');

/**
 * ### addChainableMethod (ctx, name, options)
 *
 * Adds a method to an object, such that the method can also be chained.
 *
 *     utils.addChainableMethod(StringType.prototype, 'isEmail', function (val) {
 *       if (!val) return `${val} is not a valid email`;
 *     }, null, { type: 'validator' });
 *
 * The result can then be used as both a method that can be executing,
 * or as a language chain.
 *
 *     ovt.string().required().isEmail();
 *
 * @param {Object} ctx object to which the method is added
 * @param {String} type of which method will be added
 * @param {String} name of method to add
 * @param {Object} options
 * @namespace Utils
 * @name addChainableMethod
 * @api public
 */

function addChainableMethod(ctx, type, name, options) {
  options = options || {};

  assert(isObject(ctx), `${obj2Str(ctx)} is not a valid Object`);
  assert(isString(name), `${obj2Str(name)} is not a valid String`);

  const hasChainingBehaviour = isFunction(options.chainingBehaviour);
  const hasMethod = isFunction(options.method);
  const hasParseArgs = isFunction(options.parseArgs);

  assert(
    hasMethod || hasChainingBehaviour,
    `Invalid chainable method \`${name}\`, options method or chainingBehaviour should be provided!`
  );

  // assign default type, default is `validator`
  options.type = options.type || 'validator';

  // whether the method can be overwrite, default is `true`
  options.allowMethodOverwrite = options.allowMethodOverwrite === false;

  // Default function
  const defaultFn = options.method || noop;

  // Add cooresponding method
  ctx[name] = function(fn) {
    let self = this.clone();
    let args = cloneArray(arguments);

    // Apply parseArgs
    if (hasParseArgs) {
      args = options.parseArgs.apply(null, args);
    }

    // Apply chainable behaviour
    if (hasChainingBehaviour) {
      self = options.chainingBehaviour.apply(self, args) || self;
    }

    // Add method
    if (hasMethod) {
      let _fn = defaultFn;

      // handle method overwritten for validators
      // for example: ovt.string.isEmail(function(val) { /* your custom validator */ });
      if (options.allowMethodOverwrite && options.type === 'validator' && isFunction(fn)) {
        _fn = fn;
        args.shift();
      }

      // handle custom locale
      let locale;
      if (isLocale(args[args.length - 1])) locale = args.pop();

      // Analyze references
      let refs = Object.create(null);
      for (let i = 0; i < args.length; i++) {
        if (isRef(args[i])) {
          refs[i] = args[i];
        }
      }

      // Initialize `_methods` property
      if (!self._methods) self._methods = {};

      self._methods[name] = new Method({
        name: name,
        fn: _fn,
        args: args,
        refs: refs,
        type: options.type,
        path: `${type}.${name}`,
        locale: locale
      });
    }

    return self;
  };
}

module.exports = function chainable(proto, type) {
  return function chainableProxy() {
    let args = parseArg(arguments);
    let options = args.pop();
    args.forEach(function(name) {
      addChainableMethod(proto, type, name, options);
    });
  };
};


text:
package com.jiabangou.eleme.sdk.model;

import java.io.Serializable;
import java.util.List;

/**
 * 批量添加食物分类和食物的对象
 * Created by freeway on 16/7/22.
 */
public class FoodCategoryDetailSave implements Serializable {

    private Long restaurant_id;
    private String name;
    private Integer weight;
    private List<Food> foods;

    public Long getRestaurant_id() {
        return restaurant_id;
    }

    public void setRestaurant_id(Long restaurant_id) {
        this.restaurant_id = restaurant_id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getWeight() {
        return weight;
    }

    public void setWeight(Integer weight) {
        this.weight = weight;
    }

    public List<Food> getFoods() {
        return foods;
    }

    public void setFoods(List<Food> foods) {
        this.foods = foods;
    }

    @Override
    public String toString() {
        return "FoodCategoryDetailSave{" +
                "restaurant_id=" + restaurant_id +
                ", name='" + name + '\'' +
                ", weight=" + weight +
                ", foods=" + foods +
                '}';
    }

    public static class Food implements Serializable {
        private String name;
        private Float price;
        private String description;
        private Integer max_stock;
        private Integer stock;
        private Integer tp_food_id;
        private String image_hash;
        private Short is_new;
        private Short is_featured;
        private Short is_gum;
        private Short is_spicy;
        private Float packing_fee;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Float getPrice() {
            return price;
        }

        public void setPrice(Float price) {
            this.price = price;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public Integer getMax_stock() {
            return max_stock;
        }

        public void setMax_stock(Integer max_stock) {
            this.max_stock = max_stock;
        }

        public Integer getStock() {
            return stock;
        }

        public void setStock(Integer stock) {
            this.stock = stock;
        }

        public Integer getTp_food_id() {
            return tp_food_id;
        }

        public void setTp_food_id(Integer tp_food_id) {
            this.tp_food_id = tp_food_id;
        }

        public String getImage_hash() {
            return image_hash;
        }

        public void setImage_hash(String image_hash) {
            this.image_hash = image_hash;
        }

        public Short getIs_new() {
            return is_new;
        }

        public void setIs_new(Short is_new) {
            this.is_new = is_new;
        }

        public Short getIs_featured() {
            return is_featured;
        }

        public void setIs_featured(Short is_featured) {
            this.is_featured = is_featured;
        }

        public Short getIs_gum() {
            return is_gum;
        }

        public void setIs_gum(Short is_gum) {
            this.is_gum = is_gum;
        }

        public Short getIs_spicy() {
            return is_spicy;
        }

        public void setIs_spicy(Short is_spicy) {
            this.is_spicy = is_spicy;
        }

        public Float getPacking_fee() {
            return packing_fee;
        }

        public void setPacking_fee(Float packing_fee) {
            this.packing_fee = packing_fee;
        }

        @Override
        public String toString() {
            return "Food{" +
                    "name='" + name + '\'' +
                    ", price=" + price +
                    ", description='" + description + '\'' +
                    ", max_stock=" + max_stock +
                    ", stock=" + stock +
                    ", tp_food_id=" + tp_food_id +
                    ", image_hash='" + image_hash + '\'' +
                    ", is_new=" + is_new +
                    ", is_featured=" + is_featured +
                    ", is_gum=" + is_gum +
                    ", is_spicy=" + is_spicy +
                    ", packing_fee=" + packing_fee +
                    '}';
        }
    }
}


text:
package test.order.github288;

import org.testng.annotations.Test;

public class Actual2Sample extends BaseSample {

  @Test
  public void test2() {}
}


text:
ifndef buildDir
buildDir =	$(CURDIR)/../..
endif

include $(buildDir)/config/config.mk
include $(buildDir)/config/platform.mk
include $(buildDir)/config/directories.mk
include $(buildDir)/config/common.mk

#
# Directories
#
fuseDir =	$(buildDir)/clients/fuse

objDir =	$(fuseDir)/obj
binDir =	$(fuseDir)/bin
srcDir =	$(fuseDir)/src
incDir =	$(fuseDir)/include

reSrcDir =	$(buildDir)/server/re/src
reObjDir =	$(buildDir)/server/re/obj
reIncDir =	$(buildDir)/server/re/include

#
# Source files
#
OBJS =		\
		$(objDir)/irodsFs.o

BINS =		\
		$(binDir)/irodsFs \

LIB_OBJS =	\
		$(objDir)/iFuseOper.o \
		$(objDir)/iFuseLib.o \
		$(objDir)/iFuseLib.Conn.o \
		$(objDir)/iFuseLib.Desc.o \
		$(objDir)/iFuseLib.FileCache.o \
		$(objDir)/iFuseLib.Lock.o \
		$(objDir)/iFuseLib.PathCache.o \
		$(objDir)/iFuseLib.Utils.o \
		$(reObjDir)/list.o \
		$(reObjDir)/hashtable.o \
		$(reObjDir)/region.o \

INCLUDES +=	-I$(incDir) -I$(reIncDir)

#
# Compile and link flags
#

CFLAGS_OPTIONS := -g $(CFLAGS) $(MY_CFLAG)
ifdef IRODS_FS
CFLAGS_OPTIONS += -D_REENTRANT
INCLUDES +=	-I$(fuseHomeDir)/include
endif

CFLAGS =	$(CFLAGS_OPTIONS) $(INCLUDES) $(LIB_INCLUDES) $(SVR_INCLUDES) $(MODULE_CFLAGS)

ifeq ($(OS_platform), linux_platform)
LDFLAGS +=	$(LDADD) $(MODULE_LDFLAGS) -L$(fuseHomeDir)/lib -lfuse -ldl -lrt
else
LDFLAGS +=	$(LDADD) $(MODULE_LDFLAGS) -L$(fuseHomeDir)/lib -lfuse -ldl
endif

# for checking memleak
# LDFLAGS +=	-L/data/mwan/rods/ccmalloc/ccmalloc-0.4.0/lib

LDFLAGS +=	$(LIBRARY)

ifdef GSI_AUTH

ifeq ($(ADDR_64BITS), 1)
GSI_LIB_DIR=lib64
else
GSI_LIB_DIR=lib
endif

ifeq ($(GSI_INSTALL_TYPE),)
GSI_INSTALL_TYPE2=
else
GSI_INSTALL_TYPE2=_$(GSI_INSTALL_TYPE)
endif

# GSI_SSL is set to ssl to use the system's SSL library, else use
# regular Globus version.
ifndef GSI_SSL
GSI_SSL = ssl$(GSI_INSTALL_TYPE2)
endif

# GSI_CRYPTO is set to crypto to use the system's Crypto library, else use
# regular Globus version.
ifndef GSI_CRYPTO
GSI_CRYPTO = crypto$(GSI_INSTALL_TYPE2)
endif

LIB_GSI_AUTH = \
      -L$(GLOBUS_LOCATION)/$(GSI_LIB_DIR) \
      -lglobus_gss_assist$(GSI_INSTALL_TYPE2) \
      -lglobus_gssapi_gsi$(GSI_INSTALL_TYPE2) \
      -lglobus_gsi_credential$(GSI_INSTALL_TYPE2) \
      -lglobus_gsi_proxy_core$(GSI_INSTALL_TYPE2) \
      -lglobus_gsi_callback$(GSI_INSTALL_TYPE2) \
      -lglobus_oldgaa$(GSI_INSTALL_TYPE2) \
      -lglobus_gsi_sysconfig$(GSI_INSTALL_TYPE2) \
      -lglobus_gsi_cert_utils$(GSI_INSTALL_TYPE2) \
      -lglobus_openssl_error$(GSI_INSTALL_TYPE2) \
      -lglobus_openssl$(GSI_INSTALL_TYPE2) \
      -lglobus_proxy_ssl$(GSI_INSTALL_TYPE2) \
      -l$(GSI_SSL) \
      -l$(GSI_CRYPTO) \
      -lglobus_common$(GSI_INSTALL_TYPE2) \
      -lglobus_callout$(GSI_INSTALL_TYPE2) \
      -lltdl$(GSI_INSTALL_TYPE2)
LDFLAGS += $(LIB_GSI_AUTH)
endif

ifdef KRB_AUTH
ifdef KRB_LOCATION
LIB_KRB_AUTH = -L$(KRB_LOCATION)/lib -lgssapi_krb5
else
LIB_KRB_AUTH = -lgssapi_krb5
endif
ifdef GSI_AUTH
LIB_KRB_AUTH += -ldl
endif
LDFLAGS += $(LIB_KRB_AUTH)
endif

ifdef USE_SSL
LDFLAGS        += -lssl -lcrypto
endif

#
# Principal Targets
#
.PHONY: all fuse clients clean print_cflags print_ldflags
all:	fuse
	@true

clients: fuse
	@true

fuse:	print_cflags print_ldflags $(LIB_OBJS) $(OBJS) $(BINS)
	@true

$(objDir)/%.o:	$(srcDir)/%.c $(LIBRARY)
	@echo "Compile fuse `basename $@`..."
	@$(CC) -c $(CFLAGS) -o $@ $<

$(reObjDir)/%.o:	$(reSrcDir)/%.c $(LIBRARY)
	@echo "Compile fuse `basename $@`..."
	@$(CC) -c $(CFLAGS) -o $@ $<

$(binDir)/%:	$(objDir)/%.o $(LIB_OBJS)
	@echo "Link fuse `basename $@`..."
	@$(LDR) -o $@ $< $(LIB_OBJS) $(LDFLAGS)

# Show compile flags
print_cflags:
	@echo "Compile flags:"
	@echo "    $(CFLAGS_OPTIONS)"

# Show link flags
print_ldflags:
	@echo "Link flags:"
	@echo "    $(LDFLAGS)"

# Clean
clean:
	@echo "Cleaning fuse..."
	@rm -f $(BINS) $(OBJS) $(LIB_OBJS)


text:
<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="author" content="Matt Makai">
    <meta name="description" content="Full Stack Python explains each layer of the web application stack, from the server up through the rendering in a user's browser.">
    <link rel="shortcut icon" href="theme/img/fsp-fav.png">
    <title>Monitoring - Full Stack Python</title>
    <link href="theme/css/fsp.css" rel="stylesheet">

    <link href="//netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.css" rel="stylesheet">

            Full Stack Python

Monitoring

Monitoring tools capture, analyze and display information for a web
application's execution. Every application has issues arise throughout
all levels of the web stack. Monitoring tools provide transparency so
developers and operations teams can respond and fix problems.

Why is monitoring necessary?

Capturing and analyzing data about your production environment is critical
to proactively deal with stability, performance, and errors in a web
application.

Difference between monitoring and logging

Monitoring and logging are very similar in their purpose of helping to
diagnose issues with an application and aid the debugging process. One way
to think about the difference is that logging happens based on explicit events
while monitoring is a passive background collection of data.

For example, when an error occurs, that event is explicitly logged through
code in an exception handler. Meanwhile, a monitoring agent instruments the
code and gathers data not only about the logged exception but also the
performance of the functions.

This distinction between logging and monitoring is vague and not necessarily
the only way to look at it. Pragmatically, both are useful for maintaining a
production web application.

Monitoring layers

There are several important resources to monitor on the operating system
and network level of a web stack.

CPU utilization

Memory utilization

Persistence storage consumed versus free

Network bandwidth and latency

Application level monitoring encompasses several aspects. The amount of time
and resources dedicated to each aspect will vary based on whether an
application is read-heavy, write-heavy, or subject to rapid swings in traffic.

Application warnings and errors (500-level HTTP errors)

Application code performance

Template rendering time

Browser rendering time for the application

Database querying performance

Open source monitoring projects

statsd is a node.js network daemon that
  listens for metrics and aggregates them for transfer into another service
  such as Graphite.

Graphite stores
  time-series data and displays them in graphs through a Django web application.

Bucky measures the performance of a
  web application from end user's browsers and sends that data back to the
  server for collection.

Sensu is an open source monitoring framework
  written in Ruby but applicable to any programming language web application.

Graph Explorer by Vimeo is a
  Graphite-based dashboard with added features and a slick design.

PacketBeat sniffs protocol packets. Elasticsearch
  then allows developers to search the collected data and visualize what's
  happening inside their web application using the Kibana user interface.

Munin is a client plugin-based monitoring
  system that sends monitoring traffic to the Munin node where the data can
  be analyzed and visualized. Note this project is written in Perl so Perl 5
  must be installed on the node collecting the data.

Hosted monitoring services

New Relic. Application and database monitoring as
  well as plug ins for capturing and analyzing additional data about tools in
  your stack.

CopperEgg is lower-level monitoring on server and
  infrastructure. It's popular with DevOps shops that are making changes to
  their production environments and want immediate feedback on the results
  of those modifications.

Status.io focuses on uptime and response metrics
  transparency for web applications.

StatusPage.io (yes, there's both a Status and
  StatusPage.io) provides easy set up status pages for monitoring application
  up time.

PagerDuty alerts a designated person or group
  if there are stability, performance, or uptime issues with an application.

App Enlight provides performance, exception and
  error monitoring and is currently specific to Python web applications.

Monitoring resources

The Virtues of Monitoring

Effortless Monitoring with collectd, Graphite, and Docker

Practical Guide to StatsD/Graphite Monitoring
  is a detailed guide with code examples for monitoring infrastructure.

Bit.ly describes the
  "10 Things They Forgot to Monitor"
  beyond the standard metrics such as disk & memory usage.

Four Linux server monitoring tools

How to design useful monitoring and graphing visualizations

5 years of metrics and monitoring
  is a great presentation highlighting that visualization so humans can
  understand measurements is a hard problem. Line graphs are often not
  the best solution and they are overused.

The Collector Highlight Series has an article on StatsD
  that explains how to install it and how it works.

This survey on monitoring tools
  has some nice data and graphs on what developers and operations folks use
  in their environments.

Monitoring learning checklist

Review the software-as-a-service and open source monitoring tools below. Third
party services tend to be easier to set up and host the data for you. Open
source projects give you more control but you'll need to have additional
servers ready for the monitoring.

My recommendation is to install New Relic's free
option with the trial period to see how it works with your app. It'll give you
a good idea of the capabilities for application-level monitoring tools.

As your app scales take a look at setting up one of the the open source
monitoring projects such as StatsD with Graphite. The combination of those
two projects will give you fine-grained control over the system metrics
you're collecting and visualizing.

What topic do you want to learn next?

                How do I learn more about the users of my app with web analytics?

                What should I learn about web application security?

                How do I automate the server configuration I've set up?

                How should I log events in my application outside monitoring?

<form action="http://mattmakai.us2.list-manage.com/subscribe/post?u=b7e774f0c4f05dcebbfee183d&id=b22335388d" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

Interested in a complete Full Stack Python book with detailed tutorials and example code? Sign up here and you'll get an alert email if a book is created. No other emails will be sent other than sign up confirmation.

            Email Address
            <input type="email" value="" name="EMAIL" class="required email form-control" id="mce-EMAIL">

        <input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="btn btn-success" style="margin-top: 20px;">

<input type="text" name="b_b7e774f0c4f05dcebbfee183d_b22335388d" value="">

</form>

Monitoring

          Full Stack Python is an open book that explains
          each Python web application stack layer and provides the
          best web resources for those topics.

                    There's a work-in-progress
          subjects map (.pdf)
          that visually lays out each chapter in addition to the table of
          contents found below.

          Need more detailed tutorials and walkthroughs than what is
          presented here?
          Sign up for an email alert when that content is created.

          Matt Makai built
          this site with assistance from community pull requests. On GitHub
          you can follow Matt
          to see the daily changes.

Table of Contents

                        Introduction
                        Web Frameworks
                        Django
                        Flask
                        Bottle
                        Morepath
                        Other Web Frameworks
                        Deployment
                        Servers
                        Platform-as-a-service
                        Operating Systems
                        Web Servers
                        WSGI Servers
                        Source Control
                        Application Dependencies
                        Databases
                        NoSQL Data Stores
                        Web Design
                        Cascading Style Sheets
                        JavaScript
                        Continuous Integration
                        Code Metrics
                        Configuration Management
                        Static Content
                        Caching
                        Task Queues
                        Application Programming Interfaces
                        API Integration
                        API Creation
                        Logging
                        Monitoring
                        Web Analytics
                        Web Application Security
                        Best Python Resources
                        Development Environments
                        About the Author
                        Change Log
                        Future Directions
                        What "Full Stack" Means
                        Why Use Python?
                        WebSockets

            Matt Makai
            2014


text:
package org.apache.arrow.adapter.jdbc.consumer;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.arrow.vector.TinyIntVector;

/**
 * Consumer which consume tinyInt type values from {@link ResultSet}.
 * Write the data to {@link org.apache.arrow.vector.TinyIntVector}.
 */
public class TinyIntConsumer implements JdbcConsumer<TinyIntVector> {

  private TinyIntVector vector;
  private final int columnIndexInResultSet;

  private int currentIndex;

  /**
   * Instantiate a TinyIntConsumer.
   */
  public TinyIntConsumer(TinyIntVector vector, int index) {
    this.vector = vector;
    this.columnIndexInResultSet = index;
  }

  @Override
  public void consume(ResultSet resultSet) throws SQLException {
    byte value = resultSet.getByte(columnIndexInResultSet);
    if (!resultSet.wasNull()) {
      vector.setSafe(currentIndex, value);
    }
    currentIndex++;
  }

  @Override
  public void close() throws Exception {
    this.vector.close();
  }

  @Override
  public void resetValueVector(TinyIntVector vector) {
    this.vector = vector;
    this.currentIndex = 0;
  }
}


text:
'''
Plotter
#################
This is supposed to be a collection of classes and functions to aid in plotting
'''
from bokeh.plotting import output_notebook, show, figure
from bokeh.models.ranges import Range1d
import numpy as np

def lorentzian(freq, x, fwhm, inten=None):
    '''
    Plot lorentzian lineshapes

    Args:
        freq (np.ndarray): Frequencies where the peaks will be located
        x (np.ndarray): X-axis data points
        fwhm (float): Full-width at half maximum
        inten (np.ndarray): Intensities of the peaks

    Returns:
        y (np.ndarray): Y values of the lorentzian lineshapes
    '''
    y = np.zeros(len(x))
    if inten is None:
        for fdx in freq:
            y += 1/(2*np.pi)*fwhm/((fdx-x)**2+(0.5*fwhm)**2)
    else:
        for fdx, idx in zip(freq, inten):
            y += 1/(2*np.pi)*idx*fwhm/((fdx-x)**2+(0.5*fwhm)**2)
    return y

def gaussian(freq, x, fwhm, inten=None):
    '''
    Plot gaussian lineshapes

    Args:
        freq (np.ndarray): Frequencies where the peaks will be located
        x (np.ndarray): X-axis data points
        fwhm (float): Full-width at half maximum
        inten (np.ndarray): Intensities of the peaks

    Returns:
        y (np.ndarray): Y values of the gaussian lineshapes
    '''
    y = np.zeros(len(x))
    sigma = fwhm/(np.sqrt(8*np.log(2)))
    if inten is None:
        for fdx in freq:
            y += 1/(sigma*np.sqrt(2*np.pi))*np.exp(-(x-fdx)**2/(2*sigma**2))
    else:
        for idx, fdx in zip(inten, freq):
            y += 1/(sigma*np.sqrt(2*np.pi))*idx*np.exp(-(x-fdx)**2/(2*sigma**2))
    return y

class Plot:
    '''
    Class that has a collection of methods to make plotting easier. Some of the bokeh functions
    require importing specific functions like 'show' to display the figure. We want to make
    this easier by defining methods like show so we can just import the class and it takes
    care of everything.
    '''
    def show(self):
        # method just to have simple show function like in matplotlib
        show(self.fig)

    def set_xrange(self, xmin, xmax):
        # set the xrange
        # makes it simple to flip the xaxis by giving the max value as the
        # xmin and the min value as the xmax
        self.fig.x_range = Range1d(xmin, xmax)

    def set_yrange(self, ymin, ymax):
        # set the yrange
        self.fig.y_range = Range1d(ymin, ymax)

    def __init__(self, *args, **kwargs):
        # this worries me a bit and not sure if this is the proper way to do this
        output_notebook()
        # set the title
        title = kwargs.pop('title', '')
        # set the plot area parameters
        plot_width = kwargs.pop('plot_width', 500)
        plot_height = kwargs.pop('plot_height', 500)
        # set the tools to be used
        tools = kwargs.pop('tools', 'hover, crosshair, pan, wheel_zoom, box_zoom, reset, save,')
        # create the figure
        self.fig = figure(title=title, plot_height=plot_height, plot_width=plot_width, tools=tools)

# a matplotlib example
# maybe we can make some conditional so you can use a bokeh plot or a matplotlib plot
# might be useful if we just want to display the plot right on the screen as opposed
# to having the plot on the web browser
#
#import numpy as np
#import matplotlib.pyplot as plt
#from matplotlib import ticker, rc
#
#class Plot:
#    def lorentz(freq, x, fwhm, inten=None):
#        y = np.zeros(len(x))
#        if inten is None:
#            for fdx in freq:
#                y += 1/(2*np.pi)*fwhm/((fdx-x)**2+(0.5*fwhm)**2)
#        else:
#            for fdx, idx in zip(freq, inten):
#                y += 1/(2*np.pi)*idx*fwhm/((fdx-x)**2+(0.5*fwhm)**2)
#        return y
#
#    def __init__(self, *args, **kwargs):
#        title = kwargs.pop('title', '')
#        xlabel = kwargs.pop('xlabel', '')
#        ylabel = kwargs.pop('ylabel', '')
#        marker = kwargs.pop('marker', '')
#        line = kwargs.pop('line', '-')
#        figsize = kwargs.pop('figsize', (8,8))
#        dpi = kwargs.pop('dpi', 50)
#        xrange = kwargs.pop('xrange', None)
#        yrange = kwargs.pop('yrange', None)
#        fwhm = kwargs.pop('fwhm', 15)
#        res = kwargs.pop('res', 1)
#        grid = kwargs.pop('grid', False)
#        legend = kwargs.pop('legend', True)
#        invert_x = kwargs.pop('invert_x', False)
#        font = kwargs.pop('font', 10)
#        lorentz = kwargs.pop('lorentz', True)
#        self.fig = plt.figure(figsize=figsize, dpi=dpi)
#        rc('font', size=font)


text:
**Note:** These build scripts are intended only for publishers who want to
modify and rebuild the myTarget adapter framework. If you just want to
use the myTarget adapter, simply add `pod
'GoogleMobileAdsMediationMyTarget'` to your Podfile and run `pod
install --repo-update`.

## Prerequisites
-   Xcode 7.0 or higher
-   Deployment target of 7.0 or higher
-   Google Mobile Ads SDK
-   myTarget SDK
-   myTarget adapter source code

## Setup Instructions

-   Drop GoogleMobileAds framework into Project
    Directory->Drop_Framework_And_Headers.
-   Drop Third Party Ad framework into Project
    Directory->Drop_Framework_And_Headers.

## Build Instructions

-   To build a static library, select target scheme (FatAdapter). Edit scheme to
    Release OR Build.
-   Clean and Run/Archive.
-   To build a framework, select target scheme (Framework). Edit scheme to
    Release OR Build.
-   Clean and Run/Archive.

**Note:** New adapter file and/or framework will be generated in your Project
Directory->Library folder.


text:
API Summary
===========

.. toctree::
    :maxdepth: 2

    datasouece
    file_helper
    datascience
    languages
    sql


text:
using System;

namespace Chloe.Server.Exceptions
{
    public class LinkedResourceNotFoundException: NotFoundException
    {
        public LinkedResourceNotFoundException()
            :base("Linked Resorce Not Found")
        {
        }

        public LinkedResourceNotFoundException(string message)
            :base(message)
        {

        }

        public LinkedResourceNotFoundException(string message, Exception inner)
        {

        }
    }
}


text:
"""
An interpreted text role to link docs to Trac tickets.

To use: :ticket:`XXXXX`

Based on code from psycopg2 by Daniele Varrazzo.
"""
from docutils import nodes, utils
from docutils.parsers.rst import roles

def ticket_role(name, rawtext, text, lineno, inliner, options=None, content=None):
    if options is None:
        options = {}
    try:
        num = int(text.replace('#', ''))
    except ValueError:
        msg = inliner.reporter.error(
            "ticket number must be... a number, got '%s'" % text)
        prb = inliner.problematic(rawtext, rawtext, msg)
        return [prb], [msg]

    url_pattern = inliner.document.settings.env.app.config.ticket_url
    if url_pattern is None:
        msg = inliner.reporter.warning(
            "ticket not configured: please configure ticket_url in conf.py")
        prb = inliner.problematic(rawtext, rawtext, msg)
        return [prb], [msg]

    url = url_pattern % num
    roles.set_classes(options)
    node = nodes.reference(rawtext, '#' + utils.unescape(text), refuri=url, **options)
    return [node], []

def setup(app):
    app.add_config_value('ticket_url', None, 'env')
    app.add_role('ticket', ticket_role)
    return {'parallel_read_safe': True}


text: Copyright © {{date("Y")}} OKF GREECE.


text:
git init retro
cd retro
cp /usr/share/dict/words words.big
git add words.big
git commit -m'Add big file without using git-fat'
sort words.big > sorted.big
git add sorted.big
git commit -m'Add sorted file without using git-fat'
cat > .gitattributes <<EOF
original-attributes -text
EOF
git add .gitattributes
echo 'truncated' > words.big
git commit -am'Truncated words.big and add .gitattributes'
git fat init
cat > .gitattributes <<EOF
*.big filter=fat -text
EOF
git add .gitattributes
git checkout .
git commit -am'Import big files into git-fat'

git log --stat

git fat find 10000 | awk '{print $1}' > fat-files
git filter-branch --index-filter "git fat index-filter $(realpath fat-files) --manage-gitattributes" --tag-name-filter cat -- --all

git log --stat
git checkout HEAD^
rm *
git checkout .
ls -al

# Set up place to push
git checkout master
cat > .gitfat <<EOF
[rsync]
remote = $(realpath ../retro-store)
EOF
git add .gitfat
git commit -m'Add .gitfat for local push'
git fat push

cd ..
git clone file:///$(realpath retro) retro-clone
cd retro-clone
git fat init
git fat pull


text:
<Layout>

        Header

        Main

        Footer

        overlay

</Layout>


text:
extern char LiftDoor;
extern long ClosedDoors[32];

extern void ProcessClosedDoors();
extern void SequenceDoorControl(short item_number);
extern void UnderwaterDoorCollision(short item_num, struct ITEM_INFO* l, struct COLL_INFO* coll);
extern void DoubleDoorCollision(short item_num, struct ITEM_INFO* l, struct COLL_INFO* coll);
extern void PushPullKickDoorCollision(short item_num, struct ITEM_INFO* l, struct COLL_INFO* coll);
extern void PushPullKickDoorControl(short item_number);
extern void DoorCollision(short item_num, struct ITEM_INFO* l, struct COLL_INFO* coll);
extern void DoorControl(short item_number);
extern void OpenThatDoor(struct DOORPOS_DATA* d, struct DOOR_DATA* dd);
extern void ShutThatDoor(struct DOORPOS_DATA* d, struct DOOR_DATA* dd);

#endif


text:
/*
 * Abstract:
 *	Declaration of map, a binary tree.
 */

#ifndef _CL_MAP_H_
#define _CL_MAP_H_

#include <complib/cl_qmap.h>
#include <complib/cl_qpool.h>

#ifdef __cplusplus
#  define BEGIN_C_DECLS extern "C" {
#  define END_C_DECLS   }
#else				/* !__cplusplus */
#  define BEGIN_C_DECLS
#  define END_C_DECLS
#endif				/* __cplusplus */

BEGIN_C_DECLS
/****h* Component Library/Map
* NAME
*	Map
*
* DESCRIPTION
*	Map implements a binary tree that stores user objects.  Each item stored
*	in a map has a unique 64-bit key (duplicates are not allowed).  Map
*	provides the ability to efficiently search for an item given a key.
*
*	Map may allocate memory when inserting objects, and can therefore fail
*	operations due to insufficient memory.  Use quick map in situations
*	where such insertion failures cannot be tolerated.
*
*	Map is not thread safe, and users must provide serialization when adding
*	and removing items from the map.
*
*	The map functions operates on a cl_map_t structure which should be treated
*	as opaque and should be manipulated only through the provided functions.
*
* SEE ALSO
*	Types:
*		cl_map_iterator_t
*
*	Structures:
*		cl_map_t, cl_map_item_t, cl_map_obj_t
*
*	Item Manipulation:
*		cl_map_obj, cl_map_key
*
*	Initialization:
*		cl_map_construct, cl_map_init, cl_map_destroy
*
*	Iteration:
*		cl_map_end, cl_map_head, cl_map_tail, cl_map_next, cl_map_prev
*
*	Manipulation
*		cl_map_insert, cl_map_get, cl_map_remove_item, cl_map_remove,
*		cl_map_remove_all, cl_map_merge, cl_map_delta, cl_map_get_next
*
*	Attributes:
*		cl_map_count, cl_is_map_empty, cl_is_map_inited
*********/
/****s* Component Library: Map/cl_map_t
* NAME
*	cl_map_t
*
* DESCRIPTION
*	Quick map structure.
*
*	The cl_map_t structure should be treated as opaque and should
*	be manipulated only through the provided functions.
*
* SYNOPSIS
*/
typedef struct _cl_map {
	cl_qmap_t qmap;
	cl_qpool_t pool;
} cl_map_t;
/*
* FIELDS
*	qmap
*		Quick map object that maintains the map.
*
*	pool
*		Pool of cl_map_obj_t structures used to store user objects
*		in the map.
*
* SEE ALSO
*	Map, cl_map_obj_t
*********/

/****d* Component Library: Map/cl_map_iterator_t
* NAME
*	cl_map_iterator_t
*
* DESCRIPTION
*	Iterator type used to walk a map.
*
* SYNOPSIS
*/
typedef const cl_map_item_t *cl_map_iterator_t;
/*
* NOTES
*	The iterator should be treated as opaque to prevent corrupting the map.
*
* SEE ALSO
*	Map, cl_map_head, cl_map_tail, cl_map_next, cl_map_prev, cl_map_key
*********/

/****f* Component Library: Map/cl_map_count
* NAME
*	cl_map_count
*
* DESCRIPTION
*	The cl_map_count function returns the number of items stored
*	in a map.
*
* SYNOPSIS
*/
static inline size_t cl_map_count(IN const cl_map_t * const p_map)
{
	CL_ASSERT(p_map);
	return (cl_qmap_count(&p_map->qmap));
}

/*
* PARAMETERS
*	p_map
*		[in] Pointer to a map whose item count to return.
*
* RETURN VALUE
*	Returns the number of items stored in the map.
*
* SEE ALSO
*	Map, cl_is_map_empty
*********/

/****f* Component Library: Map/cl_is_map_empty
* NAME
*	cl_is_map_empty
*
* DESCRIPTION
*	The cl_is_map_empty function returns whether a map is empty.
*
* SYNOPSIS
*/
static inline boolean_t cl_is_map_empty(IN const cl_map_t * const p_map)
{
	CL_ASSERT(p_map);
	return (cl_is_qmap_empty(&p_map->qmap));
}

/*
* PARAMETERS
*	p_map
*		[in] Pointer to a map to test for emptiness.
*
* RETURN VALUES
*	TRUE if the map is empty.
*
*	FALSE otherwise.
*
* SEE ALSO
*	Map, cl_map_count, cl_map_remove_all
*********/

/****f* Component Library: Map/cl_map_key
* NAME
*	cl_map_key
*
* DESCRIPTION
*	The cl_map_key function retrieves the key value of a map item.
*
* SYNOPSIS
*/
static inline uint64_t cl_map_key(IN const cl_map_iterator_t itor)
{
	return (cl_qmap_key(itor));
}

/*
* PARAMETERS
*	itor
*		[in] Iterator for the item whose key to return.
*
* RETURN VALUE
*	Returns the 64-bit key value for the specified iterator.
*
* NOTES
*	The iterator specified by the itor parameter must have been retrived by
*	a previous call to cl_map_head, cl_map_tail, cl_map_next, or cl_map_prev.
*
*	The key value is set in a call to cl_map_insert.
*
* SEE ALSO
*	Map, cl_map_insert, cl_map_head, cl_map_tail, cl_map_next, cl_map_prev
*********/

/****f* Component Library: Map/cl_map_construct
* NAME
*	cl_map_construct
*
* DESCRIPTION
*	The cl_map_construct function constructs a map.
*
* SYNOPSIS
*/
void cl_map_construct(IN cl_map_t * const p_map);
/*
* PARAMETERS
*	p_map
*		[in] Pointer to a cl_map_t structure to construct.
*
* RETURN VALUE
*	This function does not return a value.
*
* NOTES
*	Allows calling cl_map_init, cl_map_destroy, and cl_is_map_inited.
*
*	Calling cl_map_construct is a prerequisite to calling any other
*	map function except cl_map_init.
*
* SEE ALSO
*	Map, cl_map_init, cl_map_destroy, cl_is_map_inited
*********/

/****f* Component Library: Event/cl_is_map_inited
* NAME
*	cl_is_map_inited
*
* DESCRIPTION
*	The cl_is_map_inited function returns whether a map was
*	successfully initialized.
*
* SYNOPSIS
*/
static inline boolean_t cl_is_map_inited(IN const cl_map_t * const p_map)
{
	/*
	 * The map's pool of map items is the last thing initialized.
	 * We can therefore use it to test for initialization.
	 */
	return (cl_is_qpool_inited(&p_map->pool));
}

/*
* PARAMETERS
*	p_map
*		[in] Pointer to a cl_map_t structure whose initialization state
*		to check.
*
* RETURN VALUES
*	TRUE if the map was initialized successfully.
*
*	FALSE otherwise.
*
* NOTES
*	Allows checking the state of a map to determine if invoking
*	member functions is appropriate.
*
* SEE ALSO
*	Map
*********/

/****f* Component Library: Map/cl_map_init
* NAME
*	cl_map_init
*
* DESCRIPTION
*	The cl_map_init function initialized a map for use.
*
* SYNOPSIS
*/
cl_status_t cl_map_init(IN cl_map_t * const p_map, IN const uint32_t min_items);
/*
* PARAMETERS
*	p_map
*		[in] Pointer to a cl_map_t structure to initialize.
*
*	min_items
*		[in] Minimum number of items that can be stored.  All necessary
*		allocations to allow storing the minimum number of items is
*		performed at initialization time.
*
* RETURN VALUES
*	CL_SUCCESS if the map was initialized successfully.
*
* NOTES
*	Allows calling map manipulation functions.
*
* SEE ALSO
*	Map, cl_map_destroy, cl_map_insert, cl_map_remove
*********/

/****f* Component Library: Map/cl_map_destroy
* NAME
*	cl_map_destroy
*
* DESCRIPTION
*	The cl_map_destroy function destroys a map.
*
* SYNOPSIS
*/
void cl_map_destroy(IN cl_map_t * const p_map);
/*
* PARAMETERS
*	p_map
*		[in] Pointer to a map to destroy.
*
* RETURN VALUE
*	This function does not return a value.
*
* NOTES
*	Performs any necessary cleanup of the specified map. Further
*	operations should not be attempted on the map. cl_map_destroy does
*	not affect any of the objects stored in the map.
*	This function should only be called after a call to cl_map_construct.
*
*	In debug builds, cl_map_destroy asserts that the map is empty.
*
* SEE ALSO
*	Map, cl_map_construct, cl_map_init
*********/

/****f* Component Library: Map/cl_map_end
* NAME
*	cl_map_end
*
* DESCRIPTION
*	The cl_map_end function returns the iterator for the end of a map.
*
* SYNOPSIS
*/
static inline cl_map_iterator_t cl_map_end(IN const cl_map_t * const p_map)
{
	CL_ASSERT(p_map);
	return (cl_qmap_end(&p_map->qmap));
}

/*
* PARAMETERS
*	p_map
*		[in] Pointer to a cl_map_t structure whose end to return.
*
* RETURN VALUE
*	Iterator for the end of the map.
*
* NOTES
*	cl_map_end is useful for determining the validity of map items returned
*	by cl_map_head, cl_map_tail, cl_map_next, cl_map_prev.  If the iterator
*	by any of these functions compares to the end, the end of the map was
*	encoutered.
*	When using cl_map_head or cl_map_tail, this condition indicates that
*	the map is empty.
*
* SEE ALSO
*	Map, cl_qmap_head, cl_qmap_tail, cl_qmap_next, cl_qmap_prev
*********/

/****f* Component Library: Map/cl_map_head
* NAME
*	cl_map_head
*
* DESCRIPTION
*	The cl_map_head function returns the map item with the lowest key
*	value stored in a map.
*
* SYNOPSIS
*/
static inline cl_map_iterator_t cl_map_head(IN const cl_map_t * const p_map)
{
	CL_ASSERT(p_map);
	return (cl_qmap_head(&p_map->qmap));
}

/*
* PARAMETERS
*	p_map
*		[in] Pointer to a map whose item with the lowest key is returned.
*
* RETURN VALUES
*	Iterator for the object with the lowest key in the map.
*
*	Iterator for the map end if the map was empty.
*
* NOTES
*	cl_map_head does not remove the object from the map.
*
* SEE ALSO
*	Map, cl_map_tail, cl_map_next, cl_map_prev, cl_map_end
*********/

/****f* Component Library: Map/cl_map_tail
* NAME
*	cl_map_tail
*
* DESCRIPTION
*	The cl_map_tail function returns the map item with the highest key
*	value stored in a map.
*
* SYNOPSIS
*/
static inline cl_map_iterator_t cl_map_tail(IN const cl_map_t * const p_map)
{
	CL_ASSERT(p_map);
	return (cl_qmap_tail(&p_map->qmap));
}

/*
* PARAMETERS
*	p_map
*		[in] Pointer to a map whose item with the highest key
*		is returned.
*
* RETURN VALUES
*	Iterator for the object with the highest key in the map.
*
*	Iterator for the map end if the map was empty.
*
* NOTES
*	cl_map_end does no remove the object from the map.
*
* SEE ALSO
*	Map, cl_map_head, cl_map_next, cl_map_prev, cl_map_end
*********/

/****f* Component Library: Map/cl_map_next
* NAME
*	cl_map_next
*
* DESCRIPTION
*	The cl_map_next function returns the map item with the next higher
*	key value than a specified map item.
*
* SYNOPSIS
*/
static inline cl_map_iterator_t cl_map_next(IN const cl_map_iterator_t itor)
{
	CL_ASSERT(itor);
	return (cl_qmap_next(itor));
}

/*
* PARAMETERS
*	itor
*		[in] Iterator for an object in a map whose successor to return.
*
* RETURN VALUES
*	Iterator for the object with the next higher key value in a map.
*
*	Iterator for the map end if the specified object was the last item in
*	the map.
*
* NOTES
*	The iterator must have been retrieved by a previous call to cl_map_head,
*	cl_map_tail, cl_map_next, or cl_map_prev.
*
* SEE ALSO
*	Map, cl_map_head, cl_map_tail, cl_map_prev, cl_map_end
*********/

/****f* Component Library: Map/cl_map_prev
* NAME
*	cl_map_prev
*
* DESCRIPTION
*	The cl_map_prev function returns the map item with the next lower
*	key value than a precified map item.
*
* SYNOPSIS
*/
static inline cl_map_iterator_t cl_map_prev(IN const cl_map_iterator_t itor)
{
	CL_ASSERT(itor);
	return (cl_qmap_prev(itor));
}

/*
* PARAMETERS
*	itor
*		[in] Iterator for an object in a map whose predecessor to return.
*
* RETURN VALUES
*	Iterator for the object with the next lower key value in a map.
*
*	Iterator for the map end if the specified object was the first item in
*	the map.
*
* NOTES
*	The iterator must have been retrieved by a previous call to cl_map_head,
*	cl_map_tail, cl_map_next, or cl_map_prev.
*
* SEE ALSO
*	Map, cl_map_head, cl_map_tail, cl_map_next, cl_map_end
*********/

/****f* Component Library: Map/cl_map_insert
* NAME
*	cl_map_insert
*
* DESCRIPTION
*	The cl_map_insert function inserts a map item into a map.
*
* SYNOPSIS
*/
void *cl_map_insert(IN cl_map_t * const p_map,
		    IN const uint64_t key, IN const void *const p_object);
/*
* PARAMETERS
*	p_map
*		[in] Pointer to a map into which to add the item.
*
*	key
*		[in] Value to associate with the object.
*
*	p_object
*		[in] Pointer to an object to insert into the map.
*
* RETURN VALUES
*	Pointer to the object in the map with the specified key after the call
*	completes.
*
*	NULL if there was not enough memory to insert the desired item.
*
* NOTES
*	Insertion operations may cause the map to rebalance.
*
*	If the map already contains an object already with the specified key,
*	that object will not be replaced and the pointer to that object is
*	returned.
*
* SEE ALSO
*	Map, cl_map_remove, cl_map_item_t
*********/

/****f* Component Library: Map/cl_map_get
* NAME
*	cl_map_get
*
* DESCRIPTION
*	The cl_map_get function returns the object associated with a key.
*
* SYNOPSIS
*/
void *cl_map_get(IN const cl_map_t * const p_map, IN const uint64_t key);
/*
* PARAMETERS
*	p_map
*		[in] Pointer to a map from which to retrieve the object with
*		the specified key.
*
*	key
*		[in] Key value used to search for the desired object.
*
* RETURN VALUES
*	Pointer to the object with the desired key value.
*
*	NULL if there was no item with the desired key value stored in
*	the map.
*
* NOTES
*	cl_map_get does not remove the item from the map.
*
* SEE ALSO
*	Map, cl_map_remove, cl_map_get_next
*********/

/****f* Component Library: Map/cl_map_get_next
* NAME
*	cl_map_get_next
*
* DESCRIPTION
*	The cl_qmap_get_next function returns the first object associated with a
*	key > the key specified.
*
* SYNOPSIS
*/
void *cl_map_get_next(IN const cl_map_t * const p_map, IN const uint64_t key);
/*
* PARAMETERS
*	p_map
*		[in] Pointer to a map from which to retrieve the object with
*		the specified key.
*
*	key
*		[in] Key value used to search for the desired object.
*
* RETURN VALUES
*	Pointer to the first object with a key > the desired key value.
*
*	NULL if there was no item with a key > the desired key
*	value stored in the map.
*
* NOTES
*	cl_map_get does not remove the item from the map.
*
* SEE ALSO
*	Map, cl_map_remove, cl_map_get
*********/

/****f* Component Library: Map/cl_map_remove_item
* NAME
*	cl_map_remove_item
*
* DESCRIPTION
*	The cl_map_remove_item function removes the specified map item
*	from a map.
*
* SYNOPSIS
*/
void
cl_map_remove_item(IN cl_map_t * const p_map, IN const cl_map_iterator_t itor);
/*
* PARAMETERS
*	p_map
*		[in] Pointer to a map from which to remove the object associated
*		with the specified iterator.
*
*	itor
*		[in] Iterator for an object to remove from its map.
*
* RETURN VALUE
*	This function does not return a value.
*
* NOTES
*	Removes the object associated with the specifid iterator from its map.
*
*	The specified iterator is no longer valid after the call completes.
*
*	The iterator must have been retrieved by a previous call to cl_map_head,
*	cl_map_tail, cl_map_next, or cl_map_prev.
*
* SEE ALSO
*	Map, cl_map_remove, cl_map_remove_all, cl_map_insert, cl_map_head,
*	cl_map_tail, cl_map_next, cl_map_prev
*********/

/****f* Component Library: Map/cl_map_remove
* NAME
*	cl_map_remove
*
* DESCRIPTION
*	The cl_map_remove function removes the map item with the specified key
*	from a map.
*
* SYNOPSIS
*/
void *cl_map_remove(IN cl_map_t * const p_map, IN const uint64_t key);
/*
* PARAMETERS
*	p_map
*		[in] Pointer to a cl_map_t structure from which to remove the
*		item with the specified key.
*
*	key
*		[in] Key value used to search for the object to remove.
*
* RETURN VALUES
*	Pointer to the object associated with the specified key if
*	it was found and removed.
*
*	NULL if no object with the specified key exists in the map.
*
* SEE ALSO
*	Map, cl_map_remove_item, cl_map_remove_all, cl_map_insert
*********/

/****f* Component Library: Map/cl_map_remove_all
* NAME
*	cl_map_remove_all
*
* DESCRIPTION
*	The cl_map_remove_all function removes all objects from a map,
*	leaving it empty.
*
* SYNOPSIS
*/
void cl_map_remove_all(IN cl_map_t * const p_map);
/*
* PARAMETERS
*	p_map
*		[in] Pointer to a map to empty.
*
* RETURN VALUE
*	This function does not return a value.
*
* SEE ALSO
*	Map, cl_map_remove, cl_map_remove_item
*********/

/****f* Component Library: Map/cl_map_obj
* NAME
*	cl_map_obj
*
* DESCRIPTION
*	The cl_map_obj function returns the object associated with an iterator.
*
* SYNOPSIS
*/
static inline void *cl_map_obj(IN const cl_map_iterator_t itor)
{
	return (cl_qmap_obj(PARENT_STRUCT(itor, cl_map_obj_t, item)));
}

/*
* PARAMETERS
*	itor
*		[in] Iterator whose object to return.
*
* RETURN VALUES
*	Returns the value of the object pointer associated with the iterator.
*
*	The iterator must have been retrieved by a previous call to cl_map_head,
*	cl_map_tail, cl_map_next, or cl_map_prev.
*
* SEE ALSO
*	Map, cl_map_head, cl_map_tail, cl_map_next, cl_map_prev
*********/

/****f* Component Library: Map/cl_map_merge
* NAME
*	cl_map_merge
*
* DESCRIPTION
*	The cl_map_merge function moves all items from one map to another,
*	excluding duplicates.
*
* SYNOPSIS
*/
cl_status_t
cl_map_merge(OUT cl_map_t * const p_dest_map,
	     IN OUT cl_map_t * const p_src_map);
/*
* PARAMETERS
*	p_dest_map
*		[out] Pointer to a cl_map_t structure to which items should be added.
*
*	p_src_map
*		[in/out] Pointer to a cl_map_t structure whose items to add
*		to p_dest_map.
*
* RETURN VALUES
*	CL_SUCCESS if the operation succeeded.
*
*	CL_INSUFFICIENT_MEMORY if there was not enough memory for the operation
*	to succeed.
*
* NOTES
*	Items are evaluated based on their keys only.
*
*	Upon return from cl_map_merge, the map referenced by p_src_map contains
*	all duplicate items.
*
* SEE ALSO
*	Map, cl_map_delta
*********/

/****f* Component Library: Map/cl_map_delta
* NAME
*	cl_map_delta
*
* DESCRIPTION
*	The cl_map_delta function computes the differences between two maps.
*
* SYNOPSIS
*/
cl_status_t
cl_map_delta(IN OUT cl_map_t * const p_map1,
	     IN OUT cl_map_t * const p_map2,
	     OUT cl_map_t * const p_new, OUT cl_map_t * const p_old);
/*
* PARAMETERS
*	p_map1
*		[in/out] Pointer to the first of two cl_map_t structures whose
*		differences to compute.
*
*	p_map2
*		[in/out] Pointer to the second of two cl_map_t structures whose
*		differences to compute.
*
*	p_new
*		[out] Pointer to an empty cl_map_t structure that contains the
*		items unique to p_map2 upon return from the function.
*
*	p_old
*		[out] Pointer to an empty cl_map_t structure that contains the
*		items unique to p_map1 upon return from the function.
*
* RETURN VALUES
*	CL_SUCCESS if the operation succeeded.
*
*	CL_INSUFFICIENT_MEMORY if there was not enough memory for the operation
*	to succeed.
*
* NOTES
*	Items are evaluated based on their keys.  Items that exist in both
*	p_map1 and p_map2 remain in their respective maps.  Items that
*	exist only p_map1 are moved to p_old.  Likewise, items that exist only
*	in p_map2 are moved to p_new.  This function can be useful in evaluating
*	changes between two maps.
*
*	Both maps pointed to by p_new and p_old must be empty on input.
*
*	Upon failure, all input maps are restored to their original state.
*
* SEE ALSO
*	Map, cl_map_merge
*********/

END_C_DECLS
#endif				/* _CL_MAP_H_ */


text:
module JamesRoshambo
  class LeastPlayedThrower
    def throw(dontcare, their_throws)
      their_throws.reduce({:rock => 0, :scissors => 0, :paper => 0}){|memo, thrown| memo[thrown] += 1; memo}.sort_by{|k,v| v}.first[0]
    end
  end
end