text:
.class Lcom/android/server/notification/NotificationManagerService$10;
.super Ljava/lang/Object;
.source "NotificationManagerService.java"

# interfaces
.implements Ljava/lang/Runnable;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/server/notification/NotificationManagerService;->cancelNotification(IILjava/lang/String;Ljava/lang/String;IIIZIILcom/android/server/notification/ManagedServices$ManagedServiceInfo;)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/server/notification/NotificationManagerService;

.field final synthetic val$callingPid:I

.field final synthetic val$callingUid:I

.field final synthetic val$id:I

.field final synthetic val$listener:Lcom/android/server/notification/ManagedServices$ManagedServiceInfo;

.field final synthetic val$mustHaveFlags:I

.field final synthetic val$mustNotHaveFlags:I

.field final synthetic val$pkg:Ljava/lang/String;

.field final synthetic val$reason:I

.field final synthetic val$sendDelete:Z

.field final synthetic val$tag:Ljava/lang/String;

.field final synthetic val$userId:I

# direct methods
.method constructor <init>(Lcom/android/server/notification/NotificationManagerService;Lcom/android/server/notification/ManagedServices$ManagedServiceInfo;IILjava/lang/String;ILjava/lang/String;IIIIZ)V
    .locals 0

    .prologue
    .line 2743
    iput-object p1, p0, Lcom/android/server/notification/NotificationManagerService$10;->this$0:Lcom/android/server/notification/NotificationManagerService;

    iput-object p2, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$listener:Lcom/android/server/notification/ManagedServices$ManagedServiceInfo;

    iput p3, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$callingUid:I

    iput p4, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$callingPid:I

    iput-object p5, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$pkg:Ljava/lang/String;

    iput p6, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$id:I

    iput-object p7, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$tag:Ljava/lang/String;

    iput p8, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$userId:I

    iput p9, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$mustHaveFlags:I

    iput p10, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$mustNotHaveFlags:I

    iput p11, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$reason:I

    iput-boolean p12, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$sendDelete:Z

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

    return-void
.end method

# virtual methods
.method public run()V
    .locals 12

    .prologue
    .line 2746
    iget-object v0, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$listener:Lcom/android/server/notification/ManagedServices$ManagedServiceInfo;

    if-nez v0, :cond_1

    const/4 v9, 0x0

    .line 2747
    .local v9, "listenerName":Ljava/lang/String;
    :goto_0
    iget v0, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$callingUid:I

    iget v1, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$callingPid:I

    iget-object v2, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$pkg:Ljava/lang/String;

    iget v3, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$id:I

    iget-object v4, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$tag:Ljava/lang/String;

    iget v5, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$userId:I

    iget v6, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$mustHaveFlags:I

    iget v7, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$mustNotHaveFlags:I

    iget v8, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$reason:I

    invoke-static/range {v0 .. v9}, Lcom/android/server/EventLogTags;->writeNotificationCancel(IILjava/lang/String;ILjava/lang/String;IIIILjava/lang/String;)V

    .line 2750
    iget-object v0, p0, Lcom/android/server/notification/NotificationManagerService$10;->this$0:Lcom/android/server/notification/NotificationManagerService;

    iget-object v1, v0, Lcom/android/server/notification/NotificationManagerService;->mNotificationList:Ljava/util/ArrayList;

    monitor-enter v1

    .line 2751
    :try_start_0
    iget-object v0, p0, Lcom/android/server/notification/NotificationManagerService$10;->this$0:Lcom/android/server/notification/NotificationManagerService;

    iget-object v2, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$pkg:Ljava/lang/String;

    iget-object v3, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$tag:Ljava/lang/String;

    iget v4, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$id:I

    iget v5, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$userId:I

    invoke-virtual {v0, v2, v3, v4, v5}, Lcom/android/server/notification/NotificationManagerService;->indexOfNotificationLocked(Ljava/lang/String;Ljava/lang/String;II)I

    move-result v11

    .line 2752
    .local v11, "index":I
    if-ltz v11, :cond_4

    .line 2753
    iget-object v0, p0, Lcom/android/server/notification/NotificationManagerService$10;->this$0:Lcom/android/server/notification/NotificationManagerService;

    iget-object v0, v0, Lcom/android/server/notification/NotificationManagerService;->mNotificationList:Ljava/util/ArrayList;

    invoke-virtual {v0, v11}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;

    move-result-object v6

    check-cast v6, Lcom/android/server/notification/NotificationRecord;

    .line 2757
    .local v6, "r":Lcom/android/server/notification/NotificationRecord;
    iget v0, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$reason:I

    const/4 v2, 0x1

    if-ne v0, v2, :cond_0

    .line 2758
    iget-object v0, p0, Lcom/android/server/notification/NotificationManagerService$10;->this$0:Lcom/android/server/notification/NotificationManagerService;

    # getter for: Lcom/android/server/notification/NotificationManagerService;->mUsageStats:Lcom/android/server/notification/NotificationUsageStats;
    invoke-static {v0}, Lcom/android/server/notification/NotificationManagerService;->access$4100(Lcom/android/server/notification/NotificationManagerService;)Lcom/android/server/notification/NotificationUsageStats;

    move-result-object v0

    invoke-virtual {v0, v6}, Lcom/android/server/notification/NotificationUsageStats;->registerClickedByUser(Lcom/android/server/notification/NotificationRecord;)V

    .line 2761
    :cond_0
    invoke-virtual {v6}, Lcom/android/server/notification/NotificationRecord;->getNotification()Landroid/app/Notification;

    move-result-object v0

    iget v0, v0, Landroid/app/Notification;->flags:I

    iget v2, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$mustHaveFlags:I

    and-int/2addr v0, v2

    iget v2, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$mustHaveFlags:I

    if-eq v0, v2, :cond_2

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

    .line 2776
    .end local v6    # "r":Lcom/android/server/notification/NotificationRecord;
    :goto_1
    return-void

    .line 2746
    .end local v9    # "listenerName":Ljava/lang/String;
    .end local v11    # "index":I
    :cond_1
    iget-object v0, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$listener:Lcom/android/server/notification/ManagedServices$ManagedServiceInfo;

    iget-object v0, v0, Lcom/android/server/notification/ManagedServices$ManagedServiceInfo;->component:Landroid/content/ComponentName;

    invoke-virtual {v0}, Landroid/content/ComponentName;->toShortString()Ljava/lang/String;

    move-result-object v9

    goto :goto_0

    .line 2764
    .restart local v6    # "r":Lcom/android/server/notification/NotificationRecord;
    .restart local v9    # "listenerName":Ljava/lang/String;
    .restart local v11    # "index":I
    :cond_2
    :try_start_1
    invoke-virtual {v6}, Lcom/android/server/notification/NotificationRecord;->getNotification()Landroid/app/Notification;

    move-result-object v0

    iget v0, v0, Landroid/app/Notification;->flags:I

    iget v2, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$mustNotHaveFlags:I

    and-int/2addr v0, v2

    if-eqz v0, :cond_3

    .line 2765
    monitor-exit v1

    goto :goto_1

    .line 2775
    .end local v6    # "r":Lcom/android/server/notification/NotificationRecord;
    .end local v11    # "index":I
    :catchall_0
    move-exception v0

    monitor-exit v1
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_0

    throw v0

    .line 2768
    .restart local v6    # "r":Lcom/android/server/notification/NotificationRecord;
    .restart local v11    # "index":I
    :cond_3
    :try_start_2
    iget-object v0, p0, Lcom/android/server/notification/NotificationManagerService$10;->this$0:Lcom/android/server/notification/NotificationManagerService;

    iget-object v0, v0, Lcom/android/server/notification/NotificationManagerService;->mNotificationList:Ljava/util/ArrayList;

    invoke-virtual {v0, v11}, Ljava/util/ArrayList;->remove(I)Ljava/lang/Object;

    .line 2770
    iget-object v0, p0, Lcom/android/server/notification/NotificationManagerService$10;->this$0:Lcom/android/server/notification/NotificationManagerService;

    iget-boolean v2, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$sendDelete:Z

    iget v3, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$reason:I

    # invokes: Lcom/android/server/notification/NotificationManagerService;->cancelNotificationLocked(Lcom/android/server/notification/NotificationRecord;ZI)V
    invoke-static {v0, v6, v2, v3}, Lcom/android/server/notification/NotificationManagerService;->access$3500(Lcom/android/server/notification/NotificationManagerService;Lcom/android/server/notification/NotificationRecord;ZI)V

    .line 2771
    iget-object v5, p0, Lcom/android/server/notification/NotificationManagerService$10;->this$0:Lcom/android/server/notification/NotificationManagerService;

    iget v7, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$callingUid:I

    iget v8, p0, Lcom/android/server/notification/NotificationManagerService$10;->val$callingPid:I

    const/16 v10, 0xc

    # invokes: Lcom/android/server/notification/NotificationManagerService;->cancelGroupChildrenLocked(Lcom/android/server/notification/NotificationRecord;IILjava/lang/String;I)V
    invoke-static/range {v5 .. v10}, Lcom/android/server/notification/NotificationManagerService;->access$5100(Lcom/android/server/notification/NotificationManagerService;Lcom/android/server/notification/NotificationRecord;IILjava/lang/String;I)V

    .line 2773
    iget-object v0, p0, Lcom/android/server/notification/NotificationManagerService$10;->this$0:Lcom/android/server/notification/NotificationManagerService;

    invoke-virtual {v0}, Lcom/android/server/notification/NotificationManagerService;->updateLightsLocked()V

    .line 2775
    .end local v6    # "r":Lcom/android/server/notification/NotificationRecord;
    :cond_4
    monitor-exit v1
    :try_end_2
    .catchall {:try_start_2 .. :try_end_2} :catchall_0

    goto :goto_1
.end method


text:
#include "JniOcRDClient.h"
#include "JniUtils.h"
#include "JniOcResourceHandle.h"

#include "RDClient.h"

void RemoveOnPublishResourceListener(JNIEnv* env, jobject jListener)
{
    if (!env)
    {
        LOGE("env is null");
        return;
    }

    publishResourceListenerMapLock.lock();
    bool isFound = false;
    for (auto it = onPublishResourceListenerMap.begin(); it != onPublishResourceListenerMap.end(); ++it)
    {
        if (env->IsSameObject(jListener, it->first))
        {
            auto refPair = it->second;
            if (refPair.second > 1)
            {
                refPair.second--;
                it->second = refPair;
                onPublishResourceListenerMap.insert(*it);
                LOGI("onPublishResourceListener: ref. count decremented");
            }
            else
            {
                env->DeleteGlobalRef(it->first);
                JniOnPublishResourceListener* listener = refPair.first;
                delete listener;
                onPublishResourceListenerMap.erase(it);
                LOGI("onPublishResourceListener is removed");
            }
            isFound = true;
            break;
        }
    }
    if (!isFound)
    {
        ThrowOcException(JNI_EXCEPTION, "onPublishResourceListener not found");
    }
    publishResourceListenerMapLock.unlock();
}

JniOnPublishResourceListener* AddOnPublishResourceListener(JNIEnv* env, jobject jListener)
{
    if (!env)
    {
        LOGD("env is null");
        return nullptr;
    }

    JniOnPublishResourceListener *onPublishResourceListener = nullptr;

    publishResourceListenerMapLock.lock();

    for (auto it = onPublishResourceListenerMap.begin(); it !=
            onPublishResourceListenerMap.end(); ++it)
    {
        if (env->IsSameObject(jListener, it->first))
        {
            auto refPair = it->second;
            onPublishResourceListener = refPair.first;
            refPair.second++;
            it->second = refPair;
            onPublishResourceListenerMap.insert(*it);
            LOGD("onPublishResourceListener: ref. count incremented");
            break;
        }
    }
    if (!onPublishResourceListener)
    {
        onPublishResourceListener = new JniOnPublishResourceListener(env, jListener,
                RemoveOnPublishResourceListener);

        jobject jgListener = env->NewGlobalRef(jListener);
        onPublishResourceListenerMap.insert(
                std::pair<jobject, std::pair<JniOnPublishResourceListener*, int>>(
                    jgListener,
                    std::pair<JniOnPublishResourceListener*, int>(onPublishResourceListener, 1)));
        LOGI("onPublishResourceListener: new listener");
    }
    publishResourceListenerMapLock.unlock();
    return onPublishResourceListener;
}

void RemoveOnDeleteResourceListener(JNIEnv* env, jobject jListener)
{
    if (!env)
    {
        LOGE("env is null");
        return;
    }

    deleteResourceListenerMapLock.lock();
    bool isFound = false;
    for (auto it = onDeleteResourceListenerMap.begin(); it !=
            onDeleteResourceListenerMap.end(); ++it)
    {
        if (env->IsSameObject(jListener, it->first))
        {
            auto refPair = it->second;
            if (refPair.second > 1)
            {
                refPair.second--;
                it->second = refPair;
                onDeleteResourceListenerMap.insert(*it);
                LOGI("onDeleteResourceListener: ref. count decremented");
            }
            else
            {
                env->DeleteGlobalRef(it->first);
                JniOnDeleteResourceListener* listener = refPair.first;
                delete listener;
                onDeleteResourceListenerMap.erase(it);
                LOGI("onDeleteResourceListener is removed");
            }
            isFound = true;
            break;
        }
    }
    if (!isFound)
    {
        ThrowOcException(JNI_EXCEPTION, "onDeleteResourceListener not found");
    }
    deleteResourceListenerMapLock.unlock();
}

JniOnDeleteResourceListener* AddOnDeleteResourceListener(JNIEnv* env, jobject jListener)
{
    if (!env)
    {
        LOGD("env is null");
        return nullptr;
    }

    JniOnDeleteResourceListener *onDeleteResourceListener = nullptr;

    deleteResourceListenerMapLock.lock();

    for (auto it = onDeleteResourceListenerMap.begin(); it !=
            onDeleteResourceListenerMap.end(); ++it)
    {
        if (env->IsSameObject(jListener, it->first))
        {
            auto refPair = it->second;
            onDeleteResourceListener = refPair.first;
            refPair.second++;
            it->second = refPair;
            onDeleteResourceListenerMap.insert(*it);
            LOGD("onDeleteResourceListener: ref. count incremented");
            break;
        }
    }
    if (!onDeleteResourceListener)
    {
        onDeleteResourceListener = new JniOnDeleteResourceListener(env, jListener,
                RemoveOnDeleteResourceListener);
        jobject jgListener = env->NewGlobalRef(jListener);
        onDeleteResourceListenerMap.insert(
                std::pair<jobject, std::pair<JniOnDeleteResourceListener*, int>>(
                    jgListener,
                    std::pair<JniOnDeleteResourceListener*, int>(onDeleteResourceListener, 1)));
        LOGI("onDeleteResourceListener: new listener");
    }
    deleteResourceListenerMapLock.unlock();
    return onDeleteResourceListener;
}

/*
 * Class:     org_iotivity_base_OcRDClient
 * Method:    publishResourceToRD0
 * Signature: (Ljava/lang/String;ILorg/iotivity/base/OcRDClient/OnPublishResourceListener;I)V
 */
JNIEXPORT void JNICALL Java_org_iotivity_base_OcRDClient_publishResourceToRD0(
        JNIEnv *env,
        jclass clazz,
        jstring jHost,
        jint jConnectivityType,
        jobject jListener,
        jint jQoS)
{
    OC_UNUSED(clazz);
    LOGD("OcRDClient_publishResourceToRD");
#ifdef RD_CLIENT
    std::string host;
    if (jHost)
    {
        host = env->GetStringUTFChars(jHost, nullptr);
    }
    if (!jListener)
    {
        ThrowOcException(OC_STACK_INVALID_PARAM, "onPublishResourceListener cannot be null");
        return;
    }
    JniOnPublishResourceListener *onPubResListener = AddOnPublishResourceListener(env, jListener);

    PublishResourceCallback pubResCallback = [onPubResListener](
            const OCRepresentation& ocRepresentation,
            const int eCode)
    {
        onPubResListener->onPublishResourceCallback(ocRepresentation, eCode);
    };

    try
    {
        OCStackResult result = RDClient::Instance().publishResourceToRD(
            host,
            static_cast<OCConnectivityType>(jConnectivityType),
            pubResCallback,
            JniUtils::getQOS(env, static_cast<int>(jQoS)));

        if (OC_STACK_OK != result)
        {
            ThrowOcException(result, "Publish resource has failed");
            return;
        }
    }
    catch (OCException& e)
    {
        LOGE("%s", e.reason().c_str());
        ThrowOcException(e.code(), e.reason().c_str());
    }
#else
    OC_UNUSED(env);
    OC_UNUSED(clazz);
    OC_UNUSED(jHost)
    OC_UNUSED(jConnectivityType);
    OC_UNUSED(jListener);
    OC_UNUSED(jQoS);
    ThrowOcException(JNI_NO_SUPPORT, "Not supported");
    return;
#endif
}

/*
 * Class:     org_iotivity_base_OcRDClient
 * Method:    publishResourceToRD1
 * Signature: (Ljava/lang/String;I[Lorg/iotivity/base/OcResourceHandle;Lorg/iotivity/base/OcRDClient/OnPublishResourceListener;I)V
 */
JNIEXPORT void JNICALL Java_org_iotivity_base_OcRDClient_publishResourceToRD1(
        JNIEnv *env,
        jclass clazz,
        jstring jHost,
        jint jConnectivityType,
        jobjectArray jResourceHandleArray,
        jobject jListener,
        jint jQoS)
{
    OC_UNUSED(clazz);
    LOGD("OcRDClient_publishResourceToRD");
#ifdef RD_CLIENT
    if (!env)
    {
        LOGE("env is null");
        return;
    }
    std::string host;
    if (jHost)
    {
        host = env->GetStringUTFChars(jHost, nullptr);
    }
    if (!jListener)
    {
        ThrowOcException(OC_STACK_INVALID_PARAM, "onPublishResourceListener cannot be null");
        return;
    }
    if (!jResourceHandleArray)
    {
        ThrowOcException(OC_STACK_INVALID_PARAM, "resourceHandleList cannot be null");
        return;
    }
    JniOnPublishResourceListener *onPubResListener = AddOnPublishResourceListener(env, jListener);

    PublishResourceCallback pubResCallback = [onPubResListener](
            const OCRepresentation& ocRepresentation,
            const int eCode)
    {
        onPubResListener->onPublishResourceCallback(ocRepresentation, eCode);
    };

    std::vector<OCResourceHandle> resourceHandleList;
    jsize len = env->GetArrayLength(jResourceHandleArray);
    for (jsize i = 0; i < len; ++i)
    {
        jobject jResourceHandle = env->GetObjectArrayElement(jResourceHandleArray, i);
        if (!jResourceHandle)
        {
            ThrowOcException(JNI_EXCEPTION, "resource handle cannot be null");
            return;
        }
        JniOcResourceHandle* jniOcResourceHandle =
            JniOcResourceHandle::getJniOcResourceHandlePtr(env, jResourceHandle);
        if (!jniOcResourceHandle)
        {
            ThrowOcException(OC_STACK_INVALID_PARAM, "resource handle is invalid");
            return;
        }

        resourceHandleList.push_back(jniOcResourceHandle->getOCResourceHandle());
    }

    try
    {
        OCStackResult result = RDClient::Instance().publishResourceToRD(
            host,
            static_cast<OCConnectivityType>(jConnectivityType),
            resourceHandleList,
            pubResCallback,
            JniUtils::getQOS(env, static_cast<int>(jQoS)));

        if (OC_STACK_OK != result)
        {
            ThrowOcException(result, "Publish resource has failed");
            return;
        }
    }
    catch (OCException& e)
    {
        LOGE("%s", e.reason().c_str());
        ThrowOcException(e.code(), e.reason().c_str());
    }
#else
    OC_UNUSED(env);
    OC_UNUSED(jHost);
    OC_UNUSED(jConnectivityType);
    OC_UNUSED(jResourceHandleArray);
    OC_UNUSED(jListener);
    OC_UNUSED(jQoS);
    ThrowOcException(JNI_NO_SUPPORT, "Not supported");
    return;
#endif
}

/*
 * Class:     org_iotivity_base_OcRDClient
 * Method:    deleteResourceFromRD0
 * Signature: (Ljava/lang/String;ILorg/iotivity/base/OcRDClient/OnDeleteResourceListener;I)V
 */
JNIEXPORT void JNICALL Java_org_iotivity_base_OcRDClient_deleteResourceFromRD0(
        JNIEnv *env,
        jclass clazz,
        jstring jHost,
        jint jConnectivityType,
        jobject jListener,
        jint jQoS)
{
    OC_UNUSED(clazz);
    LOGD("OcRDClient_deleteResourceFromRD");
#ifdef RD_CLIENT
    std::string host;
    if (jHost)
    {
        host = env->GetStringUTFChars(jHost, nullptr);
    }
    if (!jListener)
    {
        ThrowOcException(OC_STACK_INVALID_PARAM, "onDeleteResourceListener cannot be null");
        return;
    }
    JniOnDeleteResourceListener *onDelResListener = AddOnDeleteResourceListener(env, jListener);

    DeleteResourceCallback delResCallback = [onDelResListener](const int eCode)
    {
        onDelResListener->onDeleteResourceCallback(eCode);
    };
    try
     {
         OCStackResult result = RDClient::Instance().deleteResourceFromRD(
             host,
             static_cast<OCConnectivityType>(jConnectivityType),
             delResCallback,
             JniUtils::getQOS(env, static_cast<int>(jQoS)));

         if (OC_STACK_OK != result)
         {
             ThrowOcException(result, "Delete resource has failed");
             return;
         }
     }
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
         ThrowOcException(e.code(), e.reason().c_str());
     }
 #else
     OC_UNUSED(env);
     OC_UNUSED(clazz);
     OC_UNUSED(jHost);
     OC_UNUSED(jConnectivityType);
     OC_UNUSED(jListener);
     OC_UNUSED(jQoS);
     ThrowOcException(JNI_NO_SUPPORT, "Not supported");
     return;
 #endif
 }

 /*
  * Class:     org_iotivity_base_OcRDClient
  * Method:    deleteResourceFromRD1
  * Signature: (Ljava/lang/String;I[Lorg/iotivity/base/OcResourceHandle;Lorg/iotivity/base/OcRDClient/OnDeleteResourceListener;I)V
  */
 JNIEXPORT void JNICALL Java_org_iotivity_base_OcRDClient_deleteResourceFromRD1(
         JNIEnv *env,
         jclass clazz,
         jstring jHost,
         jint jConnectivityType,
         jobjectArray jResourceHandleArray,
         jobject jListener,
         jint jQoS)
 {
     OC_UNUSED(clazz);
     LOGD("OcRDClient_deleteResourceFromRD");
 #ifdef RD_CLIENT
     if (!env)
     {
         LOGE("env is null");
         return;
     }
     std::string host;
     if (jHost)
     {
         host = env->GetStringUTFChars(jHost, nullptr);
     }
     if (!jListener)
     {
         ThrowOcException(OC_STACK_INVALID_PARAM, "onDeleteResourceListener cannot be null");
         return;
     }
     if (!jResourceHandleArray)
     {
         ThrowOcException(OC_STACK_INVALID_PARAM, "resourceHandleList cannot be null");
         return;
     }
     JniOnDeleteResourceListener *onDelResListener = AddOnDeleteResourceListener(env, jListener);

     DeleteResourceCallback delResCallback = [onDelResListener](const int eCode)
     {
         onDelResListener->onDeleteResourceCallback(eCode);
     };

     std::vector<OCResourceHandle> resourceHandleList;
     jsize len = env->GetArrayLength(jResourceHandleArray);
     for (jsize i = 0; i < len; ++i)
     {
         jobject jResourceHandle = env->GetObjectArrayElement(jResourceHandleArray, i);
         if (!jResourceHandle)
         {
             ThrowOcException(JNI_EXCEPTION, "resource handle cannot be null");
             return;
         }

         JniOcResourceHandle* jniOcResourceHandle =
             JniOcResourceHandle::getJniOcResourceHandlePtr(env, jResourceHandle);
         if (!jniOcResourceHandle)
         {
             ThrowOcException(OC_STACK_INVALID_PARAM, "resource handle is invalid");
             return;
         }

         resourceHandleList.push_back(jniOcResourceHandle->getOCResourceHandle());
     }

     try
     {
         OCStackResult result = RDClient::Instance().deleteResourceFromRD(
             host,
             static_cast<OCConnectivityType>(jConnectivityType),
             resourceHandleList,
             delResCallback,
             JniUtils::getQOS(env, static_cast<int>(jQoS)));

         if (OC_STACK_OK != result)
         {
             ThrowOcException(result, "Delete resource has failed");
             return;
         }
     }
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
         ThrowOcException(e.code(), e.reason().c_str());
     }
 #else
     OC_UNUSED(env);
     OC_UNUSED(jHos);
     OC_UNUSED(jConnectivityType);
     OC_UNUSED(jResourceHandleArray);
     OC_UNUSED(jListener);
     OC_UNUSED(jQoS);
     ThrowOcException(JNI_NO_SUPPORT, "Not supported");
     return;
 #endif
 }

redpajama_set_name: RedPajamaGithub


text:
import unittest
from unittest.mock import Mock, patch

from opentelemetry import context, trace
from opentelemetry.test.concurrency_test import ConcurrencyTestBase, MockFunc
from opentelemetry.test.globals_test import TraceGlobalsTest
from opentelemetry.trace.status import Status, StatusCode

class TestSpan(trace.NonRecordingSpan):
    has_ended = False
    recorded_exception = None
    recorded_status = Status(status_code=StatusCode.UNSET)

    def set_status(self, status, description=None):
        self.recorded_status = status

    def end(self, end_time=None):
        self.has_ended = True

    def is_recording(self):
        return not self.has_ended

    def record_exception(
        self, exception, attributes=None, timestamp=None, escaped=False
    ):
        self.recorded_exception = exception

class TestGlobals(TraceGlobalsTest, unittest.TestCase):
    @staticmethod
    @patch("opentelemetry.trace._TRACER_PROVIDER")
    def test_get_tracer(mock_tracer_provider):  # type: ignore
        """trace.get_tracer should proxy to the global tracer provider."""
        trace.get_tracer("foo", "var")
        mock_tracer_provider.get_tracer.assert_called_with("foo", "var", None)
        mock_provider = Mock()
        trace.get_tracer("foo", "var", mock_provider)
        mock_provider.get_tracer.assert_called_with("foo", "var", None)

class TestGlobalsConcurrency(TraceGlobalsTest, ConcurrencyTestBase):
    @patch("opentelemetry.trace.logger")
    def test_set_tracer_provider_many_threads(self, mock_logger) -> None:  # type: ignore
        mock_logger.warning = MockFunc()

        def do_concurrently() -> Mock:
            # first get a proxy tracer
            proxy_tracer = trace.ProxyTracerProvider().get_tracer("foo")

            # try to set the global tracer provider
            mock_tracer_provider = Mock(get_tracer=MockFunc())
            trace.set_tracer_provider(mock_tracer_provider)

            # start a span through the proxy which will call through to the mock provider
            proxy_tracer.start_span("foo")

            return mock_tracer_provider

        num_threads = 100
        mock_tracer_providers = self.run_with_many_threads(
            do_concurrently,
            num_threads=num_threads,
        )

        # despite trying to set tracer provider many times, only one of the
        # mock_tracer_providers should have stuck and been called from
        # proxy_tracer.start_span()
        mock_tps_with_any_call = [
            mock
            for mock in mock_tracer_providers
            if mock.get_tracer.call_count > 0
        ]

        self.assertEqual(len(mock_tps_with_any_call), 1)
        self.assertEqual(
            mock_tps_with_any_call[0].get_tracer.call_count, num_threads
        )

        # should have warned every time except for the successful set
        self.assertEqual(mock_logger.warning.call_count, num_threads - 1)

class TestTracer(unittest.TestCase):
    def setUp(self):
        self.tracer = trace.NoOpTracer()

    def test_get_current_span(self):
        """NoOpTracer's start_span will also
        be retrievable via get_current_span
        """
        self.assertEqual(trace.get_current_span(), trace.INVALID_SPAN)
        span = trace.NonRecordingSpan(trace.INVALID_SPAN_CONTEXT)
        ctx = trace.set_span_in_context(span)
        token = context.attach(ctx)
        try:
            self.assertIs(trace.get_current_span(), span)
        finally:
            context.detach(token)
        self.assertEqual(trace.get_current_span(), trace.INVALID_SPAN)

class TestUseTracer(unittest.TestCase):
    def test_use_span(self):
        self.assertEqual(trace.get_current_span(), trace.INVALID_SPAN)
        span = trace.NonRecordingSpan(trace.INVALID_SPAN_CONTEXT)
        with trace.use_span(span):
            self.assertIs(trace.get_current_span(), span)
        self.assertEqual(trace.get_current_span(), trace.INVALID_SPAN)

    def test_use_span_end_on_exit(self):

        test_span = TestSpan(trace.INVALID_SPAN_CONTEXT)

        with trace.use_span(test_span):
            pass
        self.assertFalse(test_span.has_ended)

        with trace.use_span(test_span, end_on_exit=True):
            pass
        self.assertTrue(test_span.has_ended)

    def test_use_span_exception(self):
        class TestUseSpanException(Exception):
            pass

        test_span = TestSpan(trace.INVALID_SPAN_CONTEXT)
        exception = TestUseSpanException("test exception")
        with self.assertRaises(TestUseSpanException):
            with trace.use_span(test_span):
                raise exception

        self.assertEqual(test_span.recorded_exception, exception)

    def test_use_span_set_status(self):
        class TestUseSpanException(Exception):
            pass

        test_span = TestSpan(trace.INVALID_SPAN_CONTEXT)
        with self.assertRaises(TestUseSpanException):
            with trace.use_span(test_span):
                raise TestUseSpanException("test error")

        self.assertEqual(
            test_span.recorded_status.status_code, StatusCode.ERROR
        )
        self.assertEqual(
            test_span.recorded_status.description,
            "TestUseSpanException: test error",
        )


text:
/**
 * @include GeoExt/widgets/MapPanel.js
 * @require OpenLayers/Feature/Vector.js
 * @require OpenLayers/Geometry.js
 * @require OpenLayers/BaseTypes/Pixel.js
 */

/** api: (define)
 *  module = GeoExt
 *  class = Popup
 *  base_link = `Ext.Window <http://dev.sencha.com/deploy/dev/docs/?class=Ext.Window>`_
 */
Ext.namespace("GeoExt");

/** api: example
 *  Sample code to create a popup anchored to a feature:
 *
 *  .. code-block:: javascript
 *
 *      var popup = new GeoExt.Popup({
 *          title: "My Popup",
 *          location: feature,
 *          width: 200,
 *          html: "
Popup content
",
 *          collapsible: true
 *      });
 */

/** api: constructor
 *  .. class:: Popup(config)
 *
 *      Popups are a specialized Window that supports anchoring
 *      to a particular location in a MapPanel.  When a popup
 *      is anchored to a location, that means that the popup
 *      will visibly point to the location on the map, and move
 *      accordingly when the map is panned or zoomed.
 */
GeoExt.Popup = Ext.extend(Ext.Window, {

    /** api: config[anchored]
     *  ``Boolean``  The popup begins anchored to its location.  Default is
     *  ``true``.
     */
    anchored: true,

    /** api: config[map]
     *  ``OpenLayers.Map`` or :class:`GeoExt.MapPanel`
     *  The map this popup will be anchored to (only required if ``anchored``
     *  is set to true and the map cannot be derived from the ``location``'s
     *  layer.
     */
    map: null,

    /** api: config[panIn]
     *  ``Boolean`` The popup should pan the map so that the popup is
     *  fully in view when it is rendered.  Default is ``true``.
     */
    panIn: true,

    /** api: config[unpinnable]
     *  ``Boolean`` The popup should have a "unpin" tool that unanchors it from
     *  its location.  Default is ``true``.
     */
    unpinnable: true,

    /** api: config[location]
     *  ``OpenLayers.Feature.Vector`` or ``OpenLayers.LonLat`` or
     *  ``OpenLayers.Pixel`` or ``OpenLayers.Geometry`` A location for this
     *  popup's anchor.
     */

    /** private: property[location]
     *  ``OpenLayers.LonLat``
     */
    location: null,

    /** private: property[insideViewport]
     *  ``Boolean`` Wether the popup is currently inside the map viewport.
     */
    insideViewport: null,

    /**
     * Some Ext.Window defaults need to be overriden here
     * because some Ext.Window behavior is not currently supported.
     */

    /** private: config[animCollapse]
     *  ``Boolean`` Animate the transition when the panel is collapsed.
     *  Default is ``false``.  Collapsing animation is not supported yet for
     *  popups.
     */
    animCollapse: false,

    /** private: config[draggable]
     *  ``Boolean`` Enable dragging of this Panel.  Defaults to ``false``
     *  because the popup defaults to being anchored, and anchored popups
     *  should not be draggable.
     */
    draggable: false,

    /** private: config[shadow]
     *  ``Boolean`` Give the popup window a shadow.  Defaults to ``false``
     *  because shadows are not supported yet for popups (the shadow does
     *  not look good with the anchor).
     */
    shadow: false,

    /** api: config[popupCls]
     *  ``String`` CSS class name for the popup DOM elements.  Default is
     *  "gx-popup".
     */
    popupCls: "gx-popup",

    /** api: config[ancCls]
     *  ``String``  CSS class name for the popup's anchor.
     */
    ancCls: null,

    /** api: config[anchorPosition]
     *  ``String``  Controls the anchor position for the popup. If set to
     *  ``auto``, the anchor will be positioned on the top or the bottom of
     *  the window, minimizing map movement. Supported values are ``bottom-left``,
     *  ``bottom-right``, ``top-left``, ``top-right`` or ``auto``.
     *  Defaults to ``auto``.
     */
    anchorPosition: "auto",

    /** private: method[initComponent]
     *  Initializes the popup.
     */
    initComponent: function() {
        if(this.map instanceof GeoExt.MapPanel) {
            this.map = this.map.map;
        }
        if(!this.map && this.location instanceof OpenLayers.Feature.Vector &&
                                                        this.location.layer) {
            this.map = this.location.layer.map;
        }
        if (this.location instanceof OpenLayers.Feature.Vector) {
            this.location = this.location.geometry;
        }
        if (this.location instanceof OpenLayers.Geometry) {
            if (typeof this.location.getCentroid == "function") {
                this.location = this.location.getCentroid();
            }
            this.location = this.location.getBounds().getCenterLonLat();
        } else if (this.location instanceof OpenLayers.Pixel) {
            this.location = this.map.getLonLatFromViewPortPx(this.location);
        }
        if (!(this.location instanceof OpenLayers.LonLat)) {
            this.anchored = false;
        }

        var mapExtent =  this.map.getExtent();
        if (mapExtent && this.location) {
            this.insideViewport = mapExtent.containsLonLat(this.location);
        }

        if(this.anchored) {
            this.addAnchorEvents();
            this.elements += ',anc';
        } else {
            this.unpinnable = false;
        }

        this.baseCls = this.popupCls + " " + this.baseCls;

        GeoExt.Popup.superclass.initComponent.call(this);
    },

    /** private: method[onRender]
     *  Executes when the popup is rendered.
     */
    onRender: function(ct, position) {
        GeoExt.Popup.superclass.onRender.call(this, ct, position);
        if (this.anchored) {
            this.ancCls = this.popupCls + "-anc";
            //create anchor dom element.
            this.createElement("anc", this.el.dom);
        } else {
            this.makeDraggable();
        }
    },

    /** private: method[initTools]
     *  Initializes the tools on the popup.  In particular,
     *  it adds the 'unpin' tool if the popup is unpinnable.
     */
    initTools : function() {
        if(this.unpinnable) {
            this.addTool({
                id: 'unpin',
                handler: this.unanchorPopup.createDelegate(this, [])
            });
        }

        GeoExt.Popup.superclass.initTools.call(this);
    },

    /** private: method[show]
     *  Override.
     */
    show: function() {
        GeoExt.Popup.superclass.show.apply(this, arguments);
        if(this.anchored) {
            this.position();
            if(this.panIn && !this._mapMove) {
                this.panIntoView();
            }
        }
    },

    /** private: method[maximize]
     *  Override.
     */
    maximize: function() {
        if(!this.maximized && this.anc) {
            this.unanchorPopup();
        }
        GeoExt.Popup.superclass.maximize.apply(this, arguments);
    },

    /** api: method[setSize]
     *  :param w: ``Integer``
     *  :param h: ``Integer``
     *
     *  Sets the size of the popup, taking into account the size of the anchor.
     */
    setSize: function(w, h) {
        if(this.anc) {
            var ancSize = this.anc.getSize();
            if(typeof w == 'object') {
                h = w.height - ancSize.height;
                w = w.width;
            } else if(!isNaN(h)){
                h = h - ancSize.height;
            }
        }
        GeoExt.Popup.superclass.setSize.call(this, w, h);
    },

    /** private: method[position]
     *  Positions the popup relative to its location
     */
    position: function() {
        var me = this;
        if(me._mapMove === true) {
            me.insideViewport = me.map.getExtent().containsLonLat(me.location);
            if(me.insideViewport !== me.isVisible()) {
                me.setVisible(me.insideViewport);
            }
        }

        if(me.isVisible()) {
            var locationPx = me.map.getPixelFromLonLat(me.location),
                mapBox = Ext.fly(me.map.div).getBox(true),
                y = locationPx.y + mapBox.y,
                x = locationPx.x + mapBox.x,
                elSize = me.el.getSize(),
                ancSize = me.anc.getSize(),
                ancPos = me.anchorPosition;
            if (ancPos.indexOf("right") > -1 || locationPx.x > mapBox.width / 2) {
                // right
                me.anc.addClass("right");
                var ancRight = me.el.getX(true) + elSize.width -
                               me.anc.getX(true) - ancSize.width;
                x -= elSize.width - ancRight - ancSize.width / 2;
            } else {
                // left
                me.anc.removeClass("right");
                var ancX = me.anc.getLeft(true);
                x -= ancX + ancSize.width / 2;
            }

            if (ancPos.indexOf("bottom") > -1 || locationPx.y > mapBox.height / 2) {
                // bottom
                me.anc.removeClass("top");
                y -= elSize.height + ancSize.height;
            } else {
                // top
                me.anc.addClass("top");
                y += ancSize.height; // ok
            }

            // Needed to have the right position on the first display
            // (no flash on the center of the map).
            me.setPagePosition(x, y);
            // position in the next cycle - otherwise strange shifts can occur.
            window.setTimeout(function() {
                if (me.dom) {
                    me.setPagePosition(x, y);
                }
            }, 0);
        }
    },

    /** private: method[makeDraggable]
     *  Make the window draggable
     */
    makeDraggable: function() {
        this.draggable = true;
        this.header.addClass("x-window-draggable");
        this.dd = new Ext.Window.DD(this);
    },

    /** private: method[unanchorPopup]
     *  Unanchors a popup from its location.  This removes the popup from its
     *  MapPanel and adds it to the page body.
     */
    unanchorPopup: function() {
        this.removeAnchorEvents();

        this.makeDraggable();

        //remove anchor
        this.anc.remove();
        this.anc = null;

        //hide unpin tool
        this.tools.unpin.hide();
    },

    /** private: method[panIntoView]
     *  Pans the MapPanel's map so that an anchored popup can come entirely
     *  into view, with padding specified as per normal OpenLayers.Map popup
     *  padding.
     */
    panIntoView: function() {
        var mapBox = Ext.fly(this.map.div).getBox(true);

        //assumed viewport takes up whole body element of map panel
        var popupPos =  this.getPosition(true);
        popupPos[0] -= mapBox.x;
        popupPos[1] -= mapBox.y;

        var panelSize = [mapBox.width, mapBox.height]; // [X,Y]

        var popupSize = this.getSize();

        var newPos = [popupPos[0], popupPos[1]];

        //For now, using native OpenLayers popup padding.  This may not be ideal.
        var padding = this.map.paddingForPopups;

        // X
        if(popupPos[0] < padding.left) {
            newPos[0] = padding.left;
        } else if(popupPos[0] + popupSize.width > panelSize[0] - padding.right) {
            newPos[0] = panelSize[0] - padding.right - popupSize.width;
        }

        // Y
        if(popupPos[1] < padding.top) {
            newPos[1] = padding.top;
        } else if(popupPos[1] + popupSize.height > panelSize[1] - padding.bottom) {
            newPos[1] = panelSize[1] - padding.bottom - popupSize.height;
        }

        var dx = popupPos[0] - newPos[0];
        var dy = popupPos[1] - newPos[1];

        this.map.pan(dx, dy);
    },

    /** private: method[onMapMove]
     */
    onMapMove: function() {
        if (!(this.hidden && this.insideViewport)){
            this._mapMove = true;
            this.position();
            delete this._mapMove;
        }
    },

    /** private: method[addAnchorEvents]
     */
    addAnchorEvents: function() {
        this.map.events.on({
            "move" : this.onMapMove,
            scope : this
        });

        this.on({
            "resize": this.position,
            "collapse": this.position,
            "expand": this.position,
            scope: this
        });
    },

    /** private: method[removeAnchorEvents]
     */
    removeAnchorEvents: function() {
        //stop position with location
        this.map.events.un({
            "move" : this.onMapMove,
            scope : this
        });

        this.un("resize", this.position, this);
        this.un("collapse", this.position, this);
        this.un("expand", this.position, this);

    },

    /** private: method[beforeDestroy]
     *  Cleanup events before destroying the popup.
     */
    beforeDestroy: function() {
        if(this.anchored) {
            this.removeAnchorEvents();
        }
        GeoExt.Popup.superclass.beforeDestroy.call(this);
    }
});

/** api: xtype = gx_popup */
Ext.reg('gx_popup', GeoExt.Popup);


text:
function s = procid()
% Returns a string identifying the process.

% AUTORIGHTS
% -------------------------------------------------------
% Copyright (C) 2009-2012 Ross Girshick
%
% This file is part of the voc-releaseX code
% (http://people.cs.uchicago.edu/~rbg/latent/)
% and is available under the terms of an MIT-like license
% provided in COPYING. Please retain this notice and
% COPYING if you use this file (or a portion of it) in
% your project.
% -------------------------------------------------------

d = pwd();
i = strfind(d, '/');
d = d(i(end)+1:end);
s = d;


text:
require_relative 'element'

module Calco

  class Or < Element

    def initialize condition1, condition2

      super()

      @condition1, @condition2 = Constant.wrap(condition1), Constant.wrap(condition2)

    end

    def generate row

      condition1 = generate_operand(@condition1, row)
      condition2 = generate_operand(@condition2, row)

      "OR(#{condition1};#{condition2})"

    end

  end

end


text:
#ifndef __INC_MANIPULATIONS__
#define __INC_MANIPULATIONS__

typedef enum _MANIPULATION_PROCESSOR_MANIPULATIONS {
  MANIPULATION_NONE          = 0x00000000,
  MANIPULATION_TRANSLATE_X   = 0x00000001,
  MANIPULATION_TRANSLATE_Y   = 0x00000002,
  MANIPULATION_SCALE         = 0x00000004,
  MANIPULATION_ROTATE        = 0x00000008,
  MANIPULATION_ALL           = 0x0000000F
} MANIPULATION_PROCESSOR_MANIPULATIONS;

#endif /*__INC_MANIPULATIONS__*/


text:
/*************************************************************************/
/*  texture.h                                                            */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* 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.                */
/*************************************************************************/

#ifndef TEXTURE_H
#define TEXTURE_H

#include "core/io/resource_loader.h"
#include "core/math/rect2.h"
#include "core/os/mutex.h"
#include "core/os/rw_lock.h"
#include "core/os/thread_safe.h"
#include "core/resource.h"
#include "scene/resources/curve.h"
#include "scene/resources/gradient.h"
#include "servers/camera_server.h"
#include "servers/visual_server.h"

class Texture : public Resource {
	GDCLASS(Texture, Resource);
	OBJ_SAVE_TYPE(Texture); // Saves derived classes with common type so they can be interchanged.

protected:
	static void _bind_methods();

public:
	enum Flags {
		FLAG_MIPMAPS = VisualServer::TEXTURE_FLAG_MIPMAPS,
		FLAG_REPEAT = VisualServer::TEXTURE_FLAG_REPEAT,
		FLAG_FILTER = VisualServer::TEXTURE_FLAG_FILTER,
		FLAG_ANISOTROPIC_FILTER = VisualServer::TEXTURE_FLAG_ANISOTROPIC_FILTER,
		FLAG_CONVERT_TO_LINEAR = VisualServer::TEXTURE_FLAG_CONVERT_TO_LINEAR,
		FLAG_VIDEO_SURFACE = VisualServer::TEXTURE_FLAG_USED_FOR_STREAMING,
		FLAGS_DEFAULT = FLAG_MIPMAPS | FLAG_REPEAT | FLAG_FILTER,
		FLAG_MIRRORED_REPEAT = VisualServer::TEXTURE_FLAG_MIRRORED_REPEAT
	};

	virtual int get_width() const = 0;
	virtual int get_height() const = 0;
	virtual Size2 get_size() const;
	virtual RID get_rid() const = 0;

	virtual bool is_pixel_opaque(int p_x, int p_y) const;

	virtual bool has_alpha() const = 0;

	virtual void set_flags(uint32_t p_flags) = 0;
	virtual uint32_t get_flags() const = 0;

	virtual void draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false, const Ref<Texture> &p_normal_map = Ref<Texture>()) const;
	virtual void draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile = false, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false, const Ref<Texture> &p_normal_map = Ref<Texture>()) const;
	virtual void draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false, const Ref<Texture> &p_normal_map = Ref<Texture>(), bool p_clip_uv = true) const;
	virtual bool get_rect_region(const Rect2 &p_rect, const Rect2 &p_src_rect, Rect2 &r_rect, Rect2 &r_src_rect) const;

	virtual Ref<Image> get_data() const { return Ref<Image>(); }

	Texture();
};

VARIANT_ENUM_CAST(Texture::Flags);

class BitMap;

class ImageTexture : public Texture {
	GDCLASS(ImageTexture, Texture);
	RES_BASE_EXTENSION("tex");

public:
	enum Storage {
		STORAGE_RAW,
		STORAGE_COMPRESS_LOSSY,
		STORAGE_COMPRESS_LOSSLESS
	};

private:
	RID texture;
	Image::Format format;
	uint32_t flags;
	int w, h;
	Storage storage;
	Size2 size_override;
	float lossy_storage_quality;
	mutable Ref<BitMap> alpha_cache;
	bool image_stored;

protected:
	virtual void reload_from_file();

	bool _set(const StringName &p_name, const Variant &p_value);
	bool _get(const StringName &p_name, Variant &r_ret) const;
	void _get_property_list(List<PropertyInfo> *p_list) const;

	void _reload_hook(const RID &p_hook);
	virtual void _resource_path_changed();
	static void _bind_methods();

	void _set_data(Dictionary p_data);

public:
	void create(int p_width, int p_height, Image::Format p_format, uint32_t p_flags = FLAGS_DEFAULT);
	void create_from_image(const Ref<Image> &p_image, uint32_t p_flags = FLAGS_DEFAULT);

	void set_flags(uint32_t p_flags);
	uint32_t get_flags() const;
	Image::Format get_format() const;
#ifndef DISABLE_DEPRECATED
	Error load(const String &p_path);
#endif
	void set_data(const Ref<Image> &p_image);
	Ref<Image> get_data() const;

	int get_width() const;
	int get_height() const;

	virtual RID get_rid() const;

	bool has_alpha() const;
	virtual void draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false, const Ref<Texture> &p_normal_map = Ref<Texture>()) const;
	virtual void draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile = false, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false, const Ref<Texture> &p_normal_map = Ref<Texture>()) const;
	virtual void draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false, const Ref<Texture> &p_normal_map = Ref<Texture>(), bool p_clip_uv = true) const;
	void set_storage(Storage p_storage);
	Storage get_storage() const;

	bool is_pixel_opaque(int p_x, int p_y) const;

	void set_lossy_storage_quality(float p_lossy_storage_quality);
	float get_lossy_storage_quality() const;

	void set_size_override(const Size2 &p_size);

	virtual void set_path(const String &p_path, bool p_take_over = false);

	ImageTexture();
	~ImageTexture();
};

class StreamTexture : public Texture {
	GDCLASS(StreamTexture, Texture);

public:
	enum FormatBits {
		FORMAT_MASK_IMAGE_FORMAT = (1 << 20) - 1,
		FORMAT_BIT_PNG = 1 << 20,
		FORMAT_BIT_WEBP = 1 << 21,
		FORMAT_BIT_STREAM = 1 << 22,
		FORMAT_BIT_HAS_MIPMAPS = 1 << 23,
		FORMAT_BIT_DETECT_3D = 1 << 24,
		FORMAT_BIT_DETECT_SRGB = 1 << 25,
		FORMAT_BIT_DETECT_NORMAL = 1 << 26,
	};

private:
	Error _load_data(const String &p_path, int &tw, int &th, int &tw_custom, int &th_custom, int &flags, Ref<Image> &image, int p_size_limit = 0);
	String path_to_file;
	RID texture;
	Image::Format format;
	uint32_t flags;
	int w, h;
	mutable Ref<BitMap> alpha_cache;

	virtual void reload_from_file();

	static void _requested_3d(void *p_ud);
	static void _requested_srgb(void *p_ud);
	static void _requested_normal(void *p_ud);

protected:
	static void _bind_methods();
	void _validate_property(PropertyInfo &property) const;

public:
	typedef void (*TextureFormatRequestCallback)(const Ref<StreamTexture> &);

	static TextureFormatRequestCallback request_3d_callback;
	static TextureFormatRequestCallback request_srgb_callback;
	static TextureFormatRequestCallback request_normal_callback;

	uint32_t get_flags() const;
	Image::Format get_format() const;
	Error load(const String &p_path);
	String get_load_path() const;

	int get_width() const;
	int get_height() const;
	virtual RID get_rid() const;

	virtual void set_path(const String &p_path, bool p_take_over);

	virtual void draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false, const Ref<Texture> &p_normal_map = Ref<Texture>()) const;
	virtual void draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile = false, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false, const Ref<Texture> &p_normal_map = Ref<Texture>()) const;
	virtual void draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false, const Ref<Texture> &p_normal_map = Ref<Texture>(), bool p_clip_uv = true) const;

	virtual bool has_alpha() const;
	virtual void set_flags(uint32_t p_flags);
	bool is_pixel_opaque(int p_x, int p_y) const;

	virtual Ref<Image> get_data() const;

	StreamTexture();
	~StreamTexture();
};

class ResourceFormatLoaderStreamTexture : public ResourceFormatLoader {
public:
	virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = nullptr);
	virtual void get_recognized_extensions(List<String> *p_extensions) const;
	virtual bool handles_type(const String &p_type) const;
	virtual String get_resource_type(const String &p_path) const;
};

VARIANT_ENUM_CAST(ImageTexture::Storage);

class AtlasTexture : public Texture {
	GDCLASS(AtlasTexture, Texture);
	RES_BASE_EXTENSION("atlastex");

protected:
	Ref<Texture> atlas;
	Rect2 region;
	Rect2 margin;
	bool filter_clip;

	static void _bind_methods();

public:
	virtual int get_width() const;
	virtual int get_height() const;
	virtual RID get_rid() const;

	virtual bool has_alpha() const;

	virtual void set_flags(uint32_t p_flags);
	virtual uint32_t get_flags() const;

	void set_atlas(const Ref<Texture> &p_atlas);
	Ref<Texture> get_atlas() const;

	void set_region(const Rect2 &p_region);
	Rect2 get_region() const;

	void set_margin(const Rect2 &p_margin);
	Rect2 get_margin() const;

	void set_filter_clip(const bool p_enable);
	bool has_filter_clip() const;

	virtual Ref<Image> get_data() const;

	virtual void draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false, const Ref<Texture> &p_normal_map = Ref<Texture>()) const;
	virtual void draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile = false, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false, const Ref<Texture> &p_normal_map = Ref<Texture>()) const;
	virtual void draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false, const Ref<Texture> &p_normal_map = Ref<Texture>(), bool p_clip_uv = true) const;
	virtual bool get_rect_region(const Rect2 &p_rect, const Rect2 &p_src_rect, Rect2 &r_rect, Rect2 &r_src_rect) const;

	bool is_pixel_opaque(int p_x, int p_y) const;

	AtlasTexture();
};

class Mesh;

class MeshTexture : public Texture {
	GDCLASS(MeshTexture, Texture);
	RES_BASE_EXTENSION("meshtex");

	Ref<Texture> base_texture;
	Ref<Mesh> mesh;
	Size2i size;

protected:
	static void _bind_methods();

public:
	virtual int get_width() const;
	virtual int get_height() const;
	virtual RID get_rid() const;

	virtual bool has_alpha() const;

	virtual void set_flags(uint32_t p_flags);
	virtual uint32_t get_flags() const;

	void set_mesh(const Ref<Mesh> &p_mesh);
	Ref<Mesh> get_mesh() const;

	void set_image_size(const Size2 &p_size);
	Size2 get_image_size() const;

	void set_base_texture(const Ref<Texture> &p_texture);
	Ref<Texture> get_base_texture() const;

	virtual void draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false, const Ref<Texture> &p_normal_map = Ref<Texture>()) const;
	virtual void draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile = false, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false, const Ref<Texture> &p_normal_map = Ref<Texture>()) const;
	virtual void draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false, const Ref<Texture> &p_normal_map = Ref<Texture>(), bool p_clip_uv = true) const;
	virtual bool get_rect_region(const Rect2 &p_rect, const Rect2 &p_src_rect, Rect2 &r_rect, Rect2 &r_src_rect) const;

	bool is_pixel_opaque(int p_x, int p_y) const;

	MeshTexture();
};

class LargeTexture : public Texture {
	GDCLASS(LargeTexture, Texture);
	RES_BASE_EXTENSION("largetex");

protected:
	struct Piece {
		Point2 offset;
		Ref<Texture> texture;
	};

	Vector<Piece> pieces;
	Size2i size;

	Array _get_data() const;
	void _set_data(const Array &p_array);
	static void _bind_methods();

public:
	virtual int get_width() const;
	virtual int get_height() const;
	virtual RID get_rid() const;

	virtual bool has_alpha() const;

	virtual void set_flags(uint32_t p_flags);
	virtual uint32_t get_flags() const;

	int add_piece(const Point2 &p_offset, const Ref<Texture> &p_texture);
	void set_piece_offset(int p_idx, const Point2 &p_offset);
	void set_piece_texture(int p_idx, const Ref<Texture> &p_texture);

	void set_size(const Size2 &p_size);
	void clear();

	int get_piece_count() const;
	Vector2 get_piece_offset(int p_idx) const;
	Ref<Texture> get_piece_texture(int p_idx) const;
	Ref<Image> to_image() const;

	virtual void draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false, const Ref<Texture> &p_normal_map = Ref<Texture>()) const;
	virtual void draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile = false, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false, const Ref<Texture> &p_normal_map = Ref<Texture>()) const;
	virtual void draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false, const Ref<Texture> &p_normal_map = Ref<Texture>(), bool p_clip_uv = true) const;

	bool is_pixel_opaque(int p_x, int p_y) const;

	LargeTexture();
};

class CubeMap : public Resource {
	GDCLASS(CubeMap, Resource);
	RES_BASE_EXTENSION("cubemap");

public:
	enum Storage {
		STORAGE_RAW,
		STORAGE_COMPRESS_LOSSY,
		STORAGE_COMPRESS_LOSSLESS
	};

	enum Side {

		SIDE_LEFT,
		SIDE_RIGHT,
		SIDE_BOTTOM,
		SIDE_TOP,
		SIDE_FRONT,
		SIDE_BACK
	};

	enum Flags {
		FLAG_MIPMAPS = VisualServer::TEXTURE_FLAG_MIPMAPS,
		FLAG_REPEAT = VisualServer::TEXTURE_FLAG_REPEAT,
		FLAG_FILTER = VisualServer::TEXTURE_FLAG_FILTER,
		FLAGS_DEFAULT = FLAG_MIPMAPS | FLAG_REPEAT | FLAG_FILTER,
	};

private:
	bool valid[6];
	RID cubemap;
	Image::Format format;
	uint32_t flags;
	int w, h;
	Storage storage;
	Size2 size_override;
	float lossy_storage_quality;

	_FORCE_INLINE_ bool _is_valid() const {
		for (int i = 0; i < 6; i++) {
			if (valid[i]) {
				return true;
			}
		}
		return false;
	}

protected:
	bool _set(const StringName &p_name, const Variant &p_value);
	bool _get(const StringName &p_name, Variant &r_ret) const;
	void _get_property_list(List<PropertyInfo> *p_list) const;

	static void _bind_methods();

public:
	void set_flags(uint32_t p_flags);
	uint32_t get_flags() const;
	void set_side(Side p_side, const Ref<Image> &p_image);
	Ref<Image> get_side(Side p_side) const;

	Image::Format get_format() const;
	int get_width() const;
	int get_height() const;

	virtual RID get_rid() const;

	void set_storage(Storage p_storage);
	Storage get_storage() const;

	void set_lossy_storage_quality(float p_lossy_storage_quality);
	float get_lossy_storage_quality() const;

	virtual void set_path(const String &p_path, bool p_take_over = false);

	CubeMap();
	~CubeMap();
};

VARIANT_ENUM_CAST(CubeMap::Flags)
VARIANT_ENUM_CAST(CubeMap::Side)
VARIANT_ENUM_CAST(CubeMap::Storage)

class TextureLayered : public Resource {
	GDCLASS(TextureLayered, Resource);

public:
	enum Flags {
		FLAG_MIPMAPS = VisualServer::TEXTURE_FLAG_MIPMAPS,
		FLAG_REPEAT = VisualServer::TEXTURE_FLAG_REPEAT,
		FLAG_FILTER = VisualServer::TEXTURE_FLAG_FILTER,
		FLAG_ANISOTROPIC_FILTER = VisualServer::TEXTURE_FLAG_ANISOTROPIC_FILTER,
		FLAG_CONVERT_TO_LINEAR = VisualServer::TEXTURE_FLAG_CONVERT_TO_LINEAR,
		FLAGS_DEFAULT_TEXTURE_ARRAY = FLAG_MIPMAPS | FLAG_REPEAT | FLAG_FILTER,
		FLAGS_DEFAULT_TEXTURE_3D = FLAG_FILTER,
	};

	enum CompressMode {
		COMPRESS_LOSSLESS,
		COMPRESS_VIDEO_RAM,
		COMPRESS_UNCOMPRESSED
	};

private:
	String path_to_file;
	bool is_3d;
	RID texture;
	Image::Format format;
	uint32_t flags;

	int width;
	int height;
	int depth;

	virtual void reload_from_file();

	void _set_data(const Dictionary &p_data);
	Dictionary _get_data() const;

protected:
	static void _bind_methods();

public:
	void set_flags(uint32_t p_flags);
	uint32_t get_flags() const;

	Image::Format get_format() const;
	Error load(const String &p_path);
	String get_load_path() const;

	uint32_t get_width() const;
	uint32_t get_height() const;
	uint32_t get_depth() const;

	void create(uint32_t p_width, uint32_t p_height, uint32_t p_depth, Image::Format p_format, uint32_t p_flags = FLAGS_DEFAULT_TEXTURE_ARRAY);
	void set_layer_data(const Ref<Image> &p_image, int p_layer);
	Ref<Image> get_layer_data(int p_layer) const;
	void set_data_partial(const Ref<Image> &p_image, int p_x_ofs, int p_y_ofs, int p_z, int p_mipmap = 0);

	virtual RID get_rid() const;
	virtual void set_path(const String &p_path, bool p_take_over = false);

	TextureLayered(bool p_3d = false);
	~TextureLayered();
};

VARIANT_ENUM_CAST(TextureLayered::Flags)

class Texture3D : public TextureLayered {
	GDCLASS(Texture3D, TextureLayered);

protected:
	static void _bind_methods();

public:
	void create(uint32_t p_width, uint32_t p_height, uint32_t p_depth, Image::Format p_format, uint32_t p_flags = FLAGS_DEFAULT_TEXTURE_3D) {
		TextureLayered::create(p_width, p_height, p_depth, p_format, p_flags);
	}

	Texture3D() :
			TextureLayered(true) {}
};

class TextureArray : public TextureLayered {
	GDCLASS(TextureArray, TextureLayered);

protected:
	static void _bind_methods();

public:
	void create(uint32_t p_width, uint32_t p_height, uint32_t p_depth, Image::Format p_format, uint32_t p_flags = FLAGS_DEFAULT_TEXTURE_ARRAY) {
		TextureLayered::create(p_width, p_height, p_depth, p_format, p_flags);
	}

	TextureArray() :
			TextureLayered(false) {}
};

class ResourceFormatLoaderTextureLayered : public ResourceFormatLoader {
public:
	virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = nullptr);
	virtual void get_recognized_extensions(List<String> *p_extensions) const;
	virtual bool handles_type(const String &p_type) const;
	virtual String get_resource_type(const String &p_path) const;
};

class CurveTexture : public Texture {
	GDCLASS(CurveTexture, Texture);
	RES_BASE_EXTENSION("curvetex")

private:
	RID _texture;
	Ref<Curve> _curve;
	int _width;

	void _update();

protected:
	static void _bind_methods();

public:
	void set_width(int p_width);
	int get_width() const;

	void ensure_default_setup(float p_min = 0, float p_max = 1);

	void set_curve(Ref<Curve> p_curve);
	Ref<Curve> get_curve() const;

	virtual RID get_rid() const;

	virtual int get_height() const { return 1; }
	virtual bool has_alpha() const { return false; }

	virtual void set_flags(uint32_t p_flags) {}
	virtual uint32_t get_flags() const { return FLAG_FILTER; }

	CurveTexture();
	~CurveTexture();
};
/*
	enum CubeMapSide {

		CUBEMAP_LEFT,
		CUBEMAP_RIGHT,
		CUBEMAP_BOTTOM,
		CUBEMAP_TOP,
		CUBEMAP_FRONT,
		CUBEMAP_BACK,
	};

*/
//VARIANT_ENUM_CAST( Texture::CubeMapSide );

class GradientTexture : public Texture {
	GDCLASS(GradientTexture, Texture);

public:
	struct Point {
		float offset;
		Color color;
		bool operator<(const Point &p_ponit) const {
			return offset < p_ponit.offset;
		}
	};

private:
	Ref<Gradient> gradient;
	bool update_pending;
	RID texture;
	int width;

	void _queue_update();
	void _update();

protected:
	static void _bind_methods();

public:
	void set_gradient(Ref<Gradient> p_gradient);
	Ref<Gradient> get_gradient() const;

	void set_width(int p_width);
	int get_width() const;

	virtual RID get_rid() const { return texture; }
	virtual int get_height() const { return 1; }
	virtual bool has_alpha() const { return true; }

	virtual void set_flags(uint32_t p_flags) {}
	virtual uint32_t get_flags() const { return FLAG_FILTER; }

	virtual Ref<Image> get_data() const;

	GradientTexture();
	virtual ~GradientTexture();
};

class GradientTexture2D : public Texture {
	GDCLASS(GradientTexture2D, Texture);

public:
	enum Fill {
		FILL_LINEAR,
		FILL_RADIAL,
	};
	enum Repeat {
		REPEAT_NONE,
		REPEAT,
		REPEAT_MIRROR,
	};

private:
	Ref<Gradient> gradient;
	mutable RID texture;

	int width = 64;
	int height = 64;

	uint32_t flags = FLAGS_DEFAULT;

	bool use_hdr = false;

	Vector2 fill_from;
	Vector2 fill_to = Vector2(1, 0);

	Fill fill = FILL_LINEAR;
	Repeat repeat = REPEAT_NONE;

	float _get_gradient_offset_at(int x, int y) const;

	bool update_pending = false;
	void _queue_update();
	void _update();

protected:
	static void _bind_methods();

public:
	void set_gradient(Ref<Gradient> p_gradient);
	Ref<Gradient> get_gradient() const;

	void set_width(int p_width);
	virtual int get_width() const;
	void set_height(int p_height);
	virtual int get_height() const;

	virtual void set_flags(uint32_t p_flags);
	virtual uint32_t get_flags() const;

	void set_use_hdr(bool p_enabled);
	bool is_using_hdr() const;

	void set_fill(Fill p_fill);
	Fill get_fill() const;
	void set_fill_from(Vector2 p_fill_from);
	Vector2 get_fill_from() const;
	void set_fill_to(Vector2 p_fill_to);
	Vector2 get_fill_to() const;

	void set_repeat(Repeat p_repeat);
	Repeat get_repeat() const;

	virtual RID get_rid() const;
	virtual bool has_alpha() const { return true; }
	virtual Ref<Image> get_data() const;

	GradientTexture2D();
	virtual ~GradientTexture2D();
};

VARIANT_ENUM_CAST(GradientTexture2D::Fill);
VARIANT_ENUM_CAST(GradientTexture2D::Repeat);

class ProxyTexture : public Texture {
	GDCLASS(ProxyTexture, Texture);

private:
	RID proxy;
	Ref<Texture> base;

protected:
	static void _bind_methods();

public:
	void set_base(const Ref<Texture> &p_texture);
	Ref<Texture> get_base() const;

	virtual int get_width() const;
	virtual int get_height() const;
	virtual RID get_rid() const;

	virtual bool has_alpha() const;

	virtual void set_flags(uint32_t p_flags);
	virtual uint32_t get_flags() const;

	ProxyTexture();
	~ProxyTexture();
};

class AnimatedTexture : public Texture {
	GDCLASS(AnimatedTexture, Texture);

	//use readers writers lock for this, since its far more times read than written to
	RWLock rw_lock;

public:
	enum {
		MAX_FRAMES = 256
	};

private:
	RID proxy;

	struct Frame {
		Ref<Texture> texture;
		float delay_sec;

		Frame() {
			delay_sec = 0;
		}
	};

	Frame frames[MAX_FRAMES];
	int frame_count;
	int current_frame;
	bool pause;
	bool oneshot;
	float fps;

	float time;

	uint64_t prev_ticks;

	void _update_proxy();

protected:
	static void _bind_methods();
	void _validate_property(PropertyInfo &property) const;

public:
	void set_frames(int p_frames);
	int get_frames() const;

	void set_current_frame(int p_frame);
	int get_current_frame() const;

	void set_pause(bool p_pause);
	bool get_pause() const;

	void set_oneshot(bool p_oneshot);
	bool get_oneshot() const;

	void set_frame_texture(int p_frame, const Ref<Texture> &p_texture);
	Ref<Texture> get_frame_texture(int p_frame) const;

	void set_frame_delay(int p_frame, float p_delay_sec);
	float get_frame_delay(int p_frame) const;

	void set_fps(float p_fps);
	float get_fps() const;

	virtual int get_width() const;
	virtual int get_height() const;
	virtual RID get_rid() const;

	virtual bool has_alpha() const;

	virtual void set_flags(uint32_t p_flags);
	virtual uint32_t get_flags() const;

	virtual Ref<Image> get_data() const;

	bool is_pixel_opaque(int p_x, int p_y) const;

	AnimatedTexture();
	~AnimatedTexture();
};

class CameraTexture : public Texture {
	GDCLASS(CameraTexture, Texture);

private:
	int camera_feed_id;
	CameraServer::FeedImage which_feed;

protected:
	static void _bind_methods();

public:
	virtual int get_width() const;
	virtual int get_height() const;
	virtual RID get_rid() const;
	virtual bool has_alpha() const;

	virtual void set_flags(uint32_t p_flags);
	virtual uint32_t get_flags() const;

	virtual Ref<Image> get_data() const;

	void set_camera_feed_id(int p_new_id);
	int get_camera_feed_id() const;

	void set_which_feed(CameraServer::FeedImage p_which);
	CameraServer::FeedImage get_which_feed() const;

	void set_camera_active(bool p_active);
	bool get_camera_active() const;

	CameraTexture();
	~CameraTexture();
};

// External textures as defined by https://www.khronos.org/registry/OpenGL/extensions/OES/OES_EGL_image_external.txt
class ExternalTexture : public Texture {
	GDCLASS(ExternalTexture, Texture);

private:
	RID texture;
	Size2 size;

protected:
	static void _bind_methods();

public:
	uint32_t get_external_texture_id();

	virtual Size2 get_size() const;
	void set_size(const Size2 &p_size);

	virtual int get_width() const;
	virtual int get_height() const;

	virtual RID get_rid() const;
	virtual bool has_alpha() const;

	virtual void set_flags(uint32_t p_flags);
	virtual uint32_t get_flags() const;

	ExternalTexture();
	~ExternalTexture();
};

#endif // TEXTURE_H


text:
package database

import (
	"github.com/go-kit/kit/endpoint"
	"golang.org/x/net/context"

	"github.com/obazavil/openstack-workload-transcoding/wttypes"
)

// ListJobs

type listJobsRequest struct {
}

type listJobsResponse struct {
	Jobs []wttypes.Job `json:"job,omitempty"`
	Err  error         `json:"error,omitempty"`
}

func (r listJobsResponse) error() error { return r.Err }

func makeListJobsEndpoint(ds Service) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (interface{}, error) {
		_ = request.(listJobsRequest)
		jobs, err := ds.ListJobs()
		return listJobsResponse{Jobs: jobs, Err: err}, nil
	}
}

// InsertJob

type insertJobRequest struct {
	Job wttypes.Job
}

type insertJobResponse struct {
	JobIDs wttypes.JobIDs `json:"job_ids,omitempty"`
	Err    error          `json:"error,omitempty"`
}

func (r insertJobResponse) error() error { return r.Err }

func makeInsertJobEndpoint(ds Service) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (interface{}, error) {
		req := request.(insertJobRequest)
		ids, err := ds.InsertJob(req.Job)
		return insertJobResponse{JobIDs: ids, Err: err}, nil
	}
}

// UpdateJob

type updateJobRequest struct {
	Job wttypes.Job
}

type updateJobResponse struct {
	Err error `json:"error,omitempty"`
}

func (r updateJobResponse) error() error { return r.Err }

func makeUpdateJobEndpoint(ds Service) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (interface{}, error) {
		req := request.(updateJobRequest)
		err := ds.UpdateJob(req.Job)

		return updateJobResponse{Err: err}, nil
	}
}

// GetJob

type getJobRequest struct {
	ID string
}

type getJobResponse struct {
	Job *wttypes.Job `json:"job,omitempty"`
	Err error        `json:"error,omitempty"`
}

func (r getJobResponse) error() error { return r.Err }

func makeGetJobEndpoint(ds Service) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (interface{}, error) {
		req := request.(getJobRequest)
		job, err := ds.GetJob(req.ID)
		return getJobResponse{Job: &job, Err: err}, nil
	}
}

// UpdateTranscoding

type updateTranscodingRequest struct {
	Transcoding wttypes.TranscodingTask
}

type updateTranscodingResponse struct {
	Err error `json:"error,omitempty"`
}

func (r updateTranscodingResponse) error() error { return r.Err }

func makeUpdateTranscodingEndpoint(ds Service) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (interface{}, error) {
		req := request.(updateTranscodingRequest)
		err := ds.UpdateTranscoding(req.Transcoding)

		return updateTranscodingResponse{Err: err}, nil
	}
}

// GetTranscoding

type getTranscodingRequest struct {
	ID string
}

type getTranscodingResponse struct {
	Transcoding wttypes.TranscodingTask `json:"transcoding,omitempty"`
	Err         error                   `json:"error,omitempty"`
}

func (r getTranscodingResponse) error() error { return r.Err }

func makeGetTranscodingEndpoint(ds Service) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (interface{}, error) {
		req := request.(getTranscodingRequest)
		t, err := ds.GetTranscoding(req.ID)

		return getTranscodingResponse{Transcoding: t, Err: err}, nil
	}
}

// UpdateWorkerStatus

type updateWorkerStatusRequest struct {
	WS wttypes.WorkerStatus
}

type updateWorkerStatusResponse struct {
	Err error `json:"error,omitempty"`
}

func (r updateWorkerStatusResponse) error() error { return r.Err }

func makeUpdateWorkerStatusEndpoint(ds Service) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (interface{}, error) {
		req := request.(updateWorkerStatusRequest)
		err := ds.UpdateWorkerStatus(req.WS.Addr, req.WS.Status)

		return updateWorkerStatusResponse{Err: err}, nil
	}
}


text:
/* eslint-env node */
module.exports = {
  normalizeEntityName: function() {
    // this prevents an error when the entityName is
    // not specified (since that doesn't actually matter
    // to us
  },

  description: 'Generate initial seed model to activate @cardstack/jsonapi.'
};


text:
package org.testobject.kernel.replay.impl;

import org.testobject.commons.util.image.Image;
import org.testobject.commons.util.image.ImageUtil;
import org.testobject.kernel.inference.input.Framebuffer;
import org.testobject.kernel.platform.robot.Grab;

/**
 *
 * @author enijkamp
 *
 */
public class FramebufferGrab implements Grab {

	private final Image.Int framebuffer;

	public FramebufferGrab(Image.Int framebuffer) {
		this.framebuffer = framebuffer;
	}

	@Override
	public boolean grab() {
		return true;
	}

	@Override
	public Framebuffer get() {
		return new Framebuffer(System.currentTimeMillis(), ImageUtil.deepCopy(framebuffer));
	}

	@Override
	public void reset() {

	}

	@Override
	public void close() {

	}

}


text:
/**
 * Created by Amit on 22/11/15.
 */

var express = require('express'),
    db = require('./models/db'),
    config = require('./config/config'),
    logger = require('./config/logger'),
    cluster = require('cluster'),
    os = require('os');

if(cluster.isMaster){
    //It's a Master process

    var numWorkers = os.cpus().length;

    for(var i = 0; i < numWorkers; i++ ){
        cluster.fork();
    }

    /**
     * Register callback event 'online' on cluster module when a worker is UP
     */
    cluster.on('online', function(worker){
        LOGGER.log('info', 'Worker ' + worker.process.pid + ' is online');
    });

    /**
     * Register callback event 'exit' on cluster module when a worker DIES
     * And restart the died worker process
     */
    cluster.on('exit', function(worker, code, signal){
        LOGGER.log('warn', 'Worker ' + worker.process.pid + ' died with code: ' + code + ' and signal:' + signal);
        LOGGER.log('info', 'Starting a new worker');
        cluster.fork();
    });
}else{
    //It's a Worker process
    var app = express();

    require('./config/express')(app, config);

    db.connect(config.db, function(err){
        if(err){
            LOGGER.log('error', 'Unable to connect to Mongo');
            process.exit(1);
        }else{
            app.listen(config.port, function(){
                LOGGER.log('info', 'Listening on port ' + config.port);
            });
        }
    });
}


text:
#ifndef RADIUMENGINE_HANDLE_SYSTEM
#define RADIUMENGINE_HANDLE_SYSTEM

#include <Core/Animation/Pose.hpp>
#include <Core/RaCore.hpp>
#include <Core/Types.hpp>

namespace Ra {
namespace Core {
namespace Animation {

/**
 * Type for transform names
 */
using Label = std::string;

/**
 * The HandleArray class describes the base handle structure used for deformation.
 */
class RA_CORE_API HandleArray
{
  public:
    /**
     * The SpaceType specifies the space the transform lives in.
     */
    enum class SpaceType : bool { LOCAL, MODEL };
    static_assert( std::is_same<bool, typename std::underlying_type<SpaceType>::type>::value,
                   "SpaceType is not a boolean" );
    HandleArray();
    explicit HandleArray( const uint n );
    HandleArray( const HandleArray& handle ) = default;
    HandleArray& operator=( const HandleArray& handle ) = default;

    virtual ~HandleArray();

    /**
     * @return the number of transformations
     */
    inline virtual uint size() const;

    /**
     * Clear the transformations data
     */
    virtual void clear();

    /**
     * @return the current pose in the \p MODE space.
     */
    virtual const Pose& getPose( const SpaceType MODE ) const;

    /**
     * Set the current pose.
     * @param pose the new pose
     * @param MODE the space the psoe lives in
     */
    virtual void setPose( const Pose& pose, const SpaceType MODE );

    /**
     * @return the \p i-th transformation in \p MODE space.
     */
    virtual const Transform& getTransform( const uint i, const SpaceType MODE ) const;

    /**
     * Set the i-th transform to \p T, which is given in the MODE space.
     */
    virtual void setTransform( const uint i, const Transform& T, const SpaceType MODE );

    /**
     * @return the Handle's name
     */
    inline Label getName() const;

    /**
     * Set the Handle's name
     */
    inline void setName( const Label& name );

    /**
     * @return the name of the \p i-th transform.
     */
    inline Label getLabel( const uint i ) const;

    /**
     * Set the name of the \p i-th transform.
     */
    inline void setLabel( const uint i, const Label& text );

    /**
     * The current pose of the Handle
     */
    LocalPose m_pose;

  protected:
    /**
     * The Handle's name
     */
    Label m_name;

    /**
     * The names of the transforms.
     */
    std::vector<Label> m_label;
};

} // namespace Animation
} // Namespace Core
} // Namespace Ra

#include <Core/Animation/HandleArray.inl>

#endif // RADIUMENGINE_HANDLE_SYSTEM


text:
format=pdf # pdf svg
mode=save # display save
lm_scale=0.0
acoustic_scale=0.0
#end of config

. utils/parse_options.sh

if [ $# != 3 ]; then
   echo "usage: $0 [--mode display|save] [--format pdf|svg] <utt-id> <lattice-ark> <word-list>"
   echo "e.g.:  $0 utt-0001 \"test/lat.*.gz\" tri1/graph/words.txt"
   exit 1;
fi

. path.sh

uttid=$1
lat=$2
words=$3

tmpdir=$(mktemp -d /tmp/kaldi.XXXX); # trap "rm -r $tmpdir" EXIT # cleanup

gunzip -c $lat | lattice-to-fst --lm-scale=$lm_scale --acoustic-scale=$acoustic_scale ark:- "scp,p:echo $uttid $tmpdir/$uttid.fst|" || exit 1;
! [ -s $tmpdir/$uttid.fst ] && \
  echo "Failed to extract lattice for utterance $uttid (not present?)" && exit 1;
fstdraw --portrait=true --osymbols=$words $tmpdir/$uttid.fst | dot -T${format} > $tmpdir/$uttid.${format}

if [ "$(uname)" == "Darwin" ]; then
    doc_open=open
elif [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then
    doc_open=xdg-open
elif [ $mode == "display" ] ; then
        echo "Can not automaticaly open file on your operating system"
        mode=save
fi

[ $mode == "display" ] && $doc_open $tmpdir/$uttid.${format}
[[ $mode == "display" && $? -ne 0 ]] && echo "Failed to open ${format} format." && mode=save
[ $mode == "save" ] && echo "Saving to $uttid.${format}" && cp $tmpdir/$uttid.${format} .

exit 0


text:
/**
 *
 */
package io.pkts.packet.sip;

/**
 * @author jonas@jonasborjesson.com
 */
public class SipException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    /**
     *
     */
    public SipException() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @param message
     */
    public SipException(final String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }

    /**
     * @param cause
     */
    public SipException(final Throwable cause) {
        super(cause);
        // TODO Auto-generated constructor stub
    }

    /**
     * @param message
     * @param cause
     */
    public SipException(final String message, final Throwable cause) {
        super(message, cause);
        // TODO Auto-generated constructor stub
    }

}


text:
import SimpleITK as sitk
import sys
import os

if len(sys.argv) < 3:
    print("Usage: DicomSeriesReader <input_directory> <output_file>")
    sys.exit(1)

print("Reading Dicom directory:", sys.argv[1])
reader = sitk.ImageSeriesReader()

dicom_names = reader.GetGDCMSeriesFileNames(sys.argv[1])
reader.SetFileNames(dicom_names)

image = reader.Execute()

size = image.GetSize()
print("Image size:", size[0], size[1], size[2])

print("Writing image:", sys.argv[2])

sitk.WriteImage(image, sys.argv[2])

if "SITK_NOSHOW" not in os.environ:
    sitk.Show(image, "Dicom Series")


text:
#include <err.h>
#include <debug.h>
#include <arch/x86/mmu.h>
#include <platform.h>
#include "platform_p.h"
#include <platform/pc.h>
#include <platform/multiboot.h>
#include <platform/console.h>
#include <platform/keyboard.h>
#include <dev/pci.h>
#include <dev/uart.h>

extern multiboot_info_t *_multiboot_info;
extern unsigned int _heap_end;

void platform_init_mmu_mappings(void)
{
	/* do some memory map initialization */
}

void platform_init_multiboot_info(void)
{
	unsigned int i;

	if (_multiboot_info) {
		if (_multiboot_info->flags & MB_INFO_MEM_SIZE) {
			_heap_end = _multiboot_info->mem_upper * 1024;
		}

		if (_multiboot_info->flags & MB_INFO_MMAP) {
			memory_map_t *mmap = (memory_map_t *) (_multiboot_info->mmap_addr - 4);

			dprintf(SPEW, "mmap length: %u\n", _multiboot_info->mmap_length);

			for (i=0; i < _multiboot_info->mmap_length / sizeof(memory_map_t); i++) {
				dprintf(SPEW, "base=%08x, length=%08x, type=%02x\n",
				        mmap[i].base_addr_low, mmap[i].length_low, mmap[i].type);

				if (mmap[i].type == MB_MMAP_TYPE_AVAILABLE && mmap[i].base_addr_low >= _heap_end) {
					_heap_end = mmap[i].base_addr_low + mmap[i].length_low;
				} else if (mmap[i].type != MB_MMAP_TYPE_AVAILABLE && mmap[i].base_addr_low >= _heap_end) {
					/*
					 * break on first memory hole above default heap end for now.
					 * later we can add facilities for adding free chunks to the
					 * heap for each segregated memory region.
					 */
					break;
				}
			}
		}
	}
}

void platform_early_init(void)
{
	platform_init_uart();

	/* update the heap end so we can take advantage of more ram */
	platform_init_multiboot_info();

	/* get the text console working */
	platform_init_console();

	/* initialize the interrupt controller */
	platform_init_interrupts();

	/* initialize the timer */
	platform_init_timer();
}

void platform_init(void)
{
	uart_init();

	platform_init_keyboard();

	pci_init();
}


text:
//
//  GWSquare.h
//  仿百思不得姐
//
//  Created by gongqiuwei on 16/4/29.
//  Copyright © 2016年 gongqiuwei. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface GWSquare : NSObject
/** 图片 */
@property (nonatomic, copy) NSString *icon;
/** 标题文字 */
@property (nonatomic, copy) NSString *name;
/** 链接 */
@property (nonatomic, copy) NSString *url;
@end


text:
namespace content {
class WebContents;
}  // namespace content

namespace gfx {
class Image;
}  // namespace gfx

namespace favicon {

// Creates a ContentFaviconDriver and associates it with |web_contents| if none
// exists yet.
//
// This is a helper method for ContentFaviconDriver::CreateForWebContents() that
// gets KeyedService factories from the Profile linked to web_contents.
void CreateContentFaviconDriverForWebContents(
    content::WebContents* web_contents);

// Generates a monogram in a colored circle. The color is based on the hash
// of the url and the monogram is the first letter of the URL domain.
SkBitmap GenerateMonogramFavicon(GURL url, int icon_size, int circle_size);

// Retrieves the favicon from given WebContents. If contents contain a
// network error, desaturate the favicon.
gfx::Image TabFaviconFromWebContents(content::WebContents* contents);

// Returns the image to use when no favicon is available, taking dark mode
// into account if necessary.
gfx::Image GetDefaultFavicon();

// Saves the favicon for the last committed navigation entry to the favicon
// database.
void SaveFaviconEvenIfInIncognito(content::WebContents* contents);

// Return true if the favicon for |entry| should be themified, based on both
// its visible and actual URL.
bool ShouldThemifyFaviconForEntry(content::NavigationEntry* entry);

// Recolor favicon with |alternate_color| if contrast ratio is low between
// source color and background |active_background| or
// |inactive_background|.
gfx::ImageSkia ThemeFavicon(const gfx::ImageSkia& source,
                            SkColor alternate_color,
                            SkColor active_background,
                            SkColor inactive_background);

}  // namespace favicon

#endif  // CHROME_BROWSER_FAVICON_FAVICON_UTILS_H_


text:
@extends('layouts.master.layout')

@section('title','Additional Add')

@section('content')

Dashboard

Additional Add Form

                        @include('flash::message')
                        {!! Form::open(['method'=>'POST', 'action'=> 'AdditionalsController@store','role'=>'form'])!!}
                        {{ Form::hidden('id') }}

has('extra_items_id')? 'has-error': ''}}">
                                         Item Name:
                                        {!! Form::select('extra_items_id', $extra_items, null, ['id'=>'extra_item_id','class'=>'form-control']) !!}
                                        @if($errors->has('extra_items_id'))
                                            {{$errors->first('extra_items_id')}}
                                        @endif

has('date')? 'has-error': ''}}">
                                         Enter Date:
                                        {!! Form::date("date", null, ['class' => 'form-control', 'placeholder'=> 'Enter your Date...', 'id'=>'date', 'value'=> old('date'),]) !!}
                                        @if($errors->has('date'))
                                            {{$errors->first('date')}}
                                        @endif

has('amount')? 'has-error': ''}}">
                                         Extra Amount:
                                         {!! Form::number("amount", null, ['class' => 'form-control', 'placeholder'=> 'Enter Extra Amount...', 'id'=>'extra_amount']) !!}
                                           @if($errors->has('amount'))
                                                {{$errors->first('amount')}}
                                            @endif

                                        <button type="submit" class="btn btn-success">Submit </button>

                       {!! Form::close() !!}

@stop


text: echo "one two three" > q16.txt


text:
import React, {Component} from "react";
import "./App.css";
import {
    BrowserRouter as Router,
    Route,
    Link
} from 'react-router-dom'
class App extends Component {

    render() {
        return (

{this.props.title}

                        Brought to you by {this.props.author} on{" "}
                        {this.props.now.toDateString()}

                    <Router>

                            <Route exact path="/" component="{CharacterSearchPage}"/>

                    </Router>

        );
    }
}
export default App;


text:
Converts the specified ISO 8601 representation of a date and time to its DateTimeOffset equivalent.

```csharp
public static DateTimeOffset? TryParseIso8601(string? value)
```

| parameter | description |
| --- | --- |
| value | The ISO 8601 string representation to parse. |

## Return Value

Non-null if successful.

## See Also

* class [DateTimeOffsetUtility](../DateTimeOffsetUtility.md)
* namespace [Faithlife.Utility](../../Faithlife.Utility.md)

---

# DateTimeOffsetUtility.TryParseIso8601 method (2 of 2)

Converts the specified ISO 8601 representation of a date and time to its DateTimeOffset equivalent.

```csharp
public static bool TryParseIso8601(string? value, out DateTimeOffset date)
```

| parameter | description |
| --- | --- |
| value | The ISO 8601 string representation to parse. |
| date | The DateTimeOffset equivalent. |

## Return Value

True if successful.

## See Also

* class [DateTimeOffsetUtility](../DateTimeOffsetUtility.md)
* namespace [Faithlife.Utility](../../Faithlife.Utility.md)

<!-- DO NOT EDIT: generated by xmldocmd for Faithlife.Utility.dll -->


text:
import {Injectable} from '@angular/core';
import {Http, Headers, RequestOptions} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class PhotoService {
    // private headers = new Headers(
    //     [{'Content-Type': 'application/json'},
    //     {'Access-Control-Allow-Origin':'http://192.168.1.3:8080'},
    //      {'Access-Control-Allow-Methods': 'GET'},
    //     {'Accept': 'application/json'}]);
    // private options = new RequestOptions({ headers: this.headers });
    // private _url = "http://localhost:3000/albums.json";
   private _url = 'http://jsonplaceholder.typicode.com/albums';

    constructor(private _http: Http){
    }

    getAlbums() {
        return this._http.get(this._url)
            .map(res => res.json());
    }

    getPhotos(id){
        return this._http.get(this._url + '/' + id + '/photos')
            .map(res => res.json());
    }

}


text:
{-# LANGUAGE OverloadedStrings #-}

import Control.Applicative ((<$>))
import Statistics.Sample.KernelDensity (kde)
import Text.Hastache (MuType(..), defaultConfig, hastacheFile)
import Text.Hastache.Context (mkStrContext)
import qualified Data.Attoparsec as B
import qualified Data.Attoparsec.Char8 as A
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import qualified Data.Vector.Unboxed as U

csv = do
  B.takeTill A.isEndOfLine
  (A.double `A.sepBy` A.char ',') `A.sepBy` A.endOfLine

main = do
  waits <- (either error (U.fromList . map last . filter (not.null)) .
            A.parseOnly csv) <$> B.readFile "data/faithful.csv"
  let xs = map (\(a,b) -> [a,b]) . U.toList . uncurry U.zip . kde 64 $ waits
      context "data" = MuVariable . show $ xs
  s <- hastacheFile defaultConfig "kde.tpl" (mkStrContext context)
  L.writeFile "kde.html" s


text:
<Defs>

    <AlienRace.BackstoryDef ParentName="FormerHumanBase">
        <defName>PM_HousekeeperCatBackstory</defName>
        <title>former human</title>
        <titleShort>former human</titleShort>
        <baseDescription>Someone turned [PAWN_nameDef] into an animal, using mutagenic mechanites. (Un?)fortunately, [PAWN_pronoun] retains [PAWN_possessive] human mind...but for how long? In this state, [PAWN_nameDef] have limited social interactions, but, thanks to [PAWN_pronoun] body having all necessary capabilities, is able to perform any tasks. [PAWN_nameDef] will need to be kept happy to resist instinct creeping in.</baseDescription>
        <workAllows>

ManualSkilled

Crafting

Caring

Artistic

PlantWork

Mining

Cooking

Hunting

Shooting

Constructing

        </workAllows>
    </AlienRace.BackstoryDef>

</Defs>


text:
package edu.algorithms;

import java.util.Arrays;
import java.util.Collection;

import org.openjdk.jol.info.GraphLayout;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.junit.runners.Parameterized.*;

@RunWith(Parameterized.class)
public class MemorySizeTest {

    @Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{{64}, {256}, {512}, {1024}});
    }

    private final long size;

    public MemorySizeTest(final long size) {
        this.size = size;
    }

    private Percolation p;

    @Before
    public void setUp()
            throws Exception {
        p = new Percolation((int)size);
    }

    @Test
    public void testPercolationSize()
            throws Exception {
        long percolationSize = GraphLayout.parseInstance(p).totalSize();
        assertThat(percolationSize, lessThanOrEqualTo(11 * size * size + 128 * size + 1024));
    }
}


text:
package uk.bl.wa.whois;

import static org.junit.Assert.*;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.jruby.embed.LocalContextScope;
import org.jruby.embed.ScriptingContainer;
import org.junit.Test;

import uk.bl.wa.whois.record.WhoisContact;

public class GoDaddyTest {

    ScriptingContainer container = new ScriptingContainer(LocalContextScope.CONCURRENT);

    @Test
    public void coucou() throws IOException {
        InputStream resourceAsStream = GoDaddyTest.class.getResourceAsStream("/status_registered_bis_spec.rb");
        assertFalse(resourceAsStream == null);
        container.put("content", readInputStreamAsString(GoDaddyTest.class
                .getResourceAsStream("/fixtures/responses/whois.godaddy.com/status_registered_bis.txt")));
        WhoisContact res = (WhoisContact) container.runScriptlet(resourceAsStream, "status_registered_bis_spec.rb");
        assertEquals("allan.hull@bcbsne.com", res.getEmail());
    }

    public static String readInputStreamAsString(InputStream in) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(in);
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        int result = bis.read();
        while (result != -1) {
            byte b = (byte) result;
            buf.write(b);
            result = bis.read();
        }
        return buf.toString();
    }
}