text:
#include "config.h"

#include "gmenumodel.h"

/**
 * SECTION:gmenumodel
 * @title: GMenuModel
 * @short_description: An abstract class representing the contents of a menu
 * @include: gio/gio.h
 * @see_also: #GActionGroup
 *
 * #GMenuModel represents the contents of a menu -- an ordered list of
 * menu items. The items are associated with actions, which can be
 * activated through them. Items can be grouped in sections, and may
 * have submenus associated with them. Both items and sections usually
 * have some representation data, such as labels or icons. The type of
 * the associated action (ie whether it is stateful, and what kind of
 * state it has) can influence the representation of the item.
 *
 * The conceptual model of menus in #GMenuModel is hierarchical:
 * sections and submenus are again represented by #GMenuModels.
 * Menus themselves do not define their own roles. Rather, the role
 * of a particular #GMenuModel is defined by the item that references
 * it (or, in the case of the 'root' menu, is defined by the context
 * in which it is used).
 *
 * As an example, consider the visible portions of this menu:
 *
 * ## An example menu # {#menu-example}
 *
 * ![](menu-example.png)
 *
 * There are 8 "menus" visible in the screenshot: one menubar, two
 * submenus and 5 sections:
 *
 * - the toplevel menubar (containing 4 items)
 * - the View submenu (containing 3 sections)
 * - the first section of the View submenu (containing 2 items)
 * - the second section of the View submenu (containing 1 item)
 * - the final section of the View submenu (containing 1 item)
 * - the Highlight Mode submenu (containing 2 sections)
 * - the Sources section (containing 2 items)
 * - the Markup section (containing 2 items)
 *
 * The [example][menu-model] illustrates the conceptual connection between
 * these 8 menus. Each large block in the figure represents a menu and the
 * smaller blocks within the large block represent items in that menu. Some
 * items contain references to other menus.
 *
 * ## A menu example # {#menu-model}
 *
 * ![](menu-model.png)
 *
 * Notice that the separators visible in the [example][menu-example]
 * appear nowhere in the [menu model][menu-model]. This is because
 * separators are not explicitly represented in the menu model. Instead,
 * a separator is inserted between any two non-empty sections of a menu.
 * Section items can have labels just like any other item. In that case,
 * a display system may show a section header instead of a separator.
 *
 * The motivation for this abstract model of application controls is
 * that modern user interfaces tend to make these controls available
 * outside the application. Examples include global menus, jumplists,
 * dash boards, etc. To support such uses, it is necessary to 'export'
 * information about actions and their representation in menus, which
 * is exactly what the [GActionGroup exporter][gio-GActionGroup-exporter]
 * and the [GMenuModel exporter][gio-GMenuModel-exporter] do for
 * #GActionGroup and #GMenuModel. The client-side counterparts to
 * make use of the exported information are #GDBusActionGroup and
 * #GDBusMenuModel.
 *
 * The API of #GMenuModel is very generic, with iterators for the
 * attributes and links of an item, see g_menu_model_iterate_item_attributes()
 * and g_menu_model_iterate_item_links(). The 'standard' attributes and
 * link types have predefined names: %G_MENU_ATTRIBUTE_LABEL,
 * %G_MENU_ATTRIBUTE_ACTION, %G_MENU_ATTRIBUTE_TARGET, %G_MENU_LINK_SECTION
 * and %G_MENU_LINK_SUBMENU.
 *
 * Items in a #GMenuModel represent active controls if they refer to
 * an action that can get activated when the user interacts with the
 * menu item. The reference to the action is encoded by the string id
 * in the %G_MENU_ATTRIBUTE_ACTION attribute. An action id uniquely
 * identifies an action in an action group. Which action group(s) provide
 * actions depends on the context in which the menu model is used.
 * E.g. when the model is exported as the application menu of a
 * #GtkApplication, actions can be application-wide or window-specific
 * (and thus come from two different action groups). By convention, the
 * application-wide actions have names that start with "app.", while the
 * names of window-specific actions start with "win.".
 *
 * While a wide variety of stateful actions is possible, the following
 * is the minimum that is expected to be supported by all users of exported
 * menu information:
 * - an action with no parameter type and no state
 * - an action with no parameter type and boolean state
 * - an action with string parameter type and string state
 *
 * ## Stateless
 *
 * A stateless action typically corresponds to an ordinary menu item.
 *
 * Selecting such a menu item will activate the action (with no parameter).
 *
 * ## Boolean State
 *
 * An action with a boolean state will most typically be used with a "toggle"
 * or "switch" menu item. The state can be set directly, but activating the
 * action (with no parameter) results in the state being toggled.
 *
 * Selecting a toggle menu item will activate the action. The menu item should
 * be rendered as "checked" when the state is true.
 *
 * ## String Parameter and State
 *
 * Actions with string parameters and state will most typically be used to
 * represent an enumerated choice over the items available for a group of
 * radio menu items. Activating the action with a string parameter is
 * equivalent to setting that parameter as the state.
 *
 * Radio menu items, in addition to being associated with the action, will
 * have a target value. Selecting that menu item will result in activation
 * of the action with the target value as the parameter. The menu item should
 * be rendered as "selected" when the state of the action is equal to the
 * target value of the menu item.
 */

/**
 * GMenuModel:
 *
 * #GMenuModel is an opaque structure type.  You must access it using the
 * functions below.
 *
 * Since: 2.32
 */

/**
 * GMenuAttributeIter:
 *
 * #GMenuAttributeIter is an opaque structure type.  You must access it
 * using the functions below.
 *
 * Since: 2.32
 */

/**
 * GMenuLinkIter:
 *
 * #GMenuLinkIter is an opaque structure type.  You must access it using
 * the functions below.
 *
 * Since: 2.32
 */

typedef struct
{
  GMenuLinkIter parent_instance;
  GHashTableIter iter;
  GHashTable *table;
} GMenuLinkHashIter;

typedef GMenuLinkIterClass GMenuLinkHashIterClass;

static GType g_menu_link_hash_iter_get_type (void);

G_DEFINE_TYPE (GMenuLinkHashIter, g_menu_link_hash_iter, G_TYPE_MENU_LINK_ITER)

static gboolean
g_menu_link_hash_iter_get_next (GMenuLinkIter  *link_iter,
                                const gchar   **out_name,
                                GMenuModel    **value)
{
  GMenuLinkHashIter *iter = (GMenuLinkHashIter *) link_iter;
  gpointer keyptr, valueptr;

  if (!g_hash_table_iter_next (&iter->iter, &keyptr, &valueptr))
    return FALSE;

  *out_name = keyptr;
  *value = g_object_ref (valueptr);

  return TRUE;
}

static void
g_menu_link_hash_iter_finalize (GObject *object)
{
  GMenuLinkHashIter *iter = (GMenuLinkHashIter *) object;

  g_hash_table_unref (iter->table);

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

static void
g_menu_link_hash_iter_init (GMenuLinkHashIter *iter)
{
}

static void
g_menu_link_hash_iter_class_init (GMenuLinkHashIterClass *class)
{
  GObjectClass *object_class = G_OBJECT_CLASS (class);

  object_class->finalize = g_menu_link_hash_iter_finalize;
  class->get_next = g_menu_link_hash_iter_get_next;
}

typedef struct
{
  GMenuAttributeIter parent_instance;
  GHashTableIter iter;
  GHashTable *table;
} GMenuAttributeHashIter;

typedef GMenuAttributeIterClass GMenuAttributeHashIterClass;

static GType g_menu_attribute_hash_iter_get_type (void);

G_DEFINE_TYPE (GMenuAttributeHashIter, g_menu_attribute_hash_iter, G_TYPE_MENU_ATTRIBUTE_ITER)

static gboolean
g_menu_attribute_hash_iter_get_next (GMenuAttributeIter  *attr_iter,
                                     const gchar        **name,
                                     GVariant           **value)
{
  GMenuAttributeHashIter *iter = (GMenuAttributeHashIter *) attr_iter;
  gpointer keyptr, valueptr;

  if (!g_hash_table_iter_next (&iter->iter, &keyptr, &valueptr))
    return FALSE;

  *name = keyptr;

  *value = g_variant_ref (valueptr);

  return TRUE;
}

static void
g_menu_attribute_hash_iter_finalize (GObject *object)
{
  GMenuAttributeHashIter *iter = (GMenuAttributeHashIter *) object;

  g_hash_table_unref (iter->table);

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

static void
g_menu_attribute_hash_iter_init (GMenuAttributeHashIter *iter)
{
}

static void
g_menu_attribute_hash_iter_class_init (GMenuAttributeHashIterClass *class)
{
  GObjectClass *object_class = G_OBJECT_CLASS (class);

  object_class->finalize = g_menu_attribute_hash_iter_finalize;
  class->get_next = g_menu_attribute_hash_iter_get_next;
}

G_DEFINE_ABSTRACT_TYPE (GMenuModel, g_menu_model, G_TYPE_OBJECT)

static guint g_menu_model_items_changed_signal;

static GMenuAttributeIter *
g_menu_model_real_iterate_item_attributes (GMenuModel *model,
                                           gint        item_index)
{
  GHashTable *table = NULL;
  GMenuAttributeIter *result;

  G_MENU_MODEL_GET_CLASS (model)->get_item_attributes (model, item_index, &table);

  if (table)
    {
      GMenuAttributeHashIter *iter = g_object_new (g_menu_attribute_hash_iter_get_type (), NULL);
      g_hash_table_iter_init (&iter->iter, table);
      iter->table = g_hash_table_ref (table);
      result = G_MENU_ATTRIBUTE_ITER (iter);
    }
  else
    {
      g_critical ("GMenuModel implementation '%s' doesn't override iterate_item_attributes() "
                  "and fails to return sane values from get_item_attributes()",
                  G_OBJECT_TYPE_NAME (model));
      result = NULL;
    }

  if (table != NULL)
    g_hash_table_unref (table);

  return result;
}

static GVariant *
g_menu_model_real_get_item_attribute_value (GMenuModel         *model,
                                            gint                item_index,
                                            const gchar        *attribute,
                                            const GVariantType *expected_type)
{
  GHashTable *table = NULL;
  GVariant *value = NULL;

  G_MENU_MODEL_GET_CLASS (model)
    ->get_item_attributes (model, item_index, &table);

  if (table != NULL)
    {
      value = g_hash_table_lookup (table, attribute);

      if (value != NULL)
        {
          if (expected_type == NULL || g_variant_is_of_type (value, expected_type))
            value = g_variant_ref (value);
          else
            value = NULL;
        }
    }
  else
    g_assert_not_reached ();

  if (table != NULL)
    g_hash_table_unref (table);

  return value;
}

static GMenuLinkIter *
g_menu_model_real_iterate_item_links (GMenuModel *model,
                                      gint        item_index)
{
  GHashTable *table = NULL;
  GMenuLinkIter *result;

  G_MENU_MODEL_GET_CLASS (model)
    ->get_item_links (model, item_index, &table);

  if (table)
    {
      GMenuLinkHashIter *iter = g_object_new (g_menu_link_hash_iter_get_type (), NULL);
      g_hash_table_iter_init (&iter->iter, table);
      iter->table = g_hash_table_ref (table);
      result = G_MENU_LINK_ITER (iter);
    }
  else
    {
      g_critical ("GMenuModel implementation '%s' doesn't override iterate_item_links() "
                  "and fails to return sane values from get_item_links()",
                  G_OBJECT_TYPE_NAME (model));
      result = NULL;
    }

  if (table != NULL)
    g_hash_table_unref (table);

  return result;
}

static GMenuModel *
g_menu_model_real_get_item_link (GMenuModel  *model,
                                 gint         item_index,
                                 const gchar *link)
{
  GHashTable *table = NULL;
  GMenuModel *value = NULL;

  G_MENU_MODEL_GET_CLASS (model)
    ->get_item_links (model, item_index, &table);

  if (table != NULL)
    value = g_hash_table_lookup (table, link);
  else
    g_assert_not_reached ();

  if (value != NULL)
    g_object_ref (value);

  if (table != NULL)
    g_hash_table_unref (table);

  return value;
}

static void
g_menu_model_init (GMenuModel *model)
{
}

static void
g_menu_model_class_init (GMenuModelClass *class)
{
  class->iterate_item_attributes = g_menu_model_real_iterate_item_attributes;
  class->get_item_attribute_value = g_menu_model_real_get_item_attribute_value;
  class->iterate_item_links = g_menu_model_real_iterate_item_links;
  class->get_item_link = g_menu_model_real_get_item_link;

  /**
   * GMenuModel::items-changed:
   * @model: the #GMenuModel that is changing
   * @position: the position of the change
   * @removed: the number of items removed
   * @added: the number of items added
   *
   * Emitted when a change has occured to the menu.
   *
   * The only changes that can occur to a menu is that items are removed
   * or added.  Items may not change (except by being removed and added
   * back in the same location).  This signal is capable of describing
   * both of those changes (at the same time).
   *
   * The signal means that starting at the index @position, @removed
   * items were removed and @added items were added in their place.  If
   * @removed is zero then only items were added.  If @added is zero
   * then only items were removed.
   *
   * As an example, if the menu contains items a, b, c, d (in that
   * order) and the signal (2, 1, 3) occurs then the new composition of
   * the menu will be a, b, _, _, _, d (with each _ representing some
   * new item).
   *
   * Signal handlers may query the model (particularly the added items)
   * and expect to see the results of the modification that is being
   * reported.  The signal is emitted after the modification.
   **/
  g_menu_model_items_changed_signal =
    g_signal_new ("items-changed", G_TYPE_MENU_MODEL,
                  G_SIGNAL_RUN_LAST, 0, NULL, NULL,
                  g_cclosure_marshal_generic, G_TYPE_NONE,
                  3, G_TYPE_INT, G_TYPE_INT, G_TYPE_INT);
}

/**
 * g_menu_model_is_mutable:
 * @model: a #GMenuModel
 *
 * Queries if @model is mutable.
 *
 * An immutable #GMenuModel will never emit the #GMenuModel::items-changed
 * signal. Consumers of the model may make optimisations accordingly.
 *
 * Returns: %TRUE if the model is mutable (ie: "items-changed" may be
 *     emitted).
 *
 * Since: 2.32
 */
gboolean
g_menu_model_is_mutable (GMenuModel *model)
{
  return G_MENU_MODEL_GET_CLASS (model)
    ->is_mutable (model);
}

/**
 * g_menu_model_get_n_items:
 * @model: a #GMenuModel
 *
 * Query the number of items in @model.
 *
 * Returns: the number of items
 *
 * Since: 2.32
 */
gint
g_menu_model_get_n_items (GMenuModel *model)
{
  return G_MENU_MODEL_GET_CLASS (model)
    ->get_n_items (model);
}

/**
 * g_menu_model_iterate_item_attributes:
 * @model: a #GMenuModel
 * @item_index: the index of the item
 *
 * Creates a #GMenuAttributeIter to iterate over the attributes of
 * the item at position @item_index in @model.
 *
 * You must free the iterator with g_object_unref() when you are done.
 *
 * Returns: (transfer full): a new #GMenuAttributeIter
 *
 * Since: 2.32
 */
GMenuAttributeIter *
g_menu_model_iterate_item_attributes (GMenuModel *model,
                                      gint        item_index)
{
  return G_MENU_MODEL_GET_CLASS (model)
    ->iterate_item_attributes (model, item_index);
}

/**
 * g_menu_model_get_item_attribute_value:
 * @model: a #GMenuModel
 * @item_index: the index of the item
 * @attribute: the attribute to query
 * @expected_type: (allow-none): the expected type of the attribute, or
 *     %NULL
 *
 * Queries the item at position @item_index in @model for the attribute
 * specified by @attribute.
 *
 * If @expected_type is non-%NULL then it specifies the expected type of
 * the attribute.  If it is %NULL then any type will be accepted.
 *
 * If the attribute exists and matches @expected_type (or if the
 * expected type is unspecified) then the value is returned.
 *
 * If the attribute does not exist, or does not match the expected type
 * then %NULL is returned.
 *
 * Returns: (transfer full): the value of the attribute
 *
 * Since: 2.32
 */
GVariant *
g_menu_model_get_item_attribute_value (GMenuModel         *model,
                                       gint                item_index,
                                       const gchar        *attribute,
                                       const GVariantType *expected_type)
{
  return G_MENU_MODEL_GET_CLASS (model)
    ->get_item_attribute_value (model, item_index, attribute, expected_type);
}

/**
 * g_menu_model_get_item_attribute:
 * @model: a #GMenuModel
 * @item_index: the index of the item
 * @attribute: the attribute to query
 * @format_string: a #GVariant format string
 * @...: positional parameters, as per @format_string
 *
 * Queries item at position @item_index in @model for the attribute
 * specified by @attribute.
 *
 * If the attribute exists and matches the #GVariantType corresponding
 * to @format_string then @format_string is used to deconstruct the
 * value into the positional parameters and %TRUE is returned.
 *
 * If the attribute does not exist, or it does exist but has the wrong
 * type, then the positional parameters are ignored and %FALSE is
 * returned.
 *
 * This function is a mix of g_menu_model_get_item_attribute_value() and
 * g_variant_get(), followed by a g_variant_unref().  As such,
 * @format_string must make a complete copy of the data (since the
 * #GVariant may go away after the call to g_variant_unref()).  In
 * particular, no '&' characters are allowed in @format_string.
 *
 * Returns: %TRUE if the named attribute was found with the expected
 *     type
 *
 * Since: 2.32
 */
gboolean
g_menu_model_get_item_attribute (GMenuModel  *model,
                                 gint         item_index,
                                 const gchar *attribute,
                                 const gchar *format_string,
                                 ...)
{
  GVariant *value;
  va_list ap;

  value = g_menu_model_get_item_attribute_value (model, item_index, attribute, NULL);

  if (value == NULL)
    return FALSE;

  if (!g_variant_check_format_string (value, format_string, TRUE))
    {
      g_variant_unref (value);
      return FALSE;
    }

  va_start (ap, format_string);
  g_variant_get_va (value, format_string, NULL, &ap);
  g_variant_unref (value);
  va_end (ap);

  return TRUE;
}

/**
 * g_menu_model_iterate_item_links:
 * @model: a #GMenuModel
 * @item_index: the index of the item
 *
 * Creates a #GMenuLinkIter to iterate over the links of the item at
 * position @item_index in @model.
 *
 * You must free the iterator with g_object_unref() when you are done.
 *
 * Returns: (transfer full): a new #GMenuLinkIter
 *
 * Since: 2.32
 */
GMenuLinkIter *
g_menu_model_iterate_item_links (GMenuModel *model,
                                 gint        item_index)
{
  return G_MENU_MODEL_GET_CLASS (model)
    ->iterate_item_links (model, item_index);
}

/**
 * g_menu_model_get_item_link:
 * @model: a #GMenuModel
 * @item_index: the index of the item
 * @link: the link to query
 *
 * Queries the item at position @item_index in @model for the link
 * specified by @link.
 *
 * If the link exists, the linked #GMenuModel is returned.  If the link
 * does not exist, %NULL is returned.
 *
 * Returns: (transfer full): the linked #GMenuModel, or %NULL
 *
 * Since: 2.32
 */
GMenuModel *
g_menu_model_get_item_link (GMenuModel *model,
                            gint        item_index,
                            const gchar *link)
{
  return G_MENU_MODEL_GET_CLASS (model)
    ->get_item_link (model, item_index, link);
}

/**
 * g_menu_model_items_changed:
 * @model: a #GMenuModel
 * @position: the position of the change
 * @removed: the number of items removed
 * @added: the number of items added
 *
 * Requests emission of the #GMenuModel::items-changed signal on @model.
 *
 * This function should never be called except by #GMenuModel
 * subclasses.  Any other calls to this function will very likely lead
 * to a violation of the interface of the model.
 *
 * The implementation should update its internal representation of the
 * menu before emitting the signal.  The implementation should further
 * expect to receive queries about the new state of the menu (and
 * particularly added menu items) while signal handlers are running.
 *
 * The implementation must dispatch this call directly from a mainloop
 * entry and not in response to calls -- particularly those from the
 * #GMenuModel API.  Said another way: the menu must not change while
 * user code is running without returning to the mainloop.
 *
 * Since: 2.32
 */
void
g_menu_model_items_changed (GMenuModel *model,
                            gint        position,
                            gint        removed,
                            gint        added)
{
  g_signal_emit (model, g_menu_model_items_changed_signal, 0, position, removed, added);
}

struct _GMenuAttributeIterPrivate
{
  GQuark name;
  GVariant *value;
  gboolean valid;
};

G_DEFINE_ABSTRACT_TYPE_WITH_PRIVATE (GMenuAttributeIter, g_menu_attribute_iter, G_TYPE_OBJECT)

/**
 * g_menu_attribute_iter_get_next:
 * @iter: a #GMenuAttributeIter
 * @out_name: (out) (allow-none) (transfer none): the type of the attribute
 * @value: (out) (allow-none) (transfer full): the attribute value
 *
 * This function combines g_menu_attribute_iter_next() with
 * g_menu_attribute_iter_get_name() and g_menu_attribute_iter_get_value().
 *
 * First the iterator is advanced to the next (possibly first) attribute.
 * If that fails, then %FALSE is returned and there are no other
 * effects.
 *
 * If successful, @name and @value are set to the name and value of the
 * attribute that has just been advanced to.  At this point,
 * g_menu_attribute_iter_get_name() and g_menu_attribute_iter_get_value() will
 * return the same values again.
 *
 * The value returned in @name remains valid for as long as the iterator
 * remains at the current position.  The value returned in @value must
 * be unreffed using g_variant_unref() when it is no longer in use.
 *
 * Returns: %TRUE on success, or %FALSE if there is no additional
 *     attribute
 *
 * Since: 2.32
 */
gboolean
g_menu_attribute_iter_get_next (GMenuAttributeIter  *iter,
                                const gchar        **out_name,
                                GVariant           **value)
{
  const gchar *name;

  if (iter->priv->value)
    {
      g_variant_unref (iter->priv->value);
      iter->priv->value = NULL;
    }

  iter->priv->valid = G_MENU_ATTRIBUTE_ITER_GET_CLASS (iter)
    ->get_next (iter, &name, &iter->priv->value);

  if (iter->priv->valid)
    {
      iter->priv->name = g_quark_from_string (name);
      if (out_name)
        *out_name = g_quark_to_string (iter->priv->name);

      if (value)
        *value = g_variant_ref (iter->priv->value);
    }

  return iter->priv->valid;
}

/**
 * g_menu_attribute_iter_next:
 * @iter: a #GMenuAttributeIter
 *
 * Attempts to advance the iterator to the next (possibly first)
 * attribute.
 *
 * %TRUE is returned on success, or %FALSE if there are no more
 * attributes.
 *
 * You must call this function when you first acquire the iterator
 * to advance it to the first attribute (and determine if the first
 * attribute exists at all).
 *
 * Returns: %TRUE on success, or %FALSE when there are no more attributes
 *
 * Since: 2.32
 */
gboolean
g_menu_attribute_iter_next (GMenuAttributeIter *iter)
{
  return g_menu_attribute_iter_get_next (iter, NULL, NULL);
}

/**
 * g_menu_attribute_iter_get_name:
 * @iter: a #GMenuAttributeIter
 *
 * Gets the name of the attribute at the current iterator position, as
 * a string.
 *
 * The iterator is not advanced.
 *
 * Returns: the name of the attribute
 *
 * Since: 2.32
 */
const gchar *
g_menu_attribute_iter_get_name (GMenuAttributeIter *iter)
{
  g_return_val_if_fail (iter->priv->valid, 0);

  return g_quark_to_string (iter->priv->name);
}

/**
 * g_menu_attribute_iter_get_value:
 * @iter: a #GMenuAttributeIter
 *
 * Gets the value of the attribute at the current iterator position.
 *
 * The iterator is not advanced.
 *
 * Returns: (transfer full): the value of the current attribute
 *
 * Since: 2.32
 */
GVariant *
g_menu_attribute_iter_get_value (GMenuAttributeIter *iter)
{
  g_return_val_if_fail (iter->priv->valid, NULL);

  return g_variant_ref (iter->priv->value);
}

static void
g_menu_attribute_iter_finalize (GObject *object)
{
  GMenuAttributeIter *iter = G_MENU_ATTRIBUTE_ITER (object);

  if (iter->priv->value)
    g_variant_unref (iter->priv->value);

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

static void
g_menu_attribute_iter_init (GMenuAttributeIter *iter)
{
  iter->priv = g_menu_attribute_iter_get_instance_private (iter);
}

static void
g_menu_attribute_iter_class_init (GMenuAttributeIterClass *class)
{
  GObjectClass *object_class = G_OBJECT_CLASS (class);

  object_class->finalize = g_menu_attribute_iter_finalize;
}

struct _GMenuLinkIterPrivate
{
  GQuark name;
  GMenuModel *value;
  gboolean valid;
};

G_DEFINE_ABSTRACT_TYPE_WITH_PRIVATE (GMenuLinkIter, g_menu_link_iter, G_TYPE_OBJECT)

/**
 * g_menu_link_iter_get_next:
 * @iter: a #GMenuLinkIter
 * @out_link: (out) (allow-none) (transfer none): the name of the link
 * @value: (out) (allow-none) (transfer full): the linked #GMenuModel
 *
 * This function combines g_menu_link_iter_next() with
 * g_menu_link_iter_get_name() and g_menu_link_iter_get_value().
 *
 * First the iterator is advanced to the next (possibly first) link.
 * If that fails, then %FALSE is returned and there are no other effects.
 *
 * If successful, @out_link and @value are set to the name and #GMenuModel
 * of the link that has just been advanced to.  At this point,
 * g_menu_link_iter_get_name() and g_menu_link_iter_get_value() will return the
 * same values again.
 *
 * The value returned in @out_link remains valid for as long as the iterator
 * remains at the current position.  The value returned in @value must
 * be unreffed using g_object_unref() when it is no longer in use.
 *
 * Returns: %TRUE on success, or %FALSE if there is no additional link
 *
 * Since: 2.32
 */
gboolean
g_menu_link_iter_get_next (GMenuLinkIter  *iter,
                           const gchar   **out_link,
                           GMenuModel    **value)
{
  const gchar *name;

  if (iter->priv->value)
    {
      g_object_unref (iter->priv->value);
      iter->priv->value = NULL;
    }

  iter->priv->valid = G_MENU_LINK_ITER_GET_CLASS (iter)
    ->get_next (iter, &name, &iter->priv->value);

  if (iter->priv->valid)
    {
      g_assert (name != NULL);

      iter->priv->name = g_quark_from_string (name);
      if (out_link)
        *out_link = g_quark_to_string (iter->priv->name);

      if (value)
        *value = g_object_ref (iter->priv->value);
    }

  return iter->priv->valid;
}

/**
 * g_menu_link_iter_next:
 * @iter: a #GMenuLinkIter
 *
 * Attempts to advance the iterator to the next (possibly first)
 * link.
 *
 * %TRUE is returned on success, or %FALSE if there are no more links.
 *
 * You must call this function when you first acquire the iterator to
 * advance it to the first link (and determine if the first link exists
 * at all).
 *
 * Returns: %TRUE on success, or %FALSE when there are no more links
 *
 * Since: 2.32
 */
gboolean
g_menu_link_iter_next (GMenuLinkIter *iter)
{
  return g_menu_link_iter_get_next (iter, NULL, NULL);
}

/**
 * g_menu_link_iter_get_name:
 * @iter: a #GMenuLinkIter
 *
 * Gets the name of the link at the current iterator position.
 *
 * The iterator is not advanced.
 *
 * Returns: the type of the link
 *
 * Since: 2.32
 */
const gchar *
g_menu_link_iter_get_name (GMenuLinkIter *iter)
{
  g_return_val_if_fail (iter->priv->valid, 0);

  return g_quark_to_string (iter->priv->name);
}

/**
 * g_menu_link_iter_get_value:
 * @iter: a #GMenuLinkIter
 *
 * Gets the linked #GMenuModel at the current iterator position.
 *
 * The iterator is not advanced.
 *
 * Returns: (transfer full): the #GMenuModel that is linked to
 *
 * Since: 2.32
 */
GMenuModel *
g_menu_link_iter_get_value (GMenuLinkIter *iter)
{
  g_return_val_if_fail (iter->priv->valid, NULL);

  return g_object_ref (iter->priv->value);
}

static void
g_menu_link_iter_finalize (GObject *object)
{
  GMenuLinkIter *iter = G_MENU_LINK_ITER (object);

  if (iter->priv->value)
    g_object_unref (iter->priv->value);

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

static void
g_menu_link_iter_init (GMenuLinkIter *iter)
{
  iter->priv = g_menu_link_iter_get_instance_private (iter);
}

static void
g_menu_link_iter_class_init (GMenuLinkIterClass *class)
{
  GObjectClass *object_class = G_OBJECT_CLASS (class);

  object_class->finalize = g_menu_link_iter_finalize;
}


text:
package lemming.lemmatisation;

import lemming.context.Context;
import lemming.context.ContextDao;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.util.CollectionModel;

import java.util.ArrayList;
import java.util.Collection;

/**
 * Toggles the interesting flag of selected contexts.
 */
public class MarkContextLink extends AjaxLink<Void> {
    /**
     * A data table.
     */
    private final LemmatisationDataTable dataTable;

    /**
     * Creates a mark context link.
     *
     * @param dataTable a data table which delivers row models
     */
    public MarkContextLink(LemmatisationDataTable dataTable) {
        super("markContextLink");
        this.dataTable = dataTable;
        setOutputMarkupId(true);
    }

    /**
     * Renders to the web response what the component wants to contribute.
     *
     * @param response response object
     */
    @Override
    public void renderHead(IHeaderResponse response) {
        super.renderHead(response);
        // ctrl + m
        String javaScript = "jQuery(window).on('keydown', function (event) { " +
                "var modifier = event.ctrlKey || event.metaKey; " +
                "if (modifier && event.which === 77) { " +
                "jQuery('#" + getMarkupId() + "').click(); " +
                "event.preventDefault(); event.stopPropagation(); } });";
        response.render(OnDomReadyHeaderItem.forScript(javaScript));
    }

    /**
     * Called on click.
     *
     * @param target target that produces an Ajax response
     */
    @Override
    public void onClick(AjaxRequestTarget target) {
        Collection<IModel<Context>> rowModels = dataTable.getRowModels();
        CollectionModel<Integer> selectedContextIds = new CollectionModel<>(new ArrayList<>());
        ContextDao contextDao = new ContextDao();

        for (IModel<Context> rowModel : rowModels) {
            if (rowModel.getObject().getSelected()) {
                Context context = rowModel.getObject();
                context.setInteresting(!context.getInteresting());
                contextDao.merge(context);
                selectedContextIds.getObject().add(context.getId());
            }
        }

        dataTable.updateSelectedContexts(selectedContextIds);
        target.add(dataTable);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>
<link rel="stylesheet" href="../support/base.css" />

<textarea style="display: none; width: 100%"></textarea>


text:
require 'spec_helper'

describe "Kernel release fact" do

  describe "on Windows" do
    before do
      Facter.fact(:kernel).stubs(:value).returns("windows")
      require 'facter/util/wmi'
      version = stubs 'version'
      version.stubs(:Version).returns("test_kernel")
      Facter::Util::WMI.stubs(:execquery).with("SELECT Version from Win32_OperatingSystem").returns([version])
    end

    it "should return the kernel release" do
      Facter.fact(:kernelrelease).value.should == "test_kernel"
    end
  end

  describe "on AIX" do
    before do
      Facter.fact(:kernel).stubs(:value).returns("aix")
      Facter::Core::Execution.stubs(:execute).with('oslevel -s', anything).returns("test_kernel")
    end

    it "should return the kernel release" do
      Facter.fact(:kernelrelease).value.should == "test_kernel"
    end
  end

  describe "on HP-UX" do
    before do
      Facter.fact(:kernel).stubs(:value).returns("hp-ux")
      Facter::Core::Execution.stubs(:execute).with('uname -r').returns("B.11.31")
    end

    it "should remove preceding letters" do
      Facter.fact(:kernelrelease).value.should == "11.31"
    end
  end

  describe "on everything else" do
    before do
      Facter.fact(:kernel).stubs(:value).returns("linux")
      Facter::Core::Execution.stubs(:execute).with('uname -r', anything).returns("test_kernel")
    end

    it "should return the kernel release" do
      Facter.fact(:kernelrelease).value.should == "test_kernel"
    end
  end

  describe 'on OpenBSD' do
    before do
      Facter.fact(:kernel).stubs(:value).returns :openbsd
    end

    it 'parses 5.3-current sysctl output' do
      Facter::Util::POSIX.stubs(:sysctl).with("kern.version").returns(my_fixture_read('openbsd-5.3-current'))
      Facter.value(:kernelrelease).should == '5.3-current'
    end

    it 'parses 5.3 sysctl output' do
      Facter::Util::POSIX.stubs(:sysctl).with("kern.version").returns(my_fixture_read('openbsd-5.3'))
      Facter.value(:kernelrelease).should == '5.3'
    end
  end
end


text:
package com.cubes.test;

import java.util.logging.Level;
import java.util.logging.Logger;
import com.jme3.app.SimpleApplication;
import com.jme3.math.Vector3f;
import com.jme3.scene.Node;
import com.jme3.system.AppSettings;
import com.cubes.*;

public class TestTutorial extends SimpleApplication{

    public static void main(String[] args){
        Logger.getLogger("").setLevel(Level.SEVERE);
        TestTutorial app = new TestTutorial();
        app.start();
    }

    public TestTutorial(){
        settings = new AppSettings(true);
        settings.setWidth(1280);
        settings.setHeight(720);
        settings.setTitle("Cubes Demo - Tutorial");
    }

    @Override
    public void simpleInitApp(){
        CubesTestAssets.registerBlocks();

        //This is your terrain, it contains the whole
        //block world and offers methods to modify it
        BlockTerrainControl blockTerrain = new BlockTerrainControl(CubesTestAssets.getSettings(this), new Vector3Int(1, 1, 1));

        //To set a block, just specify the location and the block object
        //(Existing blocks will be replaced)
        blockTerrain.setBlock(new Vector3Int(0, 0, 0), CubesTestAssets.BLOCK_WOOD);
        blockTerrain.setBlock(new Vector3Int(0, 0, 1), CubesTestAssets.BLOCK_WOOD);
        blockTerrain.setBlock(new Vector3Int(1, 0, 0), CubesTestAssets.BLOCK_WOOD);
        blockTerrain.setBlock(new Vector3Int(1, 0, 1), CubesTestAssets.BLOCK_STONE);
        blockTerrain.setBlock(0, 0, 0, CubesTestAssets.BLOCK_GRASS); //For the lazy users :P

        //You can place whole areas of blocks too: setBlockArea(location, size, block)
        //(The specified block will be cloned each time)
        //The following line will set 3 blocks on top of each other
        //({1,1,1}, {1,2,3} and {1,3,1})
        blockTerrain.setBlockArea(new Vector3Int(1, 1, 1), new Vector3Int(1, 3, 1), CubesTestAssets.BLOCK_STONE);

        //Removing a block works in a similar way
        blockTerrain.removeBlock(new Vector3Int(1, 2, 1));
        blockTerrain.removeBlock(new Vector3Int(1, 3, 1));

        //The terrain is a jME-Control, you can add it
        //to a node of the scenegraph to display it
        Node terrainNode = new Node();
        terrainNode.addControl(blockTerrain);
        rootNode.attachChild(terrainNode);

        cam.setLocation(new Vector3f(-10, 10, 16));
        cam.lookAtDirection(new Vector3f(1, -0.56f, -1), Vector3f.UNIT_Y);
        flyCam.setMoveSpeed(50);
    }
}


text:
import pytest
import unittest
import types
import inspect
from calvin.csparser.complete import Completion

class TestBase(unittest.TestCase):

    source_text = """
    component Foo() a -> b {
        flt : std.Identity()
        .a > flt.in
        flt.out > .b
    }
    src:std.Counter()
    snk:io.Print()
    log:io.Print()

    src.integer > snk.token, log.token
    """

    def setUp(self):
        completion = Completion()
        completion.set_source(inspect.cleandoc(self.source_text))
        self.completion = completion

    def tearDown(self):
        pass

class SanityCheck(TestBase):

    def test_sanity(self):
        completion = self.completion
        self.assertTrue(completion.metadata)
        self.assertTrue(completion.source)
        self.assertEqual(completion.source_lines[6], 'snk:io.Print()')
        self.assertEqual(completion.source_line(7), 'snk:io.Print()')
        completion._first_line_is_zero = True
        self.assertEqual(completion.source_lines[6], 'snk:io.Print()')
        self.assertEqual(completion.source_line(6), 'snk:io.Print()')

class ActorCompletionTests(TestBase):

    def test_completion_module(self):
        d = self.completion.complete(7, 4)
        self.assertEqual(set(d['suggestions']), set(self.completion.metadata.keys()))
        self.assertEqual('module', d['type'])

    def test_completion_module_partial(self):
        d = self.completion.complete(7, 5)
        self.assertEqual(set(d['suggestions']), set(['io']))
        self.assertEqual(set(d['completions']), set(['o']))

    def test_completion_module_partial2(self):
        d = self.completion.complete(6, 5)
        self.assertEqual(set(d['suggestions']), set(['std', 'sensor']))
        self.assertEqual(set(d['completions']), set(['td', 'ensor']))

    def test_completion_actor(self):
        d = self.completion.complete(6, 8)
        expected = self.completion.metadata['std'].keys()
        self.assertEqual(set(d['suggestions']), set(expected))
        self.assertEqual(set(d['completions']), set(expected))
        self.assertEqual('actor', d['type'])
        self.assertEqual(len(d['completions']), len(d['arg_dicts']))

    def test_completion_actor_partial(self):
        d = self.completion.complete(6, 10)
        expected = [x for x in self.completion.metadata['std'].keys() if x.startswith('Co')]
        self.assertEqual(set(d['suggestions']), set(expected))
        self.assertEqual(set(d['completions']), set([x[2:] for x in expected]))
        self.assertEqual(len(d['completions']), len(d['arg_dicts']))

class PortCompletionTests(TestBase):

    def test_outport(self):
        d = self.completion.complete(10, 4)
        self.assertEqual(set(d['suggestions']), set(['integer']))
        self.assertEqual(set(d['completions']), set(['integer']))
        self.assertEqual('outport', d['type'])

    def test_outport_partial(self):
        d = self.completion.complete(10, 6)
        self.assertEqual(set(d['suggestions']), set(['integer']))
        self.assertEqual(set(d['completions']), set(['teger']))

    def test_inport(self):
        d = self.completion.complete(10, 18)
        self.assertEqual(set(d['suggestions']), set(['token']))
        self.assertEqual(set(d['completions']), set(['token']))
        self.assertEqual('inport', d['type'])

    def test_inport_list(self):
        d = self.completion.complete(10, 29)
        self.assertEqual(set(d['suggestions']), set(['token']))
        self.assertEqual(set(d['completions']), set(['token']))
        self.assertEqual('inport', d['type'])

    def test_inport_partial(self):
        d = self.completion.complete(10, 20)
        self.assertEqual(set(d['suggestions']), set(['token']))
        self.assertEqual(set(d['completions']), set(['ken']))

    def test_outport_comp(self):
        d = self.completion.complete(4, 8)
        self.assertEqual(set(d['suggestions']), set(['token']))
        self.assertEqual(set(d['completions']), set(['token']))

class PortCompletionIncompleteSourceTests(PortCompletionTests):

    def setUp(self):
        super(PortCompletionIncompleteSourceTests, self).setUp()
        # Patch complete to truncate the source code
        cmpl = self.completion.complete
        def complete_trunc(self, lineno, col):
            if not self._first_line_is_zero:
                lineno = lineno - 1
            src_lines = self.source_lines[:lineno - 1] + [self.source_lines[lineno][:col]]
            src = "\n".join(src_lines)
            self.set_source(src)
            return cmpl(lineno, col)

        self.completion.complete = types.MethodType(complete_trunc, self.completion, Completion)

class PortPropertyCompletionTests(TestBase):

    @unittest.expectedFailure
    def test_outport(self):
        self.assertTrue(False)

class NoCompletions(TestBase):

    def test_completion_module(self):
        d = self.completion.complete(1, 3)
        self.assertEqual(set(d['suggestions']), set({}))


text:
import React, { PropTypes, } from 'react';
import styled from 'styled-components';
import clearLast from './calculatorFunctions/ClearLast';

const Div = styled.div`
  height: 12%;
  textAlign: center;
`;

const Allbutton = styled.button`
  height: 90%;
  width: 42%;
  background-color: rgb(221,160,221, .5);
  border: 3px solid #9F6464;
  font-size: 17px;
  border-radius: 20px;
  font-family: Arial, sans-serif;
  box-shadow: 4px 5px 3px 0 rgba(0, 0, 0, .5);
  margin-right: 5px;

  &:hover {
    background-color: #9F6464;
  },

  &:focus {
    outline-color: black;
    outline-style: solid;
    outline-width: 2px;
  },

  &:active {
    transform: translateY(3px);
  }
`;

const Lastbutton = styled(Allbutton)`
  border: 3px solid rgb(150,150,150);

  &:hover {
    background-color: rgb(150,150,150);
  }
`;

const CalculatorClearbuttons = ({ theOutput, newOutputState, }) => {
  CalculatorClearbuttons.propTypes = {
    theOutput: PropTypes.string,
    newOutputState: PropTypes.func,
  };

  const eraseAllInput = () => newOutputState('');
  const eraseLast = () => newOutputState(clearLast(theOutput));

  return (
    <Div>
      <Allbutton onClick={eraseAllInput} >Clear All</Allbutton>
      <Lastbutton onClick={eraseLast} >Clear Last</Lastbutton>
    </Div>
  );
};

export default CalculatorClearbuttons;


text:
import struct
import binascii

import dns.rdata
import dns.rdatatype

class DSBase(dns.rdata.Rdata):

    """Base class for rdata that is like a DS record

    @ivar key_tag: the key tag
    @type key_tag: int
    @ivar algorithm: the algorithm
    @type algorithm: int
    @ivar digest_type: the digest type
    @type digest_type: int
    @ivar digest: the digest
    @type digest: int
    @see: draft-ietf-dnsext-delegation-signer-14.txt"""

    __slots__ = ['key_tag', 'algorithm', 'digest_type', 'digest']

    def __init__(self, rdclass, rdtype, key_tag, algorithm, digest_type,
                 digest):
        super(DSBase, self).__init__(rdclass, rdtype)
        self.key_tag = key_tag
        self.algorithm = algorithm
        self.digest_type = digest_type
        self.digest = digest

    def to_text(self, origin=None, relativize=True, **kw):
        return '%d %d %d %s' % (self.key_tag, self.algorithm,
                                self.digest_type,
                                dns.rdata._hexify(self.digest,
                                                  chunksize=128))

    @classmethod
    def from_text(cls, rdclass, rdtype, tok, origin=None, relativize=True):
        key_tag = tok.get_uint16()
        algorithm = tok.get_uint8()
        digest_type = tok.get_uint8()
        chunks = []
        while 1:
            t = tok.get().unescape()
            if t.is_eol_or_eof():
                break
            if not t.is_identifier():
                raise dns.exception.SyntaxError
            chunks.append(t.value.encode())
        digest = b''.join(chunks)
        digest = binascii.unhexlify(digest)
        return cls(rdclass, rdtype, key_tag, algorithm, digest_type,
                   digest)

    def to_wire(self, file, compress=None, origin=None):
        header = struct.pack("!HBB", self.key_tag, self.algorithm,
                             self.digest_type)
        file.write(header)
        file.write(self.digest)

    @classmethod
    def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin=None):
        header = struct.unpack("!HBB", wire[current: current + 4])
        current += 4
        rdlen -= 4
        digest = wire[current: current + rdlen].unwrap()
        return cls(rdclass, rdtype, header[0], header[1], header[2], digest)


text:
import pytest

from pypeerassets.provider import Cryptoid, Explorer

@pytest.mark.parametrize("provider_cls", [Cryptoid, Explorer])
def test_validateaddress_peercoin(provider_cls):
    "Check Providers that can validate Peercoin addresses."

    provider = provider_cls(network='peercoin')

    # Peercoin P2PKH, P2SH addresses.
    assert provider.validateaddress("PAdonateFczhZuKLkKHozrcyMJW7Y6TKvw") is True
    assert provider.validateaddress("p92W3t7YkKfQEPDb7cG9jQ6iMh7cpKLvwK") is True

    # Peercoin Testnet P2PKH address (these _should_ be False).
    assert provider.validateaddress("mj46gUeZgeD9ufU7Fvz2dWqaX6Nswtbpba") is False
    assert provider.validateaddress("n12h8P5LrVXozfhEQEqg8SFUmVKtphBetj") is False

    # Very much not Peercoin addresses.
    assert provider.validateaddress("1BFQfjM29kubskmaAsPjPCfHYphYvKA7Pj") is False
    assert provider.validateaddress("2NFNPUYRpDXf3YXEuVT6AdMesX4kyeyDjtp") is False

@pytest.mark.parametrize("provider_cls", [Cryptoid, Explorer,])
def test_validateaddress_peercoin_testnet(provider_cls):
    "Check Providers that can validate Peercoin Testnet addresses."

    provider = provider_cls(network='peercoin-testnet')

    # Peercoin Testnet P2PKH address.
    assert provider.validateaddress("mj46gUeZgeD9ufU7Fvz2dWqaX6Nswtbpba") is True
    assert provider.validateaddress("n12h8P5LrVXozfhEQEqg8SFUmVKtphBetj") is True

    # Peercoin P2PKH, P2SH addresses (these _should_ be False).
    assert provider.validateaddress("PAdonateFczhZuKLkKHozrcyMJW7Y6TKvw") is False
    assert provider.validateaddress("p92W3t7YkKfQEPDb7cG9jQ6iMh7cpKLvwK") is False

    # Very much not Peercoin Testnet addresses.
    assert provider.validateaddress("1BFQfjM29kubskmaAsPjPCfHYphYvKA7Pj") is False
    assert provider.validateaddress("2NFNPUYRpDXf3YXEuVT6AdMesX4kyeyDjtp") is False


text:
function MsgServerModeReconnectResponse(){
	this.response = undefined;
};

MsgServerModeReconnectResponse.prototype.setResponse = function setResponse(value){
	this.response = value;
};

MsgServerModeReconnectResponse.prototype.getResponse = function getResponse(){
	return this.response;
};

MsgServerModeReconnectResponse.prototype.write = function write(buffer) {
	buffer.writeUInt8(this.response);
};

MsgServerModeReconnectResponse.prototype.getSize = function getSize(){
	return 1;
};

MsgServerModeReconnectResponse.prototype.toString = function toString(){
	var str = "";
	str+="Response: "+this.response.toString(16)+"\n";
	return str;
};

MsgServerModeReconnectResponse.parse = function parse(buffer) {
	var message = new MsgServerModeReconnectResponse();
	message.setResponse(buffer.readUInt8());

	return message;
};

module.exports = MsgServerModeReconnectResponse;


text:
<!DOCTYPE HTML>

		<meta http-equiv="Content-Type" content="html/html; charset=utf-8" />
		<title>ESTPositionView Class Reference</title>
		<meta id="xcode-display" name="xcode-display" content="render"/>
		<link rel="stylesheet" type="text/css" href="../css/styles.css" media="all" />
		<link rel="stylesheet" type="text/css" media="print" href="../css/stylesPrint.css" />
		<meta name="generator" content="appledoc 2.2.1 (build 1333)" />

Estimote Indoor Location SDK

				Estimote

ESTPositionView Class Reference

					<button aria-label="Show Table of Contents" role="checkbox" class="open" id="table_of_contents">Table of Contents</button>

					<select id="jumpTo">
	<option value="top">Jump To…</option>

	<option value="overview">Overview</option>

	<option value="tasks">Tasks</option>

	<option value="instance_methods">Instance Methods</option>

	<option value="//api/name/initWithImage:location:forViewWithBounds:">    - initWithImage:location:forViewWithBounds:</option>

	<option value="//api/name/initWithImage:location:regionOfInterest:forViewWithBounds:">    - initWithImage:location:regionOfInterest:forViewWithBounds:</option>

	<option value="//api/name/updateAccuracy:">    - updateAccuracy:</option>

</select>

Overview

Tasks

Instance Methods

initWithImage:location:forViewWithBounds:

initWithImage:location:regionOfInterest:forViewWithBounds:

updateAccuracy:

Index

Hierarchy

ESTPositionView Class Reference

	Inherits from
	UIImageView

	Declared in
	ESTPositionView.h
ESTPositionView.m

Overview

View representing current position indicator with accuracy circle.
It adjusts itself to always show correctly accuracy in scale.

Tasks

		– initWithImage:location:forViewWithBounds:

		– initWithImage:location:regionOfInterest:forViewWithBounds:

		– updateAccuracy:

Instance Methods

initWithImage:location:forViewWithBounds:

Returns an initialized ESTPositionView object for given location and size of superview.

- (instancetype)initWithImage:(UIImage *)image location:(ESTLocation *)location forViewWithBounds:(CGRect)bounds

Parameters

location

The location for which the position is visualized.

bounds

Bounds of superview.

Return Value

An initialized ESTPositionView object.

Declared In

		ESTPositionView.h

initWithImage:location:regionOfInterest:forViewWithBounds:

Returns an initialized ESTPositionView object for given location and size of superview.

- (instancetype)initWithImage:(UIImage *)image location:(ESTLocation *)location regionOfInterest:(CGRect)regionOfInterest forViewWithBounds:(CGRect)bounds

Parameters

location

The location for which the position is visualized.

regionOfInterest

Region of interest to be drawn for the location.

bounds

Bounds of superview.

Return Value

An initialized ESTPositionView object.

Declared In

		ESTPositionView.h

updateAccuracy:

Updates accuracy value.

- (void)updateAccuracy:(ESTPositionAccuracy)accuracy

Declared In

		ESTPositionView.h

Index

Hierarchy

© 2015 Estimote. All rights reserved. (Last updated: 2015-06-09)

						Generated by appledoc 2.2.1 (build 1333).


text:
/*
 * 1.1 version.
 */

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

/*
 * This applet animates graphics that it generates.  This
 * example eliminates flashing by double buffering.
 */

public class DoubleBuffer extends Applet
        	          implements Runnable {
    int frameNumber = -1;
    int delay;
    Thread animatorThread;
    boolean frozen = false;

    int squareSize = 20;
    boolean fillColumnTop = true;

    Dimension offDimension;
    Image offImage;
    Graphics offGraphics;

    public void init() {
        String str;
        int fps = 10;

        //How many milliseconds between frames?
        str = getParameter("fps");
        try {
            if (str != null) {
                fps = Integer.parseInt(str);
            }
        } catch (Exception e) {}
        delay = (fps > 0) ? (1000 / fps) : 100;

        //How many pixels wide is each square?
        str = getParameter("squareWidth");
        try {
            if (str != null) {
                squareSize = Integer.parseInt(str);
            }
        } catch (Exception e) {}

        addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                if (frozen) {
                    frozen = false;
                    start();
                } else {
                    frozen = true;

		    //Instead of calling stop(), which destroys the
		    //backbuffer, just stop the animating thread.
		    animatorThread = null;
                }
            }
       });
    }

    public void start() {
        if (frozen) {
            //Do nothing.  The user has requested that we
            //stop changing the image.
        } else {
            //Start animating!
            if (animatorThread == null) {
                animatorThread = new Thread(this);
            }
            animatorThread.start();
        }
    }

    public void stop() {
        //Stop the animating thread.
        animatorThread = null;

	//Get rid of the objects necessary for double buffering.
	offGraphics = null;
	offImage = null;
    }

    public void run() {
        //Just to be nice, lower this thread's priority
        //so it can't interfere with other processing going on.
        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

        //Remember the starting time.
        long startTime = System.currentTimeMillis();

        //Remember which thread we are.
        Thread currentThread = Thread.currentThread();

        //This is the animation loop.
        while (currentThread == animatorThread) {
            //Advance the animation frame.
            frameNumber++;

            //Display it.
            repaint();

            //Delay depending on how far we are behind.
            try {
                startTime += delay;
                Thread.sleep(Math.max(0,
                             startTime-System.currentTimeMillis()));
            } catch (InterruptedException e) {
                break;
            }
        }
    }

    //Draw the current frame of animation.
    public void paint(Graphics g) {
	update(g);
    }

    public void update(Graphics g) {
        Dimension d = getSize();
        boolean fillSquare;
        boolean fillNextFrame;
        int rowWidth = 0;
        int x = 0, y = 0;
        int w, h;
        int tmp;

	//Create the offscreen graphics context,
	//if no good one exists.
	if ( (offGraphics == null)
	  || (d.width != offDimension.width)
	  || (d.height != offDimension.height) ) {
	    offDimension = d;
	    offImage = createImage(d.width, d.height);
	    offGraphics = offImage.getGraphics();
	}

	//Erase the previous image.
	offGraphics.setColor(getBackground());
	offGraphics.fillRect(0, 0, d.width, d.height);
	offGraphics.setColor(Color.black);

        //Set width of first "square". Decide whether to fill it.
        fillSquare = fillColumnTop;
        fillColumnTop = !fillColumnTop;
        tmp = frameNumber % squareSize;
        if (tmp == 0) {
            w = squareSize;
            fillNextFrame = !fillSquare;
        } else {
            w = tmp;
            fillNextFrame = fillSquare;
        }

        //Draw from left to right.
        while (x < d.width) {
            int colHeight = 0;

            //Draw the column.
            while (y < d.height) {
                colHeight += squareSize;

                //If we don't have room for a full square, cut if off.
                if (colHeight > d.height) {
                    h = d.height - y;
                } else {
                    h = squareSize;
                }

                //Draw the rectangle if necessary.
                if (fillSquare) {
                    offGraphics.fillRect(x, y, w, h);
                    fillSquare = false;
                } else {
                    fillSquare = true;
                }

                y += h;
            } //while y

            //Determine x, y, and w for the next go around.
            x += w;
            y = 0;
            w = squareSize;
            rowWidth += w;
            if (rowWidth > d.width) {
                w = d.width - x;
            }
            fillSquare = fillColumnTop;
            fillColumnTop = !fillColumnTop;
        } //while x
        fillColumnTop = fillNextFrame;

	//Paint the image onto the screen.
	g.drawImage(offImage, 0, 0, this);
    }
}


text:
<?php

require_once(__DIR__.'/credentials.incl.php');
require_once(__DIR__.'/../../incl/NewsstandHTTP.incl.php');

use \Newsstand\HTTP;

date_default_timezone_set('UTC');
ini_set('memory_limit','384M');

if (count($argv) < 3) {
    echo "Run curseupdater.sh\n";
    exit(1);
}

fwrite(STDERR, "Starting Curse Updater..\n");

$zipPath = $argv[1];
$version = $argv[2];

if (!file_exists($zipPath)) {
    fwrite(STDERR, 'File does not exist: '.$zipPath."\n");
    exit(1);
}

function GetLatestGameVersionIDs() {
    $url = sprintf("https://wow.curseforge.com/api/game/versions?token=%s", CURSEFORGE_API_TOKEN);
    $json = HTTP::Get($url);
    if (!$json) {
        trigger_error("Empty response from curseforge game versions");
        return false;
    }
    $json = json_decode($json, true);
    if (json_last_error() != JSON_ERROR_NONE) {
        trigger_error("Invalid json response from curseforge game versions");
        return false;
    }
    if (!count($json) || !isset($json[0]['id']) || !isset($json[0]['name'])) {
        trigger_error("Unknown json response from curseforge game versions");
        return false;
    }
    usort($json, function($a,$b){
        return version_compare($b['name'], $a['name']);
    });

    $ngdpVersion = GetNGDPVersion();
    if ($ngdpVersion) {
        $result = [];
        foreach ($json as $versionObject) {
            if ($versionObject['gameVersionTypeID'] !== 517) {
                continue;
            }
            $partCount = min(substr_count($ngdpVersion, '.'), substr_count($versionObject['name'], '.')) + 1;
            if (version_compare(
                implode('.', array_slice(explode('.', $ngdpVersion), 0, $partCount)),
                implode('.', array_slice(explode('.', $versionObject['name']), 0, $partCount)),
                '<=')) {
                $result[] = $versionObject['id'];
            } else {
                break;
            }
        }
        if ($result) {
            return $result;
        }
    }

    $latest = array_shift($json);
    return [$latest['id']];
}

function GetNGDPVersion() {
    $cmd = <<<'END'
curl -s https://ribbit.everynothing.net/products/wow/versions | grep '^eu|' | awk -F '|' '{print $6}'
END;

    $result = trim(shell_exec($cmd));
    if (!$result) {
        sleep(5);
        $result = trim(shell_exec($cmd));
    }

    return $result ?: false;
}

function mimeset(&$a) {
    do {
        $boundary = '';
        for ($x = 0; $x < 16; $x++)
            $boundary .= chr(mt_rand(97,122));

        $foundit = false;
        foreach ($a as $i)
            if (isset($i['data']) && (strpos($i['data'],$boundary) !== false)) {
                $foundit = true;
                break;
            }

    } while ($foundit);

    $tr = '';

    foreach ($a as $i)
        if (isset($i['data']) && isset($i['headers'])) {
            $tr .= "--$boundary\r\n";
            foreach ($i['headers'] as $n => $v) $tr .= "$n: $v\r\n";
            $tr .= "\r\n".$i['data']."\r\n";
        }

    $tr .= "--$boundary--\r\n\r\n";

    return [$tr, $boundary];
}

$latestVersions = GetLatestGameVersionIDs();
if (!$latestVersions) {
    exit(1);
}

$metaData = [
    'changelog' => sprintf('Automatic data update for %s', date('l, F j, Y')),
    'gameVersions' => $latestVersions,
    'releaseType' => 'release',
];

$postFields = [];
$postFields[] = [
    'data' => file_get_contents($zipPath),
    'headers' => [
        'Content-Disposition' => 'form-data; name="file"; filename="TheUndermineJournal.' . $version . '.zip"',
        'Content-Type' => 'application/zip',
        'Content-Transfer-Encoding' => 'binary',
        ]
];
$postFields[] = [
    'data' => json_encode($metaData),
    'headers' => [
        'Content-Disposition' => 'form-data; name="metadata"',
        'Content-Type' => 'application/json;charset=UTF-8',
    ]
];

list($toPost, $boundary) = mimeset($postFields);
unset($postFields);

fwrite(STDERR, sprintf("Starting upload of %d bytes..\n", strlen($toPost)));

$responseHeaders = [];

$result = HTTP::Post(sprintf('https://wow.curseforge.com/api/projects/%d/upload-file', CURSEFORGE_PROJECT_ID), $toPost, [
    sprintf('Content-Type: multipart/form-data; boundary=%s', $boundary),
    sprintf('X-Api-Token: %s', CURSEFORGE_API_TOKEN),
], $responseHeaders);

$json = [];
if ($result) {
    $json = json_decode($result, true);
    if (json_last_error() != JSON_ERROR_NONE) {
        $json = [];
    }
}
if (isset($json['id'])) {
    fwrite(STDERR, sprintf("Uploaded as file ID %d\n", $json['id']));
} else {
    fwrite(STDERR, "Error received from server.\n");
    if (isset($responseHeaders['responseCode'])) {
        fwrite(STDERR, sprintf("Received response code %d\n", $responseHeaders['responseCode']));
    }
    fwrite(STDERR, $result);
    fwrite(STDERR, "\n");
}


text:
package org.asynchttpclient.consumers;

import org.asynchttpclient.BodyConsumer;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * A {@link ByteBuffer} implementation of {@link BodyConsumer}
 */
public class ByteBufferBodyConsumer implements BodyConsumer {

    private final ByteBuffer byteBuffer;

    public ByteBufferBodyConsumer(ByteBuffer byteBuffer) {
        this.byteBuffer = byteBuffer;
    }

    /**
     * {@inheritDoc}
     */
    /* @Override */
    public void consume(ByteBuffer byteBuffer) throws IOException {
        byteBuffer.put(byteBuffer);
    }

    /**
     * {@inheritDoc}
     */
    /* @Override */
    public void close() throws IOException {
        byteBuffer.flip();
    }
}


text:
export * from './apikey';
export * from './general';
export * from './types';