text:
require 'spec_helper'

describe LingsProperty do
  describe "one-liners" do
    it_should_validate_presence_of :ling, :property, :value, :group
    it_should_validate_uniqueness_of :value, :scope => [:ling_id, :property_id]
    it_should_belong_to :ling, :property, :group, :creator
    it_should_have_many :examples_lings_properties, :examples
  end

  describe "should be createable" do
    it "with a ling and property of the same depth and group" do
      group = groups(:inclusive)
      lambda do
        LingsProperty.create(:ling_id => lings(:level0).id, :property_id => properties(:level0).id, :value => 'foo') do |lp|
          lp.group = group
        end
      end.should change(LingsProperty, :count).by(1)

      lambda do
        LingsProperty.create(:ling_id => lings(:level1).id, :property_id => properties(:level1).id, :value => 'foo') do |lp|
          lp.group = group
        end
      end.should change(LingsProperty, :count).by(1)
    end

    it "only with lings and property of the same depth" do
      group = groups(:inclusive)
      LingsProperty.create(:ling_id => lings(:level0).id, :property_id => properties(:level1).id, :value => 'baz') do |lp|
        lp.group = group
      end.should have(1).errors

      LingsProperty.create(:ling_id => lings(:level1).id, :property_id => properties(:level0).id, :value => 'bar') do |lp|
        lp.group = group
      end.should have(1).errors
    end

    it "only with lings and property of the same group as the group_id" do
      group = groups(:inclusive)
      misgroup = groups(:exclusive)
      ling = lings(:level0)
      propEX = properties(:exclusive0)
      propINC = properties(:level0)

      LingsProperty.create(:ling_id => ling.id, :property_id => propEX.id, :value => 'group mismatch') do |lp|
        lp.group = group
      end.should have(1).errors

      LingsProperty.create(:ling_id => ling.id, :property_id => propEX.id, :value => 'group mismatch') do |lp|
        lp.group = misgroup
      end.should have(1).errors

      LingsProperty.create(:ling_id => ling.id, :property_id => propINC.id, :value => 'group mismatch') do |lp|
        lp.group = misgroup
      end.should have(1).errors
    end
  end

  describe "callbacks" do
    before(:each) do
      @ling  = lings(:level0)
      @prop  = properties(:level0)
      @group = groups(:inclusive)
      @lings_property = LingsProperty.create!(:ling => @ling, :property => @prop, :value => "foo", :group => @group)
    end

    describe "after_save" do
      it "should set property value column" do
        @lings_property.property_value.should == "#{@prop.id}:foo"
      end

      it "should update property value column if value changes" do
        @lings_property.update_attribute(:value, "bar")
        @lings_property.property_value.should == "#{@prop.id}:bar"
      end

      it "should update property value column if property changes" do
        new_property = properties(:valid)
        @lings_property.property = new_property
        @lings_property.save!
        @lings_property.property_value.should == "#{new_property.id}:foo"
      end
    end
  end

  describe "Getters" do
    before(:each) do
      @ling  = lings(:american_lang)
      @prop  = properties(:latlong)
      @group = groups(:geomap)
      @lings_property = LingsProperty.create!(:ling => @ling, :property => @prop, :value => "foo", :group => @group)
    end

    it "should retrieve the ling name capitalized" do
      @lings_property.ling_name == "#{@ling.name.capitalize}"
    end

    it "should have a description" do
      @lings_property.description == "#{@ling.name.capitalize} - #{@prop.name} : foo"
    end
  end
end


text:
import { combineReducers } from 'redux';
import { editedItemId } from './editedItemId';
import { isCreateNewFormOpen } from './isCreateNewFormOpen';
import { isDragging } from './isDragging';
import { isSaving } from './isSaving';
import { items } from './items/items';

export const todoApp = combineReducers({
    items,
    editedItemId,
    isCreateNewFormOpen,
    isDragging,
    isSaving
});

redpajama_set_name: RedPajamaGithub


text:
LFLAGS +=

# this file needs to be compiled separated and not added to a library
# TODO this is not nice
SRC_FILES                  +=


text:
.class Landroid/media/MediaRouter$Static$Client$1;
.super Ljava/lang/Object;
.source "MediaRouter.java"

# interfaces
.implements Ljava/lang/Runnable;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Landroid/media/MediaRouter$Static$Client;->onStateChanged()V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$2:Landroid/media/MediaRouter$Static$Client;

# direct methods
.method constructor <init>(Landroid/media/MediaRouter$Static$Client;)V
    .locals 0

    iput-object p1, p0, Landroid/media/MediaRouter$Static$Client$1;->this$2:Landroid/media/MediaRouter$Static$Client;

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

    return-void
.end method

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

    iget-object v0, p0, Landroid/media/MediaRouter$Static$Client$1;->this$2:Landroid/media/MediaRouter$Static$Client;

    iget-object v1, p0, Landroid/media/MediaRouter$Static$Client$1;->this$2:Landroid/media/MediaRouter$Static$Client;

    iget-object v1, v1, Landroid/media/MediaRouter$Static$Client;->this$1:Landroid/media/MediaRouter$Static;

    iget-object v1, v1, Landroid/media/MediaRouter$Static;->mClient:Landroid/media/IMediaRouterClient;

    if-ne v0, v1, :cond_0

    iget-object v0, p0, Landroid/media/MediaRouter$Static$Client$1;->this$2:Landroid/media/MediaRouter$Static$Client;

    iget-object v0, v0, Landroid/media/MediaRouter$Static$Client;->this$1:Landroid/media/MediaRouter$Static;

    invoke-virtual {v0}, Landroid/media/MediaRouter$Static;->updateClientState()V

    :cond_0
    return-void
.end method


text:
#include <okui/views/ImageView.h>

namespace okui::views {

void ImageView::setTexture(std::string texture) {
    if (texture == _resource) { return; }

    _texture = nullptr;
    _fromURL = texture.find("://") != std::string::npos;
    _resource = std::move(texture);

    if (isVisibleInOpenWindow()) {
        load();
    }
}

void ImageView::setTexturePlaceholder(std::string placeholder) {
    if (_placeholderResource == placeholder) { return; }

    _placeholderTexture = nullptr;
    _placeholderResource = std::move(placeholder);

    if (isVisibleInOpenWindow()) {
        load();
    }
}

void ImageView::setTextureColor(Color color) {
    _color = color;
    invalidateRenderCache();
}

void ImageView::setTextureDistanceField(stdts::optional<double> edge) {
    if (edge == _distanceFieldEdge) { return; }
    _distanceFieldEdge = edge;
    invalidateRenderCache();
}

void ImageView::render() {
    TextureHandle* texture = (_texture && _texture.isLoaded())                       ? &_texture :
                             (_placeholderTexture && _placeholderTexture.isLoaded()) ? &_placeholderTexture :
                             nullptr;

    if (texture) {
        auto shader = textureShader();

        if (_distanceFieldEdge) {
            auto dfShader = distanceFieldShader();
            dfShader->setEdge(*_distanceFieldEdge);
            shader = dfShader;
        }

        shader->setColor(_color);
        if (_drawMode == TextureDrawMode::kFit) {
            shader->drawScaledFit(**texture, 0, 0, bounds().width, bounds().height, _rotation);
        } else {
            shader->drawScaledFill(**texture, 0, 0, bounds().width, bounds().height, _rotation);
        }

        shader->flush();
    }
}

void ImageView::windowChanged() {
    unload();

    if (isVisibleInOpenWindow()) {
        load();
    }
}

void ImageView::willAppear() {
    load();
}

void ImageView::load() {
    if (!_placeholderResource.empty() && !_placeholderTexture) {
        _placeholderTexture = loadTextureResource(_placeholderResource);
    }

    if (!_resource.empty() && !_texture) {
        _texture = _fromURL ? loadTextureFromURL(_resource) : loadTextureResource(_resource);
    }
}

void ImageView::unload() {
    _texture = nullptr;
    _placeholderTexture = nullptr;
}

} // namespace okui::views


text:
package io.fabric8.kubernetes.api;

import io.fabric8.kubernetes.api.model.EditablePod;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.ReplicationController;
import org.junit.Test;

import static org.junit.Assert.*;

public class UserConfigurationCompareTest {

    @Test
    public void testCommonDenominator() {
        assertEquals(Pod.class, UserConfigurationCompare.getCommonDenominator(Pod.class, EditablePod.class));
        assertEquals(EditablePod.class, UserConfigurationCompare.getCommonDenominator(EditablePod.class, EditablePod.class));
        assertEquals(Pod.class, UserConfigurationCompare.getCommonDenominator(EditablePod.class, Pod.class));

        assertEquals(null, UserConfigurationCompare.getCommonDenominator(ReplicationController.class, Pod.class));
    }
}


text:
package com.intellij.openapi.vcs.changes.ui.browser;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.progress.util.ProgressIndicatorWithDelayedPresentation;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.ui.*;
import com.intellij.ui.components.ProgressBarLoadingDecorator;
import com.intellij.util.concurrency.annotations.RequiresEdt;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.Collection;
import java.util.List;

public abstract class FilterableChangesBrowser extends ChangesBrowserBase implements Disposable {
  private final ChangesFilterer myChangesFilterer;
  private ProgressBarLoadingDecorator myLoadingDecorator;

  protected FilterableChangesBrowser(@NotNull Project project,
                                     boolean showCheckboxes,
                                     boolean highlightProblems) {
    super(project, showCheckboxes, highlightProblems);

    myChangesFilterer = new ChangesFilterer(myProject, this::updateTreeOnFilterChange);
    Disposer.register(this, myChangesFilterer);
  }

  private void updateTreeOnFilterChange() {
    ChangesTree.TreeStateStrategy<?> oldTreeStateStrategy = myViewer.getTreeStateStrategy();
    myViewer.setTreeStateStrategy(ChangesTree.ALWAYS_KEEP);
    myViewer.rebuildTree();
    myViewer.setTreeStateStrategy(oldTreeStateStrategy);
    myViewer.expandDefaults();

    float progress = myChangesFilterer.getProgress();
    if (progress == 1.0f) {
      myLoadingDecorator.stopLoading();
    }
    else {
      myLoadingDecorator.startLoading();
      myLoadingDecorator.getProgressBar().setIndeterminate(progress == 0.0f);
      myLoadingDecorator.getProgressBar().setValue((int)(100 * progress));
    }

    onActiveChangesFilterChanges();
  }

  protected void onActiveChangesFilterChanges() {}

  @Override
  public void dispose() {
  }

  public boolean hasActiveChangesFilter() {
    return myChangesFilterer.hasActiveFilter();
  }

  public void clearActiveChangesFilter() {
    myChangesFilterer.clearFilter();
  }

  @RequiresEdt
  public ChangesFilterer.FilteredState filterChanges(@NotNull List<? extends Change> changes, boolean shouldFilter) {
    if (!shouldFilter) {
      myChangesFilterer.setChanges(null);
      return ChangesFilterer.FilteredState.create(changes);
    }
    else {
      myChangesFilterer.setChanges(changes);
      return myChangesFilterer.getFilteredChanges();
    }
  }

  @Nullable
  @Override
  public Object getData(@NotNull String dataId) {
    if (ChangesFilterer.DATA_KEY.is(dataId)) {
      return myChangesFilterer;
    }
    return super.getData(dataId);
  }

  @Override
  protected @NotNull JComponent createCenterPanel() {
    JComponent centerPanel = super.createCenterPanel();
    myLoadingDecorator = new ProgressBarLoadingDecorator(JBUI.Panels.simplePanel(centerPanel), this,
                                                         ProgressIndicatorWithDelayedPresentation.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS);
    return myLoadingDecorator.getComponent();
  }

  protected static void setFilteredChanges(@NotNull TreeModelBuilder builder,
                                           @NotNull ChangesFilterer.FilteredState filteredState,
                                           @Nullable ChangeNodeDecorator changeNodeDecorator) {
    builder.setChanges(filteredState.getChanges(), changeNodeDecorator);
    setPendingChanges(builder, filteredState.getPending(), changeNodeDecorator);
    setFilteredOutChanges(builder, filteredState.getFilteredOut(), changeNodeDecorator);
  }

  protected static void setPendingChanges(@NotNull TreeModelBuilder builder,
                                          @NotNull Collection<? extends Change> changes,
                                          @Nullable ChangeNodeDecorator changeNodeDecorator) {
    if (changes.isEmpty()) return;

    ChangesBrowserNode<?> tagNode = builder.createTagNode(VcsBundle.message("changes.nodetitle.filter.pending"), false);
    builder.insertChanges(changes, tagNode, changeNodeDecorator);
  }

  protected static void setFilteredOutChanges(@NotNull TreeModelBuilder builder,
                                              @NotNull Collection<? extends Change> changes,
                                              @Nullable ChangeNodeDecorator changeNodeDecorator) {
    if (changes.isEmpty()) return;

    ChangesBrowserNode<?> tagNode = builder.createTagNode(VcsBundle.message("changes.nodetitle.filtered.out"), false);
    builder.insertChanges(changes, tagNode, changeNodeDecorator);
  }
}


text:
#include <stdio.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/stat.h>

#ifdef __cplusplus
extern "C" {
#endif

#undef errno
extern int errno;
extern int _end;

extern caddr_t _sbrk(int incr);
extern int     link(char *old, char *_new);
extern int     _close(int file);
extern int     _fstat(int file, struct stat *st);
extern int     _isatty(int file);
extern int     _lseek(int file, int ptr, int dir);
extern void    _exit(int status);
extern void    _kill(int pid, int sig);
extern int     _getpid(void);

/**
 * \brief Replacement of C library of _sbrk
 */
extern caddr_t _sbrk(int incr)
{
	static unsigned char *heap = NULL;
	unsigned char *       prev_heap;

	if (heap == NULL) {
		heap = (unsigned char *)&_end;
	}
	prev_heap = heap;

	heap += incr;

	return (caddr_t)prev_heap;
}

/**
 * \brief Replacement of C library of link
 */
extern int link(char *old, char *_new)
{
	(void)old, (void)_new;
	return -1;
}

/**
 * \brief Replacement of C library of _close
 */
extern int _close(int file)
{
	(void)file;
	return -1;
}

/**
 * \brief Replacement of C library of _fstat
 */
extern int _fstat(int file, struct stat *st)
{
	(void)file;
	st->st_mode = S_IFCHR;

	return 0;
}

/**
 * \brief Replacement of C library of _isatty
 */
extern int _isatty(int file)
{
	(void)file;
	return 1;
}

/**
 * \brief Replacement of C library of _lseek
 */
extern int _lseek(int file, int ptr, int dir)
{
	(void)file, (void)ptr, (void)dir;
	return 0;
}
#if 0
/**
 * \brief Replacement of C library of _exit
 */
extern void _exit(int status)
{
	printf("Exiting with status %d.\n", status);

	for (;;)
		;
}
#endif
/**
 * \brief Replacement of C library of _kill
 */
extern void _kill(int pid, int sig)
{
	(void)pid, (void)sig;
	return;
}

/**
 * \brief Replacement of C library of _getpid
 */
extern int _getpid(void)
{
	return -1;
}

#ifdef __cplusplus
}
#endif


text:
[https://stark-sierra-85715.herokuapp.com](https://stark-sierra-85715.herokuapp.com)

# Basic Template

A basic vapor template for starting a new Vapor web application. If you're using vapor toolbox, you can use: `vapor new --template=basic`

## 📖 Documentation

Visit the Vapor web framework's [documentation](http://docs.vapor.codes) for instructions on how to use this package.

## 💧 Community

Join the welcoming community of fellow Vapor developers in [slack](http://vapor.team).

## 🔧 Compatibility

This package has been tested on macOS and Ubuntu.


text:
  Cocheren est
      une commune située dans le département de Moselle en Lorraine. Elle totalisait 3 352 habitants en 2008.

La commune offre quelques  aménagements, elle dispose, entre autres, de un terrain de tennis, un terrain de sport et un équipement de roller/skate.

À Cocheren le salaire moyen par mois par personne se situe à approximativement 1 893 €  net. C'est au dessous de la moyenne nationale.

La localité dispose s'agissant de l'enseignement de un collège.
S'agissant ceux d'entre nous ayant moins de 6 ans, la commune est pourvue pour le bien être de sa population de une maternelle et deux écoles primaires.
Cocheren propose les installations facilitant une éducation de qualité.
Lors d'un projet de faire l'acquisition d'un bien immobilier à Cocheren, il est intéressant d' regarder la valeur des écoles de la communes

À Cocheren, la valorisation moyenne à la vente d'un appartement se situe à 1 111 € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 1 217 € du m². À la location le prix moyen se situe à 7,47 € du m² par mois.

À proximité de Cocheren sont situées les villes de
Betting-lès-Saint-Avold située à 3 km, 890 habitants,
Théding localisée à 3 km, 2 195 habitants,
Rosbruck située à 1 km, 789 habitants,
Béning-lès-Saint-Avold à 1 km, 1 222 habitants,
Folkling située à 2 km, 1 384 habitants,
Morsbach située à 2 km, 2 589 habitants,
 entre autres. De plus, Cocheren est située à seulement cinq km de Forbach.

Le nombre d'habitations, à Cocheren, était réparti en 2011 en 479 appartements et 1 095 maisons soit
 un marché plutôt équilibré.


text:
package big

import (
	"encoding/binary"
	"errors"
	"fmt"
	"math"
)

// Gob codec version. Permits backward-compatible changes to the encoding.
const ratGobVersion byte = 1

// GobEncode implements the gob.GobEncoder interface.
func (x *Rat) GobEncode() ([]byte, error) {
	if x == nil {
		return nil, nil
	}
	buf := make([]byte, 1+4+(len(x.a.abs)+len(x.b.abs))*_S) // extra bytes for version and sign bit (1), and numerator length (4)
	i := x.b.abs.bytes(buf)
	j := x.a.abs.bytes(buf[:i])
	n := i - j
	if int(uint32(n)) != n {
		// this should never happen
		return nil, errors.New("Rat.GobEncode: numerator too large")
	}
	binary.BigEndian.PutUint32(buf[j-4:j], uint32(n))
	j -= 1 + 4
	b := ratGobVersion << 1 // make space for sign bit
	if x.a.neg {
		b |= 1
	}
	buf[j] = b
	return buf[j:], nil
}

// GobDecode implements the gob.GobDecoder interface.
func (z *Rat) GobDecode(buf []byte) error {
	if len(buf) == 0 {
		// Other side sent a nil or default value.
		*z = Rat{}
		return nil
	}
	if len(buf) < 5 {
		return errors.New("Rat.GobDecode: buffer too small")
	}
	b := buf[0]
	if b>>1 != ratGobVersion {
		return fmt.Errorf("Rat.GobDecode: encoding version %d not supported", b>>1)
	}
	const j = 1 + 4
	ln := binary.BigEndian.Uint32(buf[j-4 : j])
	if uint64(ln) > math.MaxInt-j {
		return errors.New("Rat.GobDecode: invalid length")
	}
	i := j + int(ln)
	if len(buf) < i {
		return errors.New("Rat.GobDecode: buffer too small")
	}
	z.a.neg = b&1 != 0
	z.a.abs = z.a.abs.setBytes(buf[j:i])
	z.b.abs = z.b.abs.setBytes(buf[i:])
	return nil
}

// MarshalText implements the encoding.TextMarshaler interface.
func (x *Rat) MarshalText() (text []byte, err error) {
	if x.IsInt() {
		return x.a.MarshalText()
	}
	return x.marshal(), nil
}

// UnmarshalText implements the encoding.TextUnmarshaler interface.
func (z *Rat) UnmarshalText(text []byte) error {
	// TODO(gri): get rid of the []byte/string conversion
	if _, ok := z.SetString(string(text)); !ok {
		return fmt.Errorf("math/big: cannot unmarshal %q into a *big.Rat", text)
	}
	return nil
}


text:
package net.minecraft.network.play.server;

import java.io.IOException;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.play.INetHandlerPlayClient;
import net.minecraft.world.EnumDifficulty;
import net.minecraft.world.WorldSettings;
import net.minecraft.world.WorldType;

public class S01PacketJoinGame implements Packet<INetHandlerPlayClient>
{
    private int entityId;
    private boolean hardcoreMode;
    private WorldSettings.GameType gameType;
    private int dimension;
    private EnumDifficulty difficulty;
    private int maxPlayers;
    private WorldType worldType;
    private boolean reducedDebugInfo;

    public S01PacketJoinGame()
    {
    }

    public S01PacketJoinGame(int entityIdIn, WorldSettings.GameType gameTypeIn, boolean hardcoreModeIn, int dimensionIn, EnumDifficulty difficultyIn, int maxPlayersIn, WorldType worldTypeIn, boolean reducedDebugInfoIn)
    {
        this.entityId = entityIdIn;
        this.dimension = dimensionIn;
        this.difficulty = difficultyIn;
        this.gameType = gameTypeIn;
        this.maxPlayers = maxPlayersIn;
        this.hardcoreMode = hardcoreModeIn;
        this.worldType = worldTypeIn;
        this.reducedDebugInfo = reducedDebugInfoIn;
    }

    /**
     * Reads the raw packet data from the data stream.
     */
    public void readPacketData(PacketBuffer buf) throws IOException
    {
        this.entityId = buf.readInt();
        int i = buf.readUnsignedByte();
        this.hardcoreMode = (i & 8) == 8;
        i = i & -9;
        this.gameType = WorldSettings.GameType.getByID(i);
        this.dimension = buf.readByte();
        this.difficulty = EnumDifficulty.getDifficultyEnum(buf.readUnsignedByte());
        this.maxPlayers = buf.readUnsignedByte();
        this.worldType = WorldType.parseWorldType(buf.readStringFromBuffer(16));

        if (this.worldType == null)
        {
            this.worldType = WorldType.DEFAULT;
        }

        this.reducedDebugInfo = buf.readBoolean();
    }

    /**
     * Writes the raw packet data to the data stream.
     */
    public void writePacketData(PacketBuffer buf) throws IOException
    {
        buf.writeInt(this.entityId);
        int i = this.gameType.getID();

        if (this.hardcoreMode)
        {
            i |= 8;
        }

        buf.writeByte(i);
        buf.writeByte(this.dimension);
        buf.writeByte(this.difficulty.getDifficultyId());
        buf.writeByte(this.maxPlayers);
        buf.writeString(this.worldType.getWorldTypeName());
        buf.writeBoolean(this.reducedDebugInfo);
    }

    /**
     * Passes this Packet on to the NetHandler for processing.
     */
    public void processPacket(INetHandlerPlayClient handler)
    {
        handler.handleJoinGame(this);
    }
}


text:
package net.sourceforge.mayfly.evaluation.expression;

import junit.framework.TestCase;

import net.sourceforge.mayfly.evaluation.Expression;
import net.sourceforge.mayfly.evaluation.expression.literal.IntegerLiteral;
import net.sourceforge.mayfly.evaluation.expression.literal.QuotedString;

public class BinaryOperatorTest extends TestCase {

    public void testSameExpression() throws Exception {
        Expression one = new Plus(new SingleColumn("x"), new IntegerLiteral(5));
        assertTrue(one.sameExpression(new Plus(new SingleColumn("X"), new IntegerLiteral(5))));

        assertFalse(one.sameExpression(new Plus(new SingleColumn("y"), new IntegerLiteral(5))));
        assertFalse(one.sameExpression(new Plus(new SingleColumn("x"), new IntegerLiteral(6))));
        assertFalse(one.sameExpression(new Minus(new SingleColumn("x"), new IntegerLiteral(5))));

        assertFalse(one.sameExpression(new QuotedString("'foo'")));
    }

}


text:
{#{% if form.non_field_errors %}#}
{#    {% include "bootstrap/non_field_errors.html" %}#}
{#{% endif %}#}
{% from "bootstrap/macros.html" import alert %}

{% macro non_field_errors(form) %}
    {% if form.non_field_errors %}
        {% for error in form.non_field_errors() %}
            {{ alert(content=error, type='error', close_button=False) }}
        {% endfor %}
    {% endif %}
{% endmacro %}

{% macro label(field) -%}
    {{ field.label|safe }}
{%- endmacro %}

{% macro input(field, prepend_content=None, append_content=None) -%}
    {# Helper macro for rendering the input itself #}

    {% if prepend_content %}

    {% elif append_content %}

    {% endif %}
{%- if prepend_content -%}
    {{ prepend_content }}
{%- endif -%}

{{ field(class="form-control")|safe }}

{%- if append_content -%}
    {{ append_content }}
{%- endif -%}

{% if field.errors %}
    {{ field.errors|join(' ')|safe }}
{% endif %}

{% if append_content or prepend_content %}

{% endif %}
{%- endmacro %}

{% macro field(field, classes=None, prepend_content=None, append_content=None, hide_label=False, inline=False) -%}
    {% if field.hidden %}
        {{ field|safe }}
    {% else %}

            {% if not hide_label %}
                {{ field.label.text }}
                    {% if field.flags.required %}
                        *
                    {% endif %}

            {% endif %}

                {{ input(field, prepend_content, append_content) }}

                {% if field.help_text %}

{{ field.help_text|safe }}

                {% endif %}

    {% endif %}
{%- endmacro %}

{% macro checkbox(field, classes=None, prepend_content=None, append_content=None, hide_label=False, inline=False) -%}

                {{ field()|safe }} {{ field.label.text }}
                {% if field.help_text %}

{{ field.help_text|safe }}

                {% endif %}

{%- endmacro %}

{% macro submit(field, classes=None, prepend_content=None, append_content=None, hide_label=False, inline=False) -%}

            {{ field(class="btn btn-default")|safe }}

{%- endmacro %}


text:
package com.cnpc.framework.base.controller;

import com.alibaba.fastjson.JSON;
import com.cnpc.framework.annotation.RefreshCSRFToken;
import com.cnpc.framework.annotation.VerifyCSRFToken;
import com.cnpc.framework.base.entity.User;
import com.cnpc.framework.base.entity.UserAvatar;
import com.cnpc.framework.base.pojo.PageInfo;
import com.cnpc.framework.base.pojo.Result;
import com.cnpc.framework.base.service.UserRoleService;
import com.cnpc.framework.base.service.UserService;
import com.cnpc.framework.utils.EncryptUtil;
import com.cnpc.framework.utils.PropertiesUtil;
import com.cnpc.framework.utils.StrUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private UserRoleService userRoleService;

    private final static String initPassword= PropertiesUtil.getValue("user.initPassword");

    /**
     * 用户编辑
     *
     * @return
     */
    @RefreshCSRFToken
    @RequestMapping(method = RequestMethod.GET, value = "/edit")
    private String edit(String id, HttpServletRequest request) {

        request.setAttribute("id", id);
        return "base/user/user_edit";
    }

    /**
     * 用户列表
     */

    @RequestMapping(method = RequestMethod.GET, value = "/list")
    private String list() {
        return "base/user/user_list";
    }

    //用户列表 测试数据权限
    @RequestMapping(method = RequestMethod.GET, value="/list_ff")
    private String listForFf(){
        return "base/user/user_ff_list";
    }

    @VerifyCSRFToken
    @RequestMapping(method = RequestMethod.POST, value = "/save")
    @ResponseBody
    private Result saveUser(User user, HttpServletRequest request) {
        if (StrUtil.isEmpty(user.getId())) {
            //设置初始密码
            user.setPassword(EncryptUtil.getPassword(initPassword,user.getLoginName()));
            String userId = userService.save(user).toString();
            userRoleService.setRoleForRegisterUser(userId);
            //头像和用户管理
            userService.updateUserAvatar(user, request.getRealPath("/"));
        } else {
            User oldUser=this.getUser(user.getId());
            BeanUtils.copyProperties(user,oldUser,"password");
            if(!oldUser.getLoginName().equals(user.getLoginName())){
                oldUser.setPassword(EncryptUtil.getPassword(initPassword,user.getLoginName()));
            }
            oldUser.setUpdateDateTime(new Date());
            userService.update(oldUser);
        }
        return new Result(true);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/delete/{id}")
    @ResponseBody
    private Result deleteUser(@PathVariable("id") String id) {

        User user = userService.get(User.class, id);
        try {
            userService.delete(user);
        } catch (Exception e) {
            return new Result(false);
        }
        return new Result(true);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/get")
    @ResponseBody
    private User getUser(String id) {
        //return userService.getUserById(id);
        return userService.get(User.class, id);
    }

    /**
     * loadData
     *
     * @param pInfo
     * @param conditions
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/loadData")
    @ResponseBody
    public Map<String, Object> loadData(String pInfo, String conditions) {

        Map<String, Object> map = new HashMap<String, Object>();
        PageInfo pageInfo = JSON.parseObject(pInfo, PageInfo.class);
        DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
        pageInfo.setCount(userService.getCountByCriteria(criteria));
        map.put("pageInfo", pageInfo);
        map.put("data", userService.getListByCriteria(criteria, pageInfo));
        return map;
    }

    /**
     * tab方式curd demo
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/tab/list")
    private String tablist() {

        return "base/user/user_tab_list";
    }

    /**
     * 新的页面打开 curd demo
     */
    @RequestMapping(method = RequestMethod.GET, value = "/page/list")
    private String pagelist(String id, HttpServletRequest request) {
        request.setAttribute("selectId", id);
        return "base/user/user_page_list";
    }

    /**
     * 用户编辑 new page
     *
     * @return
     */
    @RefreshCSRFToken
    @RequestMapping(method = RequestMethod.GET, value = "/page/edit")
    private String pageEdit(String id, HttpServletRequest request) {

        request.setAttribute("id", id);
        return "base/user/user_page_edit";
    }

    /**
     * 用户头像上传 avatar
     */
    @RequestMapping(method = RequestMethod.GET, value = "/avatar")
    private String avatar(String userId, HttpServletRequest request) {
        request.setAttribute("userId", userId);
        return "base/user/user_avatar";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/getAvatar")
    @ResponseBody
    private UserAvatar getAvatar(String userId) {
        return userService.getAvatarByUserId(userId);
    }

    @RequestMapping(value = "/select/{multiple}/{ids}/{callback}", method = RequestMethod.GET)
    public String selectUserPage(@PathVariable("multiple") String multiple,
                                 @PathVariable("ids") String ids,
                                 @PathVariable("callback") String callback, HttpServletRequest request) {
        request.setAttribute("multiple", multiple);
        request.setAttribute("ids", ids);
        request.setAttribute("callback",callback);
        return "base/user/user_select_list";
    }

    @RequestMapping(value = "/names", method = RequestMethod.POST)
    @ResponseBody
    public Map getNamesByIds(String ids) {
        Map<String,String> map=new HashMap<>();
            String names=userService.getUserNamesByUserIds(ids);
            map.put("name",names);
            return map;

    }
}


text:
<?php

declare(strict_types=1);

namespace Doctrine\Migrations;

/**
 * The Events class contains constants for event names that a user can subscribe to.
 */
final class Events
{
    public const onMigrationsMigrating        = 'onMigrationsMigrating';
    public const onMigrationsMigrated         = 'onMigrationsMigrated';
    public const onMigrationsVersionExecuting = 'onMigrationsVersionExecuting';
    public const onMigrationsVersionExecuted  = 'onMigrationsVersionExecuted';
    public const onMigrationsVersionSkipped   = 'onMigrationsVersionSkipped';
}


text:
module Mongoid
  module Collections

    # Provides behaviour for retrying commands on connection failure.
    module Retry

      # Retries command on connection failures.
      #
      # This is useful when using replica sets. When a primary server wents
      # down and a command is issued, the driver will raise a
      # Mongo::ConnectionFailure. We wait a little bit, because nodes are
      # electing themselves, and then retry the given command.
      #
      # By setting Mongoid.max_retries_on_connection_failure to a value of 0,
      # no attempt will be made, immediately raising connection failure.
      # Otherwise it will attempt to make the specified number of retries
      # and then raising the exception to clients.
      #
      # @example Retry the command.
      #   retry_on_connection_failure do
      #     collection.send(name, *args)
      #   end
      #
      # @since 2.0.0
      def retry_on_connection_failure
        retries = 0
        begin
          yield
        rescue Mongo::ConnectionFailure => ex
          retries = increase_retry_attempts(retries, ex)
          retry
        rescue Mongo::OperationFailure => ex
          if ex.message =~ /not master/
            retries = increase_retry_attempts(retries, ex)
            retry
          else
            raise ex
          end
        end
      end

      private

      def increase_retry_attempts(retries, ex)
        retries += 1
        raise ex if retries > Mongoid.max_retries_on_connection_failure
        Kernel.sleep(0.5)
        log_retry retries, ex
        retries
      end

      def log_retry(retry_number, ex)
        Mongoid.logger.warn "A #{ex.class.name} was raised. Retry attempt ##{retry_number}." if Mongoid.logger
      end
    end
  end
end


text:
N-Queens Problem Brute Force Solver implemented in Clojure

## Usage

```sh
lein uberjar
java -jar target/n-queens-bf-0.1.0-SNAPSHOT-standalone.jar 8
```


text:
The ChartAxisLabel control: ChartAxisLabel container for bar, line and other chart types. Based on C3.js..

**Extends**: [sap.ui.core.Element](https://openui5.hana.ondemand.com/#/api/sap.ui.core.Element) This module inherits all methods and attributes from the extended module and from all other modules in the inheritence hierarchy.

## Sample Usage (XML View)
This element must be used with the ui5.viz.Chart control and was designed to work best in XML views and in combination with data binding.
```xml
<Chart>
  <!-- tbd -->
</Chart>
```

## Properties
All properties have corresponding getters and setters. ([read which property methods are defined automatically](https://sapui5.hana.ondemand.com/#/api/sap.ui.base.ManagedObject))

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `any` | `null}` | Sets axis value. |
| `title` | `string` | `null}` | Sets axis label title. |
| `visible` | `boolean` | `true,` | Sets visibility of the element. |

## Aggregations
There are no public aggregations defined for `ui5.viz.ChartAxisLabel`.

## Events
All events return to the event callback handler [sap.ui.base.Event](https://openui5.hana.ondemand.com/#/api/sap.ui.base.Event). ([read which event methods are defined automatically](https://sapui5.hana.ondemand.com/#/api/sap.ui.base.ManagedObject))
* axisLabelUpdate Data was updated.

### `axisLabelUpdate`
Data was updated.

## Methods
There are no public methods defined for `ui5.viz.ChartAxisLabel`.


text:
package com.harmazing.openbridge.mod.operations.elasticsearch.service.impl;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.AndQueryBuilder;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.filter.Filter;
import org.elasticsearch.search.aggregations.bucket.filters.FiltersAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.filters.InternalFilters;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram.Bucket;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms.Order;
import org.elasticsearch.search.aggregations.metrics.cardinality.Cardinality;
import org.elasticsearch.search.aggregations.metrics.cardinality.CardinalityBuilder;
import org.elasticsearch.search.aggregations.metrics.cardinality.InternalCardinality;
import org.elasticsearch.search.aggregations.metrics.sum.Sum;
import org.elasticsearch.search.aggregations.metrics.sum.SumBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.harmazing.openbridge.mod.operations.elasticsearch.bean.AppMonitorForm;
import com.harmazing.openbridge.mod.operations.elasticsearch.bean.vo.FilterInfoVo;
import com.harmazing.openbridge.mod.operations.elasticsearch.bean.vo.FilterVo;
import com.harmazing.openbridge.mod.operations.elasticsearch.service.ESQuery;
import com.harmazing.openbridge.mod.operations.elasticsearch.service.IElasticSearchService;
import com.harmazing.openbridge.mod.operations.elasticsearch.service.LogSearchService;
import com.harmazing.openbridge.mod.operations.elasticsearch.util.LogType;

/**
 * elasticsearch 模块
 * @author admin
 *
 */
@Service
public class ElasticSearchServiceImpl implements IElasticSearchService{

	private static String[] pics = new String[]{"gif","png","css","js","ico","html"};
//	curl -XPOST '101.200.82.115:9200/logstash-*/app_log/_search?pretty' -d '{
//	"query":{
//	"bool":{
//	"filter":[
//	{
//	"range":{
//	"@timestamp":{
//	"gte":"2016-01-2710:26:40.111 +0800",
//	"lte":"2016-01-2810:26:42.222 +0800",
//	"format":"yyyy-MM-ddHH:mm:ss.SSS Z"
//	}
//	}
//	},
//	{
//	"term":{
//	"env_id":"12313"
//	}
//	}
//	]
//	}
//	},
//	"aggs":{
//	"result_agg":{
//	"date_histogram":{
//	"field":"@timestamp",
//	"interval":"hour",
//	"format":"yyyy-MM-ddHH:mm:ss.SSS Z",
//	"min_doc_count":0,
//	"extended_bounds":{
//	"min":"2016-01-2710:26:40.111 +0800",
//	"max":"2016-01-2810:26:42.222 +0800"
//	}
//	},
//	"aggs":{
//	"total_sum":{
//	"sum":{"field":"request_time"}
//	},
//	"success_sum":{
//	"filter":{
//	"term":{"status":"200"}
//	}
//	},
//	 "total_ip" : {
//    	"cardinality" : {
//        	"field" : "remote_addr.raw"
//        }
//    }
//	}
//	}
//	}
//	}
//	'

	@Override
	public List<Map<String,Object>> cost(AppMonitorForm form, LogType logType) throws UnknownHostException {
		ESQuery query = new ESQuery();
		AggregationBuilder sub1 = AggregationBuilders
				.filter("success_count")
			    .filter(QueryBuilders.termQuery("status", "200"));
		SumBuilder sub2 = AggregationBuilders
				.sum("total_sum")
				.field("request_time");
		CardinalityBuilder sub3 = AggregationBuilders
				.cardinality("total_ip")
				.field("remote_host.raw");
		AggregationBuilder aggregation = AggregationBuilders
                .dateHistogram("result_agg")
                .field("@timestamp")
                .interval(form.getXtype().equals("d")?DateHistogramInterval.DAY :
                		(form.getXtype().equals("h")?DateHistogramInterval.HOUR:DateHistogramInterval.MINUTE))
                .format(LogSearchService.sdf.toPattern()+" Z")
                .minDocCount(0)
                .extendedBounds(form.getBeginDate()+" +0800", form.getEndDate()+" +0800")
                .subAggregation(sub1).subAggregation(sub2).subAggregation(sub3);
		List<AbstractAggregationBuilder> abs = new ArrayList<AbstractAggregationBuilder>();
		abs.add(aggregation);

		List<QueryBuilder> qbs = new ArrayList<QueryBuilder>();
		BoolQueryBuilder bqb = QueryBuilders.boolQuery();
		qbs.add(bqb);
		QueryBuilder timeQuery = QueryBuilders.rangeQuery("@timestamp")
				.from(form.getBeginDate()+" +0800")
				.to(form.getEndDate()+" +0800")
				.includeLower(true)
				.includeUpper(false)
				.format(LogSearchService.sdf.toPattern()+" Z");
		bqb.filter(timeQuery);
//		qbs.add(timeQuery);
		if(StringUtils.hasText(form.getAppId())){
			QueryBuilder appId = QueryBuilders.termQuery("service_id", form.getAppId());
			bqb.filter(appId);
		}
		if(StringUtils.hasText(form.getEnvId())){
			QueryBuilder containId = QueryBuilders.termQuery("env_id", form.getEnvId());
			bqb.filter(containId);
		}

		if(StringUtils.hasText(form.getShowStaticSource()) && "1".equals(form.getShowStaticSource())){
			AndQueryBuilder qad = QueryBuilders.andQuery();
			for(String pic : pics){
				QueryBuilder aqn1 = QueryBuilders.notQuery(QueryBuilders.termQuery("request_type", pic));
				qad.add(aqn1);
			}
			bqb.filter(qad);
		}

		if(StringUtils.hasText(form.getStrfilter()) && !"".equals(form.getStrfilter().trim())){
//			QueryBuilder strFilter = QueryBuilders.notQuery(QueryBuilders.matchQuery("uri", form.getStrfilter()));
//			bqb.filter(strFilter);
			FilterVo filter = JSONObject.parseObject(form.getStrfilter(), FilterVo.class);

			if(filter.getFilterc() !=null && filter.getFilterc().size() >0){
				StringBuffer  msg = new StringBuffer();
				for(int i =0 ;i<filter.getFilterc().size();i++){
					FilterInfoVo info = filter.getFilterc().get(i);
					if(i!=0){
						msg.append(" ").append(info.getOperator()).append(" ").append(info.getKeyword());
					}
					else {
						msg.append(info.getKeyword());
					}
				}
				QueryStringQueryBuilder sb = QueryBuilders.queryStringQuery(msg.toString());
				sb.defaultField("uri");
				bqb.filter(sb);
			}

			if(filter.getFilternc() !=null && filter.getFilternc().size() >0){
				StringBuffer  msg = new StringBuffer();
				for(int i =0 ;i<filter.getFilternc().size();i++){
					FilterInfoVo info = filter.getFilternc().get(i);
					if(i!=0){
						msg.append(" ").append(info.getOperator()).append(" ").append(info.getKeyword());
					}
					else {
						msg.append(info.getKeyword());
					}
				}
				QueryStringQueryBuilder sb = QueryBuilders.queryStringQuery(msg.toString());
				sb.defaultField("uri");
				bqb.filter(QueryBuilders.notQuery(sb));
			}
		}
		ESQuery es = new ESQuery();
		SearchResponse response1 = es.commonSearch(new String[]{"logstash-*"}, new String[]{logType.getType()}, qbs, abs);
		List<Map<String,Object>> rs = new ArrayList<Map<String,Object>>();
		if(response1.getAggregations()!=null){
			InternalHistogram<Bucket> a = (InternalHistogram)response1.getAggregations().get("result_agg");
			for(Bucket b : a.getBuckets()){
				Map<String,Object> r = new HashMap<String,Object>();
				Aggregations as = b.getAggregations();
				Map<String, Aggregation> param = as.asMap();
				Filter  p1 = (Filter) param.get("success_count");
				Sum p2 = (Sum)param.get("total_sum");
				Cardinality p3 = (Cardinality)param.get("total_ip");
				if(b.getKey() instanceof org.joda.time.DateTime){
					org.joda.time.DateTime dt = (org.joda.time.DateTime)b.getKey();
					r.put("timestamp", dt.getMillis());
				}
				else{
					r.put("timestamp", b.getKey());
				}
				r.put("count", b.getDocCount());
				r.put("success_count", p1.getDocCount());
				r.put("total_sum", p2.getValue());
				r.put("total_ip", p3.getValue());
				rs.add(r);
			}
		}
		return rs;

	}

	@Override
	public List<Map<String, Object>> top(AppMonitorForm form, String type,LogType logType)
			throws UnknownHostException {
		ESQuery query = new ESQuery();
		AggregationBuilder lastAgg = null;
		//不能用size方法 排行不准确,具体原因看官网,这边就全部统计出来 然后取最前面的TOP的数据即可
		if(type.equals("frequency")){
			//按次数排行 根据url 用于监控页面
			lastAgg = AggregationBuilders
	                .terms("methodCount")
	                .field("uri.raw")
	                .size(0);
		}
		else if(type.equals("visit_time")){
			//访问次数 根据 service_id 用于看板页面
			lastAgg = AggregationBuilders
	                .terms("visit_time")
	                .field("service_id.raw")
	                .size(0);
		}
		else if(type.equals("elapsed")){
			//访问耗时  根据service_id 用于看板页面
			lastAgg = AggregationBuilders
					.terms("elapsed")
					.field("service_id.raw")
					.size(0)
					.order(Terms.Order.aggregation("sum_request_time", false))
					.subAggregation(
							AggregationBuilders.sum("sum_request_time").field("request_time")
					);

		}
		else if(type.equals("total_ip")){
			//访问ip数  根据service_id 用于看板页面
			lastAgg = AggregationBuilders
					.terms("total_ip")
					.field("service_id.raw")
					.size(0)
					.order(Terms.Order.aggregation("total_ip_count", false))
					.subAggregation(
							AggregationBuilders.cardinality("total_ip_count").field("remote_host.raw")
					);

		}
		else if(type.equals("success_ratio")){
			//访问成功率  根据service_id 用于看板页面
			lastAgg = AggregationBuilders
					.terms("success_ratio")
					.field("service_id.raw")
					.size(0)
					.subAggregation(
							AggregationBuilders.filter("ok").filter(QueryBuilders.termQuery("status", "200"))
					);
		}
		else if(type.equals("ip")){
			//按IP数排行 remote_addr
			lastAgg = AggregationBuilders
	                .terms("ipCount")
	                .field("remote_host.raw")
	                .size(0);
		}
		else{
			//按耗时排行
			lastAgg = AggregationBuilders
					.terms("methodTime")
					.field("uri.raw")
					.size(0)
					.order(Terms.Order.aggregation("sum_request_time", false))
					.subAggregation(
				        AggregationBuilders.sum("sum_request_time").field("request_time")
				    );
		}
		List<AbstractAggregationBuilder> abs = new ArrayList<AbstractAggregationBuilder>();
		abs.add(lastAgg);

		List<QueryBuilder> qbs = new ArrayList<QueryBuilder>();
		BoolQueryBuilder bqb = QueryBuilders.boolQuery();
		qbs.add(bqb);
		QueryBuilder timeQuery = QueryBuilders.rangeQuery("@timestamp")
				.from(form.getBeginDate()+" +0800")
				.to(form.getEndDate()+" +0800")
				.includeLower(true)
				.includeUpper(false)
				.format(LogSearchService.sdf.toPattern()+" Z");
		bqb.filter(timeQuery);
		if(StringUtils.hasText(form.getAppId())){
			QueryBuilder appId = QueryBuilders.termQuery("service_id", form.getAppId());
			bqb.filter(appId);
		}
		if(StringUtils.hasText(form.getEnvId())){
			QueryBuilder containId = QueryBuilders.termQuery("env_id", form.getEnvId());
			bqb.filter(containId);
		}
		if(form.getFilter()!=null){
			for(Map.Entry<String, Object> o : form.getFilter().entrySet()){
				String k = o.getKey();
				Object v = o.getValue();
				QueryBuilder containId = QueryBuilders.termQuery(k, v);
				bqb.filter(containId);
			}
		}
		if(StringUtils.hasText(form.getShowStaticSource()) && "1".equals(form.getShowStaticSource())){
			AndQueryBuilder qad = QueryBuilders.andQuery();
			for(String pic : pics){
				QueryBuilder aqn1 = QueryBuilders.notQuery(QueryBuilders.termQuery("request_type", pic));
				qad.add(aqn1);
			}
			bqb.filter(qad);
		}
		if(StringUtils.hasText(form.getStrfilter()) && !"".equals(form.getStrfilter().trim())){
//			QueryBuilder strFilter = QueryBuilders.notQuery(QueryBuilders.matchQuery("uri", form.getStrfilter()));
//			bqb.filter(strFilter);
			FilterVo filter = JSONObject.parseObject(form.getStrfilter(), FilterVo.class);
//			if(StringUtils.hasText(filter.getFilterpic()) && filter.getFilterpic().equals("n")){
//				AndQueryBuilder qad = QueryBuilders.andQuery();
//				for(String pic : pics){
//					QueryBuilder aqn1 = QueryBuilders.notQuery(QueryBuilders.termQuery("request_type", pic));
//					qad.add(aqn1);
//				}
//				bqb.filter(qad);
//			}
			if(filter.getFilterc() !=null && filter.getFilterc().size() >0){
				StringBuffer  msg = new StringBuffer();
				for(int i =0 ;i<filter.getFilterc().size();i++){
					FilterInfoVo info = filter.getFilterc().get(i);
					if(i!=0){
						msg.append(" ").append(info.getOperator()).append(" ").append(info.getKeyword());
					}
					else {
						msg.append(info.getKeyword());
					}
				}
				QueryStringQueryBuilder sb = QueryBuilders.queryStringQuery(msg.toString());
				sb.defaultField("uri");
				bqb.filter(sb);
			}

			if(filter.getFilternc() !=null && filter.getFilternc().size() >0){
				StringBuffer  msg = new StringBuffer();
				for(int i =0 ;i<filter.getFilternc().size();i++){
					FilterInfoVo info = filter.getFilternc().get(i);
					if(i!=0){
						msg.append(" ").append(info.getOperator()).append(" ").append(info.getKeyword());
					}
					else {
						msg.append(info.getKeyword());
					}
				}
				QueryStringQueryBuilder sb = QueryBuilders.queryStringQuery(msg.toString());
				sb.defaultField("uri");
				bqb.filter(QueryBuilders.notQuery(sb));
			}
		}
		ESQuery es = new ESQuery();
		SearchResponse response1 = es.commonSearch(new String[]{"logstash-*"}, new String[]{logType.getType()}, qbs, abs);
		Terms last = null;
		if(response1.getAggregations()!=null){
			if(type.equals("frequency")){
				last = response1.getAggregations().get("methodCount");
			}
			else if(type.equals("ip")){
				//按IP数排行 remote_addr
				last = response1.getAggregations().get("ipCount");
			}
			else if(type.equals("visit_time")){
				last = response1.getAggregations().get("visit_time");
			}
			else if(type.equals("elapsed")){
				last = response1.getAggregations().get("elapsed");
			}
			else if(type.equals("total_ip")){
				last = response1.getAggregations().get("total_ip");
			}
			else if(type.equals("success_ratio")){
				last = response1.getAggregations().get("success_ratio");
			}
			else{
				last = response1.getAggregations().get("methodTime");
			}
		}
		List<Map<String, Object>> r = new ArrayList<Map<String, Object>>();
		int i=0;
		if(last!=null && last.getBuckets()!=null && last.getBuckets().size()>0){
			for(org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket b : last.getBuckets()){
				if(form.getTop()!=-1 && i>=form.getTop() && !type.equals("success_ratio")){
					//成功率 全部放进去 然后手动排序
					break ;
				}
				Map<String,Object> m = new HashMap<String,Object>();
				String key = (String) b.getKeyAsString();
				m.put("key", key);
				long count = b.getDocCount();
				m.put("value", count);
				if(type.equals("time")){
					Aggregations as = b.getAggregations();
					Map<String, Aggregation> param = as.asMap();
					Sum s = (Sum) param.get("sum_request_time");
					m.put("value", s.value());
				}
				else if(type.equals("elapsed")){
					Aggregations as = b.getAggregations();
					Map<String, Aggregation> param = as.asMap();
					Sum s = (Sum) param.get("sum_request_time");
					m.put("value", s.value());
				}
				else if(type.equals("total_ip")){
					Aggregations as = b.getAggregations();
					Map<String, Aggregation> param = as.asMap();
					Cardinality s = (Cardinality) param.get("total_ip_count");
					m.put("value", s.value());
				}
//				else if(type.equals("total_ip")){
//					Aggregations as = b.getAggregations();
//					Map<String, Aggregation> param = as.asMap();
//					Cardinality s = (Cardinality) param.get("total_ip_count");
//					m.put("value", s.value());
//				}
				else if(type.equals("success_ratio")){
					Aggregations as = b.getAggregations();
					Map<String, Aggregation> param = as.asMap();
					Filter s = (Filter) param.get("ok");
					m.put("ok", s.getDocCount());
				}
				r.add(m);
				i++;
			}
		}
		return r;
	}

//	{
//		  "aggs" : {
//		    "messages" : {
//		      "filters" : {
//		        "filters" : {
//		          "6pajfn55kl1d7ux5rjvzp8dwsavqiyz" :   { "term" : { "service_id.raw" : "6pajfn55kl1d7ux5rjvzp8dwsavqiyz"   }},
//		          "6p7fg2nomeqglxzg6jx9gquftcdhhyj1" : { "term" : { "service_id.raw" : "6p7fg2nomeqglxzg6jx9gquftcdhhyj1" }}
//		        }
//		      },
//		      "aggs" : {
//		      	 "total_ip" : {
//		         	"cardinality" : {
//		            	"field" : "remote_addr.raw"
//		            }
//		         }
//		      }
//		    }
//		  }
//		}
	public List<Map<String,Object>> appState(List<String> appIds,LogType logType) throws UnknownHostException{
		List<AbstractAggregationBuilder> abs = new ArrayList<AbstractAggregationBuilder>();
		FiltersAggregationBuilder fb = AggregationBuilders.filters("messages");
		for(String appId : appIds){
			fb.filter(appId, QueryBuilders.termQuery("service_id", appId));
		}
		fb.subAggregation(AggregationBuilders.cardinality("total_ip").field("remote_host.raw"));
		abs.add(fb);

		ESQuery es = new ESQuery();
		SearchResponse response1 = es.commonSearch(new String[]{"logstash-*"}, new String[]{logType.getType()}, null, abs);
		List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
		if(response1.getAggregations()!=null){
			InternalFilters last = response1.getAggregations().get("messages");
			if(last!=null && last.getBuckets()!=null){
				for( org.elasticsearch.search.aggregations.bucket.filters.InternalFilters.Bucket  b : last.getBuckets()){
					String key = b.getKey();
					long docCount = b.getDocCount();
					InternalCardinality totalIp = b.getAggregations().get("total_ip");
					long ipCount = totalIp.getValue();
					Map<String,Object> m = new HashMap<String, Object>();
					m.put("key", key);
					m.put("ipPd", ipCount);
					m.put("timePd", docCount);
					result.add(m);
				}
			}
		}
		return result;
	}

}


text:
<?php

class Ess_M2ePro_Block_Adminhtml_Walmart_Listing_Variation_Product_Manage_Tabs_Variations_Help
    extends Mage_Adminhtml_Block_Widget
{
    //########################################

    public function __construct()
    {
        parent::__construct();

        // Initialization block
        // ---------------------------------------
        $this->setId('walmartListingViewHelp');
        // ---------------------------------------

        $this->setTemplate('M2ePro/walmart/listing/variation/product/manage/tabs/variations/help.phtml');
    }

    //########################################
}


text:
/*
 * patAccelMeasurement.cc
 *
 *  Created on: Nov 25, 2011
 *      Author: jchen
 */

#include "patAccelMeasurement.h"
#include "patAccelDDR.h"
patAccelMeasurement::patAccelMeasurement(double accel_time,
		double accel) {

	m_measurement_type = ACCEL;
	m_timestamp = accel_time;
	m_accel = accel;

	m_ddr = new patAccelDDR(this);
}

double patAccelMeasurement::getAccel() const {
	return m_accel;
}
void patAccelMeasurement::setMeasurementType() {
	m_measurement_type = MeasurementType(ACCEL);
}

MeasurementModelParam patAccelMeasurement::getMeasurementModelParam(const patArc* arc,
		TransportMode mode) const {
	MeasurementModelParam param;
	param.mode = mode;
	param.length_of_arc = arc->getLength();
	param.foot_on_arc = 0.5;
	param.distance_to_arc = 0.0;
	return param;
}

double patAccelMeasurement::getSimpleValue() const{
	return m_accel;
}

bool patAccelMeasurement::isGPS() const{
	return false;
}

 ostream& operator<<(ostream& str, const patAccelMeasurement& x){
 		str.precision(15);
	str << "ACCEL Time:" << x.m_timestamp << ", " << x.m_accel<<endl;

 }


text:
package org.hitogo.button.core;

/**
 * Public api interface for the basic button object. This interface includes the most basic button
 * methods which is provided by the builder classes.
 *
 * @param <T> Type of the ButtonParams object that the alert is using.
 * @see ButtonParams
 * @see ButtonImpl
 * @since 1.0.0
 */
public interface Button<T extends ButtonParams> {

    /**
     * Returns the button params object. The params object is storing all values for the button.
     *
     * @return an object which is extending ButtonParams
     * @since 1.0.0
     */
    T getParams();

    /**
     * Returns the button type. The types are based on the enum ButtonType which includes VIEW,
     * TEXT and OTHER.
     *
     * @return Type for this alert
     * @see ButtonType
     * @since 1.0.0
     */
    ButtonType getButtonType();
}


text:
BEGIN TRANSACTION;
DROP INDEX i1;
SELECT * FROM t1 WHERE b<1;
ROLLBACK;


text:
<?php

namespace Opis\Colibri\Serializable;

use Closure;
use Serializable;
use RuntimeException;
use Opis\Colibri\Application;
use Opis\Closure\SerializableClosure;

class StorageCollection implements Serializable
{
    protected $storages = array();
    protected $instances = array();
    protected $builder;
    protected $defaultStorage;

    public function __construct(Closure $builder)
    {
        $this->builder = $builder;
    }

    public function add($storage, Closure $constructor, $default = false)
    {
        if ($this->defaultStorage === null) {
            $default = true;
        }

        if ($default) {
            $this->defaultStorage = $storage;
        }

        $this->storages[$storage] = $constructor;
        unset($this->instances[$storage]);

        return $this;
    }

    public function remove($storage)
    {
        unset($this->storages[$storage]);
        unset($this->instances[$storage]);

        if ($this->defaultStorage === $storage) {
            $this->defaultStorage = null;
            if (!empty($this->storages)) {
                $this->defaultStorage = array_shift(array_keys($this->storages));
            }
        }

        return $this;
    }

    public function has($storage)
    {
        return isset($this->storages[$storage]);
    }

    public function setDefault($storage)
    {
        if ($this->has($storage)) {
            $this->defaultStorage = $storage;
        }

        return $this;
    }

    public function get(Application $app, $storage = null)
    {
        if ($storage === null) {
            $storage = $this->defaultStorage;
        }

        if (!$this->has($storage)) {
            throw new RuntimeException('Unknown storage ' . $storage);
        }

        if (!isset($this->instances[$storage])) {
            $constructor = $this->storages[$storage];
            $builder = $this->builder;
            $this->instances[$storage] = $builder($storage, $constructor, $app);
        }

        return $this->instances[$storage];
    }

    public function serialize()
    {
        SerializableClosure::enterContext();
        $object = serialize(array(
            'builder' => SerializableClosure::from($this->builder),
            'defaultStorage' => $this->defaultStorage,
            'storages' => array_map(function ($value) {
                    return SerializableClosure::from($value);
                }, $this->storages),
        ));
        SerializableClosure::exitContext();
        return $object;
    }

    public function unserialize($data)
    {
        $object = SerializableClosure::unserializeData($data);
        $this->builder = $object['builder']->getClosure();
        $this->defaultStorage = $object['defaultStorage'];
        $this->storages = array_map(function ($value) {
            return $value->getClosure();
        }, $object['storages']);
    }
}


text:
title: What is the full set of attribute expressions Mixer supports?
weight: 20
---

Please see the [Expression Language
Reference](/docs/reference/config/policy-and-telemetry/expression-language/) for
the full set of supported attribute expressions.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.Identity;
using OwinAuthenticationApi.Models;

namespace OwinAuthenticationApi
{
    public class AppUserClaimsIdentityFactory : ClaimsIdentityFactory<AppUser, string>
    {
        public async override Task<ClaimsIdentity> CreateAsync(UserManager<AppUser, string> manager,
            AppUser user, string authenticationType)
        {
            var identity = await base.CreateAsync(manager, user, authenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Country, user.Country));
            return identity;
        }
    }
}


text:
require 'zlib'

module Cabinet
  class Instance
    attr_accessor :connection, :directory

    def initialize(provider, auth={})
      fog_config      = auth.merge({:provider => fog_provider(provider)})
      self.connection = Fog::Storage.new(fog_config)
    end

    def directory=(name)
      @directory = connection.directories.get(name) || connection.directories.create(:key => name)
    end

    alias :container= :directory=
    alias :bucket=    :directory=

    def get(name)
      file(name).body
    end

    def list(regexp=/.*/)
      directory.files.reload
      directory.files.select{|f| f.key.match(regexp)}.to_a.map(&:key)
    end

    def put(name, content)
      content = content.to_s

      begin
        directory.files.create(:key => name, :body => content).content_length == content.length
      rescue
        false
      end
    end

    def touch(name)
      (exists?(name) ? put(name, get(name)) : put(name, "")) and !!reload(name)
    end

    def append(name, new_content)
      content = exists?(name) ? get(name) + new_content : new_content
      put(name, content) and !!reload(name)
    end

    def delete(name_or_regexp)
      @file = nil

      directory.files.reload

      if name_or_regexp.class == Regexp
        directory.files.select{|f| f.key.match(name_or_regexp)}.each do |file|
          file.destroy
        end
      else
        directory.files.get(name_or_regexp).destroy
      end

      true
    end

    def copy_to(klass, name)
      klass.put(name, get(name))
    end

    def exists?(name)
      !!file(name)
    end

    def modified(name)
      file(name).last_modified + 0 if exists?(name)
    end

    def compress(name, content)
      name = name.gsub(/(.+?)(\.gz)?$/, '\1.gz')
      tmp  = "/tmp/cabinet-tmp-#{name}-#{Time.now}"

      File.open(tmp, 'w') do |f|
        gz = Zlib::GzipWriter.new(f)
        gz.write content
        gz.close
      end

      put(name, File.read(tmp)) and (File.unlink(tmp) == 1)
    end

    def decompress(name)
      Zlib::GzipReader.new(StringIO.new(get(name))).read
    end

    private
      def file(name)
        raise 'No directory specified' unless directory

        if @file && @file.key == name
          @file
        else
          reload(name)
        end
      end

      def reload(name)
        directory.files.reload
        @file = directory.files.get(name)
      end

      def fog_provider(provider)
        case provider.to_s.downcase
          when 'aws', 's3', 'amazon'
            'AWS'
          when 'rackspace', 'cloudfiles', 'cloud_files'
            'Rackspace'
          when 'google', 'google_storage'
            'Google'
          when 'local', 'localhost', 'filesystem'
            'Local'
          else
            raise ArgumentError, "#{provider} is not a valid provider"
        end
      end
  end
end


text:
<!DOCTYPE html>

{% include head.html %}

Dockerizing Linked Data

                {% include primary-nav-items.html %}

            {{ content }}

        {% include footer.html %}


text:
from ca.base.generations import Generations
from ca.base.gui import play

class BriansBrain(Generations):
    states = 3
    def birth(self):
        return self.live_count == 2
    def survival(self):
        return False

play(BriansBrain)


text:
<?php
App::uses('AppShell', 'Console/Command');
App::uses('Lapis', 'Lapis.Lib');

class KeysShell extends AppShell {
	public $uses = array('Lapis.Requester');

	public function main() {
		$this->out('Lapis keys generator.');
	}

	public function getOptionParser() {
		$parser = parent::getOptionParser();
		$parser->addOption('yes', array(
			'short' => 'y',
			'help' => 'Do not prompt for confirmation. Be careful!',
			'boolean' => true
		));
		return $parser;
	}

	public function generate() {
		// TODO: options
		// --keysize
		// --root
		// --parent_id
		// --file
		// --password

		$options = array(
			'keysize' => 4096,
			'parent' => null,
			'savePrivateToDb' => true,
			'privateKeyLocation' => null,
			'password' => null
		);
		$toAsk = array(
			'parent' => true,
			'save' => true,
		);

		if ($this->params['yes']) {
			$this->out('Interaction free mode.');
			$toAsk['parent'] = false;
			$toAsk['save'] = false;
		}

		if ($toAsk['parent']) {
			$isRoot = $this->in('Is this a root key pair?', array('y', 'n'), 'y');
			if ($isRoot !== 'y') {
				$options['parent'] = $this->in('Enter parent key ID:');
			}
		}
		if ($toAsk['save']) {
			$savePrivateToDb = $this->in('Save root private key to database?', array('y', 'n'), 'y');
			if ($savePrivateToDb === 'y') {
				$options['savePrivateToDb'] = true;
				$options['password'] = $this->in("WARNING: It is a good practice to not store private key unencrypted in database.\nEnter password to encrypt private key before storing in database, blank for none (no encryption).");
			} else {
				$options['savePrivateToDb'] = false;
				$options['privateKeyLocation'] = $this->in('Enter private key location to save to:', null, APP . 'private.key');
			}
		}

		$this->out('Generating root public key pair...');
		if ($this->Requester->generate($options['password'], $options)) {
			$this->out('Key pair generated and saved successfully with key ID: ' . $this->Requester->getLastInsertID());

			if (!$options['savePrivateToDb']) {
				$this->out('Private key is written successfully to ' . $options['privateKeyLocation']);
			}
		} else {
			$this->out('Failure encountered when generating key pair.');
		}
	}
}


text:
package joshie.progression.gui.filters;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import joshie.progression.api.criteria.IFilterProvider;
import joshie.progression.api.criteria.IFilterType;
import joshie.progression.api.gui.Position;
import joshie.progression.gui.core.FeatureAbstract;
import net.minecraft.client.renderer.GlStateManager;
import org.lwjgl.opengl.GL11;

import java.util.ArrayList;
import java.util.concurrent.Callable;

import static joshie.progression.gui.core.GuiList.*;

public class FeatureItemPreview extends FeatureAbstract {
    private IFilterType filter = FilterTypeItem.INSTANCE;
    private ArrayList<Object> sorted;
    private int position;

    public FeatureItemPreview() {}

    public void select(IFilterType filter) {
        this.filter = filter;
        updateSearch();
    }

    @Override
    public boolean scroll(int mouseX, int mouseY, boolean scrolledDown) {
        if (ITEM_EDITOR.isVisible()) return false;
        mouseY -= 95;
        if (mouseY >= 40 && mouseY <= 110) {
            if (scrolledDown) position = Math.min(sorted.size() - filter.getChange(), position + filter.getChange());
            else position = Math.max(0, position - filter.getChange());
            return true;
        }

        return false;
    }

    private static Cache<Object, ArrayList<Object>> cacheList = CacheBuilder.newBuilder().maximumSize(64).build();

    public ArrayList<Object> getAllItems() {
        try {
            return cacheList.get(filter, new Callable<ArrayList<Object>>() {
                @Override
                public ArrayList<Object> call() throws Exception {
                    return (ArrayList<Object>) filter.getAllItems();
                }
            });
        } catch (Exception e) {
            return (ArrayList<Object>) filter.getAllItems();
        }
    }

    public void updateSearch() {
        int size1 = sorted != null ? sorted.size() : 0;
        position = 0; //Reset the position on update

        if (FILTER_EDITOR.get() == null) return; //NO UPDATES!!!
        sorted = new ArrayList();
        for (Object stack: getAllItems()) {
            for (IFilterProvider filter: FILTER_EDITOR.get().getFilters()) {
                if (filter.getProvided().matches(stack)) {
                    sorted.add(stack);
                }
            }
        }

        if (sorted.size() < size1) {
            //GuiCore.GROUP_EDITOR.offsetX = 0; //Reset the offset on update
            CORE.resetX();
        }
    }

    @Override
    public void drawFeature(int mouseX, int mouseY) {
        if (ITEM_EDITOR.isVisible()) return;
        GlStateManager.clear(GL11.GL_DEPTH_BUFFER_BIT);
        if (sorted == null) {
            updateSearch();
        }

        mouseY -= 95;

        int width = (int) ((double) (screenWidth - 10) / filter.getScale());
        int j = 0;
        int k = 0;
        for (int i = position; i < position + (width * 4); i++) {
            if (i >= 0 && i < sorted.size()) {
                filter.draw(offset, sorted.get(i), 0, j, Position.BOTTOM.yOffset, k, mouseX, mouseY);

                j++;

                if (j >= width) {
                    j = 0;
                    k++;
                }
            }
        }
    }

    @Override
    public boolean isOverlay() {
        return false;
    }
}


text:
package org.snf4j.websocket.handshake;

enum HttpStatus {

	SWITCHING_PROTOCOLS(101, "Switching Protocols"),
	BAD_REQUEST(400, "Bad Request"),
	FORBIDDEN(403, "Forbidden"),
	NOT_FOUND(404, "Not Found"),
	REQUEST_ENTITY_TOO_LARGE(413, "Request Entity Too Large"),
	UPGRADE_REQUIRED(426, "Upgrade Required");

	private final int status;

	private final String reason;

	HttpStatus(int status, String reason) {
		this.status = status;
		this.reason = reason;
	}

	public int getStatus() {
		return status;
	}

	public String getReason() {
		return reason;
	}
}


text:
@interface HDNavigationController : UINavigationController

@end


text:
<?php

/** @file
* @brief
*/

if (!defined('GLPI_ROOT')) {
   die("Sorry. You can't access this file directly");
}

/// Class SolutionTemplate
/**
 * Template for task
 * @since version 9.1
**/
class TaskTemplate extends CommonDropdown {

   // From CommonDBTM
   public $dohistory          = true;
   public $can_be_translated  = true;

   static $rightname          = 'taskcategory';

   static function getTypeName($nb=0) {
      return _n('Task template', 'Task templates', $nb);
   }

   function getAdditionalFields() {

      return array(array('name'  => 'taskcategories_id',
                         'label' => __('Task category'),
                         'type'  => 'dropdownValue',
                         'list'  => true),
                   array('name'  => 'actiontime',
                         'label' => __('Duration'),
                         'type'  => 'actiontime'),
                   array('name'  => 'content',
                         'label' => __('Content'),
                         'type'  => 'textarea'));
   }

   function getSearchOptions() {

      $tab                = parent::getSearchOptions();

      $tab[4]['name']     = __('Content');
      $tab[4]['field']    = 'content';
      $tab[4]['table']    = $this->getTable();
      $tab[4]['datatype'] = 'text';
      $tab[4]['htmltext'] = true;

      $tab[3]['name']     = __('Task category');
      $tab[3]['field']    = 'name';
      $tab[3]['table']    = getTableForItemType('TaskCategory');
      $tab[3]['datatype'] = 'dropdown';

      return $tab;
   }

   /**
    * @see CommonDropdown::displaySpecificTypeField()
   **/
   function displaySpecificTypeField($ID, $field=array()) {

      switch ($field['type']) {
         case 'actiontime' :
            $toadd = array();
            for ($i=9 ; $i<=100 ; $i++) {
               $toadd[] = $i*HOUR_TIMESTAMP;
            }
            Dropdown::showTimeStamp("actiontime",
                                    array('min'             => 0,
                                          'max'             => 8*HOUR_TIMESTAMP,
                                          'value'           => $this->fields["actiontime"],
                                          'addfirstminutes' => true,
                                          'inhours'         => true,
                                          'toadd'           => $toadd));
            break;
      }
   }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied.  See the License for the
  specific language governing permissions and limitations
  under the License.
-->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache.mnemonic</groupId>
    <artifactId>mnemonic-parent</artifactId>
    <version>0.10.0-SNAPSHOT</version>
    <relativePath>../pom.xml</relativePath>
  </parent>

  <artifactId>mnemonic-examples</artifactId>
  <name>mnemonic-examples</name>
  <packaging>jar</packaging>

  <properties>
    <example.name>Main</example.name>
    <example.args></example.args>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.apache.mnemonic</groupId>
      <artifactId>mnemonic-core</artifactId>
      <version>${project.version}</version>
    </dependency>
    <!-- logging dependencies -->
    <!-- assume all APIs will be used -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jul-to-slf4j</artifactId>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jcl-over-slf4j</artifactId>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
    </dependency>
  </dependencies>

  <build>
    <extensions>
      <extension>
        <groupId>kr.motd.maven</groupId>
        <artifactId>os-maven-plugin</artifactId>
        <version>1.4.0.Final</version>
      </extension>
    </extensions>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                  <mainClass>${project.groupId}.examples.Main</mainClass>
                </transformer>
              </transformers>
              <minimizeJar>true</minimizeJar>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <!-- enable the following plugin in client POM
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <version>2.10</version>
        <executions>
          <execution>
            <id>copy</id>
            <phase>package</phase>
            <goals>
              <goal>copy</goal>
            </goals>
            <configuration>
              <artifactItems>
                <artifactItem>
                  <groupId>${project.groupId}</groupId>
                  <artifactId>mnemonic-nvml-vmem-service</artifactId>
                  <version>${project.version}</version>
                  <classifier>${os.detected.classifier}</classifier>
                  <type>jar</type>
                </artifactItem>
                <artifactItem>
                  <groupId>${project.groupId}</groupId>
                  <artifactId>mnemonic-pmalloc-service</artifactId>
                  <version>${project.version}</version>
                  <classifier>${os.detected.classifier}</classifier>
                  <type>jar</type>
                </artifactItem>
                <artifactItem>
                  <groupId>${project.groupId}</groupId>
                  <artifactId>mnemonic-utilities-service</artifactId>
                  <version>${project.version}</version>
                  <classifier>${os.detected.classifier}</classifier>
                  <type>jar</type>
                </artifactItem>
              </artifactItems>
              <outputDirectory>${project.build.directory}/service-dist</outputDirectory>
              <overWriteReleases>false</overWriteReleases>
              <overWriteSnapshots>false</overWriteSnapshots>
              <overWriteIfNewer>true</overWriteIfNewer>
            </configuration>
          </execution>
        </executions>
      </plugin>
      -->
    </plugins>
  </build>

  <profiles>
    <profile>
      <id>doc</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-javadoc-plugin</artifactId>
            <configuration>
              <additionalparam>-Xdoclint:all -Xdoclint:-missing</additionalparam>
            </configuration>
            <executions>
              <execution>
                <id>attach-javadocs</id>
                <goals>
                  <goal>jar</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
    <profile>
      <id>example</id>
      <activation>
        <property>
          <name>example</name>
        </property>
      </activation>
      <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <executions>
              <execution>
                <goals>
                  <goal>exec</goal>
                </goals>
              </execution>
            </executions>
            <configuration>
              <executable>java</executable>
              <arguments>
                <!-- replace it with ${project.build.directory}/service-dist in client POM -->
                <argument>-Djava.ext.dirs=${memory.service.dist.dir}</argument>
                <argument>-ea</argument>
                <argument>-classpath</argument>
                <classpath />
                <argument>${project.groupId}.examples.${example.name}</argument>
                <commandlineArgs>${example.args}</commandlineArgs>
              </arguments>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </profile>

  </profiles>

</project>


text:
#include "tensorflow/contrib/lite/nnapi_delegate.h"
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "tensorflow/contrib/lite/builtin_op_data.h"
#include "tensorflow/contrib/lite/error_reporter.h"
#include "tensorflow/contrib/lite/model.h"
#include "tensorflow/contrib/lite/nnapi/NeuralNetworksShim.h"

namespace tflite {

// TODO(aselle): FATAL leaves resources hanging.
void FATAL(const char* format, ...) {
  va_list args;
  va_start(args, format);
  vfprintf(stderr, format, args);
  va_end(args);
  fflush(stderr);
  exit(1);
}

// TODO(aselle): Change the error model to use status codes.
#define CHECK_TFLITE_SUCCESS(x)                       \
  if (x != kTfLiteOk) {                               \
    FATAL("Aborting since tflite returned failure."); \
  }

#define CHECK_NN(x)                                   \
  if (x != ANEURALNETWORKS_NO_ERROR) {                \
    FATAL("Aborting since tflite returned failure."); \
  }

NNAPIAllocation::NNAPIAllocation(const char* filename,
                                 ErrorReporter* error_reporter)
    : MMAPAllocation(filename, error_reporter) {
  if (mmapped_buffer_ != MAP_FAILED)
    CHECK_NN(ANeuralNetworksMemory_createFromFd(buffer_size_bytes_, PROT_READ,
                                                mmap_fd_, 0, &handle_));
}

NNAPIAllocation::~NNAPIAllocation() {
  if (handle_) {
    ANeuralNetworksMemory_free(handle_);
  }
}

NNAPIDelegate::~NNAPIDelegate() {
  if (nn_model_) {
    ANeuralNetworksModel_free(nn_model_);
    nn_model_ = nullptr;
    // TODO(aselle): Is this thread-safe and callable multiple times?
  }
  // ANeuralNetworksShutdown();
}

// Adds the tensors of the interpreter to the NN API model.
// Returns the number of operands added.
uint32_t addTensorOperands(tflite::Interpreter* interpreter,
                           ANeuralNetworksModel* nn_model) {
  uint32_t next_id = 0;
  for (size_t i = 0; i < interpreter->tensors_size(); i++) {
    int32_t nn_type = 0;
    float scale = 1.0f;
    int32_t zeroPoint = 0;
    TfLiteTensor* tensor = interpreter->tensor(i);
    switch (tensor->type) {
      case kTfLiteNoType:
        // Tensors added during initialization of Ops don't have a type yet and
        // should not be registered with the NNAPI.
        continue;
      case kTfLiteFloat32:
        nn_type = ANEURALNETWORKS_TENSOR_FLOAT32;
        break;
      case kTfLiteUInt8:
        nn_type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
        scale = tensor->params.scale;
        zeroPoint = tensor->params.zero_point;
        break;
      case kTfLiteInt32:
        nn_type = ANEURALNETWORKS_TENSOR_INT32;
        scale = tensor->params.scale;
        zeroPoint = tensor->params.zero_point;
        break;
      default:
        FATAL("Unsupported type.");
    }
    // TODO(aselle): Note, many of these are intermediate results. Do I need
    // to ever specify these sizes. I am currently below doing setValue
    // on all of them, but I shouldn't in the future.
    // Answer(jeanluc): If all the operators can set the dimension correctly,
    // you won't need to.
    ANeuralNetworksOperandType operand_type{
        nn_type, static_cast<uint32_t>(tensor->dims->size),
        reinterpret_cast<uint32_t*>(tensor->dims->data), scale, zeroPoint};
    CHECK_NN(ANeuralNetworksModel_addOperand(nn_model, &operand_type));

    // TODO(aselle): Based on Michael's suggestion, limiting this to read
    // only memory
    if (tensor->allocation_type == kTfLiteMmapRo) {
      if (const NNAPIAllocation* alloc = dynamic_cast<const NNAPIAllocation*>(
              static_cast<const Allocation*>(tensor->allocation))) {
        CHECK_NN(ANeuralNetworksModel_setOperandValueFromMemory(
            nn_model, i, alloc->memory(), alloc->offset(tensor->data.raw),
            tensor->bytes));
      } else {
        CHECK_NN(ANeuralNetworksModel_setOperandValue(
            nn_model, i, tensor->data.raw, tensor->bytes));
      }
    }
    ++next_id;
  }
  return next_id;
}

// Adds the operations and their parameters to the NN API model.
// 'next-id' is the operand ID of the next operand of the model.
void AddOpsAndParams(tflite::Interpreter* interpreter,
                     ANeuralNetworksModel* nn_model, uint32_t next_id) {
  for (size_t i = 0; i < interpreter->nodes_size(); i++) {
    const auto* node_and_registration = interpreter->node_and_registration(i);
    const TfLiteNode& node = node_and_registration->first;
    const TfLiteRegistration& registration = node_and_registration->second;
    tflite::BuiltinOperator builtin =
        static_cast<tflite::BuiltinOperator>(registration.builtin_code);

    // Add the parameters.
    std::vector<uint32_t> augmented_inputs(
        node.inputs->data, node.inputs->data + node.inputs->size);

    auto add_scalar_int32 = [&nn_model, &augmented_inputs,
                             &next_id](int value) {
      ANeuralNetworksOperandType operand_type{.type = ANEURALNETWORKS_INT32};
      CHECK_NN(ANeuralNetworksModel_addOperand(nn_model, &operand_type))
      CHECK_NN(ANeuralNetworksModel_setOperandValue(nn_model, next_id, &value,
                                                    sizeof(int32_t)))
      augmented_inputs.push_back(next_id++);
    };

    auto add_scalar_float32 = [&nn_model, &augmented_inputs,
                               &next_id](float value) {
      ANeuralNetworksOperandType operand_type{.type = ANEURALNETWORKS_FLOAT32};
      CHECK_NN(ANeuralNetworksModel_addOperand(nn_model, &operand_type))
      CHECK_NN(ANeuralNetworksModel_setOperandValue(nn_model, next_id, &value,
                                                    sizeof(float)))
      augmented_inputs.push_back(next_id++);
    };

    auto add_add_params = [&add_scalar_int32]() { add_scalar_int32(0); };

    auto add_pooling_params = [&add_scalar_int32](void* data) {
      auto builtin = reinterpret_cast<TfLitePoolParams*>(data);
      add_scalar_int32(builtin->padding);
      add_scalar_int32(builtin->stride_width);
      add_scalar_int32(builtin->stride_height);
      add_scalar_int32(builtin->filter_width);
      add_scalar_int32(builtin->filter_height);
      add_scalar_int32(builtin->activation);
    };

    auto add_convolution_params = [&add_scalar_int32](void* data) {
      auto builtin = reinterpret_cast<TfLiteConvParams*>(data);
      add_scalar_int32(builtin->padding);
      add_scalar_int32(builtin->stride_width);
      add_scalar_int32(builtin->stride_height);
      add_scalar_int32(builtin->activation);
    };

    auto add_depthwise_conv_params = [&add_scalar_int32](void* data) {
      auto builtin = reinterpret_cast<TfLiteDepthwiseConvParams*>(data);
      add_scalar_int32(builtin->padding);
      add_scalar_int32(builtin->stride_width);
      add_scalar_int32(builtin->stride_height);
      add_scalar_int32(builtin->depth_multiplier);
      add_scalar_int32(builtin->activation);
    };

    auto add_fully_connected_params = [&add_scalar_int32](void* data) {
      auto builtin = reinterpret_cast<TfLiteFullyConnectedParams*>(data);
      add_scalar_int32(builtin->activation);
    };

    auto add_concatenation_params = [&add_scalar_int32](void* data) {
      auto builtin = reinterpret_cast<TfLiteConcatenationParams*>(data);
      add_scalar_int32(builtin->axis);
      if (builtin->activation != kTfLiteActNone) {
        FATAL("Concatenation does not support fused activation in NNAPI");
      }
    };

    auto add_softmax_params = [&add_scalar_float32](void* data) {
      auto builtin = reinterpret_cast<TfLiteSoftmaxParams*>(data);
      add_scalar_float32(builtin->beta);
    };

    auto add_space_to_depth_params = [&add_scalar_int32](void* data) {
      auto builtin = reinterpret_cast<TfLiteSpaceToDepthParams*>(data);
      add_scalar_int32(builtin->block_size);
    };

#if 0
    auto add_reshape_params = [&](void* data) {
      auto builtin = reinterpret_cast<TfLiteReshapeParams*>(data);
      uint32_t tensor_size_shape = builtin->num_dimensions;
      ANeuralNetworksOperandType operand_type{
          ANEURALNETWORKS_TENSOR_INT32,
          {static_cast<uint32_t>(1),
           reinterpret_cast<uint32_t*>(&tensor_size_shape)},
          0,
          0};
      CHECK_NN(ANeuralNetworksModel_addOperand(nn_model, &operand_type))
      CHECK_NN(ANeuralNetworksModel_setOperandValue(
          nn_model, next_id, builtin->shape,
          sizeof(int) * builtin->num_dimensions));
      augmented_inputs.push_back(next_id++);
    };
#endif

    ANeuralNetworksOperationType nn_op_type;
    switch (builtin) {
      case tflite::BuiltinOperator_ADD:
        nn_op_type = ANEURALNETWORKS_ADD;
        add_add_params();
        break;
      case tflite::BuiltinOperator_AVERAGE_POOL_2D:
        add_pooling_params(node.builtin_data);
        nn_op_type = ANEURALNETWORKS_AVERAGE_POOL_2D;
        break;
      case tflite::BuiltinOperator_MAX_POOL_2D:
        add_pooling_params(node.builtin_data);
        nn_op_type = ANEURALNETWORKS_MAX_POOL_2D;
        break;
      case tflite::BuiltinOperator_L2_POOL_2D:
        add_pooling_params(node.builtin_data);
        nn_op_type = ANEURALNETWORKS_L2_POOL_2D;
        break;
      case tflite::BuiltinOperator_CONV_2D:
        add_convolution_params(node.builtin_data);
        nn_op_type = ANEURALNETWORKS_CONV_2D;
        break;
      case tflite::BuiltinOperator_RELU:
        nn_op_type = ANEURALNETWORKS_RELU;
        break;
      case tflite::BuiltinOperator_RELU6:
        nn_op_type = ANEURALNETWORKS_RELU6;
        break;
      case tflite::BuiltinOperator_TANH:
        nn_op_type = ANEURALNETWORKS_TANH;
        break;
      case tflite::BuiltinOperator_LOGISTIC:
        nn_op_type = ANEURALNETWORKS_LOGISTIC;
        break;
      case tflite::BuiltinOperator_DEPTHWISE_CONV_2D:
        add_depthwise_conv_params(node.builtin_data);
        nn_op_type = ANEURALNETWORKS_DEPTHWISE_CONV_2D;
        break;
      case tflite::BuiltinOperator_CONCATENATION:
        add_concatenation_params(node.builtin_data);
        nn_op_type = ANEURALNETWORKS_CONCATENATION;
        break;
      case tflite::BuiltinOperator_SOFTMAX:
        add_softmax_params(node.builtin_data);
        nn_op_type = ANEURALNETWORKS_SOFTMAX;
        break;
      case tflite::BuiltinOperator_FULLY_CONNECTED:
        add_fully_connected_params(node.builtin_data);
        nn_op_type = ANEURALNETWORKS_FULLY_CONNECTED;
        break;
      case tflite::BuiltinOperator_RESHAPE:
        nn_op_type = ANEURALNETWORKS_RESHAPE;
        // add_reshape_params(node.builtin_data);
        break;
      case tflite::BuiltinOperator_SPACE_TO_DEPTH:
        add_space_to_depth_params(node.builtin_data);
        nn_op_type = ANEURALNETWORKS_SPACE_TO_DEPTH;
        break;
      case tflite::BuiltinOperator_CONCAT_EMBEDDINGS:
      case tflite::BuiltinOperator_LSH_PROJECTION:
      case tflite::BuiltinOperator_SVDF:
      case tflite::BuiltinOperator_HASHTABLE_LOOKUP:
      case tflite::BuiltinOperator_RNN:
      case tflite::BuiltinOperator_UNIDIRECTIONAL_SEQUENCE_RNN:
      case tflite::BuiltinOperator_EMBEDDING_LOOKUP:
      case tflite::BuiltinOperator_EMBEDDING_LOOKUP_SPARSE:
      case tflite::BuiltinOperator_LSTM:
      case tflite::BuiltinOperator_L2_NORMALIZATION:
      case tflite::BuiltinOperator_LOCAL_RESPONSE_NORMALIZATION:
      case tflite::BuiltinOperator_MUL:
      case tflite::BuiltinOperator_PAD:
      case tflite::BuiltinOperator_RESIZE_BILINEAR:
      case tflite::BuiltinOperator_CALL:
      case tflite::BuiltinOperator_SKIP_GRAM:
      case tflite::BuiltinOperator_RELU1:
      case tflite::BuiltinOperator_GATHER:
      case tflite::BuiltinOperator_SPACE_TO_BATCH_ND:
      case tflite::BuiltinOperator_BATCH_TO_SPACE_ND:
      case tflite::BuiltinOperator_TRANSPOSE:
        FATAL("Op code %d is currently not delegated to NNAPI", builtin);
        nn_op_type = -1;  // set to invalid
        break;
      case tflite::BuiltinOperator_CUSTOM:
        FATAL("Custom operations are not supported when using NNAPI.");
        nn_op_type = -1;  // set to invalid
        break;
    }

    // Add the operation.
    CHECK_NN(ANeuralNetworksModel_addOperation(
        nn_model, nn_op_type, static_cast<uint32_t>(augmented_inputs.size()),
        augmented_inputs.data(), static_cast<uint32_t>(node.outputs->size),
        reinterpret_cast<uint32_t*>(node.outputs->data)));
  }
}

TfLiteStatus NNAPIDelegate::BuildGraph(Interpreter* interpreter) {
  // TODO(aselle): This is not correct. need to handle resize invalidation.
  if (nn_model_ && nn_compiled_model_) return kTfLiteOk;

  if (!nn_model_) {
    CHECK_NN(ANeuralNetworksModel_create(&nn_model_));

    uint32_t next_id = addTensorOperands(interpreter, nn_model_);
    AddOpsAndParams(interpreter, nn_model_, next_id);
    CHECK_NN(ANeuralNetworksModel_identifyInputsAndOutputs(
        nn_model_, static_cast<uint32_t>(interpreter->inputs().size()),
        reinterpret_cast<const uint32_t*>(interpreter->inputs().data()),
        static_cast<uint32_t>(interpreter->outputs().size()),
        reinterpret_cast<const uint32_t*>(interpreter->outputs().data())));
    CHECK_NN(ANeuralNetworksModel_finish(nn_model_));
  }
  if (!nn_compiled_model_) {
    CHECK_NN(ANeuralNetworksCompilation_create(nn_model_, &nn_compiled_model_));
    CHECK_NN(ANeuralNetworksCompilation_finish(nn_compiled_model_));
  }
  return kTfLiteOk;
}

TfLiteStatus NNAPIDelegate::Invoke(Interpreter* interpreter) {
  if (!nn_model_) {
    TF_LITE_ENSURE_STATUS(BuildGraph(interpreter));
  }

  ANeuralNetworksExecution* execution = nullptr;
  CHECK_NN(ANeuralNetworksExecution_create(nn_compiled_model_, &execution));

  // Currently perform deep copy of input buffer
  for (size_t i = 0; i < interpreter->inputs().size(); i++) {
    int input = interpreter->inputs()[i];
    // TODO(aselle): Is this what we want or do we want input instead?
    // TODO(aselle): This should be called setInputValue maybe to be cons.
    TfLiteTensor* tensor = interpreter->tensor(input);
    CHECK_NN(ANeuralNetworksExecution_setInput(
        execution, i, nullptr, tensor->data.raw, tensor->bytes));
  }
  // Tell nn api where to place final data.
  for (size_t i = 0; i < interpreter->outputs().size(); i++) {
    int output = interpreter->outputs()[i];
    TfLiteTensor* tensor = interpreter->tensor(output);
    CHECK_NN(ANeuralNetworksExecution_setOutput(
        execution, i, nullptr, tensor->data.raw, tensor->bytes));
  }
  // Currently use blocking compute.
  ANeuralNetworksEvent* event = nullptr;
  CHECK_NN(ANeuralNetworksExecution_startCompute(execution, &event));
  CHECK_NN(ANeuralNetworksEvent_wait(event));
  ANeuralNetworksEvent_free(event);
  ANeuralNetworksExecution_free(execution);

#if 0
  printf("From the NN API:\n");
  TfLiteTensor* tensor = interpreter->tensor(interpreter->outputs()[0]);
  if (float* data =
          interpreter->typed_tensor<float>(interpreter->outputs()[0])) {
    size_t num = tensor->bytes / sizeof(float);
    for (float* p = data; p < data + num; p++) {
      printf(" %f", *p);
    }
    printf("\n");
  }
#endif

  return kTfLiteOk;
}

}  // namespace tflite


text:
<fmxmlsnippet type="FMObjectList">
	<CustomFunction id="327" functionArity="1" visible="True" parameters="name" name="#P_Required">
		<Calculation><![CDATA[// #P_Required ( name )
// version 1.0, Daniel A. Shockley

/*
	Used to run a normal #P, but also puts that key into a local variable, $paramKeysRequiredList, which indicates that the param is REQUIRED.

HISTORY:
	1.0 - 2019-06-25 ( dshockley ): First created.
*/

Let ( [
		$paramKeysRequiredList = List ( $paramKeysRequiredList ; name )
	];
	#P ( name )
)]]></Calculation>
	</CustomFunction>
</fmxmlsnippet>


text:
package io.druid.metadata;

import org.junit.Assert;
import org.junit.Test;

import com.fasterxml.jackson.databind.ObjectMapper;

public class DefaultPasswordProviderTest
{
  private static final String pwd = "nothing";
  private static final ObjectMapper jsonMapper = new ObjectMapper();

  @Test
  public void testExplicitConstruction() {
    DefaultPasswordProvider pp = new DefaultPasswordProvider(pwd);
    Assert.assertEquals(pwd, pp.getPassword());
  }

  @Test
  public void testFromStringConstruction() {
    DefaultPasswordProvider pp = DefaultPasswordProvider.fromString(pwd);
    Assert.assertEquals(pwd, pp.getPassword());
  }

  @Test
  public void testDeserializationFromJsonString() throws Exception {
    PasswordProvider pp = jsonMapper.readValue("\"" + pwd + "\"",
        PasswordProvider.class);
    Assert.assertEquals(pwd, pp.getPassword());
  }

  @Test
  public void testDeserializationFromJson() throws Exception {
    PasswordProvider pp = jsonMapper.readValue(
        "{\"type\": \"default\", \"password\": \"" + pwd + "\"}",
        PasswordProvider.class);
    Assert.assertEquals(pwd, pp.getPassword());
  }
}