text:
package com.tvd12.ezyfox.bean.testing.combine.pack0;

import lombok.Getter;

@Getter
public class PropertiesPack1 {

    private String hello1;
}

redpajama_set_name: RedPajamaGithub


text:
/**
 *
 */
package backend.seedgenerator;

/**
 * @author p4553d
 *
 *         Interface for all seed generators.
 *
 */
public interface ISeedGenerator {
    /**
     * Generate website specific seed from master password and website name
     *
     * @param master
     * @param site
     * @return pseudo random seed in raw form
     */
    public byte[] generateSeed(String master, String site);
}


text:
package com.opengamma.financial.security.lookup.irs;

import org.threeten.bp.LocalDate;

import com.opengamma.financial.security.irs.InterestRateSwapNotional;
import com.opengamma.financial.security.irs.InterestRateSwapNotionalVisitor;
import com.opengamma.financial.security.swap.CommodityNotional;
import com.opengamma.financial.security.swap.InterestRateNotional;
import com.opengamma.financial.security.swap.SecurityNotional;
import com.opengamma.financial.security.swap.VarianceSwapNotional;

/**
 * Visitor to obtain the IR notional amount.
 */
public class InterestRateSwapNotionalAmountVisitor implements InterestRateSwapNotionalVisitor<LocalDate,  Double> {

  @Override
  public Double visitCommodityNotional(final CommodityNotional notional, final LocalDate period) {
    return null;
  }

  @Override
  public Double visitInterestRateNotional(final InterestRateNotional notional, final LocalDate period) {
    return notional.getAmount();
  }

  @Override
  public Double visitSecurityNotional(final SecurityNotional notional, final LocalDate period) {
    return null;
  }

  @Override
  public Double visitVarianceSwapNotional(final VarianceSwapNotional notional, final LocalDate period) {
    return null;
  }

  @Override
  public Double visitInterestRateSwapNotional(final InterestRateSwapNotional notional, final LocalDate period) {
    return notional.getAmount(period);
  }

  @Override
  public Double visitInterestRateSwapNotional(final InterestRateSwapNotional notional) {
    throw new UnsupportedOperationException("InterestRateSwapNotional requires a period to get the notional for: " + notional);
  }

  @Override
  public Double visitInterestRateNotional(final InterestRateNotional notional) {
    return notional.getAmount();
  }

  @Override
  public Double visitCommodityNotional(final CommodityNotional notional) {
    throw new UnsupportedOperationException(notional + " not supported by InterestRateSwapNotionalAmountVisitor visitor");
  }

  @Override
  public Double visitSecurityNotional(final SecurityNotional notional) {
    throw new UnsupportedOperationException(notional + " not supported by InterestRateSwapNotionalAmountVisitor visitor");
  }

  @Override
  public Double visitVarianceSwapNotional(final VarianceSwapNotional notional) {
    throw new UnsupportedOperationException(notional + " not supported by InterestRateSwapNotionalAmountVisitor visitor");
  }
}


text:
module Popmovies
  class Router

    def initialize
      @bindings = {}
    end

    def on(event, &block)
      @bindings.store(event, block)
    end

    def trigger(event, *args)
      @bindings.fetch(event).call(*args)
    end

  end
end


text:
(function() {

    var module = angular.module('pullreq.service.tags', ['lib.lodash']);

    module.factory('tagService', [
        '_',
        function(_) {
            var re = /^([A-Za-z]+)\-?(\d+)?.*$/i;
            var createAndPopulateTitleTags = function(pullRequests) {
                var tags = [];
                _.each(pullRequests, function(pullRequest) {
                    var title = pullRequest.title;
                    var res = title.match(re);
                    if (res) {
                        var tagName = res[1].toUpperCase();
                        if (!_.contains(tags, tagName)) {
                            tags.push(tagName);
                        }
                        if (!pullRequest.tags) {
                            pullRequest.tags = {};
                        }
                        pullRequest.tags.title = tagName;
                    }
                });
                return _.sortBy(tags, function(tag) { return tag; });
            };

            return {
                createTitleTags: createAndPopulateTitleTags
            }
        }
    ]);
})();


text:
<!DOCTYPE html>

  <title>ScienceGist - Simplify Science</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <link rel="stylesheet" href="style.css">

  <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>

ScienceGist

Bridge the science gap and speed up the world’s research

I’ve started building a community that appreciates and nurtures the art of simplifying complex concepts. The main focus of this community is explaining very elaborate ideas and proofs, as we often see them in scientific publications, in a clear and concise manner.

Scientific communication has been a passion of mine for a few years now and I've completed several projects in the field. Although no major breakthrough came, I’ve learned a lot from my smaller projects (My projects, Tiris) and I believe this knowledge will come very handy in the future of ScienceGist.

Let's do this.

If you would like to help out with ScienceGist or you have some ideas of your own that you would like to chat about, shoot an e-mail to me@juretriglav.si. Thanks!

      By @jure


text:
package com.flash3388.flashlib.scheduling.actions;

import java.util.Collection;
import java.util.Random;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class TestActions {

    public enum ActionType {
        SMALL(SmallSizeAction::new),
        MEDIUM(MediumSizeAction::new),
        SHORT_SLEEP((params)->
                new SleepingAction(params, 1L)),
        SMALL_SINGLE_SEQ_GROUP((params)->
                new GenericSequentialActionGroup(ActionType.SMALL, 1, params)),
        SMALL_MULTI_SEQ_GROUP((params)->
                new GenericSequentialActionGroup(ActionType.SMALL, 3, params))
        ;

        private final Function<TestActionParams, Action> mActionGenerator;

        ActionType(Function<TestActionParams, Action> actionGenerator) {
            mActionGenerator = actionGenerator;
        }

        public Action create(TestActionParams params) {
            return mActionGenerator.apply(params);
        }
    }

    public static class SmallSizeAction extends TestAction {

        private final Random mRandom;

        private SmallSizeAction(TestActionParams params) {
            super(params);
            mRandom = new Random();
        }

        @Override
        public void execute() {
            byte[] bytes = new byte[1024];
            mRandom.nextBytes(bytes);

            output(bytes);
        }
    }

    public static class MediumSizeAction extends TestAction {

        private final Random mRandom;

        private MediumSizeAction(TestActionParams params) {
            super(params);
            mRandom = new Random();
        }

        @Override
        public void execute() {
            Collection<Integer> numbers = IntStream.range(0, 100)
                    .mapToObj((i) -> mRandom.nextInt())
                    .sorted(Integer::compareTo)
                    .collect(Collectors.toList());

            output(numbers);
        }
    }

    public static class SleepingAction extends TestAction {

        private final long mSleepTimeMs;

        private SleepingAction(TestActionParams params, long sleepTimeMs) {
            super(params);
            mSleepTimeMs = sleepTimeMs;
        }

        @Override
        public void execute() {
            try {
                Thread.sleep(mSleepTimeMs);
            } catch (InterruptedException e) {
                output(e);
            }
        }
    }

    public static class GenericSequentialActionGroup extends TestSequentialActionGroup {

        private GenericSequentialActionGroup(ActionType containedType, int actionsCount,
                                             TestActionParams params) {
            super(params);

            IntStream.range(0, actionsCount)
                    .forEach((i)->add(containedType.create(params)));

        }
    }
}


text:
using System;
using System.Data;

namespace MyMeta.VistaDB3x
{
#if ENTERPRISE
	using System.Runtime.InteropServices;
	[ComVisible(true), ClassInterface(ClassInterfaceType.AutoDual), ComDefaultInterface(typeof(IResultColumn))]
#endif
	public class VistaDBResultColumn : ResultColumn
	{
		public VistaDBResultColumn()
		{

		}

		#region Properties

		override public string Alias
		{
			get
			{
				return name;
			}
		}

		override public string DataTypeName
		{
			get
			{
				return typeName;
			}
		}

		override public System.Int32 Ordinal
		{
			get
			{
				return ordinal;
			}
		}

		internal string name = "";
		internal string typeName = "";
		internal System.Int32 ordinal = 0;

		#endregion
	}
}


text:
var https       = require('https')
  , events      = require('events')
  , url         = require('url')
  , util        = require('util')
  ;

var DEFAULT_LOGGER = { error   : function(msg, props) { console.log(msg); if (!!props) console.log(props);             }
                     , warning : function(msg, props) { console.log(msg); if (!!props) console.log(props);             }
                     , notice  : function(msg, props) { console.log(msg); if (!!props) console.log(props);             }
                     , info    : function(msg, props) { console.log(msg); if (!!props) console.log(props);             }
                     , debug   : function(msg, props) { console.log(msg); if (!!props) console.log(props);             }
                     };

var WinkAPI = function(options) {
  var k;

  var self = this;

  if (!(self instanceof WinkAPI)) return new WinkAPI(options);

  self.options = options;

  self.logger = self.options.logger  || {};
  for (k in DEFAULT_LOGGER) {
    if ((DEFAULT_LOGGER.hasOwnProperty(k)) && (typeof self.logger[k] === 'undefined'))  self.logger[k] = DEFAULT_LOGGER[k];
  }

  self.oauth = {};
};
util.inherits(WinkAPI, events.EventEmitter);

WinkAPI.prototype.login = function(username, passphrase, callback) {
  var json;

  var self = this;

  if (typeof callback !== 'function') throw new Error('callback is mandatory for login');

  json = { username      : username
         , client_secret : self.options.clientSecret
         , password      : passphrase
         , client_id     : self.options.clientID
         , grant_type    : 'password'
         };
  self.invoke('POST', '/oauth2/token', json, function(err, code, results) {
    var data, errors;

    if (!!err) return callback(err);

    data = results.data;
    errors = (!!results.errors) && util.isArray(results.errors) && (results.errors.length > 0) && results.errors;
    if ((!!errors) || (!data)) {
      return callback(new Error('invalid credentials: ' + JSON.stringify(!!errors ? errors : results)));
    }

    self.oauth = results.data;
    callback(null);
  });

  return self;
};

WinkAPI.prototype._refresh = function(callback) {
  var json;

  var self = this;

  if (typeof callback !== 'function') throw new Error('callback is mandatory for refresh');

  json = { client_id     : self.options.clientID
         , client_secret : self.options.clientSecret
         , refresh_token : self.oauth.refresh_token
         , grant_type    : 'refresh_token'
         };
  self.invoke('POST', '/oauth2/token', json, function(err, code, results) {
    var data, errors;

    if (!!err) return callback(err);

    data = results.data;
    errors = (!!results.errors) && util.isArray(results.errors) && (results.errors.length > 0) && results.errors;
    if ((!!errors) || (!data)) {
      return callback(new Error('invalid credentials: ' + JSON.stringify(!!errors ? errors : results)));
    }

    self.oauth = results.data;
    callback(null);
  });

  return self;
};

WinkAPI.prototype.getUser = function(callback) {
  return this.roundtrip('GET', '/users/me', callback);
};

WinkAPI.prototype.setUser = function(props, callback) {
  return this.roundtrip('PUT', '/users/me', props, callback);
};

WinkAPI.prototype.getDevices = function(callback) {
  var self = this;

  return self.invoke('GET', '/users/me/wink_devices', function(err, code, results) {
    var data, datum, devices, errors, i, k;

    if (!!err) return callback(err);

    data = results.data;
    errors = (!!results.errors) && util.isArray(results.errors) && (results.errors.length > 0) && results.errors;
    if ((!!errors) || (!data) || (!util.isArray(data))) {
      return callback(new Error('invalid response: ' + JSON.stringify(!!errors ? errors : results)));
    }

    devices = [];
    for (i = 0; i < data.length; i++) {
      datum = data[i];

      for (k in datum) if ((datum.hasOwnProperty(k)) && (k.indexOf('_id') === (k.length - 3))) {
        devices.push({ id      : datum[k]
                     , type    : k.slice(0, -3)
                     , name    : datum.name
                     , path    : '/' + k.slice(0, -3) + 's/' + datum[k]
                     , dials   : self._children(datum, 'dials')
                     , outlets : self._children(datum, 'outlets')
                     , props   : datum
                     });
        break;
      }
    }

    callback(null, devices);
  });
};

WinkAPI.prototype.getDevice = function(device, callback) {
  var self = this;

  return self.roundtrip('GET', device.path, function(err, datum) {
    var k;

    if (!!err) return callback(err);

    for (k in datum) if ((datum.hasOwnProperty(k)) && (k.indexOf('_id') === (k.length - 3))) {
      return callback(null, { id      : datum[k]
                            , type    : k.slice(0, -3)
                            , name    : datum.name
                            , path    : '/' + k.slice(0, -3) + 's/' + datum[k]
                            , dials   : self._children(datum,  'dials')
                            , outlets : self._children(datum, 'outlets')
                            , props   : datum
                            });
    }

    callback(null, null);
  });
};

WinkAPI.prototype._children = function(datum, prefix) {
  var child, children, i, id, type;

  if (!datum[prefix]) return null;

  children = {};

  type = prefix.slice(0, -1);
  id = type + '_id';
  for (i = 0; i < datum[prefix].length; i++) {
    child = datum[prefix][i];
    if (!child[id]) continue;

    children[child[id]] = { id    : child[id]
                          , type  : type
                          , name  : child.name
                          , path  : '/' + prefix + '/' + child[id]
                          , props : child
                          };
  }

  return children;
};

WinkAPI.prototype.setDevice = function(device, props, callback) {
  var self = this;

  return self.roundtrip('PUT', device.path, props, function(err, datum) {
    if (!!err) return callback(err);

    return callback(null, { id      : device.id
                          , type    : device.type
                          , name    : device.name
                          , path    : device.path
                          , dials   : self._children(datum,  'dials')
                          , outlets : self._children(datum, 'outlets')
                          , props   : datum
                          });
  });
};
WinkAPI.prototype.setOutlet = WinkAPI.prototype.setDevice;

WinkAPI.prototype.getIcons = function(callback) {
  return this.roundtrip('GET', '/icons', callback);
};

WinkAPI.prototype.getChannels = function(callback) {
  return this.roundtrip('GET', '/channels', callback);
};

WinkAPI.prototype.getServices = function(callback) {
  return this.roundtrip('GET', '/users/me/linked_services', callback);
};

WinkAPI.prototype.newService = function(props, callback) {
  return this.roundtrip('POST', '/users/me/linked_services', props, callback);
};

WinkAPI.prototype.getTrigger = function(id, callback) {
  return this.roundtrip('GET', '/triggers/' + id, callback);
};

WinkAPI.prototype.setTrigger = function(id, props, callback) {
  return this.roundtrip('PUT',  '/triggers/' + id, props, callback);
};

WinkAPI.prototype.getDialTemplates = function(callback) {
  return this.roundtrip('GET', '/dial_templates', callback);
};

WinkAPI.prototype.setDialValue = function(dial, value, callback) {
  return this.setDial(dial, { value: value }, callback);
};

WinkAPI.prototype.setDialLabels = function(dial, mainLabel, secondaryLabel, callback) {
  return this.setDial(dial, { label: mainLabel, labels: [ mainLabel, secondaryLabel] }, callback);
};

WinkAPI.prototype.setDial = function(dial, props, callback) {
  var json;

  var self = this;

  json = { name                  : props.name                  || dial.props.name
         , label                 : props.label                 || dial.props.label
         , labels                : props.labels                || dial.props.labels
         , position              : props.position              || dial.props.position
         , brightness            : props.brightness            || dial.props.brightness
         , channel_configuration : props.channel_configuration || dial.props.channel_configuration
         , dial_configuration    : props.dial_configuration    || dial.props.dial_configuration
         };
  return self.roundtrip('PUT', dial.path, json, function(err, datum) {
    if (!!err) return callback(err);

    return callback(null, { id      : dial.id
                          , type    : dial.type
                          , name    : dial.name
                          , path    : dial.path
                          , props   : datum
                          });
  });
};

WinkAPI.prototype.roundtrip = function(method, path, json, callback) {
  var self = this;

  if ((!callback) && (typeof json === 'function')) {
    callback = json;
    json = null;
  }

  return self.invoke(method, path, json, function(err, code, results) {
    var data, errors;

    if (!!err) return callback(err);

    data = results.data;
    errors = (!!results.errors) && util.isArray(results.errors) && (results.errors.length > 0) && results.errors;
    if ((!!errors) || (!data)) {
      return callback(new Error('invalid response: ' + JSON.stringify(!!errors ? errors : results)));
    }

    callback(null, data);
  });
};

WinkAPI.prototype.invoke = function(method, path, json, callback) {
  var options;

  var self = this;

  if ((!callback) && (typeof json === 'function')) {
    callback = json;
    json = null;
  }
  if (!callback) {
    callback = function(err, results) {
      if (!!err) self.logger.error('invoke', { exception: err }); else self.logger.info(path, { results: results });
    };
  }

  options = url.parse('https://winkapi.quirky.com' + path);
  options.agent = false;
  options.method = method;
  options.headers = {};
  if ((!!self.oauth.access_token) && ((!json) || (!json.grant_type))) {
    options.headers.Authorization = 'Bearer ' + self.oauth.access_token;
  }
  if (!!json) {
    options.headers['Content-Type'] = 'application/json';
    json = JSON.stringify(json);
    options.headers['Content-Length'] = Buffer.byteLength(json);
  }

  https.request(options, function(response) {
    var body = '';

    response.on('data', function(chunk) {
      body += chunk.toString();
    }).on('end', function() {
      var expected = { GET    : [ 200 ]
                     , PUT    : [ 200 ]
                     , POST   : [ 200, 201, 202 ]
                     , DELETE : [ 200 ]
                     }[method];

      var results = {};

      try { results = JSON.parse(body); } catch(ex) {
        self.logger.error(path, { event: 'json', diagnostic: ex.message, body: body });
        return callback(ex, response.statusCode);
      }

      if (expected.indexOf(response.statusCode) === -1) {
         self.logger.error(path, { event: 'https', code: response.statusCode, body: body });
         return callback(new Error('HTTP response ' + response.statusCode), response.statusCode, results);
      }

      callback(null, response.statusCode, results);
    }).on('close', function() {
      callback(new Error('premature end-of-file'));
    }).setEncoding('utf8');
  }).on('error', function(err) {
    callback(err);
  }).end(json);

  return self;
};

exports.WinkAPI = WinkAPI;


text:
<section id="appComponent">
  <my-navbar id="navbar"> Standard navbar comes here</my-navbar>
</section>

<router-outlet>


text:
require 'spec_helper'

RSpec.describe Karafka::BaseWorker do
  subject { described_class.new }

  let(:controller) do
    ClassBuilder.inherit(Karafka::BaseController) do
      def perform
        self
      end

      def after_failure
        self
      end
    end
  end

  let(:controller_instance) { controller.new }

  let(:args) { [rand.to_s, rand] }

  describe '#perform' do
    before do
      expect(subject)
        .to receive(:controller)
        .and_return(controller_instance)
        .at_least(:once)
    end

    it 'sets params and perform controller action' do
      expect(controller_instance)
        .to receive(:perform)

      subject.perform(*args)

      expect(subject.params).to eq args.last
    end

    it 'sets topic and perform controller action' do
      expect(controller_instance)
        .to receive(:perform)

      subject.perform(*args)

      expect(subject.topic).to eq args.first
    end
  end

  describe '#after_failure' do
    before do
      expect(subject)
        .to receive(:controller)
        .and_return(controller_instance)
        .at_least(:once)
    end

    context 'when after_failure method is not defined on the controller' do
      it 'does nothing' do
        expect(controller_instance)
          .to receive(:respond_to?)
          .and_return(false)
          .at_least(:once)

        expect(controller_instance)
          .not_to receive(:after_failure)

        subject.after_failure(*args)
      end
    end

    context 'when after_failure method is defined on the controller' do
      it 'executes it' do
        expect(controller_instance)
          .to receive(:respond_to?)
          .and_return(true)
          .at_least(:once)

        expect(controller_instance)
          .to receive(:after_failure)

        subject.after_failure(*args)
      end
    end
  end

  describe '#controller' do
    let(:topic) { rand.to_s }
    let(:router) { Karafka::Routing::Router.new(topic) }
    let(:interchanger) { double }
    let(:params) { double }
    let(:interchanged_params) { double }

    before do
      router
      subject.params = params
    end

    it 'expect to use router to pick controller, assign params and return' do
      expect(subject)
        .to receive(:topic) { topic }

      expect(Karafka::Routing::Router)
        .to receive(:new)
        .with(topic)
        .and_return(router)

      expect(router)
        .to receive(:build)
        .and_return(controller_instance)

      expect(controller_instance)
        .to receive(:interchanger)
        .and_return(interchanger)

      expect(interchanger)
        .to receive(:parse)
        .with(params)
        .and_return(interchanged_params)

      expect(controller_instance)
        .to receive(:params=)
        .with(interchanged_params)

      expect(subject.send(:controller)).to eq controller_instance
    end
  end
end


text:
<?php

namespace hipanel\modules\server\widgets\combo;

use hipanel\widgets\RefCombo;
use Yii;

class ServerStateRefCombo extends RefCombo
{
    public function prepareData()
    {
        $refs = parent::prepareData();
        if (Yii::$app->user->can('ref.view.not-used')) {
            return $refs;
        }

        return array_filter($refs, function ($k) {
            return in_array($k, ['setuping', 'error', 'ok']);
        }, ARRAY_FILTER_USE_KEY);
    }
}


text:
<?php

namespace Ivory\HttpAdapter\Event;

use Ivory\HttpAdapter\HttpAdapterException;
use Ivory\HttpAdapter\HttpAdapterInterface;
use Ivory\HttpAdapter\Message\ResponseInterface;

/**
 * Multi request errored event.
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class MultiRequestErroredEvent extends AbstractEvent
{
    /** @var \Ivory\HttpAdapter\HttpAdapterException[] */
    private $exceptions;

    /** @var \Ivory\HttpAdapter\Message\ResponseInterface[] */
    private $responses = array();

    /**
     * Creates a multi request errored event.
     *
     * @param \Ivory\HttpAdapter\HttpAdapterInterface   $httpAdapter The http adapter.
     * @param \Ivory\HttpAdapter\HttpAdapterException[] $exceptions  The exceptions.
     */
    public function __construct(HttpAdapterInterface $httpAdapter, array $exceptions)
    {
        parent::__construct($httpAdapter);

        $this->setExceptions($exceptions);
    }

    /**
     * Clears the exceptions.
     */
    public function clearExceptions()
    {
        $this->exceptions = array();
    }

    /**
     * Checks if there are exceptions.
     *
     * @return boolean TRUE if there are exceptions else FALSE.
     */
    public function hasExceptions()
    {
        return !empty($this->exceptions);
    }

    /**
     * Gets the exceptions.
     *
     * @return \Ivory\HttpAdapter\HttpAdapterException[] The exceptions.
     */
    public function getExceptions()
    {
        return $this->exceptions;
    }

    /**
     * Sets the exceptions.
     *
     * @param \Ivory\HttpAdapter\HttpAdapterException[] $exceptions The exceptions.
     */
    public function setExceptions(array $exceptions)
    {
        $this->clearExceptions();
        $this->addExceptions($exceptions);
    }

    /**
     * Adds the exceptions.
     *
     * @param \Ivory\HttpAdapter\HttpAdapterException[] $exceptions The exceptions.
     */
    public function addExceptions(array $exceptions)
    {
        foreach ($exceptions as $exception) {
            $this->addException($exception);
        }
    }

    /**
     * Removes the exceptions.
     *
     * @param \Ivory\HttpAdapter\HttpAdapterException[] $exceptions The exceptions.
     */
    public function removeExceptions(array $exceptions)
    {
        foreach ($exceptions as $exception) {
            $this->removeException($exception);
        }
    }

    /**
     * Checks if there is an exception.
     *
     * @param \Ivory\HttpAdapter\HttpAdapterException $exception The exception.
     *
     * @return boolean TRUE if there is the exception else FALSE.
     */
    public function hasException(HttpAdapterException $exception)
    {
        return array_search($exception, $this->exceptions, true) !== false;
    }

    /**
     * Adds an exception.
     *
     * @param \Ivory\HttpAdapter\HttpAdapterException $exception The exception
     */
    public function addException(HttpAdapterException $exception)
    {
        $this->exceptions[] = $exception;
    }

    /**
     * Removes an exception.
     *
     * @param \Ivory\HttpAdapter\HttpAdapterException $exception The exception.
     */
    public function removeException(HttpAdapterException $exception)
    {
        unset($this->exceptions[array_search($exception, $this->exceptions, true)]);
        $this->exceptions = array_values($this->exceptions);
    }

    /**
     * Clears the responses.
     */
    public function clearResponses()
    {
        $this->responses = array();
    }

    /**
     * Checks if there are responses.
     *
     * @return boolean TRUE if there are responses else FALSE.
     */
    public function hasResponses()
    {
        return !empty($this->responses);
    }

    /**
     * Gets the responses.
     *
     * @return \Ivory\HttpAdapter\Message\ResponseInterface[] The responses.
     */
    public function getResponses()
    {
        return $this->responses;
    }

    /**
     * Sets the responses.
     *
     * @param \Ivory\HttpAdapter\Message\ResponseInterface[] $responses The responses.
     */
    public function setResponses(array $responses)
    {
        $this->clearResponses();
        $this->addResponses($responses);
    }

    /**
     * Adds the responses.
     *
     * @param \Ivory\HttpAdapter\Message\ResponseInterface[] $responses The responses.
     */
    public function addResponses(array $responses)
    {
        foreach ($responses as $response) {
            $this->addResponse($response);
        }
    }

    /**
     * Removes the responses.
     *
     * @param \Ivory\HttpAdapter\Message\ResponseInterface[] $responses The responses.
     */
    public function removeResponses(array $responses)
    {
        foreach ($responses as $response) {
            $this->removeResponse($response);
        }
    }

    /**
     * Checks if there is a response.
     *
     * @param \Ivory\HttpAdapter\Message\ResponseInterface $response The response.
     *
     * @return boolean TRUE if there is the response else FALSE.
     */
    public function hasResponse(ResponseInterface $response)
    {
        return array_search($response, $this->responses, true) !== false;
    }

    /**
     * Adds a response.
     *
     * @param \Ivory\HttpAdapter\Message\ResponseInterface $response The response.
     */
    public function addResponse(ResponseInterface $response)
    {
        $this->responses[] = $response;
    }

    /**
     * Removes a response.
     *
     * @param \Ivory\HttpAdapter\Message\ResponseInterface $response The response.
     */
    public function removeResponse(ResponseInterface $response)
    {
        unset($this->responses[array_search($response, $this->responses, true)]);
        $this->responses = array_values($this->responses);
    }
}


text:
<?php

namespace Encore\Admin\Grid\Exporters;

use Encore\Admin\Grid;

abstract class AbstractExporter implements ExporterInterface
{
    /**
     * @var \Encore\Admin\Grid
     */
    protected $grid;

    /**
     * @var int
     */
    protected $page;

    /**
     * Create a new exporter instance.
     *
     * @param $grid
     */
    public function __construct(Grid $grid = null)
    {
        if ($grid) {
            $this->setGrid($grid);
        }
    }

    /**
     * Set grid for exporter.
     *
     * @param Grid $grid
     *
     * @return $this
     */
    public function setGrid(Grid $grid)
    {
        $this->grid = $grid;

        return $this;
    }

    /**
     * Get table of grid.
     *
     * @return string
     */
    public function getTable()
    {
        return $this->grid->model()->getOriginalModel()->getTable();
    }

    /**
     * Get data with export query.
     *
     * @param bool $toArray
     *
     * @return array|\Illuminate\Support\Collection|mixed
     */
    public function getData($toArray = true)
    {
        return $this->grid->getFilter()->execute($toArray);
    }

    /**
     * @param callable $callback
     * @param int      $count
     *
     * @return bool
     */
    public function chunk(callable $callback, $count = 100)
    {
        $this->grid->applyQuery();

        return $this->grid->getFilter()->chunk($callback, $count);
    }

    /**
     * @return \Illuminate\Support\Collection
     */
    public function getCollection()
    {
        return collect($this->getData());
    }

    /**
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model
     */
    public function getQuery()
    {
        $model = $this->grid->getFilter()->getModel();

        $queryBuilder = $model->getQueryBuilder();

        // Export data of giving page number.
        if ($this->page) {
            $keyName = $this->grid->getKeyName();
            $perPage = request($model->getPerPageName(), $model->getPerPage());

            $scope = (clone $queryBuilder)
                ->select([$keyName])
                ->setEagerLoads([])
                ->forPage($this->page, $perPage)->get();
            // If $querybuilder is a Model, it must be reassigned, unless it is a eloquent/query builder.
            $queryBuilder = $queryBuilder->whereIn($keyName, $scope->pluck($keyName));
        }

        return $queryBuilder;
    }

    /**
     * Export data with scope.
     *
     * @param string $scope
     *
     * @return $this
     */
    public function withScope($scope)
    {
        if ($scope == Grid\Exporter::SCOPE_ALL) {
            return $this;
        }

        list($scope, $args) = explode(':', $scope);

        if ($scope == Grid\Exporter::SCOPE_CURRENT_PAGE) {
            $this->grid->model()->usePaginate(true);
            $this->page = $args ?: 1;
        }

        if ($scope == Grid\Exporter::SCOPE_SELECTED_ROWS) {
            $selected = explode(',', $args);
            $this->grid->model()->whereIn($this->grid->getKeyName(), $selected);
        }

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    abstract public function export();
}


text:
package org.apache.flink.connector.pulsar.source.enumerator;

import org.apache.flink.api.connector.source.ReaderInfo;
import org.apache.flink.api.connector.source.SplitsAssignment;
import org.apache.flink.api.connector.source.mocks.MockSplitEnumeratorContext;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.pulsar.source.config.SourceConfiguration;
import org.apache.flink.connector.pulsar.source.enumerator.cursor.StartCursor;
import org.apache.flink.connector.pulsar.source.enumerator.cursor.StopCursor;
import org.apache.flink.connector.pulsar.source.enumerator.subscriber.PulsarSubscriber;
import org.apache.flink.connector.pulsar.source.enumerator.topic.TopicPartition;
import org.apache.flink.connector.pulsar.source.enumerator.topic.range.FullRangeGenerator;
import org.apache.flink.connector.pulsar.source.split.PulsarPartitionSplit;
import org.apache.flink.connector.pulsar.testutils.PulsarTestSuiteBase;

import org.apache.flink.shaded.guava30.com.google.common.collect.ImmutableSet;

import org.apache.pulsar.client.api.RegexSubscriptionMode;
import org.apache.pulsar.client.api.SubscriptionType;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import static java.util.stream.Collectors.toSet;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.apache.flink.connector.pulsar.source.PulsarSourceOptions.PULSAR_PARTITION_DISCOVERY_INTERVAL_MS;
import static org.apache.flink.connector.pulsar.source.PulsarSourceOptions.PULSAR_SUBSCRIPTION_NAME;
import static org.apache.flink.connector.pulsar.source.PulsarSourceOptions.PULSAR_SUBSCRIPTION_TYPE;
import static org.apache.flink.connector.pulsar.source.enumerator.PulsarSourceEnumState.initialState;
import static org.apache.flink.connector.pulsar.source.enumerator.subscriber.PulsarSubscriber.getTopicPatternSubscriber;
import static org.apache.flink.connector.pulsar.testutils.runtime.PulsarRuntimeOperator.DEFAULT_PARTITIONS;
import static org.apache.flink.shaded.guava30.com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;
import static org.assertj.core.api.Assertions.assertThat;

/** Unit tests for {@link PulsarSourceEnumerator}. */
class PulsarSourceEnumeratorTest extends PulsarTestSuiteBase {

    private static final int NUM_SUBTASKS = 3;
    private static final int READER0 = 0;
    private static final int READER1 = 1;
    private static final int READER2 = 2;
    private static final int PARTITION_DISCOVERY_CALLABLE_INDEX = 0;
    private static final boolean ENABLE_PERIODIC_PARTITION_DISCOVERY = true;
    private static final boolean DISABLE_PERIODIC_PARTITION_DISCOVERY = false;

    @ParameterizedTest
    @EnumSource(
            value = SubscriptionType.class,
            names = {"Failover", "Shared"})
    void startWithDiscoverPartitionsOnce(SubscriptionType subscriptionType) throws Exception {
        Set<String> preexistingTopics = setupPreexistingTopics();
        try (MockSplitEnumeratorContext<PulsarPartitionSplit> context =
                        new MockSplitEnumeratorContext<>(NUM_SUBTASKS);
                PulsarSourceEnumerator enumerator =
                        createEnumerator(
                                subscriptionType,
                                preexistingTopics,
                                context,
                                DISABLE_PERIODIC_PARTITION_DISCOVERY)) {

            // Start the enumerator and it should schedule a one time task to discover and assign
            // partitions.
            enumerator.start();
            assertThat(context.getPeriodicCallables()).isEmpty();
            assertThat(context.getOneTimeCallables())
                    .as("A one time partition discovery callable should have been scheduled")
                    .hasSize(1);
        }
    }

    @ParameterizedTest
    @EnumSource(
            value = SubscriptionType.class,
            names = {"Failover", "Shared"})
    void startWithPeriodicPartitionDiscovery(SubscriptionType subscriptionType) throws Exception {
        Set<String> preexistingTopics = setupPreexistingTopics();
        try (MockSplitEnumeratorContext<PulsarPartitionSplit> context =
                        new MockSplitEnumeratorContext<>(NUM_SUBTASKS);
                PulsarSourceEnumerator enumerator =
                        createEnumerator(
                                subscriptionType,
                                preexistingTopics,
                                context,
                                ENABLE_PERIODIC_PARTITION_DISCOVERY)) {

            enumerator.start();
            assertThat(context.getOneTimeCallables()).isEmpty();
            assertThat((context.getPeriodicCallables()))
                    .as("A periodic partition discovery callable should have been scheduled")
                    .hasSize(1);
        }
    }

    @ParameterizedTest
    @EnumSource(
            value = SubscriptionType.class,
            names = {"Failover", "Shared"})
    void discoverPartitionsTriggersAssignments(SubscriptionType subscriptionType) throws Throwable {
        Set<String> preexistingTopics = setupPreexistingTopics();
        try (MockSplitEnumeratorContext<PulsarPartitionSplit> context =
                        new MockSplitEnumeratorContext<>(NUM_SUBTASKS);
                PulsarSourceEnumerator enumerator =
                        createEnumerator(
                                subscriptionType,
                                preexistingTopics,
                                context,
                                DISABLE_PERIODIC_PARTITION_DISCOVERY)) {

            enumerator.start();

            // register reader 0, 1, 2
            registerReader(context, enumerator, READER0);
            registerReader(context, enumerator, READER1);
            registerReader(context, enumerator, READER2);
            assertThat(context.getSplitsAssignmentSequence()).isEmpty();

            // Run the partition discover callable and check the partition assignment.
            runOneTimePartitionDiscovery(context);
            verifyAllReaderAssignments(subscriptionType, context, preexistingTopics, 1);
        }
    }

    @ParameterizedTest
    @EnumSource(
            value = SubscriptionType.class,
            names = {"Failover", "Shared"})
    void discoverPartitionsPeriodically(SubscriptionType subscriptionType) throws Throwable {
        String dynamicTopic = "topic3-" + randomAlphabetic(10);
        Set<String> preexistingTopics = setupPreexistingTopics();
        Set<String> topicsToSubscribe = new HashSet<>(preexistingTopics);
        topicsToSubscribe.add(dynamicTopic);
        try (MockSplitEnumeratorContext<PulsarPartitionSplit> context =
                        new MockSplitEnumeratorContext<>(NUM_SUBTASKS);
                PulsarSourceEnumerator enumerator =
                        createEnumerator(
                                subscriptionType,
                                topicsToSubscribe,
                                context,
                                ENABLE_PERIODIC_PARTITION_DISCOVERY)) {

            testRegisterReadersForPreexistingTopics(
                    subscriptionType, preexistingTopics, context, enumerator);

            // invoke partition discovery callable again and there should be no new assignments.
            runPeriodicPartitionDiscovery(context);

            assertThat(context.getSplitsAssignmentSequence())
                    .as("No new assignments should be made because there is no partition change")
                    .hasSize(3);

            // Create the dynamic topic.
            operator().createTopic(dynamicTopic, DEFAULT_PARTITIONS);

            // Invoke partition discovery callable again.
            while (true) {
                runPeriodicPartitionDiscovery(context);
                if (context.getSplitsAssignmentSequence().size() < 4) {
                    sleepUninterruptibly(10, TimeUnit.MILLISECONDS);
                } else {
                    break;
                }
            }
            verifyAllReaderAssignments(subscriptionType, context, topicsToSubscribe, 4);
        }
    }

    @ParameterizedTest
    @EnumSource(
            value = SubscriptionType.class,
            names = {"Failover", "Shared"})
    void addSplitsBack(SubscriptionType subscriptionType) throws Throwable {
        Set<String> preexistingTopics = setupPreexistingTopics();
        try (MockSplitEnumeratorContext<PulsarPartitionSplit> context =
                        new MockSplitEnumeratorContext<>(NUM_SUBTASKS);
                PulsarSourceEnumerator enumerator =
                        createEnumerator(
                                subscriptionType,
                                preexistingTopics,
                                context,
                                ENABLE_PERIODIC_PARTITION_DISCOVERY)) {

            testRegisterReadersForPreexistingTopics(
                    subscriptionType, preexistingTopics, context, enumerator);

            // Simulate a reader failure.
            context.unregisterReader(READER0);
            enumerator.addSplitsBack(
                    context.getSplitsAssignmentSequence().get(0).assignment().get(READER0),
                    READER0);
            assertThat(context.getSplitsAssignmentSequence())
                    .as("The added back splits should have not been assigned")
                    .hasSize(3);

            // Simulate a reader recovery.
            registerReader(context, enumerator, READER0);
            verifyAllReaderAssignments(subscriptionType, context, preexistingTopics, 3 + 1);
        }
    }

    @ParameterizedTest
    @EnumSource(
            value = SubscriptionType.class,
            names = {"Failover", "Shared"})
    void workWithPreexistingAssignments(SubscriptionType subscriptionType) throws Throwable {
        Set<String> preexistingTopics = setupPreexistingTopics();
        PulsarSourceEnumState preexistingAssignments;
        try (MockSplitEnumeratorContext<PulsarPartitionSplit> context1 =
                        new MockSplitEnumeratorContext<>(NUM_SUBTASKS);
                PulsarSourceEnumerator enumerator =
                        createEnumerator(
                                subscriptionType,
                                preexistingTopics,
                                context1,
                                ENABLE_PERIODIC_PARTITION_DISCOVERY)) {
            testRegisterReadersForPreexistingTopics(
                    subscriptionType, preexistingTopics, context1, enumerator);
            preexistingAssignments =
                    asEnumState(context1.getSplitsAssignmentSequence().get(0).assignment());
        }

        try (MockSplitEnumeratorContext<PulsarPartitionSplit> context2 =
                        new MockSplitEnumeratorContext<>(NUM_SUBTASKS);
                PulsarSourceEnumerator enumerator =
                        createEnumerator(
                                subscriptionType,
                                preexistingTopics,
                                context2,
                                ENABLE_PERIODIC_PARTITION_DISCOVERY,
                                preexistingAssignments)) {
            enumerator.start();
            runPeriodicPartitionDiscovery(context2);

            registerReader(context2, enumerator, READER0);
            if (subscriptionType == SubscriptionType.Shared) {
                verifyAllReaderAssignments(subscriptionType, context2, preexistingTopics, 1);
            } else {
                assertThat(context2.getSplitsAssignmentSequence()).isEmpty();
            }
        }
    }

    @ParameterizedTest
    @EnumSource(
            value = SubscriptionType.class,
            names = {"Failover", "Shared"})
    void snapshotState(SubscriptionType subscriptionType) throws Throwable {
        Set<String> preexistingTopics = setupPreexistingTopics();
        try (MockSplitEnumeratorContext<PulsarPartitionSplit> context =
                        new MockSplitEnumeratorContext<>(NUM_SUBTASKS);
                PulsarSourceEnumerator enumerator =
                        createEnumerator(subscriptionType, preexistingTopics, context, false)) {
            enumerator.start();

            // No reader is registered, so the state should be empty
            final PulsarSourceEnumState state1 = enumerator.snapshotState(1L);
            assertThat(state1.getAppendedPartitions()).isEmpty();

            registerReader(context, enumerator, READER0);
            registerReader(context, enumerator, READER1);
            runOneTimePartitionDiscovery(context);

            // The state should contain splits assigned to READER0 and READER1
            final PulsarSourceEnumState state2 = enumerator.snapshotState(1L);
            verifySplitAssignmentWithPartitions(
                    getExpectedTopicPartitions(preexistingTopics), state2.getAppendedPartitions());
        }
    }

    private Set<String> setupPreexistingTopics() {
        String topic1 = "topic1-" + randomAlphabetic(10);
        String topic2 = "topic2-" + randomAlphabetic(10);

        operator().setupTopic(topic1);
        operator().setupTopic(topic2);

        return ImmutableSet.of(topic1, topic2);
    }

    private void testRegisterReadersForPreexistingTopics(
            SubscriptionType subscriptionType,
            Set<String> topics,
            MockSplitEnumeratorContext<PulsarPartitionSplit> context,
            PulsarSourceEnumerator enumerator)
            throws Throwable {
        enumerator.start();

        // register reader 0 before the partition discovery.
        registerReader(context, enumerator, READER0);
        assertThat(context.getSplitsAssignmentSequence()).isEmpty();

        // Run the partition discover callable and check the partition assignment.
        runPeriodicPartitionDiscovery(context);
        if (subscriptionType == SubscriptionType.Shared) {
            verifyAllReaderAssignments(subscriptionType, context, topics, 1);
        }

        registerReader(context, enumerator, READER1);
        registerReader(context, enumerator, READER2);

        verifyAllReaderAssignments(subscriptionType, context, topics, 3);
    }

    private PulsarSourceEnumerator createEnumerator(
            SubscriptionType subscriptionType,
            Set<String> topics,
            MockSplitEnumeratorContext<PulsarPartitionSplit> enumContext,
            boolean enablePeriodicPartitionDiscovery) {
        return createEnumerator(
                subscriptionType,
                topics,
                enumContext,
                enablePeriodicPartitionDiscovery,
                initialState());
    }

    private PulsarSourceEnumerator createEnumerator(
            SubscriptionType subscriptionType,
            Set<String> topicsToSubscribe,
            MockSplitEnumeratorContext<PulsarPartitionSplit> enumContext,
            boolean enablePeriodicPartitionDiscovery,
            PulsarSourceEnumState sourceEnumState) {
        // Use a TopicPatternSubscriber so that no exception if a subscribed topic hasn't been
        // created yet.
        String topicRegex = String.join("|", topicsToSubscribe);
        Pattern topicPattern = Pattern.compile(topicRegex);
        PulsarSubscriber subscriber =
                getTopicPatternSubscriber(topicPattern, RegexSubscriptionMode.AllTopics);

        Configuration configuration = operator().config();
        configuration.set(PULSAR_SUBSCRIPTION_TYPE, subscriptionType);
        configuration.set(PULSAR_SUBSCRIPTION_NAME, randomAlphabetic(10));
        if (enablePeriodicPartitionDiscovery) {
            configuration.set(PULSAR_PARTITION_DISCOVERY_INTERVAL_MS, 60L);
        } else {
            configuration.set(PULSAR_PARTITION_DISCOVERY_INTERVAL_MS, -1L);
        }

        return new PulsarSourceEnumerator(
                subscriber,
                StartCursor.earliest(),
                StopCursor.latest(),
                new FullRangeGenerator(),
                new SourceConfiguration(configuration),
                enumContext,
                sourceEnumState);
    }

    private void registerReader(
            MockSplitEnumeratorContext<PulsarPartitionSplit> context,
            PulsarSourceEnumerator enumerator,
            int reader) {
        context.registerReader(new ReaderInfo(reader, "testing location"));
        enumerator.addReader(reader);
    }

    private void verifyAllReaderAssignments(
            SubscriptionType subscriptionType,
            MockSplitEnumeratorContext<PulsarPartitionSplit> context,
            Set<String> topics,
            int expectedAssignmentSeqSize) {
        assertThat(context.getSplitsAssignmentSequence()).hasSize(expectedAssignmentSeqSize);
        // Merge the assignments into one
        List<SplitsAssignment<PulsarPartitionSplit>> sequence =
                context.getSplitsAssignmentSequence();
        Map<Integer, Set<PulsarPartitionSplit>> assignments = new HashMap<>();

        for (int i = 0; i < expectedAssignmentSeqSize; i++) {
            Map<Integer, List<PulsarPartitionSplit>> assignment = sequence.get(i).assignment();
            assignment.forEach(
                    (key, value) ->
                            assignments.computeIfAbsent(key, k -> new HashSet<>()).addAll(value));
        }

        // Compare assigned partitions with desired partitions.
        Set<TopicPartition> expectedTopicPartitions = getExpectedTopicPartitions(topics);
        if (subscriptionType == SubscriptionType.Failover) {
            int actualSize = assignments.values().stream().mapToInt(Set::size).sum();
            assertThat(actualSize).isEqualTo(expectedTopicPartitions.size());
        } else if (subscriptionType == SubscriptionType.Shared) {
            assignments
                    .values()
                    .forEach(
                            (splits) -> assertThat(splits).hasSize(expectedTopicPartitions.size()));
        }
    }

    private Set<TopicPartition> getExpectedTopicPartitions(Set<String> topics) {
        Set<TopicPartition> allPartitions = new HashSet<>();
        for (String topicName : topics) {
            for (int i = 0; i < DEFAULT_PARTITIONS; i++) {
                allPartitions.add(new TopicPartition(topicName, i));
            }
        }
        return allPartitions;
    }

    private void verifySplitAssignmentWithPartitions(
            Set<TopicPartition> expectedAssignment, Set<TopicPartition> actualTopicPartitions) {
        assertThat(actualTopicPartitions).isEqualTo(expectedAssignment);
    }

    // this method only works for non-Shared Mode
    private PulsarSourceEnumState asEnumState(
            Map<Integer, List<PulsarPartitionSplit>> assignments) {
        Set<TopicPartition> appendedPartitions =
                assignments.values().stream()
                        .flatMap(List::stream)
                        .map(PulsarPartitionSplit::getPartition)
                        .collect(toSet());

        return new PulsarSourceEnumState(appendedPartitions);
    }

    private void runOneTimePartitionDiscovery(
            MockSplitEnumeratorContext<PulsarPartitionSplit> context) throws Throwable {
        // Fetch potential topic descriptions
        context.runNextOneTimeCallable();
        if (!context.getOneTimeCallables().isEmpty()) {
            context.runNextOneTimeCallable();
        }
    }

    private void runPeriodicPartitionDiscovery(
            MockSplitEnumeratorContext<PulsarPartitionSplit> context) throws Throwable {
        // Fetch potential topic descriptions
        context.runPeriodicCallable(PARTITION_DISCOVERY_CALLABLE_INDEX);
        if (!context.getOneTimeCallables().isEmpty()) {
            context.runNextOneTimeCallable();
        }
    }
}


text:
[![Go Reference](https://pkg.go.dev/badge/github.com/shenwei356/bio/seq.svg)](https://pkg.go.dev/github.com/shenwei356/bio/seq)

This package defines `Seq` and `Alphabet` type, and provides some basic operations of sequence,
like validation of DNA/RNA/Protein sequence, getting reverse complement sequence and translation of RNA to protein.

This package was inspired by
[biogo](https://github.com/biogo/biogo/blob/master/alphabet/alphabet.go).


text:
using System.Buffers;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace System.Net.WebSockets
{
    internal static class ManagedWebSocketExtensions
    {
        internal static unsafe string GetString(this UTF8Encoding encoding, Span<byte> bytes)
        {
            fixed (byte* b = &MemoryMarshal.GetReference(bytes))
            {
                return encoding.GetString(b, bytes.Length);
            }
        }

        internal static Task<int> ReadAsync(this Stream stream, Memory<byte> destination, CancellationToken cancellationToken)
        {
            if (destination.TryGetArray(out ArraySegment<byte> array))
            {
                return stream.ReadAsync(array.Array, array.Offset, array.Count, cancellationToken);
            }
            else
            {
                byte[] buffer = ArrayPool<byte>.Shared.Rent(destination.Length);
                return FinishReadAsync(stream.ReadAsync(buffer, 0, destination.Length, cancellationToken), buffer, destination);

                async Task<int> FinishReadAsync(Task<int> readTask, byte[] localBuffer, Memory<byte> localDestination)
                {
                    try
                    {
                        int result = await readTask.ConfigureAwait(false);
                        new Span<byte>(localBuffer, 0, result).CopyTo(localDestination.Span);
                        return result;
                    }
                    finally
                    {
                        ArrayPool<byte>.Shared.Return(localBuffer);
                    }
                }
            }
        }
    }

    internal static class BitConverter
    {
        internal static unsafe int ToInt32(ReadOnlySpan<byte> value)
        {
            Debug.Assert(value.Length >= sizeof(int));
            return Unsafe.ReadUnaligned<int>(ref MemoryMarshal.GetReference(value));
        }
    }
}


text:
package fr.univnantes.termsuite.framework.modules;

import com.google.inject.AbstractModule;
import com.google.inject.Singleton;

import fr.univnantes.termsuite.framework.service.CorpusService;
import fr.univnantes.termsuite.framework.service.LanguageService;

public class TermSuiteModule extends AbstractModule {

	@Override
	protected void configure() {
		bind(CorpusService.class).in(Singleton.class);
		bind(LanguageService.class).in(Singleton.class);
	}
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Libraries;

import edu.wpi.first.wpilibj.Joystick;

/**
 *
 * @author Paul
 */
public class Joystick246 extends Joystick{

    double deadband = .1; // If the magnitude of the joystick is less than this value, it will be considered at 0

    public Joystick246(final int port) {
        super(port);
    }

    /**
     * Set the deadband value
     *
     * @param deadband If the magnitude of the joystick is less than this value, it will be considered at 0
     */
    public void setDeadband(double deadband)
    {
        this.deadband = deadband;
    }

    /**
     * Get the deadband value
     *
     * @return deadband If the magnitude of the joystick is less than this value, it will be considered at 0
     */
    public double getDeadband()
    {
        return deadband;
    }

    /**
     * Get the value of the axis.
     *
     * @param axis The axis to read [1-6].
     * @return The value of the axis.
     */
    public double getRawAxis(final int axis) {
        double val = super.getRawAxis(axis);
        if(Math.abs(val) <= deadband) return 0;
        else return val;
    }
}


text:
package com.zwh.mvparms.eyepetizer.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;

import com.jess.arms.di.component.AppComponent;
import com.jess.arms.mvp.IView;
import com.zwh.annotation.apt.Router;
import com.zwh.mvparms.eyepetizer.R;
import com.zwh.mvparms.eyepetizer.app.EventBusTags;
import com.zwh.mvparms.eyepetizer.app.constants.Constants;
import com.zwh.mvparms.eyepetizer.app.utils.GreenDaoHelper;
import com.zwh.mvparms.eyepetizer.app.utils.helper.CacheFragmentAdapter;
import com.zwh.mvparms.eyepetizer.mvp.model.entity.VideoDownLoadInfo;
import com.zwh.mvparms.eyepetizer.mvp.model.entity.VideoDownLoadInfoDao;
import com.zwh.mvparms.eyepetizer.mvp.ui.fragment.CacheFragment;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

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

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;

@Router(Constants.CACHE)
public class CacheActivity extends BaseActivity implements IView{

    public final static String FROM_NOTIFICATION = "from_notification";

    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.tl_tabs)
    TabLayout mTlTabs;
    @BindView(R.id.appbar)
    AppBarLayout mAppbar;
    @BindView(R.id.viewpager)
    ViewPager mViewpager;

    private boolean isFromNotification = false;

    private AppComponent mAppComponent;
    private List<CacheFragment> fragments = new ArrayList<>();
    private int size = 0;

    @Override
    public void setupActivityComponent(AppComponent appComponent) {
        mAppComponent = appComponent;
    }

    @Override
    public int initView(Bundle savedInstanceState) {
        return R.layout.activity_cache;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        isFromNotification = getIntent().getBooleanExtra(FROM_NOTIFICATION,false);
        initToolBar();
        VideoDownLoadInfo entity = new VideoDownLoadInfo();
        List<VideoDownLoadInfo> infos = GreenDaoHelper.getInstance().create(entity.getDbName())
                .getMaster().newSession()
                .getVideoDownLoadInfoDao().queryBuilder()
                .where(VideoDownLoadInfoDao.Properties.Finish.eq(false ))
                .list();
        List<String> list = new ArrayList<>();
        list.add("已缓存");
        list.add("正在缓存"+"("+(infos==null?0:infos.size())+")");
        Observable.fromIterable(list)
                .map(new Function<String, CacheFragment>() {
                    @Override
                    public CacheFragment apply(@NonNull String category) throws Exception {
                        CacheFragment fragment = CacheFragment.newInstance(category);
                        fragments.add(fragment);
                        return fragment;
                    }
                })
                .toList()
                .map(fragments -> CacheFragmentAdapter.newInstance(getSupportFragmentManager(), fragments, list))
                .subscribe(mFragmentAdapter -> mViewpager.setAdapter(mFragmentAdapter));
        mTlTabs.setupWithViewPager(mViewpager);
        if (isFromNotification){
            mViewpager.setCurrentItem(1);
        }else {
            mViewpager.setCurrentItem(0);
        }

    }

    @Subscriber(tag = EventBusTags.CACHE_DOWNLOAD_FINISH)
    private void downloadFinish(String tag) {
        VideoDownLoadInfo entity = new VideoDownLoadInfo();
        List<VideoDownLoadInfo> infos = GreenDaoHelper.getInstance().create(entity.getDbName())
                .getMaster().newSession()
                .getVideoDownLoadInfoDao().queryBuilder()
                .where(VideoDownLoadInfoDao.Properties.Finish.eq(false ))
                .list();
        mTlTabs.getTabAt(1).setText("正在缓存"+"("+(infos==null?0:infos.size())+")");
        size = infos.size();
    }
    @Subscriber(tag = EventBusTags.CACHE_DOWNLOAD_DELETE)
    private void downloadDelete(String tag) {
        size = size - 1;
        mTlTabs.getTabAt(1).setText("正在缓存"+"("+size+")");

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(String message) {

    }

    @Override
    public void launchActivity(Intent intent) {

    }

    @Override
    public void killMyself() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().removeStickyEvent(VideoDownLoadInfo.class,EventBusTags.CACHE_DOWNLOAD_BEGIN);
    }

    @Override
    protected boolean isDisplayHomeAsUpEnabled() {
        return true;
    }
}


text:
<!doctype html>

  <meta charset="utf-8">

  <title>Anchor Bay Tattoos</title>
  <meta name="description" content="Project 1">
  <meta name="Author" content="Darren Kane">
  <link rel="stylesheet" href="css/normalize.css" media="screen" title="no title">
  <link rel="stylesheet" href="zurb/css/foundation.css" />
  <link rel="stylesheet" href="zurb/css/app.css" />
  <link rel="stylesheet" href="css/style.css" media="screen" title="no title">

  <link href="https://fonts.googleapis.com/css?family=Ewert" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Playfair+Display+SC" rel="stylesheet">

    Home

Anchor Bay Tattoos

        History |
        Tattoo Artists |
        Gallery |
        Media |
        Contact Us |
        Presentation

Artists

 Pat Jones

August Pakzul Jones

Dalia

             ×

             &nbsp
             &nbsp
              Job Address:22622 Mission Blvrd. Hayward,CA 94541
             &nbsp
             &nbsp
             Call: 510.538.3863


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Class: PrecinctSplitsController</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <link rel="stylesheet" href=".././rdoc-style.css" type="text/css" media="screen" />

          Class
          PrecinctSplitsController

            In:

                lib/app/controllers/precinct_splits_controller.rb

            Parent:

                ApplicationController

Methods

      create
      destroy
      edit
      index
      new
      show
      update

Public Instance methods

          create()

POST /precinct_splits POST /precinct_splits.xml

[Source]

    # File lib/app/controllers/precinct_splits_controller.rb, line 42
42:   def create
43:     @precinct_split = PrecinctSplit.new(params[:precinct_split])
44:
45:     respond_to do |format|
46:       if @precinct_split.save
47:         flash[:notice] = 'PrecinctSplit was successfully created.'
48:         format.html { redirect_to(@precinct_split) }
49:         format.xml  { render :xml => @precinct_split, :status => :created, :location => @precinct_split }
50:       else
51:         format.html { render :action => "new" }
52:         format.xml  { render :xml => @precinct_split.errors, :status => :unprocessable_entity }
53:       end
54:     end
55:   end

          destroy()

DELETE /precinct_splits/1 DELETE /precinct_splits/1.xml

[Source]

    # File lib/app/controllers/precinct_splits_controller.rb, line 76
76:   def destroy
77:     @precinct_split = PrecinctSplit.find(params[:id])
78:     @precinct_split.destroy
79:
80:     respond_to do |format|
81:       format.html { redirect_to(precinct_splits_url) }
82:       format.xml  { head :ok }
83:     end
84:   end

          edit()

GET /precinct_splits/1/edit

[Source]

    # File lib/app/controllers/precinct_splits_controller.rb, line 36
36:   def edit
37:     @precinct_split = PrecinctSplit.find(params[:id])
38:   end

          index()

GET /precinct_splits GET /precinct_splits.xml

[Source]

    # File lib/app/controllers/precinct_splits_controller.rb, line 4
 4:   def index
 5:     @precinct_splits = PrecinctSplit.find(:all)
 6:
 7:     respond_to do |format|
 8:       format.html # index.html.erb
 9:       format.xml  { render :xml => @precinct_splits }
10:     end
11:   end

          new()

GET /precinct_splits/new GET /precinct_splits/new.xml

[Source]

    # File lib/app/controllers/precinct_splits_controller.rb, line 26
26:   def new
27:     @precinct_split = PrecinctSplit.new
28:
29:     respond_to do |format|
30:       format.html # new.html.erb
31:       format.xml  { render :xml => @precinct_split }
32:     end
33:   end

          show()

GET /precinct_splits/1 GET /precinct_splits/1.xml

[Source]

    # File lib/app/controllers/precinct_splits_controller.rb, line 15
15:   def show
16:     @precinct_split = PrecinctSplit.find(params[:id])
17:
18:     respond_to do |format|
19:       format.html # show.html.erb
20:       format.xml  { render :xml => @precinct_split }
21:     end
22:   end

          update()

PUT /precinct_splits/1 PUT /precinct_splits/1.xml

[Source]

    # File lib/app/controllers/precinct_splits_controller.rb, line 59
59:   def update
60:     @precinct_split = PrecinctSplit.find(params[:id])
61:
62:     respond_to do |format|
63:       if @precinct_split.update_attributes(params[:precinct_split])
64:         flash[:notice] = 'PrecinctSplit was successfully updated.'
65:         format.html { redirect_to(@precinct_split) }
66:         format.xml  { head :ok }
67:       else
68:         format.html { render :action => "edit" }
69:         format.xml  { render :xml => @precinct_split.errors, :status => :unprocessable_entity }
70:       end
71:     end
72:   end

[Validate]


text:
package com.intellij.testGuiFramework.fixtures;

import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.Ref;
import org.fest.reflect.exception.ReflectionError;
import org.fest.reflect.reference.TypeRef;
import org.fest.swing.core.GenericTypeMatcher;
import org.fest.swing.core.Robot;
import org.fest.swing.fixture.ContainerFixture;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.annotation.Nonnull;
import javax.swing.*;
import java.lang.ref.WeakReference;

import static com.intellij.testGuiFramework.framework.GuiTestUtil.findAndClickCancelButton;
import static com.intellij.testGuiFramework.framework.GuiTestUtil.waitUntilFound;
import static junit.framework.Assert.assertNotNull;
import static org.fest.reflect.core.Reflection.field;

@Nonnull
public abstract class IdeaDialogFixture<T extends DialogWrapper> extends ComponentFixture<IdeaDialogFixture, JDialog> implements ContainerFixture<JDialog> {
  @NotNull private final T myDialogWrapper;

  @Nullable
  protected static <T extends DialogWrapper> T getDialogWrapperFrom(@NotNull JDialog dialog, Class<T> dialogWrapperType) {
    try {
      WeakReference<DialogWrapper> dialogWrapperRef = field("myDialogWrapper").ofType(new TypeRef<WeakReference<DialogWrapper>>() {})
        .in(dialog)
        .get();
      assertNotNull(dialogWrapperRef);
      DialogWrapper wrapper = dialogWrapperRef.get();
      if (dialogWrapperType.isInstance(wrapper)) {
        return dialogWrapperType.cast(wrapper);
      }
    }
    catch (ReflectionError ignored) {
    }
    return null;
  }

  public static class DialogAndWrapper<T extends DialogWrapper> {
    public final JDialog dialog;
    public final T wrapper;

    public DialogAndWrapper(@NotNull JDialog dialog, @NotNull T wrapper) {
      this.dialog = dialog;
      this.wrapper = wrapper;
    }
  }

  @NotNull
  public static <T extends DialogWrapper> DialogAndWrapper<T> find(@NotNull Robot robot, @NotNull final Class<T> clz) {
    return find(robot, clz, new GenericTypeMatcher<JDialog>(JDialog.class) {
      @Override
      protected boolean isMatching(@NotNull JDialog component) {
        return component.isShowing();
      }
    });
  }

  @NotNull
  public static <T extends DialogWrapper> DialogAndWrapper<T> find(@NotNull Robot robot, @NotNull final Class<T> clz,
                                                                   @NotNull final GenericTypeMatcher<JDialog> matcher) {
    final Ref<T> wrapperRef = new Ref<T>();
    JDialog dialog = waitUntilFound(robot, new GenericTypeMatcher<JDialog>(JDialog.class) {
      @Override
      protected boolean isMatching(@NotNull JDialog dialog) {
        if (matcher.matches(dialog)) {
          T wrapper = getDialogWrapperFrom(dialog, clz);
          if (wrapper != null) {
            wrapperRef.set(wrapper);
            return true;
          }
        }
        return false;
      }
    });
    return new DialogAndWrapper<T>(dialog, wrapperRef.get());
  }

  protected IdeaDialogFixture(@NotNull Robot robot, @NotNull JDialog target, @NotNull T dialogWrapper) {
    super(IdeaDialogFixture.class, robot, target);
    myDialogWrapper = dialogWrapper;
  }

  protected IdeaDialogFixture(@NotNull Robot robot, @NotNull DialogAndWrapper<T> dialogAndWrapper) {
    this(robot, dialogAndWrapper.dialog, dialogAndWrapper.wrapper);
  }

  @NotNull
  protected T getDialogWrapper() {
    return myDialogWrapper;
  }

  public void clickCancel() {
    // Grab focus in case it is not automatically done by the window manager, e.g. 9wm
    focus();

    findAndClickCancelButton(this);
  }

  public void close() {
    robot().close(target());
  }
}