text:
package net.violet.platform.message;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.violet.platform.api.converters.ConversionException;
import net.violet.platform.api.converters.Converter;
import net.violet.platform.api.converters.ConverterFactory;
import net.violet.platform.api.exceptions.APIErrorMessage;
import net.violet.platform.api.exceptions.InvalidParameterException;
import net.violet.platform.api.exceptions.NoSuchPersonException;
import net.violet.platform.datamodel.Application;
import net.violet.platform.datamodel.Files;
import net.violet.platform.datamodel.Lang;
import net.violet.platform.datamodel.MimeType;
import net.violet.platform.datamodel.TtsVoice;
import net.violet.platform.datamodel.User;
import net.violet.platform.datamodel.VObject;
import net.violet.platform.datamodel.factories.Factories;
import net.violet.platform.dataobjects.ObjectType;
import net.violet.platform.dataobjects.UserData;
import net.violet.platform.dataobjects.VObjectData;
import net.violet.platform.dataobjects.MessageData.Palette;
import net.violet.platform.interactif.SecureStream;
import net.violet.platform.message.elements.Directive;
import net.violet.platform.message.elements.Expression;
import net.violet.platform.message.elements.SecurePart;
import net.violet.platform.message.elements.SequencePart;
import net.violet.platform.message.elements.SequencePartFactory;
import net.violet.platform.message.elements.SignatureAnimWrapper;
import net.violet.platform.message.elements.SignatureMusicWrapper;
import net.violet.platform.message.elements.StartInteractiveWrapper;
import net.violet.platform.message.elements.StreamWrapper;
import net.violet.platform.util.CCalendar;
import net.violet.platform.util.ConvertTools;
import net.violet.platform.voice.TTSServices;

/**
 * A Message object which can be modified.
 */
public class MessageDraft extends AddressedMessage {

	/**
	 * Regex for the TTS command
	 */
	private static final Pattern TTS_COMMAND_REGEX = Pattern.compile("TTS ([^\\s]+)\\s+(.*)");

	/**
	 * @param inPojo
	 * @param inRfid
	 * @param inCaller
	 * @return
	 * @throws NoSuchPersonException
	 * @throws InvalidParameterException
	 */
	public static List<MessageDraft> createFromPojo(Map<String, Object> inPojo, VObject inRfid, String inAPIKey) throws NoSuchPersonException, InvalidParameterException {

		// Retrieves the involved sender
		final String theFromID = (String) inPojo.get("from");
		final User sender;
		if (theFromID != null) {
			final UserData senderData = UserData.findByAPIId(theFromID, inAPIKey);
			if (senderData == null) {
				throw new NoSuchPersonException(APIErrorMessage.INVALID_SENDER);
			}
			sender = senderData.getReference();
		} else {
			sender = null;
		}

		// Builds the list of receivers
		if (inPojo.get("to") == null) {
			throw new InvalidParameterException(APIErrorMessage.MISSING_PARAMETER, "to");
		}
		if (!(inPojo.get("to") instanceof List)) {
			throw new InvalidParameterException(APIErrorMessage.NOT_A_LIST, "to");
		}

		final List<VObjectData> receiversList = new ArrayList<VObjectData>();
		for (final String aReceiver : (List<String>) inPojo.get("to")) {
			final VObjectData receiver = VObjectData.findByAPIId(aReceiver, inAPIKey);
			if (receiver != null) {
				receiversList.add(receiver);
			}
		}

		// The title (optional)
		final String msgTitle = (String) inPojo.get("title");

		// The date (optional)
		CCalendar theDeliveryDate = null;
		if ((inPojo.get("date") != null) && (sender != null)) {
			theDeliveryDate = new CCalendar(TimeZone.getTimeZone(sender.getTimezone().getTimezone_javaId()));
			theDeliveryDate.setTime((Date) inPojo.get("date"));
		}

		// The application
		final String applicationName = (String) inPojo.get("application");
		final Application app = Factories.APPLICATION.findByName(applicationName);

		// The sequences
		final List<Map<String, Object>> theSequenceArray = (List<Map<String, Object>>) inPojo.get("sequence");
		if (theSequenceArray == null) {
			throw new InvalidParameterException(APIErrorMessage.MISSING_PARAMETER, net.violet.common.StringShop.EMPTY_STRING);
		}

		final List<SequencePart> theSequence = SequencePartFactory.buildSequence(theSequenceArray, inRfid, app);

		// creates MessageDraft objects for each receiver using the specified
		// sequences
		final List<MessageDraft> theMessages = new ArrayList<MessageDraft>();
		for (final VObjectData receiver : receiversList) {
			final MessageDraft aMessage = new MessageDraft(receiver.getReference());
			aMessage.setSender(sender);
			aMessage.setTitle(msgTitle);
			aMessage.setApplication(app);
			aMessage.mPartsList.addAll(theSequence);
			aMessage.setDeliveryDate(theDeliveryDate);
			theMessages.add(aMessage);
		}

		return theMessages;
	}

	private final List<SequencePart> mIntro;
	private final List<SequencePart> mOutro;
	private final List<SequencePart> mPartsList;

	/**
	 * Creates a MessageDraft with the given object as receiver.
	 *
	 * @param inDest the receiver
	 */
	public MessageDraft(VObject inDest) {
		super(inDest);
		this.mPartsList = new ArrayList<SequencePart>();
		this.mIntro = new ArrayList<SequencePart>();
		this.mOutro = new ArrayList<SequencePart>();
	}

	/**
	 * Adds an audio file to play. The url refers to the sound to play. The
	 * boolean parameters are used to describe the reading object behavior :
	 * should it stream and/or move its ears.
	 *
	 * @param url
	 * @param streaming
	 * @param movingEars
	 */
	public void addAudio(String url, boolean streaming, boolean movingEars) {
		final Map<String, Object> pojo = new HashMap<String, Object>();
		pojo.put("modality", "net.violet.sound.mp3");
		pojo.put("url", url);
		pojo.put("streaming", streaming);
		pojo.put("withEar", movingEars);

		this.mPartsList.add(new Expression(pojo));
	}

	public void addWebRadio(String url) {
		final Map<String, Object> pojo = new HashMap<String, Object>();
		pojo.put("modality", "net.violet.webradio");
		pojo.put("url", url);
		this.mPartsList.add(new Expression(pojo));
	}

	/**
	 * Adds a serie of TTS messages indexed by their language
	 *
	 * @param inTTSMap
	 */
	public void addTTS(Map<Lang, String> inTTSMap) {

		final Map<String, Object> mainModality = new HashMap<String, Object>();
		final List<Map<String, Object>> alternatives = new ArrayList<Map<String, Object>>();
		int count = 0;

		for (final Lang lang : inTTSMap.keySet()) {

			if (count == 0) {
				mainModality.put("modality", "net.violet.tts." + lang.getIETFCode());
				mainModality.put("text", inTTSMap.get(lang));
				count++;

			} else { // c'est une alternative
				final Map<String, Object> alternative = new HashMap<String, Object>();
				alternative.put("modality", "net.violet.tts." + lang.getIETFCode());
				alternative.put("text", inTTSMap.get(lang));
				alternatives.add(alternative);
			}
		}

		if (alternatives.size() > 0) {
			mainModality.put("alt", alternatives);
		}

		this.mPartsList.add(new Expression(mainModality));
	}

	public void addPage2Browse(String inUrl) {
		final Map<String, Object> pojo = new HashMap<String, Object>();
		pojo.put("modality", "net.violet.browser");
		pojo.put("url", inUrl);
		this.mPartsList.add(new Expression(pojo));
	}

	/**
	 * Adds a secure audio content to the message.
	 *
	 * @param inUrl url to the content to add.
	 */
	public void addAudioStreamSecure(String inName, long inPosition) {
		final String theURL = SecureStream.getStreamUrl(inName, inPosition);
		this.mPartsList.add(new SecurePart(theURL));
	}

	/**
	 * Ajoute une chorégraphie au message.
	 *
	 * @param url chemin/url vers le contenu à ajouter.
	 */
	public void addChoreography(String url, boolean streaming) {
		final Map<String, Object> pojo = new HashMap<String, Object>();
		pojo.put("modality", "net.violet.choreography");
		pojo.put("url", url);
		pojo.put("streaming", streaming);
		this.mPartsList.add(new Expression(pojo));
	}

	/**
	 * Ajoute une palette pour la chorégraphie d'un message.
	 *
	 * @param palette
	 */
	public void addPalette(Palette inPalette) {

		final Map<String, Object> pojo = new HashMap<String, Object>();
		pojo.put("modality", "net.violet.palette");
		pojo.put("name", inPalette.getName());
		this.mPartsList.add(new Expression(pojo));
	}

	/**
	 * Lancement du mode interactif
	 *
	 * @param inUrl chemin/url vers le contenu à ajouter.
	 */
	public void addStartInteractive(String inUrl) {
		this.mPartsList.add(new StartInteractiveWrapper(inUrl));
	}

	/**
	 * Adds an instruction to start the interactive mode. Caution : the
	 * MessageDraft object MUST have an application to correctly start the
	 * interactive mode.
	 *
	 * @param rfid
	 */
	public void addStartInteractive(VObject rfid) {
		final Map<String, Object> pojo = new HashMap<String, Object>();
		pojo.put("action", "start-interactive");

		this.mPartsList.add(new Directive(pojo, rfid, getApplication()));
	}

	/**
	 * Arret du mode interactif
	 */
	public void addEndInteractive() {
		final Map<String, Object> pojo = new HashMap<String, Object>();
		pojo.put("action", "stop-interactive");

		this.mPartsList.add(new Directive(pojo, null, getApplication()));
	}

	/**
	 * Identification d'un flux de streaming.
	 *
	 * @param inStreamId id du stream.
	 */
	public void addStreamId(String inStreamId) {
		this.mPartsList.add(new StreamWrapper(inStreamId, true));
	}

	/**
	 * Fin d'un flux de streaming.
	 *
	 * @param inStreamId id du stream.
	 */
	public void addStreamStop(String inStreamId) {
		this.mPartsList.add(new StreamWrapper(inStreamId, false));
	}

	/**
	 * Ajoute un setting
	 *
	 * @param inSetting : ex => <setting>=<value>
	 */
	public void addSetting(String inSetting) {
		final Map<String, Object> pojo = new HashMap<String, Object>();
		final Map<String, String> settings = new HashMap<String, String>();
		settings.put(inSetting.split("=")[0], inSetting.split("=")[1]);
		pojo.put("settings", settings);

		this.mPartsList.add(new Directive(pojo, null, getApplication()));
	}

	/**
	 * Ajoute une instruction pour attendre un certain temps sans rien faire
	 *
	 * @param nbMs le nombre de milisecondes qu'on veut que le lapin attende
	 */
	public void addWaitMs(int nbMs) {

		final Map<String, Object> pojo = new HashMap<String, Object>();
		pojo.put("modality", "net.violet.wait");
		pojo.put("time_ms", nbMs);

		this.mPartsList.add(new Expression(pojo));
	}

	public void addSignature(MessageSignature inSignature) {
		this.mIntro.clear();
		this.mOutro.clear();

		if (inSignature == null) {
			return;
		}

		final String theIntroMusicUrl = inSignature.getIntroMusicUrl();
		if (theIntroMusicUrl != null) {
			this.mIntro.add(new SignatureMusicWrapper(theIntroMusicUrl));
		}

		final String theIntroAnimChoregraphyUrl = inSignature.getIntroChoregraphyUrl();
		if (theIntroAnimChoregraphyUrl != null) {
			this.mIntro.add(new SignatureAnimWrapper(inSignature.getColor4Message(), theIntroAnimChoregraphyUrl));
		}

		final String theOutroMusicUrl = inSignature.getOutroMusicUrl();
		if (theOutroMusicUrl != null) {
			this.mOutro.add(new SignatureMusicWrapper(theOutroMusicUrl));
		}

		final String theOutroAnimChoregraphyUrl = inSignature.getOutroChoregraphyUrl();
		if (theOutroAnimChoregraphyUrl != null) {
			this.mOutro.add(new SignatureAnimWrapper(inSignature.getColor4Message(), theOutroAnimChoregraphyUrl));
		}
	}

	/**
	 * Adds a Pojo object to the message draft. The given string should be
	 * encoded according to the provided format, and once decoded it must be a
	 * valid pojo according to the VioletOS Specification.
	 *
	 * @param inPojo
	 * @param format
	 * @throws ConversionException
	 * @throws InvalidParameterException
	 */
	public void addPojo(String inPojo, MimeType.MIME_TYPES format) throws ConversionException, InvalidParameterException {

		final Converter converter = ConverterFactory.getConverter(format);
		if (converter == null) {
			return;
		}

		this.mPartsList.addAll(SequencePartFactory.buildSequence(Collections.singletonList(converter.<Map<String, Object>> convertFrom(inPojo)), null, getApplication()));
	}

	/**
	 * Retourne la liste des séquences.
	 */
	public final List<Sequence> getSequenceList() {
		final List<Sequence> result = new ArrayList<Sequence>();
		final VObject dest = getReceiver();

		for (final SequencePart part : this.mIntro) {
			result.addAll(part.getSequence(dest));
		}

		for (final SequencePart part : this.mPartsList) {
			result.addAll(part.getSequence(dest));
		}

		for (final SequencePart part : this.mOutro) {
			result.addAll(part.getSequence(dest));
		}

		return result;
	}

	public final List<SequencePart> getSequencePart() {
		final List<SequencePart> result = new ArrayList<SequencePart>();
		result.addAll(this.mIntro);
		result.addAll(this.mPartsList);
		result.addAll(this.mOutro);
		return result;
	}

	public void fillMessageDraft(String inTitle, MessageSignature inSignature, MessageServices.Body[] inBody) {
		setTitle(inTitle);

		if (inSignature != null) {
			addSignature(inSignature);
		}

		fillMessageDraft(inBody);
	}

	public void fillMessageDraft(MessageServices.Body... inBody) {

		for (int i = 0; i < inBody.length; i++) {
			final Files bodyElement = inBody[i].getFile();
			final Palette paletteElement = inBody[i].getPalette();

			if ((bodyElement.getPath() != null) && !net.violet.common.StringShop.EMPTY_STRING.equals(bodyElement.getPath())) {
				addAudio(bodyElement.getPath(), inBody[i].isStream(), true);
			} else if ((bodyElement.getPath2midi() != null) && !net.violet.common.StringShop.EMPTY_STRING.equals(bodyElement.getPath2midi())) {
				addAudio(bodyElement.getPath2midi(), inBody[i].isStream(), true);
			}

			final VObjectData theReceiver = VObjectData.getData(getReceiver());

			if ((theReceiver != null) && theReceiver.isValid() && (theReceiver.getObjectType().instanceOf(ObjectType.NABAZTAG_V1) || theReceiver.getObjectType().instanceOf(ObjectType.DALDAL)) && (bodyElement.getPath2chor() != null) && !net.violet.common.StringShop.EMPTY_STRING.equals(bodyElement.getPath2chor())) {
				addPalette(paletteElement);
				addChoreography(bodyElement.getPath2chor(), inBody[i].isStream());
			}
		}
	}

	/**
	 * Ajoute des séquences à partir d'une chaîne dans un langage intermédiaire.
	 */
	public void addSequences(String[] inSequences, boolean isSecure) {

		for (final String sequence : inSequences) {

			if (sequence.startsWith("PLAY ")) { // PLAY son -> addAudio
				final String theUrl = sequence.replaceAll("PLAY ", net.violet.common.StringShop.EMPTY_STRING);
				addAudio(theUrl, false, true);

			} else if (sequence.startsWith("STREAM ")) {// STREAM [palette] url
				// -> addAudio
				final StringTokenizer theStreamOption = new StringTokenizer(sequence, net.violet.common.StringShop.SPACE);
				final int nb = theStreamOption.countTokens();
				theStreamOption.nextToken(); // exit STREAM
				if (nb == 2) {
					addAudio(theStreamOption.nextToken(), true, true);
				} else if (nb == 3) {
					final Integer paletteNum = Integer.parseInt(theStreamOption.nextToken());
					final Palette palette = Palette.findPaletteByNum(paletteNum);
					addPalette(palette);
					addAudio(theStreamOption.nextToken(), true, true);
				}

			} else if (sequence.startsWith("STREAM_ID ")) {// STREAM_ID foo ->
				// addStreamId
				final String theID = sequence.replaceAll("STREAM_ID ", net.violet.common.StringShop.EMPTY_STRING);
				addStreamId(theID);

			} else if (sequence.startsWith("STREAM_STOP ")) {// STREAM_STOP foo
				// ->
				// addStreamStop
				final String theID = sequence.replaceAll("STREAM_STOP ", net.violet.common.StringShop.EMPTY_STRING);
				addStreamStop(theID);

			} else if (sequence.startsWith("SSTREAM ") && isSecure) {// SSTREAM
				// [
				// palette
				// ] url
				// position
				// ->
				// addAudio
				final StringTokenizer theStreamOption = new StringTokenizer(sequence, net.violet.common.StringShop.SPACE);
				final int nb = theStreamOption.countTokens();
				theStreamOption.nextToken(); // exit SSTREAM
				if (nb == 3) {
					addAudioStreamSecure(theStreamOption.nextToken(), ConvertTools.atol(theStreamOption.nextToken()));
				} else if (nb == 4) {
					final int paletteNum = ConvertTools.atoi(theStreamOption.nextToken());
					final Palette palette = Palette.findPaletteByNum(paletteNum);
					addPalette(palette);
					addAudioStreamSecure(theStreamOption.nextToken(), ConvertTools.atol(theStreamOption.nextToken()));
				}

			} else if (sequence.startsWith("CHOR")) { // CHOR [palette] url -> addChoregraphy
				final StringTokenizer theChorOption = new StringTokenizer(sequence, net.violet.common.StringShop.SPACE);
				final int nb = theChorOption.countTokens();
				theChorOption.nextToken(); // exit CHOR
				if (nb == 2) {
					addChoreography(theChorOption.nextToken(), false);
				} else if (nb == 3) {
					final Integer paletteNum = Integer.parseInt(theChorOption.nextToken());
					final Palette palette = Palette.findPaletteByNum(paletteNum);
					final String theUrl = theChorOption.nextToken();
					addPalette(palette);
					addChoreography(theUrl, false);
				}

			} else if (sequence.startsWith("TTS")) {// TTS voice message ->
				// addAudio
				final Matcher theMatcher = MessageDraft.TTS_COMMAND_REGEX.matcher(sequence);
				if (theMatcher.matches()) {
					final String voice = theMatcher.group(1);
					final String message = theMatcher.group(2);
					final TtsVoice theTts = Factories.TTSVOICE.findByCommandOrName(voice, 0);
					final Files theFile = TTSServices.getDefaultInstance().postTTS(message, false, true, theTts);

					if (theFile != null) {
						addAudio(theFile.getPath(), false, true);
					}
				}

			} else if (sequence.startsWith("END")) { // END -> addEndInteractiveMode
				addEndInteractive();
			} else if (sequence.startsWith("START_INTERACTIVE") && isSecure) { // START_INTERACTIVE url - > addStartInteractive ( que si
				// isSecure
				// )
				final String theUrl = sequence.replaceAll("START_INTERACTIVE ", net.violet.common.StringShop.EMPTY_STRING);
				addStartInteractive(theUrl);
			}
		}
	}
}


text:
"use strict";

exports.__esModule = true;
// istanbul ignore next

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

// istanbul ignore next

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var _repeating = require("repeating");

var _repeating2 = _interopRequireDefault(_repeating);

var _trimRight = require("trim-right");

var _trimRight2 = _interopRequireDefault(_trimRight);

var _lodashLangIsBoolean = require("lodash/lang/isBoolean");

var _lodashLangIsBoolean2 = _interopRequireDefault(_lodashLangIsBoolean);

var _lodashCollectionIncludes = require("lodash/collection/includes");

var _lodashCollectionIncludes2 = _interopRequireDefault(_lodashCollectionIncludes);

var _lodashLangIsNumber = require("lodash/lang/isNumber");

/**
 * Buffer for collecting generated output.
 */

var _lodashLangIsNumber2 = _interopRequireDefault(_lodashLangIsNumber);

var Buffer = (function () {
  function Buffer(position, format) {
    _classCallCheck(this, Buffer);

    this.parenPushNewlineState = null;

    this.position = position;
    this._indent = format.indent.base;
    this.format = format;
    this.buf = "";
  }

  /**
   * Get the current trimmed buffer.
   */

  Buffer.prototype.get = function get() {
    return _trimRight2["default"](this.buf);
  };

  /**
   * Get the current indent.
   */

  Buffer.prototype.getIndent = function getIndent() {
    if (this.format.compact || this.format.concise) {
      return "";
    } else {
      return _repeating2["default"](this.format.indent.style, this._indent);
    }
  };

  /**
   * Get the current indent size.
   */

  Buffer.prototype.indentSize = function indentSize() {
    return this.getIndent().length;
  };

  /**
   * Increment indent size.
   */

  Buffer.prototype.indent = function indent() {
    this._indent++;
  };

  /**
   * Decrement indent size.
   */

  Buffer.prototype.dedent = function dedent() {
    this._indent--;
  };

  /**
   * Add a semicolon to the buffer.
   */

  Buffer.prototype.semicolon = function semicolon() {
    this.push(";");
  };

  /**
   * Ensure last character is a semicolon.
   */

  Buffer.prototype.ensureSemicolon = function ensureSemicolon() {
    if (!this.isLast(";")) this.semicolon();
  };

  /**
   * Add a right brace to the buffer.
   */

  Buffer.prototype.rightBrace = function rightBrace() {
    this.newline(true);
    this.push("}");
  };

  /**
   * Add a keyword to the buffer.
   */

  Buffer.prototype.keyword = function keyword(name) {
    this.push(name);
    this.space();
  };

  /**
   * Add a space to the buffer unless it is compact (override with force).
   */

  Buffer.prototype.space = function space(force) {
    if (!force && this.format.compact) return;

    if (force || this.buf && !this.isLast(" ") && !this.isLast("\n")) {
      this.push(" ");
    }
  };

  /**
   * Remove the last character.
   */

  Buffer.prototype.removeLast = function removeLast(cha) {
    if (this.format.compact) return;
    if (!this.isLast(cha)) return;

    this.buf = this.buf.substr(0, this.buf.length - 1);
    this.position.unshift(cha);
  };

  /**
   * Set some state that will be modified if a newline has been inserted before any
   * non-space characters.
   *
   * This is to prevent breaking semantics for terminatorless separator nodes. eg:
   *
   *    return foo;
   *
   * returns `foo`. But if we do:
   *
   *   return
   *   foo;
   *
   *  `undefined` will be returned and not `foo` due to the terminator.
   */

  Buffer.prototype.startTerminatorless = function startTerminatorless() {
    return this.parenPushNewlineState = {
      printed: false
    };
  };

  /**
   * Print an ending parentheses if a starting one has been printed.
   */

  Buffer.prototype.endTerminatorless = function endTerminatorless(state) {
    if (state.printed) {
      this.dedent();
      this.newline();
      this.push(")");
    }
  };

  /**
   * Add a newline (or many newlines), maintaining formatting.
   * Strips multiple newlines if removeLast is true.
   */

  Buffer.prototype.newline = function newline(i, removeLast) {
    if (this.format.compact || this.format.retainLines) return;

    if (this.format.concise) {
      this.space();
      return;
    }

    removeLast = removeLast || false;

    if (_lodashLangIsNumber2["default"](i)) {
      i = Math.min(2, i);

      if (this.endsWith("{\n") || this.endsWith(":\n")) i--;
      if (i <= 0) return;

      while (i > 0) {
        this._newline(removeLast);
        i--;
      }
      return;
    }

    if (_lodashLangIsBoolean2["default"](i)) {
      removeLast = i;
    }

    this._newline(removeLast);
  };

  /**
   * Adds a newline unless there is already two previous newlines.
   */

  Buffer.prototype._newline = function _newline(removeLast) {
    // never allow more than two lines
    if (this.endsWith("\n\n")) return;

    // remove the last newline
    if (removeLast && this.isLast("\n")) this.removeLast("\n");

    this.removeLast(" ");
    this._removeSpacesAfterLastNewline();
    this._push("\n");
  };

  /**
   * If buffer ends with a newline and some spaces after it, trim those spaces.
   */

  Buffer.prototype._removeSpacesAfterLastNewline = function _removeSpacesAfterLastNewline() {
    var lastNewlineIndex = this.buf.lastIndexOf("\n");
    if (lastNewlineIndex === -1) {
      return;
    }

    var index = this.buf.length - 1;
    while (index > lastNewlineIndex) {
      if (this.buf[index] !== " ") {
        break;
      }

      index--;
    }

    if (index === lastNewlineIndex) {
      this.buf = this.buf.substring(0, index + 1);
    }
  };

  /**
   * Push a string to the buffer, maintaining indentation and newlines.
   */

  Buffer.prototype.push = function push(str, noIndent) {
    if (!this.format.compact && this._indent && !noIndent && str !== "\n") {
      // we have an indent level and we aren't pushing a newline
      var indent = this.getIndent();

      // replace all newlines with newlines with the indentation
      str = str.replace(/\n/g, "\n" + indent);

      // we've got a newline before us so prepend on the indentation
      if (this.isLast("\n")) this._push(indent);
    }

    this._push(str);
  };

  /**
   * Push a string to the buffer.
   */

  Buffer.prototype._push = function _push(str) {
    // see startTerminatorless() instance method
    var parenPushNewlineState = this.parenPushNewlineState;
    if (parenPushNewlineState) {
      for (var i = 0; i < str.length; i++) {
        var cha = str[i];

        // we can ignore spaces since they wont interupt a terminatorless separator
        if (cha === " ") continue;

        this.parenPushNewlineState = null;

        if (cha === "\n" || cha === "/") {
          // we're going to break this terminator expression so we need to add a parentheses
          this._push("(");
          this.indent();
          parenPushNewlineState.printed = true;
        }

        break;
      }
    }

    //
    this.position.push(str);
    this.buf += str;
  };

  /**
   * Test if the buffer ends with a string.
   */

  Buffer.prototype.endsWith = function endsWith(str) {
    var buf = arguments.length <= 1 || arguments[1] === undefined ? this.buf : arguments[1];

    if (str.length === 1) {
      return buf[buf.length - 1] === str;
    } else {
      return buf.slice(-str.length) === str;
    }
  };

  /**
   * Test if a character is last in the buffer.
   */

  Buffer.prototype.isLast = function isLast(cha) {
    if (this.format.compact) return false;

    var buf = this.buf;
    var last = buf[buf.length - 1];

    if (Array.isArray(cha)) {
      return _lodashCollectionIncludes2["default"](cha, last);
    } else {
      return cha === last;
    }
  };

  return Buffer;
})();

exports["default"] = Buffer;
module.exports = exports["default"];

redpajama_set_name: RedPajamaGithub


text:
import closestTr from '../../../common/closestTr';
import entries from '../../../common/entries';
import fromEntries from '../../../common/fromEntries';
import getTextTrim from '../../../common/getTextTrim';
import getCheckboxesArray from './getCheckboxesArray';
import getInv from './getInv';

let itemsprm = null;

function updateName(checkboxes, item) {
  if (item.item_id !== 13699) return item.item_name;
  const thisItem = checkboxes.find((cb) => cb.value === String(item.inv_id));
  if (!thisItem) return item.item_name;
  return getTextTrim(thisItem.parentNode.parentNode.children[2]);
}

async function updateNamesForComposedPots(checkboxes) {
  const inv = await getInv();
  if (!inv.items) return {};
  return fromEntries(entries(inv.items).map(([key, obj]) => [key, {
    ...obj,
    item_name: updateName(checkboxes, obj),
  }]));
}

function getItemsFromInventory(checkboxes) {
  if (!itemsprm) itemsprm = updateNamesForComposedPots(checkboxes);
  return itemsprm;
}

export default async function getItems() {
  const checkboxes = getCheckboxesArray();
  if (!checkboxes.length) return [];
  const items = await getItemsFromInventory(checkboxes);
  return checkboxes
    .map((cb) => [
      closestTr(cb).cells[2],
      items[cb.value],
    ])
    .filter(([, invItem]) => invItem);
}


text:
// MESSAGE HIL_OPTICAL_FLOW PACKING

#define MAVLINK_MSG_ID_HIL_OPTICAL_FLOW 114

typedef struct __mavlink_hil_optical_flow_t
{
 uint64_t time_usec; /*< Timestamp (microseconds, synced to UNIX time or since system boot)*/
 uint32_t integration_time_us; /*< Integration time in microseconds. Divide integrated_x and integrated_y by the integration time to obtain average flow. The integration time also indicates the.*/
 float integrated_x; /*< Flow in radians around X axis (Sensor RH rotation about the X axis induces a positive flow. Sensor linear motion along the positive Y axis induces a negative flow.)*/
 float integrated_y; /*< Flow in radians around Y axis (Sensor RH rotation about the Y axis induces a positive flow. Sensor linear motion along the positive X axis induces a positive flow.)*/
 float integrated_xgyro; /*< RH rotation around X axis (rad)*/
 float integrated_ygyro; /*< RH rotation around Y axis (rad)*/
 float integrated_zgyro; /*< RH rotation around Z axis (rad)*/
 uint32_t time_delta_distance_us; /*< Time in microseconds since the distance was sampled.*/
 float distance; /*< Distance to the center of the flow field in meters. Positive value (including zero): distance known. Negative value: Unknown distance.*/
 int16_t temperature; /*< Temperature * 100 in centi-degrees Celsius*/
 uint8_t sensor_id; /*< Sensor ID*/
 uint8_t quality; /*< Optical flow quality / confidence. 0: no valid flow, 255: maximum quality*/
} mavlink_hil_optical_flow_t;

#define MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_LEN 44
#define MAVLINK_MSG_ID_114_LEN 44

#define MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_CRC 237
#define MAVLINK_MSG_ID_114_CRC 237

#define MAVLINK_MESSAGE_INFO_HIL_OPTICAL_FLOW { \
	"HIL_OPTICAL_FLOW", \
	12, \
	{  { "time_usec", NULL, MAVLINK_TYPE_UINT64_T, 0, 0, offsetof(mavlink_hil_optical_flow_t, time_usec) }, \
         { "integration_time_us", NULL, MAVLINK_TYPE_UINT32_T, 0, 8, offsetof(mavlink_hil_optical_flow_t, integration_time_us) }, \
         { "integrated_x", NULL, MAVLINK_TYPE_FLOAT, 0, 12, offsetof(mavlink_hil_optical_flow_t, integrated_x) }, \
         { "integrated_y", NULL, MAVLINK_TYPE_FLOAT, 0, 16, offsetof(mavlink_hil_optical_flow_t, integrated_y) }, \
         { "integrated_xgyro", NULL, MAVLINK_TYPE_FLOAT, 0, 20, offsetof(mavlink_hil_optical_flow_t, integrated_xgyro) }, \
         { "integrated_ygyro", NULL, MAVLINK_TYPE_FLOAT, 0, 24, offsetof(mavlink_hil_optical_flow_t, integrated_ygyro) }, \
         { "integrated_zgyro", NULL, MAVLINK_TYPE_FLOAT, 0, 28, offsetof(mavlink_hil_optical_flow_t, integrated_zgyro) }, \
         { "time_delta_distance_us", NULL, MAVLINK_TYPE_UINT32_T, 0, 32, offsetof(mavlink_hil_optical_flow_t, time_delta_distance_us) }, \
         { "distance", NULL, MAVLINK_TYPE_FLOAT, 0, 36, offsetof(mavlink_hil_optical_flow_t, distance) }, \
         { "temperature", NULL, MAVLINK_TYPE_INT16_T, 0, 40, offsetof(mavlink_hil_optical_flow_t, temperature) }, \
         { "sensor_id", NULL, MAVLINK_TYPE_UINT8_T, 0, 42, offsetof(mavlink_hil_optical_flow_t, sensor_id) }, \
         { "quality", NULL, MAVLINK_TYPE_UINT8_T, 0, 43, offsetof(mavlink_hil_optical_flow_t, quality) }, \
         } \
}

/**
 * @brief Pack a hil_optical_flow message
 * @param system_id ID of this system
 * @param component_id ID of this component (e.g. 200 for IMU)
 * @param msg The MAVLink message to compress the data into
 *
 * @param time_usec Timestamp (microseconds, synced to UNIX time or since system boot)
 * @param sensor_id Sensor ID
 * @param integration_time_us Integration time in microseconds. Divide integrated_x and integrated_y by the integration time to obtain average flow. The integration time also indicates the.
 * @param integrated_x Flow in radians around X axis (Sensor RH rotation about the X axis induces a positive flow. Sensor linear motion along the positive Y axis induces a negative flow.)
 * @param integrated_y Flow in radians around Y axis (Sensor RH rotation about the Y axis induces a positive flow. Sensor linear motion along the positive X axis induces a positive flow.)
 * @param integrated_xgyro RH rotation around X axis (rad)
 * @param integrated_ygyro RH rotation around Y axis (rad)
 * @param integrated_zgyro RH rotation around Z axis (rad)
 * @param temperature Temperature * 100 in centi-degrees Celsius
 * @param quality Optical flow quality / confidence. 0: no valid flow, 255: maximum quality
 * @param time_delta_distance_us Time in microseconds since the distance was sampled.
 * @param distance Distance to the center of the flow field in meters. Positive value (including zero): distance known. Negative value: Unknown distance.
 * @return length of the message in bytes (excluding serial stream start sign)
 */
static inline uint16_t mavlink_msg_hil_optical_flow_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg,
						       uint64_t time_usec, uint8_t sensor_id, uint32_t integration_time_us, float integrated_x, float integrated_y, float integrated_xgyro, float integrated_ygyro, float integrated_zgyro, int16_t temperature, uint8_t quality, uint32_t time_delta_distance_us, float distance)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
	char buf[MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_LEN];
	_mav_put_uint64_t(buf, 0, time_usec);
	_mav_put_uint32_t(buf, 8, integration_time_us);
	_mav_put_float(buf, 12, integrated_x);
	_mav_put_float(buf, 16, integrated_y);
	_mav_put_float(buf, 20, integrated_xgyro);
	_mav_put_float(buf, 24, integrated_ygyro);
	_mav_put_float(buf, 28, integrated_zgyro);
	_mav_put_uint32_t(buf, 32, time_delta_distance_us);
	_mav_put_float(buf, 36, distance);
	_mav_put_int16_t(buf, 40, temperature);
	_mav_put_uint8_t(buf, 42, sensor_id);
	_mav_put_uint8_t(buf, 43, quality);

        memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_LEN);
#else
	mavlink_hil_optical_flow_t packet;
	packet.time_usec = time_usec;
	packet.integration_time_us = integration_time_us;
	packet.integrated_x = integrated_x;
	packet.integrated_y = integrated_y;
	packet.integrated_xgyro = integrated_xgyro;
	packet.integrated_ygyro = integrated_ygyro;
	packet.integrated_zgyro = integrated_zgyro;
	packet.time_delta_distance_us = time_delta_distance_us;
	packet.distance = distance;
	packet.temperature = temperature;
	packet.sensor_id = sensor_id;
	packet.quality = quality;

        memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_LEN);
#endif

	msg->msgid = MAVLINK_MSG_ID_HIL_OPTICAL_FLOW;
#if MAVLINK_CRC_EXTRA
    return mavlink_finalize_message(msg, system_id, component_id, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_LEN, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_CRC);
#else
    return mavlink_finalize_message(msg, system_id, component_id, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_LEN);
#endif
}

/**
 * @brief Pack a hil_optical_flow message on a channel
 * @param system_id ID of this system
 * @param component_id ID of this component (e.g. 200 for IMU)
 * @param chan The MAVLink channel this message will be sent over
 * @param msg The MAVLink message to compress the data into
 * @param time_usec Timestamp (microseconds, synced to UNIX time or since system boot)
 * @param sensor_id Sensor ID
 * @param integration_time_us Integration time in microseconds. Divide integrated_x and integrated_y by the integration time to obtain average flow. The integration time also indicates the.
 * @param integrated_x Flow in radians around X axis (Sensor RH rotation about the X axis induces a positive flow. Sensor linear motion along the positive Y axis induces a negative flow.)
 * @param integrated_y Flow in radians around Y axis (Sensor RH rotation about the Y axis induces a positive flow. Sensor linear motion along the positive X axis induces a positive flow.)
 * @param integrated_xgyro RH rotation around X axis (rad)
 * @param integrated_ygyro RH rotation around Y axis (rad)
 * @param integrated_zgyro RH rotation around Z axis (rad)
 * @param temperature Temperature * 100 in centi-degrees Celsius
 * @param quality Optical flow quality / confidence. 0: no valid flow, 255: maximum quality
 * @param time_delta_distance_us Time in microseconds since the distance was sampled.
 * @param distance Distance to the center of the flow field in meters. Positive value (including zero): distance known. Negative value: Unknown distance.
 * @return length of the message in bytes (excluding serial stream start sign)
 */
static inline uint16_t mavlink_msg_hil_optical_flow_pack_chan(uint8_t system_id, uint8_t component_id, uint8_t chan,
							   mavlink_message_t* msg,
						           uint64_t time_usec,uint8_t sensor_id,uint32_t integration_time_us,float integrated_x,float integrated_y,float integrated_xgyro,float integrated_ygyro,float integrated_zgyro,int16_t temperature,uint8_t quality,uint32_t time_delta_distance_us,float distance)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
	char buf[MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_LEN];
	_mav_put_uint64_t(buf, 0, time_usec);
	_mav_put_uint32_t(buf, 8, integration_time_us);
	_mav_put_float(buf, 12, integrated_x);
	_mav_put_float(buf, 16, integrated_y);
	_mav_put_float(buf, 20, integrated_xgyro);
	_mav_put_float(buf, 24, integrated_ygyro);
	_mav_put_float(buf, 28, integrated_zgyro);
	_mav_put_uint32_t(buf, 32, time_delta_distance_us);
	_mav_put_float(buf, 36, distance);
	_mav_put_int16_t(buf, 40, temperature);
	_mav_put_uint8_t(buf, 42, sensor_id);
	_mav_put_uint8_t(buf, 43, quality);

        memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_LEN);
#else
	mavlink_hil_optical_flow_t packet;
	packet.time_usec = time_usec;
	packet.integration_time_us = integration_time_us;
	packet.integrated_x = integrated_x;
	packet.integrated_y = integrated_y;
	packet.integrated_xgyro = integrated_xgyro;
	packet.integrated_ygyro = integrated_ygyro;
	packet.integrated_zgyro = integrated_zgyro;
	packet.time_delta_distance_us = time_delta_distance_us;
	packet.distance = distance;
	packet.temperature = temperature;
	packet.sensor_id = sensor_id;
	packet.quality = quality;

        memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_LEN);
#endif

	msg->msgid = MAVLINK_MSG_ID_HIL_OPTICAL_FLOW;
#if MAVLINK_CRC_EXTRA
    return mavlink_finalize_message_chan(msg, system_id, component_id, chan, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_LEN, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_CRC);
#else
    return mavlink_finalize_message_chan(msg, system_id, component_id, chan, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_LEN);
#endif
}

/**
 * @brief Encode a hil_optical_flow struct
 *
 * @param system_id ID of this system
 * @param component_id ID of this component (e.g. 200 for IMU)
 * @param msg The MAVLink message to compress the data into
 * @param hil_optical_flow C-struct to read the message contents from
 */
static inline uint16_t mavlink_msg_hil_optical_flow_encode(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg, const mavlink_hil_optical_flow_t* hil_optical_flow)
{
	return mavlink_msg_hil_optical_flow_pack(system_id, component_id, msg, hil_optical_flow->time_usec, hil_optical_flow->sensor_id, hil_optical_flow->integration_time_us, hil_optical_flow->integrated_x, hil_optical_flow->integrated_y, hil_optical_flow->integrated_xgyro, hil_optical_flow->integrated_ygyro, hil_optical_flow->integrated_zgyro, hil_optical_flow->temperature, hil_optical_flow->quality, hil_optical_flow->time_delta_distance_us, hil_optical_flow->distance);
}

/**
 * @brief Encode a hil_optical_flow struct on a channel
 *
 * @param system_id ID of this system
 * @param component_id ID of this component (e.g. 200 for IMU)
 * @param chan The MAVLink channel this message will be sent over
 * @param msg The MAVLink message to compress the data into
 * @param hil_optical_flow C-struct to read the message contents from
 */
static inline uint16_t mavlink_msg_hil_optical_flow_encode_chan(uint8_t system_id, uint8_t component_id, uint8_t chan, mavlink_message_t* msg, const mavlink_hil_optical_flow_t* hil_optical_flow)
{
	return mavlink_msg_hil_optical_flow_pack_chan(system_id, component_id, chan, msg, hil_optical_flow->time_usec, hil_optical_flow->sensor_id, hil_optical_flow->integration_time_us, hil_optical_flow->integrated_x, hil_optical_flow->integrated_y, hil_optical_flow->integrated_xgyro, hil_optical_flow->integrated_ygyro, hil_optical_flow->integrated_zgyro, hil_optical_flow->temperature, hil_optical_flow->quality, hil_optical_flow->time_delta_distance_us, hil_optical_flow->distance);
}

/**
 * @brief Send a hil_optical_flow message
 * @param chan MAVLink channel to send the message
 *
 * @param time_usec Timestamp (microseconds, synced to UNIX time or since system boot)
 * @param sensor_id Sensor ID
 * @param integration_time_us Integration time in microseconds. Divide integrated_x and integrated_y by the integration time to obtain average flow. The integration time also indicates the.
 * @param integrated_x Flow in radians around X axis (Sensor RH rotation about the X axis induces a positive flow. Sensor linear motion along the positive Y axis induces a negative flow.)
 * @param integrated_y Flow in radians around Y axis (Sensor RH rotation about the Y axis induces a positive flow. Sensor linear motion along the positive X axis induces a positive flow.)
 * @param integrated_xgyro RH rotation around X axis (rad)
 * @param integrated_ygyro RH rotation around Y axis (rad)
 * @param integrated_zgyro RH rotation around Z axis (rad)
 * @param temperature Temperature * 100 in centi-degrees Celsius
 * @param quality Optical flow quality / confidence. 0: no valid flow, 255: maximum quality
 * @param time_delta_distance_us Time in microseconds since the distance was sampled.
 * @param distance Distance to the center of the flow field in meters. Positive value (including zero): distance known. Negative value: Unknown distance.
 */
#ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS

static inline void mavlink_msg_hil_optical_flow_send(mavlink_channel_t chan, uint64_t time_usec, uint8_t sensor_id, uint32_t integration_time_us, float integrated_x, float integrated_y, float integrated_xgyro, float integrated_ygyro, float integrated_zgyro, int16_t temperature, uint8_t quality, uint32_t time_delta_distance_us, float distance)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
	char buf[MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_LEN];
	_mav_put_uint64_t(buf, 0, time_usec);
	_mav_put_uint32_t(buf, 8, integration_time_us);
	_mav_put_float(buf, 12, integrated_x);
	_mav_put_float(buf, 16, integrated_y);
	_mav_put_float(buf, 20, integrated_xgyro);
	_mav_put_float(buf, 24, integrated_ygyro);
	_mav_put_float(buf, 28, integrated_zgyro);
	_mav_put_uint32_t(buf, 32, time_delta_distance_us);
	_mav_put_float(buf, 36, distance);
	_mav_put_int16_t(buf, 40, temperature);
	_mav_put_uint8_t(buf, 42, sensor_id);
	_mav_put_uint8_t(buf, 43, quality);

#if MAVLINK_CRC_EXTRA
    _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW, buf, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_LEN, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_CRC);
#else
    _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW, buf, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_LEN);
#endif
#else
	mavlink_hil_optical_flow_t packet;
	packet.time_usec = time_usec;
	packet.integration_time_us = integration_time_us;
	packet.integrated_x = integrated_x;
	packet.integrated_y = integrated_y;
	packet.integrated_xgyro = integrated_xgyro;
	packet.integrated_ygyro = integrated_ygyro;
	packet.integrated_zgyro = integrated_zgyro;
	packet.time_delta_distance_us = time_delta_distance_us;
	packet.distance = distance;
	packet.temperature = temperature;
	packet.sensor_id = sensor_id;
	packet.quality = quality;

#if MAVLINK_CRC_EXTRA
    _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW, (const char *)&packet, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_LEN, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_CRC);
#else
    _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW, (const char *)&packet, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_LEN);
#endif
#endif
}

#if MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_LEN <= MAVLINK_MAX_PAYLOAD_LEN
/*
  This varient of _send() can be used to save stack space by re-using
  memory from the receive buffer.  The caller provides a
  mavlink_message_t which is the size of a full mavlink message. This
  is usually the receive buffer for the channel, and allows a reply to an
  incoming message with minimum stack space usage.
 */
static inline void mavlink_msg_hil_optical_flow_send_buf(mavlink_message_t *msgbuf, mavlink_channel_t chan,  uint64_t time_usec, uint8_t sensor_id, uint32_t integration_time_us, float integrated_x, float integrated_y, float integrated_xgyro, float integrated_ygyro, float integrated_zgyro, int16_t temperature, uint8_t quality, uint32_t time_delta_distance_us, float distance)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
	char *buf = (char *)msgbuf;
	_mav_put_uint64_t(buf, 0, time_usec);
	_mav_put_uint32_t(buf, 8, integration_time_us);
	_mav_put_float(buf, 12, integrated_x);
	_mav_put_float(buf, 16, integrated_y);
	_mav_put_float(buf, 20, integrated_xgyro);
	_mav_put_float(buf, 24, integrated_ygyro);
	_mav_put_float(buf, 28, integrated_zgyro);
	_mav_put_uint32_t(buf, 32, time_delta_distance_us);
	_mav_put_float(buf, 36, distance);
	_mav_put_int16_t(buf, 40, temperature);
	_mav_put_uint8_t(buf, 42, sensor_id);
	_mav_put_uint8_t(buf, 43, quality);

#if MAVLINK_CRC_EXTRA
    _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW, buf, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_LEN, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_CRC);
#else
    _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW, buf, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_LEN);
#endif
#else
	mavlink_hil_optical_flow_t *packet = (mavlink_hil_optical_flow_t *)msgbuf;
	packet->time_usec = time_usec;
	packet->integration_time_us = integration_time_us;
	packet->integrated_x = integrated_x;
	packet->integrated_y = integrated_y;
	packet->integrated_xgyro = integrated_xgyro;
	packet->integrated_ygyro = integrated_ygyro;
	packet->integrated_zgyro = integrated_zgyro;
	packet->time_delta_distance_us = time_delta_distance_us;
	packet->distance = distance;
	packet->temperature = temperature;
	packet->sensor_id = sensor_id;
	packet->quality = quality;

#if MAVLINK_CRC_EXTRA
    _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW, (const char *)packet, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_LEN, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_CRC);
#else
    _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW, (const char *)packet, MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_LEN);
#endif
#endif
}
#endif

#endif

// MESSAGE HIL_OPTICAL_FLOW UNPACKING

/**
 * @brief Get field time_usec from hil_optical_flow message
 *
 * @return Timestamp (microseconds, synced to UNIX time or since system boot)
 */
static inline uint64_t mavlink_msg_hil_optical_flow_get_time_usec(const mavlink_message_t* msg)
{
	return _MAV_RETURN_uint64_t(msg,  0);
}

/**
 * @brief Get field sensor_id from hil_optical_flow message
 *
 * @return Sensor ID
 */
static inline uint8_t mavlink_msg_hil_optical_flow_get_sensor_id(const mavlink_message_t* msg)
{
	return _MAV_RETURN_uint8_t(msg,  42);
}

/**
 * @brief Get field integration_time_us from hil_optical_flow message
 *
 * @return Integration time in microseconds. Divide integrated_x and integrated_y by the integration time to obtain average flow. The integration time also indicates the.
 */
static inline uint32_t mavlink_msg_hil_optical_flow_get_integration_time_us(const mavlink_message_t* msg)
{
	return _MAV_RETURN_uint32_t(msg,  8);
}

/**
 * @brief Get field integrated_x from hil_optical_flow message
 *
 * @return Flow in radians around X axis (Sensor RH rotation about the X axis induces a positive flow. Sensor linear motion along the positive Y axis induces a negative flow.)
 */
static inline float mavlink_msg_hil_optical_flow_get_integrated_x(const mavlink_message_t* msg)
{
	return _MAV_RETURN_float(msg,  12);
}

/**
 * @brief Get field integrated_y from hil_optical_flow message
 *
 * @return Flow in radians around Y axis (Sensor RH rotation about the Y axis induces a positive flow. Sensor linear motion along the positive X axis induces a positive flow.)
 */
static inline float mavlink_msg_hil_optical_flow_get_integrated_y(const mavlink_message_t* msg)
{
	return _MAV_RETURN_float(msg,  16);
}

/**
 * @brief Get field integrated_xgyro from hil_optical_flow message
 *
 * @return RH rotation around X axis (rad)
 */
static inline float mavlink_msg_hil_optical_flow_get_integrated_xgyro(const mavlink_message_t* msg)
{
	return _MAV_RETURN_float(msg,  20);
}

/**
 * @brief Get field integrated_ygyro from hil_optical_flow message
 *
 * @return RH rotation around Y axis (rad)
 */
static inline float mavlink_msg_hil_optical_flow_get_integrated_ygyro(const mavlink_message_t* msg)
{
	return _MAV_RETURN_float(msg,  24);
}

/**
 * @brief Get field integrated_zgyro from hil_optical_flow message
 *
 * @return RH rotation around Z axis (rad)
 */
static inline float mavlink_msg_hil_optical_flow_get_integrated_zgyro(const mavlink_message_t* msg)
{
	return _MAV_RETURN_float(msg,  28);
}

/**
 * @brief Get field temperature from hil_optical_flow message
 *
 * @return Temperature * 100 in centi-degrees Celsius
 */
static inline int16_t mavlink_msg_hil_optical_flow_get_temperature(const mavlink_message_t* msg)
{
	return _MAV_RETURN_int16_t(msg,  40);
}

/**
 * @brief Get field quality from hil_optical_flow message
 *
 * @return Optical flow quality / confidence. 0: no valid flow, 255: maximum quality
 */
static inline uint8_t mavlink_msg_hil_optical_flow_get_quality(const mavlink_message_t* msg)
{
	return _MAV_RETURN_uint8_t(msg,  43);
}

/**
 * @brief Get field time_delta_distance_us from hil_optical_flow message
 *
 * @return Time in microseconds since the distance was sampled.
 */
static inline uint32_t mavlink_msg_hil_optical_flow_get_time_delta_distance_us(const mavlink_message_t* msg)
{
	return _MAV_RETURN_uint32_t(msg,  32);
}

/**
 * @brief Get field distance from hil_optical_flow message
 *
 * @return Distance to the center of the flow field in meters. Positive value (including zero): distance known. Negative value: Unknown distance.
 */
static inline float mavlink_msg_hil_optical_flow_get_distance(const mavlink_message_t* msg)
{
	return _MAV_RETURN_float(msg,  36);
}

/**
 * @brief Decode a hil_optical_flow message into a struct
 *
 * @param msg The message to decode
 * @param hil_optical_flow C-struct to decode the message contents into
 */
static inline void mavlink_msg_hil_optical_flow_decode(const mavlink_message_t* msg, mavlink_hil_optical_flow_t* hil_optical_flow)
{
#if MAVLINK_NEED_BYTE_SWAP
	hil_optical_flow->time_usec = mavlink_msg_hil_optical_flow_get_time_usec(msg);
	hil_optical_flow->integration_time_us = mavlink_msg_hil_optical_flow_get_integration_time_us(msg);
	hil_optical_flow->integrated_x = mavlink_msg_hil_optical_flow_get_integrated_x(msg);
	hil_optical_flow->integrated_y = mavlink_msg_hil_optical_flow_get_integrated_y(msg);
	hil_optical_flow->integrated_xgyro = mavlink_msg_hil_optical_flow_get_integrated_xgyro(msg);
	hil_optical_flow->integrated_ygyro = mavlink_msg_hil_optical_flow_get_integrated_ygyro(msg);
	hil_optical_flow->integrated_zgyro = mavlink_msg_hil_optical_flow_get_integrated_zgyro(msg);
	hil_optical_flow->time_delta_distance_us = mavlink_msg_hil_optical_flow_get_time_delta_distance_us(msg);
	hil_optical_flow->distance = mavlink_msg_hil_optical_flow_get_distance(msg);
	hil_optical_flow->temperature = mavlink_msg_hil_optical_flow_get_temperature(msg);
	hil_optical_flow->sensor_id = mavlink_msg_hil_optical_flow_get_sensor_id(msg);
	hil_optical_flow->quality = mavlink_msg_hil_optical_flow_get_quality(msg);
#else
	memcpy(hil_optical_flow, _MAV_PAYLOAD(msg), MAVLINK_MSG_ID_HIL_OPTICAL_FLOW_LEN);
#endif
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace MuseoCliente.Connection.Objects
{
    public class Vitrina : ResourceObject<Vitrina>
    {
        [JsonProperty]
        public String numero { get; set; }
        [JsonProperty]
        public int sala { get; set; }

        public Vitrina()
            : base( "/api/v1/vitrina/" )
        {
        }

        public void guardar()
        {
            try
            {
                this.Create();
            }
            catch( Exception e )
            {
                if( e.Source != null )
                {
                    Error.ingresarError( 3, "No se ha guardado la Informacion en la base de datos " + e.Message );
                }
            }
        }

        public void modificar()
        {
            try
            {
                this.Save( this.id.ToString() );
            }
            catch( Exception e )
            {
                if( e.Source != null )
                {
                    Error.ingresarError( 4, "No se ha modificado la Informacion en la base de datos" );
                }
            }
        }

        /*FUNCIONES ESCENCIALES*/

        public ArrayList regresarTodos()
        {
            List<Vitrina> lista = null;
            try
            {
                lista = this.GetAsCollection();
                if( lista == null )
                    Error.ingresarError( 2, "No se econtro ninguna Ficha registrada" );
            }
            catch( Exception e )
            {
                Error.ingresarError( 5, "Ha ocurrido un Error en la Coneccion Porfavor Verifique su conecciona a Internet" );
            }
            if( lista == null )
            {
                Error.ingresarError( 2, "No existen en la Base de Datos" );
                return null;
            }
            return new ArrayList( lista );
        }

        public void regresarObjeto( int id )
        {
            try
            {
                this.resource_uri = this.resource_uri + id + "/";
                Vitrina vitrina = this.Get();
                if( vitrina == null )
                {
                    Error.ingresarError( 2, "Este Objeto no existe porfavor, ingresar correcta la busqueda" );
                    return;
                }
                this.id = vitrina.id;
                this.numero = vitrina.numero;
                this.sala = vitrina.sala;
                this.resource_uri = vitrina.resource_uri;
            }
            catch( Exception e )
            {
                Error.ingresarError( 5, "Ha ocurrido un Error en la Coneccion Porfavor Verifique su conecciona a Internet" );
            }
        }

        //Funcion hecha por Miguel ... NO BORRAR!!!!!!!!
        public ArrayList regresarPorSala(int idS)
        {
            List<Vitrina> vitrinas = null;
            try
            {
                Vitrina clas = new Vitrina();
                string consulta = "?sala=" + idS;
                vitrinas = clas.GetAsCollection(consulta);
                if (vitrinas == null)
                    Error.ingresarError(2, "No se encontraron vitrinas para esta sala");
            }
            catch (Exception e)
            {
                Error.ingresarError(5, "Ha ocurrido un Error en la Coneccion Porfavor Verifique su conecciona a Internet");
            }
            if (vitrinas == null)
            {
                Error.ingresarError(2, "No se encontro la busqueda");
                return null;
            }

            return new ArrayList(vitrinas);
        }

        public void regresarObjeto()
        {
            regresarObjeto( this.id );
        }

        /*CONSULTAS*/

        public ArrayList consultarNumero( string numero )
        {
            List<Vitrina> listaNueva = null;
            try
            {
                listaNueva = this.GetAsCollection( "?numero=" + numero );
                if( listaNueva == null )
                    Error.ingresarError( 2, "no se encontraron coincidencias con el numero: " + numero );
            }
            catch( Exception e )
            {
                Error.ingresarError( 2, "no se encontraron coincidencias con el numero: " + numero );
            }
            if( listaNueva == null )
            {
                Error.ingresarError( 2, "No existen Vitrina del numero: " + numero );
                return null;
            }
            return new ArrayList( listaNueva );
        }

        /*CONSULTAR PADRE*/

        public Sala consultarSala()
        {
            Sala clase = new Sala();
            try
            {
                clase.regresarObjeto( this.sala );
            }
            catch( Exception e )
            {
                Error.ingresarError( 2, "no se encontraron coincidencias con sala: " + sala );
            }
            return ( clase );
        }

        /*CONSULTAR HIJOS*/

        public ArrayList regresarTraslados()
        {
            List<Traslado> listaNueva = null;
            try
            {
                Traslado clase = new Traslado();
                string consulta = clase.resource_uri + "?vitrina=" + this.id.ToString();
                listaNueva = clase.GetAsCollection( consulta );
                if( listaNueva == null )
                    Error.ingresarError( 2, "No se encontro ningun Trasladoa por el momento" );
            }
            catch( Exception e )
            {
                Error.ingresarError( 5, "Ha ocurrido un Error en la Coneccion Porfavor Verifique su conecciona a Internet" );
            }
            if( listaNueva == null )
            {
                Error.ingresarError( 2, "No existen Traslados de Vitrina: " + this.numero );
                return null;
            }
            return new ArrayList( listaNueva );
        }

        public void eliminar()
        {
            try
            {
                if (this.id == 0)
                {
                    Error.ingresarError(2, "No existe la Vitrina en la base de datos para poder Eliminarla ");
                    return;
                }
                this.del();
            }
            catch (Exception e)
            {
                Error.ingresarError(2, "No se ha eliminado la Vitrina Seleccionada " + e.Message);
            }
        }
    }
}


text:
package org.openqa.grid.e2e.node;

public class SmokeTest {

//  private Hub hub;
//
//  @Before
//  public void prepare() {
//    hub = GridTestHelper.prepareTestGrid(1);
//  }
//
//  @Test
//  public void browserOnWebDriver() {
//    WebDriver driver = null;
//    try {
//      DesiredCapabilities caps = GridTestHelper.getDefaultBrowserCapability();
//      driver = new RemoteWebDriver(hub.getWebDriverHubRequestURL(), caps);
//      driver.get(hub.getConsoleURL().toString());
//      assertEquals(driver.getTitle(), "Grid Console");
//    } finally {
//      if (driver != null) {
//        driver.quit();
//      }
//    }
//  }
//
//  @After
//  public void stop() {
//    hub.stop();
//  }
//
}


text:
package com.fincatto.documentofiscal.nfe310.classes.nota;

import com.fincatto.documentofiscal.DFBase;
import com.fincatto.documentofiscal.nfe310.classes.NFEndereco;
import com.fincatto.documentofiscal.nfe310.classes.NFRegimeTributario;
import com.fincatto.documentofiscal.validadores.DFStringValidador;
import org.simpleframework.xml.Element;

public class NFNotaInfoEmitente extends DFBase {
    private static final long serialVersionUID = -2236869565066526162L;

    @Element(name = "CNPJ", required = false)
    private String cnpj;

    @Element(name = "CPF", required = false)
    private String cpf;

    @Element(name = "xNome")
    private String razaoSocial;

    @Element(name = "xFant", required = false)
    private String nomeFantasia;

    @Element(name = "enderEmit")
    private NFEndereco endereco;

    @Element(name = "IE")
    private String inscricaoEstadual;

    @Element(name = "IEST", required = false)
    private String inscricaoEstadualSubstituicaoTributaria;

    @Element(name = "IM", required = false)
    private String inscricaoMunicipal;

    @Element(name = "CNAE", required = false)
    private String classificacaoNacionalAtividadesEconomicas;

    @Element(name = "CRT")
    private NFRegimeTributario regimeTributario;

    public void setCnpj(final String cnpj) {
        if (this.cpf != null && cnpj != null) {
            throw new IllegalStateException("Nao pode setar CNPJ caso CPF esteja setado");
        }
        DFStringValidador.cnpj(cnpj);
        this.cnpj = cnpj;
    }

    public void setCpf(final String cpf) {
        if (this.cnpj != null && cpf != null) {
            throw new IllegalStateException("Nao pode setar CPF caso CNPJ esteja setado");
        }
        DFStringValidador.cpf(cpf);
        this.cpf = cpf;
    }

    public void setRazaoSocial(final String razaoSocial) {
        DFStringValidador.tamanho60(razaoSocial, "Razao Social Emitente");
        this.razaoSocial = razaoSocial;
    }

    public void setNomeFantasia(final String nomeFantasia) {
        DFStringValidador.tamanho60(nomeFantasia, "Nome Fantasia Emitente");
        this.nomeFantasia = nomeFantasia;
    }

    public void setEndereco(final NFEndereco endereco) {
        this.endereco = endereco;
    }

    public void setInscricaoEstadual(final String inscricaoEstadual) {
        DFStringValidador.inscricaoEstadual(inscricaoEstadual);
        this.inscricaoEstadual = inscricaoEstadual;
    }

    public void setInscricaoEstadualSubstituicaoTributaria(final String inscricaoEstadualSubstituicaoTributaria) {
        DFStringValidador.inscricaoEstadualSemIsencao(inscricaoEstadualSubstituicaoTributaria);
        this.inscricaoEstadualSubstituicaoTributaria = inscricaoEstadualSubstituicaoTributaria;
    }

    public void setInscricaoMunicipal(final String inscricaoMunicipal) {
        DFStringValidador.tamanho15(inscricaoMunicipal, "IM Emitente");
        this.inscricaoMunicipal = inscricaoMunicipal;
    }

    public void setClassificacaoNacionalAtividadesEconomicas(final String classificacaoNacionalAtividadesEconomicas) {
        DFStringValidador.exatamente7N(classificacaoNacionalAtividadesEconomicas, "CNAE Emitente");
        this.classificacaoNacionalAtividadesEconomicas = classificacaoNacionalAtividadesEconomicas;
    }

    public void setRegimeTributario(final NFRegimeTributario regimeTributario) {
        this.regimeTributario = regimeTributario;
    }

    public String getCnpj() {
        return this.cnpj;
    }

    public String getCpf() {
        return this.cpf;
    }

    public String getRazaoSocial() {
        return this.razaoSocial;
    }

    public String getNomeFantasia() {
        return this.nomeFantasia;
    }

    public NFEndereco getEndereco() {
        return this.endereco;
    }

    public String getInscricaoEstadual() {
        return this.inscricaoEstadual;
    }

    public String getInscricaoEstadualSubstituicaoTributaria() {
        return this.inscricaoEstadualSubstituicaoTributaria;
    }

    public String getInscricaoMunicipal() {
        return this.inscricaoMunicipal;
    }

    public String getClassificacaoNacionalAtividadesEconomicas() {
        return this.classificacaoNacionalAtividadesEconomicas;
    }

    public NFRegimeTributario getRegimeTributario() {
        return this.regimeTributario;
    }
}


text:
#ifndef itkVotingBinaryIterativeHoleFillingImageFilter_h
#define itkVotingBinaryIterativeHoleFillingImageFilter_h

#include "itkVotingBinaryHoleFillingImageFilter.h"

namespace itk
{
/**
 * \class VotingBinaryIterativeHoleFillingImageFilter
 * \brief Fills in holes and cavities by iteratively applying a voting operation.
 *
 * This filter uses internally the VotingBinaryHoleFillingImageFilter, and runs
 * it iteratively until no pixels are being changed or until it reaches the
 * maximum number of iterations. The purpose of the filter is to fill in holes
 * of medium size (tens of pixels in radius). In principle the number of
 * iterations is related to the size of the holes to be filled in. The larger
 * the holes, the more iteration must be run with this filter in order to fill
 * in the full hole. The size of the neighborhood is also related to the
 * curvature of the hole borders and therefore the hole size. Note that as a
 * collateral effect this filter may also fill in cavities in the external side
 * of structures.
 *
 * This filter is templated over a single image type because the output image
 * type must be the same as the input image type. This is required in order to
 * make the iterations possible, since the output image of one iteration is
 * taken as the input image for the next iteration.
 *
 * \sa Image
 * \sa VotingBinaryImageFilter
 * \sa VotingBinaryHoleFillingImageFilter
 * \sa Neighborhood
 * \sa NeighborhoodOperator
 * \sa NeighborhoodIterator
 *
 * \ingroup IntensityImageFilters
 * \ingroup ITKLabelVoting
 */
template <typename TImage>
class ITK_TEMPLATE_EXPORT VotingBinaryIterativeHoleFillingImageFilter : public ImageToImageFilter<TImage, TImage>
{
public:
  ITK_DISALLOW_COPY_AND_MOVE(VotingBinaryIterativeHoleFillingImageFilter);

  /** Convenient type alias for simplifying declarations. */
  using InputImageType = TImage;
  using OutputImageType = TImage;

  /** Standard class type aliases. */
  using Self = VotingBinaryIterativeHoleFillingImageFilter;
  using Superclass = ImageToImageFilter<InputImageType, OutputImageType>;
  using Pointer = SmartPointer<Self>;
  using ConstPointer = SmartPointer<const Self>;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro(VotingBinaryIterativeHoleFillingImageFilter, ImageToImageFilter);

  /** Type of the internal Voting filter that is going to be executed
    iteratively */
  using VotingFilterType = VotingBinaryHoleFillingImageFilter<InputImageType, OutputImageType>;

  /** Image type alias support */
  using InputPixelType = typename InputImageType::PixelType;
  using OutputPixelType = typename OutputImageType::PixelType;

  using InputImageRegionType = typename InputImageType::RegionType;
  using OutputImageRegionType = typename OutputImageType::RegionType;

  using InputSizeType = typename InputImageType::SizeType;

  /** Maximum number of iterations. This filter is executed iteratively as
   * long as at least one pixel has changed in a previous iteration, or until
   * the maximum number of iterations has been reached. */
  itkGetConstReferenceMacro(MaximumNumberOfIterations, unsigned int);
  itkSetMacro(MaximumNumberOfIterations, unsigned int);

  /** Number of iterations executed at any given time. This is useful at the
   * end of the execution in order to verify how many iterations were
   * performed.  */
  itkGetConstReferenceMacro(CurrentNumberOfIterations, unsigned int);
  itkSetMacro(CurrentNumberOfIterations, unsigned int);

  /** Set the radius of the neighborhood used to compute the median. */
  itkSetMacro(Radius, InputSizeType);

  /** Get the radius of the neighborhood used to compute the median */
  itkGetConstReferenceMacro(Radius, InputSizeType);

  /** Set the value associated with the Foreground (or the object) on
      the binary input image and the Background . */
  itkSetMacro(BackgroundValue, InputPixelType);
  itkSetMacro(ForegroundValue, InputPixelType);

  /** Get the value associated with the Foreground (or the object) on the
      binary input image and the Background . */
  itkGetConstReferenceMacro(BackgroundValue, InputPixelType);
  itkGetConstReferenceMacro(ForegroundValue, InputPixelType);

  /** Majority threshold. It is the number of pixels over 50% that will decide
   * whether an OFF pixel will become ON or not. For example, if the
   * neighborhood of a pixel has 124 pixels (excluding itself), the 50% will be
   * 62, and if you set upd a Majority threshold of 5, that means that the
   * filter will require 67 or more neighbor pixels to be ON in order to switch
   * the current OFF pixel to ON. The default value is 1. */
  itkGetConstReferenceMacro(MajorityThreshold, unsigned int);
  itkSetMacro(MajorityThreshold, unsigned int);

  /** Returns the number of pixels that changed when the filter was executed. */
  itkGetConstReferenceMacro(NumberOfPixelsChanged, unsigned int);

#ifdef ITK_USE_CONCEPT_CHECKING
  // Begin concept checking
  itkConceptMacro(InputEqualityComparableCheck, (Concept::EqualityComparable<InputPixelType>));
  itkConceptMacro(InputOStreamWritableeCheck, (Concept::OStreamWritable<InputPixelType>));
  // End concept checking
#endif

protected:
  VotingBinaryIterativeHoleFillingImageFilter();
  ~VotingBinaryIterativeHoleFillingImageFilter() override = default;
  void
  PrintSelf(std::ostream & os, Indent indent) const override;

  /**
   * \sa ImageToImageFilter::ThreadedGenerateData(),
   *     ImageToImageFilter::GenerateData() */
  void
  GenerateData() override;

private:
  InputSizeType m_Radius;

  InputPixelType m_ForegroundValue;
  InputPixelType m_BackgroundValue;

  unsigned int m_MaximumNumberOfIterations;
  unsigned int m_CurrentNumberOfIterations;
  unsigned int m_MajorityThreshold;
  unsigned int m_NumberOfPixelsChanged;
};
} // end namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#  include "itkVotingBinaryIterativeHoleFillingImageFilter.hxx"
#endif

#endif


text:
package decorate

import "gopkg.in/workanator/go-ataman.v1/ansi"

// Style allows to make decoration style customizable.
type Style struct {
	TagOpen            Marker
	TagClose           Marker
	AttributeDelimiter Marker
	ModDelimiter       Marker
	Attributes         map[string]ansi.Attribute
}


text:
package org.apache.tinkerpop.gremlin.structure.io.graphson;

import org.apache.tinkerpop.shaded.jackson.core.JsonGenerator;
import org.apache.tinkerpop.shaded.jackson.core.JsonParser;
import org.apache.tinkerpop.shaded.jackson.core.JsonProcessingException;
import org.apache.tinkerpop.shaded.jackson.core.JsonToken;
import org.apache.tinkerpop.shaded.jackson.databind.DeserializationContext;
import org.apache.tinkerpop.shaded.jackson.databind.SerializerProvider;
import org.apache.tinkerpop.shaded.jackson.databind.deser.std.StdDeserializer;
import org.apache.tinkerpop.shaded.jackson.databind.jsontype.TypeSerializer;
import org.apache.tinkerpop.shaded.jackson.databind.ser.std.StdSerializer;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * GraphSON serializers for classes in {@code java.util.*} for the version 3.0 of GraphSON.
 */
final class JavaUtilSerializersV3d0 {

    private JavaUtilSerializersV3d0() {}

    ////////////////////////////// SERIALIZERS /////////////////////////////////

    final static class MapJacksonSerializer extends StdSerializer<Map> {
        public MapJacksonSerializer() {
            super(Map.class);
        }

        @Override
        public void serialize(final Map map, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider)
                throws IOException {
            for(Map.Entry entry : (Set<Map.Entry>) map.entrySet()) {
                jsonGenerator.writeObject(entry.getKey());
                jsonGenerator.writeObject(entry.getValue());
            }
        }

        @Override
        public void serializeWithType(final Map map, final JsonGenerator jsonGenerator,
                                      final SerializerProvider serializerProvider, final TypeSerializer typeSerializer) throws IOException {
            typeSerializer.writeTypePrefixForObject(map, jsonGenerator);
            serialize(map, jsonGenerator, serializerProvider);
            typeSerializer.writeTypeSuffixForObject(map, jsonGenerator);
        }
    }

    /**
     * Coerces {@code Map.Entry} to a {@code Map} with a single entry in it.
     */
    final static class MapEntryJacksonSerializer extends StdSerializer<Map.Entry> {

        public MapEntryJacksonSerializer() {
            super(Map.Entry.class);
        }

        @Override
        public void serialize(final Map.Entry entry, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider)
                throws IOException {
            final Map<Object,Object> m = new HashMap<>();
            if (entry != null) m.put(entry.getKey(), entry.getValue());
            jsonGenerator.writeObject(m);
        }

        @Override
        public void serializeWithType(final Map.Entry entry, final JsonGenerator jsonGenerator,
                                      final SerializerProvider serializerProvider, final TypeSerializer typeSerializer) throws IOException {
            serialize(entry, jsonGenerator, serializerProvider);
        }
    }

    final static class SetJacksonSerializer extends StdSerializer<Set> {
        public SetJacksonSerializer() {
            super(Set.class);
        }

        @Override
        public void serialize(final Set set, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider)
                throws IOException {
            for(Object o : set) {
                jsonGenerator.writeObject(o);
            }
        }

        @Override
        public void serializeWithType(final Set set, final JsonGenerator jsonGenerator,
                                      final SerializerProvider serializerProvider, final TypeSerializer typeSerializer) throws IOException {
            typeSerializer.writeTypePrefixForArray(set, jsonGenerator);
            serialize(set, jsonGenerator, serializerProvider);
            typeSerializer.writeTypeSuffixForArray(set, jsonGenerator);
        }
    }

    final static class ListJacksonSerializer extends StdSerializer<List> {
        public ListJacksonSerializer() {
            super(List.class);
        }

        @Override
        public void serialize(final List list, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider)
                throws IOException {
            for(Object o : list) {
                jsonGenerator.writeObject(o);
            }
        }

        @Override
        public void serializeWithType(final List list, final JsonGenerator jsonGenerator,
                                      final SerializerProvider serializerProvider, final TypeSerializer typeSerializer) throws IOException {
            typeSerializer.writeTypePrefixForArray(list, jsonGenerator);
            serialize(list, jsonGenerator, serializerProvider);
            typeSerializer.writeTypeSuffixForArray(list, jsonGenerator);
        }
    }

    ////////////////////////////// DESERIALIZERS /////////////////////////////////

    static class MapJacksonDeserializer extends StdDeserializer<Map> {

        protected MapJacksonDeserializer() {
            super(Map.class);
        }

        @Override
        public Map deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
            final Map<Object,Object> m = new LinkedHashMap<>();

            while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
                final Object key = deserializationContext.readValue(jsonParser, Object.class);
                jsonParser.nextToken();
                final Object val = deserializationContext.readValue(jsonParser, Object.class);
                m.put(key, val);
            }

            return m;
        }
    }

    static class SetJacksonDeserializer extends StdDeserializer<Set> {

        protected SetJacksonDeserializer() {
            super(Set.class);
        }

        @Override
        public Set deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
            final Set<Object> s = new LinkedHashSet<>();

            while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
                s.add(deserializationContext.readValue(jsonParser, Object.class));
            }

            return s;
        }
    }

    static class ListJacksonDeserializer extends StdDeserializer<List> {

        protected ListJacksonDeserializer() {
            super(List.class);
        }

        @Override
        public List deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
            final List<Object> s = new LinkedList<>();

            while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
                s.add(deserializationContext.readValue(jsonParser, Object.class));
            }

            return s;
        }
    }
}


text:
package securitycontextconstraints

import (
	"reflect"
	"testing"

	securityapi "github.com/openshift/origin/pkg/security/apis/security"
)

func TestCanonicalize(t *testing.T) {
	testCases := []struct {
		obj    *securityapi.SecurityContextConstraints
		expect *securityapi.SecurityContextConstraints
	}{
		{
			obj:    &securityapi.SecurityContextConstraints{},
			expect: &securityapi.SecurityContextConstraints{},
		},
		{
			obj: &securityapi.SecurityContextConstraints{
				Users: []string{"a"},
			},
			expect: &securityapi.SecurityContextConstraints{
				Users: []string{"a"},
			},
		},
		{
			obj: &securityapi.SecurityContextConstraints{
				Users:  []string{"a", "a"},
				Groups: []string{"b", "b"},
			},
			expect: &securityapi.SecurityContextConstraints{
				Users:  []string{"a"},
				Groups: []string{"b"},
			},
		},
		{
			obj: &securityapi.SecurityContextConstraints{
				Users:  []string{"a", "b", "a"},
				Groups: []string{"c", "d", "c"},
			},
			expect: &securityapi.SecurityContextConstraints{
				Users:  []string{"a", "b"},
				Groups: []string{"c", "d"},
			},
		},
	}
	for i, testCase := range testCases {
		Strategy.Canonicalize(testCase.obj)
		if !reflect.DeepEqual(testCase.expect, testCase.obj) {
			t.Errorf("%d: unexpected object: %#v", i, testCase.obj)
		}
	}
}


text:
// .NAME vtkCylinderRepresentation - A class defining the representation
// for a vtkBoneWidget
// .SECTION Description
// This class is used to represents a vtkBoneWidget. It derives from
// vtkBoneRepresentation and add a cylinder around the bone's line.
// The cylinder radius is automatically adjusted depending on the line's
// lenght.
// .SECTION See Also
// vtkBoneWidgetRepresentation vtkBoneWidget vtkDoubleConeRepresentation
// vtkLineRepresentation

#ifndef __vtkCylinderBoneRepresentation_h
#define __vtkCylinderBoneRepresentation_h

// Bender includes
#include "vtkBenderWidgetsExport.h"

// VTK includes
#include "vtkBoneRepresentation.h"

class vtkActor;
class vtkPolyDataMapper;
class vtkPolyData;
class vtkProperty;
class vtkTubeFilter;

class VTK_BENDER_WIDGETS_EXPORT vtkCylinderBoneRepresentation
  : public vtkBoneRepresentation
{
public:

  // Description:
  // Instantiate this class.
  static vtkCylinderBoneRepresentation *New();

  // Description:
  // Standard methods for the class.
  vtkTypeMacro(vtkCylinderBoneRepresentation, vtkBoneRepresentation);
  void PrintSelf(ostream& os, vtkIndent indent);

  // Description:
  // These are methods that satisfy vtkWidgetRepresentation's API.
  virtual void BuildRepresentation();
  virtual double *GetBounds();

  // Description:
  // Retrieve the polydata that defines the cylinder.
  // To use this method, the user provides the vtkPolyData as an
  // input argument, and the representation polydata is copied into it.
  void GetPolyData(vtkPolyData *pd);

  // Description:
  // Get the radius of the cylinder. The radius is automatically computed
  // from the distance between the two endpoints.
  vtkGetMacro(Radius,double);

  // Description:
  // Set/Get if the cylinder is capped or not. Default is true.
  vtkSetMacro(Capping, int);
  vtkGetMacro(Capping, int);

  // Description:
  // Set/Get the number of sides of the cylinder. The minimum is 3 and
  // the default is 5.
  void SetNumberOfSides(int numberOfSides);
  vtkGetMacro(NumberOfSides, int);

  // Description:
  // Get the cylinder properties. The properties of the cylinder
  // can be manipulated.
  vtkGetObjectMacro(CylinderProperty,vtkProperty);
  vtkGetObjectMacro(SelectedCylinderProperty,vtkProperty);

  // Description:
  // Methods supporting the rendering process.
  virtual void GetActors(vtkPropCollection *pc);
  virtual void ReleaseGraphicsResources(vtkWindow*);
  virtual int HasTranslucentPolygonalGeometry();

  // Description:
  // Helper function to set the opacity of all the cylinder
  // representation actors (normal and selected).
  virtual void SetOpacity(double opacity);

  // Description:
  // Helper method to highlight the line, the cylinder and the endpoints.
  virtual void Highlight(int highlight);

protected:
  vtkCylinderBoneRepresentation();
  ~vtkCylinderBoneRepresentation();

  // The cylinder
  vtkActor*          CylinderActor;
  vtkPolyDataMapper* CylinderMapper;
  vtkTubeFilter*     CylinderGenerator;

  // Properties used to control the appearance of selected objects and
  // the manipulator in general.
  vtkProperty* CylinderProperty;
  vtkProperty* SelectedCylinderProperty;
  void         CreateDefaultProperties();

  // Cylinder properties
  double Radius;
  int    Capping;
  int    NumberOfSides;

  void RebuildCylinder();
  virtual int RenderOpaqueGeometryInternal(vtkViewport*);
  virtual int RenderTranslucentPolygonalGeometryInternal(vtkViewport*);
  virtual int RenderOverlayInternal(vtkViewport*);

private:
  vtkCylinderBoneRepresentation(const vtkCylinderBoneRepresentation&);  // Not implemented
  void operator=(const vtkCylinderBoneRepresentation&);  // Not implemented
};

#endif


text:
package life.catalogue.es;

import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;

import static life.catalogue.es.EsUtil.executeRequest;
import static life.catalogue.es.EsUtil.readFromResponse;

public class EsServerVersion {

  private static EsServerVersion instance;

  public static EsServerVersion getInstance(RestClient client) {
    if (instance == null) {
      try {
        instance = new EsServerVersion(client);
      } catch (IOException e) {
        throw new EsException(e);
      }
    }
    return instance;
  }

  private final int[] version;
  private final String versionString;

  private EsServerVersion(RestClient client) throws IOException {
    Request request = new Request("GET", "/");
    Response response = executeRequest(client, request);
    HashMap<String, String> data = readFromResponse(response, "version");
    versionString = data.get("number");
    version = Arrays.stream(versionString.split("\\.")).mapToInt(Integer::parseInt).toArray();
  }

  public boolean is(int majorVersion) {
    return version[0] == majorVersion;
  }

  public boolean is(int majorVersion, int minorVersion) {
    return is(majorVersion) && version[1] == minorVersion;
  }

  public boolean is(int majorVersion, int minorVersion, int patchVersion) {
    return is(majorVersion, minorVersion) && version[2] == patchVersion;
  }

  public boolean is(int[] version) {
    int idx = 0;
    for (int v : version) {
      if (this.version.length <= idx || this.version[idx] != v) {
        return false;
      }
      idx++;
    }
    return true;
  }

  /**
   * @return semantic version as int array
   */
  public int[] getVersion() {
    return version;
  }

  public String getVersionString() {
    return versionString;
  }
}