text:
package org.jasig.portal.portlet.dao.jpa;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.Validate;
import org.jasig.portal.jpa.BasePortalJpaDao;
import org.jasig.portal.jpa.OpenEntityManager;
import org.jasig.portal.portlet.dao.IMarketplaceRatingDao;
import org.jasig.portal.portlet.dao.IPortletDefinitionDao;
import org.jasig.portal.portlet.om.IPortletDefinition;
import org.jasig.portal.portlet.marketplace.IMarketplaceRating;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import com.google.common.base.Function;

@Repository("marketplaceRatingDAO")
@Qualifier("persistence")
public class JpaMarketplaceRatingDao extends BasePortalJpaDao implements IMarketplaceRatingDao{

    private IPortletDefinitionDao portletDefinitionDao;

    @Autowired
    public void getPortletDefinitionDao(IPortletDefinitionDao dao) {
        this.portletDefinitionDao = dao;
    }

    private CriteriaQuery<MarketplaceRatingImpl> findAllMarketPlaceRating;

    @Override
    public void afterPropertiesSet() throws Exception{
        this.findAllMarketPlaceRating = this.createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<MarketplaceRatingImpl>>(){
            @Override
            public CriteriaQuery<MarketplaceRatingImpl> apply(CriteriaBuilder input) {
                final CriteriaQuery<MarketplaceRatingImpl> criteriaQuery = input.createQuery(MarketplaceRatingImpl.class);
                final Root<MarketplaceRatingImpl> definitionRoot = criteriaQuery.from(MarketplaceRatingImpl.class);
                criteriaQuery.select(definitionRoot);
                return criteriaQuery;
            }
        });
    }

    /**
     * This method will either create a new rating or update an
     * existing rating
     *
     * @param  Must not be null
     * @return the attached entity
     *
     */
    @Override
    @PortalTransactional
    public IMarketplaceRating createOrUpdateRating(IMarketplaceRating marketplaceRatingImplementation){
        Validate.notNull(marketplaceRatingImplementation, "MarketplaceRatingImpl must not be null");
        final EntityManager entityManager = this.getEntityManager();
        IMarketplaceRating temp = this.getRating(marketplaceRatingImplementation.getMarketplaceRatingPK());
        if(!entityManager.contains(marketplaceRatingImplementation) && temp!=null){
            //Entity is not managed and there is a rating for this portlet/user - update needed
            temp = entityManager.merge(marketplaceRatingImplementation);
        }else{
            //Entity is either already managed or doesn't exist - create needed
            temp = marketplaceRatingImplementation;
        }
        entityManager.persist(temp);
        return temp;
    }

    @Override
    @PortalTransactional
    public IMarketplaceRating createOrUpdateRating(int rating, String userName, String review,
            IPortletDefinition portletDefinition) {
        MarketplaceRatingImpl temp = new MarketplaceRatingImpl();
        PortletDefinitionImpl tempPortlet = new PortletDefinitionImpl(portletDefinition.getType(), portletDefinition.getFName(), portletDefinition.getName(),
                portletDefinition.getTitle(), portletDefinition.getPortletDescriptorKey().getWebAppName(), portletDefinition.getPortletDescriptorKey().getPortletName(),
                portletDefinition.getPortletDescriptorKey().isFrameworkPortlet(), portletDefinition.getPortletDefinitionId());
        MarketplaceRatingPK tempPK = new MarketplaceRatingPK(userName, tempPortlet);
        temp.setMarketplaceRatingPK(tempPK);
        temp.setRating(rating);
        temp.setReview(review);
        return this.createOrUpdateRating(temp);
    }

    /**
     * @return List of all ratings
     */
    @Override
    @PortalTransactionalReadOnly
    @OpenEntityManager(unitName = PERSISTENCE_UNIT_NAME)
    public Set<IMarketplaceRating> getAllRatings(){
        final TypedQuery<MarketplaceRatingImpl> query = this.createCachedQuery(this.findAllMarketPlaceRating);
        return new HashSet<IMarketplaceRating>(query.getResultList());
    }

    @Override
    @PortalTransactional
    public IMarketplaceRating getRating(String userName, IPortletDefinition portletDefinition) {
        PortletDefinitionImpl tempPortlet = new PortletDefinitionImpl(portletDefinition.getType(), portletDefinition.getFName(), portletDefinition.getName(),
                portletDefinition.getTitle(), portletDefinition.getPortletDescriptorKey().getWebAppName(), portletDefinition.getPortletDescriptorKey().getPortletName(),
                portletDefinition.getPortletDescriptorKey().isFrameworkPortlet(), portletDefinition.getPortletDefinitionId());
        MarketplaceRatingPK tempPK = new MarketplaceRatingPK(userName, tempPortlet);
        return this.getRating(tempPK);
    }

    /**
     * @param marketplaceRatingPK the primary key of the entity you want
     * @return an attached entity if found, null otherwise
     */
    @PortalTransactionalReadOnly
    @OpenEntityManager(unitName = PERSISTENCE_UNIT_NAME)
    public IMarketplaceRating getRating(MarketplaceRatingPK marketplaceRatingPK) {
        final MarketplaceRatingPK tempRatingPK = marketplaceRatingPK;
        MarketplaceRatingImpl temp = new MarketplaceRatingImpl();
        temp.setMarketplaceRatingPK(marketplaceRatingPK);
        final EntityManager entityManager = this.getEntityManager();
        if(entityManager.contains(temp)){
            temp = entityManager.merge(temp);
            return temp;
        }else{
            final TypedQuery<MarketplaceRatingImpl> query = this.createQuery(
            this.createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<MarketplaceRatingImpl>>(){
                @Override
                public CriteriaQuery<MarketplaceRatingImpl> apply(CriteriaBuilder input) {
                    final CriteriaQuery<MarketplaceRatingImpl> criteriaQuery = input.createQuery(MarketplaceRatingImpl.class);
                    final Root<MarketplaceRatingImpl> definitionRoot = criteriaQuery.from(MarketplaceRatingImpl.class);
                    Predicate conditionUser = input.equal(definitionRoot.get("marketplaceRatingPK").get("userName"), tempRatingPK.getUserName());
                    Predicate conditionPortlet = input.equal(definitionRoot.get("marketplaceRatingPK").get("portletDefinition"), tempRatingPK.getPortletDefinition());
                    Predicate allConditions = input.and(conditionPortlet, conditionUser);
                    criteriaQuery.where(allConditions);
                    return criteriaQuery;
                }
            }));
            List<MarketplaceRatingImpl> results = query.getResultList();
            if(!results.isEmpty()){
                return results.get(0);
            }else{
                return null;
            }
        }
    }

    /**
     * @param entity to delete - can not be null
     */
    @Override
    @PortalTransactional
    public void deleteRating(IMarketplaceRating marketplaceRatingImplementation){
        Validate.notNull(marketplaceRatingImplementation, "ratingPK can not be null");
        final IMarketplaceRating persistantMarketplaceRatingImpl;
        final EntityManager entityManager = this.getEntityManager();
        if(entityManager.contains(marketplaceRatingImplementation)){
            persistantMarketplaceRatingImpl=marketplaceRatingImplementation;
        }else{
            persistantMarketplaceRatingImpl=entityManager.merge(marketplaceRatingImplementation);
        }
        entityManager.remove(persistantMarketplaceRatingImpl);
    }

    @Override
    @PortalTransactional
    public void aggregateMarketplaceRating() {
        //setup
        EntityManager em = this.getEntityManager();

        //get list of average ratings
        Query aggregatedQuery = em.createQuery("SELECT AVG(m.rating) as rating, "
                                             + "       count(m.marketplaceRatingPK.portletDefinition.internalPortletDefinitionId) as theCount, "
                                             + "       m.marketplaceRatingPK.portletDefinition.internalPortletDefinitionId as portletId "
                                             + "  FROM MarketplaceRatingImpl m "
                                             + " GROUP BY m.marketplaceRatingPK.portletDefinition.internalPortletDefinitionId");

        List<Object[]> aggregatedResults = aggregatedQuery.getResultList();

        //update the portlet definition with the average rating
        for(Object[] result : aggregatedResults) {
            if(result != null && result.length == 3) {
                try {
                    Double averageRating = (Double)result[0];
                    Long usersRated = (Long)result[1];
                    String portletId = ((Long)result[2]).toString();

                    IPortletDefinition portletDefinition = portletDefinitionDao.getPortletDefinition(portletId);
                    if(portletDefinition != null) {
                        portletDefinition.setRating(averageRating);
                        portletDefinition.setUsersRated(usersRated);
                        em.persist(portletDefinition);
                    }
                } catch (Exception ex) {
                    logger.warn("Issue aggregating portlet ratings, recoverable",ex);
                }
            }

        }
    }
}


text:
package org.osgi.test.cases.typedevent.junit;

import static org.assertj.core.api.Assertions.assertThat;
import static org.osgi.namespace.implementation.ImplementationNamespace.*;
import static org.osgi.namespace.service.ServiceNamespace.*;
import static org.osgi.resource.Namespace.CAPABILITY_USES_DIRECTIVE;
import static org.osgi.service.typedevent.TypedEventConstants.*;

import java.util.Arrays;
import java.util.List;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.Version;
import org.osgi.framework.wiring.BundleCapability;
import org.osgi.framework.wiring.BundleWiring;
import org.osgi.service.typedevent.TypedEventBus;
import org.osgi.service.typedevent.monitor.TypedEventMonitor;
import org.osgi.test.common.annotation.InjectBundleContext;
import org.osgi.test.junit5.context.BundleContextExtension;
import org.osgi.test.junit5.service.ServiceExtension;

@ExtendWith(BundleContextExtension.class)
@ExtendWith(ServiceExtension.class)
public class TypedEventCapabilityTestCase {

	@InjectBundleContext
	BundleContext ctx;

	@ParameterizedTest
	@ValueSource(classes = {
			TypedEventBus.class, TypedEventMonitor.class
	})
	public void test_service_capability(Class< ? > clz) {

		String className = clz.getName();

		ServiceReference< ? > ref = ctx.getServiceReference(clz);

		assertThat(ref).isNotNull();

		BundleWiring wiring = ref.getBundle().adapt(BundleWiring.class);

		@SuppressWarnings("unchecked")
		BundleCapability cap = wiring.getCapabilities(SERVICE_NAMESPACE)
				.stream()
				.filter(c -> ((List<String>) c.getAttributes()
						.get(CAPABILITY_OBJECTCLASS_ATTRIBUTE))
								.contains(className))
				.findFirst()
				.orElse(null);

		assertThat(cap).isNotNull();

		assertThat(cap.getDirectives().get(CAPABILITY_USES_DIRECTIVE))
				.isEqualTo(clz.getPackage().getName());
	}

	@Test
	public void test_implementation_capability() {

		BundleCapability implCap = Arrays.stream(ctx.getBundles())
				.map(b -> b.adapt(BundleWiring.class))
				.filter(bw -> bw != null)
				.map(bw -> bw.getCapabilities(IMPLEMENTATION_NAMESPACE))
				.flatMap(lbc -> lbc.stream()
						.filter(bc -> TYPED_EVENT_IMPLEMENTATION
								.equals(bc.getAttributes()
										.get(IMPLEMENTATION_NAMESPACE))))
				.findFirst()
				.orElse(null);

		assertThat(implCap).isNotNull();

		assertThat(implCap.getDirectives().get(CAPABILITY_USES_DIRECTIVE))
				.isEqualTo(TypedEventBus.class.getPackage().getName());

		assertThat(implCap.getAttributes().get(CAPABILITY_VERSION_ATTRIBUTE))
				.isEqualTo(Version
						.parseVersion(TYPED_EVENT_SPECIFICATION_VERSION));
	}

}

redpajama_set_name: RedPajamaGithub


text:
/**
 * Test dependencies
 */

var util = require('util');
var assert = require('assert');
var socketHelper = require('./helpers/socketHelper.js');
var appHelper = require('./helpers/appHelper');
var httpHelper = require('./helpers/httpHelper');

/**
 * Errors
 */
var Err = {
  badResponse: function(response) {
    return 'Wrong server response!  Response :::\n' + util.inspect(response);
  }
};

describe('pubsub :: ', function() {

  var sailsprocess;
  var socket1;
  var socket2;
  var appName = 'testApp';

  describe('Model events', function() {

    before(function(done) {
      appHelper.build(appName, function(err) {
        if (err) {
          throw new Error(err);
        }
        socketHelper.writeModelConfig();
        appHelper.liftWithTwoSockets({
          silly: false
        }, function(err, sails, _socket1, _socket2) {
          if (err) {
            throw new Error(err);
          }
          sailsprocess = sails;
          socket1 = _socket1;
          socket2 = _socket2;

          httpHelper.testRoute('get', 'user/create?name=joe', function(err) {
            if (err) {
              return done(err);
            }
            httpHelper.testRoute('get', 'user/create?name=abby', function(err) {
              if (err) {
                return done(err);
              }
              done();
            });
          });

        });
      });
    });

    after(function(done) {

      process.chdir('../');
      appHelper.teardown();
      if (sailsprocess) {
        return sailsprocess.lower(function() {
          setTimeout(done, 100);
        });
      }
      return done();
    });

    describe('when a model no default autosubscribe contexts ', function() {

      after(function(done) {
        socket1.disconnect();
        socket2.disconnect();
        done();
      });

      afterEach(function(done) {
        socket1.removeAllListeners();
        socket2.removeAllListeners();
        done();
      });

      it('updating an instance via put should not result in any socket messages being received', function(done) {

        this.slow(3000);
        socket2.on('user', function(message) {
          assert(false, 'User event received by socket 2 when it should not have been!');
        });
        socket1.put('/user/1', {
          name: 'scott'
        });
        setTimeout(done, 1000);

      });

      describe('after subscribing to the update context', function() {
        before(function(done) {
          socket2.get('/user/subscribe?id=1&context=update', done);
        });
        it('updating an record via put should result in the correct socket messages being received', function(done) {
          var tookTooLong;
          var triggeredSocketEvent;

          var TIME_TO_WAIT = 1500;
          var timer = setTimeout(function() {
            tookTooLong = true;
            done(new Error('`update` event was not fired in a timely manner (probably was never going to happen.)  Waited ' + TIME_TO_WAIT + 'ms.'));
          }, TIME_TO_WAIT);
          socket2.on('user', function(message) {
            clearTimeout(timer);
            try {
              assert(message.id == 1 && message.verb === 'updated' && message.data.name === 'bob', Err.badResponse(message));
            }
            catch (e) { return done(e); }

            if (tookTooLong) { return; }
            if (triggeredSocketEvent) {
              return done(new Error('Socket event should not fire more than once!'));
            }
            else {
              triggeredSocketEvent = true;
              return done();
            }
          });
          socket1.put('/user/1', {
            name: 'bob'
          });
        });
      });

      it('sending a message should not result in any socket messages being received', function(done) {

        this.slow(3000);
        socket2.on('user', function(message) {
          assert(false, 'User event received by socket 2 when it should not have been!');
        });
        socket1.get('/user/message');
        setTimeout(done, 1000);

      });

      describe('after subscribing to the message context', function() {
        before(function(done) {
          socket2.get('/user/subscribe?id=1&context=message', function() {
            done();
          });
        });
        it('sending a message should result in a correct socket messages being received', function(done) {
          socket2.on('user', function(message) {
            assert(message.id == 1 && message.verb == 'messaged' && message.data.greeting == 'hello', Err.badResponse(message));
            done();
          });
          socket1.get('/user/message');
        });
      });

      it('adding a pet to the user should not result in any socket messages being received', function(done) {

        this.slow(3000);
        socket2.on('user', function(message) {
          assert(false, 'User event received by socket 2 when it should not have been!');
        });
        socket1.post('/pet', {
          name: 'rex',
          owner: 1
        });
        setTimeout(done, 1000);

      });

      describe('after subscribing to the add:pets context', function() {
        before(function(done) {
          socket2.get('/user/subscribe?id=1&context=add:pets', function() {
            done();
          });
        });
        it('adding a pet should result in a correct socket messages being received', function(done) {
          socket2.on('user', function(message) {
            assert(message.id == 1 && message.verb == 'addedTo' && message.attribute == 'pets' && message.addedId == 2, Err.badResponse(message));
            done();
          });
          socket1.post('/pet', {
            name: 'alice',
            owner: 1
          });
        });
      });

      it('removing a pet from the user should not result in any socket messages being received', function(done) {

        this.slow(3000);
        socket2.on('user', function(message) {
          assert(false, 'User event received by socket 2 when it should not have been!');
        });
        socket1.delete('/pet', {
          id: 1
        });
        setTimeout(done, 1000);

      });

      describe('after subscribing to the remove:pets context', function() {
        before(function(done) {
          socket2.get('/user/subscribe?id=1&context=remove:pets', function() {
            done();
          });
        });
        it('removing a pet should result in a correct socket messages being received', function(done) {
          socket2.on('user', function(message) {
            assert(message.id == 1 && message.verb == 'removedFrom' && message.attribute == 'pets' && message.removedId == 2, Err.badResponse(message));
            done();
          });
          socket1.delete('/pet', {
            id: 2
          });
        });
      });

      it('deleting a user should not result in any socket messages being received', function(done) {

        this.slow(3000);
        socket2.on('user', function(message) {
          assert(false, 'User event received by socket 2 when it should not have been!');
        });
        socket1.delete('/user', {
          id: 2
        });
        setTimeout(done, 1000);

      });

      describe('after subscribing to the destroy context', function() {
        before(function(done) {
          socket2.get('/user/subscribe?id=1&context=destroy', function() {
            done();
          });
        });
        it('deleting a user should result in a correct socket messages being received', function(done) {
          socket2.on('user', function(message) {
            assert(message.id == 1 && message.verb == 'destroyed', Err.badResponse(message));
            done();
          });
          socket1.delete('/user', {
            id: 1
          });
        });
      });
    });

  });
});


text:
namespace _07_DirectoryTraversal
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;

    class StartUp
    {
        static void Main()
        {
            var allFiles = Directory.GetFiles(@"D:\SoftUni\05-Csharp Advanced\08-EXERCISE STREAMS\HomeWorkResults").ToList();

            var resultCollection = new Dictionary<string, Dictionary<string, double>>();

            foreach (var file in allFiles)
            {
                var info = new FileInfo(file);
                var extention = info.Extension;
                var name = info.Name;
                double size = info.Length/1024d;

                if (resultCollection.ContainsKey(extention))
                {
                    resultCollection[extention].Add(name, size);
                }
                else
                {
                    resultCollection[extention] = new Dictionary<string, double>();
                    resultCollection[extention].Add(name, size);
                }
            }

            var reportPath = @"D:\SoftUni\05-Csharp Advanced\08-EXERCISE STREAMS\HomeWorkResults\07-DirectoryTraversal-Report.txt";
            File.Delete(reportPath);
            foreach (var file in resultCollection.OrderByDescending(x=>x.Value.Count()).ThenBy(x=>x.Key))
            {
                File.AppendAllText(reportPath, $"{file.Key}{Environment.NewLine}");

                foreach (var fileName  in file.Value.OrderBy(x=>x.Value))
                {
                    File.AppendAllText(reportPath, $"--{fileName.Key} - {fileName.Value:f3}kb{Environment.NewLine}");
                }
            }

        }
    }
}


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

namespace SpecialNumbersLab
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());

            for (int num = 1; num <= n; num++)
            {
                int sumOfDigits = 0;
                int lastDigit = num;
                while (lastDigit > 0)
                {
                    sumOfDigits += lastDigit % 10;
                    lastDigit = lastDigit / 10;
                }
                bool special = (sumOfDigits == 5) || (sumOfDigits == 7) || (sumOfDigits == 11);
                Console.WriteLine("{0} -> {1}",num,special);
            }
        }
    }
}


text:
CONTACT INFORMATION

            <address>
                BrEAST operational office

                Institut Jules Bordet

                Boulevard de Waterloo, 121 (7th floor)

                1000 Brussels

                P:+32 2 541 35 09
            </address>

            <address>
                Translational coordinator

                breast.translational@bordet.be
            </address>

            <address>
            Technical information

                breast.technical@bordet.be
            </address>


text:
Supercollider can generate a list of search results from the pages and documentation items it processes. This list is output as a JSON file, which can be fed to a search library like [Bloodhound](https://github.com/twitter/typeahead.js/blob/master/doc/bloodhound.md).

To create the result list, Supercollider gives each *page* its own result item, and also every documented *item* within each page a result as well. So, for example, given a page `button.md` with two documented Sass variables, you'll get three total results: one for the button page itself, and two for each of the button's variables.

### Usage

Search result generation should only happen when Supercollider is done processing. You can listen to the `finish` event on the stream the plugin creates to know when it's ready.

```js
Super.init().on('finish', function() {
  Super.buildSearch('_build/data/search.json');
});
```

The `.buildSearch()` function takes two parameters: a path to the file to write, and an optional callback to run when the file is written to disk.

### Configuration

Search-specific settings are set with the `.searchConfig()` method. It takes an object of settings:

- **extra** (String): file path to a JSON or YML file with an array of search results. These will be loaded and added as-is to the search result list.
- **pageTypes** (Object): definitions for custom page types. Each key is a type label, and the value is a function that determines if the label should be applied to a page.
- **sort** (Array): an array of strings representing sort criteria. The results list can be sorted by the `type` property on each result.

```js
Super.searchConfig({
  // The contents of this file will be added to the final results
  extra: 'src/assets/search.yml',
  // Sort search results so pages always appear first in the list
  sort: ['page', 'component', 'sass variable', 'sass mixin', 'sass function']
})
```

### Result Format

The final search result file is an array of objects with this format:

```js
{
  // Title of the result (derived from the item's name)
  name: 'Button',
  // Result type (used for sorting)
  type: 'page',
  // Description (derived from the item's description field)
  description: 'Buttons are a swell UI component.',
  // Link to the item (should be used by a search plugin to direct the user)
  link: 'button.html',
  // Aliases for the page (can be used by a search plugin to fuzzy search)
  tags: ['btn']
}
```

All of these fields are generated from existing data. For example, given a Sass variable with this documentation:

```scss
/// Background color of a button.
/// @type Color
$button-background: dodgerblue;
```

We get a search result of this format:

```js
{
  name: '$button-background',
  type: 'sass variable',
  description: 'Background color of a button.',
  link: 'button.html#sass-variables'
}
```


text:
package org.assertj.core.api.bytearray;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.MockitoAnnotations.initMocks;

import java.util.Comparator;

import org.assertj.core.api.ByteArrayAssert;
import org.assertj.core.api.ByteArrayAssertBaseTest;
import org.assertj.core.internal.ByteArrays;
import org.assertj.core.internal.Objects;
import org.junit.Before;
import org.mockito.Mock;

/**
 * Tests for <code>{@link ByteArrayAssert#usingDefaultElementComparator()}</code>.
 *
 * @author Joel Costigliola
 * @author Mikhail Mazursky
 */
public class ByteArrayAssert_usingDefaultElementComparator_Test extends ByteArrayAssertBaseTest {

  @Mock
  private Comparator<Byte> comparator;

  private Objects objectsBefore;

  @Before
  public void before() {
    initMocks(this);
    objectsBefore = getObjects(assertions);
    assertions.usingElementComparator(comparator);
  }

  @Override
  protected ByteArrayAssert invoke_api_method() {
    return assertions.usingDefaultElementComparator();
  }

  @Override
  protected void verify_internal_effects() {
    assertThat(objectsBefore).isSameAs(getObjects(assertions));
    assertThat(ByteArrays.instance()).isSameAs(getArrays(assertions));
  }
}


text:
package com.kit.utils;

import android.content.Context;

/**
 *
 * @ClassName ResUtils
 * @Description 获取资源文件的工具类
 * @author Zhao laozhao1005@gmail.com
 * @date 2014-7-24 下午12:55:00
 *
 */
public class ResUtils {

	public static String getText4ResStringArray(Context context, int intR) {
		String[] hibernate_copy = context.getResources().getStringArray(intR);
		String textStr = (String) ArrayUtils.getOne(hibernate_copy);
		return textStr;

	}
}


text:
/*global OO */
( function ( mw, $ ) {
	/**
	 * Factory for MessagePoster objects. This provides a pluggable to way to script the action
	 * of adding a message to someone's talk page.
	 *
	 * @class mw.messagePoster.factory
	 * @singleton
	 */
	function MessagePosterFactory() {
		this.contentModelToClass = {};
	}

	OO.initClass( MessagePosterFactory );

	// Note: This registration scheme is currently not compatible with LQT, since that doesn't
	// have its own content model, just islqttalkpage. LQT pages will be passed to the wikitext
	// MessagePoster.
	/**
	 * Register a MessagePoster subclass for a given content model.
	 *
	 * @param {string} contentModel Content model of pages this MessagePoster can post to
	 * @param {Function} constructor Constructor of a MessagePoster subclass
	 */
	MessagePosterFactory.prototype.register = function ( contentModel, constructor ) {
		if ( this.contentModelToClass[ contentModel ] !== undefined ) {
			throw new Error( 'Content model "' + contentModel + '" is already registered' );
		}

		this.contentModelToClass[ contentModel ] = constructor;
	};

	/**
	 * Unregister a given content model.
	 * This is exposed for testing and should not normally be used.
	 *
	 * @param {string} contentModel Content model to unregister
	 */
	MessagePosterFactory.prototype.unregister = function ( contentModel ) {
		delete this.contentModelToClass[ contentModel ];
	};

	/**
	 * Create a MessagePoster for given a title.
	 *
	 * A promise for this is returned. It works by determining the content model, then loading
	 * the corresponding module (which registers the MessagePoster class), and finally constructing
	 * an object for the given title.
	 *
	 * This does not require the message and should be called as soon as possible, so that the
	 * API and ResourceLoader requests run in the background.
	 *
	 * @param {mw.Title} title Title that will be posted to
	 * @param {string} [apiUrl] api.php URL if the title is on another wiki
	 * @return {jQuery.Promise} Promise resolving to a mw.messagePoster.MessagePoster.
	 *   For failure, rejected with up to three arguments:
	 *
	 *   - errorCode Error code string
	 *   - error Error explanation
	 *   - details Further error details
	 */
	MessagePosterFactory.prototype.create = function ( title, apiUrl ) {
		var factory = this,
			api = apiUrl ? new mw.ForeignApi( apiUrl ) : new mw.Api();

		return api.get( {
			action: 'query',
			prop: 'info',
			indexpageids: true,
			titles: title.getPrefixedDb()
		} ).then( function ( data ) {
			var pageId, page, contentModel, moduleName;
			if ( !data.query.pageids[ 0 ] ) {
				return $.Deferred().reject( 'unexpected-response', 'Unexpected API response' );
			}
			pageId = data.query.pageids[ 0 ];
			page = data.query.pages[ pageId ];

			contentModel = page.contentmodel;
			moduleName = 'mediawiki.messagePoster.' + contentModel;
			return mw.loader.using( moduleName ).then( function () {
				return factory.createForContentModel(
					contentModel,
					title,
					api
				);
			}, function () {
				return $.Deferred().reject( 'failed-to-load-module', 'Failed to load "' + moduleName + '"' );
			} );
		}, function ( error, details ) {
			return $.Deferred().reject( 'content-model-query-failed', error, details );
		} );
	};

	/**
	 * Creates a MessagePoster instance, given a title and content model
	 *
	 * @private
	 * @param {string} contentModel Content model of title
	 * @param {mw.Title} title Title being posted to
	 * @param {mw.Api} api mw.Api instance that the instance should use
	 * @return {mw.messagePoster.MessagePoster}
	 *
	 */
	MessagePosterFactory.prototype.createForContentModel = function ( contentModel, title, api ) {
		return new this.contentModelToClass[ contentModel ]( title, api );
	};

	mw.messagePoster = {
		factory: new MessagePosterFactory()
	};
}( mediaWiki, jQuery ) );


text:
'use strict';

const boom = require('boom');
const config = require('config');
const casCookieUtils = require('../../../utils/cas-cookie-utils.js');
const joi = require('joi');
const _ = require('lodash');
const proxy = require('../../../utils/proxy.js');

const baseUrl = '/keys';

const internals = {};

internals.credentialSchema = joi.object().keys({
    username: joi.string().required(),
    user: require('../../../controllers/users.js').userSchema,
    id: joi.string().required(),
    key: joi.string().required(),
    algorithm: joi.string().required(),
    issueTime: joi.number().required(),
    expireTime: joi.number().required(),
    studyRoles: joi.object().required()
});

internals.logOutSuccessObj = {
    message:'You are logged out.'
};

const postExample = [
    '
',
        'JSON.stringify({',
            '\tusername: btoa(\'your-username\'),',
            '\tpassword: btoa(\'your-password\'),',
        '})',
    '
',
].join('\n');

exports.register = function(server, options, next) {
    // Private route to get new hawk credentials
    // Requests must authenticate with a username and password
    const redisClient =  server.plugins['hapi-redis'].client;
    const authUtils = server.plugins.utilities.auth;
    const invalidCookie = casCookieUtils.invalidate();

    const LoginRecord = server.plugins.bookshelf.model('LoginRecord');

    server.state(casCookieUtils.cookieName, {
        path: '/',
        domain: config.get('cookieDomain')
    });

    /**
     * save a new LoginRecord model with `properties`
     * @param {object} properties contains props to assign to
     * new LoginRecordObject before saving
     * @return {Promise}          resolves to result of save operation
     */
    const saveRecordObj = (properties)=> {
        return LoginRecord.forge(properties).save(null, { method:'insert' });
    };

    server.route({
        method: 'OPTIONS',
        path: baseUrl + '/{id}',
        config: {
            tags: ['api', 'auth'],
            plugins: {
                'hapi-swagger': { nickname: 'options' }
            },
            description: 'Preflight route always responds with 200',
            auth: false,
            handler: function(request, reply) {
                reply('Clear for takeoff');
            }
        }
    });

    server.route({
        method: 'POST',
        path: baseUrl,
        config: {
            tags: ['api', 'auth'],
            plugins: {
                'hapi-swagger': { nickname: 'post' }
            },
            notes: [
                'Expects base64 encoded username/password in payload.',
                'Response includes a `set-cookie` header with JWT for COINS2.0',
                'Try generating some example POST JSON with:',
                postExample,
            ].join('
'),
            description: 'Login: Get new API key and JWT cookie',
            auth: false,
            validate: {
                headers: true, //TODO: validate x-forwaded https header
                payload: {
                    username: joi.binary().encoding('base64').required(),
                    password: joi.binary().encoding('base64').required()
                }
            },
            response: {
                schema: internals.credentialSchema
            },
            handler: function(request, reply) {
                const data = request.payload;
                const username = data.username.toString();
                const password = data.password.toString();

                /**
                 * set recordObj attributes/values
                 */
                const  recordObj = {
                    username: data.username.toString(),
                    loginTime: new Date(),
                    ipAddr: proxy.getIpAddress(request),
                    errorCode: 0,
                    success: 1
                };

                /**
                 * log error and inserts record to db for login failure
                 */
                const handleError = (err)=> {
                    recordObj.success = 0;
                    saveRecordObj(recordObj);
                    reply(boom.wrap(err));
                };

                /**
                 * generate cookie from Hawk credentials
                 * save credentials to database
                 * reply with credentials and cookie
                 * @param  {object} credentials hawk credentials object
                 * @return {Promise}            resolves when creds are saved
                 */
                const serveHawkCredentials = (credentials) => {
                    const casCookie = casCookieUtils.generate(credentials);
                    const credentialsSaved = Promise.all([
                        redisClient.saddAsync(username, credentials.id),
                        redisClient.hmsetAsync(credentials.id, credentials)
                    ]);

                    return credentialsSaved
                        .then(() => {
                            reply(credentials)
                                .state(casCookieUtils.cookieName, casCookie);
                            return credentials;
                        });
                };

                return authUtils.validateUser(username, password)
                    .then(authUtils.generateHawkCredentials)
                    .then(serveHawkCredentials)
                    .then(_.noop)
                    .then(_.partial(saveRecordObj, recordObj))
                    .catch(handleError);
            }
        }
    });

    server.route({
        method: 'DELETE',
        path: baseUrl + '/{id}',
        config: {
            tags: ['api', 'auth'],
            plugins: {
                'hapi-swagger': { nickname: 'remove' }
            },
            validate: {
                params: {
                    id: joi.string().required()
                }
            },
            notes: [
                'Auth signature required. Must match key provided in url.',
                'A `set-cookie` header in response invalidates the JWT cookie.',
                'Possible Error codes:',
                '**404** The key does not exist on the server.',
                '**401** Failed to authenticate,',
                'or the `id param` and your HAWK signature do not match.'
            ].join('
'),
            description: 'Logout: Remove API key from auth DB',
            response: {
                schema: joi.compile(internals.logOutSuccessObj)
            },
            handler: (request, reply) => {
                const username = request.auth.credentials.username;
                const id = request.auth.credentials.id;
                const validateKeyToDelete = (hawkId, id) => {
                    const errMsg = 'Access to this key not allowed';
                    if (id !== hawkId) {
                        throw boom.unauthorized(errMsg);
                    }

                    return redisClient.existsAsync(id)
                        .then((exists) => {
                            if (!exists) {
                                throw boom.unauthorized('Could not locate key');
                            }

                            return exists;
                        });
                };

                /**
                 * delete the API keys witn `id` in closure
                 * @return {Promise} resolves to array of delete results
                 */
                const deleteKey = () => {
                    return Promise.all([
                        redisClient.del(id),
                        redisClient.srem(username, id)
                    ]);
                };

                /**
                 * reply with success message and new invalid cookie
                 * @return {object} response, or whatever reply() returns
                 */
                const replySuccess = () => {
                    return reply(internals.logOutSuccessObj)
                        .code(200)
                        .state(
                            casCookieUtils.cookieName,
                            invalidCookie
                        );
                };

                validateKeyToDelete(id, request.params.id)
                    .then(deleteKey)
                    .then(replySuccess)
                    .catch((err) => {
                        request.log(['error', 'logout'], err);
                        reply(boom.wrap(err));
                        return;
                    });

            }
        }
    });

    next();
};

exports.register.attributes = {
    name: 'login'
};


text:
/**
 * @file afile
 * @author Jim Bulkowski <jim.b@paperelectron.com>
 * @project magnum-plugin-utils
 * @license MIT {@link http://opensource.org/licenses/MIT}
 */

"use strict";


text:
$(document).ready(function(){

    var profile = [];
    var twitList = [];

    var getParentsFor = function(userId){

        jQuery.ajax({
            url: "http://api.dribbble.com/players/"+userId,
            async: false,
            jsonp: "callback",
            dataType: "jsonp",
            data: {
                format: "json"
            },

            success: function( response ) {

                var twUser = response.twitter_screen_name;
                var userFrom = response.location;

                (function() {
                    if (userFrom == null) {
                        userFrom = '';
                    }

                    profile.push(
                            '

' + response.name + '

' + userFrom + '

'
                    );

                    if (twUser == null) {
                        twUser = '';
                    } else {
                        twitList.push('@'+twUser);
                    }

                }());

                var parent = response.drafted_by_player_id;
                if (parent != null){
                    getParentsFor(parent);

                } else {
                    var html = [];
                    for (i=profile.length;i>=0;i--){
                        html.push(profile[i]);
                    }

                    twitList.splice(0, 1);
                    var twitTo = twitList.join(', ');
                    var tweet = 'Guys! You\'re my @Dribbble ansestors '+twitTo+' via goo.gl/lJXdYC #DribbbleGenealogy';

                    $('#playerProfile').html(html.join(''));
                    $('#playerProfile').slideDown(3000, 'swing');

                    $('#footer').addClass('footerAfterload');
                    $('#description').addClass('afterload');
                    $('#product p').hide();
                    $('#product #title').css('font-size', '1em');
                    $('#product #title').css('margin-top', '15px');
                    $('#product form').css('margin-top', '20px');
                    $('#share p').html(tweet);
                    $('#tweettext').html('Tweet it');
                    $('#share').delay(6000).slideDown(1000);
                    $('#tw').delay(8000).slideDown(600);

                    // now refresh the lists
                    profile = [];
                    twitList = [];
                }
            }
        });
    };

    $('#submit').click(function (e) {
        e.preventDefault();

        var user = $('#user').val();
        if (user !== "") {

            getParentsFor(user);
            $('#product span').hide();

        } else {
            $('#product span').html("Enter a Dribbble Player username!");
            $('#product span').css('color', 'rgba(255, 83, 150, 1)');
        }
    });

    $('#share #tw').mouseover(function() {
        $( this ).css( 'background-color', 'rgba(47, 47, 47, 0.98)' );
    });
    $('#share #tw').mouseleave(function() {
        $( this ).css( 'background-color', '#EEDF1E' );
    });
});


text:
package gobblin.security.ssl;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;

import org.apache.commons.io.FileUtils;

import com.typesafe.config.Config;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

import gobblin.password.PasswordManager;
import gobblin.util.ConfigUtils;

/**
 * Provide different approaches to create a {@link SSLContext}
 */
public class SSLContextFactory {
  public static final String KEY_STORE_FILE_PATH = "keyStoreFilePath";
  public static final String KEY_STORE_PASSWORD = "keyStorePassword";
  public static final String KEY_STORE_TYPE = "keyStoreType";
  public static final String TRUST_STORE_FILE_PATH = "trustStoreFilePath";
  public static final String TRUST_STORE_PASSWORD = "trustStorePassword";

  private static final String DEFAULT_ALGORITHM = "SunX509";
  private static final String DEFAULT_PROTOCOL = "TLS";
  private static final String JKS_STORE_TYPE_NAME = "JKS";
  private static final String P12_STORE_TYPE_NAME = "PKCS12";

  /**
   * Create a {@link SSLContext} instance
   *
   * @param keyStoreFile a p12 or jks file depending on key store type
   * @param keyStorePassword password to access the key store
   * @param keyStoreType type of key store
   * @param trustStoreFile a jks file
   * @param trustStorePassword password to access the trust store
   */
  public static SSLContext createInstance(File keyStoreFile, String keyStorePassword, String keyStoreType, File trustStoreFile,
      String trustStorePassword) {
    if (!keyStoreType.equalsIgnoreCase(P12_STORE_TYPE_NAME) && !keyStoreType.equalsIgnoreCase(JKS_STORE_TYPE_NAME)) {
      throw new IllegalArgumentException("Unsupported keyStoreType: " + keyStoreType);
    }

    try {
      // Load KeyStore
      KeyStore keyStore = KeyStore.getInstance(keyStoreType);
      keyStore.load(toInputStream(keyStoreFile), keyStorePassword.toCharArray());

      // Load TrustStore
      KeyStore trustStore = KeyStore.getInstance(JKS_STORE_TYPE_NAME);
      trustStore.load(toInputStream(trustStoreFile), trustStorePassword.toCharArray());

      // Set KeyManger from keyStore
      KeyManagerFactory kmf = KeyManagerFactory.getInstance(DEFAULT_ALGORITHM);
      kmf.init(keyStore, keyStorePassword.toCharArray());

      // Set TrustManager from trustStore
      TrustManagerFactory trustFact = TrustManagerFactory.getInstance(DEFAULT_ALGORITHM);
      trustFact.init(trustStore);

      // Set Context to TLS and initialize it
      SSLContext sslContext = SSLContext.getInstance(DEFAULT_PROTOCOL);
      sslContext.init(kmf.getKeyManagers(), trustFact.getTrustManagers(), null);

      return sslContext;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * Create a {@link SSLContext} from a {@link Config}
   *
   *

   *   A sample configuration is:
   *
 keyStoreFilePath=/path/to/key/store
   *
 keyStorePassword=password
   *
 keyStoreType=PKCS12
   *
 trustStoreFilePath=/path/to/trust/store
   *
 trustStorePassword=password
   *

   *
   * @param srcConfig configuration
   * @return an instance of {@link SSLContext}
   */
  public static SSLContext createInstance(Config srcConfig) {
    // srcConfig.getString() will throw ConfigException if any key is missing
    String keyStoreFilePath = srcConfig.getString(KEY_STORE_FILE_PATH);
    String trustStoreFilePath = srcConfig.getString(TRUST_STORE_FILE_PATH);
    PasswordManager passwdMgr = PasswordManager.getInstance(ConfigUtils.configToState(srcConfig));
    String keyStorePassword = passwdMgr.readPassword(srcConfig.getString(KEY_STORE_PASSWORD));
    String trustStorePassword = passwdMgr.readPassword(srcConfig.getString(TRUST_STORE_PASSWORD));

    return createInstance(new File(keyStoreFilePath), keyStorePassword, srcConfig.getString(KEY_STORE_TYPE),
        new File(trustStoreFilePath), trustStorePassword);
  }

  private static InputStream toInputStream(File storeFile)
      throws IOException {
    byte[] data = FileUtils.readFileToByteArray(storeFile);
    return new ByteArrayInputStream(data);
  }
}


text:
package org.apache.dubbo.remoting.etcd;

public interface RetryPolicy {

    /**
     * Whether retry is supported when operation fails.
     *
     * @param retried the number of times retried so far
     * @param elapsed the elapsed time in millisecond since the operation was attempted
     * @param sleep   should be sleep
     * @return true should be retry
     */
    public boolean shouldRetry(int retried, long elapsed, boolean sleep);

}


text: export { default } from './RegisterForm';


text:
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.ComponentModel;
using System.Threading;
using Microsoft.Phone.Shell;
using HtmlAgilityPack;

namespace Naboo.MitbbsReader
{
    public class BackgroundDownloader : INotifyPropertyChanged
    {
        private bool _isDownloading = false;
        public bool IsDownloading
        {
            get
            {
                return _isDownloading;
            }

            private set
            {
                _isDownloading = value;
                NotifyPropertyChanged("IsDownloading");
            }
        }

        private OfflineDownloadQueue _downloadQueue;
        private Timer _timer;
        private object _lock = new object();
        private volatile bool _stopped = false;

        TimeSpan _interval = new TimeSpan(0, 15, 00);
        TimeSpan _initInterval = new TimeSpan(0, 0, 30);

        public BackgroundDownloader()
        {
            _timer = new Timer(Download_Timer);

            IsDownloading = false;
        }

        public void StartTimer(bool startNow = true)
        {
            TimeSpan interval = _initInterval;

            if (startNow)
            {
                interval = TimeSpan.FromSeconds(0);
            }

            _stopped = false;
            _timer.Change((long)interval.TotalMilliseconds, Timeout.Infinite);
        }

        public void StopTimer()
        {
            _stopped = true;
            _timer.Change(Timeout.Infinite, Timeout.Infinite);
            Stop();
        }

        private void Download_Timer(object state)
        {
            lock (_lock)
            {
                if (!_stopped)
                {
                    TimeSpan interval = _initInterval;
                    try
                    {
                        if (AppUtil.AppInfo.IsNetworkConnected() && !App.WebSession.IsConnecting)
                        {
                            interval = _interval;
                            Start();
                        }
                    }
                    finally
                    {
                        if (!_stopped)
                        {
                            _timer.Change((long)interval.TotalMilliseconds, Timeout.Infinite);
                        }
                    }
                }
            }
        }

        public void Start()
        {
            lock (_lock)
            {
                if (IsDownloading)
                {
                    return;
                }

                if (_downloadQueue == null)
                {
                    _downloadQueue = new OfflineDownloadQueue();
                    _downloadQueue.DownloadCompleted += OfflineDownload_Completed;
                    _downloadQueue.ContentDownloadCompleted += OfflineContentDownload_Completed;
                }

                if (App.Settings.OfflineContentManager.DownloadQueue.Count > 0)
                {
                    DisableIdleDetection();

                    IsDownloading = true;

                    _downloadQueue.SetDownloadContents(App.Settings.OfflineContentManager.DownloadQueue);
                    _downloadQueue.StartDownload(App.WebSession.CreateWebClient(), null);
                }
            }
        }

        public void Stop()
        {
            lock (_lock)
            {
                if (_downloadQueue != null)
                {
                    _downloadQueue.Cancel();
                }

                IsDownloading = false;

                RestoreIdleDetection();
            }
        }

        private void OfflineContentDownload_Completed(object sender, OfflineDownloadQueue.DownloadQueueContentCompletedEventArgs e)
        {
            if (e.Success)
            {
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(
                    () =>
                    {
                        App.Settings.OfflineContentManager.MoveQueuedContentToIndex(e.Content);
                        App.Settings.SaveToStorage();
                    }
                    );
            }
            else
            {
                if (AppUtil.AppInfo.IsNetworkConnected())
                {
                    e.Content.Failed = true;

                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(
                        () =>
                        {
                            App.Settings.OfflineContentManager.MoveQueuedContentToIndex(e.Content);
                            App.Settings.SaveToStorage();
                        }
                        );

                }
                else
                {
                    e.Content.Failed = false;
                }
            }
        }

        private void OfflineDownload_Completed(object sender, DataLoadedEventArgs e)
        {
            lock (_lock)
            {
                IsDownloading = false;

                RestoreIdleDetection();

                StartTimer(true);
            }
        }

        private void DisableIdleDetection()
        {
            if (Naboo.AppUtil.AppInfo.IsWifiConnected())
            {
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
            }

#if !NODO
            if (Naboo.AppUtil.AppInfo.IsNetworkConnected())
            {
                PhoneApplicationService.Current.ApplicationIdleDetectionMode = IdleDetectionMode.Disabled;
            }
#endif
        }

        private void RestoreIdleDetection()
        {
            PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Enabled;
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected void NotifyPropertyChanged(String propertyName)
        {
            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(
                () =>
                {
                    PropertyChangedEventHandler handler = PropertyChanged;
                    if (null != handler)
                    {
                        handler(this, new PropertyChangedEventArgs(propertyName));
                    }
                }
                );
        }
    }
}


text:
package Button;

import java.awt.Point;
import java.util.ArrayList;

import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.geom.Rectangle;

import Action.ConditionEnum;
import GUI.RightPanel;

public class ConditionButton extends DraggableButton{
	public Rectangle addActionBox;
	public float addActionPadding = 0;
	public float paddingBeforeEnd;
	public float iniHeight;
	private boolean extended = false;
	public ListButton listConditions;
	public ListButton listOptions;
	private Rectangle optionZone;
	private Rectangle actionListZone;
	public ArrayList<DraggableButton> actionList = new  ArrayList<DraggableButton>();
	public ConditionButton(GameContainer gc, String name, float x, float y,
			float width, float height, String text,ArrayList<ButtonRender> listC, ArrayList<ButtonRender> listOptions) {
		super(gc, name, x, y, width, height, text);
		setTotalHeight(height*2);
		paddingBeforeEnd = 0;
		iniHeight = height;
		listC.add(new ButtonRender(gc, ConditionEnum.ATTEINT.getName(), x, y, width, height, ConditionEnum.ATTEINT.getText()));
		listC.add(new ButtonRender(gc, ConditionEnum.PAS_ATTEINT.getName(), x, y, width, height, ConditionEnum.PAS_ATTEINT.getText()));
		listOptions.add(new ButtonRender(gc, "W", x, y, width, height, "eau"));
		listOptions.add(new ButtonRender(gc, "1", x, y, width, height, "mur"));
		listConditions = new ListButton(gc, name, x+100, y, width, height, listC);
		this.listOptions = new ListButton(gc, name, x+100, y, width, height, listOptions);
	}
	public void draw(Graphics g){
		if(currentImage == null){
			g.setColor(borderColor);
			g.fillRect(getX(),getY(),width,iniHeight);
			g.setColor(mainColor);
			g.fillRect(getX()+borderSize,getY()+borderSize,width-(borderSize*2),iniHeight-(borderSize*2));
		}else{
			currentImage.draw(getX(), getY());
		}
		optionZone = new Rectangle(getX()+borderSize,getY()+borderSize,width-(borderSize*2),iniHeight-(borderSize*2));
		ttf.drawString(getX()+paddingTop, getY()+paddingLeft, text, textColor);
		//ttf.drawString(getX()+iniHeight/4,getY()+borderSize+paddingBeforeEnd, "fin tant que", textColor);

		float currentY = iniHeight+getY();
		float contentHeight = 0;
		for(DraggableButton action : actionList){
			action.setY(currentY);
			action.draw(g);
			currentY += action.calculateHeight();
			contentHeight += action.calculateHeight();
		}
		addActionBox = new Rectangle(getX()+borderSize,currentY  ,width-(borderSize*2),iniHeight-(borderSize*2)+addActionPadding);
		actionListZone = new Rectangle(getX(), iniHeight+getY(), width, contentHeight);
		g.fillRect(getX()+borderSize,currentY + addActionPadding,width-(borderSize*2),iniHeight-(borderSize*2));
		this.width = 500;
		listOptions.setX(x+100);
		listOptions.setY(y);
		listOptions.setWidth(200);
		listOptions.setPositions();
		listOptions.draw(g);

		listConditions.setX(x+210);
		listConditions.setY(y);
		listConditions.setWidth(300);
		listConditions.setPositions();
		listConditions.draw(g);

	}
	public void addAction(DraggableButton action){
		actionList.add(action);
		paddingBeforeEnd += action.calculateHeight();
	}

	public boolean inAddActionBox(double mouseX,double mouseY){
		boolean isClicked = false;
		if(mouseX > addActionBox.getX() && mouseX < addActionBox.getMaxX() && mouseY > addActionBox.getY() && mouseY < addActionBox.getMaxY())
			isClicked = true;
		return isClicked;

	}
	public void extend(){
		if(!extended){
			addActionPadding += iniHeight;
			height += iniHeight;
			extended = true;
		}
	}

	public void compress() {
		if(extended){
			addActionPadding -= iniHeight;
			height -= iniHeight;
			extended = false;
		}
	}

	public boolean isClicked(Double mouseX, Double mouseY){
		Rectangle r = new Rectangle(x, y, width, calculateHeight());
		float mX = Float.valueOf(String.valueOf(mouseX));
		float mY = Float.valueOf(String.valueOf(mouseY));
		return (r.contains(mX,mY) || listConditions.isClicked(mouseX, mouseY)  || listOptions.isClicked(mouseX, mouseY));
	}
	public void onClick(Double mouseX, Double mouseY, RightPanel rightPanel){

		if(optionZone.getX()<=mouseX && optionZone.getMaxX()>=mouseX && optionZone.getY()<=mouseY && optionZone.getMaxY()>=mouseY || listConditions.isClicked(mouseX, mouseY)  || listOptions.isClicked(mouseX, mouseY)){
			if(listConditions.isClicked(mouseX, mouseY)){
				ButtonRender selection = listConditions.clickedOnSelection(mouseX, mouseY);
				if(selection != null){
					listConditions.setSelected(selection);
					listConditions.setOpen(false);
					listOptions.setOpen(false);
				}else{
					listConditions.onClick();
				}
			}else if(listOptions.isClicked(mouseX, mouseY)){
				ButtonRender selection = listOptions.clickedOnSelection(mouseX, mouseY);
				if(selection != null){
					listOptions.setSelected(selection);
					listConditions.setOpen(false);
					listOptions.setOpen(false);
				}else{
					listOptions.onClick();
				}
			}else{
				rightPanel.removeAction(this);
			}
		}
		if(actionListZone.getX()<=mouseX && actionListZone.getMaxX()>=mouseX && actionListZone.getY()<=mouseY && actionListZone.getMaxY()>=mouseY){
			for(DraggableButton a : actionList){
				if(a.isClicked(mouseX, mouseY)){
					if(a.getClass() == ConditionButton.class){
						((ConditionButton)a).onClick(mouseX, mouseY, rightPanel);
					}else{
						actionList.remove(a);
					}
					break;
				}
			}
		}

	}

	public void hoverListener(Double mouseX, Double mouseY){
		if(inAddActionBox(mouseX,mouseY)){
			if(!listConditions.isClicked(mouseX, mouseY) || !listOptions.isClicked(mouseX, mouseY)){
				extend();
				for(DraggableButton actionButtonInCondition : actionList){
					if(actionButtonInCondition.getClass() == ConditionButton.class){
						if(((ConditionButton)actionButtonInCondition).inAddActionBox(mouseX,mouseY)){
							((ConditionButton)actionButtonInCondition).extend();
						}else{
							((ConditionButton)actionButtonInCondition).compress();
						}
					}
				}
			}
		}else{
			if(actionListZone.getX()<=mouseX && actionListZone.getMaxX()>=mouseX && actionListZone.getY()<=mouseY && actionListZone.getMaxY()>=mouseY){
				for(DraggableButton a : actionList){
					if(a.getClass() == ConditionButton.class){
						((ConditionButton)a).hoverListener(mouseX, mouseY);
					}

				}
			}
			compress();
		}
	}
	@Override
	public float calculateHeight() {
		float contentHeight = iniHeight*2;
		float contentHeightV2 =  iniHeight;
		float contentHeightV3 =  iniHeight;
		for(DraggableButton action : actionList){
			contentHeight += action.calculateHeight();
		}
		if(listConditions.isOpen()){
			for(ButtonRender button : listConditions.getListArray()){
				contentHeightV2 += button.getHeight();
			}
		}
		if(listOptions.isOpen()){
			for(ButtonRender button : listOptions.getListArray()){
				contentHeightV3 += button.getHeight();
			}
		}
		return Math.max(Math.max(contentHeight,contentHeightV2),contentHeightV3)+addActionPadding;
	}

}


text:
package com.alibaba.dubbo.container;

@Deprecated
public interface Container extends org.apache.dubbo.container.Container {
}


text:
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res) {
  res.render('index.html', { title: '歡迎來到Tom的資料庫管理系統' });
});

/* GET Userlist page. */
router.get('/userlist', function(req, res) {
    var db = req.db;
    var collection = db.get('usercollection');
    collection.find({},{},function(e,docs){
        res.render('userlist', {
            "userlist" : docs
        });
    });
});

/* GET New User page. */
router.get('/add', function(req, res) {
    res.render('add', { title: '新增資料' });
});

/* POST to Add User Service */
router.post('/adduser', function(req, res) {

    // Set our internal DB variable
    var db = req.db;

    // Get our form values. These rely on the "name" attributes
    var userName = req.body.name;
    var userAge = req.body.age;
    var userEmail = req.body.email;

    // Set our collection
    var collection = db.get('usercollection');

    // Submit to the DB
    collection.insert({
        "name" : userName,
        "age" : userAge,
        "email" : userEmail
    }, function (err, doc) {
        if (err) {
            // If it failed, return error
            res.send("There was a problem adding the information to the database.");
        }
        else {
            // And forward to success page
            res.redirect("userlist");
        }
    });
});

/* GET New User page. */
router.post('/edit', function(req, res) {
    res.render('edit', { user: req.body.user });
});

/* POST to Edit User Service */
router.post('/edituser', function(req, res) {

    // Set our internal DB variable
    var db = req.db;

    // Get our form values. These rely on the "name" attributes
    var userID = req.body.id;
    var userName = req.body.name;
    var userAge = req.body.age;
    var userEmail = req.body.email;
    // Set our collection
    var collection = db.get('usercollection');

    // Submit to the DB
    collection.update({
        _id : String(userID)
    },{
        $set: { "name": userName, "age": userAge, "email": userEmail}
    },
    function (err, doc) {
        if (err) {
            // If it failed, return error
            res.send("There was a problem updating the information to the database.");
        }
        else {
            // And forward to success page
            res.redirect("userlist");
        }
    });
});

/* POST to Delete User Service */
router.post('/delete', function(req, res) {

    // Set our internal DB variable
    var db = req.db;

    // Get our form values. These rely on the "name" attributes
    var user = JSON.parse(req.body.user);
    var userID = user["_id"];

    // Set our collection
    var collection = db.get('usercollection');

    // Submit to the DB
    collection.remove({
        _id : String(userID)
    }, function (err, doc) {

        if (err) {
            // If it failed, return error
            res.send("There was a problem deleting the information to the database.");
        }
        else {
            // And forward to success page
            res.redirect("userlist");
        }
    });
});

module.exports = router;


text:
package com.sun.xml.internal.ws.wsdl;

import com.sun.istack.internal.NotNull;
import com.sun.istack.internal.Nullable;
import com.sun.xml.internal.ws.api.model.wsdl.WSDLPort;
import com.sun.xml.internal.ws.api.model.SEIModel;
import com.sun.xml.internal.ws.api.model.WSDLOperationMapping;
import com.sun.xml.internal.ws.api.WSBinding;
import com.sun.xml.internal.ws.api.message.Packet;
import com.sun.xml.internal.ws.api.message.Message;
import com.sun.xml.internal.ws.resources.ServerMessages;
import com.sun.xml.internal.ws.fault.SOAPFaultBuilder;

import javax.xml.namespace.QName;
import java.util.List;
import java.util.ArrayList;
import java.text.MessageFormat;

/**
 * This class abstracts the process of identifying the wsdl operation from a SOAP Message request.
 * This is primarily for dispatching the request messages to an endpoint method.
 *
 * Different implementations of {@link WSDLOperationFinder} are used underneath to identify the wsdl operation based on
 * if AddressingFeature is enabled or not.
 *
 * @author Rama Pulavarthi
 */
public class OperationDispatcher {
    private List<WSDLOperationFinder> opFinders;
    private WSBinding binding;

    public OperationDispatcher(@NotNull WSDLPort wsdlModel, @NotNull WSBinding binding, @Nullable SEIModel seiModel) {
        this.binding = binding;
        opFinders = new ArrayList<WSDLOperationFinder>();
        if (binding.getAddressingVersion() != null) {
            opFinders.add(new ActionBasedOperationFinder(wsdlModel, binding, seiModel));
        }
        opFinders.add(new PayloadQNameBasedOperationFinder(wsdlModel, binding, seiModel));
        opFinders.add(new SOAPActionBasedOperationFinder(wsdlModel, binding, seiModel));

    }

    /**
     * @deprecated use getWSDLOperationMapping(Packet request)
     * @param request Packet
     * @return QName of the wsdl operation.
     * @throws DispatchException if a unique operartion cannot be associated with this packet.
     */
    public @NotNull QName getWSDLOperationQName(Packet request) throws DispatchException {
        WSDLOperationMapping m = getWSDLOperationMapping(request);
        return m != null ? m.getOperationName() : null;
    }

    public @NotNull WSDLOperationMapping getWSDLOperationMapping(Packet request) throws DispatchException {
        WSDLOperationMapping opName;
        for(WSDLOperationFinder finder: opFinders) {
            opName = finder.getWSDLOperationMapping(request);
            if(opName != null)
                return opName;
        }
        //No way to dispatch this request
        String err = MessageFormat.format("Request=[SOAPAction={0},Payload='{'{1}'}'{2}]",
                request.soapAction, request.getMessage().getPayloadNamespaceURI(),
                request.getMessage().getPayloadLocalPart());
        String faultString = ServerMessages.DISPATCH_CANNOT_FIND_METHOD(err);
        Message faultMsg = SOAPFaultBuilder.createSOAPFaultMessage(
                binding.getSOAPVersion(), faultString, binding.getSOAPVersion().faultCodeClient);
        throw new DispatchException(faultMsg);
    }
}


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Test Suite on Asterisk, and other worldly endeavours</title>
    <link>http://blog.leifmadsen.com/tags/test-suite/index.xml</link>
    <description>Recent content in Test Suite on Asterisk, and other worldly endeavours</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <atom:link href="/tags/test-suite/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>Installing the Asterisk Test Suite</title>
      <link>http://blog.leifmadsen.com/blog/2010/05/03/installing-the-asterisk-test-suite/</link>
      <pubDate>Mon, 03 May 2010 15:17:57 +0000</pubDate>

      <guid>http://blog.leifmadsen.com/blog/2010/05/03/installing-the-asterisk-test-suite/</guid>
      <description>In case you missed it, I wrote an introductory article about the Asterisk Test Suite on the Asterisk blog. The post takes you from a minimally installed Ubuntu 9.10 up to the point that you can run the tests in the test suite by going through all the possible errors you might encounter getting it loaded, and how to resolve those errors (most of them being missing dependencies).
Enjoy!
http://blogs.asterisk.org/2010/04/29/installing-the-asterisk-test-suite/</description>
    </item>

  </channel>
</rss>


text:
require 'spec_helper'

describe 'neutron::db' do

  shared_examples 'neutron::db' do

    context 'with default parameters' do

      it { is_expected.to contain_neutron_config('database/connection').with_value('sqlite:////var/lib/neutron/ovs.sqlite').with_secret(true) }
      it { is_expected.to contain_neutron_config('database/idle_timeout').with_value('3600') }
      it { is_expected.to contain_neutron_config('database/min_pool_size').with_value('1') }
      it { is_expected.to contain_neutron_config('database/max_retries').with_value('10') }
      it { is_expected.to contain_neutron_config('database/retry_interval').with_value('10') }

    end

    context 'with specific parameters' do
      let :params do
        { :database_connection     => 'mysql://neutron:neutron@localhost/neutron',
          :database_idle_timeout   => '3601',
          :database_min_pool_size  => '2',
          :database_max_retries    => '11',
          :database_retry_interval => '11', }
      end

      it { is_expected.to contain_neutron_config('database/connection').with_value('mysql://neutron:neutron@localhost/neutron').with_secret(true) }
      it { is_expected.to contain_neutron_config('database/idle_timeout').with_value('3601') }
      it { is_expected.to contain_neutron_config('database/min_pool_size').with_value('2') }
      it { is_expected.to contain_neutron_config('database/max_retries').with_value('11') }
      it { is_expected.to contain_neutron_config('database/retry_interval').with_value('11') }

    end

    context 'with postgresql backend' do
      let :params do
        { :database_connection     => 'postgresql://neutron:neutron@localhost/neutron', }
      end

      it 'install the proper backend package' do
        is_expected.to contain_package('python-psycopg2').with(:ensure => 'present')
      end

    end

    context 'with incorrect database_connection string' do
      let :params do
        { :database_connection     => 'redis://neutron:neutron@localhost/neutron', }
      end

      it_raises 'a Puppet::Error', /validate_re/
    end

  end

  context 'on Debian platforms' do
    let :facts do
      { :osfamily => 'Debian',
        :operatingsystem => 'Debian',
        :operatingsystemrelease => 'jessie',
      }
    end

    it_configures 'neutron::db'
  end

  context 'on Redhat platforms' do
    let :facts do
      { :osfamily               => 'RedHat',
        :operatingsystemrelease => '7.1',
      }
    end

    it_configures 'neutron::db'
  end

end


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

namespace MotleyFool.FileWriters
{
    public class NormalizedDataWriter : FileWriterBase
    {
        public NormalizedDataWriter(string path, IDictionary<string, IList<Tuple<DateTime, double>>> allTickerData) : base(path, allTickerData) { }

        public override void Write()
        {
            base.Write();
            foreach (var kvp in allTickerData)
            {
                double firstValue = kvp.Value.First().Item2;
                writer.WriteLine("{0}\t{1}", kvp.Key, String.Join("\t", kvp.Value.Select(tickerData => tickerData.Item2 / firstValue)));
            }
        }
    }
}


text:
using System.Diagnostics;
using System.IO.PortsTests;
using System.Text;
using System.Threading;
using Legacy.Support;
using Xunit;

namespace System.IO.Ports.Tests
{
    public class ReadExisting : PortsTest
    {
        //The number of random bytes to receive for read method testing
        private const int numRndBytesToRead = 8;

        //The number of random bytes to receive for large input buffer testing
        private const int largeNumRndBytesToRead = 2048;

        private enum ReadDataFromEnum { NonBuffered, Buffered, BufferedAndNonBuffered };

        #region Test Cases

        [ConditionalFact(nameof(HasLoopbackOrNullModem))]
        public void ASCIIEncoding()
        {
            VerifyRead(new ASCIIEncoding());
        }

        [ConditionalFact(nameof(HasLoopbackOrNullModem))]
        public void UTF8Encoding()
        {
            VerifyRead(new UTF8Encoding());
        }

        [ConditionalFact(nameof(HasLoopbackOrNullModem))]
        public void UTF32Encoding()
        {
            VerifyRead(new UTF32Encoding());
        }

        [ConditionalFact(nameof(HasLoopbackOrNullModem))]
        public void SerialPort_ReadBufferedData()
        {
            int numberOfBytesToRead = 32;
            VerifyRead(Encoding.ASCII, numberOfBytesToRead, ReadDataFromEnum.Buffered);
        }

        [ConditionalFact(nameof(HasLoopbackOrNullModem))]
        public void SerialPort_IterativeReadBufferedData()
        {
            int numberOfBytesToRead = 32;
            VerifyRead(Encoding.ASCII, numberOfBytesToRead, ReadDataFromEnum.Buffered);
        }

        [ConditionalFact(nameof(HasLoopbackOrNullModem))]
        public void SerialPort_ReadBufferedAndNonBufferedData()
        {
            int numberOfBytesToRead = 64;

            VerifyRead(Encoding.ASCII, numberOfBytesToRead, ReadDataFromEnum.BufferedAndNonBuffered);
        }

        [ConditionalFact(nameof(HasLoopbackOrNullModem))]
        public void SerialPort_IterativeReadBufferedAndNonBufferedData()
        {
            int numberOfBytesToRead = 3;

            VerifyRead(Encoding.ASCII, numberOfBytesToRead, ReadDataFromEnum.BufferedAndNonBuffered);
        }

        [ConditionalFact(nameof(HasLoopbackOrNullModem))]
        public void GreedyRead()
        {
            using (SerialPort com1 = TCSupport.InitFirstSerialPort())
            using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
            {
                char[] charXmitBuffer = TCSupport.GetRandomChars(128, true);
                byte[] byteXmitBuffer = new byte[1024];
                char utf32Char = TCSupport.GenerateRandomCharNonSurrogate();
                byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new[] { utf32Char });
                int numBytes;

                Debug.WriteLine("Verifying that ReadExisting() will read everything from internal buffer and drivers buffer");

                //Put the first byte of the utf32 encoder char in the last byte of this buffer
                //when we read this later the buffer will have to be resized
                byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0];

                com1.Open();

                if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
                    com2.Open();

                com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length);

                TCSupport.WaitForReadBufferToLoad(com1, byteXmitBuffer.Length);

                //Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's
                //internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so
                //the other 3 bytes of the ut32 encoded char can be in the buffer
                com1.Read(new char[1023], 0, 1023);

                Assert.Equal(1, com1.BytesToRead);

                com1.Encoding = Encoding.UTF32;
                com2.Encoding = Encoding.UTF32;

                com2.Write(utf32CharBytes, 1, 3);
                com2.Write(charXmitBuffer, 0, charXmitBuffer.Length);

                numBytes = Encoding.UTF32.GetByteCount(charXmitBuffer);

                byte[] byteBuffer = Encoding.UTF32.GetBytes(charXmitBuffer);

                var expectedChars = new char[1 + Encoding.UTF32.GetCharCount(byteBuffer)];
                expectedChars[0] = utf32Char;

                Encoding.UTF32.GetChars(byteBuffer, 0, byteBuffer.Length, expectedChars, 1);

                TCSupport.WaitForReadBufferToLoad(com1, 4 + numBytes);

                string rcvString = com1.ReadExisting();

                Assert.NotNull(rcvString);

                char[] actualChars = rcvString.ToCharArray();

                Assert.Equal(expectedChars, actualChars);

                Assert.Equal(0, com1.BytesToRead);
            }
        }

        [ConditionalFact(nameof(HasLoopbackOrNullModem))]
        private void LargeInputBuffer()
        {
            VerifyRead(largeNumRndBytesToRead);
        }
        #endregion

        #region Verification for Test Cases

        private void VerifyRead()
        {
            VerifyRead(new ASCIIEncoding(), numRndBytesToRead);
        }

        private void VerifyRead(int numberOfBytesToRead)
        {
            VerifyRead(new ASCIIEncoding(), numberOfBytesToRead);
        }

        private void VerifyRead(Encoding encoding)
        {
            VerifyRead(encoding, numRndBytesToRead);
        }

        private void VerifyRead(Encoding encoding, int numberOfBytesToRead)
        {
            VerifyRead(encoding, numberOfBytesToRead, ReadDataFromEnum.NonBuffered);
        }

        private void VerifyRead(Encoding encoding, int numberOfBytesToRead, ReadDataFromEnum readDataFrom)
        {
            using (SerialPort com1 = TCSupport.InitFirstSerialPort())
            using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
            {
                Random rndGen = new Random(-55);
                char[] charsToWrite = new char[numberOfBytesToRead];
                byte[] bytesToWrite = new byte[numberOfBytesToRead];

                //Genrate random chars to send
                for (int i = 0; i < bytesToWrite.Length; i++)
                {
                    char randChar = (char)rndGen.Next(0, ushort.MaxValue);

                    charsToWrite[i] = randChar;
                }

                Debug.WriteLine("Verifying read method endocing={0} with {1} random chars", encoding.EncodingName,
                    bytesToWrite.Length);

                com1.ReadTimeout = 500;
                com1.Encoding = encoding;

                TCSupport.SetHighSpeed(com1, com2);

                com1.Open();

                if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
                    com2.Open();

                bytesToWrite = com1.Encoding.GetBytes(charsToWrite, 0, charsToWrite.Length);

                switch (readDataFrom)
                {
                    case ReadDataFromEnum.NonBuffered:
                        VerifyReadNonBuffered(com1, com2, bytesToWrite);
                        break;
                    case ReadDataFromEnum.Buffered:
                        VerifyReadBuffered(com1, com2, bytesToWrite);
                        break;
                    case ReadDataFromEnum.BufferedAndNonBuffered:
                        VerifyReadBufferedAndNonBuffered(com1, com2, bytesToWrite);
                        break;
                    default:
                        throw new ArgumentOutOfRangeException(nameof(readDataFrom), readDataFrom, null);
                }
            }
        }

        private void VerifyReadNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite)
        {
            char[] expectedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length);

            VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedChars);
        }

        private void VerifyReadBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite)
        {
            char[] expectedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length);

            BufferData(com1, com2, bytesToWrite);

            PerformReadOnCom1FromCom2(com1, com2, expectedChars);
        }

        private void VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite)
        {
            char[] expectedChars = new char[com1.Encoding.GetCharCount(bytesToWrite, 0, bytesToWrite.Length) * 2];
            char[] encodedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length);

            Array.Copy(encodedChars, 0, expectedChars, 0, bytesToWrite.Length);
            Array.Copy(encodedChars, 0, expectedChars, encodedChars.Length, encodedChars.Length);

            BufferData(com1, com2, bytesToWrite);

            VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedChars);
        }

        private void BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite)
        {
            com2.Write(bytesToWrite, 0, 1); // Write one byte at the begining because we are going to read this to buffer the rest of the data
            com2.Write(bytesToWrite, 0, bytesToWrite.Length);

            TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length);

            com1.Read(new char[1], 0, 1); // This should put the rest of the bytes in SerialPorts own internal buffer

            Assert.Equal(bytesToWrite.Length, com1.BytesToRead);
        }

        private void VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars)
        {
            com2.Write(bytesToWrite, 0, bytesToWrite.Length);
            com1.ReadTimeout = 500;
            Thread.Sleep((int)(((bytesToWrite.Length * 10.0) / com1.BaudRate) * 1000) + 250);
            PerformReadOnCom1FromCom2(com1, com2, expectedChars);
        }

        private void PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, char[] expectedChars)
        {
            string rcvString = com1.ReadExisting();
            char[] rcvBuffer = rcvString.ToCharArray();

            //Compare the chars that were written with the ones we expected to read
            Assert.Equal(expectedChars, rcvBuffer);

            Assert.Equal(0, com1.BytesToRead);
        }
        #endregion
    }
}