text:
{{(project | displayName) || projectName}}

Add to Project

{{imageName}}

              <osc-image-summary resource="image" name="imageName"></osc-image-summary>

              <form class="" ng-show="imageStream" novalidate name="form">

                   Name

                     <input type="text"
                            required
                            take-focus
                            minlength="2"
                            maxlength="24"
                            pattern="[a-z]([-a-z0-9]*[a-z0-9])?"
                            ng-model="name"
                            id="appname"
                            name="appname"
                            ng-change="nameTaken = false"
                            class="form-control form-control-md">

Used to uniquely identify within this project all the resources created to support the application.

                      Please enter a valid name.

A valid name is applied to all generated resources. It is an alphanumeric (a-z, and 0-9) string with a maximum length of 24 characters, where the first character is a letter (a-z), and the '-' character is allowed anywhere except the first or last character.

                      A name is required.

                      The name must have at least 2 characters.

                      This name is already in use within the project. Please choose a different name.

                  Git Repository URL

                     <input class="form-control"
                       id="sourceUrl"
                       name="sourceUrl"
                       type="text"
                       required
                       aria-describedby="from_source_help"
                       ng-model="buildConfig.sourceUrl">

                    Sample repository for {{imageName}}: {{image.metadata.annotations.sampleRepo}},
                      ref: {{image.metadata.annotations.sampleRef}},
                      context dir: {{image.metadata.annotations.sampleContextDir}}
                    Try it

                    A Git repository URL is required.

                    Git repository should be a URL.

                    Git Reference

                      <input id="gitref" ng-model="buildConfig.gitRef" type="text" placeholder="master" class="form-control form-control-md">

Optional branch, tag, or commit.

                    Context Dir

                      <input id="contextdir" ng-model="buildConfig.contextDir" type="text" placeholder="/" class="form-control form-control-md">

Optional subdirectory for the application source code, used as the context directory for the build.

                  <osc-form-section
                    header="Routing"
                    about-title="Routing"
                    about="Routing is a way to make your application publicly visible. Otherwise you may only be able to access your application by its IP address, if allowed by the system administrator."
                    expand="true"
                    can-toggle="false"
                    >

                        Create a route to the application:
                        {{routing | yesNo}}

                          <input type="checkbox" ng-model="routing.include">
                            Create a route to the application

                  </osc-form-section>

                  <osc-form-section
                    header="Deployment Configuration"
                    about-title="Deployment Configuration"
                    about="Deployment configurations describe how your application is configured
                      by the cluster and under what conditions it should be recreated (e.g. when the image changes)."
                    expand="true"
                    can-toggle="false"
                    >

Autodeploy when

                        New image is available:
                        {{deploymentConfig.deployOnNewImage | yesNo}}

                        Deployment configuration changes:
                        {{deploymentConfig.deployOnConfigChange | yesNo}}

Environment Variables

                      <osc-key-values
                        entries="deploymentConfig.envVars"
                        delimiter="="
                        key-validator="env"
                        delete-policy="added"
                        editable="true"
                       />

Autodeploy when

                          <input type="checkbox" ng-model="deploymentConfig.deployOnNewImage">
                          New image is available

                        <input type="checkbox" ng-model="deploymentConfig.deployOnConfigChange">
                        Deployment configuration changes

Environment Variables

                        <osc-key-values
                          entries="deploymentConfig.envVars"
                          delimiter="="
                          key-validator="env"
                          delete-policy="added"
                          key-validation-tooltip="A valid environment variable name is an alphanumeric (a-z and 0-9) string beginning with a letter that may contain underscores."
                        />

                  </osc-form-section>

                  <osc-form-section
                    header="Build Configuration"
                    about-title="Build Configuration"
                    about="A build configuration describes how to build your deployable image.  This includes
                      your source, the base builder image, and when to launch new builds."
                    expand="true"
                    can-toggle="false"
                    >

                        <input type="checkbox" ng-model="buildConfig.buildOnSourceChange"/>
                        Configure a webhook build trigger

                        <input type="checkbox" ng-model="buildConfig.buildOnImageChange"/>
                        Automatically build a new image when the builder image changes

                        <input type="checkbox" ng-model="buildConfig.buildOnConfigChange"/>
                        Automatically build a new image when the build configuration changes

                  </osc-form-section>

                  <osc-form-section
                    header="Scaling"
                    about-title="Scaling"
                    about="Scaling defines the number of running instances of your built image."
                    expand="true"
                    can-toggle="false"
                    >

                        Replicas:
                        {{scaling.replicas}}

                        Replicas:
                        <input type="number" class="input-number" min="0" name="replicas" ng-model="scaling.replicas" required ng-pattern="/^\-?\d+$/">

                        Replicas must be an integer value greater than or equal to 0

                  </osc-form-section>

                  <labels labels="labels" expand="true" can-toggle="false"></labels>

                  <button class="btn btn-primary btn-lg"
                      ng-click="createApp()"
                      ng-disabled="form.$invalid || nameTaken"
                      >Create</button>
                  Cancel

              </form>

                {{ emptyMessage }}


text:
var assert = require('chai').assert;
var request = require('request');
var app = require('./app');

var server;

describe('engine (handlebars)', function() {

  before(function(done) {
    server = app.listen(3000, function() {
      done();
    });
  });

  it('can use a new instance of the view engine with custom handlebars', function(done) {
    request('http://localhost:3000/', function(err, res, body) {
      assert.include(body, 'Home');
      done();
    });
  });

  after(function(done) {
    server.close(function() {
      done();
    });
  });

});

redpajama_set_name: RedPajamaGithub


text:
kabam-plugin-menu
=================

Menu generator from menu.json for basic html or spa frontends
This is a POC plugin, it is under development

Maintainer - [Ostroumov Anatolij](https://github.org/vodolaz095)


text:
var pets = [
	{
		"name": "Dozer",
		"height": "1'3\"",
		"liteInfo": "Dozer is an adorable little fluffball!",
		"info": "Dozer likes to do cat things like play with cat toys and eat cat food. His hobbies include purring, laying near the window, and knocking things off the table.",
		"pictures": [
			{
				"file": "assets/kitten1.jpg",
				"info": "So round, so fluffy!"
			},
			{
				"file": "assets/kitten2.jpg",
				"info": "What a thoughtful little kitty."
			},
			{
				"file": "assets/kitten3.jpg",
				"info": "Don't worry, Dozer. It's only a mild existential crisis."
			}
		]
	},
	{
		"name": "Fluffy",
		"height": "1'1\"",
		"liteInfo": "Fluffy is short!",
		"info": "Fluffy is your best friend! He likes to play and chew on toys. He also likes to play tug-of-war with bits of rope and socks. Did I mention he's fluffy?",
		"pictures": [
			{
				"file": "assets/puppy2.jpg",
				"info": "What a cute pup!"
			},
			{
				"file": "assets/puppy1.jpg",
				"info": "He was even cuter when he was little!"
			},
			{
				"file": "assets/puppy3.jpg",
				"info": "This was taken right after his first bath. So cute!"
			}
		]
	},
	{
		"name": "Otto",
		"height": "0'8\"",
		"liteInfo": "Wh'otter you waiting for?",
		"info": "Otto loves the water. He also loves smiling, eating snacks, and holding hands. Catch him if you can!",
		"pictures": [
			{
				"file": "assets/otter1.jpg",
				"info": "Isn't he cute??"
			},
			{
				"file": "assets/otter2.jpg",
				"info": "Snack time!"
			},
			{
				"file": "assets/otter3.jpg",
				"info": "Look at those mischievous little hands!"
			}
		]
	}
];

function clone(obj) {
	return JSON.parse(JSON.stringify(obj));
}

function getPets() {
	return clone(pets);
}

function getPet(name) {
	var ret = pets.find(function(pet) {
		return pet.name == name;
	});
	return ret ? clone(ret) : null;
}

module.exports = {
	getPets: getPets,
	getPet: getPet
};


text:
#include "DayStrategy.h"

DayStrategy::DayStrategy()
{
}

/** Strategy that updates the trigger factor by the number of days */
int DayStrategy::update(Factory* factory, int triggerFactor)
{
    //int days = factory->getDayCount(), newTriggerFactor;

    //newTriggerFactor = triggerFactor+ (days - startDayCount);

    //return newTriggerFactor;
}


text:
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN  *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.PythonTools.Analysis;

namespace Microsoft.PythonTools.Projects {
    /// <summary>
    /// Provides an extension which registers against a given analyzer.
    /// </summary>
    public interface IAnalysisExtension {
        /// <summary>
        /// Called when the extension is registered for an analyzer.
        /// </summary>
        /// <param name="analyzer"></param>
        void Register(PythonAnalyzer analyzer);

        /// <summary>
        /// Handles an extension command.  The extension receives the command body and
        /// returns a response.
        /// </summary>
        string HandleCommand(string commandId, string body);
    }
}


text:
namespace blacklist {

OptOutBlacklistItem::OptOutRecord::OptOutRecord(base::Time entry_time,
                                                bool opt_out)
    : entry_time_(entry_time), opt_out_(opt_out) {}

OptOutBlacklistItem::OptOutRecord::~OptOutRecord() {}

OptOutBlacklistItem::OptOutRecord::OptOutRecord(OptOutRecord&&) noexcept =
    default;
OptOutBlacklistItem::OptOutRecord& OptOutBlacklistItem::OptOutRecord::operator=(
    OptOutRecord&&) noexcept = default;

bool OptOutBlacklistItem::OptOutRecord::operator<(
    const OptOutRecord& other) const {
  // Fresher entries are lower priority to evict, as are non-opt-outs.
  return std::tie(entry_time_, opt_out_) >
         std::tie(other.entry_time_, other.opt_out_);
}

OptOutBlacklistItem::OptOutBlacklistItem(size_t stored_history_length,
                                         int opt_out_black_list_threshold,
                                         base::TimeDelta black_list_duration)
    : max_stored_history_length_(stored_history_length),
      opt_out_black_list_threshold_(opt_out_black_list_threshold),
      max_black_list_duration_(black_list_duration),
      total_opt_out_(0) {}

OptOutBlacklistItem::~OptOutBlacklistItem() {}

void OptOutBlacklistItem::AddEntry(bool opt_out, base::Time entry_time) {
  DCHECK_LE(opt_out_records_.size(), max_stored_history_length_);

  opt_out_records_.emplace(entry_time, opt_out);

  if (opt_out && (!most_recent_opt_out_time_ ||
                  entry_time > most_recent_opt_out_time_.value())) {
    most_recent_opt_out_time_ = entry_time;
  }
  total_opt_out_ += opt_out ? 1 : 0;

  // Remove the oldest entry if the size exceeds the max history size.
  if (opt_out_records_.size() > max_stored_history_length_) {
    DCHECK_EQ(opt_out_records_.size(), max_stored_history_length_ + 1);
    DCHECK_LE(opt_out_records_.top().entry_time(), entry_time);
    total_opt_out_ -= opt_out_records_.top().opt_out() ? 1 : 0;
    opt_out_records_.pop();
  }
  DCHECK_LE(opt_out_records_.size(), max_stored_history_length_);
}

bool OptOutBlacklistItem::IsBlackListed(base::Time now) const {
  DCHECK_LE(opt_out_records_.size(), max_stored_history_length_);
  return most_recent_opt_out_time_ &&
         now - most_recent_opt_out_time_.value() < max_black_list_duration_ &&
         total_opt_out_ >= opt_out_black_list_threshold_;
}

size_t OptOutBlacklistItem::OptOutRecordsSizeForTesting() const {
  return opt_out_records_.size();
}

}  // namespace blacklist


text:
ACREHOME=.
mysql -usalsa -psalsa salsa < $ACREHOME/src/main/AcreRepository/Global/FactModelRepository/ACRE_SCHEMA.SQL
mysql -usalsa -psalsa salsa < $ACREHOME/src/main/AcreRepository/Global/FactModelRepository/ACRE_JAVA_SCHEMA_MYSQL.SQL


text:
using testing::Mock;
using testing::Invoke;
using testing::_;

namespace content {

static const std::string kStubDeviceId = "StubDevice";
static const media::VideoCaptureParams kArbitraryParams;
static const base::WeakPtr<media::VideoFrameReceiver> kNullReceiver;
static const auto kIgnoreLogMessageCB =
    base::BindRepeating([](const std::string&) {});

class MockVideoCaptureDeviceLauncherCallbacks
    : public VideoCaptureDeviceLauncher::Callbacks {
 public:
  void OnDeviceLaunched(
      std::unique_ptr<LaunchedVideoCaptureDevice> device) override {
    DoOnDeviceLaunched(&device);
  }

  MOCK_METHOD1(DoOnDeviceLaunched,
               void(std::unique_ptr<LaunchedVideoCaptureDevice>* device));
  MOCK_METHOD1(OnDeviceLaunchFailed, void(media::VideoCaptureError error));
  MOCK_METHOD0(OnDeviceLaunchAborted, void());
};

class ServiceVideoCaptureProviderTest : public testing::Test {
 public:
  ServiceVideoCaptureProviderTest()
      : source_provider_receiver_(&mock_source_provider_) {
    OverrideVideoCaptureServiceForTesting(&mock_video_capture_service_);
  }

  ~ServiceVideoCaptureProviderTest() override {
    OverrideVideoCaptureServiceForTesting(nullptr);
  }

 protected:
  void SetUp() override {
#if defined(OS_CHROMEOS)
    provider_ = std::make_unique<ServiceVideoCaptureProvider>(
        base::BindRepeating([]() {
          return std::unique_ptr<video_capture::mojom::AcceleratorFactory>();
        }),
        kIgnoreLogMessageCB);
#else
    provider_ =
        std::make_unique<ServiceVideoCaptureProvider>(kIgnoreLogMessageCB);
#endif  // defined(OS_CHROMEOS)

    ON_CALL(mock_video_capture_service_, DoConnectToVideoSourceProvider(_))
        .WillByDefault(Invoke(
            [this](
                mojo::PendingReceiver<video_capture::mojom::VideoSourceProvider>
                    receiver) {
              if (source_provider_receiver_.is_bound())
                source_provider_receiver_.reset();
              source_provider_receiver_.Bind(std::move(receiver));
              wait_for_connection_to_service_.Quit();
            }));

    ON_CALL(mock_source_provider_, DoGetSourceInfos(_))
        .WillByDefault(Invoke([](video_capture::mojom::VideoSourceProvider::
                                     GetSourceInfosCallback& callback) {
          std::vector<media::VideoCaptureDeviceInfo> arbitrarily_empty_results;
          std::move(callback).Run(arbitrarily_empty_results);
        }));

    ON_CALL(mock_source_provider_, DoGetVideoSource(_, _))
        .WillByDefault(Invoke(
            [this](const std::string& device_id,
                   mojo::PendingReceiver<video_capture::mojom::VideoSource>*
                       receiver) {
              source_receivers_.Add(&mock_source_, std::move(*receiver));
            }));

    ON_CALL(mock_source_, DoCreatePushSubscription(_, _, _, _, _))
        .WillByDefault(Invoke(
            [this](mojo::PendingRemote<video_capture::mojom::VideoFrameHandler>
                       subscriber,
                   const media::VideoCaptureParams& requested_settings,
                   bool force_reopen_with_new_settings,
                   mojo::PendingReceiver<
                       video_capture::mojom::PushVideoStreamSubscription>
                       subscription,
                   video_capture::mojom::VideoSource::
                       CreatePushSubscriptionCallback& callback) {
              subscription_receivers_.Add(&mock_subscription_,
                                          std::move(subscription));
              std::move(callback).Run(
                  video_capture::mojom::CreatePushSubscriptionResultCode::
                      kCreatedWithRequestedSettings,
                  requested_settings);
            }));
  }

  void TearDown() override {}

  content::BrowserTaskEnvironment task_environment_;
  video_capture::MockVideoCaptureService mock_video_capture_service_;
  video_capture::MockVideoSourceProvider mock_source_provider_;
  mojo::Receiver<video_capture::mojom::VideoSourceProvider>
      source_provider_receiver_;
  video_capture::MockVideoSource mock_source_;
  mojo::ReceiverSet<video_capture::mojom::VideoSource> source_receivers_;
  video_capture::MockPushSubcription mock_subscription_;
  mojo::ReceiverSet<video_capture::mojom::PushVideoStreamSubscription>
      subscription_receivers_;
  std::unique_ptr<ServiceVideoCaptureProvider> provider_;
  base::MockCallback<VideoCaptureProvider::GetDeviceInfosCallback> results_cb_;
  base::MockCallback<
      video_capture::mojom::VideoSourceProvider::GetSourceInfosCallback>
      service_cb_;
  base::RunLoop wait_for_connection_to_service_;

 private:
  DISALLOW_COPY_AND_ASSIGN(ServiceVideoCaptureProviderTest);
};

// Tests that if connection to the service is lost during an outstanding call
// to GetDeviceInfos(), the callback passed into GetDeviceInfos() still gets
// invoked.
TEST_F(ServiceVideoCaptureProviderTest,
       GetDeviceInfosAsyncInvokesCallbackWhenLosingConnection) {
  base::RunLoop run_loop;

  video_capture::mojom::VideoSourceProvider::GetSourceInfosCallback
      callback_to_be_called_by_service;
  base::RunLoop wait_for_call_to_arrive_at_service;
  EXPECT_CALL(mock_source_provider_, DoGetSourceInfos(_))
      .WillOnce(Invoke(
          [&callback_to_be_called_by_service,
           &wait_for_call_to_arrive_at_service](
              video_capture::mojom::VideoSourceProvider::GetSourceInfosCallback&
                  callback) {
            // Hold on to the callback so we can drop it later.
            callback_to_be_called_by_service = std::move(callback);
            wait_for_call_to_arrive_at_service.Quit();
          }));
  base::RunLoop wait_for_callback_from_service;
  EXPECT_CALL(results_cb_, Run(_))
      .WillOnce(Invoke(
          [&wait_for_callback_from_service](
              const std::vector<media::VideoCaptureDeviceInfo>& results) {
            EXPECT_EQ(0u, results.size());
            wait_for_callback_from_service.Quit();
          }));

  // Exercise
  provider_->GetDeviceInfosAsync(results_cb_.Get());
  wait_for_call_to_arrive_at_service.Run();

  // Simulate that the service goes down by cutting the connections.
  source_provider_receiver_.reset();
  wait_for_callback_from_service.Run();
}

// Tests that |ServiceVideoCaptureProvider| closes the connection to the service
// after successfully processing a single request to GetDeviceInfos().
TEST_F(ServiceVideoCaptureProviderTest,
       ClosesServiceConnectionAfterGetDeviceInfos) {
  // Setup part 1
  video_capture::mojom::VideoSourceProvider::GetSourceInfosCallback
      callback_to_be_called_by_service;
  base::RunLoop wait_for_call_to_arrive_at_service;
  EXPECT_CALL(mock_source_provider_, DoGetSourceInfos(_))
      .WillOnce(Invoke(
          [&callback_to_be_called_by_service,
           &wait_for_call_to_arrive_at_service](
              video_capture::mojom::VideoSourceProvider::GetSourceInfosCallback&
                  callback) {
            // Hold on to the callback so we can drop it later.
            callback_to_be_called_by_service = std::move(callback);
            wait_for_call_to_arrive_at_service.Quit();
          }));

  // Exercise part 1: Make request to the service
  provider_->GetDeviceInfosAsync(results_cb_.Get());
  wait_for_call_to_arrive_at_service.Run();

  // Setup part 2: Now that the connection to the service is established, we can
  // listen for disconnects.
  base::RunLoop wait_for_connection_to_source_provider_to_close;
  source_provider_receiver_.set_disconnect_handler(
      base::BindOnce([](base::RunLoop* run_loop) { run_loop->Quit(); },
                     &wait_for_connection_to_source_provider_to_close));

  // Exercise part 2: The service responds
  std::vector<media::VideoCaptureDeviceInfo> arbitrarily_empty_results;
  std::move(callback_to_be_called_by_service).Run(arbitrarily_empty_results);

  // Verification: Expect |provider_| to close the connection to the service.
  wait_for_connection_to_source_provider_to_close.Run();
}

// Tests that |ServiceVideoCaptureProvider| does not close the connection to the
// service while at least one previously handed out VideoCaptureDeviceLauncher
// instance is still using it. Then confirms that it closes the connection as
// soon as the last VideoCaptureDeviceLauncher instance is released.
TEST_F(ServiceVideoCaptureProviderTest,
       KeepsServiceConnectionWhileDeviceLauncherAlive) {
  MockVideoCaptureDeviceLauncherCallbacks mock_callbacks;

  // Exercise part 1: Create a device launcher and hold on to it.
  auto device_launcher_1 = provider_->CreateDeviceLauncher();
  base::RunLoop wait_for_launch_1;
  device_launcher_1->LaunchDeviceAsync(
      kStubDeviceId, blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE,
      kArbitraryParams, kNullReceiver, base::DoNothing(), &mock_callbacks,
      wait_for_launch_1.QuitClosure());
  wait_for_connection_to_service_.Run();
  wait_for_launch_1.Run();

  // Monitor if connection gets closed
  bool connection_has_been_closed = false;
  source_provider_receiver_.set_disconnect_handler(base::BindOnce(
      [](bool* connection_has_been_closed) {
        *connection_has_been_closed = true;
      },
      &connection_has_been_closed));

  // Exercise part 2: Make a few GetDeviceInfosAsync requests
  base::RunLoop wait_for_get_device_infos_response_1;
  base::RunLoop wait_for_get_device_infos_response_2;
  provider_->GetDeviceInfosAsync(base::BindRepeating(
      [](base::RunLoop* run_loop,
         const std::vector<media::VideoCaptureDeviceInfo>&) {
        run_loop->Quit();
      },
      &wait_for_get_device_infos_response_1));
  provider_->GetDeviceInfosAsync(base::BindRepeating(
      [](base::RunLoop* run_loop,
         const std::vector<media::VideoCaptureDeviceInfo>&) {
        run_loop->Quit();
      },
      &wait_for_get_device_infos_response_2));
  wait_for_get_device_infos_response_1.Run();
  {
    base::RunLoop give_provider_chance_to_disconnect;
    give_provider_chance_to_disconnect.RunUntilIdle();
  }
  ASSERT_FALSE(connection_has_been_closed);
  wait_for_get_device_infos_response_2.Run();
  {
    base::RunLoop give_provider_chance_to_disconnect;
    give_provider_chance_to_disconnect.RunUntilIdle();
  }
  ASSERT_FALSE(connection_has_been_closed);

  // Exercise part 3: Create and release another device launcher
  auto device_launcher_2 = provider_->CreateDeviceLauncher();
  base::RunLoop wait_for_launch_2;
  device_launcher_2->LaunchDeviceAsync(
      kStubDeviceId, blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE,
      kArbitraryParams, kNullReceiver, base::DoNothing(), &mock_callbacks,
      wait_for_launch_2.QuitClosure());
  wait_for_launch_2.Run();
  device_launcher_2.reset();
  {
    base::RunLoop give_provider_chance_to_disconnect;
    give_provider_chance_to_disconnect.RunUntilIdle();
  }
  ASSERT_FALSE(connection_has_been_closed);

  // Exercise part 4: Release the initial device launcher.
  device_launcher_1.reset();
  {
    base::RunLoop give_provider_chance_to_disconnect;
    give_provider_chance_to_disconnect.RunUntilIdle();
  }
  ASSERT_TRUE(connection_has_been_closed);
}

// Tests that |ServiceVideoCaptureProvider| does not close the connection to the
// service while at least one answer to a GetDeviceInfos() request is still
// pending. Confirms that it closes the connection as soon as the last pending
// request is answered.
TEST_F(ServiceVideoCaptureProviderTest,
       DoesNotCloseServiceConnectionWhileGetDeviceInfoResponsePending) {
  // When GetDeviceInfos gets called, hold on to the callbacks, but do not
  // yet invoke them.
  std::vector<video_capture::mojom::VideoSourceProvider::GetSourceInfosCallback>
      callbacks_to_be_called_by_service;
  ON_CALL(mock_source_provider_, DoGetSourceInfos(_))
      .WillByDefault(Invoke(
          [&callbacks_to_be_called_by_service](
              video_capture::mojom::VideoSourceProvider::GetSourceInfosCallback&
                  callback) {
            callbacks_to_be_called_by_service.push_back(std::move(callback));
          }));

  // Make initial call to GetDeviceInfosAsync(). The service does not yet
  // respond.
  provider_->GetDeviceInfosAsync(base::BindRepeating(
      [](const std::vector<media::VideoCaptureDeviceInfo>&) {}));
  // Make an additional call to GetDeviceInfosAsync().
  provider_->GetDeviceInfosAsync(base::BindRepeating(
      [](const std::vector<media::VideoCaptureDeviceInfo>&) {}));
  {
    base::RunLoop give_mojo_chance_to_process;
    give_mojo_chance_to_process.RunUntilIdle();
  }
  ASSERT_EQ(2u, callbacks_to_be_called_by_service.size());

  // Monitor if connection gets closed
  bool connection_has_been_closed = false;
  source_provider_receiver_.set_disconnect_handler(base::BindOnce(
      [](bool* connection_has_been_closed) {
        *connection_has_been_closed = true;
      },
      &connection_has_been_closed));

  // The service now responds to the first request.
  std::vector<media::VideoCaptureDeviceInfo> arbitrarily_empty_results;
  std::move(callbacks_to_be_called_by_service[0])
      .Run(arbitrarily_empty_results);
  {
    base::RunLoop give_provider_chance_to_disconnect;
    give_provider_chance_to_disconnect.RunUntilIdle();
  }
  ASSERT_FALSE(connection_has_been_closed);

  // Create and release a device launcher
  auto device_launcher = provider_->CreateDeviceLauncher();
  device_launcher.reset();
  {
    base::RunLoop give_provider_chance_to_disconnect;
    give_provider_chance_to_disconnect.RunUntilIdle();
  }
  ASSERT_FALSE(connection_has_been_closed);

  // The service now responds to the second request.
  std::move(callbacks_to_be_called_by_service[1])
      .Run(arbitrarily_empty_results);
  {
    base::RunLoop give_provider_chance_to_disconnect;
    give_provider_chance_to_disconnect.RunUntilIdle();
  }
  ASSERT_TRUE(connection_has_been_closed);
}

}  // namespace content


text:
namespace Microsoft.Web.Mvc {
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    using System.Web.Mvc;
    using Microsoft.Web.Resources;

    internal sealed class AsyncActionMethodSelector {

        public AsyncActionMethodSelector(Type controllerType) {
            ControllerType = controllerType;
            PopulateLookupTables();
        }

        public Type ControllerType {
            get;
            private set;
        }

        public MethodInfo[] AliasedMethods {
            get;
            private set;
        }

        public ILookup<string, MethodInfo> NonAliasedMethods {
            get;
            private set;
        }

        private AmbiguousMatchException CreateAmbiguousActionMatchException(IEnumerable<MethodInfo> ambiguousMethods, string actionName) {
            string ambiguityList = CreateAmbiguousMatchList(ambiguousMethods);
            string message = String.Format(CultureInfo.CurrentUICulture, MvcResources.ActionMethodSelector_AmbiguousActionMatch,
                actionName, ControllerType.Name, ambiguityList);
            return new AmbiguousMatchException(message);
        }

        private AmbiguousMatchException CreateAmbiguousMethodMatchException(IEnumerable<MethodInfo> ambiguousMethods, string methodName) {
            string ambiguityList = CreateAmbiguousMatchList(ambiguousMethods);
            string message = String.Format(CultureInfo.CurrentUICulture, MvcResources.ActionMethodSelector_AmbiguousMethodMatch,
                methodName, ControllerType.Name, ambiguityList);
            return new AmbiguousMatchException(message);
        }

        private static string CreateAmbiguousMatchList(IEnumerable<MethodInfo> ambiguousMethods) {
            StringBuilder exceptionMessageBuilder = new StringBuilder();
            foreach (MethodInfo methodInfo in ambiguousMethods) {
                exceptionMessageBuilder.AppendLine();
                exceptionMessageBuilder.AppendFormat(CultureInfo.CurrentUICulture, MvcResources.ActionMethodSelector_AmbiguousMatchType, methodInfo, methodInfo.DeclaringType.FullName);
            }

            return exceptionMessageBuilder.ToString();
        }

        public ActionDescriptorCreator FindActionMethod(ControllerContext controllerContext, string actionName) {
            List<MethodInfo> methodsMatchingName = GetMatchingAliasedMethods(controllerContext, actionName);
            methodsMatchingName.AddRange(NonAliasedMethods[actionName]);
            List<MethodInfo> finalMethods = RunSelectionFilters(controllerContext, methodsMatchingName);

            switch (finalMethods.Count) {
                case 0:
                    return null;

                case 1:
                    MethodInfo entryMethod = finalMethods[0];
                    return GetActionDescriptorDelegate(entryMethod);

                default:
                    throw CreateAmbiguousActionMatchException(finalMethods, actionName);
            }
        }

        private ActionDescriptorCreator GetActionDescriptorDelegate(MethodInfo entryMethod) {
            // Is this the BeginFoo() / EndFoo() pattern?
            if (entryMethod.Name.StartsWith("Begin", StringComparison.OrdinalIgnoreCase)) {
                string endMethodName = "End" + entryMethod.Name.Substring("Begin".Length);
                MethodInfo endMethod = GetMethodByName(endMethodName);
                if (endMethod == null) {
                    string errorMessage = String.Format(CultureInfo.CurrentUICulture, MvcResources.ActionMethodSelector_CouldNotFindMethod, endMethodName, ControllerType.FullName);
                    throw new InvalidOperationException(errorMessage);
                }
                return (actionName, controllerDescriptor) => new ReflectedAsyncPatternActionDescriptor(entryMethod, endMethod, actionName, controllerDescriptor);
            }

            // Is this the Foo() / FooCompleted() pattern?
            {
                string completionMethodName = entryMethod.Name + "Completed";
                MethodInfo completionMethod = GetMethodByName(completionMethodName);
                if (completionMethod != null) {
                    return (actionName, controllerDescriptor) => new ReflectedEventPatternActionDescriptor(entryMethod, completionMethod, actionName, controllerDescriptor);
                }
            }

            // Does Foo() return a delegate that represents the continuation?
            if (TypeHelpers.TypeIsParameterlessDelegate(entryMethod.ReturnType)) {
                return (actionName, controllerDescriptor) => new ReflectedDelegatePatternActionDescriptor(entryMethod, actionName, controllerDescriptor);
            }

            // Fallback to synchronous method
            return (actionName, controllerDescriptor) => new ReflectedActionDescriptor(entryMethod, actionName, controllerDescriptor);
        }

        private static string GetCanonicalMethodName(MethodInfo methodInfo) {
            string methodName = methodInfo.Name;
            return (methodName.StartsWith("Begin", StringComparison.OrdinalIgnoreCase))
                ? methodName.Substring("Begin".Length)
                : methodName;
        }

        internal List<MethodInfo> GetMatchingAliasedMethods(ControllerContext controllerContext, string actionName) {
            // find all aliased methods which are opting in to this request
            // to opt in, all attributes defined on the method must return true

            var methods = from methodInfo in AliasedMethods
                          let attrs = (ActionNameSelectorAttribute[])methodInfo.GetCustomAttributes(typeof(ActionNameSelectorAttribute), true /* inherit */)
                          where attrs.All(attr => attr.IsValidName(controllerContext, actionName, methodInfo))
                          select methodInfo;
            return methods.ToList();
        }

        private static bool IsMethodDecoratedWithAliasingAttribute(MethodInfo methodInfo) {
            return methodInfo.IsDefined(typeof(ActionNameSelectorAttribute), true /* inherit */);
        }

        private MethodInfo GetMethodByName(string methodName) {
            List<MethodInfo> methods = (from MethodInfo methodInfo in ControllerType.GetMember(methodName, MemberTypes.Method, BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.IgnoreCase)
                                        where IsValidActionMethod(methodInfo, false /* stripInfrastructureMethods */)
                                        select methodInfo).ToList();

            switch (methods.Count) {
                case 0:
                    return null;

                case 1:
                    return methods[0];

                default:
                    throw CreateAmbiguousMethodMatchException(methods, methodName);
            }
        }

        private static bool IsValidActionMethod(MethodInfo methodInfo) {
            return IsValidActionMethod(methodInfo, true /* stripInfrastructureMethods */);
        }

        private static bool IsValidActionMethod(MethodInfo methodInfo, bool stripInfrastructureMethods) {
            if (methodInfo.IsSpecialName) {
                // not a normal method, e.g. a constructor or an event
                return false;
            }

            if (methodInfo.GetBaseDefinition().DeclaringType.IsAssignableFrom(typeof(AsyncController))) {
                // is a method on Object, ControllerBase, Controller, or AsyncController
                return false;
            };

            if (stripInfrastructureMethods) {
                string methodName = methodInfo.Name;
                if (methodName.StartsWith("End", StringComparison.OrdinalIgnoreCase) || methodName.EndsWith("Completed", StringComparison.OrdinalIgnoreCase)) {
                    // do not match EndFoo() or FooCompleted() methods, as these are infrastructure methods
                    return false;
                }
            }

            return true;
        }

        private void PopulateLookupTables() {
            MethodInfo[] allMethods = ControllerType.GetMethods(BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public);
            MethodInfo[] actionMethods = Array.FindAll(allMethods, IsValidActionMethod);

            AliasedMethods = Array.FindAll(actionMethods, IsMethodDecoratedWithAliasingAttribute);
            NonAliasedMethods = actionMethods.Except(AliasedMethods).ToLookup(GetCanonicalMethodName, StringComparer.OrdinalIgnoreCase);
        }

        private static List<MethodInfo> RunSelectionFilters(ControllerContext controllerContext, List<MethodInfo> methodInfos) {
            // remove all methods which are opting out of this request
            // to opt out, at least one attribute defined on the method must return false

            List<MethodInfo> matchesWithSelectionAttributes = new List<MethodInfo>();
            List<MethodInfo> matchesWithoutSelectionAttributes = new List<MethodInfo>();

            foreach (MethodInfo methodInfo in methodInfos) {
                ActionMethodSelectorAttribute[] attrs = (ActionMethodSelectorAttribute[])methodInfo.GetCustomAttributes(typeof(ActionMethodSelectorAttribute), true /* inherit */);
                if (attrs.Length == 0) {
                    matchesWithoutSelectionAttributes.Add(methodInfo);
                }
                else if (attrs.All(attr => attr.IsValidForRequest(controllerContext, methodInfo))) {
                    matchesWithSelectionAttributes.Add(methodInfo);
                }
            }

            // if a matching action method had a selection attribute, consider it more specific than a matching action method
            // without a selection attribute
            return (matchesWithSelectionAttributes.Count > 0) ? matchesWithSelectionAttributes : matchesWithoutSelectionAttributes;
        }

    }
}


text:
// coding: utf-8
// ----------------------------------------------------------------------------

// ----------------------------------------------------------------------------

#ifndef XPCC__NOKIA6610_HPP
#define XPCC__NOKIA6610_HPP

#include <xpcc/architecture/driver/delay.hpp>

#include <xpcc/ui/display/buffered_graphic_display.hpp>

namespace xpcc
{
	/**
	 * \brief	Driver for Nokia6610 displays
	 *
	 * Adapted from www.olimex.com
	 *
	 * bool GE12 = true generates driver for GE12 Philips PCF8833 132 x 132 x 3 driver
	 * bool GE12 = false generates driver for GE8 Epson S1D15G10
	 *
	 * GE12 not implemented yet
	 *
	 * \ingroup	driver_display
	 */
	template <typename SPI, typename CS, typename Reset, bool GE12>
	class Nokia6610 : public BufferedGraphicDisplay<130, 128>
	{
	public:
		void
		initialize();

		/**
		 * \brief	Update the display with the content of the RAM buffer
		 */
		virtual void
		update();

		/**
		 * \brief	Change display contrast 0..127
		 */
		void
		setContrast(uint8_t contrast);

	private:
		ALWAYS_INLINE void
		lcdSettings(void);

		ALWAYS_INLINE void
		writeSpiCommand(uint16_t data);

		ALWAYS_INLINE void
		writeSpiData(uint16_t data);

		ALWAYS_INLINE void
		writeSpi9Bit(uint16_t data);

		ALWAYS_INLINE void
		writeSpi9BitFlush();

		void
		lcdWrite130x130bmp(void);

		// 9bit spi managing
		uint16_t temp;				//
		uint8_t countValidBits;		// always < 8
	};
}

#include "nokia6610_impl.hpp"

#endif // XPCC__NOKIA6610_HPP


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

goog.provide('webdriver.logging');

/**
 * Logging levels.
 * @enum {{value: number, name: string}}
 */
webdriver.logging.Level = {
  ALL: {value: Number.MIN_VALUE, name: 'ALL'},
  DEBUG: {value: 500, name: 'DEBUG'},
  INFO: {value: 800, name: 'INFO'},
  WARNING: {value: 900, name: 'WARNING'},
  SEVERE: {value: 1000, name: 'SEVERE'},
  OFF: {value: Number.MAX_VALUE, name: 'OFF'}
};

/**
 * Common log types.
 * @enum {string}
 */
webdriver.logging.Type = {
  BROWSER: 'browser',
  CLIENT: 'client',
  DRIVER: 'driver',
  PROFILER: 'profiler',
  SERVER: 'server'
};

/**
 * A single log entry.
 * @param {(!webdriver.logging.Level|string)} level The entry level.
 * @param {string} message The log message.
 * @param {number=} opt_timestamp The time this entry was generated, in
 *     milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the
 *     current time will be used.
 * @constructor
 */
webdriver.logging.Entry = function(level, message, opt_timestamp) {

  /** @type {string} */
  this.level = goog.isString(level) ? level : level.name;

  /** @type {string} */
  this.message = message;

  /** @type {number} */
  this.timestamp = goog.isNumber(opt_timestamp) ? opt_timestamp : goog.now();
};

/**
 * @return {{level: string, message: string, timestamp: number}} The JSON
 *     representation of this entry.
 */
webdriver.logging.Entry.prototype.toJSON = function() {
  return {
    'level': this.level,
    'message': this.message,
    'timestamp': this.timestamp
  };
};

/**
 * Converts a {@link goog.debug.LogRecord} into a
 * {@link webdriver.logging.Entry}.
 * @param {!goog.debug.LogRecord} logRecord The record to convert.
 * @return {!webdriver.logging.Entry} The converted entry.
 */
webdriver.logging.Entry.fromClosureLogRecord = function(logRecord) {
  var level = logRecord.getLevel();
  if (level.value <= webdriver.logging.Level.DEBUG.value) {
    level = webdriver.logging.Level.DEBUG;
  } else if (level.value <= webdriver.logging.Level.INFO.value) {
    level = webdriver.logging.Level.INFO;
  } else if (level.value <= webdriver.logging.Level.WARNING.value) {
    level = webdriver.logging.Level.WARNING;
  } else {
    level = webdriver.logging.Level.SEVERE;
  }
  return new webdriver.logging.Entry(
      /** @type {!webdriver.logging.Level} */ (level),
      '[' + logRecord.getLoggerName() + '] ' + logRecord.getMessage(),
      logRecord.getMillis());
};


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import imagesLoaded from 'imagesloaded';
import omit from 'lodash.omit';

export default class ImagesLoaded extends Component {
  componentDidMount() {
    const { onAlways, done, onFail, onProgress, background } = this.props;
    const { elemContainer } = this.refs;

    /* Initializing imagesLoaded */
    this.imagesLoaded = imagesLoaded(elemContainer, { background });

    // add events
    this.imagesLoaded.on('always', onAlways);
    this.imagesLoaded.on('done', done);
    this.imagesLoaded.on('fail', onFail);
    this.imagesLoaded.on('progress', onProgress);
  }

  componentWillUnmount() {
    const { onAlways, done, onFail, onProgress } = this.props;

    // unbinding the events
    this.imagesLoaded.off('always', onAlways);
    this.imagesLoaded.off('done', done);
    this.imagesLoaded.off('fail', onFail);
    this.imagesLoaded.off('progress', onProgress);
  }

  render() {
    const { children } = this.props;
    const props = omit(this.props, Object.keys(propTypes));

    return (
      <this.props.elementType ref={'elemContainer'} {...props}>
        {children}
      </this.props.elementType>
    );
  }
}

ImagesLoaded.defaultProps = {
  elementType: 'div',
  className: 'images-loaded-container',
  background: false
};

const propTypes = {
  elementType: PropTypes.string,
  onAlways: PropTypes.func,
  done: PropTypes.func,
  onFail: PropTypes.func,
  onProgress: PropTypes.func,
  background: PropTypes.oneOfType([PropTypes.string, PropTypes.bool])
};


text:
<?php

namespace FOS\TwitterBundle\Security\User;

use Symfony\Component\Security\Core\User\UserProviderInterface;

interface UserManagerInterface extends UserProviderInterface
{
    /**
     * Creates a user for the given access token.
     *
     * @param array $token
     * @return UserInterface
     */
    function createUserFromAccessToken(array $token);
}


text:
package org.apache.excalibur.instrument.manager.http.server;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;

import org.apache.excalibur.instrument.CounterInstrument;

/**
 *
 * @author Avalon Development Team
 * @version CVS $Revision: 1.6 $ $Date: 2004/03/10 13:59:34 $
 * @since 4.1
 */
public class HTTPServer
    extends AbstractSocketServer
{
    /** List of registered HTTPURLHandlers. */
    private List m_handlers = new ArrayList();

    /** Optimized array of the handler list that lets us avoid synchronization */
    private HTTPURLHandler[] m_handlerArray;

    /** Access log file name.  Null if not configured. */
    private String m_accessLogFile;

    /** The currently open log file.  May be null. */
    private File m_currentLogFile;

    /** The currently open log PrintWriter. */
    private PrintWriter m_currentLogWriter;

    /** DateFormat used when generating log file names.  Only use when synchronized. */
    private SimpleDateFormat m_dayFormat = new SimpleDateFormat( "yyyy-MM-dd" );

    /** DateFormat used when generating log entries.  Only use when synchronized.
     *   The US Locale is set because other locales do not correctly show the month. */
    private SimpleDateFormat m_logTimeFormat =
        new SimpleDateFormat( "dd/MMM/yyyy:HH:mm:ss Z", Locale.US );

    /** Number of requests. */
    private CounterInstrument m_instrumentRequests;

    /** Number of response bytes sent to the client.  Includes all bytes, not
     *   only the content. */
    private CounterInstrument m_instrumentResponseBytes;

    /** Number of request bytes received from the client. */
    private CounterInstrument m_instrumentRequestBytes;

    /*---------------------------------------------------------------
     * Constructors
     *-------------------------------------------------------------*/
    /**
     * Creates a new HTTPServer.
     *
     * @param port The port on which the server will listen.
     * @param bindAddress The address on which the server will listen for
     *                    connections.
     */
    public HTTPServer( int port, InetAddress bindAddress )
    {
        super( port, bindAddress );

        addInstrument( m_instrumentRequests = new CounterInstrument( "requests" ) );
        addInstrument( m_instrumentResponseBytes = new CounterInstrument( "response-bytes" ) );
        addInstrument( m_instrumentRequestBytes = new CounterInstrument( "request-bytes" ) );
    }

    /*---------------------------------------------------------------
     * AbstractSocketServer Methods
     *-------------------------------------------------------------*/

    /**
     * Stops the server.
     *
     * @throws Exception If there are any problems stopping the component.
     */
    public void stop()
        throws Exception
    {
        super.stop();

        // Close the logger if it is open.
        synchronized( this )
        {
            if ( m_currentLogWriter != null )
            {
                m_currentLogWriter.close();
                m_currentLogWriter = null;
                m_currentLogFile = null;
            }
        }
    }

    /**
     * Handle a newly connected socket.  The implementation need not
     *  worry about closing the socket.
     *
     * @param socket Newly connected Socket to be handled.
     */
    protected void handleSocket( Socket socket )
    {
        if ( getLogger().isDebugEnabled() )
        {
            getLogger().debug( "handleSocket( " + socket + " ) BEGIN : "
                + Thread.currentThread().getName() );
        }

        String ip = socket.getInetAddress().getHostAddress();

        try
        {
            // As long as we have valid requests, keep the connection open.
            while ( handleRequest( socket.getInputStream(), socket.getOutputStream(), ip )
                && !isStopping() )
            {
            }
        }
        catch ( java.io.InterruptedIOException e ) // java.net.SocketTimeoutException not in 1.3
        {
            // The connection simply timed out and closed.
        }
        catch ( java.net.SocketException e )
        {
            // The connection simply timed out and closed.
        }
        catch ( Throwable e )
        {
            getLogger().debug( "Encountered an error processing the request.", e );
        }

        if ( getLogger().isDebugEnabled() )
        {
            getLogger().debug( "handleSocket( " + socket + " ) END : "
                + Thread.currentThread().getName() );
        }
    }

    /*---------------------------------------------------------------
     * Methods
     *-------------------------------------------------------------*/

    /**
     * Access log file name.  Null if not configured.
     *  If the log file name contains the string "yyyy_mm_dd" then that
     *  token will be replaced with the current day and the file will
     *  be rolled each day at midnight.
     *
     * @param accessLogFile Name of the log file or null if disabled.
     */
    public void setAccessLogFile( String accessLogFile )
    {
        m_accessLogFile = accessLogFile;
    }

    /**
     * Registers a new HTTP URL Handler with the server.
     *
     * @param handler The handler to register.
     */
    public void registerHandler( HTTPURLHandler handler )
    {
        synchronized( m_handlers )
        {
            m_handlers.add( handler );
            m_handlerArray = null;
        }
    }

    private void logAccessEvent( String ip,
                                 String method,
                                 String url,
                                 int errorCode,
                                 int contentLength,
                                 String referrer,
                                 String userAgent )
    {
        if ( m_accessLogFile == null )
        {
            return;
        }

        Date now = new Date();

        synchronized( this )
        {
            File file;
            int datePos = m_accessLogFile.indexOf( "yyyy_mm_dd" );
            if ( datePos >= 0 )
            {
                StringBuffer sb = new StringBuffer();
                if ( datePos > 0 )
                {
                    sb.append( m_accessLogFile.substring( 0, datePos ) );
                }
                sb.append( m_dayFormat.format( now ) );
                if ( datePos + 10 < m_accessLogFile.length() )
                {
                    sb.append( m_accessLogFile.substring( datePos + 10 ) );
                }

                file = new File( sb.toString() );
            }
            else
            {
                file = new File( m_accessLogFile );
            }

            if ( ( m_currentLogFile == null ) || ( !m_currentLogFile.equals( file ) ) )
            {
                // Open a new log file.
                if ( m_currentLogWriter != null )
                {
                    m_currentLogWriter.close();
                }
                try
                {
                    m_currentLogWriter = new PrintWriter( new FileWriter( file ) );
                    m_currentLogFile = file;
                }
                catch ( IOException e )
                {
                    getLogger().warn( "Unable to open: " + m_currentLogFile );
                    m_currentLogWriter = null;
                    m_currentLogFile = null;
                    return;
                }
            }

            // Now log the entry.
            StringBuffer sb = new StringBuffer();
            sb.append( ip );
            sb.append( " - - [" );
            sb.append( m_logTimeFormat.format( now ) );
            sb.append( "] \"" );
            sb.append( method );
            sb.append( " " );
            sb.append( url );
            sb.append( "\" " );
            sb.append( errorCode );
            sb.append( " " );
            sb.append( contentLength );
            sb.append( " \"" );
            sb.append( referrer );
            sb.append( "\" \"" );
            sb.append( userAgent );
            sb.append( "\"" );

            m_currentLogWriter.println( sb.toString() );
            m_currentLogWriter.flush();
        }
    }

    private boolean handleRequest( InputStream is, OutputStream os, String ip )
        throws IOException
    {
        // We only support the GET method and know nothing of headers so this is easy.
        //  The first line of the request contains the requested url along with any
        //  and all encoded variables.  All of the following lines until a pair of
        //  Line feeds are headers and can be skipped for now.

        // Read the input header
        BufferedReader r = new BufferedReader( new InputStreamReader( is ) );
        String request = r.readLine();
        if ( request == null )
        {
            // EOF
            return false;
        }

        String referrer = "-";
        String userAgent = "-";
        String host = null;
        int requestBytes = request.getBytes().length + 1;
        try
        {
            // Read any headers until we get a blank line
            String header;
            do
            {
                header = r.readLine();
                getLogger().debug( "Header: " + header );
                if ( header != null )
                {
                    if ( header.startsWith( "User-Agent: " ) )
                    {
                        userAgent = header.substring( 12 );
                    }
                    else if ( header.startsWith( "Referer: " ) )
                    {
                        referrer = header.substring( 9 );
                    }
                    else if ( header.startsWith( "Host: " ) )
                    {
                        host = header.substring( 6 );
                    }

                    requestBytes += header.getBytes().length + 1;
                }
            }
            while ( ( header != null ) && ( header.length() > 0 ) );
        }
        finally
        {
            if ( requestBytes > 0 )
            {
                m_instrumentRequestBytes.increment( requestBytes );
            }
        }

        if ( getLogger().isDebugEnabled() )
        {
            getLogger().debug( "got request: " + request + " : "
                + Thread.currentThread().getName() );
        }

        Throwable error = null;

        // Get the actual output stream so we can write the response.
        ByteArrayOutputStream hbos = new ByteArrayOutputStream();
        PrintWriter out = new PrintWriter( hbos );

        String method = "ERROR";
        String url = "";

        // Parse the header to make sure it is valid.
        StringTokenizer st = new StringTokenizer( request, " " );
        if ( st.countTokens() == 3 )
        {
            method = st.nextToken();
            url = st.nextToken();
            String version = st.nextToken();

            if ( method.equals( "GET" ) && version.startsWith( "HTTP/" ) )
            {
                // Extract the path and parameters from the request.
                String path;
                String query = null;
                int pos = url.indexOf( '?' );
                if ( pos > 0 )
                {
                    path = url.substring( 0, pos );

                    if ( pos < url.length() - 1 )
                    {
                        query = url.substring( pos + 1 );
                    }
                }
                else
                {
                    path = url;
                }

                // We now have the path and the params.
                // Look for an HTTPURLHandler which which maps to the path.  Look in
                //  order until one is found.

                HTTPURLHandler[] handlers = getHandlers();
                for ( int i = 0; i < handlers.length; i++ )
                {
                    HTTPURLHandler handler = handlers[i];

                    //getLogger().debug( "Test: '" + path + "' starts with '" + handler.getPath() + "'" );
                    if ( path.startsWith( handler.getPath() ) )
                    {
                        // We found it.
                        //getLogger().debug( "  => Matched." );

                        // Decode the query string
                        Map params = new HashMap();
                        if ( query != null )
                        {
                            //getLogger().debug( "  Raw Query: " + query );
                            decodeQuery( params, query, handler.getEncoding() );
                        }

                        if ( getLogger().isDebugEnabled() )
                        {
                            getLogger().debug( "Request Path: " + path );
                            getLogger().debug( "  Parameters: " + params.toString() );
                        }

                        m_instrumentRequests.increment();

                        // Create a ByteArrayOutputStream that will be used to get the total number
                        //  bytes that will be written in the response.  This is necessary to set
                        //  the content length in the return headers.
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        boolean ok;
                        // Handle the URL
                        try
                        {
                            handler.handleRequest( path, params, bos );

                            ok = true;
                        }
                        catch ( HTTPRedirect e )
                        {
                            // To avoid breaking some clients (including some versions of Java)
                            //  we need to only send redirects to absolute URLs.  We can only do
                            //  this if the client gave us a Host: header to work with however.
                            String redirectPath = e.getPath();
                            if ( ( host != null ) && ( redirectPath.indexOf( "://" ) < 0 ) )
                            {
                                // No protocol so add it.
                                StringBuffer sb = new StringBuffer();
                                sb.append( "http://" );
                                sb.append( host );
                                if ( redirectPath.startsWith( "." ) )
                                {
                                    // Relative path, so we need to give it a starting point.
                                    int slashPos = path.lastIndexOf( '/' );
                                    String subpath;
                                    if ( slashPos > 0 )
                                    {
                                        subpath = path.substring( 0, slashPos + 1 );
                                    }
                                    else
                                    {
                                        subpath = "/";
                                    }
                                    sb.append( subpath );
                                }
                                else if ( !redirectPath.startsWith( "/" ) )
                                {
                                    sb.append( "/" );
                                }
                                sb.append( redirectPath );

                                redirectPath = sb.toString();
                            }

                            if ( getLogger().isDebugEnabled() )
                            {
                                if ( redirectPath.equals( e.getPath() ) )
                                {
                                    getLogger().debug( "Redirect to: " + redirectPath );
                                }
                                else
                                {
                                    getLogger().debug(
                                        "Redirect to: " + e.getPath() + " -> " + redirectPath );
                                }
                            }

                            byte[] contents = ( "<title>302 Found</title>"
                                + "The document has moved here"
                                + "" ).getBytes( handler.getEncoding() );

                            // Write the response.
                            out.println( "HTTP/1.1 302 Found" ); // MOVED_TEMP
                            out.println( "Date: " + new Date() );
                            out.println( "Server: Avalon Instrument Manager HTTP Connector" );
                            out.println( "Content-Length: " + contents.length );
                            out.println( "Location: " + redirectPath );
                            out.println( "Keep-Alive: timeout=" + ( getSoTimeout() / 1000 ) );
                            out.println( "Connection: Keep-Alive" );
                            out.println( "Content-Type: " + handler.getContentType() );
                            // Make sure that no caching is done by the client
                            out.println( "Pragma: no-cache" );
                            out.println( "Expires: Thu, 01 Jan 1970 00:00:00 GMT" );
                            out.println( "Cache-Control: no-cache" );

                            // Terminate the Headers.
                            out.println( "" );

                            // Write the contents of the headers.
                            out.flush();
                            byte[] responseBytes = hbos.toByteArray();
                            os.write( responseBytes );

                            // Write out the actual data directly to the stream.
                            os.write( contents, 0, contents.length );

                            // Flush the stream and we are done.
                            os.flush();

                            // Record the total number of bytes sent to the client.
                            m_instrumentResponseBytes.increment(
                                responseBytes.length + contents.length );

                            // Log the request.
                            logAccessEvent(
                                ip, method, url, 302, contents.length, referrer, userAgent );

                            // Do not close the output stream as it may be reused.

                            return true;
                        }
                        catch ( Throwable t )
                        {
                            // Error
                            error = t;
                            ok = false;
                        }

                        if ( ok )
                        {
                            byte[] contents = bos.toByteArray();

                            // Write the response.
                            out.println( "HTTP/1.1 200 OK" );
                            out.println( "Date: " + new Date() );
                            out.println( "Server: Avalon Instrument Manager HTTP Connector" );
                            out.println( "Content-Length: " + contents.length );
                            out.println( "Keep-Alive: timeout=" + ( getSoTimeout() / 1000 ) );
                            out.println( "Connection: Keep-Alive" );
                            out.println( "Content-Type: " + handler.getContentType() );
                            // Make sure that no caching is done by the client
                            out.println( "Pragma: no-cache" );
                            out.println( "Expires: Thu, 01 Jan 1970 00:00:00 GMT" );
                            out.println( "Cache-Control: no-cache" );

                            // Terminate the Headers.
                            out.println( "" );

                            // Write the contents of the headers.
                            out.flush();
                            byte[] responseBytes = hbos.toByteArray();
                            os.write( responseBytes );

                            // Write out the actual data directly to the stream.
                            os.write( contents, 0, contents.length );

                            // Flush the stream and we are done.
                            os.flush();

                            // Record the total number of bytes sent to the client.
                            m_instrumentResponseBytes.increment(
                                responseBytes.length + contents.length );

                            // Log the request.
                            logAccessEvent( ip, method, url, 200, contents.length, referrer, userAgent );

                            // Do not close the output stream as it may be reused.

                            return true;
                        }
                        else
                        {
                            // Break out of the for loop.
                            break;
                        }
                    }
                }
            }
        }

        // If we get here then the request failed.  Always return 404 for now.
        // Write the response.
        out.println( "HTTP/1.1 404 Not Found" );
        out.println( "Date: " + new Date() );
        out.println( "Server: Avalon Instrument Manager HTTP Connector" );
        out.println( "Content-Type: text/plain; charset=UTF-8" );
        out.println( "" );
        out.println( "The Requested page does not exist" );
        if ( error !=  null )
        {
            out.println( "---" );
            if ( error instanceof FileNotFoundException )
            {
                out.println( error.getMessage() );
            }
            else
            {
                getLogger().error( "Error servicing request.", error );
                error.printStackTrace( out );
            }
        }

        // Write the contents of the headers.
        out.flush();
        byte[] responseBytes = hbos.toByteArray();
        os.write( responseBytes );
        os.flush();

        // Record the total number of bytes sent to the client.
        m_instrumentResponseBytes.increment( responseBytes.length );

        // Log the request.
        logAccessEvent( ip, method, url, 404, 0, referrer, userAgent );

        return false;
    }

    public void setParameter( Map params, String param, String value )
    {
        Object old = params.get( param );
        if ( old == null )
        {
            params.put( param, value );
        }
        else
        {
            if ( old instanceof String )
            {
                List list = new ArrayList();
                list.add( old );
                list.add( value );
                params.put( param, list );
            }
            else
            {
                List list = (List)old;
                list.add( value );
            }
        }
    }

    private void decodeParameter( Map params, String pair, String encoding )
    {
        int pos = pair.indexOf( '=' );
        if ( pos > 0 )
        {
            try
            {
                // Starting with Java 1.4, encode takes an encoding, but this needs to
                //  work with 1.3.   Use our own version.
                String param = URLCoder.decode( pair.substring( 0, pos ), encoding );

                String value;
                if ( pos < pair.length() - 1 )
                {
                    value = URLCoder.decode( pair.substring( pos + 1 ), encoding );
                }
                else
                {
                    value = "";
                }

                setParameter( params, param, value );
            }
            catch ( UnsupportedEncodingException e )
            {
                throw new IllegalArgumentException( "Unknown encoding: " + e.toString() );
            }
        }
    }

    private void decodeQuery( Map params, String query, String encoding )
    {
        StringTokenizer st = new StringTokenizer( query, "&" );
        while ( st.hasMoreTokens() )
        {
            decodeParameter( params, st.nextToken(), encoding );
        }
    }

    private HTTPURLHandler[] getHandlers()
    {
        HTTPURLHandler[] handlers = m_handlerArray;
        if ( handlers == null )
        {
            synchronized( m_handlers )
            {
                handlers = new HTTPURLHandler[ m_handlers.size() ];
                m_handlers.toArray( handlers );
                m_handlerArray = handlers;
            }
        }

        return handlers;
    }
}


text:
require File.expand_path("../common", __FILE__)

class HTMLEntities::XHTML1Test < Test::Unit::TestCase

  attr_reader :html_entities

  def setup
    @html_entities = HTMLEntities.new('xhtml1')
  end

  def test_should_encode_apos_entity
    assert_equal "'", html_entities.encode("'", :basic)
  end

  def test_should_decode_apos_entity
    assert_equal "é'", html_entities.decode("é'")
  end

  def test_should_not_decode_dotted_entity
    assert_equal "&b.Theta;", html_entities.decode("&b.Theta;")
  end

end


text:
package org.mifos.schedule.internal;

import org.joda.time.DateTime;
import org.mifos.calendar.CalendarUtils;

public class MonthlyOnDateScheduledEvent extends AbstractScheduledEvent {

    private final int every;
    private final int dayOfMonth;

    public MonthlyOnDateScheduledEvent(final int every, final int dayOfMonth) {
        this.every = every;
        this.dayOfMonth = dayOfMonth;
    }

    @Override
    public DateTime nextEventDateAfter(final DateTime startDate) {

        return CalendarUtils.getNextDateForMonthOnDate(startDate, this.dayOfMonth, this.every);
    }

    @Override
    public DateTime nearestMatchingDateBeginningAt(final DateTime startDate) {

        return CalendarUtils.getFirstDateForMonthOnDate(startDate, this.dayOfMonth);
    }

    @Override
    public int getEvery() {
        return every;
    }
}


text:
import copy

from tempest_lib.tests import fake_auth_provider

from tempest.services.compute.json import keypairs_client
from tempest.tests.services.compute import base

class TestKeyPairsClient(base.BaseComputeServiceTest):

    FAKE_KEYPAIR = {"keypair": {
        "public_key": "ssh-rsa foo Generated-by-Nova",
        "name": u'\u2740(*\xb4\u25e1`*)\u2740',
        "user_id": "525d55f98980415ba98e634972fa4a10",
        "fingerprint": "76:24:66:49:d7:ca:6e:5c:77:ea:8e:bb:9c:15:5f:98"
        }}

    def setUp(self):
        super(TestKeyPairsClient, self).setUp()
        fake_auth = fake_auth_provider.FakeAuthProvider()
        self.client = keypairs_client.KeyPairsClient(
            fake_auth, 'compute', 'regionOne')

    def _test_list_keypairs(self, bytes_body=False):
        self.check_service_client_function(
            self.client.list_keypairs,
            'tempest.common.service_client.ServiceClient.get',
            {"keypairs": []},
            bytes_body)

    def test_list_keypairs_with_str_body(self):
        self._test_list_keypairs()

    def test_list_keypairs_with_bytes_body(self):
        self._test_list_keypairs(bytes_body=True)

    def _test_show_keypair(self, bytes_body=False):
        fake_keypair = copy.deepcopy(self.FAKE_KEYPAIR)
        fake_keypair["keypair"].update({
            "deleted": False,
            "created_at": "2015-07-22T04:53:52.000000",
            "updated_at": None,
            "deleted_at": None,
            "id": 1
            })

        self.check_service_client_function(
            self.client.show_keypair,
            'tempest.common.service_client.ServiceClient.get',
            fake_keypair,
            bytes_body,
            keypair_name="test")

    def test_show_keypair_with_str_body(self):
        self._test_show_keypair()

    def test_show_keypair_with_bytes_body(self):
        self._test_show_keypair(bytes_body=True)

    def _test_create_keypair(self, bytes_body=False):
        fake_keypair = copy.deepcopy(self.FAKE_KEYPAIR)
        fake_keypair["keypair"].update({"private_key": "foo"})

        self.check_service_client_function(
            self.client.create_keypair,
            'tempest.common.service_client.ServiceClient.post',
            fake_keypair,
            bytes_body,
            name="test")

    def test_create_keypair_with_str_body(self):
        self._test_create_keypair()

    def test_create_keypair_with_bytes_body(self):
        self._test_create_keypair(bytes_body=True)

    def test_delete_keypair(self):
        self.check_service_client_function(
            self.client.delete_keypair,
            'tempest.common.service_client.ServiceClient.delete',
            {}, status=202, keypair_name='test')


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Proc. Calif. Acad. Sci. 2:179. 1863 "<I>leseurii</I>"

#### Original name
null

### Remarks
null


text:
TURNVERSION=4.5.0.4
BUILDDIR=~/rpmbuild
ARCH=`uname -p`
TURNSERVER_GIT_URL=https://github.com/coturn/coturn.git

WGETOPTIONS="--no-check-certificate"
RPMOPTIONS="-ivh --force"


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">

    <mapped-superclass name="PandaFire\CoreBundle\Model\TimeSortableItem">

        <field name="title" length="50" />

        <field name="description" type="text" nullable="true" />

        <field name="length" type="integer" />

        <field name="manualStartDate" type="datetime" nullable="true" column="manual_start_date" />

        <field name="startDate" type="datetime" nullable="true" column="start_date" />

        <field name="endDate" type="datetime" nullable="true" column="end_date" />

        <field name="dueDate" type="datetime" column="due_date" />

    </mapped-superclass>

</doctrine-mapping>


text:
<?php
// Cacha headers och innehåll så att vi kan ändra oss och skicka
// en Location-header även efter att vi börjat eka ut innehåll.
ob_start();

// Sätt den globala $repo_root till sökvägen till svn-repots root-mapp.
$repo_root = dirname(dirname(__FILE__));

/**
 * Automatiskt anropad av php on-demand för att include:a filer med klassdefinitioner.
 * Antar att den globala variabeln $repo_root innehåller sökvägen till svn-repots root-mapp.
 */
function __autoload($class) {
	global $repo_root;
	if(substr($class, -1, 1) == 'C') {
		$controller = substr($class, 0, -1);
		if(file_exists("$repo_root/controllers/$controller.local.php")) {
			require_once("$repo_root/controllers/$controller.local.php");
			return;
		}
		if(file_exists("$repo_root/controllers/$controller.php")) {
			require_once("$repo_root/controllers/$controller.php");
			return;
		}
	}
	if(file_exists($repo_root.'/classes/'.$class.'.local.php')) {
		require_once $repo_root.'/classes/'.$class.'.local.php';
		return;
	}
	if(file_exists($repo_root.'/classes/'.$class.'.php')) {
		require_once $repo_root.'/classes/'.$class.'.php';
		return;
	}
}

/**
 * Klasser som behöver instantieras till en global.
 */
$db = new DatabaseConnectioni($webpage_stage, true);
?>


text:
require 'test_helper'

class TapsHelperTest < ActionView::TestCase
end


text:
import sys
from subprocess import check_output, STDOUT, CalledProcessError

def mean(data):
    """Return the sample arithmetic mean of data."""
    n = len(data)
    if n < 1:
        raise ValueError('len < 1')
    return sum(data)/float(n)

def sq_deviation(data):
    """Return sum of square deviations of sequence data."""
    c = mean(data)
    return sum((x-c)**2 for x in data)

def pstdev(data):
    """Calculates the population standard deviation."""
    n = len(data)
    if n < 2:
        raise ValueError('len < 2')
    ss = sq_deviation(data)
    return (ss/n) ** 0.5

def scenario(command, loop=10):
    real = []
    user = []
    syst = []

    test_command = 'time -p ' + command
    for i in range(loop):
        try:
            lines = check_output([test_command], shell=True, stderr=STDOUT).split('\n')
        except CalledProcessError as e:
            lines = e.output.split('\n')
        real_time = float(lines[-4].split()[1])
        real.append(float(lines[-4].split()[1]))
        user.append(float(lines[-3].split()[1]))
        syst.append(float(lines[-2].split()[1]))
        sys.stdout.write('Loop {} => {} \n'.format(i, real_time))
        sys.stdout.flush()

    print('Command: {}'.format(command))
    print('Real: mean => {} \t pstdev => {}'.format(mean(real), pstdev(real)))
    print('User: mean => {} \t pstdev => {}'.format(mean(user), pstdev(user)))
    print('Syst: mean => {} \t pstdev => {}'.format(mean(syst), pstdev(syst)))
    print('')

scenario('az')
scenario('az cl')
scenario('az cloud')
scenario('az cloud list')
scenario('az cloud show --this-does-not-exist')


text:
/*
 * This package implements a LIDAR communication directly using
 * I2C bus from the roboRIO.  This was shown to not be reliable,
 * so we switched to the arduino with serial communications which
 * has worked well
 */

package org.usfirst.frc.team4456.robot;

import java.util.TimerTask;
import edu.wpi.first.wpilibj.I2C;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.I2C.Port;
import edu.wpi.first.wpilibj.PIDSource;
import edu.wpi.first.wpilibj.PIDSourceType;

/**
 * @author bmaranville
 *
 */
public class LidarBackup implements PIDSource
{
	private I2C i2cLidar;
	private byte[] distance;
	private int processedDistance;
	private java.util.Timer updater;

	public LidarBackup(Port port)
	{
		i2cLidar = new I2C(port, Constants.LIDAR_ADDR);
		distance = new byte[2];
		distance[0] = 0;
		distance[1] = 0;
		updater = new java.util.Timer();
		processedDistance = 1;
	}

	public int getDistance()
	{
		return processedDistance;
	}

	public double pidGet()
	{
		return (double)getDistance();
	}

	public void start()
	{
		updater.scheduleAtFixedRate(new LIDARUpdater(), 0, 100);
	}

	public void start(int period)
	{
		updater.scheduleAtFixedRate(new LIDARUpdater(), 0, period);
	}

	public void stop()
	{
		updater.cancel();
		updater = new java.util.Timer();
	}

	public void update()
	{
		long ms0 = System.nanoTime();
		boolean wr = i2cLidar.write(Constants.LIDAR_CONFIG_REGISTER,  0x04);
		long ms1 = System.nanoTime();
		System.out.println("Write:  " + (wr) + "\tTime: " + (ms1-ms0));
		Timer.delay(0.05);
		boolean rd = i2cLidar.read(Constants.LIDAR_DISTANCE_REGISTER, 2, distance);
		long ms2 = System.nanoTime();
		System.out.println("Read: " + (rd) + "\tTime: " + (ms2-ms1));
	    Timer.delay(0.05);
		System.out.println("Updating\tdistance[0]: " + distance[0] + "\tdistance[1]: " + distance[1]);
		processedDistance = (int)Integer.toUnsignedLong(distance[0] << 8) + Byte.toUnsignedInt(distance[1]);
		System.out.println("Get Distance: " + getDistance() + " cm");
	}

	/*
	public void updateWNackack()
	{
		boolean nackack = true;

		//write and wait 1ms until transaction successful
		while(nackack)
		{
			nackack = i2cLidar.write(Constants.LIDAR_CONFIG_REGISTER,  0x04);
			Timer.delay(0.05);
		}

		nackack = true;

		//read and wait 1ms until transaction successful
		while(nackack)
		{
			nackack = i2cLidar.read(Constants.LIDAR_DISTANCE_REGISTER, 2, distance);
			Timer.delay(0.05);
		}

		System.out.println("Updating\tdistance[0]: " + distance[0] + "\tdistance[1]: " + distance[1]);
		processedDistance = (int)Integer.toUnsignedLong(distance[0] << 8) + Byte.toUnsignedInt(distance[1]);
	}
	 */

	private class LIDARUpdater extends TimerTask
	{
		public void run()
		{
			update();
		}
	}

	@Override
	public PIDSourceType getPIDSourceType() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setPIDSourceType(PIDSourceType arg0) {
		// TODO Auto-generated method stub

	}
}


text:
package org.apache.cassandra.tools;

import java.io.IOException;
import java.net.InetAddress;
import java.util.List;
import java.util.Set;

import org.apache.commons.cli.*;

/**
 * JMX cluster wide operations for Cassandra.
 */
public class ClusterCmd {
    private static final String HOST_OPT_LONG = "host";
    private static final String HOST_OPT_SHORT = "h";
    private static final String PORT_OPT_LONG = "port";
    private static final String PORT_OPT_SHORT = "p";
    private static final String USERNAME_OPT_LONG = "username";
    private static final String USERNAME_OPT_SHORT = "u";
    private static final String PASSWORD_OPT_LONG = "password";
    private static final String PASSWORD_OPT_SHORT = "pw";
    private static final int defaultPort = 8080;
    private static Options options = null;
    private CommandLine cmd = null;
    private NodeProbe probe;
    private String host;
    private int port;
    private String username;
    private String password;

    static
    {
        options = new Options();
        Option optHost = new Option(HOST_OPT_SHORT, HOST_OPT_LONG, true, "node hostname or ip address");
        optHost.setRequired(true);
        options.addOption(optHost);
        options.addOption(PORT_OPT_SHORT, PORT_OPT_LONG, true, "remote jmx agent port number (defaults to " + defaultPort + ")");
        options.addOption(USERNAME_OPT_SHORT, USERNAME_OPT_LONG, true, "remote jmx agent user name");
        options.addOption(PASSWORD_OPT_SHORT, PASSWORD_OPT_LONG, true, "remote jmx agent password");
    }

    /**
     * Creates a ClusterProbe using command-line arguments.
     *
     * @param cmdArgs list of arguments passed on the command line
     * @throws ParseException for missing required, or unrecognized options
     * @throws IOException on connection failures
     */
    private ClusterCmd(String[] cmdArgs) throws ParseException, IOException, InterruptedException
    {
        parseArgs(cmdArgs);
        this.host = cmd.getOptionValue(HOST_OPT_SHORT);

        String portNum = cmd.getOptionValue(PORT_OPT_SHORT);
        if (portNum != null)
        {
            try
            {
                this.port = Integer.parseInt(portNum);
            }
            catch (NumberFormatException e)
            {
                throw new ParseException("Port must be a number");
            }
        }
        else
        {
            this.port = defaultPort;
        }

        username = cmd.getOptionValue(USERNAME_OPT_LONG);
        password = cmd.getOptionValue(PASSWORD_OPT_LONG);

        probe = new NodeProbe(host, port,username,password);
    }

    /**
     * Creates a ClusterProbe using the specified JMX host and port.
     *
     * @param host hostname or IP address of the JMX agent
     * @param port TCP port of the remote JMX agent
     * @throws IOException on connection failures
     */
    public ClusterCmd(String host, int port, String username, String password) throws IOException, InterruptedException
    {
        this.host = host;
        this.port = port;
        probe = new NodeProbe(host, port,username,password);
    }

    /**
     * Creates a ClusterProbe using the specified JMX host and default port.
     *
     * @param host hostname or IP address of the JMX agent
     * @throws IOException on connection failures
     */
    public ClusterCmd(String host,String username,String password) throws IOException, InterruptedException
    {
        this(host, defaultPort,username,password);
    }

    /**
     * Parse the supplied command line arguments.
     *
     * @param args arguments passed on the command line
     * @throws ParseException for missing required, or unrecognized options
     */
    private void parseArgs(String[] args) throws ParseException
    {
        CommandLineParser parser = new PosixParser();
        cmd = parser.parse(options, args);
    }

    /**
     * Retrieve any non-option arguments passed on the command line.
     *
     * @return non-option command args
     */
    private String[] getArgs()
    {
        return cmd.getArgs();
    }

    /**
     * Prints usage information to stdout.
     */
    private static void printUsage()
    {
        HelpFormatter hf = new HelpFormatter();
        String header = String.format(
                "%nAvailable commands: get_endpoints [keyspace] [key], global_snapshot [name], clear_global_snapshot");
        String usage = String.format("java %s -host <arg> <command>%n", ClusterCmd.class.getName());
        hf.printHelp(usage, "", options, header);
    }

    public void printEndPoints(String keyspace, String key)
    {
        List<InetAddress> endpoints = probe.getEndPoints(keyspace, key);
        System.out.println(String.format("%-17s: %s", "Key", key));
        System.out.println(String.format("%-17s: %s", "Endpoints", endpoints));
    }

     /**
     * Take a snapshot of all tables on all (live) nodes in the cluster
     *
     * @param snapshotName name of the snapshot
     */
    public void takeGlobalSnapshot(String snapshotName) throws IOException, InterruptedException
    {
        Set<String> liveNodes = probe.getLiveNodes();
        try
        {
            probe.takeSnapshot(snapshotName);
            System.out.println(host + " snapshot taken");
        }
        catch (IOException e)
        {
            System.out.println(host + " snapshot FAILED: " + e.getMessage());
        }

        liveNodes.remove(this.host);
        for (String liveNode : liveNodes)
        {
            try
            {
                this.host = liveNode;
                probe = new NodeProbe(host, port,username,password);
                probe.takeSnapshot(snapshotName);
                System.out.println(host + " snapshot taken");
            }
            catch (IOException e)
            {
                System.out.println(host + " snapshot FAILED: " + e.getMessage());
            }
        }
    }

    /**
     * Remove all the existing snapshots from all (live) nodes in the cluster
     */
    public void clearGlobalSnapshot() throws IOException, InterruptedException
    {
        Set<String> liveNodes = probe.getLiveNodes();
        try
        {
            probe.clearSnapshot();
            System.out.println(host + " snapshot cleared");
        }
        catch (IOException e)
        {
            System.out.println(host + " snapshot clear FAILED: " + e.getMessage());
        }

        liveNodes.remove(this.host);
        for (String liveNode : liveNodes)
        {
            try
            {
                this.host = liveNode;
                probe = new NodeProbe(host, port,username,password);
                probe.clearSnapshot();
                System.out.println(host + " snapshot cleared");
            }
            catch (IOException e)
            {
                System.out.println(host + " snapshot clear FAILED: " + e.getMessage());
            }
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) throws IOException, InterruptedException
    {
        ClusterCmd clusterCmd = null;
        try
        {
            clusterCmd = new ClusterCmd(args);
        }
        catch (ParseException pe)
        {
            System.err.println(pe.getMessage());
            ClusterCmd.printUsage();
            System.exit(1);
        }
        catch (IOException ioe)
        {
            System.err.println("Error connecting to remote JMX agent!");
            ioe.printStackTrace();
            System.exit(3);
        }

        if (clusterCmd.getArgs().length < 1)
        {
            System.err.println("Missing argument for command.");
            ClusterCmd.printUsage();
            System.exit(1);
        }

        // Execute the requested command.
        String[] arguments = clusterCmd.getArgs();
        String cmdName = arguments[0];
        if (cmdName.equals("get_endpoints"))
        {
            if (arguments.length <= 2)
            {
                System.err.println("missing keyspace and/or key argument");
                ClusterCmd.printUsage();
                System.exit(1);
            }
            clusterCmd.printEndPoints(arguments[1], arguments[2]);
        }
        else if (cmdName.equals("global_snapshot"))
        {
            String snapshotName = "";
            if (arguments.length > 1)
            {
                snapshotName = arguments[1];
            }
            clusterCmd.takeGlobalSnapshot(snapshotName);
        }
        else if (cmdName.equals("clear_global_snapshot"))
        {
            clusterCmd.clearGlobalSnapshot();
        }
        else
        {
            System.err.println("Unrecognized command: " + cmdName + ".");
            ClusterCmd.printUsage();
            System.exit(1);
        }

        System.exit(0);
    }

}


text:
namespace content {

bool PermissionControllerDelegate::IsPermissionOverridableByDevTools(
    PermissionType permission,
    const absl::optional<url::Origin>& origin) {
  return true;
}

}  // namespace content


text: Optimize views for android


text:
"use strict";

const Log = require('../models/log');

module.exports = (req, res, next) => {
  Log.create({
    userAgent: req.headers['user-agent'],
    route: req.url,
    verb: req.method
  }, next);
};


text:
module Main where

import Lib

main :: IO ()
main = do
  putStrLn "Excercises from Chapter 03: Strings"
  putStrLn "Some examples commented out in main function."
  putStrLn "Use 'stack ghci' to start ghci to play around. Enjoy."


text:
package se.hulot.jbpm6jboss7example.dao;

import java.lang.reflect.ParameterizedType;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.solder.logging.Logger;

public class DaoImpl<T> implements Dao<T> {
	private final Class<T> type;

	@PersistenceContext(unitName = "se.hulot.jbpm6jboss7example")
	protected EntityManager em;

	private static Logger log = Logger.getLogger(DaoImpl.class);

	@SuppressWarnings("unchecked")
	public DaoImpl() {
		type = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}

	public T create(T t) {
		log.debug("creating " + t.getClass().getSimpleName());
		em.persist(t);
		return t;
	}

	public T find(Object id) {
		log.debug("find " + type.getClass().getSimpleName() + " with id:" + id);
		return em.find(type, id);
	}

	public T update(T t) {
		log.debug("update " + type.getClass().getSimpleName());
		return em.merge(t);
	}

	public void delete(Object id) {
		log.debug("delete " + type.getClass().getSimpleName());
		T t = em.getReference(type, id);
		em.remove(t);
		em.flush();
	}
}


text:
package org.springframework.cloud.dataflow.shell.completer;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import org.springframework.cloud.dataflow.rest.resource.AppRegistrationResource;
import org.springframework.cloud.dataflow.shell.config.DataFlowShell;
import org.springframework.core.MethodParameter;
import org.springframework.shell.CompletionContext;
import org.springframework.shell.CompletionProposal;
import org.springframework.shell.standard.ValueProviderSupport;
import org.springframework.stereotype.Component;

/**
 * A {@link org.springframework.shell.standard.ValueProvider} that provides completion for Data Flow registered
 * application names.
 *
 * @author Chris Bono
 */
@Component
public class ApplicationNameValueProvider extends ValueProviderSupport {

	private final DataFlowShell dataFlowShell;

	public ApplicationNameValueProvider(DataFlowShell dataFlowShell) {
		this.dataFlowShell = dataFlowShell;
	}

	@Override
	public List<CompletionProposal> complete(MethodParameter parameter, CompletionContext completionContext, String[] hints) {
		return StreamSupport.stream(
				dataFlowShell.getDataFlowOperations().appRegistryOperations().list().spliterator(), false)
				.map(AppRegistrationResource::getName)
				.map(CompletionProposal::new)
				.collect(Collectors.toList());
	}
}


text:
package androidx.car.app.sample.places.common;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import androidx.annotation.NonNull;

import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

/** Image-related utilities. */
class ImageUtil {
    static ListenableFuture<Bitmap> loadBitmapFromUrl(@NonNull Context context,
            @NonNull String urlString) {
        SettableFuture<Bitmap> future = SettableFuture.create();
        URL url;
        try {
            url = new URL(urlString);
        } catch (MalformedURLException e) {
            future.setException(e);
            return future;
        }

        Bitmap bmp;
        try {
            bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
        } catch (IOException e) {
            future.setException(e);
            return future;
        }
        future.set(bmp);
        return future;
    }

    private ImageUtil() {
    }
}


text:
#import "ABI42_0_0RCTShadowView+Layout.h"

@interface ABI42_0_0RCTShadowView () {
  __weak ABI42_0_0RCTRootShadowView *_rootView;
}

@end

@implementation ABI42_0_0RCTShadowView (Internal)

- (void)setRootView:(ABI42_0_0RCTRootShadowView *)rootView
{
  _rootView = rootView;
}

@end


text:
layout: post
title: "Transaharienne"
date: 2008-04-17 09:01
---

Je pars ce soir pour une semaine dans le
[Sahara](http://jsaadani.free.fr/) - je posterai sûrement [quelques
photos](http://picasaweb.google.fr/kemenaran/Transaharienne2008Extrait)
au retour.

*PS: Les commentaires sont désactivés pendant la semaine, pour cause de
vague de spam difficile à contenir.*


text:
package publicsuffix

import (
	psl "github.com/weppos/publicsuffix-go/publicsuffix"
)

// PublicSuffix returns the public suffix of the domain
// using a copy of the publicsuffix.org database packaged into this library.
//
// Note. To maintain compatibility with the golang.org/x/net/publicsuffix
// this method doesn't return an error. However, in case of error,
// the returned value is empty.
func PublicSuffix(domain string) (publicSuffix string, icann bool) {
	//d, err := psl.Parse(domain)
	//if err != nil {
	//	return "", false
	//}
	//
	//return d.Rule.Value, !d.Rule.Private

	rule := psl.DefaultList.Find(domain, nil)
	publicSuffix = rule.Decompose(domain)[1]
	icann = !rule.Private

	// x/net/publicsuffix sets icann to false when the default rule "*" is used
	if rule.Value == "" && rule.Type == psl.WildcardType {
		icann = false
	}

	return
}

// EffectiveTLDPlusOne returns the effective top level domain plus one more label.
// For example, the eTLD+1 for "foo.bar.golang.org" is "golang.org".
func EffectiveTLDPlusOne(domain string) (string, error) {
	return psl.Domain(domain)
}


text:
package invtweaks.api;

import invtweaks.api.container.ContainerSection;
import net.minecraft.item.ItemStack;

import javax.annotation.Nonnull;

/**
 * Interface to access functions exposed by Inventory Tweaks
 *

 * The main @Mod instance of the mod implements this interface, so a refernce to it can
 * be obtained via @Instance("inventorytweaks") or methods in net.minecraftforge.fml.common.Loader
 *

 * All of these functions currently have no effect if called on a dedicated server.
 */
@SuppressWarnings("unused")
public interface InvTweaksAPI {
    /**
     * Add a listener for ItemTree load events
     */
    void addOnLoadListener(IItemTreeListener listener);

    /**
     * Remove a listener for ItemTree load events
     *
     * @return true if the listener was previously added
     */
    boolean removeOnLoadListener(IItemTreeListener listener);

    /**
     * Toggle sorting shortcut state.
     */
    void setSortKeyEnabled(boolean enabled);

    /**
     * Toggle sorting shortcut supression.
     * Unlike setSortKeyEnabled, this flag is automatically cleared when GUIs are closed.
     */
    void setTextboxMode(boolean enabled);

    /**
     * Compare two items using the default (non-rule based) algorithm,
     * sutable for an implementation of Comparator<ItemStack>.
     *
     * @param i
     * @param j
     * @return A value with a sign representing the relative order of the item stacks
     */
    int compareItems(@Nonnull ItemStack i, @Nonnull ItemStack j);

    /**
     * Compare two items using the default (non-rule based) algorithm,
     * almost suitable for an implementation of Comparator<ItemStack>.
     * if onlyTreeSort then items not found in the tree will be unsorted after
     * tree items for follow-up sorting.
     *
     * @param i
     * @param j
     * @param onlyTreeSort
     * @return A value with a sign representing the relative order of the item stacks
     */
    int compareItems(@Nonnull ItemStack i, @Nonnull ItemStack j, boolean onlyTreeSort);

    /**
     * Initiate a sort as if the player had clicked on a sorting button or pressed the sort key.
     */
    void sort(ContainerSection section, SortingMethod method);

}


text:
package jpasearch.repository.query.selector;

/**
 * @author speralta
 */
public interface SingleSelector<FROM, TO, S extends SingleSelector<FROM, TO, S>> extends Selector<FROM, S> {

}


text:
<?php
/**
 * Description of purifier
 *
 * @author jp-morvan
 */
class vjCommentPurifier extends HTMLPurifier
{
  private $HTML_ALLOWED = array(
    'blockquote',
    'br',
    'strong',
    'div'
  );

  public function __construct()
  {
    $config = HTMLPurifier_Config::createDefault();
    $config->set('HTML.Allowed', $this->getHTMLAllowed());
    parent::__construct($config);
  }

  private function getHTMLAllowed()
  {
    $tags = sfConfig::get('app_purifier_allowed_tags', array());
    if(sfConfig::get('app_purifier_merge', true) === true)
    {
      $tags = array_merge($this->HTML_ALLOWED, $tags);
    }
    return join(',', $tags);
  }
}
?>


text:
'use babel';

import { _ } from 'lodash';

class TextXUtil {

  getSimpleName(className) {
    return className.replace(/[a-z]*\./g, '');
  }

  getPackageName(className) {
    return className.replace('.' + this.getSimpleName(className), '');
  }

  getInverseName(className) {
    return _.reduceRight(className.split('.'), (result, next) => {
      return result + next;
    }, '');
  }

}

export default new TextXUtil();