text:
(function() {

   var lang = YAHOO.lang, Event = YAHOO.util.Event, Dom = YAHOO.util.Dom;

/**
 * Create a Color picker input field
 * @class inputEx.ColorField
 * @extends inputEx.Field
 * @constructor
 * @param {Object} options Added options for ColorField :
 *

 *
colors: list of colors to load as palette

 *
palette: default palette to be used (if colors option not provided)

 *
cellPerLine: how many colored cells in a row on the palette

 *
ratio: screen-like ratio to display the palette, syntax: [with,height], default: [16,9] (if cellPerLine not provided)

 *

 */
inputEx.ColorField = function(options) {
	inputEx.ColorField.superclass.constructor.call(this,options);
};
lang.extend(inputEx.ColorField, inputEx.Field, {

	/**
	 * Adds the 'inputEx-ColorField' default className
	 * @param {Object} options Options object as passed to the constructor
	 */
   setOptions: function(options) {
   	inputEx.ColorField.superclass.setOptions.call(this, options);

   	// Overwrite options
   	this.options.className = options.className ? options.className : 'inputEx-Field inputEx-ColorField inputEx-PickerField';

   	// Added options
   	this.options.palette = options.palette;
   	this.options.colors = options.colors;

   	if (options.ratio) { this.options.ratio = options.ratio;}
   	if (options.cellPerLine) { this.options.cellPerLine = options.cellPerLine;}
   },

	/**
	 * Render the color button and the colorpicker popup
	 */
	renderComponent: function() {

	   // A hidden input field to store the color code
	   this.el = inputEx.cn('input', {
	      type: 'hidden',
	      name: this.options.name || '',
	      value: this.options.value || '#FFFFFF' });

	   // Create a colored area
	   this.colorEl = inputEx.cn('div', {className: 'inputEx-ColorField-button'}, {backgroundColor: this.el.value});

      // This element wraps the input node in a float: none div
      this.wrapEl = inputEx.cn('div', {className: 'inputEx-PickerField-wrapper'});
	   this.wrapEl.appendChild(this.el);
	   this.wrapEl.appendChild(this.colorEl);

	   // Create overlay
      this.oOverlay = new YAHOO.widget.Overlay(Dom.generateId(), { visible: false });
      this.oOverlay.setBody(" ");
      this.oOverlay.body.id = Dom.generateId();

      // Create button
      this.button = new YAHOO.widget.Button({ type: "menu", menu: this.oOverlay, label: "    " });
      this.button.appendTo(this.wrapEl);

      // Render the overlay
      this.oOverlay.render(this.wrapEl);

      // HACK: Set position absolute to the overlay
      Dom.setStyle(this.oOverlay.body.parentNode, "position", "absolute");

      // toggle Menu when clicking on colorEl
      Event.addListener(this.colorEl,'mousedown',function(e){

         if (!this.oOverlay.cfg.getProperty("visible")) {

            // Stop event to prevent following "click" event to hide the menu !
            Event.stopEvent(e);

            // palette may not have been rendered yet
            this.renderPalette();

            // Show menu
            this.button._showMenu();
         }
      },this,true);

      // Lazy load palette
      //   -> "mousedown" and not "click" because sometimes "click" is not fired !
      this.button.on('mousedown', this.renderPalette, this, true);

	   // Elements are bound to divEl
      this.fieldContainer.appendChild(this.wrapEl);
	},

	renderPalette: function() {

      var defaultPalette, overlayBody;

      // render once !
      if (this.paletteRendered) return;

      // set default palette to be used
      defaultPalette = this.options.palette || 1;

      // set colors available
      this.colors = this.options.colors || this.setDefaultColors(defaultPalette);
      this.length = this.colors.length;

      // set PopUp size ratio (default 16/9 ratio)
      this.ratio = this.options.ratio || [16,9];

      // set color grid dimensions
      this.cellPerLine = this.options.cellPerLine || Math.ceil(Math.sqrt(this.length*this.ratio[0]/this.ratio[1]));
      this.cellPerColumn = Math.ceil(this.length/this.cellPerLine);

      // Render the color grid
      overlayBody = document.getElementById(this.oOverlay.body.id);
      this.colorGrid = this.renderColorGrid();
      overlayBody.appendChild(this.colorGrid);

      // Unsubscribe the event so this function is called only once
      this.button.unsubscribe("mousedown", this.renderPalette);

      this.paletteRendered = true;

      // Select the square in the created palette from the value
      // This must be done after "this.paletteRendered = true".
      this.markSelectedColor();
	},

	/**
	 * Set the colors to set in the picker
	 * @param {int} index Index of the palette to use
	 * @return {Array} List of colors to choose from
	 */
	setDefaultColors: function(index) {
		return inputEx.ColorField.palettes[index-1];
	},

	/**
	 * This creates a color grid
	 */
	renderColorGrid: function() {

	   var grid, eventDelegation, square, i;

	   // remember squares
	   this.squares = [];

	   // container
	   grid = inputEx.cn('div', {className: 'inputEx-ColorField-Grid'});

	   // Is event delegation available ?
	   // (YAHOO.util.Event.delegate method is in "event-delegate" YUI-module)
	   eventDelegation = !lang.isUndefined(Event.delegate);

	   for(i = 0 ; i < this.length ; i++) {

	      //var square = inputEx.cn('div', {className: 'inputEx-ColorField-square'},{backgroundColor: this.colors[i], width:this.cellWidth+"px", height:this.cellHeight+"px", margin:this.cellMargin+"px" });
	      square = inputEx.cn('div', {className: 'inputEx-ColorField-square'},{backgroundColor: this.colors[i] });
	   	grid.appendChild(square);

	   	this.squares.push(square);

	   	// No event delegation available : add a listener on each square
	   	if (!eventDelegation) {
	   	  Event.addListener(square, "mousedown", function(e) {
	   	     var el = Event.getTarget(e);
	   	     this.onColorClick(e,el,grid);
	   	  }, this, true );
   	   }

	   	//
 insertion to end a line
	   	// ( + always after the last colored square)
	   	if (i%this.cellPerLine === this.cellPerLine-1 || i === this.length-1) {
            grid.appendChild(inputEx.cn('br',{clear:'both'}));
         }
      }

      // Mousedown event delegation
      if (eventDelegation) {

         if (!lang.isUndefined(YAHOO.util.Selector)) {

            Event.delegate(grid,"mousedown",this.onColorClick,"div.inputEx-ColorField-square",this,true);

         } else {

            Event.delegate(grid,"mousedown",this.onColorClick,function(el) {
               if (el.nodeName === "DIV" && YAHOO.util.Dom.hasClass(el,'inputEx-ColorField-square')) {
                  return el;
               }
            },this,true);

         }
      }

	   return grid;
	},

	/**
	 * Handle a color selection
	 * @param {Event} e The original click event
	 */
	onColorClick: function(e,square,container) {

		// Stop the event to prevent a selection
		Event.stopEvent(e);

	   // Overlay closure
      this.oOverlay.hide();

	   // SetValue
		var color = Dom.getStyle(square,'background-color');
		var hexaColor = inputEx.ColorField.ensureHexa(color);

	   this.setValue(hexaColor);
	},

	/**
	 * Set the value
	 * @param {String} value Color to set
	 * @param {boolean} [sendUpdatedEvt] (optional) Wether this setValue should fire the updatedEvt or not (default is true, pass false to NOT send the event)
	 */
	setValue: function(value, sendUpdatedEvt) {

	   this.el.value = value;

		this.markSelectedColor(value);

		// Call Field.setValue to set class and fire updated event
		inputEx.ColorField.superclass.setValue.call(this,value, sendUpdatedEvt);
	},

	/**
	 * Return the color value
	 * @return {String} Color value
	 */
	getValue: function() {
	   return this.el.value;
	},

	/**
	 * Call overlay when field is removed
	 */
	close: function() {
	  this.oOverlay.hide();
	},

	/**
    * Purge all event listeners and remove the component from the dom
    */
   destroy: function() {

      // colorEl listener
      Event.purgeElement(this.colorEl);

      // remove squares' mousedown listener(s)
      if (this.colorGrid) {
         Event.purgeElement(this.colorGrid,true);
      }

      inputEx.ColorField.superclass.destroy.call(this);

   },

	markSelectedColor: function(value) {

		var i;

		value = value || this.getValue();

		// mark the colored square in the palette as 'selected'
		if (!!value && this.paletteRendered) {

			value = value.toLowerCase(); // normalize case for following test

			for (i=0; i<this.length; i++) {

				// test color in lower case
				if (this.colors[i].toLowerCase() === value) {

					YAHOO.util.Dom.addClass(this.squares[i],'selected');

				} else {

					YAHOO.util.Dom.removeClass(this.squares[i],'selected');

				}

			}

		}

		// set background color on colorEl
		Dom.setStyle(this.colorEl, 'background-color', this.el.value);

	}

});

// Specific message for the container
inputEx.messages.selectColor = "Select a color :";

/**
 * Default palettes
 */
inputEx.ColorField.palettes = [
   ["#FFEA99","#FFFF66","#FFCC99","#FFCAB2","#FF99AD","#FFD6FF","#FF6666","#E8EEF7","#ADC2FF","#ADADFF","#CCFFFF","#D6EAAD","#B5EDBC","#CCFF99"],
   ["#DEDFDE","#FFFF6B","#EFCB7B","#FFBE94","#FFB6B5","#A5E3FF","#A5CBFF","#99ABEF","#EFB2E7","#FF9AAD","#94E7C6","#A5FFD6","#CEFFA5","#E7EF9C","#FFE38C"],
   ["#000000","#993300","#333300","#003300","#003366","#000080","#333399","#333333","#800000","#FF6600","#808000","#008000","#008080","#0000FF","#666699","#808080","#FF0000","#FF9900","#99CC00","#339966","#33CCCC","#3366FF","#800080","#969696","#FF00FF","#FFCC00","#FFFF00","#00FF00","#00FFFF","#00CCFF","#993366","#C0C0C0","#FF99CC","#FFCC99","#FFFF99","#CCFFCC","#CCFFFF","#99CCFF","#CC99FF","#F0F0F0"],
   ["#FFFFCC","#FFFF99","#CCFFCC","#CCFF66","#99FFCC","#CCFFFF","#66CCCC","#CCCCFF","#99CCFF","#9999FF","#6666CC","#9966CC","#CC99FF","#FFCCFF","#FF99FF","#CC66CC","#FFCCCC","#FF99CC","#FFCCCC","#CC6699","#FF9999","#FF9966","#FFCC99","#FFFFCC","#FFCC66","#FFFF99","#CCCC66"],
   ["#D0D0D0","#31A8FA","#8EC1E5","#58D7CF","#89E2BB","#A7F7F8","#F6B77C","#FE993F","#FE6440","#F56572","#FA9AA3","#F7B1CA","#E584AF","#D1C3EF","#AB77B8","#C69FE7","#90D28A","#C2F175","#EDEA9A","#F3DF70","#F8D1AE","#F98064","#F54F5E","#EC9099","#F0B5BA","#EDA0BB","#D375AC","#BC8DBE","#8C77B8"],
   // idem in pastel tone (colors above with opacity 0.6 on white background)
   ["#EEEEEE","#84CBFC","#BCDAF0","#9BE7E3","#B9EED7","#CBFBFB","#FAD4B1","#FFC28C","#FFA28D","#F9A3AB","#FCC3C8","#FBD1E0","#F0B6CF","#E4DBF6","#CDAED5","#DDC6F1","#BDE4B9","#DBF7AD","#F5F3C3","#F8ECAA","#FBE4CF","#FCB3A2","#F9969F","#F4BDC2","#F6D3D6","#F5C6D7","#E5ADCE","#D7BBD8","#BAAED5"]
];

//  -> ensure color has hexadecimal format like "#FF8E00"
inputEx.ColorField.ensureHexa = function (color) {
   var rgb, hexaColor;

   // remove spaces
   color = color.replace(/\s/g, "");

   // Firefox, Safari
   //   -> format "rgb(255,143,28)"
   if (!!color.match(/^rgb\((?:\d{1,3},){2}\d{1,3}\)$/)) {

	   // Convert integer (int or string) to hexadecimal (2 chars)
	   //   ex: "214" -> "d6"
      var DecToHex = function(dec) {
         var r = parseInt(dec,10).toString(16);
         if (r.length == 1) r = "0"+r;
         return r;
      };

      rgb = color.split(/([(,)])/);
      hexaColor = '#'+DecToHex(rgb[2])+DecToHex(rgb[4])+DecToHex(rgb[6]);

   // IE, Opera
   //   -> format "#FE6D34"
   } else if (!!color.match(/^#[\da-fA-F]{6}$/)) {
      hexaColor = color;

   } else {
      // defaults to white if invalid color
      hexaColor = "#FFFFFF";
   }

   return hexaColor;
};

// Register this class as "color" type
inputEx.registerType("color", inputEx.ColorField, []);

})();


text:
"""A kernel manager with a tornado IOLoop"""

#-----------------------------------------------------------------------------
#  Copyright (C) 2013  The IPython Development Team
#
#  Distributed under the terms of the BSD License.  The full license is in
#  the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------

from __future__ import absolute_import

from zmq.eventloop import ioloop
from zmq.eventloop.zmqstream import ZMQStream

from IPython.utils.traitlets import (
    Instance
)

from IPython.kernel.manager import KernelManager
from .restarter import IOLoopKernelRestarter

#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------

def as_zmqstream(f):
    def wrapped(self, *args, **kwargs):
        socket = f(self, *args, **kwargs)
        return ZMQStream(socket, self.loop)
    return wrapped

class IOLoopKernelManager(KernelManager):

    loop = Instance('zmq.eventloop.ioloop.IOLoop', allow_none=False)

    def _loop_default(self):
        return ioloop.IOLoop.instance()

    _restarter = Instance('IPython.kernel.ioloop.IOLoopKernelRestarter')

    def start_restarter(self):
        if self.autorestart and self.has_kernel:
            if self._restarter is None:
                self._restarter = IOLoopKernelRestarter(
                    kernel_manager=self, loop=self.loop,
                    parent=self, log=self.log
                )
            self._restarter.start()

    def stop_restarter(self):
        if self.autorestart:
            if self._restarter is not None:
                self._restarter.stop()

    connect_shell = as_zmqstream(KernelManager.connect_shell)
    connect_iopub = as_zmqstream(KernelManager.connect_iopub)
    connect_stdin = as_zmqstream(KernelManager.connect_stdin)
    connect_hb = as_zmqstream(KernelManager.connect_hb)

redpajama_set_name: RedPajamaGithub


text:
package com.facebook.buck.apple;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assume.assumeThat;

import com.facebook.buck.cxx.CxxLink;
import com.facebook.buck.cxx.CxxStrip;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer;
import com.facebook.buck.rules.FakeSourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.rules.SourceWithFlags;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.rules.args.Arg;
import com.facebook.buck.rules.macros.LocationMacro;
import com.facebook.buck.rules.macros.StringWithMacrosUtils;
import com.facebook.buck.shell.Genrule;
import com.facebook.buck.shell.GenruleBuilder;
import com.facebook.buck.testutil.TargetGraphFactory;
import com.facebook.buck.util.RichStream;
import com.facebook.buck.util.environment.Platform;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;

import org.hamcrest.Matchers;
import org.junit.Test;

public class AppleTestDescriptionTest {

  @Test
  public void linkerFlagsLocationMacro() throws Exception {
    assumeThat(Platform.detect(), is(Platform.MACOS));
    GenruleBuilder depBuilder =
        GenruleBuilder.newGenruleBuilder(BuildTargetFactory.newInstance("//:dep"))
            .setOut("out");
    AppleTestBuilder builder =
        new AppleTestBuilder(BuildTargetFactory.newInstance("//:rule#macosx-x86_64"))
            .setLinkerFlags(
                ImmutableList.of(
                    StringWithMacrosUtils.format(
                        "--linker-script=%s",
                        LocationMacro.of(depBuilder.getTarget()))))
            .setSrcs(ImmutableSortedSet.of(SourceWithFlags.of(new FakeSourcePath("foo.c"))));
    TargetGraph targetGraph = TargetGraphFactory.newInstance(builder.build(), depBuilder.build());
    BuildRuleResolver resolver =
        new BuildRuleResolver(targetGraph, new DefaultTargetNodeToBuildRuleTransformer());
    SourcePathResolver pathResolver = new SourcePathResolver(new SourcePathRuleFinder(resolver));
    Genrule dep = (Genrule) depBuilder.build(resolver, targetGraph);
    assertThat(
        builder.build().getExtraDeps(),
        Matchers.hasItem(dep.getBuildTarget()));
    AppleTest test = (AppleTest) builder.build(resolver, targetGraph);
    CxxStrip strip = (CxxStrip) RichStream.from(test.getDeps())
        .filter(AppleBundle.class)
        .findFirst()
        .get()
        .getBinary()
        .get();
    BuildRule binary = strip.getDeps().first();
    assertThat(binary, Matchers.instanceOf(CxxLink.class));
    assertThat(
        Arg.stringify(((CxxLink) binary).getArgs()),
        Matchers.hasItem(
            String.format("--linker-script=%s", dep.getAbsoluteOutputFilePath(pathResolver))));
    assertThat(
        binary.getDeps(),
        Matchers.hasItem(dep));
  }

}


text:
package org.djodjo.tarator.action;

import android.view.View;
import android.widget.EditText;

import org.djodjo.tarator.UiController;
import org.djodjo.tarator.ViewAction;
import org.hamcrest.Matcher;

import static org.djodjo.tarator.matcher.ViewMatchers.isAssignableFrom;
import static org.djodjo.tarator.matcher.ViewMatchers.isDisplayed;
import static org.hamcrest.Matchers.allOf;
/**
 * Clears view text by setting {@link android.widget.EditText}s text property to "".
 */
public final class ClearTextAction implements ViewAction {
  @SuppressWarnings("unchecked")
  @Override
  public Matcher<View> getConstraints() {
    return allOf(isDisplayed(), isAssignableFrom(EditText.class));
  }

  @Override
  public void perform(UiController uiController, View view) {
    ((EditText) view).setText("");
  }

  @Override
  public String getDescription() {
    return "clear text";
  }
}


text:
@interface PodsDummy_Pods_EasyTrack : NSObject
@end
@implementation PodsDummy_Pods_EasyTrack
@end


text:
var searchData=
[
  ['my_5fnamespace',['my_namespace',['../namespacemy__namespace.html',1,'']]],
  ['testing',['testing',['../namespacemy__namespace_1_1testing.html',1,'my_namespace']]]
];


text:
package com.client.listener;

import com.client.ClientMain;
import com.client.window.WindowController;
import io.netty.channel.Channel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
 * Created by form on 2017-07-20.
 */
public class ChatListener implements KeyListener {
    private String message;

    public void keyPressed(KeyEvent event){
        if(KeyEvent.VK_ENTER == event.getKeyCode()){
            try{
                JPanel panel = WindowController.getPanel();
                for(Component component : panel.getComponents()){
                    String name = component.getName();
                    if("message".equals(name)){
                        JTextField message = (JTextField)component;
                        this.message = message.getText();
                        message.setText("");
                        break;
                    }
                }

                ClientMain client = ClientMain.getInstance();
                Channel channel = client.getChannel();
                if(!"".equals(message) && message != null){
                    channel.writeAndFlush(message);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    public void keyTyped(KeyEvent e){

    }
    public void keyReleased(KeyEvent e){

    }
}


text:
package com.google.publicalerts.cap.validator;

import static com.google.common.truth.Truth.assertThat;

import junit.framework.TestCase;

import com.google.publicalerts.cap.testing.TestResources;
import com.google.publicalerts.cap.validator.LineOffsetParser.LineOffsets;

/**
 * Tests for {@link LineOffsetParser}.
 *
 * @author shakusa@google.com (Steve Hakusa)
 */
public class LineOffsetParserTest extends TestCase {
  private static final LineOffsetParser parser = new LineOffsetParser();

  public LineOffsetParserTest(String name) {
    super(name);
  }

  public void testLineOffsets_cap() throws Exception {
    String cap = TestResources.load("weather.cap");
    LineOffsets offsets = parser.parse(cap);

    // Invalid queries
    assertThat(offsets.getXPathLineNumber("invalid")).isEqualTo(0);

    // getXPathLineNumber
    assertThat(offsets.getXPathLineNumber("/alert[1]")).isEqualTo(2);
    assertThat(offsets.getXPathLineNumber("/alert[1]/msgType[1]")).isEqualTo(8);
    assertThat(offsets.getXPathLineNumber("/alert[1]/info[1]/expires[1]")).isEqualTo(22);
    assertThat(offsets.getXPathLineNumber("/alert[1]/info[1]/parameter[2]/value[1]"))
        .isEqualTo(48);
  }

  public void testLineOffsets_atomFeed() throws Exception {
    String atom = TestResources.load("weather.atom");
    LineOffsets offsets = parser.parse(atom);

    // Invalid queries
    assertThat(offsets.getXPathLineNumber("invalid")).isEqualTo(0);

    // getXPathLineNumber
    assertThat(offsets.getXPathLineNumber("/feed[1]/entry[1]")).isEqualTo(17);
    assertThat(offsets.getXPathLineNumber("/feed[1]/entry[1]/content[1]/alert[1]")).isEqualTo(28);
    assertThat(offsets.getXPathLineNumber("/feed[1]/entry[1]/content[1]/alert[1]/info[1]"))
        .isEqualTo(37);
    assertThat(offsets.getXPathLineNumber(
        "/feed[1]/entry[1]/content[1]/alert[1]/info[1]/area[1]/geocode[2]")).isEqualTo(91);

    // getLinkLineNumber
    assertThat(offsets.getLinkLineNumber("http://www.weather.gov/alerts-beta/")).isEqualTo(16);
    assertThat(offsets.getLinkLineNumber("http://www.weather.gov/alerts-beta/wwacapget.php"
        + "?x=DC20120829202900LWXAirQualityAlertLWX20120831040000DC")).isEqualTo(25);
  }

  public void testLineOffsets_atomFeedFullyQualifiedTags() throws Exception {
    String atom = TestResources.load("amber.atom");
    LineOffsets offsets = parser.parse(atom);

    // Invalid queries
    assertThat(offsets.getXPathLineNumber("invalid")).isEqualTo(0);

    // getXPathLineNumber
    assertThat(offsets.getXPathLineNumber("/feed[1]/entry[1]")).isEqualTo(5);
    assertThat(offsets.getXPathLineNumber("/feed[1]/entry[1]/content[1]/alert[1]")).isEqualTo(16);
    assertThat(offsets.getXPathLineNumber("/feed[1]/entry[1]/content[1]/alert[1]/info[1]"))
        .isEqualTo(24);
    assertThat(offsets.getXPathLineNumber(
        "/feed[1]/entry[1]/content[1]/alert[1]/info[1]/area[1]/geocode[1]")).isEqualTo(43);
  }

  public void testLineOffsets_rssFeed() throws Exception {
    String rss = TestResources.load("ny_index.rss");
    LineOffsets offsets = parser.parse(rss);

    // Invalid queries
    assertThat(offsets.getXPathLineNumber("invalid")).isEqualTo(0);

    // getXPathLineNumber
    assertThat(offsets.getXPathLineNumber("/rss[1]/channel[1]")).isEqualTo(3);
    assertThat(offsets.getXPathLineNumber("/rss[1]/channel[1]/link[1]")).isEqualTo(6);
    assertThat(offsets.getXPathLineNumber("/rss[1]/channel[1]/item[2]/title[1]")).isEqualTo(21);

    // getLinkLineNumber
    assertThat(offsets.getLinkLineNumber("http://www.nyalert.gov/")).isEqualTo(6);
    assertThat(offsets.getLinkLineNumber("http://www.nyalert.gov/Public/"
        + "News/GetCapAlert.aspx?capID=NYAlert-ALLHAZALERT-3167113")).isEqualTo(14);
    assertThat(offsets.getLinkLineNumber("http://www.nyalert.gov/Public/"
        + "News/GetCapAlert.aspx?capID=NYAlert-ALLHAZALERT-3162202")).isEqualTo(23);
  }

  public void testLineOffsets_edxldeFeed() throws Exception {
    String rss = TestResources.load("bushfire_valid.edxlde");
    LineOffsets offsets = parser.parse(rss);

    // Invalid queries
    assertThat(offsets.getXPathLineNumber("invalid")).isEqualTo(0);

    // getXPathLineNumber
    assertThat(offsets.getXPathLineNumber("/EDXLDistribution[1]/contentObject[1]/xmlContent[1]/"
        + "embeddedXMLContent[1]/alert[1]")).isEqualTo(18);
    assertThat(offsets.getXPathLineNumber("/EDXLDistribution[1]/contentObject[2]/xmlContent[1]/"
        + "embeddedXMLContent[1]/alert[1]/sender[1]")).isEqualTo(96);
    assertThat(offsets.getXPathLineNumber("/EDXLDistribution[1]/contentObject[2]/xmlContent[1]/"
        + "embeddedXMLContent[1]/alert[1]/info[1]/parameter[2]")).isEqualTo(122);
  }

  public void testLineOffsets_invalidXml() throws Exception {
    String invalidXML = "<alert>\n<info>\n</alert>";

    try {
      parser.parse(invalidXML);
      fail();
    } catch (IllegalArgumentException expected) { }
  }
}


text:
douban-fm-music-downloader
==========================
A simple python script to download music from douban.fm, convert format to mp3.

Prerequisite
============
install avconv first
```
sudo apt-get install avconv
```


text:
<?php

/** InternalReferences.php */
namespace Applications\Entity;

use Auth\Entity\UserInterface;
use Jobs\Entity\JobInterface;
use Core\Entity\AbstractEntity;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

/**
 * @ODM\EmbeddedDocument
 */
class InternalReferences extends AbstractEntity
{

    /** @ODM\Field(type="hash") */
    protected $jobs = array();

    /**
     * @ODM\Field(type="collection")
     * @var array
     */
    protected $jobManagers = [];

    public function setJob(JobInterface $job)
    {
        if (isset($this->jobs['__id__']) && $this->jobs['__id__'] == $job->getId()) {
            return $this;
        }

        $this->jobs = array(
            '__id__' => $job->getId(),
            'userId' => ($user = $job->getUser()) ? $user->getId() : null,
        );
        $managers = array_filter(array_unique(array_map(
            function ($x) {
                return $x['id'] ?? false;
            },
            $job->getMetaData('organizations:managers', [])
        )));
        $this->setJobsManagers($managers);
        return $this;
    }

    public function setJobsId($id)
    {
        $this->jobs['__id__'] = $id;
        return $this;
    }

    public function setJobsUserId($userOrId)
    {
        if ($userOrId instanceof UserInterface) {
            $userOrId = $userOrId->getId();
        }
        $this->jobs['userId'] = $userOrId;
        return $this;
    }

    public function setJobsManagers($managers)
    {
        $this->jobManagers = $managers;
        return $this;
    }
}


text:
package com.yiibai;

public class Logging {
	/**
	 * This is the method which I would like to execute before a selected method
	 * execution.
	 */
	public void beforeAdvice() {
		System.out.println("Going to setup student profile.");
	}

	/**
	 * This is the method which I would like to execute after a selected method
	 * execution.
	 */
	public void afterAdvice() {
		System.out.println("Student profile has been setup.");
	}

	/**
	 * This is the method which I would like to execute when any method returns.
	 */
	public void afterReturningAdvice(Object retVal) {
		System.out.println("Returning:" + retVal.toString());
	}

	/**
	 * This is the method which I would like to execute if there is an exception
	 * raised.
	 */
	public void AfterThrowingAdvice(IllegalArgumentException ex) {
		System.out.println("There has been an exception: " + ex.toString());
	}
}


text:
using UnityEngine;
using System.Collections;

public class MonsterCarrot : Monster {
	// Use this for initialization
	public static int lives {
		get {
			return GameManager.Level <= 2 ? 2 : 3;
		}
	}
	public static float speed {
		get {
			return GameManager.Level <= 3 ? 0.02f : 0.04f;
		}
	}
	public static int biteDamage {
		get {
			return 2;
		}
	}
	public static float biteDelay = 0.8f;
	private Animator carrotAnimator;

	protected int nCoins = 1;

	void Awake() {
		_lives = lives;
		carrotAnimator = GetComponent<Animator>();
	}

	public override void Move() {
		MoveTowardsPlayer(10, speed);
		Biting(biteDelay, biteDamage);
	}

	protected override void OnBite() {
		carrotAnimator.SetTrigger("Bite");
		SoundManager.Instance.Play(SoundManager.Instance.carrotBite);
		// Invoke("StopBite", 0.5f);
	}

	protected override void OnBiteEnd() {
		carrotAnimator.SetTrigger("StopBite");
	}
}


text:
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
from django.db import connection

def db_table_field_exists(table_name,field):
    cursor=connection.cursor()
    return field in map(lambda x:  x[0].lower(),connection.introspection.get_table_description(cursor, table_name))

class Migration(DataMigration):

    def forwards(self, orm):
        if not db_table_field_exists("rapidsms_xforms_xformfield","question"):
            db.add_column('rapidsms_xforms_xformfield', 'question',
                self.gf('django.db.models.fields.TextField')(null=True, blank=True),)

    def backwards(self, orm):
        "Write your backwards methods here."
        db.delete_column('rapidsms_xforms_xformfield', 'question')

    models = {
        'auth.group': {
            'Meta': {'object_name': 'Group'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        'auth.permission': {
            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        'eav.attribute': {
            'Meta': {'ordering': "['name']", 'unique_together': "(('site', 'slug'),)", 'object_name': 'Attribute'},
            'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'datatype': ('eav.fields.EavDatatypeField', [], {'max_length': '6'}),
            'description': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}),
            'enum_group': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eav.EnumGroup']", 'null': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'required': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"}),
            'slug': ('eav.fields.EavSlugField', [], {'max_length': '50'}),
            'type': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'})
        },
        'eav.enumgroup': {
            'Meta': {'object_name': 'EnumGroup'},
            'enums': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['eav.EnumValue']", 'symmetrical': 'False'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'})
        },
        'eav.enumvalue': {
            'Meta': {'object_name': 'EnumValue'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'value': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50', 'db_index': 'True'})
        },
        'eav.value': {
            'Meta': {'object_name': 'Value'},
            'attribute': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['eav.Attribute']"}),
            'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'entity_ct': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'value_entities'", 'to': "orm['contenttypes.ContentType']"}),
            'entity_id': ('django.db.models.fields.IntegerField', [], {}),
            'generic_value_ct': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'value_values'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}),
            'generic_value_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
            'value_bool': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}),
            'value_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
            'value_enum': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'eav_values'", 'null': 'True', 'to': "orm['eav.EnumValue']"}),
            'value_float': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'value_int': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
            'value_text': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'})
        },
        'locations.location': {
            'Meta': {'object_name': 'Location'},
            'code': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'parent_id': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
            'parent_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']", 'null': 'True', 'blank': 'True'}),
            'point': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['locations.Point']", 'null': 'True', 'blank': 'True'}),
            'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'tree_parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['locations.Location']"}),
            'type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations'", 'null': 'True', 'to': "orm['locations.LocationType']"})
        },
        'locations.locationtype': {
            'Meta': {'object_name': 'LocationType'},
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50', 'primary_key': 'True'})
        },
        'locations.point': {
            'Meta': {'object_name': 'Point'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'latitude': ('django.db.models.fields.DecimalField', [], {'max_digits': '13', 'decimal_places': '10'}),
            'longitude': ('django.db.models.fields.DecimalField', [], {'max_digits': '13', 'decimal_places': '10'})
        },
        'rapidsms.backend': {
            'Meta': {'object_name': 'Backend'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '20'})
        },
        'rapidsms.connection': {
            'Meta': {'unique_together': "(('backend', 'identity'),)", 'object_name': 'Connection'},
            'backend': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['rapidsms.Backend']"}),
            'contact': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['rapidsms.Contact']", 'null': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'identity': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        'rapidsms.contact': {
            'Meta': {'object_name': 'Contact'},
            'active': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'birthdate': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
            'gender': ('django.db.models.fields.CharField', [], {'max_length': '1', 'null': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['auth.Group']", 'null': 'True', 'blank': 'True'}),
            'health_facility': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_caregiver': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'language': ('django.db.models.fields.CharField', [], {'max_length': '6', 'blank': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
            'occupation': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
            'reporting_location': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['locations.Location']", 'null': 'True', 'blank': 'True'}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'contact'", 'unique': 'True', 'null': 'True', 'to': "orm['auth.User']"}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'village': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'villagers'", 'null': 'True', 'to': "orm['locations.Location']"}),
            'village_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'})
        },
        'rapidsms_httprouter.message': {
            'Meta': {'object_name': 'Message'},
            'application': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True'}),
            'batch': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'messages'", 'null': 'True', 'to': "orm['rapidsms_httprouter.MessageBatch']"}),
            'connection': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'messages'", 'to': "orm['rapidsms.Connection']"}),
            'date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'direction': ('django.db.models.fields.CharField', [], {'max_length': '1', 'db_index': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'in_response_to': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'responses'", 'null': 'True', 'to': "orm['rapidsms_httprouter.Message']"}),
            'priority': ('django.db.models.fields.IntegerField', [], {'default': '10', 'db_index': 'True'}),
            'status': ('django.db.models.fields.CharField', [], {'max_length': '1', 'db_index': 'True'}),
            'text': ('django.db.models.fields.TextField', [], {'db_index': 'True'})
        },
        'rapidsms_httprouter.messagebatch': {
            'Meta': {'object_name': 'MessageBatch'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '15', 'null': 'True', 'blank': 'True'}),
            'status': ('django.db.models.fields.CharField', [], {'max_length': '1'})
        },
        'rapidsms_xforms.binaryvalue': {
            'Meta': {'object_name': 'BinaryValue'},
            'binary': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        'rapidsms_xforms.xform': {
            'Meta': {'object_name': 'XForm'},
            'active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'command_prefix': ('django.db.models.fields.CharField', [], {'default': "'+'", 'max_length': '1', 'null': 'True', 'blank': 'True'}),
            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'description': ('django.db.models.fields.TextField', [], {'max_length': '255'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'keyword': ('eav.fields.EavSlugField', [], {'max_length': '32'}),
            'keyword_prefix': ('django.db.models.fields.CharField', [], {'max_length': '1', 'null': 'True', 'blank': 'True'}),
            'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
            'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
            'response': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'restrict_message': ('django.db.models.fields.CharField', [], {'max_length': '160', 'null': 'True', 'blank': 'True'}),
            'restrict_to': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['auth.Group']", 'null': 'True', 'blank': 'True'}),
            'separator': ('django.db.models.fields.CharField', [], {'max_length': '8', 'null': 'True', 'blank': 'True'}),
            'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"})
        },
        'rapidsms_xforms.xformfield': {
            'Meta': {'ordering': "('order', 'id')", 'object_name': 'XFormField', '_ormbases': ['eav.Attribute']},
            'attribute_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['eav.Attribute']", 'unique': 'True', 'primary_key': 'True'}),
            'command': ('eav.fields.EavSlugField', [], {'max_length': '32'}),
            'field_type': ('django.db.models.fields.SlugField', [], {'max_length': '8', 'null': 'True', 'blank': 'True'}),
            'order': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'question': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'xform': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'fields'", 'to': "orm['rapidsms_xforms.XForm']"})
        },
        'rapidsms_xforms.xformfieldconstraint': {
            'Meta': {'object_name': 'XFormFieldConstraint'},
            'field': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'constraints'", 'to': "orm['rapidsms_xforms.XFormField']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'message': ('django.db.models.fields.CharField', [], {'max_length': '160'}),
            'order': ('django.db.models.fields.IntegerField', [], {'default': '1000'}),
            'test': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}),
            'type': ('django.db.models.fields.CharField', [], {'max_length': '10'})
        },
        'rapidsms_xforms.xformlist': {
            'Meta': {'ordering': "['priority']", 'object_name': 'XFormList'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'priority': ('django.db.models.fields.IntegerField', [], {}),
            'report': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['rapidsms_xforms.XFormReport']"}),
            'required': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'xform': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['rapidsms_xforms.XForm']"})
        },
        'rapidsms_xforms.xformreport': {
            'Meta': {'object_name': 'XFormReport'},
            'constraints': ('picklefield.fields.PickledObjectField', [], {}),
            'frequency': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
            'xforms': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['rapidsms_xforms.XForm']", 'through': "orm['rapidsms_xforms.XFormList']", 'symmetrical': 'False'})
        },
        'rapidsms_xforms.xformreportsubmission': {
            'Meta': {'object_name': 'XFormReportSubmission'},
            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'report': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['rapidsms_xforms.XFormReport']"}),
            'start_date': ('django.db.models.fields.DateTimeField', [], {}),
            'status': ('django.db.models.fields.CharField', [], {'max_length': '10'}),
            'submissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['rapidsms_xforms.XFormSubmission']", 'symmetrical': 'False'})
        },
        'rapidsms_xforms.xformsubmission': {
            'Meta': {'object_name': 'XFormSubmission'},
            'approved': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'confirmation_id': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'connection': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'submissions'", 'null': 'True', 'to': "orm['rapidsms.Connection']"}),
            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'has_errors': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'message': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'submissions'", 'null': 'True', 'to': "orm['rapidsms_httprouter.Message']"}),
            'raw': ('django.db.models.fields.TextField', [], {}),
            'type': ('django.db.models.fields.CharField', [], {'max_length': '8'}),
            'xform': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'submissions'", 'to': "orm['rapidsms_xforms.XForm']"})
        },
        'rapidsms_xforms.xformsubmissionvalue': {
            'Meta': {'object_name': 'XFormSubmissionValue', '_ormbases': ['eav.Value']},
            'submission': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'values'", 'to': "orm['rapidsms_xforms.XFormSubmission']"}),
            'value_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['eav.Value']", 'unique': 'True', 'primary_key': 'True'})
        },
        'sites.site': {
            'Meta': {'ordering': "('domain',)", 'object_name': 'Site', 'db_table': "'django_site'"},
            'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        }
    }

    complete_apps = ['rapidsms_xforms']
    symmetrical = True


text:
namespace Microsoft.Azure.Management.ResourceManager.Models
{
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Deployment scripts error response.
    /// </summary>
    public partial class DeploymentScriptsError
    {
        /// <summary>
        /// Initializes a new instance of the DeploymentScriptsError class.
        /// </summary>
        public DeploymentScriptsError()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the DeploymentScriptsError class.
        /// </summary>
        public DeploymentScriptsError(ErrorResponse error = default(ErrorResponse))
        {
            Error = error;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// </summary>
        [JsonProperty(PropertyName = "error")]
        public ErrorResponse Error { get; set; }

    }
}


text:
<?php
namespace app\components;

use Yii;
use yii\base\Widget;
use dektrium\user\models\RecoveryForm;

class Forgetpass extends Widget
{
	public function run()
	{

        $model = Yii::createObject([
            'class'    => RecoveryForm::className(),
            'scenario' => 'request',
        ]);
		return $this->render('forgetpass',
		[
            'model'  => $model,
        ]);

	}
}


text:
Gnieh Diffson
[![Build Status](https://travis-ci.org/gnieh/diffson.png)](https://travis-ci.org/gnieh/diffson)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/9892e2c968974ecb951d21969adbadaa)](https://www.codacy.com/app/satabin/diffson?utm_source=github.com&utm_medium=referral&utm_content=gnieh/diffson&utm_campaign=Badge_Grade)
[![Code Coverage](https://codecov.io/github/gnieh/diffson/coverage.svg?branch=master)](https://codecov.io/github/gnieh/diffson?branch=master)
[![Maven Central](https://img.shields.io/maven-central/v/org.gnieh/diffson-core_2.13.svg)](https://maven-badges.herokuapp.com/maven-central/org.gnieh/diffson-core_2.13)
[![Scaladoc](https://javadoc.io/badge/org.gnieh/diffson-core_2.13.svg)](https://javadoc.io/doc/org.gnieh/diffson-core_2.13)

----

[![Join the chat at https://gitter.im/gnieh/diffson](https://badges.gitter.im/gnieh/diffson.svg)](https://gitter.im/gnieh/diffson?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

A [Scala][6] implementation of the [RFC-6901][1], [RFC-6902][2], and [RFC-7396][11].
It also provides methods to compute _diffs_ between two Json values that produce valid Json patches or merge patches.

**Note:** if you still want to use the `3.x.y` series (without [cats][cats]), please see [this documentation][diffson3]

<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
## Table of Contents

- [Getting Started](#getting-started)
- [Json Library](#json-library)
  - [Note on (de)serialization](#note-on-deserialization)
- [Json Patch (RFC-6902)](#json-patch-rfc-6902)
  - [Basic Usage](#basic-usage)
  - [Simple diffs](#simple-diffs)
  - [Remembering old values](#remembering-old-values)
- [Json Merge Patches (RFC-7396)](#json-merge-patches-rfc-7396)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->

Getting Started
---------------

This library is published in the [Maven][7] [Central Repository][8].
You can add it to your sbt project by putting this line into your build description:
```scala
libraryDependencies += "org.gnieh" %% f"diffson-$jsonLib" % "4.1.1"
```

where `jsonLib` is either:

 - `spray-json`
 - `play-json`
 - `circe`

These versions are built for Scala 2.12, 2.13, and 3.

Scala.JS is also supported for Scala 2.12, 2.13, and 3.
To use it, add this dependency to your build file:
```scala
libraryDependencies += "org.gnieh" %%% f"diffson-$jsonLib" % "4.1.1"
```

Json Library
------------

Diffson was first developed for [spray-json][3], however, it is possible to use it with any json library of your liking.
The only requirement is to have a `Jsony` for your json library.
`Jsony` is a type class describing what operations are required to compute diffs and apply patches to Json-like types.

At the moment, diffson provides instances for [spray-json][3], [Play! Json][9], and [circe][10].
To use these implementations you need to link with the correct module and import the instance:

```scala
// spray-json
import diffson.sprayJson._
// play-json
import diffson.playJson._
// circe
import diffson.circe._
```

If you want to add support for your favorite Json library, you may only depend on diffson core module `diffson-core` and all you need to do then is to implement the `Jsony` class, which provides all the operations for diffson to be able to compute diffs and apply patches.
Contribution of new Json libraries in this repository are more than welcome.

### Note on (de)serialization

The purpose of diffson is to create and manipulate diffs and patch for Json like structures.
However the supported patch formats can also be represented as Json objects.
The core library doesn't mention any of this, as its sole purpose is the diff/patch computations.
Given the variety of Json libraries out there and there various ways of implementing the way of (de)serializing Json values, there is no good abstraction that fits this general purpose library, and this is up to the library user to do it in the most appropriate approach given the Json library of their choosing.
The various supported Json libraries in diffson provide an idiomatic way of (de)serializing the different element for each of them (e.g. the `circe` module provide `Decoder`s and `Encoder`s for all the patch types).

For instance to get circe encoder and decoder instances, you need to
```scala
import io.circe._
import diffson.circe._
import diffson.jsonpatch._

val decoder = Decoder[JsonPatch[Json]]
val encoder = Encoder[JsonPatch[Json]]
```

For Play! Json, you need to
```scala
import play.api.libs.json._
import diffson.playJson._
import diffson.playJson.DiffsonProtocol._
import diffson.jsonpatch._

val format = Json.format[JsonPatch[JsValue]]
```

For Spray Json, you need to
```scala
import spray.json._
import diffson.sprayJson._
import diffson.sprayJson.DiffsonProtocol._
import diffson.jsonpatch._

val format = implicitly[JsonFormat[JsonPatch[JsValue]]]
```

Json Patch (RFC-6902)
---------------------

### Basic Usage

Although the library is quite small and easy to use, here comes a summary of its basic usage.
Diffson uses a type-class approach based on the [cats][cats] library.
All operations that may fail are wrapped in type with a `MonadError` instance.

There are two different entities living in the `diffson.jsonpatch` and one on `diffson.jsonpointer` package useful to work with Json patches:
 - `Pointer` which allows to parse and manipulate Json pointers as defined in [RFC-6901][1],
 - `JsonPatch` which allows to parse, create and apply Json patches as defined in [RFC-6902][2],
 - `JsonDiff` which allows to compute the diff between two Json values and create Json patches.

Basically if someone wants to compute the diff between two Json objects, they can execute the following:
```scala
import diffson._
import diffson.lcs._
import diffson.circe._
import diffson.jsonpatch._
import diffson.jsonpatch.lcsdiff._

import io.circe._
import io.circe.parser._

import cats._
import cats.implicits._

implicit val lcs = new Patience[Json]

val json1 = parse("""{
                    |  "a": 1,
                    |  "b": true,
                    |  "c": ["test", "plop"]
                    |}""".stripMargin)

val json2 = parse("""{
                    |  "a": 6,
                    |  "c": ["test2", "plop"],
                    |  "d": false
                    |}""".stripMargin)

val patch =
  for {
    json1 <- json1
    json2 <- json2
  } yield diff(json1, json2)
```
which will return a patch that can be serialized in json as:
```json
[{
  "op":"replace",
  "path":"/a",
  "value":6
},{
  "op":"remove",
  "path":"/b"
},{
  "op":"replace",
  "path":"/c/0",
  "value":"test2"
},{
  "op":"add",
  "path":"/d",
  "value":false
}]
```

This example computes a diff based on an LCS, so we must provide an implicit instance of `Lcs`.
In that case we used the `Patience` instance, but other could be used.
See package `diffson.lcs` to see what implementations are available by default, or provide your own.

You can then apply an existing patch to a Json object as follows:
```scala
import scala.util.Try

import cats.implicits._

val json2 = patch[Try](json1)
```

which results in a json like:
```json
{
  "d":false,
  "c":"test2",
  "a":6
}
```
which we can easily verify is the same as `json2` modulo reordering of fields.

A patch may fail, this is why the `apply` method wraps the result in an `F[_]` with a `MonadError`.
In this example, we used the standard `Try` class, but any type `F` with the appropriate `MonadError[F, Throwable]` instance in scope can be used.

### Simple diffs

The example above uses an LCS based diff, which makes it possible to have smart diffs for arrays.
However, depending on your use case, this feature might not be what you want:
 - LCS can be intensive to compute if you have huge arrays;
 - you might want to see a modified array as a single `replace` operation.

To do so, instead of importing `diffson.jsonpatch.lcsdiff._`, import `diffson.jsonpatch.simplediff._` and you do not need to provide an `Lcs` instance.
Resulting diff will be bigger in case of different arrays, but quicker to compute.

For instance, the resulting simple diff for the example above is:
```json
[
  {
    "op" : "replace",
    "path" : "/a",
    "value" : 6
  },
  {
    "op" : "remove",
    "path" : "/b"
  },
  {
    "op" : "replace",
    "path" : "/c",
    "value" : [
      "test2",
      "plop"
    ]
  },
  {
    "op" : "add",
    "path" : "/d",
    "value" : false
  }
]
```

Note the `replace` operation for the entire array, instead of the single modified element.

### Remembering old values

Whether you use the LCS based or simple diff, you can make it remember old values for `remove` and `replace` operations.

To that end, you just need to import `diffson.jsonpatch.lcsdiff.remembering._` or `diffson.jsonpatch.simplediff.remembering._` instead.
The generated diff will add an `old` field to `remove` and `replace` operations in the patch, containing the previous version of the field in original object.
Taking the first example with the new import, we have similar code.

```scala
import diffson._
import diffson.lcs._
import diffson.circe._
import diffson.jsonpatch._
import diffson.jsonpatch.lcsdiff.remembering._

import io.circe._
import io.circe.parser._

import cats._
import cats.implicits._

implicit val lcs = new Patience[Json]

val json1 = parse("""{
                    |  "a": 1,
                    |  "b": true,
                    |  "c": ["test", "plop"]
                    |}""".stripMargin)

val json2 = parse("""{
                    |  "a": 6,
                    |  "c": ["test2", "plop"],
                    |  "d": false
                    |}""".stripMargin)

val patch =
  for {
    json1 <- json1
    json2 <- json2
  } yield diff(json1, json2)
```

which results in a result with the old value remembered in the patch:

```json
[
  {
    "op" : "replace",
    "path" : "/a",
    "value" : 6,
    "old" : 1
  },
  {
    "op" : "remove",
    "path" : "/b",
    "old" : true
  },
  {
    "op" : "replace",
    "path" : "/c/0",
    "value" : "test2",
    "old" : "test"
  },
  {
    "op" : "add",
    "path" : "/d",
    "value" : false
  }
]
```

Patches produced with this methods are still valid according to the RFC, as the new field must simply be ignored by implementations that are not aware of this encoding, so interoperability is not broken.

Json Merge Patches (RFC-7396)
-----------------------------

There are two different entities living in the `diffson.jsonmergepatch` package useful to work with Json merge patches:
 - `JsonMergePatch` which allows to parse, create and apply Json merge patches as defined in [RFC-7396][11],
 - `JsonMergeDiff` which allows to compute the diff between two Json values and create Json merge patches.

Basically if someone wants to compute the diff between two Json objects, they can execute the following:
```scala
import diffson._
import diffson.circe._
import diffson.jsonmergepatch._

import io.circe.parser._
import io.circe.syntax._

val json1 = parse("""{
              |  "a": 1,
              |  "b": true,
              |  "c": "test"
              |}""".stripMargin)

val json2 = parse("""{
              |  "a": 6,
              |  "c": "test2",
              |  "d": false
              |}""".stripMargin)

val patch =
  for {
    json1 <- json1
    json2 <- json2
  } yield diff(json1, json2)
```
which will return the following Json Merge Patch:
```json
{
  "a": 6,
  "b": null,
  "c": "test2",
  "d": false
}
```
You can then apply the patch to `json1`:
```scala
val json3 = patch(json1)
```

which will create the following Json:
```json
{
  "d":false,
  "c":"test2",
  "a":6
}
```
which we can easily verify is the same as `json2` modulo reordering of fields.

[1]: https://datatracker.ietf.org/doc/html/rfc6901
[2]: https://datatracker.ietf.org/doc/html/rfc6902
[3]: https://github.com/spray/spray-json
[4]: http://alfedenzo.livejournal.com/170301.html
[5]: https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
[6]: http://scala-lang.org
[7]: http://maven.apache.org/
[8]: http://search.maven.org/
[9]: https://www.playframework.com/documentation/latest/ScalaJson
[10]: https://circe.github.io/circe/
[11]: https://datatracker.ietf.org/doc/html/rfc7396
[cats]: https://typelevel.org/cats/
[Foldable]: https://typelevel.org/cats/typeclasses/foldable.html
[diffson3]: https://github.com/gnieh/diffson/tree/v3.1.x


text:
package amai.org.conventions;

import android.animation.ValueAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.DecelerateInterpolator;

import androidx.coordinatorlayout.widget.CoordinatorLayout;

import com.google.android.material.appbar.AppBarLayout;

public class AppBarLayoutSnapBehavior extends AppBarLayout.Behavior {

	private ValueAnimator mAnimator;
	private boolean mNestedScrollStarted = false;
	private int lastScroll;

	public AppBarLayoutSnapBehavior(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	@Override
	public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child,
	                                   View directTargetChild, View target, int nestedScrollAxes) {
		mNestedScrollStarted = super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, nestedScrollAxes);
		lastScroll = 0;
		if (mNestedScrollStarted && mAnimator != null) {
			mAnimator.cancel();
		}
		return mNestedScrollStarted;
	}

	@Override
	public void onStopNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target) {
		super.onStopNestedScroll(coordinatorLayout, child, target);

		if (!mNestedScrollStarted) {
			return;
		}

		mNestedScrollStarted = false;

		int scrollRange = child.getTotalScrollRange();
		int topOffset = getTopAndBottomOffset();

		if (topOffset <= -scrollRange || topOffset >= 0) {
			// Already fully visible or fully invisible
			return;
		}

		if (lastScroll > 0) {
			// Snap up (to fully invisible)
			animateOffsetTo(-scrollRange);
		} else {
			// Snap down (to fully visible)
			animateOffsetTo(0);
		}

//		if (topOffset < -(scrollRange / 2f)) {
//			// Snap up (to fully invisible)
//			animateOffsetTo(-scrollRange);
//		} else {
//			// Snap down (to fully visible)
//			animateOffsetTo(0);
//		}
	}

	private void animateOffsetTo(int offset) {
		if (mAnimator == null) {
			mAnimator = new ValueAnimator();
			mAnimator.setInterpolator(new DecelerateInterpolator());
			mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
				@Override
				public void onAnimationUpdate(ValueAnimator animation) {
					setTopAndBottomOffset((int) animation.getAnimatedValue());
				}
			});
		} else {
			mAnimator.cancel();
		}

		mAnimator.setIntValues(getTopAndBottomOffset(), offset);
		mAnimator.start();
	}

	@Override
	public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dx, int dy, int[] consumed) {
		super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed);
		this.lastScroll = dy;
	}
}


text:
package pgtype

import (
	"database/sql/driver"
	"encoding/binary"
	"encoding/json"
	"time"

	"github.com/jackc/pgio"
	errors "golang.org/x/xerrors"
)

type Date struct {
	Time             time.Time
	Status           Status
	InfinityModifier InfinityModifier
}

const (
	negativeInfinityDayOffset = -2147483648
	infinityDayOffset         = 2147483647
)

func (dst *Date) Set(src interface{}) error {
	if src == nil {
		*dst = Date{Status: Null}
		return nil
	}

	if value, ok := src.(interface{ Get() interface{} }); ok {
		value2 := value.Get()
		if value2 != value {
			return dst.Set(value2)
		}
	}

	switch value := src.(type) {
	case time.Time:
		*dst = Date{Time: value, Status: Present}
	case string:
		return dst.DecodeText(nil, []byte(value))
	case *time.Time:
		if value == nil {
			*dst = Date{Status: Null}
		} else {
			return dst.Set(*value)
		}
	case *string:
		if value == nil {
			*dst = Date{Status: Null}
		} else {
			return dst.Set(*value)
		}
	default:
		if originalSrc, ok := underlyingTimeType(src); ok {
			return dst.Set(originalSrc)
		}
		return errors.Errorf("cannot convert %v to Date", value)
	}

	return nil
}

func (dst Date) Get() interface{} {
	switch dst.Status {
	case Present:
		if dst.InfinityModifier != None {
			return dst.InfinityModifier
		}
		return dst.Time
	case Null:
		return nil
	default:
		return dst.Status
	}
}

func (src *Date) AssignTo(dst interface{}) error {
	switch src.Status {
	case Present:
		switch v := dst.(type) {
		case *time.Time:
			if src.InfinityModifier != None {
				return errors.Errorf("cannot assign %v to %T", src, dst)
			}
			*v = src.Time
			return nil
		default:
			if nextDst, retry := GetAssignToDstType(dst); retry {
				return src.AssignTo(nextDst)
			}
			return errors.Errorf("unable to assign to %T", dst)
		}
	case Null:
		return NullAssignTo(dst)
	}

	return errors.Errorf("cannot decode %#v into %T", src, dst)
}

func (dst *Date) DecodeText(ci *ConnInfo, src []byte) error {
	if src == nil {
		*dst = Date{Status: Null}
		return nil
	}

	sbuf := string(src)
	switch sbuf {
	case "infinity":
		*dst = Date{Status: Present, InfinityModifier: Infinity}
	case "-infinity":
		*dst = Date{Status: Present, InfinityModifier: -Infinity}
	default:
		t, err := time.ParseInLocation("2006-01-02", sbuf, time.UTC)
		if err != nil {
			return err
		}

		*dst = Date{Time: t, Status: Present}
	}

	return nil
}

func (dst *Date) DecodeBinary(ci *ConnInfo, src []byte) error {
	if src == nil {
		*dst = Date{Status: Null}
		return nil
	}

	if len(src) != 4 {
		return errors.Errorf("invalid length for date: %v", len(src))
	}

	dayOffset := int32(binary.BigEndian.Uint32(src))

	switch dayOffset {
	case infinityDayOffset:
		*dst = Date{Status: Present, InfinityModifier: Infinity}
	case negativeInfinityDayOffset:
		*dst = Date{Status: Present, InfinityModifier: -Infinity}
	default:
		t := time.Date(2000, 1, int(1+dayOffset), 0, 0, 0, 0, time.UTC)
		*dst = Date{Time: t, Status: Present}
	}

	return nil
}

func (src Date) EncodeText(ci *ConnInfo, buf []byte) ([]byte, error) {
	switch src.Status {
	case Null:
		return nil, nil
	case Undefined:
		return nil, errUndefined
	}

	var s string

	switch src.InfinityModifier {
	case None:
		s = src.Time.Format("2006-01-02")
	case Infinity:
		s = "infinity"
	case NegativeInfinity:
		s = "-infinity"
	}

	return append(buf, s...), nil
}

func (src Date) EncodeBinary(ci *ConnInfo, buf []byte) ([]byte, error) {
	switch src.Status {
	case Null:
		return nil, nil
	case Undefined:
		return nil, errUndefined
	}

	var daysSinceDateEpoch int32
	switch src.InfinityModifier {
	case None:
		tUnix := time.Date(src.Time.Year(), src.Time.Month(), src.Time.Day(), 0, 0, 0, 0, time.UTC).Unix()
		dateEpoch := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC).Unix()

		secSinceDateEpoch := tUnix - dateEpoch
		daysSinceDateEpoch = int32(secSinceDateEpoch / 86400)
	case Infinity:
		daysSinceDateEpoch = infinityDayOffset
	case NegativeInfinity:
		daysSinceDateEpoch = negativeInfinityDayOffset
	}

	return pgio.AppendInt32(buf, daysSinceDateEpoch), nil
}

// Scan implements the database/sql Scanner interface.
func (dst *Date) Scan(src interface{}) error {
	if src == nil {
		*dst = Date{Status: Null}
		return nil
	}

	switch src := src.(type) {
	case string:
		return dst.DecodeText(nil, []byte(src))
	case []byte:
		srcCopy := make([]byte, len(src))
		copy(srcCopy, src)
		return dst.DecodeText(nil, srcCopy)
	case time.Time:
		*dst = Date{Time: src, Status: Present}
		return nil
	}

	return errors.Errorf("cannot scan %T", src)
}

// Value implements the database/sql/driver Valuer interface.
func (src Date) Value() (driver.Value, error) {
	switch src.Status {
	case Present:
		if src.InfinityModifier != None {
			return src.InfinityModifier.String(), nil
		}
		return src.Time, nil
	case Null:
		return nil, nil
	default:
		return nil, errUndefined
	}
}

func (src Date) MarshalJSON() ([]byte, error) {
	switch src.Status {
	case Null:
		return []byte("null"), nil
	case Undefined:
		return nil, errUndefined
	}

	if src.Status != Present {
		return nil, errBadStatus
	}

	var s string

	switch src.InfinityModifier {
	case None:
		s = src.Time.Format("2006-01-02")
	case Infinity:
		s = "infinity"
	case NegativeInfinity:
		s = "-infinity"
	}

	return json.Marshal(s)
}

func (dst *Date) UnmarshalJSON(b []byte) error {
	var s *string
	err := json.Unmarshal(b, &s)
	if err != nil {
		return err
	}

	if s == nil {
		*dst = Date{Status: Null}
		return nil
	}

	switch *s {
	case "infinity":
		*dst = Date{Status: Present, InfinityModifier: Infinity}
	case "-infinity":
		*dst = Date{Status: Present, InfinityModifier: -Infinity}
	default:
		t, err := time.ParseInLocation("2006-01-02", *s, time.UTC)
		if err != nil {
			return err
		}

		*dst = Date{Time: t, Status: Present}
	}

	return nil
}


text:
using System.Collections.Generic;

namespace NHS111.Utils.Extensions
{
    public static class ListExtension
    {
        public static List<T> InList<T>(this T item)
        {
            return new List<T> { item };
        }
    }
}


text:
define(['jquery','webgl-heatmap',
  'jquery.balloon.min'],function($,heatmap,balloon) {
	window.MouseTracker = function(customerId) {
		var self = this;
		this.customerId = customerId;
		this.movementList = [];
		this.clickPosition = [];
		this.url=window.location.href;
		this.urlId='';
		MAX_SIZE=100;
		this.init = function() {
			console.log("MOUSETRACKER:: init " + self.url);
			var bakbakClickMap = getUrlParameter('bakbakClickMap');
			console.log("MOUSETRACKER:: init " + bakbakClickMap);
			if(bakbakClickMap == 'map') {
				if(isValidUrl()) initClickMap();
			} else if(bakbakClickMap == 'count') {
				if(isValidUrl()) initClickCount();
			} else {
				if(isValidUrl()) initForRecording();
			}
		};

		function isValidUrl() {
			self.url = self.url.replace("?bakbakClickMap=map","");
			self.url = self.url.replace("?bakbakClickMap=count","");
			if(typeof clickTrackUrls === 'undefined') {
				return false;
			}
			for(url in clickTrackUrls) {
				console.log("MOUSETRACKER:: " +url);
				if(url == self.url) {
					self.urlId = clickTrackUrls[url];
					console.log('MOUSETRACKER:: Correct URL');
					return true;
				}
			}
			return false;
		}

		function sanatizeElement(el) {
			if(el.indexOf(':') > -1) {
            	 each = el.split(':');
            	 var newEl = '';
            	 for(i in each) {
            	 	if(i==0) {
            	 		newEl=each[0];
            	 	} else {
            	 		newEl = newEl+" :"+each[i]
            	 	}
            	 }
            	 console.log(newEl);
            	 return newEl;
            }
            return el;
		}

		function initClickMap() {
			var loadingOverLay = createLoadingOverLay();
			$(loadingOverLay).fadeIn(100);
			console.log("MOUSETRACKER:: init ClickMap");
			self.url = removeURLParameter(self.url,'bakbakClickMap');
			$.get( bakbakUrl + "mousetrack/?customerId="+customerId+"&pageUrl="+self.url+"&urlId="+self.urlId).done(function(data){
				try{
					 var canvas = createCanvasOverlay();
 				   	 var heatmap = createWebGLHeatmap({canvas: canvas, intensityToAlpha:true});
				} catch(ex){
					console.log("MOUSETRACKER::cannot create heat map" );
    				console.log(ex);
				}

				var raf = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
                                         window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
                var formatted_data = [];
                var maxClickCount = 0;
                for(i in data) {
                	var element = data[i].element;
                	element= sanatizeElement(element);
                	var clickCount = data[i].clickCount;
                	var offset = $(element).offset();
                	if(offset == null) {
                		console.log("MOUSETRACKER::ERROR:: null for " + element);
                		continue;
                	}

                	pageX = data[i].x+offset.left;
                	pageY = data[i].y+offset.top;
                	pixelSize = 1;
                	formatted_data.push({x:pageX,y:pageY,size:pixelSize,count:clickCount});
                	maxClickCount = clickCount > maxClickCount ? clickCount : maxClickCount;
				}
                var update = function(){
                 	for(i in formatted_data) {
                 		var count = formatted_data[i].count;
                 		intense = count/maxClickCount;
                 		if(intense < 0.1) intense = 0.1;
                 		if(intense > 0.7) intense = 0.7;
                 		console.log("Intense " + intense);
                 		heatmap.addPoint(formatted_data[i].x,formatted_data[i].y,15,intense);
                 	}
                    //heatmap.adjustSize(); // can be commented out for statically sized heatmaps, resize clears the map
                    heatmap.update(); // adds the buffered points
                    heatmap.display(); // adds the buffered points
                    //heatmap.multiply(0.9995);
                    //heatmap.blur();
                    //heatmap.clamp(0.0, 1.0); // depending on usecase you might want to clamp it
                    //raf(update);
                }
                raf(update);
                $(loadingOverLay).fadeOut(10000);
			});
		}

		function initClickCount() {
			var loadingOverLay = createLoadingOverLay();
			$(loadingOverLay).fadeIn(100);
			//var canvas = createCanvasOverlay();
			console.log("MOUSETRACKER:: init ClickCount");
			self.url = removeURLParameter(self.url,'bakbakClickMap');
			$.get( bakbakUrl + "mousetrack/count/?customerId="+customerId+"&pageUrl="+self.url+"&urlId="+self.urlId).done(function(data_response){
				console.log("MOUSETRACKER:: init "+data_response); //use list ineterface to add data, server return formatted data.
				colors = ['rgb(206, 212, 245)','rgb(132, 229, 210)','rgb(209, 184, 236)','rgb(250, 190, 226)','#6FFF00','#FF00FF','#FFFF00', '#4D4DFF','#FE0001','#FF4105','#993CF3','#FFFF'];
				for(var index_data in data_response) {
					var elem = data_response[index_data]._id;
					elem= sanatizeElement(elem);
					console.log("MOUSETRACKER:: "+elem);
					console.log(data_response[index_data]);
					var clickCount = data_response[index_data].total;
					$(elem).attr('clickCount',clickCount);
					position = 'bottom';
					offset = $($(elem)[0]).offset();
					zIndex = $($(elem)[0]).css('z-index')
					if( 32767 < zIndex) {
						zIndex = zIndex+1000;
					} else {
						zIndex=32767;
					}
					if(offset != null) {
						if ($(window).height() <  offset.top+50) {
							position = 'top';
						}
					}
					var i = index_data % colors.length;
					$($(elem)[0]).balloon({
						contents:'
'+clickCount+'
',
						position: position,
						minLifetime: 20000,
						css: {
							'background-color': colors[i],
							'z-index': zIndex
						}
					}).showBalloon();
					$($(elem)[0]).css('border','1px solid '+colors[i]);

				}
				console.log("MOUSETRACKER:: done")
				$(loadingOverLay).fadeOut(1000);
			});
		}

		function send() {
			console.log("MOUSETRACKER:: Sending MouseTracking Data.");
			socket.mouseTrack(customerId,
				{'mouseMovements': self.movementList,
				  'clickPosition': self.clickPosition,
				 'pageUrl' : self.url,
				 'customerId' : self.customerId,
				  'urlId': self.urlId
				}
			);
			self.clickPosition=[]; //Can loose Clicks.
			initMovementList(); //Can loose some movement.
		}

		function initForRecording() {
			initMovementList();
			//initMovementListeners();
			initClickListeners();
		}

		function initClickListeners() {
			console.log("MOUSETRACKER:: init initClickListeners")
			$(window).click(function(e) {
				self.clickPosition.push(getPosition(e));
				send();
				return;
			});
		}

		function initMovementListeners() {
			$(window).mousemove(function(e) {
				self.movementList.push(getPosition(e));
				if(self.movementList.length > MAX_SIZE) {
					send();
				}
				return;
			});
		}

		function initMovementList() {
			self.movementList=[];
			self.movementList.push(getPosition(getDummyE()));
		}

		function getDummyE() {
			var e={};
			e['srcElement']=$('body');
			e['pageX']=0;
			e['pageY']=0;
			e['time']=Date.now();
			return e;
		}

		function getPosition(e) {
			var pos={};
			var el = e.srcElement;
			if(!el) {
				el=e.target;
			}
			element = findElementLocation(el);
			console.log(findElementLocation(el));
			offset = $(el).offset();
			console.log(offset);
			pos['pageX'] = e.pageX-offset.left;
			pos['pageY'] = e.pageY - offset.top;
			pos['element'] = element;
			pos['time'] = Date.now();
			return pos;
		}

		function createLoadingOverLay() {
			myCanvas = document.createElement('div');
  			document.body.appendChild(myCanvas);
  			myCanvas.style.position = 'absolute';
  			myCanvas.style.left="0px";
  			myCanvas.style.top="0px";
  			myCanvas.style.zIndex="10";
  			myCanvas.style.opacity=0.8;
  			myCanvas.style.background="#aaa";
  			myCanvas.id="bakbakloadingMask";
  			$(myCanvas).html("
Loading");
  			return myCanvas;
		}

		function createCanvasOverlay() {
  			myCanvas = document.createElement('canvas');
  			document.body.appendChild(myCanvas);
  			myCanvas.id='heatmapEl';
  			myCanvas.style.position = 'absolute';
  			myCanvas.style.left="0px";
  			myCanvas.style.top="0px";
  			myCanvas.style.zIndex="99999";
  			myCanvas.style.width="100%";
  			myCanvas.style.height="100%";
  			//myCanvas.width=myCanvas.offsetWidth;
  			//myCanvas.height=myCanvas.offsetHeight;
  			return myCanvas;
		}

	};
});


text:
package com.intellij.ide.actions;

import com.intellij.ide.IdeBundle;
import com.intellij.ide.impl.ProjectViewSelectInTarget;
import com.intellij.ide.projectView.impl.ProjectViewPane;
import com.intellij.openapi.command.UndoConfirmationPolicy;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.command.undo.GlobalUndoableAction;
import com.intellij.openapi.command.undo.UndoManager;
import com.intellij.openapi.components.impl.stores.IProjectStore;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ContentEntry;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ModuleRootModificationUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.project.ProjectKt;
import com.intellij.util.Consumer;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.JBIterable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class AttachDirectoryUtils {
  public static void chooseAndAddDirectoriesWithUndo(@NotNull Project project, @Nullable Consumer<? super List<VirtualFile>> callback) {
    Module module = getAttachTargetModule(project);
    FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createAllButJarContentsDescriptor();
    FileChooser.chooseFiles(descriptor, project, null, files -> {
      addAndSelectDirectoriesWithUndo(project, module, files);
      if (callback != null) callback.consume(files);
    });
  }

  public static void addDirectoriesWithUndo(@NotNull Project project, @NotNull List<VirtualFile> roots) {
    Module module = getAttachTargetModule(project);
    if (module == null) return;
    addAndSelectDirectoriesWithUndo(project, module, roots);
  }

  private static void addAndSelectDirectoriesWithUndo(@NotNull Project project, @Nullable Module module, @NotNull List<VirtualFile> roots) {
    addRemoveEntriesWithUndo(project, module, roots, true);
    VirtualFile file = ContainerUtil.getFirstItem(roots);
    if (file != null) {
      ProjectViewSelectInTarget.select(project, file, ProjectViewPane.ID, null, file, true);
    }
  }

  public static void addRemoveEntriesWithUndo(@NotNull Project project, @Nullable Module module, @NotNull List<VirtualFile> roots, boolean add) {
    List<VirtualFile> adjustedRoots = ContainerUtil.newArrayList(JBIterable.from(roots)
      .filter(o -> add == (ModuleUtilCore.findModuleForFile(o, project) == null))
      .filterMap(o -> o.isDirectory() ? o : o.getParent())
      .unique());
    adjustedRoots.removeIf(r -> ContainerUtil.exists(adjustedRoots, r2 -> VfsUtilCore.isAncestor(r2, r, true)));

    if (adjustedRoots.isEmpty()) return;

    class MyUndoable extends GlobalUndoableAction {
      @Override
      public void undo() {
        addRemoveEntriesInner(project, module, adjustedRoots, !add);
      }

      @Override
      public void redo() {
        addRemoveEntriesInner(project, module, adjustedRoots, add);
      }
    }
    String title = IdeBundle.message("command.name.choice.attach.detach", add ? 0 : 1, getDisplayName(adjustedRoots));
    WriteCommandAction.writeCommandAction(project)
      .withName(title)
      .withUndoConfirmationPolicy(UndoConfirmationPolicy.REQUEST_CONFIRMATION).run(()-> {
        MyUndoable undoable = new MyUndoable();
        undoable.redo();
        UndoManager.getInstance(project).undoableActionPerformed(undoable);
    });
  }

  public static void excludeEntriesWithUndo(@NotNull Project project, @NotNull List<VirtualFile> roots, boolean exclude) {
    Module module = getAttachTargetModule(project);
    if (module != null) {
      excludeEntriesWithUndo(module, roots, exclude);
    }
  }
  public static void excludeEntriesWithUndo(@NotNull Module module, @NotNull List<VirtualFile> roots, boolean exclude) {
    if (roots.isEmpty()) return;
    Project project = module.getProject();

    class MyUndoable extends GlobalUndoableAction {
      @Override
      public void undo() {
        excludeEntriesInner(module, roots, !exclude);
      }

      @Override
      public void redo() {
        excludeEntriesInner(module, roots, exclude);
      }
    }
    String title = IdeBundle.message("command.name.choice.exclude.include", exclude ? 0 : 1, getDisplayName(roots));
    WriteCommandAction.writeCommandAction(project)
      .withName(title)
      .withUndoConfirmationPolicy(UndoConfirmationPolicy.REQUEST_CONFIRMATION).run(()-> {
        MyUndoable undoable = new MyUndoable();
        undoable.redo();
        UndoManager.getInstance(project).undoableActionPerformed(undoable);
    });
  }

  public static String getDisplayName(@NotNull List<VirtualFile> roots) {
    return roots.size() == 1 ? "directory '" + roots.get(0).getName() + "'" :
           roots.size() + " " + StringUtil.pluralize("directory", roots.size());
  }

  private static void addRemoveEntriesInner(@NotNull Project project, @Nullable Module module, @NotNull List<VirtualFile> files, boolean add) {
    if (module == null) module = getAttachTargetModule(project);
    if (module == null) module = createDefaultModule(project);
    ModuleRootModificationUtil.updateModel(module, model -> {
      if (add) {
        for (VirtualFile file : files) {
          model.addContentEntry(file);
        }
      }
      else {
        for (ContentEntry entry : model.getContentEntries()) {
          if (files.contains(entry.getFile())) {
            model.removeContentEntry(entry);
          }
        }
      }
    });
  }

  private static void excludeEntriesInner(@NotNull Module module, @NotNull List<VirtualFile> files, boolean exclude) {
    ModuleRootModificationUtil.updateModel(module, model -> {
      for (ContentEntry entry : model.getContentEntries()) {
        VirtualFile root = entry.getFile();
        if (root == null) continue;
        for (VirtualFile file : files) {
          if (VfsUtilCore.isAncestor(root, file, true)) {
            if (exclude) {
              entry.addExcludeFolder(file);
            }
            else {
              entry.removeExcludeFolder(file.getUrl());
            }
          }
        }
      }
    });
  }

  @Nullable
  private static Module getAttachTargetModule(@NotNull Project project) {
    Module[] modules = ModuleManager.getInstance(project).getModules();
    return modules.length == 0 ? null : modules[0];
  }

  @NotNull
  private static Module createDefaultModule(@NotNull Project project) {
    IProjectStore store = ProjectKt.getStateStore(project);
    Path proDir = store.getProjectFilePath().getParent();
    Path modulePath = proDir.resolve(project.getName() + ".iml");
    ModuleType<?> defType = ModuleTypeManager.getInstance().getDefaultModuleType();
    return ModuleManager.getInstance(project).newModule(modulePath, defType.getId());
  }

  @NotNull
  public static List<VirtualFile> getAttachedDirectories(@NotNull Project project) {
    Module module = getAttachTargetModule(project);
    return module != null ? Arrays.asList(ModuleRootManager.getInstance(module).getContentRoots()) : Collections.emptyList();
  }
}


text:
autocommit off;
create class bowwow (arf int);
insert into bowwow values (10);
insert into bowwow values (NULL);
select count(*) from bowwow;
select count(arf) from bowwow;
rollback;


text:
package com.xsolla.android.sdk.data.model.sellable;

import com.xsolla.android.sdk.data.model.SimpleSellItem;
import com.xsolla.android.sdk.data.model.utils.XUtils;
import com.xsolla.android.sdk.util.DateTimeFormatter;
import com.xsolla.android.sdk.util.XTConst;

public class XUserSubscription {

    private long id;//"id":7224613,

    private String id_external;//"id_external":"187fc9f4",
    private String name;//"name":"7 days",
    private String status;//"status":"active",// 'active' || 'non_renewing' || 'freeze'
    private String date_next_charge;//"date_next_charge":"2016-09-26T14:10:19+03:00",
    private String payment_method;//"payment_method":"Credit\/Debit Cards",
    private String payment_visible_name;//"payment_visible_name":"415481******7741",
    private String payment_type;//"payment_type":"charge"

    private HoldDates hold_dates;//"hold_dates":null,
    private SimpleSellItem charge;//"charge":{"amount":"0.3000", "currency":"USD"},

    public long getId() {
        return id;
    }

    public String getIdExternal() {
        return id_external;
    }

    public String getTitle() {
        return name;
    }

    public String getNextCharge() {
        return DateTimeFormatter.formatDateNoTime("", date_next_charge);
    }

    public boolean isPaymentMethod() {
        return payment_method != null;
    }

    public String getPaymentMethod() {
        if(payment_method != null)
            return String.format("%s %s", payment_method, payment_visible_name);
        else
            return "";
    }

    public HoldDates getHoldDates() {
        return hold_dates;
    }

    public String getAmount() {
        return charge.getPrice();
    }

    public SubscriptionStatus getStatus() {
        switch (status){
            case "active":
                return SubscriptionStatus.ACTIVE;
            case "non_renewing":
                return SubscriptionStatus.NON_RENEWING;
            case "freeze":
                return SubscriptionStatus.FREEZE;
            default:
                return SubscriptionStatus.UNKNOWN;
        }
    }

    public String getStatusString() {
        switch (status){
            case "active":
                return XUtils.getInstance().getTranslation(XTConst.USER_SUBSCRIPTION_STATUS_ACTIVE);
            case "non_renewing":
                return XUtils.getInstance().getTranslation(XTConst.USER_SUBSCRIPTION_STATUS_NON_RENEWING);
            case "freeze":
                return XUtils.getInstance().getTranslation(XTConst.USER_SUBSCRIPTION_STATUS_FREEZE);
            default:
                return "UNKNOWN";
        }
    }

    @Override
    public String toString() {
        return "XSubscription{" +
                "id=" + id +
                ", id_external='" + id_external + '\'' +
                ", name='" + name + '\'' +
                ", status='" + status + '\'' +
                ", date_next_charge='" + date_next_charge + '\'' +
                ", payment_method='" + payment_method + '\'' +
                ", payment_visible_name='" + payment_visible_name + '\'' +
                ", payment_type='" + payment_type + '\'' +
//                ", hold_dates='" + hold_dates + '\'' +
                ", charge=" + charge +
                '}';
    }

    class HoldDates {

        private String date_from;
        private String date_to;

        @Override
        public String toString() {
            return String.format("%s — %s",
                    DateTimeFormatter.formatDateNoTime("", date_from),
                    DateTimeFormatter.formatDateNoTime("", date_to));
        }
    }
}


text:
<?php
namespace Czim\VanDomburgApiClient\Data;

/**
 * @property int     $id
 * @property \Carbon\Carbon $created_at
 * @property \Carbon\Carbon $updated_at
 * @property string  $slug
 * @property string  $title
 * @property string  $description
 * @property string  $og_title
 * @property string  $og_description
 * @property string  $og_type
 * @property string  $og_image
 */
class Seo extends AbstractDataObject
{
}


text:
package aggregated_logging

import (
	"errors"
	"testing"

	kapi "k8s.io/kubernetes/pkg/api"

	"github.com/openshift/origin/pkg/diagnostics/log"
	routesapi "github.com/openshift/origin/pkg/route/api"
)

const (
	testRoutesKey = "routes"
)

type fakeRoutesDiagnostic struct {
	fakeDiagnostic
	fakeRoutes   routesapi.RouteList
	clienterrors map[string]error
}

func newFakeRoutesDiagnostic(t *testing.T) *fakeRoutesDiagnostic {
	return &fakeRoutesDiagnostic{
		fakeDiagnostic: *newFakeDiagnostic(t),
		clienterrors:   map[string]error{},
	}
}

func (f *fakeRoutesDiagnostic) addRouteWith(condType routesapi.RouteIngressConditionType, condStatus kapi.ConditionStatus, cert string, key string) {
	ingress := routesapi.RouteIngress{
		Conditions: []routesapi.RouteIngressCondition{
			{
				Type:   condType,
				Status: condStatus,
			},
		},
	}
	route := routesapi.Route{
		ObjectMeta: kapi.ObjectMeta{Name: "aname"},
		Status: routesapi.RouteStatus{
			Ingress: []routesapi.RouteIngress{ingress},
		},
	}
	if len(cert) != 0 && len(key) != 0 {
		tls := routesapi.TLSConfig{
			Certificate: cert,
			Key:         key,
		}
		route.Spec.TLS = &tls
	}
	f.fakeRoutes.Items = append(f.fakeRoutes.Items, route)
}

func (f *fakeRoutesDiagnostic) routes(project string, options kapi.ListOptions) (*routesapi.RouteList, error) {
	value, ok := f.clienterrors[testRoutesKey]
	if ok {
		return nil, value
	}
	return &f.fakeRoutes, nil
}

func TestRouteWhenErrorFromClient(t *testing.T) {
	d := newFakeRoutesDiagnostic(t)
	d.clienterrors[testRoutesKey] = errors.New("some client error")

	checkRoutes(d, d, fakeProject)
	d.assertMessage("AGL0305", "Exp an error when there is a client error retrieving routes", log.ErrorLevel)
	d.dumpMessages()
}

func TestRouteWhenZeroRoutesAvailable(t *testing.T) {
	d := newFakeRoutesDiagnostic(t)

	checkRoutes(d, d, fakeProject)
	d.assertMessage("AGL0310", "Exp an error when there are no routes to support logging", log.ErrorLevel)
	d.dumpMessages()
}

//test error route != accepted
func TestRouteWhenRouteNotAccepted(t *testing.T) {
	d := newFakeRoutesDiagnostic(t)
	d.addRouteWith(routesapi.RouteExtendedValidationFailed, kapi.ConditionTrue, "", "")

	checkRoutes(d, d, fakeProject)
	d.assertMessage("AGL0325", "Exp an error when a route was not accepted", log.ErrorLevel)
	d.assertMessage("AGL0331", "Exp to skip the cert check since none specified", log.DebugLevel)
	d.dumpMessages()
}
func TestRouteWhenRouteAccepted(t *testing.T) {
	d := newFakeRoutesDiagnostic(t)
	d.addRouteWith(routesapi.RouteAdmitted, kapi.ConditionTrue, "", "")

	checkRoutes(d, d, fakeProject)
	d.assertNoErrors()
	d.dumpMessages()
}

func TestRouteWhenErrorDecodingCert(t *testing.T) {
	d := newFakeRoutesDiagnostic(t)
	d.addRouteWith(routesapi.RouteExtendedValidationFailed, kapi.ConditionTrue, "cert", "key")

	checkRoutes(d, d, fakeProject)
	d.assertMessage("AGL0350", "Exp an error when unable to decode cert", log.ErrorLevel)
	d.dumpMessages()
}

func TestRouteWhenErrorParsingCert(t *testing.T) {
	d := newFakeRoutesDiagnostic(t)
	d.addRouteWith(routesapi.RouteExtendedValidationFailed, kapi.ConditionTrue, "cert", "key")

	checkRoutes(d, d, fakeProject)
	d.assertMessage("AGL0350", "Exp an error when unable to decode cert", log.ErrorLevel)
	d.dumpMessages()
}