text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "gstplaysinkconvertbin.h"

#include <gst/pbutils/pbutils.h>
#include <gst/gst-i18n-plugin.h>

GST_DEBUG_CATEGORY_STATIC (gst_play_sink_convert_bin_debug);
#define GST_CAT_DEFAULT gst_play_sink_convert_bin_debug

#define parent_class gst_play_sink_convert_bin_parent_class

static void gst_play_sink_convert_bin_sink_setcaps (GstPlaySinkConvertBin *
    self, GstCaps * caps);

G_DEFINE_TYPE (GstPlaySinkConvertBin, gst_play_sink_convert_bin, GST_TYPE_BIN);

static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
    GST_PAD_SRC,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS_ANY);

static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink",
    GST_PAD_SINK,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS_ANY);

static gboolean
is_raw_caps (GstCaps * caps, gboolean audio)
{
  gint i, n;
  GstStructure *s;
  const gchar *name;
  const gchar *prefix = audio ? "audio/x-raw" : "video/x-raw";

  n = gst_caps_get_size (caps);
  for (i = 0; i < n; i++) {
    s = gst_caps_get_structure (caps, i);
    name = gst_structure_get_name (s);
    if (g_str_equal (name, prefix))
      return TRUE;
  }

  return FALSE;
}

static void
gst_play_sink_convert_bin_post_missing_element_message (GstPlaySinkConvertBin *
    self, const gchar * name)
{
  GstMessage *msg;

  msg = gst_missing_element_message_new (GST_ELEMENT_CAST (self), name);
  gst_element_post_message (GST_ELEMENT_CAST (self), msg);
}

void
gst_play_sink_convert_bin_add_conversion_element (GstPlaySinkConvertBin * self,
    GstElement * el)
{
  self->conversion_elements = g_list_append (self->conversion_elements, el);
  gst_bin_add (GST_BIN (self), gst_object_ref (el));
}

GstElement *
gst_play_sink_convert_bin_add_conversion_element_factory (GstPlaySinkConvertBin
    * self, const char *factory, const char *name)
{
  GstElement *el;

  el = gst_element_factory_make (factory, name);
  if (el == NULL) {
    gst_play_sink_convert_bin_post_missing_element_message (self, factory);
    GST_ELEMENT_WARNING (self, CORE, MISSING_PLUGIN,
        (_("Missing element '%s' - check your GStreamer installation."),
            factory),
        (self->audio ? "audio rendering might fail" :
            "video rendering might fail"));
  } else {
    gst_play_sink_convert_bin_add_conversion_element (self, el);
  }
  return el;
}

void
gst_play_sink_convert_bin_add_identity (GstPlaySinkConvertBin * self)
{
  if (self->identity)
    return;

  self->identity = gst_element_factory_make ("identity", "identity");
  if (self->identity == NULL) {
    gst_play_sink_convert_bin_post_missing_element_message (self, "identity");
    GST_ELEMENT_WARNING (self, CORE, MISSING_PLUGIN,
        (_("Missing element '%s' - check your GStreamer installation."),
            "identity"), (self->audio ?
            "audio rendering might fail" : "video rendering might fail")

        );
  } else {
    g_object_set (self->identity, "silent", TRUE, "signal-handoffs", FALSE,
        NULL);
    gst_bin_add (GST_BIN_CAST (self), self->identity);
  }
}

static void
gst_play_sink_convert_bin_set_targets (GstPlaySinkConvertBin * self,
    gboolean passthrough)
{
  GstPad *pad;
  GstElement *head, *tail;

  GST_DEBUG_OBJECT (self, "Setting pad targets with passthrough %d",
      passthrough);
  if (self->conversion_elements == NULL || passthrough) {
    GST_DEBUG_OBJECT (self, "no conversion elements, using identity (%p) as "
        "head/tail", self->identity);
    if (!passthrough) {
      GST_WARNING_OBJECT (self,
          "Doing passthrough as no converter elements were added");
    }
    head = tail = self->identity;
  } else {
    head = GST_ELEMENT (g_list_first (self->conversion_elements)->data);
    tail = GST_ELEMENT (g_list_last (self->conversion_elements)->data);
    GST_DEBUG_OBJECT (self, "conversion elements in use, picking "
        "head:%s and tail:%s", GST_OBJECT_NAME (head), GST_OBJECT_NAME (tail));
  }

  g_return_if_fail (head != NULL);
  g_return_if_fail (tail != NULL);

  pad = gst_element_get_static_pad (head, "sink");
  GST_DEBUG_OBJECT (self, "Ghosting bin sink pad to %" GST_PTR_FORMAT, pad);
  gst_ghost_pad_set_target (GST_GHOST_PAD_CAST (self->sinkpad), pad);
  gst_object_unref (pad);

  pad = gst_element_get_static_pad (tail, "src");
  GST_DEBUG_OBJECT (self, "Ghosting bin src pad to %" GST_PTR_FORMAT, pad);
  gst_ghost_pad_set_target (GST_GHOST_PAD_CAST (self->srcpad), pad);
  gst_object_unref (pad);
}

static void
gst_play_sink_convert_bin_remove_element (GstElement * element,
    GstPlaySinkConvertBin * self)
{
  gst_element_set_state (element, GST_STATE_NULL);
  gst_object_unref (element);
  gst_bin_remove (GST_BIN_CAST (self), element);
}

static void
gst_play_sink_convert_bin_on_element_added (GstElement * element,
    GstPlaySinkConvertBin * self)
{
  gst_element_sync_state_with_parent (element);
}

static GstPadProbeReturn
pad_blocked_cb (GstPad * pad, GstPadProbeInfo * info, gpointer user_data)
{
  GstPlaySinkConvertBin *self = user_data;
  GstPad *peer;
  GstCaps *caps;
  gboolean raw;

  if (GST_IS_EVENT (info->data) && !GST_EVENT_IS_SERIALIZED (info->data)) {
    GST_DEBUG_OBJECT (self, "Letting non-serialized event %s pass",
        GST_EVENT_TYPE_NAME (info->data));
    return GST_PAD_PROBE_PASS;
  }

  GST_PLAY_SINK_CONVERT_BIN_LOCK (self);
  GST_DEBUG_OBJECT (self, "Pad blocked");

  /* There must be a peer at this point */
  peer = gst_pad_get_peer (self->sinkpad);
  caps = gst_pad_get_current_caps (peer);
  if (!caps)
    caps = gst_pad_query_caps (peer, NULL);
  gst_object_unref (peer);

  raw = is_raw_caps (caps, self->audio);
  GST_DEBUG_OBJECT (self, "Caps %" GST_PTR_FORMAT " are raw: %d", caps, raw);
  gst_caps_unref (caps);

  if (raw == self->raw)
    goto unblock;
  self->raw = raw;

  gst_ghost_pad_set_target (GST_GHOST_PAD_CAST (self->sinkpad), NULL);
  gst_ghost_pad_set_target (GST_GHOST_PAD_CAST (self->srcpad), NULL);

  if (raw) {
    GST_DEBUG_OBJECT (self, "Switching to raw conversion pipeline");

    if (self->conversion_elements)
      g_list_foreach (self->conversion_elements,
          (GFunc) gst_play_sink_convert_bin_on_element_added, self);
  } else {

    GST_DEBUG_OBJECT (self, "Switch to passthrough pipeline");

    gst_play_sink_convert_bin_on_element_added (self->identity, self);
  }

  gst_play_sink_convert_bin_set_targets (self, !raw);

unblock:
  self->sink_proxypad_block_id = 0;
  GST_PLAY_SINK_CONVERT_BIN_UNLOCK (self);

  return GST_PAD_PROBE_REMOVE;
}

static gboolean
gst_play_sink_convert_bin_sink_event (GstPad * pad, GstObject * parent,
    GstEvent * event)
{
  GstPlaySinkConvertBin *self = GST_PLAY_SINK_CONVERT_BIN (parent);
  gboolean ret;

  switch (GST_EVENT_TYPE (event)) {
    case GST_EVENT_CAPS:
    {
      GstCaps *caps;

      gst_event_parse_caps (event, &caps);
      gst_play_sink_convert_bin_sink_setcaps (self, caps);
      break;
    }
    default:
      break;
  }

  ret = gst_pad_event_default (pad, parent, gst_event_ref (event));

  gst_event_unref (event);

  return ret;
}

static void
block_proxypad (GstPlaySinkConvertBin * self)
{
  if (self->sink_proxypad_block_id == 0) {
    self->sink_proxypad_block_id =
        gst_pad_add_probe (self->sink_proxypad,
        GST_PAD_PROBE_TYPE_BLOCK_DOWNSTREAM, pad_blocked_cb, self, NULL);
  }
}

static void
unblock_proxypad (GstPlaySinkConvertBin * self)
{
  if (self->sink_proxypad_block_id != 0) {
    gst_pad_remove_probe (self->sink_proxypad, self->sink_proxypad_block_id);
    self->sink_proxypad_block_id = 0;
  }
}

static void
gst_play_sink_convert_bin_sink_setcaps (GstPlaySinkConvertBin * self,
    GstCaps * caps)
{
  GstStructure *s;
  const gchar *name;
  gboolean reconfigure = FALSE;
  gboolean raw;

  GST_DEBUG_OBJECT (self, "Setting sink caps %" GST_PTR_FORMAT, caps);

  GST_PLAY_SINK_CONVERT_BIN_LOCK (self);
  s = gst_caps_get_structure (caps, 0);
  name = gst_structure_get_name (s);

  if (self->audio) {
    raw = g_str_equal (name, "audio/x-raw");
  } else {
    raw = g_str_equal (name, "video/x-raw");
  }

  GST_DEBUG_OBJECT (self, "raw %d, self->raw %d, blocked %d",
      raw, self->raw, gst_pad_is_blocked (self->sink_proxypad));

  if (raw) {
    if (!gst_pad_is_blocked (self->sink_proxypad)) {
      GstPad *target = gst_ghost_pad_get_target (GST_GHOST_PAD (self->sinkpad));

      if (!self->raw || (target && !gst_pad_query_accept_caps (target, caps))) {
        if (!self->raw)
          GST_DEBUG_OBJECT (self, "Changing caps from non-raw to raw");
        else
          GST_DEBUG_OBJECT (self, "Changing caps in an incompatible way");

        reconfigure = TRUE;
        block_proxypad (self);
      }

      if (target)
        gst_object_unref (target);
    }
  } else {
    if (self->raw && !gst_pad_is_blocked (self->sink_proxypad)) {
      GST_DEBUG_OBJECT (self, "Changing caps from raw to non-raw");
      reconfigure = TRUE;
      block_proxypad (self);
    }
  }

  /* Otherwise the setcaps below fails */
  if (reconfigure) {
    gst_ghost_pad_set_target (GST_GHOST_PAD_CAST (self->sinkpad), NULL);
    gst_ghost_pad_set_target (GST_GHOST_PAD_CAST (self->srcpad), NULL);
  }

  GST_PLAY_SINK_CONVERT_BIN_UNLOCK (self);
}

#define GST_PLAY_SINK_CONVERT_BIN_FILTER_CAPS(filter,caps) G_STMT_START {     \
  if ((filter)) {                                                             \
    GstCaps *intersection =                                                   \
        gst_caps_intersect_full ((filter), (caps), GST_CAPS_INTERSECT_FIRST); \
    gst_caps_unref ((caps));                                                  \
    (caps) = intersection;                                                    \
  }                                                                           \
} G_STMT_END

static gboolean
gst_play_sink_convert_bin_acceptcaps (GstPad * pad, GstCaps * caps)
{
  GstPlaySinkConvertBin *self =
      GST_PLAY_SINK_CONVERT_BIN (gst_pad_get_parent (pad));
  gboolean ret;
  GstPad *otherpad;

  GST_PLAY_SINK_CONVERT_BIN_LOCK (self);
  if (pad == self->srcpad) {
    otherpad = self->sinkpad;
  } else if (pad == self->sinkpad) {
    otherpad = self->srcpad;
  } else {
    GST_ERROR_OBJECT (pad, "Not one of our pads");
    otherpad = NULL;
  }

  if (otherpad) {
    ret = gst_pad_peer_query_accept_caps (otherpad, caps);
    if (!ret && self->converter_caps) {
      /* maybe we can convert */
      ret = gst_caps_can_intersect (caps, self->converter_caps);
    }
  } else {
    ret = TRUE;
  }
  GST_PLAY_SINK_CONVERT_BIN_UNLOCK (self);

  gst_object_unref (self);

  GST_DEBUG_OBJECT (pad, "Accept caps: '%" GST_PTR_FORMAT "' %d", caps, ret);

  return ret;
}

static GstCaps *
gst_play_sink_convert_bin_getcaps (GstPad * pad, GstCaps * filter)
{
  GstPlaySinkConvertBin *self =
      GST_PLAY_SINK_CONVERT_BIN (gst_pad_get_parent (pad));
  GstCaps *ret;
  GstPad *otherpad, *peer;

  GST_PLAY_SINK_CONVERT_BIN_LOCK (self);
  if (pad == self->srcpad) {
    otherpad = self->sinkpad;
  } else if (pad == self->sinkpad) {
    otherpad = self->srcpad;
  } else {
    GST_ERROR_OBJECT (pad, "Not one of our pads");
    otherpad = NULL;
  }

  if (otherpad) {
    peer = gst_pad_get_peer (otherpad);
    if (peer) {
      GstCaps *peer_caps;
      GstCaps *downstream_filter = NULL;

      /* Add all the caps that we can convert to to the filter caps,
       * otherwise downstream might just return EMPTY caps because
       * it doesn't handle the filter caps but we could still convert
       * to these caps */
      if (filter) {
        guint i, n;

        downstream_filter = gst_caps_new_empty ();

        /* Intersect raw video caps in the filter caps with the converter
         * caps. This makes sure that we don't accept raw video that we
         * can't handle, e.g. because of caps features */
        n = gst_caps_get_size (filter);
        for (i = 0; i < n; i++) {
          GstStructure *s;
          GstCaps *tmp, *tmp2;

          s = gst_structure_copy (gst_caps_get_structure (filter, i));
          if (gst_structure_has_name (s,
                  self->audio ? "audio/x-raw" : "video/x-raw")) {
            tmp = gst_caps_new_full (s, NULL);
            tmp2 = gst_caps_intersect (tmp, self->converter_caps);
            gst_caps_append (downstream_filter, tmp2);
            gst_caps_unref (tmp);
          } else {
            gst_caps_append_structure (downstream_filter, s);
          }
        }
        downstream_filter =
            gst_caps_merge (downstream_filter,
            gst_caps_ref (self->converter_caps));
      }

      peer_caps = gst_pad_query_caps (peer, downstream_filter);
      if (downstream_filter)
        gst_caps_unref (downstream_filter);
      gst_object_unref (peer);
      if (self->converter_caps && is_raw_caps (peer_caps, self->audio)) {
        GstCaps *converter_caps = gst_caps_ref (self->converter_caps);
        GstCapsFeatures *cf;
        GstStructure *s;
        guint i, n;

        ret = gst_caps_make_writable (peer_caps);

        /* Filter out ANY capsfeatures from the converter caps. We can't
         * convert to ANY capsfeatures, they are only there so that we
         * can passthrough whatever downstream can support... but we
         * definitely don't want to return them here
         */
        n = gst_caps_get_size (converter_caps);
        for (i = 0; i < n; i++) {
          s = gst_caps_get_structure (converter_caps, i);
          cf = gst_caps_get_features (converter_caps, i);

          if (cf && gst_caps_features_is_any (cf))
            continue;
          ret =
              gst_caps_merge_structure_full (ret, gst_structure_copy (s),
              (cf ? gst_caps_features_copy (cf) : NULL));
        }
        gst_caps_unref (converter_caps);
      } else {
        ret = peer_caps;
      }
    } else {
      ret = gst_caps_ref (self->converter_caps);
    }
    GST_PLAY_SINK_CONVERT_BIN_FILTER_CAPS (filter, ret);

  } else {
    ret = filter ? gst_caps_ref (filter) : gst_caps_new_any ();
  }
  GST_PLAY_SINK_CONVERT_BIN_UNLOCK (self);

  gst_object_unref (self);

  GST_DEBUG_OBJECT (pad, "Returning caps %" GST_PTR_FORMAT, ret);

  return ret;
}

static gboolean
gst_play_sink_convert_bin_query (GstPad * pad, GstObject * parent,
    GstQuery * query)
{
  gboolean res = FALSE;

  switch (GST_QUERY_TYPE (query)) {
    case GST_QUERY_CAPS:
    {
      GstCaps *filter, *caps;

      gst_query_parse_caps (query, &filter);
      caps = gst_play_sink_convert_bin_getcaps (pad, filter);
      gst_query_set_caps_result (query, caps);
      gst_caps_unref (caps);
      res = TRUE;
      break;
    }
    case GST_QUERY_ACCEPT_CAPS:
    {
      gboolean ret;
      GstCaps *caps;

      gst_query_parse_accept_caps (query, &caps);
      ret = gst_play_sink_convert_bin_acceptcaps (pad, caps);
      gst_query_set_accept_caps_result (query, ret);
      res = TRUE;
      break;
    }
    default:
      res = gst_pad_query_default (pad, parent, query);
      break;
  }
  return res;
}

void
gst_play_sink_convert_bin_remove_elements (GstPlaySinkConvertBin * self)
{
  if (self->conversion_elements) {
    g_list_foreach (self->conversion_elements,
        (GFunc) gst_play_sink_convert_bin_remove_element, self);
    g_list_free (self->conversion_elements);
    self->conversion_elements = NULL;
  }
  if (self->converter_caps) {
    gst_caps_unref (self->converter_caps);
    self->converter_caps = NULL;
  }
}

static void
gst_play_sink_convert_bin_dispose (GObject * object)
{
  GstPlaySinkConvertBin *self = GST_PLAY_SINK_CONVERT_BIN_CAST (object);

  gst_play_sink_convert_bin_remove_elements (self);

  G_OBJECT_CLASS (parent_class)->dispose (object);
}

static void
gst_play_sink_convert_bin_finalize (GObject * object)
{
  GstPlaySinkConvertBin *self = GST_PLAY_SINK_CONVERT_BIN_CAST (object);

  gst_object_unref (self->sink_proxypad);
  g_mutex_clear (&self->lock);

  G_OBJECT_CLASS (parent_class)->finalize (object);
}

void
gst_play_sink_convert_bin_cache_converter_caps (GstPlaySinkConvertBin * self)
{
  GstElement *head;
  GstPad *pad;

  if (self->converter_caps) {
    gst_caps_unref (self->converter_caps);
    self->converter_caps = NULL;
  }

  if (!self->conversion_elements) {
    GST_INFO_OBJECT (self, "No conversion elements");
    return;
  }

  head = GST_ELEMENT (g_list_first (self->conversion_elements)->data);
  pad = gst_element_get_static_pad (head, "sink");
  if (!pad) {
    GST_WARNING_OBJECT (self, "No sink pad found");
    return;
  }

  self->converter_caps = gst_pad_query_caps (pad, NULL);
  GST_INFO_OBJECT (self, "Converter caps: %" GST_PTR_FORMAT,
      self->converter_caps);

  gst_object_unref (pad);
}

static GstStateChangeReturn
gst_play_sink_convert_bin_change_state (GstElement * element,
    GstStateChange transition)
{
  GstStateChangeReturn ret;
  GstPlaySinkConvertBin *self = GST_PLAY_SINK_CONVERT_BIN_CAST (element);

  switch (transition) {
    case GST_STATE_CHANGE_PAUSED_TO_READY:
      GST_PLAY_SINK_CONVERT_BIN_LOCK (self);
      unblock_proxypad (self);
      GST_PLAY_SINK_CONVERT_BIN_UNLOCK (self);
      break;
    case GST_STATE_CHANGE_READY_TO_PAUSED:
      GST_PLAY_SINK_CONVERT_BIN_LOCK (self);
      gst_play_sink_convert_bin_set_targets (self, TRUE);
      self->raw = FALSE;
      GST_PLAY_SINK_CONVERT_BIN_UNLOCK (self);
      break;
    default:
      break;
  }

  ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
  if (ret == GST_STATE_CHANGE_FAILURE)
    return ret;

  switch (transition) {
    case GST_STATE_CHANGE_PAUSED_TO_READY:
      GST_PLAY_SINK_CONVERT_BIN_LOCK (self);
      gst_play_sink_convert_bin_set_targets (self, TRUE);
      self->raw = FALSE;
      GST_PLAY_SINK_CONVERT_BIN_UNLOCK (self);
      break;
    case GST_STATE_CHANGE_READY_TO_PAUSED:
      GST_PLAY_SINK_CONVERT_BIN_LOCK (self);
      unblock_proxypad (self);
      GST_PLAY_SINK_CONVERT_BIN_UNLOCK (self);
      break;
    default:
      break;
  }

  return ret;
}

static void
gst_play_sink_convert_bin_class_init (GstPlaySinkConvertBinClass * klass)
{
  GObjectClass *gobject_class;
  GstElementClass *gstelement_class;

  GST_DEBUG_CATEGORY_INIT (gst_play_sink_convert_bin_debug,
      "playsinkconvertbin", 0, "play bin");

  gobject_class = (GObjectClass *) klass;
  gstelement_class = (GstElementClass *) klass;

  gobject_class->dispose = gst_play_sink_convert_bin_dispose;
  gobject_class->finalize = gst_play_sink_convert_bin_finalize;

  gst_element_class_add_static_pad_template (gstelement_class, &srctemplate);
  gst_element_class_add_static_pad_template (gstelement_class, &sinktemplate);
  gst_element_class_set_static_metadata (gstelement_class,
      "Player Sink Converter Bin", "Bin/Converter",
      "Convenience bin for audio/video conversion",
      "Sebastian Dröge <sebastian.droege@collabora.co.uk>");

  gstelement_class->change_state =
      GST_DEBUG_FUNCPTR (gst_play_sink_convert_bin_change_state);
}

static void
gst_play_sink_convert_bin_init (GstPlaySinkConvertBin * self)
{
  GstPadTemplate *templ;

  g_mutex_init (&self->lock);

  templ = gst_static_pad_template_get (&sinktemplate);
  self->sinkpad = gst_ghost_pad_new_no_target_from_template ("sink", templ);
  gst_pad_set_event_function (self->sinkpad,
      GST_DEBUG_FUNCPTR (gst_play_sink_convert_bin_sink_event));
  gst_pad_set_query_function (self->sinkpad,
      GST_DEBUG_FUNCPTR (gst_play_sink_convert_bin_query));

  self->sink_proxypad =
      GST_PAD_CAST (gst_proxy_pad_get_internal (GST_PROXY_PAD (self->sinkpad)));

  gst_element_add_pad (GST_ELEMENT_CAST (self), self->sinkpad);
  gst_object_unref (templ);

  templ = gst_static_pad_template_get (&srctemplate);
  self->srcpad = gst_ghost_pad_new_no_target_from_template ("src", templ);
  gst_pad_set_query_function (self->srcpad,
      GST_DEBUG_FUNCPTR (gst_play_sink_convert_bin_query));
  gst_element_add_pad (GST_ELEMENT_CAST (self), self->srcpad);
  gst_object_unref (templ);

  gst_play_sink_convert_bin_add_identity (self);
}


text:
package flex2.compiler.swc;

import flash.localization.LocalizationManager;
import flex2.compiler.ILocalizableMessage;
import flex2.compiler.util.CompilerMessage;
import flex2.compiler.util.ThreadLocalToolkit;

/**
 * General exception for SWC problems.
 */
public class SwcException extends RuntimeException implements ILocalizableMessage
{
	private static final long serialVersionUID = -8494333073832014661L;
    Exception detailEx;

	public String getLevel()
	{
	    return ERROR;
	}

	public String getPath()
	{
	    return null;
	}

    public void setPath(String path)
    {
    }

	public int getLine()
	{
	    return -1;
	}

    public void setLine(int line)
    {
    }

	public int getColumn()
	{
	    return -1;
	}

    public void setColumn(int column)
    {
    }

	public Exception getExceptionDetail()
	{
		return detailEx;
	}

	public boolean isPathAvailable()
	{
		return true;
	}

	public String getMessage()
	{
		String msg = super.getMessage();
		if (msg != null)
		{
			return msg;
		}
		else
		{
			LocalizationManager l10n = ThreadLocalToolkit.getLocalizationManager();
			if (l10n == null)
			{
				return null;
			}
			else
			{
				return l10n.getLocalizedTextString(this);
			}
		}
	}

	public String toString()
	{
		return getMessage();
	}

	/**
	* Start of SwcExceptions, the main message classes for swc exceptions.  Only SwcException classes
	* should be logged and thrown out of the SWC package.
	**/

	public static class SwcNotLoaded extends SwcException
	{
		private static final long serialVersionUID = -2554776022462133598L;
        public SwcNotLoaded(String location, Exception exception)
		{
			this.location = location;
			this.detailEx = exception;
		}
		public String location;
	}

	public static class SwcNotExported extends SwcException
	{
		private static final long serialVersionUID = 3467058758218868806L;
        public SwcNotExported(String location, Exception exception)
		{
			this.location = location;
			this.detailEx = exception;
		}
		public String location;
	}

	public static class CouldNotFindSource extends SwcException
	{
		private static final long serialVersionUID = 1560595276060532770L;
        public CouldNotFindSource(String className)
		{
			this.className = className;
		}
		public String className;
	}

	public static class CouldNotFindFileSource extends SwcException
	{
		private static final long serialVersionUID = 2801395325513327168L;
        public CouldNotFindFileSource(String className)
		{
			this.className = className;
		}
		public String className;
	}

	public static class NoResourceBundleSource extends SwcException
	{
	    private static final long serialVersionUID = 4614290447127279268L;
        public NoResourceBundleSource( String className )
	    {
	        this.className = className;
	    }
	    public String className;
	}

	public static class NoSourceForClass extends SwcException
	{
	    private static final long serialVersionUID = -2979710207329828285L;
        public NoSourceForClass( String className, String nsTarget )
	    {
	        this.className = className;
		    this.nsTarget = nsTarget;
	    }
	    public String className;
		public String nsTarget;
	}

	public static class MissingIconFile extends SwcException
    {
        private static final long serialVersionUID = -4352255326395065440L;
        public MissingIconFile( String icon, String source )
        {
            this.icon = icon;
            this.source = source;
        }
        public String icon;
        public String source;
    }

	public static class MissingFile extends SwcException
	{
		private static final long serialVersionUID = 5684202543884980582L;
        public MissingFile(String file)
		{
			this.file = file;
		}
		public String file;
	}

	public static class NullCatalogStream extends SwcException
	{

        private static final long serialVersionUID = -998293635787865589L;
	}

	public static class UseClassName extends SwcException
	{

        private static final long serialVersionUID = 9041507300608050252L;
	}

	public static class DuplicateDefinition extends SwcException
	{
		private static final long serialVersionUID = 1516531038464434547L;
        public DuplicateDefinition(String definition, String script, String source)
		{
			this.definition = definition;
			this.script = script;
			this.source = source;
		}

		public String definition;
		public String script;
		public String source;
	}

	public static class SwcNotFound extends SwcException
	{
		private static final long serialVersionUID = 7224142779917797604L;
        public SwcNotFound(String location)
		{
			this.location = location;
		}
		public String location;
	}

	public static class NotASwcDirectory extends SwcException
	{
		private static final long serialVersionUID = 3680364244079842127L;
        public NotASwcDirectory(String directory)
		{
			this.directory = directory;
		}
		public String directory;
	}

	public static class SwcLocation extends SwcException
	{
		private static final long serialVersionUID = -4103907341840876695L;

        public SwcLocation(String location)
		{
			this.location = location;
		}

		public String location;
	}

	public static class FileNotWritten extends SwcException
	{
		private static final long serialVersionUID = -6044223715981449297L;
        public FileNotWritten(String file, String message)
		{
			this.file = file;
			this.message = message;
		}
		public String file;
		public String message;
	}

	public static class FilesNotRead extends SwcException
	{
		private static final long serialVersionUID = -7482575224824123700L;
        public FilesNotRead(String message)
		{
			this.message = message;
		}
		public String message;
	}

	public static class NotADirectory extends SwcException
	{
		private static final long serialVersionUID = -3324810541160061753L;
        public NotADirectory(String directory)
		{
			this.directory = directory;
		}
		public String directory;
	}

	public static class DirectoryNotCreated extends SwcException
	{
		private static final long serialVersionUID = 8570936566842347533L;
        public DirectoryNotCreated(String directory)
		{
			this.directory = directory;
		}
		public String directory;
	}

	public static class SwcNotRenamed extends SwcException
	{
		private static final long serialVersionUID = -2890913997385310503L;
        public SwcNotRenamed(String oldName, String newName)
		{
			this.oldName = oldName;
			this.newName = newName;
		}
		public String oldName;
		public String newName;
	}

	public static class CatalogNotFound extends SwcException
	{

        private static final long serialVersionUID = 108663682135244079L;
	}

	public static class UnsupportedOperation extends SwcException
	{
		private static final long serialVersionUID = 7507668150266635174L;
        public UnsupportedOperation(String operation, String className)
		{
			this.operation = operation;
			this.className = className;
		}
		public String operation;
		public String className;
	}

	public static class EmptyNamespace extends SwcException
	{
		private static final long serialVersionUID = -5461119352251578340L;
        public EmptyNamespace(String name)
		{
			this.name = name;
		}
		public String name;
	}

	public static class ComponentDefinedTwice extends SwcException
	{
		private static final long serialVersionUID = -6880538200104744439L;
        public ComponentDefinedTwice(String name, String className1, String className2)
		{
			this.name = name;
			this.className1 = className1;
			this.className2 = className2;
		}
		public String name;
		public String className1;
		public String className2;
	}

	public static class UnknownElementInCatalog extends SwcException
	{
		private static final long serialVersionUID = -1709365264970456008L;
        public UnknownElementInCatalog(String element, String section)
		{
			this.element = element;
			this.section = section;
		}
		public String element;
		public String section;
	}

	public static class UnsupportedFeature extends SwcException
	{
		private static final long serialVersionUID = 2318520473798835842L;
        public UnsupportedFeature(String name)
		{
			this.name = name;
		}
		public String name;
	}

	public static class NoElementValue extends SwcException
	{
		private static final long serialVersionUID = -5700047399416802509L;
        public NoElementValue(String name)
		{
			this.name = name;
		}
		public String name;
	}

	public static class ScriptUsedMultipleTimes extends SwcException
	{
		private static final long serialVersionUID = -185332682720245755L;
        public ScriptUsedMultipleTimes(String scriptName)
		{
			this.scriptName = scriptName;
		}
		public String scriptName;
	}

	public static class NoElementValueFound extends SwcException
	{
		private static final long serialVersionUID = 390935817896002861L;
        public NoElementValueFound(String name, String className)
		{
			this.name = name;
			this.className = className;
		}
		public String name;
		public String className;
	}

	public static class BadCRC extends SwcException
	{
		private static final long serialVersionUID = -2938866033550966368L;
        public BadCRC(String givenChecksum, String realChecksum)
		{
			this.givenChecksum = givenChecksum;
			this.realChecksum = realChecksum;
		}
		public String givenChecksum;
		public String realChecksum;
	}

	public static class UnknownZipFormat extends SwcException
	{
		private static final long serialVersionUID = -7447740969926776234L;
        public UnknownZipFormat(String start)
		{
			this.start = start;
		}
		public String start;
	}

	public static class NotAResource extends SwcException
	{
		private static final long serialVersionUID = -5897483545874573295L;
        public NotAResource(String className)
		{
			this.className = className;
		}
		public String className;
	}

	public static class CouldNotSetZipSize extends SwcException
	{
		private static final long serialVersionUID = -309332180325061103L;
        public CouldNotSetZipSize(String entry, String message)
		{
			this.entry = entry;
			this.message = message;
		}
		public String entry;
		public String message;
	}

	public static class UnsupportedZipCompression extends SwcException
	{
		private static final long serialVersionUID = 324265408589862036L;
        public UnsupportedZipCompression(String method)
		{
			this.method = method;
		}
		public String method;
	}

	public static class BadZipSize extends SwcException
	{
		private static final long serialVersionUID = 1320298387837461369L;
        public BadZipSize(String entry, String expected, String found)
		{
			this.entry = entry;
			this.expected = expected;
			this.found = found;
		}
		public String entry;
		public String expected;
		public String found;
	}

	public static class NotASwcFile extends SwcException
	{
		private static final long serialVersionUID = 2547089548876219296L;
        public NotASwcFile(String location)
		{
			this.location = location;
		}
		public String location;
	}

    public static class ArchiveFileException extends SwcException
    {
        public String message;

        public ArchiveFileException(String message)
        {
            this.message = message;
        }
    }

	public static class MetadataNotWritten extends CompilerMessage.CompilerWarning
	{
	    private static final long serialVersionUID = 5146935251331331679L;

        public MetadataNotWritten()
	    {
	    }
	}

	public static class DigestsNotWritten extends CompilerMessage.CompilerWarning
	{
	    private static final long serialVersionUID = 4407668372093287396L;

        public DigestsNotWritten()
	    {
	    }
	}
}

redpajama_set_name: RedPajamaGithub


text:
require_relative "version"
require_relative "exceptions"
require_relative "guard"
require_relative "callback"
require_relative "adapters/memory_transition"

module Statesman
  # The main module, that should be `extend`ed in to state machine classes.
  module Machine
    def self.included(base)
      base.extend(ClassMethods)
      base.send(:attr_reader, :object)
    end

    # Retry any transitions that fail due to a TransitionConflictError
    def self.retry_conflicts(max_retries = 1)
      retry_attempt = 0

      begin
        yield
      rescue TransitionConflictError
        retry_attempt += 1
        retry_attempt <= max_retries ? retry : raise
      end
    end

    module ClassMethods
      attr_reader :initial_state

      def states
        @states ||= []
      end

      def state(name, options = { initial: false })
        name = name.to_s
        if options[:initial]
          validate_initial_state(name)
          @initial_state = name
        end
        states << name
      end

      def successors
        @successors ||= {}
      end

      def callbacks
        @callbacks ||= {
          before:       [],
          after:        [],
          after_commit: [],
          guards:       []
        }
      end

      def transition(from: nil, to: nil)
        from = to_s_or_nil(from)
        to = array_to_s_or_nil(to)

        raise InvalidStateError, "No to states provided." if to.empty?

        successors[from] ||= []

        ([from] + to).each { |state| validate_state(state) }

        successors[from] += to
      end

      def before_transition(options = { from: nil, to: nil }, &block)
        add_callback(
          options.merge(callback_class: Callback, callback_type: :before),
          &block)
      end

      def guard_transition(options = { from: nil, to: nil }, &block)
        add_callback(
          options.merge(callback_class: Guard, callback_type: :guards),
          &block)
      end

      def after_transition(options = { from: nil, to: nil,
                                       after_commit: false }, &block)
        callback_type = options[:after_commit] ? :after_commit : :after

        add_callback(
          options.merge(callback_class: Callback, callback_type: callback_type),
          &block)
      end

      def validate_callback_condition(options = { from: nil, to: nil })
        from = to_s_or_nil(options[:from])
        to   = array_to_s_or_nil(options[:to])

        ([from] + to).compact.each { |state| validate_state(state) }
        return if from.nil? && to.empty?

        validate_not_from_terminal_state(from)
        to.each { |state| validate_not_to_initial_state(state) }

        return if from.nil? || to.empty?

        to.each { |state| validate_from_and_to_state(from, state) }
      end

      # Check that the 'from' state is not terminal
      def validate_not_from_terminal_state(from)
        unless from.nil? || successors.keys.include?(from)
          raise InvalidTransitionError,
                "Cannot transition away from terminal state '#{from}'"
        end
      end

      # Check that the 'to' state is not initial
      def validate_not_to_initial_state(to)
        unless to.nil? || successors.values.flatten.include?(to)
          raise InvalidTransitionError,
                "Cannot transition to initial state '#{to}'"
        end
      end

      # Check that the transition is valid when 'from' and 'to' are given
      def validate_from_and_to_state(from, to)
        unless successors.fetch(from, []).include?(to)
          raise InvalidTransitionError,
                "Cannot transition from '#{from}' to '#{to}'"
        end
      end

      private

      def add_callback(options, &block)
        from = to_s_or_nil(options[:from])
        to   = array_to_s_or_nil(options[:to])
        callback_klass = options.fetch(:callback_class)
        callback_type = options.fetch(:callback_type)

        validate_callback_condition(from: from, to: to)
        callbacks[callback_type] <<
          callback_klass.new(from: from, to: to, callback: block)
      end

      def validate_state(state)
        unless states.include?(state.to_s)
          raise InvalidStateError, "Invalid state '#{state}'"
        end
      end

      def validate_initial_state(state)
        unless initial_state.nil?
          raise InvalidStateError, "Cannot set initial state to '#{state}', " \
                                   "already defined as #{initial_state}."
        end
      end

      def to_s_or_nil(input)
        input.nil? ? input : input.to_s
      end

      def array_to_s_or_nil(input)
        Array(input).map { |item| to_s_or_nil(item) }
      end
    end

    def initialize(object,
                   options = {
                     transition_class: Statesman::Adapters::MemoryTransition
                   })
      @object = object
      @transition_class = options[:transition_class]
      @storage_adapter = adapter_class(@transition_class).new(
        @transition_class, object, self, options)
      send(:after_initialize) if respond_to? :after_initialize
    end

    def current_state(force_reload: false)
      last_action = last_transition(force_reload: force_reload)
      last_action ? last_action.to_state : self.class.initial_state
    end

    def in_state?(*states)
      states.flatten.any? { |state| current_state == state.to_s }
    end

    def allowed_transitions
      successors_for(current_state).select do |state|
        can_transition_to?(state)
      end
    end

    def last_transition(force_reload: false)
      @storage_adapter.last(force_reload: force_reload)
    end

    def can_transition_to?(new_state, metadata = {})
      validate_transition(from: current_state,
                          to: new_state,
                          metadata: metadata)
      true
    rescue TransitionFailedError, GuardFailedError
      false
    end

    def history
      @storage_adapter.history
    end

    def transition_to!(new_state, metadata = {})
      initial_state = current_state
      new_state = new_state.to_s

      validate_transition(from: initial_state,
                          to: new_state,
                          metadata: metadata)

      @storage_adapter.create(initial_state, new_state, metadata)

      true
    end

    def execute(phase, initial_state, new_state, transition)
      callbacks = callbacks_for(phase, from: initial_state, to: new_state)
      callbacks.each { |cb| cb.call(@object, transition) }
    end

    def transition_to(new_state, metadata = {})
      self.transition_to!(new_state, metadata)
    rescue TransitionFailedError, GuardFailedError
      false
    end

    private

    def adapter_class(transition_class)
      if transition_class == Statesman::Adapters::MemoryTransition
        Adapters::Memory
      else
        Statesman.storage_adapter
      end
    end

    def successors_for(from)
      self.class.successors[from] || []
    end

    def guards_for(options = { from: nil, to: nil })
      select_callbacks_for(self.class.callbacks[:guards], options)
    end

    def callbacks_for(phase, options = { from: nil, to: nil })
      select_callbacks_for(self.class.callbacks[phase], options)
    end

    def select_callbacks_for(callbacks, options = { from: nil, to: nil })
      from = to_s_or_nil(options[:from])
      to   = to_s_or_nil(options[:to])
      callbacks.select { |callback| callback.applies_to?(from: from, to: to) }
    end

    def validate_transition(options = { from: nil, to: nil, metadata: nil })
      from = to_s_or_nil(options[:from])
      to   = to_s_or_nil(options[:to])

      successors = self.class.successors[from] || []
      unless successors.include?(to)
        raise TransitionFailedError,
              "Cannot transition from '#{from}' to '#{to}'"
      end

      # Call all guards, they raise exceptions if they fail
      guards_for(from: from, to: to).each do |guard|
        guard.call(@object, last_transition, options[:metadata])
      end
    end

    def to_s_or_nil(input)
      input.nil? ? input : input.to_s
    end
  end
end


text:
angular
  .module('CoffeeCoder')
  .controller('LessonsController', LessonsController);

LessonsController.$inject = ['$http', '$state', 'TokenService'];
function LessonsController($http, $state, TokenService) {
  var self = this;

  self.all = [];
  self.createdLessons = [];
  self.subbedLessons = [];
  self.newLesson = {};
  self.userId = TokenService.decodeToken() || undefined;
  self.lessonToEdit = {};
  self.searchText = '';

  (function getLessons(){
    $http
      .get('https://coffee-coder-api.herokuapp.com/lessons')
      .then(function(res) {
        self.all = res.data.lessons;
      });
  }());

  (function getUser() {
    if (self.userId) {
      $http
        .get('https://coffee-coder-api.herokuapp.com/users/' + self.userId)
        .then(function(res) {
          self.user = res.data.user;
          $http
            .get('https://coffee-coder-api.herokuapp.com/lessons')
            .then(function(res) {
              self.all = res.data.lessons;
              for (var i in res.data.lessons) {
                for (var j in self.user.lessonsCreated) {
                  if (res.data.lessons[i]._id == self.user.lessonsCreated[j]) {
                    self.createdLessons.push(res.data.lessons[i]);
                  };
                };
                for (var n in self.user.lessonsSubbed) {
                  if (res.data.lessons[i]._id == self.user.lessonsSubbed[n]) {
                    self.subbedLessons.push(res.data.lessons[i]);
                  };
                };
              };
            });
        });
    } else {
      return false;
    }
  }());

  self.createLesson = function() {
    $http
      .post('https://coffee-coder-api.herokuapp.com/lessons', self.newLesson)
      .then(function(res) {
        self.all.push(self.newLesson);
        self.user.lessonsCreated.push(res.data.lesson._id);
        self.user.points += 10;
        console.log(self.user);
        $http
          .put('https://coffee-coder-api.herokuapp.com/users/' + self.userId, self.user)
          .then(function(res) {
            console.log(res);
          });
        $state.go('createdLessons');
      });
  };

  self.removeLesson = function(lesson) {
    event.preventDefault();
    $http
      .delete('https://coffee-coder-api.herokuapp.com/lessons/' + lesson._id)
      .then(function(res) {
        console.log(res.data.message);
        var index = self.all.indexOf(lesson);
        self.all.splice(index, 1);
        var index = self.createdLessons.indexOf(lesson);
        self.createdLessons.splice(index, 1);
        var index = self.user.lessonsCreated.indexOf(lesson._id);
        self.user.lessonsCreated.splice(index, 1);
        self.user.points -= 10;
        $http
          .put('https://coffee-coder-api.herokuapp.com/users/' + self.userId, self.user)
          .then(function(res) {
          });
      });
  };

  self.editLesson = function(lesson) {
    event.preventDefault();
    self.toggleEditForm();
    self.lessonToEdit = lesson;
  };

  self.updateLesson = function() {
    $http
      .put('https://coffee-coder-api.herokuapp.com/lessons/' + self.lessonToEdit._id, self.lessonToEdit)
      .then(function(response) {
        self.toggleEditForm();
      });
  };

  self.toggleEditForm = function() {
    $('form#edit-lesson').slideToggle('slow');
  };

  self.unsubscribe = function(lesson) {
    event.preventDefault();
    var index = self.subbedLessons.indexOf(lesson);
    self.subbedLessons.splice(index, 1);
    var index = self.user.lessonsSubbed.indexOf(lesson._id);
    self.user.lessonsSubbed.splice(index, 1);
    $http
      .put('https://coffee-coder-api.herokuapp.com/users/' + self.userId, self.user)
      .then(function(res) {
      });
  };

  self.isLoggedIn = function() {
    return !!TokenService.getToken();
  };

  self.selectLesson = function(lesson) {
    event.preventDefault();
    $state.go('code', {lesson: lesson, id: lesson._id});
  };

};


text:
package com.google.api.codegen.util.java;

import static org.junit.Assert.assertEquals;

import java.util.List;
import org.junit.Test;

public class JavaRenderingUtilTest {

  @Test
  public void testGetDocLines() {
    String text =
        "Sample code:\n"
            + "  @Override\n"
            + "  public boolean evaluate() {\n"
            + "    return a < b*c && d > e;\n"
            + "  }";

    List<String> lines = JavaRenderingUtil.getDocLines(text);

    assertEquals(5, lines.size());
    assertEquals("Sample code:", lines.get(0));
    assertEquals("  {@literal @}Override", lines.get(1));
    assertEquals("  public boolean evaluate() {", lines.get(2));
    assertEquals("    return a < b*c && d > e;", lines.get(3));
    assertEquals("  }", lines.get(4));
  }
}


text:
'use strict';

let chai = require('chai');
let expect = chai.expect;

let parser = require('../../../lib/parser');

let FilterSimplifier = require('../../../lib/compiler/filters/filter-simplifier');

describe('FilterSimplifier', () => {
    describe('simplify', () => {
        it('replaces ExpressionFilterTerms by their expressions', () => {
            let simplifier = new FilterSimplifier();
            let ast = parser.parseFilter('a < 5');

            expect(ast.ast.type).to.equal('ExpressionFilterTerm');

            let simplifiedAst = simplifier.simplify(ast);

            expect(simplifiedAst.ast).to.deep.equal(ast.ast.expression);
        });

        it('replaces SimpleFilterTerms with a String child by FulltextFilterTerms', () => {
            let simplifier = new FilterSimplifier();
            let ast = parser.parseFilter('"abcd"');

            expect(ast.ast.type).to.equal('SimpleFilterTerm');

            let simplifiedAst = simplifier.simplify(ast);

            expect(simplifiedAst.ast).to.deep.equal({
                type: 'FulltextFilterTerm',
                text: ast.ast.expression.value,
                location: ast.ast.location
            });
        });

        // SimpleFilterTerm nodes with a FilterLiteral child can't be tested
        // because there is no filter literal syntax.
    });
});


text: am_say( "Piger is shutting Down", 500, 3000 )


text:
"""Constants used by Home Assistant components."""
MAJOR_VERSION = 0
MINOR_VERSION = 49
PATCH_VERSION = '0.dev0'
__short_version__ = '{}.{}'.format(MAJOR_VERSION, MINOR_VERSION)
__version__ = '{}.{}'.format(__short_version__, PATCH_VERSION)
REQUIRED_PYTHON_VER = (3, 4, 2)
REQUIRED_PYTHON_VER_WIN = (3, 5, 2)
CONSTRAINT_FILE = 'package_constraints.txt'

PROJECT_NAME = 'Home Assistant'
PROJECT_PACKAGE_NAME = 'homeassistant'
PROJECT_LICENSE = 'Apache License 2.0'
PROJECT_AUTHOR = 'The Home Assistant Authors'
PROJECT_COPYRIGHT = ' 2013, {}'.format(PROJECT_AUTHOR)
PROJECT_URL = 'https://home-assistant.io/'
PROJECT_EMAIL = 'hello@home-assistant.io'
PROJECT_DESCRIPTION = ('Open-source home automation platform '
                       'running on Python 3.')
PROJECT_LONG_DESCRIPTION = ('Home Assistant is an open-source '
                            'home automation platform running on Python 3. '
                            'Track and control all devices at home and '
                            'automate control. '
                            'Installation in less than a minute.')
PROJECT_CLASSIFIERS = [
    'Intended Audience :: End Users/Desktop',
    'Intended Audience :: Developers',
    'License :: OSI Approved :: Apache Software License',
    'Operating System :: OS Independent',
    'Programming Language :: Python :: 3.4',
    'Topic :: Home Automation'
]

PROJECT_GITHUB_USERNAME = 'home-assistant'
PROJECT_GITHUB_REPOSITORY = 'home-assistant'

PYPI_URL = 'https://pypi.python.org/pypi/{}'.format(PROJECT_PACKAGE_NAME)
GITHUB_PATH = '{}/{}'.format(PROJECT_GITHUB_USERNAME,
                             PROJECT_GITHUB_REPOSITORY)
GITHUB_URL = 'https://github.com/{}'.format(GITHUB_PATH)

PLATFORM_FORMAT = '{}.{}'

# Can be used to specify a catch all when registering state or event listeners.
MATCH_ALL = '*'

# If no name is specified
DEVICE_DEFAULT_NAME = 'Unnamed Device'

WEEKDAYS = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']

SUN_EVENT_SUNSET = 'sunset'
SUN_EVENT_SUNRISE = 'sunrise'

# #### CONFIG ####
CONF_ABOVE = 'above'
CONF_ACCESS_TOKEN = 'access_token'
CONF_AFTER = 'after'
CONF_ALIAS = 'alias'
CONF_API_KEY = 'api_key'
CONF_AT = 'at'
CONF_AUTHENTICATION = 'authentication'
CONF_BASE = 'base'
CONF_BEFORE = 'before'
CONF_BELOW = 'below'
CONF_BINARY_SENSORS = 'binary_sensors'
CONF_BLACKLIST = 'blacklist'
CONF_BRIGHTNESS = 'brightness'
CONF_CODE = 'code'
CONF_COLOR_TEMP = 'color_temp'
CONF_COMMAND = 'command'
CONF_COMMAND_CLOSE = 'command_close'
CONF_COMMAND_OFF = 'command_off'
CONF_COMMAND_ON = 'command_on'
CONF_COMMAND_OPEN = 'command_open'
CONF_COMMAND_STATE = 'command_state'
CONF_COMMAND_STOP = 'command_stop'
CONF_CONDITION = 'condition'
CONF_COVERS = 'covers'
CONF_CURRENCY = 'currency'
CONF_CUSTOMIZE = 'customize'
CONF_CUSTOMIZE_DOMAIN = 'customize_domain'
CONF_CUSTOMIZE_GLOB = 'customize_glob'
CONF_DEVICE = 'device'
CONF_DEVICE_CLASS = 'device_class'
CONF_DEVICES = 'devices'
CONF_DISARM_AFTER_TRIGGER = 'disarm_after_trigger'
CONF_DISCOVERY = 'discovery'
CONF_DISPLAY_OPTIONS = 'display_options'
CONF_DOMAIN = 'domain'
CONF_DOMAINS = 'domains'
CONF_EFFECT = 'effect'
CONF_ELEVATION = 'elevation'
CONF_EMAIL = 'email'
CONF_ENTITIES = 'entities'
CONF_ENTITY_ID = 'entity_id'
CONF_ENTITY_NAMESPACE = 'entity_namespace'
CONF_EVENT = 'event'
CONF_EXCLUDE = 'exclude'
CONF_FILE_PATH = 'file_path'
CONF_FILENAME = 'filename'
CONF_FRIENDLY_NAME = 'friendly_name'
CONF_HEADERS = 'headers'
CONF_HOST = 'host'
CONF_HOSTS = 'hosts'
CONF_ICON = 'icon'
CONF_ICON_TEMPLATE = 'icon_template'
CONF_INCLUDE = 'include'
CONF_ID = 'id'
CONF_LATITUDE = 'latitude'
CONF_LONGITUDE = 'longitude'
CONF_MAC = 'mac'
CONF_METHOD = 'method'
CONF_MINIMUM = 'minimum'
CONF_MAXIMUM = 'maximum'
CONF_MONITORED_CONDITIONS = 'monitored_conditions'
CONF_MONITORED_VARIABLES = 'monitored_variables'
CONF_NAME = 'name'
CONF_OFFSET = 'offset'
CONF_OPTIMISTIC = 'optimistic'
CONF_PACKAGES = 'packages'
CONF_PASSWORD = 'password'
CONF_PATH = 'path'
CONF_PAYLOAD = 'payload'
CONF_PAYLOAD_OFF = 'payload_off'
CONF_PAYLOAD_ON = 'payload_on'
CONF_PENDING_TIME = 'pending_time'
CONF_PIN = 'pin'
CONF_PLATFORM = 'platform'
CONF_PORT = 'port'
CONF_PREFIX = 'prefix'
CONF_PROTOCOL = 'protocol'
CONF_PROXY_SSL = 'proxy_ssl'
CONF_QUOTE = 'quote'
CONF_RECIPIENT = 'recipient'
CONF_RESOURCE = 'resource'
CONF_RESOURCES = 'resources'
CONF_RGB = 'rgb'
CONF_SCAN_INTERVAL = 'scan_interval'
CONF_SENDER = 'sender'
CONF_SENSOR_CLASS = 'sensor_class'
CONF_SENSOR_TYPE = 'sensor_type'
CONF_SENSORS = 'sensors'
CONF_SLAVE = 'slave'
CONF_SSL = 'ssl'
CONF_STATE = 'state'
CONF_STRUCTURE = 'structure'
CONF_SWITCHES = 'switches'
CONF_TEMPERATURE_UNIT = 'temperature_unit'
CONF_TIME_ZONE = 'time_zone'
CONF_TIMEOUT = 'timeout'
CONF_TOKEN = 'token'
CONF_TRIGGER_TIME = 'trigger_time'
CONF_TYPE = 'type'
CONF_UNIT_OF_MEASUREMENT = 'unit_of_measurement'
CONF_UNIT_SYSTEM = 'unit_system'
CONF_URL = 'url'
CONF_USERNAME = 'username'
CONF_VALUE_TEMPLATE = 'value_template'
CONF_VERIFY_SSL = 'verify_ssl'
CONF_WEEKDAY = 'weekday'
CONF_WHITELIST = 'whitelist'
CONF_WHITELIST_EXTERNAL_DIRS = 'whitelist_external_dirs'
CONF_WHITE_VALUE = 'white_value'
CONF_XY = 'xy'
CONF_ZONE = 'zone'

# #### EVENTS ####
EVENT_HOMEASSISTANT_START = 'homeassistant_start'
EVENT_HOMEASSISTANT_STOP = 'homeassistant_stop'
EVENT_HOMEASSISTANT_CLOSE = 'homeassistant_close'
EVENT_STATE_CHANGED = 'state_changed'
EVENT_TIME_CHANGED = 'time_changed'
EVENT_CALL_SERVICE = 'call_service'
EVENT_SERVICE_EXECUTED = 'service_executed'
EVENT_PLATFORM_DISCOVERED = 'platform_discovered'
EVENT_COMPONENT_LOADED = 'component_loaded'
EVENT_SERVICE_REGISTERED = 'service_registered'
EVENT_SERVICE_REMOVED = 'service_removed'
EVENT_LOGBOOK_ENTRY = 'logbook_entry'

# #### STATES ####
STATE_ON = 'on'
STATE_OFF = 'off'
STATE_HOME = 'home'
STATE_NOT_HOME = 'not_home'
STATE_UNKNOWN = 'unknown'
STATE_OPEN = 'open'
STATE_CLOSED = 'closed'
STATE_PLAYING = 'playing'
STATE_PAUSED = 'paused'
STATE_IDLE = 'idle'
STATE_STANDBY = 'standby'
STATE_ALARM_DISARMED = 'disarmed'
STATE_ALARM_ARMED_HOME = 'armed_home'
STATE_ALARM_ARMED_AWAY = 'armed_away'
STATE_ALARM_PENDING = 'pending'
STATE_ALARM_TRIGGERED = 'triggered'
STATE_LOCKED = 'locked'
STATE_UNLOCKED = 'unlocked'
STATE_UNAVAILABLE = 'unavailable'
STATE_OK = 'ok'
STATE_PROBLEM = 'problem'

# #### STATE AND EVENT ATTRIBUTES ####
# Attribution
ATTR_ATTRIBUTION = 'attribution'

# Contains time-related attributes
ATTR_NOW = 'now'
ATTR_DATE = 'date'
ATTR_TIME = 'time'

# Contains domain, service for a SERVICE_CALL event
ATTR_DOMAIN = 'domain'
ATTR_SERVICE = 'service'
ATTR_SERVICE_DATA = 'service_data'

# Data for a SERVICE_EXECUTED event
ATTR_SERVICE_CALL_ID = 'service_call_id'

# Contains one string or a list of strings, each being an entity id
ATTR_ENTITY_ID = 'entity_id'

# String with a friendly name for the entity
ATTR_FRIENDLY_NAME = 'friendly_name'

# A picture to represent entity
ATTR_ENTITY_PICTURE = 'entity_picture'

# Icon to use in the frontend
ATTR_ICON = 'icon'

# The unit of measurement if applicable
ATTR_UNIT_OF_MEASUREMENT = 'unit_of_measurement'

CONF_UNIT_SYSTEM_METRIC = 'metric'  # type: str
CONF_UNIT_SYSTEM_IMPERIAL = 'imperial'  # type: str

# Temperature attribute
ATTR_TEMPERATURE = 'temperature'
TEMP_CELSIUS = '°C'
TEMP_FAHRENHEIT = '°F'

# Length units
LENGTH_CENTIMETERS = 'cm'  # type: str
LENGTH_METERS = 'm'  # type: str
LENGTH_KILOMETERS = 'km'  # type: str

LENGTH_INCHES = 'in'  # type: str
LENGTH_FEET = 'ft'  # type: str
LENGTH_YARD = 'yd'  # type: str
LENGTH_MILES = 'mi'  # type: str

# Volume units
VOLUME_LITERS = 'L'  # type: str
VOLUME_MILLILITERS = 'mL'  # type: str

VOLUME_GALLONS = 'gal'  # type: str
VOLUME_FLUID_OUNCE = 'fl. oz.'  # type: str

# Mass units
MASS_GRAMS = 'g'  # type: str
MASS_KILOGRAMS = 'kg'  # type: str

MASS_OUNCES = 'oz'  # type: str
MASS_POUNDS = 'lb'  # type: str

# Contains the information that is discovered
ATTR_DISCOVERED = 'discovered'

# Location of the device/sensor
ATTR_LOCATION = 'location'

ATTR_BATTERY_LEVEL = 'battery_level'
ATTR_WAKEUP = 'wake_up_interval'

# For devices which support a code attribute
ATTR_CODE = 'code'
ATTR_CODE_FORMAT = 'code_format'

# For devices which support an armed state
ATTR_ARMED = 'device_armed'

# For devices which support a locked state
ATTR_LOCKED = 'locked'

# For sensors that support 'tripping', eg. motion and door sensors
ATTR_TRIPPED = 'device_tripped'

# For sensors that support 'tripping' this holds the most recent
# time the device was tripped
ATTR_LAST_TRIP_TIME = 'last_tripped_time'

# For all entity's, this hold whether or not it should be hidden
ATTR_HIDDEN = 'hidden'

# Location of the entity
ATTR_LATITUDE = 'latitude'
ATTR_LONGITUDE = 'longitude'

# Accuracy of location in meters
ATTR_GPS_ACCURACY = 'gps_accuracy'

# If state is assumed
ATTR_ASSUMED_STATE = 'assumed_state'
ATTR_STATE = 'state'

ATTR_OPTION = 'option'

# Bitfield of supported component features for the entity
ATTR_SUPPORTED_FEATURES = 'supported_features'

# Class of device within its domain
ATTR_DEVICE_CLASS = 'device_class'

# #### SERVICES ####
SERVICE_HOMEASSISTANT_STOP = 'stop'
SERVICE_HOMEASSISTANT_RESTART = 'restart'

SERVICE_TURN_ON = 'turn_on'
SERVICE_TURN_OFF = 'turn_off'
SERVICE_TOGGLE = 'toggle'
SERVICE_RELOAD = 'reload'

SERVICE_VOLUME_UP = 'volume_up'
SERVICE_VOLUME_DOWN = 'volume_down'
SERVICE_VOLUME_MUTE = 'volume_mute'
SERVICE_VOLUME_SET = 'volume_set'
SERVICE_MEDIA_PLAY_PAUSE = 'media_play_pause'
SERVICE_MEDIA_PLAY = 'media_play'
SERVICE_MEDIA_PAUSE = 'media_pause'
SERVICE_MEDIA_STOP = 'media_stop'
SERVICE_MEDIA_NEXT_TRACK = 'media_next_track'
SERVICE_MEDIA_PREVIOUS_TRACK = 'media_previous_track'
SERVICE_MEDIA_SEEK = 'media_seek'
SERVICE_SHUFFLE_SET = 'shuffle_set'

SERVICE_ALARM_DISARM = 'alarm_disarm'
SERVICE_ALARM_ARM_HOME = 'alarm_arm_home'
SERVICE_ALARM_ARM_AWAY = 'alarm_arm_away'
SERVICE_ALARM_TRIGGER = 'alarm_trigger'

SERVICE_LOCK = 'lock'
SERVICE_UNLOCK = 'unlock'

SERVICE_OPEN = 'open'
SERVICE_CLOSE = 'close'

SERVICE_CLOSE_COVER = 'close_cover'
SERVICE_CLOSE_COVER_TILT = 'close_cover_tilt'
SERVICE_OPEN_COVER = 'open_cover'
SERVICE_OPEN_COVER_TILT = 'open_cover_tilt'
SERVICE_SET_COVER_POSITION = 'set_cover_position'
SERVICE_SET_COVER_TILT_POSITION = 'set_cover_tilt_position'
SERVICE_STOP_COVER = 'stop_cover'
SERVICE_STOP_COVER_TILT = 'stop_cover_tilt'

SERVICE_SELECT_OPTION = 'select_option'

# #### API / REMOTE ####
SERVER_PORT = 8123

URL_ROOT = '/'
URL_API = '/api/'
URL_API_STREAM = '/api/stream'
URL_API_CONFIG = '/api/config'
URL_API_DISCOVERY_INFO = '/api/discovery_info'
URL_API_STATES = '/api/states'
URL_API_STATES_ENTITY = '/api/states/{}'
URL_API_EVENTS = '/api/events'
URL_API_EVENTS_EVENT = '/api/events/{}'
URL_API_SERVICES = '/api/services'
URL_API_SERVICES_SERVICE = '/api/services/{}/{}'
URL_API_COMPONENTS = '/api/components'
URL_API_ERROR_LOG = '/api/error_log'
URL_API_LOG_OUT = '/api/log_out'
URL_API_TEMPLATE = '/api/template'

HTTP_OK = 200
HTTP_CREATED = 201
HTTP_MOVED_PERMANENTLY = 301
HTTP_BAD_REQUEST = 400
HTTP_UNAUTHORIZED = 401
HTTP_NOT_FOUND = 404
HTTP_METHOD_NOT_ALLOWED = 405
HTTP_UNPROCESSABLE_ENTITY = 422
HTTP_INTERNAL_SERVER_ERROR = 500

HTTP_BASIC_AUTHENTICATION = 'basic'
HTTP_DIGEST_AUTHENTICATION = 'digest'

HTTP_HEADER_HA_AUTH = 'X-HA-access'
HTTP_HEADER_ACCEPT_ENCODING = 'Accept-Encoding'
HTTP_HEADER_CONTENT_TYPE = 'Content-type'
HTTP_HEADER_CONTENT_ENCODING = 'Content-Encoding'
HTTP_HEADER_VARY = 'Vary'
HTTP_HEADER_CONTENT_LENGTH = 'Content-Length'
HTTP_HEADER_CACHE_CONTROL = 'Cache-Control'
HTTP_HEADER_EXPIRES = 'Expires'
HTTP_HEADER_ORIGIN = 'Origin'
HTTP_HEADER_X_REQUESTED_WITH = 'X-Requested-With'
HTTP_HEADER_ACCEPT = 'Accept'
HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN = 'Access-Control-Allow-Origin'
HTTP_HEADER_ACCESS_CONTROL_ALLOW_HEADERS = 'Access-Control-Allow-Headers'

ALLOWED_CORS_HEADERS = [HTTP_HEADER_ORIGIN, HTTP_HEADER_ACCEPT,
                        HTTP_HEADER_X_REQUESTED_WITH, HTTP_HEADER_CONTENT_TYPE,
                        HTTP_HEADER_HA_AUTH]

CONTENT_TYPE_JSON = 'application/json'
CONTENT_TYPE_MULTIPART = 'multipart/x-mixed-replace; boundary={}'
CONTENT_TYPE_TEXT_PLAIN = 'text/plain'

# The exit code to send to request a restart
RESTART_EXIT_CODE = 100

UNIT_NOT_RECOGNIZED_TEMPLATE = '{} is not a recognized {} unit.'  # type: str

LENGTH = 'length'  # type: str
MASS = 'mass'  # type: str
VOLUME = 'volume'  # type: str
TEMPERATURE = 'temperature'  # type: str
SPEED_MS = 'speed_ms'  # type: str
ILLUMINANCE = 'illuminance'  # type: str


text:
/**
 * Autogenerated by Thrift Compiler (0.9.1)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package org.apache.airavata.model.workspace;

import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;

import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SuppressWarnings("all") public class Group implements org.apache.thrift.TBase<Group, Group._Fields>, java.io.Serializable, Cloneable, Comparable<Group> {
  private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("Group");

  private static final org.apache.thrift.protocol.TField GROUP_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("groupName", org.apache.thrift.protocol.TType.STRING, (short)1);
  private static final org.apache.thrift.protocol.TField DESCRIPTION_FIELD_DESC = new org.apache.thrift.protocol.TField("description", org.apache.thrift.protocol.TType.STRING, (short)2);

  private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
  static {
    schemes.put(StandardScheme.class, new GroupStandardSchemeFactory());
    schemes.put(TupleScheme.class, new GroupTupleSchemeFactory());
  }

  private String groupName; // required
  private String description; // optional

  /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
  @SuppressWarnings("all") public enum _Fields implements org.apache.thrift.TFieldIdEnum {
    GROUP_NAME((short)1, "groupName"),
    DESCRIPTION((short)2, "description");

    private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();

    static {
      for (_Fields field : EnumSet.allOf(_Fields.class)) {
        byName.put(field.getFieldName(), field);
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, or null if its not found.
     */
    public static _Fields findByThriftId(int fieldId) {
      switch(fieldId) {
        case 1: // GROUP_NAME
          return GROUP_NAME;
        case 2: // DESCRIPTION
          return DESCRIPTION;
        default:
          return null;
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, throwing an exception
     * if it is not found.
     */
    public static _Fields findByThriftIdOrThrow(int fieldId) {
      _Fields fields = findByThriftId(fieldId);
      if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
      return fields;
    }

    /**
     * Find the _Fields constant that matches name, or null if its not found.
     */
    public static _Fields findByName(String name) {
      return byName.get(name);
    }

    private final short _thriftId;
    private final String _fieldName;

    _Fields(short thriftId, String fieldName) {
      _thriftId = thriftId;
      _fieldName = fieldName;
    }

    public short getThriftFieldId() {
      return _thriftId;
    }

    public String getFieldName() {
      return _fieldName;
    }
  }

  // isset id assignments
  private _Fields optionals[] = {_Fields.DESCRIPTION};
  public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
  static {
    Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
    tmpMap.put(_Fields.GROUP_NAME, new org.apache.thrift.meta_data.FieldMetaData("groupName", org.apache.thrift.TFieldRequirementType.REQUIRED,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
    tmpMap.put(_Fields.DESCRIPTION, new org.apache.thrift.meta_data.FieldMetaData("description", org.apache.thrift.TFieldRequirementType.OPTIONAL,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
    metaDataMap = Collections.unmodifiableMap(tmpMap);
    org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(Group.class, metaDataMap);
  }

  public Group() {
  }

  public Group(
    String groupName)
  {
    this();
    this.groupName = groupName;
  }

  /**
   * Performs a deep copy on <i>other</i>.
   */
  public Group(Group other) {
    if (other.isSetGroupName()) {
      this.groupName = other.groupName;
    }
    if (other.isSetDescription()) {
      this.description = other.description;
    }
  }

  public Group deepCopy() {
    return new Group(this);
  }

  @Override
  public void clear() {
    this.groupName = null;
    this.description = null;
  }

  public String getGroupName() {
    return this.groupName;
  }

  public void setGroupName(String groupName) {
    this.groupName = groupName;
  }

  public void unsetGroupName() {
    this.groupName = null;
  }

  /** Returns true if field groupName is set (has been assigned a value) and false otherwise */
  public boolean isSetGroupName() {
    return this.groupName != null;
  }

  public void setGroupNameIsSet(boolean value) {
    if (!value) {
      this.groupName = null;
    }
  }

  public String getDescription() {
    return this.description;
  }

  public void setDescription(String description) {
    this.description = description;
  }

  public void unsetDescription() {
    this.description = null;
  }

  /** Returns true if field description is set (has been assigned a value) and false otherwise */
  public boolean isSetDescription() {
    return this.description != null;
  }

  public void setDescriptionIsSet(boolean value) {
    if (!value) {
      this.description = null;
    }
  }

  public void setFieldValue(_Fields field, Object value) {
    switch (field) {
    case GROUP_NAME:
      if (value == null) {
        unsetGroupName();
      } else {
        setGroupName((String)value);
      }
      break;

    case DESCRIPTION:
      if (value == null) {
        unsetDescription();
      } else {
        setDescription((String)value);
      }
      break;

    }
  }

  public Object getFieldValue(_Fields field) {
    switch (field) {
    case GROUP_NAME:
      return getGroupName();

    case DESCRIPTION:
      return getDescription();

    }
    throw new IllegalStateException();
  }

  /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
  public boolean isSet(_Fields field) {
    if (field == null) {
      throw new IllegalArgumentException();
    }

    switch (field) {
    case GROUP_NAME:
      return isSetGroupName();
    case DESCRIPTION:
      return isSetDescription();
    }
    throw new IllegalStateException();
  }

  @Override
  public boolean equals(Object that) {
    if (that == null)
      return false;
    if (that instanceof Group)
      return this.equals((Group)that);
    return false;
  }

  public boolean equals(Group that) {
    if (that == null)
      return false;

    boolean this_present_groupName = true && this.isSetGroupName();
    boolean that_present_groupName = true && that.isSetGroupName();
    if (this_present_groupName || that_present_groupName) {
      if (!(this_present_groupName && that_present_groupName))
        return false;
      if (!this.groupName.equals(that.groupName))
        return false;
    }

    boolean this_present_description = true && this.isSetDescription();
    boolean that_present_description = true && that.isSetDescription();
    if (this_present_description || that_present_description) {
      if (!(this_present_description && that_present_description))
        return false;
      if (!this.description.equals(that.description))
        return false;
    }

    return true;
  }

  @Override
  public int hashCode() {
    return 0;
  }

  @Override
  public int compareTo(Group other) {
    if (!getClass().equals(other.getClass())) {
      return getClass().getName().compareTo(other.getClass().getName());
    }

    int lastComparison = 0;

    lastComparison = Boolean.valueOf(isSetGroupName()).compareTo(other.isSetGroupName());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetGroupName()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.groupName, other.groupName);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = Boolean.valueOf(isSetDescription()).compareTo(other.isSetDescription());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetDescription()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.description, other.description);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    return 0;
  }

  public _Fields fieldForId(int fieldId) {
    return _Fields.findByThriftId(fieldId);
  }

  public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
    schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
  }

  public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
    schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder("Group(");
    boolean first = true;

    sb.append("groupName:");
    if (this.groupName == null) {
      sb.append("null");
    } else {
      sb.append(this.groupName);
    }
    first = false;
    if (isSetDescription()) {
      if (!first) sb.append(", ");
      sb.append("description:");
      if (this.description == null) {
        sb.append("null");
      } else {
        sb.append(this.description);
      }
      first = false;
    }
    sb.append(")");
    return sb.toString();
  }

  public void validate() throws org.apache.thrift.TException {
    // check for required fields
    if (!isSetGroupName()) {
      throw new org.apache.thrift.protocol.TProtocolException("Required field 'groupName' is unset! Struct:" + toString());
    }

    // check for sub-struct validity
  }

  private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
    try {
      write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
    try {
      read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private static class GroupStandardSchemeFactory implements SchemeFactory {
    public GroupStandardScheme getScheme() {
      return new GroupStandardScheme();
    }
  }

  private static class GroupStandardScheme extends StandardScheme<Group> {

    public void read(org.apache.thrift.protocol.TProtocol iprot, Group struct) throws org.apache.thrift.TException {
      org.apache.thrift.protocol.TField schemeField;
      iprot.readStructBegin();
      while (true)
      {
        schemeField = iprot.readFieldBegin();
        if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
          break;
        }
        switch (schemeField.id) {
          case 1: // GROUP_NAME
            if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
              struct.groupName = iprot.readString();
              struct.setGroupNameIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          case 2: // DESCRIPTION
            if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
              struct.description = iprot.readString();
              struct.setDescriptionIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          default:
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
        }
        iprot.readFieldEnd();
      }
      iprot.readStructEnd();
      struct.validate();
    }

    public void write(org.apache.thrift.protocol.TProtocol oprot, Group struct) throws org.apache.thrift.TException {
      struct.validate();

      oprot.writeStructBegin(STRUCT_DESC);
      if (struct.groupName != null) {
        oprot.writeFieldBegin(GROUP_NAME_FIELD_DESC);
        oprot.writeString(struct.groupName);
        oprot.writeFieldEnd();
      }
      if (struct.description != null) {
        if (struct.isSetDescription()) {
          oprot.writeFieldBegin(DESCRIPTION_FIELD_DESC);
          oprot.writeString(struct.description);
          oprot.writeFieldEnd();
        }
      }
      oprot.writeFieldStop();
      oprot.writeStructEnd();
    }

  }

  private static class GroupTupleSchemeFactory implements SchemeFactory {
    public GroupTupleScheme getScheme() {
      return new GroupTupleScheme();
    }
  }

  private static class GroupTupleScheme extends TupleScheme<Group> {

    @Override
    public void write(org.apache.thrift.protocol.TProtocol prot, Group struct) throws org.apache.thrift.TException {
      TTupleProtocol oprot = (TTupleProtocol) prot;
      oprot.writeString(struct.groupName);
      BitSet optionals = new BitSet();
      if (struct.isSetDescription()) {
        optionals.set(0);
      }
      oprot.writeBitSet(optionals, 1);
      if (struct.isSetDescription()) {
        oprot.writeString(struct.description);
      }
    }

    @Override
    public void read(org.apache.thrift.protocol.TProtocol prot, Group struct) throws org.apache.thrift.TException {
      TTupleProtocol iprot = (TTupleProtocol) prot;
      struct.groupName = iprot.readString();
      struct.setGroupNameIsSet(true);
      BitSet incoming = iprot.readBitSet(1);
      if (incoming.get(0)) {
        struct.description = iprot.readString();
        struct.setDescriptionIsSet(true);
      }
    }
  }

}


text:
namespace arangodb::sepp {

struct Workload;
struct Server;

enum class ExecutionState {
  kStarting,
  kPreparing,
  kInitializing,
  kRunning,
  kStopped
};

struct Execution {
  Execution(Options const& options, std::shared_ptr<Workload> workload);
  ~Execution();
  void createThreads(Server& server);
  void joinThreads();
  Report run();
  [[nodiscard]] ExecutionState state(
      std::memory_order order = std::memory_order_relaxed) const noexcept;
  [[nodiscard]] std::uint32_t numThreads() const noexcept {
    return static_cast<std::uint32_t>(_threads.size());
  }

  void signalStartingThread() noexcept;
  void signalFinishedThread() noexcept;
  // stop execution (for example, because an error occurred somewhere)
  void stop() noexcept;
  // whether or not the execution was stopped
  bool stopped() const noexcept;

 private:
  void advanceStatusIfNotStopped(ExecutionState state) noexcept;
  void waitUntilAllThreadsAre(ThreadState state) const;

  void waitUntilRunning(ExecutionThread const& thread) const;
  void waitUntilFinished(ExecutionThread const& thread) const;
  static void waitUntilThreadStateIs(ExecutionThread const& thread,
                                     ThreadState expected);

  Report buildReport(double runtime);

  std::atomic<ExecutionState> _state;
  std::atomic<std::uint32_t> _activeThreads{0};
  Options const& _options;
  std::shared_ptr<Workload> _workload;
  std::vector<std::unique_ptr<ExecutionThread>> _threads;
};

}  // namespace arangodb::sepp


text:
var isstream = require('isstream')
  , _length = require('@request/length')

function length (req, options, done) {
  if (options.headers.get('transfer-encoding') === 'chunked' ||
      options.headers.get('content-length') !== undefined) {
    done()
    return
  }

  if (options.body && !options.multipart) {
    if (isstream(options.body)) {
      _length.async(options.body, done)
    }
    else {
      done(null, _length.sync(options.body))
    }
  }
  else if (req._src) {
    _length.async(req._src, done)
  }
  else if (options.multipart) {
    _length.multipart(options.body, done)
  }
  else {
    done(new Error('Content length not available'))
  }
}

module.exports = length


text:
describe EmsCluster do
  context("VMware") do
    before(:each) do
      @cluster = FactoryGirl.create(:ems_cluster)
      @host1 = FactoryGirl.create(:host, :ems_cluster => @cluster)
      @host2 = FactoryGirl.create(:host, :ems_cluster => @cluster)
      @rp1 = FactoryGirl.create(:resource_pool)
      @rp2 = FactoryGirl.create(:resource_pool)

      @cluster.with_relationship_type("ems_metadata") { @cluster.add_child @rp1 }
      @rp1.with_relationship_type("ems_metadata") { @rp1.add_child @rp2 }

      @vm1 = FactoryGirl.create(:vm_vmware, :host => @host1, :ems_cluster => @cluster)
      @vm1.with_relationship_type("ems_metadata") { @vm1.parent = @rp1 }
      @template1 = FactoryGirl.create(:template_vmware, :host => @host1, :ems_cluster => @cluster)

      @vm2 = FactoryGirl.create(:vm_vmware, :host => @host2, :ems_cluster => @cluster)
      @vm2.with_relationship_type("ems_metadata") { @vm2.parent = @rp2 }
      @template2 = FactoryGirl.create(:template_vmware, :host => @host2, :ems_cluster => @cluster)
    end

    it('#vms_and_templates')              { expect(@cluster.vms_and_templates).to              match_array [@vm1, @vm2, @template1, @template2] }
    it('#direct_vms_and_templates')       { expect(@cluster.direct_vms_and_templates).to       match_array [@vm1, @template1, @template2] }
    it('#vm_or_template_ids')             { expect(@cluster.vm_or_template_ids).to             match_array [@vm1.id, @vm2.id, @template1.id, @template2.id] }
    it('#direct_vm_or_template_ids')      { expect(@cluster.direct_vm_or_template_ids).to      match_array [@vm1.id, @template1.id, @template2.id] }
    it('#total_direct_vms_and_templates') { expect(@cluster.total_direct_vms_and_templates).to eq(3) }

    it('#vms')              { expect(@cluster.vms).to              match_array [@vm1, @vm2] }
    it('#direct_vms')       { expect(@cluster.direct_vms).to       match_array [@vm1] }
    it('#vm_ids')           { expect(@cluster.vm_ids).to           match_array [@vm1.id, @vm2.id] }
    it('#direct_vm_ids')    { expect(@cluster.direct_vm_ids).to    match_array [@vm1.id] }
    it('#total_direct_vms') { expect(@cluster.total_direct_vms).to eq(1) }

    it('#miq_templates')              { expect(@cluster.miq_templates).to              match_array [@template1, @template2] }
    it('#direct_miq_templates')       { expect(@cluster.direct_miq_templates).to       match_array [@template1, @template2] }
    it('#miq_template_ids')           { expect(@cluster.miq_template_ids).to           match_array [@template1.id, @template2.id] }
    it('#direct_miq_template_ids')    { expect(@cluster.direct_miq_template_ids).to    match_array [@template1.id, @template2.id] }
    it('#total_direct_miq_templates') { expect(@cluster.total_direct_miq_templates).to eq(2) }

    it('#all_vms_and_templates')   { expect(@cluster.all_vms_and_templates).to   match_array [@vm1, @vm2, @template1, @template2] }
    it('#all_vm_or_template_ids')  { expect(@cluster.all_vm_or_template_ids).to  match_array [@vm1.id, @vm2.id, @template1.id, @template2.id] }
    it('#total_vms_and_templates') { expect(@cluster.total_vms_and_templates).to eq(4) }

    it('#all_vms')    { expect(@cluster.all_vms).to    match_array [@vm1, @vm2] }
    it('#all_vm_ids') { expect(@cluster.all_vm_ids).to match_array [@vm1.id, @vm2.id] }
    it('#total_vms')  { expect(@cluster.total_vms).to eq(2) }

    it('#all_miq_templates')    { expect(@cluster.all_miq_templates).to    match_array [@template1, @template2] }
    it('#all_miq_template_ids') { expect(@cluster.all_miq_template_ids).to match_array [@template1.id, @template2.id] }
    it('#total_miq_templates')  { expect(@cluster.total_miq_templates).to eq(2) }

    it('ResourcePool#v_direct_vms') { expect(@rp1.v_direct_vms).to eq(1) }
    it('ResourcePool#v_total_vms')  { expect(@rp1.v_total_vms).to eq(2) }

    it('ResourcePool#v_direct_miq_templates') { expect(@rp1.v_direct_vms).to eq(1) }
    it('ResourcePool#v_total_miq_templates')  { expect(@rp1.v_total_vms).to eq(2) }
  end

  context("RedHat") do
    before(:each) do
      @cluster = FactoryGirl.create(:ems_cluster)
      @host1 = FactoryGirl.create(:host, :ems_cluster => @cluster)
      @host2 = FactoryGirl.create(:host, :ems_cluster => @cluster)
      @rp1 = FactoryGirl.create(:resource_pool)
      @rp2 = FactoryGirl.create(:resource_pool)

      @cluster.with_relationship_type("ems_metadata") { @cluster.add_child @rp1 }
      @rp1.with_relationship_type("ems_metadata") { @rp1.add_child @rp2 }

      @vm1 = FactoryGirl.create(:vm_redhat, :host => @host1, :ems_cluster => @cluster)
      @vm1.with_relationship_type("ems_metadata") { @vm1.parent = @rp1 }

      @vm2 = FactoryGirl.create(:vm_redhat, :host => @host2, :ems_cluster => @cluster)
      @vm2.with_relationship_type("ems_metadata") { @vm2.parent = @rp2 }

      @template1 = FactoryGirl.create(:template_redhat, :ems_cluster => @cluster)
      @template2 = FactoryGirl.create(:template_redhat, :ems_cluster => @cluster)
    end

    it('#vms_and_templates')              { expect(@cluster.vms_and_templates).to              match_array [@vm1, @vm2, @template1, @template2] }
    it('#direct_vms_and_templates')       { expect(@cluster.direct_vms_and_templates).to       match_array [@vm1, @template1, @template2] }
    it('#vm_or_template_ids')             { expect(@cluster.vm_or_template_ids).to             match_array [@vm1.id, @vm2.id, @template1.id, @template2.id] }
    it('#direct_vm_or_template_ids')      { expect(@cluster.direct_vm_or_template_ids).to      match_array [@vm1.id, @template1.id, @template2.id] }
    it('#total_direct_vms_and_templates') { expect(@cluster.total_direct_vms_and_templates).to eq(3) }

    it('#vms')              { expect(@cluster.vms).to              match_array [@vm1, @vm2] }
    it('#direct_vms')       { expect(@cluster.direct_vms).to       match_array [@vm1] }
    it('#vm_ids')           { expect(@cluster.vm_ids).to           match_array [@vm1.id, @vm2.id] }
    it('#direct_vm_ids')    { expect(@cluster.direct_vm_ids).to    match_array [@vm1.id] }
    it('#total_direct_vms') { expect(@cluster.total_direct_vms).to eq(1) }

    it('#miq_templates')              { expect(@cluster.miq_templates).to              match_array [@template1, @template2] }
    it('#direct_miq_templates')       { expect(@cluster.direct_miq_templates).to       match_array [@template1, @template2] }
    it('#miq_template_ids')           { expect(@cluster.miq_template_ids).to           match_array [@template1.id, @template2.id] }
    it('#direct_miq_template_ids')    { expect(@cluster.direct_miq_template_ids).to    match_array [@template1.id, @template2.id] }
    it('#total_direct_miq_templates') { expect(@cluster.total_direct_miq_templates).to eq(2) }

    it('#all_vms_and_templates')   { expect(@cluster.all_vms_and_templates).to   match_array [@vm1, @vm2, @template1, @template2] }
    it('#all_vm_or_template_ids')  { expect(@cluster.all_vm_or_template_ids).to  match_array [@vm1.id, @vm2.id, @template1.id, @template2.id] }
    it('#total_vms_and_templates') { expect(@cluster.total_vms_and_templates).to eq(4) }

    it('#all_vms')    { expect(@cluster.all_vms).to    match_array [@vm1, @vm2] }
    it('#all_vm_ids') { expect(@cluster.all_vm_ids).to match_array [@vm1.id, @vm2.id] }
    it('#total_vms')  { expect(@cluster.total_vms).to eq(2) }

    it('#all_miq_templates')    { expect(@cluster.all_miq_templates).to    match_array [@template1, @template2] }
    it('#all_miq_template_ids') { expect(@cluster.all_miq_template_ids).to match_array [@template1.id, @template2.id] }
    it('#total_miq_templates')  { expect(@cluster.total_miq_templates).to eq(2) }
  end

  it "#save_drift_state" do
    # TODO: Beef up with more data
    cluster = FactoryGirl.create(:ems_cluster)
    cluster.save_drift_state

    expect(cluster.drift_states.size).to eq(1)
    expect(DriftState.count).to eq(1)

    expect(cluster.drift_states.first.data).to eq({
      :aggregate_cpu_speed       => 0,
      :aggregate_cpu_total_cores => 0,
      :aggregate_memory          => 0,
      :aggregate_physical_cpus   => 0,
      :aggregate_vm_cpus         => 0,
      :aggregate_vm_memory       => 0,
      :class                     => "EmsCluster",
      :id                        => cluster.id,
      :name                      => cluster.name,
      :vms                       => [],
      :miq_templates             => [],
      :hosts                     => [],
    })
  end

  context("#perf_capture_enabled_host_ids=") do
    before do
      @miq_region = FactoryGirl.create(:miq_region, :region => 1)
      allow(MiqRegion).to receive(:my_region).and_return(@miq_region)
      @cluster = FactoryGirl.create(:ems_cluster)
      @host1 = FactoryGirl.create(:host, :ems_cluster => @cluster)
      @host2 = FactoryGirl.create(:host, :ems_cluster => @cluster)
    end

    it "Initially Performance capture for cluster and its hosts should not be set" do
      expect(@cluster.perf_capture_enabled).to eq(false)
      expect(@host1.perf_capture_enabled).to eq(false)
      expect(@host2.perf_capture_enabled).to eq(false)
    end

    it "Performance capture for cluster and its hosts should be set" do
      @cluster.perf_capture_enabled_host_ids = [@host1.id, @host2.id]
      expect(@cluster.perf_capture_enabled).to eq(true)
      expect(@host1.perf_capture_enabled).to eq(true)
      expect(@host2.perf_capture_enabled).to eq(true)
    end

    it "Performance capture for cluster and only 1 hosts should be set" do
      @cluster.perf_capture_enabled_host_ids = [@host2.id]
      expect(@cluster.perf_capture_enabled).to eq(true)
      expect(@host1.perf_capture_enabled).to eq(false)
      expect(@host2.perf_capture_enabled).to eq(true)
    end

    it "Performance capture for cluster and its hosts should get unset" do
      @cluster.perf_capture_enabled_host_ids = [@host2.id]
      @cluster.perf_capture_enabled_host_ids = []
      expect(@cluster.perf_capture_enabled).to eq(false)
      expect(@host1.perf_capture_enabled).to eq(false)
      expect(@host2.perf_capture_enabled).to eq(false)
    end
  end

  context "#node_types" do
    before(:each) do
      @ems1 = FactoryGirl.create(:ems_vmware)
      @ems2 = FactoryGirl.create(:ems_openstack_infra)
    end

    it "returns :mixed_clusters when there are both openstack & non-openstack clusters in db" do
      FactoryGirl.create(:ems_cluster, :ems_id => @ems1.id)
      FactoryGirl.create(:ems_cluster, :ems_id => @ems2.id)

      result = EmsCluster.node_types
      expect(result).to eq(:mixed_clusters)
    end

    it "returns :openstack when there are only openstack clusters in db" do
      FactoryGirl.create(:ems_cluster, :ems_id => @ems2.id)
      result = EmsCluster.node_types
      expect(result).to eq(:openstack)
    end

    it "returns :non_openstack when there are non-openstack clusters in db" do
      FactoryGirl.create(:ems_cluster, :ems_id => @ems1.id)
      result = EmsCluster.node_types
      expect(result).to eq(:non_openstack)
    end
  end

  context "#openstack_cluster?" do
    it "returns true for openstack cluster" do
      ems = FactoryGirl.create(:ems_openstack_infra)
      cluster = FactoryGirl.create(:ems_cluster, :ems_id => ems.id)

      result = cluster.openstack_cluster?
      expect(result).to be_truthy
    end

    it "returns false for non-openstack cluster" do
      ems = FactoryGirl.create(:ems_vmware)
      cluster = FactoryGirl.create(:ems_cluster, :ems_id => ems.id)
      result = cluster.openstack_cluster?
      expect(result).to be_falsey
    end
  end

  context "#tenant_identity" do
    let(:admin)    { FactoryGirl.create(:user_with_group, :userid => "admin") }
    let(:tenant)   { FactoryGirl.create(:tenant) }
    let(:ems)      { FactoryGirl.create(:ext_management_system, :tenant => tenant) }
    before         { admin }

    subject        { @cluster.tenant_identity }

    it "has tenant from provider" do
      @cluster = FactoryGirl.create(:ems_cluster, :ems_id => ems.id)

      expect(subject).to                eq(admin)
      expect(subject.current_group).to  eq(ems.tenant.default_miq_group)
      expect(subject.current_tenant).to eq(ems.tenant)
    end

    it "without a provider, has tenant from root tenant" do
      @cluster = FactoryGirl.create(:ems_cluster)

      expect(subject).to                eq(admin)
      expect(subject.current_group).to  eq(Tenant.root_tenant.default_miq_group)
      expect(subject.current_tenant).to eq(Tenant.root_tenant)
    end
  end
end


text:
<?php
// Including database connections
// error_reporting(0);
require_once 'database_connections.php';
// Fetching the updated data & storin in new variables
$data = json_decode(file_get_contents("php://input"));
// Escaping special characters from updated data
$id = mysqli_real_escape_string($con, $data->id);
$status = 'Admin';
$fullname = mysqli_real_escape_string($con, $data->fullname);

// mysqli query to insert the updated data
$query = "UPDATE users SET level='$status' WHERE id=$id";
if($response = mysqli_query($con, $query))
{
     echo true ;
}

// if unable to update the profile, tell the user
else{
     echo  false;
}

?>


text:
namespace Microsoft.Azure.Management.Subscription.Models
{
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// The list of aliases.
    /// </summary>
    public partial class SubscriptionAliasListResult
    {
        /// <summary>
        /// Initializes a new instance of the SubscriptionAliasListResult
        /// class.
        /// </summary>
        public SubscriptionAliasListResult()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the SubscriptionAliasListResult
        /// class.
        /// </summary>
        /// <param name="value">The list of alias.</param>
        /// <param name="nextLink">The link (url) to the next page of
        /// results.</param>
        public SubscriptionAliasListResult(IList<SubscriptionAliasResponse> value = default(IList<SubscriptionAliasResponse>), string nextLink = default(string))
        {
            Value = value;
            NextLink = nextLink;
            CustomInit();
        }

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

        /// <summary>
        /// Gets the list of alias.
        /// </summary>
        [JsonProperty(PropertyName = "value")]
        public IList<SubscriptionAliasResponse> Value { get; private set; }

        /// <summary>
        /// Gets the link (url) to the next page of results.
        /// </summary>
        [JsonProperty(PropertyName = "nextLink")]
        public string NextLink { get; private set; }

    }
}


text:
$(function() {
    var table_search = $('#table_search').DataTable({
        "iDisplayLength": 10,
        "aLengthMenu": [10, 25, 50],
        "sPaginationType": "full_numbers",
        "bProcessing": true,
        "bDestroy": true,
        "bServerSide": true,
        "sAjaxSource": base_url + "visita/paginate",
        "sServerMethod": "POST",
        "columns": [
            { "data": "codi_vis" },
            { "data": "fech_vis_d" },
            { "data": "visi_vis" },
            { "data": "tipo_vis" },
            { "data": "docu_vis" },
            { "data": "enti_vis" },
            { "data": "moti_vis" },
            { "data": "sede_vis" },
            { "data": "empl_vis" },
            { "data": "ofic_vis" },
            { "data": "ingr_vis_d" },
            { "data": "sali_vis_d" },
            { "data": "estado" },
            { "data": "opciones" }
        ],
        "bPaginate": true,
        "bFilter": true,
        "bSort": false,
        "displayLength": 10
    });

    jQuery.validator.addMethod("validDate", function(value, element) {
        return this.optional(element) || moment(value,"YYYY-MM-DD").isValid();
    }, "Por favor, ingrese una fecha válida en el formato YYYY-MM-DD");

    $('input[name="fech_vis"]').parent().datetimepicker({
        locale: 'es',
        format: 'YYYY-MM-DD'
    });

    $('input[name="ingr_vis"]').parent().datetimepicker({
        locale: 'es',
        format: 'hh:mm A'
    });

    $('input[name="sali_vis"]').parent().datetimepicker({
        locale: 'es',
        format: 'hh:mm A'
    });

    $('#form_vis :input[name="apel_vis"]').keyup(function() {
        $(this).val($(this).val().toUpperCase());
    });

    $('#form_vis :input[name="nomb_vis"]').keyup(function() {
        $(this).val($(this).val().toUpperCase());
    });

    var $form_vis = $('#form_vis');

    var isDestroyable = false;

    $(document).on('click', '#btn_visita', function () {
        $("#modal_vis_lbl").html('Nueva visita');

        $form_vis.get(0).reset();

        $('#form_vis :input[name="tipo_vis"]').val("D.N.I.");
        $('#form_vis :input[name="fech_vis"]').val(moment().format('YYYY-MM-DD'));
        $('#form_vis :input[name="ingr_vis"]').val(moment().format('hh:mm A'));
        $('[name="ofic_vis"]').val($('[name="empl_vis"] option:selected').data("ofic"));

        $form_vis.attr("action", base_url+"visita/save");

        $form_vis.submit(function(e) {
                $("#submit_vis").html(' Verificando...');
                $("#submit_vis").prop('disabled', true);
                if (!validator_vis.form()) {
                    $("#submit_vis").html('Guardar');
                    $("#submit_vis").prop('disabled', false);
                    return;
                }
        });

        if (isDestroyable) {
            validator_vis.destroy();
        }

        validator_vis = $form_vis.validate({
            rules: {
                fech_vis: {
                    required: true,
                    validDate: true
                },
                apel_vis: {
                    required: true,
                },
                nomb_vis: {
                    required: true,
                },
                tipo_vis: {
                    required: true,
                },
                docu_vis: {
                    required: true,
                },
                enti_vis: {
                    required: true,
                },
                moti_vis: {
                    required: true,
                },
                sede_vis: {
                    required: true,
                },
                empl_vis: {
                    required: true,
                },
                ofic_vis: {
                    required: true,
                },
                ingr_vis: {
                    required: true,
                },
            },
            highlight: function(element) {
                $(element).closest('.form-control').parent().removeClass('has-success').addClass('has-error');
            },
            unhighlight: function(element) {
                $(element).closest('.form-control').parent().removeClass('has-error').addClass('has-success');
            },
            errorPlacement: function(error, element) {
                $(element).closest('.form-group').append(error);
            }
        });

        $("label.error").hide();
        $(".error").removeClass("error");
        $("label.success").hide();
        $(".success").removeClass("success");
        isDestroyable = true;

        $("#modal_vis").modal();
    });

    $(document).on('click', '#table_search button.btn-modificar', function () {

        var tr = $(this).parent().closest('tr');
        var row = table_search.row(tr);
        var data = row.data();

        $form_vis.get(0).reset();

        //$('#form_vis select[name="codi_gpa"] option[value="'+data.codi_gpa+'"]').prop("selected", true);
        $('#form_vis :input[name="codi_vis"]').val(data.codi_vis);
        $('#form_vis :input[name="fech_vis"]').val(data.fech_vis);
        $('#form_vis :input[name="apel_vis"]').val(data.apel_vis);
        $('#form_vis :input[name="nomb_vis"]').val(data.nomb_vis);
        $('#form_vis select[name="tipo_vis"] option[value="'+data.tipo_vis+'"]').prop("selected", true);
        $('#form_vis :input[name="docu_vis"]').val(data.docu_vis);
        $('#form_vis :input[name="enti_vis"]').val(data.enti_vis);
        $('#form_vis :input[name="moti_vis"]').val(data.moti_vis);
        $('#form_vis select[name="sede_vis"] option[value="'+data.sede_vis+'"]').prop("selected", true);
        $('#form_vis select[name="empl_vis"] option[value="'+data.empl_vis+'"]').prop("selected", true);
        $('[name="ofic_vis"]').val($('[name="empl_vis"] option:selected').data("ofic"));
        $('#form_vis select[name="ofic_vis"] option[value="'+data.ofic_vis+'"]').prop("selected", true);
        $('#form_vis :input[name="ingr_vis"]').val(moment(data.ingr_vis, 'HH:mm').format('hh:mm A'));
        $('#form_vis :input[name="sali_vis"]').val((data.sali_vis_d != "-") ? moment(data.sali_vis, 'HH:mm').format('hh:mm A') : "");

        $("#modal_vis_lbl").html("Modificar Visita");

        $.removeData($form_vis.get(0),'validator');

        $form_vis.attr("action", base_url+"visita/update");

        $form_vis.submit(function(e) {
            if (!validator_vis.form()) {
                return;
            } else {
                $("#submit_vis").html(' Verificando...');
                $("#submit_vis").prop('disabled', true);
            }
        });

        if (isDestroyable) {
            validator_vis.destroy();
        }

        validator_vis = $form_vis.validate({
            rules: {
                fech_vis: {
                    required: true,
                    validDate: true
                },
                apel_vis: {
                    required: true,
                },
                nomb_vis: {
                    required: true,
                },
                tipo_vis: {
                    required: true,
                },
                docu_vis: {
                    required: true,
                },
                enti_vis: {
                    required: true,
                },
                moti_vis: {
                    required: true,
                },
                sede_vis: {
                    required: true,
                },
                empl_vis: {
                    required: true,
                },
                ofic_vis: {
                    required: true,
                },
                ingr_vis: {
                    required: true,
                },
            },
            highlight: function(element) {
                $(element).closest('.form-control').parent().removeClass('has-success').addClass('has-error');
            },
            unhighlight: function(element) {
                $(element).closest('.form-control').parent().removeClass('has-error').addClass('has-success');
            },
            errorPlacement: function(error, element) {
                $(element).closest('.form-group').append(error);
            }
        });

        $(".has-error").removeClass("has-error");
        $(".has-success").removeClass("has-success");
        isDestroyable = true;

        $("#modal_vis").modal();
    });

    $(document).on('submit', '.habilitar_vis', function () {
        return confirm("¿Está seguro de que desea habilitar Visita?");
    });

    $(document).on('submit', '.deshabilitar_vis', function () {
        return confirm("¿Está seguro de que desea deshabilitar Visita?");
    });

    $(document).on('submit', '.eliminar_vis', function () {
        return confirm("¿Está seguro de que desea eliminar Visita?");
    });

    $(document).on('click', '#btn_link', function () {
        var clipboard = new Clipboard('.btn-copiar');
        $("#modal_link").modal();
    });

    $(document).on('click', '.btn-enlace', function () {
        window.open($(this).parent().parent().find('[name="link"]').val(), "VISITAS DRAL", "width=490,height=500");
    });

    $('[name="empl_vis"]').on('change', function () {
        $('[name="ofic_vis"]').val($('[name="empl_vis"] option:selected').data("ofic"));
    });
});


text:
using System.Collections.Generic;
using System.IO;

namespace FileWatcher.Sources
{
    public interface ISourceFolder
    {
        string Folder { get; set; }

        FileSystemEventHandler Handler { get; set; }

        IEnumerable<string> GetFiles();
    }
}


text:
package metropolia.minhtn.chatapplication.service;

/**
 * Created by nmt19 on 5/1/2016.
 */
public interface MessageObserver {
    void refresh();
}