text:
require "#{File.dirname(__FILE__)}/../../abstract_unit"
require 'action_controller/cgi_process'
require 'action_controller/cgi_ext'

class CGI::Session
  def cache
    dbman.instance_variable_get(:@cache)
  end
end

uses_mocha 'MemCacheStore tests' do
if defined? MemCache::MemCacheError

class MemCacheStoreTest < Test::Unit::TestCase
  SESSION_KEY_RE = /^session:[0-9a-z]+/
  CONN_TEST_KEY = 'connection_test'
  MULTI_TEST_KEY = '0123456789'
  TEST_DATA = 'Hello test'

  def self.get_mem_cache_if_available
    begin
      require 'memcache'
      cache = MemCache.new('127.0.0.1')
      # Test availability of the connection
      cache.set(CONN_TEST_KEY, 1)
      unless cache.get(CONN_TEST_KEY) == 1
        puts 'Warning: memcache server available but corrupted.'
        return nil
      end
    rescue LoadError, MemCache::MemCacheError
      return nil
    end
    return cache
  end

  CACHE = get_mem_cache_if_available

  def test_initialization
    assert_raise(ArgumentError) { new_session('session_id' => '!invalid_id') }
    new_session do |s|
      assert_equal Hash.new, s.cache.get('session:' + s.session_id)
    end
  end

  def test_storage
    d = rand(0xffff)
    new_session do |s|
      session_key = 'session:' + s.session_id
      unless CACHE
        s.cache.expects(:get).with(session_key) \
                             .returns(:test => d)
        s.cache.expects(:set).with(session_key,
                                   has_entry(:test, d),
                                   0)
      end
      s[:test] = d
      s.close
      assert_equal d, s.cache.get(session_key)[:test]
      assert_equal d, s[:test]
    end
  end

  def test_deletion
    new_session do |s|
      session_key = 'session:' + s.session_id
      unless CACHE
        s.cache.expects(:delete)
        s.cache.expects(:get).with(session_key) \
                             .returns(nil)
      end
      s[:test] = rand(0xffff)
      s.delete
      assert_nil s.cache.get(session_key)
    end
  end

  def test_other_session_retrieval
    new_session do |sa|
      unless CACHE
        sa.cache.expects(:set).with('session:' + sa.session_id,
                                    has_entry(:test, TEST_DATA),
                                    0)
      end
      sa[:test] = TEST_DATA
      sa.close
      new_session('session_id' => sa.session_id) do |sb|
        unless CACHE
          sb.cache.expects(:[]).with('session:' + sb.session_id) \
                               .returns(:test => TEST_DATA)
        end
        assert_equal(TEST_DATA, sb[:test])
      end
    end
  end

  def test_multiple_sessions
    s_slots = Array.new(10)
    operation = :write
    last_data = nil
    reads = writes = 0
    50.times do
      current = rand(10)
      s_slots[current] ||= new_session('session_id' => MULTI_TEST_KEY,
                                       'new_session' => true)
      s = s_slots[current]
      case operation
      when :write
        last_data = rand(0xffff)
        unless CACHE
          s.cache.expects(:set).with('session:' + MULTI_TEST_KEY,
                                     { :test => last_data },
                                     0)
        end
        s[:test] = last_data
        s.close
        writes += 1
      when :read
        # Make CGI::Session#[] think there was no data retrieval yet.
        # Normally, the session caches the data during its lifetime.
        s.instance_variable_set(:@data, nil)
        unless CACHE
          s.cache.expects(:[]).with('session:' + MULTI_TEST_KEY) \
                              .returns(:test => last_data)
        end
        d = s[:test]
        assert_equal(last_data, d, "OK reads: #{reads}, OK writes: #{writes}")
        reads += 1
      end
      operation = rand(5) == 0 ? :write : :read
    end
  end

  private
  def obtain_session_options
    options = { 'database_manager' => CGI::Session::MemCacheStore,
                'session_key' => '_test_app_session'
              }
    # if don't have running memcache server we use mock instead
    unless CACHE
      options['cache'] = c = mock
      c.stubs(:[]).with(regexp_matches(SESSION_KEY_RE))
      c.stubs(:get).with(regexp_matches(SESSION_KEY_RE)) \
                   .returns(Hash.new)
      c.stubs(:add).with(regexp_matches(SESSION_KEY_RE),
                         instance_of(Hash),
                         0)
    end
    options
  end

  def new_session(options = {})
    with_cgi do |cgi|
      @options = obtain_session_options.merge(options)
      session = CGI::Session.new(cgi, @options)
      yield session if block_given?
      return session
    end
  end

  def with_cgi
    ENV['REQUEST_METHOD'] = 'GET'
    ENV['HTTP_HOST'] = 'example.com'
    ENV['QUERY_STRING'] = ''

    cgi = CGI.new('query', StringIO.new(''))
    yield cgi if block_given?
    cgi
  end
end

end # defined? MemCache
end # uses_mocha


text:
require 'uri'

module RuboCop
  module Cop
    module Style
      # This cop checks the length of lines in the source code.
      # The maximum length is configurable.
      class LineLength < Cop
        include ConfigurableMax

        MSG = 'Line is too long. [%d/%d]'

        def investigate(processed_source)
          processed_source.lines.each_with_index do |line, index|
            next unless line.length > max

            if allow_uri?
              uri_range = find_excessive_uri_range(line)
              next if uri_range && allowed_uri_position?(line, uri_range)
            end

            message = format(MSG, line.length, max)

            excessive_position = if uri_range && uri_range.begin < max
                                   uri_range.end
                                 else
                                   max
                                 end

            range = source_range(processed_source.buffer,
                                 index + 1,
                                 excessive_position...(line.length))

            add_offense(nil, range, message) do
              self.max = line.length
            end
          end
        end

        def max
          cop_config['Max']
        end

        def allow_uri?
          cop_config['AllowURI']
        end

        def allowed_uri_position?(line, uri_range)
          uri_range.begin < max && uri_range.end == line.length
        end

        def find_excessive_uri_range(line)
          last_uri_match = match_uris(line).last
          return nil unless last_uri_match
          begin_position, end_position = last_uri_match.offset(0)
          return nil if begin_position < max && end_position < max
          begin_position...end_position
        end

        def match_uris(string)
          matches = []
          unscanned_position = 0

          loop do
            match_data = string.match(URI.regexp, unscanned_position)
            break unless match_data

            uri_ish_string = match_data[0]
            matches << match_data if valid_uri?(uri_ish_string)

            _, unscanned_position = match_data.offset(0)
          end

          matches
        end

        def valid_uri?(uri_ish_string)
          URI.parse(uri_ish_string)
          true
        rescue
          false
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
FROM ubuntu:12.04
MAINTAINER George Schneeloch

ENV DEBIAN_FRONTEND noninteractive

RUN apt-get update

RUN apt-get install -y wine

RUN apt-get install -y mesa-utils

# Install OpenSSH
RUN apt-get install -y openssh-server

# Create OpenSSH privilege separation directory
RUN mkdir /var/run/sshd

# Overwrite sshd_config with our own file
ADD sshd_config /etc/ssh/

# Add the wine user that will run the browser
RUN adduser --disabled-password --gecos "Wine User" --uid 5001 wine

# Add SSH public key for the wine user
RUN mkdir /home/wine/.ssh
ADD id_rsa.pub /home/wine/.ssh/authorized_keys
RUN chown -R wine:wine /home/wine/.ssh

# Start SSH so we are ready to make a tunnel
ENTRYPOINT ["/usr/sbin/sshd",  "-D"]
VOLUME ["/tmp/.X11-unix", "/tmp/.X11-unix"]

# Expose the SSH port
EXPOSE 22


text:
$(function() {
	var Doc = function() {
			var container = $('.l-wrapper'),
				target = container;

			this.write = function(str) {
				target.append(str);
			}

			this.set = function(title) {
				target = $('
')
					.appendTo(container)
					.append('
' + (title || '') + '
');
			}

			this.reset = function() {
				target = container;
			}
		},
		doc = new Doc(),
		perf = new Perf(),
		ObservatoriumPubSub = new Observatorium(),
		jqPubSub = $({}),
		observers = [{
			name: 'Observatorium',
			observer: ObservatoriumPubSub
		}, {
			name: 'Backbone.js Events',
			observer: _.extend({}, Backbone.Events)
		}, {
			name: 'AmplifyJS PUB/SUB',
			observer: {
				on: function(name, handler, context) {
					amplify.subscribe(name, context, handler);
				},
				off: function(name) {
					amplify.unsubscribe(name);
				},
				trigger: function(name) {
					amplify.publish(name);
				}
			}
		}, {
			name: 'jQuery Events',
			observer: {
				on: function(name, handler, context) {
					jqPubSub.on(name, $.proxy(handler, context));
				},
				off: function(name) {
					jqPubSub.off(name);
				},
				trigger: function(name) {
					jqPubSub.trigger(name);
				}
			}
		}],
		testParams = [[10, 10, 10], [100, 10, 10], [10, 100, 10], [10, 10, 100]],
		run = function runNext(observer, params) {
			var testBundle,
				param;

			if (!observer) {
				observer = observers.shift();
				doc.set('Testing: ' + observer.name);
			}
			params || (params = testParams.slice(0));
			param = params.shift();

			doc.write('Testing with params: ' + param.join(', ') + ' (' + (testParams.length - params.length) + ' / ' + testParams.length + ')
');

			setTimeout(function() {
				testBundle = new Test(observer.observer, param[0], param[1], param[2]);

				perf.start();
				testBundle.bind();
				doc.write('– Events binding completed in: ' + perf.end() + ' ms.
');

				perf.start();
				testBundle.trigger();
				doc.write('– Events triggering completed in: ' + perf.end() + ' ms.
');

				perf.start();
				testBundle.remove();
				doc.write('– Events unbinding completed in: ' + perf.end() + ' ms.

');

				setTimeout(function() {
					if (params.length) {
						runNext(observer, params);
					} else {
						doc.write('
"' + observer.name + '" tests are finished!
');

						if (observers.length) {
							runNext();
						} else {
							doc.reset();
							alert('All tests are finished');
						}
					}
				}, 100);
			}, 100);
		};

	// Запускаем тестирование
	run();
});


text:
package org.jkiss.dbeaver.ui.views.qm;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.handlers.HandlerUtil;
import org.jkiss.dbeaver.ui.UIUtils;

public class QueryManagerClearHandler extends AbstractHandler {

    @Override
    public Object execute(ExecutionEvent event) throws ExecutionException {
        QueryManagerView view = UIUtils.findView(HandlerUtil.getActiveWorkbenchWindow(event), QueryManagerView.class);
        if (view != null) {
            view.getQueryLogViewer().clearLog();
        }
        return null;
    }
}


text:
using net::test::IsError;
using net::test::IsOk;

namespace net {

namespace {

std::string FirstAddress(const AddressList& address_list) {
  if (address_list.empty())
    return std::string();
  return address_list.front().ToString();
}

TEST(MappedHostResolverTest, Inclusion) {
  base::test::ScopedTaskEnvironment scoped_task_environment;

  // Outstanding request.
  std::unique_ptr<HostResolver::Request> request;
  // Create a mock host resolver, with specific hostname to IP mappings.
  std::unique_ptr<MockHostResolver> resolver_impl(new MockHostResolver());
  resolver_impl->rules()->AddSimulatedFailure("*google.com");
  resolver_impl->rules()->AddRule("baz.com", "192.168.1.5");
  resolver_impl->rules()->AddRule("foo.com", "192.168.1.8");
  resolver_impl->rules()->AddRule("proxy", "192.168.1.11");

  // Create a remapped resolver that uses |resolver_impl|.
  std::unique_ptr<MappedHostResolver> resolver(
      new MappedHostResolver(std::move(resolver_impl)));

  int rv;
  AddressList address_list;

  // Try resolving "www.google.com:80". There are no mappings yet, so this
  // hits |resolver_impl| and fails.
  TestCompletionCallback callback;
  rv = resolver->Resolve(
      HostResolver::RequestInfo(HostPortPair("www.google.com", 80)),
      DEFAULT_PRIORITY, &address_list, callback.callback(), &request,
      NetLogWithSource());
  EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
  rv = callback.WaitForResult();
  EXPECT_THAT(rv, IsError(ERR_NAME_NOT_RESOLVED));

  // Remap *.google.com to baz.com.
  EXPECT_TRUE(resolver->AddRuleFromString("map *.google.com baz.com"));
  request.reset();

  // Try resolving "www.google.com:80". Should be remapped to "baz.com:80".
  rv = resolver->Resolve(
      HostResolver::RequestInfo(HostPortPair("www.google.com", 80)),
      DEFAULT_PRIORITY, &address_list, callback.callback(), &request,
      NetLogWithSource());
  EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
  rv = callback.WaitForResult();
  EXPECT_THAT(rv, IsOk());
  EXPECT_EQ("192.168.1.5:80", FirstAddress(address_list));
  request.reset();

  // Try resolving "foo.com:77". This will NOT be remapped, so result
  // is "foo.com:77".
  rv = resolver->Resolve(HostResolver::RequestInfo(HostPortPair("foo.com", 77)),
                         DEFAULT_PRIORITY, &address_list, callback.callback(),
                         &request, NetLogWithSource());
  EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
  rv = callback.WaitForResult();
  EXPECT_THAT(rv, IsOk());
  EXPECT_EQ("192.168.1.8:77", FirstAddress(address_list));
  request.reset();

  // Remap "*.org" to "proxy:99".
  EXPECT_TRUE(resolver->AddRuleFromString("Map *.org proxy:99"));

  // Try resolving "chromium.org:61". Should be remapped to "proxy:99".
  rv = resolver->Resolve(
      HostResolver::RequestInfo(HostPortPair("chromium.org", 61)),
      DEFAULT_PRIORITY, &address_list, callback.callback(), &request,
      NetLogWithSource());
  EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
  rv = callback.WaitForResult();
  EXPECT_THAT(rv, IsOk());
  EXPECT_EQ("192.168.1.11:99", FirstAddress(address_list));
}

TEST(MappedHostResolverTest, Inclusion_ResolveHost) {
  base::test::ScopedTaskEnvironment scoped_task_environment;

  // Create a mock host resolver, with specific hostname to IP mappings.
  std::unique_ptr<MockHostResolver> resolver_impl(new MockHostResolver());
  resolver_impl->rules()->AddSimulatedFailure("*google.com");
  resolver_impl->rules()->AddRule("baz.com", "192.168.1.5");
  resolver_impl->rules()->AddRule("foo.com", "192.168.1.8");
  resolver_impl->rules()->AddRule("proxy", "192.168.1.11");

  // Create a remapped resolver that uses |resolver_impl|.
  std::unique_ptr<MappedHostResolver> resolver(
      new MappedHostResolver(std::move(resolver_impl)));

  // Try resolving "www.google.com:80". There are no mappings yet, so this
  // hits |resolver_impl| and fails.
  TestCompletionCallback callback;
  std::unique_ptr<HostResolver::ResolveHostRequest> request =
      resolver->CreateRequest(HostPortPair("www.google.com", 80),
                              NetLogWithSource(), base::nullopt);
  int rv = request->Start(callback.callback());
  EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
  rv = callback.WaitForResult();
  EXPECT_THAT(rv, IsError(ERR_NAME_NOT_RESOLVED));
  EXPECT_FALSE(request->GetAddressResults());

  // Remap *.google.com to baz.com.
  EXPECT_TRUE(resolver->AddRuleFromString("map *.google.com baz.com"));
  request.reset();

  // Try resolving "www.google.com:80". Should be remapped to "baz.com:80".
  request = resolver->CreateRequest(HostPortPair("www.google.com", 80),
                                    NetLogWithSource(), base::nullopt);
  rv = request->Start(callback.callback());
  EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
  rv = callback.WaitForResult();
  EXPECT_THAT(rv, IsOk());
  EXPECT_EQ("192.168.1.5:80",
            FirstAddress(request->GetAddressResults().value()));
  request.reset();

  // Try resolving "foo.com:77". This will NOT be remapped, so result
  // is "foo.com:77".
  request = resolver->CreateRequest(HostPortPair("foo.com", 77),
                                    NetLogWithSource(), base::nullopt);
  rv = request->Start(callback.callback());
  EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
  rv = callback.WaitForResult();
  EXPECT_THAT(rv, IsOk());
  EXPECT_EQ("192.168.1.8:77",
            FirstAddress(request->GetAddressResults().value()));
  request.reset();

  // Remap "*.org" to "proxy:99".
  EXPECT_TRUE(resolver->AddRuleFromString("Map *.org proxy:99"));

  // Try resolving "chromium.org:61". Should be remapped to "proxy:99".
  request = resolver->CreateRequest(HostPortPair("chromium.org", 61),
                                    NetLogWithSource(), base::nullopt);
  rv = request->Start(callback.callback());
  EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
  rv = callback.WaitForResult();
  EXPECT_THAT(rv, IsOk());
  EXPECT_EQ("192.168.1.11:99",
            FirstAddress(request->GetAddressResults().value()));
}

// Tests that exclusions are respected.
TEST(MappedHostResolverTest, Exclusion) {
  base::test::ScopedTaskEnvironment scoped_task_environment;

  // Outstanding request.
  std::unique_ptr<HostResolver::Request> request;
  // Create a mock host resolver, with specific hostname to IP mappings.
  std::unique_ptr<MockHostResolver> resolver_impl(new MockHostResolver());
  resolver_impl->rules()->AddRule("baz", "192.168.1.5");
  resolver_impl->rules()->AddRule("www.google.com", "192.168.1.3");

  // Create a remapped resolver that uses |resolver_impl|.
  std::unique_ptr<MappedHostResolver> resolver(
      new MappedHostResolver(std::move(resolver_impl)));

  int rv;
  AddressList address_list;
  TestCompletionCallback callback;

  // Remap "*.com" to "baz".
  EXPECT_TRUE(resolver->AddRuleFromString("map *.com baz"));

  // Add an exclusion for "*.google.com".
  EXPECT_TRUE(resolver->AddRuleFromString("EXCLUDE *.google.com"));

  // Try resolving "www.google.com". Should not be remapped due to exclusion).
  rv = resolver->Resolve(
      HostResolver::RequestInfo(HostPortPair("www.google.com", 80)),
      DEFAULT_PRIORITY, &address_list, callback.callback(), &request,
      NetLogWithSource());
  EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
  rv = callback.WaitForResult();
  EXPECT_THAT(rv, IsOk());
  EXPECT_EQ("192.168.1.3:80", FirstAddress(address_list));
  request.reset();

  // Try resolving "chrome.com:80". Should be remapped to "baz:80".
  rv = resolver->Resolve(
      HostResolver::RequestInfo(HostPortPair("chrome.com", 80)),
      DEFAULT_PRIORITY, &address_list, callback.callback(), &request,
      NetLogWithSource());
  EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
  rv = callback.WaitForResult();
  EXPECT_THAT(rv, IsOk());
  EXPECT_EQ("192.168.1.5:80", FirstAddress(address_list));
}

// Tests that exclusions are respected.
TEST(MappedHostResolverTest, Exclusion_ResolveHost) {
  base::test::ScopedTaskEnvironment scoped_task_environment;

  // Create a mock host resolver, with specific hostname to IP mappings.
  std::unique_ptr<MockHostResolver> resolver_impl(new MockHostResolver());
  resolver_impl->rules()->AddRule("baz", "192.168.1.5");
  resolver_impl->rules()->AddRule("www.google.com", "192.168.1.3");

  // Create a remapped resolver that uses |resolver_impl|.
  std::unique_ptr<MappedHostResolver> resolver(
      new MappedHostResolver(std::move(resolver_impl)));

  TestCompletionCallback callback;

  // Remap "*.com" to "baz".
  EXPECT_TRUE(resolver->AddRuleFromString("map *.com baz"));

  // Add an exclusion for "*.google.com".
  EXPECT_TRUE(resolver->AddRuleFromString("EXCLUDE *.google.com"));

  // Try resolving "www.google.com". Should not be remapped due to exclusion).
  std::unique_ptr<HostResolver::ResolveHostRequest> request =
      resolver->CreateRequest(HostPortPair("www.google.com", 80),
                              NetLogWithSource(), base::nullopt);
  int rv = request->Start(callback.callback());
  EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
  rv = callback.WaitForResult();
  EXPECT_THAT(rv, IsOk());
  EXPECT_EQ("192.168.1.3:80",
            FirstAddress(request->GetAddressResults().value()));
  request.reset();

  // Try resolving "chrome.com:80". Should be remapped to "baz:80".
  request = resolver->CreateRequest(HostPortPair("chrome.com", 80),
                                    NetLogWithSource(), base::nullopt);
  rv = request->Start(callback.callback());
  EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
  rv = callback.WaitForResult();
  EXPECT_THAT(rv, IsOk());
  EXPECT_EQ("192.168.1.5:80",
            FirstAddress(request->GetAddressResults().value()));
}

TEST(MappedHostResolverTest, SetRulesFromString) {
  base::test::ScopedTaskEnvironment scoped_task_environment;

  // Outstanding request.
  std::unique_ptr<HostResolver::Request> request;
  // Create a mock host resolver, with specific hostname to IP mappings.
  std::unique_ptr<MockHostResolver> resolver_impl(new MockHostResolver());
  resolver_impl->rules()->AddRule("baz", "192.168.1.7");
  resolver_impl->rules()->AddRule("bar", "192.168.1.9");

  // Create a remapped resolver that uses |resolver_impl|.
  std::unique_ptr<MappedHostResolver> resolver(
      new MappedHostResolver(std::move(resolver_impl)));

  int rv;
  AddressList address_list;
  TestCompletionCallback callback;

  // Remap "*.com" to "baz", and *.net to "bar:60".
  resolver->SetRulesFromString("map *.com baz , map *.net bar:60");

  // Try resolving "www.google.com". Should be remapped to "baz".
  rv = resolver->Resolve(
      HostResolver::RequestInfo(HostPortPair("www.google.com", 80)),
      DEFAULT_PRIORITY, &address_list, callback.callback(), &request,
      NetLogWithSource());
  EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
  rv = callback.WaitForResult();
  EXPECT_THAT(rv, IsOk());
  EXPECT_EQ("192.168.1.7:80", FirstAddress(address_list));
  request.reset();

  // Try resolving "chrome.net:80". Should be remapped to "bar:60".
  rv = resolver->Resolve(
      HostResolver::RequestInfo(HostPortPair("chrome.net", 80)),
      DEFAULT_PRIORITY, &address_list, callback.callback(), &request,
      NetLogWithSource());
  EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
  rv = callback.WaitForResult();
  EXPECT_THAT(rv, IsOk());
  EXPECT_EQ("192.168.1.9:60", FirstAddress(address_list));
}

TEST(MappedHostResolverTest, SetRulesFromString_ResolveHost) {
  base::test::ScopedTaskEnvironment scoped_task_environment;

  // Create a mock host resolver, with specific hostname to IP mappings.
  std::unique_ptr<MockHostResolver> resolver_impl(new MockHostResolver());
  resolver_impl->rules()->AddRule("baz", "192.168.1.7");
  resolver_impl->rules()->AddRule("bar", "192.168.1.9");

  // Create a remapped resolver that uses |resolver_impl|.
  std::unique_ptr<MappedHostResolver> resolver(
      new MappedHostResolver(std::move(resolver_impl)));

  TestCompletionCallback callback;

  // Remap "*.com" to "baz", and *.net to "bar:60".
  resolver->SetRulesFromString("map *.com baz , map *.net bar:60");

  // Try resolving "www.google.com". Should be remapped to "baz".
  std::unique_ptr<HostResolver::ResolveHostRequest> request =
      resolver->CreateRequest(HostPortPair("www.google.com", 80),
                              NetLogWithSource(), base::nullopt);
  int rv = request->Start(callback.callback());
  EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
  rv = callback.WaitForResult();
  EXPECT_THAT(rv, IsOk());
  EXPECT_EQ("192.168.1.7:80",
            FirstAddress(request->GetAddressResults().value()));
  request.reset();

  // Try resolving "chrome.net:80". Should be remapped to "bar:60".
  request = resolver->CreateRequest(HostPortPair("chrome.net", 80),
                                    NetLogWithSource(), base::nullopt);
  rv = request->Start(callback.callback());
  EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
  rv = callback.WaitForResult();
  EXPECT_THAT(rv, IsOk());
  EXPECT_EQ("192.168.1.9:60",
            FirstAddress(request->GetAddressResults().value()));
}

// Parsing bad rules should silently discard the rule (and never crash).
TEST(MappedHostResolverTest, ParseInvalidRules) {
  base::test::ScopedTaskEnvironment scoped_task_environment;

  std::unique_ptr<MappedHostResolver> resolver(
      new MappedHostResolver(std::unique_ptr<HostResolver>()));

  EXPECT_FALSE(resolver->AddRuleFromString("xyz"));
  EXPECT_FALSE(resolver->AddRuleFromString(std::string()));
  EXPECT_FALSE(resolver->AddRuleFromString(" "));
  EXPECT_FALSE(resolver->AddRuleFromString("EXCLUDE"));
  EXPECT_FALSE(resolver->AddRuleFromString("EXCLUDE foo bar"));
  EXPECT_FALSE(resolver->AddRuleFromString("INCLUDE"));
  EXPECT_FALSE(resolver->AddRuleFromString("INCLUDE x"));
  EXPECT_FALSE(resolver->AddRuleFromString("INCLUDE x :10"));
}

// Test mapping hostnames to resolving failures.
TEST(MappedHostResolverTest, MapToError) {
  base::test::ScopedTaskEnvironment scoped_task_environment;

  // Outstanding request.
  std::unique_ptr<HostResolver::Request> request;
  std::unique_ptr<MockHostResolver> resolver_impl(new MockHostResolver());
  resolver_impl->rules()->AddRule("*", "192.168.1.5");

  std::unique_ptr<MappedHostResolver> resolver(
      new MappedHostResolver(std::move(resolver_impl)));

  int rv;
  AddressList address_list;

  // Remap *.google.com to resolving failures.
  EXPECT_TRUE(resolver->AddRuleFromString("MAP *.google.com ~NOTFOUND"));

  // Try resolving www.google.com --> Should give an error.
  TestCompletionCallback callback1;
  rv = resolver->Resolve(
      HostResolver::RequestInfo(HostPortPair("www.google.com", 80)),
      DEFAULT_PRIORITY, &address_list, callback1.callback(), &request,
      NetLogWithSource());
  EXPECT_THAT(rv, IsError(ERR_NAME_NOT_RESOLVED));
  request.reset();

  // Try resolving www.foo.com --> Should succeed.
  TestCompletionCallback callback2;
  rv = resolver->Resolve(
      HostResolver::RequestInfo(HostPortPair("www.foo.com", 80)),
      DEFAULT_PRIORITY, &address_list, callback2.callback(), &request,
      NetLogWithSource());
  EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
  rv = callback2.WaitForResult();
  EXPECT_THAT(rv, IsOk());
  EXPECT_EQ("192.168.1.5:80", FirstAddress(address_list));
}

// Test mapping hostnames to resolving failures.
TEST(MappedHostResolverTest, MapToError_ResolveHost) {
  base::test::ScopedTaskEnvironment scoped_task_environment;

  // Outstanding request.
  std::unique_ptr<MockHostResolver> resolver_impl(new MockHostResolver());
  resolver_impl->rules()->AddRule("*", "192.168.1.5");

  std::unique_ptr<MappedHostResolver> resolver(
      new MappedHostResolver(std::move(resolver_impl)));

  // Remap *.google.com to resolving failures.
  EXPECT_TRUE(resolver->AddRuleFromString("MAP *.google.com ~NOTFOUND"));

  // Try resolving www.google.com --> Should give an error.
  TestCompletionCallback callback1;
  std::unique_ptr<HostResolver::ResolveHostRequest> request =
      resolver->CreateRequest(HostPortPair("www.google.com", 80),
                              NetLogWithSource(), base::nullopt);
  int rv = request->Start(callback1.callback());
  EXPECT_THAT(rv, IsError(ERR_NAME_NOT_RESOLVED));
  request.reset();

  // Try resolving www.foo.com --> Should succeed.
  TestCompletionCallback callback2;
  request = resolver->CreateRequest(HostPortPair("www.foo.com", 80),
                                    NetLogWithSource(), base::nullopt);
  rv = request->Start(callback2.callback());
  EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
  rv = callback2.WaitForResult();
  EXPECT_THAT(rv, IsOk());
  EXPECT_EQ("192.168.1.5:80",
            FirstAddress(request->GetAddressResults().value()));
}

}  // namespace

}  // namespace net


text:
dojo.provide("dojo.widget.AccordionContainer");

dojo.require("dojo.widget.*");
dojo.require("dojo.widget.AccordionPane");

dojo.widget.defineWidget(
	"dojo.widget.AccordionContainer",
	dojo.widget.HtmlWidget,
	{
		widgetType: "AccordionContainer",
		isContainer: true,
		labelNodeClass: "",
		containerNodeClass: "",
		allowCollapse: false,

		addChild: function(widget, overrideContainerNode, pos, ref, insertIndex){
			if (widget.widgetType != "AccordionPane") {
				var wrapper=dojo.widget.createWidget("AccordionPane",{label: widget.label, open: widget.open, labelNodeClass: this.labelNodeClass, containerNodeClass: this.containerNodeClass, allowCollapse: this.allowCollapse });
				wrapper.addChild(widget);
				this.addWidgetAsDirectChild(wrapper);
				this.registerChild(wrapper);
				wrapper.setSizes();
				return wrapper;
			} else {
				dojo.html.addClass(widget.containerNode, this.containerNodeClass);
				dojo.html.addClass(widget.labelNode, this.labelNodeClass);
				this.addWidgetAsDirectChild(widget);
				this.registerChild(widget);
				widget.setSizes();
				return widget;
			}
	        },

		postCreate: function() {
			var tmpChildren = this.children;
			this.children=[];
			dojo.html.removeChildren(this.domNode);
			dojo.lang.forEach(tmpChildren, dojo.lang.hitch(this,"addChild"));
		},

		removeChild: function(widget) {
			dojo.widget.AccordionContainer.superclass.removeChild.call(this, widget);
			if(this.children[0]){
				this.children[0].setSizes();
			}
		},

		onResized: function(){
			this.children[0].setSizes();
		}
	}
);

// These arguments can be specified for the children of a Accordion
// Since any widget can be specified as a child, mix them
// into the base widget class.  (This is a hack, but it's effective.)
dojo.lang.extend(dojo.widget.Widget, {
	label: "",
	open: false
});


text:
@interface OwnerViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)OwnerHeadView *headView;
@property(nonatomic,copy) UITableView *tableView;
@property(nonatomic,strong) NSMutableArray *titleArray;
@property(nonatomic,strong) NSMutableArray *imageArray;
@property(nonatomic,strong) NSArray *menuTitle;
@property(nonatomic,strong) NSArray *menuPic;
@property (strong, nonatomic) WBPopOverView *wbpopView;
@property(nonatomic,assign) BOOL isFirst;
@property(nonatomic,strong)OwnerInfoModel *model;
@property(nonatomic,strong) CompleteMemberView *completeView;
@property(nonatomic,strong) UIView *grayView;
@property(nonatomic,assign) BOOL first;

@end

@implementation OwnerViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initnavi];
    [self setUI];

}

- (void)initnavi{

    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor = RGB(57, 64, 72);
    self.navigationController.navigationBar.backgroundColor = RGB(57, 64, 72);

    self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObjectsAndKeys:kWhite,NSForegroundColorAttributeName,[UIFont systemFontOfSize:18],NSFontAttributeName, nil];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [UIImage new];

    UIButton *btnMore = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [btnMore setTitle:@"   ···" forState:(UIControlStateNormal)];
    btnMore.titleLabel.font = kFont(24);
    btnMore.frame = CGRectMake(20, 0, 40, 20);
    [btnMore addTarget:self action:@selector(btnMoreAction) forControlEvents:(UIControlEventTouchUpInside)];
    UIBarButtonItem *more = [[UIBarButtonItem alloc] initWithCustomView:btnMore];
    UIBarButtonItem *spacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemFixedSpace) target:nil action:nil];
    self.navigationItem.rightBarButtonItems = @[spacer,more];

}

- (void)btnMoreAction{

    UIView *grayView;
    [self.view addSubview:({
        grayView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        grayView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
        grayView;
    })];

    _wbpopView = [[WBPopOverView alloc] initWithOrigin:CGPointMake(ScreenW - 25, 55) Width:ScreenW*0.4 Height:45*_menuTitle.count Direction:(WBArrowDirectionUp3) view:grayView];
    [_wbpopView.backView addSubview:({
        UITableView *tableV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0,ScreenW*0.4, 45*_menuTitle.count) style:(UITableViewStylePlain)];
        tableV.delegate = self;
        tableV.dataSource = self;
        tableV.rowHeight = 45;
        tableV;
    })];
    [_wbpopView popView];
}

- (void)setUI{
    [self.view addSubview:({
        _headView = [[[NSBundle mainBundle] loadNibNamed:@"OwnerHeadView" owner:nil options:nil] firstObject];
        _headView.frame = CGRectMake(0, 0, ScreenW, 225 +100);
        [_headView.applyForCard addTarget:self action:@selector(appliForCard) forControlEvents:(UIControlEventTouchUpInside)];
        [_headView.ownerView addTarget:self action:@selector(ownerDetail) forControlEvents:(UIControlEventTouchUpInside)];
        [_headView.signBtn addTarget:self action:@selector(checkSign) forControlEvents:(UIControlEventTouchUpInside)];
        _headView;
    })];

    [self.view addSubview:({
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 225 - NavH, ScreenW, ScreenH - 225 - 49) style:(UITableViewStylePlain)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 50;
        _tableView.tableFooterView = [UIView new];
        _tableView.backgroundColor = kMainGray;
//        [_tableView setEditing:YES animated:YES];
        _tableView;
    })];

    _titleArray = [@[@"我的邀请",@"会员体系",@"我的审核",@"我的主题",@"我的资产",@"我的基金",@"退出登录"] mutableCopy];
    _imageArray = [@[@"owner_invite",@"owner_member",@"owner_select",@"owner_topic",@"owner_property",@"owner_funds",@"owner_exit"] mutableCopy];
    _menuTitle = @[@"积分排行", @"签到", @"实名认证"];
    _menuPic = @[@"owner_integral", @"owner_list", @"owner_trueName"];
}

- (void)downloadData{
    [self.view loadingOnAnyView];
    [HYBNetworking postWithUrl:@"IosIndex/login" refreshCache:NO params:@{@"phone":[Utils getValueForKey:@"phone"],@"pwd":[Utils getValueForKey:@"pwd"]} success:^(id response) {
        [self.view removeAnyView];
        SESSIONSTATE state = [Utils getStatus:response View:self showSuccessMsg:!_isFirst showErrorMsg:YES];
        if (state == SESSIONSUCCESS) {
            NSError *error;
            _isFirst = YES;
            _model = [[OwnerInfoModel alloc] initWithDictionary:response[@"data"] error:&error];
            if (!error) {
                [_headView.icon sd_setImageWithURL:[NSURL URLWithString:imageUrl(_model.u_avatar)] placeholderImage:[UIImage imageNamed:@"owner_header"]];
                _headView.phone.text = _model.u_name;
                _headView.code.text = _model.u_card;
                _headView.sign.text = [_model.u_content isEqualToString:@" "]?@"编辑个性签名🖌":_model.u_content.length>0?_model.u_content:@"编辑个性签名🖌";
                if ([_model.u_profile integerValue] == 0 && _first == NO) {
                    _first = YES;
                    [self initCompleteView];
                }
                [Utils setValue:_model.u_avatar ? _model.u_avatar:@"" key:@"icon"];
                [[NSUserDefaults standardUserDefaults] setBool:[_model.u_profile boolValue] forKey:@"profile"];
            }
        }
    } fail:^(NSError *error) {
        [self.view removeAnyView];
    }];
}

#pragma mark tableviewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return tableView == _tableView ? _titleArray.count : 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _tableView) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"cell"];
            cell.textLabel.text = _titleArray[indexPath.row];
            cell.imageView.image = [UIImage imageNamed:_imageArray[indexPath.row]];
            cell.textLabel.textColor = kDarkText;
            cell.selectionStyle =  UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        return cell;
    }else{
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:nil];
        cell.textLabel.text = _menuTitle[indexPath.row];
        cell.imageView.image = [UIImage imageNamed:_menuPic[indexPath.row]];
        cell.textLabel.textColor = kDarkGray;
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _tableView) {
        switch (indexPath.row) {
            case 0:{
                OwnerMyInviteViewController *ownerInviet = [[OwnerMyInviteViewController alloc] init];
                ownerInviet.hidesBottomBarWhenPushed = YES;
                ownerInviet.Img = _headView.icon.image;
                [self.navigationController pushViewController:ownerInviet animated:YES];
            }
                break;
            case 1:{
                if ([_model.u_id integerValue] == 1) {
                    OwnerBossViewController *bossVC = [[OwnerBossViewController alloc] init];
                    [self.navigationController pushViewController:bossVC animated:YES];
                }else{

                    OwnerMemberSystemViewController *mmeberSys = [[OwnerMemberSystemViewController alloc] init];
                    mmeberSys.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:mmeberSys animated:YES];
                }
            }
                break;
            case 2:{
                OwnerMyCheckViewController *checkVC= [[OwnerMyCheckViewController alloc] init];
                checkVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:checkVC animated:YES];
            }
                break;
            case 3:{
                OwnerMyTopicViewController *topicVC = [[OwnerMyTopicViewController alloc] init];
                topicVC.hidesBottomBarWhenPushed = YES;
                topicVC.myImg = _model.u_avatar;
                [self.navigationController pushViewController:topicVC animated:YES];
            }
                break;
            case 4:{
                OwnerPropetyViewController *integralVC = [[OwnerPropetyViewController alloc] init];
                integralVC.hidesBottomBarWhenPushed = YES;
                integralVC.icon = _headView.icon.image;
                integralVC.name = _model.u_name;
                [self.navigationController pushViewController:integralVC animated:YES];
            }
                break;
            case 5:{

            }
                break;
            case 6:{
                [self ExitAction];
            }
                break;
            default:
                break;
        }
    }else{
        switch (indexPath.row) {
            case 0:{
                OwnerIntegralViewController *integralVC = [[OwnerIntegralViewController alloc] init];
                integralVC.hidesBottomBarWhenPushed = YES;
                integralVC.icon = _headView.icon.image;
                integralVC.name = _model.u_name;
                [self.navigationController pushViewController:integralVC animated:YES];
            }
                break;
            case 1:{
                OwnerQdViewController *qdVC = [[OwnerQdViewController alloc] init];
                qdVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:qdVC animated:YES];
            }
                break;
            case 2:{
                OwnerTruthNameViewController *truthName = [[OwnerTruthNameViewController alloc] init];
                truthName.hidesBottomBarWhenPushed = YES;
                truthName.name = _model.u_name;
                [self.navigationController pushViewController:truthName animated:YES];
            }
                break;
            default:
                break;
        }

        [_wbpopView dismiss];
    }
}

//- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
//    [_titleArray exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];
//    [_imageArray exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];
//}
//
//- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath{
//    return YES;
//}
//
//- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return  UITableViewCellEditingStyleNone;
//}

- (void)initCompleteView{
    [self.view addSubview:({
        _grayView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH)];
        _grayView.backgroundColor = [UIColor blackColor];
        _grayView.alpha = 0;
        _grayView;
    })];

    [self.view addSubview:({
        _completeView = [[[NSBundle mainBundle] loadNibNamed:@"CompleteMemberView" owner:nil options:nil] firstObject];
        _completeView.frame = CGRectMake(40, (ScreenH-315)/2 - ScreenH, ScreenW - 80, 315);
        [_completeView.close addTarget:self action:@selector(closeTip) forControlEvents:(UIControlEventTouchUpInside)];
        [_completeView.completeBtn addTarget:self action:@selector(pushToCenter) forControlEvents:(UIControlEventTouchUpInside)];
        _completeView;
    })];

    [UIView animateWithDuration:0.5 animations:^{
        _grayView.alpha = 0.6;
        _completeView.frame = CGRectMake(40, (ScreenH-415)/2, ScreenW - 80, 315);
    }];
}

- (void)closeTip{
    [UIView animateWithDuration:0.3 animations:^{
        _grayView.alpha = 0;
        _completeView.frame = CGRectMake(40, (ScreenH-315)/2 - ScreenH, ScreenW - 80, 315);
    } completion:^(BOOL finished) {
        [_grayView removeFromSuperview];
        [_completeView removeFromSuperview];
    }];
}

- (void)pushToCenter{
    [self ownerDetail];
    [_grayView removeFromSuperview];
    [_completeView removeFromSuperview];
}

- (void)appliForCard{
    ApliyCardViewController *appliyV = [[ApliyCardViewController alloc] init];
    [self.navigationController pushViewController:appliyV animated:YES];
}

- (void)ownerDetail{
    MemberViewController *mmeberVC = [[MemberViewController alloc] init];
    mmeberVC.name = _model.u_name;
    mmeberVC.icon = imageUrl(_model.u_avatar);
    mmeberVC.phone = _model.u_phone;
    mmeberVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:mmeberVC animated:YES];
}

- (void)checkSign{
    OwnerSignViewController *signVC = [[OwnerSignViewController alloc] init];
    signVC.sign = _model.u_content;
    [self.navigationController pushViewController:signVC animated:YES];
}

- (void)ExitAction{
    dispatch_async(dispatch_get_main_queue(), ^{
        BaseAlertControler *view = [[BaseAlertControler alloc] init];
        UIAlertController *alert = [view alertmessage:@"确定退出" Title:@"退出可能会使你的下次登录需要账号密码,确定退出?" andBlock:^{
            [Utils removeAllValue];
            LoginViewController *hvc = [[LoginViewController alloc] init];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:hvc];
            self.view.window.rootViewController = nav;
        }];
        [self presentViewController:alert animated:YES completion:nil];
    });
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self downloadData];
    [self initnavi];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}

@end


text:
<?php namespace Braseidon\Mole\Driver;

use RollingCurl\Request;
use RollingCurl\RollingCurl;

class RollingCurlDriver implements CurlInterface
{

    /**
     * The RollingCurl instance
     *
     * @var RollingCurl
     */
    protected $rollingCurl;
}


text:
#ifndef __GAMEPAD_H__
#define __GAMEPAD_H__

#include <windows.h>
#include <Xinput.h>

#define MICROSOFTS_GREATEST_SECRET__THE_GUIDE_BUTTON_BYTE_ADDRESS 0x0400

static const WORD XINPUT_Buttons[] = {
    XINPUT_GAMEPAD_A,
    XINPUT_GAMEPAD_B,
    XINPUT_GAMEPAD_X,
    XINPUT_GAMEPAD_Y,
    XINPUT_GAMEPAD_DPAD_UP,
    XINPUT_GAMEPAD_DPAD_DOWN,
    XINPUT_GAMEPAD_DPAD_LEFT,
    XINPUT_GAMEPAD_DPAD_RIGHT,
    XINPUT_GAMEPAD_LEFT_SHOULDER,
    XINPUT_GAMEPAD_RIGHT_SHOULDER,
    XINPUT_GAMEPAD_LEFT_THUMB,
    XINPUT_GAMEPAD_RIGHT_THUMB,
    XINPUT_GAMEPAD_START,
    XINPUT_GAMEPAD_BACK,
    MICROSOFTS_GREATEST_SECRET__THE_GUIDE_BUTTON_BYTE_ADDRESS
};

class Gamepad
{
public:
    struct TopTopSecretControllerState
    {
        unsigned long eventCount;
        WORD wButtons;
        BYTE bLeftTrigger;
        BYTE bRightTrigger;
        SHORT sThumbLX;
        SHORT sThumbLY;
        SHORT sThumbRX;
        SHORT sThumbRY;
    };
    typedef int(_stdcall* STATE_GET_FUNCTION)(int, TopTopSecretControllerState*);
    STATE_GET_FUNCTION getControllerState;

    enum Buttons
    {
        A = 0,
        B = 1,
        X = 2,
        Y = 3,

        LB = 8,
        RB = 9,

        LeftStick = 10,
        RightStick = 11,

        Start = 12,
        Back = 13,

        Guide = 14
    };

    enum DPad
    {
        Up = 4,
        Down = 5,
        Left = 6,
        Right = 7
    };

    Gamepad(int id);

    TopTopSecretControllerState getState() { this->refreshState(); return this->state; }
    int getId() { return this->id; }
    bool connected();
    void update();

    struct Value2d {
        float x;
        float y;

        bool dead;
    };

    Value2d leftStick();
    Value2d rightStick();
    Value2d dPad();

    float leftTrigger();
    float rightTrigger();

    int button(int buttonId);

    bool buttonDown(int buttonId);
    bool buttonPressed(int buttonId);
    bool buttonUp(int buttonId);

    void vibrate(float leftMotor = 0.0f, float rightMotor = 0.0f);

private:
    DWORD refreshState();

    TopTopSecretControllerState state;
    int id;

    static const int ButtonCount = 15;

    enum ButtonState { NONE, DOWN, PRESSED, UP };

    ButtonState buttonStates[ButtonCount];
    bool buttonsPreviouslyPressed[ButtonCount];
    bool buttonsCurrentlyPressed[ButtonCount];
};

#endif // __GAMEPAD_H__


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Pluma\Support\Migration\Migration;
use Phinx\Migration\AbstractMigration;

class CreateScormvarsTable extends Migration
{
    /**
     * The table name.
     *
     * @var string
     */
    protected $tablename = 'scormvars';

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        if ($this->schema->hasTable($this->tablename)) {
            return;
        }

        $this->schema->create($this->tablename, function (Blueprint $table) {
            $table->increments('id');
            $table->integer('course_id')->unsigned();
            $table->integer('user_id')->unsigned();
            $table->integer('content_id')->unsigned();
            $table->string('name')->nullable();
            $table->text('val')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        $this->schema->dropIfExists($this->tablename);
    }
}


text:
module SelectraPages
  class PagesController < ApplicationController
    caches_page :show

    def show
      @page = Page.find_by_url!(params[:url])
      fresh_when @page, public: true
    end
  end
end


text:
package ml.alternet.parser.step2;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import ml.alternet.parser.step2.Calc.Additive;
import ml.alternet.parser.step2.Calc.Multiplicative;

/**
 * The user data model is a tree of expressions.
 *
 * @author Philippe Poulard
 */
public interface Expression {

    /**
     * An expression is evaluable to a value.
     *
     * @param variables The set of variables available when evaluating the expression.
     *
     * @return The computed value.
     */
    double eval(Map<String, Double> variables);

    /**
     * A function expression embeds an evaluable function.
     *
     * @author Philippe Poulard
     */
    class Function implements Expression {

        Expression argument;
        EvaluableFunction function;

        public Function(EvaluableFunction function, Expression argument) {
            this.function = function;
            this.argument = argument;
        }

        @Override
        public double eval(Map<String, Double> variables) {
            double arg = this.argument.eval(variables);
            return function.eval(arg);
        }

        @Override
        public String toString() {
            return function + "(" + argument + ")";
        }

    }

    /**
     * A constant expression wraps a number value.
     *
     * @author Philippe Poulard
     */
    class Constant implements Expression {

        Number n;

        public Constant(Number n) {
            this.n = n;
        }

        @Override
        public double eval(Map<String, Double> variables) {
            return n.doubleValue();
        }

        @Override
        public String toString() {
            return ""+ n;
        }

    }

    /**
     * A variable expression wraps a variable name.
     *
     * @author Philippe Poulard
     */
    class Variable implements Expression {

        String name;

        public Variable(String name) {
            this.name = name;
        }

        @Override
        public double eval(Map<String, Double> variables) {
            return variables.get(this.name);
        }

        @Override
        public String toString() {
            return name;
        }

    }

    /**
     * An exponent expression is made of a base and an exponent.
     *
     * @author Philippe Poulard
     */
    class Exponent implements Expression {

        Expression base;
        Expression exponent;

        public Exponent(Expression base, Expression exponent) {
            this.base = base;
            this.exponent = exponent;
        }

        @Override
        public double eval(Map<String, Double> variables) {
            double base = this.base.eval(variables);
            double exponent = this.exponent.eval(variables);
            return Math.pow(base, exponent);
        }
    }

    /**
     * A term is an expression bound with an operation
     * that appears in sums or factors expressions.
     *
     * @author Philippe Poulard
     *
     * @param <T>
     */
    class Term<T> implements Expression {
        T operation;
        Expression term;

        public Term(T operation, Expression term) {
            this.operation = operation;
            this.term = term;
        }

        @Override
        public double eval(Map<String, Double> variables) {
            return (this.operation == Additive.MINUS) ?
                - term.eval(variables) :
                + term.eval(variables);
            // can have +a or -a but can't have *a or /a
        }
        @Override
        public String toString() {
            return operation.toString() + this.term.toString();
        }
    }

    /**
     * A sum expression is made of additive(+|-) terms.
     *
     * @author Philippe Poulard
     */
    class Sum implements Expression {

        List<Term<Additive>> arguments = new ArrayList<>();

        public Sum(List<Term<Additive>> arguments) {
            this.arguments = arguments;
        }

        @Override
        public double eval(Map<String, Double> variables) {
            double sum = this.arguments.stream()
                .mapToDouble(t -> (t.operation == Additive.MINUS) ?
                            - t.term.eval(variables)
                        :   + t.term.eval(variables))
                .sum();
            return sum;
        }

        @Override
        public String toString() {
            return "(" + arguments.stream()
                .map(t -> "" + t.operation + t.term)
                .collect(Collectors.joining())
                +")";
        }

    }

    /**
     * A factor expression is made of multiplicative(*|/) terms.
     *
     * @author Philippe Poulard
     */
    class Product implements Expression {

        List<Term<Multiplicative>> arguments = new ArrayList<>();

        public Product(List<Term<Multiplicative>> arguments) {
            this.arguments = arguments;
        }

        @Override
        public double eval(Map<String, Double> variables) {
            double product = this.arguments.stream()
                .reduce(1d,
                    (val, term) -> term.operation == Multiplicative.DIV ?
                            val / term.term.eval(variables)
                        :   val * term.term.eval(variables),
                    (t1, t2) -> t1 * t2);
            return product;
        }

        @Override
        public String toString() {
            return arguments.get(0).term
                + arguments.stream()
                .skip(1)
                .map(t -> "" + t.operation + t.term)
                .collect(Collectors.joining());
        }

    }

}


text:
///
/// Copyright © 2016-2022 The Thingsboard Authors
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///

import { isPlatformBrowser } from '@angular/common';
import { ClassProvider, FactoryProvider, Injectable, InjectionToken, PLATFORM_ID } from '@angular/core';

/* Create a new injection token for injecting the window into a component. */
export const WINDOW = new InjectionToken('WindowToken');

/* Define abstract class for obtaining reference to the global window object. */
export abstract class WindowRef {

  get nativeWindow(): Window | object {
    throw new Error('Not implemented.');
  }

}

/* Define class that implements the abstract class and returns the native window object. */
@Injectable()
export class BrowserWindowRef extends WindowRef {

  constructor() {
    super();
  }

  get nativeWindow(): Window | object {
    return window;
  }

}

/* Create an factory function that returns the native window object. */
export function windowFactory(browserWindowRef: BrowserWindowRef, platformId: object): Window | object {
  if (isPlatformBrowser(platformId)) {
    return browserWindowRef.nativeWindow;
  }
  return new Object();
}

/* Create a injectable provider for the WindowRef token that uses the BrowserWindowRef class. */
export const browserWindowProvider: ClassProvider = {
  provide: WindowRef,
  useClass: BrowserWindowRef
};

/* Create an injectable provider that uses the windowFactory function for returning the native window object. */
export const windowProvider: FactoryProvider = {
  provide: WINDOW,
  useFactory: windowFactory,
  deps: [ WindowRef, PLATFORM_ID ]
};

/* Create an array of providers. */
export const WINDOW_PROVIDERS = [
  browserWindowProvider,
  windowProvider
];


text:
namespace realm {
    class List;
    class Results;
    class TableView;
    struct CollectionChangeSet;
    struct NotificationToken;
}
class RLMClassInfo;
@class RLMFastEnumerator;

@protocol RLMFastEnumerable
@property (nonatomic, readonly) RLMRealm *realm;
@property (nonatomic, readonly) RLMClassInfo *objectInfo;
@property (nonatomic, readonly) NSUInteger count;

- (realm::TableView)tableView;
- (RLMFastEnumerator *)fastEnumerator;
@end

// An object which encapulates the shared logic for fast-enumerating RLMArray
// and RLMResults, and has a buffer to store strong references to the current
// set of enumerated items
@interface RLMFastEnumerator : NSObject
- (instancetype)initWithList:(realm::List&)list
                  collection:(id)collection
                       realm:(RLMRealm *)realm
                   classInfo:(RLMClassInfo&)info;
- (instancetype)initWithResults:(realm::Results&)results
                     collection:(id)collection
                          realm:(RLMRealm *)realm
                      classInfo:(RLMClassInfo&)info;

// Detach this enumerator from the source collection. Must be called before the
// source collection is changed.
- (void)detach;

- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state
                                    count:(NSUInteger)len;
@end
NSUInteger RLMFastEnumerate(NSFastEnumerationState *state, NSUInteger len, id<RLMFastEnumerable> collection);

@interface RLMNotificationToken ()
- (void)suppressNextNotification;
- (RLMRealm *)realm;
@end

@interface RLMCancellationToken : RLMNotificationToken
- (instancetype)initWithToken:(realm::NotificationToken)token realm:(RLMRealm *)realm;
@end

@interface RLMCollectionChange ()
- (instancetype)initWithChanges:(realm::CollectionChangeSet)indices;
@end

template<typename Collection>
RLMNotificationToken *RLMAddNotificationBlock(id objcCollection,
                                              Collection& collection,
                                              void (^block)(id, RLMCollectionChange *, NSError *),
                                              bool suppressInitialChange=false);

template<typename Collection>
NSArray *RLMCollectionValueForKey(Collection& collection, NSString *key,
                                  RLMRealm *realm, RLMClassInfo& info);

std::vector<std::pair<std::string, bool>> RLMSortDescriptorsToKeypathArray(NSArray<RLMSortDescriptor *> *properties);


text:
require 'rails_helper'

RSpec.describe Category, type: :model do

  it "has a valid factory" do
    expect(create(:category, :parent)).to be_valid
  end

  it "has factory that builds a valid parent category with no parent_id" do
    expect(create(:category, :parent).parent_id).to be_nil
  end

  it "builds a valid child category when passed a valid parent_id" do
    my_parent = create(:category, :parent)
    expect(create(:category, :child, parent_id: my_parent.parent_id)).to be_valid
  end

end


text:
Do you like Flask?
Do you like Django's ORM?
If yes, you'll like [this](flaskapp/management/commands/runflask.py) too.

## Usage
```
git clone git@github.com:wh11e7rue/flask-in-django.git
cd flask-in-django
pip3 install -r requirements.txt
python3 manage.py runflask
```

## Thanks to
- https://github.com/masnun/django-orm-standalone
- https://www.caktusgroup.com/blog/2011/10/24/django-without-web/


text:
package akkit
package aggregator

import akka.actor.{Actor, ActorRefFactory, ActorRef, Props}

object CollectorSpawner {
  import Collector._

  private def spawn(actor: => Actor)(implicit context: ActorRefFactory) =
    context.actorOf(Props(actor))

  class Counter(expectedSize: Int)(implicit context: ActorRefFactory) {
    /**
     * Spawn [[Collector]] actor that collects specified objects until expected
     * count is exceeded.
     */
    def apply(objects: Any*)(implicit client: ActorRef) = spawn {
      new Collector(client = Some(client), expectedSize = Some(expectedSize)) {
        def expected(msg: Any) = objects contains msg
      }
    }

    /**
     * Spawn [[Collector]] actor that collects objects that match provided partial
     * function until expected count is exceeded.
     */
    def matching(extractor: Extractor)(implicit client: ActorRef) = spawn {
      new Collector(client = Some(client), expectedSize = Some(expectedSize)) {
        def expected(msg: Any) = extractor.isDefinedAt(msg)
        override def extract(msg: Any) = extractor(msg)
      }
    }
  }
}

trait CollectorSpawner {
  import CollectorSpawner._
  import Collector._

  implicit val context: ActorRefFactory

  object collect {
    /**
     * Spawn [[Collector]] actor that collects specified objects.
     */
    def apply(objects: Any*) = spawn {
      new Collector {
        def expected(msg: Any) = objects contains msg
      }
    }

    /**
     * Spawn [[Collector]] actor that collects objects that match provided partial
     * function.
     */
    def matching(extractor: Extractor) = spawn {
      new Collector {
        def expected(msg: Any) = extractor.isDefinedAt(msg)
        override def extract(msg: Any) = extractor(msg)
      }
    }

    /**
     * Returns a builder object that can be applied to variable number of objects
     * or a partial function to produce new [[Collector]] with counter.
     */
    def count(expectedSize: Int) = new Counter(expectedSize)
  }
}

object Collector {
  type Extractor = PartialFunction[Any, Any]
  case class Collection(result: Seq[Any])
  case object Flush
  case object Peak
}

abstract class Collector(
  expectedSize: Option[Int] = None,
  client: Option[ActorRef]  = None)
    extends Actor
{
  import Collector._

  private var result = Seq.empty[Any]

  def expected(msg: Any): Boolean
  def extract(msg: Any): Any = msg

  expectedSize foreach { size =>
    if (size <= 0) {
      client foreach { _ ! Collection(result) }
      context.stop(self)
    }
  }

  def isDone = expectedSize match {
    case Some(size) => result.size == size
    case None => false
  }

  def receive = {
    case Flush => {
      sender ! Collection(result)
      result = Seq.empty[Any]
    }

    case Peak => sender ! Collection(result)

    case msg if expected(msg) => {
      result :+= extract(msg)
      if (isDone) {
        client foreach { _ ! Collection(result) }
        context.stop(self)
      }
    }
  }
}

// vim: set ts=2 sw=2 et:


text:
package com.netflix.metacat.main.services.impl;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.netflix.metacat.common.MetacatRequestContext;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.dto.CatalogDto;
import com.netflix.metacat.common.dto.DatabaseDto;
import com.netflix.metacat.common.server.connectors.ConnectorDatabaseService;
import com.netflix.metacat.common.server.connectors.ConnectorRequestContext;
import com.netflix.metacat.common.server.connectors.ConnectorTableService;
import com.netflix.metacat.common.server.connectors.exception.DatabaseNotFoundException;
import com.netflix.metacat.common.server.converter.ConverterUtil;
import com.netflix.metacat.common.server.events.MetacatCreateDatabasePostEvent;
import com.netflix.metacat.common.server.events.MetacatCreateDatabasePreEvent;
import com.netflix.metacat.common.server.events.MetacatDeleteDatabasePostEvent;
import com.netflix.metacat.common.server.events.MetacatDeleteDatabasePreEvent;
import com.netflix.metacat.common.server.events.MetacatEventBus;
import com.netflix.metacat.common.server.events.MetacatUpdateDatabasePostEvent;
import com.netflix.metacat.common.server.events.MetacatUpdateDatabasePreEvent;
import com.netflix.metacat.common.server.spi.MetacatCatalogConfig;
import com.netflix.metacat.common.server.usermetadata.AuthorizationService;
import com.netflix.metacat.common.server.usermetadata.MetacatOperation;
import com.netflix.metacat.common.server.usermetadata.UserMetadataService;
import com.netflix.metacat.common.server.util.MetacatContextManager;
import com.netflix.metacat.main.manager.ConnectorManager;
import com.netflix.metacat.main.services.CatalogService;
import com.netflix.metacat.main.services.DatabaseService;
import com.netflix.metacat.main.services.GetDatabaseServiceParameters;
import lombok.extern.slf4j.Slf4j;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Database service implementation.
 */
@Slf4j
public class DatabaseServiceImpl implements DatabaseService {
    private final CatalogService catalogService;
    private final ConnectorManager connectorManager;
    private final UserMetadataService userMetadataService;

    private final MetacatEventBus eventBus;
    private final ConverterUtil converterUtil;
    private final AuthorizationService authorizationService;

    /**
     * Constructor.
     *
     * @param catalogService       catalog service
     * @param connectorManager     connector manager
     * @param userMetadataService  user metadata service
     * @param eventBus             internal event bus
     * @param converterUtil        utility to convert to/from Dto to connector resources
     * @param authorizationService authorization service
     */
    public DatabaseServiceImpl(
        final CatalogService catalogService,
        final ConnectorManager connectorManager,
        final UserMetadataService userMetadataService,
        final MetacatEventBus eventBus,
        final ConverterUtil converterUtil,
        final AuthorizationService authorizationService
    ) {
        this.catalogService = catalogService;
        this.connectorManager = connectorManager;
        this.userMetadataService = userMetadataService;
        this.eventBus = eventBus;
        this.converterUtil = converterUtil;
        this.authorizationService = authorizationService;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public DatabaseDto create(final QualifiedName name, final DatabaseDto dto) {
        validate(name);
        log.info("Creating schema {}", name);
        final MetacatRequestContext metacatRequestContext = MetacatContextManager.getContext();
        eventBus.post(new MetacatCreateDatabasePreEvent(name, metacatRequestContext, this));
        final ConnectorRequestContext connectorRequestContext = converterUtil.toConnectorContext(metacatRequestContext);
        connectorManager.getDatabaseService(name).create(connectorRequestContext,
            converterUtil.fromDatabaseDto(dto));
        if (dto.getDefinitionMetadata() != null) {
            log.info("Saving user metadata for schema {}", name);
            userMetadataService.saveDefinitionMetadata(name, metacatRequestContext.getUserName(),
                Optional.of(dto.getDefinitionMetadata()), true);
        }
        final DatabaseDto createdDto = get(name,
            GetDatabaseServiceParameters.builder()
                .disableOnReadMetadataIntercetor(true)
                .includeUserMetadata(dto.getDefinitionMetadata() != null)
                .includeTableNames(true)
                .build());
        eventBus.post(new MetacatCreateDatabasePostEvent(name, metacatRequestContext, this, createdDto));
        return createdDto;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void update(final QualifiedName name, final DatabaseDto dto) {
        validate(name);
        log.info("Updating schema {}", name);
        final MetacatRequestContext metacatRequestContext = MetacatContextManager.getContext();
        eventBus.post(new MetacatUpdateDatabasePreEvent(name, metacatRequestContext, this));
        try {
            final ConnectorRequestContext connectorRequestContext
                = converterUtil.toConnectorContext(metacatRequestContext);
            connectorManager.getDatabaseService(name)
                .update(connectorRequestContext, converterUtil.fromDatabaseDto(dto));
        } catch (UnsupportedOperationException ignored) {
        }
        if (dto.getDefinitionMetadata() != null) {
            log.info("Saving user metadata for schema {}", name);
            userMetadataService.saveDefinitionMetadata(name, metacatRequestContext.getUserName(),
                Optional.of(dto.getDefinitionMetadata()), true);
        }
        eventBus.post(new MetacatUpdateDatabasePostEvent(name, metacatRequestContext, this));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public DatabaseDto updateAndReturn(final QualifiedName name, final DatabaseDto dto) {
        update(name, dto);
        return get(name);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void delete(final QualifiedName name) {
        validate(name);
        final MetacatRequestContext metacatRequestContext = MetacatContextManager.getContext();
        this.authorizationService.checkPermission(metacatRequestContext.getUserName(),
            name, MetacatOperation.DELETE);
        log.info("Dropping schema {}", name);
        final DatabaseDto dto = get(name, GetDatabaseServiceParameters.builder()
            .disableOnReadMetadataIntercetor(false)
            .includeUserMetadata(true)
            .includeTableNames(true)
            .build());
        eventBus.post(new MetacatDeleteDatabasePreEvent(name, metacatRequestContext, this, dto));
        final ConnectorRequestContext connectorRequestContext = converterUtil.toConnectorContext(metacatRequestContext);
        connectorManager.getDatabaseService(name).delete(connectorRequestContext, name);

        // Delete definition metadata if it exists
        if (userMetadataService.getDefinitionMetadata(name).isPresent()) {
            log.info("Deleting user metadata for schema {}", name);
            userMetadataService.deleteDefinitionMetadata(ImmutableList.of(name));
        }
        eventBus.post(new MetacatDeleteDatabasePostEvent(name, metacatRequestContext, this, dto));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public DatabaseDto get(final QualifiedName name) {
        return get(name,
            GetDatabaseServiceParameters.builder()
                .includeUserMetadata(true)
                .includeTableNames(true)
                .disableOnReadMetadataIntercetor(false)
                .build());

    }

    /**
     * {@inheritDoc}
     */
    @Override
    public DatabaseDto get(final QualifiedName name, final GetDatabaseServiceParameters getDatabaseServiceParameters) {
        validate(name);
        final MetacatRequestContext metacatRequestContext = MetacatContextManager.getContext();
        final MetacatCatalogConfig config = connectorManager.getCatalogConfig(name);
        final ConnectorDatabaseService service = connectorManager.getDatabaseService(name);
        final ConnectorTableService tableService = connectorManager.getTableService(name);
        // Prepare the connector request
        final ConnectorRequestContext connectorRequestContext = converterUtil.toConnectorContext(metacatRequestContext);
        connectorRequestContext.setIncludeMetadata(getDatabaseServiceParameters.isIncludeMetadataFromConnector());

        final DatabaseDto dto = converterUtil.toDatabaseDto(service.get(connectorRequestContext, name));
        dto.setType(config.getType());
        if (getDatabaseServiceParameters.isIncludeTableNames()) {
            final List<QualifiedName> tableNames = tableService
                .listNames(connectorRequestContext, name, null, null, null);
            List<QualifiedName> viewNames = Collections.emptyList();
            if (config.isIncludeViewsWithTables()) {
                // TODO JdbcMetadata returns ImmutableList.of() for views.  We should change it to fetch views.
                try {
                    viewNames = service.listViewNames(connectorRequestContext, name);
                } catch (UnsupportedOperationException ignored) {
                }
            }

            // Check to see if schema exists
            if (tableNames.isEmpty() && viewNames.isEmpty() && !exists(name)) {
                throw new DatabaseNotFoundException(name);
            }
            dto.setTables(
                Stream.concat(tableNames.stream(), viewNames.stream())
                    .map(QualifiedName::getTableName)
                    .sorted(String.CASE_INSENSITIVE_ORDER)
                    .collect(Collectors.toList())
            );
        }
        if (getDatabaseServiceParameters.isIncludeUserMetadata()) {
            log.info("Populate user metadata for schema {}", name);
            userMetadataService.populateMetadata(dto,
                getDatabaseServiceParameters.isDisableOnReadMetadataIntercetor());
        }

        return dto;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean exists(final QualifiedName name) {
        final CatalogDto catalogDto = catalogService.get(QualifiedName.ofCatalog(name.getCatalogName()));
        return catalogDto.getDatabases().contains(name.getDatabaseName());
    }

    private void validate(final QualifiedName name) {
        Preconditions.checkNotNull(name, "name cannot be null");
        Preconditions.checkState(name.isDatabaseDefinition(), "name %s is not for a database", name);
    }
}


text:
.class public Lcom/google/android/gles_jni/EGLSurfaceImpl;
.super Ljavax/microedition/khronos/egl/EGLSurface;
.source "EGLSurfaceImpl.java"

# instance fields
.field mEGLSurface:I

.field private mNativePixelRef:I

# direct methods
.method public constructor <init>()V
    .locals 1

    .prologue
    const/4 v0, 0x0

    .line 24
    invoke-direct {p0}, Ljavax/microedition/khronos/egl/EGLSurface;-><init>()V

    .line 25
    iput v0, p0, Lcom/google/android/gles_jni/EGLSurfaceImpl;->mEGLSurface:I

    .line 26
    iput v0, p0, Lcom/google/android/gles_jni/EGLSurfaceImpl;->mNativePixelRef:I

    .line 27
    return-void
.end method

.method public constructor <init>(I)V
    .locals 1
    .param p1, "surface"    # I

    .prologue
    .line 28
    invoke-direct {p0}, Ljavax/microedition/khronos/egl/EGLSurface;-><init>()V

    .line 29
    iput p1, p0, Lcom/google/android/gles_jni/EGLSurfaceImpl;->mEGLSurface:I

    .line 30
    const/4 v0, 0x0

    iput v0, p0, Lcom/google/android/gles_jni/EGLSurfaceImpl;->mNativePixelRef:I

    .line 31
    return-void
.end method

# virtual methods
.method public equals(Ljava/lang/Object;)Z
    .locals 5
    .param p1, "o"    # Ljava/lang/Object;

    .prologue
    const/4 v1, 0x1

    const/4 v2, 0x0

    .line 35
    if-ne p0, p1, :cond_1

    .line 40
    :cond_0
    :goto_0
    return v1

    .line 36
    :cond_1
    if-eqz p1, :cond_2

    invoke-virtual {p0}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v3

    invoke-virtual {p1}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v4

    if-eq v3, v4, :cond_3

    :cond_2
    move v1, v2

    goto :goto_0

    :cond_3
    move-object v0, p1

    .line 38
    check-cast v0, Lcom/google/android/gles_jni/EGLSurfaceImpl;

    .line 40
    .local v0, "that":Lcom/google/android/gles_jni/EGLSurfaceImpl;
    iget v3, p0, Lcom/google/android/gles_jni/EGLSurfaceImpl;->mEGLSurface:I

    iget v4, v0, Lcom/google/android/gles_jni/EGLSurfaceImpl;->mEGLSurface:I

    if-eq v3, v4, :cond_0

    move v1, v2

    goto :goto_0
.end method

.method public hashCode()I
    .locals 1

    .prologue
    .line 46
    iget v0, p0, Lcom/google/android/gles_jni/EGLSurfaceImpl;->mEGLSurface:I

    return v0
.end method


text:
require 'ansible/ruby/modules/base'

module Ansible
  module Ruby
    module Modules
      # Create, start, stop and delete servers on the cloudscale.ch IaaS service.
      # All operations are performed using the cloudscale.ch public API v1.
      # For details consult the full API documentation: U(https://www.cloudscale.ch/en/api/v1).
      # A valid API token is required for all operations. You can create as many tokens as you like using the cloudscale.ch control panel at U(https://control.cloudscale.ch).
      class Cloudscale_server < Base
        # @return [:running, :stopped, :absent, nil] State of the server
        attribute :state
        validates :state, expression_inclusion: {:in=>[:running, :stopped, :absent], :message=>"%{value} needs to be :running, :stopped, :absent"}, allow_nil: true

        # @return [String, nil] Name of the Server.,Either C(name) or C(uuid) are required. These options are mutually exclusive.
        attribute :name
        validates :name, type: String

        # @return [String, nil] UUID of the server.,Either C(name) or C(uuid) are required. These options are mutually exclusive.
        attribute :uuid
        validates :uuid, type: String

        # @return [String, nil] Flavor of the server.
        attribute :flavor
        validates :flavor, type: String

        # @return [String, nil] Image used to create the server.
        attribute :image
        validates :image, type: String

        # @return [Integer, nil] Size of the root volume in GB.
        attribute :volume_size_gb
        validates :volume_size_gb, type: Integer

        # @return [Integer, nil] Size of the bulk storage volume in GB.,No bulk storage volume if not set.
        attribute :bulk_volume_size_gb
        validates :bulk_volume_size_gb, type: Integer

        # @return [String, nil] List of SSH public keys.,Use the full content of your .pub file here.
        attribute :ssh_keys
        validates :ssh_keys, type: String

        # @return [Boolean, nil] Attach a public network interface to the server.
        attribute :use_public_network
        validates :use_public_network, expression_inclusion: {:in=>[true, false], :message=>"%{value} needs to be true, false"}, allow_nil: true

        # @return [Boolean, nil] Attach a private network interface to the server.
        attribute :use_private_network
        validates :use_private_network, expression_inclusion: {:in=>[true, false], :message=>"%{value} needs to be true, false"}, allow_nil: true

        # @return [Boolean, nil] Enable IPv6 on the public network interface.
        attribute :use_ipv6
        validates :use_ipv6, expression_inclusion: {:in=>[true, false], :message=>"%{value} needs to be true, false"}, allow_nil: true

        # @return [String, nil] UUID of another server to create an anti-affinity group with.
        attribute :anti_affinity_with
        validates :anti_affinity_with, type: String

        # @return [Object, nil] Cloud-init configuration (cloud-config) data to use for the server.
        attribute :user_data

        # @return [String, nil] cloudscale.ch API token.,This can also be passed in the CLOUDSCALE_API_TOKEN environment variable.
        attribute :api_token
        validates :api_token, type: String

        # @return [Integer, nil] Timeout in seconds for calls to the cloudscale.ch API.
        attribute :api_timeout
        validates :api_timeout, type: Integer
      end
    end
  end
end


text:
use crate::crypto::{CertificateChain, HashAlgorithm};
use crate::fetcher::Fetcher;
use crate::http::{HttpRequest, Method};
use crate::runtime::Runtime;
use anyhow::{anyhow, Error, Result};
use der_parser::{
    ber::{BerObject, BerObjectContent},
    oid,
    oid::Oid,
};
use serde::{Deserialize, Serialize};
use std::time::{Duration, SystemTime};
use tokio::sync::Mutex;
use x509_parser::{
    certificate::X509Certificate,
    extensions::{GeneralName, ParsedExtension},
};

fn create_ocsp_request(cert: &X509Certificate, issuer: &X509Certificate) -> Vec<u8> {
    let hash_algorithm = HashAlgorithm::Sha1;
    let issuer_name = issuer.tbs_certificate.subject.as_raw();
    let issuer_key = issuer
        .tbs_certificate
        .subject_pki
        .subject_public_key
        .data
        .as_ref();
    let issuer_key_hash = hash_algorithm.digest(issuer_key);
    let issuer_name_hash = hash_algorithm.digest(issuer_name);
    let serial_number = cert.tbs_certificate.raw_serial();
    // https://tools.ietf.org/html/rfc6960#section-4.1.1
    // CertID          ::=     SEQUENCE {
    //     hashAlgorithm       AlgorithmIdentifier,
    //     issuerNameHash      OCTET STRING, -- Hash of issuer's DN
    //     issuerKeyHash       OCTET STRING, -- Hash of issuer's public key
    //     serialNumber        CertificateSerialNumber }
    let cert_id = BerObject::from_seq(vec![
        hash_algorithm.to_ber(),
        BerObject::from_obj(BerObjectContent::OctetString(&issuer_name_hash)),
        BerObject::from_obj(BerObjectContent::OctetString(&issuer_key_hash)),
        BerObject::from_obj(BerObjectContent::Integer(serial_number)),
    ]);
    // https://tools.ietf.org/html/rfc6960#section-4.1.1
    // Request         ::=     SEQUENCE {
    //     reqCert                     CertID,
    //     singleRequestExtensions     [0] EXPLICIT Extensions OPTIONAL }
    let request = BerObject::from_seq(vec![cert_id]);
    // https://tools.ietf.org/html/rfc6960#section-4.1.1
    // TBSRequest      ::=     SEQUENCE {
    //     version             [0]     EXPLICIT Version DEFAULT v1,
    //     requestorName       [1]     EXPLICIT GeneralName OPTIONAL,
    //     requestList                 SEQUENCE OF Request,
    //     requestExtensions   [2]     EXPLICIT Extensions OPTIONAL }
    let tbs_request = BerObject::from_seq(vec![BerObject::from_seq(vec![request])]);
    // https://tools.ietf.org/html/rfc6960#section-4.1.1
    // OCSPRequest     ::=     SEQUENCE {
    //     tbsRequest                  TBSRequest,
    //     optionalSignature   [0]     EXPLICIT Signature OPTIONAL }
    let ocsp_request = BerObject::from_seq(vec![tbs_request]);
    ocsp_request.to_vec().unwrap()
}

// https://datatracker.ietf.org/doc/html/rfc4325#section-2
// https://datatracker.ietf.org/doc/html/rfc3280#section-4.2.2.1
const AIA: Oid<'static> = oid!(1.3.6 .1 .5 .5 .7 .1 .1);
// https://www.iana.org/assignments/smi-numbers/smi-numbers.xhtml#smi-numbers-1.3.6.1.5.5.7.48.1
const AIA_OCSP: Oid<'static> = oid!(1.3.6 .1 .5 .5 .7 .48 .1);

pub async fn fetch_from_ca(
    cert_der: &[u8],
    issuer_der: &[u8],
    fetcher: &dyn Fetcher,
) -> Result<Vec<u8>> {
    let cert = x509_parser::parse_x509_certificate(cert_der)
        .map_err(|e| Error::from(e).context("Failed to parse cert DER"))?
        .1;
    let issuer = x509_parser::parse_x509_certificate(issuer_der)
        .map_err(|e| Error::from(e).context("Failed to parse issuer DER"))?
        .1;
    let aia = cert.extensions().iter().find(|ext| ext.oid == AIA);
    let aia = if let Some(aia) = aia {
        aia
    } else {
        // If the certificate doesn't include an AIA section, it is probably a
        // self-signed certificate. Return a stub OCSP response.
        return Ok(b"ocsp".to_vec());
    };
    let aia = if let ParsedExtension::AuthorityInfoAccess(aia) = aia.parsed_extension() {
        aia
    } else {
        return Err(anyhow!("Failed to parse AIA extension"));
    };
    let url = aia
        .accessdescs
        .iter()
        .find_map(|access_desc| {
            if access_desc.access_method == AIA_OCSP {
                match access_desc.access_location {
                    GeneralName::URI(url) => Some(url),
                    _ => None,
                }
            } else {
                None
            }
        })
        .ok_or_else(|| anyhow!("AIA OCSP responder with type of URI is not found."))?;
    let req = HttpRequest {
        body: create_ocsp_request(&cert, &issuer),
        headers: vec![(
            String::from("content-type"),
            String::from("application/ocsp-request"),
        )],
        method: Method::Post,
        url: url.into(),
    };
    let rsp = fetcher
        .fetch(req)
        .await
        .map_err(|e| e.context("Failed to fetch OCSP"))?;
    Ok(rsp.body)
}

const OCSP_KEY: &str = "OCSP";

#[derive(Serialize, Deserialize)]
struct OcspData {
    pub expiration_time: SystemTime,
    pub recommended_update_time: SystemTime,
    #[serde(with = "crate::serde_helpers::base64")]
    pub value: Vec<u8>,
}

pub enum OcspUpdateStrategy {
    EarlyAsRecommended,
    LazyIfUnexpired,
}

/// Reads OCSP in storage, checks the expiration status, and returns latest.
/// If OCSP in storage needs update, fetches it from the server and writes it
/// into storage. The outging traffic to the server is throttled to be a
/// single task.
/// If there is any error when reading from and writing to storage, the error
/// will be ignored but an error message will be printed to output/log.
pub async fn read_and_update_ocsp_in_storage(
    certificate_chain: &CertificateChain,
    runtime: &Runtime,
    strategy: OcspUpdateStrategy,
) -> Result<Vec<u8>> {
    // Checks whether we can directly return the existing OCSP in storage.
    match runtime.storage.read(OCSP_KEY).await {
        Ok(Some(old_ocsp)) => {
            if let Ok(old_ocsp) = serde_json::from_str::<OcspData>(&old_ocsp) {
                match strategy {
                    OcspUpdateStrategy::EarlyAsRecommended => {
                        if old_ocsp.recommended_update_time > runtime.now {
                            return Ok(old_ocsp.value);
                        }
                    }
                    OcspUpdateStrategy::LazyIfUnexpired => {
                        if old_ocsp.expiration_time > runtime.now {
                            return Ok(old_ocsp.value);
                        }
                    }
                }
            } else {
                // The existing OCSP in storage can't be parsed as `OcspData`.
            }
        }
        Ok(None) => {
            // There is no OCSP in storage.
        }
        Err(e) => {
            println!("Failed to read OCSP from storage. {}", e);
        }
    }
    if certificate_chain.issuers.is_empty() {
        return Err(Error::msg("Certificate chain contains no issuer."));
    }
    let cert_der = &certificate_chain.end_entity.der;
    let issuer_der = &certificate_chain.issuers[0].der;
    let new_ocsp_value = {
        static SINGLE_TASK: Mutex<()> = Mutex::const_new(());
        let guard = SINGLE_TASK.lock().await;
        let ocsp = fetch_from_ca(cert_der, issuer_der, runtime.fetcher.as_ref()).await?;
        std::mem::drop(guard);
        ocsp
    };
    const SIX_DAYS: Duration = Duration::from_secs(3600 * 24 * 6);
    const ONE_DAY: Duration = Duration::from_secs(3600 * 24);
    let new_ocsp = OcspData {
        expiration_time: runtime.now + SIX_DAYS,
        recommended_update_time: runtime.now + ONE_DAY,
        value: new_ocsp_value,
    };
    let write_result = runtime
        .storage
        .write(OCSP_KEY, &serde_json::to_string(&new_ocsp)?)
        .await;
    if let Err(e) = write_result {
        println!("Failed to write OCSP to storage. {}", e);
    }
    Ok(new_ocsp.value)
}


text:
import { CompareCondition, Metrics, StringCondition, ThresholdCondition, ThresholdRangeCondition, Tuple } from '../alert';

export class NodeType {
  static API_GATEWAY: NodeType = new NodeType('gio-apim-gateway', 'API Gateway');
  static MANAGEMENT_API: NodeType = new NodeType('gio-apim-management', 'Management API');

  static TYPES: NodeType[] = [NodeType.API_GATEWAY, NodeType.MANAGEMENT_API];

  application: string;
  name: string;

  constructor(application: string, name: string) {
    this.application = application;
    this.name = name;
  }
}

export class NodeMetrics extends Metrics {
  static NODE_HOSTNAME: NodeMetrics = new NodeMetrics('node.hostname', 'Hostname', [StringCondition.TYPE], true);

  static NODE_APPLICATION: NodeMetrics = new NodeMetrics('node.application', 'Type', [StringCondition.TYPE], true, undefined, () => {
    const applications: Tuple[] = [];

    NodeType.TYPES.forEach((app) => {
      applications.push(new Tuple(app.application, app.name));
    });

    return applications;
  });

  static OS_CPU_PERCENT: NodeMetrics = new NodeMetrics('os.cpu.percent', 'OS CPU (%)', [
    ThresholdCondition.TYPE,
    ThresholdRangeCondition.TYPE,
    CompareCondition.TYPE,
  ]);

  static PROCESS_CPU_PERCENT: NodeMetrics = new NodeMetrics('process.cpu.percent', 'Process CPU (%)', [
    ThresholdCondition.TYPE,
    ThresholdRangeCondition.TYPE,
    CompareCondition.TYPE,
  ]);

  static PROCESS_CPU_TOTAL: NodeMetrics = new NodeMetrics('process.cpu.total', 'Process CPU (total)', [
    ThresholdCondition.TYPE,
    ThresholdRangeCondition.TYPE,
    CompareCondition.TYPE,
  ]);

  static JVM_MEM_HEAP_USED: NodeMetrics = new NodeMetrics('jvm.mem.heap.used', 'JVM Heap used', [
    ThresholdCondition.TYPE,
    ThresholdRangeCondition.TYPE,
    CompareCondition.TYPE,
  ]);

  static JVM_MEM_HEAP_MAX: NodeMetrics = new NodeMetrics('jvm.mem.heap.max', 'JVM Heap max', [
    ThresholdCondition.TYPE,
    ThresholdRangeCondition.TYPE,
    CompareCondition.TYPE,
  ]);

  static JVM_MEM_HEAP_PERCENT: NodeMetrics = new NodeMetrics('jvm.mem.heap.percent', 'JVM Heap (%))', [
    ThresholdCondition.TYPE,
    ThresholdRangeCondition.TYPE,
    CompareCondition.TYPE,
  ]);

  static METRICS: NodeMetrics[] = [
    NodeMetrics.NODE_HOSTNAME,
    NodeMetrics.NODE_APPLICATION,
    NodeMetrics.OS_CPU_PERCENT,
    NodeMetrics.PROCESS_CPU_PERCENT,
    NodeMetrics.PROCESS_CPU_TOTAL,
    NodeMetrics.JVM_MEM_HEAP_USED,
    NodeMetrics.JVM_MEM_HEAP_MAX,
    NodeMetrics.JVM_MEM_HEAP_PERCENT,
  ];
}

export class NodeLifecycleMetrics extends Metrics {
  static NODE_HOSTNAME: NodeLifecycleMetrics = new NodeLifecycleMetrics('node.hostname', 'Hostname', [StringCondition.TYPE], true);

  static NODE_APPLICATION: NodeLifecycleMetrics = new NodeLifecycleMetrics(
    'node.application',
    'Type',
    [StringCondition.TYPE],
    true,
    undefined,
    () => {
      const applications: Tuple[] = [];

      NodeType.TYPES.forEach((app) => {
        applications.push(new Tuple(app.application, app.name));
      });

      return applications;
    },
  );

  static NODE_EVENT: NodeLifecycleMetrics = new NodeLifecycleMetrics('node.event', 'Event', [StringCondition.TYPE], true, undefined, () => {
    const events: Tuple[] = [];
    events.push(new Tuple('NODE_START', 'Start'));
    events.push(new Tuple('NODE_STOP', 'Stop'));
    return events;
  });

  static METRICS: NodeLifecycleMetrics[] = [
    NodeLifecycleMetrics.NODE_HOSTNAME,
    NodeLifecycleMetrics.NODE_APPLICATION,
    NodeLifecycleMetrics.NODE_EVENT,
  ];
}

export class NodeHealthcheckMetrics extends Metrics {
  static NODE_HOSTNAME: NodeHealthcheckMetrics = new NodeHealthcheckMetrics('node.hostname', 'Hostname', [StringCondition.TYPE]);

  static NODE_APPLICATION: NodeHealthcheckMetrics = new NodeHealthcheckMetrics(
    'node.application',
    'Type',
    [StringCondition.TYPE],
    undefined,
    undefined,
    () => {
      const applications: Tuple[] = [];

      NodeType.TYPES.forEach((app) => {
        applications.push(new Tuple(app.application, app.name));
      });

      return applications;
    },
  );

  static NODE_STATUS: NodeHealthcheckMetrics = new NodeHealthcheckMetrics(
    'node.healthy',
    'Status',
    [StringCondition.TYPE],
    undefined,
    undefined,
    () => {
      const events: Tuple[] = [];
      events.push(new Tuple('true', 'Healthy'));
      events.push(new Tuple('false', 'Unhealthy'));
      return events;
    },
  );

  static METRICS: NodeHealthcheckMetrics[] = [
    NodeHealthcheckMetrics.NODE_HOSTNAME,
    NodeHealthcheckMetrics.NODE_APPLICATION,
    NodeHealthcheckMetrics.NODE_STATUS,
  ];
}


text:
<?php

namespace common\models;

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

/**
 * WorkingWithSearch represents the model behind the search form about `common\models\WorkingWith`.
 */
class WorkingWithSearch extends WorkingWith
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['iWorkingWithID'], 'integer'],
            [['vWorkingWithName', 'eStatus'], 'safe'],
        ];
    }

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

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = WorkingWith::find();

        // add conditions that should always apply here

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

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'iWorkingWithID' => $this->iWorkingWithID,
        ]);

        $query->andFilterWhere(['like', 'vWorkingWithName', $this->vWorkingWithName])
            ->andFilterWhere(['like', 'eStatus', $this->eStatus]);

        return $dataProvider;
    }
}


text:
<?php

namespace morph;
/**
 * Morph collection object
 *
 * This is designed to work with finder methods within Morph_Object
 *
 * This object behaves like an array (e.g. it is Iterable, Countable and
 * provides ArrayAccess).
 *
 * This collection class also provides a bunch of additional functionality
 * such as sorting, filtering, reducing etc
 *
 * @package Morph
 */
class Collection extends \ArrayObject
{

    /**
     * @var int
     */
    private $totalCount;

    /**
     * The classname of the class this collection should allow
     * @var String
     */
    private $permissableType = '\morph\Object';

    /**
     * Sets the classname of the class this collection should allow
     * @param string $type
     * @return void
     */
    public function setPermissableType($type)
    {
        $this->permissableType = (string) $type;
    }

    /**
     * Gets the total count
     *
     * Sets the total count
     *
     * @param int $totalCount
     * @return void
     */
    public function setTotalCount($totalCount)
    {
        $this->totalCount = (int) $totalCount;
    }

    /**
     * Returns the total count if set
     *
     * @return int
     */
    public function totalCount()
    {
        return $this->totalCount;
    }

    // UTILITY FUNCTIONS

    /**
     * Iterates over each value in the collection passing them to the callback function.
     *
     * If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.
     *
     * If no callback is provided and values which equate to false will be removed
     *
     * A copy of this object is returned but with the filter applied
     *
     * @param $callback
     * @return Morph_Array
     */
    public function filter($callback = null)
    {
        return new self(\array_filter($this->getArrayCopy(), $callback));
    }

    /**
     * Performs $callback on each object within the array
     *
     * The callback function must take a minimum of 2 parameter $object and $key.
     * A third optional parameter is also supported which will be passed $userdata
     *
     * @param callback $callback The callback function that should be applied to each object
     * @param mixed $userdata If supplied is passed a third parameter to $callback
     * @return Morph_Collection this object but with the callback applied
     */
    public function walk($callback, $userdata = null)
    {
        $copy = $this->getArrayCopy();
        \array_walk($copy, $callback, $userdata);
        return new self($copy);
    }

    /**
     * Iteratively reduces this collection to a single value using a callback function
     *
     *  applies iteratively the function $callback to the elements of the array input,
     *  so as to reduce the array to a single value.
     *
     * @param callback $callback
     * @param mixed $initial
     * @return mixed
     */
    public function reduce($callback, $initial = null)
    {
        return \array_reduce($this->getArrayCopy(), $callback, $initial);
    }

    /**
     * Sorts this collection using the specified Morph_ICompare object
     *
     * @param Morph_ICompare $comparator
     * @return boolean
     */
    public function comparatorSort(ICompare $comparator)
    {
        $copy = $this->getArrayCopy(); //ArrayObject
        $sorted = \usort($copy,array($comparator, 'compare'));
        $this->exchangeArray($copy);
        return $sorted;
    }

    /**
     * Sorts this collection using the specified Morph_ICompare object
     *
     * Preserves keys
     *
     * @param $comparator
     * @return boolean
     */
    public function comparatorASort(ICompare $comparator)
    {
        return $this->uasort(array($comparator, 'compare'));
    }

    /**
     * Sorts this collection based on the specified $propertyName
     *
     * @param $propertyName
     * @return boolean
     */
    public function propertySort($propertyName, $preserveKeys = false)
    {
        $comparator = new \morph\compare\Property($propertyName);
        $sorted = null;
        if($preserveKeys === true){
            $sorted = $this->comparatorASort($comparator);
        }else{
            $sorted = $this->comparatorSort($comparator);
        }
        return $sorted;
    }

    /**
     * Sorts this collection numerically based on the specified $propertyName
     *
     * @param $propertyName
     * @return boolean
     */
    public function numericPropertySort($propertyName, $preserveKeys = false)
    {
        $comparator = new \morph\compare\NumericProperty($propertyName);
        $sorted = null;
        if($preserveKeys === true){
            $sorted = $this->comparatorASort($comparator);
        }else{
            $sorted = $this->comparatorSort($comparator);
        }
        return $sorted;
    }

    // ARRAY ACCESS FUNCTIONS

    /**
     * Appends the given $object to the collection
     *
     * This function override the parent append to do type checking
     *
     */
    public function append($object)
    {
        $this->checkType($object);
        return parent::append($object);
    }

    /**
     * Sets the given offset to the given $object
     *
     * This function override the parent offsetSet to do type checking
     *
     */
    public function offsetSet($offset, $object)
    {
        $this->checkType($object);
        return parent::offsetSet($offset, $object);
    }

    /**
     * Checks that $object is an instance of the permissable type
     *
     * Throws a RuntimeException if not
     *
     * @param $object
     */
    private function checkType($object){
        if(!($object instanceof $this->permissableType)){
            throw new \RuntimeException('object of type ' . \get_class($object) . ' does not extend ' . $this->permissableType);
        }
    }

    public function __toString()
    {
        $class = $this->permissableType;
        $count = $this->count();
        return "\morph\Collection($class) Count: $count";
    }
}