text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.Diagnostics;

namespace System.Linq
{
    /// <summary>
    /// A lightweight hash set.
    /// </summary>
    /// <typeparam name="TElement">The type of the set's items.</typeparam>
    internal sealed class Set<TElement>
    {
        /// <summary>
        /// The comparer used to hash and compare items in the set.
        /// </summary>
        private readonly IEqualityComparer<TElement> _comparer;

        /// <summary>
        /// The hash buckets, which are used to index into the slots.
        /// </summary>
        private int[] _buckets;

        /// <summary>
        /// The slots, each of which store an item and its hash code.
        /// </summary>
        private Slot[] _slots;

        /// <summary>
        /// The number of items in this set.
        /// </summary>
        private int _count;

#if DEBUG
        /// <summary>
        /// Whether <see cref="Remove"/> has been called on this set.
        /// </summary>
        /// <remarks>
        /// When <see cref="Remove"/> runs in debug builds, this flag is set to <c>true</c>.
        /// Other methods assert that this flag is <c>false</c> in debug builds, because
        /// they make optimizations that may not be correct if <see cref="Remove"/> is called
        /// beforehand.
        /// </remarks>
        private bool _haveRemoved;
#endif

        /// <summary>
        /// Constructs a set that compares items with the specified comparer.
        /// </summary>
        /// <param name="comparer">
        /// The comparer. If this is <c>null</c>, it defaults to <see cref="EqualityComparer{TElement}.Default"/>.
        /// </param>
        public Set(IEqualityComparer<TElement> comparer)
        {
            _comparer = comparer ?? EqualityComparer<TElement>.Default;
            _buckets = new int[7];
            _slots = new Slot[7];
        }

        /// <summary>
        /// Attempts to add an item to this set.
        /// </summary>
        /// <param name="value">The item to add.</param>
        /// <returns>
        /// <c>true</c> if the item was not in the set; otherwise, <c>false</c>.
        /// </returns>
        public bool Add(TElement value)
        {
#if DEBUG
            Debug.Assert(!_haveRemoved, "This class is optimised for never calling Add after Remove. If your changes need to do so, undo that optimization.");
#endif
            int hashCode = InternalGetHashCode(value);
            for (int i = _buckets[hashCode % _buckets.Length] - 1; i >= 0; i = _slots[i]._next)
            {
                if (_slots[i]._hashCode == hashCode && _comparer.Equals(_slots[i]._value, value))
                {
                    return false;
                }
            }

            if (_count == _slots.Length)
            {
                Resize();
            }

            int index = _count;
            _count++;
            int bucket = hashCode % _buckets.Length;
            _slots[index]._hashCode = hashCode;
            _slots[index]._value = value;
            _slots[index]._next = _buckets[bucket] - 1;
            _buckets[bucket] = index + 1;
            return true;
        }

        /// <summary>
        /// Attempts to remove an item from this set.
        /// </summary>
        /// <param name="value">The item to remove.</param>
        /// <returns>
        /// <c>true</c> if the item was in the set; otherwise, <c>false</c>.
        /// </returns>
        public bool Remove(TElement value)
        {
#if DEBUG
            _haveRemoved = true;
#endif
            int hashCode = InternalGetHashCode(value);
            int bucket = hashCode % _buckets.Length;
            int last = -1;
            for (int i = _buckets[bucket] - 1; i >= 0; last = i, i = _slots[i]._next)
            {
                if (_slots[i]._hashCode == hashCode && _comparer.Equals(_slots[i]._value, value))
                {
                    if (last < 0)
                    {
                        _buckets[bucket] = _slots[i]._next + 1;
                    }
                    else
                    {
                        _slots[last]._next = _slots[i]._next;
                    }

                    _slots[i]._hashCode = -1;
                    _slots[i]._value = default(TElement);
                    _slots[i]._next = -1;
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// Expands the capacity of this set to double the current capacity, plus one.
        /// </summary>
        private void Resize()
        {
            int newSize = checked((_count * 2) + 1);
            int[] newBuckets = new int[newSize];
            Slot[] newSlots = new Slot[newSize];
            Array.Copy(_slots, 0, newSlots, 0, _count);
            for (int i = 0; i < _count; i++)
            {
                int bucket = newSlots[i]._hashCode % newSize;
                newSlots[i]._next = newBuckets[bucket] - 1;
                newBuckets[bucket] = i + 1;
            }

            _buckets = newBuckets;
            _slots = newSlots;
        }

        /// <summary>
        /// Creates an array from the items in this set.
        /// </summary>
        /// <returns>An array of the items in this set.</returns>
        public TElement[] ToArray()
        {
#if DEBUG
            Debug.Assert(!_haveRemoved, "Optimised ToArray cannot be called if Remove has been called.");
#endif
            TElement[] array = new TElement[_count];
            for (int i = 0; i != array.Length; ++i)
            {
                array[i] = _slots[i]._value;
            }

            return array;
        }

        /// <summary>
        /// Creates a list from the items in this set.
        /// </summary>
        /// <returns>A list of the items in this set.</returns>
        public List<TElement> ToList()
        {
#if DEBUG
            Debug.Assert(!_haveRemoved, "Optimised ToList cannot be called if Remove has been called.");
#endif
            int count = _count;
            List<TElement> list = new List<TElement>(count);
            for (int i = 0; i != count; ++i)
            {
                list.Add(_slots[i]._value);
            }

            return list;
        }

        /// <summary>
        /// The number of items in this set.
        /// </summary>
        public int Count => _count;

        /// <summary>
        /// Unions this set with an enumerable.
        /// </summary>
        /// <param name="other">The enumerable.</param>
        public void UnionWith(IEnumerable<TElement> other)
        {
            Debug.Assert(other != null);

            foreach (TElement item in other)
            {
                Add(item);
            }
        }

        /// <summary>
        /// Gets the hash code of the provided value with its sign bit zeroed out, so that modulo has a positive result.
        /// </summary>
        /// <param name="value">The value to hash.</param>
        /// <returns>The lower 31 bits of the value's hash code.</returns>
        private int InternalGetHashCode(TElement value)
        {
            // Handle comparer implementations that throw when passed null
            return (value == null) ? 0 : _comparer.GetHashCode(value) & 0x7FFFFFFF;
        }

        /// <summary>
        /// An entry in the hash set.
        /// </summary>
        internal struct Slot
        {
            /// <summary>
            /// The hash code of the item.
            /// </summary>
            internal int _hashCode;

            /// <summary>
            /// In the case of a hash collision, the index of the next slot to probe.
            /// </summary>
            internal int _next;

            /// <summary>
            /// The item held by this slot.
            /// </summary>
            internal TElement _value;
        }
    }
}


text:
using System;
using Gtk;
using Cairo;
using Mono.Unix;

using Hyena.Gui;
using Hyena.Data.Gui;
using Hyena.Data.Gui.Accessibility;
using Banshee.Gui;

using Banshee.Streaming;
using Banshee.MediaEngine;
using Banshee.ServiceStack;

namespace Banshee.Collection.Gui
{
    class ColumnCellStatusIndicatorAccessible : ColumnCellAccessible, Atk.ImageImplementor
    {
        private string image_description;

        public ColumnCellStatusIndicatorAccessible (object bound_object, ColumnCellStatusIndicator cell, ICellAccessibleParent parent) : base (bound_object, cell as ColumnCell, parent)
        {
            image_description = cell.GetTextAlternative (bound_object);
        }

        public override void Redrawn ()
        {
            string new_image_description = cell.GetTextAlternative (bound_object);

            if (image_description != new_image_description)
                GLib.Signal.Emit (this, "visible-data-changed");

            image_description = new_image_description;
        }

        public string ImageLocale { get { return null; } }

        public bool SetImageDescription (string description)
        {
            return false;
        }

        public void GetImageSize (out int width, out int height)
        {
            if (!String.IsNullOrEmpty (cell.GetTextAlternative (bound_object)))
                width = height = 16;
            else
                width = height = Int32.MinValue;
        }

        public string ImageDescription {
            get {
                return image_description;
            }
        }

        public void GetImagePosition (out int x, out int y, Atk.CoordType coordType)
        {
            if (!String.IsNullOrEmpty (cell.GetTextAlternative (bound_object))) {
                GetPosition (out x, out y, coordType);
                x += 4;
                y += 4;
            } else {
                x = y = Int32.MinValue;
            }
        }
    }

    public class ColumnCellStatusIndicator : ColumnCell, ISizeRequestCell
    {
        const int padding = 2;

        protected enum Icon : int {
            Playing,
            Paused,
            Error,
            Protected
        }

        private string [] status_names;
        protected string [] StatusNames {
            get { return status_names; }
        }

        private int pixbuf_size = 16;
        protected virtual int PixbufSize {
            get { return pixbuf_size; }
            set { pixbuf_size = value; }
        }

        private int pixbuf_spacing = 4;
        protected virtual int PixbufSpacing {
            get { return pixbuf_spacing; }
            set { pixbuf_spacing = value; }
        }

        private Gdk.Pixbuf [] pixbufs;
        protected Gdk.Pixbuf [] Pixbufs {
            get { return pixbufs; }
        }

        public ColumnCellStatusIndicator (string property) : this (property, true)
        {
        }

        public ColumnCellStatusIndicator (string property, bool expand) : base (property, expand)
        {
            LoadPixbufs ();
            RestrictSize = true;
        }

        public bool RestrictSize { get; set; }

        public void GetWidthRange (Pango.Layout layout, out int min_width, out int max_width)
        {
            min_width = max_width = pixbuf_size + 2 * padding;
        }

        public override Atk.Object GetAccessible (ICellAccessibleParent parent)
        {
            return new ColumnCellStatusIndicatorAccessible (BoundObject, this, parent);
        }

        public override string GetTextAlternative (object obj)
        {
            var track = obj as TrackInfo;
            if (track == null)
                return "";

            int icon_index = GetIconIndex (track);

            if ((icon_index < 0) || (icon_index >= status_names.Length))
                return "";
            else
                return status_names[icon_index];
        }

        protected virtual int PixbufCount {
            get { return 4; }
        }

        protected virtual int GetIconIndex (TrackInfo track)
        {
            int icon_index = -1;

            if (track.PlaybackError != StreamPlaybackError.None) {
                icon_index = (int)(track.PlaybackError == StreamPlaybackError.Drm
                    ? Icon.Protected
                    : Icon.Error);
            } else if (track.IsPlaying) {
                icon_index = (int)(ServiceManager.PlayerEngine.CurrentState == PlayerState.Paused
                    ? Icon.Paused
                    : Icon.Playing);
            } else {
                icon_index = -1;
            }

            return icon_index;
        }

        protected virtual void LoadPixbufs ()
        {
            if (pixbufs != null && pixbufs.Length > 0) {
                for (int i = 0; i < pixbufs.Length; i++) {
                    if (pixbufs[i] != null) {
                        pixbufs[i].Dispose ();
                        pixbufs[i] = null;
                    }
                }
            }

            if (pixbufs == null) {
                pixbufs = new Gdk.Pixbuf[PixbufCount];
            }

            pixbufs[(int)Icon.Playing]   = IconThemeUtils.LoadIcon (PixbufSize, "media-playback-start");
            pixbufs[(int)Icon.Paused]    = IconThemeUtils.LoadIcon (PixbufSize, "media-playback-pause");
            pixbufs[(int)Icon.Error]     = IconThemeUtils.LoadIcon (PixbufSize, "emblem-unreadable", "dialog-error");
            pixbufs[(int)Icon.Protected] = IconThemeUtils.LoadIcon (PixbufSize, "emblem-readonly", "dialog-error");

            if (status_names == null) {
                status_names = new string[PixbufCount];
                for (int i=0; i<PixbufCount; i++)
                    status_names[i] = "";
            }

            status_names[(int)Icon.Playing]   = Catalog.GetString ("Playing");
            status_names[(int)Icon.Paused]    = Catalog.GetString ("Paused");
            status_names[(int)Icon.Error]     = Catalog.GetString ("Error");
            status_names[(int)Icon.Protected] = Catalog.GetString ("Protected");
        }

        public override void NotifyThemeChange ()
        {
            LoadPixbufs ();
        }

        public override void Render (CellContext context, StateType state, double cellWidth, double cellHeight)
        {
            TrackInfo track = BoundTrack;
            if (track == null) {
                return;
            }

            int icon_index = GetIconIndex (track);

            if (icon_index < 0 || pixbufs == null || pixbufs[icon_index] == null) {
                return;
            }

            context.Context.Translate (0, 0.5);

            Gdk.Pixbuf render_pixbuf = pixbufs[icon_index];

            Cairo.Rectangle pixbuf_area = new Cairo.Rectangle ((cellWidth - render_pixbuf.Width) / 2,
                (cellHeight - render_pixbuf.Height) / 2, render_pixbuf.Width, render_pixbuf.Height);

            if (!context.Opaque) {
                context.Context.Save ();
            }

            Gdk.CairoHelper.SetSourcePixbuf (context.Context, render_pixbuf, pixbuf_area.X, pixbuf_area.Y);
            context.Context.Rectangle (pixbuf_area);

            if (!context.Opaque) {
                context.Context.Clip ();
                context.Context.PaintWithAlpha (0.5);
                context.Context.Restore ();
            } else {
                context.Context.Fill ();
            }
        }

        protected TrackInfo BoundTrack {
            get { return BoundObject as TrackInfo; }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.springframework.boot.autoconfigure.jms;

import java.time.Duration;

import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * Configuration properties for JMS.
 *
 * @author Greg Turnquist
 * @author Phillip Webb
 * @author Stephane Nicoll
 * @since 1.0.0
 */
@ConfigurationProperties(prefix = "spring.jms")
public class JmsProperties {

	/**
	 * Whether the default destination type is topic.
	 */
	private boolean pubSubDomain = false;

	/**
	 * Connection factory JNDI name. When set, takes precedence to others connection
	 * factory auto-configurations.
	 */
	private String jndiName;

	private final Cache cache = new Cache();

	private final Listener listener = new Listener();

	private final Template template = new Template();

	public boolean isPubSubDomain() {
		return this.pubSubDomain;
	}

	public void setPubSubDomain(boolean pubSubDomain) {
		this.pubSubDomain = pubSubDomain;
	}

	public String getJndiName() {
		return this.jndiName;
	}

	public void setJndiName(String jndiName) {
		this.jndiName = jndiName;
	}

	public Cache getCache() {
		return this.cache;
	}

	public Listener getListener() {
		return this.listener;
	}

	public Template getTemplate() {
		return this.template;
	}

	public static class Cache {

		/**
		 * Whether to cache sessions.
		 */
		private boolean enabled = true;

		/**
		 * Whether to cache message consumers.
		 */
		private boolean consumers = false;

		/**
		 * Whether to cache message producers.
		 */
		private boolean producers = true;

		/**
		 * Size of the session cache (per JMS Session type).
		 */
		private int sessionCacheSize = 1;

		public boolean isEnabled() {
			return this.enabled;
		}

		public void setEnabled(boolean enabled) {
			this.enabled = enabled;
		}

		public boolean isConsumers() {
			return this.consumers;
		}

		public void setConsumers(boolean consumers) {
			this.consumers = consumers;
		}

		public boolean isProducers() {
			return this.producers;
		}

		public void setProducers(boolean producers) {
			this.producers = producers;
		}

		public int getSessionCacheSize() {
			return this.sessionCacheSize;
		}

		public void setSessionCacheSize(int sessionCacheSize) {
			this.sessionCacheSize = sessionCacheSize;
		}

	}

	public static class Listener {

		/**
		 * Start the container automatically on startup.
		 */
		private boolean autoStartup = true;

		/**
		 * Acknowledge mode of the container. By default, the listener is transacted with
		 * automatic acknowledgment.
		 */
		private AcknowledgeMode acknowledgeMode;

		/**
		 * Minimum number of concurrent consumers.
		 */
		private Integer concurrency;

		/**
		 * Maximum number of concurrent consumers.
		 */
		private Integer maxConcurrency;

		/**
		 * Timeout to use for receive calls. Use -1 for a no-wait receive or 0 for no
		 * timeout at all. The latter is only feasible if not running within a transaction
		 * manager and is generally discouraged since it prevents clean shutdown.
		 */
		private Duration receiveTimeout = Duration.ofSeconds(1);

		public boolean isAutoStartup() {
			return this.autoStartup;
		}

		public void setAutoStartup(boolean autoStartup) {
			this.autoStartup = autoStartup;
		}

		public AcknowledgeMode getAcknowledgeMode() {
			return this.acknowledgeMode;
		}

		public void setAcknowledgeMode(AcknowledgeMode acknowledgeMode) {
			this.acknowledgeMode = acknowledgeMode;
		}

		public Integer getConcurrency() {
			return this.concurrency;
		}

		public void setConcurrency(Integer concurrency) {
			this.concurrency = concurrency;
		}

		public Integer getMaxConcurrency() {
			return this.maxConcurrency;
		}

		public void setMaxConcurrency(Integer maxConcurrency) {
			this.maxConcurrency = maxConcurrency;
		}

		public String formatConcurrency() {
			if (this.concurrency == null) {
				return (this.maxConcurrency != null) ? "1-" + this.maxConcurrency : null;
			}
			return ((this.maxConcurrency != null) ? this.concurrency + "-" + this.maxConcurrency
					: String.valueOf(this.concurrency));
		}

		public Duration getReceiveTimeout() {
			return this.receiveTimeout;
		}

		public void setReceiveTimeout(Duration receiveTimeout) {
			this.receiveTimeout = receiveTimeout;
		}

	}

	public static class Template {

		/**
		 * Default destination to use on send and receive operations that do not have a
		 * destination parameter.
		 */
		private String defaultDestination;

		/**
		 * Delivery delay to use for send calls.
		 */
		private Duration deliveryDelay;

		/**
		 * Delivery mode. Enables QoS (Quality of Service) when set.
		 */
		private DeliveryMode deliveryMode;

		/**
		 * Priority of a message when sending. Enables QoS (Quality of Service) when set.
		 */
		private Integer priority;

		/**
		 * Time-to-live of a message when sending. Enables QoS (Quality of Service) when
		 * set.
		 */
		private Duration timeToLive;

		/**
		 * Whether to enable explicit QoS (Quality of Service) when sending a message.
		 * When enabled, the delivery mode, priority and time-to-live properties will be
		 * used when sending a message. QoS is automatically enabled when at least one of
		 * those settings is customized.
		 */
		private Boolean qosEnabled;

		/**
		 * Timeout to use for receive calls.
		 */
		private Duration receiveTimeout;

		public String getDefaultDestination() {
			return this.defaultDestination;
		}

		public void setDefaultDestination(String defaultDestination) {
			this.defaultDestination = defaultDestination;
		}

		public Duration getDeliveryDelay() {
			return this.deliveryDelay;
		}

		public void setDeliveryDelay(Duration deliveryDelay) {
			this.deliveryDelay = deliveryDelay;
		}

		public DeliveryMode getDeliveryMode() {
			return this.deliveryMode;
		}

		public void setDeliveryMode(DeliveryMode deliveryMode) {
			this.deliveryMode = deliveryMode;
		}

		public Integer getPriority() {
			return this.priority;
		}

		public void setPriority(Integer priority) {
			this.priority = priority;
		}

		public Duration getTimeToLive() {
			return this.timeToLive;
		}

		public void setTimeToLive(Duration timeToLive) {
			this.timeToLive = timeToLive;
		}

		public boolean determineQosEnabled() {
			if (this.qosEnabled != null) {
				return this.qosEnabled;
			}
			return (getDeliveryMode() != null || getPriority() != null || getTimeToLive() != null);
		}

		public Boolean getQosEnabled() {
			return this.qosEnabled;
		}

		public void setQosEnabled(Boolean qosEnabled) {
			this.qosEnabled = qosEnabled;
		}

		public Duration getReceiveTimeout() {
			return this.receiveTimeout;
		}

		public void setReceiveTimeout(Duration receiveTimeout) {
			this.receiveTimeout = receiveTimeout;
		}

	}

	/**
	 * Translate the acknowledge modes defined on the {@link jakarta.jms.Session}.
	 *
	 * <p>
	 * {@link jakarta.jms.Session#SESSION_TRANSACTED} is not defined as we take care of
	 * this already via a call to {@code setSessionTransacted}.
	 */
	public enum AcknowledgeMode {

		/**
		 * Messages sent or received from the session are automatically acknowledged. This
		 * is the simplest mode and enables once-only message delivery guarantee.
		 */
		AUTO(1),

		/**
		 * Messages are acknowledged once the message listener implementation has called
		 * {@link jakarta.jms.Message#acknowledge()}. This mode gives the application
		 * (rather than the JMS provider) complete control over message acknowledgement.
		 */
		CLIENT(2),

		/**
		 * Similar to auto acknowledgment except that said acknowledgment is lazy. As a
		 * consequence, the messages might be delivered more than once. This mode enables
		 * at-least-once message delivery guarantee.
		 */
		DUPS_OK(3);

		private final int mode;

		AcknowledgeMode(int mode) {
			this.mode = mode;
		}

		public int getMode() {
			return this.mode;
		}

	}

	public enum DeliveryMode {

		/**
		 * Does not require that the message be logged to stable storage. This is the
		 * lowest-overhead delivery mode but can lead to lost of message if the broker
		 * goes down.
		 */
		NON_PERSISTENT(1),

		/*
		 * Instructs the JMS provider to log the message to stable storage as part of the
		 * client's send operation.
		 */
		PERSISTENT(2);

		private final int value;

		DeliveryMode(int value) {
			this.value = value;
		}

		public int getValue() {
			return this.value;
		}

	}

}


text:
#include "lib.h"
#include "ioloop.h"
#include "array.h"
#include "unichar.h"
#include "imap-match.h"
#include "subscription-file.h"
#include "mailbox-tree.h"
#include "mailbox-list-private.h"
#include "mailbox-list-subscriptions.h"

#include <sys/stat.h>

struct subscriptions_mailbox_list_iterate_context {
	struct mailbox_list_iterate_context ctx;
	struct mailbox_tree_context *tree;
	struct mailbox_tree_iterate_context *iter;
	struct mailbox_info info;
};

static int
mailbox_list_subscription_fill_one(struct mailbox_list *list,
				   struct mailbox_list *src_list,
				   const char *name)
{
	struct mail_namespace *ns, *default_ns = list->ns;
	struct mail_namespace *namespaces = default_ns->user->namespaces;
	struct mailbox_node *node;
	const char *vname, *ns_name, *error;
	unsigned int len;
	bool created;

	/* default_ns is whatever namespace we're currently listing.
	   if we have e.g. prefix="" and prefix=pub/ namespaces with
	   pub/ namespace having subscriptions=no, we want to:

	   1) when listing "" namespace we want to skip over any names
	   that begin with pub/. */
	if (src_list->ns->prefix_len == 0)
		ns_name = name;
	else {
		/* we could have two-level namespace: ns/ns2/ */
		ns_name = t_strconcat(src_list->ns->prefix, name, NULL);
	}
	ns = mail_namespace_find_unsubscribable(namespaces, ns_name);
	if (ns != NULL && ns != default_ns) {
		if (ns->prefix_len > 0)
			return 0;
		/* prefix="" namespace=no : catching this is basically the
		   same as not finding any namespace. */
		ns = NULL;
	}

	/* 2) when listing pub/ namespace, skip over entries that don't
	   begin with pub/. */
	if (ns == NULL &&
	    (default_ns->flags & NAMESPACE_FLAG_SUBSCRIPTIONS) == 0)
		return 0;

	/* When listing shared namespace's subscriptions, we need to
	   autocreate all the visible child namespaces. their subscriptions
	   are listed later. */
	if (ns != NULL && mail_namespace_is_shared_user_root(ns)) {
		/* we'll need to get the namespace autocreated.
		   one easy way is to just ask to join a reference and
		   pattern */
		(void)mailbox_list_join_refpattern(ns->list, ns_name, "");
	}

	/* When listing pub/ namespace, skip over the namespace
	   prefix in the name. the rest of the name is storage_name. */
	if (ns == NULL)
		ns = default_ns;
	else if (strncmp(ns_name, ns->prefix, ns->prefix_len) == 0) {
		ns_name += ns->prefix_len;
		name = ns_name;
	} else {
		/* "pub" entry - this shouldn't be possible normally, because
		   it should be saved as "pub/", but handle it anyway */
		i_assert(strncmp(ns_name, ns->prefix, ns->prefix_len-1) == 0 &&
			 ns_name[ns->prefix_len-1] == '\0');
		name = ns_name = "";
	}

	len = strlen(name);
	if (len > 0 && name[len-1] == mail_namespace_get_sep(ns)) {
		/* entry ends with hierarchy separator, remove it.
		   this exists mainly for backwards compatibility with old
		   Dovecot versions and non-Dovecot software that added them */
		name = t_strndup(name, len-1);
	}

	if (!mailbox_list_is_valid_name(list, name, &error)) {
		/* we'll only get into trouble if we show this */
		return -1;
	} else {
		vname = mailbox_list_get_vname(list, name);
		if (!uni_utf8_str_is_valid(vname))
			return -1;
		node = mailbox_tree_get(list->subscriptions, vname, &created);
		node->flags = MAILBOX_SUBSCRIBED;
	}
	return 0;
}

int mailbox_list_subscriptions_refresh(struct mailbox_list *src_list,
				       struct mailbox_list *dest_list)
{
	struct subsfile_list_context *subsfile_ctx;
	struct stat st;
	enum mailbox_list_path_type type;
	const char *path, *name;
	char sep;
	int ret;

	/* src_list is subscriptions=yes, dest_list is subscriptions=no
	   (or the same as src_list) */
	i_assert((src_list->ns->flags & NAMESPACE_FLAG_SUBSCRIPTIONS) != 0);

	if (dest_list->subscriptions == NULL) {
		sep = mail_namespace_get_sep(src_list->ns);
		dest_list->subscriptions = mailbox_tree_init(sep);
	}

	type = src_list->set.control_dir != NULL ?
		MAILBOX_LIST_PATH_TYPE_CONTROL : MAILBOX_LIST_PATH_TYPE_DIR;
	if (!mailbox_list_get_root_path(src_list, type, &path) ||
	    src_list->set.subscription_fname == NULL) {
		/* no subscriptions (e.g. pop3c) */
		return 0;
	}
	path = t_strconcat(path, "/", src_list->set.subscription_fname, NULL);
	if (stat(path, &st) < 0) {
		if (errno == ENOENT) {
			/* no subscriptions */
			mailbox_tree_clear(dest_list->subscriptions);
			dest_list->subscriptions_mtime = 0;
			return 0;
		}
		mailbox_list_set_critical(dest_list, "stat(%s) failed: %m",
					  path);
		return -1;
	}
	if (st.st_mtime == dest_list->subscriptions_mtime &&
	    st.st_mtime < dest_list->subscriptions_read_time-1) {
		/* we're up to date */
		return 0;
	}

	mailbox_tree_clear(dest_list->subscriptions);
	dest_list->subscriptions_read_time = ioloop_time;

	subsfile_ctx = subsfile_list_init(dest_list, path);
	if (subsfile_list_fstat(subsfile_ctx, &st) == 0)
		dest_list->subscriptions_mtime = st.st_mtime;
	while ((name = subsfile_list_next(subsfile_ctx)) != NULL) T_BEGIN {
		T_BEGIN {
			ret = mailbox_list_subscription_fill_one(dest_list,
								 src_list, name);
		} T_END;
		if (ret < 0) {
			i_warning("Subscriptions file %s: "
				  "Removing invalid entry: %s",
				  path, name);
			(void)subsfile_set_subscribed(src_list, path,
				mailbox_list_get_temp_prefix(src_list),
				name, FALSE);

		}
	} T_END;

	if (subsfile_list_deinit(&subsfile_ctx) < 0) {
		dest_list->subscriptions_mtime = (time_t)-1;
		return -1;
	}
	return 0;
}

void mailbox_list_set_subscription_flags(struct mailbox_list *list,
					 const char *vname,
					 enum mailbox_info_flags *flags)
{
	struct mailbox_node *node;

	*flags &= ~(MAILBOX_SUBSCRIBED | MAILBOX_CHILD_SUBSCRIBED);

	node = mailbox_tree_lookup(list->subscriptions, vname);
	if (node != NULL) {
		*flags |= node->flags & MAILBOX_SUBSCRIBED;

		/* the only reason why node might have a child is if one of
		   them is subscribed */
		if (node->children != NULL)
			*flags |= MAILBOX_CHILD_SUBSCRIBED;
	}
}

void mailbox_list_subscriptions_fill(struct mailbox_list_iterate_context *ctx,
				     struct mailbox_tree_context *tree,
				     bool default_nonexistent)
{
	struct mailbox_list_iter_update_context update_ctx;
	struct mailbox_tree_iterate_context *iter;
	const char *name;

	memset(&update_ctx, 0, sizeof(update_ctx));
	update_ctx.iter_ctx = ctx;
	update_ctx.tree_ctx = tree;
	update_ctx.glob = ctx->glob;
	update_ctx.leaf_flags = MAILBOX_SUBSCRIBED;
	if (default_nonexistent)
		update_ctx.leaf_flags |= MAILBOX_NONEXISTENT;
	update_ctx.parent_flags = MAILBOX_CHILD_SUBSCRIBED;
	update_ctx.match_parents =
		(ctx->flags & MAILBOX_LIST_ITER_SELECT_RECURSIVEMATCH) != 0;

	iter = mailbox_tree_iterate_init(ctx->list->subscriptions, NULL,
					 MAILBOX_SUBSCRIBED);
	while (mailbox_tree_iterate_next(iter, &name) != NULL)
		mailbox_list_iter_update(&update_ctx, name);
	mailbox_tree_iterate_deinit(&iter);
}

struct mailbox_list_iterate_context *
mailbox_list_subscriptions_iter_init(struct mailbox_list *list,
				     const char *const *patterns,
				     enum mailbox_list_iter_flags flags)
{
	struct subscriptions_mailbox_list_iterate_context *ctx;
	pool_t pool;
	char sep = mail_namespace_get_sep(list->ns);

	pool = pool_alloconly_create("mailbox list subscriptions iter", 1024);
	ctx = p_new(pool, struct subscriptions_mailbox_list_iterate_context, 1);
	ctx->ctx.pool = pool;
	ctx->ctx.list = list;
	ctx->ctx.flags = flags;
	ctx->ctx.glob = imap_match_init_multiple(pool, patterns, TRUE, sep);
	array_create(&ctx->ctx.module_contexts, pool, sizeof(void *), 5);

	ctx->tree = mailbox_tree_init(sep);
	mailbox_list_subscriptions_fill(&ctx->ctx, ctx->tree, FALSE);

	ctx->info.ns = list->ns;
	/* the tree usually has only those entries we want to iterate through,
	   but there are also non-matching root entries (e.g. "LSUB foo/%" will
	   include the "foo"), which we'll drop with MAILBOX_MATCHED. */
	ctx->iter = mailbox_tree_iterate_init(ctx->tree, NULL, MAILBOX_MATCHED);
	return &ctx->ctx;
}

const struct mailbox_info *
mailbox_list_subscriptions_iter_next(struct mailbox_list_iterate_context *_ctx)
{
	struct subscriptions_mailbox_list_iterate_context *ctx =
		(struct subscriptions_mailbox_list_iterate_context *)_ctx;
	struct mailbox_list *list = _ctx->list;
	struct mailbox_node *node;
	enum mailbox_info_flags subs_flags;
	const char *vname, *storage_name, *error;
	int ret;

	node = mailbox_tree_iterate_next(ctx->iter, &vname);
	if (node == NULL)
		return NULL;

	ctx->info.vname = vname;
	subs_flags = node->flags & (MAILBOX_SUBSCRIBED |
				    MAILBOX_CHILD_SUBSCRIBED);

	if ((_ctx->flags & MAILBOX_LIST_ITER_RETURN_NO_FLAGS) != 0 &&
	    (_ctx->flags & MAILBOX_LIST_ITER_RETURN_CHILDREN) == 0) {
		/* don't care about flags, just return it */
		ctx->info.flags = subs_flags;
		return &ctx->info;
	}

	storage_name = mailbox_list_get_storage_name(list, vname);
	if (!mailbox_list_is_valid_name(list, storage_name, &error)) {
		/* broken entry in subscriptions file */
		ctx->info.flags = MAILBOX_NONEXISTENT;
	} else if (mailbox_list_mailbox(list, storage_name,
					&ctx->info.flags) < 0) {
		ctx->info.flags = 0;
		_ctx->failed = TRUE;
	} else if ((_ctx->flags & MAILBOX_LIST_ITER_RETURN_CHILDREN) != 0 &&
		   (ctx->info.flags & (MAILBOX_CHILDREN |
				       MAILBOX_NOCHILDREN)) == 0) {
		ret = mailbox_has_children(list, storage_name);
		if (ret < 0)
			_ctx->failed = TRUE;
		else if (ret == 0)
			ctx->info.flags |= MAILBOX_NOCHILDREN;
		else
			ctx->info.flags |= MAILBOX_CHILDREN;

	}

	ctx->info.flags &= ~(MAILBOX_SUBSCRIBED | MAILBOX_CHILD_SUBSCRIBED);
	ctx->info.flags |=
		node->flags & (MAILBOX_SUBSCRIBED | MAILBOX_CHILD_SUBSCRIBED);
	return &ctx->info;
}

int mailbox_list_subscriptions_iter_deinit(struct mailbox_list_iterate_context *_ctx)
{
	struct subscriptions_mailbox_list_iterate_context *ctx =
		(struct subscriptions_mailbox_list_iterate_context *)_ctx;
	int ret = _ctx->failed ? -1 : 0;

	mailbox_tree_iterate_deinit(&ctx->iter);
	mailbox_tree_deinit(&ctx->tree);
	pool_unref(&_ctx->pool);
	return ret;
}


text:
package com.thalmic.myo.enums;

public enum VibrationType {
    VIBRATION_SHORT,
    VIBRATION_MEDIUM,
    VIBRATION_LONG
}


text:
set -e

mkdir build
cd build
cmake -DCMAKE_INSTALL_PREFIX=../../install $@ ../
make
make test
make install
LSAN_OPTIONS=verbosity=1:log_threads=1 ctest --output-on-failure


text:
<md-data-table class="table" layout-margin flex="100" flex-gt-sm="60">

My Projects

            <md-button ng-click="project.createProject()"  aria-label="move" class="md-primary md-raised">
                Create Project
            </md-button>

                arrow_forward
                Title

                arrow_forward
                Status

                arrow_forward
                Number of Milestones

        <md-divider></md-divider>

 0">

{{item.name}}

{{ project.getStatusName(item.modules[0].status) }}

{{item.module_count}}

                    <md-divider></md-divider>

No projects found!

        <md-divider></md-divider>

</md-data-table>


text:
namespace gfx {
class Rect;
}  // namespace gfx

namespace ui {
class GestureEvent;
class KeyEvent;
class ScrollEvent;
}  // namespace ui

namespace views {

namespace internal {
class RootView;
}  // namespace internal

class View;
class ViewTargeterDelegate;

// A ViewTargeter is installed on a View that wishes to use the custom
// hit-testing or event-targeting behaviour defined by |delegate|.
class VIEWS_EXPORT ViewTargeter : public ui::EventTargeter {
 public:
  explicit ViewTargeter(ViewTargeterDelegate* delegate);
  ~ViewTargeter() override;

  // A call-through to DoesIntersectRect() on |delegate_|.
  bool DoesIntersectRect(const View* target, const gfx::Rect& rect) const;

  // A call-through to TargetForRect() on |delegate_|.
  View* TargetForRect(View* root, const gfx::Rect& rect) const;

 protected:
  // ui::EventTargeter:
  ui::EventTarget* FindTargetForEvent(ui::EventTarget* root,
                                      ui::Event* event) override;
  ui::EventTarget* FindNextBestTarget(ui::EventTarget* previous_target,
                                      ui::Event* event) override;

 private:
  View* FindTargetForKeyEvent(View* root, const ui::KeyEvent& key);
  View* FindTargetForScrollEvent(View* root, const ui::ScrollEvent& scroll);

  virtual View* FindTargetForGestureEvent(View* root,
                                          const ui::GestureEvent& gesture);
  virtual ui::EventTarget* FindNextBestTargetForGestureEvent(
      ui::EventTarget* previous_target,
      const ui::GestureEvent& gesture);

  // ViewTargeter does not own the |delegate_|, but |delegate_| must
  // outlive the targeter.
  ViewTargeterDelegate* delegate_;

  DISALLOW_COPY_AND_ASSIGN(ViewTargeter);
};

}  // namespace views

#endif  // UI_VIEWS_VIEW_TARGETER_H_


text:
package uk.ac.manchester.cs.owl.semspreadsheets.ui.task;

import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;

import uk.ac.manchester.cs.owl.semspreadsheets.repository.RepositoryItem;

/**
 *
 * @author Stuart Owen
 *
 */
public class LoadRepositoryItemTask extends AbstractTask<OWLOntology, OWLOntologyCreationException> {

	private RepositoryItem repositoryItem;

    public LoadRepositoryItemTask(RepositoryItem repositoryItem) {
        this.repositoryItem = repositoryItem;
    }

    public OWLOntology runTask() throws OWLOntologyCreationException {
        return getOntologyManager().loadOntology(repositoryItem.getPhysicalIRI());
    }

    public String getTitle() {
        return "Fetching '" + repositoryItem.getHumanReadableName() +"' ontology";
    }

}


text:
title: Design Principles
info: This style guide has been created to help designers, developers and PMs create and maintain user interface documentation. Documenting the user interface (UI) of a digital product or system reduces dramatically speeds up development time and helps to ensure new UI additions deliver a consistent experience to users.
---

# Four Guiding Principles

### 1. Simple Build.

This style guide has been created with expansion and customization in mind, it provides a simple interface to browse design components, and it's only dependency is [Jekyll](https://jekyllrb.com/).

### 2. HTML First.

The components created in this styleguide are built with HTML first. This process encourages developers to build progressively with the most versatile front-end development language.

### 3. Design for Flexibility.

Using a style guide ensures patterns adapt correctly to meet user needs, offering variation, and yet, providing design consistency and familiarity. It also allows us to build components that work well in multiple digital channels.

### 4. Reuseable Best Practices

Design, develop, test, review, and repurpose patterns, code, and design. That results in a comprehensive collection of tried-and-tested assets that reflect industry best practices.


text:
package th.co.transcipt.model;

public class Subject {

	private String code;
	private String name;
	private int credit;
	private String grade;

	public Subject(String code, String name, int credit, String grade) {
		this.code = code;
		this.name = name;
		this.credit = credit;
		this.grade = grade;
	}

	@Override
	public String toString(){
		return "["+code+"] " + name + " (" + credit + ") \t" + grade;
	}

	// getter for grade
	public String getGrade() {
		return grade;
	}

	// get grade magnitude
	public double getMagnitude() throws Exception
	{
		if (grade.equals("A")) { return 4;  }
		else if (grade.equals("A-")) { return 3.75; }
		else if (grade.equals("B+")) { return 3.25; }
		else if (grade.equals("B")) { return 3; }
		else if (grade.equals("B-")) { return 2.75; }
		else if (grade.equals("C+")) { return 2.25; }
		else if (grade.equals("C")) { return 2; }
		else if (grade.equals("C-")) { return 1.75; }
		else if (grade.equals("D")) { return 1; }
		else if (grade.equals("F")) { return 0; }

		throw new Exception("Cannot convert the grade to a magnitude");
	}

	// getter for credit
	public int getCredit() {
		return credit;
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="bootstrap/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false">
    <logging>
        <log type="coverage-clover" target="build/logs/clover.xml"/>
    </logging>
    <testsuites>
        <testsuite name="Application Test Suite">
            <directory>./tests/</directory>
        </testsuite>
    </testsuites>
</phpunit>


text:
package ws.biotea.ld2rdf.annotation.parser;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.jena.riot.RDFFormat;
import org.apache.log4j.Logger;

import ws.biotea.ld2rdf.annotation.exception.ArticleParserException;
import ws.biotea.ld2rdf.annotation.exception.InputException;
import ws.biotea.ld2rdf.annotation.exception.NoResponseException;
import ws.biotea.ld2rdf.annotation.exception.UnsupportedFormatException;
import ws.biotea.ld2rdf.annotation.model.ArticleElement;
import ws.biotea.ld2rdf.annotation.model.ContextParagraph;
import ws.biotea.ld2rdf.annotation.model.JATSArticle;
import ws.biotea.ld2rdf.annotation.model.NCBOAnnotation;
import ws.biotea.ld2rdf.annotation.model.PositionLocator;
import ws.biotea.ld2rdf.exception.DTDException;
import ws.biotea.ld2rdf.exception.RDFModelIOException;
import ws.biotea.ld2rdf.rdf.model.ao.ElementSelector;
import ws.biotea.ld2rdf.rdf.model.ao.ExactQualifier;
import ws.biotea.ld2rdf.rdf.model.ao.FoafAgent;
import ws.biotea.ld2rdf.rdf.model.ao.FoafDocument;
import ws.biotea.ld2rdf.rdf.model.ao.Topic;
import ws.biotea.ld2rdf.rdf.model.aoextended.AnnotationE;
import ws.biotea.ld2rdf.rdf.persistence.AnnotationDAO;
import ws.biotea.ld2rdf.rdf.persistence.AnnotationDAOUtil;
import ws.biotea.ld2rdf.rdf.persistence.ConstantConfig;
import ws.biotea.ld2rdf.rdfGeneration.jats.GlobalArticleConfig;
import ws.biotea.ld2rdf.util.ClassesAndProperties;
import ws.biotea.ld2rdf.util.ResourceConfig;
import ws.biotea.ld2rdf.util.annotation.AnnotationResourceConfig;
import ws.biotea.ld2rdf.util.annotation.BioOntologyConfig;
import ws.biotea.ld2rdf.util.ncbo.annotator.Ontology;
import ws.biotea.ld2rdf.util.ncbo.annotator.jaxb.newgenerated.AnnotationCollection;
import ws.biotea.ld2rdf.util.ncbo.annotator.jaxb.newgenerated.Annotations;
import ws.biotea.ld2rdf.util.ncbo.annotator.jaxb.newgenerated.Empty;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.ResIterator;
import com.hp.hpl.jena.rdf.model.Resource;

public class NCBOParser implements AnnotatorParser {
	private static Logger logger = Logger.getLogger(NCBOParser.class);
	private List<AnnotationE> lstAnnotations;

	private FoafAgent creator, author;
	private String annotator = "NCBO";
	private static final String annotatorURL = AnnotationResourceConfig.getNCBOServiceURL(); // "http://rest.bioontology.org/obs/annotator";
	private static final String ontologiesToAnnotate = Ontology.getInstance().getAllAcronymFromNCBO(); // Ontology.getAllVirtualId();
	public static final String BASE_FOAF_NCBO_ANNOTATOR = AnnotationResourceConfig.getNCBOAnnotatorURL();// "http://bioportal.bioontology.org/annotator/";
	private final static String stopWords = AnnotationResourceConfig.getNCBOStopwords(); // http://www.ranks.nl/resources/stopwords.html
	private final static Pattern excludedSections = Pattern.compile(
			"([aA]cknowledgements)|([cC]ompeting[-]interests)|([aA]uthor)(s-|--|-s|)(-contributions)|([aA]bbreviations)"); // we
																															// are
																															// replacing
																															// spaces
																															// and
																															// other
																															// chars
																															// such
																															// as
																															// '
																															// by
																															// -

	private StringBuffer articleURI;
	private String articleId;
	private JATSArticle article;

	// private String inputLocation;
	private boolean fromURL;
	private boolean onlyTitleAndAbstract;
	private ConstantConfig inStyle;

	public NCBOParser() {
	}

	/**
	 * Constructor.
	 *
	 * @param fromURL
	 * @param onlyTitleAndAbstract
	 */
	public NCBOParser(Boolean fromURL, Boolean onlyTitleAndAbstract, ConstantConfig inStyle) {
		this.articleURI = new StringBuffer();
		this.lstAnnotations = new ArrayList<>();
		this.inStyle = inStyle;

		this.fromURL = fromURL;
		this.onlyTitleAndAbstract = onlyTitleAndAbstract;
	}

	@Override
	public void init() throws URISyntaxException, MalformedURLException {
		if (this.author == null) {
			this.author = new FoafAgent();
			this.author.setId(new URI(AnnotationResourceConfig.getNCBOAnnotatorURL()));
		}
		if (this.creator == null) {
			this.creator = new FoafAgent();
			this.creator.setId(new URI(ResourceConfig.BIOTEA_RDFIZATOR));
		}
	}

	@Override
	public List<AnnotationE> parse(String documentId)
			throws IOException, URISyntaxException, NoResponseException, ArticleParserException {
		throw new ArticleParserException("URL parsing currently not supported for NCBO");
		/*
		 * this.init();
		 *
		 * this.articleId = documentId; File file = null; if (this.fromURL) {
		 * URL url; if (this.onlyTitleAndAbstract) { this.inputLocation = "";
		 * //pubmed url = new URL(this.inputLocation +
		 * ResourceConfig.getTitleAbstractPrefix() + documentId); } else {
		 * this.inputLocation = ""; //PMC-OA url = new URL(this.inputLocation +
		 * ResourceConfig.getFullTextPrefix() + documentId); } //file = new
		 * FileInputStream(url.openStream())); } else { throw new
		 * IOException("DocumentId parser cannot be used if NCBOParser has been configured to parse from files"
		 * ); } try { this.article.createArticleFromFile(file, this.articleURI,
		 * this.onlyTitleAndAbstract); } catch (InputException | DTDException |
		 * JAXBException e) { logger.fatal("File corresponding to "+ documentId
		 * + " could not be parsed"); throw new
		 * ArticleParserException("File corresponding to "+ documentId +
		 * " could not be parsed"); } this.parseParagraphs(); return
		 * this.lstAnnotations;
		 */
	}

	/**
	 * Parser a Biotea RDF file in order to annotate its content. Note: It only
	 * parses Biotea RDF files, Bio2RDF as well as any other mappings are not
	 * supported.
	 */
	@Override
	public List<AnnotationE> parse(File file)
			throws IOException, URISyntaxException, NoResponseException, ArticleParserException {
		this.init();

		if (this.fromURL) {
			throw new IOException("File parser cannot be used if NCBOParser has been configured to parse from a URL");
		}

		try {
			if (this.inStyle == ConstantConfig.JATS_FILE) {
				this.article = new JATSArticle();
				this.articleId = this.article.createArticleFromFile(file, this.articleURI, this.onlyTitleAndAbstract);
				this.parseParagraphs();
			} else if (this.inStyle == ConstantConfig.RDF_FILE) {
				this.parseRDFFile(file);
			} else {
				throw new ArticleParserException("Input syle not supported: " + this.inStyle);
			}
		} catch (InputException | DTDException | JAXBException e) {
			logger.fatal("File corresponding to " + file.getAbsolutePath() + " could not be parsed");
			throw new ArticleParserException(
					"File corresponding to " + file.getAbsolutePath() + " could not be parsed");
		}
		return this.lstAnnotations;
	}

	private int parseRDFParagraph(Resource res, Property prop, String urlToAnnotate, int length,
			List<ContextParagraph> context, StringBuffer textToAnnotate) {
		try {
			String paragraphToAnnotate = res.getProperty(prop).getObject().toString();
			if ((paragraphToAnnotate != null) && (paragraphToAnnotate.length() != 0)) {
				paragraphToAnnotate = this.prepareParagraph(paragraphToAnnotate);
				length += paragraphToAnnotate.length();
				context.add(new ContextParagraph(urlToAnnotate == null ? -1 : length, urlToAnnotate));
				textToAnnotate.append(paragraphToAnnotate);
			}
			return length;
		} catch (Exception e) {
			return -1;
		}
	}

	private void parseRDFFile(File file) throws FileNotFoundException, ArticleParserException, URISyntaxException {
		List<ContextParagraph> context = new ArrayList<ContextParagraph>();
		StringBuffer textToAnnotate = new StringBuffer();
		int length = 0;

		// create an empty model
		Model model = ModelFactory.createDefaultModel();
		// use the FileManager to find the input file
		InputStream in = new FileInputStream(file);
		// read the RDF/XML file
		model.read(in, null);
		logger.debug("===RDF READ=== " + file);

		Property rdfType = model.getProperty(ClassesAndProperties.RDF_TYPE.getURLValue());
		Property titleProp = model.getProperty(ClassesAndProperties.DCTERMS_PROP_TITLE.getURLValue());
		String articleStringURI = "";

		Resource articleClass = model.createResource(ClassesAndProperties.BIBO_ACADEMIC_ARTICLE.getURLValue());
		ResIterator resItr = model.listResourcesWithProperty(rdfType, articleClass);
		if (resItr.hasNext()) {
			Resource res = resItr.next();

			this.articleURI.delete(0, articleURI.length());
			this.articleURI.append(res.getURI().toString());
			articleStringURI = this.articleURI.toString();
			this.articleId = GlobalArticleConfig.getArticleIdFromRdfUri(ResourceConfig.getBioteaBase(null),
					articleStringURI);

			int temp = parseRDFParagraph(res, titleProp, null, length, context, textToAnnotate);
			if (temp != -1) {
				length = temp;
			}
		} else {
			throw new ArticleParserException("No id was retrieved from " + file);
		}

		Resource sectionClass = model.createResource(ClassesAndProperties.DOCO_SECTION.getURLValue());
		resItr = model.listResourcesWithProperty(rdfType, sectionClass);
		while (resItr.hasNext()) {
			Resource res = resItr.next();
			String urlToAnnotate = res.getURI().toString();
			int temp = parseRDFParagraph(res, titleProp, urlToAnnotate, length, context, textToAnnotate);
			if (temp != -1) {
				length = temp;
			} else {
				continue;
			}
		}

		Property textProp = model.getProperty(ClassesAndProperties.TEXT_PROPERTY);
		resItr = model.listResourcesWithProperty(textProp);
		while (resItr.hasNext()) {
			Resource res = resItr.next();
			Matcher matcher = NCBOParser.excludedSections.matcher(res.getURI().toString());
			if (matcher.find()) {
				continue; // excluded sections will not be annotated
			} else {
				// paragraph by paragraph
				String urlToAnnotate = res.getURI().toString();
				int temp = parseRDFParagraph(res, textProp, urlToAnnotate, length, context, textToAnnotate);
				if (temp != -1) {
					length = temp;
				} else {
					continue;
				}
			}
		}

		boolean writeDown = annotateWithNCBO(textToAnnotate.toString(), context, articleStringURI);
		if (!writeDown) {
			logger.warn("- WARNING SUBTITLE - NCBO annotations for " + this.articleId);
		}
	}

	private String prepareParagraph(String paragraph) throws UnsupportedEncodingException {
		String para = paragraph.replaceAll("[^\\p{Alpha}\\p{Z}\\p{P}\\p{N}]", "_");
		para = URLEncoder.encode(para, ResourceConfig.UTF_ENCODING);
		para = para.replace("+", " ");
		return para;
	}

	private void parseParagraphs() {
		List<ContextParagraph> context = new ArrayList<ContextParagraph>();
		StringBuffer textToAnnotate = new StringBuffer();
		int length = 0;

		String articleStringURI = this.articleURI.toString();
		for (ArticleElement element : this.article.getElements()) {
			// paragraph by paragraph
			String paragraphToAnnotate = element.getText();
			String urlToAnnotate = element.getIdentifier();
			try {
				if ((paragraphToAnnotate != null) && (paragraphToAnnotate.length() != 0)) {
					paragraphToAnnotate = this.prepareParagraph(paragraphToAnnotate);
					length += paragraphToAnnotate.length();
					context.add(new ContextParagraph(length, urlToAnnotate));
					textToAnnotate.append(paragraphToAnnotate);
				}
			} catch (UnsupportedEncodingException uee) {
				// we annotate as much as we can, some paragraphs can be omitted
				logger.warn("WARNING PARAGRAPH - NCBO annotations for " + this.articleId + "(" + urlToAnnotate
						+ ") could not be processed");
			}
		}
		boolean writeDown = annotateWithNCBO(textToAnnotate.toString(), context, articleStringURI);
		if (!writeDown) {
			logger.warn("WARNING NCBO annotations for " + articleStringURI + " could not be processed");
		}
		logger.info("===SECTIONS ANNOTATED=== " + this.articleId);
	}

	/**
	 * Annotate a short paragraph corresponding only to one context.
	 */
	private boolean annotateWithNCBO(String text, List<ContextParagraph> urlContext, String articleStringURI) {

		// System.out.println("TO ANNOT: " + urlContext + "\n" + paragraph);
		HttpClient client = new HttpClient();

		/* Set this string for your application */
		client.getParams().setParameter(HttpMethodParams.USER_AGENT, "Annotator Client Scientific Publications");

		PostMethod method = new PostMethod(annotatorURL);
		try {
			// Configure the form parameters
			method.addParameter("stop_words", stopWords);
			method.addParameter("minimum_match_length", "3");
			method.addParameter("ontologies", ontologiesToAnnotate);
			method.addParameter("text", text);
			method.addParameter("format", "xml"); // Options are 'text', 'xml',
													// 'tabDelimited'
			method.addParameter("apikey", AnnotationResourceConfig.getNCBOAPIKey());

			// Execute the POST method
			int statusCode = client.executeMethod(method);

			if (statusCode != -1) {
				try {
					InputStream annotatedParagraph = method.getResponseBodyAsStream();
					if (annotatedParagraph != null) {
						// Reader reader = new StringReader(annotatedParagraph);
						JAXBContext jc = JAXBContext
								.newInstance("ws.biotea.ld2rdf.util.ncbo.annotator.jaxb.newgenerated");
						Unmarshaller unmarshaller = jc.createUnmarshaller();
						AnnotationCollection xml;
						Object obj = new Object();
						try {
							obj = unmarshaller.unmarshal(annotatedParagraph);
							if (obj instanceof Empty) {
								return true; // no annotations were found but
												// everything was ok with the
												// response
							}
							xml = (AnnotationCollection) obj; // otherwise,
																// AnnotationCollection
																// should be the
																// unmarshalled
																// object
						} catch (Exception e) {
							logger.fatal("- FATAL DTD ERROR ANNOTATOR - NCBO annotations for " + this.articleId
									+ " cannot be unmarshalled: " + e.getMessage() + " - class: " + obj.getClass());
							return false;
						}
						logger.debug("---Annotations unmarshalled---");
						List<NCBOAnnotation> lstNCBOAnnotations = new ArrayList<>();
						List<ws.biotea.ld2rdf.util.ncbo.annotator.jaxb.newgenerated.Annotation> lstAnn = xml
								.getAnnotation();
						for (ws.biotea.ld2rdf.util.ncbo.annotator.jaxb.newgenerated.Annotation ann : lstAnn) {
							String fullId = ann.getAnnotatedClass().getId();
							List<Annotations> lstRetrievedAnnotations = ann.getAnnotationsCollection().getAnnotations();
							for (Annotations annot : lstRetrievedAnnotations) {
								NCBOAnnotation ncboAnnot = new NCBOAnnotation(annot.getText());
								int pos = lstNCBOAnnotations.indexOf(ncboAnnot);
								if (pos != -1) {
									ncboAnnot = lstNCBOAnnotations.get(pos);
								} else {
									lstNCBOAnnotations.add(ncboAnnot);
								}
								ncboAnnot.getAnnotatedClassIds().add(fullId);
								ncboAnnot.getAnnotationFromTo()
										.add(new PositionLocator(annot.getFrom().intValue(), annot.getTo().intValue()));
							}
						}

						mergeAnnotations(lstNCBOAnnotations, articleStringURI, urlContext);
					}
				} catch (Exception e) {
					// e.printStackTrace();
					logger.info("===ERROR NCBO Annotator (" + this.articleId + ")=== " + e.getMessage());
					return false;
				}
			} else {
				logger.info("===ERROR??? NCBO Annotator (" + this.articleId + ")=== (status code != 1) ");
				return false;
			}
		} catch (Exception e) {
			// e.printStackTrace();
			logger.info("===ERROR NCBO Annotator (" + this.articleId + " at " + urlContext + ")=== (http call)"
					+ e.getMessage());
			return false;
		} finally {
			if (method != null){
				method.releaseConnection();
			}
			if(client != null){
				SimpleHttpConnectionManager connManager = (SimpleHttpConnectionManager) client.getHttpConnectionManager();
				if (connManager != null){
					connManager.shutdown();
				}
			}
			method = null;
		}
		return true;
	}

	private String getURLContext(List<ContextParagraph> urlContext, int lastPosition) {
		for (ContextParagraph context : urlContext) {
			if (lastPosition <= context.getLastPosition()) {
				return context.getContextURL();
			}
		}
		return null;
	}

	private void mergeAnnotations(List<NCBOAnnotation> lstNCBOAnnotations, String articleStringURI,
			List<ContextParagraph> allContext) throws URISyntaxException {
		for (NCBOAnnotation ncboAnnot : lstNCBOAnnotations) {
			// annot: creator, body, resource, date
			ExactQualifier annot = new ExactQualifier();
			annot.setAuthor(this.author);
			annot.setCreator(this.creator);
			annot.getBodies().add(ncboAnnot.getAnnotationText());
			FoafDocument document = new FoafDocument();
			document.setUri(new URI(articleStringURI));
			annot.setResource(document);
			annot.setDocumentID(this.articleId);
			annot.setCreationDate(Calendar.getInstance());
			annot.setFrequency(ncboAnnot.getFrequency());

			for (String fullId : ncboAnnot.getAnnotatedClassIds()) {
				ws.biotea.ld2rdf.util.ncbo.annotator.NCBOOntology onto = ws.biotea.ld2rdf.util.ncbo.annotator.Ontology
						.getInstance().getOntologyByURL(fullId);
				if (onto == null) { // For NDFRT is possible to get UMLS
									// elements, those are excluded
					continue;
				}
				String partialId = fullId.substring(onto.getURL().length());
				if (partialId.startsWith("/")) {
					partialId = partialId.substring(1);
				}
				// topics
				Topic topic = new Topic();
				topic.setNameSpace(new URI(onto.getNS() + ":" + partialId));
				topic.setURL(new URI(onto.getURL() + partialId));
				annot.addTopic(topic);

				Topic topic2 = null;
				if (onto.getNS().equals(BioOntologyConfig.getNS("NCBITaxon"))) {
					topic2 = new Topic();
					topic2.setNameSpace(new URI(BioOntologyConfig.getNS("UNIPROT_TAXONOMY") + ":" + partialId)); // species:
																													// http://purl.uniprot.org/taxonomy/
					topic2.setURL(new URI(BioOntologyConfig.getURL("UNIPROT_TAXONOMY") + partialId));
					annot.addTopic(topic2);
				}
			}

			// Go to the annotations table
			if (annot != null) {
				int pos = this.lstAnnotations.indexOf(annot);
				if (pos != -1) {
					AnnotationE a = this.lstAnnotations.get(pos);
					for (PositionLocator locator : ncboAnnot.getAnnotationFromTo()) {
						String urlContext = this.getURLContext(allContext, locator.getTo());
						if (urlContext != null) {
							ElementSelector ses = new ElementSelector(a.getResource());
							ses.setElementURI(urlContext);
							if (!a.getContext().contains(ses)) {
								a.addContext(ses);
								a.setFrequency(a.getFrequency() + annot.getFrequency());
							}
						}
					}
				} else {
					for (PositionLocator locator : ncboAnnot.getAnnotationFromTo()) {
						String urlContext = this.getURLContext(allContext, locator.getTo());
						if (urlContext != null) {
							// context (selector)
							ElementSelector ses = new ElementSelector(annot.getResource());
							ses.setElementURI(urlContext);
							annot.addContext(ses);
						}
					}
					this.lstAnnotations.add(annot);
				}
			}
		}
	}

	@Override
	public List<AnnotationE> serializeToFile(String fullPathName, RDFFormat format, String base, ConstantConfig onto,
			boolean empty, boolean blankNode) throws RDFModelIOException, UnsupportedFormatException {
		List<AnnotationE> lst = null;
		try {
			AnnotationDAO dao = AnnotationDAOUtil.getDAO(base, onto);
			lst = dao.insertAnnotations(base, AnnotationResourceConfig.getBaseURLAnnotator(base, this.annotator),
					this.lstAnnotations, fullPathName, format, empty, blankNode);
			int error = this.lstAnnotations.size() - lst.size();
			if (error != 0) {
				logger.info("==ERROR writing annotations NCBO== " + error
						+ " annotations were not created, check the logs starting by 'OpenAnnotation not inserted' for more information");
			}
		} catch (Exception e) {
			logger.error("===ERROR=== Annotations for " + this.articleId + " with base " + base + " not serialized: "
					+ e.getMessage());
		}
		return lst;
	}

	@Override
	public List<AnnotationE> serializeToModel(Model model, String base, ConstantConfig onto, boolean blankNode)
			throws RDFModelIOException, UnsupportedFormatException {
		List<AnnotationE> lst = null;
		try {
			AnnotationDAO dao = AnnotationDAOUtil.getDAO(base, onto);
			lst = dao.insertAnnotations(base, AnnotationResourceConfig.getBaseURLAnnotator(base, this.annotator),
					this.lstAnnotations, model, blankNode);
			int error = this.lstAnnotations.size() - lst.size();
			if (error != 0) {
				logger.info("==ERROR writing annotations NCBO== " + error
						+ " annotations were not created, check the logs starting by 'OpenAnnotation not inserted' for more information");
			}
		} catch (Exception e) {
			logger.error("===ERROR=== Annotations for " + this.articleId + " with base " + base + " not serialized: "
					+ e.getMessage());
		}
		return lst;
	}

	@Override
	public String getArticleId() {
		return this.articleId;
	}

}


text:
<?php

require_once ($GLOBALS['HACKLIB_ROOT']);
if (!isset($GLOBALS['THRIFT_ROOT'])) {
  $GLOBALS['THRIFT_ROOT'] = __DIR__.'/..';
}
require_once $GLOBALS['THRIFT_ROOT'].'/transport/IThriftBufferedTransport.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/TNullTransport.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/TTransport.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/TTransportStatus.php';
class TFramedTransport extends TTransport
  implements TTransportStatus, IThriftBufferedTransport {
  protected $transport_;
  protected $rBuf_ = '';
  protected $rIndex_ = 0;
  protected $wBuf_ = '';
  private $read_;
  private $write_;
  public function __construct($transport = null, $read = true, $write = true) {
    $this->transport_ =
      \hacklib_cast_as_boolean($transport) ?: (new TNullTransport());
    $this->read_ = $read;
    $this->write_ = $write;
  }
  public function isOpen() {
    return $this->transport_->isOpen();
  }
  public function open() {
    $this->transport_->open();
  }
  public function close() {
    $this->transport_->close();
  }
  public function isReadable() {
    if (strlen($this->rBuf_) > 0) {
      return true;
    }
    if ($this->transport_ instanceof TTransportStatus) {
      return $this->transport_->isReadable();
    }
    return true;
  }
  public function isWritable() {
    if ($this->transport_ instanceof TTransportStatus) {
      return $this->transport_->isWritable();
    }
    return true;
  }
  public function read($len) {
    if (!\hacklib_cast_as_boolean($this->read_)) {
      return $this->transport_->read($len);
    }
    if (strlen($this->rBuf_) === 0) {
      $this->readFrame();
    }
    $out = substr($this->rBuf_, $this->rIndex_, $len);
    $this->rIndex_ += $len;
    if (strlen($this->rBuf_) <= $this->rIndex_) {
      $this->rBuf_ = '';
      $this->rIndex_ = 0;
    }
    return $out;
  }
  public function peek($len, $start = 0) {
    if (!\hacklib_cast_as_boolean($this->read_)) {
      return '';
    }
    if (strlen($this->rBuf_) === 0) {
      $this->readFrame();
    }
    $out = substr($this->rBuf_, $this->rIndex_ + $start, $len);
    return $out;
  }
  public function putBack($data) {
    if (strlen($this->rBuf_) === 0) {
      $this->rBuf_ = $data;
    } else {
      $this->rBuf_ = $data.((string) substr($this->rBuf_, $this->rIndex_));
    }
    $this->rIndex_ = 0;
  }
  private function readFrame() {
    $buf = $this->transport_->readAll(4);
    $val = unpack('N', $buf);
    $sz = $val[1];
    $this->rBuf_ = $this->transport_->readAll($sz);
    $this->rIndex_ = 0;
  }
  public function write($buf, $len = null) {
    if (!\hacklib_cast_as_boolean($this->write_)) {
      $this->transport_->write($buf);
      return;
    }
    if (($len !== null) && ($len < strlen($buf))) {
      $buf = substr($buf, 0, $len);
    }
    $this->wBuf_ .= $buf;
  }
  public function flush() {
    if ((!\hacklib_cast_as_boolean($this->write_)) ||
        \hacklib_equals(strlen($this->wBuf_), 0)) {
      $this->transport_->flush();
      return;
    }
    $out = (string) pack('N', strlen($this->wBuf_));
    $out .= $this->wBuf_;
    $this->wBuf_ = '';
    $this->transport_->write($out);
    $this->transport_->flush();
  }
}


text:
<component name="libraryTable">
  <library name="Maven: commons-digester:commons-digester:1.8.1">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/commons-digester/commons-digester/1.8.1/commons-digester-1.8.1.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/commons-digester/commons-digester/1.8.1/commons-digester-1.8.1-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/commons-digester/commons-digester/1.8.1/commons-digester-1.8.1-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
<?php

namespace SM\Bundle\AdminBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\UnitOfWork;
use Doctrine\Common\Collections\Criteria;

/**
 * CategoryRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class CategoryRepository extends EntityRepository
{
    /**
     *
     * @param type $limit
     * @param type $offset
     * @param type $criteria ==> array(
     *                              0 => array (
     *                                  'op' => 'LIKE'
     *                                  'fieldName' => 'name'
     *                                  'fieldValue' => 'ABC'
     *                              )
     *                              1 => array (
     *                                  'op' => '>'
     *                                  'fieldName' => 'id'
     *                                  'fieldValue' => '2'
     *                              )
     *                          )
     * @param type $orderBy ==> array(
     *                              0 => array()
     *                          )
     * @return type
     */
    public function getList($limit = null, $offset = null, $criteria = array(), $orderBy = array('lft' => 'ASC'))
    {
        $qb = $this->createQueryBuilder('t');
        $qb->select('t');

        if (!empty($limit)) {
            $qb->setMaxResults($limit);
        }

        if (!empty($offset)) {
            $qb->setFirstResult($offset);
        }

        if (is_array($criteria) && count($criteria) > 0) {
            foreach ($criteria as $key => $cri) {
                $qb->andWhere("t." . $cri['fieldName']. " ". $cri['op']." ". " ?$key");

                if ($cri['op'] == 'LIKE') {
                    $qb->setParameter($key, "%".$cri['fieldName']."%");
                } else {
                    $qb->setParameter($key, $cri['fieldValue']);
                }
            }
        }

        if (is_array($orderBy) && count($orderBy) > 0) {
            foreach ($orderBy as $fieldName => $sort) {
                $qb->orderBy("t.$fieldName", $sort);
            }
        }
        //echo $qb->getQuery()->getSQL();
        return $qb->getQuery()->getResult();

    }

    /**
     * get total item
     *
     * @param type $criteria
     * @return total
     */
    public function getTotal($criteria = array())
    {
        $qb = $this->createQueryBuilder('t');
        $qb->select('COUNT(t.id) as total');
        if (is_array($criteria) && count($criteria) > 0) {
            foreach ($criteria as $key => $cri) {
                $qb->andWhere("t." . $cri['fieldName']. " ". $cri['op']." ". " ?$key");

                if ($cri['op'] == 'LIKE') {
                    $qb->setParameter($key, "%".$cri['fieldName']."%");
                } else {
                    $qb->setParameter($key, $cri['fieldValue']);
                }
            }
        }
        //echo $qb->getQuery()->getSQL();
        $rst = $qb->getQuery()->getScalarResult();
        if (!empty($rst[0]['total'])) {

            return $rst[0]['total'];
        }

        return 0;
    }

    /**
     * Delete language by array id
     *
     * @param array $ids
     *
     * @return array
     */
    public function deleteByIds($ids = array())
    {
        $em = $this->getEntityManager();
        $rst = array();
        if (is_array($ids) && count($ids)) {
            foreach ($ids as $id) {
                $entity = $this->find($id);
                $em->remove($entity);
                if ($em->getUnitOfWork()->getEntityState($entity) == UnitOfWork::STATE_REMOVED) {
                    $rst[] = $id;
                }
            }
            $em->flush();
        }

        return $rst;
    }

    /**
     * get page root
     *
     * @return Page the entity page
     */
    public function getPageRoot()
    {
        $queryBuilder = $this->createQueryBuilder('j');
        $queryBuilder->andWhere('j.parent is NULL');
        $query = $queryBuilder->getQuery();
        $rst = $query->getResult();
        if (!empty($rst[0])) {

            return $rst[0];
        } else {
            $stmt = $this->_em
                    ->getConnection()
                    ->prepare("INSERT INTO {$this->_class->getTableName()} (lft, rgt) VALUES (0, 0)");
            $stmt->execute();
            $root = $this->_em->getRepository($this->_entityName)
                    ->find($this->_em->getConnection()->lastInsertId());

            return $root;
        }

        return null;
    }

    /**
     * getChildren
     *
     * @param type $parentId the id
     *
     * @return array
     */
    public function getChildren($parentId)
    {
        return $this->getEntityManager()
                        ->getRepository('SMAdminBundle:Category')
                        ->createQueryBuilder('c')
                        ->where('c.parent = :parentId')
                        ->andWhere('c.parent != c.id')
                        ->setParameter('parentId', $parentId)
                        ->orderBy('c.lft', 'ASC')
                        ->getQuery()
                        ->getResult();
    }

    /**
     * getChildrenArray
     *
     * @param type $parentId the id
     *
     * @return array
     */
    public function getChildrenArray($parentId)
    {
        return $this->getEntityManager()
                        ->getRepository('SMAdminBundle:Category')
                        ->createQueryBuilder('c')
                        ->select('c.id, c.lft, c.rgt')
                        ->where('c.parent = :parentId')
                        ->andWhere('c.parent != c.id')
                        ->setParameter('parentId', $parentId)
                        ->orderBy('c.lft', 'ASC')
                        ->getQuery()
                        ->getArrayResult();
    }

    /**
     * @param type $idPage The id of page
     * @param type $lft    Position of left
     * @param type $rgt    Position of right
     *
     * @return type
     */
    public function setLftRgt($idPage, $lft, $rgt)
    {
        return $this->getEntityManager()
                        ->getRepository('SMAdminBundle:Category')
                        ->createQueryBuilder('c')
                        ->update()
                        ->set('c.lft', $lft)
                        ->set('c.rgt', $rgt)
                        ->where('c.id = :id')
                        ->setParameter('id', $idPage)
                        ->getQuery()
                        ->execute();
    }

    /**
     * @param type $idPage The id of page
     *
     * @return type
     */
    public function getEntityArray($idPage)
    {
        return $this->getEntityManager()
                        ->getRepository('SMAdminBundle:Category')
                        ->createQueryBuilder('c')
                        ->select('c.id, c.lft, c.rgt')
                        ->where('c.id = :id')
                        ->setParameter('id', $idPage)
                        ->getQuery()
                        ->getArrayResult();
    }

    /**
     * @param type $options the option
     *
     * @return null
     */
    public function findOneArrayBy($options = array())
    {
        $queryBuilder = $this->getEntityManager()
                ->getRepository('SMAdminBundle:Category')
                ->createQueryBuilder('c')
                ->select('c.id, c.lft, c.rgt');
        $num = 0;
        foreach ($options as $key => $option) {
            $queryBuilder->andWhere("c.$key = :ii$num")
                    ->setParameter("ii$num", $option);
        }
        $rerult = $queryBuilder->getQuery()->getArrayResult();
        if (is_array($rerult) and count($rerult) > 0) {

            return $rerult[0];
        }

        return null;
    }

    /**
     * @return boolean
     */
    public function rebuildLftRgt()
    {
        //get all parent tree
        $trees = $this->getEntityManager()
                ->getRepository('SMAdminBundle:Category')
                ->createQueryBuilder('c')
                ->select('c.id, c.lft, c.rgt')
                ->where('c.parent IS NULL')
                ->getQuery()
                ->getArrayResult();
        $begin = 1;
        $end = 0;
        foreach ($trees as $tree) {
            $this->postOrderTraversal($tree, $begin, $end);
            $begin = $end + 1;
        }

        return true;
    }

    /**
     * @param type $tree  tree
     * @param type $begin begin
     * @param type &$end  end
     */
    public function postOrderTraversal($tree, $begin, &$end)
    {
        $repositor = $this->_em->getRepository('SMAdminBundle:Category');
        //get $tree childrens
        $children = $this->_em->getRepository('SMAdminBundle:Category')
                ->getChildrenArray($tree['id']);

        $tree['lft'] = $begin;
        $end = ++$begin;
        //Travesal the tree
        foreach ($children as $child) {
            $repositor->postOrderTraversal($child, $begin, $end);
            $begin = ++$end;
        }
        $tree['rgt'] = $end;
        $this->setLftRgt($tree['id'], $tree['lft'], $tree['rgt']);
    }

    /**
     * @param \SM\Bundle\AdminBundle\Entity\Category $page the page
     */
    public function moveUp(\SM\Bundle\AdminBundle\Entity\Category $page)
    {
        //get the area upper
        $entityManager = $this->_em;
        $pageArray = array(
            'id' => $page->getId(),
            'lft' => $page->getLft(),
            'rgt' => $page->getRgt(),
        );

        $repositor = $entityManager->getRepository('SMAdminBundle:Category');
        $pageUpper = $repositor->findOneArrayBy(array('rgt' => ($pageArray['lft'] - 1)));

        if ($pageUpper) {
            $del1 = $pageArray['rgt'] - $pageArray['lft'];
            $del2 = $pageUpper['rgt'] - $pageUpper['lft'];

            //calculate new lft, rgt of 2 node and swap
            $pageArray['lft'] = $pageUpper['lft'];
            $pageArray['rgt'] = $pageArray['lft'] + $del1;
            $pageUpper['lft'] = $pageArray['rgt'] + 1;
            $pageUpper['rgt'] = $pageUpper['lft'] + $del2;
            $end = 0;
            //save new order
            $repositor->postOrderTraversal($pageUpper, $pageUpper['lft'], $end);
            $repositor->postOrderTraversal($pageArray, $pageArray['lft'], $end);
        }
    }

    /**
     * @param \SM\Bundle\AdminBundle\Entity\Category $page the page
     */
    public function moveDown(\SM\Bundle\AdminBundle\Entity\Category $page)
    {
        //get the area upper
        $entityManager = $this->_em;
        $pageArray = array(
            'id' => $page->getId(),
            'lft' => $page->getLft(),
            'rgt' => $page->getRgt(),
        );

        $repositor = $entityManager->getRepository('SMAdminBundle:Category');
        $pageUnder = $repositor->findOneArrayBy(array('lft' => ($pageArray['rgt'] + 1)));
        if ($pageUnder) {
            $del1 = $pageArray['rgt'] - $pageArray['lft'];
            $del2 = $pageUnder['rgt'] - $pageUnder['lft'];

            //calculate new lft, rgt of 2 node and swap
            $pageUnder['lft'] = $pageArray['lft'];
            $pageUnder['rgt'] = $pageArray['lft'] + $del2;
            $pageArray['lft'] = $pageUnder['rgt'] + 1;
            $pageArray['rgt'] = $pageArray['lft'] + $del1;
            $end = 0;
            //save new order
            $repositor->postOrderTraversal($pageUnder, $pageUnder['lft'], $end);
            $repositor->postOrderTraversal($pageArray, $pageArray['lft'], $end);
        }
    }

    /**
     * @param type $lft lft
     * @param type $rgt rgt
     *
     * @return type
     */
    public function getAllChildren($lft, $rgt)
    {
        return $this->getEntityManager()
                ->getRepository($this->_entityName)
                ->createQueryBuilder('c')
                ->where('c.lft >= :lft')
                ->andWhere('c.rgt != :rgt')
                ->setParameters(array('lft' => $lft, 'rgt' => $rgt))
                ->orderBy('c.lft', 'ASC')
                ->getQuery()
                ->getResult();
    }

    /**
     * get option that to build param in the menu type
     *
     * @return type
     */
    public function getOptions()
    {
        $options = array();

        //get list language
        $repLanguage = $this->getEntityManager()->getRepository("SMAdminBundle:Language");
        //Get list language
        $langList = $repLanguage->getList();
        $defaultLanguage = null;
        if (is_array($langList)) {
            foreach ($langList as $language) {
                if ($language->getIsDefault()) {
                    $defaultLanguage = $language;
                }
            }
        }

        $criteria = array();
        $criteria[] = array('op' => '>', 'fieldName' => 'lft', 'fieldValue' => '1');
        $criteria[] = array('op' => '=', 'fieldName' => 'status', 'fieldValue' => '1');

        $entities = $this->getList(null, null, $criteria, array('lft' => 'ASC'));
        foreach ($entities as $obj) {
            $obj->setLanguage($defaultLanguage);
            $std = new \stdClass();
            $std->name = $obj->getCurrentLanguage()->getTreeName();
            $std->id = $obj->getId();
            $options[] = $std;
        }

        return $options;
    }
}


text:
module ngms {
  'use strict';

  export interface IMessageService {
    getChannel(channelName: string): IChannel;
    publishSync(channelName: string, message?: string | IMessage): void;
    publish(channelName: string, message?: string | IMessage): ng.IPromise<any>;
    subscribe(channelName: string, callback: ICallback, oneTime?: boolean): IToken;
    unsubscribe(token: IToken): void;
    getServiceStats(): any;
  }

  export interface IMessage {
    [index: string]: any;
    $msgId?: string;
  }

  export interface IToken {
    channelName: string;
    tokenId: string;
  }

  export interface IChannel {
    getName(): string;
    publishSync(message?: string | IMessage): void;
    publish(message?: string | IMessage): ng.IPromise<any>;
    subscribe(callback: ICallback, oneTime?: boolean): IToken;
    unsubscribe(token: IToken): void;
    unsubscribeAll(): void;
  }

  export interface ICallback {
    (message: IMessage, channelName?: string): void;
  }

}


text:
package record

import (
	"fmt"
	"math/rand"
	"time"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/client"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/watch"

	"github.com/golang/glog"
)

const maxTriesPerEvent = 12

var sleepDuration = 10 * time.Second

// EventSink knows how to store events (client.Client implements it.)
// EventSink must respect the namespace that will be embedded in 'event'.
// It is assumed that EventSink will return the same sorts of errors as
// pkg/client's REST client.
type EventSink interface {
	Create(event *api.Event) (*api.Event, error)
	Update(event *api.Event) (*api.Event, error)
}

var emptySource = api.EventSource{}

// StartRecording starts sending events to a sink. Call once while initializing
// your binary. Subsequent calls will be ignored. The return value can be ignored
// or used to stop recording, if desired.
// TODO: make me an object with parameterizable queue length and retry interval
func StartRecording(sink EventSink) watch.Interface {
	// The default math/rand package functions aren't thread safe, so create a
	// new Rand object for each StartRecording call.
	randGen := rand.New(rand.NewSource(time.Now().UnixNano()))
	return GetEvents(func(event *api.Event) {
		// Make a copy before modification, because there could be multiple listeners.
		// Events are safe to copy like this.
		eventCopy := *event
		event = &eventCopy

		previousEvent := getEvent(event)
		updateExistingEvent := previousEvent.Count > 0
		if updateExistingEvent {
			event.Count = previousEvent.Count + 1
			event.FirstTimestamp = previousEvent.FirstTimestamp
			event.Name = previousEvent.Name
			event.ResourceVersion = previousEvent.ResourceVersion
		}

		tries := 0
		for {
			if recordEvent(sink, event, updateExistingEvent) {
				break
			}
			tries++
			if tries >= maxTriesPerEvent {
				glog.Errorf("Unable to write event '%#v' (retry limit exceeded!)", event)
				break
			}
			// Randomize the first sleep so that various clients won't all be
			// synced up if the master goes down.
			if tries == 1 {
				time.Sleep(time.Duration(float64(sleepDuration) * randGen.Float64()))
			} else {
				time.Sleep(sleepDuration)
			}
		}
	})
}

// recordEvent attempts to write event to a sink. It returns true if the event
// was successfully recorded or discarded, false if it should be retried.
// If updateExistingEvent is false, it creates a new event, otherwise it updates
// existing event.
func recordEvent(sink EventSink, event *api.Event, updateExistingEvent bool) bool {
	var newEvent *api.Event
	var err error
	if updateExistingEvent {
		newEvent, err = sink.Update(event)
	} else {
		newEvent, err = sink.Create(event)
	}
	if err == nil {
		addOrUpdateEvent(newEvent)
		return true
	}

	// If we can't contact the server, then hold everything while we keep trying.
	// Otherwise, something about the event is malformed and we should abandon it.
	giveUp := false
	switch err.(type) {
	case *client.RequestConstructionError:
		// We will construct the request the same next time, so don't keep trying.
		giveUp = true
	case *errors.StatusError:
		// This indicates that the server understood and rejected our request.
		giveUp = true
	case *errors.UnexpectedObjectError:
		// We don't expect this; it implies the server's response didn't match a
		// known pattern. Go ahead and retry.
	default:
		// This case includes actual http transport errors. Go ahead and retry.
	}
	if giveUp {
		glog.Errorf("Unable to write event '%#v': '%v' (will not retry!)", event, err)
		return true
	}
	glog.Errorf("Unable to write event: '%v' (may retry after sleeping)", err)
	return false
}

// StartLogging just logs local events, using the given logging function. The
// return value can be ignored or used to stop logging, if desired.
func StartLogging(logf func(format string, args ...interface{})) watch.Interface {
	return GetEvents(func(e *api.Event) {
		logf("Event(%#v): reason: '%v' %v", e.InvolvedObject, e.Reason, e.Message)
	})
}

// GetEvents lets you see *local* events. Convenience function for testing. The
// return value can be ignored or used to stop logging, if desired.
func GetEvents(f func(*api.Event)) watch.Interface {
	w := events.Watch()
	go func() {
		defer util.HandleCrash()
		for {
			watchEvent, open := <-w.ResultChan()
			if !open {
				return
			}
			event, ok := watchEvent.Object.(*api.Event)
			if !ok {
				// This is all local, so there's no reason this should
				// ever happen.
				continue
			}
			f(event)
		}
	}()
	return w
}

const maxQueuedEvents = 1000

var events = watch.NewBroadcaster(maxQueuedEvents, watch.DropIfChannelFull)

// EventRecorder knows how to record events for an EventSource.
type EventRecorder interface {
	// Event constructs an event from the given information and puts it in the queue for sending.
	// 'object' is the object this event is about. Event will make a reference-- or you may also
	// pass a reference to the object directly.
	// 'reason' is the reason this event is generated. 'reason' should be short and unique; it will
	// be used to automate handling of events, so imagine people writing switch statements to
	// handle them. You want to make that easy.
	// 'message' is intended to be human readable.
	//
	// The resulting event will be created in the same namespace as the reference object.
	Event(object runtime.Object, reason, message string)

	// Eventf is just like Event, but with Sprintf for the message field.
	Eventf(object runtime.Object, reason, messageFmt string, args ...interface{})
}

// FromSource returns an EventRecorder that records events with the
// given event source.
func FromSource(source api.EventSource) EventRecorder {
	return &recorderImpl{source}
}

type recorderImpl struct {
	source api.EventSource
}

func (i *recorderImpl) Event(object runtime.Object, reason, message string) {
	ref, err := api.GetReference(object)
	if err != nil {
		glog.Errorf("Could not construct reference to: '%#v' due to: '%v'. Will not report event: '%v' '%v'", object, err, reason, message)
	}

	e := makeEvent(ref, reason, message)
	e.Source = i.source

	events.Action(watch.Added, e)
}

func (i *recorderImpl) Eventf(object runtime.Object, reason, messageFmt string, args ...interface{}) {
	i.Event(object, reason, fmt.Sprintf(messageFmt, args...))
}

func makeEvent(ref *api.ObjectReference, reason, message string) *api.Event {
	t := util.Now()
	return &api.Event{
		ObjectMeta: api.ObjectMeta{
			Name:      fmt.Sprintf("%v.%x", ref.Name, t.UnixNano()),
			Namespace: ref.Namespace,
		},
		InvolvedObject: *ref,
		Reason:         reason,
		Message:        message,
		FirstTimestamp: t,
		LastTimestamp:  t,
		Count:          1,
	}
}


text:
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;

fn les_1() {
    run_test(&Instruction { mnemonic: Mnemonic::LES, operand1: Some(Direct(CX)), operand2: Some(Indirect(SI, Some(OperandSize::Far16), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 12], OperandSize::Word)
}

fn les_2() {
    run_test(&Instruction { mnemonic: Mnemonic::LES, operand1: Some(Direct(BP)), operand2: Some(IndirectScaledDisplaced(ECX, Two, 364033544, Some(OperandSize::Far16), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 196, 44, 77, 8, 182, 178, 21], OperandSize::Dword)
}

fn les_3() {
    run_test(&Instruction { mnemonic: Mnemonic::LES, operand1: Some(Direct(EDI)), operand2: Some(IndirectScaledIndexedDisplaced(EBX, EDI, Eight, 1495242058, Some(OperandSize::Far32), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 188, 251, 74, 149, 31, 89], OperandSize::Dword)
}


text:
   * JavaScript function are fully optimized with object function.
   * TEX type javascript print function.
   * And easy to apply the attributes values.
   * Don't include any other symbol's.Only mention attribute Name.
   * Id's & class are added.


text:
package com.aripd.aricl.backstretch;

import javax.faces.application.ResourceDependencies;
import javax.faces.application.ResourceDependency;
import javax.faces.component.FacesComponent;
import javax.faces.component.UIComponentBase;
import javax.faces.component.UINamingContainer;
import javax.faces.context.FacesContext;
import org.primefaces.component.api.Widget;

@FacesComponent(value = Backstretch.COMPONENT_TYPE)
@ResourceDependencies({
    @ResourceDependency(library = "primefaces", name = "jquery/jquery.js"),
    @ResourceDependency(library = "primefaces", name = "core.js"),
    @ResourceDependency(library = "backstretch", name = "jquery.backstretch.js"),
    @ResourceDependency(library = "backstretch", name = "backstretch.js")})
public class Backstretch extends UIComponentBase implements Widget {

    public static final String COMPONENT_TYPE = "com.aripd.aricl.Backstretch";
    public static final String COMPONENT_FAMILY = "com.aripd.aricl";
    public static final String DEFAULT_RENDERER = "com.aripd.aricl.BackstretchRenderer";

    protected enum PropertyKeys {

        widgetVar, value, var, style, styleClass,
        centeredX, centeredY, fade, duration;

        String toString;

        PropertyKeys(String toString) {
            this.toString = toString;
        }

        PropertyKeys() {
        }

        @Override
        public String toString() {
            return ((this.toString != null) ? this.toString : super.toString());
        }
    }

    public Backstretch() {
        setRendererType(DEFAULT_RENDERER);
    }

    @Override
    public String getFamily() {
        return COMPONENT_FAMILY;
    }

    public String getWidgetVar() {
        return (String) getStateHelper().eval(PropertyKeys.widgetVar, null);
    }

    public void setWidgetVar(String _widgetVar) {
        getStateHelper().put(PropertyKeys.widgetVar, _widgetVar);
    }

    public java.lang.Object getValue() {
        return (java.lang.Object) getStateHelper().eval(PropertyKeys.value, null);
    }

    public void setValue(java.lang.Object _value) {
        getStateHelper().put(PropertyKeys.value, _value);
    }

    public String getVar() {
        return (String) getStateHelper().eval(PropertyKeys.var, null);
    }

    public void setVar(String _var) {
        getStateHelper().put(PropertyKeys.var, _var);
    }

    public String getStyle() {
        return (String) getStateHelper().eval(PropertyKeys.style, null);
    }

    public void setStyle(String _style) {
        getStateHelper().put(PropertyKeys.style, _style);
    }

    public String getStyleClass() {
        return (String) getStateHelper().eval(PropertyKeys.styleClass, null);
    }

    public void setStyleClass(String _styleClass) {
        getStateHelper().put(PropertyKeys.styleClass, _styleClass);
    }

    public boolean isCenteredX() {
        return Boolean.TRUE.equals(this.getStateHelper().eval(PropertyKeys.centeredX, false));
    }

    public void setCenteredX(boolean centeredX) {
        this.getStateHelper().put(PropertyKeys.centeredX, centeredX);
    }

    public boolean isCenteredY() {
        return Boolean.TRUE.equals(this.getStateHelper().eval(PropertyKeys.centeredY, false));
    }

    public void setCenteredY(boolean centeredY) {
        this.getStateHelper().put(PropertyKeys.centeredY, centeredY);
    }

    public String getFade() {
        return (String) getStateHelper().eval(PropertyKeys.fade, 0);
    }

    public void setFade(String fade) {
        getStateHelper().put(PropertyKeys.fade, fade);
    }

    public Integer getDuration() {
        return (Integer) getStateHelper().eval(PropertyKeys.duration, 5000);
    }

    public void setDuration(Integer duration) {
        getStateHelper().put(PropertyKeys.duration, duration);
    }

    public final static String CONTAINER_CLASS = "ui-backstretch ui-widget ui-widget-content ui-corner-all";
    public final static String PANEL_WRAPPER_CLASS = "ui-backstretch-panel-wrapper";
    public final static String PANEL_CLASS = "ui-backstretch-panel ui-helper-hidden";
    public final static String PANEL_CONTENT_CLASS = "ui-backstretch-panel-content";

    @Override
    public String resolveWidgetVar() {
        FacesContext context = getFacesContext();
        String userWidgetVar = (String) getAttributes().get("widgetVar");

        if (userWidgetVar != null) {
            return userWidgetVar;
        } else {
            return "widget_"
                    + getClientId(context).replaceAll(
                            "-|" + UINamingContainer.getSeparatorChar(context),
                            "_");
        }
    }

}