text:
require 'columnize'
require_relative '../app/complete'

class Trepan
  class Command
    attr_accessor :core, :proc

    unless defined?(MIN_ARGS)
      MIN_ARGS      = 0      # run()'s args array must be at least this many
      MAX_ARGS      = nil    # run()'s args array must be at least this many
      NEED_STACK    = false  # We'll say that commands which need a stack
                             # to run have to declare that and those that
                             # don't don't have to mention it.
    end

    def initialize(proc)
      @name = my_const(:NAME)
      @proc = proc
    end

    def category
      my_const(:CATEGORY)
    end

    # List commands arranged in an aligned columns
    def columnize_commands(commands)
      width = settings[:maxwidth]
      Columnize::columnize(commands, width, ' ' * 4,
                           true, true, ' ' * 2).chomp
    end

    def columnize_numbers(commands)
      width = settings[:maxwidth]
      Columnize::columnize(commands, width, ', ',
                           false, false, ' ' * 2).chomp
    end

    # FIXME: probably there is a way to do the delegation to proc methods
    # without having type it all out.

    def confirm(message, default)
      @proc.confirm(message, default)
    end

    def errmsg(message, opts={})
      @proc.errmsg(message, opts)
    end

    def obj_const(obj, name)
      obj.class.const_get(name)
    end

    # Convenience short-hand for @proc.msg
    def msg(message, opts={})
      @proc.msg(message, opts)
    end

    # Convenience short-hand for @proc.msg_nocr
    def msg_nocr(msg, opts={})
      @proc.msg_nocr(msg, opts)
    end

    def my_const(name)
      # Set class constant SHORT_HELP to be the first line of HELP
      # unless it has been defined in the class already.
      # The below was the simplest way I could find to do this since
      # we are the super class but want to set the subclass's constant.
      # defined? didn't seem to work here.
      c = self.class.constants
      if c.member?(:HELP) and !c.member?(:SHORT_HELP)
        short_help = self.class.const_get(:HELP).split("\n")[0].chomp('.')
        self.class.const_set(:SHORT_HELP, short_help)
      end
      self.class.const_get(name)
    end

    def name
      self.class.const_get(:NAME)
    end

    # The method that implements the debugger command.
    def run(*args)
      raise RuntimeError, 'You need to define this method elsewhere'
    end

    def section(message, opts={})
      @proc.section(message, opts)
    end

    def markdown(message, opts={})
      @proc.markdown(message, opts)
    end

    def settings
      @proc.settings
    end

    def short_help
      help_constant_sym = if self.class.constants.member?(:SHORT_HELP)
                            :SHORT_HELP
                          else :HELP
                          end
      my_const(help_constant_sym)
    end

    # Define a method called 'complete' on the singleton class.
    def self.completion(ary)
      self.send(:define_method,
                :complete,
                Proc.new {|prefix|
                  Trepan::Complete.complete_token(ary, prefix) })
    end
  end
end
if __FILE__ == $0
  class Trepan
    class CmdProcessor
      def initialize(dbgr)
      end
      def confirm(message, default)
        p ['confirm: ', message, default]
      end
      def errmsg(message, opts)
        p ['err:', message, opts]
      end
      def msg(message, opts)
        p [message, opts]
      end
      def msg_nocr(message, opts)
        p ['nocr: ', message, opts]
      end
      def section(message, opts)
        p ['section: ', message, opts]
      end
    end
    class Command::Test < Trepan::Command
      NAME = 'test'
      CATEGORY = 'testcategory'
      completion %w(a aa ab ba aac)
    end
  end
  proc = Trepan::CmdProcessor.new(nil)
  cmd = Trepan::Command::Test.new(proc)
  %w(confirm errmsg msg msg_nocr section).each do |meth|
    cmd.send(meth, 'test', nil)
  end
  p cmd.complete('aa')
end


text:
"""Isomap for manifold learning"""

# Author: Jake Vanderplas  -- <vanderplas@astro.washington.edu>
# License: BSD 3 clause (C) 2011

import numpy as np
from ..base import BaseEstimator, TransformerMixin
from ..neighbors import NearestNeighbors, kneighbors_graph
from ..utils.validation import check_is_fitted
from ..utils.validation import _deprecate_positional_args
from ..utils.graph import graph_shortest_path
from ..decomposition import KernelPCA
from ..preprocessing import KernelCenterer

class Isomap(TransformerMixin, BaseEstimator):
    """Isomap Embedding

    Non-linear dimensionality reduction through Isometric Mapping

    Read more in the :ref:`User Guide <isomap>`.

    Parameters
    ----------
    n_neighbors : int, default=5
        number of neighbors to consider for each point.

    n_components : int, default=2
        number of coordinates for the manifold

    eigen_solver : {'auto', 'arpack', 'dense'}, default='auto'
        'auto' : Attempt to choose the most efficient solver
        for the given problem.

        'arpack' : Use Arnoldi decomposition to find the eigenvalues
        and eigenvectors.

        'dense' : Use a direct solver (i.e. LAPACK)
        for the eigenvalue decomposition.

    tol : float, default=0
        Convergence tolerance passed to arpack or lobpcg.
        not used if eigen_solver == 'dense'.

    max_iter : int, default=None
        Maximum number of iterations for the arpack solver.
        not used if eigen_solver == 'dense'.

    path_method : {'auto', 'FW', 'D'}, default='auto'
        Method to use in finding shortest path.

        'auto' : attempt to choose the best algorithm automatically.

        'FW' : Floyd-Warshall algorithm.

        'D' : Dijkstra's algorithm.

    neighbors_algorithm : {'auto', 'brute', 'kd_tree', 'ball_tree'}, \
                          default='auto'
        Algorithm to use for nearest neighbors search,
        passed to neighbors.NearestNeighbors instance.

    n_jobs : int or None, default=None
        The number of parallel jobs to run.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    metric : string, or callable, default="minkowski"
        The metric to use when calculating distance between instances in a
        feature array. If metric is a string or callable, it must be one of
        the options allowed by :func:`sklearn.metrics.pairwise_distances` for
        its metric parameter.
        If metric is "precomputed", X is assumed to be a distance matrix and
        must be square. X may be a :term:`Glossary <sparse graph>`.

        .. versionadded:: 0.22

    p : int, default=2
        Parameter for the Minkowski metric from
        sklearn.metrics.pairwise.pairwise_distances. When p = 1, this is
        equivalent to using manhattan_distance (l1), and euclidean_distance
        (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.

        .. versionadded:: 0.22

    metric_params : dict, default=None
        Additional keyword arguments for the metric function.

        .. versionadded:: 0.22

    Attributes
    ----------
    embedding_ : array-like, shape (n_samples, n_components)
        Stores the embedding vectors.

    kernel_pca_ : object
        :class:`~sklearn.decomposition.KernelPCA` object used to implement the
        embedding.

    nbrs_ : sklearn.neighbors.NearestNeighbors instance
        Stores nearest neighbors instance, including BallTree or KDtree
        if applicable.

    dist_matrix_ : array-like, shape (n_samples, n_samples)
        Stores the geodesic distance matrix of training data.

    Examples
    --------
    >>> from sklearn.datasets import load_digits
    >>> from sklearn.manifold import Isomap
    >>> X, _ = load_digits(return_X_y=True)
    >>> X.shape
    (1797, 64)
    >>> embedding = Isomap(n_components=2)
    >>> X_transformed = embedding.fit_transform(X[:100])
    >>> X_transformed.shape
    (100, 2)

    References
    ----------

    .. [1] Tenenbaum, J.B.; De Silva, V.; & Langford, J.C. A global geometric
           framework for nonlinear dimensionality reduction. Science 290 (5500)
    """
    @_deprecate_positional_args
    def __init__(self, *, n_neighbors=5, n_components=2, eigen_solver='auto',
                 tol=0, max_iter=None, path_method='auto',
                 neighbors_algorithm='auto', n_jobs=None, metric='minkowski',
                 p=2, metric_params=None):
        self.n_neighbors = n_neighbors
        self.n_components = n_components
        self.eigen_solver = eigen_solver
        self.tol = tol
        self.max_iter = max_iter
        self.path_method = path_method
        self.neighbors_algorithm = neighbors_algorithm
        self.n_jobs = n_jobs
        self.metric = metric
        self.p = p
        self.metric_params = metric_params

    def _fit_transform(self, X):
        self.nbrs_ = NearestNeighbors(n_neighbors=self.n_neighbors,
                                      algorithm=self.neighbors_algorithm,
                                      metric=self.metric, p=self.p,
                                      metric_params=self.metric_params,
                                      n_jobs=self.n_jobs)
        self.nbrs_.fit(X)
        self.n_features_in_ = self.nbrs_.n_features_in_

        self.kernel_pca_ = KernelPCA(n_components=self.n_components,
                                     kernel="precomputed",
                                     eigen_solver=self.eigen_solver,
                                     tol=self.tol, max_iter=self.max_iter,
                                     n_jobs=self.n_jobs)

        kng = kneighbors_graph(self.nbrs_, self.n_neighbors,
                               metric=self.metric, p=self.p,
                               metric_params=self.metric_params,
                               mode='distance', n_jobs=self.n_jobs)

        self.dist_matrix_ = graph_shortest_path(kng,
                                                method=self.path_method,
                                                directed=False)
        G = self.dist_matrix_ ** 2
        G *= -0.5

        self.embedding_ = self.kernel_pca_.fit_transform(G)

    def reconstruction_error(self):
        """Compute the reconstruction error for the embedding.

        Returns
        -------
        reconstruction_error : float

        Notes
        -----
        The cost function of an isomap embedding is

        ``E = frobenius_norm[K(D) - K(D_fit)] / n_samples``

        Where D is the matrix of distances for the input data X,
        D_fit is the matrix of distances for the output embedding X_fit,
        and K is the isomap kernel:

        ``K(D) = -0.5 * (I - 1/n_samples) * D^2 * (I - 1/n_samples)``
        """
        G = -0.5 * self.dist_matrix_ ** 2
        G_center = KernelCenterer().fit_transform(G)
        evals = self.kernel_pca_.lambdas_
        return np.sqrt(np.sum(G_center ** 2) - np.sum(evals ** 2)) / G.shape[0]

    def fit(self, X, y=None):
        """Compute the embedding vectors for data X

        Parameters
        ----------
        X : {array-like, sparse graph, BallTree, KDTree, NearestNeighbors}
            Sample data, shape = (n_samples, n_features), in the form of a
            numpy array, sparse graph, precomputed tree, or NearestNeighbors
            object.

        y : Ignored

        Returns
        -------
        self : returns an instance of self.
        """
        self._fit_transform(X)
        return self

    def fit_transform(self, X, y=None):
        """Fit the model from data in X and transform X.

        Parameters
        ----------
        X : {array-like, sparse graph, BallTree, KDTree}
            Training vector, where n_samples in the number of samples
            and n_features is the number of features.

        y : Ignored

        Returns
        -------
        X_new : array-like, shape (n_samples, n_components)
        """
        self._fit_transform(X)
        return self.embedding_

    def transform(self, X):
        """Transform X.

        This is implemented by linking the points X into the graph of geodesic
        distances of the training data. First the `n_neighbors` nearest
        neighbors of X are found in the training data, and from these the
        shortest geodesic distances from each point in X to each point in
        the training data are computed in order to construct the kernel.
        The embedding of X is the projection of this kernel onto the
        embedding vectors of the training set.

        Parameters
        ----------
        X : array-like, shape (n_queries, n_features)
            If neighbors_algorithm='precomputed', X is assumed to be a
            distance matrix or a sparse graph of shape
            (n_queries, n_samples_fit).

        Returns
        -------
        X_new : array-like, shape (n_queries, n_components)
        """
        check_is_fitted(self)
        distances, indices = self.nbrs_.kneighbors(X, return_distance=True)

        # Create the graph of shortest distances from X to
        # training data via the nearest neighbors of X.
        # This can be done as a single array operation, but it potentially
        # takes a lot of memory.  To avoid that, use a loop:

        n_samples_fit = self.nbrs_.n_samples_fit_
        n_queries = distances.shape[0]
        G_X = np.zeros((n_queries, n_samples_fit))
        for i in range(n_queries):
            G_X[i] = np.min(self.dist_matrix_[indices[i]] +
                            distances[i][:, None], 0)

        G_X **= 2
        G_X *= -0.5

        return self.kernel_pca_.transform(G_X)

redpajama_set_name: RedPajamaGithub


text:
ZZDGMHV1 ;VAINNOV/BNT - Increate Enrollment in MyHealtheVet unit test ; 12/9/03 3:22pm
 ;;5.3;Registration;**903**;Aug 13, 1993;Build 53
 ;
 ; Submitted to OSEHRA 04/02/2015 by HP
 ; All entry points authored by Brian Tomlin 2014-2015
 ;
 ; makes it easy to run tests simply by running this routine and
 ; insures that XTMUNIT will be run only where it is present
 I $T(EN^XTMUNIT)'="" D EN^XTMUNIT("ZZDGMHV1",1)
 Q
 ;
STARTUP ; optional entry point
 ; if present executed before any other entry point any variables
 ; or other work that needs to be done for any or all tests in the
 ; routine.  This is run only once at the beginning.
 Q
 ;
SHUTDOWN ; optional entry point
 ; if present executed after all other processing is complete to remove
 ; any variables, or undo work done in STARTUP.
 Q
 ;
SETUP ; optional entry point
 ; if present it will be executed before each test entry to set up
 ; variables, etc.
 Q
 ;
TEARDOWN ; optional entry point
 ; if present it will be exceuted after each test entry to clean up
 ; variables, etc.
 Q
 ;
CHKTXT; Unit test TXT tag in DGMHV routine to verify that it properly splits the text
 ;
 TSTART
 N TXT,LEN
 S LEN=40
 S TXT="THIS IS A LONG LINE OF TEXT. THIS IS A LONG LINE OF TEXT. THIS IS A LONG LINE OF TEXT. THIS IS A LONG LINE OF TEXT. THIS IS A LONG LINE OF TEXT."
 D TXT^DGMHV(TXT,LEN)
 ; Verify tha the MARX(1) is equal to the the words in the first 40 character limit.
 D CHKEQ^XTMUNIT("THIS IS A LONG LINE OF TEXT. THIS IS A",MARX(1),"Return of text doesn't match")
 TROLLBACK
 Q
 ;
CHKLKUPACT ; Test LKUPACT tag in DGMHVAC routine and verify correct MHV SOCIALIZATION ACTIONS is returned
 ;
 TSTART
 N ACT,ACT0
 S ACT=0 F  S ACT=$O(^DGMHV(390.02,ACT)) Q:'ACT  S ACT0=$G(^DGMHV(390.02,ACT,0)) D
 . D CHKEQ^XTMUNIT(ACT0,$$LKUPACT^DGMHVAC(ACT),"Return of MHV SOCIALIZATION ACTION doesn't match")
 . W !,"Expected:  ",ACT0,!,"Actual:  ",ACT0
 . W !,"----------------------------------------------",!
 TROLLBACK
 Q
 ;
CHKCONSTAT ; Test CONSTAT tag in DGMHVUTL routine and verify that the Condensed patient MHV status is covered
 ;
 TSTART
 N DFN,DGFLDNO
 S DGFLDNO(1)=1,DGFLDNO(2)=1,DGFLDNO(3)=1
 S DFN=0 F  S DFN=$O(^DPT(DFN)) Q:'DFN  I $D(^DPT(DFN,2))!($D(^DPT(DFN,1))) D CONSTAT^DGMHVUTL(DFN,.DGFLDNO)
 TROLLBACK
 Q
 ;
XTROU ;
 ;;ZZDGMHV1
 ; Entry points for tests are specified as the third semi-colon piece,
 ; a description of what it tests is optional as the fourth semi-colon
 ; piece on a line. The first line without a third piece terminates the
 ; search for TAGs to be used as entry points
XTENT ;
 ;;CHKTXT;Unit Test to check the TXT^DGMHV API.
 ;;CHKLKUPACT;Unit Test to check the LKUPACT^DGMHVAC API for MHV SOCIALIZATIONS ACTIONS
 ;;CHKCONSTAT;Unit Test to check that the condense patient status is displayed for each patient
 Q


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/image_update"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:clickable="false"
        android:contentDescription="@string/user_s_character" />

</RelativeLayout>


text:
#include "tensorflow/dtensor/mlir/expansions/gather_spmd_expander.h"

#include <string>
#include <vector>

#include "absl/types/optional.h"
#include "llvm/Support/FormatVariadic.h"
#include "mlir/IR/BuiltinTypes.h"  // from @llvm-project
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/dtensor/cc/tensor_layout.h"
#include "tensorflow/dtensor/mlir/collectives.h"
#include "tensorflow/dtensor/mlir/layout_parsing.h"
#include "tensorflow/dtensor/mlir/shape_utils.h"
#include "tensorflow/dtensor/mlir/spmd_expander_common.h"
#include "tensorflow/dtensor/mlir/value_utils.h"

namespace tensorflow {
namespace dtensor {

StatusOr<mlir::Operation*> GatherV2SPMDExpander::ExpandOp(mlir::Operation* op) {
  auto gather_op = llvm::cast<mlir::TF::GatherV2Op>(op);
  TF_ASSIGN_OR_RETURN(int64_t axis, ExtractConstIntFromValue(gather_op.axis()));
  TF_ASSIGN_OR_RETURN(auto params_layout,
                      ExtractLayoutFromOperand(gather_op.params()));
  TF_ASSIGN_OR_RETURN(auto indices_layout,
                      ExtractLayoutFromOperand(gather_op.indices()));
  TF_ASSIGN_OR_RETURN(auto output_layout, ExtractSingleLayoutFromOp(gather_op));

  const auto params_rank = ValueRank(gather_op.params());
  const auto indices_rank = ValueRank(gather_op.indices());
  if (params_rank == -1)
    return errors::InvalidArgument("missing rank for params input");
  if (indices_rank == -1)
    return errors::InvalidArgument("missing rank for indices input");

  // Handle the case of negative axis.
  if (axis < 0) axis += params_rank;

  int batch_dims = gather_op.batch_dims();

  auto params = gather_op.params();
  auto indices = gather_op.indices();

  mlir::OpBuilder builder(op);

  // Step 1: If the params are sharded on dim axis, an unconditional all-concat
  // is generated. Alternatively, we could do: all-concating indices, followed
  // by tf.Gather + slicing with correct masks.
  //
  // Currently we only support the case that the output layout matching the
  // params layout for all non-axis dim. Other cases needs either a slicing or
  // all-concat, which can be added later.
  {
    LayoutProto tgt_params_layout;
    *tgt_params_layout.mutable_mesh_config() = params_layout->mesh().ToProto();
    // check the first half
    for (int i = 0; i < axis; ++i) {
      const auto dim_name = params_layout->sharding_spec(i);
      if (dim_name != output_layout->sharding_spec(i)) {
        return errors::InvalidArgument(
            llvm::formatv(
                "input and output layout do not agree on non-axis dim {0}. "
                "\n  params: {1}\n  output: {2}, axis: {3}",
                i, params_layout->ToString(), output_layout->ToString(), axis)
                .str());
      }
      tgt_params_layout.add_sharding_specs()->set_sharding_spec(dim_name);
    }
    // Set replicated for `axis` dim.
    tgt_params_layout.add_sharding_specs()->set_sharding_spec(
        Layout::kUnshardedDim);
    // Check the second half
    for (int i = axis + 1; i < params_rank; ++i) {
      auto dim_name = params_layout->sharding_spec(i);
      // To align the param dim with output, we can think we insert indices_rank
      // - batch_dims dims from indices and remove one from param (axis), so
      // the shifting is indices_rank - batch_dims - 1.
      if (dim_name !=
          output_layout->sharding_spec(i + indices_rank - batch_dims - 1)) {
        return errors::InvalidArgument(
            llvm::formatv(
                "input and output layout do not agree on non-axis dim {0}. "
                "\n  params: {1}\n  output: {2}, axis: {3}",
                i, params_layout->ToString(), output_layout->ToString(), axis)
                .str());
      }
      tgt_params_layout.add_sharding_specs()->set_sharding_spec(dim_name);
    }

    if (!Layout::IsUnshardedDimension(params_layout->sharding_spec(axis))) {
      TF_ASSIGN_OR_RETURN(
          params,
          EmitAllGather(builder, params, *params_layout,
                        Layout::FromProto(tgt_params_layout).ValueOrDie()));
    }
  }

  // Step 2: Check the output layout. If it requires all-relayouting indices.
  // Do it.
  //
  // Indices shape is not big typically. Relayouting is expected to be cheap.
  {
    bool indices_relayout_needed = false;
    LayoutProto tgt_indices_layout;
    *tgt_indices_layout.mutable_mesh_config() = output_layout->mesh().ToProto();
    for (int i = 0; i < indices_rank; ++i) {
      int index_in_output;
      int index_in_indices;
      if (i < batch_dims) {
        // For dim within batch_dims, indices dim is aligning at the same index
        // as output.
        index_in_output = i;
        index_in_indices = i;
      } else {
        // For dim after batch_dims, we can remove batch_dims from outputs and
        // indices first, i.e., (i - batch_dims), add axis back, i.e., axis -
        // batch_dims, and then put batch_dims back, so the target position in
        // output is
        //
        //   i - batch_dims + axis - batch_dims + batch_dims
        //
        // which is as follows:
        index_in_output = i + axis - batch_dims;
        index_in_indices = i;
      }
      tgt_indices_layout.add_sharding_specs()->set_sharding_spec(
          output_layout->sharding_spec(index_in_output));

      if (output_layout->sharding_spec(index_in_output) !=
          indices_layout->sharding_spec(index_in_indices)) {
        indices_relayout_needed = true;
      }
    }

    if (indices_relayout_needed) {
      TF_ASSIGN_OR_RETURN(
          indices,
          EmitRelayout(indices, *indices_layout,
                       Layout::FromProto(tgt_indices_layout).ValueOrDie()));
    }
  }

  auto new_gather = builder.create<mlir::TF::GatherV2Op>(
      gather_op.getLoc(), gather_op.getResult().getType(), params, indices,
      gather_op.axis(), gather_op.batch_dims());
  op->getResult(0).replaceAllUsesWith(new_gather.output());
  op->erase();

  return InferSPMDExpandedLocalShape(new_gather);
}

StatusOr<llvm::DenseMap<int, Layout>>
GatherV2SPMDExpander::ComputeLayoutForward(
    mlir::Operation* op, const llvm::DenseMap<int, Layout>& input_layouts) {
  auto gather_op = llvm::cast<mlir::TF::GatherV2Op>(op);
  TF_ASSIGN_OR_RETURN(const Mesh mesh, ExtractDeviceMeshEnclosingCluster(op));

  TF_ASSIGN_OR_RETURN(int64_t axis, ExtractConstIntFromValue(gather_op.axis()));
  int batch_dims = gather_op.batch_dims();

  absl::optional<Layout> params_layout;
  if (input_layouts.find(0) != input_layouts.end())
    params_layout.emplace(input_layouts.lookup(0));
  absl::optional<Layout> indices_layout;
  if (input_layouts.find(1) != input_layouts.end())
    indices_layout.emplace(input_layouts.lookup(1));

  const int params_rank = ValueRank(gather_op.params());
  const int indices_rank = ValueRank(gather_op.indices());
  if (params_rank == -1)
    return errors::InvalidArgument("missing rank for params input");
  if (indices_rank == -1)
    return errors::InvalidArgument("missing rank for indices input");

  // Handle the case of negative axis.
  if (axis < 0) axis += params_rank;

  if (params_layout || indices_layout) {
    std::vector<std::string> output_layout_specs;

    // Get a list of mesh dims that params uses, other than the dim for axis.
    llvm::DenseSet<llvm::StringRef> params_mesh_dims;
    if (params_layout) {
      for (int i = 0; i < params_rank; ++i)
        if (i != axis &&
            !Layout::IsUnshardedDimension(params_layout->sharding_spec(i)))
          params_mesh_dims.insert(params_layout->sharding_spec(i));
    }

    auto add_mesh_dim_if = [&](const absl::optional<Layout>& input_layout,
                               int64 dim, bool indices = false) {
      // Only add the mesh dimension to the output_layout if 1) the input layout
      // exists and 2) when the input is indices and the params dims don't
      // contain the mesh dim we are adding (to avoid two different tensor dims
      // being sharded over the same mesh dim).
      // Note that params->sharding_spec(axis) is specifically excluded from the
      // params_mesh_dims during construction above. This means that if we are
      // processing the indices layout and it contains
      // params->sharding_spec(axis) we will still add that sharding_spec to the
      // output layout.
      if (input_layout && (!indices || !params_mesh_dims.contains(
                                           input_layout->sharding_spec(dim))))
        output_layout_specs.push_back(input_layout->sharding_spec(dim));
      else
        output_layout_specs.push_back(Layout::kUnshardedDim);
    };

    for (int i = 0; i < axis; ++i) add_mesh_dim_if(params_layout, i);
    for (int i = batch_dims; i < indices_rank; ++i)
      add_mesh_dim_if(indices_layout, i, /*indices=*/true);
    for (int i = axis + 1; i < params_rank; ++i)
      add_mesh_dim_if(params_layout, i);

    TF_ASSIGN_OR_RETURN(const Layout output_layout,
                        Layout::GetLayout(output_layout_specs, mesh));
    return llvm::DenseMap<int, Layout>({{0, output_layout}});
  }

  return llvm::DenseMap<int, Layout>();
}

StatusOr<llvm::DenseMap<int, Layout>>
GatherV2SPMDExpander::ComputeLayoutBackward(
    mlir::Operation* op, const llvm::DenseMap<int, Layout>& output_layouts) {
  auto gather_op = llvm::cast<mlir::TF::GatherV2Op>(op);
  TF_ASSIGN_OR_RETURN(const Mesh mesh, ExtractDeviceMeshEnclosingCluster(op));

  llvm::DenseMap<int, Layout> input_layouts(gather_op.getNumOperands());
  // axis is const
  input_layouts[2] = Layout::ReplicatedOnMesh(mesh, /*rank=*/0);

  if (output_layouts.find(0) != output_layouts.end()) {
    // This will always exist since there is only one output.
    const Layout output_layout = output_layouts.lookup(0);

    TF_ASSIGN_OR_RETURN(int64_t axis,
                        ExtractConstIntFromValue(gather_op.axis()));
    int batch_dims = gather_op.batch_dims();

    const int params_rank = ValueRank(gather_op.params());
    const int indices_rank = ValueRank(gather_op.indices());
    if (params_rank == -1)
      return errors::InvalidArgument("missing rank for params input");
    if (indices_rank == -1)
      return errors::InvalidArgument("missing rank for indices input");

    // Handle the case of negative axis.
    if (axis < 0) axis += params_rank;

    std::vector<std::string> params_layout_specs;
    std::vector<std::string> indices_layout_specs;
    params_layout_specs.reserve(params_rank);
    indices_layout_specs.reserve(indices_rank);

    // Extract the params layout. We will request that axis is replicated as
    // that gives the least issues with spmd expansion.
    // E.g. If we had axis = 1 and parmas layout [p0 p1 p2 p3]
    // input layout [i0 i1] then the output layout would have been
    // [p0 i0 i1 p2 p3] so to go backwards, we extract the ranges [0, axis)
    // and [axis + indices.rank(), output.rank()) for params (with a replicated
    // dim for the missing dimension inbetween). Indices layout is based on the
    // range [axis, axis+indices)/
    for (int i = 0; i < axis; ++i)
      params_layout_specs.push_back(output_layout.sharding_spec(i));
    params_layout_specs.push_back(Layout::kUnshardedDim);
    for (int i = axis + indices_rank - batch_dims; i < output_layout.rank();
         ++i)
      params_layout_specs.push_back(output_layout.sharding_spec(i));

    // Extract the indices layout.
    for (int i = 0; i < batch_dims; ++i)
      indices_layout_specs.push_back(output_layout.sharding_spec(i));
    for (int i = axis; i < axis + indices_rank - batch_dims; ++i)
      indices_layout_specs.push_back(output_layout.sharding_spec(i));

    TF_ASSIGN_OR_RETURN(const Layout params_layout,
                        Layout::GetLayout(params_layout_specs, mesh));
    TF_ASSIGN_OR_RETURN(const Layout indices_layout,
                        Layout::GetLayout(indices_layout_specs, mesh));
    input_layouts[0] = params_layout;
    input_layouts[1] = indices_layout;
  }

  return input_layouts;
}

namespace {

StatusOr<Layout> GatherNdGetOutputLayoutFromInput(
    const absl::optional<Layout>& params_layout, int params_rank,
    const absl::optional<Layout>& indices_layout, int indices_rank,
    int index_dimensions, const Mesh& mesh) {
  // The layout of the output should be the layout of the first rank-1
  // dimensions of the indices plus the layout of the last params.rank -
  // indices.dims[-1] dimensions of params. If one of the two is missing we
  // replace them with replicated.
  // If sharding dimension is used by both params and indices, the params
  // layout will be respected as generally params is larger than indices.
  std::vector<ShardingSpec> output_specs(params_rank - index_dimensions +
                                         indices_rank - 1);
  absl::flat_hash_set<std::string> used_dimensions;
  const int params_offset = -index_dimensions + indices_rank - 1;

  for (int i = index_dimensions; i < params_rank; ++i) {
    if (params_layout && Layout::IsShardedSpec(params_layout->dim(i))) {
      const ShardingSpec& params_spec = params_layout->dim(i);
      output_specs[i + params_offset] = params_spec;
      used_dimensions.emplace(params_spec.sharding_spec());
    } else {
      output_specs[i + params_offset].set_sharding_spec(Layout::kUnshardedDim);
    }
  }
  for (int i = 0; i < indices_rank - 1; ++i) {
    if (indices_layout && Layout::IsShardedSpec(indices_layout->dim(i)) &&
        !used_dimensions.contains(indices_layout->sharding_spec(i)))
      output_specs[i] = indices_layout->dim(i);
    else
      output_specs[i].set_sharding_spec(Layout::kUnshardedDim);
  }
  return Layout::GetLayout(output_specs, mesh);
}

Status GatherNdGetInputLayoutFromOutput(const Layout& output_layout,
                                        Layout* params_layout, int params_rank,
                                        Layout* indices_layout,
                                        int indices_rank, int index_dimensions,
                                        const Mesh& mesh) {
  // We copy the first indices_rank - 1 dimensions of the output layout to
  // indices_layout (with the last dimensions replicated) and the remaining
  // dimensions to params_layout (with the first index_dimensions dimensions
  // replicated).
  std::vector<ShardingSpec> params_specs(params_rank);
  std::vector<ShardingSpec> indices_specs(indices_rank);

  for (int i = 0; i < index_dimensions; ++i)
    params_specs[i].set_sharding_spec(Layout::kUnshardedDim);

  const int params_offset = -index_dimensions + indices_rank - 1;
  for (int i = index_dimensions; i < params_rank; ++i)
    params_specs[i] = output_layout.dim(i + params_offset);

  for (int i = 0; i < indices_rank - 1; ++i)
    indices_specs[i] = output_layout.dim(i);

  indices_specs[indices_rank - 1].set_sharding_spec(Layout::kUnshardedDim);

  TF_ASSIGN_OR_RETURN(*params_layout, Layout::GetLayout(params_specs, mesh));
  TF_ASSIGN_OR_RETURN(*indices_layout, Layout::GetLayout(indices_specs, mesh));

  return Status::OK();
}

}  // namespace

StatusOr<mlir::Operation*> GatherNdSPMDExpander::ExpandOp(mlir::Operation* op) {
  auto gather_op = llvm::cast<mlir::TF::GatherNdOp>(op);
  TF_ASSIGN_OR_RETURN(Layout params_layout,
                      ExtractRequiredLayoutFromOperand(gather_op.params()));
  TF_ASSIGN_OR_RETURN(Layout indices_layout,
                      ExtractRequiredLayoutFromOperand(gather_op.indices()));
  TF_ASSIGN_OR_RETURN(Layout output_layout,
                      ExtractRequiredSingleLayoutFromOp(gather_op));

  TF_ASSIGN_OR_RETURN(
      llvm::ArrayRef<int64_t> indices_shape,
      GetGlobalShapeOfValueFromDTensorLayout(gather_op.indices()));
  const int index_dimensions = indices_shape.back();

  const auto params_rank = ValueRank(gather_op.params());
  const auto indices_rank = ValueRank(gather_op.indices());
  if (params_rank == -1)
    return errors::InvalidArgument("missing rank for params input");
  if (indices_rank == -1)
    return errors::InvalidArgument("missing rank for indices input");

  TF_ASSIGN_OR_RETURN(const Mesh mesh, ExtractDeviceMeshEnclosingCluster(op));

  // Note that there may be conflicts between the two input layouts.
  // To resolve these we:
  // 1) Compute output layout from the current input layouts. This ignores any
  //    sharding on the 'lookup' axis in params and the last axis in indices.
  //    If params and indices are sharded on same dimension, the indices will
  //    be unsharded in that dimension.
  // 2) Merge any new sharding from the final output layout into this layout.
  //    E.g. if the two inputs are unsharded, but the output is, this will be
  //    more efficient as the local computations will be smaller since we will
  //    more finely shard the inputs.
  // 3) Finally, we use this new output layout to compute what input layouts we
  //    need to get the given output.

  // Step 1)
  TF_ASSIGN_OR_RETURN(const Layout pre_output_layout,
                      GatherNdGetOutputLayoutFromInput(
                          params_layout, params_rank, indices_layout,
                          indices_rank, index_dimensions, mesh));

  // Step 2)
  llvm::DenseSet<llvm::StringRef> used_dimensions;
  for (const ShardingSpec& spec : pre_output_layout.sharding_specs())
    if (Layout::IsShardedSpec(spec))
      used_dimensions.insert(spec.sharding_spec());

  std::vector<ShardingSpec> sharding_specs(output_layout.rank());
  for (int i = 0; i < sharding_specs.size(); ++i) {
    if (Layout::IsShardedSpec(pre_output_layout.dim(i)))
      sharding_specs[i] = pre_output_layout.dim(i);
    // Merge in sharded dimensions from the output which aren't already used
    // by the pre_output_layout.
    else if (Layout::IsShardedSpec(output_layout.dim(i)) &&
             !used_dimensions.contains(output_layout.sharding_spec(i)))
      sharding_specs[i] = output_layout.dim(i);
    else
      sharding_specs[i].set_sharding_spec(Layout::kUnshardedDim);
  }

  // Step 3)
  TF_ASSIGN_OR_RETURN(
      const Layout merged_output_layout,
      Layout::GetLayout(sharding_specs, pre_output_layout.mesh()));

  Layout new_params_layout;
  Layout new_indices_layout;
  TF_RETURN_IF_ERROR(GatherNdGetInputLayoutFromOutput(
      merged_output_layout, &new_params_layout, params_rank,
      &new_indices_layout, indices_rank, index_dimensions, mesh));

  TF_ASSIGN_OR_RETURN(
      mlir::Value params,
      EmitRelayout(gather_op.params(), params_layout, new_params_layout));
  TF_ASSIGN_OR_RETURN(
      mlir::Value indices,
      EmitRelayout(gather_op.indices(), indices_layout, new_indices_layout));

  mlir::OpBuilder builder(op);

  // mlir::TF::GatherNdOp does not have a builder that does shape inference
  // so we have to provided the output type. This output type is incorrect and
  // we manually run shape inference after.
  mlir::TF::GatherNdOp new_gather = builder.create<mlir::TF::GatherNdOp>(
      op->getLoc(), gather_op.output().getType(), params, indices);
  InferSPMDExpandedLocalShape(new_gather);

  TF_ASSIGN_OR_RETURN(
      mlir::Value output,
      EmitRelayout(new_gather.output(), merged_output_layout, output_layout));

  gather_op.output().replaceAllUsesWith(output);
  gather_op.erase();
  return output.getDefiningOp();
}

StatusOr<llvm::DenseMap<int, Layout>>
GatherNdSPMDExpander::ComputeLayoutForward(
    mlir::Operation* op, const llvm::DenseMap<int, Layout>& input_layouts) {
  auto gather_op = llvm::cast<mlir::TF::GatherNdOp>(op);
  TF_ASSIGN_OR_RETURN(Mesh mesh, ExtractDeviceMeshEnclosingCluster(op));

  absl::optional<Layout> params_layout;
  if (input_layouts.find(0) != input_layouts.end())
    params_layout.emplace(input_layouts.lookup(0));
  absl::optional<Layout> indices_layout;
  if (input_layouts.find(1) != input_layouts.end())
    indices_layout.emplace(input_layouts.lookup(1));

  TF_ASSIGN_OR_RETURN(llvm::ArrayRef<int64_t> indices_shape,
                      ExtractGlobalInputShape(op->getOpOperand(1)));
  const int index_dimensions = indices_shape.back();
  if (index_dimensions < 0)
    return errors::Unimplemented(
        "dynamic last dimension for index is not supported");

  const int params_rank = ValueRank(gather_op.params());
  const int indices_rank = ValueRank(gather_op.indices());
  if (params_rank == -1)
    return errors::InvalidArgument("missing rank for params input");
  if (indices_rank == -1)
    return errors::InvalidArgument("missing rank for indices input");

  if (params_layout || indices_layout) {
    TF_ASSIGN_OR_RETURN(const Layout output_layout,
                        GatherNdGetOutputLayoutFromInput(
                            params_layout, params_rank, indices_layout,
                            indices_rank, index_dimensions, mesh));
    return llvm::DenseMap<int, Layout>({{0, output_layout}});
  }

  return llvm::DenseMap<int, Layout>();
}

StatusOr<llvm::DenseMap<int, Layout>>
GatherNdSPMDExpander::ComputeLayoutBackward(
    mlir::Operation* op, const llvm::DenseMap<int, Layout>& output_layouts) {
  // If there is no output layout present then do not infer any operand layouts.
  if (output_layouts.find(0) == output_layouts.end())
    return llvm::DenseMap<int, Layout>();

  auto gather_op = llvm::cast<mlir::TF::GatherNdOp>(op);
  TF_ASSIGN_OR_RETURN(Mesh mesh, ExtractDeviceMeshEnclosingCluster(op));

  TF_ASSIGN_OR_RETURN(llvm::ArrayRef<int64_t> indices_shape,
                      ExtractGlobalInputShape(op->getOpOperand(1)));
  const int index_dimensions = indices_shape.back();
  if (index_dimensions < 0)
    return errors::Unimplemented(
        "dynamic last dimension for index is not supported");

  const int params_rank = ValueRank(gather_op.params());
  const int indices_rank = ValueRank(gather_op.indices());
  if (params_rank == -1)
    return errors::InvalidArgument("missing rank for params input");
  if (indices_rank == -1)
    return errors::InvalidArgument("missing rank for indices input");

  const Layout output_layout = output_layouts.lookup(0);
  Layout params_layout, indices_layout;
  TF_RETURN_IF_ERROR(GatherNdGetInputLayoutFromOutput(
      output_layout, &params_layout, params_rank, &indices_layout, indices_rank,
      index_dimensions, mesh));
  return llvm::DenseMap<int, Layout>({
      {0, params_layout},
      {1, indices_layout},
  });
}

}  // namespace dtensor
}  // namespace tensorflow


text:
package org.kaaproject.kaa.server.control;

import static org.kaaproject.kaa.server.common.thrift.util.ThriftDtoConverter.toDataStruct;
import static org.kaaproject.kaa.server.common.thrift.util.ThriftDtoConverter.toDto;
import static org.kaaproject.kaa.server.common.thrift.util.ThriftDtoConverter.toDtoList;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.thrift.TException;
import org.junit.Assert;
import org.junit.Test;
import org.kaaproject.kaa.common.dto.ApplicationDto;
import org.kaaproject.kaa.common.dto.ConfigurationSchemaDto;
import org.kaaproject.kaa.common.dto.SchemaDto;
import org.kaaproject.kaa.common.dto.UpdateStatus;
import org.kaaproject.kaa.server.common.core.schema.KaaSchemaFactoryImpl;
import org.kaaproject.kaa.server.common.thrift.gen.control.ControlThriftException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ControlServerConfigurationSchemaIT extends AbstractTestControlServer {

    /** The Constant logger. */
    private static final Logger logger = LoggerFactory
            .getLogger(ControlServerConfigurationSchemaIT.class);

    /**
     * Test create configuration schema.
     *
     * @throws TException
     *             the t exception
     * @throws IOException Signals that an I/O exception has occurred.
     */
    @Test
    public void testCreateConfigurationSchema() throws TException, IOException {
        ConfigurationSchemaDto configurationSchema = createConfigurationSchema();
        Assert.assertFalse(strIsEmpty(configurationSchema.getId()));
        Assert.assertFalse(configurationSchema.getProtocolSchema().isEmpty());
    }

    /**
     * Test create invalid configuration schema.
     *
     * @throws TException
     *             the t exception
     * @throws IOException Signals that an I/O exception has occurred.
     */
    @Test(expected = ControlThriftException.class)
    public void testCreateInvalidConfigurationSchema() throws TException, IOException {
        ConfigurationSchemaDto configurationSchema = new ConfigurationSchemaDto();
        configurationSchema.setStatus(UpdateStatus.ACTIVE);
        String schema = getResourceAsString(TEST_INVALID_CONFIG_SCHEMA);
        configurationSchema.setSchema(new KaaSchemaFactoryImpl().createDataSchema(schema).getRawSchema());
        ApplicationDto application = createApplication();
        configurationSchema.setApplicationId(application.getId());
        client.editConfigurationSchema(toDataStruct(configurationSchema));
    }

    /**
     * Test get configuration schema.
     *
     * @throws TException
     *             the t exception
     * @throws IOException Signals that an I/O exception has occurred.
     */
    @Test
    public void testGetConfigurationSchema() throws TException, IOException {
        ConfigurationSchemaDto configurationSchema = createConfigurationSchema();

        ConfigurationSchemaDto storedConfigurationSchema = toDto(client.getConfigurationSchema(configurationSchema.getId()));

        Assert.assertNotNull(storedConfigurationSchema);
        assertConfigurationSchemasEquals(configurationSchema, storedConfigurationSchema);
    }

    /**
     * Test get configuration schemas by application id.
     *
     * @throws TException
     *             the t exception
     * @throws IOException Signals that an I/O exception has occurred.
     */
    @Test
    public void testGetConfigurationSchemasByApplicationId() throws TException, IOException {

        List<ConfigurationSchemaDto> configurationSchemas  = new ArrayList<ConfigurationSchemaDto>(11);
        ApplicationDto application = createApplication();

        List<ConfigurationSchemaDto> defaultConfigurationSchemas = toDtoList(client.getConfigurationSchemasByApplicationId(application.getId()));
        configurationSchemas.addAll(defaultConfigurationSchemas);

        for (int i=0;i<10;i++) {
            ConfigurationSchemaDto configurationSchema = createConfigurationSchema(application.getId());
            configurationSchemas.add(configurationSchema);
        }

        Collections.sort(configurationSchemas, new IdComparator());

        List<ConfigurationSchemaDto> storedConfigurationSchemas = toDtoList(client.getConfigurationSchemasByApplicationId(application.getId()));

        Collections.sort(storedConfigurationSchemas, new IdComparator());

        Assert.assertEquals(configurationSchemas.size(), storedConfigurationSchemas.size());
        for (int i=0;i<configurationSchemas.size();i++) {
            ConfigurationSchemaDto configurationSchema = configurationSchemas.get(i);
            ConfigurationSchemaDto storedConfigurationSchema = storedConfigurationSchemas.get(i);
            Assert.assertEquals(configurationSchema.getId(), storedConfigurationSchema.getId());
            Assert.assertEquals(configurationSchema.getApplicationId(), storedConfigurationSchema.getApplicationId());
            Assert.assertEquals(configurationSchema.getStatus(), storedConfigurationSchema.getStatus());
        }
    }

    /**
     * Test get configuration schema versions by application id.
     *
     * @throws TException
     *             the t exception
     * @throws IOException Signals that an I/O exception has occurred.
     */
    @Test
    public void testGetConfigurationSchemaVersionsByApplicationId() throws TException, IOException {

        List<ConfigurationSchemaDto> configurationSchemas  = new ArrayList<ConfigurationSchemaDto>(11);
        ApplicationDto application = createApplication();

        List<ConfigurationSchemaDto> defaultConfigurationSchemas = toDtoList(client.getConfigurationSchemasByApplicationId(application.getId()));
        configurationSchemas.addAll(defaultConfigurationSchemas);

        for (int i=0;i<10;i++) {
            ConfigurationSchemaDto configurationSchema = createConfigurationSchema(application.getId());
            configurationSchemas.add(configurationSchema);
        }

        Collections.sort(configurationSchemas, new IdComparator());

        List<SchemaDto> storedConfigurationSchemas = toDtoList(client.getConfigurationSchemaVersionsByApplicationId(application.getId()));

        Collections.sort(storedConfigurationSchemas, new IdComparator());

        Assert.assertEquals(configurationSchemas.size(), storedConfigurationSchemas.size());
        for (int i=0;i<configurationSchemas.size();i++) {
            ConfigurationSchemaDto configurationSchema = configurationSchemas.get(i);
            SchemaDto storedConfigurationSchema = storedConfigurationSchemas.get(i);
            assertSchemasEquals(configurationSchema, storedConfigurationSchema);
        }
    }

    /**
     * Test update configuration schema.
     *
     * @throws TException
     *             the t exception
     * @throws IOException Signals that an I/O exception has occurred.
     */
    @Test
    public void testUpdateConfigurationSchema() throws TException, IOException {
        ConfigurationSchemaDto configurationSchema = createConfigurationSchema();

        configurationSchema.setName(generateString("Test Schema 2"));
        configurationSchema.setDescription(generateString("Test Desc 2"));

        ConfigurationSchemaDto updatedConfigurationSchema = toDto(client
                .editConfigurationSchema(toDataStruct(configurationSchema)));

        Assert.assertEquals(updatedConfigurationSchema.getId(), configurationSchema.getId());
        Assert.assertEquals(updatedConfigurationSchema.getApplicationId(), configurationSchema.getApplicationId());
        Assert.assertEquals(updatedConfigurationSchema.getSchema(), configurationSchema.getSchema());
        Assert.assertEquals(updatedConfigurationSchema.getName(), configurationSchema.getName());
        Assert.assertEquals(updatedConfigurationSchema.getDescription(), configurationSchema.getDescription());
        Assert.assertEquals(updatedConfigurationSchema.getCreatedTime(), configurationSchema.getCreatedTime());
        Assert.assertEquals(updatedConfigurationSchema.getProtocolSchema(), configurationSchema.getProtocolSchema());
        Assert.assertEquals(updatedConfigurationSchema.getStatus(), configurationSchema.getStatus());
    }

    /**
     * Assert configuration schemas equals.
     *
     * @param configurationSchema the configuration schema
     * @param storedConfigurationSchema the stored configuration schema
     */
    private void assertConfigurationSchemasEquals(ConfigurationSchemaDto configurationSchema, ConfigurationSchemaDto storedConfigurationSchema) {
        Assert.assertEquals(configurationSchema.getId(), storedConfigurationSchema.getId());
        Assert.assertEquals(configurationSchema.getApplicationId(), storedConfigurationSchema.getApplicationId());
        Assert.assertEquals(configurationSchema.getSchema(), storedConfigurationSchema.getSchema());
        Assert.assertEquals(configurationSchema.getProtocolSchema(), storedConfigurationSchema.getProtocolSchema());
        Assert.assertEquals(configurationSchema.getStatus(), storedConfigurationSchema.getStatus());
    }

}


text:
package me.kernelfreeze.bedrockproxy.raknet.client.discovery;

import me.kernelfreeze.bedrockproxy.raknet.client.RakNetClient;
import me.kernelfreeze.bedrockproxy.raknet.util.RakNetUtils;

import java.util.ArrayList;

/**
 * This Thread is used by the RakNetClient to discover
 * servers, allowing the client to discover servers without being started and
 * without having to take up multiple threads.
 *
 * @author MarfGamer
 */
public class DiscoveryThread extends Thread {

    private ArrayList<RakNetClient> clients;
    private volatile boolean running;

    /**
     * Constructs a DiscoveryThread.
     */
    public DiscoveryThread() {
        this.clients = new ArrayList<RakNetClient>();
    }

    /**
     * @return the clients that are currently using the discovery system.
     */
    public RakNetClient[] getClients() {
        return clients.toArray(new RakNetClient[clients.size()]);
    }

    /**
     * Adds a RakNetClient to the discovery system so it can
     * discover servers.
     *
     * @param client the RakNetClient enabling its discovery system.
     */
    public void addClient(RakNetClient client) {
        if (clients.contains(client)) {
            return;
        }
        clients.add(client);
    }

    /**
     * Removes a RakNetClient from the discovery system, this
     * method is also called automatically by the client when it is garbage
     * collected.
     *
     * @param client the RakNetClient disabling its discovery system.
     */
    public void removeClient(RakNetClient client) {
        clients.remove(client);
    }

    /**
     * @return true if the thread has been started.
     */
    public boolean isRunning() {
        return this.running;
    }

    /**
     * shuts down the discovery system.
     */
    public void shutdown() {
        this.running = false;
    }

    @Override
    public synchronized void run() {
        this.running = true;
        while (this.running) {
            for (RakNetClient client : this.clients) {
                client.updateDiscoveryData();
            }
            RakNetUtils.threadLock(1000L);
        }
    }

}


text:
package org.hisp.dhis.analytics.shared;

import static org.apache.commons.lang3.StringUtils.isNotBlank;

import org.hisp.dhis.program.Program;
import org.hisp.dhis.program.ProgramStage;

/**
 * Specific component responsible mapping custom labels for specific cases where
 * the user is able to customize them.
 *
 * @author maikel arabori
 */
public class LabelMapper
{

    private LabelMapper()
    {
    }

    /**
     * This method maps the given column to its respective label representation.
     * The label is mainly needed to expose a more "user-friendly" name to the
     * client.
     *
     * @param column
     * @return the column's label
     */
    public static String getLabelOf( final Column column )
    {
        // TODO: Implement the logic to get the correct label of the respective
        // column. See:
        // org.hisp.dhis.analytics.event.data.DefaultEventAnalyticsService#createGridWithHeaders

        return column.getAlias();
    }

    /**
     * Finds for a custom label for event date if one exists.
     *
     * @param programStage
     * @return the custom label, otherwise the default one
     */
    public static String getEventDateLabel( final ProgramStage programStage, final String defaultLabel )
    {
        if ( programStage != null && isNotBlank( programStage.getDisplayExecutionDateLabel() ) )
        {
            return programStage.getDisplayExecutionDateLabel();
        }

        return defaultLabel;
    }

    /**
     * Finds for a custom label for enrollment date if one exists.
     *
     * @param program
     * @return the custom label, otherwise the default one
     */
    public static String getEnrollmentDateLabel( final Program program, final String defaultLabel )
    {
        if ( program != null && isNotBlank( program.getDisplayEnrollmentDateLabel() ) )
        {
            return program.getDisplayEnrollmentDateLabel();
        }

        return defaultLabel;
    }

    /**
     * Finds for a custom label for incident date if one exists.
     *
     * @param program
     * @return the custom label, otherwise the default one
     */
    public static String getIncidentDateLabel( final Program program, final String defaultLabel )
    {
        if ( program != null && isNotBlank( program.getDisplayIncidentDateLabel() ) )
        {
            return program.getDisplayIncidentDateLabel();
        }

        return defaultLabel;
    }
}


text:
import pickle
from collections import deque
from socketserver import BaseRequestHandler

from RULEngine.Communication.util.threaded_udp_server import ThreadedUDPServer
from RULEngine.Util.constant import DEBUG_RECEIVE_BUFFER_SIZE
from config.config_service import ConfigService

class UIDebugCommandReceiver(object):
    """
        Service capable d'écouter un port multicast UDP, de reçevoir et de
        traiter les paquets brutes envoyer par le serveur de débogage.
    """
    def __init__(self):
        cfg = ConfigService()
        host = cfg.config_dict["COMMUNICATION"]["ui_debug_address"]
        port = int(cfg.config_dict["COMMUNICATION"]["ui_cmd_receiver_port"])
        self.packet_list = deque(maxlen=DEBUG_RECEIVE_BUFFER_SIZE)
        handler = self.get_udp_handler(self.packet_list)
        self.server = ThreadedUDPServer(host, port, handler)

    def get_udp_handler(self, p_packet_list):
        """ Retourne la classe pour reçevoir async les paquets """

        class ThreadedUDPRequestHandler(BaseRequestHandler):
            """ Contient la logique pour traiter en callback une request. """
            def handle(self):
                """
                    Récupère la request et unpickle le paquet brute dans la
                    deque.
                """
                data = self.request[0]
                p_packet_list.append(pickle.loads(data))
        return ThreadedUDPRequestHandler

    def receive_command(self):
        """ Vide la file et retourne une liste des paquets brutes. """
        for _ in range(len(self.packet_list)):
            yield self.packet_list.pop()


text:
////////////////////////////////////////////////////////////////////////////////
// Catapult Synthesis
//
// Copyright (c) 2003-2015 Calypto Design Systems, Inc.
//       All Rights Reserved
//
// This document contains information that is proprietary to Calypto Design
// Systems, Inc. The original recipient of this document may duplicate this
// document in whole or in part for internal business purposes only, provided
// that this entire notice appears in all copies. In duplicating any part of
// this document, the recipient agrees to make every reasonable effort to
// prevent the unauthorized use and distribution of the proprietary information.
//
// The design information contained in this file is intended to be an example
// of the functionality which the end user may study in preparation for creating
// their own custom interfaces. This design does not present a complete
// implementation of the named protocol or standard.
//
// NO WARRANTY.
// CALYPTO DESIGN SYSTEMS, INC. EXPRESSLY DISCLAIMS ALL WARRANTY
// FOR THE SOFTWARE. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE
// LAW, THE SOFTWARE AND ANY RELATED DOCUMENTATION IS PROVIDED "AS IS"
// AND WITH ALL FAULTS AND WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE, OR NONINFRINGEMENT. THE ENTIRE RISK ARISING OUT OF USE OR
// DISTRIBUTION OF THE SOFTWARE REMAINS WITH YOU.
//
////////////////////////////////////////////////////////////////////////////////
/*
 * dct.cpp
 *
 *  Created on: Oct 15, 2014
 *      Author: michaelf
 */
//Folded filter because of symmetrical coefficients

#include "dct.h"

template<typename T0, typename T1,typename T2>
T2 mult_add(T0 data[8], ac_int<3,false> i) {
   T2 acc = 0;
   T1 pa[4];
   const ac_int<10> coeff[8][4] = {
         {362,  362,  362,  362},
         {502,  425,  284,   99},
         {473,  195, -195, -473},
         {425,  -99, -502, -284},
         {362, -362, -362,  362},
         {284, -502,   99,  425},
         {195, -473,  473, -195},
         { 99, -284,  425, -502}
   };

   PRE_ADD:for (int k=0 ; k < 4 ; ++k ) {
      pa[k] = data[k] + ((i&1)? (int)-data[7-k]:(int)data[7-k]);
   }

   MAC:for (int k=0 ; k < 4 ; ++k ) {
      acc += coeff[i][k] * pa[k];
   }
   return acc;
}

#pragma design
void dct_h(ac_channel<ac_int<8> > &input, ac_channel<memStruct > &mem) {//Memory interfaces must use ac_channel coding style
   memStruct local_mem;//Local struct for temporary array operations
   ac_int<8> buf0[8];//Local storage for one row of input

   ac_int<21> acc0;
   ROW0:for (int i=0; i < 8; ++i ) {
      COPY_ROW0:for (int p=0; p<8; p++)//Copy one row of input into local storage
         buf0[p] = input.read();
      COL0:for (int j=0; j < 8; ++j ) {
         acc0 = mult_add<ac_int<8>,ac_int<9>,ac_int<21> >(buf0,j);
         local_mem.data[j][i] = acc0 >> 5;
      }
   }
   mem.write(local_mem);
}

#pragma design
void dct_v(ac_channel<memStruct > &mem, ac_channel<memStruct > &output) {//Memory interfaces must use ac_channel coding style
   memStruct local_mem;//Local struct for temporary array operations
   memStruct local_output;

   ac_int<16> buf1[8];//Local storage for one row of input
   ac_int<31> acc1;

   local_mem = mem.read();
   COL1:for (int j=0; j < 8; ++j ) {
      COPY_ROW:for (int p=0; p<8; p++)//Copy one row of mem into local storage
         buf1[p] = local_mem.data[j][p];
      ROW1:for (int i=0 ; i < 8; ++i ) {
         acc1 = mult_add<ac_int<16>,ac_int<17>,ac_int<31> >(buf1,i);
         local_output.data[i][j] = acc1 >> 15 ;
      }
   }
   output.write(local_output);

}
// ---------------------------------------------------
// DCT 2D 8x8 Top
void dct(ac_channel<ac_int<8> > &input, ac_channel<memStruct > &output) {//Memory interfaces must use ac_channel coding style
   static ac_channel<memStruct > mem;//Static interconnect channel

    //Top-level design only instantiates hierarchical blocks
   dct_h(input,mem);
   dct_v(mem,output);
}


text:
if config.target_arch not in ['x86', 'x86_64']:
  config.unsupported = True


text:
<!DOCTYPE html>

        <title>Lateral On-Scroll Sliding with jQuery</title>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="Lateral On-Scroll Sliding with jQuery - Timeline Example with CSS3" />
        <meta name="keywords" content="lateral, sides, slide, scroll, jquery, css3, timeline" />
        <meta name="author" content="Codrops" />
        <link rel="shortcut icon" href="../favicon.ico">
        <link rel="stylesheet" type="text/css" href="css/demo.css" />
        <link rel="stylesheet" type="text/css" href="css/style.css" />
        <link href='http://fonts.googleapis.com/css?family=Kelly+Slab' rel='stylesheet' type='text/css' />

                    « Previous Demo: Typography Effects with CSS3 and jQuery

                        Back to the Codrops Article

				Default Demo
				Perspective Demo (Webkit only)

Lateral On-Scroll Sliding with jQuery

Codrops Timeline

				Nov
				Oct
				Sep
				Aug
				Jul
				Jun

November

2011

                        Typography Effects with CSS3 and jQuery

                            November 28, 2011
                            Typography Effects with CSS3 and jQuery

                            November 22, 2011
                            Hover and Click Trigger for Circular Elements with jQuery

                        Hover and Click Trigger for Circular Elements with jQuery

						Elastic Image Slideshow with Thumbnail Preview

                            November 21, 2011
                            Elastic Image Slideshow with Thumbnail Preview

                            November 18, 2011
                            Fullscreen Image Blur Effect with HTML5

                        Fullscreen Image Blur Effect with HTML5

                        Interactive Typography Effects with HTML5

                            November 9, 2011
                            Interactive Typography Effects with HTML5

                        Animated Buttons with CSS3

                            November 7, 2011
                            Animated Buttons with CSS3

                            November 2, 2011
                            Original Hover Effects with CSS3

                        Original Hover Effects with CSS3

October

2011

                            October 31, 2011
                            Fullscreen Image 3D Effect with CSS3 and jQuery

						Fullscreen Image 3D Effect with CSS3 and jQuery

                        Creative CSS3 Animation Menus

                            October 24, 2011
                            Creative CSS3 Animation Menus

                        Blur Menu with CSS3 Transitions

                            October 19, 2011
                            Blur Menu with CSS3 Transitions

                            October 17, 2011
                            Wave Display Effect with jQuery

						Wave Display Effect with jQuery

                        Flexible Slide-to-top Accordion

                            October 12, 2011
                            Flexible Slide-to-top Accordion

                            October 10, 2011
                            Circle Navigation Effect with CSS3

						Circle Navigation Effect with CSS3

                        Draggable Image Boxes Grid

                            October 7, 2011
                            Draggable Image Boxes Grid

September

2011

                            September 30, 2011
                            Scrollbar Visibility with jScrollPane

						Scrollbar Visibility with jScrollPane

                        Multi-level Photo Map

                            September 27, 2011
                            Multi-level Photo Map

                        Responsive Image Gallery with Thumbnail Carousel

                            September 20, 2011
                            Responsive Image Gallery with Thumbnail Carousel

                            September 12, 2011
                            Elastislide - A Responsive jQuery Carousel Plugin

						Elastislide - A Responsive jQuery Carousel Plugin

                        Slicebox - A fresh 3D image slider with graceful fallback

                            September 5, 2011
                            Slicebox - A fresh 3D image slider with graceful fallback

August

2011

                            August 30, 2011
                            Automatic Image Montage with jQuery

						Automatic Image Montage with jQuery

                        Image Zoom Tour with jQuery

                            August 23, 2011
                            Image Zoom Tour with jQuery

                            August 16, 2011
                            Circular Content Carousel with jQuery

						Circular Content Carousel with jQuery

                        Portfolio Image Navigation with jQuery

                            August 9, 2011
                            Portfolio Image Navigation with jQuery

                            August 4, 2011
                            Expanding Fullscreen Grid Portfolio

						Expanding Fullscreen Grid Portfolio

July

2011

                        Content Rotator with jQuery

                            July 29, 2011
                            Content Rotator with jQuery

                            July 22, 2011
                            Vertical Sliding Accordion with jQuery

						Vertical Sliding Accordion with jQuery

                        Animated Text and Icon Menu with jQuery

                            July 12, 2011
                            Animated Text and Icon Menu with jQuery

                            July 5, 2011
                            Fullscreen Slideshow with HTML5 Audio and jQuery

						Fullscreen Slideshow with HTML5 Audio and jQuery

                        Sliding Background Image Menu with jQuery

                            July 3, 2011
                            Sliding Background Image Menu with jQuery

June

2011

                            June 9, 2011
                            Grid Navigation Effects with jQuery

						Grid Navigation Effects with jQuery


text:
<form>
  <input id="dup" type="text" autocomplete="username">
  <input id="dup" type="password" autocomplete="current-password">
</form>


text:
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/i2c.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/err.h>
#include <linux/mutex.h>

/* How many retries on register read error */
#define MAX_RETRIES	5

/*
 * Address to scan
 * Address is fully defined internally and cannot be changed.
 */

static unsigned short normal_i2c[] = { 0x2e, I2C_CLIENT_END };

/*
 * Insmod parameters
 */

I2C_CLIENT_INSMOD_1(w83l785ts);

/*
 * The W83L785TS-S registers
 * Manufacturer ID is 0x5CA3 for Winbond.
 */

#define W83L785TS_REG_MAN_ID1		0x4D
#define W83L785TS_REG_MAN_ID2		0x4C
#define W83L785TS_REG_CHIP_ID		0x4E
#define W83L785TS_REG_CONFIG		0x40
#define W83L785TS_REG_TYPE		0x52
#define W83L785TS_REG_TEMP		0x27
#define W83L785TS_REG_TEMP_OVER		0x53 /* not sure about this one */

/*
 * Conversions
 * The W83L785TS-S uses signed 8-bit values.
 */

#define TEMP_FROM_REG(val)	((val) * 1000)

/*
 * Functions declaration
 */

static int w83l785ts_attach_adapter(struct i2c_adapter *adapter);
static int w83l785ts_detect(struct i2c_adapter *adapter, int address,
	int kind);
static int w83l785ts_detach_client(struct i2c_client *client);
static u8 w83l785ts_read_value(struct i2c_client *client, u8 reg, u8 defval);
static struct w83l785ts_data *w83l785ts_update_device(struct device *dev);

/*
 * Driver data (common to all clients)
 */

static struct i2c_driver w83l785ts_driver = {
	.driver = {
		.name	= "w83l785ts",
	},
	.id		= I2C_DRIVERID_W83L785TS,
	.attach_adapter	= w83l785ts_attach_adapter,
	.detach_client	= w83l785ts_detach_client,
};

/*
 * Client data (each client gets its own)
 */

struct w83l785ts_data {
	struct i2c_client client;
	struct class_device *class_dev;
	struct mutex update_lock;
	char valid; /* zero until following fields are valid */
	unsigned long last_updated; /* in jiffies */

	/* registers values */
	s8 temp[2]; /* 0: input
		       1: critical limit */
};

/*
 * Sysfs stuff
 */

static ssize_t show_temp(struct device *dev, struct device_attribute *devattr,
	char *buf)
{
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	struct w83l785ts_data *data = w83l785ts_update_device(dev);
	return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp[attr->index]));
}

static SENSOR_DEVICE_ATTR(temp1_input, S_IRUGO, show_temp, NULL, 0);
static SENSOR_DEVICE_ATTR(temp1_max, S_IRUGO, show_temp, NULL, 1);

/*
 * Real code
 */

static int w83l785ts_attach_adapter(struct i2c_adapter *adapter)
{
	if (!(adapter->class & I2C_CLASS_HWMON))
		return 0;
	return i2c_probe(adapter, &addr_data, w83l785ts_detect);
}

/*
 * The following function does more than just detection. If detection
 * succeeds, it also registers the new chip.
 */
static int w83l785ts_detect(struct i2c_adapter *adapter, int address, int kind)
{
	struct i2c_client *new_client;
	struct w83l785ts_data *data;
	int err = 0;

	if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA))
		goto exit;

	if (!(data = kzalloc(sizeof(struct w83l785ts_data), GFP_KERNEL))) {
		err = -ENOMEM;
		goto exit;
	}

	/* The common I2C client data is placed right before the
	 * W83L785TS-specific data. */
	new_client = &data->client;
	i2c_set_clientdata(new_client, data);
	new_client->addr = address;
	new_client->adapter = adapter;
	new_client->driver = &w83l785ts_driver;
	new_client->flags = 0;

	/*
	 * Now we do the remaining detection. A negative kind means that
	 * the driver was loaded with no force parameter (default), so we
	 * must both detect and identify the chip (actually there is only
	 * one possible kind of chip for now, W83L785TS-S). A zero kind means
	 * that the driver was loaded with the force parameter, the detection
	 * step shall be skipped. A positive kind means that the driver
	 * was loaded with the force parameter and a given kind of chip is
	 * requested, so both the detection and the identification steps
	 * are skipped.
	 */
	if (kind < 0) { /* detection */
		if (((w83l785ts_read_value(new_client,
		      W83L785TS_REG_CONFIG, 0) & 0x80) != 0x00)
		 || ((w83l785ts_read_value(new_client,
		      W83L785TS_REG_TYPE, 0) & 0xFC) != 0x00)) {
			dev_dbg(&adapter->dev,
				"W83L785TS-S detection failed at 0x%02x.\n",
				address);
			goto exit_free;
		}
	}

	if (kind <= 0) { /* identification */
		u16 man_id;
		u8 chip_id;

		man_id = (w83l785ts_read_value(new_client,
			 W83L785TS_REG_MAN_ID1, 0) << 8) +
			 w83l785ts_read_value(new_client,
			 W83L785TS_REG_MAN_ID2, 0);
		chip_id = w83l785ts_read_value(new_client,
			  W83L785TS_REG_CHIP_ID, 0);

		if (man_id == 0x5CA3) { /* Winbond */
			if (chip_id == 0x70) { /* W83L785TS-S */
				kind = w83l785ts;
			}
		}

		if (kind <= 0) { /* identification failed */
			dev_info(&adapter->dev,
				 "Unsupported chip (man_id=0x%04X, "
				 "chip_id=0x%02X).\n", man_id, chip_id);
			goto exit_free;
		}
	}

	/* We can fill in the remaining client fields. */
	strlcpy(new_client->name, "w83l785ts", I2C_NAME_SIZE);
	data->valid = 0;
	mutex_init(&data->update_lock);

	/* Default values in case the first read fails (unlikely). */
	data->temp[1] = data->temp[0] = 0;

	/* Tell the I2C layer a new client has arrived. */
	if ((err = i2c_attach_client(new_client)))
		goto exit_free;

	/*
	 * Initialize the W83L785TS chip
	 * Nothing yet, assume it is already started.
	 */

	err = device_create_file(&new_client->dev,
				 &sensor_dev_attr_temp1_input.dev_attr);
	if (err)
		goto exit_remove;

	err = device_create_file(&new_client->dev,
				 &sensor_dev_attr_temp1_max.dev_attr);
	if (err)
		goto exit_remove;

	/* Register sysfs hooks */
	data->class_dev = hwmon_device_register(&new_client->dev);
	if (IS_ERR(data->class_dev)) {
		err = PTR_ERR(data->class_dev);
		goto exit_remove;
	}

	return 0;

exit_remove:
	device_remove_file(&new_client->dev,
			   &sensor_dev_attr_temp1_input.dev_attr);
	device_remove_file(&new_client->dev,
			   &sensor_dev_attr_temp1_max.dev_attr);
	i2c_detach_client(new_client);
exit_free:
	kfree(data);
exit:
	return err;
}

static int w83l785ts_detach_client(struct i2c_client *client)
{
	struct w83l785ts_data *data = i2c_get_clientdata(client);
	int err;

	hwmon_device_unregister(data->class_dev);
	device_remove_file(&client->dev,
			   &sensor_dev_attr_temp1_input.dev_attr);
	device_remove_file(&client->dev,
			   &sensor_dev_attr_temp1_max.dev_attr);
	if ((err = i2c_detach_client(client)))
		return err;

	kfree(data);
	return 0;
}

static u8 w83l785ts_read_value(struct i2c_client *client, u8 reg, u8 defval)
{
	int value, i;

	/* Frequent read errors have been reported on Asus boards, so we
	 * retry on read errors. If it still fails (unlikely), return the
	 * default value requested by the caller. */
	for (i = 1; i <= MAX_RETRIES; i++) {
		value = i2c_smbus_read_byte_data(client, reg);
		if (value >= 0) {
			dev_dbg(&client->dev, "Read 0x%02x from register "
				"0x%02x.\n", value, reg);
			return value;
		}
		dev_dbg(&client->dev, "Read failed, will retry in %d.\n", i);
		msleep(i);
	}

	dev_err(&client->dev, "Couldn't read value from register 0x%02x. "
		"Please report.\n", reg);
	return defval;
}

static struct w83l785ts_data *w83l785ts_update_device(struct device *dev)
{
	struct i2c_client *client = to_i2c_client(dev);
	struct w83l785ts_data *data = i2c_get_clientdata(client);

	mutex_lock(&data->update_lock);

	if (!data->valid || time_after(jiffies, data->last_updated + HZ * 2)) {
		dev_dbg(&client->dev, "Updating w83l785ts data.\n");
		data->temp[0] = w83l785ts_read_value(client,
				W83L785TS_REG_TEMP, data->temp[0]);
		data->temp[1] = w83l785ts_read_value(client,
				W83L785TS_REG_TEMP_OVER, data->temp[1]);

		data->last_updated = jiffies;
		data->valid = 1;
	}

	mutex_unlock(&data->update_lock);

	return data;
}

static int __init sensors_w83l785ts_init(void)
{
	return i2c_add_driver(&w83l785ts_driver);
}

static void __exit sensors_w83l785ts_exit(void)
{
	i2c_del_driver(&w83l785ts_driver);
}

MODULE_AUTHOR("Jean Delvare <khali@linux-fr.org>");
MODULE_DESCRIPTION("W83L785TS-S driver");
MODULE_LICENSE("GPL");

module_init(sensors_w83l785ts_init);
module_exit(sensors_w83l785ts_exit);


text:
Difficulty: Medium

https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/

Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

**Example 1:**
```
Given nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.

It doesn't matter what you leave beyond the returned length.
```

**Example 2:**
```
Given nums = [0,0,1,1,1,1,2,3,3],

Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.

It doesn't matter what values are set beyond the returned length.
```

**Clarification:**

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:
```
// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}
```


text:
Axel y Sol

	    	Nosotros

	    	La invitación

	    	La iglesia

	    	El banquete

	    	Calendario

	    	Alojamiento

	    	Sube tus fotos

	    	Unas preguntitas

	    	Deja tu comentario

	    	Otros

	    	Contactos


text:
package cn.wuxia.common.spring.mvc.resolver;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.MapType;

import cn.wuxia.common.bean.MapWapper;
import cn.wuxia.common.spring.mvc.annotation.RequestJsonParam;
import cn.wuxia.common.util.reflection.ReflectionUtil;

/**
 * 解析请求参数json字符串
 *
 * @author songlin.li
 * @since 3.1
 */
@Deprecated
public class RequestJsonParamMethodArgumentResolver extends AbstractNamedValueMethodArgumentResolver implements WebArgumentResolver {

    private ObjectMapper mapper = new ObjectMapper();

    public RequestJsonParamMethodArgumentResolver() {
        super(null);
    }

    public boolean supportsParameter(MethodParameter parameter) {

        if (parameter.hasParameterAnnotation(RequestJsonParam.class)) {
            return true;
        }
        return false;
    }

    @Override
    protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) {
        RequestJsonParam annotation = parameter.getParameterAnnotation(RequestJsonParam.class);
        if (StringUtils.isBlank(annotation.value())) {
            return new RequestJsonParamNamedValueInfo(parameter.getParameterName(), annotation.required());
        } else {
            return new RequestJsonParamNamedValueInfo(annotation.value(), annotation.required());
        }

    }

    @Override
    protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest webRequest) throws Exception {
        RequestJsonParam annotation = parameter.getParameterAnnotation(RequestJsonParam.class);
        String[] paramValues = webRequest.getParameterValues(name);
        Class<?> paramType = parameter.getParameterType();
        if (paramValues == null) {
            return null;

        }

        try {
            if (paramValues.length == 1) {
                String text = paramValues[0];
                Type type = parameter.getGenericParameterType();
                if (MapWapper.class.isAssignableFrom(paramType)) {
                    MapWapper<?, ?> jsonMap = (MapWapper<?, ?>) paramType.newInstance();

                    MapType mapType = (MapType) getJavaType(HashMap.class);

                    if (type instanceof ParameterizedType) {
                        mapType = (MapType) mapType.withKeyType((JavaType) ((ParameterizedType) type).getActualTypeArguments()[0]);
                        mapType = (MapType) mapType.withContentType((JavaType) ((ParameterizedType) type).getActualTypeArguments()[1]);
                    }
                    jsonMap.setInnerMap(mapper.<Map> readValue(text, mapType));
                    return jsonMap;
                }

                JavaType javaType = getJavaType(paramType);

                if (Collection.class.isAssignableFrom(paramType)) {
                    Class genrictype = (Class) ((ParameterizedType) type).getActualTypeArguments()[0];

                    javaType = mapper.getTypeFactory().constructParametricType(Collection.class, genrictype);
                }

                return mapper.readValue(paramValues[0], javaType);
            }

        } catch (Exception e) {
            throw new RuntimeException("Could not read request json parameter", e);
        }

        throw new UnsupportedOperationException(
                "too many request json parameter '" + name + "' for method parameter type [" + paramType + "], only support one json parameter");
    }

    protected JavaType getJavaType(Class<?> clazz) {
        return mapper.constructType(clazz);
        // return TypeFactory.type(clazz);
    }

    @Override
    protected void handleMissingValue(String paramName, MethodParameter parameter) throws ServletException {
        String paramType = parameter.getParameterType().getName();
        throw new ServletRequestBindingException("Missing request json parameter '" + paramName + "' for method parameter type [" + paramType + "]");
    }

    private class RequestJsonParamNamedValueInfo extends NamedValueInfo {

        private RequestJsonParamNamedValueInfo() {
            super("", false, null);
        }

        private RequestJsonParamNamedValueInfo(String name, boolean required) {
            super(name, required, null);
        }
    }

    /**
     * spring 3.1之前
     */
    @Override
    public Object resolveArgument(MethodParameter parameter, NativeWebRequest request) throws Exception {
        if (!supportsParameter(parameter)) {
            return WebArgumentResolver.UNRESOLVED;
        }
        return resolveArgument(parameter, null, request, null);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.zhy.shanbei"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-sdk
        android:minSdkVersion="13"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_logo"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".activity.TxtContentActivity"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Black.NoTitleBar"
            />
        <activity
            android:name=".activity.MainActivity"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.NoTitleBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>

        </activity>
    </application>

</manifest>


text:
namespace llvm {
  class CallSite;
}

namespace swift {
namespace irgen {

class Address;
class Explosion;
class LoadableTypeInfo;
struct WitnessMetadata;

/// A plan for emitting a series of calls.
class CallEmission {
public:
  IRGenFunction &IGF;

private:
  /// The builtin/special arguments to pass to the call.
  SmallVector<llvm::Value*, 8> Args;

  /// The function we're going to call.
  Callee CurCallee;

  unsigned LastArgWritten;

  /// Whether we've emitted the call for the current callee yet.  This
  /// is just for debugging purposes --- e.g. the destructor asserts
  /// that it's true --- but is otherwise derivable from
  /// RemainingArgsForCallee, at least between calls.
  bool EmittedCall;

  void setFromCallee();
  void emitToUnmappedMemory(Address addr);
  void emitToUnmappedExplosion(Explosion &out);
  llvm::CallSite emitCallSite();

public:
  CallEmission(IRGenFunction &IGF, Callee &&callee)
      : IGF(IGF), CurCallee(std::move(callee)) {
    setFromCallee();
  }
  CallEmission(const CallEmission &other) = delete;
  CallEmission(CallEmission &&other);
  CallEmission &operator=(const CallEmission &other) = delete;
  ~CallEmission();

  const Callee &getCallee() const { return CurCallee; }

  SubstitutionList getSubstitutions() const {
    return CurCallee.getSubstitutions();
  }

  /// Set the arguments to the function from an explosion.
  void setArgs(Explosion &arg, WitnessMetadata *witnessMetadata = nullptr);

  void addAttribute(unsigned Index, llvm::Attribute::AttrKind Attr);

  void emitToMemory(Address addr, const LoadableTypeInfo &substResultTI);
  void emitToExplosion(Explosion &out);
};

}
}

#endif


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="se.henkan.ordpek.AddImageActivity">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <TextView
            android:text="@string/add_image_title"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />

        <Button
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:text="Add from gallery"
            android:onClick="addFromGallery"/>

        <Button
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:text="Add from camera"
            android:onClick="addFromCamera"/>

        <Button
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:text="List all images"
            android:onClick="listAllImages"/>

        <TextView
            android:id="@+id/add_text_view"
            android:text="text"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:lines="10"
            android:layout_weight="2"
            android:scrollbars = "vertical"/>

        <ImageView
            android:id="@+id/add_image_view"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:src="@drawable/op_agnes"/>

    </LinearLayout>

</RelativeLayout>


text:
<link rel="import" href="bower_components/core-header-panel/core-header-panel.html">
<link rel="import" href="bower_components/core-toolbar/core-toolbar.html">
<link rel="import" href="bower_components/paper-icon-button/paper-icon-button.html">
<link rel="import" href="bower_components/paper-item/paper-item.html">
<link rel="import" href="bower_components/paper-menu-button/paper-menu-button.html">
<link rel="import" href="bower_components/paper-tabs/paper-tabs.html">
<link rel="import" href="bower_components/paper-tabs/paper-tab.html">

<link rel="import" href="states-cards.html">

<polymer-element name="home-assistant-main" attributes="api">
  <template>

    <core-header-panel fullbleed>

      <core-toolbar class='medium-tall'>

          Home Assistant

        <paper-icon-button icon="refresh" on-click="{{handleRefreshClick}}"></paper-icon-button>
        <paper-icon-button icon="settings-remote"
          on-click="{{handleServiceClick}}"></paper-icon-button>
        <paper-menu-button icon="more-vert" halign="right">
          <paper-item label="Set State">

          </paper-item>
          <paper-item label="Trigger Event">

          </paper-item>
          <paper-item label="Log Out">

          </paper-item>
        </paper-menu-button>

            <paper-tabs id="tabsHolder" noink flex
                        selected="0" on-core-select="{{tabClicked}}">

              <paper-tab>ALL</paper-tab>

              <template repeat="{{state in api.states}}">
                <template if="{{state.isCustomGroup}}">
                  <paper-tab data-entity="{{state.entity_id}}">
                    {{state.entityDisplay}}
                  </paper-tab>
                </template>
              </template>

            </paper-tabs>

      </core-toolbar>

        <states-cards api="{{api}}" filter="{{selectedTab}}"></states-cards>

    </core-header-panel>

  </template>

</polymer-element>