text:
.class Lcom/android/internal/telephony/dataconnection/DcTracker$HtcMobileDataCallback;
.super Lcom/android/internal/telephony/MobileNetwork$ThreadCallback;
.source "DcTracker.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/internal/telephony/dataconnection/DcTracker;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "HtcMobileDataCallback"
.end annotation

# instance fields
.field private basePhone:Lcom/android/internal/telephony/PhoneBase;

.field private criticalSection:Ljava/lang/Object;

.field private dataRoaming:Lcom/android/internal/telephony/MobileNetwork$DataRoamingSetting;

.field private h:Landroid/os/Handler;

# direct methods
.method public constructor <init>(Lcom/android/internal/telephony/PhoneBase;Landroid/os/Handler;)V
    .locals 1
    .param p1, "basePhone"    # Lcom/android/internal/telephony/PhoneBase;
    .param p2, "h"    # Landroid/os/Handler;

    .prologue
    .line 7779
    invoke-direct {p0}, Lcom/android/internal/telephony/MobileNetwork$ThreadCallback;-><init>()V

    .line 7780
    new-instance v0, Ljava/lang/Object;

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

    iput-object v0, p0, Lcom/android/internal/telephony/dataconnection/DcTracker$HtcMobileDataCallback;->criticalSection:Ljava/lang/Object;

    .line 7781
    iput-object p1, p0, Lcom/android/internal/telephony/dataconnection/DcTracker$HtcMobileDataCallback;->basePhone:Lcom/android/internal/telephony/PhoneBase;

    .line 7782
    iput-object p2, p0, Lcom/android/internal/telephony/dataconnection/DcTracker$HtcMobileDataCallback;->h:Landroid/os/Handler;

    .line 7783
    return-void
.end method

# virtual methods
.method public getDataRoaming()Lcom/android/internal/telephony/MobileNetwork$DataRoamingSetting;
    .locals 2

    .prologue
    .line 7786
    iget-object v1, p0, Lcom/android/internal/telephony/dataconnection/DcTracker$HtcMobileDataCallback;->criticalSection:Ljava/lang/Object;

    monitor-enter v1

    .line 7787
    :try_start_0
    iget-object v0, p0, Lcom/android/internal/telephony/dataconnection/DcTracker$HtcMobileDataCallback;->dataRoaming:Lcom/android/internal/telephony/MobileNetwork$DataRoamingSetting;

    monitor-exit v1

    return-object v0

    .line 7788
    :catchall_0
    move-exception v0

    monitor-exit v1
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    throw v0
.end method

.method public needDataRoamingUpdate()Z
    .locals 1

    .prologue
    .line 7793
    const/4 v0, 0x1

    return v0
.end method

.method public updateDataRoaming(Landroid/content/Context;Lcom/android/internal/telephony/MobileNetwork$Selection;Lcom/android/internal/telephony/MobileNetwork$DataRoamingSetting;)V
    .locals 7
    .param p1, "context"    # Landroid/content/Context;
    .param p2, "slotNphone"    # Lcom/android/internal/telephony/MobileNetwork$Selection;
    .param p3, "status"    # Lcom/android/internal/telephony/MobileNetwork$DataRoamingSetting;

    .prologue
    .line 7798
    const-string v3, "DCT"

    new-instance v4, Ljava/lang/StringBuilder;

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

    const-string v5, "["

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    iget-object v5, p0, Lcom/android/internal/telephony/dataconnection/DcTracker$HtcMobileDataCallback;->basePhone:Lcom/android/internal/telephony/PhoneBase;

    invoke-virtual {v5}, Lcom/android/internal/telephony/PhoneBase;->getPhoneId()I

    move-result v5

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v4

    const-string v5, "]updateDataRoaming from pid = "

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-static {}, Landroid/os/Binder;->getCallingPid()I

    move-result v5

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v4

    invoke-static {v3, v4}, Landroid/telephony/Rlog;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 7800
    new-instance v0, Lcom/android/internal/telephony/MobileNetwork$Selection;

    invoke-direct {v0}, Lcom/android/internal/telephony/MobileNetwork$Selection;-><init>()V

    .line 7801
    .local v0, "Slot":Lcom/android/internal/telephony/MobileNetwork$Selection;
    const/4 v2, 0x0

    .line 7803
    .local v2, "setting":Lcom/android/internal/telephony/MobileNetwork$DataRoamingSetting;
    invoke-static {}, Lcom/android/internal/telephony/dataconnection/HtcDataCustomizationManager;->getDualSimDataRoamingPreferredSlot()Z

    move-result v3

    if-eqz v3, :cond_1

    iget-object v3, p0, Lcom/android/internal/telephony/dataconnection/DcTracker$HtcMobileDataCallback;->basePhone:Lcom/android/internal/telephony/PhoneBase;

    invoke-virtual {v3}, Lcom/android/internal/telephony/PhoneBase;->getPhoneId()I

    move-result v3

    const/4 v4, 0x1

    if-ne v3, v4, :cond_1

    .line 7805
    const-wide/16 v4, 0x1

    invoke-static {v4, v5}, Ljava/lang/Long;->valueOf(J)Ljava/lang/Long;

    move-result-object v3

    iput-object v3, v0, Lcom/android/internal/telephony/MobileNetwork$Selection;->slot:Ljava/lang/Long;

    .line 7811
    :goto_0
    :try_start_0
    invoke-static {p1, v0}, Lcom/android/internal/telephony/MobileNetwork;->getDataRoaming(Landroid/content/Context;Lcom/android/internal/telephony/MobileNetwork$Selection;)Lcom/android/internal/telephony/MobileNetwork$DataRoamingSetting;
    :try_end_0
    .catch Ljava/lang/Throwable; {:try_start_0 .. :try_end_0} :catch_0

    move-result-object v2

    .line 7816
    :goto_1
    if-nez v2, :cond_2

    .line 7833
    :cond_0
    :goto_2
    return-void

    .line 7807
    :cond_1
    const-wide/16 v4, 0x0

    invoke-static {v4, v5}, Ljava/lang/Long;->valueOf(J)Ljava/lang/Long;

    move-result-object v3

    iput-object v3, v0, Lcom/android/internal/telephony/MobileNetwork$Selection;->slot:Ljava/lang/Long;

    goto :goto_0

    .line 7813
    :catch_0
    move-exception v1

    .line 7814
    .local v1, "e":Ljava/lang/Throwable;
    const-string v3, "DCT"

    new-instance v4, Ljava/lang/StringBuilder;

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

    const-string v5, "["

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    iget-object v5, p0, Lcom/android/internal/telephony/dataconnection/DcTracker$HtcMobileDataCallback;->basePhone:Lcom/android/internal/telephony/PhoneBase;

    invoke-virtual {v5}, Lcom/android/internal/telephony/PhoneBase;->getPhoneId()I

    move-result v5

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v4

    const-string v5, "]updateDataRoaming eror."

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v4

    invoke-static {v3, v4, v1}, Landroid/telephony/Rlog;->d(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I

    goto :goto_1

    .line 7820
    .end local v1    # "e":Ljava/lang/Throwable;
    :cond_2
    iget-object v4, p0, Lcom/android/internal/telephony/dataconnection/DcTracker$HtcMobileDataCallback;->criticalSection:Ljava/lang/Object;

    monitor-enter v4

    .line 7821
    :try_start_1
    iput-object v2, p0, Lcom/android/internal/telephony/dataconnection/DcTracker$HtcMobileDataCallback;->dataRoaming:Lcom/android/internal/telephony/MobileNetwork$DataRoamingSetting;

    .line 7822
    const-string v3, "DCT"

    new-instance v5, Ljava/lang/StringBuilder;

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

    const-string v6, "["

    invoke-virtual {v5, v6}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v5

    iget-object v6, p0, Lcom/android/internal/telephony/dataconnection/DcTracker$HtcMobileDataCallback;->basePhone:Lcom/android/internal/telephony/PhoneBase;

    invoke-virtual {v6}, Lcom/android/internal/telephony/PhoneBase;->getPhoneId()I

    move-result v6

    invoke-virtual {v5, v6}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v5

    const-string v6, "]updateDataRoaming Slot="

    invoke-virtual {v5, v6}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v5

    iget-object v6, v0, Lcom/android/internal/telephony/MobileNetwork$Selection;->slot:Ljava/lang/Long;

    invoke-virtual {v5, v6}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v5

    invoke-virtual {v5}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v5

    invoke-static {v3, v5}, Landroid/telephony/Rlog;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 7823
    monitor-exit v4
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_0

    .line 7825
    invoke-static {}, Lcom/android/internal/telephony/dataconnection/HtcDataCustomizationManager;->getAllowNationalRoaming()Z

    move-result v3

    if-eqz v3, :cond_3

    .line 7826
    iget-object v3, p0, Lcom/android/internal/telephony/dataconnection/DcTracker$HtcMobileDataCallback;->h:Landroid/os/Handler;

    iget-object v4, p0, Lcom/android/internal/telephony/dataconnection/DcTracker$HtcMobileDataCallback;->h:Landroid/os/Handler;

    const v5, 0x42085

    invoke-virtual {v4, v5}, Landroid/os/Handler;->obtainMessage(I)Landroid/os/Message;

    move-result-object v4

    invoke-virtual {v3, v4}, Landroid/os/Handler;->sendMessage(Landroid/os/Message;)Z

    .line 7829
    :cond_3
    invoke-static {}, Lcom/android/internal/telephony/dataconnection/HtcDataCustomizationManager;->SPRINT_ROAMING_ENHANCE_CONFIG()Z

    move-result v3

    if-eqz v3, :cond_0

    .line 7830
    const-string v3, "DCT"

    new-instance v4, Ljava/lang/StringBuilder;

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

    const-string v5, "["

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    iget-object v5, p0, Lcom/android/internal/telephony/dataconnection/DcTracker$HtcMobileDataCallback;->basePhone:Lcom/android/internal/telephony/PhoneBase;

    invoke-virtual {v5}, Lcom/android/internal/telephony/PhoneBase;->getPhoneId()I

    move-result v5

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v4

    const-string v5, "]updateDataRoaming SPCS CDMA setting change."

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v4

    invoke-static {v3, v4}, Landroid/telephony/Rlog;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 7831
    iget-object v3, p0, Lcom/android/internal/telephony/dataconnection/DcTracker$HtcMobileDataCallback;->h:Landroid/os/Handler;

    iget-object v4, p0, Lcom/android/internal/telephony/dataconnection/DcTracker$HtcMobileDataCallback;->h:Landroid/os/Handler;

    const v5, 0x42084

    invoke-virtual {v4, v5}, Landroid/os/Handler;->obtainMessage(I)Landroid/os/Message;

    move-result-object v4

    invoke-virtual {v3, v4}, Landroid/os/Handler;->sendMessage(Landroid/os/Message;)Z

    goto/16 :goto_2

    .line 7823
    :catchall_0
    move-exception v3

    :try_start_2
    monitor-exit v4
    :try_end_2
    .catchall {:try_start_2 .. :try_end_2} :catchall_0

    throw v3
.end method


text:
from .basicconfig import ConfigHolder

class MethodHolder(ConfigHolder):
    """MethodHolder(method)
Allows for the delayed invocation of methods, and easy introspection of
formal parameters for user interfaces.
    """
    def __init__(self, method=None, **kwargs):
        super(MethodHolder, self).__init__()
        if method is None:
            return
        elif type(method) is str:
            self.__dict__["_methodname"] = method
            self.lock()
            self.update(kwargs)
        elif type(method) is _UnboundMethodType:
            self.__dict__["_methodname"] = method.__func__.__name__
            # formal names
            varnames = list(method.__func__.__code__.co_varnames)[:method.__func__.__code__.co_argcount]
            varnames.reverse()
            df = method.__func__.__defaults__ or []
            defaults = list(df) ; defaults.reverse()
            for name, deflt in zip(varnames, defaults):
                self[name] = deflt
            del self[varnames[-1]] # remove the self reference
            self.lock()
            self.update(kwargs)
        else:
            raise ValueError("MethodHolder: invalid initializer type")

    def __str__(self):
        m = self.__dict__["_methodname"]
        params = ", ".join(["%s=%r" % (n, v) for n, v in list(self.items())])
        return "%s: %s" % (m, params)

    def __repr__(self):
        return "%s(%r, %s)" % (self.__class__.__name__, self.__dict__["_methodname"],
        ", ".join(["%s=%r" % (n, v) for n, v in list(self.items())]) )

    def _methodname(self):
        return self.__dict__["_methodname"]

    methodname = property(_methodname, None, None, "Method name")

    def __call__(self, instance):
        meth = getattr(instance, self.__dict__["_methodname"])
        return meth(*(), **self)

    def copy(self):
        new = MethodHolder()
        for key, val in list(self.items()):
            new[key] = val
        new.__dict__["_methodname"] = self.__dict__["_methodname"]
        new.lock()
        return new

    def update(self, other):
        for k in list(other.keys()):
            self[k] = other[k]

_UnboundMethodType = type(MethodHolder.copy)

def _test(argv):
    class TestMe(object):
        def mymethod(self, arg1=1, arg2=2, arg3=3):
            print(arg1, arg2, arg3)

    mh = MethodHolder(TestMe.mymethod)
    print(mh)

if __name__ == "__main__":
    import sys
    _test(sys.argv)

redpajama_set_name: RedPajamaGithub


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

// This code is modified from that in the Mesa3D Graphics library available at
// http://mesa3d.org/
// The license for the original code follows:

/**
* \file lower_noise.cpp
* IR lower pass to remove noise opcodes.
*
* \author Ian Romanick <ian.d.romanick@intel.com>
*/

#include "ShaderCompilerCommon.h"
#include "ir.h"
#include "ir_rvalue_visitor.h"

class lower_noise_visitor : public ir_rvalue_visitor
{
public:
	lower_noise_visitor() : progress(false)
	{
		/* empty */
	}

	void handle_rvalue(ir_rvalue **rvalue)
	{
		if (!*rvalue)
		{
			return;
		}

		ir_expression *expr = (*rvalue)->as_expression();
		if (!expr)
		{
			return;
		}

		/* In the future, ir_unop_noise may be replaced by a call to a function
		* that implements noise.  No hardware has a noise instruction.
		*/
		if (expr->operation == ir_unop_noise)
		{
			*rvalue = ir_constant::zero(ralloc_parent(expr), expr->type);
			this->progress = true;
		}
	}

	bool progress;
};

bool lower_noise(exec_list *instructions)
{
	lower_noise_visitor v;

	visit_list_elements(&v, instructions);

	return v.progress;
}


text:
// Copyright (C) 2011 R. Keith Morley
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// (MIT/X11 License)

/// \file ONB.hpp
/// ONB

#ifndef LEGION_COMMON_MATH_ONB_HPP_
#define LEGION_COMMON_MATH_ONB_HPP_

#include <optixu/optixu_math_namespace.h>
#include <Legion/Common/Util/Preprocessor.hpp>

namespace legion
{

class ONB
{
public:
  /// Assumes normal is normalized
  LDEVICE ONB( const float3& normal );

  /// Transforms the Vector from world space to the local space
  LDEVICE float3 transform( const float3& v)const;

  /// Transforms the Vector from the local space to world
  LDEVICE float3 inverseTransform( const float3& v)const;

  LDEVICE float3 tangent()const;
  LDEVICE float3 binormal()const;
  LDEVICE float3 normal()const;

  LDEVICE float3 u()const;
  LDEVICE float3 v()const;
  LDEVICE float3 w()const;

private:
  float3 m_tangent;
  float3 m_binormal;
  float3 m_normal;
};

LDEVICE inline ONB::ONB( const float3& normal )
{
    m_normal = normal;

    if( fabs( m_normal.x ) > fabs( m_normal.z ) )
    {
        m_binormal.x = -m_normal.y;
        m_binormal.y =  m_normal.x;
        m_binormal.z =  0.0f;
    }
    else
    {
        m_binormal.x =  0.0f;
        m_binormal.y = -m_normal.z;
        m_binormal.z =  m_normal.y;
    }

    m_binormal = optix::normalize(m_binormal);
    m_tangent  = optix::cross( m_binormal, m_normal );
}

LDEVICE inline float3 ONB::tangent()const
{
    return m_tangent;
}

LDEVICE inline float3 ONB::binormal()const
{
    return m_binormal;
}

LDEVICE inline float3 ONB::normal()const
{
    return m_normal;
}

LDEVICE inline float3 ONB::u()const
{
    return m_tangent;
}

LDEVICE inline float3 ONB::v()const
{
    return m_binormal;
}

LDEVICE inline float3 ONB::w()const
{
    return m_normal;
}

LDEVICE inline float3 ONB::transform( const float3& v)const
{

    return make_float3( optix::dot( v, m_tangent  ),
                        optix::dot( v, m_binormal ),
                        optix::dot( v, m_normal   ) );
}

LDEVICE inline float3 ONB::inverseTransform( const float3& v )const
{
    return  v.x*m_tangent + v.y*m_binormal + v.z*m_normal;
}

}

#endif // LEGION_COMMON_MATH_ONB_HPP_


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    android:id="@+id/widget"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/material_deep_teal_500"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:id="@+id/widget_image"
        android:layout_gravity="center_horizontal"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/widget_temp_high"
        android:layout_gravity="center_horizontal"
        android:fontFamily="sans-serif"
        android:textAppearance="?android:textAppearanceLarge"
        android:textColor="@color/white"/>
</LinearLayout>


text:
import { ValueBlock } from "../ValueBlock";
import { EMPTY_BUFFER } from "./constants";

export class LocalEndOfContentValueBlock extends ValueBlock {

  public static override = "EndOfContentValueBlock";

  public override fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number {
    // There is no "value block" for EndOfContent type and we need to return the same offset
    return inputOffset;
  }

  public override toBER(sizeOnly?: boolean): ArrayBuffer {
    return EMPTY_BUFFER;
  }
}


text:
/**
 * Compute a test peck value based on the hen's feeding parameters.
 * @param {number} factor The linear factor to use when choosing a feed amount.
 * @return The test peck value. Guaranteed to lie within the chicken's feeding parameters.
 */
var testHenPeckValue = function(henConstants, factor) {
  return henConstants.MIN_PECK_VOLUME +
    (henConstants.MAX_PECK_VOLUME - henConstants.MIN_PECK_VOLUME) *
    factor;
}

/**
 * Compute a test drink value based on the chicken's feeding parameters.
 * @param {number} factor The linear factor to use when choosing a drink amount.
 * @return The test drink value. Guaranteed to lie within the chicken's feeding
 *     parameters.
 */
var testHenDrinkValue = function(henConstants, factor) {
  return henConstants.MIN_DRINK_VOLUME +
    (henConstants.MAX_DRINK_VOLUME - henConstants.MIN_DRINK_VOLUME) *
    factor;
}

/**
 * @fileoverview Unit tests for the Chicken object.
 */
module("Hen Object", {
  teardown: function() {
    equal(NotificationDefaultCenter().hasObserversForNotification(
        Hen.DID_LAY_EGG_NOTIFICATION), false);
    equal(NotificationDefaultCenter().hasObserversForNotification(
        Hen.DID_DIE_NOTIFICATION), false);
  }
});

/*
 * Unit tests.
 */

test("Default Constructor", function() {
  var testHen = new Hen();
  equal(testHen.feed(), 0.0);
  equal(testHen.water(), 0.0);
});

test("Peck", function() {
  var testHen = new Hen();
  var fakeFeedBag = new FakeFeedBag();
  equal(testHen.feed(), 0.0);
  testHen.peckFeed(testHen.constants.MAX_FEED / 2, fakeFeedBag);
  equal(testHen.feed(), testHen.constants.MAX_FEED / 2);
  equal(testHen.water(), 0.0);
});

test("Overeat", function() {
  var testHen = new Hen();
  var fakeFeedBag = new FakeFeedBag();
  equal(testHen.feed(), 0.0);
  testHen.peckFeed(testHen.constants.MAX_FEED * 2, fakeFeedBag);
  // When a Hen overeats, its internal feed level is reset to MAX_FEED. This is different
  // than a Pullet.
  equal(testHen.feed(), testHen.constants.MAX_FEED);
  equal(testHen.water(), 0.0);
});

test("Drink", function() {
  var testHen = new Hen();
  var fakeWaterBottle = new FakeWaterBottle();
  equal(testHen.water(), 0.0);
  testHen.drinkWater(testHen.constants.MAX_WATER / 2, fakeWaterBottle);
  equal(testHen.water(), testHen.constants.MAX_WATER / 2);
  equal(testHen.feed(), 0.0);
});

test("Drink Too Much", function() {
  var testHen = new Hen();
  var fakeWaterBottle = new FakeWaterBottle();
  equal(testHen.water(), 0.0);
  testHen.drinkWater(testHen.constants.MAX_WATER * 2, fakeWaterBottle);
  // When a Hen drinks too much, its internal feed level is reset to 0. This is
  // different than a Pullet.
  equal(testHen.water(), testHen.constants.MAX_WATER);
  equal(testHen.feed(), 0.0);
});

test("Still Alive", function() {
  var testHen = new Hen();
  ok(testHen.isStillAlive());
  testHen.setEggCount(0);
  equal(testHen.isStillAlive(), false);
});

test("Should Lay Egg", function() {
  var testHen = new Hen();
  var fakeFeedBag = new FakeFeedBag();
  var fakeWaterBottle = new FakeWaterBottle();
  equal(testHen._shouldLayEgg(), false);
  testHen.peckFeed(testHen.constants.MAX_FEED / 2, fakeFeedBag);
  testHen.drinkWater(testHen.constants.MAX_WATER / 2, fakeWaterBottle);
  equal(testHen._shouldLayEgg(), false);
  testHen.setFeed(testHen.constants.MAX_FEED);
  testHen.setWater(testHen.constants.MAX_WATER);
  equal(testHen._shouldLayEgg(), true);
});

test("Has Stats", function() {
  var testHen = new Hen();
  equal(false, testHen.hasStats());
});

/*
 * Application tests.
 */

test("Lay Egg", function() {
  var testHen = new Hen();
  var fakeFeedBag = new FakeFeedBag();
  var fakeWaterBottle = new FakeWaterBottle();
  equal(testHen.feed(), 0.0);
  // Set up an event listener for the didLayEgg event.
  var didLayEggCount = 0;
  var didLayEgg = function(chicken) {
    didLayEggCount++;
    return false;
  };
  var defaultCenter = NotificationDefaultCenter();
  defaultCenter.addNotificationObserver(Hen.DID_LAY_EGG_NOTIFICATION, didLayEgg);
  testHen.peckFeed(testHen.constants.MAX_FEED, fakeFeedBag);
  testHen.drinkWater(testHen.constants.MAX_WATER, fakeWaterBottle);
  // Max feed & water should produce an egg and reset the chicken.
  equal(testHen.feed(), 0.0);
  equal(testHen.water(), 0.0);
  equal(didLayEggCount, 1);
  defaultCenter.removeNotificationObserver(Hen.DID_LAY_EGG_NOTIFICATION, didLayEgg);
});

test("Lay 2 Eggs", function() {
  var testHen = new Hen();
  var fakeFeedBag = new FakeFeedBag();
  var fakeWaterBottle = new FakeWaterBottle();
  equal(testHen.feed(), 0.0);
  // Set up an event listener for the didLayEgg event.
  var didLayEggCount = 0;
  var didLayEgg = function(chicken) {
    didLayEggCount++;
    return false;
  };
  var defaultCenter = NotificationDefaultCenter();
  defaultCenter.addNotificationObserver(Hen.DID_LAY_EGG_NOTIFICATION, didLayEgg);
  testHen.peckFeed(testHen.constants.MAX_FEED, fakeFeedBag);
  testHen.drinkWater(testHen.constants.MAX_WATER, fakeWaterBottle);
  // Max feed & water should produce an egg and reset the chicken.
  equal(testHen.feed(), 0.0);
  equal(testHen.water(), 0.0);
  equal(didLayEggCount, 1);

  // Verify that a second egg is laid after eating & drinking enough.
  testHen.peckFeed(testHen.constants.MAX_FEED, fakeFeedBag);
  testHen.drinkWater(testHen.constants.MAX_WATER, fakeWaterBottle);
  // Max feed & water should produce an egg and reset the chicken.
  equal(testHen.feed(), 0.0);
  equal(testHen.water(), 0.0);
  equal(didLayEggCount, 2);
  defaultCenter.removeNotificationObserver(Hen.DID_LAY_EGG_NOTIFICATION, didLayEgg);
});

test("Lay All Eggs", function() {
  var testHen = new Hen();
  var fakeFeedBag = new FakeFeedBag();
  var fakeWaterBottle = new FakeWaterBottle();
  ok(testHen.isStillAlive());
  var didLayEggCount = 0;
  var didLayEgg = function(chicken) {
    didLayEggCount++;
    return false;
  };
  var didDieCount = 0;
  var didDie = function(chicken) {
    didDieCount++;
  }
  var defaultCenter = NotificationDefaultCenter();
  defaultCenter.addNotificationObserver(Hen.DID_LAY_EGG_NOTIFICATION, didLayEgg);
  defaultCenter.addNotificationObserver(Hen.DID_DIE_NOTIFICATION, didDie);
  for (var i = 0; i < testHen.constants.MAX_EGG_COUNT; ++i) {
    testHen._layEgg();
  }
  equal(testHen.isStillAlive(), false);
  equal(didLayEggCount, testHen.constants.MAX_EGG_COUNT);
  equal(didDieCount, 1);
  // Try to lay one more egg, this should do nothing.
  testHen._layEgg();
  equal(didLayEggCount, testHen.constants.MAX_EGG_COUNT);
  equal(didDieCount, 1);
  defaultCenter.removeNotificationObserver(Hen.DID_LAY_EGG_NOTIFICATION, didLayEgg);
  defaultCenter.removeNotificationObserver(Hen.DID_DIE_NOTIFICATION, didDie);
});

test("Process Game Tick", function() {
  var fakeRandomValue = 0.25;
  var fakeRandom = function() {
    return fakeRandomValue;
  }
  var testHen = new Hen();
  var testPeck = testHenPeckValue(testHen.constants, fakeRandomValue);
  var testDrink = testHenDrinkValue(testHen.constants, fakeRandomValue);
  testHen.feedBag = new FakeFeedBag();
  testHen.waterBottle = new FakeWaterBottle();
  equal(testHen.feed(), 0.0);
  equal(testHen.water(), 0.0);
  var gameTimeDelta = 0.5;
  var dateNow = Date.now() / 1000.0;
  testHen.processGameTick(dateNow, gameTimeDelta, fakeRandom, Chicken.Actions.PECK);
  equal(testHen.feed(), 0.0);
  equal(testHen.water(), 0.0);
  ok(testHen._peckVolume > 0.0);
  equal(testHen._drinkVolume, 0.0);
  // Give the chicken enough time to chew all the scratch.
  gameTimeDelta = (testPeck / testHen.constants.CHEW_RATE) + 1;
  dateNow += gameTimeDelta;
  testHen.processGameTick(dateNow, gameTimeDelta, fakeRandom, Chicken.Actions.PECK);
  equal(testHen.feed(), testPeck);
  equal(testHen.water(), 0.0);
  equal(testHen._peckVolume, 0.0);
  equal(testHen._drinkVolume, 0.0);
  testHen.processGameTick(dateNow, gameTimeDelta, fakeRandom, Chicken.Actions.DRINK);
  equal(testHen.feed(), testPeck);
  equal(testHen.water(), 0.0);
  equal(testHen._peckVolume, 0.0);
  ok(testHen._drinkVolume > 0.0);
  // Give the chicken enough time to drink all the water.
  gameTimeDelta = (testDrink / testHen.constants.DRINK_RATE) + 1;
  dateNow += gameTimeDelta;
  testHen.processGameTick(dateNow, gameTimeDelta, fakeRandom, Chicken.Actions.DRINK);
  equal(testHen.feed(), testPeck);
  equal(testHen.water(), testDrink);
  equal(testHen._peckVolume, 0.0);
  equal(testHen._drinkVolume, 0.0);
  testHen.processGameTick(dateNow, gameTimeDelta, fakeRandom, Chicken.Actions.PECK);
  equal(testHen.feed(), testPeck);
  equal(testHen.water(), testDrink);
  ok(testHen._peckVolume > 0.0);
  equal(testHen._drinkVolume, 0.0);
  gameTimeDelta = (testPeck / testHen.constants.CHEW_RATE) + 1;
  dateNow += gameTimeDelta;
  testHen.processGameTick(dateNow, gameTimeDelta, fakeRandom, Chicken.Actions.PECK);
  equal(testHen.feed(), testPeck * 2.0);
  equal(testHen.water(), testDrink);
  testHen.processGameTick(dateNow, gameTimeDelta, fakeRandom, Chicken.Actions.DRINK);
  equal(testHen._peckVolume, 0.0);
  ok(testHen._drinkVolume > 0.0);
  gameTimeDelta = (testDrink / testHen.constants.DRINK_RATE) + 1;
  dateNow += gameTimeDelta;
  testHen.processGameTick(dateNow, gameTimeDelta, fakeRandom, Chicken.Actions.DRINK);
  equal(testHen.feed(), testPeck * 2.0);
  equal(testHen.water(), testDrink * 2.0);
});

test("Process Game Tick Peck Too Soon", function() {
  var fakeRandomValue = 0.25;
  var fakeRandom = function() {
    return fakeRandomValue;
  }
  var testHen = new Hen();
  var testPeck = testHenPeckValue(testHen.constants, fakeRandomValue);
  var testDrink = testHenDrinkValue(testHen.constants, fakeRandomValue);
  testHen.feedBag = new FakeFeedBag();
  testHen.waterBottle = new FakeWaterBottle();
  equal(testHen.feed(), 0.0);
  equal(testHen.water(), 0.0);
  // Pick a time step that's 1/2 of the time needed to chew the scratch.
  var gameTimeDelta = (testPeck / testHen.constants.CHEW_RATE) / 2;
  var dateNow = Date.now() / 1000.0;
  testHen.processGameTick(dateNow, gameTimeDelta, fakeRandom, Chicken.Actions.PECK);
  equal(testHen.feed(), 0.0);
  equal(testHen.water(), 0.0);
  testHen.processGameTick(dateNow + gameTimeDelta, gameTimeDelta, fakeRandom,
      Chicken.Actions.PECK);
  equal(testHen.feed(), testPeck / 2.0);
  equal(testHen.water(), 0.0);
  testHen.processGameTick(dateNow + gameTimeDelta, gameTimeDelta, fakeRandom,
      Chicken.Actions.DRINK);
  equal(testHen.feed(), testPeck / 2.0);
  equal(testHen.water(), 0.0);
});

test("Process Game Tick Drink Too Soon", function() {
  var fakeRandomValue = 0.25;
  var fakeRandom = function() {
    return fakeRandomValue;
  }
  var testHen = new Hen();
  var testPeck = testHenPeckValue(testHen.constants, fakeRandomValue);
  var testDrink = testHenDrinkValue(testHen.constants, fakeRandomValue);
  testHen.feedBag = new FakeFeedBag();
  testHen.waterBottle = new FakeWaterBottle();
  equal(testHen.feed(), 0.0);
  equal(testHen.water(), 0.0);
  // Pick a time step that's 1/2 of the time needed to drink the water.
  var gameTimeDelta = (testDrink / testHen.constants.DRINK_RATE) / 2;
  var dateNow = Date.now() / 1000.0;
  testHen.processGameTick(dateNow, gameTimeDelta, fakeRandom, Chicken.Actions.DRINK);
  equal(testHen.feed(), 0.0);
  equal(testHen.water(), 0.0);
  testHen.processGameTick(dateNow + gameTimeDelta, gameTimeDelta, fakeRandom,
      Chicken.Actions.DRINK);
  equal(testHen.feed(), 0.0);
  equal(testHen.water(), testDrink / 2.0);
  testHen.processGameTick(dateNow + gameTimeDelta, gameTimeDelta, fakeRandom,
      Chicken.Actions.PECK);
  equal(testHen.feed(), 0.0);
  equal(testHen.water(), testDrink / 2.0);
});

test("Process Game Tick No Feed, No Water", function() {
  var fakeRandomValue = 0.5;
  var fakeRandom = function() {
    return fakeRandomValue;
  }
  var testHen = new Hen();
  var testPeck = testHenPeckValue(testHen.constants, fakeRandomValue);
  var testDrink = testHenDrinkValue(testHen.constants, fakeRandomValue);
  equal(testHen.feed(), 0.0);
  equal(testHen.water(), 0.0);
  var dateNow = Date.now() / 1000.0;
  var gameTimeDelta = 0.5;
  testHen.processGameTick(dateNow, gameTimeDelta, fakeRandom, Chicken.Actions.PECK);
  equal(testHen.feed(), 0.0);
  equal(testHen.water(), 0.0);
  // Give the chicken enough time to chew all the scratch.
  gameTimeDelta = (testPeck / testHen.constants.CHEW_RATE) + 1;
  dateNow += gameTimeDelta;
  testHen.processGameTick(dateNow + gameTimeDelta, gameTimeDelta, fakeRandom,
      Chicken.Actions.PECK);
  equal(testHen.feed(), 0.0);
  equal(testHen.water(), 0.0);
  testHen.processGameTick(dateNow + gameTimeDelta, gameTimeDelta, fakeRandom,
       Chicken.Actions.DRINK);
  equal(testHen.feed(), 0.0);
  equal(testHen.water(), 0.0);
  // Give the chicken enough time to drink all the water.
  gameTimeDelta = (testDrink / testHen.constants.DRINK_RATE) + 1;
  dateNow += gameTimeDelta;
  testHen.processGameTick(dateNow + gameTimeDelta, gameTimeDelta, fakeRandom,
      Chicken.Actions.DRINK);
  equal(testHen.feed(), 0.0);
  equal(testHen.water(), 0.0);
});

test("Whole Hen", function() {
  // Test the entire chicken cycle: eat, drink, lay an egg.
  var fakeRandomValue = 1.0;
  var fakeRandom = function() {
    return fakeRandomValue;
  }
  var testHen = new Hen();
  var testPeck = testHenPeckValue(testHen.constants, fakeRandomValue);
  var testDrink = testHenDrinkValue(testHen.constants, fakeRandomValue);
  testHen.feedBag = new FakeFeedBag();
  testHen.waterBottle = new FakeWaterBottle();
  equal(testHen.feed(), 0.0);
  equal(testHen.water(), 0.0);
  // Set up an event listener for the didLayEgg event.
  var didLayEggCount = 0;
  var didLayEgg = function(chicken) {
    didLayEggCount++;
    return false;
  };
  var defaultCenter = NotificationDefaultCenter();
  defaultCenter.addNotificationObserver(Hen.DID_LAY_EGG_NOTIFICATION, didLayEgg);
  // Eat enough scratch and drink enough water to lay an egg by choosing a time delta
  // that will process all the comestibles in one iteration.
  var peckTimeDelta = (testPeck / testHen.constants.CHEW_RATE) + 1;
  var drinkTimeDelta = (testDrink / testHen.constants.DRINK_RATE) + 1;
  var gameTimeDelta = peckTimeDelta > drinkTimeDelta ? peckTimeDelta : drinkTimeDelta;
  var dateNow = Date.now() / 1000.0;
  // Set a maximum number of iterations so the test isn't flakey.
  var maxIters = Math.floor(testHen.constants.MAX_FEED / testPeck + 0.5) + 1 +
      Math.floor(testHen.constants.MAX_WATER / testDrink + 0.5) + 1;
  while (didLayEggCount == 0 && maxIters >= 0) {
    // Peck some scratch or drink some water.
    testHen.processGameTick(dateNow, gameTimeDelta, fakeRandom);
    // Chew and eat the scratch or drink the water in one iteration.
    testHen.processGameTick(dateNow + gameTimeDelta, gameTimeDelta, fakeRandom);
    dateNow += gameTimeDelta;
    maxIters--;
  }
  ok(maxIters > 0);
  equal(testHen.feed(), 0.0);
  equal(testHen.water(), 0.0);
  equal(didLayEggCount, 1);

  defaultCenter.removeNotificationObserver(Hen.DID_LAY_EGG_NOTIFICATION, didLayEgg);
});


text:
package linear

import "errors"

// List represents a singly linked list
type List struct {
	root  *Node // Why should root be accessible?
	count int
}

var nullList *List
var nulValue Interface

// NewLinkedList returns a new empty list
func NewLinkedList() *List {
	return new(List)
}

// Size returns the number of nodes in the current linked list
func (L *List) Size() int {
	return L.count
}

// Empty verifies if the list is empty or not
func (L *List) Empty() bool {
	return L.count == 0
}

//NodeAt returns the nth(index) node
func (L *List) NodeAt(index int) *Node {
	if L.count < index {
		return nil
	}
	i := 1
	cur := L.root
	for ; i < index; i++ {
		cur = cur.Next()
	}
	return cur
}

// PushFront inserts an element at the head of the linked list
func (L *List) PushFront(value Interface) *Node {
	newNode := new(Node)
	newNode.Value = value
	newNode.next = L.root
	L.root = newNode
	L.count++
	return newNode
}

// PopFront removes the head and returns it
func (L *List) PopFront() *Node {
	if L.root == nil {
		return nil
	}
	node := L.root
	L.root = L.root.Next()
	L.count--
	return node
}

// Append adds a node with value val at  the end of the list
func (L *List) Append(val Interface) *Node {
	if L.count == 0 {
		return L.PushFront(val)
	}
	newNode := new(Node)
	newNode.Value = val
	cur := L.root
	for cur.Next() != nil {
		cur = cur.Next()
	}
	cur.next = newNode
	L.count++
	return newNode
}

// InsertAt inserts a new nth node with value 'val'
func (L *List) InsertAt(val Interface, index int) (*Node, error) {
	if index <= 0 || index > L.count {
		return nil, errors.New("Specified index out of range")
	}
	if index == 1 {
		return L.PushFront(val), nil
	}
	newNode := new(Node)
	newNode.Value = val
	i := 1
	cur := L.root
	for ; i < index-1; i++ {
		cur = cur.next
	}
	//save current indexth node
	nextNode := cur.next
	//insert the new node
	cur.next = newNode
	newNode.next = nextNode
	L.count++
	return newNode, nil
}

// RemoveAt removes the nth node (1-based indexing)
func (L *List) RemoveAt(index int) (*Node, error) {
	if index <= 0 || index > L.count {
		return nil, errors.New("Specified index out of range")
	}
	if index == 1 {
		//can be certain that PopFront won't give a nil
		return L.PopFront(), nil
	}
	cur := L.root
	for i := 1; i < index-1; i++ {
		cur = cur.next
	}
	nodeRemoved := cur.next
	cur.next = cur.next.next
	L.count--
	return nodeRemoved, nil
}

// Front returns the head of the linked list
func (L *List) Front() *Node {
	return L.NodeAt(1)
}


text:
class ApplicationController < ActionController::Base
  before_filter :configure_permitted_parameters, if: :devise_controller?
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :null_session

  protected
  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_in) { |u| u.permit( :name, :email, :username ) }
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit( :name, :email, :username, :password, :password_confirmation ) }
    devise_parameter_sanitizer.for(:account_update) { |u| u.permit( :name, :email, :username, :password, :password_confirmation, :current_password )}
  end
end


text:
namespace offline_items_collection {

class MockFilteredOfflineItemObserver {
 public:
  class MockObserver : public FilteredOfflineItemObserver::Observer {
   public:
    MockObserver();
    ~MockObserver() override;

    // FilteredOfflineItemObserver::Observer implementation.
    MOCK_METHOD1(OnItemRemoved, void(const ContentId&));
    MOCK_METHOD2(OnItemUpdated,
                 void(const OfflineItem&, const base::Optional<UpdateDelta>&));
  };

  class ScopedMockObserver : public MockObserver {
   public:
    ScopedMockObserver(FilteredOfflineItemObserver* observer,
                       const ContentId& id);
    ~ScopedMockObserver() override;

   private:
    ContentId id_;
    FilteredOfflineItemObserver* observer_;

    DISALLOW_COPY_AND_ASSIGN(ScopedMockObserver);
  };

 private:
  // Do not allow instantiation.
  MockFilteredOfflineItemObserver() = default;
  ~MockFilteredOfflineItemObserver() = default;

  DISALLOW_COPY_AND_ASSIGN(MockFilteredOfflineItemObserver);
};

}  // namespace offline_items_collection

#endif  // COMPONENTS_OFFLINE_ITEMS_COLLECTION_CORE_TEST_SUPPORT_MOCK_FILTERED_OFFLINE_ITEM_OBSERVER_H_


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information

namespace DotNetNuke.Web.Extensions
{
    using System;
    using System.Linq;

    using DotNetNuke.DependencyInjection.Extensions;
    using DotNetNuke.Web.Api;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.DependencyInjection.Extensions;

    /// <summary>
    /// Adds DNN Web API Specific startup extensions to simplify the
    /// <see cref="Startup"/> Class.
    /// </summary>
    internal static class StartupExtensions
    {
        /// <summary>
        /// Configures all of the <see cref="DnnApiController"/>'s to be used
        /// with the Service Collection for Dependency Injection.
        /// </summary>
        /// <param name="services">
        /// Service Collection used to registering services in the container.
        /// </param>
        public static void AddWebApi(this IServiceCollection services)
        {
            var controllerTypes = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(x => x.SafeGetTypes())
                .Where(x => typeof(DnnApiController).IsAssignableFrom(x) &&
                            x.IsClass &&
                            !x.IsAbstract);
            foreach (var controller in controllerTypes)
            {
                services.TryAddScoped(controller);
            }
        }
    }
}


text:
require 'marc'

module Avalon
  class BibRetriever
    XSLT_FILE = File.expand_path('../bib_retriever/MARC21slim2MODS3-5-avalon.xsl',__FILE__)
    attr_reader :config

    class << self
      def configured?
        begin
          instance.present?
        rescue ArgumentError
          false
        end
      end

      def instance
        config = Settings.bib_retriever
        unless config.respond_to?(:[]) and config['protocol'].present?
          raise ArgumentError, "Missing/invalid bib retriever configuration"
        end

        case config['protocol'].downcase
        when 'sru', /^yaz/
          require 'avalon/bib_retriever/sru'
          Avalon::BibRetriever::SRU.new config
        when /^z(oom|39)/
          require 'avalon/bib_retriever/zoom'
          Avalon::BibRetriever::Zoom.new config
        else
          raise ArgumentError, "Unknown bib retriever protocol: #{config['protocol']}"
        end
      end

      protected :new, :allocate
    end

    def initialize config
      @config = config
    end

    def marcxml2mods(marcxml)
      xsl ||= Dir.chdir(File.dirname(XSLT_FILE)) { Nokogiri::XSLT.parse(File.read(XSLT_FILE)) }
      doc = Nokogiri::XML(marcxml)
      mods = xsl.transform(doc)
      mods.to_s
    end

    def marc2mods(marc)
      record = MARC::Reader.decode marc
      marcxml = record.to_xml.to_s
      marcxml2mods(marcxml)
    end
  end
end


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>Test jQluster.RemoteSelectorFactory</title>
<link rel="stylesheet" href="./qunit.css">


text:
#include "jaxlib/gpu/solver_kernels.h"

#include <algorithm>
#include <cstdint>
#include <stdexcept>
#include <utility>
#include <vector>

#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/synchronization/mutex.h"
#include "jaxlib/gpu/gpu_kernel_helpers.h"
#include "jaxlib/handle_pool.h"
#include "jaxlib/kernel_helpers.h"
#include "tensorflow/compiler/xla/service/custom_call_status.h"

#ifdef JAX_GPU_CUDA
#include "third_party/gpus/cuda/include/cusolverSp.h"
#endif  // JAX_GPU_CUDA

namespace jax {

template <>
/*static*/ absl::StatusOr<SolverHandlePool::Handle> SolverHandlePool::Borrow(
    gpuStream_t stream) {
  SolverHandlePool* pool = Instance();
  absl::MutexLock lock(&pool->mu_);
  gpusolverDnHandle_t handle;
  if (pool->handles_[stream].empty()) {
    JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnCreate(&handle)));
  } else {
    handle = pool->handles_[stream].back();
    pool->handles_[stream].pop_back();
  }
  if (stream) {
    JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnSetStream(handle, stream)));
  }
  return Handle(pool, handle, stream);
}

#ifdef JAX_GPU_CUDA

template <>
/*static*/ absl::StatusOr<SpSolverHandlePool::Handle>
SpSolverHandlePool::Borrow(gpuStream_t stream) {
  SpSolverHandlePool* pool = Instance();
  absl::MutexLock lock(&pool->mu_);
  cusolverSpHandle_t handle;
  if (pool->handles_[stream].empty()) {
    JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusolverSpCreate(&handle)));
  } else {
    handle = pool->handles_[stream].back();
    pool->handles_[stream].pop_back();
  }
  if (stream) {
    JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusolverSpSetStream(handle, stream)));
  }
  return Handle(pool, handle, stream);
}

#endif  // JAX_GPU_CUDA

namespace JAX_GPU_NAMESPACE {

static int SizeOfSolverType(SolverType type) {
  switch (type) {
    case SolverType::F32:
      return sizeof(float);
    case SolverType::F64:
      return sizeof(double);
    case SolverType::C64:
      return sizeof(gpuComplex);
    case SolverType::C128:
      return sizeof(gpuDoubleComplex);
  }
}

// getrf: LU decomposition

static absl::Status Getrf_(gpuStream_t stream, void** buffers,
                           const char* opaque, size_t opaque_len) {
  auto s = UnpackDescriptor<GetrfDescriptor>(opaque, opaque_len);
  JAX_RETURN_IF_ERROR(s.status());
  const GetrfDescriptor& d = **s;
  auto h = SolverHandlePool::Borrow(stream);
  JAX_RETURN_IF_ERROR(h.status());
  auto& handle = *h;
  if (buffers[1] != buffers[0]) {
    JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpuMemcpyAsync(
        buffers[1], buffers[0],
        SizeOfSolverType(d.type) * static_cast<std::int64_t>(d.batch) *
            static_cast<std::int64_t>(d.m) * static_cast<std::int64_t>(d.n),
        gpuMemcpyDeviceToDevice, stream)));
  }

  int* ipiv = static_cast<int*>(buffers[2]);
  int* info = static_cast<int*>(buffers[3]);
  void* workspace = buffers[4];
  switch (d.type) {
    case SolverType::F32: {
      float* a = static_cast<float*>(buffers[1]);
      for (int i = 0; i < d.batch; ++i) {
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnSgetrf(
            handle.get(), d.m, d.n, a, d.m, static_cast<float*>(workspace),
            d.lwork, ipiv, info)));
        a += d.m * d.n;
        ipiv += std::min(d.m, d.n);
        ++info;
      }
      break;
    }
    case SolverType::F64: {
      double* a = static_cast<double*>(buffers[1]);
      for (int i = 0; i < d.batch; ++i) {
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnDgetrf(
            handle.get(), d.m, d.n, a, d.m, static_cast<double*>(workspace),
            d.lwork, ipiv, info)));
        a += d.m * d.n;
        ipiv += std::min(d.m, d.n);
        ++info;
      }
      break;
    }
    case SolverType::C64: {
      gpuComplex* a = static_cast<gpuComplex*>(buffers[1]);
      for (int i = 0; i < d.batch; ++i) {
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnCgetrf(
            handle.get(), d.m, d.n, a, d.m, static_cast<gpuComplex*>(workspace),
            d.lwork, ipiv, info)));
        a += d.m * d.n;
        ipiv += std::min(d.m, d.n);
        ++info;
      }
      break;
    }
    case SolverType::C128: {
      gpuDoubleComplex* a = static_cast<gpuDoubleComplex*>(buffers[1]);
      for (int i = 0; i < d.batch; ++i) {
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnZgetrf(
            handle.get(), d.m, d.n, a, d.m,
            static_cast<gpuDoubleComplex*>(workspace), d.lwork, ipiv, info)));
        a += d.m * d.n;
        ipiv += std::min(d.m, d.n);
        ++info;
      }
      break;
    }
  }
  return absl::OkStatus();
}

void Getrf(gpuStream_t stream, void** buffers, const char* opaque,
           size_t opaque_len, XlaCustomCallStatus* status) {
  auto s = Getrf_(stream, buffers, opaque, opaque_len);
  if (!s.ok()) {
    XlaCustomCallStatusSetFailure(status, std::string(s.message()).c_str(),
                                  s.message().length());
  }
}

// geqrf: QR decomposition

static absl::Status Geqrf_(gpuStream_t stream, void** buffers,
                           const char* opaque, size_t opaque_len) {
  auto s = UnpackDescriptor<GeqrfDescriptor>(opaque, opaque_len);
  JAX_RETURN_IF_ERROR(s.status());
  const GeqrfDescriptor& d = **s;
  auto h = SolverHandlePool::Borrow(stream);
  JAX_RETURN_IF_ERROR(h.status());
  auto& handle = *h;
  if (buffers[1] != buffers[0]) {
    JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpuMemcpyAsync(
        buffers[1], buffers[0],
        SizeOfSolverType(d.type) * static_cast<std::int64_t>(d.batch) *
            static_cast<std::int64_t>(d.m) * static_cast<std::int64_t>(d.n),
        gpuMemcpyDeviceToDevice, stream)));
  }

  int* info = static_cast<int*>(buffers[3]);
  void* workspace = buffers[4];
  switch (d.type) {
    case SolverType::F32: {
      float* a = static_cast<float*>(buffers[1]);
      float* tau = static_cast<float*>(buffers[2]);
      for (int i = 0; i < d.batch; ++i) {
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(
            gpusolverDnSgeqrf(handle.get(), d.m, d.n, a, d.m, tau,
                              static_cast<float*>(workspace), d.lwork, info)));
        a += d.m * d.n;
        tau += std::min(d.m, d.n);
        ++info;
      }
      break;
    }
    case SolverType::F64: {
      double* a = static_cast<double*>(buffers[1]);
      double* tau = static_cast<double*>(buffers[2]);
      for (int i = 0; i < d.batch; ++i) {
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(
            gpusolverDnDgeqrf(handle.get(), d.m, d.n, a, d.m, tau,
                              static_cast<double*>(workspace), d.lwork, info)));
        a += d.m * d.n;
        tau += std::min(d.m, d.n);
        ++info;
      }
      break;
    }
    case SolverType::C64: {
      gpuComplex* a = static_cast<gpuComplex*>(buffers[1]);
      gpuComplex* tau = static_cast<gpuComplex*>(buffers[2]);
      for (int i = 0; i < d.batch; ++i) {
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnCgeqrf(
            handle.get(), d.m, d.n, a, d.m, tau,
            static_cast<gpuComplex*>(workspace), d.lwork, info)));
        a += d.m * d.n;
        tau += std::min(d.m, d.n);
        ++info;
      }
      break;
    }
    case SolverType::C128: {
      gpuDoubleComplex* a = static_cast<gpuDoubleComplex*>(buffers[1]);
      gpuDoubleComplex* tau = static_cast<gpuDoubleComplex*>(buffers[2]);
      for (int i = 0; i < d.batch; ++i) {
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnZgeqrf(
            handle.get(), d.m, d.n, a, d.m, tau,
            static_cast<gpuDoubleComplex*>(workspace), d.lwork, info)));
        a += d.m * d.n;
        tau += std::min(d.m, d.n);
        ++info;
      }
      break;
    }
  }
  return absl::OkStatus();
}

void Geqrf(gpuStream_t stream, void** buffers, const char* opaque,
           size_t opaque_len, XlaCustomCallStatus* status) {
  auto s = Geqrf_(stream, buffers, opaque, opaque_len);
  if (!s.ok()) {
    XlaCustomCallStatusSetFailure(status, std::string(s.message()).c_str(),
                                  s.message().length());
  }
}

#ifdef JAX_GPU_CUDA

// csrlsvqr: Linear system solve via Sparse QR

static absl::Status Csrlsvqr_(gpuStream_t stream, void** buffers,
                              const char* opaque, size_t opaque_len,
                              int& singularity) {
  auto s = UnpackDescriptor<CsrlsvqrDescriptor>(opaque, opaque_len);
  JAX_RETURN_IF_ERROR(s.status());
  const CsrlsvqrDescriptor& d = **s;

  // This is the handle to the CUDA session. Gets a cusolverSp handle.
  auto h = SpSolverHandlePool::Borrow(stream);
  JAX_RETURN_IF_ERROR(h.status());
  auto& handle = *h;

  cusparseMatDescr_t matdesc = nullptr;
  JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusparseCreateMatDescr(&matdesc)));
  JAX_RETURN_IF_ERROR(
      JAX_AS_STATUS(cusparseSetMatType(matdesc, CUSPARSE_MATRIX_TYPE_GENERAL)));
  JAX_RETURN_IF_ERROR(JAX_AS_STATUS(
      cusparseSetMatIndexBase(matdesc, CUSPARSE_INDEX_BASE_ZERO)));

  switch (d.type) {
    case SolverType::F32: {
      float* csrValA = static_cast<float*>(buffers[0]);
      int* csrRowPtrA = static_cast<int*>(buffers[1]);
      int* csrColIndA = static_cast<int*>(buffers[2]);
      float* b = static_cast<float*>(buffers[3]);
      float* x = static_cast<float*>(buffers[4]);

      JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusolverSpScsrlsvqr(
          handle.get(), d.n, d.nnz, matdesc, csrValA, csrRowPtrA, csrColIndA, b,
          (float)d.tol, d.reorder, x, &singularity)));

      break;
    }
    case SolverType::F64: {
      double* csrValA = static_cast<double*>(buffers[0]);
      int* csrRowPtrA = static_cast<int*>(buffers[1]);
      int* csrColIndA = static_cast<int*>(buffers[2]);
      double* b = static_cast<double*>(buffers[3]);
      double* x = static_cast<double*>(buffers[4]);

      JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusolverSpDcsrlsvqr(
          handle.get(), d.n, d.nnz, matdesc, csrValA, csrRowPtrA, csrColIndA, b,
          d.tol, d.reorder, x, &singularity)));

      break;
    }
    case SolverType::C64: {
      gpuComplex* csrValA = static_cast<gpuComplex*>(buffers[0]);
      int* csrRowPtrA = static_cast<int*>(buffers[1]);
      int* csrColIndA = static_cast<int*>(buffers[2]);
      gpuComplex* b = static_cast<gpuComplex*>(buffers[3]);
      gpuComplex* x = static_cast<gpuComplex*>(buffers[4]);

      JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusolverSpCcsrlsvqr(
          handle.get(), d.n, d.nnz, matdesc, csrValA, csrRowPtrA, csrColIndA, b,
          (float)d.tol, d.reorder, x, &singularity)));

      break;
    }
    case SolverType::C128: {
      gpuDoubleComplex* csrValA = static_cast<gpuDoubleComplex*>(buffers[0]);
      int* csrRowPtrA = static_cast<int*>(buffers[1]);
      int* csrColIndA = static_cast<int*>(buffers[2]);
      gpuDoubleComplex* b = static_cast<gpuDoubleComplex*>(buffers[3]);
      gpuDoubleComplex* x = static_cast<gpuDoubleComplex*>(buffers[4]);

      JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusolverSpZcsrlsvqr(
          handle.get(), d.n, d.nnz, matdesc, csrValA, csrRowPtrA, csrColIndA, b,
          (float)d.tol, d.reorder, x, &singularity)));

      break;
    }
  }

  cusparseDestroyMatDescr(matdesc);
  return absl::OkStatus();
}

void Csrlsvqr(gpuStream_t stream, void** buffers, const char* opaque,
              size_t opaque_len, XlaCustomCallStatus* status) {
  // Is >= 0 if A is singular.
  int singularity = -1;

  auto s = Csrlsvqr_(stream, buffers, opaque, opaque_len, singularity);
  if (!s.ok()) {
    XlaCustomCallStatusSetFailure(status, std::string(s.message()).c_str(),
                                  s.message().length());
  }

  if (singularity >= 0) {
    auto s = std::string("Singular matrix in linear solve.");
    XlaCustomCallStatusSetFailure(status, s.c_str(), s.length());
  }
}

#endif  // JAX_GPU_CUDA

// orgqr/ungqr: apply elementary Householder transformations

static absl::Status Orgqr_(gpuStream_t stream, void** buffers,
                           const char* opaque, size_t opaque_len) {
  auto s = UnpackDescriptor<OrgqrDescriptor>(opaque, opaque_len);
  JAX_RETURN_IF_ERROR(s.status());
  const OrgqrDescriptor& d = **s;
  auto h = SolverHandlePool::Borrow(stream);
  JAX_RETURN_IF_ERROR(h.status());
  auto& handle = *h;
  if (buffers[2] != buffers[0]) {
    JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpuMemcpyAsync(
        buffers[2], buffers[0],
        SizeOfSolverType(d.type) * static_cast<std::int64_t>(d.batch) *
            static_cast<std::int64_t>(d.m) * static_cast<std::int64_t>(d.n),
        gpuMemcpyDeviceToDevice, stream)));
  }

  int* info = static_cast<int*>(buffers[3]);
  void* workspace = buffers[4];
  switch (d.type) {
    case SolverType::F32: {
      float* a = static_cast<float*>(buffers[2]);
      float* tau = static_cast<float*>(buffers[1]);
      for (int i = 0; i < d.batch; ++i) {
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(
            gpusolverDnSorgqr(handle.get(), d.m, d.n, d.k, a, d.m, tau,
                              static_cast<float*>(workspace), d.lwork, info)));
        a += d.m * d.n;
        tau += d.k;
        ++info;
      }
      break;
    }
    case SolverType::F64: {
      double* a = static_cast<double*>(buffers[2]);
      double* tau = static_cast<double*>(buffers[1]);
      for (int i = 0; i < d.batch; ++i) {
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(
            gpusolverDnDorgqr(handle.get(), d.m, d.n, d.k, a, d.m, tau,
                              static_cast<double*>(workspace), d.lwork, info)));
        a += d.m * d.n;
        tau += d.k;
        ++info;
      }
      break;
    }
    case SolverType::C64: {
      gpuComplex* a = static_cast<gpuComplex*>(buffers[2]);
      gpuComplex* tau = static_cast<gpuComplex*>(buffers[1]);
      for (int i = 0; i < d.batch; ++i) {
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnCungqr(
            handle.get(), d.m, d.n, d.k, a, d.m, tau,
            static_cast<gpuComplex*>(workspace), d.lwork, info)));
        a += d.m * d.n;
        tau += d.k;
        ++info;
      }
      break;
    }
    case SolverType::C128: {
      gpuDoubleComplex* a = static_cast<gpuDoubleComplex*>(buffers[2]);
      gpuDoubleComplex* tau = static_cast<gpuDoubleComplex*>(buffers[1]);
      for (int i = 0; i < d.batch; ++i) {
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnZungqr(
            handle.get(), d.m, d.n, d.k, a, d.m, tau,
            static_cast<gpuDoubleComplex*>(workspace), d.lwork, info)));
        a += d.m * d.n;
        tau += d.k;
        ++info;
      }
      break;
    }
  }
  return absl::OkStatus();
}

void Orgqr(gpuStream_t stream, void** buffers, const char* opaque,
           size_t opaque_len, XlaCustomCallStatus* status) {
  auto s = Orgqr_(stream, buffers, opaque, opaque_len);
  if (!s.ok()) {
    XlaCustomCallStatusSetFailure(status, std::string(s.message()).c_str(),
                                  s.message().length());
  }
}

// Symmetric (Hermitian) eigendecomposition, QR algorithm: syevd/heevd

static absl::Status Syevd_(gpuStream_t stream, void** buffers,
                           const char* opaque, size_t opaque_len) {
  auto s = UnpackDescriptor<SyevdDescriptor>(opaque, opaque_len);
  JAX_RETURN_IF_ERROR(s.status());
  const SyevdDescriptor& d = **s;
  auto h = SolverHandlePool::Borrow(stream);
  JAX_RETURN_IF_ERROR(h.status());
  auto& handle = *h;
  JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpuMemcpyAsync(
      buffers[1], buffers[0],
      SizeOfSolverType(d.type) * static_cast<std::int64_t>(d.batch) *
          static_cast<std::int64_t>(d.n) * static_cast<std::int64_t>(d.n),
      gpuMemcpyDeviceToDevice, stream)));
  gpusolverEigMode_t jobz = GPUSOLVER_EIG_MODE_VECTOR;
  int* info = static_cast<int*>(buffers[3]);
  void* work = buffers[4];
  switch (d.type) {
    case SolverType::F32: {
      float* a = static_cast<float*>(buffers[1]);
      float* w = static_cast<float*>(buffers[2]);
      for (int i = 0; i < d.batch; ++i) {
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(
            gpusolverDnSsyevd(handle.get(), jobz, d.uplo, d.n, a, d.n, w,
                              static_cast<float*>(work), d.lwork, info)));
        a += d.n * d.n;
        w += d.n;
        ++info;
      }
      break;
    }
    case SolverType::F64: {
      double* a = static_cast<double*>(buffers[1]);
      double* w = static_cast<double*>(buffers[2]);
      for (int i = 0; i < d.batch; ++i) {
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(
            gpusolverDnDsyevd(handle.get(), jobz, d.uplo, d.n, a, d.n, w,
                              static_cast<double*>(work), d.lwork, info)));
        a += d.n * d.n;
        w += d.n;
        ++info;
      }
      break;
    }
    case SolverType::C64: {
      gpuComplex* a = static_cast<gpuComplex*>(buffers[1]);
      float* w = static_cast<float*>(buffers[2]);
      for (int i = 0; i < d.batch; ++i) {
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(
            gpusolverDnCheevd(handle.get(), jobz, d.uplo, d.n, a, d.n, w,
                              static_cast<gpuComplex*>(work), d.lwork, info)));
        a += d.n * d.n;
        w += d.n;
        ++info;
      }
      break;
    }
    case SolverType::C128: {
      gpuDoubleComplex* a = static_cast<gpuDoubleComplex*>(buffers[1]);
      double* w = static_cast<double*>(buffers[2]);
      for (int i = 0; i < d.batch; ++i) {
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnZheevd(
            handle.get(), jobz, d.uplo, d.n, a, d.n, w,
            static_cast<gpuDoubleComplex*>(work), d.lwork, info)));
        a += d.n * d.n;
        w += d.n;
        ++info;
      }
      break;
    }
  }
  return absl::OkStatus();
}

void Syevd(gpuStream_t stream, void** buffers, const char* opaque,
           size_t opaque_len, XlaCustomCallStatus* status) {
  auto s = Syevd_(stream, buffers, opaque, opaque_len);
  if (!s.ok()) {
    XlaCustomCallStatusSetFailure(status, std::string(s.message()).c_str(),
                                  s.message().length());
  }
}

// Symmetric (Hermitian) eigendecomposition, Jacobi algorithm: syevj/heevj
// Supports batches of matrices up to size 32.

absl::Status Syevj_(gpuStream_t stream, void** buffers, const char* opaque,
                    size_t opaque_len) {
  auto s = UnpackDescriptor<SyevjDescriptor>(opaque, opaque_len);
  JAX_RETURN_IF_ERROR(s.status());
  const SyevjDescriptor& d = **s;
  auto h = SolverHandlePool::Borrow(stream);
  JAX_RETURN_IF_ERROR(h.status());
  auto& handle = *h;
  if (buffers[1] != buffers[0]) {
    JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpuMemcpyAsync(
        buffers[1], buffers[0],
        SizeOfSolverType(d.type) * static_cast<std::int64_t>(d.batch) *
            static_cast<std::int64_t>(d.n) * static_cast<std::int64_t>(d.n),
        gpuMemcpyDeviceToDevice, stream)));
  }
  gpuSyevjInfo_t params;
  JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnCreateSyevjInfo(&params)));
  std::unique_ptr<gpuSyevjInfo, void (*)(gpuSyevjInfo_t)> params_cleanup(
      params, [](gpuSyevjInfo_t p) { gpusolverDnDestroySyevjInfo(p); });

  gpusolverEigMode_t jobz = GPUSOLVER_EIG_MODE_VECTOR;
  int* info = static_cast<int*>(buffers[3]);
  void* work = buffers[4];
  if (d.batch == 1) {
    switch (d.type) {
      case SolverType::F32: {
        float* a = static_cast<float*>(buffers[1]);
        float* w = static_cast<float*>(buffers[2]);
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnSsyevj(
            handle.get(), jobz, d.uplo, d.n, a, d.n, w,
            static_cast<float*>(work), d.lwork, info, params)));
        break;
      }
      case SolverType::F64: {
        double* a = static_cast<double*>(buffers[1]);
        double* w = static_cast<double*>(buffers[2]);
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnDsyevj(
            handle.get(), jobz, d.uplo, d.n, a, d.n, w,
            static_cast<double*>(work), d.lwork, info, params)));
        break;
      }
      case SolverType::C64: {
        gpuComplex* a = static_cast<gpuComplex*>(buffers[1]);
        float* w = static_cast<float*>(buffers[2]);
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnCheevj(
            handle.get(), jobz, d.uplo, d.n, a, d.n, w,
            static_cast<gpuComplex*>(work), d.lwork, info, params)));
        break;
      }
      case SolverType::C128: {
        gpuDoubleComplex* a = static_cast<gpuDoubleComplex*>(buffers[1]);
        double* w = static_cast<double*>(buffers[2]);
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnZheevj(
            handle.get(), jobz, d.uplo, d.n, a, d.n, w,
            static_cast<gpuDoubleComplex*>(work), d.lwork, info, params)));
        break;
      }
    }
  } else {
    switch (d.type) {
      case SolverType::F32: {
        float* a = static_cast<float*>(buffers[1]);
        float* w = static_cast<float*>(buffers[2]);
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnSsyevjBatched(
            handle.get(), jobz, d.uplo, d.n, a, d.n, w,
            static_cast<float*>(work), d.lwork, info, params, d.batch)));
        break;
      }
      case SolverType::F64: {
        double* a = static_cast<double*>(buffers[1]);
        double* w = static_cast<double*>(buffers[2]);
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnDsyevjBatched(
            handle.get(), jobz, d.uplo, d.n, a, d.n, w,
            static_cast<double*>(work), d.lwork, info, params, d.batch)));
        break;
      }
      case SolverType::C64: {
        gpuComplex* a = static_cast<gpuComplex*>(buffers[1]);
        float* w = static_cast<float*>(buffers[2]);
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnCheevjBatched(
            handle.get(), jobz, d.uplo, d.n, a, d.n, w,
            static_cast<gpuComplex*>(work), d.lwork, info, params, d.batch)));
        break;
      }
      case SolverType::C128: {
        gpuDoubleComplex* a = static_cast<gpuDoubleComplex*>(buffers[1]);
        double* w = static_cast<double*>(buffers[2]);
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(
            gpusolverDnZheevjBatched(handle.get(), jobz, d.uplo, d.n, a, d.n, w,
                                     static_cast<gpuDoubleComplex*>(work),
                                     d.lwork, info, params, d.batch)));
        break;
      }
    }
  }
  return absl::OkStatus();
}

void Syevj(gpuStream_t stream, void** buffers, const char* opaque,
           size_t opaque_len, XlaCustomCallStatus* status) {
  auto s = Syevj_(stream, buffers, opaque, opaque_len);
  if (!s.ok()) {
    XlaCustomCallStatusSetFailure(status, std::string(s.message()).c_str(),
                                  s.message().length());
  }
}

// Singular value decomposition using QR algorithm: gesvd

static absl::Status Gesvd_(gpuStream_t stream, void** buffers,
                           const char* opaque, size_t opaque_len) {
  auto s = UnpackDescriptor<GesvdDescriptor>(opaque, opaque_len);
  JAX_RETURN_IF_ERROR(s.status());
  const GesvdDescriptor& d = **s;
  auto h = SolverHandlePool::Borrow(stream);
  JAX_RETURN_IF_ERROR(h.status());
  auto& handle = *h;
  JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpuMemcpyAsync(
      buffers[1], buffers[0],
      SizeOfSolverType(d.type) * static_cast<std::int64_t>(d.batch) *
          static_cast<std::int64_t>(d.m) * static_cast<std::int64_t>(d.n),
      gpuMemcpyDeviceToDevice, stream)));
  int* info = static_cast<int*>(buffers[5]);
  void* work = buffers[6];
  int64_t k = d.jobu == 'A' ? d.m : d.n;
  switch (d.type) {
    case SolverType::F32: {
      float* a = static_cast<float*>(buffers[1]);
      float* s = static_cast<float*>(buffers[2]);
      float* u = static_cast<float*>(buffers[3]);
      float* vt = static_cast<float*>(buffers[4]);
      for (int i = 0; i < d.batch; ++i) {
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnSgesvd(
            handle.get(), d.jobu, d.jobvt, d.m, d.n, a, d.m, s, u, d.m, vt, d.n,
            static_cast<float*>(work), d.lwork,
            /*rwork=*/nullptr, info)));
        a += d.m * d.n;
        s += std::min(d.m, d.n);
        u += d.m * k;
        vt += d.n * d.n;
        ++info;
      }
      break;
    }
    case SolverType::F64: {
      double* a = static_cast<double*>(buffers[1]);
      double* s = static_cast<double*>(buffers[2]);
      double* u = static_cast<double*>(buffers[3]);
      double* vt = static_cast<double*>(buffers[4]);
      for (int i = 0; i < d.batch; ++i) {
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnDgesvd(
            handle.get(), d.jobu, d.jobvt, d.m, d.n, a, d.m, s, u, d.m, vt, d.n,
            static_cast<double*>(work), d.lwork,
            /*rwork=*/nullptr, info)));
        a += d.m * d.n;
        s += std::min(d.m, d.n);
        u += d.m * k;
        vt += d.n * d.n;
        ++info;
      }
      break;
    }
    case SolverType::C64: {
      gpuComplex* a = static_cast<gpuComplex*>(buffers[1]);
      float* s = static_cast<float*>(buffers[2]);
      gpuComplex* u = static_cast<gpuComplex*>(buffers[3]);
      gpuComplex* vt = static_cast<gpuComplex*>(buffers[4]);
      for (int i = 0; i < d.batch; ++i) {
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnCgesvd(
            handle.get(), d.jobu, d.jobvt, d.m, d.n, a, d.m, s, u, d.m, vt, d.n,
            static_cast<gpuComplex*>(work), d.lwork, /*rwork=*/nullptr, info)));
        a += d.m * d.n;
        s += std::min(d.m, d.n);
        u += d.m * k;
        vt += d.n * d.n;
        ++info;
      }
      break;
    }
    case SolverType::C128: {
      gpuDoubleComplex* a = static_cast<gpuDoubleComplex*>(buffers[1]);
      double* s = static_cast<double*>(buffers[2]);
      gpuDoubleComplex* u = static_cast<gpuDoubleComplex*>(buffers[3]);
      gpuDoubleComplex* vt = static_cast<gpuDoubleComplex*>(buffers[4]);
      for (int i = 0; i < d.batch; ++i) {
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnZgesvd(
            handle.get(), d.jobu, d.jobvt, d.m, d.n, a, d.m, s, u, d.m, vt, d.n,
            static_cast<gpuDoubleComplex*>(work), d.lwork,
            /*rwork=*/nullptr, info)));
        a += d.m * d.n;
        s += std::min(d.m, d.n);
        u += d.m * k;
        vt += d.n * d.n;
        ++info;
      }
      break;
    }
  }
  return absl::OkStatus();
}

void Gesvd(gpuStream_t stream, void** buffers, const char* opaque,
           size_t opaque_len, XlaCustomCallStatus* status) {
  auto s = Gesvd_(stream, buffers, opaque, opaque_len);
  if (!s.ok()) {
    XlaCustomCallStatusSetFailure(status, std::string(s.message()).c_str(),
                                  s.message().length());
  }
}

#ifdef JAX_GPU_CUDA

// Singular value decomposition using Jacobi algorithm: gesvdj

static absl::Status Gesvdj_(gpuStream_t stream, void** buffers,
                            const char* opaque, size_t opaque_len) {
  auto s = UnpackDescriptor<GesvdjDescriptor>(opaque, opaque_len);
  JAX_RETURN_IF_ERROR(s.status());
  const GesvdjDescriptor& d = **s;
  auto h = SolverHandlePool::Borrow(stream);
  JAX_RETURN_IF_ERROR(h.status());
  auto& handle = *h;
  JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpuMemcpyAsync(
      buffers[1], buffers[0],
      SizeOfSolverType(d.type) * static_cast<std::int64_t>(d.batch) *
          static_cast<std::int64_t>(d.m) * static_cast<std::int64_t>(d.n),
      gpuMemcpyDeviceToDevice, stream)));
  int* info = static_cast<int*>(buffers[5]);
  void* work = buffers[6];
  gesvdjInfo_t params;
  JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusolverDnCreateGesvdjInfo(&params)));
  std::unique_ptr<gesvdjInfo, void (*)(gesvdjInfo*)> params_cleanup(
      params, [](gesvdjInfo* p) { cusolverDnDestroyGesvdjInfo(p); });
  if (d.batch == 1) {
    switch (d.type) {
      case SolverType::F32: {
        float* a = static_cast<float*>(buffers[1]);
        float* s = static_cast<float*>(buffers[2]);
        float* u = static_cast<float*>(buffers[3]);
        float* v = static_cast<float*>(buffers[4]);
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusolverDnSgesvdj(
            handle.get(), d.jobz, d.econ, d.m, d.n, a, d.m, s, u, d.m, v, d.n,
            static_cast<float*>(work), d.lwork, info, params)));
        break;
      }
      case SolverType::F64: {
        double* a = static_cast<double*>(buffers[1]);
        double* s = static_cast<double*>(buffers[2]);
        double* u = static_cast<double*>(buffers[3]);
        double* v = static_cast<double*>(buffers[4]);
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusolverDnDgesvdj(
            handle.get(), d.jobz, d.econ, d.m, d.n, a, d.m, s, u, d.m, v, d.n,
            static_cast<double*>(work), d.lwork, info, params)));
        break;
      }
      case SolverType::C64: {
        gpuComplex* a = static_cast<gpuComplex*>(buffers[1]);
        float* s = static_cast<float*>(buffers[2]);
        gpuComplex* u = static_cast<gpuComplex*>(buffers[3]);
        gpuComplex* v = static_cast<gpuComplex*>(buffers[4]);
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusolverDnCgesvdj(
            handle.get(), d.jobz, d.econ, d.m, d.n, a, d.m, s, u, d.m, v, d.n,
            static_cast<gpuComplex*>(work), d.lwork, info, params)));
        break;
      }
      case SolverType::C128: {
        gpuDoubleComplex* a = static_cast<gpuDoubleComplex*>(buffers[1]);
        double* s = static_cast<double*>(buffers[2]);
        gpuDoubleComplex* u = static_cast<gpuDoubleComplex*>(buffers[3]);
        gpuDoubleComplex* v = static_cast<gpuDoubleComplex*>(buffers[4]);
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusolverDnZgesvdj(
            handle.get(), d.jobz, d.econ, d.m, d.n, a, d.m, s, u, d.m, v, d.n,
            static_cast<gpuDoubleComplex*>(work), d.lwork, info, params)));
        break;
      }
    }
  } else {
    switch (d.type) {
      case SolverType::F32: {
        float* a = static_cast<float*>(buffers[1]);
        float* s = static_cast<float*>(buffers[2]);
        float* u = static_cast<float*>(buffers[3]);
        float* v = static_cast<float*>(buffers[4]);
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusolverDnSgesvdjBatched(
            handle.get(), d.jobz, d.m, d.n, a, d.m, s, u, d.m, v, d.n,
            static_cast<float*>(work), d.lwork, info, params, d.batch)));
        break;
      }
      case SolverType::F64: {
        double* a = static_cast<double*>(buffers[1]);
        double* s = static_cast<double*>(buffers[2]);
        double* u = static_cast<double*>(buffers[3]);
        double* v = static_cast<double*>(buffers[4]);
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusolverDnDgesvdjBatched(
            handle.get(), d.jobz, d.m, d.n, a, d.m, s, u, d.m, v, d.n,
            static_cast<double*>(work), d.lwork, info, params, d.batch)));
        break;
      }
      case SolverType::C64: {
        gpuComplex* a = static_cast<gpuComplex*>(buffers[1]);
        float* s = static_cast<float*>(buffers[2]);
        gpuComplex* u = static_cast<gpuComplex*>(buffers[3]);
        gpuComplex* v = static_cast<gpuComplex*>(buffers[4]);
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusolverDnCgesvdjBatched(
            handle.get(), d.jobz, d.m, d.n, a, d.m, s, u, d.m, v, d.n,
            static_cast<gpuComplex*>(work), d.lwork, info, params, d.batch)));
        break;
      }
      case SolverType::C128: {
        gpuDoubleComplex* a = static_cast<gpuDoubleComplex*>(buffers[1]);
        double* s = static_cast<double*>(buffers[2]);
        gpuDoubleComplex* u = static_cast<gpuDoubleComplex*>(buffers[3]);
        gpuDoubleComplex* v = static_cast<gpuDoubleComplex*>(buffers[4]);
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(cusolverDnZgesvdjBatched(
            handle.get(), d.jobz, d.m, d.n, a, d.m, s, u, d.m, v, d.n,
            static_cast<gpuDoubleComplex*>(work), d.lwork, info, params,
            d.batch)));
        break;
      }
    }
  }
  return absl::OkStatus();
}

void Gesvdj(gpuStream_t stream, void** buffers, const char* opaque,
            size_t opaque_len, XlaCustomCallStatus* status) {
  auto s = Gesvdj_(stream, buffers, opaque, opaque_len);
  if (!s.ok()) {
    XlaCustomCallStatusSetFailure(status, std::string(s.message()).c_str(),
                                  s.message().length());
  }
}

#endif  // JAX_GPU_CUDA

// sytrd/hetrd: symmetric (Hermitian) tridiagonal reduction

static absl::Status Sytrd_(gpuStream_t stream, void** buffers,
                           const char* opaque, size_t opaque_len) {
  auto s = UnpackDescriptor<SytrdDescriptor>(opaque, opaque_len);
  JAX_RETURN_IF_ERROR(s.status());
  const SytrdDescriptor& d = **s;
  auto h = SolverHandlePool::Borrow(stream);
  JAX_RETURN_IF_ERROR(h.status());
  auto& handle = *h;
  if (buffers[1] != buffers[0]) {
    JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpuMemcpyAsync(
        buffers[1], buffers[0],
        SizeOfSolverType(d.type) * static_cast<std::int64_t>(d.batch) *
            static_cast<std::int64_t>(d.n) * static_cast<std::int64_t>(d.lda),
        gpuMemcpyDeviceToDevice, stream)));
  }

  int* info = static_cast<int*>(buffers[5]);
  void* workspace = buffers[6];
  switch (d.type) {
    case SolverType::F32: {
      float* a = static_cast<float*>(buffers[1]);
      float* d_out = static_cast<float*>(buffers[2]);
      float* e_out = static_cast<float*>(buffers[3]);
      float* tau = static_cast<float*>(buffers[4]);
      for (int i = 0; i < d.batch; ++i) {
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnSsytrd(
            handle.get(), d.uplo, d.n, a, d.lda, d_out, e_out, tau,
            static_cast<float*>(workspace), d.lwork, info)));
        a += d.lda * d.n;
        d_out += d.n;
        e_out += d.n - 1;
        tau += d.n - 1;
        ++info;
      }
      break;
    }
    case SolverType::F64: {
      double* a = static_cast<double*>(buffers[1]);
      double* d_out = static_cast<double*>(buffers[2]);
      double* e_out = static_cast<double*>(buffers[3]);
      double* tau = static_cast<double*>(buffers[4]);
      for (int i = 0; i < d.batch; ++i) {
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnDsytrd(
            handle.get(), d.uplo, d.n, a, d.lda, d_out, e_out, tau,
            static_cast<double*>(workspace), d.lwork, info)));
        a += d.lda * d.n;
        d_out += d.n;
        e_out += d.n - 1;
        tau += d.n - 1;
        ++info;
      }
      break;
    }
    case SolverType::C64: {
      gpuComplex* a = static_cast<gpuComplex*>(buffers[1]);
      float* d_out = static_cast<float*>(buffers[2]);
      float* e_out = static_cast<float*>(buffers[3]);
      gpuComplex* tau = static_cast<gpuComplex*>(buffers[4]);
      for (int i = 0; i < d.batch; ++i) {
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnChetrd(
            handle.get(), d.uplo, d.n, a, d.lda, d_out, e_out, tau,
            static_cast<gpuComplex*>(workspace), d.lwork, info)));
        a += d.lda * d.n;
        d_out += d.n;
        e_out += d.n - 1;
        tau += d.n - 1;
        ++info;
      }
      break;
    }
    case SolverType::C128: {
      gpuDoubleComplex* a = static_cast<gpuDoubleComplex*>(buffers[1]);
      double* d_out = static_cast<double*>(buffers[2]);
      double* e_out = static_cast<double*>(buffers[3]);
      gpuDoubleComplex* tau = static_cast<gpuDoubleComplex*>(buffers[4]);
      for (int i = 0; i < d.batch; ++i) {
        JAX_RETURN_IF_ERROR(JAX_AS_STATUS(gpusolverDnZhetrd(
            handle.get(), d.uplo, d.n, a, d.lda, d_out, e_out, tau,
            static_cast<gpuDoubleComplex*>(workspace), d.lwork, info)));
        a += d.lda * d.n;
        d_out += d.n;
        e_out += d.n - 1;
        tau += d.n - 1;
        ++info;
      }
      break;
    }
  }
  return absl::OkStatus();
}

void Sytrd(gpuStream_t stream, void** buffers, const char* opaque,
           size_t opaque_len, XlaCustomCallStatus* status) {
  auto s = Sytrd_(stream, buffers, opaque, opaque_len);
  if (!s.ok()) {
    XlaCustomCallStatusSetFailure(status, std::string(s.message()).c_str(),
                                  s.message().length());
  }
}

}  // namespace JAX_GPU_NAMESPACE
}  // namespace jax


text:
require 'rubygems'
require 'cgi'
require 'json'
require 'openssl'
require 'net/http'

module Shodan

  # The Shodan class interfaces with the official Shodan API.
  # For more information on the API, please visit https://developer.shodan.io
  #
  # Author:: achillean (mailto:jmath@shodan.io)
  #
  # :title:Shodan::Shodan
  class Shodan
    attr_accessor :api_key
    attr_accessor :base_url
    attr_accessor :exploits

    def initialize(api_key)
      @api_key = api_key
      @base_url = "https://api.shodan.io/"
      @base_url_exploits = "https://exploits.shodan.io/api/"

      @exploits = Exploits.new(self)
    end

    # Internal method that sends out the HTTP request.
    # Expects a webservice function (ex. 'search') name and a hash of arguments.
    def request(type, func, args)
      if type == "exploits"
        base_url = @base_url_exploits
      else
        base_url = @base_url
      end

      # Convert the argument hash into a string
      args_string = args.map{|k, v| "#{CGI.escape(k.to_s)}=#{CGI.escape(v.to_s)}"}.join("&")

      # Craft the final request URL
      url = "#{base_url}#{func}?key=#{@api_key}&#{args_string}"

      # Send the request
      uri = URI.parse(url)
      http = Net::HTTP.new(uri.host, uri.port)
      http.use_ssl = true
      http.verify_mode = OpenSSL::SSL::VERIFY_NONE
      response = http.get(uri.request_uri)

      # Convert the JSON data into a native Ruby hash
      data = JSON.parse(response.body)

      # Raise an error if something went wrong
      if data.has_key? 'error'
        raise data['error']
      end

      return data
    end

    # Get all available information on an IP.
    #
    # Arguments:
    # ip  - host IP (string)
    #
    # Returns a hash containing the host information
    def host(ip)
      return request('shodan', "shodan/host/#{ip}", {})
    end

    # Perform a search on Shodan.
    #
    # Arguments:
    # query - search query; same format as the website (string)
    #
    # Returns a hash containing the search results
    def search(query, params={})
      params[:query] = query
      return request('shodan', 'shodan/host/search', params)
    end

    # Find how many results there are for a search term.
    #
    # Arguments:
    # query - search query; same format as the website (string)
    #
    # Returns a hash containing the total number of search results
    def count(query, params={})
      params[:query] = query
      return request('shodan', 'shodan/host/count', params)
    end

    # Returns information about the current API key.
    def info()
      return request('shodan', 'api-info', {})
    end
  end

  # The Exploits class shouldn't be used independently,
  # as it depends on the Shodan class.
  #
  # Author:: achillean (mailto:jmath@shodan.io)
  #
  # :title:Shodan::Exploits
  class Exploits
    attr_accessor :api

    def initialize(api)
      @api = api
    end

    # Search the Shodan Exploits archive for exploits.
    #
    # Arguments:
    # query     -- Search terms
    #
    # Optional arguments:
    # facets    -- A comma-separated list of properties to get summary information on.
    # page      -- The page number to page through results 100 exploits at a time.
    #
    # Returns:
    # A dictionary with 2 main items: matches (list) and total (int).
    # Please visit https://developer.shodan.io/api/exploit-specification for up-to-date information on what an Exploit result contains.
    def search(query, params={})
      params[:query] = query
      return @api.request('exploits', 'search', params)
    end

    # Search the Shodan Exploits archive for exploits but don't return results, only the number of matches.
    #
    # Arguments:
    # query     -- Search terms
    #
    # Optional arguments:
    # facets    -- A comma-separated list of properties to get summary information on.
    #
    # Returns:
    # A dictionary with 1 main item: total (int).
    def count(query, params={})
      params[:query] = query
      return @api.request('exploits', 'count', params)
    end

  end

end


text:
.mint-indexsection {
    padding: 0;
    margin: 0
}
.mint-indexsection-index {
    padding: 10px;
    background-color: #fafafa
}


text:
Proxy Cache for Multiple Domains

## Installation

This module is installed via npm:

```sh
npm i proxy-cache-multi-domain --save
```

## Example Usage

```js
var proxyCacheMultiDomain = require('proxy-cache-multi-domain')
console.log(proxyCacheMultiDomain)())
```

## Rights

Copyright (C) 2015 by Yieme, License: MIT


text:
- [Homologene sub-tab](#homologene-sub-tab)
- [Orthologs and paralogs sub-tab](#orthologs-and-paralogs-sub-tab)

Users can search for the homologous genes.
The search is being performed in the inner copy of [`NCBI Homologene`](https://www.ncbi.nlm.nih.gov/homologene/) database or in uploaded custom databases.

There are two ways to start the search of homologous genes:

- from the context menu at the **Browser** panel by the left-click on any gene at the GENE track:
  ![NGB GUI](images/homologs-01.png)
- from the context menu at the **Genes** panel by the right-click on any gene:
  ![NGB GUI](images/homologs-02.png)

**_Note_**: in both cases, these items in menus are available only if the feature has `gene` feature type and non-empty gene name.

After, the search in the inner copy of NCBI Homologene database is being performed using the gene name and the current species.
**Homologs** panel will be opened automatically (_at the picture below the search results for `ETNK1` gene is shown_):
  ![NGB GUI](images/homologs-03.png)

This panel contains two sub-tabs:

- "**Homologene**" (_opened by default_) - for displaying search results of gene homologs from the NCBI Homologene database
- "**Orthologs & paralogs**" - for displaying search results of gene orthologs and paralogs from the corresponding NCBI Database (`NCBI Orthologs`) and/or inner NGB databases

## Homologene sub-tab

Here, the search results over NCBI Homologene database are being shown:
  ![NGB GUI](images/homologs-04.png)

Each record contains:

- _Gene name_ - gene names of all homologs of the certain record (ordered alphabetically)
- _Protein name_ - the most "popular" protein name among all homologs of the certain record (the one that meet the most times)
- _Info_ - additional record info (_optionally_)

Click any row in that table to open details of the certain Homologene record:
  ![NGB GUI](images/homologs-05.png)
  ![NGB GUI](images/homologs-06.png)

This form contains:

- button to return to the previous table (with the list of found Homologene records)
  ![NGB GUI](images/homologs-07.png)
- additional record info where homologs were found (if exists) - as the **Homologs** table header
- **Homologs** table that contains two columns:
    - _Gene_ - for a gene info with two sub-columns:
        - _Name_ - for a gene name
        - _Species_ - for a species name
    - _Protein_ - for a protein info with following sub-columns:
        - _Accession ID_ - for a protein sequence accession ID. It is a hyperlink. User can click it and navigate to the corresponding protein page in NCBI (in a new tab)
        - _Protein_ - for a protein name
        - _Aa_ - for a protein sequence length
        - _Domains_ - for an approximate image of the conserved protein domains. Each image contains:
            - a line for a full protein length
            - one or several color rectangles - each for the specific conserved domain. Different domains are drawn by different colors, the same domains are drawn in the same colors

The table supports sorting by any sub-column, except "Domains".

Gene names in this table are hyperlinks.
User can click any gene of interest and navigate:

- to the corresponding location of the selected species at the GENE track in "**Browser**" panel (if the reference is uploaded in NGB)
  ![NGB GUI](images/homologs-08.png)
  ![NGB GUI](images/homologs-09.png)
- to the corresponding gene page in NCBI (if the reference is not uploaded in NGB)

User can click any domain rectangle in the table and a tooltip will appear with a full "legend" of the corresponding gene domains:
  ![NGB GUI](images/homologs-10.png)
Tooltip contains:

- accession ID as a hyperlink to the corresponding protein page in NCBI
- full protein sequence length
- list of domains. For each domain are specified:
    - domain color and positions
    - domain ID as a hyperlink to the corresponding conserved domains database page in NCBI
    - domain name

## Orthologs and paralogs sub-tab

This sub-tab can be opened manually (after the search of "similar genes" is performed).
Here, the search results over orthologs and paralogs NGB databases (NCBI Orthologs or custom) should be shown, e.g.:
  ![NGB GUI](images/homologs-11.png)

Each record contains:

- _Gene name_ - gene name of all homologs of the certain record (ordered alphabetically)
- _Protein name_ - the most "popular" protein name among all homologs of the certain record (the one that meet the most times)
- _Info_ - record info with database name where the results were found

Click any row in that table to open results details from the certain database:
  ![NGB GUI](images/homologs-12.png)
  ![NGB GUI](images/homologs-13.png)

This form contains:

- arrow-button to return to the previous table (with the list of found records)
- additional record info where orthologs and paralogs were found (if exists)
- **Orthologs and paralogs** table that contains columns:
    - _Name_ - for a gene name
    - _Species_ - for a species name
    - _Aa_ - for a protein sequence length
    - _Domains_ - for an approximate image of the conserved protein domains (similar to **Homologs** table)
    - _Type_ - for a type of the homolog - _`Ortholog`_ or _`Paralog`_

The table supports sorting by any sub-column, except "Domains".

Gene names in this table are hyperlinks.
User can click any gene of interest and navigate to the GENE track in the "**Browser**" panel (if the reference is uploaded in NGB) or to the corresponding gene page in NCBI (if the reference is not uploaded in NGB) - similarly to the **Homologs** table.

User can click any domain rectangle in the table and a tooltip will appear with a full "legend" of the corresponding gene domains - similarly to the **Homologs** table.

> **_Note_**: some data may often be missing in the **Orthologs and paralogs** table.
> In this case:
>
> - if the gene name is unknown - gene ID is displayed instead
> - if the protein sequence length is unknown - zero is displayed in the corresponding column
> - if there is no info about domains - nothing is displayed in the corresponding column


text:
/*
 * 文  件   名: DictController.java
 * 版         本 : vigor-platform-console © 2016 Anttribe. All rights reserved.
 * 描         述 : <描述>
 * 修   改  人: zhaoyong
 * 修改时间: 2016年3月27日
 */
package org.anttribe.vigor.platform.console.modules.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.anttribe.vigor.infra.common.constants.Constants;
import org.anttribe.vigor.infra.common.constants.Keys;
import org.anttribe.vigor.infra.common.entity.Result;
import org.anttribe.vigor.infra.common.errorno.SystemErrorNo;
import org.anttribe.vigor.infra.common.exception.ServiceException;
import org.anttribe.vigor.infra.common.exception.UnifyException;
import org.anttribe.vigor.infra.common.web.controller.AbstractController;
import org.anttribe.vigor.infra.dict.domain.Dict;
import org.anttribe.vigor.infra.dict.service.IDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author zhaoyong
 * @version 2016年3月27日
 */
@Controller
@RequestMapping("/dict")
public class DictController extends AbstractController
{
    @Autowired
    private IDictService dictService;

    @RequestMapping(value = {"", "/", "/index"})
    public ModelAndView index(HttpServletRequest request, ModelAndView mv, Dict dict)
    {
        mv.setViewName(Views.LIST_VIEW);

        Map<String, Object> criteria = new HashMap<String, Object>();
        List<Dict> dicts = dictService.listEntities(criteria);
        mv.addObject(Keys.KEY_PAGE_DATA, dicts);
        return mv;
    }

    @RequestMapping("/list/exec")
    @ResponseBody
    public Result<?> doList(HttpServletRequest request, Dict dict)
    {
        Result<List<Dict>> result = new Result<List<Dict>>();
        try
        {
            Map<String, Object> criteria = new HashMap<String, Object>();
            criteria.put("key", dict.getKey());
            List<Dict> dicts = dictService.listEntities(criteria);
            result.setData(dicts);

            result.setResultCode(Constants.Common.DEFAULT_RESULT_CODE);
        }
        catch (ServiceException e)
        {
            result.setResultCode(e.getErrorNo());
        }
        return result;
    }

    @RequestMapping("/add")
    public ModelAndView add(HttpServletRequest request, ModelAndView mv, Dict dict)
    {
        mv.setViewName(Views.ADD_VIEW);
        mv.addObject(Keys.KEY_PARAM, dict);

        return mv;
    }

    @RequestMapping("/edit")
    public ModelAndView edit(HttpServletRequest request, ModelAndView mv, Dict dict)
    {
        if (null == dict || null == dict.getId())
        {
            throw new UnifyException(SystemErrorNo.DATA_NOT_EXIST_ERROR);
        }

        Map<String, Object> criteria = new HashMap<String, Object>();
        criteria.put("id", dict.getId());
        dict = dictService.findEntity(criteria);
        if (null == dict || null == dict.getId())
        {
            throw new UnifyException(SystemErrorNo.DATA_NOT_EXIST_ERROR);
        }

        mv.setViewName(Views.EDIT_VIEW);
        mv.addObject(Keys.KEY_PARAM, dict);
        return mv;
    }

    @ResponseBody
    @RequestMapping("/edit/exec")
    public Result<?> doEdit(HttpServletRequest request, Dict dict)
    {
        Result<?> result = new Result<String>();
        try
        {
            // TODO: 数据校验

            dictService.persistentEntity(dict);
            result.setResultCode(Constants.Common.DEFAULT_RESULT_CODE);
        }
        catch (ServiceException e)
        {
            result.setResultCode(e.getErrorNo());
        }
        return result;
    }

    @ResponseBody
    @RequestMapping("/remove/exec")
    public Result<?> doRemove(HttpServletRequest request, Dict dict)
    {
        Result<?> result = new Result<String>();
        try
        {
            Map<String, Object> criteria = new HashMap<String, Object>();
            criteria.put("id", dict.getId());
            dictService.removeEntity(criteria);
            result.setResultCode(Constants.Common.DEFAULT_RESULT_CODE);
        }
        catch (ServiceException e)
        {
            result.setResultCode(e.getErrorNo());
        }
        return result;
    }

    class Views
    {
        /**
         * 列表视图
         */
        public static final String LIST_VIEW = "/modules/system/dict/list";

        /**
         * 添加视图
         */
        public static final String ADD_VIEW = "/modules/system/dict/edit";

        /**
         * 编辑视图
         */
        public static final String EDIT_VIEW = "/modules/system/dict/edit";
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:background="@color/black"
             android:padding="2dp"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/imageView"
        android:minHeight="150dp"
        android:scaleType="centerCrop"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</FrameLayout>


text:
(function($){

	'use strict';

	var themifyGalleryShortcode = {
		init: function(){
			this.galleryShortcode();
		},

		galleryShortcode: function(){
			var clone = wp.media.gallery.shortcode, wpgallery = wp.media.gallery, file_frame, frame;

			$('.themify-gallery-shortcode-btn').on('click', function(event) {
				var shortcode_val = $(this).closest('.themify_field').find('.themify-gallery-shortcode-input');

				if (file_frame) {
					file_frame.open();
				} else {
					if ($.trim(shortcode_val.val()).length > 0) {
						file_frame = wpgallery.edit($.trim(shortcode_val.val()));
					} else {
						file_frame = wp.media.frames.file_frame = wp.media({
							frame : 'post',
							state : 'gallery-edit',
							title : wp.media.view.l10n.editGalleryTitle,
							editing : true,
							multiple : true,
							selection : false
						});
					}
				}

				wp.media.gallery.shortcode = function(attachments) {
					var props = attachments.props.toJSON(), attrs = _.pick(props, 'orderby', 'order');

					if (attachments.gallery)
						_.extend(attrs, attachments.gallery.toJSON());

					attrs.ids = attachments.pluck('id');

					// Copy the `uploadedTo` post ID.
					if (props.uploadedTo)
						attrs.id = props.uploadedTo;

					// Check if the gallery is randomly ordered.
					if (attrs._orderbyRandom)
						attrs.orderby = 'rand';
					delete attrs._orderbyRandom;

					// If the `ids` attribute is set and `orderby` attribute
					// is the default value, clear it for cleaner output.
					if (attrs.ids && 'post__in' === attrs.orderby)
						delete attrs.orderby;

					// Remove default attributes from the shortcode.
					_.each(wp.media.gallery.defaults, function(value, key) {
						if (value === attrs[key])
							delete attrs[key];
					});

					var shortcode = new wp.shortcode({
						tag : 'gallery',
						attrs : attrs,
						type : 'single'
					});

					shortcode_val.val(shortcode.string());

					wp.media.gallery.shortcode = clone;
					return shortcode;
				};

				file_frame.on('update', function(selection) {
					var shortcode = wp.media.gallery.shortcode(selection).string().slice(1, -1);
					shortcode_val.val('[' + shortcode + ']');
				});

				if ($.trim(shortcode_val.val()).length == 0) {
					$('.media-menu').find('.media-menu-item').last().trigger('click');
				}
				event.preventDefault();
			});
		}
	};
	$(document).ready(function() {
		themifyGalleryShortcode.init();
	});
})(jQuery);


text:
package mocks

import gh "poule/gh"
import github "github.com/google/go-github/github"
import mock "github.com/stretchr/testify/mock"

// SearchService is an autogenerated mock type for the SearchService type
type SearchService struct {
	mock.Mock
}

// Issues provides a mock function with given fields: query, opt
func (_m *SearchService) Issues(query string, opt *github.SearchOptions) (*github.IssuesSearchResult, *github.Response, error) {
	ret := _m.Called(query, opt)

	var r0 *github.IssuesSearchResult
	if rf, ok := ret.Get(0).(func(string, *github.SearchOptions) *github.IssuesSearchResult); ok {
		r0 = rf(query, opt)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(*github.IssuesSearchResult)
		}
	}

	var r1 *github.Response
	if rf, ok := ret.Get(1).(func(string, *github.SearchOptions) *github.Response); ok {
		r1 = rf(query, opt)
	} else {
		if ret.Get(1) != nil {
			r1 = ret.Get(1).(*github.Response)
		}
	}

	var r2 error
	if rf, ok := ret.Get(2).(func(string, *github.SearchOptions) error); ok {
		r2 = rf(query, opt)
	} else {
		r2 = ret.Error(2)
	}

	return r0, r1, r2
}

var _ gh.SearchService = (*SearchService)(nil)


text:
"""Contains the logic for `aq show machine --all`."""

from aquilon.worker.broker import BrokerCommand  # pylint: disable=W0611
from aquilon.worker.formats.machine import SimpleMachineList
from aquilon.aqdb.model import Machine

class CommandShowMachineAll(BrokerCommand):

    def render(self, session, **arguments):
        q = session.query(Machine.label)
        q = q.order_by(Machine.label)
        return SimpleMachineList(q.all())


text:
package org.pm4j.common.crud;

/**
 * Interface for common CRUD scenarios.
 *
 * @param <T>
 *            Type of the handled entities.
 * @param <T_ID>
 *            Type of the entity identifier.
 *
 * @author Olaf Boede
 */
public interface CrudService<T, T_ID> {

    /**
     * Persists a new or updated entity.
     *
     * @param entity
     *            The entity to save.
     * @return The saved entity.
     */
    T save(T entity);

    /**
     * Deletes the given entity.
     *
     * @param entity
     *            The entity to delete.
     */
    void delete(T entity);

    /**
     * Finds an entity by ID.
     *
     * @param id
     *            ID of the instance to find.
     * @return The found instance or null.
     */
    T findById(T_ID id);

}