text:
.class final Lokhttp3/Cache$Entry;
.super Ljava/lang/Object;
.source "Cache.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lokhttp3/Cache;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x1a
    name = "Entry"
.end annotation

# static fields
.field private static final RECEIVED_MILLIS:Ljava/lang/String;

.field private static final SENT_MILLIS:Ljava/lang/String;

# instance fields
.field private final code:I

.field private final handshake:Lokhttp3/Handshake;
    .annotation runtime Ljavax/annotation/Nullable;
    .end annotation
.end field

.field private final message:Ljava/lang/String;

.field private final protocol:Lokhttp3/Protocol;

.field private final receivedResponseMillis:J

.field private final requestMethod:Ljava/lang/String;

.field private final responseHeaders:Lokhttp3/Headers;

.field private final sentRequestMillis:J

.field private final url:Ljava/lang/String;

.field private final varyHeaders:Lokhttp3/Headers;

# direct methods
.method static constructor <clinit>()V
    .locals 2

    .prologue
    .line 476
    new-instance v0, Ljava/lang/StringBuilder;

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

    invoke-static {}, Lokhttp3/internal/platform/Platform;->get()Lokhttp3/internal/platform/Platform;

    move-result-object v1

    invoke-virtual {v1}, Lokhttp3/internal/platform/Platform;->getPrefix()Ljava/lang/String;

    move-result-object v1

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

    move-result-object v0

    const-string v1, "-Sent-Millis"

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

    move-result-object v0

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

    move-result-object v0

    sput-object v0, Lokhttp3/Cache$Entry;->SENT_MILLIS:Ljava/lang/String;

    .line 479
    new-instance v0, Ljava/lang/StringBuilder;

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

    invoke-static {}, Lokhttp3/internal/platform/Platform;->get()Lokhttp3/internal/platform/Platform;

    move-result-object v1

    invoke-virtual {v1}, Lokhttp3/internal/platform/Platform;->getPrefix()Ljava/lang/String;

    move-result-object v1

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

    move-result-object v0

    const-string v1, "-Received-Millis"

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

    move-result-object v0

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

    move-result-object v0

    sput-object v0, Lokhttp3/Cache$Entry;->RECEIVED_MILLIS:Ljava/lang/String;

    return-void
.end method

.method constructor <init>(Lokhttp3/Response;)V
    .locals 2
    .param p1, "response"    # Lokhttp3/Response;

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

    .line 595
    invoke-virtual {p1}, Lokhttp3/Response;->request()Lokhttp3/Request;

    move-result-object v0

    invoke-virtual {v0}, Lokhttp3/Request;->url()Lokhttp3/HttpUrl;

    move-result-object v0

    invoke-virtual {v0}, Lokhttp3/HttpUrl;->toString()Ljava/lang/String;

    move-result-object v0

    iput-object v0, p0, Lokhttp3/Cache$Entry;->url:Ljava/lang/String;

    .line 596
    invoke-static {p1}, Lokhttp3/internal/http/HttpHeaders;->varyHeaders(Lokhttp3/Response;)Lokhttp3/Headers;

    move-result-object v0

    iput-object v0, p0, Lokhttp3/Cache$Entry;->varyHeaders:Lokhttp3/Headers;

    .line 597
    invoke-virtual {p1}, Lokhttp3/Response;->request()Lokhttp3/Request;

    move-result-object v0

    invoke-virtual {v0}, Lokhttp3/Request;->method()Ljava/lang/String;

    move-result-object v0

    iput-object v0, p0, Lokhttp3/Cache$Entry;->requestMethod:Ljava/lang/String;

    .line 598
    invoke-virtual {p1}, Lokhttp3/Response;->protocol()Lokhttp3/Protocol;

    move-result-object v0

    iput-object v0, p0, Lokhttp3/Cache$Entry;->protocol:Lokhttp3/Protocol;

    .line 599
    invoke-virtual {p1}, Lokhttp3/Response;->code()I

    move-result v0

    iput v0, p0, Lokhttp3/Cache$Entry;->code:I

    .line 600
    invoke-virtual {p1}, Lokhttp3/Response;->message()Ljava/lang/String;

    move-result-object v0

    iput-object v0, p0, Lokhttp3/Cache$Entry;->message:Ljava/lang/String;

    .line 601
    invoke-virtual {p1}, Lokhttp3/Response;->headers()Lokhttp3/Headers;

    move-result-object v0

    iput-object v0, p0, Lokhttp3/Cache$Entry;->responseHeaders:Lokhttp3/Headers;

    .line 602
    invoke-virtual {p1}, Lokhttp3/Response;->handshake()Lokhttp3/Handshake;

    move-result-object v0

    iput-object v0, p0, Lokhttp3/Cache$Entry;->handshake:Lokhttp3/Handshake;

    .line 603
    invoke-virtual {p1}, Lokhttp3/Response;->sentRequestAtMillis()J

    move-result-wide v0

    iput-wide v0, p0, Lokhttp3/Cache$Entry;->sentRequestMillis:J

    .line 604
    invoke-virtual {p1}, Lokhttp3/Response;->receivedResponseAtMillis()J

    move-result-wide v0

    iput-wide v0, p0, Lokhttp3/Cache$Entry;->receivedResponseMillis:J

    .line 605
    return-void
.end method

.method constructor <init>(Lokio/Source;)V
    .locals 22
    .param p1, "in"    # Lokio/Source;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    .prologue
    .line 540
    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    .line 542
    :try_start_0
    invoke-static/range {p1 .. p1}, Lokio/Okio;->buffer(Lokio/Source;)Lokio/BufferedSource;

    move-result-object v14

    .line 543
    .local v14, "source":Lokio/BufferedSource;
    invoke-interface {v14}, Lokio/BufferedSource;->readUtf8LineStrict()Ljava/lang/String;

    move-result-object v19

    move-object/from16 v0, v19

    move-object/from16 v1, p0

    iput-object v0, v1, Lokhttp3/Cache$Entry;->url:Ljava/lang/String;

    .line 544
    invoke-interface {v14}, Lokio/BufferedSource;->readUtf8LineStrict()Ljava/lang/String;

    move-result-object v19

    move-object/from16 v0, v19

    move-object/from16 v1, p0

    iput-object v0, v1, Lokhttp3/Cache$Entry;->requestMethod:Ljava/lang/String;

    .line 545
    new-instance v17, Lokhttp3/Headers$Builder;

    invoke-direct/range {v17 .. v17}, Lokhttp3/Headers$Builder;-><init>()V

    .line 546
    .local v17, "varyHeadersBuilder":Lokhttp3/Headers$Builder;
    invoke-static {v14}, Lokhttp3/Cache;->readInt(Lokio/BufferedSource;)I

    move-result v18

    .line 547
    .local v18, "varyRequestHeaderLineCount":I
    const/4 v7, 0x0

    .local v7, "i":I
    :goto_0
    move/from16 v0, v18

    if-ge v7, v0, :cond_0

    .line 548
    invoke-interface {v14}, Lokio/BufferedSource;->readUtf8LineStrict()Ljava/lang/String;

    move-result-object v19

    move-object/from16 v0, v17

    move-object/from16 v1, v19

    invoke-virtual {v0, v1}, Lokhttp3/Headers$Builder;->addLenient(Ljava/lang/String;)Lokhttp3/Headers$Builder;

    .line 547
    add-int/lit8 v7, v7, 0x1

    goto :goto_0

    .line 550
    :cond_0
    invoke-virtual/range {v17 .. v17}, Lokhttp3/Headers$Builder;->build()Lokhttp3/Headers;

    move-result-object v19

    move-object/from16 v0, v19

    move-object/from16 v1, p0

    iput-object v0, v1, Lokhttp3/Cache$Entry;->varyHeaders:Lokhttp3/Headers;

    .line 552
    invoke-interface {v14}, Lokio/BufferedSource;->readUtf8LineStrict()Ljava/lang/String;

    move-result-object v19

    invoke-static/range {v19 .. v19}, Lokhttp3/internal/http/StatusLine;->parse(Ljava/lang/String;)Lokhttp3/internal/http/StatusLine;

    move-result-object v15

    .line 553
    .local v15, "statusLine":Lokhttp3/internal/http/StatusLine;
    iget-object v0, v15, Lokhttp3/internal/http/StatusLine;->protocol:Lokhttp3/Protocol;

    move-object/from16 v19, v0

    move-object/from16 v0, v19

    move-object/from16 v1, p0

    iput-object v0, v1, Lokhttp3/Cache$Entry;->protocol:Lokhttp3/Protocol;

    .line 554
    iget v0, v15, Lokhttp3/internal/http/StatusLine;->code:I

    move/from16 v19, v0

    move/from16 v0, v19

    move-object/from16 v1, p0

    iput v0, v1, Lokhttp3/Cache$Entry;->code:I

    .line 555
    iget-object v0, v15, Lokhttp3/internal/http/StatusLine;->message:Ljava/lang/String;

    move-object/from16 v19, v0

    move-object/from16 v0, v19

    move-object/from16 v1, p0

    iput-object v0, v1, Lokhttp3/Cache$Entry;->message:Ljava/lang/String;

    .line 556
    new-instance v12, Lokhttp3/Headers$Builder;

    invoke-direct {v12}, Lokhttp3/Headers$Builder;-><init>()V

    .line 557
    .local v12, "responseHeadersBuilder":Lokhttp3/Headers$Builder;
    invoke-static {v14}, Lokhttp3/Cache;->readInt(Lokio/BufferedSource;)I

    move-result v11

    .line 558
    .local v11, "responseHeaderLineCount":I
    const/4 v7, 0x0

    :goto_1
    if-ge v7, v11, :cond_1

    .line 559
    invoke-interface {v14}, Lokio/BufferedSource;->readUtf8LineStrict()Ljava/lang/String;

    move-result-object v19

    move-object/from16 v0, v19

    invoke-virtual {v12, v0}, Lokhttp3/Headers$Builder;->addLenient(Ljava/lang/String;)Lokhttp3/Headers$Builder;

    .line 558
    add-int/lit8 v7, v7, 0x1

    goto :goto_1

    .line 561
    :cond_1
    sget-object v19, Lokhttp3/Cache$Entry;->SENT_MILLIS:Ljava/lang/String;

    move-object/from16 v0, v19

    invoke-virtual {v12, v0}, Lokhttp3/Headers$Builder;->get(Ljava/lang/String;)Ljava/lang/String;

    move-result-object v13

    .line 562
    .local v13, "sendRequestMillisString":Ljava/lang/String;
    sget-object v19, Lokhttp3/Cache$Entry;->RECEIVED_MILLIS:Ljava/lang/String;

    move-object/from16 v0, v19

    invoke-virtual {v12, v0}, Lokhttp3/Headers$Builder;->get(Ljava/lang/String;)Ljava/lang/String;

    move-result-object v10

    .line 563
    .local v10, "receivedResponseMillisString":Ljava/lang/String;
    sget-object v19, Lokhttp3/Cache$Entry;->SENT_MILLIS:Ljava/lang/String;

    move-object/from16 v0, v19

    invoke-virtual {v12, v0}, Lokhttp3/Headers$Builder;->removeAll(Ljava/lang/String;)Lokhttp3/Headers$Builder;

    .line 564
    sget-object v19, Lokhttp3/Cache$Entry;->RECEIVED_MILLIS:Ljava/lang/String;

    move-object/from16 v0, v19

    invoke-virtual {v12, v0}, Lokhttp3/Headers$Builder;->removeAll(Ljava/lang/String;)Lokhttp3/Headers$Builder;

    .line 565
    if-eqz v13, :cond_2

    .line 566
    invoke-static {v13}, Ljava/lang/Long;->parseLong(Ljava/lang/String;)J

    move-result-wide v20

    .line 567
    :goto_2
    move-wide/from16 v0, v20

    move-object/from16 v2, p0

    iput-wide v0, v2, Lokhttp3/Cache$Entry;->sentRequestMillis:J

    .line 568
    if-eqz v10, :cond_3

    .line 569
    invoke-static {v10}, Ljava/lang/Long;->parseLong(Ljava/lang/String;)J

    move-result-wide v20

    .line 570
    :goto_3
    move-wide/from16 v0, v20

    move-object/from16 v2, p0

    iput-wide v0, v2, Lokhttp3/Cache$Entry;->receivedResponseMillis:J

    .line 571
    invoke-virtual {v12}, Lokhttp3/Headers$Builder;->build()Lokhttp3/Headers;

    move-result-object v19

    move-object/from16 v0, v19

    move-object/from16 v1, p0

    iput-object v0, v1, Lokhttp3/Cache$Entry;->responseHeaders:Lokhttp3/Headers;

    .line 573
    invoke-direct/range {p0 .. p0}, Lokhttp3/Cache$Entry;->isHttps()Z

    move-result v19

    if-eqz v19, :cond_6

    .line 574
    invoke-interface {v14}, Lokio/BufferedSource;->readUtf8LineStrict()Ljava/lang/String;

    move-result-object v4

    .line 575
    .local v4, "blank":Ljava/lang/String;
    invoke-virtual {v4}, Ljava/lang/String;->length()I

    move-result v19

    if-lez v19, :cond_4

    .line 576
    new-instance v19, Ljava/io/IOException;

    new-instance v20, Ljava/lang/StringBuilder;

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

    const-string v21, "expected \"\" but was \""

    invoke-virtual/range {v20 .. v21}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v20

    move-object/from16 v0, v20

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

    move-result-object v20

    const-string v21, "\""

    invoke-virtual/range {v20 .. v21}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v20

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

    move-result-object v20

    invoke-direct/range {v19 .. v20}, Ljava/io/IOException;-><init>(Ljava/lang/String;)V

    throw v19
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 590
    .end local v4    # "blank":Ljava/lang/String;
    .end local v7    # "i":I
    .end local v10    # "receivedResponseMillisString":Ljava/lang/String;
    .end local v11    # "responseHeaderLineCount":I
    .end local v12    # "responseHeadersBuilder":Lokhttp3/Headers$Builder;
    .end local v13    # "sendRequestMillisString":Ljava/lang/String;
    .end local v14    # "source":Lokio/BufferedSource;
    .end local v15    # "statusLine":Lokhttp3/internal/http/StatusLine;
    .end local v17    # "varyHeadersBuilder":Lokhttp3/Headers$Builder;
    .end local v18    # "varyRequestHeaderLineCount":I
    :catchall_0
    move-exception v19

    invoke-interface/range {p1 .. p1}, Lokio/Source;->close()V

    throw v19

    .line 567
    .restart local v7    # "i":I
    .restart local v10    # "receivedResponseMillisString":Ljava/lang/String;
    .restart local v11    # "responseHeaderLineCount":I
    .restart local v12    # "responseHeadersBuilder":Lokhttp3/Headers$Builder;
    .restart local v13    # "sendRequestMillisString":Ljava/lang/String;
    .restart local v14    # "source":Lokio/BufferedSource;
    .restart local v15    # "statusLine":Lokhttp3/internal/http/StatusLine;
    .restart local v17    # "varyHeadersBuilder":Lokhttp3/Headers$Builder;
    .restart local v18    # "varyRequestHeaderLineCount":I
    :cond_2
    const-wide/16 v20, 0x0

    goto :goto_2

    .line 570
    :cond_3
    const-wide/16 v20, 0x0

    goto :goto_3

    .line 578
    .restart local v4    # "blank":Ljava/lang/String;
    :cond_4
    :try_start_1
    invoke-interface {v14}, Lokio/BufferedSource;->readUtf8LineStrict()Ljava/lang/String;

    move-result-object v6

    .line 579
    .local v6, "cipherSuiteString":Ljava/lang/String;
    invoke-static {v6}, Lokhttp3/CipherSuite;->forJavaName(Ljava/lang/String;)Lokhttp3/CipherSuite;

    move-result-object v5

    .line 580
    .local v5, "cipherSuite":Lokhttp3/CipherSuite;
    move-object/from16 v0, p0

    invoke-direct {v0, v14}, Lokhttp3/Cache$Entry;->readCertificateList(Lokio/BufferedSource;)Ljava/util/List;

    move-result-object v9

    .line 581
    .local v9, "peerCertificates":Ljava/util/List;, "Ljava/util/List<Ljava/security/cert/Certificate;>;"
    move-object/from16 v0, p0

    invoke-direct {v0, v14}, Lokhttp3/Cache$Entry;->readCertificateList(Lokio/BufferedSource;)Ljava/util/List;

    move-result-object v8

    .line 582
    .local v8, "localCertificates":Ljava/util/List;, "Ljava/util/List<Ljava/security/cert/Certificate;>;"
    invoke-interface {v14}, Lokio/BufferedSource;->exhausted()Z

    move-result v19

    if-nez v19, :cond_5

    .line 583
    invoke-interface {v14}, Lokio/BufferedSource;->readUtf8LineStrict()Ljava/lang/String;

    move-result-object v19

    invoke-static/range {v19 .. v19}, Lokhttp3/TlsVersion;->forJavaName(Ljava/lang/String;)Lokhttp3/TlsVersion;

    move-result-object v16

    .line 585
    .local v16, "tlsVersion":Lokhttp3/TlsVersion;
    :goto_4
    move-object/from16 v0, v16

    invoke-static {v0, v5, v9, v8}, Lokhttp3/Handshake;->get(Lokhttp3/TlsVersion;Lokhttp3/CipherSuite;Ljava/util/List;Ljava/util/List;)Lokhttp3/Handshake;

    move-result-object v19

    move-object/from16 v0, v19

    move-object/from16 v1, p0

    iput-object v0, v1, Lokhttp3/Cache$Entry;->handshake:Lokhttp3/Handshake;
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_0

    .line 590
    .end local v4    # "blank":Ljava/lang/String;
    .end local v5    # "cipherSuite":Lokhttp3/CipherSuite;
    .end local v6    # "cipherSuiteString":Ljava/lang/String;
    .end local v8    # "localCertificates":Ljava/util/List;, "Ljava/util/List<Ljava/security/cert/Certificate;>;"
    .end local v9    # "peerCertificates":Ljava/util/List;, "Ljava/util/List<Ljava/security/cert/Certificate;>;"
    .end local v16    # "tlsVersion":Lokhttp3/TlsVersion;
    :goto_5
    invoke-interface/range {p1 .. p1}, Lokio/Source;->close()V

    .line 592
    return-void

    .line 584
    .restart local v4    # "blank":Ljava/lang/String;
    .restart local v5    # "cipherSuite":Lokhttp3/CipherSuite;
    .restart local v6    # "cipherSuiteString":Ljava/lang/String;
    .restart local v8    # "localCertificates":Ljava/util/List;, "Ljava/util/List<Ljava/security/cert/Certificate;>;"
    .restart local v9    # "peerCertificates":Ljava/util/List;, "Ljava/util/List<Ljava/security/cert/Certificate;>;"
    :cond_5
    :try_start_2
    sget-object v16, Lokhttp3/TlsVersion;->SSL_3_0:Lokhttp3/TlsVersion;

    goto :goto_4

    .line 587
    .end local v4    # "blank":Ljava/lang/String;
    .end local v5    # "cipherSuite":Lokhttp3/CipherSuite;
    .end local v6    # "cipherSuiteString":Ljava/lang/String;
    .end local v8    # "localCertificates":Ljava/util/List;, "Ljava/util/List<Ljava/security/cert/Certificate;>;"
    .end local v9    # "peerCertificates":Ljava/util/List;, "Ljava/util/List<Ljava/security/cert/Certificate;>;"
    :cond_6
    const/16 v19, 0x0

    move-object/from16 v0, v19

    move-object/from16 v1, p0

    iput-object v0, v1, Lokhttp3/Cache$Entry;->handshake:Lokhttp3/Handshake;
    :try_end_2
    .catchall {:try_start_2 .. :try_end_2} :catchall_0

    goto :goto_5
.end method

.method private isHttps()Z
    .locals 2

    .prologue
    .line 654
    iget-object v0, p0, Lokhttp3/Cache$Entry;->url:Ljava/lang/String;

    const-string v1, "https://"

    invoke-virtual {v0, v1}, Ljava/lang/String;->startsWith(Ljava/lang/String;)Z

    move-result v0

    return v0
.end method

.method private readCertificateList(Lokio/BufferedSource;)Ljava/util/List;
    .locals 9
    .param p1, "source"    # Lokio/BufferedSource;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Lokio/BufferedSource;",
            ")",
            "Ljava/util/List",
            "<",
            "Ljava/security/cert/Certificate;",
            ">;"
        }
    .end annotation

    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    .prologue
    .line 658
    invoke-static {p1}, Lokhttp3/Cache;->readInt(Lokio/BufferedSource;)I

    move-result v4

    .line 659
    .local v4, "length":I
    const/4 v7, -0x1

    if-ne v4, v7, :cond_1

    invoke-static {}, Ljava/util/Collections;->emptyList()Ljava/util/List;

    move-result-object v6

    .line 670
    :cond_0
    return-object v6

    .line 662
    :cond_1
    :try_start_0
    const-string v7, "X.509"

    invoke-static {v7}, Ljava/security/cert/CertificateFactory;->getInstance(Ljava/lang/String;)Ljava/security/cert/CertificateFactory;

    move-result-object v1

    .line 663
    .local v1, "certificateFactory":Ljava/security/cert/CertificateFactory;
    new-instance v6, Ljava/util/ArrayList;

    invoke-direct {v6, v4}, Ljava/util/ArrayList;-><init>(I)V

    .line 664
    .local v6, "result":Ljava/util/List;, "Ljava/util/List<Ljava/security/cert/Certificate;>;"
    const/4 v3, 0x0

    .local v3, "i":I
    :goto_0
    if-ge v3, v4, :cond_0

    .line 665
    invoke-interface {p1}, Lokio/BufferedSource;->readUtf8LineStrict()Ljava/lang/String;

    move-result-object v5

    .line 666
    .local v5, "line":Ljava/lang/String;
    new-instance v0, Lokio/Buffer;

    invoke-direct {v0}, Lokio/Buffer;-><init>()V

    .line 667
    .local v0, "bytes":Lokio/Buffer;
    invoke-static {v5}, Lokio/ByteString;->decodeBase64(Ljava/lang/String;)Lokio/ByteString;

    move-result-object v7

    invoke-virtual {v0, v7}, Lokio/Buffer;->write(Lokio/ByteString;)Lokio/Buffer;

    .line 668
    invoke-virtual {v0}, Lokio/Buffer;->inputStream()Ljava/io/InputStream;

    move-result-object v7

    invoke-virtual {v1, v7}, Ljava/security/cert/CertificateFactory;->generateCertificate(Ljava/io/InputStream;)Ljava/security/cert/Certificate;

    move-result-object v7

    invoke-interface {v6, v7}, Ljava/util/List;->add(Ljava/lang/Object;)Z
    :try_end_0
    .catch Ljava/security/cert/CertificateException; {:try_start_0 .. :try_end_0} :catch_0

    .line 664
    add-int/lit8 v3, v3, 0x1

    goto :goto_0

    .line 671
    .end local v0    # "bytes":Lokio/Buffer;
    .end local v1    # "certificateFactory":Ljava/security/cert/CertificateFactory;
    .end local v3    # "i":I
    .end local v5    # "line":Ljava/lang/String;
    .end local v6    # "result":Ljava/util/List;, "Ljava/util/List<Ljava/security/cert/Certificate;>;"
    :catch_0
    move-exception v2

    .line 672
    .local v2, "e":Ljava/security/cert/CertificateException;
    new-instance v7, Ljava/io/IOException;

    invoke-virtual {v2}, Ljava/security/cert/CertificateException;->getMessage()Ljava/lang/String;

    move-result-object v8

    invoke-direct {v7, v8}, Ljava/io/IOException;-><init>(Ljava/lang/String;)V

    throw v7
.end method

.method private writeCertList(Lokio/BufferedSink;Ljava/util/List;)V
    .locals 8
    .param p1, "sink"    # Lokio/BufferedSink;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Lokio/BufferedSink;",
            "Ljava/util/List",
            "<",
            "Ljava/security/cert/Certificate;",
            ">;)V"
        }
    .end annotation

    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    .prologue
    .line 679
    .local p2, "certificates":Ljava/util/List;, "Ljava/util/List<Ljava/security/cert/Certificate;>;"
    :try_start_0
    invoke-interface {p2}, Ljava/util/List;->size()I

    move-result v5

    int-to-long v6, v5

    invoke-interface {p1, v6, v7}, Lokio/BufferedSink;->writeDecimalLong(J)Lokio/BufferedSink;

    move-result-object v5

    const/16 v6, 0xa

    .line 680
    invoke-interface {v5, v6}, Lokio/BufferedSink;->writeByte(I)Lokio/BufferedSink;

    .line 681
    const/4 v2, 0x0

    .local v2, "i":I
    invoke-interface {p2}, Ljava/util/List;->size()I

    move-result v4

    .local v4, "size":I
    :goto_0
    if-ge v2, v4, :cond_0

    .line 682
    invoke-interface {p2, v2}, Ljava/util/List;->get(I)Ljava/lang/Object;

    move-result-object v5

    check-cast v5, Ljava/security/cert/Certificate;

    invoke-virtual {v5}, Ljava/security/cert/Certificate;->getEncoded()[B

    move-result-object v0

    .line 683
    .local v0, "bytes":[B
    invoke-static {v0}, Lokio/ByteString;->of([B)Lokio/ByteString;

    move-result-object v5

    invoke-virtual {v5}, Lokio/ByteString;->base64()Ljava/lang/String;

    move-result-object v3

    .line 684
    .local v3, "line":Ljava/lang/String;
    invoke-interface {p1, v3}, Lokio/BufferedSink;->writeUtf8(Ljava/lang/String;)Lokio/BufferedSink;

    move-result-object v5

    const/16 v6, 0xa

    .line 685
    invoke-interface {v5, v6}, Lokio/BufferedSink;->writeByte(I)Lokio/BufferedSink;
    :try_end_0
    .catch Ljava/security/cert/CertificateEncodingException; {:try_start_0 .. :try_end_0} :catch_0

    .line 681
    add-int/lit8 v2, v2, 0x1

    goto :goto_0

    .line 687
    .end local v0    # "bytes":[B
    .end local v2    # "i":I
    .end local v3    # "line":Ljava/lang/String;
    .end local v4    # "size":I
    :catch_0
    move-exception v1

    .line 688
    .local v1, "e":Ljava/security/cert/CertificateEncodingException;
    new-instance v5, Ljava/io/IOException;

    invoke-virtual {v1}, Ljava/security/cert/CertificateEncodingException;->getMessage()Ljava/lang/String;

    move-result-object v6

    invoke-direct {v5, v6}, Ljava/io/IOException;-><init>(Ljava/lang/String;)V

    throw v5

    .line 690
    .end local v1    # "e":Ljava/security/cert/CertificateEncodingException;
    .restart local v2    # "i":I
    .restart local v4    # "size":I
    :cond_0
    return-void
.end method

# virtual methods
.method public matches(Lokhttp3/Request;Lokhttp3/Response;)Z
    .locals 2
    .param p1, "request"    # Lokhttp3/Request;
    .param p2, "response"    # Lokhttp3/Response;

    .prologue
    .line 693
    iget-object v0, p0, Lokhttp3/Cache$Entry;->url:Ljava/lang/String;

    invoke-virtual {p1}, Lokhttp3/Request;->url()Lokhttp3/HttpUrl;

    move-result-object v1

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

    move-result-object v1

    invoke-virtual {v0, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v0

    if-eqz v0, :cond_0

    iget-object v0, p0, Lokhttp3/Cache$Entry;->requestMethod:Ljava/lang/String;

    .line 694
    invoke-virtual {p1}, Lokhttp3/Request;->method()Ljava/lang/String;

    move-result-object v1

    invoke-virtual {v0, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v0

    if-eqz v0, :cond_0

    iget-object v0, p0, Lokhttp3/Cache$Entry;->varyHeaders:Lokhttp3/Headers;

    .line 695
    invoke-static {p2, v0, p1}, Lokhttp3/internal/http/HttpHeaders;->varyMatches(Lokhttp3/Response;Lokhttp3/Headers;Lokhttp3/Request;)Z

    move-result v0

    if-eqz v0, :cond_0

    const/4 v0, 0x1

    .line 693
    :goto_0
    return v0

    .line 695
    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method

.method public response(Lokhttp3/internal/cache/DiskLruCache$Snapshot;)Lokhttp3/Response;
    .locals 6
    .param p1, "snapshot"    # Lokhttp3/internal/cache/DiskLruCache$Snapshot;

    .prologue
    .line 699
    iget-object v3, p0, Lokhttp3/Cache$Entry;->responseHeaders:Lokhttp3/Headers;

    const-string v4, "Content-Type"

    invoke-virtual {v3, v4}, Lokhttp3/Headers;->get(Ljava/lang/String;)Ljava/lang/String;

    move-result-object v2

    .line 700
    .local v2, "contentType":Ljava/lang/String;
    iget-object v3, p0, Lokhttp3/Cache$Entry;->responseHeaders:Lokhttp3/Headers;

    const-string v4, "Content-Length"

    invoke-virtual {v3, v4}, Lokhttp3/Headers;->get(Ljava/lang/String;)Ljava/lang/String;

    move-result-object v1

    .line 701
    .local v1, "contentLength":Ljava/lang/String;
    new-instance v3, Lokhttp3/Request$Builder;

    invoke-direct {v3}, Lokhttp3/Request$Builder;-><init>()V

    iget-object v4, p0, Lokhttp3/Cache$Entry;->url:Ljava/lang/String;

    .line 702
    invoke-virtual {v3, v4}, Lokhttp3/Request$Builder;->url(Ljava/lang/String;)Lokhttp3/Request$Builder;

    move-result-object v3

    iget-object v4, p0, Lokhttp3/Cache$Entry;->requestMethod:Ljava/lang/String;

    const/4 v5, 0x0

    .line 703
    invoke-virtual {v3, v4, v5}, Lokhttp3/Request$Builder;->method(Ljava/lang/String;Lokhttp3/RequestBody;)Lokhttp3/Request$Builder;

    move-result-object v3

    iget-object v4, p0, Lokhttp3/Cache$Entry;->varyHeaders:Lokhttp3/Headers;

    .line 704
    invoke-virtual {v3, v4}, Lokhttp3/Request$Builder;->headers(Lokhttp3/Headers;)Lokhttp3/Request$Builder;

    move-result-object v3

    .line 705
    invoke-virtual {v3}, Lokhttp3/Request$Builder;->build()Lokhttp3/Request;

    move-result-object v0

    .line 706
    .local v0, "cacheRequest":Lokhttp3/Request;
    new-instance v3, Lokhttp3/Response$Builder;

    invoke-direct {v3}, Lokhttp3/Response$Builder;-><init>()V

    .line 707
    invoke-virtual {v3, v0}, Lokhttp3/Response$Builder;->request(Lokhttp3/Request;)Lokhttp3/Response$Builder;

    move-result-object v3

    iget-object v4, p0, Lokhttp3/Cache$Entry;->protocol:Lokhttp3/Protocol;

    .line 708
    invoke-virtual {v3, v4}, Lokhttp3/Response$Builder;->protocol(Lokhttp3/Protocol;)Lokhttp3/Response$Builder;

    move-result-object v3

    iget v4, p0, Lokhttp3/Cache$Entry;->code:I

    .line 709
    invoke-virtual {v3, v4}, Lokhttp3/Response$Builder;->code(I)Lokhttp3/Response$Builder;

    move-result-object v3

    iget-object v4, p0, Lokhttp3/Cache$Entry;->message:Ljava/lang/String;

    .line 710
    invoke-virtual {v3, v4}, Lokhttp3/Response$Builder;->message(Ljava/lang/String;)Lokhttp3/Response$Builder;

    move-result-object v3

    iget-object v4, p0, Lokhttp3/Cache$Entry;->responseHeaders:Lokhttp3/Headers;

    .line 711
    invoke-virtual {v3, v4}, Lokhttp3/Response$Builder;->headers(Lokhttp3/Headers;)Lokhttp3/Response$Builder;

    move-result-object v3

    new-instance v4, Lokhttp3/Cache$CacheResponseBody;

    invoke-direct {v4, p1, v2, v1}, Lokhttp3/Cache$CacheResponseBody;-><init>(Lokhttp3/internal/cache/DiskLruCache$Snapshot;Ljava/lang/String;Ljava/lang/String;)V

    .line 712
    invoke-virtual {v3, v4}, Lokhttp3/Response$Builder;->body(Lokhttp3/ResponseBody;)Lokhttp3/Response$Builder;

    move-result-object v3

    iget-object v4, p0, Lokhttp3/Cache$Entry;->handshake:Lokhttp3/Handshake;

    .line 713
    invoke-virtual {v3, v4}, Lokhttp3/Response$Builder;->handshake(Lokhttp3/Handshake;)Lokhttp3/Response$Builder;

    move-result-object v3

    iget-wide v4, p0, Lokhttp3/Cache$Entry;->sentRequestMillis:J

    .line 714
    invoke-virtual {v3, v4, v5}, Lokhttp3/Response$Builder;->sentRequestAtMillis(J)Lokhttp3/Response$Builder;

    move-result-object v3

    iget-wide v4, p0, Lokhttp3/Cache$Entry;->receivedResponseMillis:J

    .line 715
    invoke-virtual {v3, v4, v5}, Lokhttp3/Response$Builder;->receivedResponseAtMillis(J)Lokhttp3/Response$Builder;

    move-result-object v3

    .line 716
    invoke-virtual {v3}, Lokhttp3/Response$Builder;->build()Lokhttp3/Response;

    move-result-object v3

    .line 706
    return-object v3
.end method

.method public writeTo(Lokhttp3/internal/cache/DiskLruCache$Editor;)V
    .locals 8
    .param p1, "editor"    # Lokhttp3/internal/cache/DiskLruCache$Editor;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    .prologue
    const/16 v7, 0xa

    .line 608
    const/4 v3, 0x0

    invoke-virtual {p1, v3}, Lokhttp3/internal/cache/DiskLruCache$Editor;->newSink(I)Lokio/Sink;

    move-result-object v3

    invoke-static {v3}, Lokio/Okio;->buffer(Lokio/Sink;)Lokio/BufferedSink;

    move-result-object v1

    .line 610
    .local v1, "sink":Lokio/BufferedSink;
    iget-object v3, p0, Lokhttp3/Cache$Entry;->url:Ljava/lang/String;

    invoke-interface {v1, v3}, Lokio/BufferedSink;->writeUtf8(Ljava/lang/String;)Lokio/BufferedSink;

    move-result-object v3

    .line 611
    invoke-interface {v3, v7}, Lokio/BufferedSink;->writeByte(I)Lokio/BufferedSink;

    .line 612
    iget-object v3, p0, Lokhttp3/Cache$Entry;->requestMethod:Ljava/lang/String;

    invoke-interface {v1, v3}, Lokio/BufferedSink;->writeUtf8(Ljava/lang/String;)Lokio/BufferedSink;

    move-result-object v3

    .line 613
    invoke-interface {v3, v7}, Lokio/BufferedSink;->writeByte(I)Lokio/BufferedSink;

    .line 614
    iget-object v3, p0, Lokhttp3/Cache$Entry;->varyHeaders:Lokhttp3/Headers;

    invoke-virtual {v3}, Lokhttp3/Headers;->size()I

    move-result v3

    int-to-long v4, v3

    invoke-interface {v1, v4, v5}, Lokio/BufferedSink;->writeDecimalLong(J)Lokio/BufferedSink;

    move-result-object v3

    .line 615
    invoke-interface {v3, v7}, Lokio/BufferedSink;->writeByte(I)Lokio/BufferedSink;

    .line 616
    const/4 v0, 0x0

    .local v0, "i":I
    iget-object v3, p0, Lokhttp3/Cache$Entry;->varyHeaders:Lokhttp3/Headers;

    invoke-virtual {v3}, Lokhttp3/Headers;->size()I

    move-result v2

    .local v2, "size":I
    :goto_0
    if-ge v0, v2, :cond_0

    .line 617
    iget-object v3, p0, Lokhttp3/Cache$Entry;->varyHeaders:Lokhttp3/Headers;

    invoke-virtual {v3, v0}, Lokhttp3/Headers;->name(I)Ljava/lang/String;

    move-result-object v3

    invoke-interface {v1, v3}, Lokio/BufferedSink;->writeUtf8(Ljava/lang/String;)Lokio/BufferedSink;

    move-result-object v3

    const-string v4, ": "

    .line 618
    invoke-interface {v3, v4}, Lokio/BufferedSink;->writeUtf8(Ljava/lang/String;)Lokio/BufferedSink;

    move-result-object v3

    iget-object v4, p0, Lokhttp3/Cache$Entry;->varyHeaders:Lokhttp3/Headers;

    .line 619
    invoke-virtual {v4, v0}, Lokhttp3/Headers;->value(I)Ljava/lang/String;

    move-result-object v4

    invoke-interface {v3, v4}, Lokio/BufferedSink;->writeUtf8(Ljava/lang/String;)Lokio/BufferedSink;

    move-result-object v3

    .line 620
    invoke-interface {v3, v7}, Lokio/BufferedSink;->writeByte(I)Lokio/BufferedSink;

    .line 616
    add-int/lit8 v0, v0, 0x1

    goto :goto_0

    .line 623
    :cond_0
    new-instance v3, Lokhttp3/internal/http/StatusLine;

    iget-object v4, p0, Lokhttp3/Cache$Entry;->protocol:Lokhttp3/Protocol;

    iget v5, p0, Lokhttp3/Cache$Entry;->code:I

    iget-object v6, p0, Lokhttp3/Cache$Entry;->message:Ljava/lang/String;

    invoke-direct {v3, v4, v5, v6}, Lokhttp3/internal/http/StatusLine;-><init>(Lokhttp3/Protocol;ILjava/lang/String;)V

    invoke-virtual {v3}, Lokhttp3/internal/http/StatusLine;->toString()Ljava/lang/String;

    move-result-object v3

    invoke-interface {v1, v3}, Lokio/BufferedSink;->writeUtf8(Ljava/lang/String;)Lokio/BufferedSink;

    move-result-object v3

    .line 624
    invoke-interface {v3, v7}, Lokio/BufferedSink;->writeByte(I)Lokio/BufferedSink;

    .line 625
    iget-object v3, p0, Lokhttp3/Cache$Entry;->responseHeaders:Lokhttp3/Headers;

    invoke-virtual {v3}, Lokhttp3/Headers;->size()I

    move-result v3

    add-int/lit8 v3, v3, 0x2

    int-to-long v4, v3

    invoke-interface {v1, v4, v5}, Lokio/BufferedSink;->writeDecimalLong(J)Lokio/BufferedSink;

    move-result-object v3

    .line 626
    invoke-interface {v3, v7}, Lokio/BufferedSink;->writeByte(I)Lokio/BufferedSink;

    .line 627
    const/4 v0, 0x0

    iget-object v3, p0, Lokhttp3/Cache$Entry;->responseHeaders:Lokhttp3/Headers;

    invoke-virtual {v3}, Lokhttp3/Headers;->size()I

    move-result v2

    :goto_1
    if-ge v0, v2, :cond_1

    .line 628
    iget-object v3, p0, Lokhttp3/Cache$Entry;->responseHeaders:Lokhttp3/Headers;

    invoke-virtual {v3, v0}, Lokhttp3/Headers;->name(I)Ljava/lang/String;

    move-result-object v3

    invoke-interface {v1, v3}, Lokio/BufferedSink;->writeUtf8(Ljava/lang/String;)Lokio/BufferedSink;

    move-result-object v3

    const-string v4, ": "

    .line 629
    invoke-interface {v3, v4}, Lokio/BufferedSink;->writeUtf8(Ljava/lang/String;)Lokio/BufferedSink;

    move-result-object v3

    iget-object v4, p0, Lokhttp3/Cache$Entry;->responseHeaders:Lokhttp3/Headers;

    .line 630
    invoke-virtual {v4, v0}, Lokhttp3/Headers;->value(I)Ljava/lang/String;

    move-result-object v4

    invoke-interface {v3, v4}, Lokio/BufferedSink;->writeUtf8(Ljava/lang/String;)Lokio/BufferedSink;

    move-result-object v3

    .line 631
    invoke-interface {v3, v7}, Lokio/BufferedSink;->writeByte(I)Lokio/BufferedSink;

    .line 627
    add-int/lit8 v0, v0, 0x1

    goto :goto_1

    .line 633
    :cond_1
    sget-object v3, Lokhttp3/Cache$Entry;->SENT_MILLIS:Ljava/lang/String;

    invoke-interface {v1, v3}, Lokio/BufferedSink;->writeUtf8(Ljava/lang/String;)Lokio/BufferedSink;

    move-result-object v3

    const-string v4, ": "

    .line 634
    invoke-interface {v3, v4}, Lokio/BufferedSink;->writeUtf8(Ljava/lang/String;)Lokio/BufferedSink;

    move-result-object v3

    iget-wide v4, p0, Lokhttp3/Cache$Entry;->sentRequestMillis:J

    .line 635
    invoke-interface {v3, v4, v5}, Lokio/BufferedSink;->writeDecimalLong(J)Lokio/BufferedSink;

    move-result-object v3

    .line 636
    invoke-interface {v3, v7}, Lokio/BufferedSink;->writeByte(I)Lokio/BufferedSink;

    .line 637
    sget-object v3, Lokhttp3/Cache$Entry;->RECEIVED_MILLIS:Ljava/lang/String;

    invoke-interface {v1, v3}, Lokio/BufferedSink;->writeUtf8(Ljava/lang/String;)Lokio/BufferedSink;

    move-result-object v3

    const-string v4, ": "

    .line 638
    invoke-interface {v3, v4}, Lokio/BufferedSink;->writeUtf8(Ljava/lang/String;)Lokio/BufferedSink;

    move-result-object v3

    iget-wide v4, p0, Lokhttp3/Cache$Entry;->receivedResponseMillis:J

    .line 639
    invoke-interface {v3, v4, v5}, Lokio/BufferedSink;->writeDecimalLong(J)Lokio/BufferedSink;

    move-result-object v3

    .line 640
    invoke-interface {v3, v7}, Lokio/BufferedSink;->writeByte(I)Lokio/BufferedSink;

    .line 642
    invoke-direct {p0}, Lokhttp3/Cache$Entry;->isHttps()Z

    move-result v3

    if-eqz v3, :cond_2

    .line 643
    invoke-interface {v1, v7}, Lokio/BufferedSink;->writeByte(I)Lokio/BufferedSink;

    .line 644
    iget-object v3, p0, Lokhttp3/Cache$Entry;->handshake:Lokhttp3/Handshake;

    invoke-virtual {v3}, Lokhttp3/Handshake;->cipherSuite()Lokhttp3/CipherSuite;

    move-result-object v3

    invoke-virtual {v3}, Lokhttp3/CipherSuite;->javaName()Ljava/lang/String;

    move-result-object v3

    invoke-interface {v1, v3}, Lokio/BufferedSink;->writeUtf8(Ljava/lang/String;)Lokio/BufferedSink;

    move-result-object v3

    .line 645
    invoke-interface {v3, v7}, Lokio/BufferedSink;->writeByte(I)Lokio/BufferedSink;

    .line 646
    iget-object v3, p0, Lokhttp3/Cache$Entry;->handshake:Lokhttp3/Handshake;

    invoke-virtual {v3}, Lokhttp3/Handshake;->peerCertificates()Ljava/util/List;

    move-result-object v3

    invoke-direct {p0, v1, v3}, Lokhttp3/Cache$Entry;->writeCertList(Lokio/BufferedSink;Ljava/util/List;)V

    .line 647
    iget-object v3, p0, Lokhttp3/Cache$Entry;->handshake:Lokhttp3/Handshake;

    invoke-virtual {v3}, Lokhttp3/Handshake;->localCertificates()Ljava/util/List;

    move-result-object v3

    invoke-direct {p0, v1, v3}, Lokhttp3/Cache$Entry;->writeCertList(Lokio/BufferedSink;Ljava/util/List;)V

    .line 648
    iget-object v3, p0, Lokhttp3/Cache$Entry;->handshake:Lokhttp3/Handshake;

    invoke-virtual {v3}, Lokhttp3/Handshake;->tlsVersion()Lokhttp3/TlsVersion;

    move-result-object v3

    invoke-virtual {v3}, Lokhttp3/TlsVersion;->javaName()Ljava/lang/String;

    move-result-object v3

    invoke-interface {v1, v3}, Lokio/BufferedSink;->writeUtf8(Ljava/lang/String;)Lokio/BufferedSink;

    move-result-object v3

    invoke-interface {v3, v7}, Lokio/BufferedSink;->writeByte(I)Lokio/BufferedSink;

    .line 650
    :cond_2
    invoke-interface {v1}, Lokio/BufferedSink;->close()V

    .line 651
    return-void
.end method


text:
Rime with Windows
===

Prerequisites
---
librime is tested to work on Windows with the following build tools and libraries:
  - VS2013
  - [Boost](http://www.boost.org/)>=1.56
  - [cmake](http://www.cmake.org/)>=2.8
  - [msysgit](https://msysgit.github.io/)

You may need to update Boost when using a higher version of VS.

The following command line tools from msysgit are needed by `build.bat` to automate the build process:
  - **git**, used by `build.bat thirdparty` to clone `windows` branch from [lotem/leveldb](https://github.com/lotem/leveldb)
  - **sed**, used by `build.bat thirdparty` to edit project files for static-linking C++ runtime (/MT)

You can also build third-party libraries manually without them, by following instructions in the build script.

Get the code
---
``` batch
git clone git@github.com:lotem/librime.git
```
or [download from github](https://github.com/lotem/librime).

Setup a build environment
---
Copy `env.bat` from `env.bat.template` and edit the script according to your setup.
Specifically, make sure `BOOST_ROOT` is set to the path where you extracted Boost source;
modify `*_INSTALL_PATH` if you've installed build tools in a custom location.

When finished, run `shell.bat` to complete the following steps in a prepared command prompt.

Build Boost
---
``` batch
build.bat boost
```

Build third-party libraries
---
``` batch
build.bat thirdparty
```
This builds dependent libraries in `thirdparty\src\*`, and copies artifacts to `thirdparty\lib` and `thirdparty\bin`.

Build librime
---
``` batch
build.bat
```
This creates `build\lib\Release\rime.dll`.

Try it in the console
---
``` batch
copy /Y build\lib\Release\rime.dll build\bin
copy /Y thirdparty\bin\*.dll build\bin
cd build\bin
echo "congmingdeRime{space}shurufa" | Release\rime_api_console > output.txt
```

redpajama_set_name: RedPajamaGithub


text:
using NUnit.Framework;

namespace Common.Logging
{
    [TestFixture]
    public class LogLevelNumericComparisonTests
    {
        [Test]
        public void IncreasingSeverityLogLevelsMaintainRelativeNumericOrdering()
        {
            Assert.That(
                LogLevel.All < LogLevel.Trace &&
                LogLevel.Trace < LogLevel.Debug &&
                LogLevel.Debug < LogLevel.Info &&
                LogLevel.Warn < LogLevel.Error &&
                LogLevel.Error < LogLevel.Fatal &&
                LogLevel.Fatal < LogLevel.Off
                );
        }
    }
}


text:
import React from 'react';
import { render, screen } from '@testing-library/react';
import { Homepage } from './Homepage';

describe('Homepage', () => {
  beforeEach(() => {
    jest.spyOn(document, 'querySelector').mockImplementation(
      () =>
        (({
          href: '',
        } as unknown) as Element),
    );
  });

  test('renders the name title', () => {
    render(<Homepage />);
    const nameTitleElement = screen.getByText(/Hello, I am Kevin McCartney/i);
    expect(nameTitleElement).toBeInTheDocument();
  });

  test('renders the role title', () => {
    render(<Homepage />);
    const nameTitleElement = screen.getByText(/Engineer, mentor, & teacher/i);
    expect(nameTitleElement).toBeInTheDocument();
  });

  test('renders linkedin link', () => {
    render(<Homepage />);
    const nameTitleElement = screen.getByTestId(
      'linkedin-link',
    ) as HTMLLinkElement;
    expect(nameTitleElement.href).toBe(
      'https://www.linkedin.com/in/kevinmccartney2',
    );
  });

  test('renders twitter link', () => {
    render(<Homepage />);
    const nameTitleElement = screen.getByTestId(
      'twitter-link',
    ) as HTMLLinkElement;
    expect(nameTitleElement.href).toBe('https://twitter.com/kmccartneydev');
  });

  test('renders github link', () => {
    render(<Homepage />);
    const nameTitleElement = screen.getByTestId(
      'github-link',
    ) as HTMLLinkElement;
    expect(nameTitleElement.href).toBe('https://github.com/kevinmccartney');
  });

  test('renders how i was made link', () => {
    render(<Homepage />);
    const nameTitleElement = screen.getByTestId(
      'how-i-was-made-link',
    ) as HTMLLinkElement;
    expect(nameTitleElement.href).toBe(
      'https://github.com/kevinmccartney/kevinmccartney.is',
    );
  });
});


text:
<?php

class SettingController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	//public $layout='//layouts/column2';
	public $defaultAction = 'index';

	/**
	 * Initialize admin page theme
	 */
	public function init()
	{
		if(!Yii::app()->user->isGuest) {
			if(Yii::app()->user->level == 1) {
				$arrThemes = Utility::getCurrentTemplate('admin');
				Yii::app()->theme = $arrThemes['folder'];
				$this->layout = $arrThemes['layout'];
			} else {
				$this->redirect(Yii::app()->createUrl('site/login'));
			}
		} else {
			$this->redirect(Yii::app()->createUrl('site/login'));
		}
	}

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			//'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array(),
				'users'=>array('@'),
				'expression'=>'isset(Yii::app()->user->level)',
				//'expression'=>'isset(Yii::app()->user->level) && (Yii::app()->user->level != 1)',
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('manage'),
				'users'=>array('@'),
				'expression'=>'isset(Yii::app()->user->level) && (Yii::app()->user->level == 1)',
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array(),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$this->redirect(array('manage'));
	}

	/**
	 * Manages all models.
	 */
	public function actionManage()
	{
		$category=new BannerCategory('search');
		$category->unsetAttributes();  // clear any default values
		if(isset($_GET['BannerCategory'])) {
			$category->attributes=$_GET['BannerCategory'];
		}

		$columnTemp = array();
		if(isset($_GET['GridColumn'])) {
			foreach($_GET['GridColumn'] as $key => $val) {
				if($_GET['GridColumn'][$key] == 1) {
					$columnTemp[] = $key;
				}
			}
		}
		$columns = $category->getGridColumn($columnTemp);

		$model=$this->loadModel(1);

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['BannerSetting'])) {
			$model->attributes=$_POST['BannerSetting'];

			$jsonError = CActiveForm::validate($model);
			if(strlen($jsonError) > 2) {
				$errors = $model->getErrors();
				$summary['msg'] = "
".Yii::t('phrase', 'Please fix the following input errors:')."";
				$summary['msg'] .= "
";
				foreach($errors as $key => $value) {
					$summary['msg'] .= "
{$value[0]}
";
				}
				$summary['msg'] .= "

";

				$message = json_decode($jsonError, true);
				$merge = array_merge_recursive($summary, $message);
				$encode = json_encode($merge);
				echo $encode;

			} else {
				if(isset($_GET['enablesave']) && $_GET['enablesave'] == 1) {
					if($model->save()) {
						echo CJSON::encode(array(
							'type' => 0,
							'msg' => '
'.Yii::t('phrase', 'Banner setting success updated.').'
',
						));
					} else {
						print_r($model->getErrors());
					}
				}
			}

		} else {
			$this->pageTitle = Yii::t('phrase', 'Banner Settings');
			$this->pageDescription = '';
			$this->pageMeta = '';
			$this->render('admin_manage',array(
				'model'=>$model,
				'category'=>$category,
				'columns' => $columns,
			));
		}
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model = BannerSetting::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404, Yii::t('phrase', 'The requested page does not exist.'));
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='banner-setting-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}


text:
/*
    Document   : club-recognition.css
    Created on : Oct 25, 2012, 5:00:49 PM
    Author     : Nikesh Hajari
    Description:
        Purpose of the stylesheet follows.
*/

label.error {
    font-weight: bold;
    color: red;
    padding: 2px 8px;
    margin-top: 2px;
}

.required-star{
    color: red;
}

.recognition-button-container{
    text-align: center;
}

.btn-delete-eboard-member{
    margin-top: 3px;
}

.center-submit-button{
    text-align: center;
    margin-top: 20px;
}


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

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

Unit 'qBitTorrentWebUI'
Package

[Overview][Constants][Classes][Index]
[#lazqBitTorrentWebUI]

TqBitTorrentWebUI.Host

Host/Address  for the qBittorrent client.

Declaration

Source position: qBitTorrentWebUI.pas line 125

<tt> published property TqBitTorrentWebUI.Host : string
  read FHost
  write FHost;</tt>


text:
***ScalaTest/ScalaUtils 2.1.3***

ScalaTest 2.1.3 is a maintenance release for the 2.1.x series that includes a few enhancements and bug fixes. No source code using ScalaTest 2.0+ should break, but you will likely need to do a clean build to upgrade from 2.0. However, 2.1.3 is binary compatible with 2.1.0, 2.1.1, and 2.1.2, so you can just change the version number in your build to upgrade from earlier 2.1.x releases.

The list of enhancements and bug fixes below includes all changes since 2.1.0:

### Enhancements

* Added `-z` argument support to sbt integration, allowing test name wildcards to be specified when using sbt.

* Enhanced [`Prettifier.default`](http://doc.scalatest.org/2.1.3/index.html#org.scalautils.Prettifier$) to handle `scala.xml.NodeSeq` and `scala.xml.NodeBuffer`.

* Enhanced [`Prettifier.default`](http://doc.scalatest.org/2.1.3/index.html#org.scalautils.Prettifier$) to handle recursive class definitions like `Fred` `extends` `Seq[Fred]`.

* Refactored [`Prettifier.default`](http://doc.scalatest.org/2.1.3/index.html#org.scalautils.Prettifier$) to use `stringPrefix` for better performance.

* Added `-t` argument support to sbt integration, allowing full test names to be specified when using sbt.

* Disallow any suffix for [`Runner`](http://doc.scalatest.org/2.1.3/index.html#org.scalatest.tools.Runner$) command line arguments that do not take a suffix. This will give a better error message if someone enters `-z"database"` instead of `-z "database"`.

### Bug fixes

* Added missing must support to `noException`, `a [SomeException]` and `an [Exception]` matcher syntax.

* Fixed `StackOverflowError` problem in `Prettifier.default` method when used with `scala.xml.Node`.

* Fixed an owner chain problem in the assert macro ([issue 276](https://github.com/scalatest/scalatest/issues/276)).


text:
package org.kuali.kfs.module.purap.businessobject;

import java.util.LinkedHashMap;

import org.kuali.kfs.coa.businessobject.Chart;
import org.kuali.kfs.coa.businessobject.Organization;
import org.kuali.rice.core.api.util.type.KualiDecimal;
import org.kuali.rice.krad.bo.PersistableBusinessObjectBase;

/**
 * Organization Parameter Business Object. Maintenance document for organization parameters.
 */
public class OrganizationParameter extends PersistableBusinessObjectBase {

    private String chartOfAccountsCode;
    private String organizationCode;
    private KualiDecimal organizationAutomaticPurchaseOrderLimit;

    private Chart chartOfAccounts;
    private Organization organization;
    private boolean activeIndicator;

    public boolean isActiveIndicator() {
        return activeIndicator;
    }

    public void setActiveIndicator(boolean activeIndicator) {
        this.activeIndicator = activeIndicator;
    }

    /**
     * Default constructor.
     */
    public OrganizationParameter() {

    }

    public Chart getChartOfAccounts() {
        return chartOfAccounts;
    }

    /**
     * @deprecated
     */
    public void setChartOfAccounts(Chart chartOfAccounts) {
        this.chartOfAccounts = chartOfAccounts;
    }

    public String getChartOfAccountsCode() {
        return chartOfAccountsCode;
    }

    public void setChartOfAccountsCode(String chartOfAccountsCode) {
        this.chartOfAccountsCode = chartOfAccountsCode;
    }

    public Organization getOrganization() {
        return organization;
    }

    /**
     * @deprecated
     */
    public void setOrganization(Organization organization) {
        this.organization = organization;
    }

    public KualiDecimal getOrganizationAutomaticPurchaseOrderLimit() {
        return organizationAutomaticPurchaseOrderLimit;
    }

    public void setOrganizationAutomaticPurchaseOrderLimit(KualiDecimal organizationAutomaticPurchaseOrderLimit) {
        this.organizationAutomaticPurchaseOrderLimit = organizationAutomaticPurchaseOrderLimit;
    }

    public String getOrganizationCode() {
        return organizationCode;
    }

    public void setOrganizationCode(String organizationCode) {
        this.organizationCode = organizationCode;
    }

    /**
     * @see org.kuali.rice.krad.bo.BusinessObjectBase#toStringMapper()
     */
    protected LinkedHashMap toStringMapper_RICE20_REFACTORME() {
        LinkedHashMap m = new LinkedHashMap();
        m.put("chartOfAccountsCode", this.chartOfAccountsCode);
        m.put("organizationCode", this.organizationCode);
        return m;
    }
}


text:
package com.jme3.animation;

import static com.jme3.animation.LoopMode.Cycle;
import static com.jme3.animation.LoopMode.DontLoop;
import static com.jme3.animation.LoopMode.Loop;

/**
 *
 * @author Nehon
 */
public class AnimationUtils {

    /**
     * Clamps the time according to duration and loopMode
     * @param time
     * @param duration
     * @param loopMode
     * @return
     */
     public static float clampWrapTime(float time, float duration, LoopMode loopMode){
        if (time == 0) {
            return 0; // prevent division by 0 errors
        }
        switch (loopMode) {
            case Cycle:
                boolean sign = ((int) (time / duration) % 2) != 0;
                return sign ? -(duration - (time % duration)) : time % duration;
            case DontLoop:
                return time > duration ? duration : (time < 0 ? 0 : time);
            case Loop:
                return time % duration;
        }
        return time;
     }
}


text:
ALTER TABLE entry
CHANGE COLUMN entry_color entry_background_color VARCHAR(45) NULL DEFAULT 'FFFFFF',
ADD COLUMN entry_text_color VARCHAR(45) NULL DEFAULT '000000' AFTER entry_background_color;


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

<title>Uses of Class com.cypaubr.jmath.geometry.trigonometry.Triangle</title>
<meta name="date" content="2017-01-12">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.cypaubr.jmath.geometry.trigonometry.Triangle

Packages that use Triangle

Package
Description

<Unnamed>

Uses of Triangle in <Unnamed>

Fields in <Unnamed> declared as Triangle

Modifier and Type
Field and Description

private Triangle
TriangleTest.triangle

private Triangle
TriangleTest.trianglePoint

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
using System.IO;
using System.Text;

namespace Abc.NCrafts.Quizz.Questions._021
{
    [CorrectAnswer(Difficulty = Difficulty.Medium)]
    public class Answer3
    {
        private const string _text = "Am I allocating?";

        public static void Run()
        {
            var stream = new MemoryStream(1000);
            var messageBytes = Encoding.ASCII.GetBytes(_text);

            // begin
            stream.Write(messageBytes, 0, messageBytes.Length);

            var bytes = stream.GetBuffer();
            for (var i = 0; i < stream.Length; i++)
            {
                bytes[i] = (byte)char.ToUpper((char)bytes[i]);
            }
            // end

            Logger.LogAscii(bytes, stream.Length);
        }
    }
}


text:
@implementation NSMutableArray (Sidekick)

- (void)insertObjects:(NSArray *)objects startingAtIndex:(NSUInteger)idx
{
	for (id item in objects.reverseObjectEnumerator) {
		[self insertObject:item atIndex:idx];
	}
}

@end


text:
package com.anuragkapur.misc;

/**
 * Problem Statment: Refer README
 *
 * Assumptions:
 *

 * Starting point assumed (0,0), matrix top left point is (0,0)
 *

 *

 * Movement from a given path can only be downward or to the right. Diagonal not allowed.
 *

 *
 * Optimisations possible:
 * The given implementation performs some extra computation as some recursive calls are repeated.
 * i.e. there are repeating sub problems. Hence, using DP, this can be further optimised.
 *
 * @author anuragkapur
 */
public class AllPaths2Points2DMatrix {

	// matrix dimensions
	private static int maxRows = 5;
	private static int maxColumns = 4;

	// end point
	private static int endX = 2;
	private static int endY = 2;

	private static int count;

	/**
	 * Depth first search
	 *
	 * @param x
	 * @param y
	 * @param path
	 */
	private static void dfs(int x, int y, String path) {

		if(x < endX) {
			dfs(x+1 ,y, path+"("+x+","+y+")");
		}
		if(y < endY) {
			dfs(x, y+1, path+"("+x+","+y+")");
		}
		if(x == endX && y == endY) {
			path += "("+x+","+y+")";
			//System.out.format("Path number:%d found\n",++count);
			//System.out.println("Path :: " + path);
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		// start from the origin
		dfs(0, 0, "");
	}
}


text:
<?php

$collections['createpair']='custom';
$allowed_methods['createpair']='GET';
$domain['createpair']='security';

$collections['signrecord']='custom';
$allowed_methods['signrecord']='POST';
$domain['signrecord']='security';
$dbtype['signrecord']='orcl';

$collections['verifyrecord']='custom';
$allowed_methods['verifyrecord']='GET';
$domain['verifyrecord']='security';
$dbtype['verifyrecord']='orcl';

$collections['getdatasignature']='custom';
$allowed_methods['getdatasignature']='POST';
$domain['getdatasignature']='security';


text: This \#hashtag and \@username were escaped


text:
from branca.element import MacroElement
from jinja2 import Template

from folium.elements import JSCSSMixin
from folium.utilities import parse_options

class BeautifyIcon(JSCSSMixin, MacroElement):
    """
    Create a BeautifyIcon that can be added to a Marker

    Parameters
    ----------
    icon: string, default None
        the Font-Awesome icon name to use to render the marker.
    icon_shape: string, default None
        the icon shape
    border_width: integer, default 3
        the border width of the icon
    border_color: string with hexadecimal RGB, default '#000'
        the border color of the icon
    text_color: string with hexadecimal RGB, default '#000'
        the text color of the icon
    background_color: string with hexadecimal RGB, default '#FFF'
        the background color of the icon
    inner_icon_style: string with css styles for the icon, default ''
        the css styles of the icon
    spin: boolean, default False
        allow the icon to be spinning.
    number: integer, default None
        the number of the icon.

    Examples
    --------
    Plugin Website: https://github.com/masajid390/BeautifyMarker
    >>> BeautifyIcon(
    ...     text_color="#000", border_color="transparent", background_color="#FFF"
    ... ).add_to(marker)
    >>> number_icon = BeautifyIcon(
    ...     text_color="#000",
    ...     border_color="transparent",
    ...     background_color="#FFF",
    ...     number=10,
    ...     inner_icon_style="font-size:12px;padding-top:-5px;",
    ... )
    >>> Marker(
    ...     location=[45.5, -122.3],
    ...     popup=folium.Popup("Portland, OR"),
    ...     icon=number_icon,
    ... )
    >>> BeautifyIcon(icon="arrow-down", icon_shape="marker").add_to(marker)

    """

    _template = Template(
        """
        {% macro script(this, kwargs) %}
            var {{ this.get_name() }} = new L.BeautifyIcon.icon(
                {{ this.options|tojson }}
            )
            {{ this._parent.get_name() }}.setIcon({{ this.get_name() }});
        {% endmacro %}
        """
    )
    ICON_SHAPE_TYPES = [
        "circle",
        "circle-dot",
        "doughnut",
        "rectangle-dot",
        "marker",
        None,
    ]

    default_js = [
        (
            "beautify_icon_js",
            "https://cdn.jsdelivr.net/gh/marslan390/BeautifyMarker/leaflet-beautify-marker-icon.min.js",
        )
    ]
    default_css = [
        (
            "beautify_icon_css",
            "https://cdn.jsdelivr.net/gh/marslan390/BeautifyMarker/leaflet-beautify-marker-icon.min.css",
        )
    ]

    def __init__(
        self,
        icon=None,
        icon_shape=None,
        border_width=3,
        border_color="#000",
        text_color="#000",
        background_color="#FFF",
        inner_icon_style="",
        spin=False,
        number=None,
        **kwargs
    ):
        super().__init__()
        self._name = "BeautifyIcon"

        self.options = parse_options(
            icon=icon,
            icon_shape=icon_shape,
            border_width=border_width,
            border_color=border_color,
            text_color=text_color,
            background_color=background_color,
            inner_icon_style=inner_icon_style,
            spin=spin,
            isAlphaNumericIcon=number is not None,
            text=number,
            **kwargs
        )


text:
/**************************************************************************/
/*!
    @file     pmu.c

    @section LICENSE

    Software License Agreement (BSD License)

    Copyright (c) 2013, K. Townsend (microBuilder.eu)
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:
    1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
    3. Neither the name of the copyright holders nor the
    names of its contributors may be used to endorse or promote products
    derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**************************************************************************/
#ifndef __PMU_H__
#define __PMU_H__

#ifdef __cplusplus
extern "C" {
#endif

#include "projectconfig.h"

#define MCU_SLEEP           (0)
#define MCU_DEEP_SLEEP      (1)
#define MCU_POWER_DOWN      (2)

#define NVIC_LP_SEVONPEND   (0x10)
#define NVIC_LP_SLEEPDEEP   (0x04)
#define NVIC_LP_SLEEPONEXIT (0x02)

#define IRC_OUT_PD          (0x1<<0)
#define IRC_PD              (0x1<<1)
#define FLASH_PD            (0x1<<2)
#define BOD_PD              (0x1<<3)
#define ADC_PD              (0x1<<4)
#define SYS_OSC_PD          (0x1<<5)
#define WDT_OSC_PD          (0x1<<6)
#define SYS_PLL_PD          (0x1<<7)
#define USBPLL_PD           (0x1<<8)
#define USBPAD_PD           (0x1<<10)

void PMU_Sleep( uint32_t SleepMode, uint32_t SleepCtrl );

#ifdef __cplusplus
}
#endif

#endif


text:
<!doctype html>

    <title>gallery-beacon-listener</title>

    <meta charset="utf-8" />


text:
from . import matchers
from . import signature
from . import verification as verificationModule
from .utils import contains_strict

from collections import deque
import functools

class InvocationError(AttributeError):
    pass

class Invocation(object):
    def __init__(self, mock, method_name):
        self.mock = mock
        self.method_name = method_name
        self.strict = mock.strict

        self.params = ()
        self.named_params = {}

    def _remember_params(self, params, named_params):
        self.params = params
        self.named_params = named_params

    def __repr__(self):
        args = [repr(p) if p is not Ellipsis else '...'
                for p in self.params]
        kwargs = ["%s=%r" % (key, val)
                  if key is not matchers.KWARGS_SENTINEL else '**kwargs'
                  for key, val in self.named_params.items()]
        params = ", ".join(args + kwargs)
        return "%s(%s)" % (self.method_name, params)

class RememberedInvocation(Invocation):
    def __init__(self, mock, method_name):
        super(RememberedInvocation, self).__init__(mock, method_name)
        self.verified = False
        self.verified_inorder = False

    def ensure_mocked_object_has_method(self, method_name):
        if not self.mock.has_method(method_name):
            raise InvocationError(
                "You tried to call a method '%s' the object (%s) doesn't "
                "have." % (method_name, self.mock.mocked_obj))

    def ensure_signature_matches(self, method_name, args, kwargs):
        sig = self.mock.get_signature(method_name)
        if not sig:
            return

        signature.match_signature(sig, args, kwargs)

    def __call__(self, *params, **named_params):
        if self.strict:
            self.ensure_mocked_object_has_method(self.method_name)
            self.ensure_signature_matches(
                self.method_name, params, named_params)

        self._remember_params(params, named_params)
        self.mock.remember(self)

        for matching_invocation in self.mock.stubbed_invocations:
            if matching_invocation.matches(self):
                matching_invocation.should_answer(self)
                return matching_invocation.answer_first(
                    *params, **named_params)

        if self.strict:
            stubbed_invocations = [
                invoc
                for invoc in self.mock.stubbed_invocations
                if invoc.method_name == self.method_name
            ]
            raise InvocationError(
                """
Called but not expected:

    %s

Stubbed invocations are:

    %s

"""
                % (
                    self,
                    "\n    ".join(
                        str(invoc) for invoc in reversed(stubbed_invocations)
                    )
                )
            )

        return None

class RememberedProxyInvocation(Invocation):
    '''Remeber params and proxy to method of original object.

    Calls method on original object and returns it's return value.
    '''
    def __init__(self, mock, method_name):
        super(RememberedProxyInvocation, self).__init__(mock, method_name)
        self.verified = False
        self.verified_inorder = False

    def __call__(self, *params, **named_params):
        self._remember_params(params, named_params)
        self.mock.remember(self)
        obj = self.mock.spec
        try:
            method = getattr(obj, self.method_name)
        except AttributeError:
            raise AttributeError(
                "You tried to call method '%s' which '%s' instance does not "
                "have." % (self.method_name, obj))
        return method(*params, **named_params)

class MatchingInvocation(Invocation):
    @staticmethod
    def compare(p1, p2):
        if isinstance(p1, matchers.Matcher):
            if not p1.matches(p2):
                return False
        elif p1 != p2:
            return False
        return True

    def _remember_params(self, params, named_params):
        if (
            contains_strict(params, Ellipsis)
            and (params[-1] is not Ellipsis or named_params)
        ):
            raise TypeError('Ellipsis must be the last argument you specify.')

        if contains_strict(params, matchers.args):
            raise TypeError('args must be used as *args')

        if (
            contains_strict(params, matchers.kwargs)
            or contains_strict(params, matchers.KWARGS_SENTINEL)
        ):
            raise TypeError('kwargs must be used as **kwargs')

        def wrap(p):
            if p is any or p is matchers.any_:
                return matchers.any_()
            return p

        self.params = tuple(wrap(p) for p in params)
        self.named_params = {k: wrap(v) for k, v in named_params.items()}

    # Note: matches(a, b) does not imply matches(b, a) because
    # the left side might contain wildcards (like Ellipsis) or matchers.
    # In its current form the right side is a concrete call signature.
    def matches(self, invocation):  # noqa: C901 (too complex)
        if self.method_name != invocation.method_name:
            return False

        for x, p1 in enumerate(self.params):
            # assume Ellipsis is the last thing a user declares
            if p1 is Ellipsis:
                return True

            if p1 is matchers.ARGS_SENTINEL:
                break

            try:
                p2 = invocation.params[x]
            except IndexError:
                return False

            if not self.compare(p1, p2):
                return False
        else:
            if len(self.params) != len(invocation.params):
                return False

        for key, p1 in sorted(
            self.named_params.items(),
            key=lambda k_v: 1 if k_v[0] is matchers.KWARGS_SENTINEL else 0
        ):
            if key is matchers.KWARGS_SENTINEL:
                break

            try:
                p2 = invocation.named_params[key]
            except KeyError:
                return False

            if not self.compare(p1, p2):
                return False
        else:
            if len(self.named_params) != len(invocation.named_params):
                return False

        return True

class VerifiableInvocation(MatchingInvocation):
    def __init__(self, mock, method_name, verification):
        super(VerifiableInvocation, self).__init__(mock, method_name)
        self.verification = verification

    def __call__(self, *params, **named_params):
        self._remember_params(params, named_params)
        matched_invocations = []
        for invocation in self.mock.invocations:
            if self.matches(invocation):
                matched_invocations.append(invocation)

        self.verification.verify(self, len(matched_invocations))

        # check (real) invocations as verified
        for invocation in matched_invocations:
            invocation.verified = True

        # check stubs as 'used'
        if verification_has_lower_bound_of_zero(self.verification):
            for stub in self.mock.stubbed_invocations:
                # Remember: matches(a, b) does not imply matches(b, a)
                # (see above!), so we check for both
                if stub.matches(self) or self.matches(stub):
                    stub.allow_zero_invocations = True

def verification_has_lower_bound_of_zero(verification):
    if (isinstance(verification, verificationModule.Times) and
            verification.wanted_count == 0):
        return True

    if (isinstance(verification, verificationModule.Between) and
            verification.wanted_from == 0):
        return True

    return False

class StubbedInvocation(MatchingInvocation):
    def __init__(self, mock, method_name, verification=None, strict=None):
        super(StubbedInvocation, self).__init__(mock, method_name)

        #: Holds the verification set up via `expect`.
        #: The verification will be verified implicitly, while using this stub.
        self.verification = verification

        if strict is not None:
            self.strict = strict

        self.answers = CompositeAnswer()

        #: Counts how many times this stub has been 'used'.
        #: A stub gets used, when a real invocation matches its argument
        #: signature, and asks for an answer.
        self.used = 0

        #: Set if `verifyStubbedInvocationsAreUsed` should pass, regardless
        #: of any factual invocation. E.g. set by `verify(..., times=0)`
        if verification_has_lower_bound_of_zero(verification):
            self.allow_zero_invocations = True
        else:
            self.allow_zero_invocations = False

    def ensure_mocked_object_has_method(self, method_name):
        if not self.mock.has_method(method_name):
            raise InvocationError(
                "You tried to stub a method '%s' the object (%s) doesn't "
                "have." % (method_name, self.mock.mocked_obj))

    def ensure_signature_matches(self, method_name, args, kwargs):
        sig = self.mock.get_signature(method_name)
        if not sig:
            return

        signature.match_signature_allowing_placeholders(sig, args, kwargs)

    def __call__(self, *params, **named_params):
        if self.strict:
            self.ensure_mocked_object_has_method(self.method_name)
            self.ensure_signature_matches(
                self.method_name, params, named_params)
        self._remember_params(params, named_params)

        self.mock.stub(self.method_name)
        self.mock.finish_stubbing(self)
        return AnswerSelector(self)

    def forget_self(self):
        self.mock.forget_stubbed_invocation(self)

    def add_answer(self, answer):
        self.answers.add(answer)

    def answer_first(self, *args, **kwargs):
        self.used += 1
        return self.answers.answer(*args, **kwargs)

    def should_answer(self, invocation):
        # type: (RememberedInvocation) -> None
        verification = self.verification
        if not verification:
            return

        # This check runs before `answer_first`. We add '1' because we want
        # to know if the verification passes if this call gets through.
        actual_count = self.used + 1

        if isinstance(verification, verificationModule.Times):
            if actual_count > verification.wanted_count:
                raise InvocationError(
                    "\nWanted times: %i, actual times: %i"
                    % (verification.wanted_count, actual_count))
        elif isinstance(verification, verificationModule.AtMost):
            if actual_count > verification.wanted_count:
                raise InvocationError(
                    "\nWanted at most: %i, actual times: %i"
                    % (verification.wanted_count, actual_count))
        elif isinstance(verification, verificationModule.Between):
            if actual_count > verification.wanted_to:
                raise InvocationError(
                    "\nWanted between: [%i, %i], actual times: %i"
                    % (verification.wanted_from,
                       verification.wanted_to,
                       actual_count))

        # The way mockito's `verify` works is, that it checks off all 'real',
        # remembered invocations, if they get verified. This is a simple
        # mechanism so that a later `verifyNoMoreInteractions` just has to
        # ensure that all invocations have this flag set to ``True``.
        # For verifications set up via `expect` we want all invocations
        # to get verified 'implicitly', on-the-go, so we set this flag here.
        invocation.verified = True

    def verify(self):
        if self.verification:
            self.verification.verify(self, self.used)

    def check_used(self):
        if not self.allow_zero_invocations and self.used < len(self.answers):
            raise verificationModule.VerificationError("\nUnused stub: %s" % self)

def return_(value, *a, **kw):
    return value

def raise_(exception, *a, **kw):
    raise exception

class AnswerSelector(object):
    def __init__(self, invocation):
        self.invocation = invocation

    def thenReturn(self, *return_values):
        for return_value in return_values:
            self.__then(functools.partial(return_, return_value))
        return self

    def thenRaise(self, *exceptions):
        for exception in exceptions:
            self.__then(functools.partial(raise_, exception))
        return self

    def thenAnswer(self, *callables):
        for callable in callables:
            self.__then(callable)
        return self

    def __then(self, answer):
        self.invocation.add_answer(answer)

    def __enter__(self):
        pass

    def __exit__(self, *exc_info):
        self.invocation.verify()
        self.invocation.check_used()
        self.invocation.forget_self()

class CompositeAnswer(object):
    def __init__(self):
        #: Container for answers, which are just ordinary callables
        self.answers = deque()

        #: Counter for the maximum answers we ever had
        self.answer_count = 0

    def __len__(self):
        # The minimum is '1' bc we always have a default answer of 'None'
        return max(1, self.answer_count)

    def add(self, answer):
        self.answer_count += 1
        self.answers.append(answer)

    def answer(self, *args, **kwargs):
        if len(self.answers) == 0:
            return None

        if len(self.answers) == 1:
            a = self.answers[0]
        else:
            a = self.answers.popleft()

        return a(*args, **kwargs)


text:
<?php
/**
 * @package WordPress
 * @subpackage Alphasss Members
 */

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) exit;

if ( ! class_exists( 'Alphasss_Members_Admin' ) ):

class Alphasss_Members_Admin
{
	/**
	 * Plugin options
	 *
	 * @var array
	 */
	public $options = array();

	private function __construct(){}

	public static function instance()
	{
		static $instance = null;

		if ( null === $instance ) {
			$instance = new Alphasss_Members_Admin;
			$instance->setup();
		}

		return $instance;
	}

	/**
	 * Get option
	 *
	 * @param  string $key Option key
	 *
	 * @return mixed Option value
	 */
	public function option( $key )
	{
		return alphasss_members()->option( $key );
	}

	/**
	 * Setup admin class
	 */
	public function setup()
	{
		if ( ( ! is_admin() && ! is_network_admin() ) || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$actions = array('admin_init', 'admin_menu', 'network_admin_menu');

		foreach( $actions as $action ) {
			add_action( $action, array( $this, $action ) );
		}
	}

	/**
	 * Register admin settings
	 */
	public function admin_init()
	{
		register_setting( 'alpahsss_members_plugin_options', 'alpahsss_members_plugin_options', array( $this, 'plugin_options_validate' ) );
		add_settings_section( 'general_section', __( 'General Settings', 'alpahsss' ), array( $this, 'section_general' ), __FILE__ );

		add_settings_field( 'publish-key', __( 'Publish key', 'alpahsss' ), array( $this, 'setting_publish_key' ), __FILE__, 'general_section' );
		add_settings_field( 'subscribe-key', __( 'Subscribe key', 'alpahsss' ), array( $this, 'setting_subscribe_key' ), __FILE__, 'general_section' );
		add_settings_field( 'channel-prefix', __( 'Channel prefix', 'alpahsss' ), array( $this, 'setting_channel_prefix' ), __FILE__, 'general_section' );
	}

	public function setting_publish_key()
	{
		if ( ! $value = $this->option( 'publish-key' ) ) {
			$value = '';
		}

		printf( '<input id="publish-key" name="alpahsss_members_plugin_options[publish-key]" value="%s" /> ', $value);

		_e('Add publish key', 'alpahsss-members');
	}

	public function setting_subscribe_key()
	{
		if ( ! $value = $this->option( 'subscribe-key' ) ) {
			$value = '';
		}

		printf( '<input id="subscribe-key" name="alpahsss_members_plugin_options[subscribe-key]" value="%s" /> ', $value);

		_e('Add subscribe key', 'alpahsss-members');
	}

	public function setting_channel_prefix()
	{
		if ( ! $value = $this->option( 'channel-prefix' ) ) {
			$value = '';
		}

		printf( '<input id="channel-prefix" name="alpahsss_members_plugin_options[channel-prefix]" value="%s" /> ', $value);

		_e('Add channel prefix', 'alpahsss-members');
	}

	/**
	 * Add plugin settings page
	 */
	public function admin_menu()
	{
		add_options_page( 'Alpahsss Members', 'Alpahsss Members', 'manage_options', __FILE__, array( $this, 'options_page' ) );
	}

	/**
	 * Add plugin settings page
	 */
	public function network_admin_menu()
	{
		return $this->admin_menu();
	}

	/**
	 * Render settings page
	 */
	public function options_page()
	{
	?>

Alpahsss Members

			<form action="options.php" method="post">
			<?php settings_fields('alpahsss_members_plugin_options'); ?>
			<?php do_settings_sections(__FILE__); ?>

				<input name="Submit" type="submit" class="button-primary" value="<?php esc_attr_e('Save Changes'); ?>" />

			</form>

	<?php
	}

	/**
	 * General settings section
	 */
	public function section_general()
	{
		_e( 'Some dummy text here', 'alpahsss-members' );
	}

	/**
	 * Validate plugin option
	 *
	 * @return array
	 */
	public function plugin_options_validate( $input )
	{
		$input['publish-key']   = esc_html ( $input['publish-key'] );
		$input['subscribe-key'] = esc_html ( $input['subscribe-key'] );
		$input['channel-prefix'] = esc_html ( $input['channel-prefix'] );

		return $input;
	}
}
// End class Alpahsss_Members_Admin

endif;

?>


text:
package consulo.util.lang.ref;

import javax.annotation.Nullable;
import java.util.function.Supplier;

/**
 * @author ven
 */
public class SimpleReference<T> implements Supplier<T> {
  private T myValue;

  public SimpleReference() {
  }

  public SimpleReference(@Nullable T value) {
    myValue = value;
  }

  public boolean isNull() {
    return myValue == null;
  }

  @Override
  public T get() {
    return myValue;
  }

  public void set(@Nullable T value) {
    myValue = value;
  }

  public boolean setIfNull(@Nullable T value) {
    if (myValue == null) {
      myValue = value;
      return true;
    }
    return false;
  }

  public static <T> SimpleReference<T> create() {
    return new SimpleReference<>();
  }

  public static <T> SimpleReference<T> create(@Nullable T value) {
    return new SimpleReference<>(value);
  }

  @Override
  public String toString() {
    return String.valueOf(myValue);
  }
}


text:
package interceptor

// Chain is an interceptor that runs all child interceptors in order.
type Chain struct {
	interceptors []Interceptor
}

// NewChain returns a new Chain interceptor.
func NewChain(interceptors []Interceptor) *Chain {
	return &Chain{interceptors: interceptors}
}

// BindRTCPReader lets you modify any incoming RTCP packets. It is called once per sender/receiver, however this might
// change in the future. The returned method will be called once per packet batch.
func (i *Chain) BindRTCPReader(reader RTCPReader) RTCPReader {
	for _, interceptor := range i.interceptors {
		reader = interceptor.BindRTCPReader(reader)
	}

	return reader
}

// BindRTCPWriter lets you modify any outgoing RTCP packets. It is called once per PeerConnection. The returned method
// will be called once per packet batch.
func (i *Chain) BindRTCPWriter(writer RTCPWriter) RTCPWriter {
	for _, interceptor := range i.interceptors {
		writer = interceptor.BindRTCPWriter(writer)
	}

	return writer
}

// BindLocalStream lets you modify any outgoing RTP packets. It is called once for per LocalStream. The returned method
// will be called once per rtp packet.
func (i *Chain) BindLocalStream(ctx *StreamInfo, writer RTPWriter) RTPWriter {
	for _, interceptor := range i.interceptors {
		writer = interceptor.BindLocalStream(ctx, writer)
	}

	return writer
}

// UnbindLocalStream is called when the Stream is removed. It can be used to clean up any data related to that track.
func (i *Chain) UnbindLocalStream(ctx *StreamInfo) {
	for _, interceptor := range i.interceptors {
		interceptor.UnbindLocalStream(ctx)
	}
}

// BindRemoteStream lets you modify any incoming RTP packets. It is called once for per RemoteStream. The returned method
// will be called once per rtp packet.
func (i *Chain) BindRemoteStream(ctx *StreamInfo, reader RTPReader) RTPReader {
	for _, interceptor := range i.interceptors {
		reader = interceptor.BindRemoteStream(ctx, reader)
	}

	return reader
}

// UnbindRemoteStream is called when the Stream is removed. It can be used to clean up any data related to that track.
func (i *Chain) UnbindRemoteStream(ctx *StreamInfo) {
	for _, interceptor := range i.interceptors {
		interceptor.UnbindRemoteStream(ctx)
	}
}

// Close closes the Interceptor, cleaning up any data if necessary.
func (i *Chain) Close() error {
	var errs []error
	for _, interceptor := range i.interceptors {
		errs = append(errs, interceptor.Close())
	}

	return flattenErrs(errs)
}


text:
<?php

namespace Fixtures\Bundles\RepositoryServiceBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/** @ORM\Entity */
class TestDefaultRepoEntity
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     *
     * @var int
     */
    private $id;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Gov. Forest Exp. Sta. 46: 118 (1950)

#### Original name
Amphichaeta cephalotaxi Sawada

### Remarks
null


text:
<?php

class SiteController extends Controller {

    public function actions() {

    }

    public function actionIndex() {
        $this->render('index');
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError() {
        $this->pageTitle = 'Page not found. Error 404.';

        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest) {
                echo $error['message'];
            } else {
                $this->render('error', $error);
            }

            Error404::push($error);
        }
    }
}


text:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.TagHelpers;
using Microsoft.Extensions.Caching.Memory;

namespace HtmlGenerationWebSite;

public class Startup
{
    // Set up application services
    public void ConfigureServices(IServiceCollection services)
    {
        // Add MVC services to the services container. Change default FormTagHelper.AntiForgery to false. Usually
        // null which is interpreted as true unless element includes an action attribute.
        services.AddMvc(ConfigureMvcOptions)
            .InitializeTagHelper<FormTagHelper>((helper, _) => helper.Antiforgery = false);

        services.AddSingleton(typeof(ISignalTokenProviderService<>), typeof(SignalTokenProviderService<>));
        services.AddSingleton<ProductsService>();
        services.Configure<MemoryCacheOptions>(o => o.TrackLinkedCacheEntries = true);
    }

    public virtual void Configure(IApplicationBuilder app)
    {
        app.UseStaticFiles();

        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "areaRoute",
                pattern: "{area:exists}/{controller}/{action}/{id?}",
                defaults: new { action = "Index" });
            endpoints.MapControllerRoute(
                name: "productRoute",
                pattern: "Product/{action}",
                defaults: new { controller = "Product" });
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller}/{action}/{id?}",
                defaults: new { controller = "HtmlGeneration_Home", action = "Index" });

            endpoints.MapRazorPages();
        });
    }

    public static void Main(string[] args)
    {
        var host = CreateWebHostBuilder(args)
            .Build();

        host.Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        new WebHostBuilder()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseStartup<Startup>()
            .UseKestrel()
            .UseIISIntegration();

    protected virtual void ConfigureMvcOptions(MvcOptions options)
    {
    }
}


text:
"""Unittests for cros."""

from __future__ import print_function

import sys

from chromite.lib import commandline
from chromite.lib import cros_test_lib
from chromite.scripts import cros

assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'

class RunScriptTest(cros_test_lib.MockTempDirTestCase):
  """Test the main functionality."""

  def setUp(self):
    self.PatchObject(cros, '_RunSubCommand', autospec=True)

  def testDefaultLogLevel(self):
    """Test that the default log level is set to notice."""
    arg_parser = self.PatchObject(commandline, 'ArgumentParser',
                                  return_value=commandline.ArgumentParser())
    cros.GetOptions()
    arg_parser.assert_called_with(caching=True, default_log_level='notice')

  def testSubcommand(self):
    """Test parser when given a subcommand."""
    parser = cros.GetOptions('lint')
    opts = parser.parse_args(['lint'])
    self.assertEqual(opts.subcommand, 'lint')


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

    <title>com.parse</title>
    <link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

com.parse

Classes

ParseCrashReporting


text:
<?php

/**
 * @group markup
 */
final class PhutilSyntaxHighlighterException extends Exception {
}


text:
Any contribution is appreciated! You might want to:

* Fix spelling errors
* Improve documentation
* Add tests for untested code
* Add new features
* Fix bugs

## How can I contribute?

* Use [issues](https://github.com/pdfminer/pdfminer.six/issues) to report bugs and features
    - If you report a bug in the results for a particular pdf, include that pdf. This allows others to replicate the
     issue.
* Fix issues by [creating pull requests](https://help.github.com/en/articles/creating-a-pull-request).
* Help others by sharing your thoughs in comments on issues and pull requests.
* Join the chat on [gitter](https://gitter.im/pdfminer-six/Lobby)

## Guidelines for creating issues

* Search previous issues, as yours might be a duplicate.
* When creating a new issue for a bug, include a minimal reproducible example.
* When creating a new issue for a feature, be sure to describe the context of the problem you are trying to solve. This
  will help others to see the importance of your feature request.

## Guideline for creating pull request

* A pull request should close an existing issue. For example, use "Fix #123" to indicate that your PR fixes issue 123.
* Pull requests should be merged to master.
* Include unit tests when possible. In case of bugs, this will help to prevent the same mistake in the future. In case
  of features, this will show that your code works correctly.
* Code should work for Python 3.6+.
* Test your code by using nox (see below).
* New features should be well documented using docstrings.
* Check if the [README.md](../README.md) or [readthedocs](../docs/source) documentation needs to be updated.
* Check spelling and grammar.
* Don't forget to update the [CHANGELOG.md](CHANGELOG.md#[Unreleased]).

## Guidelines for posting comments

* [Be cordial and positive](https://www.kennethreitz.org/essays/be-cordial-or-be-on-your-way)

## Guidelines for publishing

* Publishing is automated. Add a YYYYMMDD version tag and GitHub workflows will do the rest.

## Getting started

1. Clone the repository

    ```sh
    git clone https://github.com/pdfminer/pdfminer.six
    cd pdfminer.six
    ```

2. Install dev dependencies

    ```sh
    pip install -e .[dev]
    ```

3. Run the tests

    On all Python versions:

    ```sh
    nox
   ```

   Or on a single Python version:

   ```sh
    nox -e py36
    ```


text:
package org.apache.spark.metrics

import java.util.concurrent.CountDownLatch

import org.apache.spark.executor.{DataWriteMethod, OutputMetrics, TaskMetrics}
import org.apache.spark.{TaskContext, SparkConf, SparkEnv}
import org.mockito.Mockito._
import org.scalatest.mock.MockitoSugar
import org.scalatest.{BeforeAndAfter, FlatSpec, Matchers}

import com.datastax.spark.connector.writer.{RichStatement, WriteConf}

class OutputMetricsUpdaterSpec extends FlatSpec with Matchers with BeforeAndAfter with MockitoSugar {

  val ts = System.currentTimeMillis()

  after {
    SparkEnv.set(null)
  }

  private def newTaskContext(): TaskContext = {
    val tc = mock[TaskContext]
    when(tc.taskMetrics()) thenReturn new TaskMetrics
    tc
  }

  private def newRichStatement(): RichStatement = {
    new RichStatement() {
      override val bytesCount = 100
      override val rowsCount = 10
    }
  }

  "OutputMetricsUpdater" should "initialize task metrics properly when they are empty" in {
    val tc = newTaskContext()
    tc.taskMetrics().outputMetrics = None

    val conf = new SparkConf(loadDefaults = false)
    conf.set("spark.cassandra.output.metrics", "true")

    SparkEnv.set(mock[SparkEnv])
    OutputMetricsUpdater(tc, WriteConf.fromSparkConf(conf))

    tc.taskMetrics().outputMetrics.isDefined shouldBe true
    tc.taskMetrics().outputMetrics.get.writeMethod shouldBe DataWriteMethod.Hadoop
    tc.taskMetrics().outputMetrics.get.bytesWritten shouldBe 0L
    tc.taskMetrics().outputMetrics.get.recordsWritten shouldBe 0L
  }

  it should "initialize task metrics properly when they are defined" in {
    val tc = newTaskContext()
    tc.taskMetrics().outputMetrics = Some(new OutputMetrics(DataWriteMethod.Hadoop))

    val conf = new SparkConf(loadDefaults = false)
    conf.set("spark.cassandra.output.metrics", "true")

    SparkEnv.set(mock[SparkEnv])
    OutputMetricsUpdater(tc, WriteConf.fromSparkConf(conf))

    tc.taskMetrics().outputMetrics.isDefined shouldBe true
    tc.taskMetrics().outputMetrics.get.writeMethod shouldBe DataWriteMethod.Hadoop
    tc.taskMetrics().outputMetrics.get.bytesWritten shouldBe 0L
    tc.taskMetrics().outputMetrics.get.recordsWritten shouldBe 0L
  }

  it should "create updater which uses task metrics" in {
    val tc = newTaskContext()
    tc.taskMetrics().outputMetrics = None

    val conf = new SparkConf(loadDefaults = false)
    conf.set("spark.cassandra.output.metrics", "true")

    SparkEnv.set(mock[SparkEnv])
    val updater = OutputMetricsUpdater(tc, WriteConf.fromSparkConf(conf))

    val rc = newRichStatement()
    updater.batchFinished(success = true, rc, ts, ts)
    tc.taskMetrics().outputMetrics.get.bytesWritten shouldBe 100L // change registered when success
    tc.taskMetrics().outputMetrics.get.recordsWritten shouldBe 10L

    updater.batchFinished(success = false, rc, ts, ts)
    tc.taskMetrics().outputMetrics.get.bytesWritten shouldBe 100L // change not regsitered when failure
    tc.taskMetrics().outputMetrics.get.recordsWritten shouldBe 10L
  }

  it should "create updater which does not use task metrics" in {
    val tc = mock[TaskContext]
    val conf = new SparkConf(loadDefaults = false)
    conf.set("spark.cassandra.output.metrics", "false")

    SparkEnv.set(mock[SparkEnv])
    val updater = OutputMetricsUpdater(tc, WriteConf.fromSparkConf(conf))

    val rc = newRichStatement()
    updater.batchFinished(success = true, rc, ts, ts)
    updater.batchFinished(success = false, rc, ts, ts)

    verify(tc, never).taskMetrics()
  }

  it should "create updater which uses Codahale metrics" in {
    val tc = newTaskContext()
    val conf = new SparkConf(loadDefaults = false)
    SparkEnv.set(mock[SparkEnv])
    val ccs = new CassandraConnectorSource
    CassandraConnectorSource.instance should not be None

    val updater = OutputMetricsUpdater(tc, WriteConf.fromSparkConf(conf))

    val rc = newRichStatement()
    updater.batchFinished(success = true, rc, ts, ts)
    ccs.writeRowMeter.getCount shouldBe 10L
    ccs.writeByteMeter.getCount shouldBe 100L
    ccs.writeSuccessCounter.getCount shouldBe 1L
    ccs.writeFailureCounter.getCount shouldBe 0L

    updater.batchFinished(success = false, rc, ts, ts)
    ccs.writeRowMeter.getCount shouldBe 10L
    ccs.writeByteMeter.getCount shouldBe 100L
    ccs.writeSuccessCounter.getCount shouldBe 1L
    ccs.writeFailureCounter.getCount shouldBe 1L

    updater.finish()
    ccs.writeTaskTimer.getCount shouldBe 1L
  }

  it should "create updater which doesn't use Codahale metrics" in {
    val tc = newTaskContext()
    val conf = new SparkConf(loadDefaults = false)
    SparkEnv.set(mock[SparkEnv])

    val updater = OutputMetricsUpdater(tc, WriteConf.fromSparkConf(conf))
    val rc = newRichStatement()
    updater.batchFinished(success = true, rc, ts, ts)
    updater.batchFinished(success = false, rc, ts, ts)

    CassandraConnectorSource.instance shouldBe None

    updater.finish()
  }

  it should "work correctly with multiple threads" in {
    val tc = newTaskContext()
    tc.taskMetrics().outputMetrics = None

    val conf = new SparkConf(loadDefaults = false)
    conf.set("spark.cassandra.output.metrics", "true")

    SparkEnv.set(mock[SparkEnv])
    val updater = OutputMetricsUpdater(tc, WriteConf.fromSparkConf(conf))

    val rc = newRichStatement()

    val latch = new CountDownLatch(32)
    class TestThread extends Thread {
      override def run(): Unit = {
        latch.countDown()
        latch.await()
        for (i <- 1 to 100000)
          updater.batchFinished(success = true, rc, ts, ts)
      }
    }

    val threads = Array.fill(32)(new TestThread)
    threads.foreach(_.start())
    threads.foreach(_.join())

    tc.taskMetrics().outputMetrics.get.bytesWritten shouldBe 320000000L
    tc.taskMetrics().outputMetrics.get.recordsWritten shouldBe 32000000L
  }

}


text:
#pragma once
#include <Doremi/Core/Include/EventHandler/Events/Event.hpp>
#include <Doremi/Core/Include/EntityComponent/Constants.hpp>
#include <stdint.h>

namespace Doremi
{
    namespace Core
    {
        struct GunFireToggleEvent : public Event
        {
            GunFireToggleEvent() : Event(EventType::GunFireToggle), entityID(0), isFiring(false) {}
            GunFireToggleEvent(uint32_t p_entityID, bool p_isFiring) : Event(EventType::GunFireToggle), entityID(p_entityID), isFiring(p_isFiring) {}

            /**
            Write object to stream
            */
            void Write(Streamer* p_streamer, uint32_t& op_bitsWritten) override
            {
                p_streamer->WriteUnsignedInt32(entityID);
                p_streamer->WriteBool(isFiring);
                op_bitsWritten += sizeof(uint32_t) * 8 + 1;
            }

            /**
            Read object from stream
            */
            void Read(Streamer* p_streamer, uint32_t& op_bitsRead) override
            {
                entityID = p_streamer->ReadUnsignedInt32();
                isFiring = p_streamer->ReadBool();
                op_bitsRead += sizeof(uint32_t) * 8 + 1;
            }

            EntityID entityID;
            bool isFiring;
        };
    }
}