text:
"""Command line function 'roc'."""
from __future__ import print_function
from gimmemotifs.motif import read_motifs
from gimmemotifs.plot import roc_plot
from gimmemotifs.stats import calc_stats_iterator
from gimmemotifs.config import MotifConfig, DIRECT_NAME, INDIRECT_NAME
import numpy as np
import pandas as pd
import os
import re
import sys
from statsmodels.stats.multitest import multipletests

def html_report(outdir, infile, pwmfile, threshold=0.01):
    df = pd.read_table(infile, index_col=0)
    del df.index.name
    df["corrected P-value"] = multipletests(df["P-value"], method="fdr_bh")[1]

    cols = [
            "Logo",
            "# matches",
            "# matches background",
            "P-value",
            "log10 P-value",
            "corrected P-value",
            "ROC AUC",
            "PR AUC",
            "Enr. at 1% FPR",
            "Recall at 10% FDR"
    ]

    motifs = read_motifs(pwmfile)
    idx = [motif.id for motif in motifs]
    direct = [",".join(motif.factors[DIRECT_NAME]) for motif in motifs]
    indirect = [",".join(motif.factors[INDIRECT_NAME]) for motif in motifs]
    m2f = pd.DataFrame({DIRECT_NAME:direct, INDIRECT_NAME:indirect}, index=idx)

    factor_cols = [DIRECT_NAME, INDIRECT_NAME]
    if True:
        for factor_col in factor_cols:
            f = m2f[factor_col].str.len() > 30
            m2f[factor_col] = '
' + m2f[factor_col].str.slice(0,30)
            m2f.loc[f, factor_col] += '(...)'
            m2f[factor_col] += '
'
        df = df.join(m2f)
        cols = factor_cols + cols

    df = df[df["corrected P-value"] <= threshold]

    df["Logo"] = [''.format(re.sub('[^-_\w]+', '_', x)) for x in list(df.index)]

    df = df[cols]
    if not os.path.exists(outdir + "/logos"):
        os.makedirs(outdir + "/logos")
    for motif in motifs:
        if motif.id in df.index:
            motif.to_img(outdir + "/logos/{}.png".format(re.sub('[^-_\w]+', '_', motif.id)), fmt="PNG")

    bar_cols = [
            "log10 P-value", "ROC AUC", "PR AUC", "MNCP",
            "Enr. at 1% FPR", "Recall at 10% FDR"
            ]
    template_dir = MotifConfig().get_template_dir()
    js = open(os.path.join(template_dir, "sortable/sortable.min.js"), encoding="utf-8").read()
    css = open(os.path.join(template_dir, "sortable/sortable-theme-slick.css"), encoding="utf-8").read()
    with open(outdir + "/gimme.roc.report.html", "w",  encoding="utf-8") as f:
        f.write("\n")
        f.write("\n".format(css))
        f.write("\n")
        f.write("\n")
        if df.shape[0] > 0:
            f.write(df.sort_values("ROC AUC", ascending=False).style.bar(bar_cols).set_precision(3).set_table_attributes("data-sortable").render().replace("data-sortable", 'class="sortable-theme-slick" data-sortable'))
        else:
            f.write("No enriched motifs found.")
        f.write("\n".format(js))
        f.write("\n")

def roc(args):
    """ Calculate ROC_AUC and other metrics and optionally plot ROC curve."""
    outputfile = args.outfile
    # Default extension for image
    if outputfile and not outputfile.endswith(".png"):
        outputfile += ".png"

    motifs = read_motifs(args.pwmfile, fmt="pwm")

    ids = []
    if args.ids:
        ids = args.ids.split(",")
    else:
        ids = [m.id for m in motifs]
    motifs = [m for m in motifs if (m.id in ids)]

    stats = [
            "phyper_at_fpr",
            "roc_auc",
            "pr_auc",
            "enr_at_fpr",
            "recall_at_fdr",
            "roc_values",
            "matches_at_fpr",
            ]

    plot_x = []
    plot_y = []
    legend = []

    f_out = sys.stdout
    if args.outdir:
        if not os.path.exists(args.outdir):
            os.makedirs(args.outdir)
        f_out = open(args.outdir + "/gimme.roc.report.txt", "w")

    # Print the metrics
    f_out.write("Motif\t# matches\t# matches background\tP-value\tlog10 P-value\tROC AUC\tPR AUC\tEnr. at 1% FPR\tRecall at 10% FDR\n")

    for motif_stats in calc_stats_iterator(motifs, args.sample, args.background,
            genome=args.genome, stats=stats, ncpus=args.ncpus):

        for motif in motifs:
            if str(motif) in motif_stats:
                if outputfile:
                    x, y = motif_stats[str(motif)]["roc_values"]
                    plot_x.append(x)
                    plot_y.append(y)
                    legend.append(motif.id)
                log_pvalue = np.inf
                if motif_stats[str(motif)]["phyper_at_fpr"] > 0:
                    log_pvalue = -np.log10(motif_stats[str(motif)]["phyper_at_fpr"])
                f_out.write("{}\t{:d}\t{:d}\t{:.2e}\t{:.3f}\t{:.3f}\t{:.3f}\t{:.2f}\t{:0.4f}\n".format(
                      motif.id,
                      motif_stats[str(motif)]["matches_at_fpr"][0],
                      motif_stats[str(motif)]["matches_at_fpr"][1],
                      motif_stats[str(motif)]["phyper_at_fpr"],
                      log_pvalue,
                      motif_stats[str(motif)]["roc_auc"],
                      motif_stats[str(motif)]["pr_auc"],
                      motif_stats[str(motif)]["enr_at_fpr"],
                      motif_stats[str(motif)]["recall_at_fdr"],
                      ))
    f_out.close()

    if args.outdir:
        html_report(
            args.outdir,
            args.outdir + "/gimme.roc.report.txt",
            args.pwmfile,
            0.01,
            )

    # Plot the ROC curve
    if outputfile:
        roc_plot(outputfile, plot_x, plot_y, ids=legend)


text:
/**
 *
 */
using org.javarosa.core.services.locale;
using org.javarosa.core.util;
using org.javarosa.core.util.externalizable;
using System;
using System.IO;
namespace org.javarosa.core.reference
{

    /**
     * The ReferenceDataSource is a source of locale data which
     * is located at a location which is defined by a ReferenceURI.
     *
     * @author Acellam Guy ,  Clayton Sims
     * @date Jun 1, 2009
     *
     */
    public class ReferenceDataSource : LocaleDataSource
    {

        String referenceURI;

        /**
         * NOTE: FOR SERIALIZATION ONLY!
         */
        public ReferenceDataSource()
        {

        }

        /**
         * Creates a new Data Source for Locale data with the given resource URI.
         *
         * @param resourceURI a URI to the resource file from which data should be loaded
         * @throws NullPointerException if resourceURI is null
         */
        public ReferenceDataSource(String referenceURI)
        {
            if (referenceURI == null)
            {
                throw new NullReferenceException("Reference URI cannot be null when creating a Resource File Data Source");
            }
            this.referenceURI = referenceURI;
        }

        /* (non-Javadoc)
         * @see org.javarosa.core.services.locale.LocaleDataSource#getLocalizedText()
         */
        public OrderedHashtable getLocalizedText()
        {
            try
            {
                Stream is_renamed = ReferenceManager._().DeriveReference(referenceURI).Stream;
                return LocalizationUtils.parseLocaleInput(is_renamed);
            }
            catch (IOException e)
            {
                Console.WriteLine(e.StackTrace);
                throw new SystemException("IOException while getting localized text at reference " + referenceURI);
            }
            catch (InvalidReferenceException e)
            {
                Console.WriteLine(e.StackTrace);
                throw new SystemException("Invalid Reference! " + referenceURI);
            }
        }

        /* (non-Javadoc)
        * @see org.javarosa.core.util.externalizable.Externalizable#readExternal(java.io.DataInputStream, org.javarosa.core.util.externalizable.PrototypeFactory)
        */
        //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'"
        public virtual void readExternal(System.IO.BinaryReader in_Renamed, PrototypeFactory pf)
        {
            //UPGRADE_ISSUE: Method 'java.io.DataInputStream.readUTF' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaioDataInputStreamreadUTF'"
            referenceURI = in_Renamed.ReadString();
        }

        /* (non-Javadoc)
            * @see org.javarosa.core.util.externalizable.Externalizable#writeExternal(java.io.DataOutputStream)
            */
        //UPGRADE_TODO: Class 'java.io.DataOutputStream' was converted to 'System.IO.BinaryWriter' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataOutputStream'"
        public virtual void writeExternal(System.IO.BinaryWriter out_Renamed)
        {
            //UPGRADE_ISSUE: Method 'java.io.DataOutputStream.writeUTF' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaioDataOutputStreamwriteUTF_javalangString'"
            out_Renamed.Write(referenceURI);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
Accepts an array of objects with label and value properties and outputs a string of select dropdown option values. The label property is used for the option display text and the value property is used to populate the option value attribute. The output can be inserted into a select tag.

**Usage:**

    // array = [ { label: "Please Select", value: "" }, { label: "Option 1", value: "1" } ]
    {{option-list array "selected value"}}
    // Output => <option value="">Please Select</option><option value="1">Option 1</option>

**Other Dependencies:** N/A


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

<title>MeshRendererInternal (Torch Engine 1.0 API)</title>
<meta name="date" content="2016-08-15">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.snakybo.torch.renderer

Class MeshRendererInternal

java.lang.Object

com.snakybo.torch.renderer.MeshRendererInternal

public final class MeshRendererInternal
extends java.lang.Object

Since:

1.0

Constructor Summary

Constructors

Constructor and Description

MeshRendererInternal(Mesh mesh,
                    Material material)

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
create()

void
destroy()

Material
getMaterial()

void
render()

void
setMaterial(Material material)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MeshRendererInternal

public MeshRendererInternal(Mesh mesh,
                            Material material)

Method Detail

create

public final void create()

render

public final void render()

destroy

public final void destroy()

setMaterial

public final void setMaterial(Material material)

getMaterial

public final Material getMaterial()

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
#pragma once

#include "envoy/access_log/access_log.h"
#include "envoy/api/api.h"
#include "envoy/config/core/v3/health_check.pb.h"
#include "envoy/data/core/v3/health_check_event.pb.h"
#include "envoy/grpc/status.h"
#include "envoy/type/v3/http.pb.h"
#include "envoy/type/v3/range.pb.h"

#include "common/common/logger.h"
#include "common/grpc/codec.h"
#include "common/http/codec_client.h"
#include "common/router/header_parser.h"
#include "common/stream_info/stream_info_impl.h"
#include "common/upstream/health_checker_base_impl.h"

#include "src/proto/grpc/health/v1/health.pb.h"

namespace Envoy {
namespace Upstream {

/**
 * Factory for creating health checker implementations.
 */
class HealthCheckerFactory : public Logger::Loggable<Logger::Id::health_checker> {
public:
  /**
   * Create a health checker.
   * @param health_check_config supplies the health check proto.
   * @param cluster supplies the owning cluster.
   * @param runtime supplies the runtime loader.
   * @param random supplies the random generator.
   * @param dispatcher supplies the dispatcher.
   * @param event_logger supplies the event_logger.
   * @param validation_visitor message validation visitor instance.
   * @return a health checker.
   */
  static HealthCheckerSharedPtr
  create(const envoy::config::core::v3::HealthCheck& health_check_config,
         Upstream::Cluster& cluster, Runtime::Loader& runtime, Runtime::RandomGenerator& random,
         Event::Dispatcher& dispatcher, AccessLog::AccessLogManager& log_manager,
         ProtobufMessage::ValidationVisitor& validation_visitor, Api::Api& api);
};

/**
 * HTTP health checker implementation. Connection keep alive is used where possible.
 */
class HttpHealthCheckerImpl : public HealthCheckerImplBase {
public:
  HttpHealthCheckerImpl(const Cluster& cluster, const envoy::config::core::v3::HealthCheck& config,
                        Event::Dispatcher& dispatcher, Runtime::Loader& runtime,
                        Runtime::RandomGenerator& random, HealthCheckEventLoggerPtr&& event_logger);

  /**
   * Utility class checking if given http status matches configured expectations.
   */
  class HttpStatusChecker {
  public:
    HttpStatusChecker(
        const Protobuf::RepeatedPtrField<envoy::type::v3::Int64Range>& expected_statuses,
        uint64_t default_expected_status);

    bool inRange(uint64_t http_status) const;

  private:
    std::vector<std::pair<uint64_t, uint64_t>> ranges_;
  };

private:
  struct HttpActiveHealthCheckSession : public ActiveHealthCheckSession,
                                        public Http::ResponseDecoder,
                                        public Http::StreamCallbacks {
    HttpActiveHealthCheckSession(HttpHealthCheckerImpl& parent, const HostSharedPtr& host);
    ~HttpActiveHealthCheckSession() override;

    void onResponseComplete();
    enum class HealthCheckResult { Succeeded, Degraded, Failed };
    HealthCheckResult healthCheckResult();
    bool shouldClose() const;

    // ActiveHealthCheckSession
    void onInterval() override;
    void onTimeout() override;
    void onDeferredDelete() final;

    // Http::StreamDecoder
    void decodeData(Buffer::Instance&, bool end_stream) override {
      if (end_stream) {
        onResponseComplete();
      }
    }
    void decodeMetadata(Http::MetadataMapPtr&&) override {}

    // Http::ResponseDecoder
    void decode100ContinueHeaders(Http::ResponseHeaderMapPtr&&) override {}
    void decodeHeaders(Http::ResponseHeaderMapPtr&& headers, bool end_stream) override;
    void decodeTrailers(Http::ResponseTrailerMapPtr&&) override { onResponseComplete(); }

    // Http::StreamCallbacks
    void onResetStream(Http::StreamResetReason reason,
                       absl::string_view transport_failure_reason) override;
    void onAboveWriteBufferHighWatermark() override {}
    void onBelowWriteBufferLowWatermark() override {}

    void onEvent(Network::ConnectionEvent event);

    class ConnectionCallbackImpl : public Network::ConnectionCallbacks {
    public:
      ConnectionCallbackImpl(HttpActiveHealthCheckSession& parent) : parent_(parent) {}
      // Network::ConnectionCallbacks
      void onEvent(Network::ConnectionEvent event) override { parent_.onEvent(event); }
      void onAboveWriteBufferHighWatermark() override {}
      void onBelowWriteBufferLowWatermark() override {}

    private:
      HttpActiveHealthCheckSession& parent_;
    };

    ConnectionCallbackImpl connection_callback_impl_{*this};
    HttpHealthCheckerImpl& parent_;
    Http::CodecClientPtr client_;
    Http::ResponseHeaderMapPtr response_headers_;
    const std::string& hostname_;
    const Http::Protocol protocol_;
    Network::Address::InstanceConstSharedPtr local_address_;
    bool expect_reset_{};
  };

  using HttpActiveHealthCheckSessionPtr = std::unique_ptr<HttpActiveHealthCheckSession>;

  virtual Http::CodecClient* createCodecClient(Upstream::Host::CreateConnectionData& data) PURE;

  // HealthCheckerImplBase
  ActiveHealthCheckSessionPtr makeSession(HostSharedPtr host) override {
    return std::make_unique<HttpActiveHealthCheckSession>(*this, host);
  }
  envoy::data::core::v3::HealthCheckerType healthCheckerType() const override {
    return envoy::data::core::v3::HTTP;
  }

  Http::CodecClient::Type codecClientType(const envoy::type::v3::CodecClientType& type);

  const std::string path_;
  const std::string host_value_;
  absl::optional<Matchers::StringMatcherImpl> service_name_matcher_;
  Router::HeaderParserPtr request_headers_parser_;
  const HttpStatusChecker http_status_checker_;

protected:
  const Http::CodecClient::Type codec_client_type_;
};

/**
 * Production implementation of the HTTP health checker that allocates a real codec client.
 */
class ProdHttpHealthCheckerImpl : public HttpHealthCheckerImpl {
public:
  using HttpHealthCheckerImpl::HttpHealthCheckerImpl;

  // HttpHealthCheckerImpl
  Http::CodecClient* createCodecClient(Upstream::Host::CreateConnectionData& data) override;
};

/**
 * Utility class for loading a binary health checking config and matching it against a buffer.
 * Split out for ease of testing. The type of matching performed is the following (this is the
 * MongoDB health check request and response):
 *
 * "send": [
    {"binary": "39000000"},
    {"binary": "EEEEEEEE"},
    {"binary": "00000000"},
    {"binary": "d4070000"},
    {"binary": "00000000"},
    {"binary": "746573742e"},
    {"binary": "24636d6400"},
    {"binary": "00000000"},
    {"binary": "FFFFFFFF"},

    {"binary": "13000000"},
    {"binary": "01"},
    {"binary": "70696e6700"},
    {"binary": "000000000000f03f"},
    {"binary": "00"}
   ],
   "receive": [
    {"binary": "EEEEEEEE"},
    {"binary": "01000000"},
    {"binary": "00000000"},
    {"binary": "0000000000000000"},
    {"binary": "00000000"},
    {"binary": "11000000"},
    {"binary": "01"},
    {"binary": "6f6b"},
    {"binary": "00000000000000f03f"},
    {"binary": "00"}
   ]
 *
 * During each health check cycle, all of the "send" bytes are sent to the target server. Each
 * binary block can be of arbitrary length and is just concatenated together when sent.
 *
 * On the receive side, "fuzzy" matching is performed such that each binary block must be found,
 * and in the order specified, but not necessary contiguous. Thus, in the example above,
 * "FFFFFFFF" could be inserted in the response between "EEEEEEEE" and "01000000" and the check
 * would still pass.
 */
class TcpHealthCheckMatcher {
public:
  using MatchSegments = std::list<std::vector<uint8_t>>;

  static MatchSegments loadProtoBytes(
      const Protobuf::RepeatedPtrField<envoy::config::core::v3::HealthCheck::Payload>& byte_array);
  static bool match(const MatchSegments& expected, const Buffer::Instance& buffer);
};

/**
 * TCP health checker implementation.
 */
class TcpHealthCheckerImpl : public HealthCheckerImplBase {
public:
  TcpHealthCheckerImpl(const Cluster& cluster, const envoy::config::core::v3::HealthCheck& config,
                       Event::Dispatcher& dispatcher, Runtime::Loader& runtime,
                       Runtime::RandomGenerator& random, HealthCheckEventLoggerPtr&& event_logger);

private:
  struct TcpActiveHealthCheckSession;

  struct TcpSessionCallbacks : public Network::ConnectionCallbacks,
                               public Network::ReadFilterBaseImpl {
    TcpSessionCallbacks(TcpActiveHealthCheckSession& parent) : parent_(parent) {}

    // Network::ConnectionCallbacks
    void onEvent(Network::ConnectionEvent event) override { parent_.onEvent(event); }
    void onAboveWriteBufferHighWatermark() override {}
    void onBelowWriteBufferLowWatermark() override {}

    // Network::ReadFilter
    Network::FilterStatus onData(Buffer::Instance& data, bool) override {
      parent_.onData(data);
      return Network::FilterStatus::StopIteration;
    }

    TcpActiveHealthCheckSession& parent_;
  };

  struct TcpActiveHealthCheckSession : public ActiveHealthCheckSession {
    TcpActiveHealthCheckSession(TcpHealthCheckerImpl& parent, const HostSharedPtr& host)
        : ActiveHealthCheckSession(parent, host), parent_(parent) {}
    ~TcpActiveHealthCheckSession() override;

    void onData(Buffer::Instance& data);
    void onEvent(Network::ConnectionEvent event);

    // ActiveHealthCheckSession
    void onInterval() override;
    void onTimeout() override;
    void onDeferredDelete() final;

    TcpHealthCheckerImpl& parent_;
    Network::ClientConnectionPtr client_;
    std::shared_ptr<TcpSessionCallbacks> session_callbacks_;
    // If true, stream close was initiated by us, not e.g. remote close or TCP reset.
    // In this case healthcheck status already reported, only state cleanup required.
    bool expect_close_{};
  };

  using TcpActiveHealthCheckSessionPtr = std::unique_ptr<TcpActiveHealthCheckSession>;

  // HealthCheckerImplBase
  ActiveHealthCheckSessionPtr makeSession(HostSharedPtr host) override {
    return std::make_unique<TcpActiveHealthCheckSession>(*this, host);
  }
  envoy::data::core::v3::HealthCheckerType healthCheckerType() const override {
    return envoy::data::core::v3::TCP;
  }

  const TcpHealthCheckMatcher::MatchSegments send_bytes_;
  const TcpHealthCheckMatcher::MatchSegments receive_bytes_;
};

/**
 * gRPC health checker implementation.
 */
class GrpcHealthCheckerImpl : public HealthCheckerImplBase {
public:
  GrpcHealthCheckerImpl(const Cluster& cluster, const envoy::config::core::v3::HealthCheck& config,
                        Event::Dispatcher& dispatcher, Runtime::Loader& runtime,
                        Runtime::RandomGenerator& random, HealthCheckEventLoggerPtr&& event_logger);

private:
  struct GrpcActiveHealthCheckSession : public ActiveHealthCheckSession,
                                        public Http::ResponseDecoder,
                                        public Http::StreamCallbacks {
    GrpcActiveHealthCheckSession(GrpcHealthCheckerImpl& parent, const HostSharedPtr& host);
    ~GrpcActiveHealthCheckSession() override;

    void onRpcComplete(Grpc::Status::GrpcStatus grpc_status, const std::string& grpc_message,
                       bool end_stream);
    bool isHealthCheckSucceeded(Grpc::Status::GrpcStatus grpc_status) const;
    void resetState();
    void logHealthCheckStatus(Grpc::Status::GrpcStatus grpc_status,
                              const std::string& grpc_message);

    // ActiveHealthCheckSession
    void onInterval() override;
    void onTimeout() override;
    void onDeferredDelete() final;

    // Http::StreamDecoder
    void decodeData(Buffer::Instance&, bool end_stream) override;
    void decodeMetadata(Http::MetadataMapPtr&&) override {}

    // Http::ResponseDecoder
    void decode100ContinueHeaders(Http::ResponseHeaderMapPtr&&) override {}
    void decodeHeaders(Http::ResponseHeaderMapPtr&& headers, bool end_stream) override;
    void decodeTrailers(Http::ResponseTrailerMapPtr&&) override;

    // Http::StreamCallbacks
    void onResetStream(Http::StreamResetReason reason,
                       absl::string_view transport_failure_reason) override;
    void onAboveWriteBufferHighWatermark() override {}
    void onBelowWriteBufferLowWatermark() override {}

    void onEvent(Network::ConnectionEvent event);
    void onGoAway();

    class ConnectionCallbackImpl : public Network::ConnectionCallbacks {
    public:
      ConnectionCallbackImpl(GrpcActiveHealthCheckSession& parent) : parent_(parent) {}
      // Network::ConnectionCallbacks
      void onEvent(Network::ConnectionEvent event) override { parent_.onEvent(event); }
      void onAboveWriteBufferHighWatermark() override {}
      void onBelowWriteBufferLowWatermark() override {}

    private:
      GrpcActiveHealthCheckSession& parent_;
    };

    class HttpConnectionCallbackImpl : public Http::ConnectionCallbacks {
    public:
      HttpConnectionCallbackImpl(GrpcActiveHealthCheckSession& parent) : parent_(parent) {}
      // Http::ConnectionCallbacks
      void onGoAway() override { parent_.onGoAway(); }

    private:
      GrpcActiveHealthCheckSession& parent_;
    };

    ConnectionCallbackImpl connection_callback_impl_{*this};
    HttpConnectionCallbackImpl http_connection_callback_impl_{*this};
    GrpcHealthCheckerImpl& parent_;
    Http::CodecClientPtr client_;
    Http::RequestEncoder* request_encoder_;
    Grpc::Decoder decoder_;
    std::unique_ptr<grpc::health::v1::HealthCheckResponse> health_check_response_;
    // If true, stream reset was initiated by us (GrpcActiveHealthCheckSession), not by HTTP stack,
    // e.g. remote reset. In this case healthcheck status has already been reported, only state
    // cleanup is required.
    bool expect_reset_ = false;
  };

  virtual Http::CodecClientPtr createCodecClient(Upstream::Host::CreateConnectionData& data) PURE;

  // HealthCheckerImplBase
  ActiveHealthCheckSessionPtr makeSession(HostSharedPtr host) override {
    return std::make_unique<GrpcActiveHealthCheckSession>(*this, host);
  }
  envoy::data::core::v3::HealthCheckerType healthCheckerType() const override {
    return envoy::data::core::v3::GRPC;
  }

  const Protobuf::MethodDescriptor& service_method_;
  absl::optional<std::string> service_name_;
  absl::optional<std::string> authority_value_;
};

/**
 * Production implementation of the gRPC health checker that allocates a real codec client.
 */
class ProdGrpcHealthCheckerImpl : public GrpcHealthCheckerImpl {
public:
  using GrpcHealthCheckerImpl::GrpcHealthCheckerImpl;

  // GrpcHealthCheckerImpl
  Http::CodecClientPtr createCodecClient(Upstream::Host::CreateConnectionData& data) override;
};

} // namespace Upstream
} // namespace Envoy


text:
/**
    Defines the entire MixPanel API that the application can access.

    These events are actually a combination of EVENT and TYPE that we
    use to let an admin see a limited number of events on the surface but also
    break down those events into useful types. By giving each EVENT a
    TYPE we will create a standard that will make it easy for an unfamiliar
    admin to view statistics.

    MixPanel Version: 2?
    See MixPanel: http://mixpanel.com

    event.js and mixpanel.js are the only modules that access the GLOBAL mixpanel.

    @exports MP

    @requires Const
    @requires MPEvent
    @requires mixpanel (non-AMD)

    @return {Object} A set of functions that define the MP API. This decoupling
        stops folks from creating adhoc MP Events, as external users cannot
        call the internal Event objects' track function directly.
*/
define(
        [
            "js/constants",
            "lib/mixpanel/event",
            "order!lib/mixpanel/mixpanel-min"
        ],
        function (Const, MPEvent) {

// Imports
var createObject = MPEvent.createObject;
var enterData = MPEvent.enterData;
var playerTagged = MPEvent.playerTagged;
var requestLogin = MPEvent.requestLogin;
var signUp = MPEvent.signUp;
var viewPage = MPEvent.viewPage;
var GAME = Const.API_OBJECT.GAME;

/**
    Sqoreboard's token from the mixpanel dashboard.
*/
var MIXPANEL_TOKEN =  "21e3cfefb46bbded0d61eb0dca4bcec7";

/**
    Setup mixpanel functionality.
*/
var initializeMixPanel = (function () {
    mixpanel.init(MIXPANEL_TOKEN);
    mixpanel.set_config({
        //debug: true // adds a bunch of console.log output
    });
}());

return {
    /**
        Identify the User based on Person ID using Mixpanls' identify.
        @param {string} id The User's Person ID
    */
    identifyUser: function (id) {
        mixpanel.identify(id);
        // insert id as name
        mixpanel.name_tag(id);
        // FIXME remove this property but allow to set elsewhere
        mixpanel.register({"gender": "male"});
    },

    /**
        Track a successfully added Game by wrapping the "Create Object"
        event.
        @param {number} numberOfTags The number of tagged folks.
        @param {boolean} isScored True if the game was scored.
        @param {string} creatorsResult The result of the game's creator.
            (e.g. WON, LOST)
    */
    trackCreateGame: function (numberOfTags, isScored, creatorsResult) {
        createObject.trackCreateObject(
                GAME,
                numberOfTags,
                isScored,
                creatorsResult);
    },

    /**
        Track data entered by the user to construct a game.
        @param {string} dataType The type of inputted data.
        @param {string} inputValue The inputted data.
        @param {string} pageName The page the user is on.
    */
    trackEnterDataForGame: function (dataType, inputValue, pageName) {
        enterData.trackEnterData(
                GAME,
                dataType,
                inputValue,
                pageName);
    },

    /**
        Track player tagged to a game by the user.
        @param {string} distinctID the id to make object player into the
            active user.
        @param {string} objectType object the player is tagged to.
        @param {string} taggerID id of the tagger.
        @param {boolean} isSelfTag True if the tagger and distinct ID are
            the same.
    */
    trackPlayerTaggedToGame: function (distinctID, taggerID, isSelfTag) {
        playerTagged.trackPlayerTagged(
                distinctID,
                GAME,
                taggerID,
                isSelfTag);
    },

    /**
        Track a facebook login request by wrapping the "Request Login"
        event.
    */
    trackRequestFacebookLogin: function () {
        requestLogin.trackRequestLogin(requestLogin.LOGIN_TYPE.FACEBOOK);
    },

    /**
        Track a Facebook sign up by wrapping "Sign Up".
    */
    trackSignUpThroughFacebook: function () {
        signUp.trackSignUp(signUp.LOGIN_TYPE.FACEBOOK);
    },

    /**
        Track a landing view by wrapping the "View Page" event.
        @param {string} pageName The name of the page (e.g., "landing").
        @param {string} path The path to the page (e.g., "/").
    */
    trackViewLanding: function (pageName, path) {
        viewPage.trackViewPage(viewPage.PAGE_TYPE.LANDING, pageName, path);
    },

    /**
        Track a dialog view by wrapping the "View Page" event.
        @param {string} pageName The name of the page (e.g., "create_game").
        @param {string} path The path to the page (e.g., "/rankings").
    */
        trackViewDialog: function (pageName, path) {
        viewPage.trackViewPage(viewPage.PAGE_TYPE.DIALOG, pageName, path);
    },

    /**
        Track a tab view by wrapping the "View Page" event.
        @param {string} pageName The name of the page (e.g., "games").
        @param {string} path The path to the page (e.g., "/games").
    */
    trackViewTab: function (pageName, path) {
        viewPage.trackViewPage(viewPage.PAGE_TYPE.TAB, pageName, path);
    }
};

});


text:
require 'spec_helper'

# @todo: Fix namespace structure. Should be ETL::Control::Source::FileSource
describe ETL::Control::FileSource do
  let(:ctl_file)    { fail "ctl_file must first be defined, at line -#{__LINE__}- in the file #{__FILE__}." }
  let(:src_config)  { fail "src_config must first be defined, at line -#{__LINE__}- in the file #{__FILE__}." }

  let(:control)     { ETL::Control.parse(ctl_file) }
  let(:definition)  { [ :first_name, :last_name, :ssn, { :name => :age, :type => :integer } ] }

  context "When using a single file source" do
    let(:source)  { ETL::Control::FileSource.new(control, src_config, definition) }
    let(:rows)    { source.map { |row| row } }

    context "When using a relative path" do
      let(:ctl_file)    { fixture_path('delimited.ctl') }
      let(:src_config)  { {:file => 'data/delimited.txt', :parser => :csv} }

      before(:each) { definition << :sex }

      it 'should find 3 rows in the delimited file' do
        rows.should have(3).items
      end
    end

    context "When using a relative directory-glob as the file source" do
      let(:ctl_file)    { fixture_path('multiple_delimited.ctl') }
      let(:src_config)  { {:file => 'data/multiple_delimited_*.txt', :parser => :csv} }

      it "should find 6 rows in total" do
        rows.should have(6).items
      end
    end

    # @todo: Not the most useful test?  Oh well?
    context "When using an absolute path" do
      let(:ctl_file)    { fixture_path('delimited_absolute.ctl') }
      let(:src_config)  { {:file => fixture_path('data/delimited.txt'), :parser => :csv} }

      before(:each) { definition << :sex }

      it 'should (again) find 3 rows in the delimited file' do
        rows.should have(3).items
      end
    end

    context "When using a file source with an xml parser" do
      let(:ctl_file)  { fixture_path('xml.ctl') }
      let(:sources)   { control.sources }
      let(:rows)      { sources.map(&:to_a).tap(&:flatten!) }

      it "should find 3 rows" do
        rows.should have(3).items
      end

      it "should only contain file sources" do
        sources.each { |source| source.should be_an_instance_of ETL::Control::FileSource }
      end
    end
  end # When using a single file source

  context "When using multiple file sources" do
    context "multiple_source_delimited.ctl" do
      let(:ctl_file){ fixture_path('multiple_source_delimited.ctl') }
      let(:sources) { control.sources }
      let(:rows)    { sources.map(&:to_a).tap(&:flatten!) }

      it "should contain two sources" do
        control.should have(2).sources
      end

      it "should only contain file sources" do
        sources.each { |source| source.should be_an_instance_of ETL::Control::FileSource }
      end

      it "should find 12 rows in total" do
        rows.should have(12).items
      end
    end
  end # When using multiple file sources
end


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<link rel="stylesheet" type="text/css" href="style/style.css">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Code - Strona poświęcona kodowaniu</title>

				codePal

Strona Główna

O nas

Serwis

Produkt

Kontakt

Witamy

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
		Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua

Nagłówek Kolumny

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Galeria

Kontakt

		<form class="contact-form">
			<input type="text" name="name" placeholder="Imię i Nazwisko:" id="name">

			<input type="text" name="email" placeholder="Email:" id="email">

			<textarea name="message" id="message" placeholder="Wiadomość:"></textarea>

			<button type="submit" class="button button-color" id="submit">Wyślij</button>

		</form>


text:
//-----------------------------------------------------------------------
// <copyright file="EntityExtensions.cs" company="Rare Crowds Inc">
// Copyright 2012-2013 Rare Crowds, Inc.
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using DataAccessLayer;
using Diagnostics;
using EntityUtilities;

namespace AppNexusUtilities
{
    ///
    /// Extensions for getting/setting AppNexus specific properties from Entities
    ///
    public static class EntityExtensions
    {
        /// Sets the AppNexus member ID of a CompanyEntity
        /// <param name="this">The company</param>
        /// <param name="memberId">AppNexus member ID</param>
        [SuppressMessage("Microsoft.Design", "CA1011", Justification = "Only valid for CompanyEntity")]
        public static void SetAppNexusMemberId(this CompanyEntity @this, int memberId)
        {
            @this.SetPropertyValueByName(AppNexusEntityProperties.MemberId, (double)memberId);
        }

        /// Gets the AppNexus member ID of a CompanyEntity
        /// <param name="this">The company</param>
        /// <returns>AppNexus member ID if set; Otherwise, null.</returns>
        [SuppressMessage("Microsoft.Design", "CA1011", Justification = "Only valid for CompanyEntity")]
        public static int? GetAppNexusMemberId(this CompanyEntity @this)
        {
            return @this.TryGetNumericPropertyValue(AppNexusEntityProperties.MemberId);
        }

        /// Sets the AppNexus advertiser ID of a CompanyEntity
        /// <param name="this">The company</param>
        /// <param name="advertiserId">AppNexus advertiser ID</param>
        [SuppressMessage("Microsoft.Design", "CA1011", Justification = "Only valid for CompanyEntity")]
        public static void SetAppNexusAdvertiserId(this CompanyEntity @this, int advertiserId)
        {
            @this.SetPropertyValueByName(AppNexusEntityProperties.AdvertiserId, (double)advertiserId);
        }

        /// Gets the AppNexus advertiser ID of a CompanyEntity
        /// <param name="this">The company</param>
        /// <returns>AppNexus advertiser ID if set; Otherwise, null.</returns>
        [SuppressMessage("Microsoft.Design", "CA1011", Justification = "Only valid for CompanyEntity")]
        public static int? GetAppNexusAdvertiserId(this CompanyEntity @this)
        {
            return @this.TryGetNumericPropertyValue(AppNexusEntityProperties.AdvertiserId);
        }

        /// Sets the AppNexus line item ID of a CampaignEntity
        /// <param name="this">The campaign</param>
        /// <param name="lineItemId">AppNexus line item ID</param>
        [SuppressMessage("Microsoft.Design", "CA1011", Justification = "Only valid for CampaignEntity")]
        public static void SetAppNexusLineItemId(this CampaignEntity @this, int lineItemId)
        {
            @this.SetPropertyValueByName(AppNexusEntityProperties.LineItemId, (double)lineItemId);
        }

        /// Sets the AppNexus creative id
        /// <param name="this">The creative</param>
        /// <param name="creativeId">The creative id</param>
        [SuppressMessage("Microsoft.Design", "CA1011", Justification = "Only valid for CreativeEntity")]
        public static void SetAppNexusCreativeId(this CreativeEntity @this, int creativeId)
        {
            @this.SetPropertyValueByName(AppNexusEntityProperties.CreativeId, (double)creativeId);
        }

        /// Sets the AppNexus creative id
        /// <param name="this">The creative</param>
        /// <returns>The creative id</returns>
        [SuppressMessage("Microsoft.Design", "CA1011", Justification = "Only valid for CreativeEntity")]
        public static int? GetAppNexusCreativeId(this CreativeEntity @this)
        {
            return @this.TryGetNumericPropertyValue(AppNexusEntityProperties.CreativeId);
        }

        /// Gets the AppNexus line item ID of a CampaignEntity
        /// <param name="this">The campaign</param>
        /// <returns>AppNexus line item ID if set; Otherwise, null.</returns>
        [SuppressMessage("Microsoft.Design", "CA1011", Justification = "Only valid for CampaignEntity")]
        public static int? GetAppNexusLineItemId(this CampaignEntity @this)
        {
            return @this.TryGetNumericPropertyValue(AppNexusEntityProperties.LineItemId);
        }

        /// Sets the AppNexus audit status for a creative
        /// <param name="this">The creative</param>
        /// <param name="auditStatus">The audit status</param>
        [SuppressMessage("Microsoft.Design", "CA1011", Justification = "Only valid for CreativeEntity")]
        public static void SetAppNexusAuditStatus(this CreativeEntity @this, string auditStatus)
        {
            @this.SetPropertyValueByName(AppNexusEntityProperties.CreativeAuditStatus, auditStatus);
        }

        /// Gets the AppNexus audit status for a creative
        /// <param name="this">The creative</param>
        /// <returns>The audit status</returns>
        [SuppressMessage("Microsoft.Design", "CA1011", Justification = "Only valid for CreativeEntity")]
        public static string GetAppNexusAuditStatus(this CreativeEntity @this)
        {
            var value = @this.TryGetPropertyValueByName(AppNexusEntityProperties.CreativeAuditStatus);
            return value != null ? (string)value : null;
        }

        /// Sets the AppNexus include domains list for an entity (company or campaign)
        /// <param name="this">The entity</param>
        /// <param name="includeDomainList">The include domains list</param>
        [SuppressMessage("Microsoft.Design", "CA1011", Justification = "Only valid for IEntity")]
        public static void SetAppNexusIncludeDomainList(this IEntity @this, string[] includeDomainList)
        {
            @this.SetPropertyValueByName(AppNexusEntityProperties.IncludeDomainList, string.Join("\n", includeDomainList));
        }

        /// Gets the AppNexus include domains list for an entity (company or campaign)
        /// <param name="this">The entity</param>
        /// <returns>The include domains list</returns>
        [SuppressMessage("Microsoft.Design", "CA1011", Justification = "Only valid for IEntity")]
        public static string[] GetAppNexusIncludeDomainList(this IEntity @this)
        {
            var value = @this.TryGetPropertyValueByName(AppNexusEntityProperties.IncludeDomainList);
            return value != null ?
                ((string)value)
                    .Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(s => s.Trim())
                    .Where(s => !string.IsNullOrWhiteSpace(s))
                    .ToArray() :
                null;
        }

        /// Sets the AppNexus include domains list for an entity (company or campaign)
        /// <param name="this">The campaign</param>
        /// <param name="includeDomainListId">The include domains list</param>
        [SuppressMessage("Microsoft.Design", "CA1011", Justification = "Only valid for CampaignEntity")]
        public static void SetAppNexusIncludeDomainListId(this CampaignEntity @this, int includeDomainListId)
        {
            @this.SetPropertyValueByName(AppNexusEntityProperties.IncludeDomainListId, (double)includeDomainListId);
        }

        /// Gets the AppNexus include domains list for an entity (company or campaign)
        /// <param name="this">The campaign</param>
        /// <returns>The include domains list</returns>
        [SuppressMessage("Microsoft.Design", "CA1011", Justification = "Only valid for CampaignEntity")]
        public static int? GetAppNexusIncludeDomainListId(this CampaignEntity @this)
        {
            return @this.TryGetNumericPropertyValue(AppNexusEntityProperties.IncludeDomainListId);
        }
    }
}


text:
package com.intellij.psi.impl.source.xml.stub;

import com.intellij.psi.stubs.StubElement;
import com.intellij.psi.xml.XmlTag;

public interface XmlTagStub<T extends XmlTag> extends StubElement<T> {
}


text:
@class CKDispatcherProperty;
@interface NSObject (CKDispatcher)
@property(nonatomic, strong) CKDispatcherProperty *ck_property;
@end


text:
/*Libraries*/
var util = require('util');
var jwt  = require('jsonwebtoken');
var randomstring = require('randomstring');
var bodyParser = require('body-parser');
var passport = require('passport');
var Auth0Strategy = require('passport-auth0');
var urllib = require('urllib');

/*config*/
var config = require('../config.js');
var configMail = require('../configMail.js');

/*models*/
var Uzanto = require('../models/uzanto');
var UzantoAuxAsocio = require('../models/uzantoAuxAsocio');
var Grupo = require('../models/grupo');
var Aneco = require('../models/aneco');

/*modules*/
var query = require('../modules/query');
var hash = require('../modules/hash');
var mail = require('../modules/mail');
var file = require('../modules/file');
var utilAPI = require('../modules/utilAPI');
var auth = require('../modules/auth');

var sendToken = function(id, res){
  utilAPI.cxuMembro(id).then(function(sucess){
    if(sucess) {
      permeso = ['uzanto', 'membro'];
    } else {
      permeso = ['uzanto'];
    }
    var uzanto = {
      id: id,
      permesoj: permeso,
    };
    var token = jwt.sign(uzanto, config.sekretoJWT, {expiresIn: "30d"});
    res.status(200).send({token: token, uzanto: uzanto});
  });
}

var proviMalnovaRetejo = function(uzantnomo, pasvorto, cres) {
  var options = {
     "method":"POST",
     "data": {"salvt": uzantnomo, "pvorto": pasvorto,
              "submetu": "KLAKU+POR+ENIRI"},
      "jar": true
  };
  try {
    urllib.request('https://reto.uea.org/index.php?a=persone', options,
      function (err, data, res) {
        if(res.headers && res.headers['set-cookie']){
          var options2 = {
                          "method": "GET",
                          "headers":{"Cookie": res.headers['set-cookie'][0].split(';')[0]}
                        };
          urllib.request('https://reto.uea.org/index.php?a=persone', options2, function (err, data, res) {
            if(data) {
              var data = data.toString();
              var indexOf = data.indexOf('UEA-kodo');
              if(indexOf > -1) {
                ueakodo = data.substring(indexOf + 20, indexOf + 26).replace("-", "");
                UzantoAuxAsocio.find('ueakodo', ueakodo).then(function(response){
                  if(response.length == 1) {
                    var id = response[0].id;
                    var p1 = UzantoAuxAsocio.update(id, 'uzantnomo', uzantnomo);
                    var pasvortajDatumoj = hash.sha512(pasvorto, null);
                    var p2 = UzantoAuxAsocio.update(id, 'pasvortoSalt', pasvortajDatumoj.salt);
                    var p3 = UzantoAuxAsocio.update(id, 'pasvortoHash', pasvortajDatumoj.hash);
                    Promise.all([p1, p2, p3]).then(function(values) {
                      sendToken(id, res);
                    });
                  } else {
                    cres.status(401).send({message: 'Viaj datumoj ne estas en nia nova sistemo, \
                                                    kontaktu sekretario@co.uea.org\
                                                    kaj transdonu vian UEA-kodon'});
                  }
                });
            } else {
              cres.status(401).send({message: 'La uzantnomo aŭ pasvorto ne estas ĝusta'});
            }
          } else {
            cres.status(401).send({message: 'La uzantnomo aŭ pasvorto ne estas ĝusta'});
          }
       });
       } else {
          cres.status(401).send({message: 'Okazis eraro je via peto! Provu denove pli malfrue.'});
       }
  });
  } catch(error) {
    cres.status(401).send({message: 'Okazis eraro je via peto! Provu denove pli malfrue.'});
  }
}

/*
  POST - /uzantoj/ensaluti
*/
var _ensaluti = function(req, res) {
  UzantoAuxAsocio.find('uzantnomo', req.body.uzantnomo).then(
    function(sucess) {
      if (sucess.length == 0) {
        if (req.body.uzantnomo.indexOf('@') > -1) {
          Uzanto.find('retposxto', req.body.uzantnomo).then(function(sucess){
            if(sucess.length == 1) {
              UzantoAuxAsocio.find('id', sucess[0].id).then(function(sucess){
                if (!hash.valigiPasvorto(sucess[0].pasvortoSalt, req.body.pasvorto,
                                          sucess[0].pasvortoHash)) {
                  res.status(401).send({message: 'Malĝusta pasvorto'});
                }
                sendToken(sucess[0].id, res);
              });
            } else if(sucess.length == 0){
              res.status(401).send({message: 'Tiu retadreso apartenas al neniu en nia datumbazo. \
                                              Provu ensaluti per uzantnomo'});
            } else {
              res.status(401).send({message: 'Tiu retadreso apartenas al\
                                              pli ol unu persono en nia datumbazo. \
                                              Provu ensaluti per uzantnomo'});
            }
          });
        } else {
         proviMalnovaRetejo(req.body.uzantnomo, req.body.pasvorto, res);
        }
      } else {
        if (!hash.valigiPasvorto(sucess[0].pasvortoSalt, req.body.pasvorto,
                                  sucess[0].pasvortoHash)) {
          res.status(401).send({message: 'Malĝusta pasvorto'});
        }
        sendToken(sucess[0].id, res);
    }
  });
}

/*
  GET /uzantoj/:id
*/
var _getUzanto = function(req, res){
  Uzanto.find('id', req.params.id).then(function(sucess){
      var uzanto = sucess;
      res.status(200).send(uzanto);
  });
}

var _getUzantoj = function(req, res){
  Uzanto.find().then(function(sucess){
      var uzanto = sucess.filter(query.search(req.query));
      res.status(200).send(uzanto);
  });
}

function makeUEAkodo() {
  var text = "";
  var possible = "abcdefghijklmnopqrstuvwxyz";

  for (var i = 0; i < 4; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));

  number = (text.substring(0, 1).charCodeAt(0) - 96) * 2;
  number += (text.substring(1, 2).charCodeAt(0) - 96) * 3;
  number += (text.substring(2, 3).charCodeAt(0) - 96) * 4;
  number += (text.substring(3, 4).charCodeAt(0) - 96) * 5;
  number = 26 - (number % 26);

  text += String.fromCharCode(number + 96);

  return text;
}

var _postUzanto = function(req, res){
  Uzanto.find('retposxto', req.body.uzantnomo).then(function(result) {
    if(result[0]) {
      res.status(200).send({id: result[0].id});
    } else{
      UzantoAuxAsocio.find().then(function(result){
        var ueakodoj = [];
        result.map(function(item){ueakodoj.push(item.ueakodo)});
        if(req.body.ueakodo) {
          ueakodo = req.body.ueakodo;
        } else {
          var ueakodo = "";
          while(true) {
            ueakodo = makeUEAkodo();
            if(ueakodoj.indexOf(ueakodo) < 0) {
              break;
            }
          }
        }
        UzantoAuxAsocio.insert(req.body.uzantnomo, req.body.pasvorto, ueakodo).then(function (result){
           if (result) {
             Uzanto.insert(result.insertId, req.body.personanomo, req.body.familianomo, req.body.titolo,
                           req.body.bildo, req.body.adreso, req.body.posxtkodo, req.body.idLando,
                           req.body.naskigxtago, req.body.notoj, req.body.retposxto, req.body.telhejmo,
                           req.body.teloficejo, req.body.telportebla, req.body.tttpagxo, req.body.urbo).then(
                function(success) {
                     var html = util.format(configMail.registriUzanton, req.body.personanomo);
                     var to = util.format('{"%s" : "%s"}', req.body.retposxto, req.body.personanomo);
                     var mailOptions = {
                         to: JSON.parse(to),
                         subject: 'Nova aliĝo',
                         html: html
                       };
                     mail.sendiRetmesagxo(mailOptions);
                     res.status(201).send({id: result.insertId});
                   },
                   function (fail) {
                     res.status(500).send({message: 'Internal Error'});
                   });
              }
         });
      });
    }
  });
}

var _forgesisPasvorton = function(req, res) {
    Uzanto.findForgesis(req.body.retposxto, req.body.naskigxtago).then(
      function(sucess) {
        if (sucess.length > 0) {
          var novaPasvorto = randomstring.generate(10);
          var pasvortajDatumoj = hash.sha512(novaPasvorto, null);
          UzantoAuxAsocio.update(sucess[0].id, 'pasvortoSalt', pasvortajDatumoj.salt);
          UzantoAuxAsocio.update(sucess[0].id, 'pasvortoHash', pasvortajDatumoj.hash);
          UzantoAuxAsocio.find('id', sucess[0].id).then(
          function (sucess) {
            if(req.body.retposxto) {
                var html = util.format(configMail.novaPasvorto, novaPasvorto);
                var to = util.format('{"%s" : "UEA-membro"}', req.body.retposxto);
                var mailOptions = {
                    to: JSON.parse(to),
                    subject: 'Restarigo de la forgesita pasvorto por UEA',
                    html: html
                  }
                mail.sendiRetmesagxo(mailOptions);
              }
            res.status(200).send({message: 'Nova pasvorto estis sendita al via retpoŝto'});
        });
      }
      else {
          res.status(400).send({message: "Ne ekzistas uzantoj kun la indikitaj datumoj je la sistemo"});
      }
  });
}

var _updateUzanto = function(req, res){
  var sciigi = new Promise(
    function(resolve, reject) {
      Uzanto.find('id', req.params.id).then(function(sucess){
        if(sucess[0].retposxto) {
          var uzanto = sucess[0];
          if(req.body.kampo == "pasvorto") {
            var valoro = "kaŝita pasvorto"
          } else {
            var valoro = req.body.valoro;
          }
          var html = util.format(configMail.updateUzanto, uzanto.personanomo, req.body.kampo, valoro);
          var to = util.format('{"%s" : "%s"}', uzanto.retposxto, uzanto.personanomo);
          var mailOptions = {
              to: JSON.parse(to),
              subject: 'Ĝisdatigo de datumoj en via profilo ĉe UEA',
              html: html
            }
          mail.sendiRetmesagxo(mailOptions);
          resolve();
        } else {
          resolve();
        }
      });
    });

  sciigi.then(function() {
      if (req.body.kampo == 'id') {
        res.status(403).send({message: "vi ne povas ŝanĝi vian ID"});
        return;
      }

      if (req.body.kampo == 'pasvorto') {
        var novaPasvorto = req.body.valoro;
        var pasvortajDatumoj = hash.sha512(novaPasvorto, null);
        UzantoAuxAsocio.update(req.params.id, 'pasvortoSalt', pasvortajDatumoj.salt);
        UzantoAuxAsocio.update(req.params.id, 'pasvortoHash', pasvortajDatumoj.hash);
        res.status(200).send({message: "Ĝisdatigo sukcese farita"});
        return;
      }

      if((req.body.kampo == 'ueakodo') || (req.body.kampo == 'uzantnomo')) {
        UzantoAuxAsocio.update(req.params.id, req.body.kampo, req.body.valoro).then(
          function(sucess){
            if(sucess) {
              res.status(200).send({message: "Ĝisdatigo sukcese farita"});
            } else {
              res.status(500).send({message: "Eraro en la servilo"});
            }
          });
          return;
      }

      Uzanto.update(req.params.id, req.body.kampo, req.body.valoro).then(
        function(sucess) {
          if (sucess) {
            res.status(200).send({message: "Ĝisdatigo sukcese farita"});
          } else {
            res.status(500).send({message: "Eraro en la servilo"});
          }
      });
    });
}

var _cxuMembro = function(req, res) {
  if(!req.params.retposxto) {
    res.status(200).send({membroID: false});
  }

  Uzanto.find('retposxto', req.params.retposxto).then(function(sucess){
      if(sucess && sucess.length == 1) {
        utilAPI.cxuMembro(sucess[0].id).then(function(sucess){
          res.status(200).send({membro: sucess});
        });
      } else {
        UzantoAuxAsocio.find('ueakodo', req.params.retposxto).then(function(sucess){
          if(sucess && sucess.length == 1){
            utilAPI.cxuMembro(sucess[0].id).then(function(sucess){
              res.status(200).send({membro: sucess});
            });
          } else {
            res.status(200).send({membro: false});
          }
        });
      }
  });
}

var _postBildo = function(req, res) {
  file.writeFile('/sistemo', 'uzantbildo' + req.params.id, 'file', req, res);
}

var _getBildo = function(req, res) {
  file.readFile('uzantbildo' + req.params.id, 'image/png', res);
}

var _getGrupoj = function(req,res) {
  Uzanto.findGrupoj(req.params.id).then(function(sucess){
    res.status(200).send(sucess);
  });
}

var _delete = function(req, res) {
  UzantoAuxAsocio.delete(req.params.id).then(function(sucess){
    UzantoAuxAsocio.find('id', req.params.id).then(function(sucess){
      if(sucess.length <= 0){
        Uzanto.delete(req.params.id).then(function(sucess){
          Uzanto.find('id', req.params.id).then(function(sucess){
            if(sucess.length <= 0)
              res.status(204).send({message: 'Ok'});
            else
              res.status(500).send({message: 'Internal Error'});
          });
        });
      } else {
        res.status(500).send({message: 'Internal Error'});
      }
    });
  });
}

var _adapti = function(req, res) {
  UzantoAuxAsocio.insert(null, null, req.body.ueakodo).then(
    function(result){
      if (result) {
        var id = result.insertId;
        Uzanto.insert(result.insertId, req.body.personanomo,
                      req.body.familianomo, req.body.titolo,
                      req.body.bildo, req.body.adreso,
                      req.body.posxtkodo, req.body.idLando,
                      req.body.naskigxtago, req.body.notoj,
                      req.body.retposxto, req.body.telhejmo,
                      req.body.teloficejo, req.body.telportebla,
                      req.body.tttpagxo, req.body.urbo).then(
                        function(result){
                          if(result) {
                            res.status(201).send({message: 'Ok', id: id});
                          } else {
                            res.status(500).send({message: 'Internal error'});
                          }
                        });
      } else {
        UzantoAuxAsocio.find('ueakodo', req.body.ueakodo).then(function(sucess){
            res.status(200).send(sucess);
        });
      }
  });
}

var _ensalutiSenPasvorto = function(req, res){
    Uzanto.find('retposxto', req.user.displayName).then(function(sucess){
      var params = '';
        if (sucess.length < 1) {
          params = "?message=Ne estas membroj kun tiu retpoŝtadreso en nia sistemo";
        } else if(sucess.length > 1) {
         params = "?message=Estas pli ol 1 uzanto kies tiu retpoŝtadreso estis indikita. Provu\
                   ensaluti pere de uzantnomo kaj pasvorto aŭ skribu al sekretario@co.uea.org\
                   por informi al kiu tiu retpoŝtadreso vere apartenas";
        } else {
          var uzanto = {
            id: sucess[0].id,
            uzantnomo: sucess[0].uzantnomo,
            permeso: 'uzanto'
          };
          var token = jwt.sign(uzanto, config.sekretoJWT, {expiresIn: 18000});
          params = '?token=' + token +'&id=' + sucess[0].id
        }
        res.redirect(req.session.returnTo || config.loginURL + params)
    });
}

module.exports = {
  forgesisPasvorton:_forgesisPasvorton,
  getGrupoj:_getGrupoj,
  postBildo: _postBildo,
  getBildo: _getBildo,
  getUzanto: _getUzanto,
  postUzanto: _postUzanto,
  updateUzanto: _updateUzanto,
  ensaluti: _ensaluti,
  cxuMembro: _cxuMembro,
  adapti: _adapti,
  ensalutiSenPasvorto: _ensalutiSenPasvorto,
  getUzantoj: _getUzantoj,
  delete: _delete
}


text:
require("alias");

module.exports = "index.js";


text:
package kafka.consumer

import org.easymock.EasyMock
import org.I0Itec.zkclient.ZkClient
import org.apache.zookeeper.data.Stat
import kafka.utils.{TestUtils, Logging, ZkUtils, Json}
import org.junit.Assert._
import kafka.common.TopicAndPartition
import kafka.consumer.PartitionAssignorTest.StaticSubscriptionInfo
import kafka.consumer.PartitionAssignorTest.Scenario
import kafka.consumer.PartitionAssignorTest.WildcardSubscriptionInfo
import org.junit.Test

class PartitionAssignorTest extends Logging {

  @Test
  def testRoundRobinPartitionAssignor() {
    val assignor = new RoundRobinAssignor

    /** various scenarios with only wildcard consumers */
    (1 to PartitionAssignorTest.TestCaseCount).foreach { _ =>
      val consumerCount = 1.max(TestUtils.random.nextInt(PartitionAssignorTest.MaxConsumerCount + 1))
      val topicCount = PartitionAssignorTest.MinTopicCount.max(TestUtils.random.nextInt(PartitionAssignorTest.MaxTopicCount + 1))

      val topicPartitionCounts = Map((1 to topicCount).map(topic => {
        ("topic-" + topic, PartitionAssignorTest.MinPartitionCount.max(TestUtils.random.nextInt(PartitionAssignorTest.MaxPartitionCount)))
      }):_*)

      val subscriptions = Map((1 to consumerCount).map { consumer =>
        val streamCount = 1.max(TestUtils.random.nextInt(PartitionAssignorTest.MaxStreamCount + 1))
        ("g1c" + consumer, WildcardSubscriptionInfo(streamCount, ".*", isWhitelist = true))
      }:_*)
      val scenario = Scenario("g1", topicPartitionCounts, subscriptions)
      val zkUtils = PartitionAssignorTest.setupZkClientMock(scenario)
      EasyMock.replay(zkUtils.zkClient)
      PartitionAssignorTest.assignAndVerify(scenario, assignor, zkUtils, verifyAssignmentIsUniform = true)
    }
  }

  @Test
  def testRangePartitionAssignor() {
    val assignor = new RangeAssignor
    (1 to PartitionAssignorTest.TestCaseCount).foreach { _ =>
      val consumerCount = 1.max(TestUtils.random.nextInt(PartitionAssignorTest.MaxConsumerCount + 1))
      val topicCount = PartitionAssignorTest.MinTopicCount.max(TestUtils.random.nextInt(PartitionAssignorTest.MaxTopicCount + 1))

      val topicPartitionCounts = Map((1 to topicCount).map(topic => {
        ("topic-" + topic, PartitionAssignorTest.MinPartitionCount.max(TestUtils.random.nextInt(PartitionAssignorTest.MaxPartitionCount)))
      }):_*)

      val subscriptions = Map((1 to consumerCount).map { consumer =>
        val streamCounts = Map((1 to topicCount).map(topic => {
            val streamCount = 1.max(TestUtils.random.nextInt(PartitionAssignorTest.MaxStreamCount + 1))
            ("topic-" + topic, streamCount)
          }):_*)
        ("g1c" + consumer, StaticSubscriptionInfo(streamCounts))
      }:_*)
      val scenario = Scenario("g1", topicPartitionCounts, subscriptions)
      val zkUtils = PartitionAssignorTest.setupZkClientMock(scenario)
      EasyMock.replay(zkUtils.zkClient)

      PartitionAssignorTest.assignAndVerify(scenario, assignor, zkUtils)
    }
  }
}

private object PartitionAssignorTest extends Logging {

  private val TestCaseCount = 3
  private val MaxConsumerCount = 10
  private val MaxStreamCount = 8
  private val MaxTopicCount = 100
  private val MinTopicCount = 0
  private val MaxPartitionCount = 120
  private val MinPartitionCount = 8

  private trait SubscriptionInfo {
    def registrationString: String
  }

  private case class StaticSubscriptionInfo(streamCounts: Map[String, Int]) extends SubscriptionInfo {
    def registrationString =
      Json.encode(Map("version" -> 1,
                      "subscription" -> streamCounts,
                      "pattern" -> "static",
                      "timestamp" -> 1234.toString))

    override def toString = {
      "Stream counts: " + streamCounts
    }
  }

  private case class WildcardSubscriptionInfo(streamCount: Int, regex: String, isWhitelist: Boolean)
          extends SubscriptionInfo {
    def registrationString =
      Json.encode(Map("version" -> 1,
                      "subscription" -> Map(regex -> streamCount),
                      "pattern" -> (if (isWhitelist) "white_list" else "black_list")))

    override def toString = {
      "\"%s\":%d (%s)".format(regex, streamCount, if (isWhitelist) "whitelist" else "blacklist")
    }
  }

  private case class Scenario(group: String,
                              topicPartitionCounts: Map[String, Int],
                              /* consumerId -> SubscriptionInfo */
                              subscriptions: Map[String, SubscriptionInfo]) {
    override def toString = {
      "\n" +
      "Group                  : %s\n".format(group) +
      "Topic partition counts : %s\n".format(topicPartitionCounts) +
      "Consumer assignment : %s\n".format(subscriptions)
    }
  }

  private def setupZkClientMock(scenario: Scenario) = {
    val consumers = java.util.Arrays.asList(scenario.subscriptions.keys.toSeq:_*)

    val zkClient = EasyMock.createStrictMock(classOf[ZkClient])
    val zkUtils = ZkUtils(zkClient, false)
    EasyMock.checkOrder(zkClient, false)

    EasyMock.expect(zkClient.getChildren("/consumers/%s/ids".format(scenario.group))).andReturn(consumers)
    EasyMock.expectLastCall().anyTimes()

    scenario.subscriptions.foreach { case(consumerId, subscriptionInfo) =>
      EasyMock.expect(zkClient.readData("/consumers/%s/ids/%s".format(scenario.group, consumerId), new Stat()))
              .andReturn(subscriptionInfo.registrationString)
      EasyMock.expectLastCall().anyTimes()
    }

    scenario.topicPartitionCounts.foreach { case(topic, partitionCount) =>
      val replicaAssignment = Map((0 until partitionCount).map(partition => (partition.toString, Seq(0))):_*)
      EasyMock.expect(zkClient.readData("/brokers/topics/%s".format(topic), new Stat()))
              .andReturn(zkUtils.replicaAssignmentZkData(replicaAssignment))
      EasyMock.expectLastCall().anyTimes()
    }

    EasyMock.expect(zkUtils.zkClient.getChildren("/brokers/topics")).andReturn(
      java.util.Arrays.asList(scenario.topicPartitionCounts.keys.toSeq:_*))
    EasyMock.expectLastCall().anyTimes()

    zkUtils
  }

  private def assignAndVerify(scenario: Scenario, assignor: PartitionAssignor, zkUtils: ZkUtils,
                              verifyAssignmentIsUniform: Boolean = false) {
    val assignments = scenario.subscriptions.map { case (consumer, _)  =>
      val ctx = new AssignmentContext("g1", consumer, excludeInternalTopics = true, zkUtils)
      assignor.assign(ctx).get(consumer)
    }

    // check for uniqueness (i.e., any partition should be assigned to exactly one consumer stream)
    val globalAssignment = collection.mutable.Map[TopicAndPartition, ConsumerThreadId]()
    assignments.foreach(assignment => {
      assignment.foreach { case(topicPartition, owner) =>
        val previousOwnerOpt = globalAssignment.put(topicPartition, owner)
        assertTrue("Scenario %s: %s is assigned to two owners.".format(scenario, topicPartition), previousOwnerOpt.isEmpty)
      }
    })

    // check for coverage (i.e., all given partitions are owned)
    val assignedPartitions = globalAssignment.keySet
    val givenPartitions = scenario.topicPartitionCounts.flatMap{ case (topic, partitionCount) =>
      (0 until partitionCount).map(partition => TopicAndPartition(topic, partition))
    }.toSet
    assertTrue("Scenario %s: the list of given partitions and assigned partitions are different.".format(scenario),
      givenPartitions == assignedPartitions)

    // check for uniform assignment
    if (verifyAssignmentIsUniform) {
      val partitionCountForStream = partitionCountPerStream(globalAssignment)
      if (partitionCountForStream.nonEmpty) {
        val maxCount = partitionCountForStream.valuesIterator.max
        val minCount = partitionCountForStream.valuesIterator.min
        assertTrue("Scenario %s: assignment is not uniform (partition counts per stream are in the range [%d, %d])"
          .format(scenario, minCount, maxCount), (maxCount - minCount) <= 1)
      }
    }
  }

  /** For each consumer stream, count the number of partitions that it owns. */
  private def partitionCountPerStream(assignment: collection.Map[TopicAndPartition, ConsumerThreadId]) = {
    val ownedCounts = collection.mutable.Map[ConsumerThreadId, Int]()
    assignment.foreach { case (_, owner) =>
      val updatedCount = ownedCounts.getOrElse(owner, 0) + 1
      ownedCounts.put(owner, updatedCount)
    }
    ownedCounts
  }
}


text:
import { testAlert } from '../test.utils';
import { newE2EPage } from '@stencil/core/testing';

const DIRECTORY = 'basic';
const getActiveElementText = async (page) => {
  const activeElement = await page.evaluateHandle(() => document.activeElement);
  return await page.evaluate(el => el && el.textContent, activeElement);
}

test('alert: focus trap', async () => {
  const page = await newE2EPage({ url: '/src/components/alert/test/basic?ionic:_testing=true' });

  await page.click('#multipleButtons');
  await page.waitForSelector('#multipleButtons');

  let alert = await page.find('ion-alert');

  expect(alert).not.toBe(null);
  await alert.waitForVisible();

  await page.keyboard.press('Tab');

  const activeElementText = await getActiveElementText(page);
  expect(activeElementText).toEqual('Open Modal');

  await page.keyboard.down('Shift');
  await page.keyboard.press('Tab');
  await page.keyboard.up('Shift');

  const activeElementTextTwo = await getActiveElementText(page);
  expect(activeElementTextTwo).toEqual('Cancel');

  await page.keyboard.press('Tab');

  const activeElementTextThree = await getActiveElementText(page);
  expect(activeElementTextThree).toEqual('Open Modal');
});

test(`alert: basic`, async () => {
  await testAlert(DIRECTORY, '#basic');
});

test(`alert: basic, long message`, async () => {
  await testAlert(DIRECTORY, '#longMessage');
});

test(`alert: basic, multiple buttons`, async () => {
  await testAlert(DIRECTORY, '#multipleButtons');
});

test(`alert: basic, no message`, async () => {
  await testAlert(DIRECTORY, '#noMessage');
});

test(`alert: basic, confirm`, async () => {
  await testAlert(DIRECTORY, '#confirm');
});

test(`alert: basic, prompt`, async () => {
  await testAlert(DIRECTORY, '#prompt');
});

test(`alert: basic, radio`, async () => {
  await testAlert(DIRECTORY, '#radio');
});

test(`alert: basic, checkbox`, async () => {
  await testAlert(DIRECTORY, '#checkbox');
});

// Right to Left tests
// ------------------------------------------------------

test(`alert:rtl: basic`, async () => {
  await testAlert(DIRECTORY, '#basic', true);
});

test(`alert:rtl: basic, long message`, async () => {
  await testAlert(DIRECTORY, '#longMessage', true);
});

test(`alert:rtl: basic, multiple buttons`, async () => {
  await testAlert(DIRECTORY, '#multipleButtons', true);
});

test(`alert:rtl: basic, no message`, async () => {
  await testAlert(DIRECTORY, '#noMessage', true);
});

test(`alert:rtl: basic, confirm`, async () => {
  await testAlert(DIRECTORY, '#confirm', true);
});

test(`alert:rtl: basic, prompt`, async () => {
  await testAlert(DIRECTORY, '#prompt', true);
});

test(`alert:rtl: basic, radio`, async () => {
  await testAlert(DIRECTORY, '#radio', true);
});

test(`alert:rtl: basic, checkbox`, async () => {
  await testAlert(DIRECTORY, '#checkbox', true);
});


text:
module Regressor
  module Model
    module Validation
      module Length
        def length_validators
          extract_validators(::ActiveModel::Validations::LengthValidator).inject([]) do |result, validator|
            result << generate_length_examples(validator, validator.options[:minimum]-1, validator.options[:minimum]) if validator.options[:minimum]
            result << generate_length_examples(validator, validator.options[:maximum] + 1, validator.options[:maximum]) if validator.options[:maximum]
            result
          end.flatten.compact.uniq.join("\n  ")
        end

        private

        def generate_length_examples(validator, upper_bound, lower_bound)
          validator.attributes.inject([]) do |result, attribute|
            result << "it { is_expected.to allow_value(Faker::Lorem.characters(#{lower_bound})).for :#{attribute} }"
            result << "it { is_expected.not_to allow_value(Faker::Lorem.characters(#{upper_bound})).for :#{attribute} }"
            result
          end
        end

      end
    end
  end
end


text:
from cms.utils.compat.dj import python_2_unicode_compatible
from django.db import models
from django.utils.translation import ugettext_lazy as _
from cms.models import CMSPlugin

@python_2_unicode_compatible
class GoogleMap(CMSPlugin):
    """
    A google maps integration
    """
    title = models.CharField(_("map title"), max_length=100, blank=True,
                             null=True)

    address = models.CharField(_("address"), max_length=150)
    zipcode = models.CharField(_("zip code"), max_length=30)
    city = models.CharField(_("city"), max_length=100)

    content = models.CharField(_("additional content"), max_length=255,
                         blank=True,
                         help_text=_('Displayed under address in the bubble.'))
    ZOOM_LEVELS = map(lambda c: (c, str(c)), range(22))
    zoom = models.PositiveSmallIntegerField(_("zoom level"),
                                            choices=ZOOM_LEVELS, default=13)

    lat = models.DecimalField(_('latitude'), max_digits=10, decimal_places=6,
                              null=True, blank=True,
                              help_text=_('Use latitude & longitude to fine '
                                          'tune the map position.'))
    lng = models.DecimalField(_('longitude'), max_digits=10, decimal_places=6,
                              null=True, blank=True)

    route_planer_title = models.CharField(_("route planer title"),
                               max_length=150, blank=True, null=True,
                               default=_('Calculate your fastest way to here'))
    route_planer = models.BooleanField(_("route planer"), default=False)

    width = models.CharField(_('width'), max_length=6, default='100%',
                           help_text=_('Plugin width (in pixels or percent).'))
    height = models.CharField(_('height'), max_length=6, default='400px',
                              help_text=_('Plugin height (in pixels).'))

    def __str__(self):
        return u"%s (%s, %s %s)" % (self.get_title(), self.address,
                                    self.zipcode, self.city,)

    def get_title(self):
        if self.title is None:
            return _("Map")
        return self.title

    def get_lat_lng(self):
        if self.lat and self.lng:
            return (self.lat, self.lng)


text:
define(
  'components/repos',
  [
    'react',
    'collection/repo/user',
    'collection/repo/starred',
    'model/repo/starred',
    'components/loader'
  ],
  function (React, UserRepoCollection, StarredRepoCollection, StarredRepoModel, ComponentLoader) {
    'use strict';

    var Repo = React.createClass({
      getInitialState: function () {
        return {
          starred: 'set'
        }
      },

      componentDidMount: function () {
        this.setState({
          starred: (!!this.props.starred) ? '[x]' : 'set'
        });
      },

      star: function (repo) {
        event.preventDefault();

        var starredRepoCollection = App.StarredRepos;

        var id = repo.get('id');
        var starred = true;

        if (starredRepoCollection.get(id)) {
          starred = !(!!starredRepoCollection.get(id).get('starred'))
        }

        if (!!starred) {
          var starredRepoModel = new StarredRepoModel(repo.toJSON());
          starredRepoModel.set({starred: starred});
          starredRepoCollection.create(
            starredRepoModel
          );
        } else {
          starredRepoCollection.get(id).destroy();
        }

        Backbone.Events.trigger('repo:starred', starredRepoCollection);

        this.setState({
          starred: (!!starred) ? '[x]' : 'set'
        });
      },

      render: function() {
        var repo = this.props.repo;

        return (
          React.DOM.tr(
            {},
            React.DOM.td(
              {},
              React.DOM.a(
                {
                  href: '#/repos/' + repo.get('owner').login + '/' + repo.get('name')
                },
                repo.get('name')
              )
            ),
            React.DOM.td(
              {},
              repo.get('description')
            ),
            React.DOM.td(
              {},
              (!!repo.get('fork') ? 'Sim' : 'Não')
            ),
            React.DOM.td(
              {},
              React.DOM.a(
                {
                  href: '#',
                  onClick: this.star.bind(this, this.props.repo)
                },
                this.state.starred
              )
            )
          )
        );
      }
    });

    var Repos = React.createClass({
      getInitialState: function() {
        return { repos: this.props.repos };
      },

      componentWillMount: function() {
        Backbone.Events.on('results:loading', _.bind(function () {
          this.setState({
            repos: null
          });
        }, this));

        Backbone.Events.on('results:fetch', _.bind(function () {
          this.setState({
            repos: this.props.repos
          });
        }, this));

        Backbone.Events.on('repo:starred', _.bind(function (starredRepoCollection) {
          this.getStarredRepos();
        }, this));
      },

      componentWillUnmount: function () {
        Backbone.Events.off('results:loading');
        Backbone.Events.off('results:fetch');
        Backbone.Events.off('repo:starred');
      },

      componentDidMount: function() {
        this.getStarredRepos();

        // repos of user
        if (!!this.props.user) {
          var userRepoCollection    = new UserRepoCollection();

          userRepoCollection.fetch();

          userRepoCollection.on('sync', _.bind(function(userRepoCollection , repos) {
            this.setState({
              repos: userRepoCollection
            });
          }, this));
        }
      },

      getStarredRepos: function () {
        var starredRepoCollection = new StarredRepoCollection();

        // get starred repos from local storage
        starredRepoCollection.fetch()
          .done(_.bind(function(){
            App.StarredRepos = starredRepoCollection;

            this.setState({
              starreds: starredRepoCollection
            });
          }, this));
      },

      noResults: function () {
        var feedback = 'Nenhum resultado encontrado.';
        if (!(!!this.state.repos))
          feedback = React.createElement(ComponentLoader);

        return (
          React.DOM.tr(
            {},
            React.DOM.td(
              {
                colSpan: 4,
                style: {
                  textAlign: 'center'
                }
              },
              feedback
            )
          )
        );
      },

      hasStar: function (id) {
        if (this.state.starreds.get(id)) {
          return !!this.state.starreds.get(id).get('starred');
        }
      },

      render: function() {
        var repos = this.noResults();

        if (!!this.state.repos && !!this.state.starreds && this.state.repos.length > 0) {
          var repos = this.state.repos.map(_.bind(function(repo) {
            var starred = this.hasStar(repo.get('id'));
            return React.createElement(
              Repo,
              {
                key: repo.get('id'),
                repo: repo,
                starred: starred
              }
            );
          }, this));
        }

        var title = (!!this.props.title)
                      ? this.props.title
                      : '';

        return (
          React.DOM.div(
            {},
            React.DOM.h1(
              {},
              title
            ),
            React.DOM.table(
              {},
              React.DOM.thead(
                {},
                React.DOM.tr(
                  {},
                  React.DOM.th(
                    {width: 200},
                    'Nome'
                  ),
                  React.DOM.th(
                    {},
                    'Descrição'
                  ),
                  React.DOM.th(
                    {},
                    'Fork?'
                  ),
                  React.DOM.th(
                    {},
                    'Favoritar'
                  )
                )
              ),
              React.DOM.tbody(
                {},
                repos
              )
            )
          )
        );
      }
    });

    return Repos;
  }
);


text:
'use strict';

module.exports = {
  postCSSLoader: require('./postcss-loader'),
};


text:
package com.github.jtendermint.jabci.api;

import com.github.jtendermint.jabci.types.RequestCommit;
import com.github.jtendermint.jabci.types.ResponseCommit;

public interface ICommit {

    /***
     *
Persist the application state.

     *
Return an (optional) Merkle root hash of the application state

     *
ResponseCommit.Data is included as the Header.AppHash in the next block

     *
     *
Returns:

     *

     *
- {@code Data ([]byte)}: The Merkle root hash of the application state
     *

     *
     * @see In Documentation
     */
    ResponseCommit requestCommit(RequestCommit requestCommit);

}


text:
from __future__ import absolute_import
from satispy.io import DimacsCnf
from satispy import Variable
from satispy import Solution

from subprocess import *
import tempfile

import time
import os

class Lingeling(object):
    COMMAND = 'lingeling %s'

    def __init__(self, command=COMMAND):
        self.command = command

    def solve(self, cnf):
        s = Solution()

        # NamedTemporaryFile doesn't work on Windows, see https://stackoverflow.com/questions/15169101/how-to-create-a-temporary-file-that-can-be-read-by-a-subprocess
        infile, infilename = tempfile.mkstemp(suffix="cnf")

        try:
            io = DimacsCnf()
            os.write(infile, io.tostring(cnf))
            os.close(infile)

            try:
                cmd = self.command % (infilename.replace("\\","/"))
                check_output(cmd, stderr=STDOUT, shell=True)
            # Lingeling and most SAT-solvers use a non-zero return code, which in most POSIX command indicates an error.
            # That's why python raises an exception, but here it's expected
            except CalledProcessError as call:
                if call.returncode != 10 and call.returncode != 20:
                    s.error = call.output
                    return s
        finally:
            os.remove(infilename)

        if call.returncode != 10:
            return s

        s.success = True

        for line in call.output.split("\n"):
            # Solution line example: v 1 -2 3 -4 5 6 0
            if len(line) > 0 and line[0] == 'v':
                varz = line.split(" ")[1:-1]
                for v in varz:
                    v = v.strip()
                    value = v[0] != '-'
                    v = v.lstrip('-')
                    vo = io.varobj(v)
                    s.varmap[vo] = value

        return s


text:
package edu.teco.dnd.module.messages.joinStartApp;

import edu.teco.dnd.module.ApplicationID;
import edu.teco.dnd.network.messages.Response;

/**
 * send when a module failed to join an application.
 *
 * @author Marvin Marx
 *
 */

public class JoinApplicationNak extends Response {

	public static final String MESSAGE_TYPE = "join application nak";

	/**
	 * ID of the application that was supposed to be joined.
	 */
	public ApplicationID applicationID;

	/**
	 * human readable name of the application.
	 */
	public String name;

	/**
	 *
	 * @param name
	 *            human readable name of the application.
	 * @param applicationID
	 *            UUID of the application that was supposed to be joined.
	 */
	public JoinApplicationNak(String name, ApplicationID applicationID) {
		this.name = name;
		this.applicationID = applicationID;
	}

	@SuppressWarnings("unused")
	/* for gson */
	private JoinApplicationNak() {
		name = null;
		applicationID = null;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = super.hashCode();
		result = prime * result + ((applicationID == null) ? 0 : applicationID.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (!super.equals(obj)) {
			return false;
		}
		if (getClass() != obj.getClass()) {
			return false;
		}
		JoinApplicationNak other = (JoinApplicationNak) obj;
		if (applicationID == null) {
			if (other.applicationID != null) {
				return false;
			}
		} else if (!applicationID.equals(other.applicationID)) {
			return false;
		}
		if (name == null) {
			if (other.name != null) {
				return false;
			}
		} else if (!name.equals(other.name)) {
			return false;
		}
		return true;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "JoinApplicationNak [name=" + name + ", applicationID=" + applicationID + ", getSourceUUID()="
				+ getSourceUUID() + ", getUUID()=" + getUUID() + "]";
	}

}


text:
<?php

namespace FuelElasticsearch;

class Index
{

	protected $_name;
	protected $_db;
	protected $_connection;
	protected $_params = array();
	protected $_mappings = array();
	protected $_settings = array();

	public function __construct($db, $name)
	{
		$this->_db = $db;
		$this->_connection = $this->_db->get_connection();
		$this->_name = $name;

		$this->_params = array(
		   'index' => $this->_name,
		);
	}

	public function exists()
	{
		return $this->_connection->indices()->exists($this->_params);
	}

	public function create($settings = null, $mappings = null)
	{
		if (!$this->exists())
		{
			$settings and $this->_settings = $settings;
			$mappings and $this->_mappings = $mappings;

			$params = \Arr::merge($this->_params, array(
				'body' => array(
				   'settings' => $this->_settings,
				   'mappings' => $this->_mappings,
				),
			));

			return $this->_connection->indices()->create($params);
		}
		throw new Exception('Index already exists');
	}

	public function delete()
	{
		if ($this->exists())
		{
			$this->_connection->indices()->delete($this->_params);
		}
	}

	public function get_settings()
	{
		if ($this->exists())
		{
			return $this->_connection->indices()->getSettings($this->_params);
		}
	}

	public function get_mapping()
	{
		if ($this->exists())
		{
			return $this->_connection->indices()->getMapping($this->_params);
		}
	}

	public function get_name()
	{
		return $this->_name;
	}

}


text:
<?php

namespace ProcessWire\GraphQL\Test\FieldtypePageId;

use ProcessWire\GraphQL\Utils;
use ProcessWire\GraphQL\Test\GraphQLTestCase;

class PageIdTest extends GraphQLTestCase
{
  const settings = [
    "login" => "admin",
    "legalTemplates" => ["skyscraper"],
    "legalPageFields" => ["id"],
  ];

  public function testValue()
  {
    $skyscraper = Utils::pages()->get("template=skyscraper");
    $query = "{
      skyscraper (s: \"id=$skyscraper->id\") {
        list {
          id
        }
      }
    }";
    $res = self::execute($query);
    self::assertEquals(
      $skyscraper->id,
      $res->data->skyscraper->list[0]->id,
      "Retrieves `id` field of the page."
    );
    self::assertObjectNotHasAttribute("errors", $res, "There are errors.");
  }
}


text:
package com.bootdo.system.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bootdo.system.dao.UserMapper;
import com.bootdo.system.dao.UserRoleMapper;
import com.bootdo.system.domain.SysUserDO;
import com.bootdo.system.domain.UserRoleDO;
import com.bootdo.system.service.UserService;

@Transactional
@Service
public class UserServiceImp implements UserService {
	@Autowired
	UserMapper userMapper;
	@Autowired
	UserRoleMapper userRoleMapper;
	private static final Logger logger = LoggerFactory.getLogger(UserService.class);

	@Override
	public SysUserDO get(Long id) {
		List<Long> roleIds = userRoleMapper.listRoleId(id);
		SysUserDO user = userMapper.get(id);
		user.setroleIds(roleIds);
		return user;
	}

	@Override
	public List<SysUserDO> list(Map<String, Object> map) {
		return userMapper.list(map);
	}

	@Override
	public int count(Map<String, Object> map) {
		return userMapper.count(map);
	}

	@Transactional
	@Override
	public int save(SysUserDO user) {
		int r = 0;
		userMapper.save(user);
		Long userId = user.getUserId();
		List<Long> roles = user.getroleIds();
		userRoleMapper.removeByUserId(userId);
		for (Long roleId : roles) {
			UserRoleDO ur = new UserRoleDO();
			ur.setUserId(userId);
			ur.setRoleId(roleId);
			r = userRoleMapper.save(ur);
		}
		return r;
	}

	@Override
	public int update(SysUserDO user) {
		int r = 0;
		userMapper.update(user);
		Long userId = user.getUserId();
		List<Long> roles = user.getroleIds();
		userRoleMapper.removeByUserId(userId);
		for (Long roleId : roles) {
			UserRoleDO ur = new UserRoleDO();
			ur.setUserId(userId);
			ur.setRoleId(roleId);
			r = userRoleMapper.save(ur);
		}
		return r;
	}

	@Override
	public int remove(Long userId) {
		userRoleMapper.removeByUserId(userId);
		return userMapper.remove(userId);
	}

	@Override
	public boolean exit(Map<String, Object> params) {
		boolean exit;
		exit = userMapper.list(params).size() > 0;
		return exit;
	}

	@Override
	public Set<String> listRoles(Long userId) {
		return null;
	}

	@Override
	public int resetPwd(SysUserDO user) {
		int r = userMapper.update(user);
		return r;
	}

	@Transactional
	@Override
	public int batchremove(List<Long> userIds) {
		int count = userMapper.batchRemove(userIds);
		userRoleMapper.batchRemoveByUserId(userIds);
		return count;
	}

}


text:
#ifndef __STDIO_H
#define __STDIO_H

#include <stdarg.h>

#ifndef NULL
#define NULL 0
#endif

#ifndef __SIZE_T_DEF
#define __SIZE_T_DEF
typedef unsigned size_t;
#endif

#define EOF (-1)

#ifndef SEEK_SET
#define SEEK_SET 0
#endif
#ifndef SEEK_CUR
#define SEEK_CUR 1
#endif
#ifndef SEEK_END
#define SEEK_END 2
#endif

#ifndef __FPOS_T_DEF
#define __FPOS_T_DEF
typedef struct
{
  unsigned short halves[2];
} fpos_t;
#endif

typedef struct __stream FILE;

extern FILE *__stdin, *__stdout, *__stderr;
#define stdin  __stdin
#define stdout __stdout
#define stderr __stderr

#define _IOFBF 01
#define _IONBF 02
#define _IOLBF 04

#define BUFSIZ 1024

#ifdef _DOS
#define FOPEN_MAX 20
#define FILENAME_MAX 80
#define L_tmpnam 80
#define TMP_MAX 10000
#endif

#ifdef _WINDOWS
#define FOPEN_MAX 20
#define FILENAME_MAX 260
#define L_tmpnam 260
#define TMP_MAX 10000
#endif

#ifdef _LINUX
#define FOPEN_MAX 20
#define FILENAME_MAX 4096
#define L_tmpnam 20
#define TMP_MAX 10000
#endif

FILE* fopen(char*, char*);
FILE* freopen(char*, char*, FILE*);
int fflush(FILE*);
int fclose(FILE*);
int remove(char*);
int rename(char*, char*);
size_t fread(void*, size_t, size_t, FILE*);
int fgetc(FILE*);
int getc(FILE*);
int getchar(void);
char* fgets(char*, int, FILE*);
char* gets(char*);
int ungetc(int, FILE*);
size_t fwrite(void*, size_t, size_t, FILE*);
int fputc(int, FILE*);
int putc(int, FILE*);
int putchar(int);
int fputs(char*, FILE*);
int puts(char*);
void perror(char*);
#ifdef __SMALLER_C_32__
long ftell(FILE*);
int fseek(FILE*, long, int);
#endif
int/*0 on success,-1 on failure*/ __ftell(FILE*, fpos_t*/*position out*/);
int __fseek(FILE*, fpos_t*/*position in*/, int/*whence*/);
void rewind(FILE*);
int fgetpos(FILE*, fpos_t*);
int fsetpos(FILE*, fpos_t*);
void clearerr(FILE*);
int ferror(FILE*);
int feof(FILE*);
int setvbuf(FILE*, char*, int, size_t);
void setbuf(FILE*, char*);
int fileno(FILE*);
char* tmpnam(char*);
FILE* tmpfile(void);

int vfprintf(FILE*, char*, va_list);
int fprintf(FILE*, char*, ...);
int vprintf(char*, va_list);
int printf(char*, ...);
int vsprintf(char*, char*, va_list);
int sprintf(char*, char*, ...);
int vsnprintf(char*, size_t, char*, va_list);
int snprintf(char*, size_t, char*, ...);

int vfscanf(FILE*, char*, va_list);
int fscanf(FILE*, char*, ...);
int vscanf(char*, va_list);
int scanf(char*, ...);
int vsscanf(char*, char*, va_list);
int sscanf(char*, char*, ...);

#endif


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Index — Sonata ~ MediaBundle  documentation</title>

  <link href='https://fonts.googleapis.com/css?family=Lato:400,700|Roboto+Slab:400,700|Inconsolata:400,700' rel='stylesheet' type='text/css'>

    <link rel="stylesheet" href="_static/css/theme.css" type="text/css" />

    <link rel="top" title="Sonata ~ MediaBundle  documentation" href="index.html"/>

         Sonata ~ MediaBundle

  <form id ="rtd-search-form" class="wy-form" action="search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

1. Installation

1.1. Base bundles

1.2. Installation

2. Helpers

2.1. PHP Usage

2.2. Twig usage

2.3. Thumbnails for files

3. Creating a Media Provider: A Vimeo Provider

3.1. Media Entity

3.2. Case Study

3.3. Initialize the class

3.4. Register the Class with the Service Container

3.5. View Helper

4. Media Context

4.1. <tt class="docutils literal">AdminBundle</tt> Integration

5. Usages

5.1. Saving a media file

5.2. Retrieving metadata information

6. Form Type

6.1. Media Type

7. Security

7.1. Configuration Example

7.2. Creating your own Security Download Strategy

8. Command Line Tools

8.1. Media commands

9. Advanced Configuration

10. Amazon S3

10.1. Configuration

11. Extra

11.1. Pixlr Integration

12. Sonata Notification Bundle Integration

13. Liip Imagine Bundle Integration

14. CKEditor Integration

14.1. Medias in CKEditor with CoopTilleulsCKEditorSonataMediaBundle

14.2. Medias in CKEditor with SonataFormatterBundle

15. API

15.1. Setup

15.2. Serialization

15.3. Sending a media file

16. Troubleshooting

16.1. Media Formats

        Sonata ~ MediaBundle

Docs »

Index

        © Copyright 2010-2014, Thomas Rabaix.

  Sphinx theme provided by Read the Docs