text:
// Copyright (c) 2019-2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifndef BITCOIN_UTIL_CHECK_H
#define BITCOIN_UTIL_CHECK_H

#include <attributes.h>

#include <stdexcept>
#include <utility>

class NonFatalCheckError : public std::runtime_error
{
public:
    NonFatalCheckError(const char* msg, const char* file, int line, const char* func);
};

/** Helper for CHECK_NONFATAL() */
template <typename T>
T&& inline_check_non_fatal(LIFETIMEBOUND T&& val, const char* file, int line, const char* func, const char* assertion)
{
    if (!val) {
        throw NonFatalCheckError{assertion, file, line, func};
    }
    return std::forward<T>(val);
}

/**
 * Identity function. Throw a NonFatalCheckError when the condition evaluates to false
 *
 * This should only be used
 * - where the condition is assumed to be true, not for error handling or validating user input
 * - where a failure to fulfill the condition is recoverable and does not abort the program
 *
 * For example in RPC code, where it is undesirable to crash the whole program, this can be generally used to replace
 * asserts or recoverable logic errors. A NonFatalCheckError in RPC code is caught and passed as a string to the RPC
 * caller, which can then report the issue to the developers.
 */
#define CHECK_NONFATAL(condition) \
    inline_check_non_fatal(condition, __FILE__, __LINE__, __func__, #condition)

#if defined(NDEBUG)
#error "Cannot compile without assertions!"
#endif

/** Helper for Assert() */
void assertion_fail(const char* file, int line, const char* func, const char* assertion);

/** Helper for Assert()/Assume() */
template <bool IS_ASSERT, typename T>
T&& inline_assertion_check(LIFETIMEBOUND T&& val, [[maybe_unused]] const char* file, [[maybe_unused]] int line, [[maybe_unused]] const char* func, [[maybe_unused]] const char* assertion)
{
    if constexpr (IS_ASSERT
#ifdef ABORT_ON_FAILED_ASSUME
                  || true
#endif
    ) {
        if (!val) {
            assertion_fail(file, line, func, assertion);
        }
    }
    return std::forward<T>(val);
}

/** Identity function. Abort if the value compares equal to zero */
#define Assert(val) inline_assertion_check<true>(val, __FILE__, __LINE__, __func__, #val)

/**
 * Assume is the identity function.
 *
 * - Should be used to run non-fatal checks. In debug builds it behaves like
 *   Assert()/assert() to notify developers and testers about non-fatal errors.
 *   In production it doesn't warn or log anything.
 * - For fatal errors, use Assert().
 * - For non-fatal errors in interactive sessions (e.g. RPC or command line
 *   interfaces), CHECK_NONFATAL() might be more appropriate.
 */
#define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val)

/**
 * NONFATAL_UNREACHABLE() is a macro that is used to mark unreachable code. It throws a NonFatalCheckError.
 */
#define NONFATAL_UNREACHABLE()                                        \
    throw NonFatalCheckError(                                         \
        "Unreachable code reached (non-fatal)", __FILE__, __LINE__, __func__)

#endif // BITCOIN_UTIL_CHECK_H


text:
require 'spec_helper'

describe "gws_monitor_answers", type: :feature, dbscope: :example do
  let(:site) { gws_site }
  let(:g1) { create(:gws_group, name: "#{site.name}/g-#{unique_id}") }
  let(:g2) { create(:gws_group, name: "#{site.name}/g-#{unique_id}") }
  let(:r1) { create(:gws_role_admin) }
  let(:u1) { create(:gws_user, group_ids: [g1.id], gws_role_ids: [r1.id]) }
  let(:item1) do
    create(
      :gws_monitor_topic, attend_group_ids: [g1.id, g2.id], state: 'public', article_state: 'open', spec_config: 'my_group',
      answer_state_hash: { g1.id.to_s => "answered", g2.id.to_s => "preparation" }
    )
  end
  let(:item2) do
    create(
      :gws_monitor_topic, attend_group_ids: [g1.id, g2.id], state: 'public', article_state: 'open',
      spec_config: 'other_groups_and_contents', answer_state_hash: { g1.id.to_s => "answered", g2.id.to_s => "preparation" }
    )
  end

  context "with auth" do
    before { login_user u1 }

    it "#index display only my group" do
      item1
      visit gws_monitor_answers_path(site)
      expect(page).to have_content(item1.name)
      expect(page).to have_content('回答状況(1/1)')
    end

    it "#index display all groups" do
      item2
      visit gws_monitor_answers_path(site)
      expect(page).to have_content(item2.name)
      expect(page).to have_content('回答状況(1/2)')
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package thread.actor;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.event.Logging;
import akka.event.LoggingAdapter;

public class GreetingActor extends UntypedActor {
  LoggingAdapter log = Logging.getLogger(getContext().system(), this);

  public void onReceive(Object message) throws Exception {
    if (message instanceof Greeting)
      log.info("Hello " + ((Greeting) message).who);
  }

    public static void main(String[] args) throws Exception {
        ActorSystem system = ActorSystem.create("MySystem");
        ActorRef greeter = system.actorOf(Props.create(GreetingActor.class), "greeter");
        greeter.tell(new Greeting("Charlie Parker"), ActorRef.noSender());
    }
}


text:
layout: post
title: 465 - Optimal Account Balancing
date: 2020-02-02
tags:
- Leetcode
categories:
- Array
author: Jason
---
A group of friends went on holiday and sometimes lent each other money. For example, Alice paid for Bill's lunch for $10. Then later Chris gave Alice $5 for a taxi ride. We can model each transaction as a tuple (x, y, z) which means person x gave person y $z. Assuming Alice, Bill, and Chris are person 0, 1, and 2 respectively (0, 1, 2 are the person's ID), the transactions can be represented as [[0, 1, 10], [2, 0, 5]]. Given a list of transactions between a group of people, return the minimum number of transactions required to settle the debt.

```python
from collections import defaultdict
class Solution:
    def minTransfers(self, transactions: List[List[int]]) -> int:
        value_map = defaultdict(int)
        for a, b, c in transactions:
            value_map[a] -= c
            value_map[b] += c

        debts = list(value_map.values())
        def dfs(start):
            while start < len(debts) and debts[start] == 0:
                start += 1
            if start == len(debts):
                return 0
            ret = float("inf")
            for i in range(start + 1, len(debts)):
                if debts[i] * debts[start] < 0:
                    debts[i] += debts[start]
                    ret = min(ret, dfs(start + 1) + 1)
                    debts[i] -= debts[start]
            return ret

        return dfs(0)
```


text:
using UnityEngine;
using System.Collections;

public class ElectronicDevice : UsableDevice {

	public AudioClip audio;

	public int noise_range_percent = 5;

	public int delta_active_power_phase1 = 0;
	public int delta_reactive_power_phase1 = 0;
	private int effective_delta_active_power_phase1 = 0;
	private int effective_delta_reactive_power_phase1 = 0;
//	public int delta_spike_active_power_phase1 = 0;
//	public int time_spike_active_power_phase1 = 0;

	public int delta_active_power_phase2 = 0;
	public int delta_reactive_power_phase2 = 0;
	private int effective_delta_active_power_phase2 = 0;
	private int effective_delta_reactive_power_phase2 = 0;
//	public int delta_spike_active_power_phase2 = 0;
//	public int time_spike_active_power_phase2 = 0;

	public int delta_active_power_phase3 = 0;
	public int delta_reactive_power_phase3 = 0;
	private int effective_delta_active_power_phase3 = 0;
	private int effective_delta_reactive_power_phase3 = 0;
//	public int delta_spike_active_power_phase3 = 0;
//	public int time_spike_active_power_phase3 = 0;

	private SmartElectronicMeter smartElectronicMeterScript;

	private Request powerRequest;

    // Use this for initialization
    void Start () {
		smartElectronicMeterScript = null;
		deviceState = State.Off;
		powerRequest = null;
	}

	protected override bool Init ()
	{
		if (smartElectronicMeterScript == null) {
			GameObject smartElectronicMeter = GameObject.Find ("SmartPanel");
			if(smartElectronicMeter == null)
				Debug.Log("Not Loaded");
			smartElectronicMeterScript = smartElectronicMeter.GetComponent<SmartElectronicMeter> ();
			return true;
		}
		return false;
	}

	protected override State OnOn ()
	{
		if (audio != null)
			AudioSource.PlayClipAtPoint (audio,transform.position);

		int noise_range = (int)(delta_active_power_phase1 * ((float)noise_range_percent / 100.0));
		effective_delta_active_power_phase1 = delta_active_power_phase1 + Random.Range(-noise_range, noise_range);
		noise_range = (int)(delta_reactive_power_phase1 * ((float)noise_range_percent / 100.0));
		effective_delta_reactive_power_phase1 = delta_reactive_power_phase1 + Random.Range(-noise_range, noise_range);
		noise_range = (int)(delta_active_power_phase2 * ((float)noise_range_percent / 100.0));
		effective_delta_active_power_phase2 = delta_active_power_phase2 + Random.Range(-noise_range, noise_range);
		noise_range = (int)(delta_reactive_power_phase2 * ((float)noise_range_percent / 100.0));
		effective_delta_reactive_power_phase2 = delta_reactive_power_phase2 + Random.Range(-noise_range, noise_range);
		noise_range = (int)(delta_active_power_phase3 * ((float)noise_range_percent / 100.0));
		effective_delta_active_power_phase3 = delta_active_power_phase3 + Random.Range(-noise_range, noise_range);
		noise_range = (int)(delta_reactive_power_phase3 * ((float)noise_range_percent / 100.0));
		effective_delta_reactive_power_phase3 = delta_reactive_power_phase3 + Random.Range(-noise_range, noise_range);
		powerRequest = smartElectronicMeterScript.RequestForEnergy (effective_delta_active_power_phase1, effective_delta_reactive_power_phase1
			, effective_delta_active_power_phase2, effective_delta_reactive_power_phase2, effective_delta_active_power_phase3, effective_delta_reactive_power_phase3);
		return State.Opening;
	}

	protected override State OnClose ()
	{
		powerRequest.Revert();
		smartElectronicMeterScript.ResquestForRevert(powerRequest);
		return State.Closing;
	}

	protected override State OnOpening ()
	{
		if(powerRequest.IsRequestDone == true)
			return State.On;
		return State.Opening;
	}

	protected override State OnClosing ()
	{
		if(powerRequest.IsRequestDone == true)
			return State.Off;
		return State.Closing;
	}

}


text:
using System;

namespace Ractor {

    // Instead use schemaless type extensions, e.g. User and User.UserInfo
    // and instead of hierarchy just add properties - will be stored in serialized format
    // Other usage of TPH are unclear

    /// <summary>
    /// Use one table to store a hierarchy of POCOs.
    /// </summary>
    [Obsolete] // TODO delete or implement? with automaping should not be that complex, but what are the use cases?...
    [AttributeUsage(AttributeTargets.Class)]
    public class TablePerHierarchyAttribute : Attribute {
        /// <summary>
        /// A POCO that defines storage table
        /// </summary>
        public Type TableDefinition { get; set; }

        public TablePerHierarchyAttribute(Type tableDefinition) {
            TableDefinition = tableDefinition;
        }

    }
}


text:
using UnityEngine;
using System.Collections;

namespace Trepid.Flocking
{
	/// <summary>
	/// This is a randomized parameter that is squared.
	/// Use this for distances so we don't need to normalize vectors.
	/// Normalizing vectors requires square root operations, which are slow.
	/// </summary>
	[System.Serializable]
	public class RandomizedParameterSquared : RandomizedParameter
	{
		#region Vars
		protected float generatedValueSquared;
		#endregion

		#region Methods
		public override void GenerateValue()
		{
			base.GenerateValue();
			generatedValueSquared = generatedValue * generatedValue;
		}

		public float GetValueSqr()
		{
			if (!generated)
			{
				GenerateValue();
				generated = true;
			}
			return generatedValueSquared;
		}
		#endregion
	}
}


text:
body{
padding:35px 0 0 0;
margin:0;
}

.admin-top-menu{ height:30px;background-color:#F0F0F0;box-shadow:0px 0px 8px #808080;position:fixed;top:0;width:100%;z-index:100;line-height:18px;
background: #FCFCFC; /* Old browsers */
background: -moz-linear-gradient(top, #FCFCFC 0%, #E8E8E8 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#FCFCFC), color-stop(100%,#E8E8E8)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #FCFCFC 0%,#E8E8E8 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #FCFCFC 0%,#E8E8E8 100%); /* Opera11.10+ */
background: -ms-linear-gradient(top, #FCFCFC 0%,#E8E8E8 100%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#FCFCFC', endColorstr='#E8E8E8',GradientType=0 ); /* IE6-9 */
background: linear-gradient(top, #FCFCFC 0%,#E8E8E8 100%); /* W3C */
}
.admin-list > li{list-style:none;float:left;position:relative;}
.admin-list > li > a{display:block;color:#333;text-decoration:none;font-size:14px;font-family:Tahoma, Verdana, sans-serif;padding:6px 20px 7px 22px;}
.admin-list{margin:0 0 0 15px;padding:0;}
.admin-list > li > a > span, .exit-list li > a > span{display:inline-block;width:16px;height:16px;position:absolute;left:0px;top:8px;background-image:url(../images/icon-sprite.png);-webkit-transition:background-position 0.3s ease;-moz-transition:background-position 0.3s ease;}
.exit-list li a{color:#333;text-decoration:none;font-size:14px;font-family:Tahoma, Verdana, sans-serif;padding:6px 20px 7px 22px;position:relative;}
.exit-list li > a {padding:6px 20px 7px 19px;}
.exit-list{margin:4px 0 0 0;list-style:none;}
.exit-list li{float:left;margin:0 0 0 25px;}

.left-side{float:left;}
.admin-site-icon{background-position:-137px 0;}
.right-side{float:right;}
.user-icon{background-position:-156px 0px;background-repeat:no-repeat;}
.exit-list .exit-icon{background-position:-172px 0px;background-repeat:no-repeat;}

.message-error{display:none; padding:30px;/*height:30px;*/border:1px solid #BA0A0A;float:right;border-radius:3px;-moz-border-radius:3px;
    -webkit-border-radius:3px;/*margin:4px 0 5px 0;*/margin:0;color:#fff;text-shadow:1px 1px 1px #444;bottom:0;right:0;position: fixed;z-index: 55;
  background-color: #BA0A0A;
  background-image: -webkit-gradient(linear, 0 0%, 0 100%, from(#EA3E3E), to(#FF1515));
  background-image: -webkit-linear-gradient(top, #EA3E3E 0%, #FF1515 100%);
  background-image: -moz-linear-gradient(top, #EA3E3E 0%, #FF1515 100%);
  background-image: -ms-linear-gradient(top, #EA3E3E 0%, #FF1515 100%);
  background-image: -o-linear-gradient(top, #EA3E3E 0%, #FF1515 100%);
  background-image: -linear-gradient(top, #EA3E3E 0%, #FF1515 100%);
  opacity:0.9;
  filter: alpha(opacity=90);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#EA3E3E', endColorstr='#FF1515',GradientType=0 );}
.message-succes{display:none; padding:30px;/*height:10px;*/border:1px solid green;float:right;border-radius:3px;-moz-border-radius:3px;
    -webkit-border-radius:3px;/*margin:4px 0 5px 0;*/margin:0;color:#fff;text-shadow:1px 1px 1px #444;position: fixed;bottom:0;right:0;z-index: 55;
  background-color: #28BB1D;
  background-image: -webkit-gradient(linear, 0 0%, 0 100%, from(#5CD054), to(#28BB1D));
  background-image: -webkit-linear-gradient(top, #5CD054 0%, #28BB1D 100%);
  background-image: -moz-linear-gradient(top, #5CD054 0%, #28BB1D 100%);
  background-image: -ms-linear-gradient(top, #5CD054 0%, #28BB1D 100%);
  background-image: -o-linear-gradient(top, #5CD054 0%, #28BB1D 100%);
  background-image: -linear-gradient(top, #5CD054 0%, #28BB1D 100%);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#5CD054', endColorstr='#28BB1D',GradientType=0 );
  opacity:0.9;
  filter: alpha(opacity=90);
}

.fastEdit, .modalOpen{
  border: #FF1515 dashed 1px;
  background: rgb(248, 248, 248) url(../images/icons/edit-icon.png) right top no-repeat;
  cursor: hand;
  min-height: 20px;
  padding:3px 5px 1px 5px;
  font-size:12px;
  font-family:Tahoma, Verdana, sans-serif;
  color:#444;
  text-transform:none;
}

.exist-admin-context{
	position:relative;
}
.admin-context{
    display: none;
    text-align: left;
	background: #fff;
	padding: 5px 0;
    font-weight: normal;
	border-radius: 5px;
	-moz-border-radius: 5px;
	-webkit-border-radius: 5px;
	position: absolute;
	top: 100%;
	left: 20%;
	border: 1px solid #ccc;
	z-index: 666;
	box-shadow: 0 5px 10px rgba(0,0,0,0.2);
	-moz-box-shadow: 0 5px 10px rgba(0,0,0,0.2);
	-webkit-box-shadow: 0 5px 10px rgba(0,0,0,0.2);
}

.admin-context .modalOpen{
	color:#000;
	padding-right:30px;
	border:none;
	background: #fff;
	position:relative;
    text-shadow:none;
}

.modalOpen .admin-edit-icon{
	display:block;
	width:16px;
	height:16px;
	background:url(../images/icons/edit-icon.png) 0 0 no-repeat;
	position:absolute;
	top:5px;
	right:5px;
}

.modalOpen .admin-add-icon{
	display:block;
	width:16px;
	height:16px;
	background:url(../images/icons/add-icon.png) 0 0 no-repeat;
	position:absolute;
	top:5px;
	right:5px;
}

.admin-context .modalOpen:hover{
  background-color:#E0E0E0;
}

.admin-top-menu .site-edit{
    position: relative;
    display: inline-block;
    padding: 0 70px 0 0;
    line-height: 21px;
}

.admin-top-menu .site-edit .switch{
    position: absolute;
    right:0;
    top:0;
}

.admin-top-menu .site-edit .switch, .admin-top-menu .site-edit.enabled .switch{
    display: inline-block;
    width:56px;
    height:25px;
}

.admin-top-menu .site-edit .switch{
    background: url(../images/off.png) no-repeat;
}

.admin-top-menu .site-edit.enabled .switch{
    background: url(../images/on.png) no-repeat;
}

.exit-list li .clear-cache{
    position: relative;
    top: 2px;
    background: url("../images/icons/refresh-icon.png") left center no-repeat;
    padding-left: 22px;
}


text:
namespace policy {

// Decodes a CloudPolicySettings object into a policy map. The implementation is
// generated code in policy/cloud_policy_generated.cc.
void DecodePolicy(const enterprise_management::CloudPolicySettings& policy,
                  PolicyMap* policies);

UserCloudPolicyStoreBase::UserCloudPolicyStoreBase() {
}

UserCloudPolicyStoreBase::~UserCloudPolicyStoreBase() {
}

scoped_ptr<UserCloudPolicyValidator> UserCloudPolicyStoreBase::CreateValidator(
    scoped_ptr<enterprise_management::PolicyFetchResponse> policy) {
  // Configure the validator.
  UserCloudPolicyValidator* validator =
      UserCloudPolicyValidator::Create(policy.Pass());
  validator->ValidatePolicyType(dm_protocol::kChromeUserPolicyType);
  validator->ValidateAgainstCurrentPolicy(
      policy_.get(),
      CloudPolicyValidatorBase::TIMESTAMP_REQUIRED,
      CloudPolicyValidatorBase::DM_TOKEN_REQUIRED);
  validator->ValidatePayload();
  return scoped_ptr<UserCloudPolicyValidator>(validator);
}

void UserCloudPolicyStoreBase::InstallPolicy(
    scoped_ptr<enterprise_management::PolicyData> policy_data,
    scoped_ptr<enterprise_management::CloudPolicySettings> payload) {
  // Decode the payload.
  policy_map_.Clear();
  DecodePolicy(*payload, &policy_map_);
  policy_ = policy_data.Pass();
}

}  // namespace policy


text:
"""
Implementation of the public HTTP APIs.
"""


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/isteps/istep12/call_cen_set_inband_addr.C $           */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2017                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include    <stdint.h>

#include    <trace/interface.H>
#include    <initservice/taskargs.H>
#include    <errl/errlentry.H>

#include    <isteps/hwpisteperror.H>
#include    <errl/errludtarget.H>

#include    <initservice/isteps_trace.H>

//  targeting support.
#include    <targeting/common/commontargeting.H>
#include    <targeting/common/utilFilter.H>

//Fapi Support
#include    <config.h>
#include    <fapi2.H>
#include    <fapi2/plat_hwp_invoker.H>
#include    <util/utilmbox_scratch.H>

//HWP
#include    <p9c_set_inband_addr.H>

using   namespace   ISTEP;
using   namespace   ISTEP_ERROR;
using   namespace   ERRORLOG;
using   namespace   TARGETING;

namespace ISTEP_12
{
void* call_cen_set_inband_addr (void *io_pArgs)
{
    IStepError l_StepError;
    errlHndl_t l_err = NULL;

    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_cen_set_inband_addr entry" );

    TARGETING::TargetHandleList l_procTargetList;
    getAllChips(l_procTargetList, TYPE_PROC);

    TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "call_cen_set_inband_addr: %d proc chips found",
            l_procTargetList.size());

    for (const auto & l_proc_target : l_procTargetList)
    {
        TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
            "p9c_set_inband_addr HWP target HUID %.8x",
            TARGETING::get_huid(l_proc_target));

        //  call the HWP with each target
        fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_fapi_proc_target
                (l_proc_target);

        FAPI_INVOKE_HWP(l_err, p9c_set_inband_addr, l_fapi_proc_target);

        //  process return code.
        if ( l_err )
        {
            TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                "ERROR 0x%.8X:  p9c_set_inband_addr HWP on target HUID %.8x",
                l_err->reasonCode(), TARGETING::get_huid(l_proc_target) );

            // capture the target data in the elog
            ErrlUserDetailsTarget(l_proc_target).addToLog( l_err );

            // Create IStep error log and cross reference to error that occurred
            l_StepError.addErrorDetails( l_err );

            // Commit Error
            errlCommit( l_err, ISTEP_COMP_ID );
        }
        else
        {
            TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                     "SUCCESS :  p9c_set_inband_addr HWP");
        }

    }

    TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_cen_set_inband_addr exit" );

    // end task, returning any errorlogs to IStepDisp
    return l_StepError.getErrorHandle();

}

};


text:
import {Component, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';

import {TreeNode, emptyTree} from '../util';

@Component({
  selector: 'tree',
  inputs: ['data'],
  template:
      `<span [style.backgroundColor]="data.depth % 2 ? '' : 'grey'"> {{data.value}} </span><tree *ngIf='data.right != null' [data]='data.right'></tree><tree *ngIf='data.left != null' [data]='data.left'></tree>`
})
export class TreeComponent {
  data: TreeNode = emptyTree;
}

@NgModule({imports: [BrowserModule], bootstrap: [TreeComponent], declarations: [TreeComponent]})
export class AppModule {
}


text:
feature_name: Web Bluetooth / Get Devices
chrome_version: 87
check_min_version: true
feature_id: 4797798639730688
icon_url: icon.png
index: index.html
---

{% include_relative _includes/intro.html %}

This sample illustrates the use of the Web Bluetooth API to get a list of
Bluetooth devices that the website has been granted permission to use by the
user. You may want to check out the Get
Devices (Async Await) sample.

<button id="getBluetoothDevices">Get Bluetooth Devices</button>
<button id="requestBluetoothDevice">Request Bluetooth Device</button>

{% include output_helper.html %}

{% include js_snippet.html filename='get-devices.js' %}

{% include_relative _includes/utils.html %}


text:
package it.cnr.isti.melampo.index.searching;

import it.cnr.isti.melampo.index.CosineSimilarity;
import it.cnr.isti.melampo.index.Parameters;
import it.cnr.isti.melampo.index.LireObjectFieldAdder;
import it.cnr.isti.melampo.index.settings.LireSettings;
import it.cnr.isti.melampo.tools.OrderTopKArrayList;
import it.cnr.isti.melampo.vir.exceptions.VIRException;
import it.cnr.isti.melampo.vir.lire.LireReader;
import it.cnr.isti.melampo.vir.lire.LireSearcher;
import it.cnr.isti.vir.features.mpeg7.LireObject;
import it.cnr.isti.vir.similarity.metric.LireMetric;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.PerFieldAnalyzerWrapper;
import org.apache.lucene.analysis.WhitespaceAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class LireMP7CSearcher implements MelampoSearcher {

	private static IndexSearcher m_sMPG7C;

	private static LireSearcher m_soSearcher;
	private ScoreDoc[] m_hits;

	private static PerFieldAnalyzerWrapper m_wrapper;
	private static int m_hitsPerPage = 100;
	private static int m_retrieve = 100;

	private static LireObjectFieldAdder m_sfaALL;

	private static int m_toppivsQ;
	private static int m_toppivsI;
	private static int m_nPivots;
	private static String m_PivFile;

	// for reordering purposes
	private static LireObject[] m_so;
	private static LireReader m_sreader;

	private LireObject sq;
	private LireMetric sm;
	private IndexReader rMPG7C;

	private Analyzer analyzer = new WhitespaceAnalyzer();
	private String query;

	@Override
	public void OpenIndex(File propertyFile) throws IOException, VIRException {

		System.out.println("index conf file: " + propertyFile.getAbsolutePath());

		if (m_sMPG7C != null)
			return;

		LireSettings settings = new LireSettings(propertyFile);

		m_soSearcher = new LireSearcher(settings);

		m_sreader = new LireReader(settings);
		//m_so = m_sreader.getAllSapirObject();

		String indexPath = settings.getLuceneIndexPathLire();
		if (indexPath != null) {
			Directory dir = FSDirectory.open(new File(indexPath));
			rMPG7C = IndexReader.open(dir, true);
			m_sMPG7C = new IndexSearcher(rMPG7C);
			m_sMPG7C.setSimilarity(new CosineSimilarity());
			System.out.println("mpeg-7 Pre-Combined using cosine similarity");
			System.out.println(indexPath + " open " + rMPG7C.numDocs()
					+ " docs");
		}

		StandardAnalyzer sa = new StandardAnalyzer(Version.LUCENE_30);
		m_wrapper = new PerFieldAnalyzerWrapper(sa);
		m_wrapper.addAnalyzer(Parameters.LIRE_MP7ALL, analyzer);

		m_nPivots = settings.getnPivots();
		m_PivFile = settings.getPivotsPath();

		m_sfaALL = new LireObjectFieldAdder(new LireMetric());
		m_sfaALL.loadBinPivots(m_PivFile, m_nPivots);

		m_toppivsQ = settings.getToppivsQ();

		m_toppivsI = settings.getToppivsI();

		// for reordering
		double clw = 1.0;
		double csw = 1.0;
		double ehw = 1.0;
		double htw = 1.0;
		double scw = 1.0;
		sm = new LireMetric();
	}

	@Override
	public String prepareQuery(String value, String field,
			boolean isQueryID) throws VIRException {
		sq = m_soSearcher.getObject(value, isQueryID);
		query = m_sfaALL.metricObjectToStringQ(sq, m_toppivsQ,
					m_toppivsI);
		return query;
	}

	@Override
	public void query()
			throws ParseException, IOException {
		BooleanClause.Occur[] flags = new BooleanClause.Occur[1];
		flags[0] = getOccur();

		String[] v = {query};
		String[] f = {Parameters.LIRE_MP7ALL};

		Query q = MultiFieldQueryParser.parse(Version.LUCENE_30, v,
				f, flags, m_wrapper);

		TopDocs td = null;

		System.out.println("Using standalone MPEG-7 combined features index");
		td = m_sMPG7C.search(q, m_retrieve);

		m_hits = td.scoreDocs;
	}

	@Override
	public void reorderResults() {
		ScoreDoc[] m_hitsNew = null;
		if (sq == null)
			return;
		int nresults = 0;
		if (m_hits.length < m_hitsPerPage)
			nresults = m_hits.length;
		else
			nresults = m_hitsPerPage;
		m_hitsNew = new ScoreDoc[nresults];
		OrderTopKArrayList knn = new OrderTopKArrayList(nresults);
		for (int i = 0; i < m_hits.length; i++) {
			int d = m_hits[i].doc;
			LireObject s=null;
			try {
				s = m_sreader.getObject(d);
			} catch (VIRException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			knn.insert(sm.distance(sq, s), i);
		}
		for (int i = 0; i < nresults; i++) {
			m_hitsNew[i] = m_hits[knn.get(i)];
		}
		m_hits = m_hitsNew;
	}

	@Override
	public String[][] getResults(int startFrom, int numElements)
			throws IOException {
		String[][] retval = new String[numElements][3];
		for (int i = 0; i < numElements; i++) {
			if (startFrom + i > m_hits.length - 1)
				break;
			float score = m_hits[startFrom + i].score;
			retval[i][0] = ((Float) score).toString();
			Document d = null;
			d = m_sMPG7C.doc(m_hits[startFrom + i].doc);
			retval[i][1] = d.get(Parameters.IDFIELD);
		}
		return retval;
	}

	@Override
	public Searcher getIndex() {
		return m_sMPG7C;
	}

	@Override
	public Occur getOccur() {
		return Occur.SHOULD;
	}

	@Override
	public IndexReader getIndexReader() {
		return rMPG7C;
	}

	@Override
	public Analyzer getAnalyzer() {
		return analyzer;
	}

}


text:
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//
using Microsoft.MixedReality.Toolkit.UI;
using Microsoft.MixedReality.Toolkit.Utilities.Editor;
using UnityEditor;
using UnityEngine;

namespace Microsoft.MixedReality.Toolkit.Editor
{
    [CustomEditor(typeof(PinchSlider))]
    public class PinchSliderInspector : UnityEditor.Editor
    {
        private static GUIStyle labelStyle;

        public override void OnInspectorGUI()
        {
            if (target != null)
            {
                InspectorUIUtility.RenderHelpURL(target.GetType());
            }

            DrawDefaultInspector();
        }

        private void OnSceneGUI()
        {
            if (labelStyle == null)
            {
                labelStyle = new GUIStyle();
                labelStyle.normal.textColor = Color.white;
            }

            PinchSlider slider = target as PinchSlider;
            if (slider != null)
            {
                Handles.color = Color.cyan;
                Vector3 startPos = slider.SliderStartPosition;
                Vector3 endPos = slider.SliderEndPosition;
                Handles.DrawLine(startPos, endPos);

                EditorGUI.BeginChangeCheck();

                float handleSize = HandleUtility.GetHandleSize(startPos) * 0.15f;
                slider.SliderStartPosition = Handles.FreeMoveHandle(startPos,
                    Quaternion.identity,
                    handleSize,
                    Vector3.zero,
                    Handles.SphereHandleCap);
                slider.SliderEndPosition = Handles.FreeMoveHandle(endPos,
                    Quaternion.identity,
                    handleSize,
                    Vector3.zero,
                    Handles.SphereHandleCap);

                if (EditorGUI.EndChangeCheck())
                {
                    var sliderStartSerialized = serializedObject.FindProperty("sliderStartDistance");
                    var sliderEndSerialized = serializedObject.FindProperty("sliderEndDistance");
                    sliderStartSerialized.floatValue = slider.SliderStartDistance;
                    sliderEndSerialized.floatValue = slider.SliderEndDistance;
                    serializedObject.ApplyModifiedProperties();
                }

                DrawLabelWithDottedLine(startPos + (Vector3.up * handleSize * 10f), startPos, handleSize, "slider start");
                DrawLabelWithDottedLine(endPos + (Vector3.up * handleSize * 10f), endPos, handleSize, "slider end");
            }
        }

        private void DrawLabelWithDottedLine(Vector3 labelPos, Vector3 dottedLineStart, float handleSize, string labelText)
        {
            Handles.color = Color.white;
            Handles.Label(labelPos + Vector3.up * handleSize, labelText, labelStyle);
            Handles.DrawDottedLine(dottedLineStart, labelPos, 5f);
        }
    }

}


text:
#!/usr/bin/env python
# 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.

# TODO (qinmin): Need to refactor this file as base should not know about
# higher level concepts. Currently this file has knowledge about higher level
# java classes.

"""Extracts native methods from a Java file and generates the JNI bindings.
If you change this, please run and update the tests."""

import collections
import optparse
import os
import re
import string
from string import Template
import subprocess
import sys
import textwrap
import zipfile

UNKNOWN_JAVA_TYPE_PREFIX = 'UNKNOWN_JAVA_TYPE: '

class ParseError(Exception):
  """Exception thrown when we can't parse the input file."""

  def __init__(self, description, *context_lines):
    Exception.__init__(self)
    self.description = description
    self.context_lines = context_lines

  def __str__(self):
    context = '\n'.join(self.context_lines)
    return '***\nERROR: %s\n\n%s\n***' % (self.description, context)

class Param(object):
  """Describes a param for a method, either java or native."""

  def __init__(self, **kwargs):
    self.datatype = kwargs['datatype']
    self.name = kwargs['name']

class NativeMethod(object):
  """Describes a C/C++ method that is called by Java code"""

  def __init__(self, **kwargs):
    self.static = kwargs['static']
    self.java_class_name = kwargs['java_class_name']
    self.return_type = kwargs['return_type']
    self.name = kwargs['name']
    self.params = kwargs['params']
    if self.params:
      assert type(self.params) is list
      assert type(self.params[0]) is Param
    if (self.params and
        self.params[0].datatype == 'int' and
        self.params[0].name.startswith('native')):
      self.type = 'method'
      self.p0_type = self.params[0].name[len('native'):]
      if kwargs.get('native_class_name'):
        self.p0_type = kwargs['native_class_name']
    else:
      self.type = 'function'
    self.method_id_var_name = kwargs.get('method_id_var_name', None)

class CalledByNative(object):
  """Describes a java method exported to c/c++"""

  def __init__(self, **kwargs):
    self.system_class = kwargs['system_class']
    self.unchecked = kwargs['unchecked']
    self.static = kwargs['static']
    self.java_class_name = kwargs['java_class_name']
    self.return_type = kwargs['return_type']
    self.env_call = kwargs['env_call']
    self.name = kwargs['name']
    self.params = kwargs['params']
    self.method_id_var_name = kwargs.get('method_id_var_name', None)

def JavaDataTypeToC(java_type):
  """Returns a C datatype for the given java type."""
  java_pod_type_map = {
      'int': 'jint',
      'byte': 'jbyte',
      'boolean': 'jboolean',
      'long': 'jlong',
      'double': 'jdouble',
      'float': 'jfloat',
  }
  java_type_map = {
      'void': 'void',
      'String': 'jstring',
  }
  if java_type in java_pod_type_map:
    return java_pod_type_map[java_type]
  elif java_type in java_type_map:
    return java_type_map[java_type]
  elif java_type.endswith('[]'):
    if java_type[:-2] in java_pod_type_map:
      return java_pod_type_map[java_type[:-2]] + 'Array'
    return 'jobjectArray'
  else:
    return 'jobject'

def JavaParamToJni(param):
  """Converts a java param into a JNI signature type."""
  pod_param_map = {
      'int': 'I',
      'boolean': 'Z',
      'long': 'J',
      'double': 'D',
      'float': 'F',
      'byte': 'B',
      'void': 'V',
  }
  object_param_list = [
      'Ljava/lang/String',
      'Ljava/lang/Boolean',
      'Ljava/lang/Integer',
      'Ljava/lang/Long',
      'Ljava/lang/Object',
      'Ljava/util/List',
      'Ljava/util/ArrayList',
      'Ljava/util/HashMap',
      'Landroid/graphics/Bitmap',
      'Landroid/content/Context',
      'Landroid/graphics/Canvas',
      'Landroid/view/Surface',
      'Landroid/view/KeyEvent',
      'Landroid/graphics/Rect',
      'Landroid/graphics/RectF',
      'Landroid/view/View',
      'Landroid/graphics/Matrix',
      'Landroid/graphics/Point',
      'Ljava/nio/ByteBuffer',
      'Ljava/io/InputStream',
      'Ljava/util/Vector',
  ]
  app_param_list = [
      'Landroid/graphics/SurfaceTexture',
      'Lcom/google/android/apps/chrome/AutofillData',
      'Lcom/google/android/apps/chrome/ChromeBrowserProvider$BookmarkNode',
      'Lcom/google/android/apps/chrome/ChromeHttpAuthHandler',
      'Lcom/google/android/apps/chrome/ChromeContextMenuInfo',
      'Lcom/google/android/apps/chrome/OmniboxSuggestion',
      'Lcom/google/android/apps/chrome/PageInfoViewer',
      'Lcom/google/android/apps/chrome/Tab',
      'Lcom/google/android/apps/chrome/database/SQLiteCursor',
      'Lcom/google/android/apps/chrome/infobar/InfoBarContainer',
      'Lcom/google/android/apps/chrome/infobar/InfoBarContainer$NativeInfoBar',
      ('Lcom/google/android/apps/chrome/preferences/ChromeNativePreferences$'
       'PasswordListObserver'),
      'Lorg/chromium/base/SystemMessageHandler',
      'Lorg/chromium/chrome/browser/JSModalDialog',
      'Lorg/chromium/chrome/browser/ProcessUtils',
      'Lorg/chromium/chrome/browser/SelectFileDialog',
      'Lorg/chromium/content/browser/ContentVideoView',
      'Lorg/chromium/content/browser/ContentViewClient',
      'Lorg/chromium/content/browser/ContentViewCore',
      'Lorg/chromium/content/browser/ContentHttpAuthHandler',
      'Lorg/chromium/content/browser/DeviceOrientation',
      'Lorg/chromium/content/browser/FileChooserParams',
      'Lorg/chromium/content/browser/FindNotificationDetails',
      'Lorg/chromium/content/browser/InterceptedRequestData',
      'Lorg/chromium/content/browser/JavaInputStream',
      'Lorg/chromium/content/browser/LocationProvider',
      'Lorg/chromium/content/browser/SandboxedProcessArgs',
      'Lorg/chromium/content/browser/SandboxedProcessConnection',
      'Lorg/chromium/content/app/SandboxedProcessService',
      'Lorg/chromium/content/browser/TouchPoint',
      'Lorg/chromium/content/browser/WaitableNativeEvent',
      'Lorg/chromium/content/common/DeviceInfo',
      'Lorg/chromium/content/common/SurfaceTextureListener',
      'Lorg/chromium/media/MediaPlayerListener',
      'Lorg/chromium/net/NetworkChangeNotifier',
      'Lorg/chromium/net/ProxyChangeListener',
  ]
  if param == 'byte[][]':
    return '[[B'
  prefix = ''
  # Array?
  if param[-2:] == '[]':
    prefix = '['
    param = param[:-2]
  # Generic?
  if '<' in param:
    param = param[:param.index('<')]
  if param in pod_param_map:
    return prefix + pod_param_map[param]
  for qualified_name in object_param_list + app_param_list:
    if (qualified_name.endswith('/' + param) or
        qualified_name.endswith('$' + param.replace('.', '$'))):
      return prefix + qualified_name + ';'
  else:
    return UNKNOWN_JAVA_TYPE_PREFIX + prefix + param + ';'

def JniSignature(params, returns, wrap):
  """Returns the JNI signature for the given datatypes."""
  items = ['(']
  items += [JavaParamToJni(param.datatype) for param in params]
  items += [')']
  items += [JavaParamToJni(returns)]
  if wrap:
    return '\n' + '\n'.join(['"' + item + '"' for item in items])
  else:
    return '"' + ''.join(items) + '"'

def ParseParams(params):
  """Parses the params into a list of Param objects."""
  if not params:
    return []
  ret = []
  for p in [p.strip() for p in params.split(',')]:
    items = p.split(' ')
    if 'final' in items:
      items.remove('final')
    param = Param(
        datatype=items[0],
        name=(items[1] if len(items) > 1 else 'p%s' % len(ret)),
    )
    ret += [param]
  return ret

def GetUnknownDatatypes(items):
  """Returns a list containing the unknown datatypes."""
  unknown_types = {}
  for item in items:
    all_datatypes = ([JavaParamToJni(param.datatype)
                      for param in item.params] +
                     [JavaParamToJni(item.return_type)])
    for d in all_datatypes:
      if d.startswith(UNKNOWN_JAVA_TYPE_PREFIX):
        unknown_types[d] = (unknown_types.get(d, []) +
                            [item.name or 'Unable to parse'])
  return unknown_types

def ExtractJNINamespace(contents):
  re_jni_namespace = re.compile('.*?@JNINamespace\("(.*?)"\)')
  m = re.findall(re_jni_namespace, contents)
  if not m:
    return ''
  return m[0]

def ExtractFullyQualifiedJavaClassName(java_file_name, contents):
  re_package = re.compile('.*?package (.*?);')
  matches = re.findall(re_package, contents)
  if not matches:
    raise SyntaxError('Unable to find "package" line in %s' % java_file_name)
  return (matches[0].replace('.', '/') + '/' +
          os.path.splitext(os.path.basename(java_file_name))[0])

def ExtractNatives(contents):
  """Returns a list of dict containing information about a native method."""
  contents = contents.replace('\n', '')
  natives = []
  re_native = re.compile(r'(@NativeClassQualifiedName'
                         '\(\"(?P<native_class_name>.*?)\"\))?\s*'
                         '(@NativeCall(\(\"(?P<java_class_name>.*?)\"\)))?\s*'
                         '(?P<qualifiers>\w+\s\w+|\w+|\s+)\s*?native '
                         '(?P<return>\S*?) '
                         '(?P<name>\w+?)\((?P<params>.*?)\);')
  for match in re.finditer(re_native, contents):
    native = NativeMethod(
        static='static' in match.group('qualifiers'),
        java_class_name=match.group('java_class_name'),
        native_class_name=match.group('native_class_name'),
        return_type=match.group('return'),
        name=match.group('name').replace('native', ''),
        params=ParseParams(match.group('params')))
    natives += [native]
  return natives

def GetEnvCallForReturnType(return_type):
  """Maps the types availabe via env->Call__Method."""
  env_call_map = {'boolean': ('Boolean', ''),
                  'byte': ('Byte', ''),
                  'char': ('Char', ''),
                  'short': ('Short', ''),
                  'int': ('Int', ''),
                  'long': ('Long', ''),
                  'float': ('Float', ''),
                  'void': ('Void', ''),
                  'double': ('Double', ''),
                  'String': ('Object', 'jstring'),
                  'Object': ('Object', ''),
                 }
  return env_call_map.get(return_type, ('Object', ''))

def GetMangledMethodName(name, jni_signature):
  """Returns a mangled method name for a (name, jni_signature) pair.

     The returned name can be used as a C identifier and will be unique for all
     valid overloads of the same method.

  Args:
     name: string.
     jni_signature: string.

  Returns:
      A mangled name.
  """
  sig_translation = string.maketrans('[()/;$', 'apq_xs')
  mangled_name = name + '_' + string.translate(jni_signature, sig_translation,
                                               '"')
  assert re.match(r'[0-9a-zA-Z_]+', mangled_name)
  return mangled_name

def MangleCalledByNatives(called_by_natives):
  """Mangles all the overloads from the call_by_natives list."""
  method_counts = collections.defaultdict(
      lambda: collections.defaultdict(lambda: 0))
  for called_by_native in called_by_natives:
    java_class_name = called_by_native.java_class_name
    name = called_by_native.name
    method_counts[java_class_name][name] += 1
  for called_by_native in called_by_natives:
    java_class_name = called_by_native.java_class_name
    method_name = called_by_native.name
    method_id_var_name = method_name
    if method_counts[java_class_name][method_name] > 1:
      jni_signature = JniSignature(called_by_native.params,
                                   called_by_native.return_type,
                                   False)
      method_id_var_name = GetMangledMethodName(method_name, jni_signature)
    called_by_native.method_id_var_name = method_id_var_name
  return called_by_natives

# Regex to match the JNI return types that should be included in a
# ScopedJavaLocalRef.
RE_SCOPED_JNI_RETURN_TYPES = re.compile('jobject|jclass|jstring|.*Array')

# Regex to match a string like "@CalledByNative public void foo(int bar)".
RE_CALLED_BY_NATIVE = re.compile(
    '@CalledByNative(?P<Unchecked>(Unchecked)*?)(?:\("(?P<annotation>.*)"\))?'
    '\s+(?P<prefix>[\w ]*?)'
    '\s*(?P<return_type>\w+)'
    '\s+(?P<name>\w+)'
    '\s*\((?P<params>[^\)]*)\)')

def ExtractCalledByNatives(contents):
  """Parses all methods annotated with @CalledByNative.

  Args:
    contents: the contents of the java file.

  Returns:
    A list of dict with information about the annotated methods.
    TODO(bulach): return a CalledByNative object.

  Raises:
    ParseError: if unable to parse.
  """
  called_by_natives = []
  for match in re.finditer(RE_CALLED_BY_NATIVE, contents):
    called_by_natives += [CalledByNative(
        system_class=False,
        unchecked='Unchecked' in match.group('Unchecked'),
        static='static' in match.group('prefix'),
        java_class_name=match.group('annotation') or '',
        return_type=match.group('return_type'),
        env_call=GetEnvCallForReturnType(match.group('return_type')),
        name=match.group('name'),
        params=ParseParams(match.group('params')))]
  # Check for any @CalledByNative occurrences that weren't matched.
  unmatched_lines = re.sub(RE_CALLED_BY_NATIVE, '', contents).split('\n')
  for line1, line2 in zip(unmatched_lines, unmatched_lines[1:]):
    if '@CalledByNative' in line1:
      raise ParseError('could not parse @CalledByNative method signature',
                       line1, line2)
  return MangleCalledByNatives(called_by_natives)

class JNIFromJavaP(object):
  """Uses 'javap' to parse a .class file and generate the JNI header file."""

  def __init__(self, contents, namespace):
    self.contents = contents
    self.namespace = namespace
    self.fully_qualified_class = re.match('.*?class (.*?) ',
                                          contents[1]).group(1)
    self.fully_qualified_class = self.fully_qualified_class.replace('.', '/')
    self.java_class_name = self.fully_qualified_class.split('/')[-1]
    if not self.namespace:
      self.namespace = 'JNI_' + self.java_class_name
    re_method = re.compile('(.*?)(\w+?) (\w+?)\((.*?)\)')
    self.called_by_natives = []
    for method in contents[2:]:
      match = re.match(re_method, method)
      if not match:
        continue
      self.called_by_natives += [CalledByNative(
          system_class=True,
          unchecked=False,
          static='static' in match.group(1),
          java_class_name='',
          return_type=match.group(2),
          name=match.group(3),
          params=ParseParams(match.group(4)),
          env_call=GetEnvCallForReturnType(match.group(2)))]
    self.called_by_natives = MangleCalledByNatives(self.called_by_natives)
    self.inl_header_file_generator = InlHeaderFileGenerator(
        self.namespace, self.fully_qualified_class, [], self.called_by_natives)

  def GetContent(self):
    return self.inl_header_file_generator.GetContent()

  @staticmethod
  def CreateFromClass(class_file, namespace):
    class_name = os.path.splitext(os.path.basename(class_file))[0]
    p = subprocess.Popen(args=['javap', class_name],
                         cwd=os.path.dirname(class_file),
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    stdout, _ = p.communicate()
    jni_from_javap = JNIFromJavaP(stdout.split('\n'), namespace)
    return jni_from_javap

class JNIFromJavaSource(object):
  """Uses the given java source file to generate the JNI header file."""

  def __init__(self, contents, fully_qualified_class):
    contents = self._RemoveComments(contents)
    jni_namespace = ExtractJNINamespace(contents)
    natives = ExtractNatives(contents)
    called_by_natives = ExtractCalledByNatives(contents)
    if len(natives) == 0 and len(called_by_natives) == 0:
      raise SyntaxError('Unable to find any JNI methods for %s.' %
                        fully_qualified_class)
    inl_header_file_generator = InlHeaderFileGenerator(
        jni_namespace, fully_qualified_class, natives, called_by_natives)
    self.content = inl_header_file_generator.GetContent()

  def _RemoveComments(self, contents):
    ret = []
    for c in [c.strip() for c in contents.split('\n')]:
      if not c.startswith('//'):
        ret += [c]
    return '\n'.join(ret)

  def GetContent(self):
    return self.content

  @staticmethod
  def CreateFromFile(java_file_name):
    contents = file(java_file_name).read()
    fully_qualified_class = ExtractFullyQualifiedJavaClassName(java_file_name,
                                                               contents)
    return JNIFromJavaSource(contents, fully_qualified_class)

class InlHeaderFileGenerator(object):
  """Generates an inline header file for JNI integration."""

  def __init__(self, namespace, fully_qualified_class, natives,
               called_by_natives):
    self.namespace = namespace
    self.fully_qualified_class = fully_qualified_class
    self.class_name = self.fully_qualified_class.split('/')[-1]
    self.natives = natives
    self.called_by_natives = called_by_natives
    self.header_guard = fully_qualified_class.replace('/', '_') + '_JNI'
    unknown_datatypes = GetUnknownDatatypes(self.natives +
                                            self.called_by_natives)
    if unknown_datatypes:
      msg = ('There are a few unknown datatypes in %s' %
             self.fully_qualified_class)
      msg += '\nPlease, edit %s' % sys.argv[0]
      msg += '\nand add the java type to JavaParamToJni()\n'
      for unknown_datatype in unknown_datatypes:
        msg += '\n%s in methods:\n' % unknown_datatype
        msg += '\n '.join(unknown_datatypes[unknown_datatype])
      raise SyntaxError(msg)

  def GetContent(self):
    """Returns the content of the JNI binding file."""
    template = Template("""\
// 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.

// This file is autogenerated by
//     ${SCRIPT_NAME}
// For
//     ${FULLY_QUALIFIED_CLASS}

#ifndef ${HEADER_GUARD}
#define ${HEADER_GUARD}

#include <jni.h>

#include "base/android/jni_android.h"
#include "base/android/scoped_java_ref.h"
#include "base/basictypes.h"
#include "base/logging.h"

using base::android::ScopedJavaLocalRef;

// Step 1: forward declarations.
namespace {
$CLASS_PATH_DEFINITIONS
}  // namespace

$OPEN_NAMESPACE
$FORWARD_DECLARATIONS

// Step 2: method stubs.
$METHOD_STUBS

// Step 3: GetMethodIDs and RegisterNatives.
static void GetMethodIDsImpl(JNIEnv* env) {
$GET_METHOD_IDS_IMPL
}

static bool RegisterNativesImpl(JNIEnv* env) {
  GetMethodIDsImpl(env);
$REGISTER_NATIVES_IMPL
  return true;
}
$CLOSE_NAMESPACE
#endif  // ${HEADER_GUARD}
""")
    script_components = os.path.abspath(sys.argv[0]).split(os.path.sep)
    base_index = script_components.index('base')
    script_name = os.sep.join(script_components[base_index:])
    values = {
        'SCRIPT_NAME': script_name,
        'FULLY_QUALIFIED_CLASS': self.fully_qualified_class,
        'CLASS_PATH_DEFINITIONS': self.GetClassPathDefinitionsString(),
        'FORWARD_DECLARATIONS': self.GetForwardDeclarationsString(),
        'METHOD_STUBS': self.GetMethodStubsString(),
        'OPEN_NAMESPACE': self.GetOpenNamespaceString(),
        'NAMESPACE': self.GetNamespaceString(),
        'GET_METHOD_IDS_IMPL': self.GetMethodIDsImplString(),
        'REGISTER_NATIVES_IMPL': self.GetRegisterNativesImplString(),
        'CLOSE_NAMESPACE': self.GetCloseNamespaceString(),
        'HEADER_GUARD': self.header_guard,
    }
    return WrapOutput(template.substitute(values))

  def GetClassPathDefinitionsString(self):
    ret = []
    ret += [self.GetClassPathDefinitions()]
    return '\n'.join(ret)

  def GetForwardDeclarationsString(self):
    ret = []
    for native in self.natives:
      if native.type != 'method':
        ret += [self.GetForwardDeclaration(native)]
    return '\n'.join(ret)

  def GetMethodStubsString(self):
    ret = []
    for native in self.natives:
      if native.type == 'method':
        ret += [self.GetNativeMethodStub(native)]
    for called_by_native in self.called_by_natives:
      ret += [self.GetCalledByNativeMethodStub(called_by_native)]
    return '\n'.join(ret)

  def GetKMethodsString(self, clazz):
    ret = []
    for native in self.natives:
      if (native.java_class_name == clazz or
          (not native.java_class_name and clazz == self.class_name)):
        ret += [self.GetKMethodArrayEntry(native)]
    return '\n'.join(ret)

  def GetMethodIDsImplString(self):
    ret = []
    ret += [self.GetFindClasses()]
    for called_by_native in self.called_by_natives:
      ret += [self.GetMethodIDImpl(called_by_native)]
    return '\n'.join(ret)

  def GetRegisterNativesImplString(self):
    """Returns the implementation for RegisterNatives."""
    template = Template("""\
  static const JNINativeMethod kMethods${JAVA_CLASS}[] = {
${KMETHODS}
  };
  const int kMethods${JAVA_CLASS}Size = arraysize(kMethods${JAVA_CLASS});

  if (env->RegisterNatives(g_${JAVA_CLASS}_clazz,
                           kMethods${JAVA_CLASS},
                           kMethods${JAVA_CLASS}Size) < 0) {
    LOG(ERROR) << "RegisterNatives failed in " << __FILE__;
    return false;
  }
""")
    ret = []
    all_classes = self.GetUniqueClasses(self.natives)
    all_classes[self.class_name] = self.fully_qualified_class
    for clazz in all_classes:
      kmethods = self.GetKMethodsString(clazz)
      if kmethods:
        values = {'JAVA_CLASS': clazz,
                  'KMETHODS': kmethods}
        ret += [template.substitute(values)]
    if not ret: return ''
    return '\n' + '\n'.join(ret)

  def GetOpenNamespaceString(self):
    if self.namespace:
      return 'namespace %s {' % self.namespace
    return ''

  def GetNamespaceString(self):
    if self.namespace:
      return '%s::' % self.namespace
    return ''

  def GetCloseNamespaceString(self):
    if self.namespace:
      return '}  // namespace %s\n' % self.namespace
    return ''

  def GetJNIFirstParam(self, native):
    ret = []
    if native.type == 'method':
      ret = ['jobject obj']
    elif native.type == 'function':
      if native.static:
        ret = ['jclass clazz']
      else:
        ret = ['jobject obj']
    return ret

  def GetParamsInDeclaration(self, native):
    """Returns the params for the stub declaration.

    Args:
      native: the native dictionary describing the method.

    Returns:
      A string containing the params.
    """
    return ',\n    '.join(self.GetJNIFirstParam(native) +
                          [JavaDataTypeToC(param.datatype) + ' ' +
                           param.name
                           for param in native.params])

  def GetCalledByNativeParamsInDeclaration(self, called_by_native):
    return ',\n    '.join([JavaDataTypeToC(param.datatype) + ' ' +
                           param.name
                           for param in called_by_native.params])

  def GetForwardDeclaration(self, native):
    template = Template("""
static ${RETURN} ${NAME}(JNIEnv* env, ${PARAMS});
""")
    values = {'NAMESPACE': self.GetNamespaceString(),
              'RETURN': JavaDataTypeToC(native.return_type),
              'NAME': native.name,
              'PARAMS': self.GetParamsInDeclaration(native)}
    return template.substitute(values)

  def GetNativeMethodStub(self, native):
    """Returns stubs for native methods."""
    template = Template("""\
static ${RETURN} ${NAME}(JNIEnv* env, ${PARAMS_IN_DECLARATION}) {
  DCHECK(${PARAM0_NAME}) << "${NAME}";
  ${P0_TYPE}* native = reinterpret_cast<${P0_TYPE}*>(${PARAM0_NAME});
  return native->${NAME}(env, obj${PARAMS_IN_CALL})${POST_CALL};
}
""")
    params_for_call = ', '.join(p.name for p in native.params[1:])
    if params_for_call:
      params_for_call = ', ' + params_for_call

    return_type = JavaDataTypeToC(native.return_type)
    if re.match(RE_SCOPED_JNI_RETURN_TYPES, return_type):
      scoped_return_type = 'ScopedJavaLocalRef<' + return_type + '>'
      post_call = '.Release()'
    else:
      scoped_return_type = return_type
      post_call = ''
    values = {
        'RETURN': return_type,
        'SCOPED_RETURN': scoped_return_type,
        'NAMESPACE': self.GetNamespaceString(),
        'NAME': native.name,
        'PARAMS_IN_DECLARATION': self.GetParamsInDeclaration(native),
        'PARAM0_NAME': native.params[0].name,
        'P0_TYPE': native.p0_type,
        'PARAMS_IN_CALL': params_for_call,
        'POST_CALL': post_call
    }
    return template.substitute(values)

  def GetCalledByNativeMethodStub(self, called_by_native):
    """Returns a string."""
    function_signature_template = Template("""\
static ${RETURN_TYPE} Java_${JAVA_CLASS}_${METHOD}(\
JNIEnv* env${FIRST_PARAM_IN_DECLARATION}${PARAMS_IN_DECLARATION})""")
    function_header_template = Template("""\
${FUNCTION_SIGNATURE} {""")
    function_header_with_unused_template = Template("""\
${FUNCTION_SIGNATURE} __attribute__ ((unused));
${FUNCTION_SIGNATURE} {""")
    template = Template("""
static jmethodID g_${JAVA_CLASS}_${METHOD_ID_VAR_NAME} = 0;
${FUNCTION_HEADER}
  /* Must call RegisterNativesImpl()  */
  DCHECK(g_${JAVA_CLASS}_clazz);
  DCHECK(g_${JAVA_CLASS}_${METHOD_ID_VAR_NAME});
  ${RETURN_DECLARATION}
  ${PRE_CALL}env->Call${STATIC}${ENV_CALL}Method(${FIRST_PARAM_IN_CALL},
      g_${JAVA_CLASS}_${METHOD_ID_VAR_NAME}${PARAMS_IN_CALL})${POST_CALL};
  ${CHECK_EXCEPTION}
  ${RETURN_CLAUSE}
}""")
    if called_by_native.static:
      first_param_in_declaration = ''
      first_param_in_call = ('g_%s_clazz' %
                             (called_by_native.java_class_name or
                              self.class_name))
    else:
      first_param_in_declaration = ', jobject obj'
      first_param_in_call = 'obj'
    params_in_declaration = self.GetCalledByNativeParamsInDeclaration(
        called_by_native)
    if params_in_declaration:
      params_in_declaration = ', ' + params_in_declaration
    params_for_call = ', '.join(param.name
                                for param in called_by_native.params)
    if params_for_call:
      params_for_call = ', ' + params_for_call
    pre_call = ''
    post_call = ''
    if called_by_native.env_call[1]:
      pre_call = 'static_cast<%s>(' % called_by_native.env_call[1]
      post_call = ')'
    check_exception = ''
    if not called_by_native.unchecked:
      check_exception = 'base::android::CheckException(env);'
    return_type = JavaDataTypeToC(called_by_native.return_type)
    return_declaration = ''
    return_clause = ''
    if return_type != 'void':
      pre_call = '  ' + pre_call
      return_declaration = return_type + ' ret ='
      if re.match(RE_SCOPED_JNI_RETURN_TYPES, return_type):
        return_type = 'ScopedJavaLocalRef<' + return_type + '>'
        return_clause = 'return ' + return_type + '(env, ret);'
      else:
        return_clause = 'return ret;'
    values = {
        'JAVA_CLASS': called_by_native.java_class_name or self.class_name,
        'METHOD': called_by_native.name,
        'RETURN_TYPE': return_type,
        'RETURN_DECLARATION': return_declaration,
        'RETURN_CLAUSE': return_clause,
        'FIRST_PARAM_IN_DECLARATION': first_param_in_declaration,
        'PARAMS_IN_DECLARATION': params_in_declaration,
        'STATIC': 'Static' if called_by_native.static else '',
        'PRE_CALL': pre_call,
        'POST_CALL': post_call,
        'ENV_CALL': called_by_native.env_call[0],
        'FIRST_PARAM_IN_CALL': first_param_in_call,
        'PARAMS_IN_CALL': params_for_call,
        'METHOD_ID_VAR_NAME': called_by_native.method_id_var_name,
        'CHECK_EXCEPTION': check_exception,
    }
    values['FUNCTION_SIGNATURE'] = (
        function_signature_template.substitute(values))
    if called_by_native.system_class:
      values['FUNCTION_HEADER'] = (
          function_header_with_unused_template.substitute(values))
    else:
      values['FUNCTION_HEADER'] = function_header_template.substitute(values)
    return template.substitute(values)

  def GetKMethodArrayEntry(self, native):
    template = Template("""\
    { "native${NAME}", ${JNI_SIGNATURE}, reinterpret_cast<void*>(${NAME}) },""")
    values = {'NAME': native.name,
              'JNI_SIGNATURE': JniSignature(native.params, native.return_type,
                                            True)}
    return template.substitute(values)

  def GetUniqueClasses(self, origin):
    ret = {self.class_name: self.fully_qualified_class}
    for entry in origin:
      class_name = self.class_name
      jni_class_path = self.fully_qualified_class
      if entry.java_class_name:
        class_name = entry.java_class_name
        jni_class_path = self.fully_qualified_class + '$' + class_name
      ret[class_name] = jni_class_path
    return ret

  def GetClassPathDefinitions(self):
    """Returns the ClassPath constants."""
    ret = []
    template = Template("""\
const char k${JAVA_CLASS}ClassPath[] = "${JNI_CLASS_PATH}";""")
    native_classes = self.GetUniqueClasses(self.natives)
    called_by_native_classes = self.GetUniqueClasses(self.called_by_natives)
    all_classes = native_classes
    all_classes.update(called_by_native_classes)
    for clazz in all_classes:
      values = {
          'JAVA_CLASS': clazz,
          'JNI_CLASS_PATH': all_classes[clazz],
      }
      ret += [template.substitute(values)]
    ret += ''
    for clazz in called_by_native_classes:
      template = Template("""\
// Leaking this jclass as we cannot use LazyInstance from some threads.
jclass g_${JAVA_CLASS}_clazz = NULL;""")
      values = {
          'JAVA_CLASS': clazz,
      }
      ret += [template.substitute(values)]
    return '\n'.join(ret)

  def GetFindClasses(self):
    """Returns the imlementation of FindClass for all known classes."""
    template = Template("""\
  g_${JAVA_CLASS}_clazz = reinterpret_cast<jclass>(env->NewGlobalRef(
      base::android::GetUnscopedClass(env, k${JAVA_CLASS}ClassPath)));""")
    ret = []
    for clazz in self.GetUniqueClasses(self.called_by_natives):
      values = {'JAVA_CLASS': clazz}
      ret += [template.substitute(values)]
    return '\n'.join(ret)

  def GetMethodIDImpl(self, called_by_native):
    """Returns the implementation of GetMethodID."""
    template = Template("""\
  g_${JAVA_CLASS}_${METHOD_ID_VAR_NAME} =
      base::android::Get${STATIC}MethodID(
          env, g_${JAVA_CLASS}_clazz,
          "${NAME}",
          ${JNI_SIGNATURE});
""")
    values = {
        'JAVA_CLASS': called_by_native.java_class_name or self.class_name,
        'NAME': called_by_native.name,
        'METHOD_ID_VAR_NAME': called_by_native.method_id_var_name,
        'STATIC': 'Static' if called_by_native.static else '',
        'JNI_SIGNATURE': JniSignature(called_by_native.params,
                                      called_by_native.return_type,
                                      True)
    }
    return template.substitute(values)

def WrapOutput(output):
  ret = []
  for line in output.splitlines():
    if len(line) < 80:
      stripped = line.rstrip()
      if len(ret) == 0 or len(ret[-1]) or len(stripped):
        ret.append(stripped)
    else:
      first_line_indent = ' ' * (len(line) - len(line.lstrip()))
      subsequent_indent =  first_line_indent + ' ' * 4
      if line.startswith('//'):
        subsequent_indent = '//' + subsequent_indent
      wrapper = textwrap.TextWrapper(width=80,
                                     subsequent_indent=subsequent_indent,
                                     break_long_words=False)
      ret += [wrapped.rstrip() for wrapped in wrapper.wrap(line)]
  ret += ['']
  return '\n'.join(ret)

def ExtractJarInputFile(jar_file, input_file, out_dir):
  """Extracts input file from jar and returns the filename.

  The input file is extracted to the same directory that the generated jni
  headers will be placed in.  This is passed as an argument to script.

  Args:
    jar_file: the jar file containing the input files to extract.
    input_files: the list of files to extract from the jar file.
    out_dir: the name of the directories to extract to.

  Returns:
    the name of extracted input file.
  """
  jar_file = zipfile.ZipFile(jar_file)

  out_dir = os.path.join(out_dir, os.path.dirname(input_file))
  if not os.path.exists(out_dir):
    os.makedirs(out_dir)
  extracted_file_name = os.path.join(out_dir, os.path.basename(input_file))
  with open(extracted_file_name, 'w') as outfile:
    outfile.write(jar_file.read(input_file))

  return extracted_file_name

def GenerateJNIHeader(input_file, output_file, namespace):
  try:
    if os.path.splitext(input_file)[1] == '.class':
      jni_from_javap = JNIFromJavaP.CreateFromClass(input_file, namespace)
      content = jni_from_javap.GetContent()
    else:
      jni_from_java_source = JNIFromJavaSource.CreateFromFile(input_file)
      content = jni_from_java_source.GetContent()
  except ParseError, e:
    print e
    sys.exit(1)
  if output_file:
    if not os.path.exists(os.path.dirname(os.path.abspath(output_file))):
      os.makedirs(os.path.dirname(os.path.abspath(output_file)))
    with file(output_file, 'w') as f:
      f.write(content)
  else:
    print output

def main(argv):
  usage = """usage: %prog [OPTIONS]
This script will parse the given java source code extracting the native
declarations and print the header file to stdout (or a file).
See SampleForTests.java for more details.
  """
  option_parser = optparse.OptionParser(usage=usage)
  option_parser.add_option('-j', dest='jar_file',
                           help='Extract the list of input files from'
                           ' a specified jar file.'
                           ' Uses javap to extract the methods from a'
                           ' pre-compiled class. --input should point'
                           ' to pre-compiled Java .class files.')
  option_parser.add_option('-n', dest='namespace',
                           help='Uses as a namespace in the generated header,'
                           ' instead of the javap class name.')
  option_parser.add_option('--input_file',
                           help='Single input file name. The output file name '
                           'will be derived from it. Must be used with '
                           '--output_dir.')
  option_parser.add_option('--output_dir',
                           help='The output directory. Must be used with '
                           '--input')
  options, args = option_parser.parse_args(argv)
  if options.jar_file:
    input_file = ExtractJarInputFile(options.jar_file, options.input_file,
                                     options.output_dir)
  else:
    input_file = options.input_file
  output_file = None
  if options.output_dir:
    root_name = os.path.splitext(os.path.basename(input_file))[0]
    output_file = os.path.join(options.output_dir, root_name) + '_jni.h'
  GenerateJNIHeader(input_file, output_file, options.namespace)

if __name__ == '__main__':
  sys.exit(main(sys.argv))


text:
html {
	background: url(../images/background.jpg) no-repeat center center fixed;
	-webkit-background-size: cover;
	-moz-background-size: cover;
	-o-background-size: cover;
	background-size: cover;
}

body {
	background-color: transparent;
}

.maincontainer {
	margin-top: 50px;
	padding-top: 20px;
}

.bold {
	font-weight: bold;
}

.navspan {
	position: relative;
	display: block;
	padding: 15px;
	color: #777;
	line-height: 20px;
}

.navspan:hover {
	color: #333;
	cursor: pointer;
}

.navspan {
	position: relative;
	display: block;
	padding: 15px;
	color: #777;
	line-height: 20px;
}

.dropdown-menu .navspan {
	display: block;
	padding: 3px 20px;
	clear: both;
	color: #777;
	line-height: 20px;
}

.dropdown-menu .navspan:hover {
	color: #262626;
	cursor: pointer;
	background-color: #f5f5f5;
}

#module {
	width: 60%;
	height: 500px;
}

.centertext {
	text-align: center;
}

.dpt-arrow-btn {
	font-size: 40px;
	margin: 5px;
}

.table tbody tr td {
    border-bottom: 1px solid #ddd;
}

.dpt-row {
    border-bottom: 1px solid #ddd;
    border-top: 1px solid #ddd;
    margin-left: 5px;
    margin-right: 5px;
    padding: 8px;
    margin-top: -1px;
}

/*
 * https://github.com/jschr/bootstrap-modal/
 */

 .modal {
	overflow: visible !important;
 }

 .modal-footer {
	padding: 10px !important;
 }

.bootstrap-dialog {

}
.bootstrap-dialog .modal-header {
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
	height: 37px;
	padding: 10px;
}
.bootstrap-dialog .bootstrap-dialog-title {
    color: #000;
    display: inline-block;
}
.bootstrap-dialog.type-default .bootstrap-dialog-title {
    color: #333;
}
.bootstrap-dialog .bootstrap-dialog-title {
    font-size: 16px;
}
.bootstrap-dialog.size-large .bootstrap-dialog-title {
    font-size: 24px;
}
.bootstrap-dialog .bootstrap-dialog-close-button {
    float: right;
    filter:alpha(opacity=90);
    -moz-opacity:0.9;
    -khtml-opacity: 0.9;
    opacity: 0.9;
}
.bootstrap-dialog .bootstrap-dialog-close-button {
    font-size: 20px;
}
.bootstrap-dialog.size-large .bootstrap-dialog-close-button {
    font-size: 30px;
}
.bootstrap-dialog .bootstrap-dialog-close-button:hover {
    cursor: pointer;
    filter: alpha(opacity=100);
    -moz-opacity: 1;
    -khtml-opacity: 1;
    opacity: 1;
}
.bootstrap-dialog .bootstrap-dialog-message {
    font-size: 14px;
}
.bootstrap-dialog.size-large .bootstrap-dialog-message {
    font-size: 18px;
}
.bootstrap-dialog.type-default .modal-header {
    background-color: #f5f5f5;
}
.bootstrap-dialog.type-info .modal-header {
    background-color: #f5f5f5;
}
.bootstrap-dialog.type-primary .modal-header {
    background-color: #f5f5f5;
}
.bootstrap-dialog.type-success .modal-header {
    background-color: #5cb85c;
}
.bootstrap-dialog.type-warning .modal-header {
    background-color: #f0ad4e;
}
.bootstrap-dialog.type-danger .modal-header {
    background-color: #d9534f;
}
.bootstrap-dialog .bootstrap-dialog-button-icon {
    margin-right: 3px;
}

/**
 * Icon animation
 * Copied from font-awesome: http://fontawesome.io/
 **/
.icon-spin {
    display: inline-block;
    -moz-animation: spin 2s infinite linear;
    -o-animation: spin 2s infinite linear;
    -webkit-animation: spin 2s infinite linear;
    animation: spin 2s infinite linear;
}
@-moz-keyframes spin {
    0% {
    -moz-transform: rotate(0deg);
}
100% {
    -moz-transform: rotate(359deg);
}
}
@-webkit-keyframes spin {
    0% {
    -webkit-transform: rotate(0deg);
}
100% {
    -webkit-transform: rotate(359deg);
}
}
@-o-keyframes spin {
    0% {
    -o-transform: rotate(0deg);
}
100% {
    -o-transform: rotate(359deg);
}
}
@-ms-keyframes spin {
    0% {
    -ms-transform: rotate(0deg);
}
100% {
    -ms-transform: rotate(359deg);
}
}
@keyframes spin {
    0% {
    transform: rotate(0deg);
}
100% {
    transform: rotate(359deg);
}
}
/** End of icon animation **/


text:
title: Rational zeros of a function of three variables
localeTitle: 三个变量函数的有理零点
---
## 问题180:三个变量函数的有理零点

这是一个存根。 [帮助我们的社区扩展它](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/project-euler/problem-180-rational-zeros-of-a-function-of-three-variables/index.md) 。

[这种快速风格指南有助于确保您的拉取请求被接受](https://github.com/freecodecamp/guides/blob/master/README.md) 。


text:
html, body {
    padding: 0;
    margin: 0;
    background-color: #f0f0f0;
}
#content {
    padding: 8px;
    margin: 0 auto;
}

.rtl {
    direction:rtl;
}
img {
    display: block;
    background-color: #e6e7e8;
    padding: 0;
    margin: 0;
}
.fullwidth_img,
.inline_img {
    position: relative;
}
.fullwidth_img {
    margin-bottom: 1.3rem;
    border-bottom: 1px solid #c4c4c4;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -webkitTouchCallout: none;
}
.fullwidth_img:first-of-type {
    border-bottom: none;
}
.inline_img {
    float: right;
    margin: 0.8rem 0 0.8rem 0.8rem;
}
.rtl .inline_img {
    float: left;
    margin: 0.8rem 0.8rem 0.8rem 0;
}
.fullwidth_img,
.inline_img {
    display: block;
    clear: both;
/*
    Causing some issues and byproducts that require performance hit. Disabling.
    display: none; /* as part of NEWSAPPS-368 */
*/
}
.inline_img + .bbc-caption {
    float: right;
    clear: right;
}
.rtl .inline_img + .bbc-caption {
    float: left;
    clear: left;
}
.inline_img_caption {
    border-bottom: 1px solid #c4c4c4;
}
.playVideoIcon, .playAudioIcon {
    position: absolute;
    top: 0;
    left: 0;
    display: block;
    width: 100%;
    height: 100%;
    background-size: 91px 91px;
    background-repeat: no-repeat;
    border: 0;
    opacity: 0.9;
}

.inline_img .playVideoIcon,
.inline_img .playAudioIcon {
    background-size: 44px 44px;
}

/* Retina or not */
@media only screen and (-webkit-device-pixel-ratio: 1) {
    .playVideoIcon {
        background-image:url(overlay_video.png);
    }
    .playVideoOverIcon {
        background-image:url(overlay_video_touch.png);
    }
    .playAudioIcon {
        background-image:url(overlay_audio.png);
    }
    .playAudioOverIcon {
        background-image:url(overlay_audio_touch.png);
    }
}
@media only screen and (-webkit-device-pixel-ratio: 2) {
    .playVideoIcon {
        background-image:url(overlay_video@2x.png);
    }
    .playVideoOverIcon {
        background-image:url(overlay_video_touch@2x.png);
    }
    .playAudioIcon {
        background-image:url(overlay_audio@2x.png);
    }
    .playAudioOverIcon {
        background-image:url(overlay_audio_touch@2x.png);
    }
}


text:
using BehaviourTree.Demo.EventListeners;
using BehaviourTree.Demo.GameEngine;
using BehaviourTree.Demo.Systems;
using BehaviourTree.Demo.UI;
using System;
using System.Windows.Forms;

namespace BehaviourTree.Demo
{
    internal static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        public static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var engine = new Engine();

            using (var renderSystem = new HostForm())
            {
                renderSystem.Show();

                var mapSize = renderSystem.ClientRectangle.Size;

                var world = new World(engine, mapSize, renderSystem.Font);
                world.Create();

                engine.AddSystem(new HealthSystem(engine));
                engine.AddSystem(new StaminaSystem(engine));
                engine.AddSystem(new AiSystem(engine));
                engine.AddSystem(new MoveSystem(engine, mapSize));
                engine.AddSystem(new LootableSystem(engine));
                engine.AddSystem(new UserInputsSystem());
                engine.SubscribeToEvent(new OnCharacterDeathAddTombstone());
                engine.SubscribeToEvent(new OnCharacterDeathDropBackpack());
                engine.SubscribeToEvent(new OnHealthReachedZeroRemoveEntity());
                engine.SubscribeToEvent(new OnEntityRemovedClearTargets());

                engine.AddRenderSystem(renderSystem);
                engine.AddRenderSystem(new RenderRenderableComponentsSystem(engine, renderSystem.Graphics));
                engine.AddRenderSystem(new RenderHealthBarSystem(engine, renderSystem.Graphics));
                engine.AddRenderSystem(new RenderStaminaBarSystem(engine, renderSystem.Graphics));
                engine.AddRenderSystem(new RenderInventorySystem(engine, renderSystem.Graphics, renderSystem.Font));

                var gameRunner = new GameRunner(engine);

                gameRunner.Run(shouldStop: () => !renderSystem.Created);
            }
        }
    }
}


text:
<?php

namespace RapidRoute\Tests\Helpers;

use RapidRoute\RouteCollection;

/**
 * @author Elliot Levin <elliotlevin@hotmail.com>
 */
class CustomRouteCollection extends RouteCollection
{

}


text:
import React from 'react';
export default class Message extends React.Component {
    render() {
        return (

{this.props.author}:{this.props.children}
                <button onClick={()=>{this.props.click(this.props.id)}} className="btn btn-danger">删除</button> {this.props.date&&this.props.date.toLocaleString()}

        )
    }
}


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

		<meta http-equiv="content-type" content="text/html; charset=utf-8" />
		<link rel="shortcut icon" type="image/ico" href="http://www.sprymedia.co.uk/media/images/favicon.ico" />

		<title>DataTables example</title>

				DataTables server-side processing with user selectable rows example

Preamble

When you want to detail with user selectable rows and DataTables, it is relatively simple when using DOM based data - but if using server-side processing, DataTables doesn't retain state over pages / filters etc, leaving this to the server-side instead. As such, you will need to keep a track of which rows a user as selected and mark them as selected on each draw. This is shown in this demo, which uses a unique ID in the first (and hidden) column.

Credit for this example belongs with forum member iuliandum. Thanks!

Live example

			ID
			Rendering engine
			Browser
			Platform(s)
			Engine version
			CSS grade

			Loading data from server

			ID
			Rendering engine
			Browser
			Platform(s)
			Engine version
			CSS grade

Initialisation code

var oTable;
var gaiSelected =  [];

$(document).ready(function() {
	$('#form').submit( function() {
		alert (gaiSelected);
		return false;
	} );

	/* Init the table */
	oTable = $("#example").dataTable({
		"bProcessing": true,
		"bServerSide": true,
		"sAjaxSource": "../examples_support/server_processing_id.php",
		"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
			if ( jQuery.inArray(aData[0], gaiSelected) != -1 )
			{
				$(nRow).addClass('row_selected');
			}
			return nRow;
		},
		"aoColumns": [
			{ "bVisible": 0, "aTargets": [0] }
		]
	});

	/* Click event handler */
	$('#example tbody tr').live('click', function () {
		var aData = oTable.fnGetData( this );
		var iId = aData[0];

		if ( jQuery.inArray(iId, gaiSelected) == -1 )
		{
			gaiSelected[gaiSelected.length++] = iId;
		}
		else
		{
			gaiSelected = jQuery.grep(gaiSelected, function(value) {
				return value != iId;
			} );
		}

		$(this).toggleClass('row_selected');
	} );
} );

Other examples

Basic initialisation

Zero configuration

Feature enablement

Sorting data

Multi-column sorting

Multiple tables

Hidden columns

DOM positioning

State saving

Alternative pagination styles

Scrolling:
					Horizontal /
					Vertical /
					Both /
					Themed

Change language information (internationalisation)

ThemeRoller themes (Smoothness)

Advanced initialisation

Events (pre initialisation)

Events (post initialisation)

Column rendering

Sorting without HTML tags

Multiple table controls (sDom)

Defining length menu options

Custom toolbar (element) around table

Row highlighting with CSS

Column grouping through col/row spans

Row grouping

Row callback

Footer callback

Change language information from a file (internationalisation)

Data sources

DOM

Javascript array

Ajax source

Server side processing

Server-side processing

Obtain server-side data

Add extra HTTP variables

Use HTTP POST

Custom column ordering (in callback data)

Pipelining data (reduce Ajax calls for paging)

Show and hide details about a particular record

User selectable rows (multiple rows)

API

Dynamically add a new row

Individual column filtering (using "input" elements)

Individual column filtering (using "select" elements)

Highlight rows and columns

Show and hide details about a particular record

User selectable rows (multiple rows)

User selectable rows (single row) and delete rows

Editable rows (with jEditable)

Submit form with elements in table

Index column (static number column)

Show and hide columns dynamically

API function use in initialisation object (callback)

DataTables scrolling and tabs

Regular expression filtering

Plug-ins

Add custom API functions

Sorting and type detection

Custom pagination controls

Range filtering / custom filtering

Live DOM sorting

Automatic HTML type detection

Please refer to the DataTables documentation for full information about its API properties and methods.

				DataTables © Allan Jardine 2008-2010


text:
"""
Encodes WAV files from cdparanoia ("trackNN.cdda.wav") to MP3 format.

Processing is done in parallel using as many subprocesses as the machine has
cores.

Information w.r.t. artist, song titles et cetera is gathered from a text file
called "album.json", which should have the following info;

    {
        "title": "title of the album",
        "artist": "name of the artist",
        "year": 1985,
        "genre": "rock",
        "tracks": [
            "foo",
            "bar",
            "spam",
            "eggs"
        ]
    }
"""

from functools import partial
import argparse
import concurrent.futures as cf
import json
import logging
import os
import subprocess as sp
import sys

__version__ = "2020.04.01"

def main():
    """Entry point for make-mp3."""
    tfn = "album.json"
    with open(tfn) as jf:
        data = json.load(jf)
    keys = data.keys()
    for key in ["title", "year", "genre", "artist", "tracks"]:
        if key not in keys:
            logging.error(f'key "{key}" not in "{tfn}"')
            sys.exit(1)
    logging.info("album name: " + data["title"])
    logging.info("artist: " + data["artist"])
    logging.info("year: " + str(data["year"]))
    logging.info("genre: " + data["genre"])
    num = len(data["tracks"])
    with cf.ThreadPoolExecutor(max_workers=os.cpu_count()) as tp:
        for idx, rv in tp.map(partial(runmp3, data=data), range(num)):
            tnum = idx + 1
            if rv == 0:
                tt = data["tracks"][idx]
                logging.info(f'finished track {tnum}, "{tt}"')
            else:
                logging.error(f"conversion of track {tnum} failed, return code {rv}")

def setup():
    """Process command-line arguments. Check for required programs."""
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--log",
        default="warning",
        choices=["debug", "info", "warning", "error"],
        help="logging level (defaults to 'warning')",
    )
    parser.add_argument("-v", "--version", action="version", version=__version__)
    args = parser.parse_args(sys.argv[1:])
    logging.basicConfig(
        level=getattr(logging, args.log.upper(), None),
        format="%(levelname)s: %(message)s",
    )
    logging.debug(f"command line arguments = {sys.argv}")
    logging.debug(f"parsed arguments = {args}")
    # Check for required programs.
    try:
        sp.run(["lame"], stdout=sp.DEVNULL, stderr=sp.DEVNULL)
        logging.info("found "lame"")
    except FileNotFoundError:
        logging.error("the program "lame" cannot be found")
        sys.exit(1)

def runmp3(idx, data):
    """
    Use the lame(1) program to convert a music file to MP3 format.

    Arguments:
        idx: track index (starts from 0)
        data: album data dictionary

    Returns:
        A tuple containing the track index and return value of lame.
    """
    num = idx + 1
    args = [
        "lame",
        "-S",
        "--preset",
        "standard",
        "--tt",
        data["tracks"][idx],
        "--ta",
        data["artist"],
        "--tl",
        data["title"],
        "--ty",
        str(data["year"]),
        "--tn",
        "{:02d}".format(num),
        "--tg",
        data["genre"],
        f"track{num:02d}.cdda.wav",
        f"track{num:02d}.mp3",
    ]
    p = sp.run(args, stdout=sp.DEVNULL, stderr=sp.DEVNULL)
    return (idx, p.returncode)

if __name__ == "__main__":
    main()


text:
WallRide
========
[![Build Status](https://travis-ci.org/tagbangers/wallride.svg?branch=master)](https://travis-ci.org/tagbangers/wallride) [![Join the chat at https://gitter.im/talk-wallride/Lobby](https://badges.gitter.im/talk-wallride/Lobby.svg)](https://gitter.im/talk-wallride/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

WallRide is a multilingual easy-to-customize open source CMS made by 100% pure Java,
using [Spring Framework](http://projects.spring.io/spring-framework/), [Hibernate](http://hibernate.org/) and [Thymeleaf](http://www.thymeleaf.org/).

WallRide focuses on sophisticated UI, simple and clean source code
and easy deploy to AWS BeansTalk(of course other servlet containers)

We hope this CMS is loved by many developers of principles all over the world.

Documentation
========
[Documentation is here.](http://wallride.org/docs/guide.html)

Screen Shots
========
[Screen Shots is here.](https://github.com/tagbangers/wallride/wiki/Screen-shots)


text:
<?php

defined('KAZINDUZI_PATH') or exit('No direct script access allowed');

/**
 * Description of cart
 *
 * @author Emmanuel_Leonie
 */
class Cart
{

    private static $_instance;
    private $config = array();
    private $session = false;
    private $data = array();

    /**
     *
     * @param array $data
     */
    public function __construct(array $data = array())
    {
        $this->data = $data;
        $this->config = \Kazinduzi::getConfig('session');
        $this->session = \Kazinduzi::session();
        if (!$this->session->get('cart') || !is_array($this->session->get('cart'))) {
            $this->session->add('cart', $this->data);
        }
    }

    /**
     * Create a singleton for the Customer
     * @return mixed
     */
    public static function getSingleton()
    {
        if (static::$_instance === null) {
            static::$_instance = new static();
        }
        return static::$_instance;
    }

    /**
     *
     * @param type $productid
     * @param int|type $qty
     * @param array $options
     * @return bool|Cart
     * @throws Exception
     */
    public function add($productid, $qty = 1, array $options = [])
    {
        if (!$options) {
            $key = $productid;
        } else {
            $key = $productid . ':' . base64_encode(serialize($options));
        }
        if (is_numeric($qty) && ((int) $qty > 0)) {
            if (!array_key_exists($key, $__cart_data = $this->session->get('cart'))) {
                $__cart_data[$key] = (int) $qty;
            } else {
                $__cart_data[$key] += (int) $qty;
            }
            $this->session->add('cart', $__cart_data);
            return $this;
        }
        return false;
    }

    /**
     *
     * @param type $key
     * @param type $qty
     * @return Cart
     * @throws Exception
     */
    public function update($key, $qty)
    {
        if (!is_numeric($qty))
            throw new Exception('Invalid quantity provided', 1000);
        if ((int) $qty && ((int) $qty > 0) && array_key_exists($key, $data = $this->session->get('cart'))) {
            $data[$key] = (int) $qty;
            $this->session->add('cart', $data);
        } else {
            $this->remove($key);
        }
        return $this;
    }

    /**
     * Remove item from the cart
     * @param string $key
     * @return \Cart
     */
    public function remove($key)
    {
        if (array_key_exists($key, $data = $this->session->get('cart'))) {
            if (isset($data[$key])) {
                unset($data[$key]);
            }
            $this->session->add('cart', $data);
        }
        return $this;
    }

    /**
     * Alias for the clear method
     * @return boolean
     */
    public function destroy()
    {
        $this->clear();
        return true;
    }

    /**
     * Clear or destroy the cart
     * @return boolean
     */
    public function clear()
    {
        if ($this->session->get('cart')) {
            $this->session->remove('cart');
        }
        return true;
    }

    /**
     * @todo to be implemented for the sub-total
     */
    public function getSubTotal()
    {
        $sub_total = 0.0;
        if ($this->hasProducts()) {
            foreach ($this->session->get('cart') as $id => $qty) {
                $product_id = explode(':', $id);
                $Product = new Product($product_id[0]);
                $sub_total += $Product->price * (float) $qty;
            }
        }
        return $sub_total;
    }

    /**
     * Is there any products in the cart
     * @return bool
     */
    public function hasProducts()
    {
        return count($this->session->get('cart')) > 0;
    }

    /**
     * @todo
     */
    public function getTotal()
    {
        $total = 0.0;
        if ($this->hasProducts()) {
            foreach ($this->session->get('cart') as $id => $qty) {
                $product_id = explode(':', $id);
                $Product = new Product($product_id[0]);
                $total += $Product->price * (float) $qty * (100.0 + $Product->tax) / 100.0;
            }
        }
        return $total;
    }

    /**
     * Checks if
     * @return boolean
     */
    public function hasShipping()
    {
        static $shipping = false;
        foreach ($this->session->get('cart') as $id => $qty) {
            $product_id = explode(':', $id);
            $Product = new Product($product_id[0]);
            if ($Product->shipping) {
                $shipping = true;
                break;
            }
        }
        return $shipping;
    }

    /**
     * Get contents of the cart
     * @return array \Product
     * @throws Exception
     */
    public function getContent()
    {
        if (!$this->hasProducts())
            throw new Exception(1000, 'Cart is empty');
        return $this->session->get('cart');
    }

    /**
     * Get item counter of the cart
     * @return int
     * @throws Exception
     */
    public function getCountItems()
    {
        if (!$this->hasProducts())
            return 0;
        $count = 0;
        foreach ($this->session->get('cart') as $id => $qty) {
            $count += (int) $qty;
        }
        return $count;
    }

}


text:
package org.elasticsearch.action.search;

import org.elasticsearch.action.Action;
import org.elasticsearch.client.SearchClient;

/**
 */
public class SearchAction extends Action<SearchRequest, SearchResponse, SearchRequestBuilder, SearchClient> {

    public static final SearchAction INSTANCE = new SearchAction();
    public static final String NAME = "search";

    private SearchAction() {
        super(NAME);
    }

    @Override
    public SearchResponse newResponse() {
        return new SearchResponse();
    }

    @Override
    public SearchRequestBuilder newRequestBuilder(SearchClient client) {
        return new SearchRequestBuilder(client);
    }
}


text:
This sample provides a custom control button that will be available in the context menu for a feature layer in the TOC. Selecting this option will display a window containing the metadata for the layer.

View it live

```
Language:      C#
Subject:       Framework
Contributor:   ArcGIS Pro SDK Team <arcgisprosdk@esri.com>
Organization:  Esri, http://www.esri.com
Date:          9/3/2015
ArcGIS Pro:    1.1
Visual Studio: 2013, 2015
```

##Resources

* [API Reference online](http://pro.arcgis.com/en/pro-app/sdk/api-reference)
* ArcGIS Pro SDK for .NET (pro.arcgis.com)
* [arcgis-pro-sdk-community-samples](http://github.com/Esri/arcgis-pro-sdk-community-samples)
* [FAQ](http://github.com/Esri/arcgis-pro-sdk/wiki/FAQ)
* [ArcGIS Pro SDK icons](https://github.com/Esri/arcgis-pro-sdk/releases/tag/1.1.0.3308)
* [ProConcepts: ArcGIS Pro Add in Samples](https://github.com/Esri/arcgis-pro-sdk-community-samples/wiki/ProConcepts-ArcGIS-Pro-Add-in-Samples)

##How to use the sample

1. In Visual Studio click the Build menu. Then select Build Solution.
2. Click Start button to open ArcGIS Pro.
3. ArcGIS Pro will open.
4. Open a map that contains feature geometry.
5. Right click on a  feature layer in the TOC.
6. Select Layer Viewer.
![UI](Screenshots/Screen.png)
7. The application will display the layer's metadata information.
![UI](Screenshots/Screen2.png)

[](Esri Tags: ArcGIS-Pro-SDK)
[](Esri Language: C-Sharp)

 ArcGIS Pro 1.1 SDK for Microsoft .NET Framework

                    [Home](https://github.com/Esri/arcgis-pro-sdk/wiki) | ArcGIS Pro SDK | API Reference | [Requirements](#requirements) | [Download](#download) |  Samples


text:
package voldemort.routing;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import voldemort.cluster.Node;
import voldemort.utils.FnvHashFunction;
import voldemort.utils.HashFunction;

import com.google.common.collect.Sets;

/**
 * A Routing strategy that routes each request to the first N nodes where N is a
 * user defined replication factor.
 *
 * The mapping is computed by creating partitions of a fixed size, and
 * maintaining a mapping from partition tag to Node. These nodes are mapped onto
 * a ring.
 *
 * A preference list of nodes to route to is created by taking the partition
 * into which the key hashes, and then taking the next N nodes on the ring.
 *
 *
 */
public class ConsistentRoutingStrategy implements RoutingStrategy {

    private final int numReplicas;
    private final Node[] partitionToNode;
    private final HashFunction hash;

    public ConsistentRoutingStrategy(Collection<Node> nodes, int numReplicas) {
        this(new FnvHashFunction(), nodes, numReplicas);
    }

    public ConsistentRoutingStrategy(HashFunction hash, Collection<Node> nodes, int numReplicas) {
        this.numReplicas = numReplicas;
        this.hash = hash;
        SortedMap<Integer, Node> m = new TreeMap<Integer, Node>();
        for(Node n: nodes) {
            for(Integer partition: n.getPartitionIds()) {
                if(m.containsKey(partition))
                    throw new IllegalArgumentException("Duplicate partition id " + partition
                                                       + " in cluster configuration " + nodes);
                m.put(partition, n);
            }
        }

        this.partitionToNode = new Node[m.size()];
        for(int i = 0; i < m.size(); i++) {
            if(!m.containsKey(i))
                throw new IllegalArgumentException("Invalid configuration, missing partition " + i);
            this.partitionToNode[i] = m.get(i);
        }
    }

    /**
     * A modified version of abs that always returns a non-negative value.
     * Math.abs returns Integer.MIN_VALUE if a == Integer.MIN_VALUE and this
     * method returns Integer.MAX_VALUE in that case.
     */
    private static int abs(int a) {
        if(a >= 0)
            return a;
        else if(a != Integer.MIN_VALUE)
            return -a;
        return Integer.MAX_VALUE;
    }

    public List<Node> routeRequest(byte[] key) {
        List<Integer> partitionList = getPartitionList(key);

        if(partitionList.size() == 0)
            return new ArrayList<Node>(0);

        List<Node> preferenceList = new ArrayList<Node>(partitionList.size());
        for(int partition: partitionList) {
            preferenceList.add(partitionToNode[partition]);
        }

        return preferenceList;
    }

    public List<Integer> getReplicatingPartitionList(int index) {
        List<Node> preferenceList = new ArrayList<Node>(numReplicas);
        List<Integer> replicationPartitionsList = new ArrayList<Integer>(numReplicas);

        if(partitionToNode.length == 0) {
            return new ArrayList<Integer>(0);
        }

        for(int i = 0; i < partitionToNode.length; i++) {
            // add this one if we haven't already
            if(!preferenceList.contains(partitionToNode[index])) {
                preferenceList.add(partitionToNode[index]);
                replicationPartitionsList.add(index);
            }

            // if we have enough, go home
            if(preferenceList.size() >= numReplicas)
                return replicationPartitionsList;
            // move to next clockwise slot on the ring
            index = (index + 1) % partitionToNode.length;
        }

        // we don't have enough, but that may be okay
        return replicationPartitionsList;
    }

    public Set<Node> getNodes() {
        Set<Node> s = Sets.newHashSetWithExpectedSize(partitionToNode.length);
        for(Node n: this.partitionToNode)
            s.add(n);
        return s;
    }

    Node getNodeByPartition(int partition) {
        return partitionToNode[partition];
    }

    Set<Integer> getPartitionsByNode(Node n) {
        Set<Integer> tags = new HashSet<Integer>();
        for(int i = 0; i < partitionToNode.length; i++)
            if(partitionToNode[i].equals(n))
                tags.add(i);
        return tags;
    }

    public List<Integer> getPartitionList(byte[] key) {
        int index = abs(hash.hash(key)) % (Math.max(1, this.partitionToNode.length));
        return getReplicatingPartitionList(index);
    }
}