text:
.class public Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;
.super Ljava/lang/Object;
.source "VoIPInterfaceManager.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/VoIPInterfaceManager;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x1
    name = "CallSessionInfo"
.end annotation

# instance fields
.field private actionName:Ljava/lang/String;

.field private callCountInThisSession:I

.field private callNumber:Ljava/lang/String;

.field clientCallback:Landroid/os/IVoIPCallbackInterface;

.field private isIncoming:Ljava/lang/Boolean;

.field private mCurrCallState:Lcom/android/server/VoIPInterfaceManager$CallState;

.field private packageName:Ljava/lang/String;

.field private remotePartyNumber:Ljava/lang/String;

.field final synthetic this$0:Lcom/android/server/VoIPInterfaceManager;

.field private useBTCall:Ljava/lang/Boolean;

.field private useHoldCall:Ljava/lang/Boolean;

# direct methods
.method static synthetic -get0(Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;)Ljava/lang/String;
    .locals 1

    iget-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->callNumber:Ljava/lang/String;

    return-object v0
.end method

.method static synthetic -get1(Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;)Ljava/lang/Boolean;
    .locals 1

    iget-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->isIncoming:Ljava/lang/Boolean;

    return-object v0
.end method

.method static synthetic -get2(Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;)Lcom/android/server/VoIPInterfaceManager$CallState;
    .locals 1

    iget-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->mCurrCallState:Lcom/android/server/VoIPInterfaceManager$CallState;

    return-object v0
.end method

.method static synthetic -get3(Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;)Ljava/lang/String;
    .locals 1

    iget-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->remotePartyNumber:Ljava/lang/String;

    return-object v0
.end method

.method static synthetic -set0(Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;Ljava/lang/Boolean;)Ljava/lang/Boolean;
    .locals 0

    iput-object p1, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->useBTCall:Ljava/lang/Boolean;

    return-object p1
.end method

.method static synthetic -set1(Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;Ljava/lang/Boolean;)Ljava/lang/Boolean;
    .locals 0

    iput-object p1, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->useHoldCall:Ljava/lang/Boolean;

    return-object p1
.end method

.method public constructor <init>(Lcom/android/server/VoIPInterfaceManager;)V
    .locals 3

    const/4 v2, 0x0

    const/4 v1, 0x0

    iput-object p1, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->this$0:Lcom/android/server/VoIPInterfaceManager;

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

    sget-object v0, Lcom/android/server/VoIPInterfaceManager$CallState;->IDLE:Lcom/android/server/VoIPInterfaceManager$CallState;

    iput-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->mCurrCallState:Lcom/android/server/VoIPInterfaceManager$CallState;

    iput-object v1, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->packageName:Ljava/lang/String;

    iput-object v1, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->actionName:Ljava/lang/String;

    iput-object v1, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->callNumber:Ljava/lang/String;

    iput-object v1, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->remotePartyNumber:Ljava/lang/String;

    invoke-static {v2}, Ljava/lang/Boolean;->valueOf(Z)Ljava/lang/Boolean;

    move-result-object v0

    iput-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->useBTCall:Ljava/lang/Boolean;

    invoke-static {v2}, Ljava/lang/Boolean;->valueOf(Z)Ljava/lang/Boolean;

    move-result-object v0

    iput-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->useHoldCall:Ljava/lang/Boolean;

    invoke-static {v2}, Ljava/lang/Boolean;->valueOf(Z)Ljava/lang/Boolean;

    move-result-object v0

    iput-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->isIncoming:Ljava/lang/Boolean;

    iput v2, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->callCountInThisSession:I

    iput-object v1, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->clientCallback:Landroid/os/IVoIPCallbackInterface;

    return-void
.end method

# virtual methods
.method public clearCallSessionInfo()V
    .locals 2

    const-class v1, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;

    monitor-enter v1

    const/4 v0, 0x0

    :try_start_0
    iput-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->packageName:Ljava/lang/String;

    const/4 v0, 0x0

    iput-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->actionName:Ljava/lang/String;

    const/4 v0, 0x0

    iput-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->callNumber:Ljava/lang/String;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    monitor-exit v1

    return-void

    :catchall_0
    move-exception v0

    monitor-exit v1

    throw v0
.end method

.method public getBTStatus()Z
    .locals 3

    iget-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->this$0:Lcom/android/server/VoIPInterfaceManager;

    new-instance v1, Ljava/lang/StringBuilder;

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

    const-string/jumbo v2, "getBTStatus:"

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

    move-result-object v1

    iget-object v2, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->useBTCall:Ljava/lang/Boolean;

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

    move-result-object v1

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

    move-result-object v1

    invoke-static {v0, v1}, Lcom/android/server/VoIPInterfaceManager;->-wrap0(Lcom/android/server/VoIPInterfaceManager;Ljava/lang/String;)V

    iget-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->useBTCall:Ljava/lang/Boolean;

    invoke-virtual {v0}, Ljava/lang/Boolean;->booleanValue()Z

    move-result v0

    return v0
.end method

.method public getCallCountInThisSession()I
    .locals 2

    const-class v0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;

    monitor-enter v0

    :try_start_0
    iget v1, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->callCountInThisSession:I
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    monitor-exit v0

    return v1

    :catchall_0
    move-exception v1

    monitor-exit v0

    throw v1
.end method

.method public getClientCallbackInstance()Landroid/os/IVoIPCallbackInterface;
    .locals 2

    const-class v0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;

    monitor-enter v0

    :try_start_0
    iget-object v1, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->clientCallback:Landroid/os/IVoIPCallbackInterface;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    monitor-exit v0

    return-object v1

    :catchall_0
    move-exception v1

    monitor-exit v0

    throw v1
.end method

.method public getCurrentCallState()Lcom/android/server/VoIPInterfaceManager$CallState;
    .locals 2

    const-class v0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;

    monitor-enter v0

    :try_start_0
    iget-object v1, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->mCurrCallState:Lcom/android/server/VoIPInterfaceManager$CallState;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    monitor-exit v0

    return-object v1

    :catchall_0
    move-exception v1

    monitor-exit v0

    throw v1
.end method

.method public getDirection()Z
    .locals 2

    const-class v1, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;

    monitor-enter v1

    :try_start_0
    iget-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->isIncoming:Ljava/lang/Boolean;

    invoke-virtual {v0}, Ljava/lang/Boolean;->booleanValue()Z
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    move-result v0

    monitor-exit v1

    return v0

    :catchall_0
    move-exception v0

    monitor-exit v1

    throw v0
.end method

.method public getHoldStatus()Z
    .locals 1

    iget-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->useHoldCall:Ljava/lang/Boolean;

    invoke-virtual {v0}, Ljava/lang/Boolean;->booleanValue()Z

    move-result v0

    return v0
.end method

.method public getPackageName()Ljava/lang/String;
    .locals 2

    const-class v0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;

    monitor-enter v0

    :try_start_0
    iget-object v1, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->packageName:Ljava/lang/String;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    monitor-exit v0

    return-object v1

    :catchall_0
    move-exception v1

    monitor-exit v0

    throw v1
.end method

.method public getRegisteredCallNumber()Ljava/lang/String;
    .locals 2

    const-class v0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;

    monitor-enter v0

    :try_start_0
    iget-object v1, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->callNumber:Ljava/lang/String;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    monitor-exit v0

    return-object v1

    :catchall_0
    move-exception v1

    monitor-exit v0

    throw v1
.end method

.method public getRemotePartyNumber()Ljava/lang/String;
    .locals 2

    const-class v0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;

    monitor-enter v0

    :try_start_0
    iget-object v1, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->remotePartyNumber:Ljava/lang/String;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    monitor-exit v0

    return-object v1

    :catchall_0
    move-exception v1

    monitor-exit v0

    throw v1
.end method

.method public getactionName()Ljava/lang/String;
    .locals 2

    const-class v0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;

    monitor-enter v0

    :try_start_0
    iget-object v1, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->actionName:Ljava/lang/String;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    monitor-exit v0

    return-object v1

    :catchall_0
    move-exception v1

    monitor-exit v0

    throw v1
.end method

.method public isValidSessionInfo()Z
    .locals 4

    const-class v1, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;

    monitor-enter v1

    :try_start_0
    iget-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->packageName:Ljava/lang/String;

    if-eqz v0, :cond_0

    iget-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->actionName:Ljava/lang/String;

    if-nez v0, :cond_1

    :cond_0
    iget-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->this$0:Lcom/android/server/VoIPInterfaceManager;

    const-string/jumbo v2, "    ** YOU SHOULD FILL OUT ALL FIELD ** "

    invoke-static {v0, v2}, Lcom/android/server/VoIPInterfaceManager;->-wrap0(Lcom/android/server/VoIPInterfaceManager;Ljava/lang/String;)V

    iget-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->this$0:Lcom/android/server/VoIPInterfaceManager;

    new-instance v2, Ljava/lang/StringBuilder;

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

    const-string/jumbo v3, "    isValidSessionInfo() : pakageName : "

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

    move-result-object v2

    iget-object v3, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->packageName:Ljava/lang/String;

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

    move-result-object v2

    const-string/jumbo v3, ", actionName : "

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

    move-result-object v2

    iget-object v3, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->actionName:Ljava/lang/String;

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

    move-result-object v2

    const-string/jumbo v3, ", callNumber :"

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

    move-result-object v2

    iget-object v3, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->callNumber:Ljava/lang/String;

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

    move-result-object v2

    const-string/jumbo v3, ", clientCallback : "

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

    move-result-object v2

    iget-object v3, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->clientCallback:Landroid/os/IVoIPCallbackInterface;

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

    move-result-object v2

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

    move-result-object v2

    invoke-static {v0, v2}, Lcom/android/server/VoIPInterfaceManager;->-wrap0(Lcom/android/server/VoIPInterfaceManager;Ljava/lang/String;)V
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    const/4 v0, 0x0

    monitor-exit v1

    return v0

    :cond_1
    :try_start_1
    iget-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->callNumber:Ljava/lang/String;

    if-eqz v0, :cond_0

    iget-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->clientCallback:Landroid/os/IVoIPCallbackInterface;

    if-eqz v0, :cond_0

    iget-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->this$0:Lcom/android/server/VoIPInterfaceManager;

    const-string/jumbo v2, "    isValidSessionInfo() : All session field is valid"

    invoke-static {v0, v2}, Lcom/android/server/VoIPInterfaceManager;->-wrap0(Lcom/android/server/VoIPInterfaceManager;Ljava/lang/String;)V

    iget-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->this$0:Lcom/android/server/VoIPInterfaceManager;

    new-instance v2, Ljava/lang/StringBuilder;

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

    const-string/jumbo v3, "    isValidSessionInfo() : pakageName : "

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

    move-result-object v2

    iget-object v3, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->packageName:Ljava/lang/String;

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

    move-result-object v2

    const-string/jumbo v3, ", actionName : "

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

    move-result-object v2

    iget-object v3, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->actionName:Ljava/lang/String;

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

    move-result-object v2

    const-string/jumbo v3, ", callNumber :"

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

    move-result-object v2

    iget-object v3, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->callNumber:Ljava/lang/String;

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

    move-result-object v2

    const-string/jumbo v3, ", clientCallback : "

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

    move-result-object v2

    iget-object v3, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->clientCallback:Landroid/os/IVoIPCallbackInterface;

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

    move-result-object v2

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

    move-result-object v2

    invoke-static {v0, v2}, Lcom/android/server/VoIPInterfaceManager;->-wrap0(Lcom/android/server/VoIPInterfaceManager;Ljava/lang/String;)V
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_0

    const/4 v0, 0x1

    monitor-exit v1

    return v0

    :catchall_0
    move-exception v0

    monitor-exit v1

    throw v0
.end method

.method public setBTStatus(Z)V
    .locals 3

    iget-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->this$0:Lcom/android/server/VoIPInterfaceManager;

    new-instance v1, Ljava/lang/StringBuilder;

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

    const-string/jumbo v2, "setBTStatus:"

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

    move-result-object v1

    invoke-virtual {v1, p1}, Ljava/lang/StringBuilder;->append(Z)Ljava/lang/StringBuilder;

    move-result-object v1

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

    move-result-object v1

    invoke-static {v0, v1}, Lcom/android/server/VoIPInterfaceManager;->-wrap0(Lcom/android/server/VoIPInterfaceManager;Ljava/lang/String;)V

    invoke-static {p1}, Ljava/lang/Boolean;->valueOf(Z)Ljava/lang/Boolean;

    move-result-object v0

    iput-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->useBTCall:Ljava/lang/Boolean;

    return-void
.end method

.method public setCallCountInThisSession(I)V
    .locals 2

    const-class v0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;

    monitor-enter v0

    :try_start_0
    iput p1, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->callCountInThisSession:I
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    monitor-exit v0

    return-void

    :catchall_0
    move-exception v1

    monitor-exit v0

    throw v1
.end method

.method public setCallSessionInfo(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Landroid/os/IVoIPCallbackInterface;)V
    .locals 2

    const-class v1, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;

    monitor-enter v1

    :try_start_0
    iput-object p1, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->packageName:Ljava/lang/String;

    iput-object p2, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->actionName:Ljava/lang/String;

    iput-object p3, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->callNumber:Ljava/lang/String;

    iput-object p4, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->clientCallback:Landroid/os/IVoIPCallbackInterface;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    monitor-exit v1

    return-void

    :catchall_0
    move-exception v0

    monitor-exit v1

    throw v0
.end method

.method public setCallState(Lcom/android/server/VoIPInterfaceManager$CallState;)V
    .locals 2

    const-class v0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;

    monitor-enter v0

    :try_start_0
    iput-object p1, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->mCurrCallState:Lcom/android/server/VoIPInterfaceManager$CallState;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    monitor-exit v0

    return-void

    :catchall_0
    move-exception v1

    monitor-exit v0

    throw v1
.end method

.method public setDirection(Z)V
    .locals 3

    iget-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->this$0:Lcom/android/server/VoIPInterfaceManager;

    new-instance v1, Ljava/lang/StringBuilder;

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

    const-string/jumbo v2, "setDirection:"

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

    move-result-object v1

    invoke-virtual {v1, p1}, Ljava/lang/StringBuilder;->append(Z)Ljava/lang/StringBuilder;

    move-result-object v1

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

    move-result-object v1

    invoke-static {v0, v1}, Lcom/android/server/VoIPInterfaceManager;->-wrap0(Lcom/android/server/VoIPInterfaceManager;Ljava/lang/String;)V

    invoke-static {p1}, Ljava/lang/Boolean;->valueOf(Z)Ljava/lang/Boolean;

    move-result-object v0

    iput-object v0, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->isIncoming:Ljava/lang/Boolean;

    return-void
.end method

.method public setRemotePartyNumber(Ljava/lang/String;)V
    .locals 2

    const-class v0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;

    monitor-enter v0

    :try_start_0
    iput-object p1, p0, Lcom/android/server/VoIPInterfaceManager$CallSessionInfo;->remotePartyNumber:Ljava/lang/String;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    monitor-exit v0

    return-void

    :catchall_0
    move-exception v1

    monitor-exit v0

    throw v1
.end method


text:
[![Build Status](https://travis-ci.org/contentful/contentful-webhook-listener.rb.svg)](https://travis-ci.org/contentful/contentful-webhook-listener.rb)

# Contentful Webhook Listener

A Simple HTTP Webserver with pluggable behavior for listening to API Webhooks

## Contentful
[Contentful](https://www.contentful.com) provides a content infrastructure for digital teams to power content in websites, apps, and devices. Unlike a CMS, Contentful was built to integrate with the modern software stack. It offers a central hub for structured content, powerful management and delivery APIs, and a customizable web app that enable developers and content creators to ship digital products faster.

## What does `contentful-webhook-listener` do?
The aim of `contentful-webhook-listener` is to have developers setting up their Contentful
Webhooks for triggering background jobs.

## Installation

Add this line to your application's Gemfile:

    gem 'contentful-webhook-listener'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install contentful-webhook-listener

## Usage

* Require gem:

```ruby
require 'contentful/webhook/listener'
```

* Create your own Controllers:

```ruby
class MyController < Contentful::Webhook::Listener::Controllers::Base
  def perform(request, response)
    "do your process..." # This will run on a brackground Thread
  end
end
```

* Configure and start your Webhook Listener

```ruby
require 'logger'

Contentful::Webhook::Listener::Server.start do |config|
  config[:port] = 5678         # Optional
  config[:address] = "0.0.0.0" # Optional
  config[:logger] = Logger.new(STDOUT) # Optional, will use a NullLogger by default
  config[:endpoints] = [
    {
      endpoint: "/receive",     # Where your server will listen
      controller: MyController, # The controller that will process the endpoint
      timeout: 15               # If using Wait, will wait `X` seconds before executing
    }
  ]
end
```

You can add multiple endpoints, each with it's own Controller.

### Webhook Aware Controllers

You can create controllers that can respond on specific Webhook events.

```ruby
class MyController < Contentful::Webhook::Listener::Controllers::WebhookAware
  def publish
    # Do stuff on publish
    if webhook.entry?
      logger.info "published Entry ID: #{webhook.id} for Space: #{webhook.space_id}"
    end
  end

  def unpublish
    # Do stuff on unpublish
  end

  def archive
    # Do stuff on archive
  end

  def unarchive
    # Do stuff on unarchive
  end

  def create
    # Do stuff on create
  end

  def save
    # Do stuff on save
  end

  def delete
    # Do stuff on delete
  end
end
```

The controller has a `webhook` object bound when invoked, that has a few helpers:

* `webhook.entry?` will return if the webhook was fired for an Entry
* `webhook.asset?` will return if the webhook was fired for an Asset
* `webhook.content_type?` will return if the webhook was fired for a Content Type

* `webhook.id` will return the Resource (Entry/Asset/Content Type) ID
* `webhook.space_id` will return the Space ID

* `webhook.sys` will include the metadata for the resource
* `webhook.fields` will include the resource fields (not included on Unpublish)

## Contributing

1. Fork it ( https://github.com/[my-github-username]/contentful-webhook-listener/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request

redpajama_set_name: RedPajamaGithub


text:
tags: technology
layout: post
title: "More photo fun"
---

Got the rest of the wedding photos scanned in. We probably did two-thirds of the book and I think we got all the good ones -- at least the non-redundant good ones. Scanning is a real time eater, but I think the quality is excellent, particularly compared with sub-$1000 digital cameras. (Although they're probably two generations better than when I last looked at them, so I should probably change that to sub-$500...)

Since there are so many photos, I split them up into ceremony photos and reception photos. There will also be a separate page of photos that Trudy took (She rocks!) as well as disposable camera shots. Trudy is visiting friends before she starts medical school and stayed over last night. She took about two and a half rolls of black-and-white film -- most of the shots are excellent. Can't wait to get them in.

Also spent a huge amount of time standardizing all the photos I have so that the small (thumbnail) version is within certain constraints. Again, real time eater, but I have a pretty consistent library now, just ripe for filename parsing to put entries into a database :)

The next step is to allow you to browse the library by clicking on a person's name or an event and seeing all the photos that have that person or that were taken at that event. Here's a preview: a few photos from my trip to Spokane, Washington in 1996 for a Rural ITS conference. Cat fiends can also see all the currently scanned photos of Jackson and La Choy.


text:
package cn.purchasenear.v1.goods.rpcservice.spring;

import java.util.Random;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.geo.GeoDistance;
import org.elasticsearch.common.lang3.StringUtils;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.FilterBuilder;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import cn.purchasenear.v1.goods.consts.ElasticSearchTypeEnum;
import cn.purchasenear.v1.goods.domain.GoodsInfoVO;
import cn.purchasenear.v1.goods.domain.SearchGoodsVO;
import cn.purchasenear.v1.goods.domain.SearchInfoVO;
import cn.purchasenear.v1.goods.service.GoodsSearchService;

@Component
@Lazy(true)
public class GoodsSearchServiceImpl implements GoodsSearchService{

	private static SearchGoodsVO searchGoodsVO = new SearchGoodsVO();
	private Logger logger = Logger.getLogger(getClass());
	ThreadLocal<String> id = new ThreadLocal<String>();
	public SearchGoodsVO searhGoods(SearchInfoVO info){
		if (id.get() == null) {
			id.set(UUID.randomUUID().toString().replace("-", ""));
		}
		logger.debug("ID["+id.get()+"],SearchInfoVO搜索条件:" + info);
		//2.检查参数是否合法:是否必填先,是否参数不合法
		//3.根据条件封装es条件和过滤规则
		TransportClient client = ElasticSearchClient.getClient();
		SearchRequestBuilder builder =
				client.prepareSearch(ElasticSearchTypeEnum.GOODS.getIndex())
				.setTypes(ElasticSearchTypeEnum.GOODS.getType());
		builder.setSearchType(SearchType.DEFAULT);

		BoolQueryBuilder sBoolQueryBuilder = QueryBuilders.boolQuery();

		//构建搜索条件
		buildSearchCondition(sBoolQueryBuilder, info);

		//地理位置查询:
		FilterBuilder filterBuilder = FilterBuilders.geoDistanceFilter("locations")
				.point(info.getLatitude(),info.getLongitude())
				.distance(info.getDistance(), DistanceUnit.METERS)
				.optimizeBbox("memory")
				.geoDistance(GeoDistance.ARC);

		QueryBuilder queryBuilder =
				QueryBuilders.filteredQuery(sBoolQueryBuilder,filterBuilder);
		logger.info("ID["+id.get()+"],ES search expression: " + queryBuilder.toString());
		builder.setQuery(queryBuilder);

		//构建排序字段
		buildSort(builder, info);

		//构建分页
		buildSearchPage(builder, info);

    	//开始执行查询:
		SearchResponse response =  builder.execute().actionGet();
		SearchHits hits = response.getHits();
		logger.info("ID["+id.get()+"],search resultset.size=" + hits.getTotalHits());
        SearchHit[] searchHists = hits.getHits();
        GoodsInfoVO[] goods = new GoodsInfoVO[searchHists.length];
        if(searchHists.length>0){
        	int i = 0;
            for(SearchHit hit:searchHists){
                GoodsInfoVO goodsInfo = new GoodsInfoVO();
                goodsInfo.copy(hit);
                goods[i] = goodsInfo;
                i++;
                logger.debug("ID["+id.get()+"],search result:"+goodsInfo);
            }
        }

		//5.对结果封装成SearchGoods
		SearchGoodsVO searchGoodsVO = new SearchGoodsVO();
		searchGoodsVO.copyFromInfo(info);
		searchGoodsVO.setGoodsList(goods);

		return searchGoodsVO;

	}

	private void buildSearchPage(SearchRequestBuilder builder, SearchInfoVO info) {
		//分页:
		int page = 0;
		int pageSize = 10;
		if(info.getPage()>0){
			page = info.getPage();
		}
		if(info.getPageSize()>0){
			pageSize = info.getPageSize();
		}
		info.setPage(page);
		info.setPageSize(pageSize);
    	builder.setFrom(page).setSize(pageSize);
	}

	private void buildSort(SearchRequestBuilder builder, SearchInfoVO info) {
		/**排序:
		•	price	boolean	false	是否以商品价格排序,默认false
		•	saled	boolean	false	是否以销量排序,默认false
		•	browsed	boolean	false	是否以浏览量排序,默认false
		*/
		if(info.isPrice()){
			builder.addSort("price",SortOrder.ASC) ;// Query
		}else if(info.isSaled()){
			builder.addSort("saleCount",SortOrder.DESC) ;// Query
		}else if(info.isBrowsed()){
			builder.addSort("browseCount",SortOrder.DESC) ;// Query
		}
	}

	private void buildSearchCondition(BoolQueryBuilder sBoolQueryBuilder,
			SearchInfoVO info) {
		//模糊查询:goodsName and sellerName
		if(!StringUtils.isEmpty(info.getGoodsName())){
			sBoolQueryBuilder.must(QueryBuilders.fuzzyQuery("goodsName", "*"+info.getGoodsName()+"*"));
		}
		if(!StringUtils.isEmpty(info.getSellerName())){
			sBoolQueryBuilder.must(QueryBuilders.fuzzyQuery("sellerName", "*"+info.getSellerName()+"*"));
		}

		//GoodsCategory支持多种商品类型查询
		if(!StringUtils.isEmpty(info.getGoodsCategory())){
			sBoolQueryBuilder.must(QueryBuilders.inQuery("goodsCategory", info.getGoodsCategory().split(",")));
		}
		//品牌支持多种查询
		if(!StringUtils.isEmpty(info.getBrand())){
			sBoolQueryBuilder.must(QueryBuilders.inQuery("brandId", info.getBrand().split(",")));
		}

		/**lowPrice and highPrice*/
		if(info.getLowPrice()>0){ //查询的商品价格不低于此值: >=
			sBoolQueryBuilder.must(QueryBuilders.rangeQuery("price").gte(info.getLowPrice()));
		}
		if(info.getHighPrice()>0){//查询的商品价格不高于此值: <=
			sBoolQueryBuilder.must(QueryBuilders.rangeQuery("price").lte(info.getHighPrice()));
		}

		//hypostatic
		if(info.getHypostatic()!=0){
			sBoolQueryBuilder.must(QueryBuilders.matchQuery("hypostatic", info.getHypostatic()));
		}

		//deliver
		if(info.getDeliver()!=0){
			sBoolQueryBuilder.must(QueryBuilders.matchQuery("deliver", info.getDeliver()));
		}
		//secondHand
		if(info.getSecond_hand()!=0){
			sBoolQueryBuilder.must(QueryBuilders.matchQuery("secondHand", info.getSecond_hand()));
		}
		//barter
		if(info.getBarter()!=0){
			sBoolQueryBuilder.must(QueryBuilders.matchQuery("barter", info.getBarter()));
		}
	}

	public static void main(String[] args) {
		ElasticSearchClient.initClient("localhost:9300", "elasticsearch");
		SearchInfoVO req = new SearchInfoVO();
		req.setLatitude(50);
		req.setLongitude(50);
		req.setDistance(1000);
		req.setGoodsCategory("1,2,3");
		req.setLowPrice(50);
		req.setHighPrice(100);
		req.setBarter(1);
		req.setHypostatic(1);
		req.setSecond_hand(1);
		req.setDeliver(1);
		//分页查询
		req.setPage(0);
		req.setPageSize(10);

		//req.setPrice(true);
		//req.setSaled(true);
		//req.setBrowsed(true);
		System.out.println(new GoodsSearchServiceImpl().searhGoods(req));
	}

}


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using DataService.Context;
using DataService.Entities.Pedagogy;

namespace DataService.ViewModel
{
    /// <summary>
    /// Model d'une matiere
    /// </summary>
    public class MatiereCard
    {
        /// <summary>
        /// Model d'une matiere
        /// </summary>
        /// <param name="mat"></param>
        public MatiereCard ( Matiere mat )
        {
            MatiereId = mat.MatiereGuid;
            Name = mat.Name;
            Coeff = mat.Coefficient;
            //COLOR = Mat.COULEUR;

            using (var db = new Ef())
            {
                var sId = db.Cours.FirstOrDefault (c => c.MatiereGuid == mat.MatiereGuid)?.StaffGuid;

                InstructeurName = db.Staff?.Find(sId)?.FullName; //--------

                InstructeurPhoto = db.Staff?.Find(sId)?.PhotoIdentity; //------

                var weekDays = new List<DayOfWeek> { DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday, DayOfWeek.Saturday, DayOfWeek.Sunday };
                var T = new TimeSpan(0,0,0);
                var scheduleDate = DateTime.Today.Date;

                foreach (var mc in db.Cours.Where(c => c.MatiereGuid == mat.MatiereGuid && c.StartDate <= scheduleDate && c.EndDate >= scheduleDate))
                {
                    var coursDuree = mc.EndTime - mc.StartTime;
                    //.GetValueOrDefault().TimeOfDay
                    foreach (var d in weekDays)
                    {
                        var dayNum = (int)d;

                        if (mc.RecurrenceDays.Contains(dayNum.ToString()))
                        {
                            T = T.Add(coursDuree);
                        }
                    }
                    HeuresParSemaine = T.TotalHours.ToString(CultureInfo.InvariantCulture); //---
                }
            }
        }

        /// <summary>
        ///
        /// </summary>
        public Guid MatiereId { get; }

        /// <summary>
        /// Nomination
        /// </summary>
        public string Name { get; }

        /// <summary>
        /// Coefficient
        /// </summary>
        public int Coeff { get; }

        /// <summary>
        /// Nomination
        /// </summary>
        //public string COLOR { get; }

        /// <summary>
        /// Heures par semaine
        /// </summary>
        public string HeuresParSemaine { get; }

        /// <summary>
        /// Nom de l'instructeur
        /// </summary>
        public string InstructeurName { get; }

        /// <summary>
        /// Photo de l'instructeur
        /// </summary>
        public byte[] InstructeurPhoto { get; set; }

    }
}


text:
// define(function(require, exports, module) {

// <INJECTED SOURCE:START>

// THIS FILE IS GENERATED FROM SOURCE IN THE GCLI PROJECT
// DO NOT EDIT IT DIRECTLY

var exports = {};

const TEST_URI = "data:text/html;charset=utf-8,
gcli-testUtil.js
";

function test() {
  var tests = Object.keys(exports);
  // Push setup to the top and shutdown to the bottom
  tests.sort(function(t1, t2) {
    if (t1 == "setup" || t2 == "shutdown") return -1;
    if (t2 == "setup" || t1 == "shutdown") return 1;
    return 0;
  });
  info("Running tests: " + tests.join(", "))
  tests = tests.map(function(test) { return exports[test]; });
  DeveloperToolbarTest.test(TEST_URI, tests, true);
}

// <INJECTED SOURCE:END>

var util = require('gcli/util');
// var assert = require('test/assert');

exports.testFindCssSelector = function(options) {
  var nodes = options.window.document.querySelectorAll('*');
  for (var i = 0; i < nodes.length; i++) {
    var selector = util.findCssSelector(nodes[i]);
    var matches = options.window.document.querySelectorAll(selector);

    assert.is(matches.length, 1, 'multiple matches for ' + selector);
    assert.is(matches[0], nodes[i], 'non-matching selector: ' + selector);
  }
};

// });


text:
function [isEqual,reportStr]= structcompare(SX,SY,absTol,relTol)
% STRUCTCOMPARE compares two structures using the specified tolerance
%
% Input:
%   regular:
%       S1: struct[] - first input structure
%       S2: struct[] - second input structure
%   optional:
%       absTol: double[1,1] - maximum allowed tolerance, default value is 0
%       relTol: double[1,1] - maximum allowed relative tolerance, isn't
%                             used by default
%
%
% Output:
%   isEqual: logical[1,1] - true if the structures are found equal
%   reportStr: char[1,1] report about the found differences
%
%
% $Author: Peter Gagarinov, PhD <pgagarinov@gmail.com> $
% $Copyright: 2015-2016 Peter Gagarinov, PhD
%             2015 Moscow State University,
%            Faculty of Computational Mathematics and Computer Science,
%            System Analysis Department$
%
%

import mxberry.core.struct.structcomparevec;
if nargin<3
    absTol=0;
end
if nargin<4
    relTol=[];
end
%
if ~isequal(size(SX),size(SY))
    isEqual=false;
    reportStr={'sizes are different'};
    return;
end
[isEqualVec,reportStr]=structcomparevec(SX(:),SY(:),absTol,relTol);
isEqual=all(isEqualVec);


text:
* * *

title: Hour of Code Event How-To layout: wide nav: resources_nav

* * *

# Guide Acara Hour of Code

Adakan acara Hour of Code saat Computer Science Education Week (Des 8-14) untuk selebrasi ilmu komputer dan menginspirasi pelajar untuk mencobanya. Siapa saja, dimana saja dapat mengorganisasikan sebuah acara Hour of Code.

## 1) Persiapkan acaramu

  * Tentukan tempat, tanggal dan waktu
  * Kirimkan [sebuah surat](<%= hoc_uri('https://docs.google.com/a/code.org/document/d/1eP41sKW7y0qq_JvkRIgZK8dWYICaGRZ4CCDETXa78wY/edit') %>) untuk menundang walikota, anggota dewan, gubernur, atau seorang pebisnis yang berpengaruh untuk menjadi pembicara.
  * Undang media/pers, statsiun tv lokal, surat kabar, blogger edukasi/teknologi. Lihat [pers kit](<%= hoc_uri('/resources/press-kit') %>) kami untuk bantuan.

## 2) Saat acara

  * Awali acara anda dengan salah satu dari [ video inspiratif](<%= hoc_uri('/resources#videos') %>).
  * Berikan pembukaan mengenai garis-garis besar pentingnya ilmu komputer, menggunakan [statistik dan infografik](<%= hoc_uri('/resources/stats') %>).

  * Ide lain untuk acara:
      * Undang pemimpin industri lokal untuk mendiskusikan pekerjaannya yang berhubungan dengan ilmu komputer
      * Undang politisi lokal dan buat pelajar untuk mengajarkannya cara mengkoding
      * Tonton salah satu dari sesi Q&A dengan duta Hour of Code. Mereka akan direkam dan dapat di lihat pada halaman Code.org pada Youtube. Tahun ini partisipan termasuk Bill Gates, Sheryl Sandberg, Ashton Kutcher, dan banyak lagi!
      * Buat sekelompok pelajar untuk mendemonstrasikan aktivitas tanpa komputer
      * Buat sekelompok pelajar untuk mengajarkan kepala sekolah atau sekelompok uru bagaimana cara mengkoding
      * Jika sekolah telah mengajarkan ilmu komputer, buat para pelajar mendemonstrasikan projek

## 3) Bagikan bagaimana jadinya

  * Bagikan foto dari acaramu pada Facebook dan Twitter.
  * Gunakan hashtag **#HourofCode**

## Contoh Perencanaan Acara

**Acara:** Pertemuan pembukaan Computer Science Education Week

**Tanggal:** 8 Des (awal Computer Science Education Week)

**Waktu:** Saat sekolah. Lebih dianjurkan acara pertengahan pagi. Perkiraan sekitar satu jam.

**Lokasi:** Ruang pertemuan (teater, gym, kafetaria,dll)

## Jadwal Acara

      Waktu

      Kegiatan

      10:00-10:05 am

      Dibuka dengan salah satu dari video inspiratif kami

    10:05-10:15 am

    Kepala sekolah memberikan kata pembuka mengenai pentingnya ilmu komputer. Gunakan Statistik dan infographics sebagai referensi.

    10:15-10:17 am

    Dibuka dengan salah satu dari video inspiratif kami

    10:17-10:30 am

    Tamu spesial yang berbicara mengenai latar belakang mereka dan bagiaman teknologi dan ilmu komputer memainkan peran penting pada kehidupan sehari-hari.

    10:30-10:40 am

    Pelajar melakukan mendemostrasikan Hour of Code untuk skolah. Untuk hal menyenangkannya ajarkan kepala sekolah, politisi atau pelajar lain.

    10:40-11:00 pm

    Pelajar mendemostrasikan kegiatan tanpa komputer dan bagaimana ilmu komputer dapat diajarkan tanpa menggunakan komputer.

    11:00-11:05 pm

    Guru yang membantu mengadakan acara di sekolah memberikan pidato penutupan.


text:
* **Developer Manual**: Trabalho de Python.pdf
* **Installer**: cidadeBela.exe
* **Executable**: cidadeBela/
- _Run_ cidadeBela/cidadeBela/janelaGrafica.exe
- _Run - Dev_ cidadeBela/cidadeBela/janelaGrafica - Desenvolvedor.exe
* **Python Files**: cidadeBela.py/
 - _Easy run_ cidadeBela.py/janelaGrafica.py
 - _Easy run - Dev_ cidadeBela.py/janelaGrafica - Desenvolvedor.py
* **Tools**: Programa/

![Image demonstration 1](Demo1.png)
![Image demonstration 2](Demo2.png)
![Image demonstration 3](Demo3.png)
![Image demonstration 4](Demo4.png)


text:
function r = list(varargin)
jylist = jybuiltins('list');
r = jylist(varargin);


text:
require 'test_helper'

class MailEngine::MailTemplateFileTest < ActiveSupport::TestCase
  context "Mail template file" do
    setup do
      @template = FactoryGirl.create(:dirzip_mail_template, :format => "html")
    end

    context "after updated" do
      setup do
        @template.mail_template_files.last.update_attributes :file => File.open(File.join(Rails.root, '../..', 'test', 'fixtures', 'files', 'image.png'))
      end

      should "update the file url in the mail template html" do
        @template.reload
        assert @template.body.include?(@template.mail_template_files.last.file.url)
      end
    end
  end

end


text:
"use strict";

var Safe                = require("../Safe"),
    Type                = require("../Type"),
    Assert              = require("../Assert"),
    ExceptionList       = require("../Exception/ExceptionList"),
    Types               = require("./Types");

/**
 *
 * @class
 * Stores the result of a schema evaluation. It will keep reference to
 * the global structure and the evaluation tree as well.
 *
 * @param {*} schema
 * @param {*} value
 *
 *
 */
var SchemaResult = function(schema, value){

    /// validate schema
    Assert.instanceOf(Types.SchemaDefinition)
        .assert(schema);

    /// make sure its a value
    value = Safe.value(value);

    /**
     *
     * Top-down global error tracking
     *
     * @type {ExceptionList}
     *
     */
    var errors = new ExceptionList();

    /**
     *
     * SchemaResult API
     *
     * @type {Object}
     *
     */
    var self = {

        /**
         *
         * Get the errors
         *
         * @return {ExceptionList}
         *
         */
        getErrors: function(){
            return errors;
        },

        /**
         *
         * Add the given errors
         *
         * @param {ExceptionList} error
         *
         */
        addError: function(error){
            errors.push(error);
        },

        /**
         *
         * Checks if the result is valid
         *
         * @return {Boolean}
         *
         */
        isValid: function(){
            return errors.length === 0;
        },

        /**
         *
         * Get the value result.
         *
         * @return {*}
         *
         */
        getValue: function(){
            return value;
        },

        /**
         *
         * Set the value of the given index.
         *
         * @param {*} value
         * @param {Object} options
         *
         */
        setValue: function(val, options) {

            /// normalize val
            val = Safe.value(val);

            /// normalize options
            options = Safe.object(options);
            options.index   = Safe.value(options.index, null);

            if(options.index !== null){
                value[options.index] = val;
            }
            else {
                value = val;
            }

        }

    };

    /// expose module as 'Typed' SchemaResult instance
    return new Types.SchemaResult(self);

};

module.exports = SchemaResult;


text:
import * as Preact from '../../../src/preact';
import {WithAmpContext} from '../../../src/preact/context';
import {animateCollapse, animateExpand} from './animations';
import {forwardRef} from '../../../src/preact/compat';
import {omit} from '../../../src/core/types/object';
import {
  randomIdGenerator,
  sequentialIdGenerator,
} from '../../../src/utils/id-generator';
import {
  useCallback,
  useContext,
  useEffect,
  useImperativeHandle,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
} from '../../../src/preact';
import {useStyles} from './component.jss';
import objstr from 'obj-str';

const AccordionContext = Preact.createContext(
  /** @type {AccordionDef.AccordionContext} */ ({})
);

const SectionContext = Preact.createContext(
  /** @type {AccordionDef.SectionContext} */ ({})
);

/** @type {!Object<string, boolean>} */
const EMPTY_EXPANDED_MAP = {};

/** @type {!Object<string, function(boolean):undefined|undefined>} */
const EMPTY_EVENT_MAP = {};

const generateSectionId = sequentialIdGenerator();
const generateRandomId = randomIdGenerator(100000);

/**
 * @param {!AccordionDef.AccordionProps} props
 * @param {{current: (!AccordionDef.AccordionApi|null)}} ref
 * @return {PreactDef.Renderable}
 */
function AccordionWithRef(
  {
    as: Comp = 'section',
    expandSingleSection = false,
    animate = false,
    children,
    id,
    ...rest
  },
  ref
) {
  const [expandedMap, setExpandedMap] = useState(EMPTY_EXPANDED_MAP);
  const eventMapRef = useRef(EMPTY_EVENT_MAP);
  const [randomPrefix] = useState(generateRandomId);
  const prefix = id || `a${randomPrefix}`;

  useEffect(() => {
    if (!expandSingleSection) {
      return;
    }
    setExpandedMap((expandedMap) => {
      const newExpandedMap = {};
      let expanded = 0;
      for (const k in expandedMap) {
        newExpandedMap[k] = expandedMap[k] && expanded++ == 0;
      }
      return newExpandedMap;
    });
  }, [expandSingleSection]);

  const registerSection = useCallback(
    (id, defaultExpanded, {current: onExpandStateChange}) => {
      setExpandedMap((expandedMap) => {
        return setExpanded(
          id,
          defaultExpanded,
          expandedMap,
          expandSingleSection
        );
      });
      eventMapRef.current = {...eventMapRef.current, [id]: onExpandStateChange};
      return () => {
        setExpandedMap((expandedMap) => omit(expandedMap, id));
        eventMapRef.current = omit(
          /** @type {!Object} */ (eventMapRef.current),
          id
        );
      };
    },
    [expandSingleSection]
  );

  const toggleExpanded = useCallback(
    (id, opt_expand) => {
      setExpandedMap((expandedMap) => {
        const newExpanded = opt_expand ?? !expandedMap[id];
        const newExpandedMap = setExpanded(
          id,
          newExpanded,
          expandedMap,
          expandSingleSection
        );

        // Schedule a single microtask to fire events for
        // all changed sections (order not defined)
        Promise.resolve().then(() => {
          for (const k in expandedMap) {
            const onExpandStateChange = eventMapRef.current[k];
            if (onExpandStateChange && expandedMap[k] != newExpandedMap[k]) {
              onExpandStateChange(newExpandedMap[k]);
            }
          }
        });
        return newExpandedMap;
      });
    },
    [expandSingleSection]
  );

  const isExpanded = useCallback(
    (id, defaultExpanded) => expandedMap[id] ?? defaultExpanded,
    [expandedMap]
  );

  const toggle = useCallback(
    (id) => {
      if (id) {
        if (id in expandedMap) {
          toggleExpanded(id);
        }
      } else {
        // Toggle all should do nothing when expandSingleSection is true
        if (!expandSingleSection) {
          for (const k in expandedMap) {
            toggleExpanded(k);
          }
        }
      }
    },
    [expandedMap, toggleExpanded, expandSingleSection]
  );

  const expand = useCallback(
    (id) => {
      if (id) {
        if (!isExpanded(id, true)) {
          toggleExpanded(id);
        }
      } else {
        // Expand all should do nothing when expandSingleSection is true
        if (!expandSingleSection) {
          for (const k in expandedMap) {
            if (!isExpanded(k, true)) {
              toggleExpanded(k);
            }
          }
        }
      }
    },
    [expandedMap, toggleExpanded, isExpanded, expandSingleSection]
  );

  const collapse = useCallback(
    (id) => {
      if (id) {
        if (isExpanded(id, false)) {
          toggleExpanded(id);
        }
      } else {
        for (const k in expandedMap) {
          if (isExpanded(k, false)) {
            toggleExpanded(k);
          }
        }
      }
    },
    [expandedMap, toggleExpanded, isExpanded]
  );

  useImperativeHandle(
    ref,
    () =>
      /** @type {!AccordionDef.AccordionApi} */ ({
        toggle,
        expand,
        collapse,
      }),
    [toggle, collapse, expand]
  );

  const context = useMemo(
    () =>
      /** @type {!AccordionDef.AccordionContext} */ ({
        registerSection,
        toggleExpanded,
        isExpanded,
        animate,
        prefix,
      }),
    [registerSection, toggleExpanded, isExpanded, animate, prefix]
  );

  return (
    <Comp id={id} {...rest}>
      <AccordionContext.Provider value={context}>
        {children}
      </AccordionContext.Provider>
    </Comp>
  );
}

const Accordion = forwardRef(AccordionWithRef);
Accordion.displayName = 'Accordion'; // Make findable for tests.
export {Accordion};

/**
 * @param {string} id
 * @param {boolean} value
 * @param {!Object<string, boolean>} expandedMap
 * @param {boolean} expandSingleSection
 * @return {!Object<string, boolean>}
 */
function setExpanded(id, value, expandedMap, expandSingleSection) {
  let newExpandedMap;
  if (expandSingleSection && value) {
    newExpandedMap = {[id]: value};
    for (const k in expandedMap) {
      if (k != id) {
        newExpandedMap[k] = false;
      }
    }
  } else {
    newExpandedMap = {...expandedMap, [id]: value};
  }
  return newExpandedMap;
}

/**
 * @param {!AccordionDef.AccordionSectionProps} props
 * @return {PreactDef.Renderable}
 */
export function AccordionSection({
  as: Comp = 'section',
  expanded: defaultExpanded = false,
  animate: defaultAnimate = false,
  id: propId,
  children,
  onExpandStateChange,
  ...rest
}) {
  const [genId] = useState(generateSectionId);
  const id = propId || genId;
  const [suffix] = useState(generateRandomId);
  const [expandedState, setExpandedState] = useState(defaultExpanded);
  const [contentIdState, setContentIdState] = useState(null);
  const [headerIdState, setHeaderIdState] = useState(null);

  const {
    registerSection,
    animate: contextAnimate,
    isExpanded,
    toggleExpanded,
    prefix,
  } = useContext(AccordionContext);

  const expanded = isExpanded ? isExpanded(id, defaultExpanded) : expandedState;
  const animate = contextAnimate ?? defaultAnimate;
  const contentId =
    contentIdState || `${prefix || 'a'}-content-${id}-${suffix}`;
  const headerId = headerIdState || `${prefix || 'a'}-header-${id}-${suffix}`;

  // Storing this state change callback in a ref because this may change
  // frequently and we do not want to trigger a re-register of the section
  // each time  the callback is updated
  const onExpandStateChangeRef = useRef(
    /** @type {?function(boolean):undefined|undefined} */ (null)
  );
  onExpandStateChangeRef.current = onExpandStateChange;
  useLayoutEffect(() => {
    if (registerSection) {
      return registerSection(id, defaultExpanded, onExpandStateChangeRef);
    }
  }, [registerSection, id, defaultExpanded]);

  const toggleHandler = useCallback(
    (opt_expand) => {
      if (toggleExpanded) {
        toggleExpanded(id, opt_expand);
      } else {
        setExpandedState((prev) => {
          const newValue = opt_expand ?? !prev;
          Promise.resolve().then(() => {
            const onExpandStateChange = onExpandStateChangeRef.current;
            if (onExpandStateChange) {
              onExpandStateChange(newValue);
            }
          });
          return newValue;
        });
      }
    },
    [id, toggleExpanded]
  );

  const context = useMemo(
    () =>
      /** @type {AccordionDef.SectionContext} */ ({
        animate,
        contentId,
        headerId,
        expanded,
        toggleHandler,
        setContentId: setContentIdState,
        setHeaderId: setHeaderIdState,
      }),
    [animate, contentId, headerId, expanded, toggleHandler]
  );

  return (
    <Comp {...rest} expanded={expanded}>
      <SectionContext.Provider value={context}>
        {children}
      </SectionContext.Provider>
    </Comp>
  );
}

/**
 * @param {!AccordionDef.AccordionHeaderProps} props
 * @return {PreactDef.Renderable}
 */
export function AccordionHeader({
  as: Comp = 'div',
  role = 'button',
  className = '',
  tabIndex = 0,
  id,
  children,
  ...rest
}) {
  const {
    contentId,
    headerId,
    expanded,
    toggleHandler,
    setHeaderId,
  } = useContext(SectionContext);
  const classes = useStyles();

  useLayoutEffect(() => {
    if (setHeaderId) {
      setHeaderId(id);
    }
  }, [setHeaderId, id]);

  return (
    <Comp
      {...rest}
      id={headerId}
      role={role}
      className={`${className} ${classes.sectionChild} ${classes.header}`}
      tabIndex={tabIndex}
      aria-controls={contentId}
      onClick={() => toggleHandler()}
      aria-expanded={String(expanded)}
    >
      {children}
    </Comp>
  );
}

/**
 * @param {!AccordionDef.AccordionContentProps} props
 * @return {PreactDef.Renderable}
 */
export function AccordionContent({
  as: Comp = 'div',
  role = 'region',
  className = '',
  id,
  children,
  ...rest
}) {
  const ref = useRef(null);
  const hasMountedRef = useRef(false);
  const {contentId, headerId, expanded, animate, setContentId} = useContext(
    SectionContext
  );
  const classes = useStyles();

  useEffect(() => {
    hasMountedRef.current = true;
    return () => (hasMountedRef.current = false);
  }, []);

  useLayoutEffect(() => {
    if (setContentId) {
      setContentId(id);
    }
  }, [setContentId, id]);

  useLayoutEffect(() => {
    const hasMounted = hasMountedRef.current;
    const content = ref.current;
    if (!animate || !hasMounted || !content || !content.animate) {
      return;
    }
    return expanded ? animateExpand(content) : animateCollapse(content);
  }, [expanded, animate]);

  return (
    <WithAmpContext renderable={expanded}>
      <Comp
        {...rest}
        ref={ref}
        className={objstr({
          [className]: true,
          [classes.sectionChild]: true,
          [classes.contentHidden]: !expanded,
        })}
        id={contentId}
        aria-labelledby={headerId}
        role={role}
      >
        {children}
      </Comp>
    </WithAmpContext>
  );
}