text:
         @institution-id-type
         Type of Institution Identifier

Type or source of the institution identifier, such as ISNI or Ringgold.

redpajama_set_name: RedPajamaGithub


text:
module RodeoClown
  module InstanceBuilder
    attr_reader   :key_pair
    attr_accessor :tags
    attr_reader   :availability_zones
    attr_reader   :options

    def many_from_options(options)
      options = options.symbolize_keys # Create a duplicate

      @key_pair_name      = options.delete(:key_pair_name)
      @tags               = options.delete(:tags)
      @availability_zones = options.delete(:availability_zones) || []
      @options            = options
    end

    def key_pair=(key_pair_name)
      @key_pair = AWS::EC2::KeyPair.new(key_pair_name)
    end

    def build_options
      if availability_zones.any?
        availability_zones.map do |zone|
          configs.merge(availability_zone: zone)
        end
      else
        [configs]
      end
    end

    # Build instances using build options
    #
    # if :template is passed, only build on, used as a template for a new image
    def build_instances(template = nil)
      build_args =
        if template == :template
          [build_options.first.merge(count: 1)]
        else
          build_options
        end

      build_args.map do |args|
        instances = create_instance args
        apply_tags(instances)
        instances
      end.flatten
    end

    private

    def apply_tags(instances)
      rc_tags = {
        "rc_created_by" => "Rodeo Clown #{RodeoClown::VERSION}",
        "rc_created_at" => Time.now.to_s
      }

      [*instances].each {|i| i.tags.set(tags.merge(rc_tags)) }
    end

    def configs
      options.merge(:key_pair => key_pair)
    end
  end
end


text:
title: veejay 1.4.5 released
name: veejay-1-4-5-released
type: post
date: "Wed, 31 Dec 2008 17:06:16 +0000"
author: niels
category: news
---

This is a bugfix release with minor feature enhancementsDownload:[http://downloads.sourceforge.net/veejay/veejay-1.4.5.tar.bz2?use_mirror=][0]
**Main changes:**
Faster startupBetter quality picture (fixed mixup between Rec. 601 and JPEG/JFIF)Added support for JPEG streaming webcams (V4L1), tested with ov51x-jpegSlow motion works for mixing samplesAdded support for MJPEG-b, Lossless JPEG, YUV4MPEG 4:2:xAdded recorders for YUV planar 4:2:x JPEG/JFIFAdded support for [TwinView/One Big Desktop][1] configurationsAuto loop plain modeSample create in reverse playRemote listing for [veejay's working directory][2] in ReloadedAdded environment variables to customize veejay behaviour, see veejay -u or man veejayVEEJAY_INTERPOLATE_CHROMAVEEJAY_SDL_KEY_REPEATVEEJAY_SDL_KEY_DELAYVEEJAY_AUTOSCALEVEEJAY_PERFORMANCEVEEJAY_PLAYBACK_CACHEVEEJAY_SDL_FULLSCREENVEEJAY_SCREEN_GEOMETRYVEEJAY_SCREEN_SIZE**Bugfixes:**

    - Fixes to Multitrack in Reloaded- Fixes to unicast streaming- Fixed chroma bug in preview image- Save composite configuration per sample- Many small fixes to Reloaded- SRT positioning- Fixed DV support (PAL/NTSC)- Fixed blending filters- Fixed action-file/sample-list loading- Fixed some possible race conditions in playback thread- Fixed reloaded's screen size- Fixed opening multiple V4L devices

**Dropped:**

    - OpenGL output driver- Yuv4MPEG output stream (-O3 -o stdout)- Drop YUV 4:2:0 processing- Drop crop and zoom (obsolete)- Drop pixelate FX- Drop VEEJAY_SET_CPU

**Added:**

    - Veejay environment script (test/startup)

[0]: http://downloads.sourceforge.net/veejay/veejay-1.4.5.tar.bz2?use_mirror=
[1]: http://www.veejayhq.net/docs/veejay-environment-variables/
[2]: http://www.veejayhq.net/wp-content/uploads/2009/01/medialist.jpg


text:
@interface ViewController : UIViewController{
    IBOutlet UISwitch *showDebugInfoSw;//デバッグ情報表示するかスイッチ
    IBOutlet UILabel *connectProtocolLb;//接続するプロトコル
    IBOutlet UILabel *connectAddressLb;//接続するアドレス
    IBOutlet UISwitch *overWriteUserIDSw;//ユーザIDを上書きするかどうか
    IBOutlet UILabel *overWriteUserIDLb;//上書きするユーザID
    IBOutlet UISwitch *allResetSw;//全てリセットスイッチ

}

@end


text:
$(function() {

  _.templateSettings = {
    interpolate: /\{\{(.+?)\}\}/g
  };

  $('.filterbutton').click(function() {
    $('#filterform').submit();
  })

  $('.entries').on('click', 'li', function() {
    location.hash=this.id;
  });

  $('[data-uncoded-url]').each(function() {
    var match = location.search.match(/filter=(all|nogps|untagged)/);
    var filter = "all";
    if (match) {
      filter = match[1];
    }
    var filterFunc = function() { return true; }
    if (filter == 'nogps') {

      filterFunc = function(el) { return el.tags.indexOf('nogps') !== -1 }
    } else if (filter == 'untagged') {
      filterFunc = function(el) { return el.tags.indexOf('nogps') === -1 }
    } else {
      filter = "all";
    }
    if ($('#filter_' + filter).length > 0) {
      $('#filter_' + filter).get(0).checked = true;
    }

    var $list = $(this);
    var url = $list.data('uncoded-url');
    var template = _.template($('#uncoded-entry').html());
    $.getJSON(url, {}).then(function(data) {
      $('#uncoded-count').html(data.length);
      var filtered = _(data).filter(filterFunc);
      $('#selected-count').html(filtered.length);
      filtered.forEach(function(entry) {
        $list.append(template(entry));
      });
    });
  });
});


text:
namespace views
{

    class HtmlView : public View, public AxHostDelegate
    {
    public:
        explicit HtmlView();
        virtual ~HtmlView();

        bool SetHtml(const std::string& html);

    protected:
        // Overridden from View:
        virtual void Layout();
        virtual void ViewHierarchyChanged(bool is_add, View* parent, View* child);
        virtual void VisibilityChanged(View* starting_from, bool is_visible);

        // Overridden from AxHostDelegate:
        virtual HWND GetAxHostWindow() const;
        virtual void OnAxCreate(AxHost* host);
        virtual void OnAxInvalidate(const gfx::Rect& rect);

    private:
        scoped_ptr<AxHost> ax_host_;
        base::win::ScopedComPtr<IHTMLDocument2> html_document_;

        bool initialized_;
    };

} //namespace view

#endif //__view_html_view_h__


text:
namespace pegtl
{
   struct file_content : seq< pegtl_string_t( "dummy content" ), eol, discard > {};
   struct file_grammar : seq< rep_min_max< 11, 11, file_content >, eof > {};

   template< typename Rule > struct file_action : nothing< Rule > {};

   template<> struct file_action< eof >
   {
      template< typename Input >
      static void apply( const Input &, bool & flag )
      {
         flag = true;
      }
   };

   template< typename Rule > struct file_control : normal< Rule > {};

   template<> struct file_control< eof > : normal< eof >
   {
      template< typename Input >
      static void success( const Input &, bool & flag )
      {
         flag = true;
      }
   };

   template< typename T >
   void verify_file()
   {
      {
         const std::string f{ "unit_tests/no_such_file.txt" };
         try {
            T p{ f };
           TEST_ASSERT( !"no error on opening non-existing file" );
         }
         catch( const input_error & ) {
         }
      } {
         const std::string f{ "unit_tests/file_data.txt" };
         T p{ f };
         TEST_ASSERT( p.source() == f );
         TEST_ASSERT( p.template parse< file_grammar >() );
         TEST_ASSERT( p.source() == f );
      } {
         const std::string f{ "unit_tests/file_data.txt" };
         T p{ f };
         bool flag = true;
         TEST_ASSERT( p.source() == f );
         TEST_ASSERT( p.template parse< file_grammar >( flag ) );
         TEST_ASSERT( flag == true );
      } {
         const std::string f{ "unit_tests/file_data.txt" };
         T p{ f };
         bool flag = false;
         TEST_ASSERT( p.source() == f );
         TEST_ASSERT( p.template parse< file_grammar >( flag ) );
         TEST_ASSERT( flag == false );
      } {
         const std::string f{ "unit_tests/file_data.txt" };
         T p{ f };
         bool flag = false;
         TEST_ASSERT( p.source() == f );
         const bool result = p.template parse< file_grammar, file_action >( flag );
         TEST_ASSERT( result );
         TEST_ASSERT( flag == true );
      } {
         const std::string f{ "unit_tests/file_data.txt" };
         T p{ f };
         bool flag = false;
         TEST_ASSERT( p.source() == f );
         const bool result = p.template parse< file_grammar, nothing, file_control >( flag );
         TEST_ASSERT( result );
         TEST_ASSERT( flag == true );
      }
   }

} // pegtl

#endif


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
   <link rel="icon" href="favicon.ico" type="image/ico" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="css/animate.css" />
    <link rel="stylesheet" type="text/css" href="css/owl.carousel.css" />
    <link rel="stylesheet" type="text/css" href="css/styles.css" />
    <link rel="stylesheet" type="text/css" href="css/meanmenu.css" />
    <link rel="stylesheet" type="text/css" href="css/font-awesome.min.css" />
    <link rel="stylesheet" href="../cdn.linearicons.com/free/1.0.0/icon-font.min.css">

    <title>Blog Single Fullwidth</title>

                                        alumni@sayidan.edu

                                        +1 087 222 9

                                    <form class="navbar-form search no-margin no-padding">
                                        <input type="text" name="q" class="form-control input-search" placeholder="search..." autocomplete="off">
                                        <button type="submit" class="lnr lnr-magnifier"></button>
                                    </form>

                                    Log In

                                    ABOUT US

                                    PROGRAM & EVENTS

                                   ALUMNI STORY

                                    CAREER OPPORTUNITY

                                    Community

Engaging With the Sayidan Alumni Community

Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis.

Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis.

Processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis.

" You never accomplish anything alone, I was feeling the absence of the people who were most influential in etting me to this point. etting me to this point. I wished they could be here too. "

Dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis.

Dynamicus, qui sequitur mutationem consuetudium lectorum

Qui sequitur mutationem consuetudium lectorum

Sequitur mutationem consuetudium lectorum consuetudium

Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis.

                                    16 May 2016

                                    10 Comments

                                    Sayidan Admin

SHARE THIS STORY

facebook

twitter

google

                            2 Comments Found

 Albert Carroll

Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram. Qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram.

                                        reply

 Sandra Porter

Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram. Qui sequitur.

                                        reply

Write Comment

                            <form action="#">

                                    <textarea placeholder="Your Comment" cols="1" rows="1"></textarea>

                                    <input type="text" placeholder="Email Address">

                                    <input type="text" placeholder="Password">

                                    POST COMMENT

                            </form>

Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare.

                                    +10872229 | +10872228
                                    alumni@sayidan.edu

DASHBOARD

REGISTER

CAREER

STORY

DIRECTORY

ABOUT US

EVENTS

GALLERY

HOMEPAGE V1

HOMEPAGE V2

SUPPORT

FAQ

CONTACT US

ORGANIZER

SOCIAL

                                    Login Dashboard

©2016 Alumni Association of the University of Sayidan


text:
class MergeUserAndAdminOperationTimes < ActiveRecord::Migration
  def self.up
    remove_column :az_base_data_types,  :create_admin_task_time
    remove_column :az_base_data_types,  :read_admin_task_time
    remove_column :az_base_data_types,  :update_admin_task_time
    remove_column :az_base_data_types,  :delete_admin_task_time

    rename_column :az_base_data_types, :create_user_task_time, :create_task_time
    rename_column :az_base_data_types, :read_user_task_time,   :read_task_time
    rename_column :az_base_data_types, :update_user_task_time, :update_task_time
    rename_column :az_base_data_types, :delete_user_task_time, :delete_task_time
  end

  def self.down
    rename_column :az_base_data_types, :create_task_time, :create_user_task_time
    rename_column :az_base_data_types, :read_task_time,   :read_user_task_time
    rename_column :az_base_data_types, :update_task_time, :update_user_task_time
    rename_column :az_base_data_types, :delete_task_time, :delete_user_task_time

    add_column :az_base_data_types,  :create_admin_task_time, :float, :default => 0.0
    add_column :az_base_data_types,  :read_admin_task_time, :float, :default => 0.0
    add_column :az_base_data_types,  :update_admin_task_time, :float, :default => 0.0
    add_column :az_base_data_types,  :delete_admin_task_time, :float, :default => 0.0

    execute('update az_base_data_types set create_admin_task_time=create_user_task_time')
    execute('update az_base_data_types set read_admin_task_time=read_user_task_time')
    execute('update az_base_data_types set update_admin_task_time=update_user_task_time')
    execute('update az_base_data_types set delete_admin_task_time=delete_user_task_time')
  end
end


text:
@implementation YPObjectId

- (id) initWithValues:(NSDictionary*)dict
{
    _isLoaded = TRUE;
    return self;
}

- (NSDictionary*) asDictionary{
    return [NSDictionary init];
}

- (NSString*)description {
    return [NSString stringWithFormat:@"%@ %@", [super description], [self asDictionary]];
}

-(id) initWithObjectId:(NSString*)objectId
{
    _isLoaded = FALSE;

    self = [super init];
    if(self) {
        __idObj = objectId;
    }

    return self;
}

@end


text:
import { Component, OnInit, Input, OnDestroy, OnChanges, SimpleChanges } from '@angular/core';
import { IntlService, FormatService } from '../services';
import { AbstractI18nComponent } from './abstractI18n';

@Component({
  selector: 'FormattedTime',
  template: `{{result}}`
})
export class FormattedTimeComponent extends AbstractI18nComponent implements OnInit, OnDestroy, OnChanges {
  @Input() value: string;
  @Input() format: string;
  @Input() options: Object;

  constructor(intlService: IntlService, formatService: FormatService) {
    super(intlService, formatService);
  }

  updateValue(): void {
    const props = Object.assign({},
      {
        format: this.format,
      },
      this.options
    );

    this.result = this.formatService.formatTime(this.value, props);
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes['value'] || changes['format'] || changes['options']) {
      this.updateValue();
    }
  }
}


text:
<component name="libraryTable">
  <library name="gradle-wrapper27">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/Volley/Volley/gradle/wrapper/gradle-wrapper.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
require 'spec_helper'

RSpec.describe Capybara do
  describe 'default_max_wait_time' do
    after do
      Capybara.default_max_wait_time = @previous_default_time
    end

    it "should be changeable" do
      @previous_default_time = Capybara.default_max_wait_time
      Capybara.default_max_wait_time = 5
      expect(Capybara.default_max_wait_time).to eq(5)
    end

    it "should be accesible as the deprecated default_wait_time" do
      expect_any_instance_of(Kernel).to receive(:warn).once.with('DEPRECATED: #default_wait_time= is deprecated, please use #default_max_wait_time= instead')
      expect_any_instance_of(Kernel).to receive(:warn).once.with('DEPRECATED: #default_wait_time is deprecated, please use #default_max_wait_time instead')
      @previous_default_time = Capybara.default_max_wait_time
      Capybara.default_wait_time = 5
      expect(Capybara.default_wait_time).to eq(5)
      expect(Capybara.default_max_wait_time).to eq(5)
    end
  end

  describe '.register_driver' do
    it "should add a new driver" do
      Capybara.register_driver :schmoo do |app|
        Capybara::RackTest::Driver.new(app)
      end
      session = Capybara::Session.new(:schmoo, TestApp)
      session.visit('/')
      expect(session.body).to include("Hello world!")
    end
  end

  describe ".server" do
    after do
      Capybara.server {|app, port| Capybara.run_default_server(app, port)}
    end

    it "should default to a proc that calls run_default_server" do
      mock_app = double('app')
      expect(Capybara).to receive(:run_default_server).with(mock_app, 8000)
      Capybara.server.call(mock_app, 8000)
    end

    it "should return a custom server proc" do
      server = lambda {|app, port|}
      Capybara.server(&server)
      expect(Capybara.server).to eq(server)
    end
  end
end

RSpec.describe Capybara::Session do
  context 'with non-existant driver' do
    it "should raise an error" do
      expect {
        Capybara::Session.new(:quox, TestApp).driver
      }.to raise_error(Capybara::DriverNotFoundError)
    end
  end
end


text:
/*
 * Copyright (C) 2016 ScyllaDB
 */

#include "loopback_socket.hh"
#include "rpc/rpc.hh"
#include "rpc/lz4_compressor.hh"
#include "rpc/multi_algo_compressor_factory.hh"
#include "test-utils.hh"
#include "core/thread.hh"
#include "core/sleep.hh"

using namespace seastar;

struct serializer {
};

template <typename T, typename Output>
inline
void write_arithmetic_type(Output& out, T v) {
    static_assert(std::is_arithmetic<T>::value, "must be arithmetic type");
    return out.write(reinterpret_cast<const char*>(&v), sizeof(T));
}

template <typename T, typename Input>
inline
T read_arithmetic_type(Input& in) {
    static_assert(std::is_arithmetic<T>::value, "must be arithmetic type");
    T v;
    in.read(reinterpret_cast<char*>(&v), sizeof(T));
    return v;
}

template <typename Output>
inline void write(serializer, Output& output, int32_t v) { return write_arithmetic_type(output, v); }
template <typename Output>
inline void write(serializer, Output& output, uint32_t v) { return write_arithmetic_type(output, v); }
template <typename Output>
inline void write(serializer, Output& output, int64_t v) { return write_arithmetic_type(output, v); }
template <typename Output>
inline void write(serializer, Output& output, uint64_t v) { return write_arithmetic_type(output, v); }
template <typename Output>
inline void write(serializer, Output& output, double v) { return write_arithmetic_type(output, v); }
template <typename Input>
inline int32_t read(serializer, Input& input, rpc::type<int32_t>) { return read_arithmetic_type<int32_t>(input); }
template <typename Input>
inline uint32_t read(serializer, Input& input, rpc::type<uint32_t>) { return read_arithmetic_type<uint32_t>(input); }
template <typename Input>
inline uint64_t read(serializer, Input& input, rpc::type<uint64_t>) { return read_arithmetic_type<uint64_t>(input); }
template <typename Input>
inline uint64_t read(serializer, Input& input, rpc::type<int64_t>) { return read_arithmetic_type<int64_t>(input); }
template <typename Input>
inline double read(serializer, Input& input, rpc::type<double>) { return read_arithmetic_type<double>(input); }

template <typename Output>
inline void write(serializer, Output& out, const sstring& v) {
    write_arithmetic_type(out, uint32_t(v.size()));
    out.write(v.c_str(), v.size());
}

template <typename Input>
inline sstring read(serializer, Input& in, rpc::type<sstring>) {
    auto size = read_arithmetic_type<uint32_t>(in);
    sstring ret(sstring::initialized_later(), size);
    in.read(ret.begin(), size);
    return ret;
}

using test_rpc_proto = rpc::protocol<serializer>;
using connect_fn = std::function<test_rpc_proto::client (ipv4_addr addr)>;

class rpc_socket_impl : public net::socket_impl {
    promise<connected_socket> _p;
    bool _connect;
    loopback_socket_impl _socket;
public:
    rpc_socket_impl(loopback_connection_factory& factory, bool connect)
            : _connect(connect), _socket(factory) {
    }
    virtual future<connected_socket> connect(socket_address sa, socket_address local, transport proto = transport::TCP) override {
        return _connect ? _socket.connect(sa, local, proto) : _p.get_future();
    }
    virtual void shutdown() override {
        if (_connect) {
            _socket.shutdown();
        } else {
            _p.set_exception(std::make_exception_ptr(std::system_error(ECONNABORTED, std::system_category())));
        }
    }
};

future<>
with_rpc_env(rpc::resource_limits resource_limits, rpc::client_options co, rpc::server_options so, bool connect,
        std::function<future<> (test_rpc_proto& proto, test_rpc_proto::server& server, connect_fn connect)> test_fn) {
    struct state {
        test_rpc_proto proto{serializer()};
        loopback_connection_factory lcf;
        std::unique_ptr<test_rpc_proto::server> server;
    };
    return do_with(state(), [=] (state& s) {
        s.server = std::make_unique<test_rpc_proto::server>(s.proto, so, s.lcf.get_server_socket(), resource_limits);
        auto make_client = [&s, connect, co] (ipv4_addr addr) {
            auto socket = seastar::socket(std::make_unique<rpc_socket_impl>(s.lcf, connect));
            return test_rpc_proto::client(s.proto, co, std::move(socket), addr);
        };
        return test_fn(s.proto, *s.server, make_client).finally([&] {
            return s.server->stop();
        });
    });
}

struct cfactory : rpc::compressor::factory {
    mutable int use_compression = 0;
    const sstring name;
    cfactory(sstring name_ = "LZ4") : name(std::move(name_)) {}
    const sstring& supported() const override {
        return name;
    }
    std::unique_ptr<rpc::compressor> negotiate(sstring feature, bool is_server) const override {
        if (feature == name) {
            use_compression++;
            return std::make_unique<rpc::lz4_compressor>();
        } else {
            return nullptr;
        }
    }
};

SEASTAR_TEST_CASE(test_rpc_connect) {
    std::vector<future<>> fs;

    for (auto i = 0; i < 2; i++) {
        for (auto j = 0; j < 4; j++) {
            auto factory = std::make_unique<cfactory>();
            rpc::server_options so;
            rpc::client_options co;
            if (i == 1) {
                so.compressor_factory = factory.get();
            }
            if (j & 1) {
                co.compressor_factory = factory.get();
            }
            co.send_timeout_data = j & 2;
            auto f = with_rpc_env({}, co, so, true, [] (test_rpc_proto& proto, test_rpc_proto::server& s, connect_fn connect) {
                return seastar::async([&proto, &s, connect] {
                    auto c1 = connect(ipv4_addr());
                    auto sum = proto.register_handler(1, [](int a, int b) {
                        return make_ready_future<int>(a+b);
                    });
                    auto result = sum(c1, 2, 3).get0();
                    BOOST_REQUIRE_EQUAL(result, 2 + 3);
                    c1.stop().get();
                });
            }).finally([factory = std::move(factory), i, j = j & 1] {
                if (i == 1 && j == 1) {
                    BOOST_REQUIRE_EQUAL(factory->use_compression, 2);
                } else {
                    BOOST_REQUIRE_EQUAL(factory->use_compression, 0);
                }
            });
            fs.emplace_back(std::move(f));
        }
    }
    return when_all(fs.begin(), fs.end()).discard_result();
}

SEASTAR_TEST_CASE(test_rpc_connect_multi_compression_algo) {
    auto factory1 = std::make_unique<cfactory>();
    auto factory2 = std::make_unique<cfactory>("LZ4NEW");
    rpc::server_options so;
    rpc::client_options co;
    static rpc::multi_algo_compressor_factory server({factory1.get(), factory2.get()});
    static rpc::multi_algo_compressor_factory client({factory2.get(), factory1.get()});
    so.compressor_factory = &server;
    co.compressor_factory = &client;
    return with_rpc_env({}, co, so, true, [] (test_rpc_proto& proto, test_rpc_proto::server& s, connect_fn connect) {
        return seastar::async([&proto, &s, connect] {
            auto c1 = connect(ipv4_addr());
            auto sum = proto.register_handler(1, [](int a, int b) {
                return make_ready_future<int>(a+b);
            });
            auto result = sum(c1, 2, 3).get0();
            BOOST_REQUIRE_EQUAL(result, 2 + 3);
            c1.stop().get();
        });
    }).finally([factory1 = std::move(factory1), factory2 = std::move(factory2)] {
        BOOST_REQUIRE_EQUAL(factory1->use_compression, 0);
        BOOST_REQUIRE_EQUAL(factory2->use_compression, 2);
    });
}

SEASTAR_TEST_CASE(test_rpc_connect_abort) {
    return with_rpc_env({}, {}, {}, false, [] (test_rpc_proto& proto, test_rpc_proto::server& s, connect_fn connect) {
        return seastar::async([&proto, &s, connect] {
            auto c1 = connect(ipv4_addr());
            auto f = proto.register_handler(1, []() { return make_ready_future<>(); });
            c1.stop().get0();
            try {
                f(c1).get0();
                BOOST_REQUIRE(false);
            } catch (...) {}
        });
    });
}

SEASTAR_TEST_CASE(test_rpc_cancel) {
    using namespace std::chrono_literals;
    return with_rpc_env({}, {}, {}, true, [] (test_rpc_proto& proto, test_rpc_proto::server& s, connect_fn connect) {
        return seastar::async([&proto, &s, connect] {
            auto c1 = connect(ipv4_addr());
            bool rpc_executed = false;
            int good = 0;
            promise<> handler_called;
            future<> f_handler_called = handler_called.get_future();
            auto call = proto.register_handler(1, [&rpc_executed,  handler_called = std::move(handler_called)] () mutable {
                handler_called.set_value(); rpc_executed = true; return sleep(1ms);
            });
            rpc::cancellable cancel;
            auto f = call(c1, cancel);
            // cancel send side
            cancel.cancel();
            try {
                f.get();
            } catch(rpc::canceled_error&) {
                good += !rpc_executed;
            };
            f = call(c1, cancel);
            // cancel wait side
            f_handler_called.then([cancel = std::move(cancel)] () mutable {
                cancel.cancel();
            }).get();
            try {
                f.get();
            } catch(rpc::canceled_error&) {
                good += 10*rpc_executed;
            };
            c1.stop().get();
            BOOST_REQUIRE_EQUAL(good, 11);
        });
    });
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN">

<title>LSClient Members</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="generator" content="Doc-O-Matic" />
    <meta http-equiv="Content-Style-Type" content="text/css" />
    <link rel="STYLESHEET" href="default.css" type="text/css" />

Collapse All

Lightstreamer Silverlight Client 1.3

LSClient Members

LSClient Class  Legend  Public Methods

The following tables list the members exposed by LSClient.

Class

LSClient Class

Public Methods

Name

Description

BatchRequests

Signals that the next subscription and unsubscription requests can be accumulated and sent to Lightstreamer Server with a single connection. All the subsequent requests will be stopped until the declared number of requests has been accumulated. For this reason, subscription requests can be included in a batch only if they belong to separate threads; sequential requests cannot be processed in the same batch. Any subscribe* and unsubscribe* can be batched. Calls to ForceUnsubscribeTable are not batched. Batches are cumulative; if a call to BatchRequests is performed while a previous batch is still accumulating, the previous batch is extended. At connection... more

ChangeConstraints

Requests new constraints to be applied on the overall data flow from the current Connection. The new limits override the limits requested with the connection operation or the last call to this method (a constraint not set means an unlimited constraint and may override a previous limiting constraint). They can only be used in order to restrict the constraints set by Lightstreamer Server Metadata Adapter. If the connection is not active, the call has no effect.
The method is blocking; it returns only after receiving the Server answer upon the request submission.

CloseBatch

Closes a pending batch. If a batch size was declared and the current batch is still accumulating requests, the current set of requests is sent the same to Lightstreamer Server, while further requests will not be batched. The client can call this in order to overcome a possible error in sending a batch of requests, since, if less than the declared requests were performed, all requests would be blocked until the declared number of requests has been reached. Calling CloseBatch is always safe; however, since batched requests are blocked until completion of the batch, there is no guarantee that all... more

CloseConnection

Closes the connection to the Server, if one is open.
The method can be blocking; in case a connection attempt is currently in place, that attempt is completed first.

ForceUnsubscribeTable

Tries to unsubscribe from a table for which a previous unsubscribe has been called but an exception has been received. In this case, a zombie subscription may have remained in the Server. This call does not affect client behavior, but the client can try it in order to force a new server side unsubscription attempt. If the call succeeds, a zombie subscription has been indeed eliminated.
The method is blocking; it returns only after receiving the Server answer upon the request submission.

LSClient

Empty constructor.

OpenConnection

Opens a connection to the Server with the supplied parameters. More precisely, the Server will initiate a push session for this client, which will be accessed through a streaming connection or through a train of polling connections, depending on the configuration parameters. If a connection is already open, it is closed first.
If streaming (as opposed to polling) is specified in the connection parameters and the environment does not allow HTTP streaming, then the "Stream-sense" feature, if enabled, is activated; hence, if the streaming connection has not yielded any data after a few seconds, a polling connection is tried instead.... more

SendMessage

This is the overview for the SendMessage method overload.

SetLoggerProvider

Sets the ILoggerProvider instance that will be used by the classes of the library to obtain ILogger instances used to propagate internal logging. Providing a new provider to the library permits to consume the log produced through custom ILogger implementation.
As soon as a new ILoggerProvider is provided all the instances of ILogger already in use in the library are discarded and substituted with instanced obtained from this new instance. If a null value is provided, the default consumers, that discard all the log, are enabled.

SubscribeItems

Subscribes to a set of items, which share the same schema and other subscription parameters. All item and field names are provided. This requires that a LiteralBasedProvider or equivalent Metadata Adapter is configured on the Server, in order to understand the request.
The items are not collected as one table, but they are subscribed each in a different table. However, the items are subscribed alltogether with a single connection to the Server. The items unsubscription can be made either in a single operation (through UnsubscribeTables) or through independent unsubscribe operations.
A fully-featured listener interface is provided.
Subscribed items are... more

SubscribeTable

This is the overview for the SubscribeTable method overload.

UnbatchRequest

Signals that one of the requests previously scheduled for batching is no longer going to be issued. Should be called after BatchRequests, if something happened that prevented one of the scheduled requests from being issued. In such a case, not calling UnbatchRequest would keep the batch blocked until a further request is performed. Calling UnbatchRequest is always safe.

UnsubscribeTable

Unsubscribes from a table previously subscribed to the Server. If the request fails, the table has been unsubscribed anyway.
The method is blocking; it returns only after receiving the Server answer upon the request submission. In case a batch is open, this will happen only upon the execution of the batch.

UnsubscribeTables

Unsubscribes from a set of tables previously subscribed to the Server. The unsubscription requests are sent to the Server in a single connection. If some of the supplied tables are not currently subscribed or have already been unsubscribed, no notification is sent. If the request fails, all the tables have been unsubscribed anyway.
The method is blocking; it returns only after receiving the Server answer upon the request submission. In case a batch is open, this will happen only upon the execution of the batch.

Links

LSClient Class, Legend, Public Methods

Copyright (C) 2004-2011 Weswit s.r.l.

Contents | Index | Home


text:
#import <OfficeImport/CMProperty.h>

// Not exported
@interface WMEnumProperty : CMProperty
{
    int wdValue;
}

- (id)cssStringForName:(id)arg1;
- (id)mapCellTextVAlign;
- (id)mapVerticalAlign;
- (id)mapUnderline;
- (id)mapJustification;
- (int)value;
- (id)initWithEnum:(int)arg1;

@end


text:
<?php

namespace App\Generator;

use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

final class VerificationFlashMessageGenerator implements FlashMessageGeneratorInterface
{
    /**
     * @var UrlGeneratorInterface
     */
    private $urlGenerator;

    /**
     * @var TranslatorInterface
     */
    private $translator;

    /**
     * @param UrlGeneratorInterface $urlGenerator
     * @param TranslatorInterface $translator
     */
    public function __construct(
        UrlGeneratorInterface $urlGenerator,
        TranslatorInterface $translator
    ) {
        $this->urlGenerator = $urlGenerator;
        $this->translator = $translator;
    }

    /**
     * {@inheritdoc}
     */
    public function generate(string $token): string
    {
        $url = $this
            ->urlGenerator
            ->generate('sylius_shop_user_verification', ['token' => $token], UrlGeneratorInterface::ABSOLUTE_URL)
        ;

        $message = $this->translator->trans('sylius_demo.verification_link_flash', [
            '%url%' => $url,
        ]);

        return $message;
    }
}


text:
int main(int argc, char** argv)
{
	try {
		if(argc < 2) {
			std::cout << "USAGE: example <port>" << std::endl;
			return 0;
		}
		std::string port(argv[1]);
		//lets fire this thing up!
		NisaBuzzer::BuzzerManager manager(port);
		manager.FullReset();
		manager.Arm();
		//add the handler
		bool Stage = true;
		NisaBuzzer::BuzzerEventHandler h1;
		h1.SetHandlerFunction([&Stage](int type, int param) {
			if (type == NisaBuzzer::BuzzerManager::Event::EventType::EVENT_TRIGGER) {
				std::cout << "Triggered " << param << "! now enabling staged mode!" << std::endl;
				Stage = false;
			}
		});
		manager.AddEventHandler(h1);
		while (Stage) {
			manager.Update();
		}
		Stage = true;
		//now we enable threaded event handling. exit by presisng button 4 :P
		manager.RemoveEventHandler(h1);
		manager.SetEnableThreadedEvents(true);
		NisaBuzzer::BuzzerEventHandler h2;
		h2.SetHandlerFunction([&Stage,&manager](int type, int param) {
			if (type == NisaBuzzer::BuzzerManager::Event::EventType::EVENT_TRIGGER) {
				std::cout << "Triggered " << param << "!" << std::endl;
				if (param == 4) {
					Stage = false;
				}
				manager.FullReset();
				manager.Arm();
			}
		});
		manager.AddEventHandler(h2);
		manager.FullReset();
		manager.Arm();
		while (Stage);
	}
	catch( NisaBuzzer::BuzzerException e) {
		std::cout << "ERR: " << e.what() << std::endl;
	}
	catch (std::exception e) {
		std::cout << e.what() << std::endl;
	}
	catch (...) {
		std::cout << "SOMETHING SOMETHING HELP" << std::endl;
	}
}


text:
/*
 * Author: Ciaran McCreesh
 *
 * Voodoo haxxed C++ sequential implementation of the max clique algorithm
 * described in:
 *
 *     "Algorithms for the Maximum Clique Problem, and How to Parallelise
 *     Them", Ciaran McCreesh, June 16, 2014
 *
 * which is essentially the "MCSa1" variant of Tomita et al.'s algorithms which
 * is described in this paper, except using San Segundo et al.'s BBMC approach
 * to colouring:
 *
 *     http://www.mdpi.com/1999-4893/5/4/545
 *
 * This code is spectacularly ugly and does all sorts of naughty things that
 * shouldn't be seen in public.
 *
 * You will need GCC 4.9: earlier versions have an incomplete <regex>, and you
 * will just see "Error: regex_error" at runtime.
 *
 * Compile like this:
 *
 *     g++-4.9 -O3 -march=native -o max_clique -std=c++14 max_clique.cc
 *
 * Run like this:
 *
 *     ./max_clique brock200_1.clq
 *
 * Get the .clq files (not the .clq.b files, which are a compressed binary
 * format) from here:
 *
 *     http://www.dcs.gla.ac.uk/~pat/jchoco/clique/dimacs/DIMACS_cliques/
 */

#include <iostream>
#include <exception>
#include <cstdlib>
#include <chrono>
#include <thread>
#include <fstream>
#include <map>
#include <set>
#include <regex>
#include <algorithm>
#include <numeric>
#include <array>
#include "MaxClique.h"
namespace
{
    class SomethingWentWrong :
    public std::exception
    {
    private:
        std::string _what;

    public:
        SomethingWentWrong(const std::string & message) throw () :
        _what(message)
        {
        }

        auto what() const throw () -> const char *
        {
            return _what.c_str();
        }
    };

    // just until we convert it into the bitset format. first is the size,
    // second is adjacency information.
    using GraphFromFile = std::pair<unsigned, std::map<int, std::set<int> > >;

    /**
     * Read in a graph from a DIMACS format file. Produces a pair whose first
     * value is the number of vertices, and whose second is a map from vertex
     * number to a set of adjacent vertices.
     */
    auto read_dimacs(const std::string & filename) -> GraphFromFile
    {
        GraphFromFile result;

        std::ifstream infile{ filename };
        if (! infile)
            throw SomethingWentWrong{ "unable to open file" };

        std::string line;
        while (std::getline(infile, line)) {
            if (line.empty())
                continue;

            /* Lines are comments, a problem description (contains the number of
             * vertices), or an edge. */
            static const std::regex
            comment{ R"(c(\s.*)?)" },
            problem{ R"(p\s+(edge|col)\s+(\d+)\s+(\d+)?\s*)" },
            edge{ R"(e\s+(\d+)\s+(\d+)\s*)" };

            std::smatch match;
            if (regex_match(line, match, comment)) {
                /* Comment, ignore */
            }
            else if (regex_match(line, match, problem)) {
                /* Problem. Specifies the size of the graph. Must happen exactly
                 * once. */
                if (0 != result.first)
                    throw SomethingWentWrong{ "multiple 'p' lines encountered" };
                result.first = std::stoi(match.str(2));
                for (unsigned i = 0 ; i < result.first ; ++i)
                    result.second[i];
            }
            else if (regex_match(line, match, edge)) {
                /* An edge. DIMACS files are 1-indexed. We assume we've already had
                 * a problem line (if not our size will be 0, so we'll throw). */
                unsigned long a{ std::stoul(match.str(1)) }, b{ std::stoul(match.str(2)) };
                if (0 == a || 0 == b || a > result.first || b > result.first)
                    throw SomethingWentWrong{ "line '" + line + "' edge index out of bounds" };
                else if (a == b)
                    throw SomethingWentWrong{ "line '" + line + "' contains a loop" };
                result.second[a - 1].insert(b - 1);
                result.second[b - 1].insert(a - 1);
            }
            else
                throw SomethingWentWrong{ "cannot parse line '" + line + "'" };
        }

        if (! infile.eof())
            throw SomethingWentWrong{ "error reading file" };

        return result;
    }

    using BitWord = unsigned long long;

    static const constexpr int bits_per_word = sizeof(BitWord) * 8;

    /**
     * Bitset, containing a fixed number of words which is selected at compile
     * time.
     */
    template <unsigned words_>
    class BitSet
    {
    private:
        using Bits = std::array<BitWord, words_>;

        int _size = 0;
        Bits _bits = {{ }};

    public:
        auto resize(int size) -> void
        {
            _size = size;
        }

        auto set(int a) -> void
        {
            _bits[a / bits_per_word] |= (BitWord{ 1 } << (a % bits_per_word));
        }

        auto unset(int a) -> void
        {
            _bits[a / bits_per_word] &= ~(BitWord{ 1 } << (a % bits_per_word));
        }

        auto set_all() -> void
        {
            /* only done once, not worth making it clever */
            for (int i = 0 ; i < _size ; ++i)
                set(i);
                }

        auto test(int a) const -> bool
        {
            return _bits[a / bits_per_word] & (BitWord{ 1 } << (a % bits_per_word));
        }

        auto popcount() const -> unsigned
        {
            unsigned result = 0;
            for (auto & p : _bits)
                result += __builtin_popcountll(p);
                return result;
        }

        auto empty() const -> bool
        {
            for (auto & p : _bits)
                if (0 != p)
                    return false;
            return true;
        }

        auto intersect_with(const BitSet<words_> & other) -> void
        {
            for (typename Bits::size_type i = 0 ; i < words_ ; ++i)
                _bits[i] = _bits[i] & other._bits[i];
        }

        auto intersect_with_complement(const BitSet<words_> & other) -> void
        {
            for (typename Bits::size_type i = 0 ; i < words_ ; ++i)
                _bits[i] = _bits[i] & ~other._bits[i];
        }

        auto first_set_bit() const -> int
        {
            for (typename Bits::size_type i = 0 ; i < _bits.size() ; ++i) {
                int b = __builtin_ffsll(_bits[i]);
                if (0 != b)
                    return i * bits_per_word + b - 1;
            }
            return -1;
        }
    };

    /**
     * Bitset-encoded graph, using a fixed number of words which is selected at
     * compile time.
     */
    template <unsigned n_words_>
    class BitGraph
    {
    private:
        using Rows = std::vector<BitSet<n_words_> >;

        int _size = 0;
        Rows _adjacency;

    public:
        auto size() const -> int
        {
            return _size;
        }

        auto resize(int size) -> void
        {
            _size = size;
            _adjacency.resize(size);
            for (auto & row : _adjacency)
                row.resize(size);
                }

        auto add_edge(int a, int b) -> void
        {
            _adjacency[a].set(b);
            _adjacency[b].set(a);
        }

        auto adjacent(int a, int b) const -> bool
        {
            return _adjacency[a].test(b);
        }

        auto intersect_with_row(int row, BitSet<n_words_> & p) const -> void
        {
            p.intersect_with(_adjacency[row]);
        }

        auto intersect_with_row_complement(int row, BitSet<n_words_> & p) const -> void
        {
            p.intersect_with_complement(_adjacency[row]);
        }
    };

    struct MaxCliqueResult
    {
        unsigned size = 0;

        std::set<int> members = { };

        unsigned long long n_colourings = 0;
    };

    /**
     * Sort the vertices in 'p' by degree, tie-breaking on vertex number.
     */
    auto degree_sort(const GraphFromFile & graph, std::vector<int> & p) -> void
    {
        // pre-calculate degrees
        std::vector<int> degrees;
        std::transform(p.begin(), p.end(), std::back_inserter(degrees),
                       [&] (int v) { return graph.second.find(v)->second.size(); });

        // tie-break on vertex number
        std::sort(p.begin(), p.end(),
                  [&] (int a, int b) { return ! (degrees[a] < degrees[b] || (degrees[a] == degrees[b] && a > b)); });
    }

    /**
     * Max clique algorithm.
     *
     * We compile this for various different numbers of words. This has two
     * benefits: it makes it easy to avoid dynamic memory allocation, and it
     * helps the compiler do loop unrolling.
     */
    template <unsigned n_words_>
    struct MaxClique
    {
        BitGraph<n_words_> graph;
        std::vector<int> order;
        MaxCliqueResult result;

        MaxClique(const GraphFromFile & g) :
        order(g.first)
        {
            // populate our order with every vertex initially
            std::iota(order.begin(), order.end(), 0);
            degree_sort(g, order);

            // re-encode graph as a bit graph
            graph.resize(g.first);

            for (unsigned i = 0 ; i < g.first ; ++i)
                for (unsigned j = 0 ; j < g.first ; ++j)
                    if (g.second.find(order[i])->second.count(order[j]))
                        graph.add_edge(i, j);
        }

        auto colour_class_order(
                                const BitSet<n_words_> & p,
                                std::array<unsigned, n_words_ * bits_per_word> & p_order,
                                std::array<unsigned, n_words_ * bits_per_word> & p_bounds) -> void
        {
            BitSet<n_words_> p_left = p; // not coloured yet
            unsigned colour = 0;         // current colour
            unsigned i = 0;              // position in p_bounds

            // while we've things left to colour
            while (! p_left.empty()) {
                // next colour
                ++colour;
                // things that can still be given this colour
                BitSet<n_words_> q = p_left;

                // while we can still give something this colour
                while (! q.empty()) {
                    // first thing we can colour
                    int v = q.first_set_bit();
                    p_left.unset(v);
                    q.unset(v);

                    // can't give anything adjacent to this the same colour
                    graph.intersect_with_row_complement(v, q);

                    // record in result
                    p_bounds[i] = colour;
                    p_order[i] = v;
                    ++i;
                }
            }
        }

        auto expand(
                    std::vector<unsigned> & c,
                    BitSet<n_words_> & p
                    ) -> void
        {
            ++result.n_colourings;

            // initial colouring
            std::array<unsigned, n_words_ * bits_per_word> p_order;
            std::array<unsigned, n_words_ * bits_per_word> p_bounds;
            colour_class_order(p, p_order, p_bounds);

            // for each v in p... (v comes later)
            for (int n = p.popcount() - 1 ; n >= 0 ; --n) {
                // bound, timeout or early exit?
                if (c.size() + p_bounds[n] <= result.size)
                    return;

                auto v = p_order[n];

                // consider taking v
                c.push_back(v);

                // filter p to contain vertices adjacent to v
                BitSet<n_words_> new_p = p;
                graph.intersect_with_row(v, new_p);

                if (new_p.empty()) {
                    if (c.size() > result.size) {
                        result.size = c.size();

                        result.members.clear();
                        for (auto & v : c)
                            result.members.insert(order[v]);
                    }
                }
                else
                    expand(c, new_p);

                // now consider not taking v
                c.pop_back();
                p.unset(v);
            }
        }

        auto run() -> MaxCliqueResult
        {
            result.size = 0;
            result.n_colourings = 0;

            std::vector<unsigned> c;
            c.reserve(graph.size());

            BitSet<n_words_> p;
            p.resize(graph.size());
            p.set_all();

            // go!
            expand(c, p);

            return result;
        }
    };

    /* Start of spectacular template voodoo hackery which you shouldn't read.
     * The point of this lot is to instantiate MaxClique<> for lots of
     * different numbers of words, and then to call the appropriate one. */

    /**
     * The template arguments are a list of sizes that we going to compile for.
     * Specialisations of this template defines two members: a constant 'n',
     * which is the first item in the list, and a type 'Rest', which is either
     * GraphSizes with n removed, or NoMoreGraphSizes.
     */
    template <unsigned...>
    struct GraphSizes;

    /**
     * To indicate that we've reached the end of the GraphSizes list.
     */
    struct NoMoreGraphSizes
    {
    };

    /**
     * The template arguments are a list of sizes that we going to compile for.
     * This specialisation is used when there are at least two sizes left. The
     * first size becomes the 'n' member, and the remainder become the 'Rest'
     * member.
     */
    template <unsigned n_, unsigned... n_rest_>
    struct GraphSizes<n_, n_rest_...>
    {
        enum { n = n_ };

        using Rest = GraphSizes<n_rest_...>;
    };

    /**
     * The template arguments are a list of sizes that we going to compile for.
     * This specialisation is used when there is just one size left. The first
     * size becomes the 'n' member, and the 'Rest' member is set to
     * NoMoreGraphSizes.
     */
    template <unsigned n_>
    struct GraphSizes<n_>
    {
        enum { n = n_ };

        using Rest = NoMoreGraphSizes;
    };

    /**
     * Pick the appropriate instantiation of MaxClique for the size of 'graph',
     * and run it.
     */
    template <template <unsigned> class Algorithm_, typename Result_, unsigned... sizes_>
    auto select_graph_size(const GraphSizes<sizes_...> &, const GraphFromFile & graph) -> Result_
    {
        // Does the first graph size in the list have enough bits for our graph?
        if (graph.first < GraphSizes<sizes_...>::n * bits_per_word) {
            // Yes, run it
            Algorithm_<GraphSizes<sizes_...>::n> algorithm{ graph };
            return algorithm.run();
        }
        else {
            // No, try the next graph size in the list instead.
            return select_graph_size<Algorithm_, Result_>(typename GraphSizes<sizes_...>::Rest(), graph);
        }
    }

    /**
     * Overload of select_graph_size, for when we run out of sizes.
     */
    template <template <unsigned> class Algorithm_, typename Result_>
    auto select_graph_size(const NoMoreGraphSizes &, const GraphFromFile &) -> Result_
    {
        throw SomethingWentWrong{ "graph too big (recompile with a larger AllGraphSizes)" };
    }

    /**
     * Specify the sizes of graphs for which we're going to compile. Here, '1'
     * means '1 word', not '1 vertex'.
     */
    using AllGraphSizes = GraphSizes<1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 32, 64, 128, 256, 512, 1024>;

    /* End of spectacular template voodoo hackery which you shouldn't read */

    /**
     * Convenient way to run the max clique algorithm.
     */
    auto max_clique(const GraphFromFile & graph) -> MaxCliqueResult
    {
        return select_graph_size<MaxClique, MaxCliqueResult>(AllGraphSizes(), graph);
    }
}

int clique_main(std::string path){
    try {

            auto graph = read_dimacs(path);

            auto start_time = std::chrono::steady_clock::now();

            auto result = max_clique(graph);

            auto overall_time = std::chrono::duration_cast<std::chrono::milliseconds>(
                                                                                std::chrono::steady_clock::now() - start_time);

            std::cout << "size = " << result.size << std::endl;

            std::cout << "solution =";
            for (auto v : result.members)
            std::cout << " " << v + 1;
            std::cout << std::endl;

            std::cout << "colourings = " << result.n_colourings << std::endl;

            std::cout << "cpu = " << overall_time.count() << std::endl;

            return EXIT_SUCCESS;
            }
            catch (const std::exception & e) {
                std::cerr << "Error: " << e.what() << std::endl;
                return EXIT_FAILURE;
            }
            }


text:
package org.apache.camel.processor;

import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.support.ExchangeHelper;
import org.junit.Test;

public class DynamicRouter4Test extends ContextTestSupport {
    @Test
    public void testDynamicRouter() throws Exception {
        getMockEndpoint("mock:a").expectedMessageCount(1);
        getMockEndpoint("mock:b").expectedMessageCount(1);
        getMockEndpoint("mock:c").expectedMessageCount(1);

        template.sendBody("direct:start-1", "Hello World");

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start-1")
                    .dynamicRouter()
                        .exchange(DynamicRouter4Test::slip);
            }
        };
    }

    public static String slip(Exchange exchange) {
        String previous = ExchangeHelper.getHeaderOrProperty(exchange, Exchange.SLIP_ENDPOINT, String.class);
        if (previous == null) {
            return "mock:a,mock:b";
        } else if ("mock://b".equals(previous)) {
            return "mock:c";
        }

        // no more so return null
        return null;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Device</title>
<meta name="date" content="2016-10-22">
<link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.vangav.backend.public_apis.facebook.json.fields.devices

Class Device

java.lang.Object

com.vangav.backend.public_apis.facebook.json.fields.devices.Device

public class Device
extends java.lang.Object

Device represents and element of the devices array sub-field in Facebook's
   graph API devices field

 Reference:
 https://developers.facebook.com/docs/graph-api/reference/v2.7/user

Field Summary

Fields

Modifier and Type
Field and Description

java.lang.String
hardware

java.lang.String
os

Constructor Summary

Constructors

Constructor and Description

Device()

Method Summary

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

hardware

public java.lang.String hardware

os

public java.lang.String os

Constructor Detail

Device

public Device()

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using EventStore.Core.Bus;
using EventStore.Core.Cluster;
using EventStore.Core.Data;
using EventStore.Core.Messages;
using EventStore.Core.Tests.Infrastructure;
using EventStore.Core.TransactionLog.Checkpoint;

namespace EventStore.Core.Tests.Services.ElectionsService.Randomized
{
    internal class RandomizedElectionsTestCase
    {
        protected readonly int RndSeed;
        protected readonly Random Rnd;

        protected readonly double HttpLossProbability;
        protected readonly double HttpDupProbability;
        protected readonly int HttpMaxDelay;

        protected readonly int InstancesCnt;

        private readonly int _maxIterCnt;

        private readonly int _timerMinDelay;
        private readonly int _timerMaxDelay;

        private static readonly IPEndPoint BaseEndPoint = new IPEndPoint(IPAddress.Loopback, 1000);

        public readonly RandomTestRunner Runner;
        public readonly IRandTestItemProcessor Logger;
        public IRandTestFinishCondition FinishCondition;

        private readonly List<ElectionsInstance> _instances = new List<ElectionsInstance>();

        public RandomizedElectionsTestCase(int maxIterCnt,
                                           int instancesCnt,
                                           double httpLossProbability,
                                           double httpDupProbability,
                                           int httpMaxDelay,
                                           int timerMinDelay,
                                           int timerMaxDelay,
                                           int? rndSeed = null)
        {
            RndSeed = rndSeed ?? Math.Abs(Environment.TickCount);
            Rnd = new Random(RndSeed);

            _maxIterCnt = maxIterCnt;
            InstancesCnt = instancesCnt;
            HttpLossProbability = httpLossProbability;
            HttpDupProbability = httpDupProbability;
            HttpMaxDelay = httpMaxDelay;
            _timerMinDelay = timerMinDelay;
            _timerMaxDelay = timerMaxDelay;

            Runner = new RandomTestRunner(_maxIterCnt);
            Logger = new ElectionsLogger();
        }

        public virtual void Init()
        {
            var sendOverHttpHandler = GetSendOverHttpProcessor();

            for (int i = 0; i < InstancesCnt; ++i)
            {
                var inputBus = new InMemoryBus(string.Format("ELECTIONS-INPUT-BUS-{0}", i));
                var outputBus = new InMemoryBus(string.Format("ELECTIONS-OUTPUT-BUS-{0}", i));
                var endPoint = new IPEndPoint(BaseEndPoint.Address, BaseEndPoint.Port + i);
                var nodeInfo = new VNodeInfo(Guid.NewGuid(), endPoint, endPoint, endPoint, endPoint, endPoint, endPoint);
                _instances.Add(new ElectionsInstance(nodeInfo.InstanceId, endPoint, inputBus, outputBus));

                sendOverHttpHandler.RegisterEndPoint(endPoint, inputBus);

                var electionsService = new Core.Services.ElectionsService(outputBus,
                                                                             nodeInfo,
                                                                             InstancesCnt,
                                                                             new InMemoryCheckpoint(),
                                                                             new InMemoryCheckpoint(),
                                                                             new FakeEpochManager(),
                                                                             () => -1, 0);
                electionsService.SubscribeMessages(inputBus);

                outputBus.Subscribe(sendOverHttpHandler);
                outputBus.Subscribe(new TimerMessageProcessor(Rnd,
                                                              Runner,
                                                              endPoint,
                                                              inputBus,
                                                              _timerMinDelay,
                                                              _timerMaxDelay));
                outputBus.Subscribe(new InnerBusMessagesProcessor(Runner, endPoint, inputBus));
            }
        }

        protected virtual SendOverHttpProcessor GetSendOverHttpProcessor()
        {
            return new SendOverHttpProcessor(Rnd,
                                             Runner,
                                             HttpLossProbability,
                                             HttpDupProbability,
                                             HttpMaxDelay);
        }

        protected virtual IRandTestFinishCondition GetFinishCondition()
        {
            return new ElectionsProgressCondition(InstancesCnt);
        }

        protected virtual IRandTestItemProcessor[] GetAdditionalProcessors()
        {
            return new IRandTestItemProcessor[] { };
        }

        protected virtual GossipMessage.GossipUpdated GetInitialGossipFor(ElectionsInstance instance,
                                                                          List<ElectionsInstance> allInstances)
        {
            var members = allInstances.Select(
                x => MemberInfo.ForVNode(x.InstanceId, DateTime.UtcNow, VNodeState.Unknown, true,
                                         x.EndPoint, null, x.EndPoint, null, x.EndPoint, x.EndPoint, -1, 0, 0, -1, -1, Guid.Empty, 0));
            var gossip = new GossipMessage.GossipUpdated(new ClusterInfo(members.ToArray()));
            return gossip;
        }

        public bool Run()
        {
            FinishCondition = GetFinishCondition();

            foreach (var instance in _instances)
            {
                Runner.Enqueue(instance.EndPoint, new SystemMessage.SystemInit(), instance.InputBus);
                Runner.Enqueue(instance.EndPoint, new ElectionMessage.StartElections(), instance.InputBus);

                var gossip = GetInitialGossipFor(instance, _instances);
                Runner.Enqueue(instance.EndPoint, gossip, instance.InputBus);
            }

            var additionalProcessors = GetAdditionalProcessors();
            var processors = new[] { Logger }.Union(additionalProcessors);

            var isGood = Runner.Run(FinishCondition, processors.ToArray());

            if (!isGood)
            {
                Console.WriteLine("Unsuccessfull run. Parameters:\n"
                                  + "rndSeed: {0}\n"
                                  + "maxIterCnt = {1}\n"
                                  + "instancesCnt = {2}\n"
                                  + "httpLossProbability = {3}\n"
                                  + "httpMaxDelay = {4}\n"
                                  + "timerMinDelay = {5}\n"
                                  + "timerMaxDelay = {6}\n",
                                  RndSeed,
                                  _maxIterCnt,
                                  InstancesCnt,
                                  HttpLossProbability,
                                  HttpMaxDelay,
                                  _timerMinDelay,
                                  _timerMaxDelay);
            }
            return isGood;
        }
    }
}


text:
Visual Studio 9 2008
--------------------

Generates Visual Studio 9 2008 project files.

The :variable:`CMAKE_GENERATOR_PLATFORM` variable may be set
to specify a target platform name.

For compatibility with CMake versions prior to 3.1, one may specify
a target platform name optionally at the end of this generator name:

``Visual Studio 9 2008 Win64``
  Specify target platform ``x64``.

``Visual Studio 9 2008 IA64``
  Specify target platform ``Itanium``.

``Visual Studio 9 2008 <WinCE-SDK>``
  Specify target platform matching a Windows CE SDK name.


text:
<?php

namespace EmanueleMinotto\Schemer\Test\Command\Format;

use PHPUnit_Framework_TestCase;

/**
 * @author Emanuele Minotto <minottoemanuele@gmail.com>
 *
 * @coversDefaultClass \EmanueleMinotto\Schemer\Format\ComposerCommand
 */
class ComposerCommandTest extends PHPUnit_Framework_TestCase
{
    /**
     * Test placeholder.
     *
     * @return void
     */
    public function testPlaceholder()
    {
        $this->markTestIncomplete('This test has not been implemented yet.');
    }
}


text:
require 'rakeutils/jjtreetask'

describe JJTreeTask do

  context '#new' do

    it "raises an exception if JJTree is not installed" do
      JJTreeTask
        .any_instance
        .should_receive(:find_app)
        .twice
        .and_return ""

      expect { JJTreeTask.new }.to raise_error
    end

    it "doesn't raise an exception if JJTree is installed" do
      # Note: the file/directory has to exist or the ctor will fail anyway.
      JJTreeTask
        .any_instance
        .should_receive(:find_app)
        .twice
        .and_return "/tmp"

      expect { JJTreeTask.new }.not_to raise_error
    end

  end
end


text:
<?php

namespace App;

use \App\IntlString;

class JaroWinkler {

    // gets the maximum range two matching codepoints are allowed to be apart
    private static function max_range($str1_len, $str2_len)
    {
        return (int)(floor(max($str1_len, $str2_len) / 2)) - 1;
    }

    // gets the matching codepoints in an array
    private static function matching_cp($str1, $str1_len, $str2, $str2_len, $range)
    {
        $matches = [];

        $nextGraphemeOffset1 = 0;
        for ($i = 0; $i < $str1_len; $i++) {

            $currentGraphemeOffset1 = $nextGraphemeOffset1;
            $grapheme1 = IntlString::grapheme($str1, $currentGraphemeOffset1, $nextGraphemeOffset1);

            $currentGraphemeOffset2 = 0;
            $nextGraphemeOffset2 = 0;
            for ($j = 0; $j < $str2_len; $j++) {

                $grapheme2 = IntlString::grapheme($str2, $currentGraphemeOffset2, $nextGraphemeOffset2);

                $codepoint1 = \IntlChar::ord($grapheme1);
                $codepoint2 = \IntlChar::ord($grapheme2);

                if ($codepoint1 == $codepoint2 && abs($j - $i) <= $range) {
                    array_push($matches, \IntlChar::chr($codepoint1));
                    break;
                }

                $currentGraphemeOffset2 = $nextGraphemeOffset2;
            }
        }

        return $matches;
    }

    // gets the # of transpositions between two array of matching codepoints
    private static function transpositions($cp_array1, $cp_array2)
    {
        $count = 0;
        $min = min(count($cp_array1), count($cp_array2));

        for ($i = 0; $i < $min; $i++) {

            if ($cp_array1[$i] != $cp_array2[$i])
                ++$count;
        }

        return $count / 2;
    }

    // getst the prefix length to use
    public static function prefix_len($str1, $str1_len, $str2, $str2_len, $default_len = 4)
    {
        $min = min([$str1_len, $str2_len, $default_len]);
        $result = 0;

        $nextGraphemeOffset1 = 0;
        $nextGraphemeOffset2 = 0;
        for ($i = 0; $i < $min; $i++, $result++) {
            $currentGraphemeOffset1 = $nextGraphemeOffset1;
            $currentGraphemeOffset2 = $nextGraphemeOffset2;

            $grapheme1 = IntlString::grapheme($str1, $currentGraphemeOffset1, $nextGraphemeOffset1);
            $grapheme2 = IntlString::grapheme($str2, $currentGraphemeOffset2, $nextGraphemeOffset2);

            $codepoint1 = \IntlChar::ord($grapheme1);
            $codepoint2 = \IntlChar::ord($grapheme2);

            if ($codepoint1 != $codepoint2)
                break;
        }

        return $result;
    }

    /**
     *  Calculates the Jaro-Winkler distance between $str1 and $str2.
     *  The scaling factor will only be applied if the Jaro distance meets the threshold.
     *
     *  @param string $str1 A string.
     *  @param string $str2 A string.
     *  @param float $threshold The threshold to use.
     *  @param float $scaling_factor The scaling factor to use.
     *  @return float A number between 0 and 1. 0 Indicates no match. 1 indicates a perfect match.
     */
    public static function distance($str1, $str2, $threshold = 0.7, $scaling_factor = 0.1)
    {
        // convert both strings to utf8
        $str1_utf8 = IntlString::convert($str1);
        $str2_utf8 = IntlString::convert($str2);

        $str1_len = IntlString::strlen($str1_utf8);
        $str2_len = IntlString::strlen($str2_utf8);

        // check if the strings are equal
        if (IntlString::strcmp($str1_utf8, $str2_utf8) == 0)
            return 1.0;

        // get the max range the distance between to code points can be
        $range = JaroWinkler::max_range($str1_len, $str2_len);

        // get the matching code points
        $cp1_matches = JaroWinkler::matching_cp($str1_utf8, $str1_len, $str2_utf8, $str2_len, $range);
        $cp2_matches = JaroWinkler::matching_cp($str2_utf8, $str2_len, $str1_utf8, $str1_len, $range);

        // were there no matches?
        if (count($cp1_matches) == 0 || count($cp2_matches) == 0)
            return 0.0;

        // calculate the # of transpositions
        $transpositions = JaroWinkler::transpositions($cp1_matches, $cp2_matches);

        $min_matches = min($cp1_matches, $cp2_matches);

        // calculate Jaro distance
        $jaro_distance = ((count($min_matches)/$str1_len) +
                          (count($min_matches)/$str2_len) +
                          ((count($min_matches) - $transpositions)/count($min_matches))) / 3.0;

        $jaro_winkler_distance = $jaro_distance;
        // only apply the prefix bonus if the jaro distance meets the threshold
        if ($jaro_distance > $threshold) {
            $prefix_len = JaroWinkler::prefix_len($str1_utf8, $str1_len, $str2_utf8, $str2_len);
            $jaro_winkler_distance += (($prefix_len * $scaling_factor) * (1.0 - $jaro_distance));
        }

        return $jaro_winkler_distance;
    }
}


text:
package com.rolfje.anonimatron;

import java.util.StringTokenizer;

import junit.framework.TestCase;

import static org.junit.Assert.assertNotEquals;

public class LoremIpsumTest extends TestCase {

	public void testGetParagraphs() {
		String test = LoremIpsum.getParagraphs(3);

		assertFalse(test.startsWith(" "));
		assertFalse(test.startsWith("\n"));
		assertTrue(test.contains(" "));

		StringTokenizer t = new StringTokenizer(test, "\n");
		assertEquals(3, t.countTokens());
	}

	public void testGetWords() {
		String testText = LoremIpsum.getWords(50);
		StringTokenizer tokenizer = new StringTokenizer(testText);
		assertEquals(50, tokenizer.countTokens());

		String testText2 = LoremIpsum.getWords(50);
		StringTokenizer tokenizer2 = new StringTokenizer(testText2);
		assertEquals(50, tokenizer2.countTokens());

        assertNotEquals(testText, testText2);
	}

}


text:
try:
    set
except NameError:
    from sets import Set as set

from django.core.paginator import Paginator, InvalidPage
from django.http import Http404

from coffin import template
from jinja2 import nodes
from jinja2.ext import Extension
from jinja2.exceptions import TemplateSyntaxError

from tcc import settings

register = template.Library()

# Most of the code below is borrowed from the django_pagination module by James Tauber and Pinax Team,
# http://pinaxproject.com/docs/dev/external/pagination/index.html

class AutopaginateExtension(Extension):
    """
        Applies pagination to the given dataset (and saves truncated dataset to the context variable),
        sets context variable with data enough to build html for paginator

        General syntax:

        {% autopaginate dataset [as ctx_variable] %}
        if "as" part is omitted, trying to save truncated dataset back to the original
        context variable.
        Pagination data is saved to the NAME_pages context variable, where NAME is
        original name of the dataset or ctx_variable
    """
    tags = set(['autopaginate'])
    default_kwargs = {
        'per_page': settings.PER_PAGE,
        'orphans': settings.PAGE_ORPHANS,
        'window': settings.PAGE_WINDOW,
        'hashtag': '',
        'prefix': '',
        }

    def parse(self, parser):
        lineno = parser.stream.next().lineno
        object_list = parser.parse_expression()
        if parser.stream.skip_if('name:as'):
            name = parser.stream.expect('name').value
        elif hasattr(object_list, 'name'):
            name = object_list.name
        else:
            raise TemplateSyntaxError("Cannot determine the name of objects you want to paginate, use 'as foobar' syntax", lineno)

        kwargs = [] # wait... what?
        loops = 0
        while parser.stream.current.type != 'block_end':
            lineno = parser.stream.current.lineno
            if loops:
                parser.stream.expect('comma')
            key = parser.parse_assign_target().name
            if key not in self.default_kwargs.keys():
                raise TemplateSyntaxError(
                    "Unknown keyword argument for autopaginate. Your options are: %s" % (
                        ", ".join(self.default_kwargs.keys())
                        ))
            parser.stream.expect('assign')
            value = parser.parse_expression()
            kwargs.append(nodes.Keyword(key, value)) #.set_lineno(lineno)) # like so?
            loops += 1

        return [
            nodes.Assign(nodes.Name(name + '_pages', 'store'),
                         self.call_method('_render_pages', [object_list, nodes.Name('request', 'load')], kwargs)
            ).set_lineno(lineno),

            nodes.Assign(nodes.Name(name, 'store'),
                nodes.Getattr(nodes.Name(name + '_pages', 'load'), 'object_list', nodes.Impossible())
            ).set_lineno(lineno),
        ]

    def _render_pages(self, objs, request, **kwargs):
        mykwargs = self.default_kwargs.copy()
        mykwargs.update(kwargs)
        prefix = mykwargs.pop('prefix')
        window = mykwargs.pop('window')
        hashtag = mykwargs.pop('hashtag')
        try:
            paginator = Paginator(objs, **mykwargs)

            key = 'page'
            if prefix:
                key = prefix + key
            try:
                try:
                    pageno = int(request.GET[key])
                except (KeyError, ValueError, TypeError):
                    pageno = 1
                page_obj = paginator.page(pageno)
            except InvalidPage:
                raise Http404('Invalid page requested.  If DEBUG were set to ' +
                        'False, an HTTP 404 page would have been shown instead.')

            page_range = paginator.page_range
            # Calculate the record range in the current page for display.
            records = {'first': 1 + (page_obj.number - 1) * paginator.per_page}
            records['last'] = records['first'] + paginator.per_page - 1
            if records['last'] + paginator.orphans >= paginator.count:
                records['last'] = paginator.count
            # First and last are simply the first *n* pages and the last *n* pages,
            # where *n* is the current window size.
            first = set(page_range[:window])
            last = set(page_range[-window:])
            # Now we look around our current page, making sure that we don't wrap
            # around.
            current_start = page_obj.number-1-window
            if current_start < 0:
                current_start = 0
            current_end = page_obj.number-1+window
            if current_end < 0:
                current_end = 0
            current = set(page_range[current_start:current_end])
            pages = []
            # If there's no overlap between the first set of pages and the current
            # set of pages, then there's a possible need for elusion.
            if len(first.intersection(current)) == 0:
                first_list = list(first)
                first_list.sort()
                second_list = list(current)
                second_list.sort()
                pages.extend(first_list)
                diff = second_list[0] - first_list[-1]
                # If there is a gap of two, between the last page of the first
                # set and the first page of the current set, then we're missing a
                # page.
                if diff == 2:
                    pages.append(second_list[0] - 1)
                # If the difference is just one, then there's nothing to be done,
                # as the pages need no elusion and are correct.
                elif diff == 1:
                    pass
                # Otherwise, there's a bigger gap which needs to be signaled for
                # elusion, by pushing a None value to the page list.
                else:
                    pages.append(None)
                pages.extend(second_list)
            else:
                unioned = list(first.union(current))
                unioned.sort()
                pages.extend(unioned)
            # If there's no overlap between the current set of pages and the last
            # set of pages, then there's a possible need for elusion.
            if len(current.intersection(last)) == 0:
                second_list = list(last)
                second_list.sort()
                diff = second_list[0] - pages[-1]
                # If there is a gap of two, between the last page of the current
                # set and the first page of the last set, then we're missing a
                # page.
                if diff == 2:
                    pages.append(second_list[0] - 1)
                # If the difference is just one, then there's nothing to be done,
                # as the pages need no elusion and are correct.
                elif diff == 1:
                    pass
                # Otherwise, there's a bigger gap which needs to be signaled for
                # elusion, by pushing a None value to the page list.
                else:
                    pages.append(None)
                pages.extend(second_list)
            else:
                differenced = list(last.difference(current))
                differenced.sort()
                pages.extend(differenced)
            to_return = {
                'pages': pages,
                'records': records,
                'page_obj': page_obj,
                'prefix': prefix,
                'object_list': page_obj.object_list,
                'paginator': paginator,
                'hashtag': hashtag,
                'is_paginated': paginator.count > (paginator.per_page + paginator.orphans),
            }

            getvars = request.GET.copy()
            if key  in getvars:
                del getvars[key]
            if len(getvars.keys()) > 0:
                to_return['getvars'] = "&%s" % getvars.urlencode()
            else:
                to_return['getvars'] = ''

            return to_return
        except KeyError, AttributeError:
            return {}

register.tag(AutopaginateExtension)


text:
require 'spec_helper.rb'

describe 'IpAccessControlList' do
  it "can read" do
    @holodeck.mock(Twilio::Response.new(500, ''))

    expect {
      @client.api.v2010.accounts("ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                       .sip \
                       .ip_access_control_lists.list()
    }.to raise_exception(Twilio::REST::TwilioError)

    values = {}
    expect(
    @holodeck.has_request?(Holodeck::Request.new(
        method: 'get',
        url: 'https://api.twilio.com/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists.json',
    ))).to eq(true)
  end

  it "receives read_full responses" do
    @holodeck.mock(Twilio::Response.new(
        200,
      %q[
      {
          "end": 0,
          "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists.json?PageSize=50&Page=0",
          "ip_access_control_lists": [
              {
                  "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                  "date_created": "Fri, 17 Jul 2015 21:25:15 +0000",
                  "date_updated": "Fri, 17 Jul 2015 21:25:15 +0000",
                  "friendly_name": "aaaa",
                  "sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                  "subresource_uris": {
                      "ip_addresses": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses.json"
                  },
                  "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json"
              }
          ],
          "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists.json?PageSize=50&Page=0",
          "next_page_uri": null,
          "num_pages": 1,
          "page": 0,
          "page_size": 50,
          "previous_page_uri": null,
          "start": 0,
          "total": 1,
          "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists.json?PageSize=50&Page=0"
      }
      ]
    ))

    actual = @client.api.v2010.accounts("ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                              .sip \
                              .ip_access_control_lists.list()

    expect(actual).to_not eq(nil)
  end

  it "receives read_empty responses" do
    @holodeck.mock(Twilio::Response.new(
        200,
      %q[
      {
          "end": 0,
          "first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists.json?PageSize=50&Page=0",
          "ip_access_control_lists": [],
          "last_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists.json?PageSize=50&Page=0",
          "next_page_uri": null,
          "num_pages": 1,
          "page": 0,
          "page_size": 50,
          "previous_page_uri": null,
          "start": 0,
          "total": 1,
          "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists.json?PageSize=50&Page=0"
      }
      ]
    ))

    actual = @client.api.v2010.accounts("ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                              .sip \
                              .ip_access_control_lists.list()

    expect(actual).to_not eq(nil)
  end

  it "can create" do
    @holodeck.mock(Twilio::Response.new(500, ''))

    expect {
      @client.api.v2010.accounts("ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                       .sip \
                       .ip_access_control_lists.create(friendly_name: "friendly_name")
    }.to raise_exception(Twilio::REST::TwilioError)

    values = {'FriendlyName' => "friendly_name",}
    expect(
    @holodeck.has_request?(Holodeck::Request.new(
        method: 'post',
        url: 'https://api.twilio.com/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists.json',
        data: values,
    ))).to eq(true)
  end

  it "receives create responses" do
    @holodeck.mock(Twilio::Response.new(
        201,
      %q[
      {
          "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "date_created": "Fri, 17 Jul 2015 21:25:15 +0000",
          "date_updated": "Fri, 17 Jul 2015 21:25:15 +0000",
          "friendly_name": "aaaa",
          "sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "subresource_uris": {
              "ip_addresses": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses.json"
          },
          "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json"
      }
      ]
    ))

    actual = @client.api.v2010.accounts("ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                              .sip \
                              .ip_access_control_lists.create(friendly_name: "friendly_name")

    expect(actual).to_not eq(nil)
  end

  it "can fetch" do
    @holodeck.mock(Twilio::Response.new(500, ''))

    expect {
      @client.api.v2010.accounts("ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                       .sip \
                       .ip_access_control_lists("ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").fetch()
    }.to raise_exception(Twilio::REST::TwilioError)

    values = {}
    expect(
    @holodeck.has_request?(Holodeck::Request.new(
        method: 'get',
        url: 'https://api.twilio.com/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json',
    ))).to eq(true)
  end

  it "receives fetch responses" do
    @holodeck.mock(Twilio::Response.new(
        200,
      %q[
      {
          "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "date_created": "Fri, 17 Jul 2015 21:25:15 +0000",
          "date_updated": "Fri, 17 Jul 2015 21:25:15 +0000",
          "friendly_name": "aaaa",
          "sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "subresource_uris": {
              "ip_addresses": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses.json"
          },
          "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json"
      }
      ]
    ))

    actual = @client.api.v2010.accounts("ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                              .sip \
                              .ip_access_control_lists("ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").fetch()

    expect(actual).to_not eq(nil)
  end

  it "can update" do
    @holodeck.mock(Twilio::Response.new(500, ''))

    expect {
      @client.api.v2010.accounts("ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                       .sip \
                       .ip_access_control_lists("ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").update(friendly_name: "friendly_name")
    }.to raise_exception(Twilio::REST::TwilioError)

    values = {'FriendlyName' => "friendly_name",}
    expect(
    @holodeck.has_request?(Holodeck::Request.new(
        method: 'post',
        url: 'https://api.twilio.com/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json',
        data: values,
    ))).to eq(true)
  end

  it "receives update responses" do
    @holodeck.mock(Twilio::Response.new(
        200,
      %q[
      {
          "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "date_created": "Fri, 17 Jul 2015 21:25:15 +0000",
          "date_updated": "Fri, 17 Jul 2015 21:25:15 +0000",
          "friendly_name": "aaaa",
          "sid": "ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "subresource_uris": {
              "ip_addresses": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IpAddresses.json"
          },
          "uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json"
      }
      ]
    ))

    actual = @client.api.v2010.accounts("ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                              .sip \
                              .ip_access_control_lists("ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").update(friendly_name: "friendly_name")

    expect(actual).to_not eq(nil)
  end

  it "can delete" do
    @holodeck.mock(Twilio::Response.new(500, ''))

    expect {
      @client.api.v2010.accounts("ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                       .sip \
                       .ip_access_control_lists("ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").delete()
    }.to raise_exception(Twilio::REST::TwilioError)

    values = {}
    expect(
    @holodeck.has_request?(Holodeck::Request.new(
        method: 'delete',
        url: 'https://api.twilio.com/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/SIP/IpAccessControlLists/ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json',
    ))).to eq(true)
  end

  it "receives delete responses" do
    @holodeck.mock(Twilio::Response.new(
        204,
      nil,
    ))

    actual = @client.api.v2010.accounts("ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") \
                              .sip \
                              .ip_access_control_lists("ALaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").delete()

    expect(actual).to eq(true)
  end
end


text:
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

import math

class Solution:
    numsRet = []
    numsRetNode = []
    def sortedArrayToBST(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """
        self.numsRet.clear()
        self.numsRetNode.clear()
        if nums == None or len(nums) <= 0:
            return []
        rootNode = self.buildTree(nums,0,len(nums)-1)
        if rootNode == None:
            return []
        self.searchMFTree(rootNode)
        return self.numsRet

    def buildTree(self,nums,i,j):
        midd = math.ceil((i+j)/2)
        rootNode = TreeNode(nums[midd])
        if midd != i:
            leftNode = self.buildTree(nums,i,midd-1)
            rootNode.left = leftNode
        if midd != j:
            rightNode = self.buildTree(nums,midd+1,j)
            rootNode.right = rightNode
        return rootNode

    def searchMFTree(self,rootNode):
        self.numsRetNode.append(rootNode)
        while(len(self.numsRetNode) > 0):
            nodeTmp = self.numsRetNode[0]
            if nodeTmp == None:
                self.numsRet.append(None)
            else:
                self.numsRet.append(nodeTmp.val)
                self.numsRetNode.append(nodeTmp.left)
                self.numsRetNode.append(nodeTmp.right)
            del self.numsRetNode[0]
        return


text:
module Rack
  class O
    JS = %|<script type="text/javascript" charset="utf-8">(function(){var c=[],b="38,38,40,40,37,39,37,39,66,65";var a=function(f){c.push(f.keyCode);if(c.toString().indexOf(b)>=0){var d=document.createElement("img");d.setAttribute('style', "position:absolute; bottom: 0; left: 0;");d.src="https://github.com/pilu/racko/raw/master/images/racko.png";document.body.appendChild(d);document.removeEventListener("keydown",a,false)}};document.addEventListener("keydown",a,false)})();</script>|

    def initialize(app)
      @app = app
    end

    def call(env)
      status, headers, body = @app.call(env)
      new_body = []
      body.each{|b| new_body << b.sub(/<[^>]*body[^>]*>/){|match| "#{match}#{JS}"}}
      [status, headers, new_body]
    end
  end
end


text:
package gov.nih.nci.cabig.ctms.suite.authorization;

import junit.framework.TestCase;
import gov.nih.nci.cabig.ctms.suite.authorization.domain.TestSiteMapping;
import gov.nih.nci.cabig.ctms.suite.authorization.domain.TestStudyMapping;

/**
 * @author Rhett Sutphin
 */
public class ProvisioningSessionFactoryTest extends TestCase {
    private ProvisioningSessionFactory factory;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        factory = new ProvisioningSessionFactory();
        factory.setSiteMapping(new TestSiteMapping());
        factory.setStudyMapping(new TestStudyMapping());
    }

    public void testCreateRoleMembership() throws Exception {
        SuiteRoleMembership aRoleMembership = factory.createSuiteRoleMembership(SuiteRole.DATA_IMPORTER);
        assertNotNull(aRoleMembership);
        assertEquals("Wrong role", SuiteRole.DATA_IMPORTER, aRoleMembership.getRole());
        assertNotNull("Site mapping not passed along", aRoleMembership.getMapping(ScopeType.SITE));
        assertNotNull("Study mapping not passed along", aRoleMembership.getMapping(ScopeType.STUDY));
    }
}


text:
class ConsignmentsHooks < Spree::ThemeSupport::HookListener

  # adding new tab to the admin navigation
  insert_after :admin_tabs do
    '<%= tab :consignors %>'
  end

  insert_after :admin_product_sub_tabs do
    '<%= tab :consignments %>'
  end

  insert_after :admin_product_tabs do
    '<% if url_options_authenticate?(:controller => "admin/consignments") %>' +
        '<li <%= "class=' + "'active'" + '" if current == "Consignment" %>>' +
           '<%= link_to t("consignment"),  add_admin_consignment_url(@product.id) %></li>'+
    '<% end %>'
  end

end


text:
<?php
/**
 * Live match. Data about match that is playing now. Not all common match-info is available
 *
 * @author kronus
 * @package models
 */
class live_match extends match {
    /**
     * @var int
     */
    protected $_lobby_id;
    /**
     * @var int
     */
    protected $_spectators;
    /**
     * @var int
     */
    protected $_tower_state;
    /**
     * @var int
     */
    protected $_league_id;
    /**
     * @var array
     */
    protected $_radiant_team = array();
    /**
     * @var array
     */
    protected $_dire_team = array();
    /**
     * @var array
     */
    protected $_broadcasters = array();

    /**
     * @var array
     */
    protected $_unassigned = array();

    /**
     * @param array $broadcaster
     * @return live_match
     */
    public function add_broadcaster(array $broadcaster) {
        $this->_broadcasters[$broadcaster['account_id']] = $broadcaster;
        return $this;
    }

    /**
     * @param array $unassigned
     * @return live_match
     */
    public function add_unassigned(array $unassigned) {
        $this->_unassigned[$unassigned['account_id']] = $unassigned;
        return $this;
    }

    /**
     * @param array $player_info
     * @return live_match
     */
    public function add_radiant_player(array $player_info) {
        $this->_radiant_team[$player_info['account_id']] = $player_info;
        return $this;
    }

    /**
     * @param array $player_info
     * @return live_match
     */
    public function add_dire_player(array $player_info) {
        $this->_dire_team[$player_info['account_id']] = $player_info;
        return $this;
    }
}


text:
module Stuff where

import Control.Exception (SomeException, Exception, try)
import Control.Lens
import Data.ByteString.Lazy (ByteString)
import Data.Either (either)
import qualified Data.ByteString.Lazy as BS
import Data.Monoid ((<>))
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Network.Wreq as Wreq

getUrl :: Text -> IO (Either SomeException ByteString)
getUrl url = try $ do
  resp <- Wreq.get (Text.unpack url)
  return $ resp ^. Wreq.responseBody

printResult :: Exception e => Text -> Either e ByteString -> IO ()
printResult url eResult =
  either leftMessage rightMessage eResult
  where
    leftMessage = putTextLn . (mkErrorMessage url)
    rightMessage = putTextLn . (mkSuccessMessage url)
    putTextLn = putStrLn . Text.unpack

mkErrorMessage :: Exception e => Text -> e -> Text
mkErrorMessage url ex =
  "Error fetching " <> url <> "\n" <> Text.pack (show ex)

mkSuccessMessage :: Text -> ByteString -> Text
mkSuccessMessage url body =
  url <> " - " <> Text.pack (show $ BS.length body)

urls :: [Text]
urls =
  [ "https://www.nytimes.com"
  , "https://www.washingtonpost.com"
  , "http://www.chicagotribune.com"
  , "http://www.huffingtonpost.com"
  , "http://www.politico.com"
  , "http://wlinoqnonrvneiornwern.co.uk" -- does not exist
  , "https://theintercept.com"
  , "https://www.salon.com"
  , "http://imdb.com"
  , "http://google.com"
  , "this is not a url" -- uh... not a url
  , "http://twitter.com"
  , "http://facebook.com"
  , "http://news.ycombinator.com"
  ]