text:
<link rel=StyleSheet Type="text/css" href="style.css">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<title>Magcut.js</title>

A web tool for burst images

Output

Input 1

Input 2

How to Instructions

1

Select multiple pictures from one scene by either select a scene from the Demo-sets or choose from your own photos to edit in the Application

2

Wait until the images are stitched together in the application. For the demo image-sets the homographies are already computed

3

Traverse the multiple images via the mouse scroll wheel. To select one base reference image simply click in the image

4

The difference between the reference image and all other images are computed and highlighted. This allows you to select content to add or remove.  First you can adjust a global threshold by scroll the mouse wheel inside the difference image

5

Click inside a region to adjust that particular region. Once the region is selected the color will change

6

Click the blend button to let the application blend in all selected regions in the reference image

Introduction to Burst

 Burst mode is a good choise when it comes to photographing moving subjects. One example is shooting sports. Sports photography can be hard because sports move fast, the athletes move fast and the fields are big. With the camera in burst mode we can hold down the shutter and pan the camera along when the athletes movement.

Putting the camera settings in to burst mode are good in other situations too.  Animals and children are similar to athletes in the way that the move fast.

You often only get one chance to capture a snapshot and to do this in a situation where many things  happening at ones, to freezing the moment of a dynamic scene when everything looks right can be a harsh task.

The success rate is usually low and therefore photographers need good software to to edit down the number of candidates to do post-processing in. It is here our proposal comes into play.

Magcut is an image editor that let the user rearrange the photographed scene to maximize the visibility or to change the composition. This can be done in several ways either by adding and moving objects or by removing objects within the scene.

Our application is suited for dynamic scenes where objects are moving. It also allows the camera to move slightly within a scene. We assume that the burst of images provided by the user contains some differences. That is, differences between each single image.

Materials

The source code and the data can be found on github in the Link.

Related

The application uses image stitching. Please see The project Image Stitching with HTML5, canvas and JavaScript Demo page
and/or the Source code for more information on stitching.

magcut

	Demo

	App

%*******************************************************************************
%****************************** Forth Chapter *********************************
%*******************************************************************************

\chapter{The Image Editing Tool}

\ifpdf
\graphicspath{{Chapter2/Figs/Raster/}{Chapter2/Figs/PDF/}{Chapter2/Figs/}}
\else
\graphicspath{{Chapter2/Figs/Vector/}{Chapter2/Figs/}}
\fi

\section{Related work}
Previous work have shown why user interaction is important and how the arisen results of research in the related field can be used alongside with user interaction.
\\
\\
In the paper of Barnes, et al[] they clarify some scenarios where user interaction is required to obtain the best result, as for example retargeting algorithms. Several methods currently used by photographers provides a control over the outcome where the user is trying to optimize a set of goals that are known to the user and not to the specific algorithm. So authors (Barnes) (Bai) argues that human interaction is absolutely necessary in order to have a framework for these tools. The cause is that it is only through the user input, the best results can be achieved with current algorithms. Users helps to create a target goal in advance which helps to lead the algorithm in the right direction.

Further more in Barnes et al's paper []. When it comes to Image editing, it is often the case that the user has difficulties to in advance exactly specify his/her objectives. In some cases this may even be impossible. Instead the artistic process of creating the desired image is to use trial and error methods. This is because the user aims to optimize the results with respect to personal criteria that are specific to the images under consideration.

They argue that the photo editing tools to be created must be sufficiently flexible to allow users to carry out various goals, while at the same time the tools must be effective enough to be able to show the results immediately so that the user can make the changes as needed.

\section{Use Cases}
Lets now take a look at what our proposed Image Editing Tool is capable to do by go through a number of use cases that are relevant to use in our application.

\subsection{Example Remove content}

	\begin{figure}
		\def\tabularxcolumn#1{m{#1}}
		\begin{tabularx}{\linewidth}{@{}cXX@{}}
			%[width=\textwidth]
			\begin{tabular}{cc}
				\subfloat[B]{\includegraphics[width=0.35\textwidth]{EandL/P1180179.jpg}} \\  \subfloat[D]{\includegraphics[width=0.35\textwidth]{EandL/P1180179.jpg}}\\
			\end{tabular}
			&
			\subfloat[G]{\includegraphics[width=0.7\textwidth]{EandL/P1180179.jpg}}
		\end{tabularx}
		\caption{Many figures}\label{foo}
	\end{figure}
%\begin{figure}[htbp]
%	\begin{subfigure}{0.35\textwidth}
%		\includegraphics[width=\textwidth]{EandL/P1180178.jpg}
%		\caption{Input 1, the base image} \label{fig:ex1rm_a}
%	\end{subfigure}%
%	\\
%	\begin{subfigure}{0.35\textwidth}
%		\includegraphics[width=\textwidth]{EandL/P1180179.jpg}
%		\caption{Input 2} \label{fig:ex1rm_b}
%	\end{subfigure}%
%	~
%	\begin{subfigure}{0.50\textwidth}
%		\includegraphics[width=\textwidth]{EandL/ut480.png}
%		\caption{Input 2 Rectified and cropped} \label{fig:ex1rm_c}
%	\end{subfigure}
%	\caption{Creation of mosaic}\label{fig:ex1rm}
%\end{figure}


text:
module G5IntegrationsValidations
  module YardiVoyagerInventoryCtaThresholdValidations
    extend ActiveSupport::Concern

    CTAS_FOR_IN_AND_ABOVE_THRESHOLD = %w(reservation online_application)
    CTAS_FOR_BELOW_THRESHOLD = %w(call)

    included do
      include ActiveModel::Validations

      validates(:unit_availability_cta_in_and_above_threshold, {
        inclusion: {in: CTAS_FOR_IN_AND_ABOVE_THRESHOLD}
      })

      validates(:unit_availability_cta_below_threshold, {
        inclusion: {in: CTAS_FOR_BELOW_THRESHOLD}
      })

    end
  end

end

redpajama_set_name: RedPajamaGithub


text:
package org.apache.heron.streamlet.impl;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;

import org.junit.Test;

import org.apache.heron.api.grouping.ShuffleStreamGrouping;
import org.apache.heron.api.topology.TopologyBuilder;
import org.apache.heron.api.utils.Utils;
import org.apache.heron.common.basics.ByteAmount;
import org.apache.heron.resource.TestBasicBolt;
import org.apache.heron.resource.TestBolt;
import org.apache.heron.resource.TestSpout;
import org.apache.heron.resource.TestWindowBolt;
import org.apache.heron.streamlet.Builder;
import org.apache.heron.streamlet.Config;
import org.apache.heron.streamlet.Context;
import org.apache.heron.streamlet.IStreamletBasicOperator;
import org.apache.heron.streamlet.IStreamletRichOperator;
import org.apache.heron.streamlet.IStreamletWindowOperator;
import org.apache.heron.streamlet.KVStreamlet;
import org.apache.heron.streamlet.KeyedWindow;
import org.apache.heron.streamlet.SerializableConsumer;
import org.apache.heron.streamlet.SerializablePredicate;
import org.apache.heron.streamlet.SerializableTransformer;
import org.apache.heron.streamlet.Source;
import org.apache.heron.streamlet.Streamlet;
import org.apache.heron.streamlet.StreamletReducers;
import org.apache.heron.streamlet.WindowConfig;
import org.apache.heron.streamlet.impl.streamlets.ConsumerStreamlet;
import org.apache.heron.streamlet.impl.streamlets.CountByKeyAndWindowStreamlet;
import org.apache.heron.streamlet.impl.streamlets.CountByKeyStreamlet;
import org.apache.heron.streamlet.impl.streamlets.CustomStreamlet;
import org.apache.heron.streamlet.impl.streamlets.FilterStreamlet;
import org.apache.heron.streamlet.impl.streamlets.FlatMapStreamlet;
import org.apache.heron.streamlet.impl.streamlets.GeneralReduceByKeyStreamlet;
import org.apache.heron.streamlet.impl.streamlets.JoinStreamlet;
import org.apache.heron.streamlet.impl.streamlets.KVStreamletShadow;
import org.apache.heron.streamlet.impl.streamlets.KeyByStreamlet;
import org.apache.heron.streamlet.impl.streamlets.MapStreamlet;
import org.apache.heron.streamlet.impl.streamlets.ReduceByKeyAndWindowStreamlet;
import org.apache.heron.streamlet.impl.streamlets.ReduceByKeyStreamlet;
import org.apache.heron.streamlet.impl.streamlets.SourceStreamlet;
import org.apache.heron.streamlet.impl.streamlets.SpoutStreamlet;
import org.apache.heron.streamlet.impl.streamlets.SupplierStreamlet;
import org.apache.heron.streamlet.impl.streamlets.TransformStreamlet;
import org.apache.heron.streamlet.impl.streamlets.UnionStreamlet;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

/**
 * Unit tests for {@link StreamletImpl}
 */
public class StreamletImplTest {

  private Builder builder = Builder.newBuilder();

  @Test
  public void testBasicParams() {
    Streamlet<Double> sample = builder.newSource(() -> Math.random());
    sample.setName("MyStreamlet");
    sample.setNumPartitions(20);
    assertEquals("MyStreamlet", sample.getName());
    assertEquals(20, sample.getNumPartitions());
    sample.setName("AnotherName");
    assertEquals("AnotherName", sample.getName());
    sample.setNumPartitions(10);
    assertEquals(10, sample.getNumPartitions());
    StreamletImpl<Double> bStreamlet = (StreamletImpl<Double>) sample;
    assertFalse(bStreamlet.isBuilt());
    assertEquals(bStreamlet.getChildren().size(), 0);
  }

  @Test
  public void testSplitAndWithStream() {
    Map<String, SerializablePredicate<Double>> splitter = new HashMap();
    splitter.put("all", i -> true);
    splitter.put("positive", i -> i > 0);
    splitter.put("negative", i -> i < 0);

    Streamlet<Double> baseStreamlet = builder.newSource(() -> Math.random());
    // The streamlet should have three output streams after split()
    Streamlet<Double> multiStreams = baseStreamlet.split(splitter);

    // Default stream is used
    Streamlet<Double> positiveStream = multiStreams.withStream("positive");
    Streamlet<Double> negativeStream = multiStreams.withStream("negative");

    Streamlet<Double> allMap = multiStreams.withStream("all").map((num) -> num * 10);
    Streamlet<Double> positiveMap = positiveStream.map((num) -> num * 10);
    Streamlet<Double> negativeMap = negativeStream.map((num) -> num * 10);

    // Original streamlet should still have the default strean id eventhough the id
    // is not available. Other shadow streamlets should have the correct stream ids.
    assertEquals(multiStreams.getStreamId(), Utils.DEFAULT_STREAM_ID);
    assertEquals(positiveStream.getStreamId(), "positive");
    assertEquals(negativeStream.getStreamId(), "negative");

    StreamletImpl<Double> impl = (StreamletImpl<Double>) multiStreams;
    assertEquals(impl.getChildren().size(), 3);

    // Children streamlets should have the right parent stream id
    assertEquals(((MapStreamlet<Double, Double>) allMap).getParent().getStreamId(),
        "all");
    assertEquals(((MapStreamlet<Double, Double>) positiveMap).getParent().getStreamId(),
        "positive");
    assertEquals(((MapStreamlet<Double, Double>) negativeMap).getParent().getStreamId(),
        "negative");
  }

  @Test(expected = RuntimeException.class)
  public void testSplitAndWithWrongStream() {
    Map<String, SerializablePredicate<Double>> splitter = new HashMap();
    splitter.put("all", i -> true);
    splitter.put("positive", i -> i > 0);
    splitter.put("negative", i -> i < 0);

    Streamlet<Double> baseStreamlet = builder.newSource(() -> Math.random());
    // The streamlet should have three output streams after split()
    Streamlet<Double> multiStreams = baseStreamlet.split(splitter);

    // Select a good stream id and a bad stream id
    Streamlet<Double> goodStream = multiStreams.withStream("positive");
    Streamlet<Double> badStream = multiStreams.withStream("wrong-id");
  }

  @Test(expected = RuntimeException.class)
  public void testWithWrongStream() {
    Streamlet<Double> baseStreamlet = builder.newSource(() -> Math.random());
    // Normal Streamlet objects, including sources, have only the default stream id.
    // Selecting any other stream using withStream() should trigger a runtime
    // exception
    Streamlet<Double> badStream = baseStreamlet.withStream("wrong-id");
  }

  @Test
  public void testSupplierStreamlet() {
    Streamlet<Double> streamlet = builder.newSource(() -> Math.random());
    assertTrue(streamlet instanceof SupplierStreamlet);
  }

  @Test
  public void testSourceStreamlet() {
    Streamlet<String> streamlet = builder.newSource(new TestSource());
    assertTrue(streamlet instanceof SourceStreamlet);
  }

  @Test
  public void testSpoutStreamlet() {
    TestSpout spout = new TestSpout();
    Streamlet<Double> streamlet = builder.newSource(spout);
    assertTrue(streamlet instanceof SpoutStreamlet);
  }

  @Test
  @SuppressWarnings("unchecked")
  public void testMapStreamlet() {
    Streamlet<Double> baseStreamlet = builder.newSource(() -> Math.random());
    Streamlet<Double> streamlet = baseStreamlet.setNumPartitions(20).map((num) -> num * 10);
    assertTrue(streamlet instanceof MapStreamlet);
    MapStreamlet<Double, Double> mStreamlet = (MapStreamlet<Double, Double>) streamlet;
    assertEquals(20, mStreamlet.getNumPartitions());
    SupplierStreamlet<Double> supplierStreamlet = (SupplierStreamlet<Double>) baseStreamlet;
    assertEquals(supplierStreamlet.getChildren().size(), 1);
    assertEquals(supplierStreamlet.getChildren().get(0), streamlet);
  }

  @Test
  @SuppressWarnings("unchecked")
  public void testFlatMapStreamlet() {
    Streamlet<Double> baseStreamlet = builder.newSource(() -> Math.random());
    Streamlet<Double> streamlet = baseStreamlet.setNumPartitions(20)
                                               .flatMap((num) -> Arrays.asList(num * 10));
    assertTrue(streamlet instanceof FlatMapStreamlet);
    FlatMapStreamlet<Double, Double> mStreamlet = (FlatMapStreamlet<Double, Double>) streamlet;
    assertEquals(20, mStreamlet.getNumPartitions());
    SupplierStreamlet<Double> supplierStreamlet = (SupplierStreamlet<Double>) baseStreamlet;
    assertEquals(supplierStreamlet.getChildren().size(), 1);
    assertEquals(supplierStreamlet.getChildren().get(0), streamlet);
  }

  @Test
  @SuppressWarnings("unchecked")
  public void testFilterStreamlet() {
    Streamlet<Double> baseStreamlet = builder.newSource(() -> Math.random());
    Streamlet<Double> streamlet = baseStreamlet.setNumPartitions(20).filter((num) -> num != 0);
    assertTrue(streamlet instanceof FilterStreamlet);
    FilterStreamlet<Double> mStreamlet = (FilterStreamlet<Double>) streamlet;
    assertEquals(20, mStreamlet.getNumPartitions());
    SupplierStreamlet<Double> supplierStreamlet = (SupplierStreamlet<Double>) baseStreamlet;
    assertEquals(supplierStreamlet.getChildren().size(), 1);
    assertEquals(supplierStreamlet.getChildren().get(0), streamlet);
  }

  @Test
  @SuppressWarnings("unchecked")
  public void testRepartitionStreamlet() {
    Streamlet<Double> baseStreamlet = builder.newSource(() -> Math.random());
    Streamlet<Double> streamlet = baseStreamlet.setNumPartitions(20).repartition(40);
    assertTrue(streamlet instanceof MapStreamlet);
    MapStreamlet<Double, Double> mStreamlet = (MapStreamlet<Double, Double>) streamlet;
    assertEquals(40, mStreamlet.getNumPartitions());
    SupplierStreamlet<Double> supplierStreamlet = (SupplierStreamlet<Double>) baseStreamlet;
    assertEquals(20, supplierStreamlet.getNumPartitions());
    assertEquals(supplierStreamlet.getChildren().size(), 1);
    assertEquals(supplierStreamlet.getChildren().get(0), streamlet);
  }

  @Test
  @SuppressWarnings("unchecked")
  public void testCloneStreamlet() {
    Streamlet<Double> baseStreamlet = builder.newSource(() -> Math.random());
    List<Streamlet<Double>> streamlets = baseStreamlet.setNumPartitions(20).clone(2);
    assertEquals(streamlets.size(), 2);
    assertTrue(streamlets.get(0) instanceof MapStreamlet);
    assertTrue(streamlets.get(1) instanceof MapStreamlet);
    SupplierStreamlet<Double> supplierStreamlet = (SupplierStreamlet<Double>) baseStreamlet;
    assertEquals(20, supplierStreamlet.getNumPartitions());
    assertEquals(supplierStreamlet.getChildren().size(), 2);
    assertEquals(supplierStreamlet.getChildren(), streamlets);
  }

  @Test
  @SuppressWarnings("unchecked")
  public void testUnionStreamlet() {
    Streamlet<Double> baseStreamlet1 = builder.newSource(() -> Math.random());
    Streamlet<Double> baseStreamlet2 = builder.newSource(() -> Math.random());
    Streamlet<Double> streamlet = baseStreamlet1.union(baseStreamlet2);
    assertTrue(streamlet instanceof UnionStreamlet);
    SupplierStreamlet<Double> supplierStreamlet1 = (SupplierStreamlet<Double>) baseStreamlet1;
    SupplierStreamlet<Double> supplierStreamlet2 = (SupplierStreamlet<Double>) baseStreamlet2;
    assertEquals(supplierStreamlet1.getChildren().size(), 1);
    assertEquals(supplierStreamlet1.getChildren().get(0), streamlet);
    assertEquals(supplierStreamlet2.getChildren().size(), 1);
    assertEquals(supplierStreamlet2.getChildren().get(0), streamlet);
  }

  @Test
  @SuppressWarnings("unchecked")
  public void testTransformStreamlet() {
    Streamlet<Double> baseStreamlet = builder.newSource(() -> Math.random());
    Streamlet<Double> streamlet =
        baseStreamlet.transform(new SerializableTransformer<Double, Double>() {
          @Override
          public void setup(Context context) {

          }

          @Override
          public void transform(Double aDouble, Consumer<Double> consumer) {
            consumer.accept(aDouble);
          }

          @Override
          public void cleanup() {

          }
        });
    assertTrue(streamlet instanceof TransformStreamlet);
    SupplierStreamlet<Double> supplierStreamlet = (SupplierStreamlet<Double>) baseStreamlet;
    assertEquals(supplierStreamlet.getChildren().size(), 1);
    assertEquals(supplierStreamlet.getChildren().get(0), streamlet);
  }

  private class MyBoltOperator extends TestBolt implements IStreamletRichOperator<Double, Double> {
  }

  @Test
  @SuppressWarnings("unchecked")
  public void testCustomStreamletFromBolt() {
    Streamlet<Double> baseStreamlet = builder.newSource(() -> Math.random());
    Streamlet<Double> streamlet = baseStreamlet.setNumPartitions(20)
                                               .applyOperator(new MyBoltOperator());
    assertTrue(streamlet instanceof CustomStreamlet);
    CustomStreamlet<Double, Double> mStreamlet = (CustomStreamlet<Double, Double>) streamlet;
    assertEquals(20, mStreamlet.getNumPartitions());
    SupplierStreamlet<Double> supplierStreamlet = (SupplierStreamlet<Double>) baseStreamlet;
    assertEquals(supplierStreamlet.getChildren().size(), 1);
    assertEquals(supplierStreamlet.getChildren().get(0), streamlet);
  }

  @Test
  @SuppressWarnings("unchecked")
  public void testCustomStreamletWithGrouperFromBolt() throws Exception {
    Streamlet<Double> baseStreamlet = builder.newSource(() -> Math.random());
    Streamlet<Double> streamlet = baseStreamlet.setNumPartitions(20)
                                               .applyOperator(new MyBoltOperator(),
                                                              new ShuffleStreamGrouping());
    assertTrue(streamlet instanceof CustomStreamlet);
    CustomStreamlet<Double, Double> mStreamlet = (CustomStreamlet<Double, Double>) streamlet;
    assertEquals(20, mStreamlet.getNumPartitions());
    SupplierStreamlet<Double> supplierStreamlet = (SupplierStreamlet<Double>) baseStreamlet;
    assertEquals(supplierStreamlet.getChildren().size(), 1);
    assertEquals(supplierStreamlet.getChildren().get(0), streamlet);
  }

  private class MyBasicBoltOperator extends TestBasicBolt
      implements IStreamletBasicOperator<Double, Double> {
  }

  @Test
  @SuppressWarnings("unchecked")
  public void testCustomStreamletFromBasicBolt() {
    Streamlet<Double> baseStreamlet = builder.newSource(() -> Math.random());
    Streamlet<Double> streamlet = baseStreamlet.setNumPartitions(20)
                                               .applyOperator(new MyBasicBoltOperator());
    assertTrue(streamlet instanceof CustomStreamlet);
    CustomStreamlet<Double, Double> mStreamlet =
        (CustomStreamlet<Double, Double>) streamlet;
    assertEquals(20, mStreamlet.getNumPartitions());
    SupplierStreamlet<Double> supplierStreamlet = (SupplierStreamlet<Double>) baseStreamlet;
    assertEquals(supplierStreamlet.getChildren().size(), 1);
    assertEquals(supplierStreamlet.getChildren().get(0), streamlet);
  }

  private class MyWindowBoltOperator extends TestWindowBolt
      implements IStreamletWindowOperator<Double, Double> {
  }

  @Test
  @SuppressWarnings("unchecked")
  public void testCustomStreamletFromWindowBolt() {
    Streamlet<Double> baseStreamlet = builder.newSource(() -> Math.random());
    Streamlet<Double> streamlet = baseStreamlet.setNumPartitions(20)
                                               .applyOperator(new MyWindowBoltOperator());
    assertTrue(streamlet instanceof CustomStreamlet);
    CustomStreamlet<Double, Double> mStreamlet =
        (CustomStreamlet<Double, Double>) streamlet;
    assertEquals(20, mStreamlet.getNumPartitions());
    SupplierStreamlet<Double> supplierStreamlet = (SupplierStreamlet<Double>) baseStreamlet;
    assertEquals(supplierStreamlet.getChildren().size(), 1);
    assertEquals(supplierStreamlet.getChildren().get(0), streamlet);
  }

  @Test
  public void testKeyByStreamlet() {
    Streamlet<Double> baseStreamlet = builder.newSource(() -> Math.random());
    KVStreamlet<Long, Double> streamlet = baseStreamlet.keyBy(x -> Math.round(x));

    assertTrue(streamlet instanceof KVStreamletShadow);
    KVStreamletShadow<Long, Double> mStreamlet =
        (KVStreamletShadow<Long, Double>) streamlet;
    assertTrue(mStreamlet.getReal() instanceof KeyByStreamlet);
    assertEquals(1, mStreamlet.getNumPartitions());
    SupplierStreamlet<Double> supplierStreamlet = (SupplierStreamlet<Double>) baseStreamlet;
    assertEquals(supplierStreamlet.getChildren().size(), 1);
    assertEquals(supplierStreamlet.getChildren().get(0), mStreamlet.getReal());
  }

  @Test
  @SuppressWarnings("unchecked")
  public void testReduceByKeyStreamlet() {
    Streamlet<Double> baseStreamlet = builder.newSource(() -> Math.random());
    KVStreamlet<String, Double> streamlet = baseStreamlet.setNumPartitions(20)
        .<String, Double>reduceByKey(x -> (x > 0) ? "positive" : ((x < 0) ? "negative" : "zero"),
            x -> x,
            StreamletReducers::sum);

    assertTrue(streamlet instanceof KVStreamletShadow);
    KVStreamletShadow<String, Double> mStreamlet =
        (KVStreamletShadow<String, Double>) streamlet;
    assertTrue(mStreamlet.getReal() instanceof ReduceByKeyStreamlet);
    assertEquals(20, mStreamlet.getNumPartitions());
    SupplierStreamlet<Double> supplierStreamlet = (SupplierStreamlet<Double>) baseStreamlet;
    assertEquals(supplierStreamlet.getChildren().size(), 1);
    assertEquals(supplierStreamlet.getChildren().get(0), mStreamlet.getReal());
  }

  @Test
  @SuppressWarnings("unchecked")
  public void testGeneralReduceByKeyStreamlet() {
    Streamlet<Double> baseStreamlet = builder.newSource(() -> Math.random());
    KVStreamlet<String, Double> streamlet = baseStreamlet.setNumPartitions(20)
        .reduceByKey(x -> (x > 0) ? "positive" : ((x < 0) ? "negative" : "zero"),
            0.0,
            StreamletReducers::sum);

    assertTrue(streamlet instanceof KVStreamletShadow);
    KVStreamletShadow<String, Double> mStreamlet =
        (KVStreamletShadow<String, Double>) streamlet;
    assertTrue(mStreamlet.getReal() instanceof GeneralReduceByKeyStreamlet);
    assertEquals(20, mStreamlet.getNumPartitions());
    SupplierStreamlet<Double> supplierStreamlet = (SupplierStreamlet<Double>) baseStreamlet;
    assertEquals(supplierStreamlet.getChildren().size(), 1);
    assertEquals(supplierStreamlet.getChildren().get(0), mStreamlet.getReal());
  }

  @Test
  @SuppressWarnings("unchecked")
  public void testCountByKeyStreamlet() {
    Streamlet<Double> baseStreamlet = builder.newSource(() -> Math.random());
    KVStreamlet<String, Long> streamlet = baseStreamlet.setNumPartitions(20)
        .countByKey(x -> (x > 0) ? "positive" : ((x < 0) ? "negative" : "zero"));

    assertTrue(streamlet instanceof KVStreamletShadow);
    KVStreamletShadow<String, Long> mStreamlet =
        (KVStreamletShadow<String, Long>) streamlet;
    assertTrue(mStreamlet.getReal() instanceof CountByKeyStreamlet);
    assertEquals(20, mStreamlet.getNumPartitions());
    SupplierStreamlet<Double> supplierStreamlet = (SupplierStreamlet<Double>) baseStreamlet;
    assertEquals(supplierStreamlet.getChildren().size(), 1);
    assertEquals(supplierStreamlet.getChildren().get(0), mStreamlet.getReal());
  }

  @Test
  @SuppressWarnings("unchecked")
  public void testCountByKeyAndWindowStreamlet() {
    Streamlet<Double> baseStreamlet = builder.newSource(() -> Math.random());
    KVStreamlet<KeyedWindow<String>, Long> streamlet = baseStreamlet.setNumPartitions(20)
        .countByKeyAndWindow(x -> (x > 0) ? "positive" : ((x < 0) ? "negative" : "zero"),
                             WindowConfig.TumblingCountWindow(10));

    assertTrue(streamlet instanceof KVStreamletShadow);
    KVStreamletShadow<KeyedWindow<String>, Long> mStreamlet =
        (KVStreamletShadow<KeyedWindow<String>, Long>) streamlet;
    assertTrue(mStreamlet.getReal() instanceof CountByKeyAndWindowStreamlet);
    assertEquals(20, mStreamlet.getNumPartitions());
    SupplierStreamlet<Double> supplierStreamlet = (SupplierStreamlet<Double>) baseStreamlet;
    assertEquals(supplierStreamlet.getChildren().size(), 1);
    assertEquals(supplierStreamlet.getChildren().get(0), mStreamlet.getReal());
  }

  @Test
  @SuppressWarnings("unchecked")
  public void testSimpleBuild() throws Exception {
    Streamlet<String> baseStreamlet = builder.newSource(() -> "sa re ga ma");
    baseStreamlet.flatMap(x -> Arrays.asList(x.split(" ")))
                 .reduceByKeyAndWindow(x -> x, x -> 1, WindowConfig.TumblingCountWindow(10),
                     (x, y) -> x + y);
    SupplierStreamlet<String> supplierStreamlet = (SupplierStreamlet<String>) baseStreamlet;
    assertFalse(supplierStreamlet.isBuilt());
    TopologyBuilder topologyBuilder = new TopologyBuilder();
    Set<String> stageNames = new HashSet<>();
    supplierStreamlet.build(topologyBuilder, stageNames);
    assertTrue(supplierStreamlet.allBuilt());
    assertEquals(supplierStreamlet.getChildren().size(), 1);
    assertTrue(supplierStreamlet.getChildren().get(0) instanceof FlatMapStreamlet);
    FlatMapStreamlet<String, String> fStreamlet =
        (FlatMapStreamlet<String, String>) supplierStreamlet.getChildren().get(0);
    assertEquals(fStreamlet.getChildren().size(), 1);
    assertTrue(fStreamlet.getChildren().get(0) instanceof ReduceByKeyAndWindowStreamlet);
    ReduceByKeyAndWindowStreamlet<String, Integer, Integer> rStreamlet =
        (ReduceByKeyAndWindowStreamlet<String, Integer, Integer>) fStreamlet
            .getChildren().get(0);
    assertEquals(rStreamlet.getChildren().size(), 0);
  }

  @Test
  @SuppressWarnings("unchecked")
  public void testComplexBuild() {
    // First source
    Streamlet<String> baseStreamlet1 = builder.newSource(() -> "sa re ga ma");
    Streamlet<String> leftStream =
        baseStreamlet1.flatMap(x -> Arrays.asList(x.split(" ")));

    // Second source
    Streamlet<String> baseStreamlet2 = builder.newSource(() -> "I Love You");
    Streamlet<String> rightStream =
        baseStreamlet2.flatMap(x -> Arrays.asList(x.split(" ")));

    // join
    leftStream.join(rightStream, x -> x, x -> x,
        WindowConfig.TumblingCountWindow(10), (x, y) -> x + y);

    SupplierStreamlet<String> supplierStreamlet1 = (SupplierStreamlet<String>) baseStreamlet1;
    SupplierStreamlet<String> supplierStreamlet2 = (SupplierStreamlet<String>) baseStreamlet2;
    assertFalse(supplierStreamlet1.isBuilt());
    assertFalse(supplierStreamlet2.isBuilt());
    TopologyBuilder topologyBuilder = new TopologyBuilder();
    Set<String> stageNames = new HashSet<>();
    supplierStreamlet1.build(topologyBuilder, stageNames);
    assertTrue(supplierStreamlet1.isBuilt());
    assertFalse(supplierStreamlet1.allBuilt());

    supplierStreamlet2.build(topologyBuilder, stageNames);
    assertTrue(supplierStreamlet1.allBuilt());
    assertTrue(supplierStreamlet2.allBuilt());

    // go over all stuff
    assertEquals(supplierStreamlet1.getChildren().size(), 1);
    assertTrue(supplierStreamlet1.getChildren().get(0) instanceof FlatMapStreamlet);
    FlatMapStreamlet<String, String> fStreamlet =
        (FlatMapStreamlet<String, String>) supplierStreamlet1.getChildren().get(0);
    assertEquals(fStreamlet.getChildren().size(), 1);
    assertTrue(fStreamlet.getChildren().get(0) instanceof JoinStreamlet);
    JoinStreamlet<String, String, String, String> jStreamlet =
        (JoinStreamlet<String, String, String, String>) fStreamlet.getChildren().get(0);
    assertEquals(jStreamlet.getChildren().size(), 0);

    assertEquals(supplierStreamlet2.getChildren().size(), 1);
    assertTrue(supplierStreamlet2.getChildren().get(0) instanceof FlatMapStreamlet);
    fStreamlet =
        (FlatMapStreamlet<String, String>) supplierStreamlet2.getChildren().get(0);
    assertEquals(fStreamlet.getChildren().size(), 1);
    assertTrue(fStreamlet.getChildren().get(0) instanceof JoinStreamlet);
    jStreamlet =
        (JoinStreamlet<String, String, String, String>) fStreamlet.getChildren().get(0);
    assertEquals(jStreamlet.getChildren().size(), 0);
  }

  @Test
  @SuppressWarnings("unchecked")
  public void testCalculatedDefaultStageNames() {
    // create SupplierStreamlet
    Streamlet<String> baseStreamlet = builder.newSource(() ->
        "This is test content");
    SupplierStreamlet<String> supplierStreamlet = (SupplierStreamlet<String>) baseStreamlet;
    assertEquals(supplierStreamlet.getChildren().size(), 0);

    // apply the consumer function
    baseStreamlet.consume((SerializableConsumer<String>) s -> { });

    // build SupplierStreamlet
    assertFalse(supplierStreamlet.isBuilt());
    TopologyBuilder topologyBuilder = new TopologyBuilder();
    Set<String> stageNames = new HashSet<>();
    supplierStreamlet.build(topologyBuilder, stageNames);

    // verify SupplierStreamlet
    assertTrue(supplierStreamlet.allBuilt());
    assertEquals(1, supplierStreamlet.getChildren().size());
    assertTrue(supplierStreamlet.getChildren().get(0) instanceof ConsumerStreamlet);
    assertEquals("consumer1", supplierStreamlet.getChildren().get(0).getName());

    // verify stageNames
    assertEquals(2, stageNames.size());
    List<String> expectedStageNames = Arrays.asList("consumer1", "supplier1");
    assertTrue(stageNames.containsAll(expectedStageNames));

    // verify ConsumerStreamlet
    ConsumerStreamlet<String> consumerStreamlet =
        (ConsumerStreamlet<String>) supplierStreamlet.getChildren().get(0);
    assertEquals(0, consumerStreamlet.getChildren().size());
  }

  @Test
  public void testConfigBuilder() {
    Config defaultConfig = Config.defaultConfig();
    assertEquals(defaultConfig.getSerializer(), Config.Serializer.KRYO);
    assertEquals(0, Double.compare(defaultConfig.getPerContainerCpu(), 1.0));
    assertEquals(defaultConfig.getPerContainerRam(), ByteAmount.fromMegabytes(100).asBytes());
    assertEquals(defaultConfig.getDeliverySemantics(), Config.DeliverySemantics.ATMOST_ONCE);
    Config nonDefaultConfig = Config.newBuilder()
        .setDeliverySemantics(Config.DeliverySemantics.EFFECTIVELY_ONCE)
        .setSerializer(Config.Serializer.JAVA)
        .setPerContainerCpu(3.5)
        .setPerContainerRamInGigabytes(10)
        .build();
    assertEquals(nonDefaultConfig.getDeliverySemantics(),
        Config.DeliverySemantics.EFFECTIVELY_ONCE);
    assertEquals(nonDefaultConfig.getSerializer(), Config.Serializer.JAVA);
    assertEquals(nonDefaultConfig.getPerContainerRamAsGigabytes(), 10);
    assertEquals(nonDefaultConfig.getPerContainerRamAsMegabytes(), 1024 * 10);
    assertEquals(0, Double.compare(nonDefaultConfig.getPerContainerCpu(), 3.5));
  }

  @Test
  public void testDefaultStreamletNameIfNotSet() {
    // create SupplierStreamlet
    Streamlet<String> baseStreamlet = builder.newSource(() ->
        "This is test content");
    SupplierStreamlet<String> supplierStreamlet = (SupplierStreamlet<String>) baseStreamlet;
    Set<String> stageNames = new HashSet<>();

    // set default name by streamlet name prefix
    supplierStreamlet.setDefaultNameIfNone(
        StreamletImpl.StreamletNamePrefix.SUPPLIER, stageNames);

    // verify stageNames
    assertEquals(1, stageNames.size());
    assertTrue(stageNames.containsAll(Arrays.asList("supplier1")));
  }

  @Test
  public void testStreamletNameIfAlreadySet() {
    String supplierName = "MyStringSupplier";
    // create SupplierStreamlet
    Streamlet<String> baseStreamlet = builder.newSource(() ->
        "This is test content");
    SupplierStreamlet<String> supplierStreamlet = (SupplierStreamlet<String>) baseStreamlet;
    supplierStreamlet.setName(supplierName);
    Set<String> stageNames = new HashSet<>();

    // set default name by streamlet name prefix
    supplierStreamlet.setDefaultNameIfNone(
        StreamletImpl.StreamletNamePrefix.SUPPLIER, stageNames);

    // verify stageNames
    assertEquals(1, stageNames.size());
    assertTrue(stageNames.containsAll(Arrays.asList(supplierName)));
  }

  @Test(expected = RuntimeException.class)
  public void testStreamletNameIfDuplicateNameIsSet() {
    // create SupplierStreamlet
    Streamlet<String> baseStreamlet = builder.newSource(() ->
        "This is test content");

    SupplierStreamlet<String> supplierStreamlet = (SupplierStreamlet<String>) baseStreamlet;

    // set duplicate streamlet name and expect thrown exception
    supplierStreamlet
        .map((content) -> content.toUpperCase()).setName("MyMapStreamlet")
        .map((content) -> content + "_test_suffix").setName("MyMapStreamlet");

    // build SupplierStreamlet
    assertFalse(supplierStreamlet.isBuilt());
    TopologyBuilder topologyBuilder = new TopologyBuilder();
    Set<String> stageNames = new HashSet<>();
    supplierStreamlet.build(topologyBuilder, stageNames);
  }

  @Test
  public void testSetNameWithInvalidValues() {
    Streamlet<Double> streamlet = builder.newSource(() -> Math.random());
    Function<String, Streamlet<Double>> function = streamlet::setName;
    testByFunction(function, null);
    testByFunction(function, "");
    testByFunction(function, "  ");
  }

  @Test(expected = IllegalArgumentException.class)
  public void testSetNumPartitionsWithInvalidValue() {
    Streamlet<Double> streamlet = builder.newSource(() -> Math.random());
    streamlet.setNumPartitions(0);
  }

  @Test(expected = IllegalArgumentException.class)
  public void testWithStreamWithInvalidValue() {
    Streamlet<Double> baseStreamlet = builder.newSource(() -> Math.random());
    baseStreamlet.withStream("");
  }

  @Test(expected = IllegalArgumentException.class)
  @SuppressWarnings("unchecked")
  public void testCloneStreamletWithInvalidNumberOfClone() {
    Streamlet<Double> baseStreamlet = builder.newSource(() -> Math.random());
    baseStreamlet.setNumPartitions(20).clone(0);
  }

  private void testByFunction(Function<String, Streamlet<Double>> function, String sName) {
    try {
      function.apply(sName);
      fail("Should have thrown an IllegalArgumentException because streamlet name is invalid");
    } catch (IllegalArgumentException e) {
      assertEquals("Streamlet name cannot be null/blank", e.getMessage());
    }
  }

  private class TestSource implements Source<String> {

    private List<String> list;
    @Override
    public void setup(Context context) {
      list = Arrays.asList("aa", "bb", "cc");
    }

    @Override
    public Collection<String> get() {
      return list;
    }

    @Override
    public void cleanup() {
      list.clear();
    }
  }

}


text:
package org.thingsboard.server.common.data.device.data;

public enum  PowerMode {
    PSM, DRX, E_DRX
}


text:
from collections import namedtuple
from copy import deepcopy
from functools import partial

from jax import random
import jax.numpy as jnp
from jax.tree_util import register_pytree_node, tree_flatten, tree_unflatten

import numpyro
import numpyro.distributions as dist
from numpyro.primitives import mutable as numpyro_mutable

__all__ = [
    "flax_module",
    "haiku_module",
    "random_flax_module",
    "random_haiku_module",
]

def flax_module(
    name, nn_module, *args, input_shape=None, apply_rng=None, mutable=None, **kwargs
):
    """
    Declare a :mod:`~flax` style neural network inside a
    model so that its parameters are registered for optimization via
    :func:`~numpyro.primitives.param` statements.

    Given a flax ``nn_module``, in flax to evaluate the module with
    a given set of parameters, we use: ``nn_module.apply(params, x)``.
    In a NumPyro model, the pattern will be::

        net = flax_module("net", nn_module)
        y = net(x)

    or with dropout layers::

        net = flax_module("net", nn_module, apply_rng=["dropout"])
        rng_key = numpyro.prng_key()
        y = net(x, rngs={"dropout": rng_key})

    :param str name: name of the module to be registered.
    :param flax.linen.Module nn_module: a `flax` Module which has .init and .apply methods
    :param args: optional arguments to initialize flax neural network
        as an alternative to `input_shape`
    :param tuple input_shape: shape of the input taken by the
        neural network.
    :param list apply_rng: A list to indicate which extra rng _kinds_ are needed for
        ``nn_module``. For example, when ``nn_module`` includes dropout layers, we
        need to set ``apply_rng=["dropout"]``. Defaults to None, which means no extra
        rng key is needed. Please see
        `Flax Linen Intro <https://flax.readthedocs.io/en/latest/notebooks/linen_intro.html#Invoking-Modules>`_
        for more information in how Flax deals with stochastic layers like dropout.
    :param list mutable: A list to indicate mutable states of ``nn_module``. For example,
        if your module has BatchNorm layer, we will need to define ``mutable=["batch_stats"]``.
        See the above `Flax Linen Intro` tutorial for more information.
    :param kwargs: optional keyword arguments to initialize flax neural network
        as an alternative to `input_shape`
    :return: a callable with bound parameters that takes an array
        as an input and returns the neural network transformed output
        array.
    """
    try:
        import flax  # noqa: F401
    except ImportError as e:
        raise ImportError(
            "Looking like you want to use flax to declare "
            "nn modules. This is an experimental feature. "
            "You need to install `flax` to be able to use this feature. "
            "It can be installed with `pip install flax`."
        ) from e
    module_key = name + "$params"
    nn_params = numpyro.param(module_key)

    if mutable:
        nn_state = numpyro_mutable(name + "$state")
        assert nn_state is None or isinstance(nn_state, dict)
        assert (nn_state is None) == (nn_params is None)

    if nn_params is None:
        # feed in dummy data to init params
        args = (jnp.ones(input_shape),) if input_shape is not None else args
        rng_key = numpyro.prng_key()
        # split rng_key into a dict of rng_kind: rng_key
        rngs = {}
        if apply_rng:
            assert isinstance(apply_rng, list)
            for kind in apply_rng:
                rng_key, subkey = random.split(rng_key)
                rngs[kind] = subkey
        rngs["params"] = rng_key

        nn_vars = flax.core.unfreeze(nn_module.init(rngs, *args, **kwargs))
        if "params" not in nn_vars:
            raise ValueError(
                "Your nn_module does not have any parameter. Currently, it is not"
                " supported in NumPyro. Please make a github issue if you need"
                " that feature."
            )
        nn_params = nn_vars["params"]
        if mutable:
            nn_state = {k: v for k, v in nn_vars.items() if k != "params"}
            assert set(mutable) == set(nn_state)
            numpyro_mutable(name + "$state", nn_state)
        # make sure that nn_params keep the same order after unflatten
        params_flat, tree_def = tree_flatten(nn_params)
        nn_params = tree_unflatten(tree_def, params_flat)
        numpyro.param(module_key, nn_params)

    def apply_with_state(params, *args, **kwargs):
        params = {"params": params, **nn_state}
        out, new_state = nn_module.apply(params, mutable=mutable, *args, **kwargs)
        nn_state.update(**new_state)
        return out

    def apply_without_state(params, *args, **kwargs):
        return nn_module.apply({"params": params}, *args, **kwargs)

    apply_fn = apply_with_state if mutable else apply_without_state
    return partial(apply_fn, nn_params)

def haiku_module(name, nn_module, *args, input_shape=None, apply_rng=False, **kwargs):
    """
    Declare a :mod:`~haiku` style neural network inside a
    model so that its parameters are registered for optimization via
    :func:`~numpyro.primitives.param` statements.

    Given a haiku ``nn_module``, in haiku to evaluate the module with
    a given set of parameters, we use: ``nn_module.apply(params, None, x)``.
    In a NumPyro model, the pattern will be::

        net = haiku_module("net", nn_module)
        y = net(x)  # or y = net(rng_key, x)

    or with dropout layers::

        net = haiku_module("net", nn_module, apply_rng=True)
        rng_key = numpyro.prng_key()
        y = net(rng_key, x)

    :param str name: name of the module to be registered.
    :param nn_module: a `haiku` Module which has .init and .apply methods
    :type nn_module: haiku.Transformed or haiku.TransformedWithState
    :param args: optional arguments to initialize flax neural network
        as an alternative to `input_shape`
    :param tuple input_shape: shape of the input taken by the
        neural network.
    :param bool apply_rng: A flag to indicate if the returned callable requires
        an rng argument (e.g. when ``nn_module`` includes dropout layers). Defaults
        to False, which means no rng argument is needed. If this is True, the signature
        of the returned callable ``nn = haiku_module(..., apply_rng=True)`` will be
        ``nn(rng_key, x)`` (rather than ``nn(x)``).
    :param kwargs: optional keyword arguments to initialize flax neural network
        as an alternative to `input_shape`
    :return: a callable with bound parameters that takes an array
        as an input and returns the neural network transformed output
        array.
    """
    try:
        import haiku as hk  # noqa: F401
    except ImportError as e:
        raise ImportError(
            "Looking like you want to use haiku to declare "
            "nn modules. This is an experimental feature. "
            "You need to install `haiku` to be able to use this feature. "
            "It can be installed with `pip install dm-haiku`."
        ) from e

    if not apply_rng:
        nn_module = hk.without_apply_rng(nn_module)

    module_key = name + "$params"
    nn_params = numpyro.param(module_key)
    with_state = isinstance(nn_module, hk.TransformedWithState)
    if with_state:
        nn_state = numpyro_mutable(name + "$state")
        assert nn_state is None or isinstance(nn_state, dict)
        assert (nn_state is None) == (nn_params is None)

    if nn_params is None:
        args = (jnp.ones(input_shape),) if input_shape is not None else args
        # feed in dummy data to init params
        rng_key = numpyro.prng_key()
        if with_state:
            nn_params, nn_state = nn_module.init(rng_key, *args, **kwargs)
            nn_state = dict(nn_state)
            numpyro_mutable(name + "$state", nn_state)
        else:
            nn_params = nn_module.init(rng_key, *args, **kwargs)
        # haiku init returns an immutable dict
        nn_params = hk.data_structures.to_mutable_dict(nn_params)
        # we cast it to a mutable one to be able to set priors for parameters
        # make sure that nn_params keep the same order after unflatten
        params_flat, tree_def = tree_flatten(nn_params)
        nn_params = tree_unflatten(tree_def, params_flat)
        numpyro.param(module_key, nn_params)

    def apply_with_state(params, *args, **kwargs):
        out, new_state = nn_module.apply(params, nn_state, *args, **kwargs)
        nn_state.update(**new_state)
        return out

    apply_fn = apply_with_state if with_state else nn_module.apply
    return partial(apply_fn, nn_params)

# register an "empty" parameter which only stores its shape
# so that the optimizer can skip optimize this parameter, while
# it still provides shape information for priors
ParamShape = namedtuple("ParamShape", ["shape"])
register_pytree_node(
    ParamShape, lambda x: ((None,), x.shape), lambda shape, x: ParamShape(shape)
)

def _update_params(params, new_params, prior, prefix=""):
    """
    A helper to recursively set prior to new_params.
    """
    for name, item in params.items():
        flatten_name = ".".join([prefix, name]) if prefix else name
        if isinstance(item, dict):
            assert not isinstance(prior, dict) or flatten_name not in prior
            new_item = new_params[name]
            _update_params(item, new_item, prior, prefix=flatten_name)
        elif (not isinstance(prior, dict)) or flatten_name in prior:
            if isinstance(params[name], ParamShape):
                param_shape = params[name].shape
            else:
                param_shape = jnp.shape(params[name])
                params[name] = ParamShape(param_shape)
            if isinstance(prior, dict):
                d = prior[flatten_name]
            elif callable(prior) and not isinstance(prior, dist.Distribution):
                d = prior(flatten_name, param_shape)
            else:
                d = prior
            param_batch_shape = param_shape[: len(param_shape) - d.event_dim]
            # XXX: here we set all dimensions of prior to event dimensions.
            new_params[name] = numpyro.sample(
                flatten_name, d.expand(param_batch_shape).to_event()
            )

def random_flax_module(
    name,
    nn_module,
    prior,
    *args,
    input_shape=None,
    apply_rng=None,
    mutable=None,
    **kwargs
):
    """
    A primitive to place a prior over the parameters of the Flax module `nn_module`.

    .. note::
        Parameters of a Flax module are stored in a nested dict. For example,
        the module `B` defined as follows::

            class A(flax.linen.Module):
                @flax.linen.compact
                def __call__(self, x):
                    return nn.Dense(1, use_bias=False, name='dense')(x)

            class B(flax.linen.Module):
                @flax.linen.compact
                def __call__(self, x):
                    return A(name='inner')(x)

        has parameters `{'inner': {'dense': {'kernel': param_value}}}`. In the argument
        `prior`, to specify `kernel` parameter, we join the path to it using dots:
        `prior={"inner.dense.kernel": param_prior}`.

    :param str name: name of NumPyro module
    :param flax.linen.Module: the module to be registered with NumPyro
    :param prior: a NumPyro distribution or a Python dict with parameter names as keys and
        respective distributions as values. For example::

            net = random_flax_module("net",
                                     flax.linen.Dense(features=1),
                                     prior={"bias": dist.Cauchy(), "kernel": dist.Normal()},
                                     input_shape=(4,))

        Alternatively, we can use a callable. For example the following are equivalent::

            prior=(lambda name, shape: dist.Cauchy() if name == "bias" else dist.Normal())
            prior={"bias": dist.Cauchy(), "kernel": dist.Normal()}

    :type prior: dict, ~numpyro.distributions.Distribution or callable
    :param args: optional arguments to initialize flax neural network
        as an alternative to `input_shape`
    :param tuple input_shape: shape of the input taken by the neural network.
    :param list apply_rng: A list to indicate which extra rng _kinds_ are needed for
        ``nn_module``. For example, when ``nn_module`` includes dropout layers, we
        need to set ``apply_rng=["dropout"]``. Defaults to None, which means no extra
        rng key is needed. Please see
        `Flax Linen Intro <https://flax.readthedocs.io/en/latest/notebooks/linen_intro.html#Invoking-Modules>`_
        for more information in how Flax deals with stochastic layers like dropout.
    :param list mutable: A list to indicate mutable states of ``nn_module``. For example,
        if your module has BatchNorm layer, we will need to define ``mutable=["batch_stats"]``.
        See the above `Flax Linen Intro` tutorial for more information.
    :param kwargs: optional keyword arguments to initialize flax neural network
        as an alternative to `input_shape`
    :returns: a sampled module

    **Example**

    .. doctest::

        # NB: this example is ported from https://github.com/ctallec/pyvarinf/blob/master/main_regression.ipynb
        >>> import numpy as np; np.random.seed(0)
        >>> import tqdm
        >>> from flax import linen as nn
        >>> from jax import jit, random
        >>> import numpyro
        >>> import numpyro.distributions as dist
        >>> from numpyro.contrib.module import random_flax_module
        >>> from numpyro.infer import Predictive, SVI, TraceMeanField_ELBO, autoguide, init_to_feasible
        ...
        >>> class Net(nn.Module):
        ...     n_units: int
        ...
        ...     @nn.compact
        ...     def __call__(self, x):
        ...         x = nn.Dense(self.n_units)(x[..., None])
        ...         x = nn.relu(x)
        ...         x = nn.Dense(self.n_units)(x)
        ...         x = nn.relu(x)
        ...         mean = nn.Dense(1)(x)
        ...         rho = nn.Dense(1)(x)
        ...         return mean.squeeze(), rho.squeeze()
        ...
        >>> def generate_data(n_samples):
        ...     x = np.random.normal(size=n_samples)
        ...     y = np.cos(x * 3) + np.random.normal(size=n_samples) * np.abs(x) / 2
        ...     return x, y
        ...
        >>> def model(x, y=None, batch_size=None):
        ...     module = Net(n_units=32)
        ...     net = random_flax_module("nn", module, dist.Normal(0, 0.1), input_shape=())
        ...     with numpyro.plate("batch", x.shape[0], subsample_size=batch_size):
        ...         batch_x = numpyro.subsample(x, event_dim=0)
        ...         batch_y = numpyro.subsample(y, event_dim=0) if y is not None else None
        ...         mean, rho = net(batch_x)
        ...         sigma = nn.softplus(rho)
        ...         numpyro.sample("obs", dist.Normal(mean, sigma), obs=batch_y)
        ...
        >>> n_train_data = 5000
        >>> x_train, y_train = generate_data(n_train_data)
        >>> guide = autoguide.AutoNormal(model, init_loc_fn=init_to_feasible)
        >>> svi = SVI(model, guide, numpyro.optim.Adam(5e-3), TraceMeanField_ELBO())
        >>> n_iterations = 3000
        >>> svi_result = svi.run(random.PRNGKey(0), n_iterations, x_train, y_train, batch_size=256)
        >>> params, losses = svi_result.params, svi_result.losses
        >>> n_test_data = 100
        >>> x_test, y_test = generate_data(n_test_data)
        >>> predictive = Predictive(model, guide=guide, params=params, num_samples=1000)
        >>> y_pred = predictive(random.PRNGKey(1), x_test[:100])["obs"].copy()
        >>> assert losses[-1] < 3000
        >>> assert np.sqrt(np.mean(np.square(y_test - y_pred))) < 1
    """
    nn = flax_module(
        name,
        nn_module,
        *args,
        input_shape=input_shape,
        apply_rng=apply_rng,
        mutable=mutable,
        **kwargs
    )
    params = nn.args[0]
    new_params = deepcopy(params)
    with numpyro.handlers.scope(prefix=name):
        _update_params(params, new_params, prior)
    nn_new = partial(nn.func, new_params, *nn.args[1:], **nn.keywords)
    return nn_new

def random_haiku_module(
    name, nn_module, prior, *args, input_shape=None, apply_rng=False, **kwargs
):
    """
    A primitive to place a prior over the parameters of the Haiku module `nn_module`.

    :param str name: name of NumPyro module
    :param nn_module: the module to be registered with NumPyro
    :type nn_module: haiku.Transformed or haiku.TransformedWithState
    :param prior: a NumPyro distribution or a Python dict with parameter names as keys and
        respective distributions as values. For example::

            net = random_haiku_module("net",
                                      haiku.transform(lambda x: hk.Linear(1)(x)),
                                      prior={"linear.b": dist.Cauchy(), "linear.w": dist.Normal()},
                                      input_shape=(4,))

        Alternatively, we can use a callable. For example the following are equivalent::

            prior=(lambda name, shape: dist.Cauchy() if name.startswith("b") else dist.Normal())
            prior={"bias": dist.Cauchy(), "kernel": dist.Normal()}

    :type prior: dict, ~numpyro.distributions.Distribution or callable
    :param args: optional arguments to initialize flax neural network
        as an alternative to `input_shape`
    :param tuple input_shape: shape of the input taken by the neural network.
    :param bool apply_rng: A flag to indicate if the returned callable requires
        an rng argument (e.g. when ``nn_module`` includes dropout layers). Defaults
        to False, which means no rng argument is needed. If this is True, the signature
        of the returned callable ``nn = haiku_module(..., apply_rng=True)`` will be
        ``nn(rng_key, x)`` (rather than ``nn(x)``).
    :param kwargs: optional keyword arguments to initialize flax neural network
        as an alternative to `input_shape`
    :returns: a sampled module
    """
    nn = haiku_module(
        name, nn_module, *args, input_shape=input_shape, apply_rng=apply_rng, **kwargs
    )
    params = nn.args[0]
    new_params = deepcopy(params)
    with numpyro.handlers.scope(prefix=name):
        _update_params(params, new_params, prior)
    nn_new = partial(nn.func, new_params, *nn.args[1:], **nn.keywords)
    return nn_new


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>OperationOptions | mongodb</title>
	<meta name="description" content="Documentation for mongodb">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					mongodb

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-externals" checked />
							Externals

					Menu

					mongodb

					OperationOptions

Interface OperationOptions

Hierarchy

						BSONSerializeOptions

								OperationOptions

										CommandOperationOptions

Index

Properties

bson<wbr>Reg<wbr>Exp

bypass<wbr>Pinning<wbr>Check

check<wbr>Keys

fields<wbr>AsRaw

ignore<wbr>Undefined

promote<wbr>Buffers

promote<wbr>Longs

promote<wbr>Values

raw

read<wbr>Preference

serialize<wbr>Functions

session

will<wbr>Retry<wbr>Writes

Properties

Optional bson<wbr>Reg<wbr>Exp

bson<wbr>Reg<wbr>Exp: boolean

Inherited from BSONSerializeOptions.bsonRegExp

Defined in node_modules/bson/bson.d.ts:314

return BSON regular expressions as BSONRegExp instances.

Optional bypass<wbr>Pinning<wbr>Check

bypass<wbr>Pinning<wbr>Check: boolean

Defined in src/operations/operation.ts:33

internal

Hints to executeOperation that this operation should not unpin on an ended transaction

Optional check<wbr>Keys

check<wbr>Keys: boolean

Inherited from BSONSerializeOptions.checkKeys

Defined in node_modules/bson/bson.d.ts:920

the serializer will check if keys are valid.

Optional fields<wbr>AsRaw

fields<wbr>AsRaw: Document

Inherited from BSONSerializeOptions.fieldsAsRaw

Defined in node_modules/bson/bson.d.ts:312

allow to specify if there what fields we wish to return as unserialized raw buffer.

Optional ignore<wbr>Undefined

ignore<wbr>Undefined: boolean

Inherited from BSONSerializeOptions.ignoreUndefined

Defined in node_modules/bson/bson.d.ts:924

serialize will not emit undefined fields (default:true)

Optional promote<wbr>Buffers

promote<wbr>Buffers: boolean

Inherited from BSONSerializeOptions.promoteBuffers

Defined in node_modules/bson/bson.d.ts:308

when deserializing a Binary will return it as a node.js Buffer instance.

Optional promote<wbr>Longs

promote<wbr>Longs: boolean

Inherited from BSONSerializeOptions.promoteLongs

Defined in node_modules/bson/bson.d.ts:306

when deserializing a Long will fit it into a Number if it's smaller than 53 bits

Optional promote<wbr>Values

promote<wbr>Values: boolean

Inherited from BSONSerializeOptions.promoteValues

Defined in node_modules/bson/bson.d.ts:310

when deserializing will promote BSON values to their Node.js closest equivalent types.

Optional raw

raw: boolean

Inherited from BSONSerializeOptions.raw

Defined in src/bson.ts:56

Return BSON filled buffers from operations

Optional read<wbr>Preference

read<wbr>Preference: ReadPreferenceLike

Defined in src/operations/operation.ts:30

The preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest).

Optional serialize<wbr>Functions

serialize<wbr>Functions: boolean

Inherited from BSONSerializeOptions.serializeFunctions

Defined in node_modules/bson/bson.d.ts:922

serialize the javascript functions (default:false).

Optional session

session: ClientSession

Defined in src/operations/operation.ts:26

Specify ClientSession for this command

Optional will<wbr>Retry<wbr>Writes

will<wbr>Retry<wbr>Writes: boolean

Defined in src/operations/operation.ts:27

						Exports

						Operation<wbr>Options

								bson<wbr>Reg<wbr>Exp

								bypass<wbr>Pinning<wbr>Check

								check<wbr>Keys

								fields<wbr>AsRaw

								ignore<wbr>Undefined

								promote<wbr>Buffers

								promote<wbr>Longs

								promote<wbr>Values

								raw

								read<wbr>Preference

								serialize<wbr>Functions

								session

								will<wbr>Retry<wbr>Writes

Legend

Constructor

Property

Method

Accessor

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Constructor

Property

Method

Private property

Private method

Static property

Static method

Generated using TypeDoc


text:
package com.gemstone.gemfire.internal.cache.xmlcache;

import java.util.HashSet;
import java.util.Properties;

import com.gemstone.gemfire.i18n.LogWriterI18n;
import com.gemstone.gemfire.internal.i18n.LocalizedStrings;

/**
 * Property resolver for resolving ${} like strings with system or Gemfire
 * properties in Cache.xml
 *
 * @author Shobhit Agarwal
 * @since 6.6
 */
public class CacheXmlPropertyResolver implements PropertyResolver{

  LogWriterI18n logWriter;

  /**
   * Would not throw any exception {@link IllegalArgumentException} if property
   * could not be resolved
   */
  private boolean ignoreUnresolvedProperties = false;

  /** Would not throw any exception if property could not be resolved */
  private int propertyOverridden = SYSTEM_PROPERTIES_OVERRIDE;

  private CacheXmlPropertyResolverHelper helper = null;

  /**
   * A properties object to hold all user specified properties passed through
   * .properties file or passed as {@link Properties} objects. It will be set
   * by CacheXmlParser if gemfire.properties has to be included during
   * replacement.
   */
  private Properties props = null;

  public CacheXmlPropertyResolver(boolean ignoreUnresolvedProperties,
      int propertyOverridden, Properties props) {
    super();
    this.ignoreUnresolvedProperties = ignoreUnresolvedProperties;
    this.propertyOverridden = propertyOverridden;
    this.props = props;
  }

  public int getPropertyOverridden() {
    return propertyOverridden;
  }

  /**
   * Sets propertyOverridden with one of the constants specified in
   * this {@link CacheXmlPropertyResolver} class.
   *
   * @param propertyOverridden
   */
  public void setPropertyOverridden(int propertyOverridden) {
    this.propertyOverridden = propertyOverridden;
  }

  public void setIgnoreUnresolvedProperties(boolean ignoreUnresolvedProperties) {
    this.ignoreUnresolvedProperties = ignoreUnresolvedProperties;
  }

  public boolean isIgnoreUnresolvedProperties() {
    return ignoreUnresolvedProperties;
  }

  /**
   * Resolves the given property string either from system properties or given
   * properties. and returns the replacement of the property found in available
   * properties. If no string replacement is found then {@link IllegalArgumentException}
   * would be thrown based on ignoreUnresolvedProperties flag being set by
   * {@link CacheXmlParser}.
   *
   * @param replaceString
   * @return resolvedString
   */
  public String resolveReplaceString(String replaceString) {
    String replacement = null;

    //Get System property first.
    replacement = System.getProperty(replaceString);

    //Override system property if replacement is null or we want to override system property.
    if((replacement == null || getPropertyOverridden() == SYSTEM_PROPERTIES_OVERRIDE) && props != null){
      String userDefined = props.getProperty(replaceString);
      if(userDefined != null){
        replacement = userDefined;
      }
    }
    return replacement;
  }

  /**
   * @param stringWithPrefixAndSuffix
   * @param prefix
   * @param suffix
   * @return string
   */
  public String processUnresolvableString(String stringWithPrefixAndSuffix, String prefix, String suffix){
    String resolvedString = null;
    try{
      if (helper == null){
        helper = new CacheXmlPropertyResolverHelper(prefix, suffix);
      }
      /** A resolvedString can be same as stringWithPrefixAndSuffix if
       * ignoreUnresolvedProperties is set true and we just return it as is.
       */
      resolvedString = helper.parseResolvablePropString(stringWithPrefixAndSuffix, this, new HashSet<String>());
    } catch (IllegalArgumentException e) {
      if(ignoreUnresolvedProperties) {
        //Do Nothing
      } else {
        if(getLogWriter() != null) {
          logWriter.error(LocalizedStrings.CacheXmlPropertyResolver_UNSEROLVAVLE_STRING_FORMAT_ERROR__0, stringWithPrefixAndSuffix);
        } else {
          throw e;
        }
      }
    }
    return resolvedString;
  }

  public LogWriterI18n getLogWriter() {
    return logWriter;
  }

  public void setLogWriter(LogWriterI18n logWriter) {
    this.logWriter = logWriter;
  }

  public void setProps(Properties props) {
    this.props = props;
  }

  public String processUnresolvableString(String stringWithPrefixAndSuffix) {
    return processUnresolvableString(stringWithPrefixAndSuffix, null, null);
  }
}


text:
namespace base {

// Mac-specific file watcher implementation based on FSEvents.
// There are trade-offs between the FSEvents implementation and a kqueue
// implementation. The biggest issues are that FSEvents on 10.6 sometimes drops
// events and kqueue does not trigger for modifications to a file in a watched
// directory. See file_path_watcher_mac.cc for the code that decides when to
// use which one.
class FilePathWatcherFSEvents : public FilePathWatcher::PlatformDelegate {
 public:
  FilePathWatcherFSEvents();

  // FilePathWatcher::PlatformDelegate overrides.
  bool Watch(const FilePath& path,
             bool recursive,
             const FilePathWatcher::Callback& callback) override;
  void Cancel() override;

 private:
  static void FSEventsCallback(ConstFSEventStreamRef stream,
                               void* event_watcher,
                               size_t num_events,
                               void* event_paths,
                               const FSEventStreamEventFlags flags[],
                               const FSEventStreamEventId event_ids[]);

  ~FilePathWatcherFSEvents() override;

  // Called from FSEventsCallback whenever there is a change to the paths.
  void OnFilePathsChanged(const std::vector<FilePath>& paths);

  // Called on the message_loop() thread to dispatch path events. Can't access
  // target_ and resolved_target_ directly as those are modified on the
  // libdispatch thread.
  void DispatchEvents(const std::vector<FilePath>& paths,
                      const FilePath& target,
                      const FilePath& resolved_target);

  // Cleans up and stops the event stream.
  void CancelOnMessageLoopThread() override;

  // (Re-)Initialize the event stream to start reporting events from
  // |start_event|.
  void UpdateEventStream(FSEventStreamEventId start_event);

  // Returns true if resolving the target path got a different result than
  // last time it was done.
  bool ResolveTargetPath();

  // Report an error watching the given target.
  void ReportError(const FilePath& target);

  // Destroy the event stream.
  void DestroyEventStream();

  // Start watching the FSEventStream.
  void StartEventStream(FSEventStreamEventId start_event, const FilePath& path);

  // Callback to notify upon changes.
  // (Only accessed from the message_loop() thread.)
  FilePathWatcher::Callback callback_;

  // Target path to watch (passed to callback).
  // (Only accessed from the libdispatch thread.)
  FilePath target_;

  // Target path with all symbolic links resolved.
  // (Only accessed from the libdispatch thread.)
  FilePath resolved_target_;

  // Backend stream we receive event callbacks from (strong reference).
  // (Only accessed from the libdispatch thread.)
  FSEventStreamRef fsevent_stream_;

  DISALLOW_COPY_AND_ASSIGN(FilePathWatcherFSEvents);
};

}  // namespace base

#endif  // BASE_FILES_FILE_PATH_WATCHER_FSEVENTS_H_


text:
package org.springframework.aop.support.annotation;

import org.junit.jupiter.api.Test;

import org.springframework.aop.MethodMatcher;
import org.springframework.aop.Pointcut;
import org.springframework.beans.factory.annotation.Qualifier;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Unit tests for {@link AnnotationMatchingPointcut}.
 *
 * @author Sam Brannen
 * @since 5.1.10
 */
class AnnotationMatchingPointcutTests {

	@Test
	void classLevelPointcuts() {
		Pointcut pointcut1 = new AnnotationMatchingPointcut(Qualifier.class, true);
		Pointcut pointcut2 = new AnnotationMatchingPointcut(Qualifier.class, true);
		Pointcut pointcut3 = new AnnotationMatchingPointcut(Qualifier.class);

		assertThat(pointcut1.getClassFilter().getClass()).isEqualTo(AnnotationClassFilter.class);
		assertThat(pointcut2.getClassFilter().getClass()).isEqualTo(AnnotationClassFilter.class);
		assertThat(pointcut3.getClassFilter().getClass()).isEqualTo(AnnotationClassFilter.class);
		assertThat(pointcut1.getClassFilter().toString()).contains(Qualifier.class.getName());

		assertThat(pointcut1.getMethodMatcher()).isEqualTo(MethodMatcher.TRUE);
		assertThat(pointcut2.getMethodMatcher()).isEqualTo(MethodMatcher.TRUE);
		assertThat(pointcut3.getMethodMatcher()).isEqualTo(MethodMatcher.TRUE);

		assertThat(pointcut1).isEqualTo(pointcut2);
		assertThat(pointcut1).isNotEqualTo(pointcut3);
		assertThat(pointcut1.hashCode()).isEqualTo(pointcut2.hashCode());
		// #1 and #3 have equivalent hash codes even though equals() returns false.
		assertThat(pointcut1.hashCode()).isEqualTo(pointcut3.hashCode());
		assertThat(pointcut1.toString()).isEqualTo(pointcut2.toString());
	}

	@Test
	void methodLevelPointcuts() {
		Pointcut pointcut1 = new AnnotationMatchingPointcut(null, Qualifier.class, true);
		Pointcut pointcut2 = new AnnotationMatchingPointcut(null, Qualifier.class, true);
		Pointcut pointcut3 = new AnnotationMatchingPointcut(null, Qualifier.class);

		assertThat(pointcut1.getClassFilter().getClass().getSimpleName()).isEqualTo("AnnotationCandidateClassFilter");
		assertThat(pointcut2.getClassFilter().getClass().getSimpleName()).isEqualTo("AnnotationCandidateClassFilter");
		assertThat(pointcut3.getClassFilter().getClass().getSimpleName()).isEqualTo("AnnotationCandidateClassFilter");
		assertThat(pointcut1.getClassFilter().toString()).contains(Qualifier.class.getName());

		assertThat(pointcut1.getMethodMatcher().getClass()).isEqualTo(AnnotationMethodMatcher.class);
		assertThat(pointcut2.getMethodMatcher().getClass()).isEqualTo(AnnotationMethodMatcher.class);
		assertThat(pointcut3.getMethodMatcher().getClass()).isEqualTo(AnnotationMethodMatcher.class);

		assertThat(pointcut1).isEqualTo(pointcut2);
		assertThat(pointcut1).isNotEqualTo(pointcut3);
		assertThat(pointcut1.hashCode()).isEqualTo(pointcut2.hashCode());
		// #1 and #3 have equivalent hash codes even though equals() returns false.
		assertThat(pointcut1.hashCode()).isEqualTo(pointcut3.hashCode());
		assertThat(pointcut1.toString()).isEqualTo(pointcut2.toString());
	}

	@Test
	void classLevelAndMethodLevelPointcuts() {
		Pointcut pointcut1 = new AnnotationMatchingPointcut(Qualifier.class, Qualifier.class, true);
		Pointcut pointcut2 = new AnnotationMatchingPointcut(Qualifier.class, Qualifier.class, true);
		Pointcut pointcut3 = new AnnotationMatchingPointcut(Qualifier.class, Qualifier.class);

		assertThat(pointcut1.getClassFilter().getClass()).isEqualTo(AnnotationClassFilter.class);
		assertThat(pointcut2.getClassFilter().getClass()).isEqualTo(AnnotationClassFilter.class);
		assertThat(pointcut3.getClassFilter().getClass()).isEqualTo(AnnotationClassFilter.class);
		assertThat(pointcut1.getClassFilter().toString()).contains(Qualifier.class.getName());

		assertThat(pointcut1.getMethodMatcher().getClass()).isEqualTo(AnnotationMethodMatcher.class);
		assertThat(pointcut2.getMethodMatcher().getClass()).isEqualTo(AnnotationMethodMatcher.class);
		assertThat(pointcut3.getMethodMatcher().getClass()).isEqualTo(AnnotationMethodMatcher.class);
		assertThat(pointcut1.getMethodMatcher().toString()).contains(Qualifier.class.getName());

		assertThat(pointcut1).isEqualTo(pointcut2);
		assertThat(pointcut1).isNotEqualTo(pointcut3);
		assertThat(pointcut1.hashCode()).isEqualTo(pointcut2.hashCode());
		// #1 and #3 have equivalent hash codes even though equals() returns false.
		assertThat(pointcut1.hashCode()).isEqualTo(pointcut3.hashCode());
		assertThat(pointcut1.toString()).isEqualTo(pointcut2.toString());
	}

}


text:
<?php

namespace Concrete\Core\Logging\Search\ColumnSet\Column;

use Concrete\Core\Database\Query\AndWhereNotExistsTrait;
use Concrete\Core\Logging\LogEntry;
use Concrete\Core\Logging\LogList;
use Concrete\Core\Search\Column\Column;
use Concrete\Core\Search\Column\PagerColumnInterface;
use Concrete\Core\Search\ItemList\Pager\PagerProviderInterface;

class ChannelColumn extends Column implements PagerColumnInterface
{

    use AndWhereNotExistsTrait;

    public function getColumnKey()
    {
        return 'l.channel';
    }

    public function getColumnName()
    {
        return t('Channel');
    }

    public function getColumnCallback()
    {
        return 'getChannel';
    }

    /**
     * @param LogList $itemList
     * @param $mixed LogEntry
     * @noinspection PhpDocSignatureInspection
     */
    public function filterListAtOffset(PagerProviderInterface $itemList, $mixed)
    {
        $query = $itemList->getQueryObject();
        $sort = $this->getColumnSortDirection() == 'desc' ? '<' : '>';
        $where = sprintf('l.channel %s :channel', $sort);
        $query->setParameter('channel', $mixed->getChannel());
        $this->andWhereNotExists($query, $where);
    }

}


text:
package org.sparkcommerce.openadmin.server.dao;

import org.sparkcommerce.openadmin.dto.FieldMetadata;

import java.util.Map;

/**
 * @author Jeff Fischer
 */
public interface PropertyBuilder {

    public Map<String, FieldMetadata> execute(Boolean overridePopulateManyToOne);

}


text:
$("#return").click(function() {

	history.back();
});
var sortType = "hot";

function request(paras) {
	var url = location.href;
	var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
	var paraObj = {}
	for(i = 0; j = paraString[i]; i++) {
		paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=") + 1, j.length);
	}
	var returnValue = paraObj[paras.toLowerCase()];
	if(typeof(returnValue) == "undefined") {
		return "";
	} else {
		return returnValue;
	}
}

var wareID = decodeURIComponent(request("wareID"));

var page = 1;

var wareTogetherType = "web";

var getWareInfo = function() {

	var message = {
		"LINK": "together",
		"ISTR": "inq",
		"CONT": "wareInfo",
		"wareID": wareID,

	};

	$.ajax({
		type: "GET",
		url: "http://api.celerstar.com/together/index.php",
		timeout: 3000, //超时时间:30秒
		data: message,
		dataType: 'jsonp',
		jsonp: "callback", //传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(默认为:callback)

		success: function(data) {
			console.log(data["NOTE"].wareWebName);

			if(data["INFO"] == "true") {
				$("#wareWebName").html(data["NOTE"].wareWebName);
				$("#title").html(data["NOTE"].wareWebName);
				$("#wareSynopsis").html(data["NOTE"].wareSynopsis);
				//$("#indexUrl").html(data["NOTE"].wareIndexUrl);
				$("#indexUrl").attr("href", "View.html?url=" + encodeURIComponent(data["NOTE"].wareIndexUrl));

				if(data["NOTE"].wareSiteMaster != "") {
					$("#wareSiteMaster").html(data["NOTE"].wareSiteMaster);
				}

				$("#wareImage").html('

');

			}

		},

		error: function() {

		},
		  complete: function(XMLHttpRequest, status) {
			if(status == 'timeout') {}
		}

	});

	return false;
}

var relwareHotNum = function() {

	var message = {
		"LINK": "together",
		"ISTR": "rev",
		"CONT": "wareHotNum",
		"wareID": wareID,

	};

	$.ajax({
		type: "GET",
		url: "http://api.celerstar.com/together/index.php",
		timeout: 3000, //超时时间:30秒
		data: message,
		dataType: 'jsonp',
		jsonp: "callback", //传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(默认为:callback)

		success: function(data) {
			console.log(JSON.stringify(data));
		},

		error: function() {},
		  complete: function(XMLHttpRequest, status) {}

	});

	return false;
}

var ajax_str = function(string) {

	$.ajax({
		type: "GET",
		url: "http://api.celerstar.com/together/index.php",
		timeout: 3000, //超时时间:30秒
		data: string,
		dataType: 'jsonp',
		jsonp: "callback", //传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(默认为:callback)

		success: function(data) {
			if(data["INFO"] == "true") {

				page = data["Page"];
				$("#List").empty();
				var size = 0;
				for(var p in data["LIST"]) {
					size++;
					var wareTogetherTitle = data["LIST"][p].wareTogetherTitle;
					var wareTogetherURL = data["LIST"][p].wareTogetherURL;
					var wareTogetherHotNum = data["LIST"][p].wareTogetherHotNum;
					var wareTogetherId = data["LIST"][p].wareTogetherId;

					$("#List").append('
' + wareTogetherTitle + '' + wareTogetherHotNum + '
');

				}

				if(size == 0) {

					$("#List").append('
无数据
');

				}

			}
		},

		error: function() {

		},
		  complete: function(XMLHttpRequest, status) {
			if(status == 'timeout') {}
		}

	});

	return false;
}

var refresh = function(Page) {
	var message = {
		"LINK": "together",
		"ISTR": "inq",
		"CONT": "List",
		"wareID": wareID,
		"sortType": sortType,
		"wareTogetherType": wareTogetherType,
		"Page": Page,
		"PerPageNum": 20,
	};

	ajax_str(message);
}

getWareInfo();
relwareHotNum();
refresh(0);

$("#top").click(function() {
	refresh(1);
});

$("#next").click(function() {
	page = page + 1;
	refresh(page);
});

$("#web").click(function() {
	wareTogetherType = "web";
	refresh(1);
});

$("#tutorial").click(function() {
	wareTogetherType = "tutorial";
	refresh(1);
});

$("#document").click(function() {
	wareTogetherType = "document";
	refresh(1);
});
$("#book").click(function() {
	wareTogetherType = "book";
	refresh(1);
});
$("#video").click(function() {
	wareTogetherType = "video";
	refresh(1);
});
$("#ppt").click(function() {
	wareTogetherType = "ppt";
	refresh(1);
});
$("#file").click(function() {
	wareTogetherType = "file";
	refresh(1);
});
$("#other").click(function() {
	wareTogetherType = "other";
	refresh(1);
});


text:
PYTHONIC_NS_BEGIN
namespace numpy
{
  namespace random
  {
    template <class pS>
    types::ndarray<double, pS> negative_binomial(double n, double p,
                                                 pS const &shape);

    auto negative_binomial(double n, double p, long size)
        -> decltype(negative_binomial(n, p, types::array<long, 1>{{size}}));

    double negative_binomial(double n, double p, types::none_type size = {});

    DEFINE_FUNCTOR(pythonic::numpy::random, negative_binomial);
  }
}
PYTHONIC_NS_END

#endif


text:
#include "tfcore_unix.h"
#include "tredisdriver.h"
#include "tsystemglobal.h"
#include <QTcpSocket>
#include <TApplicationServerBase>
using namespace Tf;

constexpr int DEFAULT_PORT = 6379;
constexpr int SEND_BUF_SIZE = 128 * 1024;
constexpr int RECV_BUF_SIZE = 128 * 1024;

TRedisDriver::TRedisDriver() :
    TKvsDriver()
{
    _buffer.reserve(1023);
}

TRedisDriver::~TRedisDriver()
{
    close();
}

bool TRedisDriver::isOpen() const
{
    return _socket > 0;
}

bool TRedisDriver::open(const QString &, const QString &, const QString &, const QString &host, quint16 port, const QString &)
{
    if (isOpen()) {
        return true;
    }

    QTcpSocket tcpSocket;

    // Sets socket options
    tcpSocket.setSocketOption(QAbstractSocket::LowDelayOption, 1);

    // Sets buffer size of socket
    int val = tcpSocket.socketOption(QAbstractSocket::SendBufferSizeSocketOption).toInt();
    if (val < SEND_BUF_SIZE) {
        tcpSocket.setSocketOption(QAbstractSocket::SendBufferSizeSocketOption, SEND_BUF_SIZE);
    }

    val = tcpSocket.socketOption(QAbstractSocket::ReceiveBufferSizeSocketOption).toInt();
    if (val < RECV_BUF_SIZE) {
        tcpSocket.setSocketOption(QAbstractSocket::ReceiveBufferSizeSocketOption, RECV_BUF_SIZE);
    }

    _host = (host.isEmpty()) ? "localhost" : host;
    _port = (port == 0) ? DEFAULT_PORT : port;

    tSystemDebug("Redis open host:%s  port:%d", qPrintable(_host), _port);
    tcpSocket.connectToHost(_host, _port);

    bool ret = tcpSocket.waitForConnected(5000);
    if (Q_LIKELY(ret)) {
        tSystemDebug("Redis open successfully");
    } else {
        tSystemError("Redis open failed");
        close();
        return false;
    }

    _socket = TApplicationServerBase::duplicateSocket(tcpSocket.socketDescriptor());
    return _socket > 0;
}

void TRedisDriver::close()
{
    if (_socket > 0) {
        tf_close(_socket);
        _socket = 0;
    }
}

bool TRedisDriver::writeCommand(const QByteArray &command)
{
    if (Q_UNLIKELY(!isOpen())) {
        tSystemError("Not open Redis session  [%s:%d]", __FILE__, __LINE__);
        return false;
    }

    qint64 total = 0;
    while (total < command.length()) {
        if (tf_poll_send(_socket, 5000) == 0) {
            qint64 len = tf_send(_socket, command.data() + total, command.length() - total, 0);
            if (len < 0) {
                break;
            }
            total += len;
        } else {
            break;
        }
    }
    return total == command.length();
}

bool TRedisDriver::readReply()
{
    if (Q_UNLIKELY(!isOpen())) {
        tSystemError("Not open Redis session  [%s:%d]", __FILE__, __LINE__);
        return false;
    }

    QByteArray buf;
    buf.reserve(RECV_BUF_SIZE);
    int timeout = 5000;
    int len = 0;

    while (tf_poll_recv(_socket, timeout) == 0) {
        len = tf_recv(_socket, buf.data(), RECV_BUF_SIZE, 0);
        if (len <= 0) {
            break;
        }

        buf.resize(len);
        _buffer += buf;
        if (len < RECV_BUF_SIZE) {
            break;
        }
        timeout = 1;
    }

    return len > 0;
}

void TRedisDriver::moveToThread(QThread *)
{
}


text:
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Parsing;
using Microsoft.PythonTools.Parsing.Ast;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Win32;
using TestUtilities;
using TestUtilities.Python;

namespace PythonToolsTests {
    [TestClass]
    public class CPythonInterpreterTests {
        internal static readonly CPythonInterpreterFactoryProvider InterpFactory = new CPythonInterpreterFactoryProvider(false);

        [ClassInitialize]
        public static void DoDeployment(TestContext context) {
            AssertListener.Initialize();
            PythonTestData.Deploy();
        }

        [TestMethod, Priority(0)]
        public void FactoryProvider() {
            var provider = InterpFactory;
            var factories = provider.GetInterpreterFactories().ToArray();

            Console.WriteLine("Discovered:");
            foreach (var factory in factories) {
                var id = factory.Configuration.Id;
                Console.WriteLine("  {0} - {1}".FormatInvariant(id, factory.Configuration.Description));

                Assert.IsTrue(id.StartsWith("Global|"), "Expected 'Global' prefix on '{0}'".FormatInvariant(factory.Configuration.Id));

                Assert.IsNotNull(factory.CreateInterpreter(), "failed to create interpreter");

                if (id.StartsWith("Global|PythonCore|")) {
                    var description = factory.Configuration.Description;
                    var sysVersion = factory.Configuration.Version;
                    var sysArch = factory.Configuration.Architecture;

                    AssertUtil.Contains(description, "Python", sysVersion.ToString(), sysArch.ToString());

                    Assert.IsTrue(sysVersion.Major == 2 || sysVersion.Major == 3, "unknown SysVersion '{0}'".FormatInvariant(sysVersion));

                    Assert.AreEqual(PythonRegistrySearch.PythonCoreCompanyDisplayName, provider.GetProperty(id, PythonRegistrySearch.CompanyPropertyKey));
                    Assert.AreEqual(PythonRegistrySearch.PythonCoreSupportUrl, provider.GetProperty(id, PythonRegistrySearch.SupportUrlPropertyKey));
                }
            }
        }

        [TestMethod, Priority(1)]
        public void DiscoverRegistryRace() {
            // https://github.com/Microsoft/PTVS/issues/558

            using (var key = Registry.CurrentUser.CreateSubKey(@"Software\Python\PythonCore")) {
                for (int changes = 0; changes < 1000; ++changes) {
                    // Doesn't matter about the name - we just want to trigger
                    // discovery and then remove the key during GetSubKeyNames.
                    key.CreateSubKey("NotARealInterpreter").Close();
                    key.DeleteSubKey("NotARealInterpreter", false);
                }
            }
        }

        [TestMethod, Priority(0)]
        public void ImportFromSearchPath() {
            var analyzer = new PythonAnalysis(PythonLanguageVersion.V35);
            analyzer.AddModule("test-module", "from test_package import *");
            analyzer.WaitForAnalysis();
            AssertUtil.CheckCollection(analyzer.GetAllNames(), null, new[] { "package_method", "package_method_two", "test_package" });

            analyzer.SetSearchPaths(TestData.GetPath("TestData\\AddImport"));
            analyzer.ReanalyzeAll();

            AssertUtil.CheckCollection(analyzer.GetAllNames(), new[] { "package_method", "package_method_two" }, new[] { "test_package" });
        }

        [TestMethod, Priority(0)]
        public void ImportPydFromSearchPath() {
            PythonTypeDatabase.ExtensionModuleLoader.AlwaysGenerateDb = true;
            try {
                var analyzer = new PythonAnalysis("Global|PythonCore|2.7-32");

                analyzer.AddModule("test-module", "from spam import *");
                analyzer.WaitForAnalysis();
                AssertUtil.CheckCollection(analyzer.GetAllNames(), null, new[] { "system", "spam" });

                analyzer.SetSearchPaths(TestData.GetPath("TestData"));
                analyzer.ReanalyzeAll(CancellationTokens.After60s);

                AssertUtil.CheckCollection(analyzer.GetAllNames(), new[] { "system" }, new[] { "spam" });
            } finally {
                PythonTypeDatabase.ExtensionModuleLoader.AlwaysGenerateDb = false;
            }
        }

        [TestMethod, Priority(0)]
        public void ImportFromZipFile() {
            var analyzer = new PythonAnalysis(PythonLanguageVersion.V35);
            analyzer.AddModule("test-module", "from test_package import *");
            analyzer.WaitForAnalysis();
            AssertUtil.CheckCollection(analyzer.GetAllNames(), null, new[] { "package_method", "package_method_two", "test_package" });

            analyzer.SetSearchPaths(TestData.GetPath("TestData\\AddImport.zip"));
            analyzer.ReanalyzeAll();

            AssertUtil.CheckCollection(analyzer.GetAllNames(), new[] { "package_method", "package_method_two" }, new[] { "test_package" });
        }

        private static void AnalyzeCode(
            out PythonAnalyzer analyzer,
            out IPythonProjectEntry entry,
            string code,
            Version preferredVersion = null,
            InterpreterArchitecture preferredArch = null,
            string module = "test-module"
        ) {
            var provider = InterpFactory;
            var factory = provider.GetInterpreterFactories().OrderByDescending(f => f.Configuration.Version)
                .Where(f => preferredVersion == null || f.Configuration.Version == preferredVersion)
                .Where(f => preferredArch == null || f.Configuration.Architecture == preferredArch)
                .FirstOrDefault();
            Assert.IsNotNull(factory, "no factory found");

            analyzer = PythonAnalyzer.CreateSynchronously(factory);
            var path = Path.Combine(TestData.GetTempPath(randomSubPath: true), module.Replace('.', '\\'));
            Directory.CreateDirectory(PathUtils.GetParent(path));
            File.WriteAllText(path, code);

            entry = analyzer.AddModule(module, path);
            PythonAst ast;
            using (var p = Parser.CreateParser(new StringReader(code), factory.GetLanguageVersion())) {
                ast = p.ParseFile();
                entry.UpdateTree(ast, null);
            }

            entry.Analyze(CancellationToken.None, true);
        }
    }
}


text:
package com.josephshanak.musicgenerator.core;

/**
 * Created by Joe on 3/7/2017.
 *
 * @author Joe
 * @history 3/7/2017 - Created
 */
public class PercussionMeasureBuilder extends MeasureBuilder {
    private final PercussionTrack percussionTrack;

    PercussionMeasureBuilder(PercussionTrack percussionTrack, int numBeats, NoteDuration
            noteThatGetsBeat, int tempo) {
        super(tempo, noteThatGetsBeat, numBeats);
        this.percussionTrack = percussionTrack;
    }

    @Override
    public RestBuilder newRest(NoteDuration duration) {
        return new RestBuilder(duration, this);
    }

    @Override
    public PercussionNoteBuilder newNote(NoteDuration duration) {
        return new PercussionNoteBuilder(duration, this);
    }

    @Override
    public PercussionChordBuilder newChord(NoteDuration duration) {
        return new PercussionChordBuilder(duration, this);
    }

    public PercussionMeasure createMeasure() {
        PercussionMeasure measure = new PercussionMeasure(numBeats, noteThatGetsBeat, tempo);
        for (Event event : events) {
            measure.addEvent(event);
        }
        return measure;
    }
}


text:
package edu.uci.ics.comet.eventprocessor;

public class Globals {

	public static final String CONFIG_FOLDER = "cfg";
	public static final String CONFIG_FILENAME = "config.xml";

	private Globals() {
	}

}