text:
package org.ovirt.engine.core.bll.gluster;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.argThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.ovirt.engine.core.utils.MockConfigRule.mockConfig;

import java.util.ArrayList;
import java.util.List;

import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatcher;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.ovirt.engine.core.bll.interfaces.BackendInternal;
import org.ovirt.engine.core.bll.utils.ClusterUtils;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.action.gluster.GlusterServiceParameters;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterServerService;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterService;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterServiceStatus;
import org.ovirt.engine.core.common.businessentities.gluster.ServiceType;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.constants.gluster.GlusterConstants;
import org.ovirt.engine.core.common.errors.VDSError;
import org.ovirt.engine.core.common.errors.VdcBllErrors;
import org.ovirt.engine.core.common.interfaces.VDSBrokerFrontend;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.common.vdscommands.VDSParametersBase;
import org.ovirt.engine.core.common.vdscommands.VDSReturnValue;
import org.ovirt.engine.core.common.vdscommands.gluster.GlusterServiceVDSParameters;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dao.gluster.GlusterServerServiceDao;
import org.ovirt.engine.core.dao.gluster.GlusterServiceDao;
import org.ovirt.engine.core.utils.MockConfigRule;

@RunWith(MockitoJUnitRunner.class)
public class ManageGlusterServiceCommandTest {
    ManageGlusterServiceCommand cmd;

    @Mock
    GlusterServerServiceDao serverServiceDao;
    @Mock
    GlusterServiceDao serviceDao;
    @Mock
    protected BackendInternal backend;
    @Mock
    protected VDSBrokerFrontend vdsBrokerFrontend;
    @Mock
    ClusterUtils clusterUtils;

    @ClassRule
    public static MockConfigRule mcr = new MockConfigRule(
            mockConfig(ConfigValues.DefaultMinThreadPoolSize, 10),
            mockConfig(ConfigValues.DefaultMaxThreadPoolSize, 20),
            mockConfig(ConfigValues.DefaultMaxThreadWaitQueueSize, 100));

    private final Guid startedServiceId1 = Guid.newGuid();
    private final Guid startedServiceId2 = Guid.newGuid();
    private final Guid stoppedServiceId1 = Guid.newGuid();
    private final Guid stoppedServiceId2 = Guid.newGuid();

    private void prepareMocks(ManageGlusterServiceCommand command) {
        doReturn(serverServiceDao).when(command).getGlusterServerServiceDao();
        doReturn(serviceDao).when(command).getGlusterServiceDao();
        doReturn(clusterUtils).when(command).getClusterUtils();
        doReturn(getUpServers()).when(clusterUtils).getAllUpServers(any(Guid.class));
        doReturn(null).when(serverServiceDao).getByServerIdAndServiceType(null, null);
        doReturn(null).when(serviceDao).getByServiceType(null);
    }

    private List<VDS> getUpServers() {
        final VDS vds1 = new VDS();
        vds1.setId(Guid.newGuid());
        vds1.setVdsName("gfs1");
        vds1.setVdsGroupId(Guid.newGuid());
        vds1.setStatus(VDSStatus.Up);
        final VDS vds2 = new VDS();
        vds2.setId(Guid.newGuid());
        vds2.setVdsName("gfs2");
        vds2.setVdsGroupId(Guid.newGuid());
        vds2.setStatus(VDSStatus.Up);

        return new ArrayList<VDS>() {
            {
                add(vds1);
                add(vds2);
            }
        };
    }

    private void mockBackend(boolean succeeded, VdcBllErrors errorCode, GlusterServiceStatus status) {
        when(cmd.getBackend()).thenReturn(backend);
        when(backend.getResourceManager()).thenReturn(vdsBrokerFrontend);

        VDSReturnValue vdsReturnValue = new VDSReturnValue();
        vdsReturnValue.setSucceeded(succeeded);
        if (!succeeded) {
            vdsReturnValue.setVdsError(new VDSError(errorCode, ""));
        } else {
            if (status == GlusterServiceStatus.STOPPED) {
                vdsReturnValue.setReturnValue(getGlusterServerServicesByServerIdAndServiceType(Guid.newGuid(),
                        ServiceType.GLUSTER_SWIFT,
                        status));
            } else {
                // Adding one additional service for the case of stop so that save mechanism can be tested out
                Guid serverId = Guid.newGuid();
                List<GlusterServerService> serverServiceList =
                        getGlusterServerServicesByServerIdAndServiceType(serverId,
                                ServiceType.GLUSTER_SWIFT,
                                status);
                GlusterServerService srvc3 = new GlusterServerService();
                srvc3.setMessage("test-msg3");
                srvc3.setPid(10000);
                srvc3.setPort(20000);
                srvc3.setServerId(serverId);
                srvc3.setServiceId(Guid.newGuid());
                srvc3.setServiceName("srvc3");
                srvc3.setServiceType(ServiceType.GLUSTER_SWIFT);
                srvc3.setStatus(status);

                serverServiceList.add(srvc3);
                vdsReturnValue.setReturnValue(serverServiceList);
            }
        }
        when(vdsBrokerFrontend.RunVdsCommand(eq(VDSCommandType.ManageGlusterService), argThat(anyServiceVDS()))).thenReturn(vdsReturnValue);
    }

    private ArgumentMatcher<VDSParametersBase> anyServiceVDS() {
        return new ArgumentMatcher<VDSParametersBase>() {

            @Override
            public boolean matches(Object argument) {
                if (!(argument instanceof GlusterServiceVDSParameters)) {
                    return false;
                }
                return true;
            }
        };
    }

    private List<GlusterServerService> getGlusterServerServicesByServerIdAndServiceType(Guid serverId,
            ServiceType serviceType, GlusterServiceStatus status) {
        List<GlusterServerService> serviceList = new ArrayList<GlusterServerService>();
        GlusterServerService srvc1 = new GlusterServerService();

        srvc1.setMessage("test-msg1");
        srvc1.setPid(10000);
        srvc1.setPort(20000);
        srvc1.setServerId(serverId);
        srvc1.setServiceId((status == GlusterServiceStatus.RUNNING) ? startedServiceId1 : stoppedServiceId1);
        srvc1.setServiceName("srvc1");
        srvc1.setServiceType(serviceType);
        srvc1.setStatus(status);
        serviceList.add(srvc1);

        GlusterServerService srvc2 = new GlusterServerService();
        srvc2.setMessage("test-msg2");
        srvc2.setPid(30000);
        srvc2.setPort(40000);
        srvc2.setServerId(serverId);
        srvc2.setServiceId((status == GlusterServiceStatus.RUNNING) ? startedServiceId2 : stoppedServiceId2);
        srvc2.setServiceName("srvc2");
        srvc2.setServiceType(serviceType);
        srvc2.setStatus(status);
        serviceList.add(srvc2);

        return serviceList;
    }

    private List<GlusterService> getGlusterServiceListByServiceType(ServiceType serviceType, GlusterServiceStatus status) {
        List<GlusterService> serviceList = new ArrayList<GlusterService>();
        GlusterService srvc1 = new GlusterService();

        srvc1.setId((status == GlusterServiceStatus.RUNNING) ? startedServiceId1 : stoppedServiceId1);
        srvc1.setServiceName("srvc1");
        srvc1.setServiceType(serviceType);
        serviceList.add(srvc1);

        GlusterService srvc2 = new GlusterService();
        srvc2.setId((status == GlusterServiceStatus.RUNNING) ? startedServiceId2 : stoppedServiceId2);
        srvc2.setServiceName("srvc2");
        srvc2.setServiceType(serviceType);
        serviceList.add(srvc2);

        return serviceList;
    }

    @Test
    public void canDoActionFails() {
        GlusterServiceParameters params = new GlusterServiceParameters();
        params.setActionType("InvalidActionType");
        cmd = spy(new ManageGlusterServiceCommand(params));
        assertFalse(cmd.canDoAction());

        params.setClusterId(null);
        params.setServerId(null);
        assertFalse(cmd.canDoAction());
    }

    @Test
    public void canDoActionSucceedsWithValidActionTypes() {
        GlusterServiceParameters params = new GlusterServiceParameters();
        params.setActionType(GlusterConstants.MANAGE_GLUSTER_SERVICE_ACTION_TYPE_START);
        cmd = spy(new ManageGlusterServiceCommand(params));
        prepareMocks(cmd);
        assertFalse(cmd.canDoAction());

        params.setActionType(GlusterConstants.MANAGE_GLUSTER_SERVICE_ACTION_TYPE_STOP);
        cmd = spy(new ManageGlusterServiceCommand(params));
        prepareMocks(cmd);
        assertFalse(cmd.canDoAction());

        params.setClusterId(Guid.newGuid());
        cmd = spy(new ManageGlusterServiceCommand(params));
        prepareMocks(cmd);
        assertTrue(cmd.canDoAction());

        params.setServerId(Guid.newGuid());
        cmd = spy(new ManageGlusterServiceCommand(params));
        prepareMocks(cmd);
        assertTrue(cmd.canDoAction());

        params.setClusterId(Guid.newGuid());
        params.setServerId(Guid.newGuid());
        prepareMocks(cmd);
        assertTrue(cmd.canDoAction());
    }

    @Test
    public void canDoActionFailsOnNull() {
        cmd =
                spy(new ManageGlusterServiceCommand(new GlusterServiceParameters(null,
                        null,
                        ServiceType.NFS,
                        GlusterConstants.MANAGE_GLUSTER_SERVICE_ACTION_TYPE_START)));
        prepareMocks(cmd);
        assertFalse(cmd.canDoAction());
    }

    private void setUpMockUpForStart() {
        prepareMocks(cmd);
        when(serviceDao.getByServiceType(any(ServiceType.class))).thenReturn(getGlusterServiceListByServiceType(ServiceType.GLUSTER_SWIFT,
                GlusterServiceStatus.STOPPED));
        doReturn(getGlusterServerServicesByServerIdAndServiceType(Guid.newGuid(),
                ServiceType.GLUSTER_SWIFT,
                GlusterServiceStatus.STOPPED)).when(serverServiceDao)
                .getByServerIdAndServiceType(any(Guid.class), any(ServiceType.class));

    }

    private void setUpMockUpForStop() {
        prepareMocks(cmd);
        when(serviceDao.getByServiceType(any(ServiceType.class))).thenReturn(getGlusterServiceListByServiceType(ServiceType.GLUSTER_SWIFT,
                GlusterServiceStatus.RUNNING));
        doReturn(getGlusterServerServicesByServerIdAndServiceType(Guid.newGuid(),
                ServiceType.GLUSTER_SWIFT,
                GlusterServiceStatus.RUNNING)).when(serverServiceDao)
                .getByServerIdAndServiceType(any(Guid.class), any(ServiceType.class));

    }

    private void setUpMockUpForRestart() {
        prepareMocks(cmd);
        when(serviceDao.getByServiceType(any(ServiceType.class))).thenReturn(getGlusterServiceListByServiceType(ServiceType.GLUSTER_SWIFT,
                GlusterServiceStatus.RUNNING));
        doReturn(getGlusterServerServicesByServerIdAndServiceType(Guid.newGuid(),
                ServiceType.GLUSTER_SWIFT,
                GlusterServiceStatus.RUNNING)).when(serverServiceDao)
                .getByServerIdAndServiceType(any(Guid.class), any(ServiceType.class));

    }

    @Test
    public void testExecuteCommandByClusterIdForStart() {
        cmd =
                spy(new ManageGlusterServiceCommand(new GlusterServiceParameters(Guid.newGuid(),
                        null,
                        ServiceType.GLUSTER_SWIFT,
                        GlusterConstants.MANAGE_GLUSTER_SERVICE_ACTION_TYPE_START)));
        setUpMockUpForStart();
        mockBackend(true, null, GlusterServiceStatus.STOPPED);
        cmd.executeCommand();
        verify(serverServiceDao, times(4)).updateByServerIdAndServiceType(any(GlusterServerService.class));
        assertEquals(cmd.getAuditLogTypeValue(), AuditLogType.GLUSTER_SERVICE_STARTED);
    }

    @Test
    public void testExecuteCommandByClusterIdForStop() {
        cmd =
                spy(new ManageGlusterServiceCommand(new GlusterServiceParameters(Guid.newGuid(),
                        null,
                        ServiceType.GLUSTER_SWIFT,
                        GlusterConstants.MANAGE_GLUSTER_SERVICE_ACTION_TYPE_STOP)));
        setUpMockUpForStop();
        mockBackend(true, null, GlusterServiceStatus.RUNNING);
        cmd.executeCommand();
        verify(serverServiceDao, times(4)).updateByServerIdAndServiceType(any(GlusterServerService.class));
        verify(serverServiceDao, times(2)).save(any(GlusterServerService.class));
        assertEquals(cmd.getAuditLogTypeValue(), AuditLogType.GLUSTER_SERVICE_STOPPED);
    }

    @Test
    public void testExecuteCommandByClusterIdForRestart() {
        cmd =
                spy(new ManageGlusterServiceCommand(new GlusterServiceParameters(Guid.newGuid(),
                        null,
                        ServiceType.GLUSTER_SWIFT,
                        GlusterConstants.MANAGE_GLUSTER_SERVICE_ACTION_TYPE_RESTART)));
        setUpMockUpForRestart();
        mockBackend(true, null, GlusterServiceStatus.RUNNING);
        cmd.executeCommand();
        verify(serverServiceDao, times(4)).updateByServerIdAndServiceType(any(GlusterServerService.class));
        assertEquals(cmd.getAuditLogTypeValue(), AuditLogType.GLUSTER_SERVICE_RESTARTED);
    }

    @Test
    public void testExecuteCommandByServerIdForStart() {
        cmd =
                spy(new ManageGlusterServiceCommand(new GlusterServiceParameters(null,
                        Guid.newGuid(),
                        ServiceType.GLUSTER_SWIFT,
                        GlusterConstants.MANAGE_GLUSTER_SERVICE_ACTION_TYPE_START)));
        setUpMockUpForStart();
        mockBackend(true, null, GlusterServiceStatus.STOPPED);
        cmd.executeCommand();
        verify(serverServiceDao, times(2)).updateByServerIdAndServiceType(any(GlusterServerService.class));
        assertEquals(cmd.getAuditLogTypeValue(), AuditLogType.GLUSTER_SERVICE_STARTED);
    }

    @Test
    public void testExecuteCommandByServerIdForStop() {
        cmd =
                spy(new ManageGlusterServiceCommand(new GlusterServiceParameters(null,
                        Guid.newGuid(),
                        ServiceType.GLUSTER_SWIFT,
                        GlusterConstants.MANAGE_GLUSTER_SERVICE_ACTION_TYPE_STOP)));
        setUpMockUpForStop();
        mockBackend(true, null, GlusterServiceStatus.RUNNING);
        cmd.executeCommand();
        verify(serverServiceDao, times(2)).updateByServerIdAndServiceType(any(GlusterServerService.class));
        verify(serverServiceDao, times(1)).save(any(GlusterServerService.class));
        assertEquals(cmd.getAuditLogTypeValue(), AuditLogType.GLUSTER_SERVICE_STOPPED);
    }

    @Test
    public void testExecuteCommandByServerIdForRestart() {
        cmd =
                spy(new ManageGlusterServiceCommand(new GlusterServiceParameters(null,
                        Guid.newGuid(),
                        ServiceType.GLUSTER_SWIFT,
                        GlusterConstants.MANAGE_GLUSTER_SERVICE_ACTION_TYPE_RESTART)));
        setUpMockUpForRestart();
        mockBackend(true, null, GlusterServiceStatus.RUNNING);
        cmd.executeCommand();
        verify(serverServiceDao, times(2)).updateByServerIdAndServiceType(any(GlusterServerService.class));
        assertEquals(cmd.getAuditLogTypeValue(), AuditLogType.GLUSTER_SERVICE_RESTARTED);
    }

    @Test
    public void testExecuteCommandFailsWithClusterIdForStart() {
        cmd =
                spy(new ManageGlusterServiceCommand(new GlusterServiceParameters(Guid.newGuid(),
                        null,
                        ServiceType.GLUSTER_SWIFT,
                        GlusterConstants.MANAGE_GLUSTER_SERVICE_ACTION_TYPE_START)));
        setUpMockUpForStart();
        mockBackend(false, VdcBllErrors.GlusterServicesActionFailed, GlusterServiceStatus.STOPPED);
        cmd.executeCommand();
        verify(serverServiceDao, never()).updateByServerIdAndServiceType(any(GlusterServerService.class));
        assertEquals(cmd.getAuditLogTypeValue(), AuditLogType.GLUSTER_SERVICE_START_FAILED);
    }

    @Test
    public void testExecuteCommandFailsWithClusterIdForStop() {
        cmd =
                spy(new ManageGlusterServiceCommand(new GlusterServiceParameters(Guid.newGuid(),
                        null,
                        ServiceType.GLUSTER_SWIFT,
                        GlusterConstants.MANAGE_GLUSTER_SERVICE_ACTION_TYPE_STOP)));
        setUpMockUpForStart();
        mockBackend(false, VdcBllErrors.GlusterServicesActionFailed, GlusterServiceStatus.RUNNING);
        cmd.executeCommand();
        verify(serverServiceDao, never()).updateByServerIdAndServiceType(any(GlusterServerService.class));
        assertEquals(cmd.getAuditLogTypeValue(), AuditLogType.GLUSTER_SERVICE_STOP_FAILED);
    }

    @Test
    public void testExecuteCommandFailsWithClusterIdForRestart() {
        cmd =
                spy(new ManageGlusterServiceCommand(new GlusterServiceParameters(Guid.newGuid(),
                        null,
                        ServiceType.GLUSTER_SWIFT,
                        GlusterConstants.MANAGE_GLUSTER_SERVICE_ACTION_TYPE_RESTART)));
        setUpMockUpForStart();
        mockBackend(false, VdcBllErrors.GlusterServicesActionFailed, GlusterServiceStatus.RUNNING);
        cmd.executeCommand();
        verify(serverServiceDao, never()).updateByServerIdAndServiceType(any(GlusterServerService.class));
        assertEquals(cmd.getAuditLogTypeValue(), AuditLogType.GLUSTER_SERVICE_RESTART_FAILED);
    }

    @Test
    public void testExecuteCommandFailsWithServerIdForStart() {
        cmd =
                spy(new ManageGlusterServiceCommand(new GlusterServiceParameters(Guid.newGuid(),
                        null,
                        ServiceType.GLUSTER_SWIFT,
                        GlusterConstants.MANAGE_GLUSTER_SERVICE_ACTION_TYPE_START)));
        setUpMockUpForStart();
        mockBackend(false, VdcBllErrors.GlusterServicesActionFailed, GlusterServiceStatus.STOPPED);
        cmd.executeCommand();
        verify(serverServiceDao, never()).updateByServerIdAndServiceType(any(GlusterServerService.class));
        assertEquals(cmd.getAuditLogTypeValue(), AuditLogType.GLUSTER_SERVICE_START_FAILED);
    }

    @Test
    public void testExecuteCommandFailsWithServerIdForStop() {
        cmd =
                spy(new ManageGlusterServiceCommand(new GlusterServiceParameters(Guid.newGuid(),
                        null,
                        ServiceType.GLUSTER_SWIFT,
                        GlusterConstants.MANAGE_GLUSTER_SERVICE_ACTION_TYPE_STOP)));
        setUpMockUpForStart();
        mockBackend(false, VdcBllErrors.GlusterServicesActionFailed, GlusterServiceStatus.RUNNING);
        cmd.executeCommand();
        verify(serverServiceDao, never()).updateByServerIdAndServiceType(any(GlusterServerService.class));
        assertEquals(cmd.getAuditLogTypeValue(), AuditLogType.GLUSTER_SERVICE_STOP_FAILED);
    }

    @Test
    public void testExecuteCommandFailsWithServerIdForRestart() {
        cmd =
                spy(new ManageGlusterServiceCommand(new GlusterServiceParameters(Guid.newGuid(),
                        null,
                        ServiceType.GLUSTER_SWIFT,
                        GlusterConstants.MANAGE_GLUSTER_SERVICE_ACTION_TYPE_RESTART)));
        setUpMockUpForStart();
        mockBackend(false, VdcBllErrors.GlusterServicesActionFailed, GlusterServiceStatus.RUNNING);
        cmd.executeCommand();
        verify(serverServiceDao, never()).updateByServerIdAndServiceType(any(GlusterServerService.class));
        assertEquals(cmd.getAuditLogTypeValue(), AuditLogType.GLUSTER_SERVICE_RESTART_FAILED);
    }
}


text:
class Rhino < Formula
  desc "JavaScript engine"
  homepage "https://www.mozilla.org/rhino/"
  url "https://github.com/mozilla/rhino/releases/download/Rhino1_7_11_Release/rhino-1.7.11.zip"
  sha256 "94c16e4de06fc08b5f7bf492284b8dc94c6357d3f96cc06fc06dcd6ae3f39547"

  bottle :unneeded

  conflicts_with "nut", :because => "both install `rhino` binaries"

  def install
    rhino_jar = "rhino-#{version}.jar"
    libexec.install "lib/#{rhino_jar}"
    bin.write_jar_script libexec/rhino_jar, "rhino"
    doc.install Dir["docs/*"]
  end

  test do
    assert_equal "42", shell_output("#{bin}/rhino -e \"print(6*7)\"").chomp
  end
end

redpajama_set_name: RedPajamaGithub


text:
import os
from argparse import ArgumentParser
from os import makedirs
import logging
JUDG_LOG = logging.getLogger("JUDGMENTS")

from intent.igt.consts import ODIN_TYPE, ODIN_JUDGMENT_ATTRIBUTE
from xigt import xigtpath

from intent.igt.igtutils import rgp, get_judgment
from xigt.codecs import xigtxml
from xigt.consts import INCREMENTAL

if __name__ == '__main__':
    p = ArgumentParser()
    p.add_argument('FILE', nargs='+')
    p.add_argument('-d', '--dest', required=True, help='Output directory for modified files.')
    p.add_argument('-f', '--force', help='Force overwrite existing files.')

    args = p.parse_args()

    for path in args.FILE:
        with open(path, 'r', encoding='utf-8') as f:
            xc = xigtxml.load(f, mode=INCREMENTAL)

            for inst in xc:
                JUDG_LOG.info('Processing instance "{}"'.format(inst.id))
                for item in xigtpath.findall(inst, 'tier[@type='+ODIN_TYPE+']/item'):

                    # Skip blank lines
                    if item.value() is None:
                        continue

                    # Get the judgment and add it if it is non-null.
                    j = get_judgment(item.value())
                    if j is not None:
                        item.attributes[ODIN_JUDGMENT_ATTRIBUTE] = j
                        JUDG_LOG.debug('Judgment found on item "{}"'.format(item.id))

            # Make the output directory if it doesn't exist.
            makedirs(args.dest, exist_ok=True)
            outpath = os.path.join(args.dest, os.path.basename(path))

            if not os.path.exists(outpath) or args.force:
                with open(outpath, 'w', encoding='utf-8') as out_f:
                    xigtxml.dump(out_f, xc)


text:
<?xml version="1.0"?>

<ruleset name="36"
    xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
  <description>
This ruleset contains links to rules that are new in PMD v3.6
  </description>

  <rule ref="rulesets/java/strings.xml/InefficientEmptyStringCheck"/>
  <rule ref="rulesets/java/design.xml/UnsynchronizedStaticDateFormatter"/>
  <rule ref="rulesets/java/strings.xml/InsufficientStringBufferDeclaration"/>
  <rule ref="rulesets/java/junit.xml/SimplifyBooleanAssertion"/>
  <rule ref="rulesets/java/basic.xml/AvoidThreadGroup"/>
  <rule ref="rulesets/jsp/basic-jsf.xml/DontNestJsfInJstlIteration"/>
  <rule ref="rulesets/jsp/basic.xml/NoLongScripts"/>
  <rule ref="rulesets/jsp/basic.xml/NoScriptlets"/>
  <rule ref="rulesets/jsp/basic.xml/NoInlineStyleInformation"/>
  <rule ref="rulesets/jsp/basic.xml/NoJspForward"/>
  <rule ref="rulesets/jsp/basic.xml/NoClassAttribute"/>
  <rule ref="rulesets/jsp/basic.xml/IframeMissingSrcAttribute"/>
  <rule ref="rulesets/jsp/basic.xml/NoHtmlComments"/>
</ruleset>


text:
const listeners = {};

export function listen(action, callback) {

  listeners[action] = listeners[action] || [];
  listeners[action].push(callback);
}

export function emit(action, ...params) {

  const callbacks = listeners[action];

  if (callbacks) {

    callbacks.forEach((callback) => callback(...params));
  }
}


text:
#include <ImfChannelList.h>
#include <ImfInputPart.h>
#include <ImfMultiPartInputFile.h>

#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow_io/core/kernels/io_stream.h"

namespace tensorflow {
namespace data {
namespace {

class OpenEXRIStream : public OPENEXR_IMF_INTERNAL_NAMESPACE::IStream {
 public:
  OpenEXRIStream(const string& filename, SizedRandomAccessFile* file,
                 int64 size)
      : OPENEXR_IMF_INTERNAL_NAMESPACE::IStream(filename.c_str()),
        file_(file),
        size_(size),
        pos_(0) {}

  ~OpenEXRIStream() {}

  bool read(char c[/*n*/], int n) override {
    if (pos_ + n > size_) {
      throw IEX_NAMESPACE::InputExc("Unexpected end of file.");
    }
    StringPiece result;
    Status status = file_->Read(pos_, n, &result, c);
    if (!status.ok() || result.size() < n) {
      throw IEX_NAMESPACE::InputExc("Unexpected end of file.");
    }
    pos_ += n;
    return (pos_ < size_);
  }
  OPENEXR_IMF_INTERNAL_NAMESPACE::Int64 tellg() override { return pos_; }
  void seekg(OPENEXR_IMF_INTERNAL_NAMESPACE::Int64 pos) override {
    if (pos > size_) {
      throw IEX_NAMESPACE::InputExc("seekg beyond end of file");
    }
    pos_ = pos;
  }

 private:
  SizedRandomAccessFile* file_ = nullptr;
  OPENEXR_IMF_INTERNAL_NAMESPACE::Int64 size_ = 0;
  OPENEXR_IMF_INTERNAL_NAMESPACE::Int64 pos_ = 0;
};

class DecodeEXRInfoOp : public OpKernel {
 public:
  explicit DecodeEXRInfoOp(OpKernelConstruction* context) : OpKernel(context) {
    env_ = context->env();
  }

  void Compute(OpKernelContext* context) override {
    const Tensor* input_tensor;
    OP_REQUIRES_OK(context, context->input("input", &input_tensor));

    const string filename = "memory";
    string memory = input_tensor->scalar<tstring>()();
    std::unique_ptr<SizedRandomAccessFile> file(new SizedRandomAccessFile(
        env_, filename, memory.data(), memory.size()));
    uint64 size;
    OP_REQUIRES_OK(context, file->GetFileSize(&size));

    OpenEXRIStream stream(filename, file.get(), size);
    Imf::MultiPartInputFile input_file(stream);

    std::vector<std::pair<int64, int64>> shape;
    std::vector<std::vector<int64>> dtype;
    std::vector<std::vector<string>> channel;
    int64 maxchannel = 0;
    for (int i = 0; i < input_file.parts(); i++) {
      Imath::Box2i dw = input_file.header(i).dataWindow();
      int64 height = dw.max.y - dw.min.y + 1;
      int64 width = dw.max.x - dw.min.x + 1;
      shape.push_back(std::pair<int64, int64>(height, width));

      dtype.push_back(std::vector<int64>());
      channel.push_back(std::vector<string>());
      for (Imf::ChannelList::ConstIterator c =
               input_file.header(i).channels().begin();
           c != input_file.header(i).channels().end(); c++) {
        switch (c.channel().type) {
          case Imf::UINT:
            dtype.back().push_back(DT_UINT32);
            break;
          case Imf::HALF:
            dtype.back().push_back(DT_HALF);
            break;
          case Imf::FLOAT:
            dtype.back().push_back(DT_FLOAT);
            break;
          default:
            OP_REQUIRES(context, false,
                        errors::InvalidArgument("invalid data type: ",
                                                c.channel().type));
        }
        channel.back().push_back(c.name());
      }
      maxchannel = maxchannel > channel.back().size() ? maxchannel
                                                      : channel.back().size();
    }

    Tensor* shape_tensor = nullptr;
    OP_REQUIRES_OK(context,
                   context->allocate_output(
                       0, TensorShape({static_cast<int64>(shape.size()), 2}),
                       &shape_tensor));
    for (size_t i = 0; i < shape.size(); i++) {
      shape_tensor->flat<int64>()(i * 2) = shape[i].first;
      shape_tensor->flat<int64>()(i * 2 + 1) = shape[i].second;
    }

    Tensor* dtype_tensor = nullptr;
    OP_REQUIRES_OK(
        context,
        context->allocate_output(
            1, TensorShape({static_cast<int64>(dtype.size()), maxchannel}),
            &dtype_tensor));
    Tensor* channel_tensor = nullptr;
    OP_REQUIRES_OK(
        context,
        context->allocate_output(
            2, TensorShape({static_cast<int64>(dtype.size()), maxchannel}),
            &channel_tensor));
    for (size_t i = 0; i < dtype.size(); i++) {
      for (size_t j = 0; j < dtype[i].size(); j++) {
        dtype_tensor->flat<int64>()(i * maxchannel + j) = dtype[i][j];
        channel_tensor->flat<tstring>()(i * maxchannel + j) = channel[i][j];
      }
      for (size_t j = dtype[i].size(); j < maxchannel; j++) {
        dtype_tensor->flat<int64>()(i * maxchannel + j) = 0;
        channel_tensor->flat<tstring>()(i * maxchannel + j) = "";
      }
    }
  }

 private:
  mutex mu_;
  Env* env_ TF_GUARDED_BY(mu_);
};
class DecodeEXROp : public OpKernel {
 public:
  explicit DecodeEXROp(OpKernelConstruction* context) : OpKernel(context) {
    env_ = context->env();
  }

  void Compute(OpKernelContext* context) override {
    const Tensor* input_tensor;
    OP_REQUIRES_OK(context, context->input("input", &input_tensor));

    const Tensor* index_tensor;
    OP_REQUIRES_OK(context, context->input("index", &index_tensor));

    const Tensor* channel_tensor;
    OP_REQUIRES_OK(context, context->input("channel", &channel_tensor));

    const string filename = "memory";
    string memory = input_tensor->scalar<tstring>()();
    std::unique_ptr<SizedRandomAccessFile> file(new SizedRandomAccessFile(
        env_, filename, memory.data(), memory.size()));
    uint64 size;
    OP_REQUIRES_OK(context, file->GetFileSize(&size));

    OpenEXRIStream stream(filename, file.get(), size);
    Imf::MultiPartInputFile input_file(stream);

    const int64 index = index_tensor->scalar<int64>()();
    string channel = channel_tensor->scalar<tstring>()();

    Imf::InputPart input_part(input_file, index);

    Imath::Box2i dw = input_part.header().dataWindow();

    int64 height = dw.max.y - dw.min.y + 1;
    int64 width = dw.max.x - dw.min.x + 1;

    DataType dtype = DT_INVALID;
    Imf::PixelType pixel_type = Imf::UINT;
    int x_sampling, y_sampling;
    for (Imf::ChannelList::ConstIterator c =
             input_part.header().channels().begin();
         c != input_part.header().channels().end(); c++) {
      if (channel == c.name()) {
        pixel_type = c.channel().type;
        x_sampling = c.channel().xSampling;
        y_sampling = c.channel().ySampling;
        switch (pixel_type) {
          case Imf::UINT:
            dtype = DT_UINT32;
            break;
          case Imf::HALF:
            dtype = DT_HALF;
            break;
          case Imf::FLOAT:
            dtype = DT_FLOAT;
            break;
          default:
            OP_REQUIRES(
                context, false,
                errors::InvalidArgument("invalid pixel type: ", pixel_type));
        }
      }
    }
    OP_REQUIRES(context, (dtype != DT_INVALID),
                errors::InvalidArgument("unable to find channel: ", channel));

    Tensor* output_tensor = nullptr;
    OP_REQUIRES_OK(context,
                   context->allocate_output(0, TensorShape({height, width}),
                                            &output_tensor));

    char* base;
    size_t byte;
    switch (dtype) {
      case DT_UINT32:
        base = (char*)output_tensor->flat<uint32>().data();
        byte = sizeof(uint32);
        break;
      case DT_HALF:
        base = (char*)output_tensor->flat<Eigen::half>().data();
        byte = sizeof(Eigen::half);
        break;
      case DT_FLOAT:
        base = (char*)output_tensor->flat<float>().data();
        byte = sizeof(float);
        break;
      default:
        OP_REQUIRES(context, false,
                    errors::InvalidArgument("invalid data type: ", dtype));
    }

    Imf::FrameBuffer frame_buffer;
    frame_buffer.insert(channel, Imf::Slice::Make(pixel_type, base, dw, 0, 0,
                                                  x_sampling, y_sampling));

    input_part.setFrameBuffer(frame_buffer);
    input_part.readPixels(dw.min.y, dw.max.y);
  }

 private:
  mutex mu_;
  Env* env_ TF_GUARDED_BY(mu_);
};
REGISTER_KERNEL_BUILDER(Name("IO>DecodeExrInfo").Device(DEVICE_CPU),
                        DecodeEXRInfoOp);
REGISTER_KERNEL_BUILDER(Name("IO>DecodeExr").Device(DEVICE_CPU), DecodeEXROp);

}  // namespace
}  // namespace data
}  // namespace tensorflow


text:
package net.fehmicansaglam.tepkin

import java.net.InetSocketAddress

import akka.actor._
import akka.io.{IO, Tcp}
import net.fehmicansaglam.tepkin.TepkinMessage.{Idle, Init, ShutDown}
import net.fehmicansaglam.tepkin.protocol.AuthMechanism
import net.fehmicansaglam.tepkin.protocol.message.Message

import scala.collection.mutable

/**
 * Manages a connection pool to a single MongoDB instance.
 *
 * @param remote MongoDB instance remote address
 * @param poolSize Number of connections.
 * @param databaseName Authentication database
 * @param credentials Optional. Authentication credentials.
 * @param authMechanism Optional. Authentication mechanism.
 */
class MongoPool(remote: InetSocketAddress,
                poolSize: Int,
                databaseName: String,
                credentials: Option[MongoCredentials],
                authMechanism: Option[AuthMechanism]) extends Actor {

  import context.system

  val manager = IO(Tcp)
  var idleConnections = Set.empty[ActorRef]
  val stash = mutable.Queue.empty[(ActorRef, Message)]

  self ! Init

  def receive: Receive = {

    // Create initial pool of connections.
    case Init =>
      (0 until poolSize) foreach { i =>
        context.watch {
          context.actorOf(
            MongoConnection.props(manager, remote, databaseName, credentials, authMechanism),
            s"connection-$i"
          )
        }
      }

    // First connection has been established.
    case Idle =>
      idleConnections += sender()
      context.become(working)
      if (stash.nonEmpty) {
        val item = stash.dequeue()
        self.tell(item._2, item._1)
      }

    case message: Message => stash.enqueue((sender(), message))
  }

  def working: Receive = {

    // Sender has finished its task and is idle.
    case Idle =>
      idleConnections += sender()

      (1 to Math.min(idleConnections.size, stash.size)) foreach { _ =>
        val item = stash.dequeue()
        idleConnections.head.tell(item._2, item._1)
        idleConnections = idleConnections.tail
      }

    case message: Message =>
      if (idleConnections.isEmpty) {
        stash.enqueue((sender(), message))
      } else {
        idleConnections.head.forward(message)
        idleConnections = idleConnections.tail
      }

    case ShutDown =>
      context.become(shuttingDown)
      if (stash.isEmpty) {
        idleConnections foreach (_ ! ShutDown)
      }
  }

  def shuttingDown: Receive = {

    case Idle =>
      idleConnections += sender()

      (1 to Math.min(idleConnections.size, stash.size)) foreach { _ =>
        val item = stash.dequeue()
        idleConnections.head.tell(item._2, item._1)
        idleConnections = idleConnections.tail
      }

      if (stash.isEmpty) {
        idleConnections.foreach(_ ! ShutDown)
      }

    case Terminated(connection) =>
      idleConnections -= connection
      if (idleConnections.isEmpty) {
        context.stop(self)
      }
  }

  override def postStop(): Unit = {
    context.system.terminate()
    ()
  }
}

object MongoPool {
  def props(remote: InetSocketAddress,
            poolSize: Int,
            databaseName: String,
            credentials: Option[MongoCredentials] = None,
            authMechanism: Option[AuthMechanism] = None): Props = {
    Props(classOf[MongoPool], remote, poolSize, databaseName, credentials, authMechanism)
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Approve.RuleCenter;

public partial class KC_ApplyHTBA_Print : System.Web.UI.Page
{
    RCenter rc = new RCenter();
    protected void Page_Load(object sender, EventArgs e)
    {
        string ReportServer = rc.GetSysObjectContent("_ReportServer");
        if (string.IsNullOrEmpty(ReportServer))
        {
            ReportServer = "http://" + Request.Url.Host + ":8075/WebReport/ReportServer?reportlet=";
        }
        //Response.Redirect(string.Format("{0}JSGC-KCHT.cpt{1}", ReportServer, "&FBaseId=" + Request.QueryString["FBaseId"] + "&FAppId=" + Request.QueryString["FAppId"]));

        if (!string.IsNullOrEmpty(Request.QueryString["FBaseId"]) && !string.IsNullOrEmpty(Request.QueryString["FAppId"]))
        {
            Response.Redirect(string.Format("{0}JSGC-KCHT.cpt{1}", ReportServer, "&FBaseId=" + Request.QueryString["FBaseId"] + "&FAppId=" + Request.QueryString["FAppId"]));
        }
        else
        {
            Response.Redirect(string.Format("{0}JSGC-KCHT.cpt{1}", ReportServer, "&FBaseId=" + Session["FBaseId"] + "&FAppId=" + Session["FAppId"]));
        }
    }
}


text:
(function($) {
  "use strict";

  $.paginator = function(element, options) {
    var defaults = {
      additionalCssClass: "",
      currentPageNumber: 1,
      maxPageNumber: 1,
      textTemplate: "Страница {{= it.currentPageNumber }} из {{= it.maxPageNumber }}",
      texts: {
        firstButtonTitle: "В начало",
        previousButtonTitle: "Предыдущая страница",
        inputTitle: "Кликните, чтобы ввести номер страницы",
        nextButtonTitle: "Следующая страница",
        lastButtonTitle: "В конец"
      },
      onPageNumberChanged: function() { }
    };

    var paginator = this;

    paginator.setCurrentPageNumber = setCurrentPageNumber;
    paginator.setMaxPageNumber = setMaxPageNumber;
    paginator.disablePaginator = disablePaginator;
    paginator.enablePaginator = enablePaginator;

    function createPaginator() {
      paginator.settings = $.extend(true, defaults, options);
      paginator.element = $(element);

      paginator.element
        .addClass("paginator " + paginator.settings.additionalCssClass)
        .append(
          "<button type='button' class='left-button' data-action='first' title='" + paginator.settings.texts.firstButtonTitle + "'></button>" +
          "<button type='button' class='left-button' data-action='previous' title='" + paginator.settings.texts.previousButtonTitle + "'></button>" +
          "<input type='text' title='" + paginator.settings.texts.inputTitle + "' />" +
          "<button type='button' class='right-button' data-action='next' title='" + paginator.settings.texts.nextButtonTitle + "'></button>" +
          "<button type='button' class='right-button' data-action='last' title='" + paginator.settings.texts.lastButtonTitle + "'></button>");

      paginator.input = paginator.element.find("input");
      paginator.leftButtons = paginator.element.find(".left-button");
      paginator.rightButtons = paginator.element.find(".right-button");
    }

    function setInputText() {
      var templateFunction = doT.template(paginator.settings.textTemplate);

      paginator.input.val(templateFunction({
        currentPageNumber: paginator.settings.currentPageNumber,
        maxPageNumber: paginator.settings.maxPageNumber
      }));
    }

    function setButtonsState() {
      if (paginator.settings.currentPageNumber === 1 && paginator.settings.maxPageNumber === 1) {
        paginator.leftButtons
          .addClass("disabled")
          .prop("disabled", true);

        paginator.rightButtons
          .addClass("disabled")
          .prop("disabled", true);
      } else if (paginator.settings.currentPageNumber === 1 && paginator.settings.maxPageNumber > paginator.settings.currentPageNumber) {
        paginator.leftButtons
          .addClass("disabled")
          .prop("disabled", true);

        paginator.rightButtons
          .removeClass("disabled")
          .prop("disabled", false);
      } else if (paginator.settings.currentPageNumber > 1 && paginator.settings.maxPageNumber > paginator.settings.currentPageNumber) {
        paginator.leftButtons
          .removeClass("disabled")
          .prop("disabled", false);

        paginator.rightButtons
          .removeClass("disabled")
          .prop("disabled", false);
      } else if (paginator.settings.currentPageNumber === paginator.settings.maxPageNumber) {
        paginator.leftButtons
          .removeClass("disabled")
          .prop("disabled", false);

        paginator.rightButtons
          .addClass("disabled")
          .prop("disabled", true);
      }
    }

    function setCurrentPageNumber(pageNumber) {
      if (!isNaN(pageNumber) && pageNumber >= 1 && pageNumber <= paginator.settings.maxPageNumber) {
        paginator.settings.currentPageNumber = pageNumber;
        setButtonsState();
        paginator.settings.onPageNumberChanged(paginator.settings.currentPageNumber);
      }

      setInputText();
    }

    function setMaxPageNumber(pageNumber) {
      if (isNaN(pageNumber) || pageNumber < 1) {
        return;
      }

      paginator.settings.maxPageNumber = pageNumber;

      if (paginator.settings.currentPageNumber > pageNumber) {
        paginator.settings.currentPageNumber = pageNumber;
        setButtonsState();
        paginator.settings.onPageNumberChanged(paginator.settings.currentPageNumber);
      }

      setInputText();
    }

    function disablePaginator() {
      paginator.element.find("button")
        .addClass("disabled")
        .prop("disabled", true);

      paginator.element.find("input")
        .addClass("disabled")
        .prop("disabled", true);
    }

    function enablePaginator() {
      paginator.element.find("input")
        .removeClass("disabled")
        .prop("disabled", false);

      setButtonsState();
    }

    function initializeEventHandlers() {
      paginator.element.on("click", "button", function(e) {
        e.preventDefault();

        switch ($(this).data("action")) {
          case "first":
            if (paginator.settings.currentPageNumber === 1) {
              return;
            }

            paginator.settings.currentPageNumber = 1;

            break;
          case "previous":
            if (paginator.settings.currentPageNumber === 1) {
              return;
            }

            paginator.settings.currentPageNumber -= 1;

            break;
          case "next":
            if (paginator.settings.currentPageNumber === paginator.settings.maxPageNumber) {
              return;
            }

            paginator.settings.currentPageNumber += 1;

            break;
          case "last":
            if (paginator.settings.currentPageNumber === paginator.settings.maxPageNumber) {
              return;
            }

            paginator.settings.currentPageNumber = paginator.settings.maxPageNumber;

            break;
        }

        setButtonsState();
        setInputText();
        paginator.settings.onPageNumberChanged(paginator.settings.currentPageNumber);
      });

      paginator.input.on("focus", function() {
        paginator.input.val(paginator.settings.currentPageNumber);
        paginator.input.select().mouseup(function(e) {
          e.preventDefault();
        });
      });

      paginator.input.on("blur", function() {
        var currentPageNumber = parseInt($(this).val(), 10);

        if (currentPageNumber !== paginator.settings.currentPageNumber) {
          setCurrentPageNumber(currentPageNumber);
        } else {
          setInputText();
        }
      });

      paginator.input.on("keydown", function(e) {
        if (e.keyCode === 13 || e.keyCode === 27) {
          paginator.input.blur();
        }
      });
    }

    (function() {
      createPaginator();
      initializeEventHandlers();

      setButtonsState();
      setInputText();
    })();
  };

  $.fn.paginator = function(options) {
    return this.each(function() {
      var $this = $(this);

      if (!$this.data("paginator")) {
        $this.data("paginator", new $.paginator(this, options));
      }
    });
  };
})(jQuery);


text:
**Work in progress**

Based on [SDCycleScrollView](https://github.com/gsdios/SDCycleScrollView), [commit 101](https://github.com/gsdios/SDCycleScrollView/tree/83e6de02cdccb4bd144b3fb2eaf74b79b1d9a9e2).

## Usage

### Carthage

Added following line to your `Cartfile`:

```
github "venj/CycleScrollView" ~> 1.0.0
```

## Current Work

Make a PhotoBrowser based on CycleScrollView.

## TODO

1. More Swifty ;)
2. Replace the dependency of SDWebImage
3. Carthage compatibility
4. Create a new PhotoBrowser base on this project
5. Make API compatible with Objective-C (API compatibility with original SDCycleScrollView)
6. Code compatibility with Swift 2.2 (when its finally released.)

## License

[MIT](LICENSE)


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>spring-cloud-netflix</artifactId>
        <groupId>org.springframework.cloud</groupId>
        <version>2.1.1.BUILD-SNAPSHOT</version>
        <relativePath>..</relativePath> <!-- lookup parent from repository -->
    </parent>

    <artifactId>spring-cloud-netflix-zuul</artifactId>
    <packaging>jar</packaging>
    <name>Spring Cloud Netflix Zuul</name>
    <description>Spring Cloud Netflix Zuul</description>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-netflix-hystrix</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.netflix.hystrix</groupId>
            <artifactId>hystrix-core</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.netflix.ribbon</groupId>
            <artifactId>ribbon-loadbalancer</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.netflix.ribbon</groupId>
            <artifactId>ribbon-core</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.netflix.ribbon</groupId>
            <artifactId>ribbon-httpclient</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-commons</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-context</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.netflix.zuul</groupId>
            <artifactId>zuul-core</artifactId>
            <optional>true</optional>
            <exclusions>
                <exclusion>
                    <artifactId>groovy-all</artifactId>
                    <groupId>org.codehaus.groovy</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>mockito-all</artifactId>
                    <groupId>org.mockito</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.netflix.netflix-commons</groupId>
            <artifactId>netflix-commons-util</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.retry</groupId>
            <artifactId>spring-retry</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-test-support</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace AutoMapper.Internal
{
    using Configuration;

    public static class ReflectionHelper
    {
        public static bool CanBeSet(MemberInfo propertyOrField)
        {
            return propertyOrField is FieldInfo field ?
                        !field.IsInitOnly :
                        ((PropertyInfo)propertyOrField).CanWrite;
        }

        public static object GetDefaultValue(ParameterInfo parameter)
        {
            if (parameter.DefaultValue == null && parameter.ParameterType.IsValueType())
            {
                return Activator.CreateInstance(parameter.ParameterType);
            }
            return parameter.DefaultValue;
        }

        public static object MapMember(ResolutionContext context, MemberInfo member, object value, object destination = null)
        {
            var memberType = GetMemberType(member);
            var destValue = destination == null ? null : GetMemberValue(member, destination);
            return context.Map(value, destValue, value?.GetType() ?? memberType, memberType, PropertyMap.Default);
        }

        public static bool IsDynamic(object obj) => obj is IDynamicMetaObjectProvider;

        public static bool IsDynamic(Type type) => typeof(IDynamicMetaObjectProvider).IsAssignableFrom(type);

        public static void SetMemberValue(MemberInfo propertyOrField, object target, object value)
        {
            if (propertyOrField is PropertyInfo property)
            {
                property.SetValue(target, value, null);
                return;
            }
            if (propertyOrField is FieldInfo field)
            {
                field.SetValue(target, value);
                return;
            }
            throw Expected(propertyOrField);
        }

        private static ArgumentOutOfRangeException Expected(MemberInfo propertyOrField)
            => new ArgumentOutOfRangeException(nameof(propertyOrField), "Expected a property or field, not " + propertyOrField);

        public static object GetMemberValue(MemberInfo propertyOrField, object target)
        {
            if (propertyOrField is PropertyInfo property)
            {
                return property.GetValue(target, null);
            }
            if (propertyOrField is FieldInfo field)
            {
                return field.GetValue(target);
            }
            throw Expected(propertyOrField);
        }

        public static IEnumerable<MemberInfo> GetMemberPath(Type type, string fullMemberName)
        {
            MemberInfo property = null;
            foreach (var memberName in fullMemberName.Split('.'))
            {
                var currentType = GetCurrentType(property, type);
                yield return property = currentType.GetFieldOrProperty(memberName);
            }
        }

        private static Type GetCurrentType(MemberInfo member, Type type)
        {
            var memberType = member?.GetMemberType() ?? type;
            if (memberType.IsGenericType() && typeof(IEnumerable).IsAssignableFrom(memberType))
            {
                memberType = memberType.GetTypeInfo().GenericTypeArguments[0];
            }
            return memberType;
        }

        public static MemberInfo GetFieldOrProperty(LambdaExpression expression)
        {
            var memberExpression = expression.Body as MemberExpression;
            return memberExpression != null
                ? memberExpression.Member
                : throw new ArgumentOutOfRangeException(nameof(expression), "Expected a property/field access expression, not " + expression);
        }

        public static MemberInfo FindProperty(LambdaExpression lambdaExpression)
        {
            Expression expressionToCheck = lambdaExpression;

            var done = false;

            while (!done)
            {
                switch (expressionToCheck.NodeType)
                {
                    case ExpressionType.Convert:
                        expressionToCheck = ((UnaryExpression)expressionToCheck).Operand;
                        break;
                    case ExpressionType.Lambda:
                        expressionToCheck = ((LambdaExpression)expressionToCheck).Body;
                        break;
                    case ExpressionType.MemberAccess:
                        var memberExpression = ((MemberExpression)expressionToCheck);

                        if (memberExpression.Expression.NodeType != ExpressionType.Parameter &&
                            memberExpression.Expression.NodeType != ExpressionType.Convert)
                        {
                            throw new ArgumentException(
                                $"Expression '{lambdaExpression}' must resolve to top-level member and not any child object's properties. You can use ForPath, a custom resolver on the child type or the AfterMap option instead.",
                                nameof(lambdaExpression));
                        }

                        var member = memberExpression.Member;

                        return member;
                    default:
                        done = true;
                        break;
                }
            }

            throw new AutoMapperConfigurationException(
                "Custom configuration for members is only supported for top-level individual members on a type.");
        }

        public static Type GetMemberType(MemberInfo memberInfo)
        {
            switch (memberInfo)
            {
                case MethodInfo mInfo:
                    return mInfo.ReturnType;
                case PropertyInfo pInfo:
                    return pInfo.PropertyType;
                case FieldInfo fInfo:
                    return fInfo.FieldType;
                case null:
                    throw new ArgumentNullException(nameof(memberInfo));
                default:
                    throw new ArgumentOutOfRangeException(nameof(memberInfo));
            }
        }

        /// <summary>
        /// if targetType is oldType, method will return newType
        /// if targetType is not oldType, method will return targetType
        /// if targetType is generic type with oldType arguments, method will replace all oldType arguments on newType
        /// </summary>
        /// <param name="targetType"></param>
        /// <param name="oldType"></param>
        /// <param name="newType"></param>
        /// <returns></returns>
        public static Type ReplaceItemType(Type targetType, Type oldType, Type newType)
        {
            if (targetType == oldType)
                return newType;

            if (targetType.IsGenericType())
            {
                var genSubArgs = targetType.GetTypeInfo().GenericTypeArguments;
                var newGenSubArgs = new Type[genSubArgs.Length];
                for (var i = 0; i < genSubArgs.Length; i++)
                    newGenSubArgs[i] = ReplaceItemType(genSubArgs[i], oldType, newType);
                return targetType.GetGenericTypeDefinition().MakeGenericType(newGenSubArgs);
            }

            return targetType;
        }
    }
}


text:
/* To override the forms template, remove this and replace with app/templates/forgot-password.hbs */
export { default } from 'ember-authenticate-me/templates/forgot-password';


text:
package com.o19s.es.ltr.ranker;

import org.elasticsearch.core.Nullable;

/**
 * A ranker used by {@link com.o19s.es.ltr.query.RankerQuery}
 * to compute a score based on a set of feature scores.
 */
public interface LtrRanker {

    /**
     * LtrRanker name
     *
     * @return the ranker name
     */
    String name();

    /**
     * Data point implementation used by this ranker
     * A data point is used to store feature scores.
     * A single instance will be created for every Scorer.
     * The implementation does not have to be thread-safe and meant to be reused.
     * The ranker must always provide a new instance of the data point when this method is called with null.
     *
     * @param reuse allows Ranker to reuse a feature vector instance
     * @return the new feature vector to be used by this ranker
     */
    FeatureVector newFeatureVector(@Nullable FeatureVector reuse);

    /**
     * Score the data point.
     * At this point all feature scores are set.
     * features that did not match are set with a score to 0
     *
     * @param point the feature vector point to compute the score for
     * @return the score computed for the given point
     */
    float score(FeatureVector point);

    /**
     * A FeatureVector used to store individual feature scores
     */
    interface FeatureVector {
        /**
         * Set the score for the given featureId
         *
         * @param featureId the feature-id to set the score for
         * @param score the feature's score
         */
        void setFeatureScore(int featureId, float score);

        /**
         * Retrieve the score for the given feature-id
         *
         * @param featureId the feature-id to retrieve the score for
         * @return the score computed for the given feature
         */
        float getFeatureScore(int featureId);

    }
}


text:
layout: post
title: Genética Jedi
---

Las fuerzas aliadas están muy preocupadas: hace años que no se sabe nada de los Jedis y se teme que su desaparición sea definitiva. Para buscar una solución han dado instrucciones a los mejores genetistas de la República para que encuentren el hijo con mayor número de _midiclorianos_ de cada familia y así poder refundar la Orden.

Los genetistas han descubierto que la cantidad de _midiclorianos_ de un hijo es el número de midiclorianos que obtiene de los padres multiplicado por la influencia de la Fuerza el día del nacimiento del niño.

En los sistemas planetarios hay muchas familias candidatas, así que se necesita un programa que procese los datos y ordene de mayor a menor el número de _midiclorianos_ del mejor hijo de cada familia.

# Entrada

El programa deberá leer, de la entrada estándar, múltiples casos de prueba. Cada uno comienza con un número 1 ≤ _F_ ≤ 20 indicando el número de familias analizadas, seguido de la información de cada una de ellas.

Para cada familia se especifica, en una primera línea, el número de hijos de la familia (al menos uno), seguido de la cantidad de _midiclorianos_ que los padres transmiten a sus retoños. La segunda línea contiene un número por cada uno de los hijos, indicando la influencia de la Fuerza el día de su nacimiento.

La entrada termina con un caso sin familias.

# Salida

Para cada caso, el programa escribirá una línea de números ordenada de mayor a menor con los midiclorianos del mejor hijo de cada familia. Se garantiza que ningún número será mayor que 1.000.000.000.

# Entrada de ejemplo

```
5
2
2 20
0 10
1 30
15
1
2 50
1 15
0
```

# Salida de ejemplo

```
450 200
750
```
# Solución propuesta

``` python

```

[Enlace del código](https://github.com/israelem/aceptaelreto/blob/master/codes/2018-02-05-genetica.py)

[Enlace en aceptaelreto.com](https://www.aceptaelreto.com/problem/statement.php?id=431)


text:
require 'spec_helper'

describe Backline::Attributes do

  let(:dummy_class) do
    Class.new do
      include Backline::Attributes
    end
  end

  subject { dummy_class.new }

  describe '.attribute' do
    it 'should add the new attribute to the attributes hash' do
      expect { dummy_class.attribute(:foo, bar: :baz) }
        .to change(dummy_class.attributes, :count).by(1)
    end

    it 'should generate a getter method' do
      dummy_class.attribute(:foo)
      expect(subject).to respond_to(:foo)
      expect(subject.foo).to eq(nil)
    end

    it 'should generate a setter method' do
      dummy_class.attribute(:foo)
      expect(subject).to respond_to(:foo=)
      expect(subject.foo = :bar).to eq(:bar)
    end
  end

  describe '.attribute_names' do
    it 'should return the attribute names' do
      dummy_class.attribute(:foo)
      expect(dummy_class.attribute_names).to eq(['foo'])
    end
  end

  describe '#read_attribute' do
    before do
      subject.attributes['foo'] = :bar
    end

    it 'should return the requested attributes value' do
      expect(subject.read_attribute(:foo)).to eq(:bar)
    end
  end

  describe '#write_attribute' do
    it 'should store the given attributes value' do
      expect { subject.write_attribute(:foo, :bar) }
        .to change(subject, :attributes).from({}).to('foo' => :bar)
    end
  end

end


text:
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta content="history" name="save" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>FileLogger Properties</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            OpenPop.NET POP3 Library Documentation

FileLogger Properties

The properties of the FileLogger class are listed below. For a complete list of FileLogger class members, see the FileLogger Members topic.

Public Static Properties

Enabled	 Turns the logging on and off.

LogFile	 The file to which log messages will be written

Verbose	 Enables or disables the output of Debug level log messages

See Also

        FileLogger Class | OpenPop.Common.Logging Namespace

      <object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;">
        <param name="Keyword" value="FileLogger class, properties">
        </param>
      </object>

          Send comments on this topic.

          Public Domain Dedication

Generated from assembly OpenPop [2.0.4.369] by NDoc3


text:
package org.apache.flink.api.common.eventtime;

import org.apache.flink.annotation.Public;

import javax.annotation.Nullable;

import java.time.Duration;

import static org.apache.flink.util.Preconditions.checkArgument;
import static org.apache.flink.util.Preconditions.checkNotNull;

/**
 * WatermarkStrategies is a simply way to build a {@link WatermarkStrategy} by configuring
 * common strategies.
 */
@Public
public final class WatermarkStrategies<T> {

	/**
	 * The {@link TimestampAssigner} to use. This can be {@code null} for cases where records come
	 * out of a source with valid timestamps, for example from Kafka.
	 */
	@Nullable
	private TimestampAssignerSupplier<T> timestampAssignerSupplier = null;

	/** The base strategy for watermark generation. Starting point, is always set. */
	private final WatermarkStrategy<T> baseStrategy;

	/** Optional idle timeout for watermarks. */
	@Nullable
	private Duration idleTimeout;

	private WatermarkStrategies(WatermarkStrategy<T> baseStrategy) {
		this.baseStrategy = baseStrategy;
	}

	// ------------------------------------------------------------------------
	//  builder methods
	// ------------------------------------------------------------------------

	/**
	 * Add an idle timeout to the watermark strategy.
	 * If no records flow in a partition of a stream for that amount of time, then that partition
	 * is considered "idle" and will not hold back the progress of watermarks in downstream operators.
	 *
	 *
Idleness can be important if some partitions have little data and might not have events during
	 * some periods. Without idleness, these streams can stall the overall event time progress of the
	 * application.
	 */
	public WatermarkStrategies<T> withIdleness(Duration idleTimeout) {
		checkNotNull(idleTimeout, "idleTimeout");
		checkArgument(!(idleTimeout.isZero() || idleTimeout.isNegative()), "idleTimeout must be greater than zero");
		this.idleTimeout = idleTimeout;
		return this;
	}

	/**
	 * Adds the given {@link TimestampAssigner} (via a {@link TimestampAssignerSupplier}) to this
	 * {@link WatermarkStrategies}.
	 *
	 *
You can use this when a {@link TimestampAssigner} needs additional context, for example
	 * access to the metrics system.
	 *
	 *

	 * {@code WatermarkStrategy<Object> wmStrategy = WatermarkStrategies
	 *   .forMonotonousTimestamps()
	 *   .withTimestampAssigner((ctx) -> new MetricsReportingAssigner(ctx))
	 *   .build();
	 * }

	 */
	public WatermarkStrategies<T> withTimestampAssigner(TimestampAssignerSupplier<T> timestampAssigner) {
		checkNotNull(timestampAssigner, "timestampAssigner");
		this.timestampAssignerSupplier = timestampAssigner;
		return this;
	}

	/**
	 * Adds the given {@link TimestampAssigner} to this {@link WatermarkStrategies}.
	 *
	 *
You can use this in case you want to specify a {@link TimestampAssigner} via a lambda
	 * function.
	 *
	 *

	 * {@code WatermarkStrategy<CustomObject> wmStrategy = WatermarkStrategies
	 *   .<CustomObject>forMonotonousTimestamps()
	 *   .withTimestampAssigner((event, timestamp) -> event.getTimestamp())
	 *   .build();
	 * }

	 */
	public WatermarkStrategies<T> withTimestampAssigner(SerializableTimestampAssigner<T> timestampAssigner) {
		checkNotNull(timestampAssigner, "timestampAssigner");
		this.timestampAssignerSupplier = TimestampAssignerSupplier.of(timestampAssigner);
		return this;
	}

	/**
	 * Build the watermark strategy.
	 */
	public WatermarkStrategy<T> build() {
		WatermarkStrategy<T> strategy = this.baseStrategy;

		if (idleTimeout != null) {
			strategy = new WithIdlenessStrategy<>(strategy, idleTimeout);
		}

		if (timestampAssignerSupplier != null) {
			strategy = new WithTimestampAssigner<>(strategy, timestampAssignerSupplier);
		}

		return strategy;
	}

	// ------------------------------------------------------------------------
	//  builder entry points
	// ------------------------------------------------------------------------

	/**
	 * Starts building a watermark strategy for situations with monotonously ascending
	 * timestamps.
	 *
	 *
The watermarks are generated periodically and tightly follow the latest
	 * timestamp in the data. The delay introduced by this strategy is mainly the periodic
	 * interval in which the watermarks are generated.
	 *
	 * @see AscendingTimestampsWatermarks
	 */
	public static <T> WatermarkStrategies<T> forMonotonousTimestamps() {
		return new WatermarkStrategies<>((ctx) -> new AscendingTimestampsWatermarks<>());
	}

	/**
	 * Starts building a watermark strategy for situations where records are out of order, but
	 * you can place an upper bound on how far the events are out of order.
	 * An out-of-order bound B means that once the an event with timestamp T was encountered, no
	 * events older than {@code T - B} will follow any more.
	 *
	 *
The watermarks are generated periodically. The delay introduced by this watermark strategy
	 * is the periodic interval length, plus the out of orderness bound.
	 *
	 * @see BoundedOutOfOrdernessWatermarks
	 */
	public static <T> WatermarkStrategies<T> forBoundedOutOfOrderness(Duration maxOutOfOrderness) {
		return new WatermarkStrategies<>((ctx) -> new BoundedOutOfOrdernessWatermarks<>(maxOutOfOrderness));
	}

	/**
	 * Starts building a watermark strategy based on an existing {@code WatermarkStrategy}.
	 */
	public static <T> WatermarkStrategies<T> forStrategy(WatermarkStrategy<T> strategy) {
		return new WatermarkStrategies<>(strategy);
	}

	/**
	 * Starts building a watermark strategy based on an existing {@link WatermarkGeneratorSupplier}.
	 */
	public static <T> WatermarkStrategies<T> forGenerator(WatermarkGeneratorSupplier<T> generatorSupplier) {
		return new WatermarkStrategies<>(new FromWatermarkGeneratorSupplier<>(generatorSupplier));
	}

	// ------------------------------------------------------------------------

	private static final class FromWatermarkGeneratorSupplier<T> implements WatermarkStrategy<T> {
		private static final long serialVersionUID = 1L;

		private final WatermarkGeneratorSupplier<T> generatorSupplier;

		private FromWatermarkGeneratorSupplier(WatermarkGeneratorSupplier<T> generatorSupplier) {
			this.generatorSupplier = generatorSupplier;
		}

		@Override
		public WatermarkGenerator<T> createWatermarkGenerator(WatermarkGeneratorSupplier.Context context) {
			return generatorSupplier.createWatermarkGenerator(context);
		}
	}

	/**
	 * A {@link WatermarkStrategy} that overrides the {@link TimestampAssigner} of the given base
	 * {@link WatermarkStrategy}.
	 */
	private static final class WithTimestampAssigner<T> implements WatermarkStrategy<T> {
		private static final long serialVersionUID = 1L;

		private final WatermarkStrategy<T> baseStrategy;
		private final TimestampAssignerSupplier<T> timestampAssigner;

		private WithTimestampAssigner(WatermarkStrategy<T> baseStrategy, TimestampAssignerSupplier<T> timestampAssigner) {
			this.baseStrategy = baseStrategy;
			this.timestampAssigner = timestampAssigner;
		}

		@Override
		public TimestampAssigner<T> createTimestampAssigner(TimestampAssignerSupplier.Context context) {
			return timestampAssigner.createTimestampAssigner(context);
		}

		@Override
		public WatermarkGenerator<T> createWatermarkGenerator(WatermarkGeneratorSupplier.Context context) {
			return baseStrategy.createWatermarkGenerator(context);
		}
	}

	private static final class WithIdlenessStrategy<T> implements WatermarkStrategy<T> {
		private static final long serialVersionUID = 1L;

		private final WatermarkStrategy<T> baseStrategy;
		private final Duration idlenessTimeout;

		private WithIdlenessStrategy(WatermarkStrategy<T> baseStrategy, Duration idlenessTimeout) {
			this.baseStrategy = baseStrategy;
			this.idlenessTimeout = idlenessTimeout;
		}

		@Override
		public TimestampAssigner<T> createTimestampAssigner(TimestampAssignerSupplier.Context context) {
			return baseStrategy.createTimestampAssigner(context);
		}

		@Override
		public WatermarkGenerator<T> createWatermarkGenerator(WatermarkGeneratorSupplier.Context context) {
			return new WatermarksWithIdleness<>(baseStrategy.createWatermarkGenerator(context), idlenessTimeout);
		}
	}
}


text:
require 'rspec/mocks'
require_relative '../../../spec_helper'
require_relative '../../../../app/controllers/carto/api/database_groups_controller'
require_relative '.././../../factories/visualization_creation_helpers'

# cURL samples:
# - Rename group: curl -v -H "Content-Type: application/json" -X PUT -d '{ "display_name": "Demo Group" }' "http://central-org-b-admin.localhost.lan:3000/api/v1/organization/95c2c425-5c8c-4b20-8999-d79cd20c2f2c/groups/c662f7ee-aefb-4f49-93ea-1f671a77bb36?api_key=665646f527c3006b124c15a308bb98f4ed1f52e4"
# - Add users: curl -v -H "Content-Type: application/json" -X POST -d '{ "users" : ["78ee570a-812d-4cce-928c-e5ebeb4708e8", "7e53c96c-1598-43e0-b23e-290daf633547"] }' "http://central-org-b-admin.localhost.lan:3000/api/v1/organization/95c2c425-5c8c-4b20-8999-d79cd20c2f2c/groups/c662f7ee-aefb-4f49-93ea-1f671a77bb36/users?api_key=665646f527c3006b124c15a308bb98f4ed1f52e4"
# - Remove users: curl -v -H "Content-Type: application/json" -X DELETE -d '{ "users" : ["78ee570a-812d-4cce-928c-e5ebeb4708e8", "7e53c96c-1598-43e0-b23e-290daf633547"] }' "http://central-org-b-admin.localhost.lan:3000/api/v1/organization/95c2c425-5c8c-4b20-8999-d79cd20c2f2c/groups/c662f7ee-aefb-4f49-93ea-1f671a77bb36/users?api_key=665646f527c3006b124c15a308bb98f4ed1f52e4"

describe Carto::Api::GroupsController do
  include_context 'organization with users helper'

  shared_examples_for 'Groups editor management' do
    before(:all) do
      @org_user_1_json = {
        "id" => @org_user_1.id,
        "name" => @org_user_1.name,
        "last_name" => @org_user_1.last_name,
        "username" => @org_user_1.username,
        "avatar_url" => @org_user_1.avatar_url,
        "base_url" => @org_user_1.public_url,
        "disqus_shortname" => @org_user_1.disqus_shortname,
        "viewer" => @org_user_1.viewer,
        "org_admin" => false,
        "org_user" => true,
        "remove_logo" => @org_user_1.remove_logo?,
        "google_maps_query_string" => @org_user_1.google_maps_query_string
      }

      @group_1 = FactoryGirl.create(:random_group, display_name: 'g_1', organization: @carto_organization)
      @group_1_json = { 'id' => @group_1.id, 'organization_id' => @group_1.organization_id, 'name' => @group_1.name, 'display_name' => @group_1.display_name }
      @group_2 = FactoryGirl.create(:random_group, display_name: 'g_2', organization: @carto_organization)
      @group_2_json = { 'id' => @group_2.id, 'organization_id' => @group_2.organization_id, 'name' => @group_2.name, 'display_name' => @group_2.display_name }
      @group_3 = FactoryGirl.create(:random_group, display_name: 'g_3', organization: @carto_organization)
      @group_3_json = { 'id' => @group_3.id, 'organization_id' => @group_3.organization_id, 'name' => @group_3.name, 'display_name' => @group_3.display_name }
      @headers = {'CONTENT_TYPE'  => 'application/json', :format => "json" }
    end

    after(:all) do
      @group_1.destroy
      @group_2.destroy
      @group_3.destroy
    end

    before(:each) do
      @carto_organization.reload
    end

    describe '#index' do

      it 'returns 401 without authentication' do
        get_json api_v1_organization_groups_url(user_domain: @admin_user.username, organization_id: @carto_organization.id), {}, @headers do |response|
          response.status.should == 401
        end
      end

      it 'returns groups with pagination metadata' do
        get_json api_v1_organization_groups_url(user_domain: @admin_user.username, organization_id: @carto_organization.id, api_key: @admin_user.api_key), {}, @headers do |response|
          response.status.should == 200
          expected_response = {
            groups: [ @group_1_json, @group_2_json, @group_3_json ],
            total_entries: 3
          }
          response.body.should == expected_response
        end
      end

      it 'returns paginated groups with pagination metadata' do
        get_json api_v1_organization_groups_url(user_domain: @admin_user.username, organization_id: @carto_organization.id, api_key: @admin_user.api_key), { page: 2, per_page: 1, order: 'display_name' }, @headers do |response|
          response.status.should == 200
          expected_response = {
            groups: [ @group_2_json ],
            total_entries: 3
          }
          response.body.should == expected_response
        end
      end

      it 'can search by name' do
        get_json api_v1_organization_groups_url(user_domain: @admin_user.username, organization_id: @carto_organization.id, api_key: @admin_user.api_key, q: @group_2.name), { page: 1, per_page: 1, order: 'display_name' }, @headers do |response|
          response.status.should == 200
          expected_response = {
            groups: [ @group_2_json ],
            total_entries: 1
          }
          response.body.should == expected_response
        end
      end

      describe "users groups" do

        before(:each) do
          @group_1.add_user(@org_user_1.username)
        end

        after(:each) do
          @group_1.remove_user(@org_user_1.username)
        end

        it 'returns user groups if user_id is requested' do
          get_json api_v1_user_groups_url(user_domain: @org_user_1.username, user_id: @org_user_1.id, api_key: @org_user_1.api_key), {}, @headers do |response|
            response.status.should == 200
            expected_response = {
              groups: [ @group_1_json ],
              total_entries: 1
            }
            response.body.should == expected_response
          end
        end

        it 'optionally fetches number of shared tables, maps and users' do
          get_json api_v1_user_groups_url(user_domain: @org_user_1.username, user_id: @org_user_1.id, api_key: @org_user_1.api_key), {}, @headers do |response|
            response.status.should == 200
            expected_response = {
              groups: [
                @group_1_json
              ],
              total_entries: 1
            }
            response.body.should == expected_response
          end

          get_json api_v1_user_groups_url(user_domain: @org_user_1.username, user_id: @org_user_1.id, api_key: @org_user_1.api_key, fetch_shared_tables_count: true, fetch_shared_maps_count: true, fetch_users: true), {}, @headers do |response|
            response.status.should == 200
            expected_response = {
              groups: [
                @group_1_json.merge({
                  'shared_tables_count' => 0,
                  'shared_maps_count' => 0,
                  'users' => [ @org_user_1_json ]
                })
              ],
              total_entries: 1
            }
            response.body.should == expected_response
          end
        end

        it 'can fetch number of shared tables, maps and users when a table is shared' do
          bypass_named_maps
          table_user_2 = create_table_with_options(@org_user_2)
          permission = CartoDB::Permission[Carto::Visualization.find(table_user_2['table_visualization'][:id]).permission.id]
          permission.set_group_permission(@group_1, Carto::Permission::ACCESS_READONLY)
          permission.save

          get_json api_v1_user_groups_url(user_domain: @org_user_1.username, user_id: @org_user_1.id, api_key: @org_user_1.api_key, fetch_shared_tables_count: true, fetch_shared_maps_count: true, fetch_users: true), {}, @headers do |response|
            response.status.should == 200
            expected_response = {
              groups: [
               @group_1_json.merge({
                  'shared_tables_count' => 1,
                  'shared_maps_count' => 0,
                  'users' => [ @org_user_1_json ]
                })
              ],
              total_entries: 1
            }
            response.body.should == expected_response
          end
        end

      end

    end

    it '#show returns a group' do
      get_json api_v1_organization_groups_show_url(user_domain: @admin_user.username, organization_id: @carto_organization.id, group_id: @group_1.id, api_key: @admin_user.api_key), { }, @headers do |response|
        response.status.should == 200
        response.body.should == @group_1_json.symbolize_keys
      end
    end

    it '#show support fetch_shared_maps_count, fetch_shared_tables_count and fetch_users' do
      get_json api_v1_organization_groups_show_url(user_domain: @admin_user.username, organization_id: @carto_organization.id, group_id: @group_1.id, api_key: @admin_user.api_key, fetch_shared_tables_count: true, fetch_shared_maps_count: true, fetch_users: true), { }, @headers do |response|
        response.status.should == 200
        response.body[:shared_tables_count].should_not be_nil
        response.body[:shared_maps_count].should_not be_nil
        response.body[:users].should_not be_nil
      end
    end

    it '#create fails if user is not owner' do
      post_json api_v1_organization_groups_create_url(user_domain: @org_user_1.username, organization_id: @carto_organization.id, api_key: @org_user_1.api_key), { display_name: 'willfail' }, @headers do |response|
        response.status.should == 400
      end
    end

    it '#create triggers group creation' do
      display_name = 'a new group'
      name = 'a new group'

      # Replacement for extension interaction
      fake_database_role = 'fake_database_role'
      fake_group_creation = Carto::Group.new_instance(@carto_organization.database_name, name, fake_database_role)
      fake_group_creation.save
      Carto::Group.expects(:create_group_extension_query).with(anything, name).returns(fake_group_creation)

      post_json api_v1_organization_groups_create_url(user_domain: @admin_user.username, organization_id: @carto_organization.id, api_key: @admin_user.api_key), { display_name: display_name }, @headers do |response|
        response.status.should == 200
        response.body[:id].should_not be_nil
        response.body[:organization_id].should == @carto_organization.id
        response.body[:name].should == name
        response.body[:display_name].should == display_name

        # Also check database data because Group changes something after extension interaction
        new_group = Carto::Group.find(response.body[:id])
        new_group.organization_id.should == @carto_organization.id
        new_group.name.should == name
        new_group.display_name.should == display_name
        new_group.database_role.should_not be_nil
      end
    end

    it '#update triggers group renaming' do
      group = @carto_organization.groups.first
      new_display_name = 'A Group %Renamed'
      expected_new_name = 'A Group _Renamed'

      Carto::Group.expects(:rename_group_extension_query).with(anything, group.name, expected_new_name)

      put_json api_v1_organization_groups_update_url(user_domain: @admin_user.username, organization_id: @carto_organization.id, group_id: group.id, api_key: @admin_user.api_key), { display_name: new_display_name }, @headers do |response|
        response.status.should == 200
        response.body[:id].should_not be_nil
        response.body[:organization_id].should == @carto_organization.id
        # INFO: since test doesn't actually trigger the extension we only check expectation on renaming call and display name
        response.body[:display_name].should == new_display_name
        response.body[:shared_tables_count].should_not be_nil
        response.body[:shared_maps_count].should_not be_nil
        response.body[:users].should_not be_nil

        # Also check database data because Group changes something after extension interaction
        new_group = Carto::Group.find(response.body[:id])
        new_group.organization_id.should == @carto_organization.id
        new_group.display_name.should == new_display_name
        new_group.database_role.should_not be_nil
      end
    end

    it '#update returns 409 and a meaningful error message if there is a group with the same name within the organization' do
      group = @carto_organization.groups[0]
      group_2 = @carto_organization.groups[1]

      Carto::Group.expects(:rename_group_extension_query).with(anything, anything, anything).never

      put_json api_v1_organization_groups_update_url(user_domain: @admin_user.username, organization_id: @carto_organization.id, group_id: group.id, api_key: @admin_user.api_key), { display_name: group_2.display_name }, @headers do |response|
        response.status.should == 409
        response.body[:errors][0].should match /A group with that name already exists/
      end
    end

    it '#add_users triggers group inclusion' do
      group = @carto_organization.groups.first
      user = @org_user_1

      Carto::Group.expects(:add_users_group_extension_query).with(anything, group.name, [user.username])

      post_json api_v1_organization_groups_add_users_url(user_domain: @admin_user.username, organization_id: @carto_organization.id, group_id: group.id, api_key: @admin_user.api_key), { user_id: user.id }, @headers do |response|
        response.status.should == 200
        # INFO: since test doesn't actually trigger the extension we only check expectation on membership call
      end
    end

    it '#remove_users triggers group exclusion' do
      group = @carto_organization.groups.first
      user = @carto_org_user_1
      group.users << user
      group.save
      group.reload
      group.users.include?(user)

      Carto::Group.expects(:remove_users_group_extension_query).with(anything, group.name, [user.username])

      delete_json api_v1_organization_groups_remove_users_url(user_domain: @admin_user.username, organization_id: @carto_organization.id, group_id: group.id, api_key: @admin_user.api_key, user_id: user.id), {}, @headers do |response|
        response.status.should == 200
        # INFO: since test doesn't actually trigger the extension we only check expectation on membership call
      end
    end

    it '#add_users allows batches and triggers group inclusion' do
      group = @carto_organization.groups.first
      user_1 = @org_user_1
      user_2 = @org_user_2

      Carto::Group.expects(:add_users_group_extension_query).with(anything, group.name, [user_1.username, user_2.username])

      post_json api_v1_organization_groups_add_users_url(user_domain: @admin_user.username, organization_id: @carto_organization.id, group_id: group.id, api_key: @admin_user.api_key), { users: [ user_1.id, user_2.id ] }, @headers do |response|
        response.status.should == 200
        # INFO: since test doesn't actually trigger the extension we only check expectation on membership call
      end
    end

    it '#remove_users allows batches and triggers group exclusion' do
      group = @carto_organization.groups.first
      user_1 = @carto_org_user_1
      user_2 = @carto_org_user_2
      group.users << user_2
      group.save
      group.reload
      group.users.include?(user_1)
      group.users.include?(user_2)

      Carto::Group.expects(:remove_users_group_extension_query).with(anything, group.name, [user_1.username, user_2.username])

      delete_json api_v1_organization_groups_remove_users_url(user_domain: @admin_user.username, organization_id: @carto_organization.id, group_id: group.id, api_key: @admin_user.api_key), { users: [ user_1.id, user_2.id ] }, @headers do |response|
        response.status.should == 200
        # INFO: since test doesn't actually trigger the extension we only check expectation on membership call
      end
    end

    it '#drops triggers deletion of existing groups' do
      group = @carto_organization.groups.first

      Carto::Group.expects(:destroy_group_extension_query).with(anything, group.name)

      delete_json api_v1_organization_groups_destroy_url(user_domain: @admin_user.username, organization_id: @carto_organization.id, group_id: group.id, api_key: @admin_user.api_key), { }, @headers do |response|
        response.status.should == 204

        # Extension is simulated, so we delete the group manually
        group.delete
      end
    end

  end

  describe 'with organization owner' do
    it_behaves_like 'Groups editor management' do
      before(:all) do
        @admin_user = @organization.owner
      end
    end
  end

  describe 'with organization admin' do
    it_behaves_like 'Groups editor management' do
      before(:all) do
        @org_user_2.org_admin = true
        @org_user_2.save
        @admin_user = @org_user_2
      end
    end
  end
end


text:
package com.tianyu.jty.wechat.util;

/**
 * Created by xtao on 2015/12/2.
 */
public class Ticket {
    private Integer errcode;
    private String errmsg;
    private String ticket;
    private Integer expires_in;

    public Ticket() {
    }

    public Integer getErrcode() {
        return errcode;
    }

    public void setErrcode(Integer errcode) {
        this.errcode = errcode;
    }

    public String getErrmsg() {
        return errmsg;
    }

    public void setErrmsg(String errmsg) {
        this.errmsg = errmsg;
    }

    public String getTicket() {
        return ticket;
    }

    public void setTicket(String ticket) {
        this.ticket = ticket;
    }

    public Integer getExpires_in() {
        return expires_in;
    }

    public void setExpires_in(Integer expires_in) {
        this.expires_in = expires_in;
    }
}


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports Microsoft.CodeAnalysis.Text
Imports Roslyn.Test.Utilities

Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Expressions
    Public Class AddressOfKeywordRecommenderTests

        <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub NoneInClassDeclaration()
            VerifyRecommendationsMissing(<ClassDeclaration>|</ClassDeclaration>, "AddressOf")
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AddressOfNotInStatement()
            VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "AddressOf")
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AddressOfAfterReturn()
            VerifyRecommendationsContain(<MethodBody>Return |</MethodBody>, "AddressOf")
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AddressOfAfterArgument1()
            VerifyRecommendationsContain(<MethodBody>Foo(|</MethodBody>, "AddressOf")
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AddressOfAfterArgument2()
            VerifyRecommendationsContain(<MethodBody>Foo(bar, |</MethodBody>, "AddressOf")
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AddressOfAfterBinaryExpression()
            VerifyRecommendationsContain(<MethodBody>Foo(bar + |</MethodBody>, "AddressOf")
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AddressOfAfterNot()
            VerifyRecommendationsContain(<MethodBody>Foo(Not |</MethodBody>, "AddressOf")
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AddressOfAfterTypeOf()
            VerifyRecommendationsContain(<MethodBody>If TypeOf |</MethodBody>, "AddressOf")
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AddressOfAfterDoWhile()
            VerifyRecommendationsContain(<MethodBody>Do While |</MethodBody>, "AddressOf")
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AddressOfAfterDoUntil()
            VerifyRecommendationsContain(<MethodBody>Do Until |</MethodBody>, "AddressOf")
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AddressOfAfterLoopWhile()
            VerifyRecommendationsContain(<MethodBody>
Do
Loop While |</MethodBody>, "AddressOf")
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AddressOfAfterLoopUntil()
            VerifyRecommendationsContain(<MethodBody>
Do
Loop Until |</MethodBody>, "AddressOf")
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AddressOfAfterIf()
            VerifyRecommendationsContain(<MethodBody>If |</MethodBody>, "AddressOf")
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AddressOfAfterElseIf()
            VerifyRecommendationsContain(<MethodBody>ElseIf |</MethodBody>, "AddressOf")
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AddressOfAfterElseSpaceIf()
            VerifyRecommendationsContain(<MethodBody>Else If |</MethodBody>, "AddressOf")
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AddressOfAfterError()
            VerifyRecommendationsContain(<MethodBody>Error |</MethodBody>, "AddressOf")
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AddressOfAfterThrow()
            VerifyRecommendationsContain(<MethodBody>Throw |</MethodBody>, "AddressOf")
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AddressOfAfterInitializer()
            VerifyRecommendationsContain(<MethodBody>Dim x = |</MethodBody>, "AddressOf")
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AddressOfAfterArrayInitializerSquiggle()
            VerifyRecommendationsContain(<MethodBody>Dim x = {|</MethodBody>, "AddressOf")
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AddressOfAfterArrayInitializerComma()
            VerifyRecommendationsContain(<MethodBody>Dim x = {0, |</MethodBody>, "AddressOf")
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AddressOfInAddHandler()
            VerifyRecommendationsContain(<MethodBody>AddHandler foo, |</MethodBody>, "AddressOf")
        End Sub

        <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AddressOfInRemoveHandler()
            VerifyRecommendationsContain(<MethodBody>RemoveHandler foo, |</MethodBody>, "AddressOf")
        End Sub

        <WorkItem(543270)>
        <WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AddressOfInDelegateCreation()
            Dim code = <ModuleDeclaration><![CDATA[
Module Program
    Sub Main(args As String())
        Dim f1 As New Foo2( |
    End Sub

    Delegate Sub Foo2()

    Function Bar2() As Object
        Return Nothing
    End Function
End Module
]]></ModuleDeclaration>
            VerifyRecommendationsContain(code, "AddressOf")
        End Sub

        <WpfFact>
        <WorkItem(545206)>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AddressOfNotAfterAddressOf()
            Dim code = <ModuleDeclaration><![CDATA[
Sub Main(args As String())
    Dim d As Func(Of Boolean) = AddressOf |
End Sub
Function Foo() As Boolean
    Return True
End Function
]]></ModuleDeclaration>
            VerifyRecommendationsMissing(code, "AddressOf")
        End Sub

        <WpfFact>
        <WorkItem(545206)>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AddressOfNotAfterAddressOfInDelegateCreation()
            Dim code = <ModuleDeclaration><![CDATA[
Sub Main(args As String())
    Dim d As New Foo(AddressOf |
End Sub
Delegate Sub Foo()
]]></ModuleDeclaration>
            VerifyRecommendationsMissing(code, "AddressOf")
        End Sub

        <WpfFact>
        <WorkItem(545206)>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub AddressOfNestedInsideAddressOfExpression()
            Dim code = <ModuleDeclaration><![CDATA[
Class C
    Sub M(args As String())
        Dim x As Action = AddressOf Foo2(|
    End Sub

    Sub Foo()
    End Sub

    Function Foo2(a As Action) As C
        Return New C()
    End Function
End Class
]]></ModuleDeclaration>
            VerifyRecommendationsContain(code, "AddressOf")
        End Sub
    End Class
End Namespace


text:
<?php

namespace backend\models\search;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Products;

/**
 * ProductSearch represents the model behind the search form about `common\models\Products`.
 */
class ProductSearch extends Products
{
    /**
     * @inheritdoc
     */
    public $price;
    public $add_price;

    public function rules()
    {
        return [
            [['id', 'brand_id', 'bulk_id', 'author_id', 'updater_id', 'created_at', 'updated_at', 'status', 'is_available', 'is_new', 'is_action'], 'integer'],
            [['price'],  'number'],
            [['add_price'],'string'],
            [['product_code', 'gender', 'product_name', 'description'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Products::find()->with(['price'])->where(['status'=>1]);

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'brand_id' => $this->brand_id,
            'bulk_id' => $this->bulk_id,
            'author_id' => $this->author_id,
            'price' => $this->price,
            'updater_id' => $this->updater_id,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
            'status' => $this->status,
            'is_available' => $this->is_available,
            'is_new' => $this->is_new,
            'is_action' => $this->is_action,
        ]);

        $query->andFilterWhere(['like', 'product_code', $this->product_code])
            ->andFilterWhere(['like', 'gender', $this->gender])
            ->andFilterWhere(['like', 'product_name', $this->product_name])
            ->andFilterWhere(['like', 'description', $this->description]);

        return $dataProvider;
    }
}


text:
if Rails.env.production?
  Home::Application.config.session_store :cookie_store, :key => 'quantifiedawesome', :domain => '.quantifiedawesome.com'
else
  Home::Application.config.session_store :cookie_store, :key => 'quantifiedawesome', :domain => :all
end
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rails generate session_migration")
# Home::Application.config.session_store :active_record_store