text:
using System;
using Amqp;

namespace Test.Amqp
{
    /// <summary>
    /// For self tests that create AMQP connections to a broker
    /// define the URI of the broker and the name of the queue to use.
    ///
    /// The default broker on localhost may be overridden with
    /// environment variable AMQPNETLITE_TESTTARGET. A single URI
    /// specifies both the broker (scheme, user, password, host, porte
    /// and source or target (path) of the broker resource to be
    /// exercised by the self tests.
    /// </summary>
    public class TestTarget
    {
        internal const string envVarName = "AMQPNETLITE_TESTTARGET";
        internal const string defaultAddress = "amqp://guest:guest@localhost:5672/q1";
        internal string address;
        internal string path;

        public TestTarget()
        {
#if !COMPACT_FRAMEWORK && !NETFX_CORE && !NETMF
            this.address = Environment.GetEnvironmentVariable(envVarName);
#endif
            if (this.address == null)
            {
                this.address = defaultAddress;
            }

            // Verify that the URI is well formed.
            Address addr = new Address(this.address);
            // Extract the path without the leading "/".
            path = addr.Path.Substring(1);
        }

        public string Path
        {
            get
            {
                return path;
            }
        }

        public Address Address
        {
            get
            {
                return new Address(address);
            }
        }
    }
}


text:
'use strict';

let React;
let ReactFabric;
let ReactNative;
let UIManager;
let createReactNativeComponentClass;
let ReactNativePrivateInterface;

describe('created with ReactFabric called with ReactNative', () => {
  beforeEach(() => {
    jest.resetModules();
    require('react-native/Libraries/ReactPrivate/InitializeNativeFabricUIManager');
    ReactNative = require('react-native-renderer');
    jest.resetModules();
    ReactNativePrivateInterface = require('react-native/Libraries/ReactPrivate/ReactNativePrivateInterface');
    UIManager = require('react-native/Libraries/ReactPrivate/ReactNativePrivateInterface')
      .UIManager;
    jest.mock('shared/ReactFeatureFlags', () =>
      require('shared/forks/ReactFeatureFlags.native-oss'),
    );

    React = require('react');
    ReactFabric = require('react-native-renderer/fabric');
    createReactNativeComponentClass = require('react-native/Libraries/ReactPrivate/ReactNativePrivateInterface')
      .ReactNativeViewConfigRegistry.register;
  });

  it('find Fabric instances with the RN renderer', () => {
    const View = createReactNativeComponentClass('RCTView', () => ({
      validAttributes: {title: true},
      uiViewClassName: 'RCTView',
    }));

    const ref = React.createRef();

    class Component extends React.Component {
      render() {
        return <View title="foo" />;
      }
    }

    ReactFabric.render(<Component ref={ref} />, 11);

    const instance = ReactNative.findHostInstance_DEPRECATED(ref.current);
    expect(instance._nativeTag).toBe(2);
  });

  it('find Fabric nodes with the RN renderer', () => {
    const View = createReactNativeComponentClass('RCTView', () => ({
      validAttributes: {title: true},
      uiViewClassName: 'RCTView',
    }));

    const ref = React.createRef();

    class Component extends React.Component {
      render() {
        return <View title="foo" />;
      }
    }

    ReactFabric.render(<Component ref={ref} />, 11);

    const handle = ReactNative.findNodeHandle(ref.current);
    expect(handle).toBe(2);
  });

  it('dispatches commands on Fabric nodes with the RN renderer', () => {
    nativeFabricUIManager.dispatchCommand.mockClear();
    const View = createReactNativeComponentClass('RCTView', () => ({
      validAttributes: {title: true},
      uiViewClassName: 'RCTView',
    }));

    const ref = React.createRef();

    ReactFabric.render(<View title="bar" ref={ref} />, 11);
    expect(nativeFabricUIManager.dispatchCommand).not.toBeCalled();
    ReactNative.dispatchCommand(ref.current, 'myCommand', [10, 20]);
    expect(nativeFabricUIManager.dispatchCommand).toHaveBeenCalledTimes(1);
    expect(
      nativeFabricUIManager.dispatchCommand,
    ).toHaveBeenCalledWith(expect.any(Object), 'myCommand', [10, 20]);
    expect(UIManager.dispatchViewManagerCommand).not.toBeCalled();
  });

  it('dispatches sendAccessibilityEvent on Fabric nodes with the RN renderer', () => {
    nativeFabricUIManager.sendAccessibilityEvent.mockClear();
    const View = createReactNativeComponentClass('RCTView', () => ({
      validAttributes: {title: true},
      uiViewClassName: 'RCTView',
    }));

    const ref = React.createRef();

    ReactFabric.render(<View title="bar" ref={ref} />, 11);
    expect(nativeFabricUIManager.sendAccessibilityEvent).not.toBeCalled();
    ReactNative.sendAccessibilityEvent(ref.current, 'focus');
    expect(nativeFabricUIManager.sendAccessibilityEvent).toHaveBeenCalledTimes(
      1,
    );
    expect(nativeFabricUIManager.sendAccessibilityEvent).toHaveBeenCalledWith(
      expect.any(Object),
      'focus',
    );
    expect(UIManager.sendAccessibilityEvent).not.toBeCalled();
  });
});

describe('created with ReactNative called with ReactFabric', () => {
  beforeEach(() => {
    jest.resetModules();
    require('react-native/Libraries/ReactPrivate/InitializeNativeFabricUIManager');
    ReactFabric = require('react-native-renderer/fabric');
    jest.resetModules();
    UIManager = require('react-native/Libraries/ReactPrivate/ReactNativePrivateInterface')
      .UIManager;
    jest.mock('shared/ReactFeatureFlags', () =>
      require('shared/forks/ReactFeatureFlags.native-oss'),
    );
    ReactNative = require('react-native-renderer');

    React = require('react');
    createReactNativeComponentClass = require('react-native/Libraries/ReactPrivate/ReactNativePrivateInterface')
      .ReactNativeViewConfigRegistry.register;
  });

  it('find Paper instances with the Fabric renderer', () => {
    const View = createReactNativeComponentClass('RCTView', () => ({
      validAttributes: {title: true},
      uiViewClassName: 'RCTView',
    }));

    const ref = React.createRef();

    class Component extends React.Component {
      render() {
        return <View title="foo" />;
      }
    }

    ReactNative.render(<Component ref={ref} />, 11);

    const instance = ReactFabric.findHostInstance_DEPRECATED(ref.current);
    expect(instance._nativeTag).toBe(3);
  });

  it('find Paper nodes with the Fabric renderer', () => {
    const View = createReactNativeComponentClass('RCTView', () => ({
      validAttributes: {title: true},
      uiViewClassName: 'RCTView',
    }));

    const ref = React.createRef();

    class Component extends React.Component {
      render() {
        return <View title="foo" />;
      }
    }

    ReactNative.render(<Component ref={ref} />, 11);

    const handle = ReactFabric.findNodeHandle(ref.current);
    expect(handle).toBe(3);
  });

  it('dispatches commands on Paper nodes with the Fabric renderer', () => {
    UIManager.dispatchViewManagerCommand.mockReset();
    const View = createReactNativeComponentClass('RCTView', () => ({
      validAttributes: {title: true},
      uiViewClassName: 'RCTView',
    }));

    const ref = React.createRef();

    ReactNative.render(<View title="bar" ref={ref} />, 11);
    expect(UIManager.dispatchViewManagerCommand).not.toBeCalled();
    ReactFabric.dispatchCommand(ref.current, 'myCommand', [10, 20]);
    expect(UIManager.dispatchViewManagerCommand).toHaveBeenCalledTimes(1);
    expect(
      UIManager.dispatchViewManagerCommand,
    ).toHaveBeenCalledWith(expect.any(Number), 'myCommand', [10, 20]);

    expect(nativeFabricUIManager.dispatchCommand).not.toBeCalled();
  });

  it('dispatches sendAccessibilityEvent on Paper nodes with the Fabric renderer', () => {
    ReactNativePrivateInterface.legacySendAccessibilityEvent.mockReset();
    const View = createReactNativeComponentClass('RCTView', () => ({
      validAttributes: {title: true},
      uiViewClassName: 'RCTView',
    }));

    const ref = React.createRef();

    ReactNative.render(<View title="bar" ref={ref} />, 11);
    expect(
      ReactNativePrivateInterface.legacySendAccessibilityEvent,
    ).not.toBeCalled();
    ReactFabric.sendAccessibilityEvent(ref.current, 'focus');
    expect(
      ReactNativePrivateInterface.legacySendAccessibilityEvent,
    ).toHaveBeenCalledTimes(1);
    expect(
      ReactNativePrivateInterface.legacySendAccessibilityEvent,
    ).toHaveBeenCalledWith(expect.any(Number), 'focus');

    expect(nativeFabricUIManager.sendAccessibilityEvent).not.toBeCalled();
  });
});

redpajama_set_name: RedPajamaGithub


text:
package forklift.integration;

import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertTrue;
import com.github.dcshock.avro.schemas.AvroMessage;
import forklift.Forklift;
import forklift.connectors.ConnectorException;
import forklift.connectors.ForkliftConnectorI;
import forklift.consumer.Consumer;
import forklift.decorators.MultiThreaded;
import forklift.decorators.OnMessage;
import forklift.decorators.Producer;
import forklift.decorators.Queue;
import forklift.exception.StartupException;
import forklift.integration.server.TestServiceManager;
import forklift.producers.ForkliftProducerI;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class RebalanceTests {

    private static final Logger log = LoggerFactory.getLogger(RebalanceTests.class);
    private static AtomicInteger called = new AtomicInteger(0);
    private static AtomicInteger messagesSent = new AtomicInteger(0);
    private static boolean isInjectNull = true;
    TestServiceManager serviceManager;

    @After
    public void after() {
        serviceManager.stop();
    }

    @Before
    public void setup() {
        serviceManager = new TestServiceManager();
        serviceManager.start();
        called.set(0);
        messagesSent.set(0);
        isInjectNull = true;
    }

    private class ForkliftServer{

        private ExecutorService executor;
        private Class[] consumerClasses;
        private Forklift forklift;
        private List<Consumer> consumers = new ArrayList<Consumer>();
        private String name;
        private volatile boolean running = false;

        public ForkliftServer(String name, ExecutorService executor, Class<?>... consumerClasses){
            this.name = name;
            this.executor = executor;
            this.consumerClasses = consumerClasses;
            try {
                this.forklift = serviceManager.newManagedForkliftInstance(name);
            } catch (StartupException e) {
               log.error("Error constructing forklift server");
            }
        }

        public ForkliftProducerI getProducer(String topicName){
            return forklift.getConnector().getTopicProducer(topicName);
        }

        public void startConsumers(){
            log.info("Starting Consumers for server: " + name);
            for (Class<?> c : consumerClasses) {
                Consumer consumer = new Consumer(c, forklift.getConnector());
                consumers.add(consumer);
                executor.submit(() -> consumer.listen());
            }
        }

        public void startProducers(){

            ForkliftProducerI producer1 = getProducer("forklift-string-topic");
            ForkliftProducerI producer2 = getProducer("forklift-map-topic");
            ForkliftProducerI producer3 = getProducer("forklift-object-topic");
            Random random = new Random();
            running = true;
            executor.execute(() -> {
                while (running) {
                    long jitter = random.nextLong() % 50;
                    try {
                        producer1.send("String message");
                        messagesSent.incrementAndGet();
                        Thread.currentThread().sleep(jitter);
                    } catch (Exception e) {
                    }
                }
            });
            executor.execute(() -> {
                while (running) {
                    long jitter = random.nextLong() % 50;
                    try {
                        final Map<String, String> m = new HashMap<>();
                        m.put("x", "producer key value send test");
                        producer2.send(m);
                        messagesSent.incrementAndGet();
                        Thread.currentThread().sleep(jitter);
                    } catch (Exception e) {
                    }
                }
            });
            executor.execute(() -> {
                while (running) {
                    long jitter = random.nextLong() % 50;
                    try {
                        final TestMessage m = new TestMessage(new String("x=producer object send test"), 1);
                        producer3.send(m);
                        messagesSent.incrementAndGet();
                        Thread.currentThread().sleep(jitter);
                    } catch (Exception e) {
                    }
                }
            });
        }

        public void stopProducers(){
            running = false;
        }

        public void shutdown(){
            stopProducers();
            log.info("Stopping Consumers for server: " + name);
            consumers.forEach(consumer -> consumer.shutdown());
            forklift.shutdown();
        }
    }

    @Test
    public void testRebalanceUnderLoad() throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(35);
        ForkliftServer server1 = new ForkliftServer("Server1", executor, StringConsumer.class, ForkliftMapConsumer.class, ForkliftObjectConsumer.class);
        ForkliftServer server2 = new ForkliftServer("Server2", executor, StringConsumer.class, ForkliftMapConsumer.class, ForkliftObjectConsumer.class);
        ForkliftServer server3 = new ForkliftServer("Server3", executor, StringConsumer.class, ForkliftMapConsumer.class, ForkliftObjectConsumer.class);
        ForkliftServer server4 = new ForkliftServer("Server4", executor, StringConsumer.class, ForkliftMapConsumer.class, ForkliftObjectConsumer.class);
        ForkliftServer server5 = new ForkliftServer("Server5", executor, StringConsumer.class, ForkliftMapConsumer.class, ForkliftObjectConsumer.class);
        ForkliftServer server6 = new ForkliftServer("Server6", executor, StringConsumer.class, ForkliftMapConsumer.class, ForkliftObjectConsumer.class);
        ForkliftServer server7 = new ForkliftServer("Server7", executor, StringConsumer.class, ForkliftMapConsumer.class, ForkliftObjectConsumer.class);

        server4.startProducers();
        server5.startProducers();
        server6.startProducers();
        server7.startProducers();
        Thread.sleep(2000);
        server1.startConsumers();
        server2.startConsumers();
        Thread.sleep(10000);
        server1.shutdown();
        Thread.sleep(5000);
        server3.startConsumers();
        Thread.sleep(5000);
        server2.shutdown();

        server4.stopProducers();
        server5.stopProducers();
        server6.stopProducers();
        server7.stopProducers();
        log.info("Messages sent: " + messagesSent.get());
        //wait to finish any processing
        for(int i = 0; i < 60 && called.get() != messagesSent.get(); i++){
            log.info("Waiting: " + i);
            Thread.sleep(1000);
        }
        server3.shutdown();
        assertEquals(messagesSent.get(), called.get());
        assertTrue(messagesSent.get() > 0);

    }

    @Test
    public void testMultipleConcurrentRebalancing() throws StartupException, InterruptedException, ConnectorException {

        ExecutorService executor = Executors.newFixedThreadPool(35);

        ForkliftServer server1 = new ForkliftServer("Server1", executor, StringConsumer.class, ForkliftMapConsumer.class, ForkliftObjectConsumer.class);
        ForkliftServer server2 = new ForkliftServer("Server2", executor, StringConsumer.class, ForkliftMapConsumer.class, ForkliftObjectConsumer.class);
        ForkliftServer server3 = new ForkliftServer("Server3", executor, StringConsumer.class, ForkliftMapConsumer.class, ForkliftObjectConsumer.class);
        ForkliftServer server4 = new ForkliftServer("Server4", executor, StringConsumer.class, ForkliftMapConsumer.class, ForkliftObjectConsumer.class);
        ForkliftServer server5 = new ForkliftServer("Server5", executor, StringConsumer.class, ForkliftMapConsumer.class, ForkliftObjectConsumer.class);
        ForkliftServer server6 = new ForkliftServer("Server6", executor, StringConsumer.class, ForkliftMapConsumer.class, ForkliftObjectConsumer.class);
        ForkliftServer server7 = new ForkliftServer("Server7", executor, StringConsumer.class, ForkliftMapConsumer.class, ForkliftObjectConsumer.class);
        ForkliftServer server8 = new ForkliftServer("Server8", executor, StringConsumer.class, ForkliftMapConsumer.class, ForkliftObjectConsumer.class);
        ForkliftServer server9 = new ForkliftServer("Server9", executor, StringConsumer.class, ForkliftMapConsumer.class, ForkliftObjectConsumer.class);
        ForkliftServer server10 = new ForkliftServer("Server10", executor, StringConsumer.class, ForkliftMapConsumer.class, ForkliftObjectConsumer.class);

        server10.startProducers();
        Thread.sleep(500);
        server1.startConsumers();
        server2.startConsumers();
        server3.startConsumers();
        server4.startConsumers();
        server5.startConsumers();
        server6.startConsumers();
        server7.startConsumers();
        server8.startConsumers();
        server9.startConsumers();
        server10.startConsumers();
        Thread.sleep(5000);

        server1.shutdown();
        server2.shutdown();
        server3.shutdown();
        Thread.sleep(5000);
        server4.shutdown();
        server5.shutdown();
        server6.shutdown();
        Thread.sleep(5000);
        server7.shutdown();
        server8.shutdown();
        server9.shutdown();

        server10.stopProducers();
        //wait to finish any processing
        for(int i = 0; i < 60 && called.get() != messagesSent.get(); i++){
            log.info("Waiting: " + i);
            Thread.sleep(1000);
        }
        log.info("Messages sent: " + messagesSent.get());
        server10.shutdown();
        assertEquals(messagesSent.get(), called.get());
        assertTrue(messagesSent.get() > 0);
    }

    private List<Consumer> setupConsumers(ForkliftConnectorI connector, Class<?>... consumersClasses) {
        List<Consumer> consumers = new ArrayList<>();
        for (Class<?> c : consumersClasses) {
            Consumer consumer = new Consumer(c, connector);
            consumers.add(consumer);
        }
        return consumers;
    }

    @Queue("forklift-string-topic")
    public static class StringConsumer {

        @forklift.decorators.Message
        private String value;

        @Producer(queue = "forklift-string-topic")
        private ForkliftProducerI injectedProducer;

        @OnMessage
        public void onMessage() {
            if (value == null) {
                return;
            }
            int i = called.getAndIncrement();
            isInjectNull = injectedProducer != null ? false : true;
        }
    }

    @Queue("forklift-avro-topic")
    public static class ForkliftAvroConsumer {

        @forklift.decorators.Message
        private AvroMessage value;

        @Producer(queue = "forklift-avro-topic")
        private ForkliftProducerI injectedProducer;

        @OnMessage
        public void onMessage() {
            if (value == null) {
                return;
            }
            int i = called.getAndIncrement();
            isInjectNull = injectedProducer != null ? false : true;
        }
    }

    @MultiThreaded(10)
    @Queue("forklift-string-topic")
    public static class MultiThreadedStringConsumer {

        @forklift.decorators.Message
        private String value;

        @Producer(queue = "forklift-string-topic")
        private ForkliftProducerI injectedProducer;

        @OnMessage
        public void onMessage() {
            if (value == null) {
                return;
            }
            int i = called.getAndIncrement();
            isInjectNull = injectedProducer != null ? false : true;
        }
    }

    @Queue("forklift-map-topic")
    public static class ForkliftMapConsumer {

        @forklift.decorators.Message
        private Map<String, String> mapMessage;

        @Producer(queue = "forklift-string-topic")
        private ForkliftProducerI injectedProducer;

        @OnMessage
        public void onMessage() {
            if (mapMessage == null || mapMessage.size() == 0) {
                return;
            }
            int i = called.getAndIncrement();
            isInjectNull = injectedProducer != null ? false : true;
        }
    }

    @Queue("forklift-object-topic")
    public static class ForkliftObjectConsumer {

        @forklift.decorators.Message
        private TestMessage testMessage;

        @Producer(queue = "forklift-string-topic")
        private ForkliftProducerI injectedProducer;

        @OnMessage
        public void onMessage() {
            if (testMessage == null || testMessage.getText() == null) {
                return;
            }
            int i = called.getAndIncrement();
            isInjectNull = injectedProducer != null ? false : true;
        }
    }

}


text:
package org.mifos.application.accounts.financial.business.service;

import java.sql.Date;
import java.util.Set;

import junit.framework.Assert;

import org.mifos.application.accounts.business.AccountActionDateEntity;
import org.mifos.application.accounts.business.AccountActionEntity;
import org.mifos.application.accounts.business.AccountFeesActionDetailEntity;
import org.mifos.application.accounts.business.AccountPaymentEntity;
import org.mifos.application.accounts.business.AccountTestUtils;
import org.mifos.application.accounts.business.AccountTrxnEntity;
import org.mifos.application.accounts.business.FeesTrxnDetailEntity;
import org.mifos.application.accounts.financial.business.FinancialTransactionBO;
import org.mifos.application.accounts.financial.util.helpers.FinancialActionConstants;
import org.mifos.application.accounts.loan.business.LoanBO;
import org.mifos.application.accounts.loan.business.LoanBOTestUtils;
import org.mifos.application.accounts.loan.business.LoanScheduleEntity;
import org.mifos.application.accounts.loan.business.LoanTrxnDetailEntity;
import org.mifos.application.accounts.savings.business.SavingsBO;
import org.mifos.application.accounts.savings.business.SavingBOTestUtils;
import org.mifos.application.accounts.savings.business.SavingsTrxnDetailEntity;
import org.mifos.application.accounts.savings.persistence.SavingsPersistence;
import org.mifos.application.accounts.savings.util.helpers.SavingsTestHelper;
import org.mifos.application.accounts.util.helpers.AccountActionTypes;
import org.mifos.application.accounts.util.helpers.AccountState;
import org.mifos.application.accounts.util.helpers.AccountStateFlag;
import org.mifos.application.accounts.util.helpers.AccountStates;
import org.mifos.application.customer.business.CustomerBO;
import org.mifos.application.customer.util.helpers.CustomerStatus;
import org.mifos.application.master.business.PaymentTypeEntity;
import org.mifos.application.master.persistence.MasterPersistence;
import org.mifos.application.meeting.business.MeetingBO;
import org.mifos.application.personnel.business.PersonnelBO;
import org.mifos.application.personnel.persistence.PersonnelPersistence;
import org.mifos.application.personnel.util.helpers.PersonnelConstants;
import org.mifos.application.productdefinition.business.LoanOfferingBO;
import org.mifos.application.productdefinition.business.SavingsOfferingBO;
import org.mifos.framework.MifosIntegrationTestCase;
import org.mifos.framework.TestUtils;
import org.mifos.framework.components.configuration.business.Configuration;
import org.mifos.framework.exceptions.ApplicationException;
import org.mifos.framework.exceptions.SystemException;
import org.mifos.framework.hibernate.helper.StaticHibernateUtil;
import org.mifos.framework.persistence.TestDatabase;
import org.mifos.framework.security.util.UserContext;
import org.mifos.framework.util.helpers.Money;
import org.mifos.framework.util.helpers.TestObjectFactory;

public class FinancialBusinessServiceIntegrationTest extends MifosIntegrationTestCase {
    public FinancialBusinessServiceIntegrationTest() throws SystemException, ApplicationException {
        super();
    }

    private static final double DELTA = 0.00000001;

    protected LoanBO loan = null;

    protected SavingsBO savings;

    protected SavingsOfferingBO savingsOffering;

    protected CustomerBO center = null;

    private CustomerBO group = null;

    private UserContext userContext;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        userContext = TestUtils.makeUser();
    }

    @Override
    protected void tearDown() throws Exception {
        try {
            TestObjectFactory.cleanUp(loan);
            TestObjectFactory.cleanUp(savings);
            TestObjectFactory.cleanUp(group);
            TestObjectFactory.cleanUp(center);
        } catch (Exception e) {
            // TODO Whoops, cleanup didnt work, reset db
            TestDatabase.resetMySQLDatabase();
        }
        StaticHibernateUtil.closeSession();
        super.tearDown();
    }

    public void testLoanAdjustmentAccountingEntries() throws Exception {
        Date currentDate = new Date(System.currentTimeMillis());
        loan = getLoanAccount();
        loan.setUserContext(TestUtils.makeUser());
        AccountPaymentEntity accountPaymentEntity = new AccountPaymentEntity(loan, TestObjectFactory
                .getMoneyForMFICurrency(630), "1111", currentDate, new PaymentTypeEntity(Short.valueOf("1")), new Date(
                System.currentTimeMillis()));
        FinancialBusinessService financialBusinessService = new FinancialBusinessService();
        AccountTrxnEntity accountTrxnEntity = getAccountTrxnObj(accountPaymentEntity);
        accountPaymentEntity.addAccountTrxn(accountTrxnEntity);
        AccountTestUtils.addAccountPayment(accountPaymentEntity, loan);

        financialBusinessService.buildAccountingEntries(accountTrxnEntity);

        TestObjectFactory.updateObject(loan);
       Assert.assertEquals(accountTrxnEntity.getFinancialTransactions().size(), 10);

        int countNegativeFinTrxn = 0;
        for (FinancialTransactionBO finTrxn : accountTrxnEntity.getFinancialTransactions()) {
            if (finTrxn.getPostedAmount().getAmountDoubleValue() < 0)
                countNegativeFinTrxn++;
            else
               Assert.assertEquals("Positive finTrxn values", finTrxn.getPostedAmount().getAmountDoubleValue(), 200.0);
        }
       Assert.assertEquals("Negative finTrxn values count", countNegativeFinTrxn, 9);
       Assert.assertEquals("Positive finTrxn values count", accountTrxnEntity.getFinancialTransactions().size()
                - countNegativeFinTrxn, 1);
    }

    private AccountTrxnEntity getAccountTrxnObj(AccountPaymentEntity accountPaymentEntity) throws Exception {
        MasterPersistence masterPersistenceService = new MasterPersistence();
        Date currentDate = new Date(System.currentTimeMillis());

        LoanScheduleEntity accountAction = (LoanScheduleEntity) loan.getAccountActionDate(Short.valueOf("1"));

        LoanTrxnDetailEntity accountTrxnEntity = new LoanTrxnDetailEntity(accountPaymentEntity,
                AccountActionTypes.LOAN_ADJUSTMENT, Short.valueOf("1"), accountAction
                        .getActionDate(), TestObjectFactory.getPersonnel(PersonnelConstants.SYSTEM_USER), currentDate,
                TestObjectFactory.getMoneyForMFICurrency(630), "test for loan adjustment", null, TestObjectFactory
                        .getMoneyForMFICurrency(200), TestObjectFactory.getMoneyForMFICurrency(300), new Money(),
                TestObjectFactory.getMoneyForMFICurrency(10), TestObjectFactory.getMoneyForMFICurrency(20), null,
                masterPersistenceService);

        for (AccountFeesActionDetailEntity accountFeesActionDetailEntity : accountAction.getAccountFeesActionDetails()) {
            LoanBOTestUtils.setFeeAmountPaid(accountFeesActionDetailEntity, TestObjectFactory
                    .getMoneyForMFICurrency(100));
            FeesTrxnDetailEntity feeTrxn = new FeesTrxnDetailEntity(accountTrxnEntity, accountFeesActionDetailEntity
                    .getAccountFee(), accountFeesActionDetailEntity.getFeeAmount());
            accountTrxnEntity.addFeesTrxnDetail(feeTrxn);
        }

        return accountTrxnEntity;
    }

    private LoanBO getLoanAccount() {
        Date startDate = new Date(System.currentTimeMillis());
        MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
        center = TestObjectFactory.createCenter(this.getClass().getSimpleName() + " Center", meeting);
        group = TestObjectFactory.createGroupUnderCenter(this.getClass().getSimpleName() + " Group", CustomerStatus.GROUP_ACTIVE, center);
        LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(this.getClass().getSimpleName() + "","FL",startDate, meeting);
        return TestObjectFactory.createLoanAccount("42423142341", group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING,
                startDate, loanOffering);
    }

    public void testSavingsAdjustmentDepositAccountingEntries() throws Exception {
        createInitialObjectsForSavings();
        SavingsTestHelper helper = new SavingsTestHelper();
        SavingsPersistence savingsPersistence = new SavingsPersistence();

        PersonnelBO createdBy = new PersonnelPersistence().getPersonnel(userContext.getId());
        Money depositAmount = new Money(Configuration.getInstance().getSystemConfig().getCurrency(), "1000.0");
        Money balanceAmount = new Money(Configuration.getInstance().getSystemConfig().getCurrency(), "5000.0");
        java.util.Date trxnDate = helper.getDate("20/05/2006");

        AccountPaymentEntity payment = helper.createAccountPaymentToPersist(savings, depositAmount, balanceAmount,
                trxnDate, AccountActionTypes.SAVINGS_DEPOSIT.getValue(), savings, createdBy, group);
        AccountTestUtils.addAccountPayment(payment, savings);

        SavingBOTestUtils.setBalance(savings, balanceAmount);
        savings.update();
        StaticHibernateUtil.commitTransaction();
        StaticHibernateUtil.closeSession();

        savings = savingsPersistence.findById(savings.getAccountId());
        savings.setUserContext(userContext);
        payment = savings.getLastPmnt();
        balanceAmount = new Money(Configuration.getInstance().getSystemConfig().getCurrency(), "4000.0");
        AccountTrxnEntity accountTrxn = helper.createAccountTrxn(payment, depositAmount.negate(), balanceAmount,
                trxnDate, trxnDate, AccountActionTypes.SAVINGS_ADJUSTMENT.getValue(), savings, createdBy, group, "",
                null);
        payment.addAccountTrxn(accountTrxn);
        SavingBOTestUtils.setBalance(savings, balanceAmount);

        FinancialBusinessService financialBusinessService = new FinancialBusinessService();
        financialBusinessService.buildAccountingEntries(accountTrxn);
        savings.update();
        StaticHibernateUtil.commitTransaction();
        StaticHibernateUtil.closeSession();

        savings = savingsPersistence.findById(savings.getAccountId());
        savings.setUserContext(userContext);
        payment = savings.getLastPmnt();
       Assert.assertEquals(Integer.valueOf(2).intValue(), payment.getAccountTrxns().size());
        for (AccountTrxnEntity trxn : payment.getAccountTrxns()) {
            if (trxn.getAccountActionEntity().getId().equals(AccountActionTypes.SAVINGS_ADJUSTMENT.getValue())) {
               Assert.assertTrue(true);
               Assert.assertEquals(Integer.valueOf(2).intValue(), trxn.getFinancialTransactions().size());
                int countNegativeFinTrxn = 0;
                for (FinancialTransactionBO finTrxn : trxn.getFinancialTransactions()) {
                    if (finTrxn.getPostedAmount().getAmountDoubleValue() < 0) {
                        countNegativeFinTrxn++;
                       Assert.assertEquals(1000.0, finTrxn.getPostedAmount().negate().getAmountDoubleValue(), DELTA);
                    } else
                       Assert.assertTrue(false);
                }

               Assert.assertEquals("Negative finTrxn values count", 2, countNegativeFinTrxn);
               Assert.assertEquals("Positive finTrxn values count", 0, accountTrxn.getFinancialTransactions().size()
                        - countNegativeFinTrxn);
            }
        }
        group = savings.getCustomer();
        center = group.getParentCustomer();
    }

    public void testSavingsAdjustmentWithdrawalAccountingEntries() throws Exception {
        createInitialObjectsForSavings();
        SavingsTestHelper helper = new SavingsTestHelper();
        SavingsPersistence savingsPersistence = new SavingsPersistence();

        PersonnelBO createdBy = new PersonnelPersistence().getPersonnel(userContext.getId());
        Money withdrawalAmount = new Money(Configuration.getInstance().getSystemConfig().getCurrency(), "1000.0");
        Money balanceAmount = new Money(Configuration.getInstance().getSystemConfig().getCurrency(), "5000.0");
        java.util.Date trxnDate = helper.getDate("20/05/2006");

        AccountPaymentEntity payment = helper.createAccountPaymentToPersist(savings, withdrawalAmount, balanceAmount,
                trxnDate, AccountActionTypes.SAVINGS_WITHDRAWAL.getValue(), savings, createdBy, group);
        AccountTestUtils.addAccountPayment(payment, savings);
        SavingBOTestUtils.setBalance(savings, balanceAmount);
        savings.update();
        StaticHibernateUtil.commitTransaction();
        StaticHibernateUtil.closeSession();

        savings = savingsPersistence.findById(savings.getAccountId());
        savings.setUserContext(userContext);
        payment = savings.getLastPmnt();
        balanceAmount = new Money(Configuration.getInstance().getSystemConfig().getCurrency(), "6000.0");
        AccountTrxnEntity accountTrxn = helper.createAccountTrxn(payment, withdrawalAmount, balanceAmount, trxnDate,
                trxnDate, AccountActionTypes.SAVINGS_ADJUSTMENT.getValue(), savings, createdBy, group,
                "correction entry", null);
        payment.addAccountTrxn(accountTrxn);
        SavingBOTestUtils.setBalance(savings, balanceAmount);

        FinancialBusinessService financialBusinessService = new FinancialBusinessService();
        financialBusinessService.buildAccountingEntries(accountTrxn);
        savings.update();
        StaticHibernateUtil.commitTransaction();
        StaticHibernateUtil.closeSession();

        savings = savingsPersistence.findById(savings.getAccountId());
        savings.setUserContext(userContext);
        payment = savings.getLastPmnt();
       Assert.assertEquals(Integer.valueOf(2).intValue(), payment.getAccountTrxns().size());
        for (AccountTrxnEntity trxn : payment.getAccountTrxns()) {
            if (trxn.getAccountActionEntity().getId().equals(AccountActionTypes.SAVINGS_ADJUSTMENT.getValue())) {
               Assert.assertTrue(true);
               Assert.assertEquals(Integer.valueOf(2).intValue(), trxn.getFinancialTransactions().size());
                int countNegativeFinTrxn = 0;
                for (FinancialTransactionBO finTrxn : trxn.getFinancialTransactions()) {
                    if (finTrxn.getPostedAmount().getAmountDoubleValue() < 0) {
                        countNegativeFinTrxn++;
                    } else
                       Assert.assertEquals(1000.0, finTrxn.getPostedAmount().getAmountDoubleValue(), DELTA);
                   Assert.assertEquals("correction entry", finTrxn.getNotes());
                }

               Assert.assertEquals("Negative finTrxn values count", 0, countNegativeFinTrxn);
               Assert.assertEquals("Positive finTrxn values count", 2, accountTrxn.getFinancialTransactions().size()
                        - countNegativeFinTrxn);

            }
        }
        group = savings.getCustomer();
        center = group.getParentCustomer();
    }

    public void testWithdrawalEntriesOnSavingsCloseAccount() throws Exception {
        try {
            createInitialObjectsForSavings();
            SavingsTestHelper helper = new SavingsTestHelper();
            PersonnelBO createdBy = new PersonnelPersistence().getPersonnel(userContext.getId());
            Money withdrawalAmount = new Money(Configuration.getInstance().getSystemConfig().getCurrency(), "1000.7");
            java.util.Date trxnDate = helper.getDate("20/05/2006");

            AccountPaymentEntity payment = helper.createAccountPaymentToPersist(savings, withdrawalAmount, new Money(),
                    trxnDate, AccountActionTypes.SAVINGS_WITHDRAWAL.getValue(), savings, createdBy, group);

           Assert.assertEquals(Integer.valueOf(1).intValue(), payment.getAccountTrxns().size());
            FinancialBusinessService financialBusinessService = new FinancialBusinessService();
            AccountTestUtils.addAccountPayment(payment, savings);
            SavingsTrxnDetailEntity accountTrxn = null;
            for (AccountTrxnEntity trxn : payment.getAccountTrxns())
                accountTrxn = (SavingsTrxnDetailEntity) trxn;
            savings.setUserContext(TestObjectFactory.getContext());
            savings.changeStatus(AccountState.SAVINGS_CLOSED.getValue(), AccountStateFlag.SAVINGS_REJECTED.getValue(),
                    "");
            financialBusinessService.buildAccountingEntries(accountTrxn);
            Set<FinancialTransactionBO> financialTrxns = accountTrxn.getFinancialTransactions();
           Assert.assertEquals(Integer.valueOf(4).intValue(), financialTrxns.size());

            int withdrawalTrxns = 0;
            int roundingTrxns = 0;
            for (FinancialTransactionBO finTrxn : financialTrxns) {
                if (finTrxn.getFinancialAction().getId().equals(FinancialActionConstants.ROUNDING.getValue()))
                    roundingTrxns++;
                else
                    withdrawalTrxns++;
            }
           Assert.assertEquals(Integer.valueOf(2).intValue(), roundingTrxns);
           Assert.assertEquals(Integer.valueOf(2).intValue(), withdrawalTrxns);
           Assert.assertEquals(new Money("1000.7"), accountTrxn.getWithdrawlAmount());

            TestObjectFactory.flushandCloseSession();

            savings = new SavingsPersistence().findById(savings.getAccountId());
            group = savings.getCustomer();
            center = group.getParentCustomer();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void createInitialObjectsForSavings() throws Exception {
        MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
        center = TestObjectFactory.createCenter(this.getClass().getSimpleName() + " Center_Active_test", meeting);
        group = TestObjectFactory.createGroupUnderCenter(this.getClass().getSimpleName() + " Group_Active_test", CustomerStatus.GROUP_ACTIVE, center);
        SavingsTestHelper helper = new SavingsTestHelper();
        savingsOffering = helper.createSavingsOffering("sav 1234", "cvf1", (short) 31, (short) 7);
        savings = helper.createSavingsAccount("000100000000017", savingsOffering, group,
                AccountStates.SAVINGS_ACC_APPROVED, userContext);
    }

    public void testLoanWriteOffAccountingEntries() throws Exception {
        loan = getLoanAccount();
        loan.setUserContext(TestUtils.makeUser());
        AccountPaymentEntity accountPaymentEntity = new AccountPaymentEntity(loan, TestObjectFactory
                .getMoneyForMFICurrency(630), null, null, new PaymentTypeEntity(Short.valueOf("1")), new Date(System
                .currentTimeMillis()));
        FinancialBusinessService financialBusinessService = new FinancialBusinessService();
        AccountActionDateEntity accountActionDateEntity = loan.getAccountActionDate(Short.valueOf("1"));
        PersonnelBO personnel = new PersonnelPersistence().getPersonnel(loan.getUserContext().getId());
        LoanTrxnDetailEntity loanTrxnDetailEntity = new LoanTrxnDetailEntity(accountPaymentEntity,
                AccountActionTypes.WRITEOFF, accountActionDateEntity.getInstallmentId(),
                accountActionDateEntity.getActionDate(), personnel, new Date(System.currentTimeMillis()),
                ((LoanScheduleEntity) accountActionDateEntity).getPrincipal(), "Loan Written Off", null,
                ((LoanScheduleEntity) accountActionDateEntity).getPrincipal(), new Money(), new Money(), new Money(),
                new Money(), null, new MasterPersistence());

        accountPaymentEntity.addAccountTrxn(loanTrxnDetailEntity);
        AccountTestUtils.addAccountPayment(accountPaymentEntity, loan);
        financialBusinessService.buildAccountingEntries(loanTrxnDetailEntity);
        TestObjectFactory.updateObject(loan);
        Set<FinancialTransactionBO> finTrxnSet = loanTrxnDetailEntity.getFinancialTransactions();
       Assert.assertEquals(finTrxnSet.size(), 2);
        int countNegativeFinTrxn = 0;
        for (FinancialTransactionBO finTrxn : finTrxnSet) {
            if (finTrxn.getPostedAmount().getAmountDoubleValue() < 0) {
               Assert.assertEquals("Negative finTrxn values", finTrxn.getPostedAmount().negate().getAmountDoubleValue(),
                        100.0);
                countNegativeFinTrxn++;
            } else
               Assert.assertEquals("Positive finTrxn values", finTrxn.getPostedAmount().getAmountDoubleValue(), 100.0);
        }
       Assert.assertEquals("Negative finTrxn values count", countNegativeFinTrxn, 1);
       Assert.assertEquals("Positive finTrxn values count", finTrxnSet.size() - countNegativeFinTrxn, 1);
    }

    public void testLoanRescheduleAccountingEntries() throws Exception {
        loan = getLoanAccount();
        loan.setUserContext(TestUtils.makeUser());
        AccountPaymentEntity accountPaymentEntity = new AccountPaymentEntity(loan, TestObjectFactory
                .getMoneyForMFICurrency(630), null, null, new PaymentTypeEntity(Short.valueOf("1")), new Date(System
                .currentTimeMillis()));
        FinancialBusinessService financialBusinessService = new FinancialBusinessService();
        AccountActionDateEntity accountActionDateEntity = loan.getAccountActionDate(Short.valueOf("1"));
        PersonnelBO personnel = new PersonnelPersistence().getPersonnel(loan.getUserContext().getId());
        LoanTrxnDetailEntity loanTrxnDetailEntity = new LoanTrxnDetailEntity(accountPaymentEntity,
                AccountActionTypes.LOAN_RESCHEDULED, accountActionDateEntity.getInstallmentId(),
                accountActionDateEntity.getActionDate(), personnel, new Date(System.currentTimeMillis()),
                ((LoanScheduleEntity) accountActionDateEntity).getPrincipal(), "Loan Rescheduled", null,
                ((LoanScheduleEntity) accountActionDateEntity).getPrincipal(), new Money(), new Money(), new Money(),
                new Money(), null, new MasterPersistence());

        accountPaymentEntity.addAccountTrxn(loanTrxnDetailEntity);
        AccountTestUtils.addAccountPayment(accountPaymentEntity, loan);
        financialBusinessService.buildAccountingEntries(loanTrxnDetailEntity);
        TestObjectFactory.updateObject(loan);
        Set<FinancialTransactionBO> finTrxnSet = loanTrxnDetailEntity.getFinancialTransactions();
       Assert.assertEquals(finTrxnSet.size(), 2);
        int countNegativeFinTrxn = 0;
        for (FinancialTransactionBO finTrxn : finTrxnSet) {
            if (finTrxn.getPostedAmount().getAmountDoubleValue() < 0) {
               Assert.assertEquals("Negative finTrxn values", finTrxn.getPostedAmount().negate().getAmountDoubleValue(),
                        100.0);
                countNegativeFinTrxn++;
            } else
               Assert.assertEquals("Positive finTrxn values", finTrxn.getPostedAmount().getAmountDoubleValue(), 100.0);
        }
       Assert.assertEquals("Negative finTrxn values count", countNegativeFinTrxn, 1);
       Assert.assertEquals("Positive finTrxn values count", finTrxnSet.size() - countNegativeFinTrxn, 1);
    }

}


text:
<?php
require_once('TF2Player.php');

class SoldierPlayer extends TF2Player
{
    public function __construct($stuff)
    {
       parent::__construct($stuff);
    }
}
?>


text:
namespace Treehopper.Libraries.Sensors.Humidity
{
    internal interface IHumiditySensor : IPollable
    {
        double RelativeHumidity { get; }
    }
}


text:
package HuffmanCoding_v1;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Comparator;
import java.util.Map;

/**
 * Huffman encoding obeys the huffman algorithm.
 * It compresses the input sentence and serializes the "huffman code"
 * and the "tree" used to generate  the huffman code
 * Both the serialized files are intended to be sent to client.
 *
 * http://algs4.cs.princeton.edu/55compression/Huffman.java.html
 * http://codereview.stackexchange.com/questions/44473/huffman-code-implementation
 *
 */
public  class Huffman
{
	private Huffman(){};

}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Sendega.com.sendega.smsc {

    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    [System.ServiceModel.ServiceContractAttribute(Namespace="http://smsc.sendega.com/Content", ConfigurationName="com.sendega.smsc.ContentSoap")]
    public interface ContentSoap {

        [System.ServiceModel.OperationContractAttribute(Action="http://smsc.sendega.com/Content/SendMms", ReplyAction="*")]
        [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
        Sendega.com.sendega.smsc.SendResult SendMms(string username, string password, double destination, int pricegroup, string subject, string messageText, string dlrUrl, string extID, string refID, string imageUrl);

        [System.ServiceModel.OperationContractAttribute(Action="http://smsc.sendega.com/Content/SendMms", ReplyAction="*")]
        System.Threading.Tasks.Task<Sendega.com.sendega.smsc.SendResult> SendMmsAsync(string username, string password, double destination, int pricegroup, string subject, string messageText, string dlrUrl, string extID, string refID, string imageUrl);

        [System.ServiceModel.OperationContractAttribute(Action="http://smsc.sendega.com/Content/Send", ReplyAction="*")]
        [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
        Sendega.com.sendega.smsc.SendResult Send(
                    string username,
                    string password,
                    string sender,
                    string destination,
                    int pricegroup,
                    int contentTypeID,
                    string contentHeader,
                    string content,
                    string dlrUrl,
                    int ageLimit,
                    string extID,
                    string sendDate,
                    string refID,
                    int priority,
                    int gwID,
                    int pid,
                    int dcs);

        [System.ServiceModel.OperationContractAttribute(Action="http://smsc.sendega.com/Content/Send", ReplyAction="*")]
        System.Threading.Tasks.Task<Sendega.com.sendega.smsc.SendResult> SendAsync(
                    string username,
                    string password,
                    string sender,
                    string destination,
                    int pricegroup,
                    int contentTypeID,
                    string contentHeader,
                    string content,
                    string dlrUrl,
                    int ageLimit,
                    string extID,
                    string sendDate,
                    string refID,
                    int priority,
                    int gwID,
                    int pid,
                    int dcs);

        [System.ServiceModel.OperationContractAttribute(Action="http://smsc.sendega.com/Content/RequestNumberEnquiry", ReplyAction="*")]
        [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
        Sendega.com.sendega.smsc.NumberEnquiryResult RequestNumberEnquiry(string username, string password, double msisdn, string returnUrl);

        [System.ServiceModel.OperationContractAttribute(Action="http://smsc.sendega.com/Content/RequestNumberEnquiry", ReplyAction="*")]
        System.Threading.Tasks.Task<Sendega.com.sendega.smsc.NumberEnquiryResult> RequestNumberEnquiryAsync(string username, string password, double msisdn, string returnUrl);

        [System.ServiceModel.OperationContractAttribute(Action="http://smsc.sendega.com/Content/SetOperator", ReplyAction="*")]
        [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
        void SetOperator(string username, string password, decimal msisdn, short mcc, short mnc);

        [System.ServiceModel.OperationContractAttribute(Action="http://smsc.sendega.com/Content/SetOperator", ReplyAction="*")]
        System.Threading.Tasks.Task SetOperatorAsync(string username, string password, decimal msisdn, short mcc, short mnc);
    }

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.6.1038.0")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://smsc.sendega.com/Content")]
    public partial class SendResult : object, System.ComponentModel.INotifyPropertyChanged {

        private System.Guid messageIDField;

        private string errorMessageField;

        private int errorNumberField;

        private bool successField;

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Order=0)]
        public System.Guid MessageID {
            get {
                return this.messageIDField;
            }
            set {
                this.messageIDField = value;
                this.RaisePropertyChanged("MessageID");
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Order=1)]
        public string ErrorMessage {
            get {
                return this.errorMessageField;
            }
            set {
                this.errorMessageField = value;
                this.RaisePropertyChanged("ErrorMessage");
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Order=2)]
        public int ErrorNumber {
            get {
                return this.errorNumberField;
            }
            set {
                this.errorNumberField = value;
                this.RaisePropertyChanged("ErrorNumber");
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Order=3)]
        public bool Success {
            get {
                return this.successField;
            }
            set {
                this.successField = value;
                this.RaisePropertyChanged("Success");
            }
        }

        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

        protected void RaisePropertyChanged(string propertyName) {
            System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
            if ((propertyChanged != null)) {
                propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }
    }

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.6.1038.0")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://smsc.sendega.com/Content")]
    public partial class NumberEnquiryResult : object, System.ComponentModel.INotifyPropertyChanged {

        private string errorMessageField;

        private int errorNumberField;

        private double msisdnField;

        private string cityField;

        private string zipField;

        private string address2Field;

        private string address1Field;

        private string surnameField;

        private string firstnameField;

        private System.Guid messageIDField;

        private bool successField;

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Order=0)]
        public string ErrorMessage {
            get {
                return this.errorMessageField;
            }
            set {
                this.errorMessageField = value;
                this.RaisePropertyChanged("ErrorMessage");
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Order=1)]
        public int ErrorNumber {
            get {
                return this.errorNumberField;
            }
            set {
                this.errorNumberField = value;
                this.RaisePropertyChanged("ErrorNumber");
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Order=2)]
        public double Msisdn {
            get {
                return this.msisdnField;
            }
            set {
                this.msisdnField = value;
                this.RaisePropertyChanged("Msisdn");
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Order=3)]
        public string City {
            get {
                return this.cityField;
            }
            set {
                this.cityField = value;
                this.RaisePropertyChanged("City");
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Order=4)]
        public string Zip {
            get {
                return this.zipField;
            }
            set {
                this.zipField = value;
                this.RaisePropertyChanged("Zip");
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Order=5)]
        public string Address2 {
            get {
                return this.address2Field;
            }
            set {
                this.address2Field = value;
                this.RaisePropertyChanged("Address2");
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Order=6)]
        public string Address1 {
            get {
                return this.address1Field;
            }
            set {
                this.address1Field = value;
                this.RaisePropertyChanged("Address1");
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Order=7)]
        public string Surname {
            get {
                return this.surnameField;
            }
            set {
                this.surnameField = value;
                this.RaisePropertyChanged("Surname");
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Order=8)]
        public string Firstname {
            get {
                return this.firstnameField;
            }
            set {
                this.firstnameField = value;
                this.RaisePropertyChanged("Firstname");
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Order=9)]
        public System.Guid MessageID {
            get {
                return this.messageIDField;
            }
            set {
                this.messageIDField = value;
                this.RaisePropertyChanged("MessageID");
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Order=10)]
        public bool Success {
            get {
                return this.successField;
            }
            set {
                this.successField = value;
                this.RaisePropertyChanged("Success");
            }
        }

        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

        protected void RaisePropertyChanged(string propertyName) {
            System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
            if ((propertyChanged != null)) {
                propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }
    }

    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    public interface ContentSoapChannel : Sendega.com.sendega.smsc.ContentSoap, System.ServiceModel.IClientChannel {
    }

    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    public partial class ContentSoapClient : System.ServiceModel.ClientBase<Sendega.com.sendega.smsc.ContentSoap>, Sendega.com.sendega.smsc.ContentSoap {

        public ContentSoapClient() {
        }

        public ContentSoapClient(string endpointConfigurationName) :
                base(endpointConfigurationName) {
        }

        public ContentSoapClient(string endpointConfigurationName, string remoteAddress) :
                base(endpointConfigurationName, remoteAddress) {
        }

        public ContentSoapClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
                base(endpointConfigurationName, remoteAddress) {
        }

        public ContentSoapClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
                base(binding, remoteAddress) {
        }

        public Sendega.com.sendega.smsc.SendResult SendMms(string username, string password, double destination, int pricegroup, string subject, string messageText, string dlrUrl, string extID, string refID, string imageUrl) {
            return base.Channel.SendMms(username, password, destination, pricegroup, subject, messageText, dlrUrl, extID, refID, imageUrl);
        }

        public System.Threading.Tasks.Task<Sendega.com.sendega.smsc.SendResult> SendMmsAsync(string username, string password, double destination, int pricegroup, string subject, string messageText, string dlrUrl, string extID, string refID, string imageUrl) {
            return base.Channel.SendMmsAsync(username, password, destination, pricegroup, subject, messageText, dlrUrl, extID, refID, imageUrl);
        }

        public Sendega.com.sendega.smsc.SendResult Send(
                    string username,
                    string password,
                    string sender,
                    string destination,
                    int pricegroup,
                    int contentTypeID,
                    string contentHeader,
                    string content,
                    string dlrUrl,
                    int ageLimit,
                    string extID,
                    string sendDate,
                    string refID,
                    int priority,
                    int gwID,
                    int pid,
                    int dcs) {
            return base.Channel.Send(username, password, sender, destination, pricegroup, contentTypeID, contentHeader, content, dlrUrl, ageLimit, extID, sendDate, refID, priority, gwID, pid, dcs);
        }

        public System.Threading.Tasks.Task<Sendega.com.sendega.smsc.SendResult> SendAsync(
                    string username,
                    string password,
                    string sender,
                    string destination,
                    int pricegroup,
                    int contentTypeID,
                    string contentHeader,
                    string content,
                    string dlrUrl,
                    int ageLimit,
                    string extID,
                    string sendDate,
                    string refID,
                    int priority,
                    int gwID,
                    int pid,
                    int dcs) {
            return base.Channel.SendAsync(username, password, sender, destination, pricegroup, contentTypeID, contentHeader, content, dlrUrl, ageLimit, extID, sendDate, refID, priority, gwID, pid, dcs);
        }

        public Sendega.com.sendega.smsc.NumberEnquiryResult RequestNumberEnquiry(string username, string password, double msisdn, string returnUrl) {
            return base.Channel.RequestNumberEnquiry(username, password, msisdn, returnUrl);
        }

        public System.Threading.Tasks.Task<Sendega.com.sendega.smsc.NumberEnquiryResult> RequestNumberEnquiryAsync(string username, string password, double msisdn, string returnUrl) {
            return base.Channel.RequestNumberEnquiryAsync(username, password, msisdn, returnUrl);
        }

        public void SetOperator(string username, string password, decimal msisdn, short mcc, short mnc) {
            base.Channel.SetOperator(username, password, msisdn, mcc, mnc);
        }

        public System.Threading.Tasks.Task SetOperatorAsync(string username, string password, decimal msisdn, short mcc, short mnc) {
            return base.Channel.SetOperatorAsync(username, password, msisdn, mcc, mnc);
        }
    }
}


text:
package com.gh4a.loader;

import android.content.Context;
import android.widget.Toast;

import com.gh4a.Gh4Application;

public class LoaderResult<T> {
    private T mData;
    private Exception mException;

    LoaderResult(T data) {
        mData = data;
    }

    LoaderResult(Exception e) {
        mException = e;
    }

    public T getData() {
        return mData;
    }

    public boolean isSuccess() {
        return mException == null;
    }

    private boolean isAuthError() {
        if (mException == null) {
            return false;
        }
        return "Received authentication challenge is null".equalsIgnoreCase(mException.getMessage())
                || "No authentication challenges found".equalsIgnoreCase(mException.getMessage());
    }

    public Exception getException() {
        return mException;
    }

    public String getErrorMessage() {
        return mException != null ? mException.getMessage() : null;
    }

    public boolean handleError(Context context) {
        if (isSuccess()) {
            return false;
        }

        if (isAuthError()) {
            Gh4Application.get().logout();
        }
        Toast.makeText(context, getErrorMessage(), Toast.LENGTH_SHORT).show();
        return true;
    }
}


text:
package com.konkerlabs.platform.registry.api.test.web.controller;

import com.konkerlabs.platform.registry.api.config.WebMvcConfig;
import com.konkerlabs.platform.registry.api.model.HealthAlertInputVO;
import com.konkerlabs.platform.registry.api.test.config.MongoTestConfig;
import com.konkerlabs.platform.registry.api.test.config.WebTestConfiguration;
import com.konkerlabs.platform.registry.api.web.controller.HealthAlertRestController;
import com.konkerlabs.platform.registry.api.web.wrapper.CrudResponseAdvice;
import com.konkerlabs.platform.registry.business.model.*;
import com.konkerlabs.platform.registry.business.services.api.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import java.text.MessageFormat;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;

import static org.hamcrest.Matchers.*;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = HealthAlertRestController.class)
@AutoConfigureMockMvc(secure = false)
@ContextConfiguration(classes = {
        WebTestConfiguration.class,
        MongoTestConfig.class,
        WebMvcConfig.class,
        CrudResponseAdvice.class
})
public class HealthAlertRestControllerTest extends WebLayerTestContext {

    @Autowired
    private ApplicationService applicationService;

    @Autowired
    private Tenant tenant;

    @Autowired
    private Application application;

    @Autowired
    private AlertTriggerService alertTriggerService;

    @Autowired
    private HealthAlertService healthAlertService;

    @Autowired
    private DeviceRegisterService deviceRegisterService;

    private AlertTrigger silenceAlertTrigger;

    private HealthAlert healthAlertA;

    private HealthAlert healthAlertB;

    private Device device;

    private final String BASEPATH = "triggers";

    @Before
    public void setUp() {

        silenceAlertTrigger = new AlertTrigger();
        silenceAlertTrigger.setGuid("2cdc391d-6a31-4103-9679-52cb6f2e5df5");
        silenceAlertTrigger.setName("silence");
        silenceAlertTrigger.setTenant(tenant);
        silenceAlertTrigger.setApplication(application);
        silenceAlertTrigger.setType(AlertTrigger.AlertTriggerType.SILENCE);

        Instant creationDateTime = Instant.parse("2007-12-03T10:15:30.00Z");

        device = Device.builder()
                .deviceId("iu9ocqczgw")
                .build();

        healthAlertA = HealthAlert.builder()
                .device(device)
                .alertTrigger(silenceAlertTrigger)
                .alertId("alert-a-id")
                .description("alert-a-desc")
                .guid("71c9713e-1bfe-402b-9456-44464c864575")
                .lastChange(creationDateTime)
                .registrationDate(creationDateTime)
                .severity(HealthAlert.HealthAlertSeverity.FAIL)
                .build();

        healthAlertB = HealthAlert.builder()
                .device(device)
                .alertTrigger(silenceAlertTrigger)
                .alertId("alert-b-id")
                .description("alert-b-desc")
                .guid("6d796020-892b-43f5-9694-57bc730bde2b")
                .lastChange(creationDateTime)
                .registrationDate(creationDateTime)
                .severity(HealthAlert.HealthAlertSeverity.WARN)
                .build();

        when(applicationService.getByApplicationName(tenant, application.getName()))
            .thenReturn(ServiceResponseBuilder.<Application> ok().withResult(application).build());

        when(alertTriggerService.findByTenantAndApplicationAndName(tenant, application, silenceAlertTrigger.getName()))
            .thenReturn(ServiceResponseBuilder.<AlertTrigger> ok().withResult(silenceAlertTrigger).build());

        when(deviceRegisterService.findByDeviceId(tenant, application, device.getDeviceId()))
            .thenReturn(ServiceResponseBuilder.<Device> ok().withResult(device).build());

        when(healthAlertService.findByTenantApplicationTriggerAndAlertId(
                tenant,
                application,
                silenceAlertTrigger,
                healthAlertA.getAlertId())
        ).thenReturn(ServiceResponseBuilder.<HealthAlert> ok().withResult(healthAlertA).build());

    }

    @After
    public void tearDown() {
        Mockito.reset(applicationService);
    }

    @Test
    public void shouldListHealthAlerts() throws Exception {

        List<HealthAlert> alertTriggers = new ArrayList<>();
        alertTriggers.add(healthAlertA);
        alertTriggers.add(healthAlertB);

        when(healthAlertService
                        .findAllByTenantApplicationAndTrigger(
                                tenant,
                                application,
                                silenceAlertTrigger
                        ))
            .thenReturn(ServiceResponseBuilder.<List<HealthAlert>> ok()
                    .withResult(alertTriggers).build());

        getMockMvc()
                .perform(MockMvcRequestBuilders
        		.get(MessageFormat.format("/{0}/{1}/{2}/alerts/", application.getName(), BASEPATH, silenceAlertTrigger.getName()))
        		.contentType("application/json")
        		.accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.OK.value())))
                .andExpect(jsonPath("$.status", is("success")))
                .andExpect(jsonPath("$.timestamp",greaterThan(1400000000)))
                .andExpect(jsonPath("$.result", hasSize(2)))
                .andExpect(jsonPath("$.result[0].alertId", is(healthAlertA.getAlertId())))
                .andExpect(jsonPath("$.result[0].description", is(healthAlertA.getDescription())))
                .andExpect(jsonPath("$.result[1].alertId", is(healthAlertB.getAlertId())))
                .andExpect(jsonPath("$.result[1].description", is(healthAlertB.getDescription())))
                ;

    }

    @Test
    public void shouldUpdateHealthAlert() throws Exception {

        when(healthAlertService
                .update(Matchers.any(Tenant.class), Matchers.any(Application.class), Matchers.anyString(), Matchers.any(HealthAlert.class)))
                .thenReturn(ServiceResponseBuilder.<HealthAlert> ok()
                        .withResult(healthAlertA).build());

        getMockMvc()
                .perform(MockMvcRequestBuilders
                        .put(MessageFormat.format("/{0}/{1}/{2}/alerts/{3}", application.getName(), BASEPATH, silenceAlertTrigger.getName(), healthAlertA.getAlertId()))
                        .content(getJson(new HealthAlertInputVO().apply(healthAlertA)))
                        .contentType("application/json")
                        .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.OK.value())))
                .andExpect(jsonPath("$.status", is("success")))
                .andExpect(jsonPath("$.timestamp",greaterThan(1400000000)))
                .andExpect(jsonPath("$.result.alertId", is(healthAlertA.getAlertId())))
                .andExpect(jsonPath("$.result.deviceId", is(device.getDeviceId())))
                .andExpect(jsonPath("$.result.description", is(healthAlertA.getDescription())))
                .andExpect(jsonPath("$.result.occurrenceDate", is("2007-12-03T10:15:30Z")))
                .andExpect(jsonPath("$.result.severity", is("FAIL")))
                .andExpect(jsonPath("$.result.type", is("SILENCE")))
                .andExpect(jsonPath("$.result.triggerName", is(silenceAlertTrigger.getName())))
        ;

    }

    @Test
    public void shouldEditHealthAlert() throws Exception {

        when(healthAlertService.update(Matchers.any(Tenant.class), Matchers.any(Application.class), Matchers.anyString(), Matchers.any(HealthAlert.class)))
                .thenReturn(ServiceResponseBuilder.<HealthAlert> ok()
                        .withResult(healthAlertA).build());

        getMockMvc()
                .perform(MockMvcRequestBuilders
                        .put(MessageFormat.format("/{0}/{1}/{2}/alerts/{3}", application.getName(), BASEPATH, silenceAlertTrigger.getName(), healthAlertA.getAlertId()))
                        .contentType("application/json")
                        .content(getJson(new HealthAlertInputVO().apply(healthAlertA)))
                        .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.OK.value())))
                .andExpect(jsonPath("$.status", is("success")))
                .andExpect(jsonPath("$.timestamp",greaterThan(1400000000)))
                .andExpect(jsonPath("$.result.alertId", is(healthAlertA.getAlertId())))
                .andExpect(jsonPath("$.result.deviceId", is(device.getDeviceId())))
                .andExpect(jsonPath("$.result.description", is(healthAlertA.getDescription())))
                .andExpect(jsonPath("$.result.occurrenceDate", is("2007-12-03T10:15:30Z")))
                .andExpect(jsonPath("$.result.severity", is("FAIL")))
                .andExpect(jsonPath("$.result.type", is("SILENCE")))
                .andExpect(jsonPath("$.result.triggerName", is(silenceAlertTrigger.getName())))

                ;
    }

    @Test
    public void shouldEditNonExistingHealthAlert() throws Exception {

        when(healthAlertService.findByTenantApplicationTriggerAndAlertId(
                tenant,
                application,
                silenceAlertTrigger,
                healthAlertA.getAlertId())
        ).thenReturn(ServiceResponseBuilder.<HealthAlert> error()
                .withMessage(HealthAlertService.Validations.HEALTH_ALERT_DOES_NOT_EXIST.getCode()).build());

        when(healthAlertService.register(Matchers.any(Tenant.class), Matchers.any(Application.class), Matchers.any(HealthAlert.class)))
                .thenReturn(ServiceResponseBuilder.<HealthAlert> ok()
                        .withResult(healthAlertA).build());

        getMockMvc()
                .perform(MockMvcRequestBuilders
                        .put(MessageFormat.format("/{0}/{1}/{2}/alerts/{3}", application.getName(), BASEPATH, silenceAlertTrigger.getName(), healthAlertA.getAlertId()))
                        .contentType("application/json")
                        .content(getJson(new HealthAlertInputVO().apply(healthAlertA)))
                        .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.OK.value())))
                .andExpect(jsonPath("$.status", is("success")))
                .andExpect(jsonPath("$.timestamp",greaterThan(1400000000)))
                .andExpect(jsonPath("$.result.alertId", is(healthAlertA.getAlertId())))
                .andExpect(jsonPath("$.result.deviceId", is(device.getDeviceId())))
                .andExpect(jsonPath("$.result.description", is(healthAlertA.getDescription())))
                .andExpect(jsonPath("$.result.occurrenceDate", is("2007-12-03T10:15:30Z")))
                .andExpect(jsonPath("$.result.severity", is("FAIL")))
                .andExpect(jsonPath("$.result.type", is("SILENCE")))
                .andExpect(jsonPath("$.result.triggerName", is(silenceAlertTrigger.getName())))

        ;
    }

    @Test
    public void shouldCreateHealthAlert() throws Exception {

        when(healthAlertService.register(Matchers.any(Tenant.class), Matchers.any(Application.class), Matchers.any(HealthAlert.class)))
                .thenReturn(ServiceResponseBuilder.<HealthAlert> ok()
                        .withResult(healthAlertA).build());

        getMockMvc()
                .perform(MockMvcRequestBuilders
                        .post(MessageFormat.format("/{0}/{1}/{2}/alerts", application.getName(), BASEPATH, silenceAlertTrigger.getName()))
                        .contentType("application/json")
                        .content(getJson(new HealthAlertInputVO().apply(healthAlertA)))
                        .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().is2xxSuccessful())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.CREATED.value())))
                .andExpect(jsonPath("$.status", is("success")))
                .andExpect(jsonPath("$.timestamp",greaterThan(1400000000)))
                .andExpect(jsonPath("$.result.alertId", is(healthAlertA.getAlertId())))
                .andExpect(jsonPath("$.result.deviceId", is(device.getDeviceId())))
                .andExpect(jsonPath("$.result.description", is(healthAlertA.getDescription())))
                .andExpect(jsonPath("$.result.occurrenceDate", is("2007-12-03T10:15:30Z")))
                .andExpect(jsonPath("$.result.severity", is("FAIL")))
                .andExpect(jsonPath("$.result.type", is("SILENCE")))
                .andExpect(jsonPath("$.result.triggerName", is(silenceAlertTrigger.getName())))
        ;

    }

    @Test
    public void shouldRemoveHealthAlert() throws Exception {

        when(healthAlertService.remove(Matchers.any(Tenant.class), Matchers.any(Application.class), Matchers.anyString(), Matchers.any(HealthAlert.Solution.class)))
                .thenReturn(ServiceResponseBuilder.<HealthAlert> ok()
                        .withResult(healthAlertA).build());

        getMockMvc()
                .perform(MockMvcRequestBuilders
                        .delete(MessageFormat.format("/{0}/{1}/{2}/alerts/{3}", application.getName(), BASEPATH, silenceAlertTrigger.getName(), healthAlertA.getAlertId()))
                        .contentType("application/json")
                        .content(getJson(new HealthAlertInputVO().apply(healthAlertA)))
                        .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().is2xxSuccessful())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.NO_CONTENT.value())))
                .andExpect(jsonPath("$.status", is("success")))
                .andExpect(jsonPath("$.timestamp",greaterThan(1400000000)))
                .andExpect(jsonPath("$.result").doesNotExist());

    }

    @Test
    public void shouldReadHealthAlert() throws Exception {

        getMockMvc()
                .perform(MockMvcRequestBuilders
                        .get(MessageFormat.format("/{0}/{1}/{2}/alerts/{3}", application.getName(), BASEPATH, silenceAlertTrigger.getName(), healthAlertA.getAlertId()))
                        .contentType("application/json")
                        .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().is2xxSuccessful())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.OK.value())))
                .andExpect(jsonPath("$.status", is("success")))
                .andExpect(jsonPath("$.timestamp",greaterThan(1400000000)))
                .andExpect(jsonPath("$.result.alertId", is(healthAlertA.getAlertId())))
                .andExpect(jsonPath("$.result.deviceId", is(device.getDeviceId())))
                .andExpect(jsonPath("$.result.description", is(healthAlertA.getDescription())))
                .andExpect(jsonPath("$.result.occurrenceDate", is("2007-12-03T10:15:30Z")))
                .andExpect(jsonPath("$.result.severity", is("FAIL")))
                .andExpect(jsonPath("$.result.type", is("SILENCE")))
                .andExpect(jsonPath("$.result.triggerName", is(silenceAlertTrigger.getName())))
        ;

    }

}


text:
// ------------------------------------------------------------------------------
//  <auto-generated>
//      This code was generated by SpecFlow (http://www.specflow.org/).
//      SpecFlow Version:1.9.0.77
//      SpecFlow Generator Version:1.9.0.0
//      Runtime Version:4.0.30319.17929
//
//      Changes to this file may cause incorrect behavior and will be lost if
//      the code is regenerated.
//  </auto-generated>
// ------------------------------------------------------------------------------
#region Designer generated code
#pragma warning disable
namespace YouTrack.Rest.Features.General.Issues
{
    using TechTalk.SpecFlow;

    [System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "1.9.0.77")]
    [System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [NUnit.Framework.TestFixtureAttribute()]
    [NUnit.Framework.DescriptionAttribute("Delete an Issue")]
    public partial class DeleteAnIssueFeature
    {

        private static TechTalk.SpecFlow.ITestRunner testRunner;

#line 1 "DeleteAnIssue.feature"
#line hidden

        [NUnit.Framework.TestFixtureSetUpAttribute()]
        public virtual void FeatureSetup()
        {
            testRunner = TechTalk.SpecFlow.TestRunnerManager.GetTestRunner();
            TechTalk.SpecFlow.FeatureInfo featureInfo = new TechTalk.SpecFlow.FeatureInfo(new System.Globalization.CultureInfo("en-US"), "Delete an Issue", "", ProgrammingLanguage.CSharp, ((string[])(null)));
            testRunner.OnFeatureStart(featureInfo);
        }

        [NUnit.Framework.TestFixtureTearDownAttribute()]
        public virtual void FeatureTearDown()
        {
            testRunner.OnFeatureEnd();
            testRunner = null;
        }

        [NUnit.Framework.SetUpAttribute()]
        public virtual void TestInitialize()
        {
        }

        [NUnit.Framework.TearDownAttribute()]
        public virtual void ScenarioTearDown()
        {
            testRunner.OnScenarioEnd();
        }

        public virtual void ScenarioSetup(TechTalk.SpecFlow.ScenarioInfo scenarioInfo)
        {
            testRunner.OnScenarioStart(scenarioInfo);
        }

        public virtual void ScenarioCleanup()
        {
            testRunner.CollectScenarioErrors();
        }

        [NUnit.Framework.TestAttribute()]
        [NUnit.Framework.DescriptionAttribute("Deleting an existing issue")]
        public virtual void DeletingAnExistingIssue()
        {
            TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Deleting an existing issue", ((string[])(null)));
#line 3
this.ScenarioSetup(scenarioInfo);
#line 4
 testRunner.Given("I have created an issue", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given ");
#line 5
  testRunner.When("I delete the issue", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line 6
  testRunner.Then("the issue is deleted", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line hidden
            this.ScenarioCleanup();
        }
    }
}
#pragma warning restore
#endregion


text:
<?xml version="1.0" encoding="utf-8"?>
<groceries>
	<catName>Dairy</catName>
	<prodName>Milk</prodName>
	<imageName>assets/dairy_milk.jpg</imageName>
	<cost>1.20</cost>
	<listPrice>1.99</listPrice>
	<isOrganic>true</isOrganic>
	<isLowFat>true</isLowFat>
	<description>Direct from California where cows are happiest!</description>
</groceries>


text:
<?php
namespace Neos\Flow\ObjectManagement\Exception;

/**
 * "Wrong Scope" Exception
 *
 * @api
 */
class WrongScopeException extends \Neos\Flow\ObjectManagement\Exception
{
}


text:
package com.lothrazar.cyclic.block.soundrecord;

import com.lothrazar.cyclic.gui.ButtonMachine;
import com.lothrazar.cyclic.gui.ScreenBase;
import com.lothrazar.cyclic.gui.TextureEnum;
import com.lothrazar.cyclic.net.PacketTileData;
import com.lothrazar.cyclic.registry.PacketRegistry;
import com.lothrazar.cyclic.registry.TextureRegistry;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.player.Inventory;

public class ScreenSoundRecorder extends ScreenBase<ContainerSoundRecorder> {

  public ScreenSoundRecorder(ContainerSoundRecorder screenContainer, Inventory inv, Component titleIn) {
    super(screenContainer, inv, titleIn);
    this.imageHeight = this.imageWidth = 256;
  }

  @Override
  public void init() {
    super.init();
    int x, y;
    x = leftPos + 4;
    y = topPos + 174;
    int bsize = 20;
    final String pf = "block.cyclic.sound_recorder.";
    ButtonMachine buttonClear = addRenderableWidget(new ButtonMachine(x, y, bsize, bsize, TextureEnum.CRAFT_EMPTY, TileSoundRecorder.Fields.CLEARALL.ordinal(), (p) -> {
      menu.tile.clearSounds();
      PacketRegistry.INSTANCE.sendToServer(new PacketTileData(TileSoundRecorder.Fields.CLEARALL.ordinal(), 1, menu.tile.getBlockPos()));
    }));
    buttonClear.xOffset = -3;
    buttonClear.yOffset = -2;
    buttonClear.setTooltip(pf + "clear");
    bsize = 16;
    y = topPos + 8;
    for (int i = 0; i < TileSoundRecorder.MAX_SOUNDS; i++) {
      ButtonMachine btnSave = addRenderableWidget(new ButtonMachine(x, y, bsize, bsize,
          TextureEnum.RENDER_SHOW, i, (p) -> {
            int soundIndex = ((ButtonMachine) p).getTileField();
            PacketRegistry.INSTANCE.sendToServer(new PacketTileData(TileSoundRecorder.Fields.SAVE.ordinal(), soundIndex, menu.tile.getBlockPos()));
          }));
      //      btnSave.active = !container.tile.inputSlots.getStackInSlot(0).isEmpty();
      btnSave.xOffset = 2;
      btnSave.yOffset = 2;
      btnSave.setTooltip(pf + "save");
      //      btnSave.setTextureId(TextureEnum.RENDER_SHOW);
      ButtonMachine btnIgnore = addRenderableWidget(new ButtonMachine(x + bsize, y, bsize, bsize,
          TextureEnum.POWER_STOP, i, (p) -> {
            int soundIndex = ((ButtonMachine) p).getTileField();
            menu.tile.ignoreSound(soundIndex);
            PacketRegistry.INSTANCE.sendToServer(new PacketTileData(TileSoundRecorder.Fields.IGNORE.ordinal(), soundIndex, menu.tile.getBlockPos()));
          }));
      btnIgnore.xOffset = -1;
      btnIgnore.yOffset = -1;
      btnIgnore.setTooltip(pf + "ignore");
      //      btnIgnore.setTextureId();
      y += bsize;
    }
    //    buttonClear.setTooltip(pf + "clear");
  }

  @Override
  public void render(PoseStack ms, int mouseX, int mouseY, float partialTicks) {
    this.renderBackground(ms);
    super.render(ms, mouseX, mouseY, partialTicks);
    this.renderTooltip(ms, mouseX, mouseY);
  }

  @Override
  protected void renderLabels(PoseStack ms, int mouseX, int mouseY) {
    this.drawButtonTooltips(ms, mouseX, mouseY);
    //    this.drawName(ms, this.title.getString());
    int x = 38, y = 12;
    for (int i = 0; i < TileSoundRecorder.MAX_SOUNDS; i++) {
      String s = menu.tile.getFieldString(i);
      this.drawString(ms, s, x, y);
      y += 16;
    }
  }

  @Override
  protected void renderBg(PoseStack ms, float partialTicks, int mouseX, int mouseY) {
    this.drawBackground(ms, TextureRegistry.INVENTORY_SOUND);
    this.drawSlot(ms, 8, 208, TextureRegistry.SLOT_SOUND);
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
class GrabAndGo
{
    static void Main()
    {
        var numbers = Console.ReadLine().Split().Select(long.Parse).ToArray();
        long num = int.Parse(Console.ReadLine());

        if (!numbers.Contains(num))
        {
            Console.WriteLine("No occurrences were found!");
        }

        else
        {
            var index = 0;
            long sum = 0;
            for (int i = numbers.Length - 1; i >= 0; i--)
            {
                if (numbers[i] == num)
                {
                    index = i;
                    break;
                }
            }

            for (int i = 0; i < index; i++)
            {
                sum += numbers[i];
            }

            Console.WriteLine(sum);
        }
    }
}


text:
namespace RealEstateSystem.Web.Api.Areas.HelpPage.ModelDescriptions
{
    public class DictionaryModelDescription : KeyValuePairModelDescription
    {
    }
}


text:
- app.py: Everything needed to run the plugin as a standalone Flask app with test data,
or run as a plugin within an airflow instance
- models.py: All database queries and data generation abstracted out of app.py
- utils.py: Helper functions such as a database hook creation function
- static/ and templates/: DO NOT EDIT THESE DIRECTLY, rather edit files within
../../dev/ and use gulp to compile them into these folders.


text:
module Fog
  module Compute
    class Brightbox
      class Real
        # Lists summary details of cloud IP addresses owned by the account.
        #
        #
        # @return [Hash] if successful Hash version of JSON object
        #
        # @see https://api.gb1.brightbox.com/1.0/#cloud_ip_list_cloud_ips
        #
        def list_cloud_ips
          wrapped_request("get", "/1.0/cloud_ips", [200])
        end

      end
    end
  end
end


text:
"""Imports from submodules to make higher up imports easier"""
from .sqs import SQSClient


text:
package net.coding.program.common.network;

import android.content.Context;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.PersistentCookieStore;

/**
 * Created by chaochen on 14-10-8.
 */
public class MyAsyncHttpClient {

    public static AsyncHttpClient createClient(Context context) {
        AsyncHttpClient client = new AsyncHttpClient();
        PersistentCookieStore cookieStore = new PersistentCookieStore(context);
        client.setCookieStore(cookieStore);
//        去除 ssl 验证
//        try {
//            SSLContext sslContext = SSLContext.getInstance("TLS");
//            sslContext.init(null, new TrustManager[]{new CustomX509TrustManager()},
//                    new SecureRandom());
//            SSLSocketFactory ssf = new CustomSSLSocketFactory(sslContext);
//            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
//            Scheme scheme = new Scheme("https", ssf, 443);
//            client.getHttpClient().getConnectionManager().getSchemeRegistry()
//                    .register(scheme);
//
//        } catch (Exception e) {
//            Global.errorLog(e);
//        }

        return client;
    }

}


text:
Bluetooth A2DP API
==================

Overview
--------

`Instructions`_

.. _Instructions: ../template.html

Application Example
-------------------

Check :example:`bluetooth` folder in ESP-IDF examples, which contains the following application:

* This is a A2DP sink client demo. This demo can be discovered and connected by A2DP source device and receive the audio stream from remote device - :example:`bluetooth/a2dp_sink`

API Reference
-------------

.. include:: /_build/inc/esp_a2dp_api.inc


text:
"""Manage HTTP servers with CherryPy."""

import warnings

import cherrypy
from cherrypy.lib import attributes
from cherrypy._cpcompat import basestring, py3k

# We import * because we want to export check_port
# et al as attributes of this module.
from cherrypy.process.servers import *

class Server(ServerAdapter):
    """An adapter for an HTTP server.

    You can set attributes (like socket_host and socket_port)
    on *this* object (which is probably cherrypy.server), and call
    quickstart. For example::

        cherrypy.server.socket_port = 80
        cherrypy.quickstart()
    """

    socket_port = 8080
    """The TCP port on which to listen for connections."""

    _socket_host = '127.0.0.1'
    def _get_socket_host(self):
        return self._socket_host
    def _set_socket_host(self, value):
        if value == '':
            raise ValueError("The empty string ('') is not an allowed value. "
                             "Use '0.0.0.0' instead to listen on all active "
                             "interfaces (INADDR_ANY).")
        self._socket_host = value
    socket_host = property(_get_socket_host, _set_socket_host,
        doc="""The hostname or IP address on which to listen for connections.

        Host values may be any IPv4 or IPv6 address, or any valid hostname.
        The string 'localhost' is a synonym for '127.0.0.1' (or '::1', if
        your hosts file prefers IPv6). The string '0.0.0.0' is a special
        IPv4 entry meaning "any active interface" (INADDR_ANY), and '::'
        is the similar IN6ADDR_ANY for IPv6. The empty string or None are
        not allowed.""")

    socket_file = None
    """If given, the name of the UNIX socket to use instead of TCP/IP.

    When this option is not None, the `socket_host` and `socket_port` options
    are ignored."""

    socket_queue_size = 5
    """The 'backlog' argument to socket.listen(); specifies the maximum number
    of queued connections (default 5)."""

    socket_timeout = 10
    """The timeout in seconds for accepted connections (default 10)."""

    shutdown_timeout = 5
    """The time to wait for HTTP worker threads to clean up."""

    protocol_version = 'HTTP/1.1'
    """The version string to write in the Status-Line of all HTTP responses,
    for example, "HTTP/1.1" (the default). Depending on the HTTP server used,
    this should also limit the supported features used in the response."""

    thread_pool = 10
    """The number of worker threads to start up in the pool."""

    thread_pool_max = -1
    """The maximum size of the worker-thread pool. Use -1 to indicate no limit."""

    max_request_header_size = 500 * 1024
    """The maximum number of bytes allowable in the request headers. If exceeded,
    the HTTP server should return "413 Request Entity Too Large"."""

    max_request_body_size = 100 * 1024 * 1024
    """The maximum number of bytes allowable in the request body. If exceeded,
    the HTTP server should return "413 Request Entity Too Large"."""

    instance = None
    """If not None, this should be an HTTP server instance (such as
    CPWSGIServer) which cherrypy.server will control. Use this when you need
    more control over object instantiation than is available in the various
    configuration options."""

    ssl_context = None
    """When using PyOpenSSL, an instance of SSL.Context."""

    ssl_certificate = None
    """The filename of the SSL certificate to use."""

    ssl_certificate_chain = None
    """When using PyOpenSSL, the certificate chain to pass to
    Context.load_verify_locations."""

    ssl_private_key = None
    """The filename of the private key to use with SSL."""

    if py3k:
        ssl_module = 'builtin'
        """The name of a registered SSL adaptation module to use with the builtin
        WSGI server. Builtin options are: 'builtin' (to use the SSL library built
        into recent versions of Python). You may also register your
        own classes in the wsgiserver.ssl_adapters dict."""
    else:
        ssl_module = 'pyopenssl'
        """The name of a registered SSL adaptation module to use with the builtin
        WSGI server. Builtin options are 'builtin' (to use the SSL library built
        into recent versions of Python) and 'pyopenssl' (to use the PyOpenSSL
        project, which you must install separately). You may also register your
        own classes in the wsgiserver.ssl_adapters dict."""

    statistics = False
    """Turns statistics-gathering on or off for aware HTTP servers."""

    nodelay = True
    """If True (the default since 3.1), sets the TCP_NODELAY socket option."""

    wsgi_version = (1, 0)
    """The WSGI version tuple to use with the builtin WSGI server.
    The provided options are (1, 0) [which includes support for PEP 3333,
    which declares it covers WSGI version 1.0.1 but still mandates the
    wsgi.version (1, 0)] and ('u', 0), an experimental unicode version.
    You may create and register your own experimental versions of the WSGI
    protocol by adding custom classes to the wsgiserver.wsgi_gateways dict."""

    def __init__(self):
        self.bus = cherrypy.engine
        self.httpserver = None
        self.interrupt = None
        self.running = False

    def httpserver_from_self(self, httpserver=None):
        """Return a (httpserver, bind_addr) pair based on self attributes."""
        if httpserver is None:
            httpserver = self.instance
        if httpserver is None:
            from cherrypy import _cpwsgi_server
            httpserver = _cpwsgi_server.CPWSGIServer(self)
        if isinstance(httpserver, basestring):
            # Is anyone using this? Can I add an arg?
            httpserver = attributes(httpserver)(self)
        return httpserver, self.bind_addr

    def start(self):
        """Start the HTTP server."""
        if not self.httpserver:
            self.httpserver, self.bind_addr = self.httpserver_from_self()
        ServerAdapter.start(self)
    start.priority = 75

    def _get_bind_addr(self):
        if self.socket_file:
            return self.socket_file
        if self.socket_host is None and self.socket_port is None:
            return None
        return (self.socket_host, self.socket_port)
    def _set_bind_addr(self, value):
        if value is None:
            self.socket_file = None
            self.socket_host = None
            self.socket_port = None
        elif isinstance(value, basestring):
            self.socket_file = value
            self.socket_host = None
            self.socket_port = None
        else:
            try:
                self.socket_host, self.socket_port = value
                self.socket_file = None
            except ValueError:
                raise ValueError("bind_addr must be a (host, port) tuple "
                                 "(for TCP sockets) or a string (for Unix "
                                 "domain sockets), not %r" % value)
    bind_addr = property(_get_bind_addr, _set_bind_addr,
        doc='A (host, port) tuple for TCP sockets or a str for Unix domain sockets.')

    def base(self):
        """Return the base (scheme://host[:port] or sock file) for this server."""
        if self.socket_file:
            return self.socket_file

        host = self.socket_host
        if host in ('0.0.0.0', '::'):
            # 0.0.0.0 is INADDR_ANY and :: is IN6ADDR_ANY.
            # Look up the host name, which should be the
            # safest thing to spit out in a URL.
            import socket
            host = socket.gethostname()

        port = self.socket_port

        if self.ssl_certificate:
            scheme = "https"
            if port != 443:
                host += ":%s" % port
        else:
            scheme = "http"
            if port != 80:
                host += ":%s" % port

        return "%s://%s" % (scheme, host)


text:
package org.carlspring.strongbox.storage.routing;

/**
 * @author Przemyslaw Fusik
 */
public interface RepositoryIdentifiable
{
    String getStorageId();

    String getRepositoryId();

    String getStorageIdAndRepositoryId();
}