text:
// Code generated by lister-gen. DO NOT EDIT.

package v1alpha1

import (
	"k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/client-go/tools/cache"
	v1alpha1 "knative.dev/eventing-kafka-broker/third_party/pkg/apis/keda/v1alpha1"
)

// ScaledJobLister helps list ScaledJobs.
// All objects returned here must be treated as read-only.
type ScaledJobLister interface {
	// List lists all ScaledJobs in the indexer.
	// Objects returned here must be treated as read-only.
	List(selector labels.Selector) (ret []*v1alpha1.ScaledJob, err error)
	// ScaledJobs returns an object that can list and get ScaledJobs.
	ScaledJobs(namespace string) ScaledJobNamespaceLister
	ScaledJobListerExpansion
}

// scaledJobLister implements the ScaledJobLister interface.
type scaledJobLister struct {
	indexer cache.Indexer
}

// NewScaledJobLister returns a new ScaledJobLister.
func NewScaledJobLister(indexer cache.Indexer) ScaledJobLister {
	return &scaledJobLister{indexer: indexer}
}

// List lists all ScaledJobs in the indexer.
func (s *scaledJobLister) List(selector labels.Selector) (ret []*v1alpha1.ScaledJob, err error) {
	err = cache.ListAll(s.indexer, selector, func(m interface{}) {
		ret = append(ret, m.(*v1alpha1.ScaledJob))
	})
	return ret, err
}

// ScaledJobs returns an object that can list and get ScaledJobs.
func (s *scaledJobLister) ScaledJobs(namespace string) ScaledJobNamespaceLister {
	return scaledJobNamespaceLister{indexer: s.indexer, namespace: namespace}
}

// ScaledJobNamespaceLister helps list and get ScaledJobs.
// All objects returned here must be treated as read-only.
type ScaledJobNamespaceLister interface {
	// List lists all ScaledJobs in the indexer for a given namespace.
	// Objects returned here must be treated as read-only.
	List(selector labels.Selector) (ret []*v1alpha1.ScaledJob, err error)
	// Get retrieves the ScaledJob from the indexer for a given namespace and name.
	// Objects returned here must be treated as read-only.
	Get(name string) (*v1alpha1.ScaledJob, error)
	ScaledJobNamespaceListerExpansion
}

// scaledJobNamespaceLister implements the ScaledJobNamespaceLister
// interface.
type scaledJobNamespaceLister struct {
	indexer   cache.Indexer
	namespace string
}

// List lists all ScaledJobs in the indexer for a given namespace.
func (s scaledJobNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.ScaledJob, err error) {
	err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {
		ret = append(ret, m.(*v1alpha1.ScaledJob))
	})
	return ret, err
}

// Get retrieves the ScaledJob from the indexer for a given namespace and name.
func (s scaledJobNamespaceLister) Get(name string) (*v1alpha1.ScaledJob, error) {
	obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name)
	if err != nil {
		return nil, err
	}
	if !exists {
		return nil, errors.NewNotFound(v1alpha1.Resource("scaledjob"), name)
	}
	return obj.(*v1alpha1.ScaledJob), nil
}


text:
require 'rails_helper'

RSpec.describe 'User uses api to check status' do
  let(:user) { FactoryBot.create(:user) }
  let(:encoded_token) { JWT.encode({ user_id: user.id }, Rails.application.secrets.secret_key_base) }

  it 'without an auth header and gets an error' do
    get api_my_pendant_record_status_path

    expect(response.body).to eq '{"error":"Not Authorized"}'
  end

  it 'with a valid auth header gets status' do
    get api_my_pendant_record_status_path, headers: { 'Authorization' => encoded_token }

    expect(response.body).to eq '{"pendant_recorded?":false}'
  end

  context 'when the user has recorded a pendant' do
    let!(:pendant_record) { FactoryBot.create :pendant_record, user: user }

    it 'with a valid auth header gets status of true' do
      get api_my_pendant_record_status_path, headers: { 'Authorization' => encoded_token }

      expect(response.body).to eq '{"pendant_recorded?":true}'
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
.class Landroid/widget/AbsListView$WindowRunnnable;
.super Ljava/lang/Object;
.source "AbsListView.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/widget/AbsListView;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x2
    name = "WindowRunnnable"
.end annotation

# instance fields
.field private mOriginalAttachCount:I

.field final synthetic this$0:Landroid/widget/AbsListView;

# direct methods
.method private constructor <init>(Landroid/widget/AbsListView;)V
    .locals 0

    .prologue
    .line 3972
    iput-object p1, p0, Landroid/widget/AbsListView$WindowRunnnable;->this$0:Landroid/widget/AbsListView;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method synthetic constructor <init>(Landroid/widget/AbsListView;Landroid/widget/AbsListView$1;)V
    .locals 0
    .param p1, "x0"    # Landroid/widget/AbsListView;
    .param p2, "x1"    # Landroid/widget/AbsListView$1;

    .prologue
    .line 3972
    invoke-direct {p0, p1}, Landroid/widget/AbsListView$WindowRunnnable;-><init>(Landroid/widget/AbsListView;)V

    return-void
.end method

# virtual methods
.method public rememberWindowAttachCount()V
    .locals 1

    .prologue
    .line 3976
    iget-object v0, p0, Landroid/widget/AbsListView$WindowRunnnable;->this$0:Landroid/widget/AbsListView;

    # invokes: Landroid/widget/AbsListView;->getWindowAttachCount()I
    invoke-static {v0}, Landroid/widget/AbsListView;->access$400(Landroid/widget/AbsListView;)I

    move-result v0

    iput v0, p0, Landroid/widget/AbsListView$WindowRunnnable;->mOriginalAttachCount:I

    .line 3977
    return-void
.end method

.method public sameWindow()Z
    .locals 2

    .prologue
    .line 3980
    iget-object v0, p0, Landroid/widget/AbsListView$WindowRunnnable;->this$0:Landroid/widget/AbsListView;

    # invokes: Landroid/widget/AbsListView;->getWindowAttachCount()I
    invoke-static {v0}, Landroid/widget/AbsListView;->access$500(Landroid/widget/AbsListView;)I

    move-result v0

    iget v1, p0, Landroid/widget/AbsListView$WindowRunnnable;->mOriginalAttachCount:I

    if-ne v0, v1, :cond_0

    const/4 v0, 0x1

    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method


text:
require 'rubysimf'
require 'rubysimf_modules/queue_systems'

class Cliente
end

def simular(nro_corrida, lambda, mu, k)
  puts "Corrida #{nro_corrida}"
  $nro_clientes = 0

  $sim = RubySimF::Simulator.instance
  $sim.init

  $v_tiempo_interarribo = RubySimF::Random::ExponentialVariate.new :lambda => lambda
  $v_tiempo_servicio = RubySimF::Random::ExponentialVariate.new :lambda => mu

  $mundo_exterior = RubySimF::QueueSystems::Source.new(
    :class => Cliente,
    :interarrival_time_random_variate => $v_tiempo_interarribo)

  $oficina_banco = RubySimF::QueueSystems::BasicQueueSystem.new(
    :service_time_random_variate => $v_tiempo_servicio,
    :number_of_servers => k)

  $mundo_exterior.deliver_to $oficina_banco

  $oficina_banco.declare_output_method{|cliente|
    #puts "Cliente #{$nro_clientes} servido"
    $nro_clientes +=1
    $nro_clientes_global +=1

    $sim.statistics_on if $nro_clientes == $clientes_a_descartar
    $sim.stop if $nro_clientes == $clientes_por_corrida
  }

  $mundo_exterior.generate
  $sim.simulate :statistics_on => false

  $recolector_ls << $oficina_banco.ls
  $recolector_lq << $oficina_banco.lq
  $recolector_wq << $oficina_banco.wq
  $recolector_ws << $oficina_banco.ws
end

def converge(ls_real)
  return false if $corrida < 3
  $porcentaje_tope = 1
  if $recolector_ls.mean && $recolector_ls.standard_desviation
    $diferencia = ($recolector_ls.mean-ls_real).abs
    $epsilon = $porcentaje_tope/100.0 * ls_real
    $desv = $recolector_ls.standard_desviation
    return $desv <= $diferencia && $diferencia <= $epsilon
  else
    return false
  end
end

$lambda = ARGV[0].to_f
$mu = ARGV[1].to_f
$k = ARGV[2].to_i
$archivo = "m_m_#{$k}_#{"%.0f"%$lambda}_#{"%.0f"%$mu}.txt"

#principal

$clientes_por_corrida = 26000
$clientes_a_descartar = 1000

$nro_clientes_global = 1
$diferencia = 1000000
$epsilon = 1000
$desv = 1000000000

$recolector_lq = RubySimF::Collector.new
$recolector_ls = RubySimF::Collector.new
$recolector_wq = RubySimF::Collector.new
$recolector_ws = RubySimF::Collector.new
$corrida = 1
while $corrida <=120#!converge para[:ls_real]
  simular($corrida, $lambda, $mu, $k)
  File.open($archivo, "a") { |archivo|
    #archivo.puts "nro_corridas|desviacion|diferencia|epsilon|lambda|mu|k|lq|ls|wq|ws" if $corrida == 1
    #archivo.puts "#{$corrida}|#{$desv}|#{$diferencia}|#{$epsilon}|#{para[:lambda]}|#{para[:mu]}|#{para[:k]}|#{$recolector_lq.mean}|#{$recolector_ls.mean}|#{$recolector_wq.mean}|#{$recolector_ws.mean}"
    archivo.puts "nro_corridas|lambda|mu|k|lq|ls|wq|ws" if $corrida == 1
    archivo.puts "#{$corrida}|#{$lambda}|#{$mu}|#{$k}|#{$recolector_lq.mean}|#{$recolector_ls.mean}|#{$recolector_wq.mean}|#{$recolector_ws.mean}"
  }
  $corrida += 1
end


text:
<!DOCTYPE html>

  <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <title>SlickGrid example 11: No vertical scrolling (autoHeight)</title>
  <link rel="stylesheet" href="../slick.grid.css" type="text/css"/>
  <link rel="stylesheet" href="examples.css" type="text/css"/>

Demonstrates:

autoHeight:true grid option


text:
#include <boost/detail/lightweight_test_report.hpp>
#include <boost/filesystem.hpp>

namespace fs = boost::filesystem;

int test_main(int, char*[])     // note name
{
  BOOST_TEST(2 + 2 == 5);       // one convertible-to-bool argument
  BOOST_TEST_EQ(4 + 4, 9);      // two EqualityComparible arguments
  BOOST_TEST(fs::exists("."));  // should pass, so nothing reported

  return ::boost::report_errors();   // required
}

//  Copyright Beman Dawes 2014
//  Distributed under the Boost Software License, Version 1.0.
//  www.boost.org/LICENSE_1_0.txt


text:
namespace arangodb {
namespace basics {

////////////////////////////////////////////////////////////////////////////////
/// @brief read unlocker
///
/// A ReadUnlocker unlocks a read-write lock during its lifetime and reacquires
/// the read-lock again when it is destroyed.
////////////////////////////////////////////////////////////////////////////////

class ReadUnlocker {
  ReadUnlocker(ReadUnlocker const&) = delete;
  ReadUnlocker& operator=(ReadUnlocker const&) = delete;

 public:
  //////////////////////////////////////////////////////////////////////////////
  /// @brief unlocks the lock
  ///
  /// The constructor unlocks the lock, the destructors acquires a read-lock.
  //////////////////////////////////////////////////////////////////////////////

  explicit ReadUnlocker(ReadWriteLock* readWriteLock) noexcept
      : _readWriteLock(readWriteLock) {
    _readWriteLock->unlockRead();
  }

  ////////////////////////////////////////////////////////////////////////////////
  /// @brief unlocks the lock
  ///
  /// The constructor unlocks the lock, the destructors acquires a
  /// read-lock.
  ////////////////////////////////////////////////////////////////////////////////

  ////////////////////////////////////////////////////////////////////////////////
  /// @brief acquires the read-lock
  ////////////////////////////////////////////////////////////////////////////////

  ~ReadUnlocker() { _readWriteLock->lockRead(); }

 private:
  ////////////////////////////////////////////////////////////////////////////////
  /// @brief the read-write lock
  ////////////////////////////////////////////////////////////////////////////////

  ReadWriteLock* _readWriteLock;
};
}  // namespace basics
}  // namespace arangodb


text:
JavaScript observable objects everywhere

`obs.js` is a tiny JavaScript library (~0.5kb) which runs almost everywhere (ES3 compliant), making it easy to work with data in observable JavaScript objects with computable properties.

## How to use

Instantiate a new observable object by calling `obs()`:

```javascript
var data = obs();
```

Now, set and get properties easily by calling `data(property, value)` or `data(property)`:

```javascript
data('color', 'orange');   // set property
var color = data('color'); // get property
data('color', undefined);  // clear property
```

Add an observer by passing a function to `data()`:

```javascript
data(function(property, value){
  console.log(property + ' changed to ' + value);
});
```

Call `data()` with no arguments to get a copy of all properties and values:

```javascript
var copy = data(); // {color: 'red'}
```

## The callable nature of an observable object

An observable object created by `obs()` is actually a multipurpose function, changing its functionality depending on what is input:
* Provided with an `object`, all its properties and values are set from the input object, discarding all previously set properties, then returns itself. Objects (including arrays and functions) are assigned by reference, other values by copy. Registered observers are notified about each property change, including discarded properties.
* Provided with a `function`, it registers this as an observer and returns a function to be used for unregistering the observer. All registered observers are called on each property change, with two arguments: `property` and `value`.
* Provided with no argument, it returns an object with properties and values reflecting its current state. Computable properties are computed and set to the return value of the computation.
* Provided with `null`, it returns an object with properties and values reflecting its current state. Computable properties are preserved as callable functions.
* Provided with two arguments, it treats the first as a property to be set and the second as a value to assign to the property, then returns the value. Pass a value of `undefined` to clear a property. All observers are notified.
* Provided with a single argument, it treats this as a property to be read and returns its value, or `undefined` if the property has been cleared or is not defined. If the value is a function, it is treated as a computable property, and the return value from calling the function is returned.

## Code examples of all features

```javascript
// create new observable object
var data = obs();

// fill it with some data
data({
  name: 'John',
  age: 56
});

// or do both at the same time
var data = obs({
  name: 'John',
  age: 56
});

// add an observer,
// keep a reference to its unregistration function
var unregister = data(
  function(property, value){
    console.log(property + ' just set to ' + value);
  }
);

// write some data
// and watch the console output of the observer
data('age', 57);            // evaluates to the set value of 57
data('best friend', 'Bob'); // evaluates to the set value of 'Bob'

// unregister the observer
unregister();

// read data
var age = data('age');

// clear data
data('age', undefined);

// use computable properties
data({
  birthyear: 1987,
  age: function(){
    return (new Date).getFullYear() - this.birthyear;
  }
})
var age = data('age'); // returns the computed age

// get an object copy of the data state
var copy = data();     // {'birthyear': 1987, 'age': 30}

// get an object copy of the data
// with computable properties preserved
var copy = data(null); // {'birthyear': 1987, 'age': function(){...}}

// get an observable copy
var observableCopy = obs()(data(null));

// refresh all registered observers
data(data(null));

// clear all data
data({});
```

## Tests

Tests are in the file `index.html` which can be [run online](https://tomaslangkaas.github.io/obs.js/).


text:
class GuiThreadFuncHelper : public QObject
{
    Q_OBJECT

    explicit GuiThreadFuncHelper(QObject *parent = 0):QObject(parent){}
public:
    static GuiThreadFuncHelper * getInstance(QObject *parent = 0){
        static GuiThreadFuncHelper instance(parent);
        return &instance;
    }

signals:

public slots:
    void availableCameras(QObject * getter){
        QMetaObject::invokeMethod(getter, "availableCameras", Qt::QueuedConnection,
        Q_ARG(QList<QCameraInfo>, QCameraInfo::availableCameras()));
    }
};

#endif // GUITHREADFUNCHELPER_H


text:
package fathom.realm.pam;

import com.google.common.base.Preconditions;
import com.typesafe.config.Config;
import fathom.authc.StandardCredentials;
import fathom.realm.Account;
import fathom.realm.CachingRealm;
import fathom.utils.Util;
import org.jvnet.libpam.PAM;
import org.jvnet.libpam.PAMException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 * @author James Moger
 */
public class PamRealm extends CachingRealm {

    private static Logger log = LoggerFactory.getLogger(PamRealm.class);

    private String serviceName;

    public PamRealm() {
        super();
    }

    @Override
    public void setup(Config config) {
        super.setup(config);

        String os = System.getProperty("os.name").toLowerCase();
        Preconditions.checkState(!os.startsWith("windows"), "PAM authentication is not supported on '{0}'", os);

        // Try to identify the passwd database
        String[] files = {"/etc/shadow", "/etc/master.passwd"};
        File passwdFile = null;
        for (String name : files) {
            File f = new File(name);
            if (f.exists()) {
                passwdFile = f;
                break;
            }
        }
        if (passwdFile == null) {
            log.warn("Could not find a passwd database!");
        } else if (!passwdFile.canRead()) {
            log.warn("Can not read passwd database {}! PAM authentications may fail!", passwdFile);
        }

        serviceName = "system-auth";
        if (config.hasPath("serviceName")) {
            serviceName = config.getString("serviceName");
        }
    }

    @Override
    public void start() {
        log.debug("Realm '{}' configuration:", getRealmName());
        Util.logSetting(log, "serviceName", serviceName);
        super.logCacheSettings(log);
    }

    @Override
    public void stop() {
    }

    @Override
    public Account authenticate(StandardCredentials requestCredentials) {

        final String username = requestCredentials.getUsername();
        final String password = requestCredentials.getPassword();

        if (hasAccount(username)) {
            // account is cached, authenticate against the cache
            return super.authenticate(requestCredentials);
        }

        return authenticate(username, password);
    }

    @Override
    public Account authenticate(final String username, final String password) {
        PAM pam = null;
        try {
            pam = new PAM(serviceName);
            pam.authenticate(username, password);
            log.debug("Authentication succeeded for '{}' against '{}'", username, getRealmName());

            Account account = new Account(null, new StandardCredentials(username, password));
            cacheAccount(account);

            return account;
        } catch (PAMException e) {
            log.debug("Authentication failed for '{}' against '{}'", username, getRealmName());
            log.error(e.getMessage());
        } finally {
            if (pam != null) {
                pam.dispose();
            }
        }

        return null;
    }

}


text:
{% extends "detail_base.html" %}

{% load i18n %}
{% load ifsetting_tag %}
{% load portal_tags %}

{% block head_title %}{{object.name}}{% endblock %}

{% block body_class %}repositories{% endblock %}

{% block sidebar_details %}
    {% include "_repository_info.html" %}
{% endblock %}

{% block body_description %}
    {% include "_repository_description_diff.html" %}
{% endblock %}


text:
{% load i18n pages_tags %}
{% spaceless %}

{% if branch_level == 0 %}

{% endif %}
{% for page in page_branch %}
    {% if page.is_current_child and page.in_menu %}

        {{ page.title }}

    {% endif %}
    {% if page.has_children_in_menu %}{% page_menu page %}{% endif %}
{% endfor %}
{% if branch_level == 0 %}

{% endif %}
{% endspaceless %}


text:
SYNONYM

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

#### Published in
Bull. trimest. Soc. mycol. Fr. 43: 186 (1927)

#### Original name
Agaricus splendens Pers., 1801

### Remarks
null


text:
'use babel';

const fs = require('fs')
const esprima = require('esprima')
const spokenCode = require('./spoken-code.js')
const { Emitter, CompositeDisposable } = require('atom')
const pushAnalyzer = require('./analyzer.js')

export default class SpokenCodeView {

  constructor(serializedState) {
    this.element = document.createElement('div')
    this.element.classList.add('spoken-code')
    this.element.setAttribute('id', 'word-box')
    this.element.style.margin = 'auto'
    this.element.style.textAlign = 'center'
    this.element.style.height = '20px'
    this.element.style.color = 'white'

    const message = document.createElement('div')
    message.classList.add('message')
    this.element.appendChild(message)
  }

  serialize() {}

  destroy() {
    this.element.remove()
  }

  getElement() {
    return this.element;
  }

  setText(text) {
    if (text.length === 0) {
      textToSpeech(['Please make a selection'])
    }
    else if (text.length > 500) {
      textToSpeech(['Please make a smaller selection'])
    }
    else {
      parseText(text)
        .then(response => {
          textToSpeech(response)
          console.log(response)
        })
        .catch(reason => {
          textToSpeech(['Bad Syntax.'])
        })
    }
  }
}

const parseText = (text) => {
  return new Promise((resolve, reject) => {
    const tokenizer = esprima.parse(text, {sourceType:'script'})
    if (tokenizer) {
      let analyzedString = pushAnalyzer(tokenizer.body)
      resolve(analyzedString)
    }
    else {
      reject(tokenizer.body)
    }
  })
}

const textToSpeech = (text) => {
  const wordBox = document.getElementById('word-box')
  const button = document.createElement('button')
  button.setAttribute('id', 'speak-button')
  button.style.textAlign = 'center'
  button.style.margin = 'auto'
  button.style.color = 'white'
  button.style.background = 'black'
  button.style.border = '0px'
  button.style.width = '250px'
  button.style.cursor = 'pointer'
  wordBox.textContent = ''
  button.textContent = 'Speak Code to Me'
  wordBox.appendChild(button)
  button.addEventListener('click', () => {
    let msg = new SpeechSynthesisUtterance();
    msg.text = text
    msg.onerror = (event) => {
      button.textContent = 'Error with Speech Conversion: ' + event.error
      button.addEventListener('click', () => {
        spokenCode.default.toggle()
      })
    }
    msg.onstart = () => {
      spokenCode.default.toggle()
    }
    speechSynthesis.speak(msg)
  })
}


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.content.browser;

import android.content.Context;
import android.view.View;

/**
 * Allows customization for clients of the ContentVideoView.
 * The implementer is responsible for displaying the Android view when
 * {@link #onShowCustomView(View)} is called.
 */
public interface ContentVideoViewContextDelegate {
    public void onShowCustomView(View view);
    public void onDestroyContentVideoView();
    public Context getContext();
    public String getPlayBackErrorText();
    public String getUnknownErrorText();
    public String getErrorButton();
    public String getErrorTitle();
    public String getVideoLoadingText();
}


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

package ipv6

import (
	"fmt"

	"gvisor.dev/gvisor/pkg/bufferv2"
	"gvisor.dev/gvisor/pkg/tcpip"
	"gvisor.dev/gvisor/pkg/tcpip/header"
	"gvisor.dev/gvisor/pkg/tcpip/stack"
)

// icmpv6DestinationUnreachableSockError is a general ICMPv6 Destination
// Unreachable error.
//
// +stateify savable
type icmpv6DestinationUnreachableSockError struct{}

// Origin implements tcpip.SockErrorCause.
func (*icmpv6DestinationUnreachableSockError) Origin() tcpip.SockErrOrigin {
	return tcpip.SockExtErrorOriginICMP6
}

// Type implements tcpip.SockErrorCause.
func (*icmpv6DestinationUnreachableSockError) Type() uint8 {
	return uint8(header.ICMPv6DstUnreachable)
}

// Info implements tcpip.SockErrorCause.
func (*icmpv6DestinationUnreachableSockError) Info() uint32 {
	return 0
}

var _ stack.TransportError = (*icmpv6DestinationNetworkUnreachableSockError)(nil)

// icmpv6DestinationNetworkUnreachableSockError is an ICMPv6 Destination Network
// Unreachable error.
//
// It indicates that the destination network is unreachable.
//
// +stateify savable
type icmpv6DestinationNetworkUnreachableSockError struct {
	icmpv6DestinationUnreachableSockError
}

// Code implements tcpip.SockErrorCause.
func (*icmpv6DestinationNetworkUnreachableSockError) Code() uint8 {
	return uint8(header.ICMPv6NetworkUnreachable)
}

// Kind implements stack.TransportError.
func (*icmpv6DestinationNetworkUnreachableSockError) Kind() stack.TransportErrorKind {
	return stack.DestinationNetworkUnreachableTransportError
}

var _ stack.TransportError = (*icmpv6DestinationPortUnreachableSockError)(nil)

// icmpv6DestinationPortUnreachableSockError is an ICMPv6 Destination Port
// Unreachable error.
//
// It indicates that a packet reached the destination host, but the transport
// protocol was not active on the destination port.
//
// +stateify savable
type icmpv6DestinationPortUnreachableSockError struct {
	icmpv6DestinationUnreachableSockError
}

// Code implements tcpip.SockErrorCause.
func (*icmpv6DestinationPortUnreachableSockError) Code() uint8 {
	return uint8(header.ICMPv6PortUnreachable)
}

// Kind implements stack.TransportError.
func (*icmpv6DestinationPortUnreachableSockError) Kind() stack.TransportErrorKind {
	return stack.DestinationPortUnreachableTransportError
}

var _ stack.TransportError = (*icmpv6DestinationAddressUnreachableSockError)(nil)

// icmpv6DestinationAddressUnreachableSockError is an ICMPv6 Destination Address
// Unreachable error.
//
// It indicates that a packet was not able to reach the destination.
//
// +stateify savable
type icmpv6DestinationAddressUnreachableSockError struct {
	icmpv6DestinationUnreachableSockError
}

// Code implements tcpip.SockErrorCause.
func (*icmpv6DestinationAddressUnreachableSockError) Code() uint8 {
	return uint8(header.ICMPv6AddressUnreachable)
}

// Kind implements stack.TransportError.
func (*icmpv6DestinationAddressUnreachableSockError) Kind() stack.TransportErrorKind {
	return stack.DestinationHostUnreachableTransportError
}

var _ stack.TransportError = (*icmpv6PacketTooBigSockError)(nil)

// icmpv6PacketTooBigSockError is an ICMPv6 Packet Too Big error.
//
// It indicates that a link exists on the path to the destination with an MTU
// that is too small to carry the packet.
//
// +stateify savable
type icmpv6PacketTooBigSockError struct {
	mtu uint32
}

// Origin implements tcpip.SockErrorCause.
func (*icmpv6PacketTooBigSockError) Origin() tcpip.SockErrOrigin {
	return tcpip.SockExtErrorOriginICMP6
}

// Type implements tcpip.SockErrorCause.
func (*icmpv6PacketTooBigSockError) Type() uint8 {
	return uint8(header.ICMPv6PacketTooBig)
}

// Code implements tcpip.SockErrorCause.
func (*icmpv6PacketTooBigSockError) Code() uint8 {
	return uint8(header.ICMPv6UnusedCode)
}

// Info implements tcpip.SockErrorCause.
func (e *icmpv6PacketTooBigSockError) Info() uint32 {
	return e.mtu
}

// Kind implements stack.TransportError.
func (*icmpv6PacketTooBigSockError) Kind() stack.TransportErrorKind {
	return stack.PacketTooBigTransportError
}

func (e *endpoint) checkLocalAddress(addr tcpip.Address) bool {
	if e.nic.Spoofing() {
		return true
	}

	if addressEndpoint := e.AcquireAssignedAddress(addr, false, stack.NeverPrimaryEndpoint); addressEndpoint != nil {
		addressEndpoint.DecRef()
		return true
	}
	return false
}

// handleControl handles the case when an ICMP packet contains the headers of
// the original packet that caused the ICMP one to be sent. This information is
// used to find out which transport endpoint must be notified about the ICMP
// packet.
func (e *endpoint) handleControl(transErr stack.TransportError, pkt stack.PacketBufferPtr) {
	h, ok := pkt.Data().PullUp(header.IPv6MinimumSize)
	if !ok {
		return
	}
	hdr := header.IPv6(h)

	// We don't use IsValid() here because ICMP only requires that up to
	// 1280 bytes of the original packet be included. So it's likely that it
	// is truncated, which would cause IsValid to return false.
	//
	// Drop packet if it doesn't have the basic IPv6 header or if the
	// original source address doesn't match an address we own.
	srcAddr := hdr.SourceAddress()
	if !e.checkLocalAddress(srcAddr) {
		return
	}

	// Keep needed information before trimming header.
	p := hdr.TransportProtocol()
	dstAddr := hdr.DestinationAddress()

	// Skip the IP header, then handle the fragmentation header if there
	// is one.
	if _, ok := pkt.Data().Consume(header.IPv6MinimumSize); !ok {
		panic("could not consume IPv6MinimumSize bytes")
	}
	if p == header.IPv6FragmentHeader {
		f, ok := pkt.Data().PullUp(header.IPv6FragmentHeaderSize)
		if !ok {
			return
		}
		fragHdr := header.IPv6Fragment(f)
		if !fragHdr.IsValid() || fragHdr.FragmentOffset() != 0 {
			// We can't handle fragments that aren't at offset 0
			// because they don't have the transport headers.
			return
		}
		p = fragHdr.TransportProtocol()

		// Skip fragmentation header and find out the actual protocol
		// number.
		if _, ok := pkt.Data().Consume(header.IPv6FragmentHeaderSize); !ok {
			panic("could not consume IPv6FragmentHeaderSize bytes")
		}
	}

	e.dispatcher.DeliverTransportError(srcAddr, dstAddr, ProtocolNumber, p, transErr, pkt)
}

// getLinkAddrOption searches NDP options for a given link address option using
// the provided getAddr function as a filter. Returns the link address if
// found; otherwise, returns the zero link address value. Also returns true if
// the options are valid as per the wire format, false otherwise.
func getLinkAddrOption(it header.NDPOptionIterator, getAddr func(header.NDPOption) tcpip.LinkAddress) (tcpip.LinkAddress, bool) {
	var linkAddr tcpip.LinkAddress
	for {
		opt, done, err := it.Next()
		if err != nil {
			return "", false
		}
		if done {
			break
		}
		if addr := getAddr(opt); len(addr) != 0 {
			// No RFCs define what to do when an NDP message has multiple Link-Layer
			// Address options. Since no interface can have multiple link-layer
			// addresses, we consider such messages invalid.
			if len(linkAddr) != 0 {
				return "", false
			}
			linkAddr = addr
		}
	}
	return linkAddr, true
}

// getSourceLinkAddr searches NDP options for the source link address option.
// Returns the link address if found; otherwise, returns the zero link address
// value. Also returns true if the options are valid as per the wire format,
// false otherwise.
func getSourceLinkAddr(it header.NDPOptionIterator) (tcpip.LinkAddress, bool) {
	return getLinkAddrOption(it, func(opt header.NDPOption) tcpip.LinkAddress {
		if src, ok := opt.(header.NDPSourceLinkLayerAddressOption); ok {
			return src.EthernetAddress()
		}
		return ""
	})
}

// getTargetLinkAddr searches NDP options for the target link address option.
// Returns the link address if found; otherwise, returns the zero link address
// value. Also returns true if the options are valid as per the wire format,
// false otherwise.
func getTargetLinkAddr(it header.NDPOptionIterator) (tcpip.LinkAddress, bool) {
	return getLinkAddrOption(it, func(opt header.NDPOption) tcpip.LinkAddress {
		if dst, ok := opt.(header.NDPTargetLinkLayerAddressOption); ok {
			return dst.EthernetAddress()
		}
		return ""
	})
}

func isMLDValid(pkt stack.PacketBufferPtr, iph header.IPv6, routerAlert *header.IPv6RouterAlertOption) bool {
	// As per RFC 2710 section 3:
	//   All MLD messages described in this document are sent with a link-local
	//   IPv6 Source Address, an IPv6 Hop Limit of 1, and an IPv6 Router Alert
	//   option in a Hop-by-Hop Options header.
	if routerAlert == nil || routerAlert.Value != header.IPv6RouterAlertMLD {
		return false
	}
	if len(pkt.TransportHeader().Slice()) < header.ICMPv6HeaderSize+header.MLDMinimumSize {
		return false
	}
	if iph.HopLimit() != header.MLDHopLimit {
		return false
	}
	if !header.IsV6LinkLocalUnicastAddress(iph.SourceAddress()) {
		return false
	}
	return true
}

func (e *endpoint) handleICMP(pkt stack.PacketBufferPtr, hasFragmentHeader bool, routerAlert *header.IPv6RouterAlertOption) {
	sent := e.stats.icmp.packetsSent
	received := e.stats.icmp.packetsReceived
	h := header.ICMPv6(pkt.TransportHeader().Slice())
	if len(h) < header.ICMPv6MinimumSize {
		received.invalid.Increment()
		return
	}
	iph := header.IPv6(pkt.NetworkHeader().Slice())
	srcAddr := iph.SourceAddress()
	dstAddr := iph.DestinationAddress()

	// Validate ICMPv6 checksum before processing the packet.
	payload := pkt.Data()
	if got, want := h.Checksum(), header.ICMPv6Checksum(header.ICMPv6ChecksumParams{
		Header:      h,
		Src:         srcAddr,
		Dst:         dstAddr,
		PayloadCsum: payload.Checksum(),
		PayloadLen:  payload.Size(),
	}); got != want {
		received.invalid.Increment()
		return
	}

	isNDPValid := func() bool {
		// As per RFC 4861 sections 4.1 - 4.5, 6.1.1, 6.1.2, 7.1.1, 7.1.2 and
		// 8.1, nodes MUST silently drop NDP packets where the Hop Limit field
		// in the IPv6 header is not set to 255, or the ICMPv6 Code field is not
		// set to 0.
		//
		// As per RFC 6980 section 5, nodes MUST silently drop NDP messages if the
		// packet includes a fragmentation header.
		return !hasFragmentHeader && iph.HopLimit() == header.NDPHopLimit && h.Code() == 0
	}

	// TODO(b/112892170): Meaningfully handle all ICMP types.
	switch icmpType := h.Type(); icmpType {
	case header.ICMPv6PacketTooBig:
		received.packetTooBig.Increment()
		networkMTU, err := calculateNetworkMTU(h.MTU(), header.IPv6MinimumSize)
		if err != nil {
			networkMTU = 0
		}
		e.handleControl(&icmpv6PacketTooBigSockError{mtu: networkMTU}, pkt)

	case header.ICMPv6DstUnreachable:
		received.dstUnreachable.Increment()
		switch h.Code() {
		case header.ICMPv6NetworkUnreachable:
			e.handleControl(&icmpv6DestinationNetworkUnreachableSockError{}, pkt)
		case header.ICMPv6PortUnreachable:
			e.handleControl(&icmpv6DestinationPortUnreachableSockError{}, pkt)
		}
	case header.ICMPv6NeighborSolicit:
		received.neighborSolicit.Increment()
		if !isNDPValid() || len(h) < header.ICMPv6NeighborSolicitMinimumSize {
			received.invalid.Increment()
			return
		}

		ns := header.NDPNeighborSolicit(h.MessageBody())
		targetAddr := ns.TargetAddress()

		// As per RFC 4861 section 4.3, the Target Address MUST NOT be a multicast
		// address.
		if header.IsV6MulticastAddress(targetAddr) {
			received.invalid.Increment()
			return
		}

		var it header.NDPOptionIterator
		{
			var err error
			it, err = ns.Options().Iter(false /* check */)
			if err != nil {
				// Options are not valid as per the wire format, silently drop the
				// packet.
				received.invalid.Increment()
				return
			}
		}

		if e.hasTentativeAddr(targetAddr) {
			// If the target address is tentative and the source of the packet is a
			// unicast (specified) address, then the source of the packet is
			// attempting to perform address resolution on the target. In this case,
			// the solicitation is silently ignored, as per RFC 4862 section 5.4.3.
			//
			// If the target address is tentative and the source of the packet is the
			// unspecified address (::), then we know another node is also performing
			// DAD for the same address (since the target address is tentative for us,
			// we know we are also performing DAD on it). In this case we let the
			// stack know so it can handle such a scenario and do nothing further with
			// the NS.
			if srcAddr == header.IPv6Any {
				var nonce []byte
				for {
					opt, done, err := it.Next()
					if err != nil {
						received.invalid.Increment()
						return
					}
					if done {
						break
					}
					if n, ok := opt.(header.NDPNonceOption); ok {
						nonce = n.Nonce()
						break
					}
				}

				// Since this is a DAD message we know the sender does not actually hold
				// the target address so there is no "holder".
				var holderLinkAddress tcpip.LinkAddress

				// We would get an error if the address no longer exists or the address
				// is no longer tentative (DAD resolved between the call to
				// hasTentativeAddr and this point). Both of these are valid scenarios:
				//   1) An address may be removed at any time.
				//   2) As per RFC 4862 section 5.4, DAD is not a perfect:
				//       "Note that the method for detecting duplicates
				//        is not completely reliable, and it is possible that duplicate
				//        addresses will still exist"
				//
				// TODO(gvisor.dev/issue/4046): Handle the scenario when a duplicate
				// address is detected for an assigned address.
				switch err := e.dupTentativeAddrDetected(targetAddr, holderLinkAddress, nonce); err.(type) {
				case nil, *tcpip.ErrBadAddress, *tcpip.ErrInvalidEndpointState:
				default:
					panic(fmt.Sprintf("unexpected error handling duplicate tentative address: %s", err))
				}
			}

			// Do not handle neighbor solicitations targeted to an address that is
			// tentative on the NIC any further.
			return
		}

		// At this point we know that the target address is not tentative on the NIC
		// so the packet is processed as defined in RFC 4861, as per RFC 4862
		// section 5.4.3.

		// Is the NS targeting us?
		if !e.checkLocalAddress(targetAddr) {
			return
		}

		sourceLinkAddr, ok := getSourceLinkAddr(it)
		if !ok {
			received.invalid.Increment()
			return
		}

		// As per RFC 4861 section 4.3, the Source Link-Layer Address Option MUST
		// NOT be included when the source IP address is the unspecified address.
		// Otherwise, on link layers that have addresses this option MUST be
		// included in multicast solicitations and SHOULD be included in unicast
		// solicitations.
		unspecifiedSource := srcAddr == header.IPv6Any
		if len(sourceLinkAddr) == 0 {
			if header.IsV6MulticastAddress(dstAddr) && !unspecifiedSource {
				received.invalid.Increment()
				return
			}
		} else if unspecifiedSource {
			received.invalid.Increment()
			return
		} else {
			switch err := e.nic.HandleNeighborProbe(ProtocolNumber, srcAddr, sourceLinkAddr); err.(type) {
			case nil:
			case *tcpip.ErrNotSupported:
			// The stack may support ICMPv6 but the NIC may not need link resolution.
			default:
				panic(fmt.Sprintf("unexpected error when informing NIC of neighbor probe message: %s", err))
			}
		}

		// As per RFC 4861 section 7.1.1:
		//   A node MUST silently discard any received Neighbor Solicitation
		//   messages that do not satisfy all of the following validity checks:
		//    ...
		//    - If the IP source address is the unspecified address, the IP
		//      destination address is a solicited-node multicast address.
		if unspecifiedSource && !header.IsSolicitedNodeAddr(dstAddr) {
			received.invalid.Increment()
			return
		}

		// As per RFC 4861 section 7.2.4:
		//
		//   If the source of the solicitation is the unspecified address, the node
		//   MUST [...] and multicast the advertisement to the all-nodes address.
		//
		remoteAddr := srcAddr
		if unspecifiedSource {
			remoteAddr = header.IPv6AllNodesMulticastAddress
		}

		// Even if we were able to receive a packet from some remote, we may not
		// have a route to it - the remote may be blocked via routing rules. We must
		// always consult our routing table and find a route to the remote before
		// sending any packet.
		r, err := e.protocol.stack.FindRoute(e.nic.ID(), targetAddr, remoteAddr, ProtocolNumber, false /* multicastLoop */)
		if err != nil {
			// If we cannot find a route to the destination, silently drop the packet.
			return
		}
		defer r.Release()

		// If the NS has a source link-layer option, resolve the route immediately
		// to avoid querying the neighbor table when the neighbor entry was updated
		// as probing the neighbor table for a link address will transition the
		// entry's state from stale to delay.
		//
		// Note, if the source link address is unspecified and this is a unicast
		// solicitation, we may need to perform neighbor discovery to send the
		// neighbor advertisement response. This is expected as per RFC 4861 section
		// 7.2.4:
		//
		//   Because unicast Neighbor Solicitations are not required to include a
		//   Source Link-Layer Address, it is possible that a node sending a
		//   solicited Neighbor Advertisement does not have a corresponding link-
		//   layer address for its neighbor in its Neighbor Cache. In such
		//   situations, a node will first have to use Neighbor Discovery to
		//   determine the link-layer address of its neighbor (i.e., send out a
		//   multicast Neighbor Solicitation).
		//
		if len(sourceLinkAddr) != 0 {
			r.ResolveWith(sourceLinkAddr)
		}

		optsSerializer := header.NDPOptionsSerializer{
			header.NDPTargetLinkLayerAddressOption(e.nic.LinkAddress()),
		}
		neighborAdvertSize := header.ICMPv6NeighborAdvertMinimumSize + optsSerializer.Length()
		pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{
			ReserveHeaderBytes: int(r.MaxHeaderLength()) + neighborAdvertSize,
		})
		defer pkt.DecRef()
		pkt.TransportProtocolNumber = header.ICMPv6ProtocolNumber
		packet := header.ICMPv6(pkt.TransportHeader().Push(neighborAdvertSize))
		packet.SetType(header.ICMPv6NeighborAdvert)
		na := header.NDPNeighborAdvert(packet.MessageBody())

		// As per RFC 4861 section 7.2.4:
		//
		//   If the source of the solicitation is the unspecified address, the node
		//   MUST set the Solicited flag to zero and [..]. Otherwise, the node MUST
		//   set the Solicited flag to one and [..].
		//
		na.SetSolicitedFlag(!unspecifiedSource)
		na.SetOverrideFlag(true)
		na.SetTargetAddress(targetAddr)
		na.Options().Serialize(optsSerializer)
		packet.SetChecksum(header.ICMPv6Checksum(header.ICMPv6ChecksumParams{
			Header: packet,
			Src:    r.LocalAddress(),
			Dst:    r.RemoteAddress(),
		}))

		// RFC 4861 Neighbor Discovery for IP version 6 (IPv6)
		//
		// 7.1.2. Validation of Neighbor Advertisements
		//
		// The IP Hop Limit field has a value of 255, i.e., the packet
		// could not possibly have been forwarded by a router.
		if err := r.WritePacket(stack.NetworkHeaderParams{Protocol: header.ICMPv6ProtocolNumber, TTL: header.NDPHopLimit, TOS: stack.DefaultTOS}, pkt); err != nil {
			sent.dropped.Increment()
			return
		}
		sent.neighborAdvert.Increment()

	case header.ICMPv6NeighborAdvert:
		received.neighborAdvert.Increment()
		if !isNDPValid() || len(h) < header.ICMPv6NeighborAdvertMinimumSize {
			received.invalid.Increment()
			return
		}

		na := header.NDPNeighborAdvert(h.MessageBody())

		it, err := na.Options().Iter(false /* check */)
		if err != nil {
			// If we have a malformed NDP NA option, drop the packet.
			received.invalid.Increment()
			return
		}

		targetLinkAddr, ok := getTargetLinkAddr(it)
		if !ok {
			received.invalid.Increment()
			return
		}

		targetAddr := na.TargetAddress()

		e.dad.mu.Lock()
		e.dad.mu.dad.StopLocked(targetAddr, &stack.DADDupAddrDetected{HolderLinkAddress: targetLinkAddr})
		e.dad.mu.Unlock()

		if e.hasTentativeAddr(targetAddr) {
			// We only send a nonce value in DAD messages to check for loopedback
			// messages so we use the empty nonce value here.
			var nonce []byte

			// We just got an NA from a node that owns an address we are performing
			// DAD on, implying the address is not unique. In this case we let the
			// stack know so it can handle such a scenario and do nothing furthur with
			// the NDP NA.
			//
			// We would get an error if the address no longer exists or the address
			// is no longer tentative (DAD resolved between the call to
			// hasTentativeAddr and this point). Both of these are valid scenarios:
			//   1) An address may be removed at any time.
			//   2) As per RFC 4862 section 5.4, DAD is not a perfect:
			//       "Note that the method for detecting duplicates
			//        is not completely reliable, and it is possible that duplicate
			//        addresses will still exist"
			//
			// TODO(gvisor.dev/issue/4046): Handle the scenario when a duplicate
			// address is detected for an assigned address.
			switch err := e.dupTentativeAddrDetected(targetAddr, targetLinkAddr, nonce); err.(type) {
			case nil, *tcpip.ErrBadAddress, *tcpip.ErrInvalidEndpointState:
				return
			default:
				panic(fmt.Sprintf("unexpected error handling duplicate tentative address: %s", err))
			}
		}

		// At this point we know that the target address is not tentative on the
		// NIC. However, the target address may still be assigned to the NIC but not
		// tentative (it could be permanent). Such a scenario is beyond the scope of
		// RFC 4862. As such, we simply ignore such a scenario for now and proceed
		// as normal.
		//
		// TODO(b/143147598): Handle the scenario described above. Also inform the
		// netstack integration that a duplicate address was detected outside of
		// DAD.

		// As per RFC 4861 section 7.1.2:
		//   A node MUST silently discard any received Neighbor Advertisement
		//   messages that do not satisfy all of the following validity checks:
		//    ...
		//    - If the IP Destination Address is a multicast address the
		// 	    Solicited flag is zero.
		if header.IsV6MulticastAddress(dstAddr) && na.SolicitedFlag() {
			received.invalid.Increment()
			return
		}

		// If the NA message has the target link layer option, update the link
		// address cache with the link address for the target of the message.
		switch err := e.nic.HandleNeighborConfirmation(ProtocolNumber, targetAddr, targetLinkAddr, stack.ReachabilityConfirmationFlags{
			Solicited: na.SolicitedFlag(),
			Override:  na.OverrideFlag(),
			IsRouter:  na.RouterFlag(),
		}); err.(type) {
		case nil:
		case *tcpip.ErrNotSupported:
		// The stack may support ICMPv6 but the NIC may not need link resolution.
		default:
			panic(fmt.Sprintf("unexpected error when informing NIC of neighbor confirmation message: %s", err))
		}

	case header.ICMPv6EchoRequest:
		received.echoRequest.Increment()
		// As per RFC 4291 section 2.7, multicast addresses must not be used as
		// source addresses in IPv6 packets.
		localAddr := dstAddr
		if header.IsV6MulticastAddress(dstAddr) {
			localAddr = ""
		}

		r, err := e.protocol.stack.FindRoute(e.nic.ID(), localAddr, srcAddr, ProtocolNumber, false /* multicastLoop */)
		if err != nil {
			// If we cannot find a route to the destination, silently drop the packet.
			return
		}
		defer r.Release()

		if !e.protocol.allowICMPReply(header.ICMPv6EchoReply) {
			sent.rateLimited.Increment()
			return
		}

		replyPkt := stack.NewPacketBuffer(stack.PacketBufferOptions{
			ReserveHeaderBytes: int(r.MaxHeaderLength()) + header.ICMPv6EchoMinimumSize,
			Payload:            pkt.Data().ToBuffer(),
		})
		defer replyPkt.DecRef()
		icmp := header.ICMPv6(replyPkt.TransportHeader().Push(header.ICMPv6EchoMinimumSize))
		replyPkt.TransportProtocolNumber = header.ICMPv6ProtocolNumber
		copy(icmp, h)
		icmp.SetType(header.ICMPv6EchoReply)
		replyData := replyPkt.Data()
		icmp.SetChecksum(header.ICMPv6Checksum(header.ICMPv6ChecksumParams{
			Header:      icmp,
			Src:         r.LocalAddress(),
			Dst:         r.RemoteAddress(),
			PayloadCsum: replyData.Checksum(),
			PayloadLen:  replyData.Size(),
		}))
		replyTClass, _ := iph.TOS()
		if err := r.WritePacket(stack.NetworkHeaderParams{
			Protocol: header.ICMPv6ProtocolNumber,
			TTL:      r.DefaultTTL(),
			// Even though RFC 4443 does not mention anything about it, Linux uses the
			// TrafficClass of the received echo request when replying.
			// https://github.com/torvalds/linux/blob/0280e3c58f9/net/ipv6/icmp.c#L797
			TOS: replyTClass,
		}, replyPkt); err != nil {
			sent.dropped.Increment()
			return
		}
		sent.echoReply.Increment()

	case header.ICMPv6EchoReply:
		received.echoReply.Increment()
		if len(h) < header.ICMPv6EchoMinimumSize {
			received.invalid.Increment()
			return
		}
		e.dispatcher.DeliverTransportPacket(header.ICMPv6ProtocolNumber, pkt)

	case header.ICMPv6TimeExceeded:
		received.timeExceeded.Increment()

	case header.ICMPv6ParamProblem:
		received.paramProblem.Increment()

	case header.ICMPv6RouterSolicit:
		received.routerSolicit.Increment()

		//
		// Validate the RS as per RFC 4861 section 6.1.1.
		//

		// Is the NDP payload of sufficient size to hold a Router Solictation?
		if !isNDPValid() || len(h)-header.ICMPv6HeaderSize < header.NDPRSMinimumSize {
			received.invalid.Increment()
			return
		}

		if !e.Forwarding() {
			received.routerOnlyPacketsDroppedByHost.Increment()
			return
		}

		rs := header.NDPRouterSolicit(h.MessageBody())
		it, err := rs.Options().Iter(false /* check */)
		if err != nil {
			// Options are not valid as per the wire format, silently drop the packet.
			received.invalid.Increment()
			return
		}

		sourceLinkAddr, ok := getSourceLinkAddr(it)
		if !ok {
			received.invalid.Increment()
			return
		}

		// If the RS message has the source link layer option, update the link
		// address cache with the link address for the source of the message.
		if len(sourceLinkAddr) != 0 {
			// As per RFC 4861 section 4.1, the Source Link-Layer Address Option MUST
			// NOT be included when the source IP address is the unspecified address.
			// Otherwise, it SHOULD be included on link layers that have addresses.
			if srcAddr == header.IPv6Any {
				received.invalid.Increment()
				return
			}

			// A RS with a specified source IP address modifies the neighbor table
			// in the same way a regular probe would.
			switch err := e.nic.HandleNeighborProbe(ProtocolNumber, srcAddr, sourceLinkAddr); err.(type) {
			case nil:
			case *tcpip.ErrNotSupported:
			// The stack may support ICMPv6 but the NIC may not need link resolution.
			default:
				panic(fmt.Sprintf("unexpected error when informing NIC of neighbor probe message: %s", err))
			}
		}

	case header.ICMPv6RouterAdvert:
		received.routerAdvert.Increment()

		//
		// Validate the RA as per RFC 4861 section 6.1.2.
		//

		// Is the NDP payload of sufficient size to hold a Router Advertisement?
		if !isNDPValid() || len(h)-header.ICMPv6HeaderSize < header.NDPRAMinimumSize {
			received.invalid.Increment()
			return
		}

		routerAddr := srcAddr

		// Is the IP Source Address a link-local address?
		if !header.IsV6LinkLocalUnicastAddress(routerAddr) {
			// ...No, silently drop the packet.
			received.invalid.Increment()
			return
		}

		ra := header.NDPRouterAdvert(h.MessageBody())
		it, err := ra.Options().Iter(false /* check */)
		if err != nil {
			// Options are not valid as per the wire format, silently drop the packet.
			received.invalid.Increment()
			return
		}

		sourceLinkAddr, ok := getSourceLinkAddr(it)
		if !ok {
			received.invalid.Increment()
			return
		}

		//
		// At this point, we have a valid Router Advertisement, as far
		// as RFC 4861 section 6.1.2 is concerned.
		//

		// If the RA has the source link layer option, update the link address
		// cache with the link address for the advertised router.
		if len(sourceLinkAddr) != 0 {
			switch err := e.nic.HandleNeighborProbe(ProtocolNumber, routerAddr, sourceLinkAddr); err.(type) {
			case nil:
			case *tcpip.ErrNotSupported:
			// The stack may support ICMPv6 but the NIC may not need link resolution.
			default:
				panic(fmt.Sprintf("unexpected error when informing NIC of neighbor probe message: %s", err))
			}
		}

		e.mu.Lock()
		e.mu.ndp.handleRA(routerAddr, ra)
		e.mu.Unlock()

	case header.ICMPv6RedirectMsg:
		// TODO(gvisor.dev/issue/2285): Call `e.nud.HandleProbe` after validating
		// this redirect message, as per RFC 4871 section 7.3.3:
		//
		//    "A Neighbor Cache entry enters the STALE state when created as a
		//    result of receiving packets other than solicited Neighbor
		//    Advertisements (i.e., Router Solicitations, Router Advertisements,
		//    Redirects, and Neighbor Solicitations).  These packets contain the
		//    link-layer address of either the sender or, in the case of Redirect,
		//    the redirection target.  However, receipt of these link-layer
		//    addresses does not confirm reachability of the forward-direction path
		//    to that node.  Placing a newly created Neighbor Cache entry for which
		//    the link-layer address is known in the STALE state provides assurance
		//    that path failures are detected quickly. In addition, should a cached
		//    link-layer address be modified due to receiving one of the above
		//    messages, the state SHOULD also be set to STALE to provide prompt
		//    verification that the path to the new link-layer address is working."
		received.redirectMsg.Increment()
		if !isNDPValid() {
			received.invalid.Increment()
			return
		}

	case header.ICMPv6MulticastListenerQuery, header.ICMPv6MulticastListenerReport, header.ICMPv6MulticastListenerDone:
		switch icmpType {
		case header.ICMPv6MulticastListenerQuery:
			received.multicastListenerQuery.Increment()
		case header.ICMPv6MulticastListenerReport:
			received.multicastListenerReport.Increment()
		case header.ICMPv6MulticastListenerDone:
			received.multicastListenerDone.Increment()
		default:
			panic(fmt.Sprintf("unrecognized MLD message = %d", icmpType))
		}

		if !isMLDValid(pkt, iph, routerAlert) {
			received.invalid.Increment()
			return
		}

		switch icmpType {
		case header.ICMPv6MulticastListenerQuery:
			e.mu.Lock()
			e.mu.mld.handleMulticastListenerQuery(header.MLD(h.MessageBody()))
			e.mu.Unlock()
		case header.ICMPv6MulticastListenerReport:
			e.mu.Lock()
			e.mu.mld.handleMulticastListenerReport(header.MLD(h.MessageBody()))
			e.mu.Unlock()
		case header.ICMPv6MulticastListenerDone:
		default:
			panic(fmt.Sprintf("unrecognized MLD message = %d", icmpType))
		}

	default:
		received.unrecognized.Increment()
	}
}

// LinkAddressProtocol implements stack.LinkAddressResolver.
func (*endpoint) LinkAddressProtocol() tcpip.NetworkProtocolNumber {
	return header.IPv6ProtocolNumber
}

// LinkAddressRequest implements stack.LinkAddressResolver.
func (e *endpoint) LinkAddressRequest(targetAddr, localAddr tcpip.Address, remoteLinkAddr tcpip.LinkAddress) tcpip.Error {
	remoteAddr := targetAddr
	if len(remoteLinkAddr) == 0 {
		remoteAddr = header.SolicitedNodeAddr(targetAddr)
		remoteLinkAddr = header.EthernetAddressFromMulticastIPv6Address(remoteAddr)
	}

	if len(localAddr) == 0 {
		// Find an address that we can use as our source address.
		addressEndpoint := e.AcquireOutgoingPrimaryAddress(remoteAddr, false /* allowExpired */)
		if addressEndpoint == nil {
			return &tcpip.ErrNetworkUnreachable{}
		}

		localAddr = addressEndpoint.AddressWithPrefix().Address
		addressEndpoint.DecRef()
	} else if !e.checkLocalAddress(localAddr) {
		// The provided local address is not assigned to us.
		return &tcpip.ErrBadLocalAddress{}
	}

	return e.sendNDPNS(localAddr, remoteAddr, targetAddr, remoteLinkAddr, header.NDPOptionsSerializer{
		header.NDPSourceLinkLayerAddressOption(e.nic.LinkAddress()),
	})
}

// ResolveStaticAddress implements stack.LinkAddressResolver.
func (*endpoint) ResolveStaticAddress(addr tcpip.Address) (tcpip.LinkAddress, bool) {
	if header.IsV6MulticastAddress(addr) {
		return header.EthernetAddressFromMulticastIPv6Address(addr), true
	}
	return tcpip.LinkAddress([]byte(nil)), false
}

// ======= ICMP Error packet generation =========

// icmpReason is a marker interface for IPv6 specific ICMP errors.
type icmpReason interface {
	isICMPReason()
	// respondToMulticast indicates whether this error falls under the exception
	// outlined by RFC 4443 section 2.4 point e.3 exception 2:
	//
	//   (e.3) A packet destined to an IPv6 multicast address. (There are two
	//   exceptions to this rule: (1) the Packet Too Big Message (Section 3.2) to
	//   allow Path MTU discovery to work for IPv6 multicast, and (2) the Parameter
	//   Problem Message, Code 2 (Section 3.4) reporting an unrecognized IPv6
	//   option (see Section 4.2 of [IPv6]) that has the Option Type highest-
	//   order two bits set to 10).
	respondsToMulticast() bool
}

// icmpReasonParameterProblem is an error during processing of extension headers
// or the fixed header defined in RFC 4443 section 3.4.
type icmpReasonParameterProblem struct {
	code header.ICMPv6Code

	// pointer is defined in the RFC 4443 setion 3.4 which reads:
	//
	//  Pointer         Identifies the octet offset within the invoking packet
	//                  where the error was detected.
	//
	//                  The pointer will point beyond the end of the ICMPv6
	//                  packet if the field in error is beyond what can fit
	//                  in the maximum size of an ICMPv6 error message.
	pointer uint32

	respondToMulticast bool
}

func (*icmpReasonParameterProblem) isICMPReason() {}

func (p *icmpReasonParameterProblem) respondsToMulticast() bool {
	return p.respondToMulticast
}

// icmpReasonAdministrativelyProhibited is an error where the destination is
// administratively prohibited.
type icmpReasonAdministrativelyProhibited struct{}

func (*icmpReasonAdministrativelyProhibited) isICMPReason() {}

func (*icmpReasonAdministrativelyProhibited) respondsToMulticast() bool {
	return false
}

// icmpReasonPortUnreachable is an error where the transport protocol has no
// listener and no alternative means to inform the sender.
type icmpReasonPortUnreachable struct{}

func (*icmpReasonPortUnreachable) isICMPReason() {}

func (*icmpReasonPortUnreachable) respondsToMulticast() bool {
	return false
}

// icmpReasonNetUnreachable is an error where no route can be found to the
// network of the final destination.
type icmpReasonNetUnreachable struct{}

func (*icmpReasonNetUnreachable) isICMPReason() {}

func (*icmpReasonNetUnreachable) respondsToMulticast() bool {
	return false
}

// icmpReasonHostUnreachable is an error in which the host specified in the
// internet destination field of the datagram is unreachable.
type icmpReasonHostUnreachable struct{}

func (*icmpReasonHostUnreachable) isICMPReason() {}

func (*icmpReasonHostUnreachable) respondsToMulticast() bool {
	return false
}

// icmpReasonFragmentationNeeded is an error where a packet is to big to be sent
// out through the outgoing MTU, as per RFC 4443 page 9, Packet Too Big Message.
type icmpReasonPacketTooBig struct{}

func (*icmpReasonPacketTooBig) isICMPReason() {}

func (*icmpReasonPacketTooBig) respondsToMulticast() bool {
	return true
}

// icmpReasonHopLimitExceeded is an error where a packet's hop limit exceeded in
// transit to its final destination, as per RFC 4443 section 3.3.
type icmpReasonHopLimitExceeded struct{}

func (*icmpReasonHopLimitExceeded) isICMPReason() {}

func (*icmpReasonHopLimitExceeded) respondsToMulticast() bool {
	return false
}

// icmpReasonReassemblyTimeout is an error where insufficient fragments are
// received to complete reassembly of a packet within a configured time after
// the reception of the first-arriving fragment of that packet.
type icmpReasonReassemblyTimeout struct{}

func (*icmpReasonReassemblyTimeout) isICMPReason() {}

func (*icmpReasonReassemblyTimeout) respondsToMulticast() bool {
	return false
}

// returnError takes an error descriptor and generates the appropriate ICMP
// error packet for IPv6 and sends it.
func (p *protocol) returnError(reason icmpReason, pkt stack.PacketBufferPtr, deliveredLocally bool) tcpip.Error {
	origIPHdr := header.IPv6(pkt.NetworkHeader().Slice())
	origIPHdrSrc := origIPHdr.SourceAddress()
	origIPHdrDst := origIPHdr.DestinationAddress()

	// Only send ICMP error if the address is not a multicast v6
	// address and the source is not the unspecified address.
	//
	// There are exceptions to this rule.
	// See: point e.3) RFC 4443 section-2.4
	//
	//	 (e) An ICMPv6 error message MUST NOT be originated as a result of
	//       receiving the following:
	//
	//       (e.1) An ICMPv6 error message.
	//
	//       (e.2) An ICMPv6 redirect message [IPv6-DISC].
	//
	//       (e.3) A packet destined to an IPv6 multicast address.  (There are
	//             two exceptions to this rule: (1) the Packet Too Big Message
	//             (Section 3.2) to allow Path MTU discovery to work for IPv6
	//             multicast, and (2) the Parameter Problem Message, Code 2
	//             (Section 3.4) reporting an unrecognized IPv6 option (see
	//             Section 4.2 of [IPv6]) that has the Option Type highest-
	//             order two bits set to 10).
	//
	allowResponseToMulticast := reason.respondsToMulticast()
	isOrigDstMulticast := header.IsV6MulticastAddress(origIPHdrDst)
	if (!allowResponseToMulticast && isOrigDstMulticast) || origIPHdrSrc == header.IPv6Any {
		return nil
	}

	// If the packet wasn't delivered locally, do not use the packet's destination
	// address as the response's source address as we should not own the
	// destination address of a packet we are forwarding.
	//
	// If the packet was originally destined to a multicast address, then do not
	// use the packet's destination address as the source for the response ICMP
	// packet as "multicast addresses must not be used as source addresses in IPv6
	// packets", as per RFC 4291 section 2.7.
	localAddr := origIPHdrDst
	if !deliveredLocally || isOrigDstMulticast {
		localAddr = ""
	}
	// Even if we were able to receive a packet from some remote, we may not have
	// a route to it - the remote may be blocked via routing rules. We must always
	// consult our routing table and find a route to the remote before sending any
	// packet.
	route, err := p.stack.FindRoute(pkt.NICID, localAddr, origIPHdrSrc, ProtocolNumber, false /* multicastLoop */)
	if err != nil {
		return err
	}
	defer route.Release()

	p.mu.Lock()
	// We retrieve an endpoint using the newly constructed route's NICID rather
	// than the packet's NICID. The packet's NICID corresponds to the NIC on
	// which it arrived, which isn't necessarily the same as the NIC on which it
	// will be transmitted. On the other hand, the route's NIC *is* guaranteed
	// to be the NIC on which the packet will be transmitted.
	netEP, ok := p.mu.eps[route.NICID()]
	p.mu.Unlock()
	if !ok {
		return &tcpip.ErrNotConnected{}
	}

	if pkt.TransportProtocolNumber == header.ICMPv6ProtocolNumber {
		if typ := header.ICMPv6(pkt.TransportHeader().Slice()).Type(); typ.IsErrorType() || typ == header.ICMPv6RedirectMsg {
			return nil
		}
	}

	sent := netEP.stats.icmp.packetsSent
	icmpType, icmpCode, counter, typeSpecific := func() (header.ICMPv6Type, header.ICMPv6Code, tcpip.MultiCounterStat, uint32) {
		switch reason := reason.(type) {
		case *icmpReasonParameterProblem:
			return header.ICMPv6ParamProblem, reason.code, sent.paramProblem, reason.pointer
		case *icmpReasonAdministrativelyProhibited:
			return header.ICMPv6DstUnreachable, header.ICMPv6Prohibited, sent.dstUnreachable, 0
		case *icmpReasonPortUnreachable:
			return header.ICMPv6DstUnreachable, header.ICMPv6PortUnreachable, sent.dstUnreachable, 0
		case *icmpReasonNetUnreachable:
			return header.ICMPv6DstUnreachable, header.ICMPv6NetworkUnreachable, sent.dstUnreachable, 0
		case *icmpReasonHostUnreachable:
			return header.ICMPv6DstUnreachable, header.ICMPv6AddressUnreachable, sent.dstUnreachable, 0
		case *icmpReasonPacketTooBig:
			return header.ICMPv6PacketTooBig, header.ICMPv6UnusedCode, sent.packetTooBig, 0
		case *icmpReasonHopLimitExceeded:
			return header.ICMPv6TimeExceeded, header.ICMPv6HopLimitExceeded, sent.timeExceeded, 0
		case *icmpReasonReassemblyTimeout:
			return header.ICMPv6TimeExceeded, header.ICMPv6ReassemblyTimeout, sent.timeExceeded, 0
		default:
			panic(fmt.Sprintf("unsupported ICMP type %T", reason))
		}
	}()

	if !p.allowICMPReply(icmpType) {
		sent.rateLimited.Increment()
		return nil
	}

	network, transport := pkt.NetworkHeader().View(), pkt.TransportHeader().View()

	// As per RFC 4443 section 2.4
	//
	//    (c) Every ICMPv6 error message (type < 128) MUST include
	//    as much of the IPv6 offending (invoking) packet (the
	//    packet that caused the error) as possible without making
	//    the error message packet exceed the minimum IPv6 MTU
	//    [IPv6].
	mtu := int(route.MTU())
	const maxIPv6Data = header.IPv6MinimumMTU - header.IPv6FixedHeaderSize
	if mtu > maxIPv6Data {
		mtu = maxIPv6Data
	}
	available := mtu - header.ICMPv6ErrorHeaderSize
	if available < header.IPv6MinimumSize {
		return nil
	}
	payloadLen := network.Size() + transport.Size() + pkt.Data().Size()
	if payloadLen > available {
		payloadLen = available
	}
	payload := bufferv2.MakeWithView(network)
	payload.Append(transport)
	dataBuf := pkt.Data().ToBuffer()
	payload.Merge(&dataBuf)
	payload.Truncate(int64(payloadLen))

	newPkt := stack.NewPacketBuffer(stack.PacketBufferOptions{
		ReserveHeaderBytes: int(route.MaxHeaderLength()) + header.ICMPv6ErrorHeaderSize,
		Payload:            payload,
	})
	defer newPkt.DecRef()
	newPkt.TransportProtocolNumber = header.ICMPv6ProtocolNumber

	icmpHdr := header.ICMPv6(newPkt.TransportHeader().Push(header.ICMPv6DstUnreachableMinimumSize))
	icmpHdr.SetType(icmpType)
	icmpHdr.SetCode(icmpCode)
	icmpHdr.SetTypeSpecific(typeSpecific)

	pktData := newPkt.Data()
	icmpHdr.SetChecksum(header.ICMPv6Checksum(header.ICMPv6ChecksumParams{
		Header:      icmpHdr,
		Src:         route.LocalAddress(),
		Dst:         route.RemoteAddress(),
		PayloadCsum: pktData.Checksum(),
		PayloadLen:  pktData.Size(),
	}))
	if err := route.WritePacket(
		stack.NetworkHeaderParams{
			Protocol: header.ICMPv6ProtocolNumber,
			TTL:      route.DefaultTTL(),
			TOS:      stack.DefaultTOS,
		},
		newPkt,
	); err != nil {
		sent.dropped.Increment()
		return err
	}
	counter.Increment()
	return nil
}

// OnReassemblyTimeout implements fragmentation.TimeoutHandler.
func (p *protocol) OnReassemblyTimeout(pkt stack.PacketBufferPtr) {
	// OnReassemblyTimeout sends a Time Exceeded Message as per RFC 2460 Section
	// 4.5:
	//
	//   If the first fragment (i.e., the one with a Fragment Offset of zero) has
	//   been received, an ICMP Time Exceeded -- Fragment Reassembly Time Exceeded
	//   message should be sent to the source of that fragment.
	if !pkt.IsNil() {
		p.returnError(&icmpReasonReassemblyTimeout{}, pkt, true /* deliveredLocally */)
	}
}


text:
package main

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestUserAssignation(t *testing.T) {
	user1 := assignment{Email: "fake1@gmail.com", Days: []string{}}
	user2 := assignment{Email: "fake2@gmail.com", Days: []string{}}
	user3 := assignment{Email: "fake3@gmail.com", Days: []string{}}

	var allUsers []assignment
	allUsers = append(allUsers, user1, user2, user3)

	userAssignation, index, err := createUserAssignation(allUsers, 3, 0)
	if err != nil {
		t.Fatal(err)
	}
	assert.Equal(t, allUsers, userAssignation)
	assert.Equal(t, 3, index)
}

func TestUserAssignationStartingOnNonZeroIndexn(t *testing.T) {
	user1 := assignment{Email: "fake1@gmail.com", Days: []string{}}
	user2 := assignment{Email: "fake2@gmail.com", Days: []string{}}
	user3 := assignment{Email: "fake3@gmail.com", Days: []string{}}

	var allUsers []assignment
	allUsers = append(allUsers, user1, user2, user3)

	userAssignation, index, err := createUserAssignation(allUsers, 3, 2)
	if err != nil {
		t.Fatal(err)
	}
	var expected []assignment
	expected = append(expected, user3, user1, user2)
	assert.Equal(t, expected, userAssignation)
	assert.Equal(t, 2, index)
}

func TestUserAssignationZeroUsers(t *testing.T) {

	var allUsers []assignment

	userAssignation, index, err := createUserAssignation(allUsers, 3, 2)
	if err != nil {
		t.Fatal(err)
	}

	assert.Equal(t, []assignment([]assignment(nil)), userAssignation)
	assert.Equal(t, 0, index)
}

func TestUserAssignationMoreSlotsThanUsers(t *testing.T) {

	user1 := assignment{Email: "fake1@gmail.com", Days: []string{}}
	user2 := assignment{Email: "fake2@gmail.com", Days: []string{}}
	user3 := assignment{Email: "fake3@gmail.com", Days: []string{}}

	var allUsers []assignment
	allUsers = append(allUsers, user1, user2, user3)

	userAssignation, index, err := createUserAssignation(allUsers, 10, 0)
	if err != nil {
		t.Fatal(err)
	}

	assert.Equal(t, allUsers, userAssignation)
	assert.Equal(t, 0, index)
}


text:
package nl.gridline.zieook.inx.movielens.items;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.hadoop.io.Writable;
import org.apache.mahout.math.Varint;

/**
 * [purpose]
 *

 * Project zieook-movielens

 * RecommendationElement.java created 4 mrt. 2011
 *

 * Copyright, all rights reserved 2011 GridLine Amsterdam
 * @author Job
 * @version $Revision:$, $Date:$
 */
public class RecommendationElement implements Writable, Cloneable
{

	private int _itemIndex;
	private double _similarityValue;

	public RecommendationElement()
	{

	}

	public RecommendationElement(int index, double value)
	{
		this._itemIndex = index;
		this._similarityValue = value;
	}

	public int getItemIndex()
	{
		return _itemIndex;
	}

	public double getSimilarityValue()
	{
		return _similarityValue;
	}

	@Override
	public RecommendationElement clone()
	{
		return new RecommendationElement(_itemIndex, _similarityValue);
	}

	@Override
	public void readFields(DataInput in) throws IOException
	{
		_itemIndex = Varint.readSignedVarInt(in);
		_similarityValue = in.readDouble();
	}

	@Override
	public void write(DataOutput out) throws IOException
	{
		Varint.writeSignedVarInt(_itemIndex, out);
		out.writeDouble(_similarityValue);
	}

	@Override
	public int hashCode()
	{
		return _itemIndex;
	}

	@Override
	public boolean equals(Object other)
	{
		return other instanceof RecommendationElement && _itemIndex == ((RecommendationElement) other)._itemIndex;
	}

	@Override
	public String toString()
	{
		return (String.format("%d:%f", _itemIndex, _similarityValue));
	}

}


text:
* { margin: 0; padding: 0; }
body { padding: 50px; background: #4c4c4c url(../../../../images/nvidia.com/grad1.png) 0 0 repeat-x; color: #d9d9d9; font: 14px/normal Tahoma, Arial, Helvetica, sans-serif; }
h1 { margin-bottom: .5em; border-bottom: solid 1px #d9d9d9; font-family: Arial, Helvetica, sans-serif; font-weight: normal; font-size: 180%; text-indent: 5px; letter-spacing: -1px; }
cite { float: right; }
ul.classic { list-style: disc; margin-bottom: 1em; padding-left: 2em; }
div.section { clear: both; padding-top: 50px; }

.table1 { float: right; margin-bottom: 2em; border: solid 1px #eee; }
.table1 caption { color: #fff; text-align: center; padding-bottom: 5px; }
.table1 th, .table1 td { padding: 7px; }
.table1 th, .table1 thead td { background-color: lightyellow; color: #000; }
.table1 tbody td { background-color: #fff; color: #000; }
.table1 tbody th { text-align: right; }

#wmfg { clear: both; float: left; }


text:
package org.radargun.reporting.html;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

import org.radargun.config.Cluster;
import org.radargun.config.Property;
import org.radargun.logging.Log;
import org.radargun.logging.LogFactory;
import org.radargun.reporting.Timeline;

/**
 * Presents {@link Timeline timelines} from all workers and main.
 * Uses {@link TimelineChart} to generate image files.
 *
 * @author Radim Vansa <rvansa@redhat.com>
 */
public class TimelineDocument extends HtmlDocument {
   private static final Log log = LogFactory.getLog(TimelineDocument.class);
   private final Configuration configuration;
   private final String configName;
   private final String title;
   private final Cluster cluster;
   private List<Timeline> timelines;
   private Map<Timeline.Category, Double> minValues = new HashMap<>();
   private Map<Timeline.Category, Double> maxValues = new HashMap<>();
   private Map<Timeline.Category, Integer> valueCategories = new TreeMap<>();
   private Map<String, Integer> eventCategories = new TreeMap<>();
   private Timeline.Category.Type categoryType;
   private long startTimestamp = Long.MAX_VALUE, endTimestamp = Long.MIN_VALUE;

   public TimelineDocument(Configuration configuration, String directory, String configName, String title, List<Timeline> timelines, Timeline.Category.Type categoryType, Cluster cluster) {
      super(directory, categoryType.toString() + "_timeline_" + configName + ".html", title + " Timeline");
      this.title = title;
      this.configuration = configuration;
      this.timelines = new ArrayList<>(timelines);
      this.categoryType = categoryType;
      Collections.sort(this.timelines);
      this.configName = configName;
      this.cluster = cluster;

      for (Timeline timeline : this.timelines) {
         startTimestamp = Math.min(startTimestamp, timeline.getFirstTimestamp());
         endTimestamp = Math.max(endTimestamp, timeline.getLastTimestamp());
         for (String category : timeline.getEventCategories()) {
            if (!eventCategories.containsKey(category)) {
               eventCategories.put(category, eventCategories.size());
            }
         }

         for (Timeline.Category category : timeline.getValueCategories()) {
            if (!valueCategories.containsKey(category)) {
               valueCategories.put(category, valueCategories.size());
            }

            List<Timeline.Value> values = timeline.getValues(category);
            double min = Long.MAX_VALUE, max = Long.MIN_VALUE;
            for (Timeline.Value value : values) {
               double d = value.value.doubleValue();
               max = Math.max(max, d);
               min = Math.min(min, d);
            }
            if (min <= max) {
               Double prevMin = minValues.get(category);
               Double prevMax = maxValues.get(category);
               minValues.put(category, prevMin == null ? min : Math.min(prevMin, min));
               maxValues.put(category, prevMax == null ? max : Math.max(prevMax, max));
            }
         }
      }
      // in order to show event categories, we need at least one value category
      if (valueCategories.isEmpty()) {
         Timeline.Category defaultCategory = Timeline.Category.sysCategory(" ");
         valueCategories.put(defaultCategory, 0);
         minValues.put(defaultCategory, 0d);
         maxValues.put(defaultCategory, 0d);
      }
   }

   @Override
   public String getTitle() {
      return title;
   }

   public String range(final Timeline.Category valueCategory, final int valueCategoryId) {
      Double min = minValues.get(valueCategory);
      if (min == null || min > 0) min = 0d;
      Double max = maxValues.get(valueCategory);
      if (max == null || max < 0) max = 0d;
      minValues.put(valueCategory, min);
      maxValues.put(valueCategory, max);

      return String.format("timeline_%s_%d_range.png", configName, valueCategoryId);
   }

   public String getValueChartFile(int valueCategoryId, int workerIndex) {
      return String.format("timeline_%s_v%d_%d.png", configName, valueCategoryId, workerIndex);
   }

   public Map<Timeline.Category, Integer> getValueCategoriesOfType(String categoryType) {
      return valueCategories.entrySet().stream().filter(e -> e.getKey().getType().toString().equals(categoryType)).collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue(), (v1,v2) -> {
         throw new RuntimeException(String.format("Duplicate key for values %s and %s", v1, v2));
      }, TreeMap::new));
   }

   public void createTestCharts() {
      createReportDirectory();

      final AtomicBoolean firstDomain = new AtomicBoolean(true);
      final String relativeDomainFile = "domain_" + configName + "_relative.png";
      final String absoluteDomainFile = "domain_" + configName + "_absolute.png";
      ArrayList<Future> chartTaskFutures = new ArrayList<>();
      for (Map.Entry<Timeline.Category, Integer> valueEntry : getValueCategoriesOfType(categoryType.toString()).entrySet()) {
         final Timeline.Category valueCategory = valueEntry.getKey();
         final int valueCategoryId = valueEntry.getValue();

         /* Range */
         final String rangeFile = range(valueCategory, valueCategoryId);

         /* Charts */
         final AtomicBoolean firstRange = new AtomicBoolean(true);
         for (Timeline timeline : timelines) {
            List<Timeline.Value> categoryValues = timeline.getValues(valueCategory);
            final List<Timeline.Value> values = categoryValues != null ? categoryValues : Collections.EMPTY_LIST;
            final int workerIndex = timeline.workerIndex;
            final String valueChartFile = getValueChartFile(valueCategoryId, workerIndex);

            chartTaskFutures.add(HtmlReporter.executor.submit(new Callable<Void>() {
               @Override
               public Void call() throws Exception {
                  log.info("Generating chart for " + valueCategory);
                  TimelineChart chart = new TimelineChart();
                  chart.setDimensions(configuration.width, configuration.height);

                  chart.setEvents(values, workerIndex, startTimestamp, endTimestamp, minValues.get(valueCategory) * 1.1, maxValues.get(valueCategory) * 1.1);

                  chart.saveChart(directory + File.separator + valueChartFile);

                  if (firstRange.compareAndSet(true, false)) {
                     chart.saveRange(directory + File.separator + rangeFile);
                  }
                  if (firstDomain.compareAndSet(true, false)) {
                     chart.saveRelativeDomain(directory + File.separator + relativeDomainFile);
                     chart.saveAbsoluteDomain(directory + File.separator + absoluteDomainFile);
                  }
                  return null;
               }
            }));
         }
      }

      for (Timeline timeline : timelines) {
         final int workerIndex = timeline.workerIndex;
         for (String ec : timeline.getEventCategories()) {
            final String eventCategory = ec;
            final List<Timeline.MarkerEvent> events = timeline.getEvents(eventCategory);
            if (events == null) continue;

            chartTaskFutures.add(HtmlReporter.executor.submit(new Callable<Void>() {
               @Override
               public Void call() throws Exception {
                  TimelineChart chart = new TimelineChart();
                  chart.setDimensions(configuration.width, configuration.height);
                  chart.setEvents(events, workerIndex, startTimestamp, endTimestamp, 0, 0);

                  String chartFile = String.format("timeline_%s_e%d_%d.png", configName, eventCategories.get(eventCategory), workerIndex);
                  chart.saveChart(directory + File.separator + chartFile);
                  return null;
               }
            }));
         }
      }
      /* wait until all charts are generated */

      for (Future f : chartTaskFutures) {
         try {
            f.get();
         } catch (Exception e) {
            log.error("Failed to generate on of the charts: ", e);
         }
      }
   }

   /**
    * The following methods are used in Freemarker templates
    * e.g. method getPercentiles() can be used as getPercentiles() or percentiles in template
    */

   public Configuration getConfiguration() {
      return configuration;
   }

   public String getConfigName() {
      return configName;
   }

   public Cluster getCluster() {
      return cluster;
   }

   public List<Timeline> getTimelines() {
      return timelines;
   }

   public Map<Timeline.Category, Double> getMinValues() {
      return minValues;
   }

   public Map<Timeline.Category, Double> getMaxValues() {
      return maxValues;
   }

   public Map<Timeline.Category, Integer> getValueCategories() {
      return valueCategories;
   }

   public Map<String, Integer> getEventCategories() {
      return eventCategories;
   }

   public long getStartTimestamp() {
      return startTimestamp;
   }

   public long getEndTimestamp() {
      return endTimestamp;
   }

   public String generateEventChartFile(int eventCategoryId, int workerIndex) {
      return String.format("timeline_%s_e%d_%d.png", configName, eventCategoryId, workerIndex);
   }

   public String getCheckboxColor(Timeline timeline) {
      return String.format("#%06X", TimelineChart.getColorForIndex(timeline.workerIndex));
   }

   public static class Configuration {
      @Property(name = "chart.width", doc = "Width of the chart in pixels. Default is 1024.")
      private int width = 1024;

      @Property(name = "chart.height", doc = "Height of the chart in pixels. Default is 500.")
      private int height = 500;

      /**
       * The following methods are used in Freemarker templates
       * e.g. method getPercentiles() can be used as getPercentiles() or percentiles in template
       */

      public int getWidth() {
         return width;
      }

      public int getHeight() {
         return height;
      }
   }
}


text:
from PyQt4 import QtGui

class Actor(object):
	#
	# Init
	#
	def __init__(self, name, colour = 0x000000):
		self.name = name
		self.setColour(colour)
		self.setSpeed(1)
		self.cell = (0, 0)
		self.x = 0
		self.y = 0
		self.canPass = False

		# Can this actor go through other actors?
		self.ignoreBlocking = False

		# Does this actor block the LOS of other actors?
		self.losBlocking = True

		# Our action list
		self.actions = {}

	#
	# Setup
	#
	def setup(self, world):
		self.world = world
		self.grid_density = world.grid_density
		self.maxdist = world.grid_density - 1
		self.alive = True

	#
	# A tick - your main entry point to the world.
	# This should be overridden, and will be called once per (World.tick rate)/second
	#
	def tick(self, world, tick):
		oldactions = {}
		for action in self.actions:
			oldactions[action] = self.actions[action]

		self.actions = {}
		for action in oldactions:
			lst = oldactions[action]
			newNum = action - 1
			if newNum >= 0:
				self.actions[newNum] = lst
			else:
				for (name, args) in lst:
					self.onAction(name, args)

	#
	# Called when we collide with something
	#
	def onCollision(self, obj):
		pass

	# Set our colour
	def setColour(self, colour):
		self.colour = QtGui.QColor(colour)

	# Set our speed (how many blocks can we move per second?)
	def setSpeed(self, speed):
		self.speed = speed

	# Set our position, ensuring its in the grid
	def setPos(self, (x, y)):
		constrained_x = self.constrain(x, 0, self.maxdist)
		constrained_y = self.constrain(y, 0, self.maxdist)

		if self.canCollide((constrained_x, constrained_y)):
			self.x = constrained_x
			self.y = constrained_y
			self.cell = (constrained_x, constrained_y)
			return not (constrained_x != x or constrained_y != y)

		return False

	# Can we collide with a given cell?
	def canCollide(self, cell):
		if self.ignoreBlocking:
			return True

		if self.world.isEmptyCell(cell):
			return True

		objs = self.world.cells[cell]
		f = True
		for o in objs:
			f = f and o.canPass

		return f

	# Move right
	def moveRight(self):
		return self.setPos((self.x + 1, self.y))

	# Move left
	def moveLeft(self):
		return self.setPos((self.x - 1, self.y))

	# Move up
	def moveUp(self):
		return self.setPos((self.x, self.y - 1))

	# Move down
	def moveDown(self):
		return self.setPos((self.x, self.y + 1))

	# Render
	def render(self, world):
		painter = QtGui.QPainter(world)
		rect = world.contentsRect()

		painter.setPen(self.colour)

		# Render equal to one grid size
		sizeX = rect.width() / self.grid_density
		sizeY = rect.height() / self.grid_density

		# Pad in
		x = self.x * sizeX
		y = self.y * sizeY

		# Draw
		painter.fillRect(x + 1, y + 1, sizeX - 2, sizeY - 2, self.colour)

	#
	# Constrains a number to a min/max
	#
	def constrain(self, x, xmin, xmax):
		if x > xmax:
			return xmax
		if x < xmin:
			return xmin
		return x

	#
	# Perform an action in (ticks) ticks
	#
	def doIn(self, ticks, action, args = []):
		if not ticks in self.actions:
			self.actions[ticks] = []
		self.actions[ticks].append((action, args))

	#
	# Perform an action
	# (Called by doIn)
	#
	def onAction(self, name, args):
		pass

	# Delete this Actor
	def kill(self):
		self.alive = False

	# Our string
	def __str__( self ):
		return self.name


text:
execute "install opam" do
  command "wget https://raw.github.com/ocaml/opam/master/shell/opam_installer.sh -O - | sh -s /usr/local/bin"
  not_if "test -e /usr/local/bin/opam"
end

execute "install ocaml" do
  command "opam switch 4.06.0"
end


text:
<?php
namespace Seyon\PHPBB3\UserBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use \Symfony\Component\Security\Core\User\AdvancedUserInterface;
use \Doctrine\Common\Collections\ArrayCollection;
use \Seyon\PHPBB3\UserBundle\Entity\Group\Base as BaseGroup;

/**
 *
 * @ORM\Table(name="groups")
 * @ORM\Entity
 */
class Group extends BaseGroup
{

    public function getId(){
        return $this->id;
    }

    public function getGroupName(){
        return $this->groupName;
    }

    public function getUsers(){
        $users = array();
        foreach($this->users as $userGroup){
            $users[] = $userGroup->getUser();
        }
        return $users;
    }
}


text:
package service

import (
	"encoding/hex"
	"fmt"

	"github.com/Sirupsen/logrus"
	"github.com/docker/distribution/digest"
	distreference "github.com/docker/distribution/reference"
	"github.com/docker/docker/api/types/swarm"
	"github.com/docker/docker/cli/command"
	"github.com/docker/docker/cli/trust"
	"github.com/docker/docker/reference"
	"github.com/docker/docker/registry"
	"github.com/docker/notary/tuf/data"
	"github.com/pkg/errors"
	"golang.org/x/net/context"
)

func resolveServiceImageDigest(dockerCli *command.DockerCli, service *swarm.ServiceSpec) error {
	if !command.IsTrusted() {
		// Digests are resolved by the daemon when not using content
		// trust.
		return nil
	}

	image := service.TaskTemplate.ContainerSpec.Image

	// We only attempt to resolve the digest if the reference
	// could be parsed as a digest reference. Specifying an image ID
	// is valid but not resolvable. There is no warning message for
	// an image ID because it's valid to use one.
	if _, err := digest.ParseDigest(image); err == nil {
		return nil
	}

	ref, err := reference.ParseNamed(image)
	if err != nil {
		return fmt.Errorf("Could not parse image reference %s", service.TaskTemplate.ContainerSpec.Image)
	}
	if _, ok := ref.(reference.Canonical); !ok {
		ref = reference.WithDefaultTag(ref)

		taggedRef, ok := ref.(reference.NamedTagged)
		if !ok {
			// This should never happen because a reference either
			// has a digest, or WithDefaultTag would give it a tag.
			return errors.New("Failed to resolve image digest using content trust: reference is missing a tag")
		}

		resolvedImage, err := trustedResolveDigest(context.Background(), dockerCli, taggedRef)
		if err != nil {
			return fmt.Errorf("Failed to resolve image digest using content trust: %v", err)
		}
		logrus.Debugf("resolved image tag to %s using content trust", resolvedImage.String())
		service.TaskTemplate.ContainerSpec.Image = resolvedImage.String()
	}
	return nil
}

func trustedResolveDigest(ctx context.Context, cli *command.DockerCli, ref reference.NamedTagged) (distreference.Canonical, error) {
	repoInfo, err := registry.ParseRepositoryInfo(ref)
	if err != nil {
		return nil, err
	}

	authConfig := command.ResolveAuthConfig(ctx, cli, repoInfo.Index)

	notaryRepo, err := trust.GetNotaryRepository(cli, repoInfo, authConfig, "pull")
	if err != nil {
		return nil, errors.Wrap(err, "error establishing connection to trust repository")
	}

	t, err := notaryRepo.GetTargetByName(ref.Tag(), trust.ReleasesRole, data.CanonicalTargetsRole)
	if err != nil {
		return nil, trust.NotaryError(repoInfo.FullName(), err)
	}
	// Only get the tag if it's in the top level targets role or the releases delegation role
	// ignore it if it's in any other delegation roles
	if t.Role != trust.ReleasesRole && t.Role != data.CanonicalTargetsRole {
		return nil, trust.NotaryError(repoInfo.FullName(), fmt.Errorf("No trust data for %s", ref.String()))
	}

	logrus.Debugf("retrieving target for %s role\n", t.Role)
	h, ok := t.Hashes["sha256"]
	if !ok {
		return nil, errors.New("no valid hash, expecting sha256")
	}

	dgst := digest.NewDigestFromHex("sha256", hex.EncodeToString(h))

	// Using distribution reference package to make sure that adding a
	// digest does not erase the tag. When the two reference packages
	// are unified, this will no longer be an issue.
	return distreference.WithDigest(ref, dgst)
}


text:
/**
 correlation_plate.h
 Purpose: This file defines the class CorrelationPlate. This class contains the variables necessary to store the measurement of the cross-correlation in a single plate

 @author Ignasi Pérez-Ràfols (iprafols@icc.ub.edu)
 @version 1.0 10/02/2014

 */

#ifndef _CorrelationPlate_h
#define _CorrelationPlate_h

// libraries needed
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
////////

// classes needed
#include "astro_object.h"
#include "astro_object_dataset.h"
#include "lya_auto_interpolation_map.h"
#include "lya_mean_projected_deltas_interpolation_map.h"
#include "lya_pixel.h"
#include "lya_spectrum.h"
#include "pair.h"
#include "plate.h"
#include "spectra_dataset.h"
#include "sphere_point.h"
////////

// functions needed
#include "function_to_str.hpp"
////////

#include "defines.h"
#include "typedefs.h"

class CorrelationPlate: public Plate{

public:
    // -------------------------------------------------------------
    // constructors

    // constructs empty object
    CorrelationPlate(){};

    // constructs "bad data" CorrelationPlate
    CorrelationPlate(int bad_data);

    // constructs object and initializes its variables
    CorrelationPlate(const Input& input, const int plate_number, const std::vector<int>& plate_neighbours);

    // constructs object and initializes its variables
    CorrelationPlate(const int plate_number, const int num_bins, const std::string& results, const std::string& pairs_file_name, const std::vector<int>& plate_neighbours, const size_t& flag_verbose_correlation_plate, const size_t& flag_write_partial_results, const bool& flag_projection_correction);

    // -------------------------------------------------------------
    // access methods

    // access function for flag_verbose_correlation_plate_
    size_t flag_verbose_correlation_plate() const {return flag_verbose_correlation_plate_;}

    // access function for flag_write_partial_results_
    size_t flag_write_partial_results() const {return flag_write_partial_results_;}

    // access function for flag_projection_correction_
    bool flag_projection_correction() const {return flag_projection_correction_;}

    // access functions for mean_pi_
    std::vector<double> mean_pi() const {return mean_pi_;}
    double mean_pi(size_t index) const;

    // access functions for mean_sigma_
    std::vector<double> mean_sigma() const {return mean_sigma_;}
    double mean_sigma(size_t index) const;

    // access function for mean_redshift_
    double mean_z() const {return mean_z_;}

    // access function for mean_z_in_bin_
    std::vector<double> mean_z_in_bin() const {return mean_z_in_bin_;}
    double mean_z_in_bin(size_t index) const;

    // access function for num_bins_
    size_t num_bins() const {return num_bins_;}

    // access funtion for num_averaged_pairs_
    std::vector<int> num_averaged_pairs() const {return num_averaged_pairs_;}
    int num_averaged_pairs(size_t index) const;

    // access function for pairs_file_name_
    std::string pairs_file_name() const {return pairs_file_name_;}

    // access function for plate_neigbours_
    std::vector<int> plate_neighbours() const {return plate_neighbours_;}

    // access function for results_
    std::string results() const {return results_;}

    // access functions for weight_
    std::vector<double> weight() const {return weight_;}
    double weight(size_t index) const;

    // access function for weight_z_
    double weight_z() const {return weight_z_;}

    // access functions for xi_
    std::vector<double> xi() const {return xi_;}
    double xi(size_t index) const;

    // access functions for xi_correction_
    std::vector<double> xi_correction() const {return xi_correction_;}
    double xi_correction(size_t index) const;

    // -------------------------------------------------------------
    // set methods

    // set flag_verbose_correlation_plate_
    void set_flag_verbose_correlation_plate(size_t value) {flag_verbose_correlation_plate_ = value;}

    // set mean_pi_
    void set_mean_pi(size_t index, double value);

    // set mean_sigma_
    void set_mean_sigma(size_t index, double value);

    // set mean_z_
    void set_mean_z(double mean_z) {mean_z_ = mean_z;}

    // set mean_z_in_bin_
    void set_mean_z_in_bin(size_t index, double value);

    // set num_averaged_pairs_
    void set_num_averaged_pairs(size_t index, int value);

    // set weight_
    void set_weight(size_t index, double value);

    // set weight_z_
    void set_weight_z(double weight_z) {weight_z_ = weight_z;}

    // set xi_
    void set_xi(size_t index, double value);

    // set xi_correction_
    void set_xi_correction(size_t index, double value);

    // -------------------------------------------------------------
    // other methods

    // compute cross-correlation
    void ComputeCrossCorrelation(const AstroObjectDataset& object_list, const SpectraDataset& spectra_list, const Input& input, const LyaMeanProjectedDeltasInterpolationMap& mean_proj_deltas);

    //returns a string with the information for the selected bin
    std::string Info(size_t bin);

    //returns a string with the column information
    static std::string InfoHeader(const bool& flag_projection_correction);

    // Normalizes the cross correlation results
    void Normalize();

    // Saves the cross correlation resutls
    void SaveCrossCorrelation(const Input& input);

    // -------------------------------------------------------------
    // operator overload

    // adition
    void operator+= (const CorrelationPlate& other);

    // subtraction
    CorrelationPlate operator- (const CorrelationPlate& other);

    // multiplication
    CorrelationPlate operator* (const CorrelationPlate& other);

private:
    // verbose flag
    size_t flag_verbose_correlation_plate_;

    // flag to write partial results
    size_t flag_write_partial_results_;

    // flag to compute the projection correction
    bool flag_projection_correction_;

    // maximum number of pairs stored in each bin
    size_t max_pairs_;

    // mean value of parallel separation in bin
    std::vector<double> mean_pi_;

    // mean value of perpendicular separation in bin
    std::vector<double> mean_sigma_;

    // mean redshift
    double mean_z_;

    // mean redshift in bin
    std::vector<double> mean_z_in_bin_;

    // number of bins
    size_t num_bins_;

    // number of pairs averaged
    std::vector<int> num_averaged_pairs_;

    // pairs file name
    std::string pairs_file_name_;

    // pairs information
    std::vector<std::vector<Pair> > pairs_information_;

    // plate number for neighbouring plates
    std::vector<int> plate_neighbours_;

    // position inside pairs_information_ of the next pair information
    std::vector<size_t> position_;

    // results directory (missing the bin number)
    std::string results_;

    // weight
    std::vector<double> weight_;

    // mean redshift weight
    double weight_z_;

    // cross correlation in bin
    std::vector<double> xi_;

    // correction to the cross correlation in bin
    std::vector<double> xi_correction_;

    // -------------------------------------------------------------
    // other methods

    // adding contribution to xi in the specified bin
    void AddPair(const size_t& k_index, const LyaPixel& pixel, const double& pi, const double& sigma, const LyaMeanProjectedDeltasInterpolationMap& mean_proj_deltas);

    // keeps the pair information for latter storage
    void KeepPair(const int& k_index, const LyaSpectrum& lya_spectrum, const size_t& pixel_number, const size_t obj_plate, const size_t obj_num);

    // write down pair information in bin file
    void SavePairs(const int& k_index);

};

#endif


text:
/**
 * Listens for the app launching then creates the window
 *
 * @see http://developer.chrome.com/trunk/apps/app.runtime.html
 * @see http://developer.chrome.com/trunk/apps/app.window.html
 */
chrome.app.runtime.onLaunched.addListener(function() {
  chrome.app.window.create('index.html',
    {frame:"none", bounds: {width: 500, height: 400}});
});


text:
using System;
using BrowserStack;
using System.Collections.Generic;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;

namespace BrowserStackExample
{
  class Example
  {
    static void Main(string[] args)
    {
      Local local = new Local();

      List<KeyValuePair<string, string>> options = new List<KeyValuePair<string, string>>() {
        new KeyValuePair<string, string>("key", BROWSERSTACK_ACCESS_KEY),
        //new KeyValuePair<string, string>("localIdentifier", "identifier"),
        //new KeyValuePair<string, string>("f", "C:\\Users\\Admin\\Desktop\\"),
        new KeyValuePair<string, string>("onlyAutomate", "true"),
        new KeyValuePair<string, string>("verbose", "true"),
        new KeyValuePair<string, string>("forcelocal", "true"),
        new KeyValuePair<string, string>("binarypath", "C:\\Users\\Admin\\Desktop\\BrowserStackLocal.exe"),
        new KeyValuePair<string, string>("logfile", "C:\\Users\\Admin\\Desktop\\local.log"),
      };
      local.start(options);

      // Run WebDriver Tests
      IWebDriver driver;
      DesiredCapabilities capability = DesiredCapabilities.Chrome();
      capability.SetCapability("browserstack.user", BROWSERSTACK_USERNAME);
      capability.SetCapability("browserstack.key", BROWSERSTACK_ACCESS_KEY);
      //capability.SetCapability("browserstack.localIdentifier", "identifier");
      capability.SetCapability("browserstack.local", true);
      capability.SetCapability("build", "build");

      driver = new RemoteWebDriver(
        new Uri("http://hub.browserstack.com/wd/hub/"), capability
      );
      driver.Navigate().GoToUrl("http://www.google.com");
      Console.WriteLine(driver.Title);

      IWebElement query = driver.FindElement(By.Name("q"));
      query.SendKeys("Browserstack");
      query.Submit();
      Console.WriteLine(driver.Title);

      driver.Quit();
      local.stop();
      Console.WriteLine("Test Completed.");
      Console.ReadLine();
    }
  }
}


text:
Ext.namespace('Ext.theme.is')['theme-conference-app'] = true;
Ext.theme.name = 'theme-conference-app';