text:
.class public Lcom/android/internal/app/MediaRouteControllerDialog;
.super Landroid/app/Dialog;
.source "MediaRouteControllerDialog.java"

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/android/internal/app/MediaRouteControllerDialog$MediaRouterCallback;
    }
.end annotation

# static fields
.field private static final VOLUME_UPDATE_DELAY_MILLIS:I = 0xfa

# instance fields
.field private final mCallback:Lcom/android/internal/app/MediaRouteControllerDialog$MediaRouterCallback;

.field private mControlView:Landroid/view/View;

.field private mCreated:Z

.field private mCurrentIconDrawable:Landroid/graphics/drawable/Drawable;

.field private mDisconnectButton:Landroid/widget/Button;

.field private mIsWfd:Z

.field private mMediaRouteConnectingDrawable:Landroid/graphics/drawable/Drawable;

.field private mMediaRouteOnDrawable:Landroid/graphics/drawable/Drawable;

.field private mRoute:Landroid/media/MediaRouter$RouteInfo;

.field private final mRouter:Landroid/media/MediaRouter;

.field private mVolumeControlEnabled:Z

.field private mVolumeLayout:Landroid/widget/LinearLayout;

.field private mVolumeSlider:Landroid/widget/SeekBar;

.field private mVolumeSliderTouched:Z

# direct methods
.method public constructor <init>(Landroid/content/Context;I)V
    .locals 12
    .param p1, "context"    # Landroid/content/Context;
    .param p2, "theme"    # I

    .prologue
    const/4 v11, 0x6

    const/4 v10, 0x2

    const/4 v3, 0x0

    const/4 v8, 0x1

    .line 77
    invoke-direct {p0, p1, p2}, Landroid/app/Dialog;-><init>(Landroid/content/Context;I)V

    .line 65
    iput-boolean v8, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mVolumeControlEnabled:Z

    .line 74
    iput-boolean v3, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mIsWfd:Z

    .line 79
    const-string v7, "media_router"

    invoke-virtual {p1, v7}, Landroid/content/Context;->getSystemService(Ljava/lang/String;)Ljava/lang/Object;

    move-result-object v7

    check-cast v7, Landroid/media/MediaRouter;

    iput-object v7, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mRouter:Landroid/media/MediaRouter;

    .line 80
    new-instance v7, Lcom/android/internal/app/MediaRouteControllerDialog$MediaRouterCallback;

    const/4 v9, 0x0

    invoke-direct {v7, p0, v9}, Lcom/android/internal/app/MediaRouteControllerDialog$MediaRouterCallback;-><init>(Lcom/android/internal/app/MediaRouteControllerDialog;Lcom/android/internal/app/MediaRouteControllerDialog$1;)V

    iput-object v7, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mCallback:Lcom/android/internal/app/MediaRouteControllerDialog$MediaRouterCallback;

    .line 82
    iget-object v7, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mRouter:Landroid/media/MediaRouter;

    invoke-virtual {v7}, Landroid/media/MediaRouter;->getSelectedRoute()Landroid/media/MediaRouter$RouteInfo;

    move-result-object v7

    iput-object v7, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mRoute:Landroid/media/MediaRouter$RouteInfo;

    .line 84
    iget-object v7, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mRoute:Landroid/media/MediaRouter$RouteInfo;

    invoke-virtual {v7}, Landroid/media/MediaRouter$RouteInfo;->getSupportedTypes()I

    move-result v6

    .line 85
    .local v6, "supportedTypes":I
    iget-object v7, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mRoute:Landroid/media/MediaRouter$RouteInfo;

    invoke-virtual {v7}, Landroid/media/MediaRouter$RouteInfo;->getStatusCode()I

    move-result v5

    .line 87
    .local v5, "statusCode":I
    and-int/lit8 v7, v6, 0x4

    if-eqz v7, :cond_0

    if-eq v5, v10, :cond_0

    if-eq v5, v11, :cond_0

    move v3, v8

    .line 90
    .local v3, "shouldRepick":Z
    :cond_0
    if-eqz v3, :cond_2

    .line 91
    iget-object v7, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mRouter:Landroid/media/MediaRouter;

    invoke-virtual {v7}, Landroid/media/MediaRouter;->getRouteCount()I

    move-result v2

    .line 92
    .local v2, "routeCount":I
    const/4 v0, 0x0

    .local v0, "i":I
    :goto_0
    if-ge v0, v2, :cond_2

    .line 93
    iget-object v7, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mRouter:Landroid/media/MediaRouter;

    invoke-virtual {v7, v0}, Landroid/media/MediaRouter;->getRouteAt(I)Landroid/media/MediaRouter$RouteInfo;

    move-result-object v1

    .line 94
    .local v1, "r":Landroid/media/MediaRouter$RouteInfo;
    const/4 v7, 0x4

    invoke-virtual {v1, v7}, Landroid/media/MediaRouter$RouteInfo;->matchesTypes(I)Z

    move-result v7

    if-eqz v7, :cond_3

    .line 95
    invoke-virtual {v1}, Landroid/media/MediaRouter$RouteInfo;->getStatusCode()I

    move-result v4

    .line 96
    .local v4, "status":I
    if-eq v4, v10, :cond_1

    if-ne v4, v11, :cond_3

    .line 98
    :cond_1
    iput-object v1, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mRoute:Landroid/media/MediaRouter$RouteInfo;

    .line 99
    iput-boolean v8, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mIsWfd:Z

    .line 107
    .end local v0    # "i":I
    .end local v1    # "r":Landroid/media/MediaRouter$RouteInfo;
    .end local v2    # "routeCount":I
    .end local v4    # "status":I
    :cond_2
    return-void

    .line 92
    .restart local v0    # "i":I
    .restart local v1    # "r":Landroid/media/MediaRouter$RouteInfo;
    .restart local v2    # "routeCount":I
    :cond_3
    add-int/lit8 v0, v0, 0x1

    goto :goto_0
.end method

.method static synthetic access$100(Lcom/android/internal/app/MediaRouteControllerDialog;)Z
    .locals 1
    .param p0, "x0"    # Lcom/android/internal/app/MediaRouteControllerDialog;

    .prologue
    .line 49
    iget-boolean v0, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mVolumeSliderTouched:Z

    return v0
.end method

.method static synthetic access$102(Lcom/android/internal/app/MediaRouteControllerDialog;Z)Z
    .locals 0
    .param p0, "x0"    # Lcom/android/internal/app/MediaRouteControllerDialog;
    .param p1, "x1"    # Z

    .prologue
    .line 49
    iput-boolean p1, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mVolumeSliderTouched:Z

    return p1
.end method

.method static synthetic access$200(Lcom/android/internal/app/MediaRouteControllerDialog;)V
    .locals 0
    .param p0, "x0"    # Lcom/android/internal/app/MediaRouteControllerDialog;

    .prologue
    .line 49
    invoke-direct {p0}, Lcom/android/internal/app/MediaRouteControllerDialog;->updateVolume()V

    return-void
.end method

.method static synthetic access$300(Lcom/android/internal/app/MediaRouteControllerDialog;)Landroid/widget/SeekBar;
    .locals 1
    .param p0, "x0"    # Lcom/android/internal/app/MediaRouteControllerDialog;

    .prologue
    .line 49
    iget-object v0, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mVolumeSlider:Landroid/widget/SeekBar;

    return-object v0
.end method

.method static synthetic access$400(Lcom/android/internal/app/MediaRouteControllerDialog;)Landroid/media/MediaRouter$RouteInfo;
    .locals 1
    .param p0, "x0"    # Lcom/android/internal/app/MediaRouteControllerDialog;

    .prologue
    .line 49
    iget-object v0, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mRoute:Landroid/media/MediaRouter$RouteInfo;

    return-object v0
.end method

.method static synthetic access$500(Lcom/android/internal/app/MediaRouteControllerDialog;)Z
    .locals 1
    .param p0, "x0"    # Lcom/android/internal/app/MediaRouteControllerDialog;

    .prologue
    .line 49
    iget-boolean v0, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mIsWfd:Z

    return v0
.end method

.method static synthetic access$600(Lcom/android/internal/app/MediaRouteControllerDialog;)Landroid/media/MediaRouter;
    .locals 1
    .param p0, "x0"    # Lcom/android/internal/app/MediaRouteControllerDialog;

    .prologue
    .line 49
    iget-object v0, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mRouter:Landroid/media/MediaRouter;

    return-object v0
.end method

.method static synthetic access$700(Lcom/android/internal/app/MediaRouteControllerDialog;)Z
    .locals 1
    .param p0, "x0"    # Lcom/android/internal/app/MediaRouteControllerDialog;

    .prologue
    .line 49
    invoke-direct {p0}, Lcom/android/internal/app/MediaRouteControllerDialog;->update()Z

    move-result v0

    return v0
.end method

.method private getIconDrawable()Landroid/graphics/drawable/Drawable;
    .locals 2

    .prologue
    .line 304
    iget-object v0, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mRoute:Landroid/media/MediaRouter$RouteInfo;

    invoke-virtual {v0}, Landroid/media/MediaRouter$RouteInfo;->isConnecting()Z

    move-result v0

    if-eqz v0, :cond_1

    .line 305
    iget-object v0, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mMediaRouteConnectingDrawable:Landroid/graphics/drawable/Drawable;

    if-nez v0, :cond_0

    .line 306
    invoke-virtual {p0}, Lcom/android/internal/app/MediaRouteControllerDialog;->getContext()Landroid/content/Context;

    move-result-object v0

    invoke-virtual {v0}, Landroid/content/Context;->getResources()Landroid/content/res/Resources;

    move-result-object v0

    const v1, 0x1080354

    invoke-virtual {v0, v1}, Landroid/content/res/Resources;->getDrawable(I)Landroid/graphics/drawable/Drawable;

    move-result-object v0

    iput-object v0, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mMediaRouteConnectingDrawable:Landroid/graphics/drawable/Drawable;

    .line 309
    :cond_0
    iget-object v0, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mMediaRouteConnectingDrawable:Landroid/graphics/drawable/Drawable;

    .line 315
    :goto_0
    return-object v0

    .line 311
    :cond_1
    iget-object v0, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mMediaRouteOnDrawable:Landroid/graphics/drawable/Drawable;

    if-nez v0, :cond_2

    .line 312
    invoke-virtual {p0}, Lcom/android/internal/app/MediaRouteControllerDialog;->getContext()Landroid/content/Context;

    move-result-object v0

    invoke-virtual {v0}, Landroid/content/Context;->getResources()Landroid/content/res/Resources;

    move-result-object v0

    const v1, 0x1080362

    invoke-virtual {v0, v1}, Landroid/content/res/Resources;->getDrawable(I)Landroid/graphics/drawable/Drawable;

    move-result-object v0

    iput-object v0, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mMediaRouteOnDrawable:Landroid/graphics/drawable/Drawable;

    .line 315
    :cond_2
    iget-object v0, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mMediaRouteOnDrawable:Landroid/graphics/drawable/Drawable;

    goto :goto_0
.end method

.method private isVolumeControlAvailable()Z
    .locals 2

    .prologue
    const/4 v0, 0x1

    .line 332
    iget-boolean v1, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mVolumeControlEnabled:Z

    if-eqz v1, :cond_0

    iget-object v1, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mRoute:Landroid/media/MediaRouter$RouteInfo;

    invoke-virtual {v1}, Landroid/media/MediaRouter$RouteInfo;->getVolumeHandling()I

    move-result v1

    if-ne v1, v0, :cond_0

    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method

.method private update()Z
    .locals 4

    .prologue
    const/4 v2, 0x0

    .line 278
    iget-boolean v3, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mIsWfd:Z

    if-eqz v3, :cond_0

    .line 279
    iget-object v3, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mRoute:Landroid/media/MediaRouter$RouteInfo;

    invoke-virtual {v3}, Landroid/media/MediaRouter$RouteInfo;->getStatusCode()I

    move-result v1

    .line 280
    .local v1, "status":I
    const/4 v3, 0x2

    if-eq v1, v3, :cond_2

    const/4 v3, 0x6

    if-eq v1, v3, :cond_2

    .line 282
    invoke-virtual {p0}, Lcom/android/internal/app/MediaRouteControllerDialog;->dismiss()V

    .line 300
    .end local v1    # "status":I
    :goto_0
    return v2

    .line 287
    :cond_0
    iget-object v3, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mRoute:Landroid/media/MediaRouter$RouteInfo;

    invoke-virtual {v3}, Landroid/media/MediaRouter$RouteInfo;->isSelected()Z

    move-result v3

    if-eqz v3, :cond_1

    iget-object v3, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mRoute:Landroid/media/MediaRouter$RouteInfo;

    invoke-virtual {v3}, Landroid/media/MediaRouter$RouteInfo;->isDefault()Z

    move-result v3

    if-eqz v3, :cond_2

    .line 288
    :cond_1
    invoke-virtual {p0}, Lcom/android/internal/app/MediaRouteControllerDialog;->dismiss()V

    goto :goto_0

    .line 292
    :cond_2
    iget-object v2, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mRoute:Landroid/media/MediaRouter$RouteInfo;

    invoke-virtual {v2}, Landroid/media/MediaRouter$RouteInfo;->getName()Ljava/lang/CharSequence;

    move-result-object v2

    invoke-virtual {p0, v2}, Lcom/android/internal/app/MediaRouteControllerDialog;->setTitle(Ljava/lang/CharSequence;)V

    .line 293
    invoke-direct {p0}, Lcom/android/internal/app/MediaRouteControllerDialog;->updateVolume()V

    .line 295
    invoke-direct {p0}, Lcom/android/internal/app/MediaRouteControllerDialog;->getIconDrawable()Landroid/graphics/drawable/Drawable;

    move-result-object v0

    .line 296
    .local v0, "icon":Landroid/graphics/drawable/Drawable;
    iget-object v2, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mCurrentIconDrawable:Landroid/graphics/drawable/Drawable;

    if-eq v0, v2, :cond_3

    .line 297
    iput-object v0, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mCurrentIconDrawable:Landroid/graphics/drawable/Drawable;

    .line 298
    invoke-virtual {p0}, Lcom/android/internal/app/MediaRouteControllerDialog;->getWindow()Landroid/view/Window;

    move-result-object v2

    const/4 v3, 0x3

    invoke-virtual {v2, v3, v0}, Landroid/view/Window;->setFeatureDrawable(ILandroid/graphics/drawable/Drawable;)V

    .line 300
    :cond_3
    const/4 v2, 0x1

    goto :goto_0
.end method

.method private updateVolume()V
    .locals 2

    .prologue
    .line 320
    iget-boolean v0, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mVolumeSliderTouched:Z

    if-nez v0, :cond_0

    .line 321
    invoke-direct {p0}, Lcom/android/internal/app/MediaRouteControllerDialog;->isVolumeControlAvailable()Z

    move-result v0

    if-eqz v0, :cond_1

    .line 322
    iget-object v0, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mVolumeLayout:Landroid/widget/LinearLayout;

    const/4 v1, 0x0

    invoke-virtual {v0, v1}, Landroid/widget/LinearLayout;->setVisibility(I)V

    .line 323
    iget-object v0, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mVolumeSlider:Landroid/widget/SeekBar;

    iget-object v1, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mRoute:Landroid/media/MediaRouter$RouteInfo;

    invoke-virtual {v1}, Landroid/media/MediaRouter$RouteInfo;->getVolumeMax()I

    move-result v1

    invoke-virtual {v0, v1}, Landroid/widget/SeekBar;->setMax(I)V

    .line 324
    iget-object v0, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mVolumeSlider:Landroid/widget/SeekBar;

    iget-object v1, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mRoute:Landroid/media/MediaRouter$RouteInfo;

    invoke-virtual {v1}, Landroid/media/MediaRouter$RouteInfo;->getVolume()I

    move-result v1

    invoke-virtual {v0, v1}, Landroid/widget/SeekBar;->setProgress(I)V

    .line 329
    :cond_0
    :goto_0
    return-void

    .line 326
    :cond_1
    iget-object v0, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mVolumeLayout:Landroid/widget/LinearLayout;

    const/16 v1, 0x8

    invoke-virtual {v0, v1}, Landroid/widget/LinearLayout;->setVisibility(I)V

    goto :goto_0
.end method

# virtual methods
.method public getMediaControlView()Landroid/view/View;
    .locals 1

    .prologue
    .line 134
    iget-object v0, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mControlView:Landroid/view/View;

    return-object v0
.end method

.method public getRoute()Landroid/media/MediaRouter$RouteInfo;
    .locals 1

    .prologue
    .line 113
    iget-object v0, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mRoute:Landroid/media/MediaRouter$RouteInfo;

    return-object v0
.end method

.method public isVolumeControlEnabled()Z
    .locals 1

    .prologue
    .line 158
    iget-boolean v0, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mVolumeControlEnabled:Z

    return v0
.end method

.method public onAttachedToWindow()V
    .locals 4

    .prologue
    .line 244
    invoke-super {p0}, Landroid/app/Dialog;->onAttachedToWindow()V

    .line 246
    iget-object v0, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mRouter:Landroid/media/MediaRouter;

    const/4 v1, 0x0

    iget-object v2, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mCallback:Lcom/android/internal/app/MediaRouteControllerDialog$MediaRouterCallback;

    const/4 v3, 0x2

    invoke-virtual {v0, v1, v2, v3}, Landroid/media/MediaRouter;->addCallback(ILandroid/media/MediaRouter$Callback;I)V

    .line 247
    invoke-direct {p0}, Lcom/android/internal/app/MediaRouteControllerDialog;->update()Z

    .line 248
    return-void
.end method

.method protected onCreate(Landroid/os/Bundle;)V
    .locals 3
    .param p1, "savedInstanceState"    # Landroid/os/Bundle;

    .prologue
    .line 163
    invoke-super {p0, p1}, Landroid/app/Dialog;->onCreate(Landroid/os/Bundle;)V

    .line 165
    invoke-virtual {p0}, Lcom/android/internal/app/MediaRouteControllerDialog;->getWindow()Landroid/view/Window;

    move-result-object v1

    const/4 v2, 0x3

    invoke-virtual {v1, v2}, Landroid/view/Window;->requestFeature(I)Z

    .line 167
    const v1, 0x1090063

    invoke-virtual {p0, v1}, Lcom/android/internal/app/MediaRouteControllerDialog;->setContentView(I)V

    .line 169
    const v1, 0x102030c

    invoke-virtual {p0, v1}, Lcom/android/internal/app/MediaRouteControllerDialog;->findViewById(I)Landroid/view/View;

    move-result-object v1

    check-cast v1, Landroid/widget/LinearLayout;

    iput-object v1, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mVolumeLayout:Landroid/widget/LinearLayout;

    .line 170
    const v1, 0x102030d

    invoke-virtual {p0, v1}, Lcom/android/internal/app/MediaRouteControllerDialog;->findViewById(I)Landroid/view/View;

    move-result-object v1

    check-cast v1, Landroid/widget/SeekBar;

    iput-object v1, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mVolumeSlider:Landroid/widget/SeekBar;

    .line 171
    iget-object v1, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mVolumeSlider:Landroid/widget/SeekBar;

    new-instance v2, Lcom/android/internal/app/MediaRouteControllerDialog$1;

    invoke-direct {v2, p0}, Lcom/android/internal/app/MediaRouteControllerDialog$1;-><init>(Lcom/android/internal/app/MediaRouteControllerDialog;)V

    invoke-virtual {v1, v2}, Landroid/widget/SeekBar;->setOnSeekBarChangeListener(Landroid/widget/SeekBar$OnSeekBarChangeListener;)V

    .line 207
    const v1, 0x102030f

    invoke-virtual {p0, v1}, Lcom/android/internal/app/MediaRouteControllerDialog;->findViewById(I)Landroid/view/View;

    move-result-object v1

    check-cast v1, Landroid/widget/Button;

    iput-object v1, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mDisconnectButton:Landroid/widget/Button;

    .line 208
    iget-object v1, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mDisconnectButton:Landroid/widget/Button;

    new-instance v2, Lcom/android/internal/app/MediaRouteControllerDialog$2;

    invoke-direct {v2, p0}, Lcom/android/internal/app/MediaRouteControllerDialog$2;-><init>(Lcom/android/internal/app/MediaRouteControllerDialog;)V

    invoke-virtual {v1, v2}, Landroid/widget/Button;->setOnClickListener(Landroid/view/View$OnClickListener;)V

    .line 227
    const/4 v1, 0x1

    iput-boolean v1, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mCreated:Z

    .line 228
    invoke-direct {p0}, Lcom/android/internal/app/MediaRouteControllerDialog;->update()Z

    move-result v1

    if-eqz v1, :cond_0

    .line 229
    invoke-virtual {p0, p1}, Lcom/android/internal/app/MediaRouteControllerDialog;->onCreateMediaControlView(Landroid/os/Bundle;)Landroid/view/View;

    move-result-object v1

    iput-object v1, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mControlView:Landroid/view/View;

    .line 230
    const v1, 0x102030e

    invoke-virtual {p0, v1}, Lcom/android/internal/app/MediaRouteControllerDialog;->findViewById(I)Landroid/view/View;

    move-result-object v0

    check-cast v0, Landroid/widget/FrameLayout;

    .line 232
    .local v0, "controlFrame":Landroid/widget/FrameLayout;
    iget-object v1, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mControlView:Landroid/view/View;

    if-eqz v1, :cond_1

    .line 233
    iget-object v1, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mControlView:Landroid/view/View;

    invoke-virtual {v0, v1}, Landroid/widget/FrameLayout;->addView(Landroid/view/View;)V

    .line 234
    const/4 v1, 0x0

    invoke-virtual {v0, v1}, Landroid/widget/FrameLayout;->setVisibility(I)V

    .line 239
    .end local v0    # "controlFrame":Landroid/widget/FrameLayout;
    :cond_0
    :goto_0
    return-void

    .line 236
    .restart local v0    # "controlFrame":Landroid/widget/FrameLayout;
    :cond_1
    const/16 v1, 0x8

    invoke-virtual {v0, v1}, Landroid/widget/FrameLayout;->setVisibility(I)V

    goto :goto_0
.end method

.method public onCreateMediaControlView(Landroid/os/Bundle;)Landroid/view/View;
    .locals 1
    .param p1, "savedInstanceState"    # Landroid/os/Bundle;

    .prologue
    .line 125
    const/4 v0, 0x0

    return-object v0
.end method

.method public onDetachedFromWindow()V
    .locals 2

    .prologue
    .line 252
    iget-object v0, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mRouter:Landroid/media/MediaRouter;

    iget-object v1, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mCallback:Lcom/android/internal/app/MediaRouteControllerDialog$MediaRouterCallback;

    invoke-virtual {v0, v1}, Landroid/media/MediaRouter;->removeCallback(Landroid/media/MediaRouter$Callback;)V

    .line 254
    invoke-super {p0}, Landroid/app/Dialog;->onDetachedFromWindow()V

    .line 255
    return-void
.end method

.method public onKeyDown(ILandroid/view/KeyEvent;)Z
    .locals 4
    .param p1, "keyCode"    # I
    .param p2, "event"    # Landroid/view/KeyEvent;

    .prologue
    const/16 v3, 0x19

    const/4 v1, 0x1

    .line 259
    if-eq p1, v3, :cond_0

    const/16 v0, 0x18

    if-ne p1, v0, :cond_2

    .line 261
    :cond_0
    iget-object v2, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mRoute:Landroid/media/MediaRouter$RouteInfo;

    if-ne p1, v3, :cond_1

    const/4 v0, -0x1

    :goto_0
    invoke-virtual {v2, v0}, Landroid/media/MediaRouter$RouteInfo;->requestUpdateVolume(I)V

    .line 264
    :goto_1
    return v1

    :cond_1
    move v0, v1

    .line 261
    goto :goto_0

    .line 264
    :cond_2
    invoke-super {p0, p1, p2}, Landroid/app/Dialog;->onKeyDown(ILandroid/view/KeyEvent;)Z

    move-result v1

    goto :goto_1
.end method

.method public onKeyUp(ILandroid/view/KeyEvent;)Z
    .locals 1
    .param p1, "keyCode"    # I
    .param p2, "event"    # Landroid/view/KeyEvent;

    .prologue
    .line 269
    const/16 v0, 0x19

    if-eq p1, v0, :cond_0

    const/16 v0, 0x18

    if-ne p1, v0, :cond_1

    .line 271
    :cond_0
    const/4 v0, 0x1

    .line 273
    :goto_0
    return v0

    :cond_1
    invoke-super {p0, p1, p2}, Landroid/app/Dialog;->onKeyUp(ILandroid/view/KeyEvent;)Z

    move-result v0

    goto :goto_0
.end method

.method public setVolumeControlEnabled(Z)V
    .locals 1
    .param p1, "enable"    # Z

    .prologue
    .line 145
    iget-boolean v0, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mVolumeControlEnabled:Z

    if-eq v0, p1, :cond_0

    .line 146
    iput-boolean p1, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mVolumeControlEnabled:Z

    .line 147
    iget-boolean v0, p0, Lcom/android/internal/app/MediaRouteControllerDialog;->mCreated:Z

    if-eqz v0, :cond_0

    .line 148
    invoke-direct {p0}, Lcom/android/internal/app/MediaRouteControllerDialog;->updateVolume()V

    .line 151
    :cond_0
    return-void
.end method


text:
<?xml version="1.0" encoding="UTF-8" ?>
<formData>
    <id required="true" type="number"/>
    <dir condition="=" requiredIf="formData.classifier" type="directory" value="efwd"/>
    <type required="true" type="text"/>
    <classifier required="true" type="text"/>

    <jsFunction name="validate" language="groovy"><![CDATA[
		import net.sf.json.JSONObject;

		def JSONObject validate(JSONObject requestJson, JSONObject responseJson) {
			if (requestJson.isEmpty() || !requestJson.has("classifier")) {
				responseJson.put("classifier", "The required key 'classifier' is missing in formData")
				return responseJson;
			}

            if (requestJson.getString("classifier").equalsIgnoreCase("efwd") && !requestJson.has("dir")) {
                responseJson.put("dir", "The required key 'dir' is missing in formData when classifier is efwd")
                return responseJson;
            }

            return responseJson;
		}
	 ]]>
    </jsFunction>
</formData>

redpajama_set_name: RedPajamaGithub


text:
/*
 * The Plaid API
 * The Plaid REST API. Please see https://plaid.com/docs/api for more details.
 *
 * The version of the OpenAPI document: 2020-09-14_1.205.3
 *
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

package com.plaid.client.model;

import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.plaid.client.model.Asset;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * No documentation available
 */
@ApiModel(description = "No documentation available")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2022-11-17T17:52:41.932844Z[Etc/UTC]")
public class Assets {
  public static final String SERIALIZED_NAME_A_S_S_E_T = "ASSET";
  @SerializedName(SERIALIZED_NAME_A_S_S_E_T)
  private List<Asset> ASSET = new ArrayList<>();

  public Assets ASSET(List<Asset> ASSET) {

    this.ASSET = ASSET;
    return this;
  }

  public Assets addASSETItem(Asset ASSETItem) {
    this.ASSET.add(ASSETItem);
    return this;
  }

   /**
   * No documentation available
   * @return ASSET
  **/
  @ApiModelProperty(required = true, value = "No documentation available")

  public List<Asset> getASSET() {
    return ASSET;
  }

  public void setASSET(List<Asset> ASSET) {
    this.ASSET = ASSET;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    Assets assets = (Assets) o;
    return Objects.equals(this.ASSET, assets.ASSET);
  }

  @Override
  public int hashCode() {
    return Objects.hash(ASSET);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class Assets {\n");
    sb.append("    ASSET: ").append(toIndentedString(ASSET)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }

}


text:
from fabric.api import run, cd, prefix

def restart():
    """Restart the development env"""
    with cd('/www/finepy'):
        with prefix('source venv/bin/activate'):
            run('sudo venv/bin/supervisorctl restart finepy')

def restart_local():
    """Restart the development env"""
    with cd('/opt/www/finepy'):
        with prefix('source ../venv/bin/activate'):
            run('../venv/bin/supervisorctl restart finepy')

if __name__ == "__main__":
    restart()


text:
CKEDITOR.plugins.setLang( 'selectall', 'en-au', {
	toolbar: 'Select All'
} );


text:
from django.db import models

from country.models import Country

class Region(models.Model):
    """
    Region in country.
    """
    name = models.CharField(max_length=128, null=False, blank=False, db_index=True)
    display_name = models.CharField(max_length=128, null=False, blank=False)
    active = models.BooleanField(default=True, null=False)
    parent = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, default=None, related_name='sub_regions')
    country = models.ForeignKey(Country, on_delete=models.PROTECT, related_name='regions')

    def save(self, **kwargs):
        self.name = self.name.lower()
        super().save(**kwargs)

    def __repr__(self):
        return "Region: id={0}, " \
               "name={1}, " \
               "display_name={2}, " \
               "active={3}, " \
               "parent={4}, "\
               "country={5}".format(self.id, self.name, self.display_name,
                                    self.active, self.parent_id, self.country_id)


text:
SYNONYM

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

#### Published in
Revta R. Acad. Cienc. exact. fis. nat. Madr. 14: 581 (1916)

#### Original name
Hemidiscia prunorum Lázaro Ibiza, 1916

### Remarks
null


text:
import React          from 'react';
import { connect }    from 'react-redux';
import counterActions from 'actions/counter';
import { Link }       from 'react-router';
import styles         from './HomeView.scss';

// We define mapStateToProps where we'd normally use
// the @connect decorator so the data requirements are clear upfront, but then
// export the decorated component after the main class definition so
// the component can be tested w/ and w/o being connected.
// See: http://rackt.github.io/redux/docs/recipes/WritingTests.html
const mapStateToProps = (state) => ({
  counter : state.counter
});
export class HomeView extends React.Component {
  static propTypes = {
    increment : React.PropTypes.func,
    counter   : React.PropTypes.number
  }

  render () {
    return (

Welcome to the React Redux Starter Kit

          Sample Counter:
          {this.props.counter}

        <button className='btn btn-default'
                onClick={this.props.increment}>
          Increment
        </button>

        <Link to='/about'>Go To About View</Link>

    );
  }
}

export default connect(mapStateToProps, counterActions)(HomeView);


text:
package com.bol.openapi;

import com.bol.api.openapi_4_0.Pong;

public class OpenApiClient {

    private final OpenApi api;

    public OpenApiClient(OpenApi api) {
        this.api = api;
    }

    public static OpenApiClient withDefaultClient(String key) {
        return new OpenApiClient(OpenApiHttpClient.create(key));
    }

    OpenApi getApi() {
        return api;
    }

    public HealthStatus getHealthStatus() {
        try {
            Pong pong = api.ping();
            return HealthStatus.builder().isHealthy();
        } catch (RuntimeException ex) {
            return HealthStatus.builder().isUnhealthy(ex.getMessage());
        }
    }

    public SearchBuilder searchBuilder() {
        return new SearchBuilder(this);
    }

    public ListBuilder listBuilder() {
        return new ListBuilder(this);
    }
}


text:
package com.pushtorefresh.storio.contentresolver.design;

import android.database.Cursor;
import android.net.Uri;

import com.pushtorefresh.storio.contentresolver.operation.get.GetResolver;
import com.pushtorefresh.storio.contentresolver.query.Query;

import org.junit.Test;

import java.util.List;

import static org.mockito.Mockito.mock;

public class GetOperationDesignTest extends OperationDesignTest {

    @SuppressWarnings("unchecked")
    @Test
    public void getCursorBlocking() {
        Cursor cursor = storIOContentResolver()
                .get()
                .cursor()
                .withQuery(new Query.Builder()
                        .uri(mock(Uri.class))
                        .build())
                .withGetResolver(mock(GetResolver.class))
                .prepare()
                .executeAsBlocking();
    }

    @Test
    public void getListOfObjectsBlocking() {
        List<Article> articles = storIOContentResolver()
                .get()
                .listOfObjects(Article.class)
                .withQuery(mock(Query.class))
                .withGetResolver(ArticleMeta.GET_RESOLVER)
                .prepare()
                .executeAsBlocking();
    }
}


text:
#region Copyright
//
// DotNetNuke® - http://www.dotnetnuke.com
// Copyright (c) 2002-2014
// by DotNetNuke Corporation
//
// 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.
#endregion
using System;
using System.Globalization;

using DotNetNuke.Common;
using DotNetNuke.Common.Internal;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Users;
using DotNetNuke.UI.Modules;

namespace DotNetNuke.Web.Mvp
{
    public abstract class ProfileModuleViewBase<TModel> : ModuleView<TModel>, IProfileModule where TModel : class, new()
    {
        #region IProfileModule Members

        public abstract bool DisplayModule { get; }

        public int ProfileUserId
        {
            get
            {
                int UserId = Null.NullInteger;
                if (!string.IsNullOrEmpty(Request.Params["UserId"]))
                {
                    UserId = Int32.Parse(Request.Params["UserId"]);
                }
                return UserId;
            }
        }

        #endregion

        #region Protected Properties

        protected bool IsUser
        {
            get
            {
                return ProfileUserId == ModuleContext.PortalSettings.UserId;
            }
        }

        protected UserInfo ProfileUser
        {
            get { return UserController.GetUserById(ModuleContext.PortalId, ProfileUserId); }
        }

        #endregion

        #region Private Methods

        private string GetRedirectUrl()
        {
            //redirect user to default page if not specific the home tab, do this action to prevent loop redirect.
            var homeTabId = ModuleContext.PortalSettings.HomeTabId;
            string redirectUrl;

            if (homeTabId > Null.NullInteger)
            {
                redirectUrl = TestableGlobals.Instance.NavigateURL(homeTabId);
            }
            else
            {
                redirectUrl = TestableGlobals.Instance.GetPortalDomainName(PortalSettings.Current.PortalAlias.HTTPAlias, Request, true) + "/" + Globals.glbDefaultPage;
            }

            return redirectUrl;
        }

        #endregion

        #region Protected Methods

        protected override void OnInit(EventArgs e)
        {
            if (ProfileUserId == Null.NullInteger &&
                            (ModuleContext.PortalSettings.ActiveTab.TabID == ModuleContext.PortalSettings.UserTabId
                                || ModuleContext.PortalSettings.ActiveTab.ParentId == ModuleContext.PortalSettings.UserTabId))
            {
                //Clicked on breadcrumb - don't know which user
                Response.Redirect(Request.IsAuthenticated
                                      ? Globals.NavigateURL(ModuleContext.PortalSettings.ActiveTab.TabID, "", "UserId=" + ModuleContext.PortalSettings.UserId.ToString(CultureInfo.InvariantCulture))
                                      : GetRedirectUrl(), true);
            }

            base.OnInit(e);
        }

        #endregion
    }
}


text:
package aurelienribon.utils.io;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author Aurelien Ribon | http://www.aurelienribon.com/
 */
public class HttpUtils {
	public static DownloadTask downloadAsync(URL input, OutputStream output, Callback callback) {
		final DownloadTask task = new DownloadTask(input, output, callback);

		new Thread(new Runnable() {
			@Override public void run() {
				task.download();
			}
		}).start();

		return task;
	}

	public static interface Callback {
		public void completed();
		public void canceled();
		public void error(IOException ex);
		public void updated(int length, int totalLength);
	}

	public static class DownloadTask {
		private final URL input;
		private final OutputStream output;
		private final Callback callback;
		private boolean run = true;

		public DownloadTask(URL input, OutputStream output, Callback callback) {
			this.input = input;
			this.output = output;
			this.callback = callback;
		}

		public void stop() {
			run = false;
		}

		public URL getInput() {
			return input;
		}

		public OutputStream getOutput() {
			return output;
		}

		public Callback getCallback() {
			return callback;
		}

		private void download() {
			OutputStream os = null;
			InputStream is = null;
			IOException ex = null;

			try {
				HttpURLConnection connection = (HttpURLConnection) input.openConnection();
				connection.setDoInput(true);
				connection.setDoOutput(false);
				connection.setUseCaches(true);
				connection.setConnectTimeout(3000);
				connection.connect();

				is = new BufferedInputStream(connection.getInputStream(), 4096);
				os = output;

				byte[] data = new byte[4096];
				int length = connection.getContentLength();
				int total = 0;

				int count;
				while (run && (count = is.read(data)) != -1) {
					total += count;
					os.write(data, 0, count);
					if (callback != null) callback.updated(total, length);
				}

			} catch (IOException ex1) {
				ex = ex1;

			} finally {
				if (os != null) try {os.flush(); os.close();} catch (IOException ex1) {}
				if (is != null) try {is.close();} catch (IOException ex1) {}

				if (callback != null) {
					if (ex != null) callback.error(ex);
					else if (run == true) callback.completed();
					else callback.canceled();
				}
			}
		}
	}
}


text:
use crate::stream::TryStreamExt;
use core::pin::Pin;
use futures_core::stream::TryStream;
use futures_core::task::{Context, Poll};
use futures_io::{AsyncRead, AsyncWrite, AsyncBufRead};
use std::cmp;
use std::io::{Error, Result};

/// Reader for the [`into_async_read`](super::TryStreamExt::into_async_read) method.
#[derive(Debug)]
#[must_use = "readers do nothing unless polled"]
pub struct IntoAsyncRead<St>
where
    St: TryStream<Error = Error> + Unpin,
    St::Ok: AsRef<[u8]>,
{
    stream: St,
    state: ReadState<St::Ok>,
}

impl<St> Unpin for IntoAsyncRead<St>
where
    St: TryStream<Error = Error> + Unpin,
    St::Ok: AsRef<[u8]>,
{
}

#[derive(Debug)]
enum ReadState<T: AsRef<[u8]>> {
    Ready { chunk: T, chunk_start: usize },
    PendingChunk,
    Eof,
}

impl<St> IntoAsyncRead<St>
where
    St: TryStream<Error = Error> + Unpin,
    St::Ok: AsRef<[u8]>,
{
    pub(super) fn new(stream: St) -> Self {
        IntoAsyncRead {
            stream,
            state: ReadState::PendingChunk,
        }
    }
}

impl<St> AsyncRead for IntoAsyncRead<St>
where
    St: TryStream<Error = Error> + Unpin,
    St::Ok: AsRef<[u8]>,
{
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<Result<usize>> {
        loop {
            match &mut self.state {
                ReadState::Ready { chunk, chunk_start } => {
                    let chunk = chunk.as_ref();
                    let len = cmp::min(buf.len(), chunk.len() - *chunk_start);

                    buf[..len].copy_from_slice(
                        &chunk[*chunk_start..*chunk_start + len],
                    );
                    *chunk_start += len;

                    if chunk.len() == *chunk_start {
                        self.state = ReadState::PendingChunk;
                    }

                    return Poll::Ready(Ok(len));
                }
                ReadState::PendingChunk => {
                    match ready!(self.stream.try_poll_next_unpin(cx)) {
                        Some(Ok(chunk)) => {
                            if !chunk.as_ref().is_empty() {
                                self.state = ReadState::Ready {
                                    chunk,
                                    chunk_start: 0,
                                };
                            }
                        }
                        Some(Err(err)) => {
                            self.state = ReadState::Eof;
                            return Poll::Ready(Err(err));
                        }
                        None => {
                            self.state = ReadState::Eof;
                            return Poll::Ready(Ok(0));
                        }
                    }
                }
                ReadState::Eof => {
                    return Poll::Ready(Ok(0));
                }
            }
        }
    }
}

impl<St> AsyncWrite for IntoAsyncRead<St>
where
    St: TryStream<Error = Error> + AsyncWrite + Unpin,
    St::Ok: AsRef<[u8]>,
{
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8]
    ) -> Poll<Result<usize>> {
        Pin::new( &mut self.stream ).poll_write( cx, buf )
    }

    fn poll_flush(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>
    ) -> Poll<Result<()>> {
        Pin::new( &mut self.stream ).poll_flush( cx )
    }

    fn poll_close(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>
    ) -> Poll<Result<()>> {
        Pin::new( &mut self.stream ).poll_close( cx )
    }
}

impl<St> AsyncBufRead for IntoAsyncRead<St>
where
    St: TryStream<Error = Error> + Unpin,
    St::Ok: AsRef<[u8]>,
{
    fn poll_fill_buf(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Result<&[u8]>> {
        while let ReadState::PendingChunk = self.state {
            match ready!(self.stream.try_poll_next_unpin(cx)) {
                Some(Ok(chunk)) => {
                    if !chunk.as_ref().is_empty() {
                        self.state = ReadState::Ready {
                            chunk,
                            chunk_start: 0,
                        };
                    }
                }
                Some(Err(err)) => {
                    self.state = ReadState::Eof;
                    return Poll::Ready(Err(err));
                }
                None => {
                    self.state = ReadState::Eof;
                    return Poll::Ready(Ok(&[]));
                }
            }
        }

        if let ReadState::Ready { ref chunk, chunk_start } = self.into_ref().get_ref().state {
            let chunk = chunk.as_ref();
            return Poll::Ready(Ok(&chunk[chunk_start..]));
        }

        // To get to this point we must be in ReadState::Eof
        Poll::Ready(Ok(&[]))
    }

    fn consume(
        mut self: Pin<&mut Self>,
        amount: usize,
    ) {
         // https://github.com/rust-lang-nursery/futures-rs/pull/1556#discussion_r281644295
        if amount == 0 { return }
        if let ReadState::Ready { chunk, chunk_start } = &mut self.state {
            *chunk_start += amount;
            debug_assert!(*chunk_start <= chunk.as_ref().len());
            if *chunk_start >= chunk.as_ref().len() {
                self.state = ReadState::PendingChunk;
            }
        } else {
            debug_assert!(false, "Attempted to consume from IntoAsyncRead without chunk");
        }
    }
}


text:
package org.apache.dubbo.common.convert.multiple;

import org.apache.dubbo.common.utils.CollectionUtils;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.NavigableSet;
import java.util.Queue;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.TransferQueue;

import static java.util.Arrays.asList;
import static org.apache.dubbo.common.extension.ExtensionLoader.getExtensionLoader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
 * {@link StringToSortedSetConverter} Test
 *
 * @since 2.7.6
 */
public class StringToSortedSetConverterTest {

    private MultiValueConverter converter;

    @BeforeEach
    public void init() {
        converter = getExtensionLoader(MultiValueConverter.class).getExtension("string-to-sorted-set");
    }

    @Test
    public void testAccept() {

        assertFalse(converter.accept(String.class, Collection.class));

        assertFalse(converter.accept(String.class, List.class));
        assertFalse(converter.accept(String.class, AbstractList.class));
        assertFalse(converter.accept(String.class, LinkedList.class));
        assertFalse(converter.accept(String.class, ArrayList.class));

        assertFalse(converter.accept(String.class, Set.class));
        assertTrue(converter.accept(String.class, SortedSet.class));
        assertTrue(converter.accept(String.class, NavigableSet.class));
        assertTrue(converter.accept(String.class, TreeSet.class));
        assertTrue(converter.accept(String.class, ConcurrentSkipListSet.class));

        assertFalse(converter.accept(String.class, Queue.class));
        assertFalse(converter.accept(String.class, BlockingQueue.class));
        assertFalse(converter.accept(String.class, TransferQueue.class));
        assertFalse(converter.accept(String.class, Deque.class));
        assertFalse(converter.accept(String.class, BlockingDeque.class));

        assertFalse(converter.accept(null, char[].class));
        assertFalse(converter.accept(null, String.class));
        assertFalse(converter.accept(null, String.class));
        assertFalse(converter.accept(null, null));
    }

    @Test
    public void testConvert() {

        Set values = new TreeSet(asList(1, 2, 3));

        SortedSet result = (SortedSet) converter.convert("1,2,3", List.class, Integer.class);

        assertTrue(CollectionUtils.equals(values, result));

        values = new TreeSet(asList("123"));

        result = (SortedSet) converter.convert("123", NavigableSet.class, String.class);

        assertTrue(CollectionUtils.equals(values, result));

        assertNull(converter.convert(null, Collection.class, Integer.class));
        assertNull(converter.convert("", Collection.class, null));
    }

    @Test
    public void testGetSourceType() {
        assertEquals(String.class, converter.getSourceType());
    }

    @Test
    public void testGetPriority() {
        assertEquals(Integer.MAX_VALUE - 3, converter.getPriority());
    }
}


text:
// Header for CToolbarItem class

#ifndef __CTOOLBARITEM__MULBERRY__
#define __CTOOLBARITEM__MULBERRY__

//typedef	CommandT CCommandID;

#include "cdstring.h"
#include "ptrvector.h"

// Classes
class CToolbarItem
{
public:
	class CToolbarItemInfo
	{
	public:
		CToolbarItemInfo(const CToolbarItem* item, const cdstring& extra = cdstring::null_str)
		{
			mItem = item;
			mExtraInfo = extra;
		}
		CToolbarItemInfo(const CToolbarItemInfo& copy)
			{ _copy(copy); }
		~CToolbarItemInfo() {}

		CToolbarItemInfo& operator=(const CToolbarItemInfo& copy)					// Assignment with same type
			{ if (this != &copy) _copy(copy); return *this; }

		const CToolbarItem* GetItem() const
			{ return mItem; }

		const cdstring& GetExtraInfo() const
			{ return mExtraInfo; }
		void SetExtraInfo(const cdstring& extra)
			{ mExtraInfo = extra; }

	private:
		const CToolbarItem*	mItem;
		cdstring			mExtraInfo;

		void _copy(const CToolbarItemInfo& copy)
		{ mItem = copy.mItem;
		  mExtraInfo = copy.mExtraInfo; }
	};

	typedef ptrvector<CToolbarItem> CToolbarItems;
	typedef std::vector<CToolbarItemInfo> CToolbarPtrItems;

	enum EItemType
	{
		eNone = 0,
		eSeparator,
		eSpace,
		eExpandSpace,
		ePushButton,
		eToggleButton,
		ePopupButton,
		ePopupPushButton,
		ePopupToggleButton,
		ePopupMenu,
		eStaticText,
		eEditText,
		eStaticIcon,

		// Special-case items
		eCabinetButton,
		eCopyToButton,
		eSelectButton,
		eSMTPAccountPopup
	};

	struct SToolbarItem
	{
		EItemType		mType;
		unsigned long	mTitleID;
		bool			mDynamicTitle;
		unsigned long	mIconID;
		bool			mToggleIcon;
		unsigned long	mCommand;
		unsigned long	mAltCommand;
		unsigned long	mMenuCommand;
		unsigned long	mMenuAltCommand;
		unsigned long	mPopupMenu;
	};

	CToolbarItem(const SToolbarItem& details)
		: mType(details.mType), mTitleID(details.mTitleID), mDynamicTitle(details.mDynamicTitle), mIconID(details.mIconID), mToggleIcon(details.mToggleIcon),
			mCommand(details.mCommand), mAltCommand(details.mAltCommand), mMenuCommand(details.mMenuCommand), mMenuAltCommand(details.mMenuAltCommand), mPopupMenu(details.mPopupMenu) {}
	CToolbarItem(const CToolbarItem& copy)
		{ _copy(copy); }
	~CToolbarItem() {}

	CToolbarItem& operator=(const CToolbarItem& copy)					// Assignment with same type
		{ if (this != &copy) _copy(copy); return *this; }

	EItemType GetType() const
		{ return mType; }
	unsigned long GetTitleID() const
		{ return mTitleID; }
	bool IsDynamicTitle() const
		{ return mDynamicTitle; }
	unsigned long GetIconID() const
		{ return mIconID; }
	bool IsToggleIcon() const
		{ return mToggleIcon; }
	unsigned long GetCommand() const
		{ return mCommand; }
	unsigned long GetAltCommand() const
		{ return mAltCommand; }
	unsigned long GetMenuCommand() const
		{ return mMenuCommand; }
	unsigned long GetMenuAltCommand() const
		{ return mMenuAltCommand; }
	unsigned long GetPopupMenu() const
		{ return mPopupMenu; }

protected:
	EItemType		mType;
	unsigned long	mTitleID;
	bool			mDynamicTitle;
	unsigned long	mIconID;
	bool			mToggleIcon;
	unsigned long	mCommand;
	unsigned long	mAltCommand;
	unsigned long	mMenuCommand;
	unsigned long	mMenuAltCommand;
	unsigned long	mPopupMenu;

private:
	void _copy(const CToolbarItem& copy)
	{ mType = copy.mType;
	  mTitleID = copy.mTitleID;
	  mDynamicTitle = copy.mDynamicTitle;
	  mIconID = copy.mIconID;
	  mToggleIcon = copy.mToggleIcon;
	  mCommand = copy.mCommand;
	  mAltCommand = copy.mAltCommand;
	  mMenuCommand = copy.mMenuCommand;
	  mMenuAltCommand = copy.mMenuAltCommand;
	  mPopupMenu = copy.mPopupMenu; }
};

#endif


text:
import React from 'react';
import Navigation from './Navigation';
import Link from '../Link/Link';

class Header extends React.Component {

  render() {
    return (

 (this.root = node)}>

                <Link className="nav-item" to="/">
                  Tabula
                </Link>

              <Navigation />

    );
  }

}

export default Header;


text:
var stringifyBody = require('../stringifier/one-time').body;
var stringifySelectors = require('../stringifier/one-time').selectors;

function removeDuplicates(tokens) {
  var matched = {};
  var moreThanOnce = [];
  var id, token;
  var body, bodies;

  for (var i = 0, l = tokens.length; i < l; i++) {
    token = tokens[i];
    if (token[0] != 'selector')
      continue;

    id = stringifySelectors(token[1]);

    if (matched[id] && matched[id].length == 1)
      moreThanOnce.push(id);
    else
      matched[id] = matched[id] || [];

    matched[id].push(i);
  }

  for (i = 0, l = moreThanOnce.length; i < l; i++) {
    id = moreThanOnce[i];
    bodies = [];

    for (var j = matched[id].length - 1; j >= 0; j--) {
      token = tokens[matched[id][j]];
      body = stringifyBody(token[2]);

      if (bodies.indexOf(body) > -1)
        token[2] = [];
      else
        bodies.push(body);
    }
  }
}

module.exports = removeDuplicates;


text:
  A Simple Reactive Form showing the usage of formControlName, formGroup with validation.

<form (ngSubmit) = "handleUserData()" novalidate [formGroup] = "r2Group">

        Name:
        <input type="text" class="form-control" name="name" required
            formControlName= "name" />

            Name is required

            Name minimum length should be three characters

        Username:
        <input type="text" class="form-control"
                name="username" required formControlName= "username" />

            Username is required

            Username minimum length should be three characters

            Username maximum length should be 10 characters

        <button type="submit" class="btn btn-primary">submit</button>

 Angular : {{r2Group.value | json}}

</form>


text:
package org.jkiss.dbeaver.core.application.update;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.action.Action;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.IHandlerActivation;
import org.eclipse.ui.handlers.IHandlerService;
import org.jkiss.dbeaver.core.CoreMessages;

public class CheckForUpdateAction extends Action {

    public static final String P2_PLUGIN_ID = "org.eclipse.equinox.p2.ui.sdk";
    public static final String P2_UPDATE_COMMAND = "org.eclipse.equinox.p2.ui.sdk.update";

    private static IHandlerActivation p2UpdateHandlerActivation;

    public CheckForUpdateAction() {
        super(CoreMessages.actions_menu_check_update);
        setId("org.jkiss.dbeaver.action.checkForUpdate");
    }

    @Override
    public void run() {
        new DBeaverVersionChecker(true).schedule();
    }

    public static void deactivateStandardHandler(IWorkbenchWindow window) {
        if (p2UpdateHandlerActivation != null) {
            return;
        }
        IHandlerService srv = window.getService(IHandlerService.class);
        p2UpdateHandlerActivation = srv.activateHandler(CheckForUpdateAction.P2_UPDATE_COMMAND, new AbstractHandler() {
            @Override
            public Object execute(ExecutionEvent event) throws ExecutionException {
                new CheckForUpdateAction().run();
                return null;
            }
        });
    }

    public static void activateStandardHandler(IWorkbenchWindow window) {
        if (p2UpdateHandlerActivation == null) {
            return;
        }
        IHandlerService srv = window.getService(IHandlerService.class);
        srv.deactivateHandler(p2UpdateHandlerActivation);
        p2UpdateHandlerActivation = null;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Governance.TimerJobs.Data;

namespace Governance.TimerJobs.Policy
{
    /// <summary>
    /// AdministratorsPolicy make sure a site collection shoulds have 2 administrators at least
    /// </summary>
    public class AdministratorsPolicy : SitePolicy
    {
        /// <summary>
        /// All site collection record with less than 2 administrators will be selected from DB repository for going thru governance workflow
        /// </summary>
        public override Expression<Func<SiteInformation, bool>> NoncompliancePredictor
        {
            get { return site => site.Administrators.Count() < 2; }
        }

        public override IEnumerable<NoncomplianceType> GetNoncompliances(SiteInformation site)
        {
            if (IsCompliant(site))
                yield break;
            yield return NoncomplianceType.NoAdditionalSiteAdmin;
        }

        /// <summary>
        /// Site collection with 2 or more administrators will be marked as compliant
        /// </summary>
        /// <param name="site">Site information entity</param>
        /// <returns>Returns true if the site collection is compliant, otherwise returns false.</returns>
        public override bool IsCompliant(SiteInformation site)
        {
            return site.Administrators.Count() >= 2;
        }
    }
}


text:
@implementation CDOTestEntityBase

@dynamic id;
@dynamic added;

+ (instancetype)foundryBuildWithContext:(NSManagedObjectContext*)context
{
    id  entity  = [super foundryBuildWithContext:context];

    return entity;
}

+ (NSDictionary*)foundryBuildSpecs
{
    return @{
             @"id"      : @(FoundryPropertyTypeUUID),
             @"added"   : @(FoundryPropertyTypeCustom),
             };
}

+ (id)foundryAttributeForProperty:(NSString*)property
{
    if ([property isEqualToString:@"added"])
    {
        return [NSDate date];
    }

    return nil;
}

@end


text:
//package com.example.android.openbciBLE;
package uk.ac.lancs.scc.openbcible;

import java.util.HashMap;
import java.util.SimpleTimeZone;
import java.util.StringTokenizer;
import java.util.UUID;

/**
 * This class includes a small subset of standard GATT attributes for demonstration purposes.
 */
public class SampleGattAttributes {
    private static HashMap<String, String> attributes = new HashMap();

    //Standard services that may be used to see if other BLEs are visible
    public final static String UUID_GENERIC_DEVICE_SERVICE = "00001800-0000-1000-8000-00805f9b34fb";
    public final static String UUID_DEVICE_NAME = "00002a00-0000-1000-8000-00805f9b34fb";
    public final static String UUID_DEVICE_APPEARANCE = "00002a01-0000-1000-8000-00805f9b34fb";

    //device information service and characteristics
    public final static String UUID_DEVICE_INFORMATION_SERVICE = "0000180a-0000-1000-8000-00805f9b34fb";
    public final static String UUID_MANUFACTURER_NAME = "00002a29-0000-1000-8000-00805f9b34fb";
    public final static String UUID_MODEL_NUMBER = "00002a24-0000-1000-8000-00805f9b34fb";

    //additional one characteristic
    public final static String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb";

    //standard characteristics
    public final static String UUID_HEART_RATE_SERVICE = "0000180d-0000-1000-8000-00805f9b34fb";
    public final static String UUID_HEART_RATE_MEASUREMENT = "00002a37-0000-1000-8000-00805f9b34fb";

    public final static String UUID_BATTERY_SERVICE = "0000180f-0000-1000-8000-00805f9b34fb";
    public final static String UUID_BATTERY_LEVEL = "00002a19-0000-1000-8000-00805f9b34fb";

    //Ganglion Service/Characteristics UUIDs (SIMBLEE Chip Defaults)
    public final static String UUID_GANGLION_SERVICE = "0000fe84-0000-1000-8000-00805f9b34fb";
    public final static String UUID_GANGLION_RECEIVE = "2d30c082-f39f-4ce6-923f-3484ea480596";
    public final static String UUID_GANGLION_SEND = "2d30c083-f39f-4ce6-923f-3484ea480596";
    public final static String UUID_GANGLION_DISCONNECT = "2d30c084-f39f-4ce6-923f-3484ea480596";

    //Cyton Service/Characteristics UUIDs (RFDuino Chip Defaults)
    public final static String UUID_CYTON_SERVICE = "00002220-0000-1000-8000-00805f9b34fb";
    public final static String UUID_CYTON_RECEIVE = "00002221-0000-1000-8000-00805f9b34fb";
    public final static String UUID_CYTON_SEND = "00002222-0000-1000-8000-00805f9b34fb";
    public final static String UUID_CYTON_DISCONNECT = "00002223-0000-1000-8000-00805f9b34fb";

    //Device names
    public final static String DEVICE_NAME_GANGLION = "GANGLION";
    public final static String DEVICE_NAME_CYTON = "CYTON";

    static {
        // Sample Services.
        attributes.put(UUID_GANGLION_SERVICE,    "Ganglion Service (via SIMBLEE)");
        attributes.put(UUID_GANGLION_RECEIVE,    "Ganglion Receive");
        attributes.put(UUID_GANGLION_SEND,       "Ganglion Send");
        attributes.put(UUID_GANGLION_DISCONNECT, "Ganglion Disconnect");

        attributes.put(UUID_CYTON_SERVICE,    "Cyton Service (via RFDuino)");
        attributes.put(UUID_CYTON_RECEIVE,    "Cyton Receive");
        attributes.put(UUID_CYTON_SEND,       "Cyton Send");
        attributes.put(UUID_CYTON_DISCONNECT, "Cyton Disconnect");

        attributes.put(UUID_HEART_RATE_SERVICE, "Heart Rate Service");
        attributes.put(UUID_HEART_RATE_MEASUREMENT, "Heart Rate Measurement");

        attributes.put(UUID_BATTERY_SERVICE, "Battery State Service");
        attributes.put(UUID_BATTERY_LEVEL, "Battery Level");

        attributes.put(UUID_GENERIC_DEVICE_SERVICE, "Generic Access Service");
        attributes.put(UUID_DEVICE_NAME, "Device Name");
        attributes.put(UUID_DEVICE_APPEARANCE,"Appearance");

        attributes.put(UUID_DEVICE_INFORMATION_SERVICE,"Device Information Service");
        attributes.put(UUID_MANUFACTURER_NAME, "Manufacturer Name");
        attributes.put(UUID_MODEL_NUMBER,"Model Number");
    }

    public static String lookup(String uuid, String defaultName) {
        String name = attributes.get(uuid);
        return name == null ? defaultName : name;
    }

    public static String getShortUUID(UUID uuid){
        if(uuid.toString().contains("0000-1000-8000-00805f9b34fb")){
            return uuid.toString().substring(0,7);
        }
        else
            return uuid.toString().substring(0,7)+"...";
    }
}


text:
import { } from 'googlemaps';
import { ActivatedRoute, Router } from '@angular/router';
import { Component, ElementRef, OnInit, NgZone, ViewChild } from '@angular/core';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { FormControl } from '@angular/forms';
import { MapsAPILoader } from '@agm/core';
import { MdDialog, MdDialogRef } from '@angular/material';
import { ToasterService } from 'angular2-toaster';
import { TranslateService } from 'ng2-translate';
import { Observable } from 'rxjs/Rx';

import { CreateTagDialogComponent } from '../../tags/create-tag-dialog/create-tag-dialog.component';
import { ConfigService } from '../../../config.service';
import { Exhibit } from '../shared/exhibit.model';
import { ExhibitService } from '../shared/exhibit.service';
import { MediaService } from '../../media/shared/media.service';
import { Medium } from '../../media/shared/medium.model';
import { SelectMediumDialogComponent } from '../../media/select-medium-dialog/select-medium-dialog.component';
import { Status } from '../../shared/status.model';
import { Tag } from '../../tags/shared/tag.model';
import { TagService } from '../../tags/shared/tag.service';
import { UploadMediumDialogComponent } from '../../media/upload-medium-dialog/upload-medium-dialog.component';
import { ChangeHistoryComponent } from '../../shared/change-history/change-history.component';

@Component({
  moduleId: module.id,
  selector: 'hip-edit-exhibit',
  styleUrls: ['edit-exhibit.component.css'],
  templateUrl: 'edit-exhibit.component.html'
})
export class EditExhibitComponent implements OnInit {
  id: number;
  exhibit = Exhibit.emptyExhibit();
  statusOptions = Status.getValues();
  private tags: Array<object> = [];
  private audioName: string;
  private imageName: string;
  public searchControl: FormControl;
  private selectDialogRef: MdDialogRef<SelectMediumDialogComponent>;
  private uploadDialogRef: MdDialogRef<UploadMediumDialogComponent>;
  private createDialogRef: MdDialogRef<CreateTagDialogComponent>;
  private changeHistoryDialogRef: MdDialogRef<ChangeHistoryComponent>;

  @ViewChild('autosize') autosize: any ;
  @ViewChild('search')
  public searchElementRef: ElementRef;
  previewURL: SafeUrl;
  lat = parseFloat (this.config.get('defaultLatitude'));
  lng = parseFloat (this.config.get('defaultLongitude'));

  constructor(private exhibitService: ExhibitService,
              private mediumService: MediaService,
              private sanitizer: DomSanitizer,
              private tagService: TagService,
              private toasterService: ToasterService,
              private translateService: TranslateService,
              private router: Router,
              private activatedExhibit: ActivatedRoute,
              private mapsAPILoader: MapsAPILoader,
              private ngZone: NgZone,
              private dialog: MdDialog,
              private config: ConfigService) {}

  ngOnInit() {
    let context = this;
    this.id = +this.activatedExhibit.snapshot.params['id'];
    this.exhibitService.getExhibit(this.id)
      .then(
        (response: Exhibit) => {
          this.exhibit = response;
          this.getMediaName();
          this.getTagNames();
          this.updateMap();
          setTimeout(function() { context.autosize.resizeToFitContent(); }, 250);
        }
      ).catch(
        (error: any) => {
          this.toasterService.pop('error', this.getTranslatedString('Error fetching exhibit') , error);
        }
    );
    this.initMapAutocomplete();
  }

  initMapAutocomplete() {
    let context = this;
    this.searchControl = new FormControl();
    this.mapsAPILoader.load().then(() => {
      let autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, {
        types: ['address']
      });
      autocomplete.addListener('place_changed', () => {
        this.ngZone.run(() => {
          // get the place result
          let place: google.maps.places.PlaceResult = autocomplete.getPlace();
          // verify result
          if (place.geometry === undefined || place.geometry === null) {
            return;
          }
            context.lat = place.geometry.location.lat();
            context.lng = place.geometry.location.lng();
        });
      });
    });

  }

  editExhibit(exhibit: Exhibit) {
    if (this.exhibit.latitude) {
      this.exhibit.latitude = this.exhibit.latitude.toString().replace(/,/g, '.');
    }
    if (this.exhibit.longitude) {
      this.exhibit.longitude = this.exhibit.longitude.toString().replace(/,/g, '.');
    }
    this.exhibitService.updateExhibit(this.exhibit)
      .then(
        () => {
          this.handleResponseUpdate();
          setTimeout(() => {
            this.router.navigate(['/mobile-content/exhibits']);
          }, 500);
        }
      ).catch(
        (error: any) => {
          this.toasterService.pop('error', this.getTranslatedString('Error while saving') , error);
        }
      );
  }

  updateData() {
    let temparr = [];
    for (let i = 0; i < this.tags.length; i++ ) {
      temparr.push(this.tags[i]['value']);
    }
    this.exhibit.tags = temparr;
  }

  addMedia() {
    this.uploadDialogRef = this.dialog.open(UploadMediumDialogComponent, {width: '35em'});
    this.uploadDialogRef.afterClosed().subscribe(
      (obj: any) => {
        if (!obj) { return; }

        let newMedium = obj.media;
        let file: File = obj.file;
        if (!newMedium) { return; }

        this.mediumService.postMedia(newMedium)
          .then(
            (res: any) => {
              if (file) {
                return this.mediumService.uploadFile(res, file);
              }
            }
          ).then(
            () => this.toasterService.pop('success', this.translate('media saved'))
          ).catch(
            err => this.toasterService.pop('error', this.translate('Error while saving'), err)
          );
      }
    );
  }

  addTag() {
    this.createDialogRef = this.dialog.open(CreateTagDialogComponent, {width: '45em'});
    this.createDialogRef.afterClosed().subscribe(
      (newTag: Tag) => {
        if (newTag) {
          this.tagService.createTag(newTag)
            .then(
              response => {
                this.toasterService.pop('success', this.translate('tag saved'));
              }
            ).catch(
            error => this.toasterService.pop('error', this.translate('Error while saving'), error)
          );
        }
        this.createDialogRef = null;
      }
    );
  }

  getMediaName() {
    if (!this.exhibit.image) {
      this.imageName = this.getTranslatedString('no image selected');
    } else {
      this.mediumService.getMediaById(this.exhibit.image)
        .then(
          response => {
            this.imageName = response.title;
            this.previewImage(response.id);
          }
        ).catch(
          error => this.toasterService.pop('error', this.translate('Error fetching image'), error)
        );

    }
  }

  previewImage(id: number) {
    // preview image
    this.mediumService.downloadFile(id, true)
      .then(
        (response: any) => {
          let base64Data: string;
          let reader = new FileReader();
          reader.readAsDataURL(response);
          reader.onloadend = () => {
            base64Data = reader.result;
            this.previewURL = this.sanitizer.bypassSecurityTrustUrl(base64Data);
          };
        }
      );
  }

  getTagNames() {
    let tagArray = '';
    for (let i = 0; i < this.exhibit.tags.length; i++ ) {
      tagArray = tagArray + '&IncludeOnly=' + this.exhibit.tags[i] + '&';
    }
    this.tagService.getAllTags(1, 50, 'ALL', '', 'id', tagArray).then(
      response => {
        for (let tag of this.exhibit.tags) {
          let index = response.items.map(function(x: Tag) {return x.id; }).indexOf(tag);
          let tagElement = {display: response.items[index].title, value: tag};
          this.tags.push( tagElement );
        }
      }
    ).catch(
      error => this.toasterService.pop('error', this.getTranslatedString('Error while saving'), error)
    );
  }

  requestAutoCompleteItems = (search: string): Observable<Array<object>> => {
    return Observable.fromPromise(this.tagService.getAllTags(1, 50, 'PUBLISHED', search)
      .then(
        data => {
          let tags = data.items;
          let returnData = [];
          for (let tag of tags) {
            let tagElement = {display: tag.title, value: tag.id};
            returnData.push( tagElement );
          }
          return returnData;
        }
      )
    );
  }

  getTranslatedString(data: any) {
    let translatedResponse: string;
    this.translateService.get(data).subscribe(
      (value: string) => {
        translatedResponse = value;
      }
    );
    return translatedResponse;
  }

  selectLocation(event: any) {
    this.exhibit.latitude = event.coords.lat;
    this.exhibit.longitude = event.coords.lng;
  }

  selectImage() {
    this.selectDialogRef = this.dialog.open(SelectMediumDialogComponent, { width: '75%', data: { type: 'Image' } });
    this.selectDialogRef.afterClosed().subscribe(
      (selectedMedium: Medium) => {
        if (selectedMedium) {
          this.exhibit.image = selectedMedium.id;
          this.imageName = selectedMedium.title;
          this.previewImage(this.exhibit.image);
        }
      }
    );
  }

  removeImage() {
    this.exhibit.image = null;
    this.previewURL = null;
    this.getMediaName();
  }

  updateMap() {
    if (this.exhibit.latitude) {
      this.lat = +this.exhibit.latitude;
    }
    if (this.exhibit.longitude) {
      this.lng = +this.exhibit.longitude;
    }
  }

  openHistory() {
    let context = this;
    this.exhibitService.getHistory(this.exhibit.id)
      .then(
        (response) => {
          this.changeHistoryDialogRef = this.dialog.open(ChangeHistoryComponent, { width: '60%',
            data: {
              title: context.exhibit.name,
              data: response
            }
          });
        }
      ).catch(
      (error: any) => {
        this.toasterService.pop('error', this.getTranslatedString('Error fetching history') , error);
      }
    );
  }

  private handleResponseUpdate() {
    this.toasterService.pop('success', 'Success', this.exhibit.name + ' - ' + this.getTranslatedString('exhibit updated'));
  }

  private translate(data: string): string {
    let translatedResponse: string;
    this.translateService.get(data).subscribe(
      (value: string) => {
        translatedResponse = value;
      }
    );
    return translatedResponse;
  }
}


text:
require 'rubygems'
require 'bundler'
begin
  Bundler.setup(:default, :development)
rescue Bundler::BundlerError => e
  $stderr.puts e.message
  $stderr.puts "Run `bundle install` to install missing gems"
  exit e.status_code
end
require 'simplecov'
SimpleCov.command_name 'Unit Tests'
SimpleCov.start do
  add_filter "/test/"
end

require 'test/unit'
require 'shoulda'
require 'mocha'

require 'thread'
require 'rails/all'

$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'wherewolf'

class TestApp < Rails::Application
  config.root = File.dirname(__FILE__)
end

Rails.application = TestApp
Wherewolf::Railtie.initializers.first.run(Rails.application)
ActiveRecord::Migration.verbose = false

class AddUsers < ActiveRecord::Migration
  def up
    create_table :players do |t|
      t.string :name
      t.string :position
      t.boolean :active
      t.date :first_cap
    end

    create_table :teams do |t|
      t.string :team
    end

    create_table :countries do |t|
      t.string :name
      t.string :jersey_color
    end
  end

  def down
    drop_table :users
    drop_table :teams
    drop_table :countries
  end
end

class Player < ActiveRecord::Base
  has_query_parsing
end

class Team < ActiveRecord::Base
end

class Country < ActiveRecord::Base
  attr_accessible :name
  has_query_parsing :whitelist => [ :name ]
end

class Test::Unit::TestCase
  def setup_fixtures
    Player.create!(:name => "Patrick 'Paddy' Carew", :position => 'lock', :first_cap => '1899-06-24', :active => false)
    Player.create!(:name => "Charlie Ellis", :position => 'flanker', :first_cap => '1899-06-24', :active => false)
    Player.create!(:name => "Arthur Corfe", :position => 'flanker', :first_cap => '1899-07-22', :active => false)
    Player.create!(:name => "Syd Miller", :position => 'wing', :first_cap => '1899-08-05', :active => false)
    Player.create!(:name => "Charlie Redwood", :position => 'wing', :first_cap => '1903-08-15', :active => false)
    Player.create!(:name => "Patrick 'Pat' Walsh", :position => 'no. 8', :first_cap => '1904-07-02', :active => false)
    Player.create!(:name => "John Manning", :position => 'fly-half', :first_cap => '1904-07-23', :active => false)
    Player.create!(:name => "Dally Messenger", :position => 'wing', :first_cap => '1907-08-03', :active => false)
    Player.create!(:name => "Salesi Ma'afu", :position => 'prop', :first_cap => '2010-06-05', :active => true)
    Player.create!(:name => "James Slipper", :position => 'prop', :first_cap => nil, :active => true)
  end

  def setup_database
    ActiveRecord::Base.establish_connection({
      :adapter => 'sqlite3',
      :database => ':memory:',
      :verbosity => 'quiet'
    })
    Arel::Table.engine = Arel::Sql::Engine.new(ActiveRecord::Base)
    AddUsers.migrate(:up)
  end
end


text:
from django import template

register = template.Library()

def distribute_entrys(inboxentry):
    boxentrys = inboxentry.box_set.all()
    return {'boxentrys': boxentrys}


text:
const R = require('ramda')

const format = R.curry((data, {
  attributes = [],
  transform = R.identity,
  transformSelf = R.identity
}) => {
  if (R.isArrayLike(data)) {
    return R.pipe(
      R.when(
        () => !R.isEmpty(attributes),
        R.project(attributes)
      ),
      R.map(R.evolve(transform)),
      transformSelf
    )(data)
  } else {
    return R.pipe(
      R.when(
        () => !R.isEmpty(attributes),
        R.pick(attributes)
      ),
      R.evolve(transform)
    )(data)
  }
})

module.exports = format


text: Here is a paragraph.


text:
A lightweight open Anchor CMS theme for my personal blog.

# Allowed customized fields:

## Site:

- **disqus_shortname**: Disqus shortname for displaying disqus comments on posts that allow commenting.
- **analytics_id**: Google Analytics ID for tracking.
- **twitter**: Twitter username to be displayed on footer
- **facebook**: Facebook account to be displayed on footer

## For posts:

- **featured-image**: the featured image to be displayed in the post header. Type: image, Filetypes: jpg,jpeg,png,gif,svg


text:
package com.ctrip.framework.apollo.portal.spi.defaultimpl;

import com.ctrip.framework.apollo.common.entity.App;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.portal.constant.PermissionType;
import com.ctrip.framework.apollo.portal.constant.RoleType;
import com.ctrip.framework.apollo.portal.entity.po.Permission;
import com.ctrip.framework.apollo.portal.entity.po.Role;
import com.ctrip.framework.apollo.portal.service.RoleInitializationService;
import com.ctrip.framework.apollo.portal.service.RolePermissionService;
import com.ctrip.framework.apollo.portal.spi.UserInfoHolder;
import com.ctrip.framework.apollo.portal.util.RoleUtils;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

/**
 * Created by timothy on 2017/4/26.
 */
public class DefaultRoleInitializationService implements RoleInitializationService {
    @Autowired
    private UserInfoHolder userInfoHolder;
    @Autowired
    private RolePermissionService rolePermissionService;

    @Transactional
    public void initAppRoles(App app) {
        String appId = app.getAppId();

        String appMasterRoleName = RoleUtils.buildAppMasterRoleName(appId);

        //has created before
        if (rolePermissionService.findRoleByRoleName(appMasterRoleName) != null) {
            return;
        }
        String operator = userInfoHolder.getUser().getUserId();
        //create app permissions
        createAppMasterRole(appId);

        //assign master role to user
        rolePermissionService
                .assignRoleToUsers(RoleUtils.buildAppMasterRoleName(appId), Sets.newHashSet(app.getOwnerName()),
                        operator);

        initNamespaceRoles(appId, ConfigConsts.NAMESPACE_APPLICATION);

        //assign modify、release namespace role to user
        rolePermissionService.assignRoleToUsers(RoleUtils.buildNamespaceRoleName(appId, ConfigConsts.NAMESPACE_APPLICATION, RoleType.MODIFY_NAMESPACE),
                Sets.newHashSet(operator), operator);
        rolePermissionService.assignRoleToUsers(RoleUtils.buildNamespaceRoleName(appId, ConfigConsts.NAMESPACE_APPLICATION, RoleType.RELEASE_NAMESPACE),
                Sets.newHashSet(operator), operator);

    }

    @Transactional
    public void initNamespaceRoles(String appId, String namespaceName) {

        String modifyNamespaceRoleName = RoleUtils.buildModifyNamespaceRoleName(appId, namespaceName);
        if (rolePermissionService.findRoleByRoleName(modifyNamespaceRoleName) == null) {
            createDefaultNamespaceRole(appId, namespaceName, PermissionType.MODIFY_NAMESPACE,
                    RoleUtils.buildModifyNamespaceRoleName(appId, namespaceName));
        }

        String releaseNamespaceRoleName = RoleUtils.buildReleaseNamespaceRoleName(appId, namespaceName);
        if (rolePermissionService.findRoleByRoleName(releaseNamespaceRoleName) == null) {
            createDefaultNamespaceRole(appId, namespaceName, PermissionType.RELEASE_NAMESPACE,
                    RoleUtils.buildReleaseNamespaceRoleName(appId, namespaceName));
        }
    }

    private void createAppMasterRole(String appId) {
        Set<Permission> appPermissions =
                FluentIterable.from(Lists.newArrayList(
                        PermissionType.CREATE_CLUSTER, PermissionType.CREATE_NAMESPACE, PermissionType.ASSIGN_ROLE))
                        .transform(permissionType -> createPermission(appId, permissionType)).toSet();
        Set<Permission> createdAppPermissions = rolePermissionService.createPermissions(appPermissions);
        Set<Long>
                appPermissionIds =
                FluentIterable.from(createdAppPermissions).transform(permission -> permission.getId()).toSet();

        //create app master role
        Role appMasterRole = createRole(RoleUtils.buildAppMasterRoleName(appId));

        rolePermissionService.createRoleWithPermissions(appMasterRole, appPermissionIds);
    }

    private Permission createPermission(String targetId, String permissionType) {
        Permission permission = new Permission();
        permission.setPermissionType(permissionType);
        permission.setTargetId(targetId);
        String userId = userInfoHolder.getUser().getUserId();
        permission.setDataChangeCreatedBy(userId);
        permission.setDataChangeLastModifiedBy(userId);
        return permission;
    }

    private Role createRole(String roleName) {
        Role role = new Role();
        role.setRoleName(roleName);
        String operator = userInfoHolder.getUser().getUserId();
        role.setDataChangeCreatedBy(operator);
        role.setDataChangeLastModifiedBy(operator);
        return role;
    }

    private void createDefaultNamespaceRole(String appId, String namespaceName, String permissionType, String roleName) {

        Permission permission =
                createPermission(RoleUtils.buildNamespaceTargetId(appId, namespaceName), permissionType);
        Permission createdPermission = rolePermissionService.createPermission(permission);

        Role role = createRole(roleName);
        rolePermissionService
                .createRoleWithPermissions(role, Sets.newHashSet(createdPermission.getId()));
    }
}


text: <?php echo $sectionName ?>


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W30648_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">GEOLOGIC PROGNOSIS

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Weli Name: Sorenson 5-16H Rig: Cyclone 02 Prospect: Antelope Target: Middle Bakken Spacing: 2560

    <p class="styleSans313.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">E] Pre-Staked
staked Rig Grade Elevation: 2169' KB: 22' RKB: 2191'
FORMATION SUBSEA
Pierre Shale 1,791 "2,205 4,396 Dakota Group (fka Mowry) -2,557 4,748
Basal Dakota Sand -3,336 5,527 Dunham Salt Top -4,303 6,494 Dunham Salt Base 4,335
Pine Salt Top 4,631
Pine Salt Base -4,684 6,875 Minnekahta ~4,712
Opeche Salt Top -4,811 7,002 Opeche Salt Base —4,867 7,058 Minnelusa Group —5,183 7,374 Tyler —5,423 7,614 Kibby —5,953 8,1 Top Charles -6,105 8,296 Base Last Charles Salt -6,777 8,968 Mission Canyon -6,961
Lodgepole -7,633 9,824 Upper Bakken Shale -8,384 10,575 Middle Bakken Member -8,409 10,600 Middle Bakken Target —8,423
End of Lateral

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Sorenson 5—16H AFE v1

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">SHL: 466 FNL Sec. 16 Mountrail
HL: 556' FNL Sec. 21 Mountraii

    <p class="styleSans1.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">2045' 154N ND
2400' 1 54 N
ND

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">FWL 94W
FWL 94W


text:
const addCommand = require('./lib/add-command');

/**
 * waits for a specific string (or regex) to appear in the specified selector
 * @param {string} selector
 * @param {string|RegExp} value
 * @param {number} [timeout=500]
 * @param {booean} [reverse=false]
 */
addCommand('waitForSpecificText', function waitForSpecificText(selector, value, timeout = 5000, reverse = false) {
  let condition;

  if (typeof value === 'string') {
    condition = () => this.getText(selector) === value;
  }
  else if (value instanceof RegExp) {
    condition = () => value.test(this.getText(selector));
  }
  else {
    throw new Error('`value` must be a string or a RegExp');
  }

  if (reverse) {
    this.waitUntil(() => !condition(), timeout, `$('${selector}') did not change from ${value} within the expected timeout`);
  }
  else {
    this.waitUntil(() => condition(), timeout, `$('${selector}') did not equal ${value} within the expected timeout`);
  }
});


text:
	CREATE TABLE wpm."role_collectionPermission" (
		  id_role integer NOT NULL
		, id_collectionPermission integer NOT NULL
	  	, CONSTRAINT "role_collectionPermission_pkey" PRIMARY KEY (id_role, id_collectionPermission)
	  	, CONSTRAINT "role_collectionPermission_fk_id_role" FOREIGN KEY (id_role)
	  		REFERENCES wpm."role" (id) MATCH SIMPLE
	  		ON UPDATE CASCADE
	  		ON DELETE CASCADE
	  	, CONSTRAINT "role_collectionPermission_fk_id_collectionPermission" FOREIGN KEY (id_collectionPermission)
	  		REFERENCES wpm."collectionPermission" (id) MATCH SIMPLE
	  		ON UPDATE CASCADE
	  		ON DELETE CASCADE
	);