text:
package es.deusto.weblab.client.ui.widgets;

import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

import es.deusto.weblab.client.ui.audio.AudioManager;
import es.deusto.weblab.client.ui.widgets.WlButton.IWlButtonUsed;
import es.deusto.weblab.client.ui.widgets.exceptions.WlWidgetException;

public class WlTimedButton extends VerticalPanel implements IWlWidget{

	public static int DEFAULT_TIME = 1000;

	private final WlButton button;
	private final WlIntegerTextbox textbox;
	private final VerticalPanel visiblePanel;
	private final WlActionListenerContainer actionListenerContainer;
	private int time;

	private final Label titleLabel = new Label();

	public WlTimedButton(){
		this(WlTimedButton.DEFAULT_TIME);
	}

	public WlTimedButton(int time){

		this.button = new WlButton();
		this.button.setTime(time);
		this.textbox = new WlIntegerTextbox();
		this.textbox.setText(new Integer(time));
		this.time = time;

		this.actionListenerContainer = new WlActionListenerContainer();

		this.visiblePanel = this;
		this.setWidth("100%");
		this.visiblePanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		this.visiblePanel.add(this.button.getWidget());
		this.visiblePanel.add(this.titleLabel);
		//this.visiblePanel.add(this.textbox.getWidget());

		this.button.addActionListener(new IWlActionListener(){
			@Override
			public void onAction(IWlWidget widget) {
				WlTimedButton.this.fireActionListeners();
				AudioManager.getInstance().playBest("snd/switch");
			}
		});

		this.textbox.addActionListener(new IWlActionListener(){
			@Override
			public void onAction(IWlWidget widget) {
				final int intValue;
				try {
					intValue = WlTimedButton.this.textbox.getValue().intValue();
					AudioManager.getInstance().playBest("snd/switch");
				} catch (final WlWidgetException e) {
					return;
				}
				WlTimedButton.this.time = intValue;
				WlTimedButton.this.button.setTime(intValue);
			}
		});

	}

	@Override
	public String getTitle() {
		return this.titleLabel.getText();
	}

	@Override
	public void setTitle(String title) {
		this.titleLabel.setText(title);
	}

	@Override
	public void dispose(){
		this.button.dispose();
		this.textbox.dispose();
	}

	public void addActionListener(IWlActionListener listener){
		this.actionListenerContainer.addActionListener(listener);
	}

	public void removeActionListener(IWlActionListener listener){
		this.actionListenerContainer.removeActionListener(listener);
	}

	public void addButtonListener(IWlButtonUsed listener){
		this.button.addButtonListener(listener);
	}

	protected void fireActionListeners(){
		this.actionListenerContainer.fireActionListeners(this);
	}

	public int getTime(){
		return this.time;
	}

	@Override
	public Widget getWidget() {
		return this.visiblePanel;
	}
}


text:
                <form id="volume_form" name="project_form" class="form-horizontal">
                    <input type="hidden" name="projectName" id="projectName">

                                所属项目*

                                    <select id="projectID" class="form-control select2" name="projectID" disabled="disabled">
                                        <option selected="selected" value="">选择一个项目</option>
                                    </select>

                                选择合同*

                                    <select id="laborID" class="form-control select2" name="laborID" disabled="disabled">
                                        <option selected="selected" value="">选择一个合同</option>
                                    </select>

                                施工班组*

                                    <input type="text" class="form-control" id="constructionTeam" name="constructionTeam" placeholder="施工班组" readonly="readonly">

                                施工起始时间*

                                    <input type="text" class="form-control" data-flag="datepicker" data-format="yyyy-mm-dd" name="startTime" id="startTime"
                                        placeholder="起始时间" disabled="disabled">

                                所属项目子项*

                                    <select id="projectSubID" class="form-control select2" name="projectSubID" disabled="disabled">
                                        <option selected="selected" value="">选择一个项目子项</option>
                                    </select>

                                合同总价(元)

                                    <input type="text" class="form-control" id="contractPrice" name="contractPrice" placeholder="合同总价" readonly="readonly">

                                施工负责人*

                                    <input type="text" class="form-control" id="constructionManager" name="constructionManager" readonly="readonly">

                                施工结束时间*

                                    <input type="text" class="form-control" data-flag="datepicker" data-format="yyyy-mm-dd" name="endTime" id="endTime"
                                        placeholder="结束时间" disabled="disabled">

                            工程量*

                                <textarea class="form-control" id="volume" name="volume" rows="8" cols="100" disabled="disabled"></textarea>

上报金额:

人工费:尚未审批;人工扣款:尚未审批;

上报小计:尚未审批

功效:

                                审核人工费(元)*

                                    <input type="text" onkeyup="value=value.replace(/[^\d.]/g,'')" class="form-control calculate" id="businessLabour" name="businessLabour" placeholder="审核人工费" value="0">

                                审核机械费(元)*

                                    <input readonly="readonly" type="text" onkeyup="value=value.replace(/[^\d.]/g,'')" class="form-control calculate" id="businessMech" name="businessMech" placeholder="审核机械费" value="0">

                                审核材料费(元)*

                                    <input readonly="readonly" type="text" onkeyup="value=value.replace(/[^\d.]/g,'')" class="form-control calculate" id="businessMat" name="businessMat" placeholder="审核材料费" value="0">

                                功效

                                    <input type="text" class="form-control calculate" id="jygx" name="jygx" placeholder="功效" >

                                审核人工扣款(元)*

                                    <input type="text" onkeyup="value=value.replace(/[^\d.]/g,'')" class="form-control calculate" id="businessDebit" name="businessDebit" placeholder="审核应扣款" value="0">

                                审核机械扣款(元)*

                                    <input readonly="readonly" type="text" onkeyup="value=value.replace(/[^\d.]/g,'')" class="form-control calculate" id="businessDebitjx" name="businessDebitjx" placeholder="审核应扣款" value="0">

                                审核材料扣款(元)*

                                    <input readonly="readonly" type="text" onkeyup="value=value.replace(/[^\d.]/g,'')" class="form-control calculate" id="businessDebitcl" name="businessDebitcl" placeholder="审核应扣款" value="0">

                                审核包工包料(元)*

                                    <input type="text" onkeyup="value=value.replace(/[^\d.]/g,'')" class="form-control calculate" id="businessPack" name="businessPack" placeholder="审核包工包料" value="0">

                                功效比

                                    <input type="text" class="form-control calculate" id="jygxb" name="jygxb" placeholder="功效比" >

                                审核后总计(元)*

                                    <input type="text" onkeyup="value=value.replace(/[^\d.]/g,'')" class="form-control" id="businessSub" name="businessSub" placeholder="审核后总计" value="0" readonly="readonly">

                            <button type="button" class="btn btn-success" id="lookFkd">班组罚款单</button>

                </form>

                            班组工程量(所属班组全部)

                    <select  class="form-control select2" name="pv.sblx" style="width:200px;" operator="eq">
                    	<option selected="selected" value="">选择一个类型</option>
                    	<option value="10">包清工</option>
                    	<option value="20">包工包料</option>
                    	<option value="30">机械</option>
                    </select>
                    <input id = "bzid" name="l.construction_team_id" style="display: none" operator="eq">

                        <button type="button" class="btn btn-primary" data-btn-type="search">查询</button>

redpajama_set_name: RedPajamaGithub


text:
"""Classes representing various MJCF attribute data types."""

import abc
import collections
import hashlib
import io
import os

from dm_control.mjcf import base
from dm_control.mjcf import constants
from dm_control.mjcf import debugging
from dm_control.mjcf import skin
from dm_control.mujoco.wrapper import util
import numpy as np

# Copybara placeholder for internal file handling dependency.

from dm_control.utils import io as resources

_INVALID_REFERENCE_TYPE = (
    'Reference should be an MJCF Element whose type is {valid_type!r}: '
    'got {actual_type!r}.')

_MESH_EXTENSIONS = ('.stl', '.msh', '.obj')

# MuJoCo's compiler enforces this.
_INVALID_MESH_EXTENSION = (
    'Mesh files must have one of the following extensions: {}, got {{}}.'
    .format(_MESH_EXTENSIONS))

class _Attribute(metaclass=abc.ABCMeta):
  """Abstract base class for MJCF attribute data types."""

  def __init__(self, name, required, parent, value,
               conflict_allowed, conflict_behavior):
    self._name = name
    self._required = required
    self._parent = parent
    self._value = None
    self._conflict_allowed = conflict_allowed
    self._conflict_behavior = conflict_behavior
    self._check_and_assign(value)

  def _check_and_assign(self, new_value):
    if new_value is None:
      self.clear()
    elif isinstance(new_value, str):
      self._assign_from_string(new_value)
    else:
      self._assign(new_value)
    if debugging.debug_mode():
      self._last_modified_stack = debugging.get_current_stack_trace()

  @property
  def last_modified_stack(self):
    if debugging.debug_mode():
      return self._last_modified_stack

  @property
  def value(self):
    return self._value

  @value.setter
  def value(self, new_value):
    self._check_and_assign(new_value)

  @abc.abstractmethod
  def _assign(self, value):
    raise NotImplementedError  # pragma: no cover

  def clear(self):
    if self._required:
      raise AttributeError(
          'Attribute {!r} of element <{}> is required'
          .format(self._name, self._parent.tag))
    else:
      self._force_clear()

  def _force_clear(self):
    self._before_clear()
    self._value = None
    if debugging.debug_mode():
      self._last_modified_stack = debugging.get_current_stack_trace()

  def _before_clear(self):
    pass

  def _assign_from_string(self, string):
    self._assign(string)

  def to_xml_string(self, prefix_root, **kwargs):  # pylint: disable=unused-argument
    if self._value is None:
      return None
    else:
      return str(self._value)

  @property
  def conflict_allowed(self):
    return self._conflict_allowed

  @property
  def conflict_behavior(self):
    return self._conflict_behavior

class String(_Attribute):
  """A string MJCF attribute."""

  def _assign(self, value):
    if not isinstance(value, str):
      raise ValueError('Expect a string value: got {}'.format(value))
    elif not value:
      self.clear()
    else:
      self._value = value

class Integer(_Attribute):
  """An integer MJCF attribute."""

  def _assign(self, value):
    try:
      float_value = float(value)
      int_value = int(float(value))
      if float_value != int_value:
        raise ValueError
    except ValueError:
      raise ValueError(
          'Expect an integer value: got {}'.format(value)) from None
    self._value = int_value

class Float(_Attribute):
  """An float MJCF attribute."""

  def _assign(self, value):
    try:
      float_value = float(value)
    except ValueError:
      raise ValueError('Expect a float value: got {}'.format(value)) from None
    self._value = float_value

  def to_xml_string(self, prefix_root=None,
                    *,
                    precision=constants.XML_DEFAULT_PRECISION,
                    zero_threshold=0,
                    **kwargs):
    if self._value is None:
      return None
    else:
      out = io.BytesIO()
      value = self._value
      if abs(value) < zero_threshold:
        value = 0.0
      np.savetxt(out, [value], fmt=f'%.{precision:d}g', newline=' ')
      return util.to_native_string(out.getvalue())[:-1]  # Strip trailing space.

class Keyword(_Attribute):
  """A keyword MJCF attribute."""

  def __init__(self, name, required, parent, value,
               conflict_allowed, conflict_behavior, valid_values):
    self._valid_values = collections.OrderedDict(
        (value.lower(), value) for value in valid_values)
    super().__init__(name, required, parent, value, conflict_allowed,
                     conflict_behavior)

  def _assign(self, value):
    if value is None or value == '':  # pylint: disable=g-explicit-bool-comparison
      self.clear()
    else:
      try:
        self._value = self._valid_values[str(value).lower()]
      except KeyError:
        raise ValueError('Expect keyword to be one of {} but got: {}'.format(
            list(self._valid_values.values()), value)) from None

  @property
  def valid_values(self):
    return list(self._valid_values.keys())

class Array(_Attribute):
  """An array MJCF attribute."""

  def __init__(self, name, required, parent, value,
               conflict_allowed, conflict_behavior, length, dtype):
    self._length = length
    self._dtype = dtype
    super().__init__(name, required, parent, value, conflict_allowed,
                     conflict_behavior)

  def _assign(self, value):
    self._value = self._check_shape(np.array(value, dtype=self._dtype))

  def _assign_from_string(self, string):
    self._assign(np.fromstring(string, dtype=self._dtype, sep=' '))

  def to_xml_string(self, prefix_root=None,
                    *,
                    precision=constants.XML_DEFAULT_PRECISION,
                    zero_threshold=0,
                    **kwargs):
    if self._value is None:
      return None
    else:
      out = io.BytesIO()
      value = self._value
      if zero_threshold:
        value = np.copy(value)
        value[np.abs(value) < zero_threshold] = 0
      np.savetxt(out, value, fmt=f'%.{precision:d}g', newline=' ')
      return util.to_native_string(out.getvalue())[:-1]  # Strip trailing space.

  def _check_shape(self, array):
    actual_length = array.shape[0]
    if len(array.shape) > 1:
      raise ValueError('Expect one-dimensional array: got {}'.format(array))
    if self._length and actual_length > self._length:
      raise ValueError('Expect array with no more than {} entries: got {}'
                       .format(self._length, array))
    return array

class Identifier(_Attribute):
  """A string attribute that represents a unique identifier of an element."""

  def _assign(self, value):
    if not isinstance(value, str):
      raise ValueError('Expect a string value: got {}'.format(value))
    elif not value:
      self.clear()
    elif self._parent.spec.namespace == 'body' and value == 'world':
      raise ValueError('A body cannot be named \'world\'. '
                       'The name \'world\' is used by MuJoCo to refer to the '
                       '<worldbody>.')
    elif constants.PREFIX_SEPARATOR in value:
      raise ValueError(
          'An identifier cannot contain a {!r}, '
          'as this is reserved for scoping purposes: got {!r}'
          .format(constants.PREFIX_SEPARATOR, value))
    else:
      old_value = self._value
      if value != old_value:
        self._parent.namescope.add(
            self._parent.spec.namespace, value, self._parent)
        if old_value:
          self._parent.namescope.remove(self._parent.spec.namespace, old_value)
      self._value = value

  def _before_clear(self):
    if self._value:
      self._parent.namescope.remove(self._parent.spec.namespace, self._value)

  def _defaults_string(self, prefix_root):
    prefix = self._parent.namescope.full_prefix(prefix_root, as_list=True)
    prefix.append(self._value or '')
    return constants.PREFIX_SEPARATOR.join(prefix) or constants.PREFIX_SEPARATOR

  def to_xml_string(self, prefix_root=None, **kwargs):
    if self._parent.tag == constants.DEFAULT:
      return self._defaults_string(prefix_root)
    elif self._value:
      prefix = self._parent.namescope.full_prefix(prefix_root, as_list=True)
      prefix.append(self._value)
      return constants.PREFIX_SEPARATOR.join(prefix)
    else:
      return self._value

class Reference(_Attribute):
  """A string attribute that represents a reference to an identifier."""

  def __init__(self, name, required, parent, value,
               conflict_allowed, conflict_behavior, reference_namespace):
    self._reference_namespace = reference_namespace
    super().__init__(name, required, parent, value, conflict_allowed,
                     conflict_behavior)

  def _check_dead_reference(self):
    if isinstance(self._value, base.Element) and self._value.is_removed:
      self.clear()

  @property
  def value(self):
    self._check_dead_reference()
    return super().value

  @value.setter
  def value(self, new_value):
    super(Reference, self.__class__).value.fset(self, new_value)

  @property
  def reference_namespace(self):
    if isinstance(self._reference_namespace, _Attribute):
      return constants.INDIRECT_REFERENCE_ATTRIB.get(
          self._reference_namespace.value, self._reference_namespace.value)
    else:
      return self._reference_namespace

  def _assign(self, value):
    if not isinstance(value, (base.Element, str)):
      raise ValueError(
          'Expect a string or `mjcf.Element` value: got {}'.format(value))
    elif not value:
      self.clear()
    else:
      if isinstance(value, base.Element):
        value_namespace = (
            value.spec.namespace.split(constants.NAMESPACE_SEPARATOR)[0])
        if value_namespace != self.reference_namespace:
          raise ValueError(_INVALID_REFERENCE_TYPE.format(
              valid_type=self.reference_namespace,
              actual_type=value_namespace))
      self._value = value

  def _before_clear(self):
    if isinstance(self._value, base.Element):
      if isinstance(self._reference_namespace, _Attribute):
        self._reference_namespace._force_clear()  # pylint: disable=protected-access

  def _defaults_string(self, prefix_root):
    """Generates the XML string if this is a reference to a defaults class.

    To prevent global defaults from clashing, we turn all global defaults
    into a properly named defaults class. Therefore, care must be taken when
    this attribute is not explicitly defined. If the parent element can be
    traced up to a body with a nontrivial 'childclass' then must continue to
    leave this attribute undefined.

    Args:
      prefix_root: A `NameScope` object to be treated as root
        for the purpose of calculating the prefix.

    Returns:
      A string to be used in the generated XML.
    """
    self._check_dead_reference()
    prefix = self._parent.namescope.full_prefix(prefix_root)
    if not self._value:
      defaults_root = self._parent.parent
      while defaults_root is not None:
        if (hasattr(defaults_root, constants.CHILDCLASS)
            and defaults_root.childclass):
          break
        defaults_root = defaults_root.parent
      if defaults_root is None:
        # This element doesn't belong to a childclass'd body.
        global_class = self._parent.root.default.dclass or ''
        out_string = (prefix + global_class) or constants.PREFIX_SEPARATOR
      else:
        out_string = None
    else:
      out_string = prefix + self._value
    return out_string

  def to_xml_string(self, prefix_root, **kwargs):
    self._check_dead_reference()
    if isinstance(self._value, base.Element):
      return self._value.prefixed_identifier(prefix_root)
    elif (self.reference_namespace == constants.DEFAULT
          and self._name != constants.CHILDCLASS):
      return self._defaults_string(prefix_root)
    elif self._value:
      return self._parent.namescope.full_prefix(prefix_root) + self._value
    else:
      return None

class BasePath(_Attribute):
  """A string attribute that represents a base path for an asset type."""

  def __init__(self, name, required, parent, value,
               conflict_allowed, conflict_behavior, path_namespace):
    self._path_namespace = path_namespace
    super().__init__(name, required, parent, value, conflict_allowed,
                     conflict_behavior)

  def _assign(self, value):
    if not isinstance(value, str):
      raise ValueError('Expect a string value: got {}'.format(value))
    elif not value:
      self.clear()
    else:
      self._parent.namescope.replace(
          constants.BASEPATH, self._path_namespace, value)
      self._value = value

  def _before_clear(self):
    if self._value:
      self._parent.namescope.remove(constants.BASEPATH, self._path_namespace)

  def to_xml_string(self, prefix_root=None, **kwargs):
    return None

class BaseAsset:
  """Base class for binary assets."""

  __slots__ = ('extension', 'prefix')

  def __init__(self, extension, prefix=''):
    self.extension = extension
    self.prefix = prefix

  def __eq__(self, other):
    return self.get_vfs_filename() == other.get_vfs_filename()

  def get_vfs_filename(self):
    """Returns the name of the asset file as registered in MuJoCo's VFS."""
    # Hash the contents of the asset to get a unique identifier.
    hash_string = hashlib.sha1(util.to_binary_string(self.contents)).hexdigest()
    # Prepend the prefix, if one exists.
    if self.prefix:
      prefix = self.prefix
      raw_length = len(prefix) + len(hash_string) + len(self.extension) + 1
      if raw_length > constants.MAX_VFS_FILENAME_LENGTH:
        trim_amount = raw_length - constants.MAX_VFS_FILENAME_LENGTH
        prefix = prefix[:-trim_amount]
      filename = '-'.join([prefix, hash_string])
    else:
      filename = hash_string

    # An extension is needed because MuJoCo's compiler looks at this when
    # deciding how to load meshes and heightfields.
    return filename + self.extension

class Asset(BaseAsset):
  """Class representing a binary asset."""

  __slots__ = ('contents',)

  def __init__(self, contents, extension, prefix=''):
    """Initializes a new `Asset`.

    Args:
      contents: The contents of the file as a bytestring.
      extension: A string specifying the file extension (e.g. '.png', '.stl').
      prefix: (optional) A prefix applied to the filename given in MuJoCo's VFS.
    """
    self.contents = contents
    super().__init__(extension, prefix)

class SkinAsset(BaseAsset):
  """Class representing a binary asset corresponding to a skin."""

  __slots__ = ('skin', 'parent', '_cached_revision', '_cached_contents')

  def __init__(self, contents, parent, extension, prefix=''):
    self.skin = skin.parse(
        contents, lambda body_name: parent.root.find('body', body_name))
    self.parent = parent
    self._cached_revision = -1
    self._cached_contents = None
    super().__init__(extension, prefix)

  @property
  def contents(self):
    if self._cached_revision < self.parent.namescope.revision:
      self._cached_contents = skin.serialize(self.skin)
      self._cached_revision = self.parent.namescope.revision
    return self._cached_contents

class File(_Attribute):
  """Attribute representing an asset file."""

  def __init__(self, name, required, parent, value,
               conflict_allowed, conflict_behavior, path_namespace):
    self._path_namespace = path_namespace
    super().__init__(name, required, parent, value, conflict_allowed,
                     conflict_behavior)
    parent.namescope.files.add(self)

  def _assign(self, value):
    if not value:
      self.clear()
    else:
      if isinstance(value, str):
        asset = self._get_asset_from_path(value)
      elif isinstance(value, Asset):
        asset = value
      else:
        raise ValueError('Expect either a string or `Asset` value: got {}'
                         .format(value))
      self._validate_extension(asset.extension)
      self._value = asset

  def _get_asset_from_path(self, path):
    """Constructs a `Asset` given a file path."""
    _, basename = os.path.split(path)
    filename, extension = os.path.splitext(basename)

    # Look in the dict of pre-loaded assets before checking the filesystem.
    try:
      contents = self._parent.namescope.assets[path]
    except KeyError:
      # Construct the full path to the asset file, prefixed by the path to the
      # model directory, and by `meshdir` or `texturedir` if appropriate.
      path_parts = []
      if self._parent.namescope.model_dir:
        path_parts.append(self._parent.namescope.model_dir)
      try:
        base_path = self._parent.namescope.get(constants.BASEPATH,
                                               self._path_namespace)
        path_parts.append(base_path)
      except KeyError:
        pass
      path_parts.append(path)
      full_path = os.path.join(*path_parts)  # pylint: disable=no-value-for-parameter
      contents = resources.GetResource(full_path)
    if self._parent.tag == constants.SKIN:
      return SkinAsset(contents=contents, parent=self._parent,
                       extension=extension, prefix=filename)
    else:
      return Asset(contents=contents, extension=extension, prefix=filename)

  def _validate_extension(self, extension):
    if self._parent.tag == constants.MESH:
      if extension.lower() not in _MESH_EXTENSIONS:
        raise ValueError(_INVALID_MESH_EXTENSION.format(extension))

  def get_contents(self):
    """Returns a bytestring representing the contents of the asset."""
    if self._value is None:
      raise RuntimeError('You must assign a value to this attribute before '
                         'querying the contents.')
    return self._value.contents

  def to_xml_string(self, prefix_root=None, **kwargs):
    """Returns the asset filename as it will appear in the generated XML."""
    del prefix_root  # Unused
    if self._value is not None:
      return self._value.get_vfs_filename()
    else:
      return None


text:
package com.android.customseekbar;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

public class CustomSeekBar extends View
{
	private static final String TAG = "SeekBar";
	private static final int DEFAULT_PROGRESS_COUNT = 0;
	private static final float DEFAULT_BAR_WEIGHT_PX = 3;
	private static final int DEFAULT_BAR_COLOR = 0xff27839a;
	private static final float DEFAULT_CONNECTING_LINE_WEIGHT_PX = 3;
	private static final int DEFAULT_THUMB_IMAGE_NORMAL = R.drawable.slider_thumb;
	private static final int DEFAULT_THUMB_IMAGE_PRESSED = R.drawable.slider_thumb;
	private static final int DEFAULT_CONNECTING_LINE_COLOR = 0xffffffff;
	private static final float DEFAULT_THUMB_RADIUS_DP = 5;
	private static final int DEFAULT_THUMB_COLOR_NORMAL = 0xffffffff;
	private static final int DEFAULT_THUMB_COLOR_PRESSED = 0xffffffff;
	private int mProgressCount = DEFAULT_PROGRESS_COUNT;
	private float mBarWeight = DEFAULT_BAR_WEIGHT_PX;
	private int mBarColor = DEFAULT_BAR_COLOR;
	private float mConnectingLineWeight = DEFAULT_CONNECTING_LINE_WEIGHT_PX;
	private int mConnectingLineColor = DEFAULT_CONNECTING_LINE_COLOR;
	private int mThumbImageNormal = DEFAULT_THUMB_IMAGE_NORMAL;
	private int mThumbImagePressed = DEFAULT_THUMB_IMAGE_PRESSED;

	private float mThumbRadiusDP = DEFAULT_THUMB_RADIUS_DP;
	private int mThumbColorNormal = DEFAULT_THUMB_COLOR_NORMAL;
	private int mThumbColorPressed = DEFAULT_THUMB_COLOR_PRESSED;
	private boolean mFirstSetTickCount = true;
	private int mDefaultWidth = 400;
	private int mDefaultHeight = 100;
	private SeekThumb mLeftThumb;
	private BackgroundBar mBar;
	private TrailingLine mConnectingLine;
	private CustomSeekBar.OnSeekBarChangeListener mListener;
	private int mLeftIndex = 0;
	private int mRightIndex = mProgressCount - 1;

	public CustomSeekBar(Context context)
	{
		super(context);
	}

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

	public CustomSeekBar(Context context, AttributeSet attrs, int defStyle)
	{
		super(context, attrs, defStyle);
		SeekBarInit(context, attrs);
	}

	@Override
	public Parcelable onSaveInstanceState()
	{
		final Bundle bundle = new Bundle();
		bundle.putParcelable("instanceState", super.onSaveInstanceState());
		bundle.putInt("TICK_COUNT", mProgressCount);
		// bundle.putFloat("TICK_HEIGHT_DP", mTickHeightDP);
		bundle.putFloat("BAR_WEIGHT", mBarWeight);
		bundle.putInt("BAR_COLOR", mBarColor);
		bundle.putFloat("CONNECTING_LINE_WEIGHT", mConnectingLineWeight);
		bundle.putInt("CONNECTING_LINE_COLOR", mConnectingLineColor);
		bundle.putInt("THUMB_IMAGE_NORMAL", mThumbImageNormal);
		bundle.putInt("THUMB_IMAGE_PRESSED", mThumbImagePressed);
		bundle.putFloat("THUMB_RADIUS_DP", mThumbRadiusDP);
		bundle.putInt("THUMB_COLOR_NORMAL", mThumbColorNormal);
		bundle.putInt("THUMB_COLOR_PRESSED", mThumbColorPressed);
		bundle.putInt("LEFT_INDEX", mLeftIndex);
		bundle.putInt("RIGHT_INDEX", mRightIndex);
		bundle.putBoolean("FIRST_SET_TICK_COUNT", mFirstSetTickCount);
		return bundle;
	}

	@Override
	public void onRestoreInstanceState(Parcelable state)
	{
		if (state instanceof Bundle)
		{
			final Bundle bundle = (Bundle) state;
			mProgressCount = bundle.getInt("TICK_COUNT");
			// mTickHeightDP = bundle.getFloat("TICK_HEIGHT_DP");
			mBarWeight = bundle.getFloat("BAR_WEIGHT");
			mBarColor = bundle.getInt("BAR_COLOR");
			mConnectingLineWeight = bundle.getFloat("CONNECTING_LINE_WEIGHT");
			mConnectingLineColor = bundle.getInt("CONNECTING_LINE_COLOR");
			mThumbImageNormal = bundle.getInt("THUMB_IMAGE_NORMAL");
			mThumbImagePressed = bundle.getInt("THUMB_IMAGE_PRESSED");
			mThumbRadiusDP = bundle.getFloat("THUMB_RADIUS_DP");
			mThumbColorNormal = bundle.getInt("THUMB_COLOR_NORMAL");
			mThumbColorPressed = bundle.getInt("THUMB_COLOR_PRESSED");
			mLeftIndex = bundle.getInt("LEFT_INDEX");
			mRightIndex = bundle.getInt("RIGHT_INDEX");
			mFirstSetTickCount = bundle.getBoolean("FIRST_SET_TICK_COUNT");
			setThumbIndices(mLeftIndex, mRightIndex);
			super.onRestoreInstanceState(bundle.getParcelable("instanceState"));
		}
		else
		{
			super.onRestoreInstanceState(state);
		}
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
	{

		int width;
		int height;
		final int measureWidthMode = MeasureSpec.getMode(widthMeasureSpec);
		final int measureHeightMode = MeasureSpec.getMode(heightMeasureSpec);
		final int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
		final int measureHeight = MeasureSpec.getSize(heightMeasureSpec);
		if (measureWidthMode == MeasureSpec.AT_MOST)
		{
			width = measureWidth;
		}
		else
			if (measureWidthMode == MeasureSpec.EXACTLY)
			{
				width = measureWidth;
			}
			else
			{
				width = mDefaultWidth;
			}
		if (measureHeightMode == MeasureSpec.AT_MOST)
		{
			height = Math.min(mDefaultHeight, measureHeight);
		}
		else
			if (measureHeightMode == MeasureSpec.EXACTLY)
			{
				height = measureHeight;
			}
			else
			{
				height = mDefaultHeight;
			}
		setMeasuredDimension(width, height);
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh)
	{
		super.onSizeChanged(w, h, oldw, oldh);
		final Context ctx = getContext();
		final float yPos = h / 2f;
		mLeftThumb = new SeekThumb(ctx, yPos, mThumbColorNormal, mThumbColorPressed, mThumbRadiusDP, mThumbImageNormal, mThumbImagePressed);

		final float marginLeft = mLeftThumb.getHalfWidth();
		final float barLength = w - 2 * marginLeft;
		mBar = new BackgroundBar(ctx, marginLeft, yPos, barLength, mProgressCount, mBarWeight, mBarColor);
		mLeftThumb.setX(marginLeft + (mLeftIndex / (float) (mProgressCount - 1)) * barLength);
		final int newLeftIndex = mBar.getNearestTickIndex(mLeftThumb);
		if (newLeftIndex != mLeftIndex)
		{
			mLeftIndex = newLeftIndex;
			if (mListener != null)
			{
				mListener.onIndexChangeListener(this, mLeftIndex);
			}
		}
		mConnectingLine = new TrailingLine(ctx, yPos, mConnectingLineWeight, mConnectingLineColor);
	}

	@Override
	protected void onDraw(Canvas canvas)
	{

		super.onDraw(canvas);

		mBar.draw(canvas);

		mConnectingLine.draw(canvas, mLeftThumb, null);

		mLeftThumb.draw(canvas);

	}

	@SuppressLint("ClickableViewAccessibility")
	@Override
	public boolean onTouchEvent(MotionEvent event)
	{

		if (!isEnabled())
		{
			return false;
		}

		switch (event.getAction())
		{

		case MotionEvent.ACTION_DOWN:
			onActionDown(event.getX(), event.getY());
			return true;

		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_CANCEL:
			this.getParent().requestDisallowInterceptTouchEvent(false);
			onActionUp(event.getX(), event.getY());
			return true;

		case MotionEvent.ACTION_MOVE:
			onActionMove(event.getX());
			this.getParent().requestDisallowInterceptTouchEvent(true);
			return true;

		default:
			return false;
		}
	}

	public void setOnSeekBarChangeListener(CustomSeekBar.OnSeekBarChangeListener listener)
	{
		mListener = listener;
	}

	public void setTickCount(int tickCount)
	{

		if (isValidTickCount(tickCount))
		{
			mProgressCount = tickCount;

			if (mFirstSetTickCount)
			{
				mLeftIndex = 0;
				mRightIndex = mProgressCount - 1;

				if (mListener != null)
				{
					mListener.onIndexChangeListener(this, mLeftIndex);
				}
			}
			if (indexOutOfSeek(mLeftIndex, mRightIndex))
			{
				mLeftIndex = 0;
				mRightIndex = mProgressCount - 1;

				if (mListener != null)
					mListener.onIndexChangeListener(this, mLeftIndex);
			}

			createBar();
			createThumbs();
		}
		else
		{
			Log.e(TAG, "tickCount less than 2; invalid tickCount.");
			throw new IllegalArgumentException("tickCount less than 2; invalid tickCount.");
		}
	}

	public void setBarWeight(float barWeight)
	{

		mBarWeight = barWeight;
		createBar();
	}

	public void setBarColor(int barColor)
	{

		mBarColor = barColor;
		createBar();
	}

	public void setConnectingLineWeight(float connectingLineWeight)
	{

		mConnectingLineWeight = connectingLineWeight;
		createConnectingLine();
	}

	public void setConnectingLineColor(int connectingLineColor)
	{

		mConnectingLineColor = connectingLineColor;
		createConnectingLine();
	}

	public void setThumbRadius(float thumbRadius)
	{

		mThumbRadiusDP = thumbRadius;
		createThumbs();
	}

	public void setThumbImageNormal(int thumbImageNormalID)
	{
		mThumbImageNormal = thumbImageNormalID;
		createThumbs();
	}

	public void setThumbImagePressed(int thumbImagePressedID)
	{
		mThumbImagePressed = thumbImagePressedID;
		createThumbs();
	}

	public void setThumbColorNormal(int thumbColorNormal)
	{
		mThumbColorNormal = thumbColorNormal;
		createThumbs();
	}

	public void setThumbColorPressed(int thumbColorPressed)
	{
		mThumbColorPressed = thumbColorPressed;
		createThumbs();
	}

	public void setThumbIndices(int leftThumbIndex, int rightThumbIndex)
	{
		if (indexOutOfSeek(leftThumbIndex, rightThumbIndex))
		{

			Log.e(TAG, "A thumb index is out of bounds. Check that it is between 0 and mProgressCount - 1");
			throw new IllegalArgumentException("A thumb index is out of bounds. Check that it is between 0 and mProgressCount - 1");

		}
		else
		{

			if (mFirstSetTickCount == true)
				mFirstSetTickCount = false;

			mLeftIndex = leftThumbIndex;
			mRightIndex = rightThumbIndex;
			createThumbs();

			if (mListener != null)
			{
				mListener.onIndexChangeListener(this, mLeftIndex);
			}
		}

		invalidate();
		requestLayout();
	}

	public int getLeftIndex()
	{
		return mLeftIndex;
	}

	public int getRightIndex()
	{
		return mRightIndex;
	}

	private void SeekBarInit(Context context, AttributeSet attrs)
	{
		TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CustomSeekBar, 0, 0);

		try
		{
			final Integer tickCount = ta.getInteger(R.styleable.CustomSeekBar_progressCount, DEFAULT_PROGRESS_COUNT);

			if (isValidTickCount(tickCount))
			{
				mProgressCount = tickCount;
				mLeftIndex = 0;
				mRightIndex = mProgressCount - 1;

				if (mListener != null)
				{
					mListener.onIndexChangeListener(this, mLeftIndex);
				}

			}
			else
			{

				Log.e(TAG, "tickCount less than 2; invalid tickCount. XML input ignored.");
			}

			mBarWeight = ta.getDimension(R.styleable.CustomSeekBar_barWeight, DEFAULT_BAR_WEIGHT_PX);
			mBarColor = ta.getColor(R.styleable.CustomSeekBar_barColor, DEFAULT_BAR_COLOR);
			mConnectingLineWeight = ta.getDimension(R.styleable.CustomSeekBar_connectingLineWeight, DEFAULT_CONNECTING_LINE_WEIGHT_PX);
			mConnectingLineColor = ta.getColor(R.styleable.CustomSeekBar_connectingLineColor, DEFAULT_CONNECTING_LINE_COLOR);
			mThumbRadiusDP = ta.getDimension(R.styleable.CustomSeekBar_thumbRadius, DEFAULT_THUMB_RADIUS_DP);
			mThumbImageNormal = ta.getResourceId(R.styleable.CustomSeekBar_thumbImageNormal, DEFAULT_THUMB_IMAGE_NORMAL);
			mThumbImagePressed = ta.getResourceId(R.styleable.CustomSeekBar_thumbImagePressed, DEFAULT_THUMB_IMAGE_PRESSED);
			mThumbColorNormal = ta.getColor(R.styleable.CustomSeekBar_thumbColorNormal, DEFAULT_THUMB_COLOR_NORMAL);
			mThumbColorPressed = ta.getColor(R.styleable.CustomSeekBar_thumbColorPressed, DEFAULT_THUMB_COLOR_PRESSED);

		}
		finally
		{

			ta.recycle();
		}

	}

	private void createBar()
	{

		mBar = new BackgroundBar(getContext(), getMarginLeft(), getYPos(), getBarLength(), mProgressCount, mBarWeight, mBarColor);
		invalidate();
	}

	private void createConnectingLine()
	{

		mConnectingLine = new TrailingLine(getContext(), getYPos(), mConnectingLineWeight, mConnectingLineColor);
		invalidate();
	}

	private void createThumbs()
	{

		Context ctx = getContext();
		float yPos = getYPos();

		mLeftThumb = new SeekThumb(ctx, yPos, mThumbColorNormal, mThumbColorPressed, mThumbRadiusDP, mThumbImageNormal, mThumbImagePressed);

		float marginLeft = getMarginLeft();
		float barLength = getBarLength();
		mLeftThumb.setX(marginLeft + (mLeftIndex / (float) (mProgressCount - 1)) * barLength);
		invalidate();
	}

	private float getMarginLeft()
	{
		return ((mLeftThumb != null) ? mLeftThumb.getHalfWidth() : 0);
	}

	private float getYPos()
	{
		return (getHeight() / 2f);
	}

	private float getBarLength()
	{
		return (getWidth() - 2 * getMarginLeft());
	}

	private boolean indexOutOfSeek(int leftThumbIndex, int rightThumbIndex)
	{
		return (leftThumbIndex < 0 || leftThumbIndex >= mProgressCount || rightThumbIndex < 0 || rightThumbIndex >= mProgressCount);
	}

	private boolean isValidTickCount(int tickCount)
	{
		return (tickCount > 1);
	}

	private void onActionDown(float x, float y)
	{

		if (!mLeftThumb.isPressed() && mLeftThumb.isInTargetZone(x, y))
		{

			pressThumb(mLeftThumb);

		}
	}

	private void onActionUp(float x, float y)
	{

		if (mLeftThumb.isPressed())
		{

			releaseThumb(mLeftThumb);

		}
		else
		{

			final int newLeftIndex = mBar.getNearestTickIndex(mLeftThumb);
			if (newLeftIndex != mLeftIndex)
			{
				mLeftIndex = newLeftIndex;

				if (mListener != null)
				{
					mListener.onIndexChangeListener(this, mLeftIndex);
				}
			}
		}
	}

	private void onActionMove(float x)
	{

		if (mLeftThumb.isPressed())
		{
			moveThumb(mLeftThumb, x);
		}
		final int newLeftIndex = mBar.getNearestTickIndex(mLeftThumb);
		if (newLeftIndex != mLeftIndex)
		{
			mLeftIndex = newLeftIndex;

			if (mListener != null)
			{
				mListener.onIndexChangeListener(this, mLeftIndex);
			}
		}
	}

	private void pressThumb(SeekThumb thumb)
	{
		if (mFirstSetTickCount == true)
			mFirstSetTickCount = false;
		thumb.press();
		invalidate();
	}

	private void releaseThumb(SeekThumb thumb)
	{

		final float nearestTickX = mBar.getNearestTickCoordinate(thumb);
		thumb.setX(nearestTickX);
		thumb.release();
		invalidate();
	}

	private void moveThumb(SeekThumb thumb, float x)
	{
		if (x < mBar.getLeftX() || x > mBar.getRightX())
		{
		}
		else
		{
			thumb.setX(x);
			invalidate();
		}
	}

	public static interface OnSeekBarChangeListener
	{
		public void onIndexChangeListener(CustomSeekBar SeekBar, int leftThumbIndex);
	}
}


text:
package edu.iastate.cs228.hw5;

import java.util.List;
import java.util.ArrayList;
import java.util.NoSuchElementException;

interface PurePriorityQueue<E>
{
  int size();
  boolean isEmpty();
  void add(E element);
  // Returns a high-priority element without removing it.
  E getMin();
  // Removes a high-priority element.
  E removeMin();
}

public class Heap<E extends Comparable<? super E>>
   implements PurePriorityQueue<E>
{
  private static final int INIT_CAP = 10;
  private ArrayList<E> list;

  public Heap()
  {
    list = new ArrayList<E>(INIT_CAP);
  }

  public Heap(int aSize)
  {
     if ( aSize < 1 )
	throw new IllegalStateException();
     list = new ArrayList<E>(aSize);
  }

  // Builds a heap from a list of elements.
  public Heap(List<E>  aList)
  {
     int j, k;
     int len = aList.size();
     if ( len < 1 )
	throw new IllegalArgumentException();
     list = new ArrayList<E>(len);
     for ( E t : aList )
        list.add(t);
     if ( len < 2 ) return;
     j = (len - 2) / 2; // j is the largest index of an internal node with a child.
     for ( k = j; k >= 0; k-- )
        percolateDown(k);
  }  // O(n) time

  public int size()
  {
    return list.size();
  }

  public boolean isEmpty()
  {
    return list.isEmpty();
  }

  public void add(E element)
  {
    if ( element == null )
      throw new NullPointerException("add");
    list.add(element); // append it to the end of the list
    percolateUp(); // move it up to the proper place
  }

  // move the last element up to the proper place.
  private void percolateUp()
  {
     int child = list.size() - 1; // last element in the list
     int parent;
     while ( child > 0 )
     {
       parent = (child - 1) / 2; // use the (j-1)/2 formula
       if ( list.get(child).compareTo(list.get(parent)) >= 0 )
          break;
       swap(parent, child);
       child = parent;
     }
  }

  private void swap(int parent, int child)
  {
    E tmp = list.get(parent);
    list.set( parent, list.get(child) );
    list.set(child, tmp);
  }

  public E getMin()
  {
    if ( list.isEmpty() )
      throw new NoSuchElementException();
    return list.get(0);
  }

  public E removeMin()
  {
    if ( list.isEmpty() )
      throw new NoSuchElementException();
    E minElem = list.get(0); // get the min element at the root
    list.set(0, list.get(list.size() - 1) ); // copy the last element to the root
    list.remove( list.size() - 1 ); // remove the last element from the list
    if ( ! list.isEmpty() )
     percolateDown(0); // move the element at the root down to the proper place
    return minElem;
  }

  // Move the element at index start down to the proper place.
  private void percolateDown(int start)
  {
    if ( start < 0 || start >= list.size() )
      throw new RuntimeException("start < 0 or >= n");
    int parent = start;
    int child = 2 * parent + 1; // use the 2*i+1 formula
    while ( child < list.size() )
    {
      if ( child + 1 < list.size() &&
           list.get(child).compareTo(list.get(child + 1)) > 0 )
          child++; // select the smaller child
      if ( list.get(child).compareTo(list.get(parent)) >= 0 )
          break; // reach the proper place
      swap(parent, child);
      parent = child;
      child = 2 * parent + 1;
    }
  }

  // Heap Sort
  public static <E extends Comparable<? super E>> void heapSort(List<E> aList)
  {
    if ( aList.isEmpty() ) return;
    Heap<E> aHeap = new Heap<E>(aList);
    aList.clear();
    while ( ! aHeap.isEmpty() )
      aList.add( aHeap.removeMin() );
  } // repeatedly remove the smallest element in the heap and add it to the list.

} // Heap


text:
//
//  AllGroupViewController.m
//  Intelligentlamp
//
//  Created by L on 16/8/28.
//  Copyright © 2016年 L. All rights reserved.
//

#import "AllGroupViewController.h"

#import "AllGroupModel.h"
#import "AllGroupCell.h"
#import "GroupLampViewController.h"
#import "GroupSetUpViewController.h"
#import "GroupFooterView.h"
#import "AddGroupViewController.h"

@interface AllGroupViewController()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,strong) UITableView *tableView;//列表
@property (nonatomic ,strong) NSMutableArray *allDataArr;//列表数据源
@property (nonatomic ,strong) GroupFooterView *footView;//尾部

@property (assign , nonatomic) int pageno; /*第几页*/
@property (nonatomic, copy) NSString *refreshTime;//最后刷新的时间,下拉刷新时要传

@end

@implementation AllGroupViewController

- (void)viewDidLoad{
    [super viewDidLoad];

    _refreshTime = [[NSString alloc]init];
    _pageno = 1;
//    self.navigationItem.rightBarButtonItem = [self rightBarItem];

    [self leftBarButtonItem:[UIImage imageNamed:@"BackArrow"] withClickBtnAction:^{
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [self setTitleViewWithStr:@"分组"];

    [self layoutUI];

    [self setTableID];
}
#pragma -mark ViewController 生命周期函数

- (UIBarButtonItem *)rightBarItem{

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 40, 30);
    [btn setTitle:@"编辑" forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    [btn setTitleColor:AllLampTitleColor forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc]initWithCustomView:btn];
    return rightBarItem;
}
//按钮对应tableView的编辑模式
-(void)btnPressed:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    if (self.tableView.editing == YES)
    {
        [btn setTitle:@"编辑" forState:UIControlStateNormal];
        [self.tableView setEditing:NO animated:YES];
    }
    else
    {
        [btn setTitle:@"完成" forState:UIControlStateNormal];
        [self.tableView setEditing:YES animated:YES];
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (NSMutableArray *)allDataArr{
    if (_allDataArr == nil) {
        _allDataArr = [NSMutableArray array];
    }
    return _allDataArr;
}

- (void)layoutUI{

    WEAKSELF

    _tableView = [[UITableView alloc]init];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];

    //添加_footView
    _footView = [[GroupFooterView alloc]init];
    [_footView layoutFooterView];
    CGFloat height = [_footView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height + _footView.frame.origin.y;

    CGRect footFrame             = _footView.frame;
    footFrame.size.height        = height;
    _footView.frame          = footFrame;
//    [self.tableView setTableFooterView:_footView];

    _footView.addGroupBlock = ^(){
        AddGroupViewController *vc = [[AddGroupViewController alloc]init];
        vc.hidesBottomBarWhenPushed = YES;
        [weakSelf.navigationController pushViewController:vc animated:YES];

    };

    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        _pageno ++;
        // 进入刷新状态后会自动调用这个block
        [weakSelf networkForAllGroup];
    }];

    _tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [_allDataArr removeAllObjects];
        weakSelf.pageno = 1;
        [weakSelf networkForAllGroup];

    }];
    [_tableView.mj_header beginRefreshing];

}

- (void)networkForAllGroup{

    NSMutableDictionary *dic                = [NSMutableDictionary dictionary];
    [dic setValue:@"1.0.0" forKey:@"version"];
    [dic setValue:_lampId forKey:@"deviceId"];
    [dic setValue:getUserId() forKey:@"userId"];
    [dic setValue:_refreshTime forKey:@"refreshTime"];
    [dic setValue:getUserToken() forKey:@"token"];
    [dic setValue:[NSString stringWithFormat:@"%d",_pageno] forKey:@"pageNo"];//页数
    [dic setValue:@"10" forKey:@"pageSize"];//每页多少数据

    [self showNetWorkView];

    [LXNetworking postWithUrl:Group_GetDeviceGroupList params:dic success:^(id response) {
        [self hideNetWorkView];

        if ([response[@"deviceGroupList"] isEqual:[NSNull null]]) {

            [self showRemendWarningView:@"没有更多数据" withBlock:nil];
            [_tableView.mj_footer endRefreshing];
            [_tableView.mj_header endRefreshing];
            return ;
        }

        if (response[@"deviceGroupList"] != nil ||![response[@"deviceGroupList"] isEqual:[NSNull null]]) {

            NSArray *arr = response[@"deviceGroupList"];
            _refreshTime = response[@"refreshTime"];
            for (int i = 0; i<arr.count; i++) {
                AllGroupModel *model = [[AllGroupModel alloc]init];
                model.groupId = arr[i][@"groupId"];
                model.groupImg = arr[i][@"groupLogoURL"];
                model.groupTitle = arr[i][@"groupName"];
                model.groupDescribe = arr[i][@"description"];
                model.groupOpenTime = arr[i][@"timingOpenTime"];
                model.groupCloseTime = arr[i][@"timingCloseTime"];
                model.createTime = arr[i][@"createTime"];

                [self.allDataArr addObject:model];
            }

        }

        [_tableView reloadData];
        [_tableView.mj_footer endRefreshing];
        [_tableView.mj_header endRefreshing];
    } fail:^(NSError *error) {
        [self hideNetWorkView];
        [_tableView.mj_footer endRefreshing];
        [_tableView.mj_header endRefreshing];
    } showHUD:nil];

}

- (void)setTableID{
    [self.tableView registerClass:[AllGroupCell class] forCellReuseIdentifier:NSStringFromClass([AllGroupCell class])];
}

#pragma - mark UITableViewDelegate and DataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _allDataArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AllGroupCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([AllGroupCell class]) forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.indexPath = indexPath ;
    cell.setUpBtn.hidden = YES;
    cell.model = _allDataArr[indexPath.row];

    cell.setUpBlock = ^(NSIndexPath *index){
//        GroupSetUpViewController *vc = [[GroupSetUpViewController alloc]init];
//        vc.model =_allDataArr[index.row];
//        vc.hidesBottomBarWhenPushed = YES;
//        [self.navigationController pushViewController:vc animated:YES];
    };

    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    GroupLampViewController *vc = [[GroupLampViewController alloc]init];
//    vc.hidesBottomBarWhenPushed = YES;
//    AllGroupModel *model = [[AllGroupModel alloc]init];
//    model = _allDataArr[indexPath.row];
//    vc.controllerTitle = model.groupTitle;
//    [self.navigationController pushViewController:vc animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 61;
}

#pragma - mark UITableView的编辑方法

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath

{
    return YES;
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return UITableViewCellEditingStyleDelete;

}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath

{
      [_allDataArr removeObjectAtIndex:indexPath.row];

    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

@end


text:
package main

import (
	"fmt"
	"log"
	"net"
	"os"
	"os/signal"
	"runtime"
	"strings"
	"syscall"
	"time"

	"github.com/bitly/go-nsq"
	"github.com/giskook/go-toolkit"
	"github.com/giskook/gotcp"
	"github.com/giskook/gotcp/examples/das"
)

func getMacByte(Mac string) []byte {
	var mac []byte
	var macbits byte
	macbits = 0
	for i := 0; i < len(Mac)/2; i += 2 {
		macbits += Mac[i] - '0'
		macbits += (Mac[i+1] - '0') * 16
		mac = append(mac, macbits)
		macbits = 0
	}

	return mac
}

func recvNsq(q *gotcp.Mqhub, topic string, channel string) {
	config := nsq.NewConfig()
	consumer, errormsg := nsq.NewConsumer(topic, channel, config)
	if errormsg != nil {
		log.Printf("create Consumer error-->" + errormsg.Error())
		return
	}

	consumer.AddHandler(nsq.HandlerFunc(func(message *nsq.Message) error {
		cmd := message.Body
		fmt.Printf("recv message from nsq %v\n", cmd)
		commandtype := cmd[0]
		mac := string(cmd[1:13])
		fmt.Printf("recv mac from nsq %s\n", mac)
		serialid := gktoolkit.BytesToUInt32(cmd[13:17])
		fmt.Printf("recv serialid from nsq %d\n", serialid)
		_topic := string(cmd[17:len(cmd)])
		fmt.Printf("recv topic from nsq %s\n", _topic)
		var feedback []byte
		if commandtype == 0 { // check online
			feedback = append(feedback, 0x00)
			feedback = append(feedback, mac...)
			feedback = append(feedback, gktoolkit.UInt32ToBytes(serialid)...)
			if q.Exist(mac) {
				feedback = append(feedback, 0x01)
			} else {
				feedback = append(feedback, 0x00)
			}
			q.Send(_topic, feedback)
		} else {
			macupper := strings.ToUpper(mac)
			if q.GetConn(macupper) != nil {
				fmt.Printf("-------mac :%s,topic :%s----\n", mac, _topic)
				q.GetConn(macupper).SetTopic(_topic)
				q.GetConn(macupper).SetMac(macupper)
				q.GetConn(macupper).NsqWritePacket(das.NewNsqPacket(_topic, commandtype, getMacByte(macupper), serialid, 0), time.Second)
			}
		}

		return nil
	}))

	err := consumer.ConnectToNSQD(q.GetAddr())
	if err != nil {
		log.Panic("Could not connect")
	}
}

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	// create a tcp listener
	tcpAddr, err := net.ResolveTCPAddr("tcp4", ":7082")
	checkError(err)
	listener, err := net.ListenTCP("tcp", tcpAddr)
	checkError(err)

	// create a server
	config := &gotcp.Config{
		PacketSendChanLimit:    20,
		PacketReceiveChanLimit: 20,
	}

	mqconfig := &gotcp.MqConfig{
		Addr:    "127.0.0.1:4150",
		Topic:   "commandproduce",
		Channel: "1",
	}

	nsqhub := gotcp.Newmqhub(mqconfig, &das.NsqProtocol{})

	nsqhub.Start()
	go recvNsq(nsqhub, "command", "1")

	srv := gotcp.NewServer(config, &das.DasCallback{}, &das.DasProtocol{}, nsqhub)

	// starts service
	go srv.Start(listener, time.Second)
	fmt.Println("listening:", listener.Addr())

	// catchs system signal
	chSig := make(chan os.Signal)
	signal.Notify(chSig, syscall.SIGINT, syscall.SIGTERM)
	fmt.Println("Signal: ", <-chSig)

	// stops server
	srv.Stop()
}

func checkError(err error) {
	if err != nil {
		log.Fatal(err)
	}
}


text:
{{ super() }}

# endblock

# block contents

Execution Error
Unfortunately there were errors when running your tournament simulation. Sorry.

# for error in errors

{{ error.text }}

# endfor

If this happens multiple times, you can contact us and tell us about the problem.
You could try it again.

# endblock


text:
module Gemfiler
  class Filer
    attr_accessor :cabinet, :groups, :uncategorized

    def initialize(cabinet)
      @cabinet       = cabinet
      @groups        = {}
      @uncategorized = []
    end

    def group
      cabinet.gems.each do |gem|
        if gem[:groups]
          gem_groups           = gem.delete(:groups).sort
          groups[gem_groups] ||= []
          groups[gem_groups] << gem
        else
          uncategorized << gem
        end
      end
    end

    def alphabetize
      self.uncategorized = alphabetize_from_array(self.uncategorized)
      self.groups = self.groups.inject({}) do |hash, (groups, gems)|
        hash[groups] = alphabetize_from_array(gems)
        hash
      end
    end

    # Delegate shim
    def shim
      cabinet.shim
    end

    private

    def alphabetize_from_array(gems)
      gems.sort_by {|g| g[:name] }
    end
  end
end


text:
namespace torch { namespace cudnn {

cudnnDataType_t getCudnnDataType(PyObject *tensorClass)
{
  if (tensorClass == THCPFloatTensorClass) {
    return CUDNN_DATA_FLOAT;
  } else if (tensorClass == THCPDoubleTensorClass) {
    return CUDNN_DATA_DOUBLE;
  } else if (tensorClass == THCPHalfTensorClass) {
    return CUDNN_DATA_HALF;
  }
  if (!PyType_Check(tensorClass)) {
    throw std::runtime_error("getCudnnDataType() expects a PyTypeObject");
  }
  std::string msg("getCudnnDataType() not supported for ");
  msg += ((PyTypeObject*)tensorClass)->tp_name;
  throw std::runtime_error(msg);
}

cudnnDataType_t getCudnnDataType(const thpp::Tensor& tensor)
{
  if (tensor.type() == thpp::Type::FLOAT) {
    return CUDNN_DATA_FLOAT;
  } else if (tensor.type() == thpp::Type::DOUBLE) {
    return CUDNN_DATA_DOUBLE;
  } else if (tensor.type() == thpp::Type::HALF) {
    return CUDNN_DATA_HALF;
  }
  std::string msg("getCudnnDataType() not supported for ");
  msg += (int)tensor.type();
  throw std::runtime_error(msg);
}

PyObject * getTensorClass(PyObject *args)
{
  for (int i = 0; i < PyTuple_Size(args); i++) {
    PyObject *item = PyTuple_GET_ITEM(args, i);
    if (THPModule_isTensor(item)) {
      return (PyObject*)Py_TYPE(item);
    }
  }
  return NULL;
}

void _THVoidTensor_assertContiguous(THVoidTensor *tensor, const std::string& name)
{
  static const std::string error_str = "cuDNN requires contiguous ";
  // Contiguity check
  long long expectedStride = 1;
  for (int i = tensor->nDimension-1; i >= 0; --i) {
    if (tensor->stride[i] != expectedStride)
      throw std::invalid_argument(error_str + name);
    expectedStride *= tensor->size[i];
  }
}

}}  // namespace torch::cudnn


text:
'''
htriple

Numerically integrate the dynamics of a hierarchical triple.
'''

import numpy as np
from math import *
from scipy.integrate import ode, quad

from constants import *
from secular import *
from full import *

class HTriple:
    def __init__(self, setup):
        self.setSetup(setup)

        self.outputLimit     = 1e6
        self.sampling      = 1
        self.method        = 'full'
        self.methodOptions = {}

        self.initSolver()
        self.setIntegrator()
        self.reset()

        pass

    def setSetup(self, setup):
        for key in ['phi', 'i', 'e1', 'e2', 'g1', 'g2']:
            if key not in setup:
                setup[key] = 0.

        self.setup     = setup

    def initSolver(self):
        self.solver = ode(self._derivatives)

        pass

    def setMethod(self, method = 'secular', options = {}):
        if method not in ['secular', 'full']:
            raise ValueError("Method must be either 'secular' or full.")

        self.method = method
        self.methodOptions = options

    def setIntegrator(self, algorithm='vode', h=1e-3, atol=1e-9, rtol=1e-9, nsteps=1):
        self.nstep     = 0
        self.algorithm = algorithm
        self.h         = h
        self.atol      = atol
        self.rtol      = rtol
        self.nsteps    = nsteps

        self.solver.set_integrator(self.algorithm, nsteps=self.nsteps, atol=self.atol, rtol=self.rtol)

    def setSolver(self, solver):
        self.solver = solver

    def reset(self):
        self.t         = 0
        self.duration  = 0
        self.tmax      = 0

        if self.method == 'secular':
            self.strategy = SecularEvolutionEquations(self.setup, self.methodOptions)

        if self.method == 'full':
            self.strategy = FullEvolutionEquations(self.setup, self.methodOptions)

        self.state = self.strategy.getInitialConditions()
        self.solver.set_initial_value(self.state, self.t)

        self.steps = np.zeros((int(self.outputLimit), len(self.state)))
        self.steps[0] = self.state

    def _derivatives(self, t, x):
        return self.strategy.derivatives(t, x)

    def evolve(self, years):
        if self.duration == False:
            self.reset()

        self.duration = self.duration + years

        self.tmax = self.tmax + years / self.strategy.time

        while (self.t < self.tmax):
          self._step()

          if self.nstep % self.sampling == 0:
            self.steps[self.nstep/self.sampling] = self.state

        laststep = (self.nstep / self.sampling) + 1
        self.steps[laststep] = self.state

        return self.strategy.getResult()

    def _step(self):
        self.solver.integrate(self.tmax, step=True)
        self.nstep += 1

        self.t = self.solver.t / yr2s
        self.state = self.strategy.afterStep(self.solver.y)
        self.strategy.saveResult(self.t, self.state)

class Setup:
    def __init__(self, **kwargs):
        self.__dict__ = kwargs


text:
package org.wso2.carbon.device.mgt.common.spi;

import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.ProvisioningConfig;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;

/**
 * Composite interface that acts as the SPI exposing all device management as well as application management
 * functionalities.
 */
public interface DeviceManagementService {

    void init() throws DeviceManagementException;

    String getType();

    DeviceManager getDeviceManager();

    ApplicationManager getApplicationManager();

    ProvisioningConfig getProvisioningConfig();

    PushNotificationConfig getPushNotificationConfig();

}


text:
#ifndef sitkConditional_h
#define sitkConditional_h

namespace itk
{
namespace simple
{

/* \brief An object for selection of a type at compile-time.
 * *
 * If VCode is true, then the member Type will be TIfTrue, otherwise
 * the member typedef Type will be equivalent to TIfFalse.
 *
 */
template <bool VCond, class TIfTrue, class TIfFalse> struct Conditional { typedef TIfTrue Type; };
/** \cond SPECIALIZATION_IMPLEMENTATION */
template<class TIfTrue, class TIfFalse>
struct Conditional<false, TIfTrue, TIfFalse> { typedef TIfFalse Type; };

/**\endcond*/

/* \brief An object for selecting an integer value at compile-time.
 *
 *
 * If VCode is true, then the member Value will be TIfTrue, otherwise
 * the member Value  will be equivalent to TIfFalse.
 *
 * This class also contains a typedef for ValueType, which is an the
 * selected integral constant as a type.
 */
template <bool VCond, int TIfTrue, int TIfFalse>
struct ConditionalValue
  : public itk::simple::Conditional<VCond,
                                    nsstd::integral_constant<int, TIfTrue>,
                                    nsstd::integral_constant<int, TIfFalse> >::Type
{
private:
  typedef ConditionalValue Self;
public:
  typedef typename Self::value_type ValueType;
  typedef typename Self::type       Type;

  static const ValueType Value = Self::value;
};

}
}

#endif // sitkConditional_h


text:
require_relative '../../imcmo'
require_relative '../../imccoremeta'
require_relative '../../imcmeta'

class BiosProfileConsts
    ADMIN_ACTION_ACTIVATE = "activate"
    ADMIN_ACTION_DELETE = "delete"
    BACKUP_ON_ACTIVATE_FALSE = "false"
    BACKUP_ON_ACTIVATE_NO = "no"
    BACKUP_ON_ACTIVATE_TRUE = "true"
    BACKUP_ON_ACTIVATE_YES = "yes"
    REBOOT_ON_ACTIVATE_FALSE = "false"
    REBOOT_ON_ACTIVATE_NO = "no"
    REBOOT_ON_ACTIVATE_TRUE = "true"
    REBOOT_ON_ACTIVATE_YES = "yes"
end

class BiosProfile < ManagedObject
    #This is BiosProfile class.

    @@consts = BiosProfileConsts.new()
#    @@naming_props = set([u'name'])

    @@mo_meta = {
        "classic" => MoMeta.new("BiosProfile", "biosProfile", "bios-profile-[name]", VersionMeta::VERSION301C, "InputOutput", 0xff, [], ["admin", "read-only", "user"], ["Get", "Set"]),
        "modular" => MoMeta.new("BiosProfile", "biosProfile", "bios-profile-[name]", VersionMeta::VERSION301C, "InputOutput", 0xff, [], ["admin", "read-only", "user"], ["Get", "Set"])
    }

    def self.mo_meta
        @@mo_meta
    end

    @@prop_meta = {

        "classic" => {
        "admin_action" => MoPropertyMeta.new("admin_action", "adminAction", "string", VersionMeta::VERSION301C, MoPropertyMeta::READ_WRITE, 0x2, 0, 510, nil, ["activate", "delete"], []),
        "backup_on_activate" => MoPropertyMeta.new("backup_on_activate", "backupOnActivate", "string", VersionMeta::VERSION301C, MoPropertyMeta::READ_WRITE, 0x4, nil, nil, nil, ["No", "Yes", "false", "no", "true", "yes"], []),
        "child_action" => MoPropertyMeta.new("child_action", "childAction", "string", VersionMeta::VERSION301C, MoPropertyMeta::INTERNAL, nil, nil, nil, nil, [], []),
        "description" => MoPropertyMeta.new("description", "description", "string", VersionMeta::VERSION301C, MoPropertyMeta::READ_ONLY, nil, 0, 510, nil, [], []),
        "dn" => MoPropertyMeta.new("dn", "dn", "string", VersionMeta::VERSION301C, MoPropertyMeta::READ_WRITE, 0x8, 0, 255, nil, [], []),
        "enabled" => MoPropertyMeta.new("enabled", "enabled", "string", VersionMeta::VERSION301C, MoPropertyMeta::READ_WRITE, 0x10, nil, nil, nil, ["No", "Yes", "false", "no", "true", "yes"], []),
        "id" => MoPropertyMeta.new("id", "id", "string", VersionMeta::VERSION301C, MoPropertyMeta::READ_ONLY, nil, 0, 510, nil, [], []),
        "name" => MoPropertyMeta.new("name", "name", "string", VersionMeta::VERSION301C, MoPropertyMeta::NAMING, nil, 0, 510, nil, [], []),
        "reboot_on_activate" => MoPropertyMeta.new("reboot_on_activate", "rebootOnActivate", "string", VersionMeta::VERSION301C, MoPropertyMeta::READ_WRITE, 0x20, nil, nil, nil, ["No", "Yes", "false", "no", "true", "yes"], []),
        "rn" => MoPropertyMeta.new("rn", "rn", "string", VersionMeta::VERSION301C, MoPropertyMeta::READ_WRITE, 0x40, 0, 255, nil, [], []),
        "status" => MoPropertyMeta.new("status", "status", "string", VersionMeta::VERSION301C, MoPropertyMeta::READ_WRITE, 0x80, nil, nil, nil, ["", "created", "deleted", "modified", "removed"], []),
        },

        "modular" => {
            "admin_action" => MoPropertyMeta.new("admin_action", "adminAction", "string", VersionMeta::VERSION301C, MoPropertyMeta::READ_WRITE, 0x2, 0, 510, nil, ["activate", "delete"], []),
            "backup_on_activate" => MoPropertyMeta.new("backup_on_activate", "backupOnActivate", "string", VersionMeta::VERSION301C, MoPropertyMeta::READ_WRITE, 0x4, nil, nil, nil, ["No", "Yes", "no", "yes"], []),
            "child_action" => MoPropertyMeta.new("child_action", "childAction", "string", VersionMeta::VERSION301C, MoPropertyMeta::INTERNAL, nil, nil, nil, nil, [], []),
            "description" => MoPropertyMeta.new("description", "description", "string", VersionMeta::VERSION301C, MoPropertyMeta::READ_ONLY, nil, 0, 510, nil, [], []),
            "dn" => MoPropertyMeta.new("dn", "dn", "string", VersionMeta::VERSION301C, MoPropertyMeta::READ_WRITE, 0x8, 0, 255, nil, [], []),
            "enabled" => MoPropertyMeta.new("enabled", "enabled", "string", VersionMeta::VERSION301C, MoPropertyMeta::READ_WRITE, 0x10, nil, nil, nil, ["No", "Yes", "no", "yes"], []),
            "id" => MoPropertyMeta.new("id", "id", "string", VersionMeta::VERSION301C, MoPropertyMeta::READ_ONLY, nil, 0, 510, nil, [], []),
            "name" => MoPropertyMeta.new("name", "name", "string", VersionMeta::VERSION301C, MoPropertyMeta::NAMING, nil, 0, 510, nil, [], []),
            "reboot_on_activate" => MoPropertyMeta.new("reboot_on_activate", "rebootOnActivate", "string", VersionMeta::VERSION301C, MoPropertyMeta::READ_WRITE, 0x20, nil, nil, nil, ["No", "Yes", "no", "yes"], []),
            "rn" => MoPropertyMeta.new("rn", "rn", "string", VersionMeta::VERSION301C, MoPropertyMeta::READ_WRITE, 0x40, 0, 255, nil, [], []),
            "status" => MoPropertyMeta.new("status", "status", "string", VersionMeta::VERSION301C, MoPropertyMeta::READ_WRITE, 0x80, nil, nil, nil, ["", "created", "deleted", "modified", "removed"], []),
        },

    }

    def self.prop_meta
        @@prop_meta
    end

    @@prop_map = {

        "classic" => {
        "adminAction" => "admin_action",
        "backupOnActivate" => "backup_on_activate",
        "childAction" => "child_action",
        "description" => "description",
        "dn" => "dn",
        "enabled" => "enabled",
        "id" => "id",
        "name" => "name",
        "rebootOnActivate" => "reboot_on_activate",
        "rn" => "rn",
        "status" => "status",
        },

        "modular" => {
            "adminAction" => "admin_action",
            "backupOnActivate" => "backup_on_activate",
            "childAction" => "child_action",
            "description" => "description",
            "dn" => "dn",
            "enabled" => "enabled",
            "id" => "id",
            "name" => "name",
            "rebootOnActivate" => "reboot_on_activate",
            "rn" => "rn",
            "status" => "status",
        },

    }

    def self.prop_map
        @@prop_map
    end

    attr_reader :name
    attr_accessor :admin_action
    attr_accessor :backup_on_activate
    attr_reader :child_action
    attr_reader :description
    attr_accessor :enabled
    attr_reader :id
    attr_accessor :reboot_on_activate
    attr_accessor :status

    def initialize(parent_mo_or_dn: nil,name: nil,  **kwargs)
        @dirty_mask = 0
        @name = name
        @admin_action = nil
        @backup_on_activate = nil
        @child_action = nil
        @description = nil
        @enabled = nil
        @id = nil
        @reboot_on_activate = nil
        @status = nil

        super(class_id: "BiosProfile", parent_mo_or_dn: parent_mo_or_dn, **kwargs)

    end
end


text:
package com.jaquadro.minecraft.storagedrawersextra.core;

import com.jaquadro.minecraft.chameleon.Chameleon;
import com.jaquadro.minecraft.chameleon.resources.ModelRegistry;
import com.jaquadro.minecraft.storagedrawers.StorageDrawers;
import com.jaquadro.minecraft.storagedrawers.api.storage.EnumBasicDrawer;
import com.jaquadro.minecraft.storagedrawers.config.ConfigManager;
import com.jaquadro.minecraft.storagedrawersextra.StorageDrawersExtra;
import com.jaquadro.minecraft.storagedrawersextra.block.BlockExtraDrawers;
import com.jaquadro.minecraft.storagedrawersextra.block.BlockTrimExtra;
import com.jaquadro.minecraft.storagedrawersextra.block.EnumMod;
import com.jaquadro.minecraft.storagedrawersextra.block.EnumVariant;
import com.jaquadro.minecraft.storagedrawersextra.client.model.ExtraDrawerModel;
import com.jaquadro.minecraft.storagedrawersextra.client.model.ExtraTrimModel;
import com.jaquadro.minecraft.storagedrawersextra.config.ConfigManagerExt;
import com.jaquadro.minecraft.storagedrawersextra.item.ItemExtraDrawers;
import com.jaquadro.minecraft.storagedrawersextra.item.ItemTrimExtra;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.minecraftforge.registries.IForgeRegistry;

import javax.annotation.Nonnull;

public class ModBlocks
{
    public static BlockExtraDrawers extraDrawers;
    public static BlockTrimExtra[] extraTrim;

    @Mod.EventBusSubscriber(modid = StorageDrawersExtra.MOD_ID)
    public static class Registration
    {
        @SubscribeEvent
        public static void registerBlocks (RegistryEvent.Register<Block> event) {
            IForgeRegistry<Block> registry = event.getRegistry();

            extraDrawers = new BlockExtraDrawers("extra_drawers", "extraDrawers");
            registry.register(extraDrawers);

            extraTrim = new BlockTrimExtra[EnumVariant.groupCount()];
            for (int i = 0; i < extraTrim.length; i++) {
                extraTrim[i] = new BlockTrimExtra("extra_trim_" + i, "extraTrim" + i, i);
                registry.register(extraTrim[i]);
            }
        }

        @SubscribeEvent
        public static void registerItems (RegistryEvent.Register<Item> event) {
            IForgeRegistry<Item> registry = event.getRegistry();

            registry.register(new ItemExtraDrawers(extraDrawers).setRegistryName(extraDrawers.getRegistryName()));
            for (BlockTrimExtra trim : extraTrim)
                registry.register(new ItemTrimExtra(trim).setRegistryName(trim.getRegistryName()));

            for (String key : new String[] { "drawerBasic" })
                OreDictionary.registerOre(key, new ItemStack(extraDrawers, 1, OreDictionary.WILDCARD_VALUE));
            for (String key : new String[] { "drawerTrim" }) {
                for (BlockTrimExtra block : extraTrim)
                    OreDictionary.registerOre(key, new ItemStack(block, 1, OreDictionary.WILDCARD_VALUE));
            }
        }

        private static final ResourceLocation EMPTY_GROUP = new ResourceLocation("", "");

        @Nonnull
        public static ItemStack makeBasicDrawerItemStack (EnumBasicDrawer info, String material, int count) {
            @Nonnull ItemStack stack = new ItemStack(ModBlocks.extraDrawers, count, info.getMetadata());

            NBTTagCompound data = new NBTTagCompound();
            data.setString("material", material);
            stack.setTagCompound(data);

            return stack;
        }

        @SubscribeEvent
        public static void registerRecipes (RegistryEvent.Register<IRecipe> event) {
            IForgeRegistry<IRecipe> registry = event.getRegistry();
            ConfigManager config = StorageDrawers.config;
            ConfigManagerExt configExt = StorageDrawersExtra.config;

            for (EnumVariant variant : EnumVariant.values()) {
                if (variant == EnumVariant.DEFAULT)
                    continue;

                EnumMod mod = variant.getMod();
                if (mod == null || !mod.isEnabled(configExt.getModToggleState(mod)))
                    continue;

                @Nonnull ItemStack plankStack = ItemStack.EMPTY;
                if (variant.getPlankResource() != null) {
                    Block block = Block.getBlockFromName(variant.getPlankResource().toString());
                    if (block != null)
                        plankStack = new ItemStack(block, 1, variant.getPlankMeta());
                }

                @Nonnull ItemStack slabStack = ItemStack.EMPTY;
                if (variant.getSlabResource() != null) {
                    Block block = Block.getBlockFromName(variant.getSlabResource().toString());
                    if (block != null)
                        slabStack = new ItemStack(block, 1, variant.getSlabMeta());
                }

                String material = variant.getResource().toString();

                if (config.isBlockEnabled(EnumBasicDrawer.FULL1.getUnlocalizedName()) && !plankStack.isEmpty()) {
                    @Nonnull ItemStack result = makeBasicDrawerItemStack(EnumBasicDrawer.FULL1, material, config.getBlockRecipeOutput(EnumBasicDrawer.FULL1.getUnlocalizedName()));
                    registry.register(new ShapedOreRecipe(EMPTY_GROUP, result, "xxx", " y ", "xxx", 'x', plankStack, 'y', "chestWood")
                        .setRegistryName(result.getItem().getRegistryName() + "_" + EnumBasicDrawer.FULL1.getUnlocalizedName() + "_" + variant.toString()));
                }
                if (config.isBlockEnabled(EnumBasicDrawer.FULL2.getUnlocalizedName()) && !plankStack.isEmpty()) {
                    @Nonnull ItemStack result = makeBasicDrawerItemStack(EnumBasicDrawer.FULL2, material, config.getBlockRecipeOutput(EnumBasicDrawer.FULL2.getUnlocalizedName()));
                    registry.register(new ShapedOreRecipe(EMPTY_GROUP, result, "xyx", "xxx", "xyx", 'x', plankStack, 'y', "chestWood")
                        .setRegistryName(result.getItem().getRegistryName() + "_" + EnumBasicDrawer.FULL2.getUnlocalizedName() + "_" + variant.toString()));
                }
                if (config.isBlockEnabled(EnumBasicDrawer.FULL4.getUnlocalizedName()) && !plankStack.isEmpty()) {
                    @Nonnull ItemStack result = makeBasicDrawerItemStack(EnumBasicDrawer.FULL4, material, config.getBlockRecipeOutput(EnumBasicDrawer.FULL4.getUnlocalizedName()));
                    registry.register(new ShapedOreRecipe(EMPTY_GROUP, result, "yxy", "xxx", "yxy", 'x', plankStack, 'y', "chestWood")
                        .setRegistryName(result.getItem().getRegistryName() + "_" + EnumBasicDrawer.FULL4.getUnlocalizedName() + "_" + variant.toString()));
                }
                if (config.isBlockEnabled(EnumBasicDrawer.HALF2.getUnlocalizedName()) && !slabStack.isEmpty()) {
                    @Nonnull ItemStack result = makeBasicDrawerItemStack(EnumBasicDrawer.HALF2, material, config.getBlockRecipeOutput(EnumBasicDrawer.HALF2.getUnlocalizedName()));
                    registry.register(new ShapedOreRecipe(EMPTY_GROUP, result, "xyx", "xxx", "xyx", 'x', slabStack, 'y', "chestWood")
                        .setRegistryName(result.getItem().getRegistryName() + "_" + EnumBasicDrawer.HALF2.getUnlocalizedName() + "_" + variant.toString()));
                }
                if (config.isBlockEnabled(EnumBasicDrawer.HALF4.getUnlocalizedName()) && !slabStack.isEmpty()) {
                    @Nonnull ItemStack result = makeBasicDrawerItemStack(EnumBasicDrawer.HALF4, material, config.getBlockRecipeOutput(EnumBasicDrawer.HALF4.getUnlocalizedName()));
                    registry.register(new ShapedOreRecipe(EMPTY_GROUP, result, "yxy", "xxx", "yxy", 'x', slabStack, 'y', "chestWood")
                        .setRegistryName(result.getItem().getRegistryName() + "_" + EnumBasicDrawer.HALF4.getUnlocalizedName() + "_" + variant.toString()));
                }
                if (config.isBlockEnabled("trim") && !plankStack.isEmpty()) {
                    @Nonnull ItemStack result = new ItemStack(ModBlocks.extraTrim[variant.getGroupIndex()], config.getBlockRecipeOutput("trim"), variant.getGroupMeta());
                    registry.register(new ShapedOreRecipe(EMPTY_GROUP, result, "xyx", "yyy", "xyx", 'x', "stickWood", 'y', plankStack)
                        .setRegistryName(result.getItem().getRegistryName() + "_" + variant.toString()));
                }
            }
        }

        @SubscribeEvent
        @SideOnly(Side.CLIENT)
        public static void registerModels (ModelRegistryEvent event) {
            extraDrawers.initDynamic();

            ModelRegistry modelRegistry = Chameleon.instance.modelRegistry;

            modelRegistry.registerModel(new ExtraDrawerModel.Register());
            for (BlockTrimExtra block : extraTrim)
                modelRegistry.registerModel(new ExtraTrimModel.Register(block));
        }
    }
}


text: MathJax.Localization.addTranslation("cy","TeX",{version:"2.7.7",isLoaded:true,strings:{}});MathJax.Ajax.loadComplete("[MathJax]/localization/cy/TeX.js");


text:
using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;

namespace ImageFileHandler
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}


text:
<?php
/**
 * Shipping Calculator
 *
 * @author 		WooThemes
 * @package 	WooCommerce/Templates
 * @version     1.6.4
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

global $woocommerce;

if ( get_option('woocommerce_enable_shipping_calc')=='no' || ! $woocommerce->cart->needs_shipping() ) return;
?>

<?php do_action( 'woocommerce_before_shipping_calculator' ); ?>

<form class="shipping_calculator" action="<?php echo esc_url( $woocommerce->cart->get_cart_url() ); ?>" method="post">

<?php _e( 'Calculate Shipping', 'woocommerce' ); ?> ↓

		<select name="calc_shipping_country" id="calc_shipping_country" class="country_to_state" rel="calc_shipping_state">
			<option value=""><?php _e( 'Select a country…', 'woocommerce' ); ?></option>
			<?php
				foreach( $woocommerce->countries->get_allowed_countries() as $key => $value )
					echo '<option value="' . $key . '"' . selected( $woocommerce->customer->get_shipping_country(), esc_attr( $key ), false ) . '>' . esc_html( $value ) . '</option>';
			?>
		</select>
		<?php
			$current_cc = $woocommerce->customer->get_shipping_country();
			$current_r = $woocommerce->customer->get_shipping_state();

			$states = $woocommerce->countries->get_states( $current_cc );

			if ( is_array( $states ) && empty( $states ) ) {

				// Hidden
				?>
				<input type="hidden" name="calc_shipping_state" id="calc_shipping_state" placeholder="<?php _e( 'State / county', 'woocommerce' ); ?>" />
				<?php

			} elseif ( is_array( $states ) ) {

				// Dropdown
				?>

					<select name="calc_shipping_state" id="calc_shipping_state" placeholder="<?php _e( 'State / county', 'woocommerce' ); ?>"><option value=""><?php _e( 'Select a state…', 'woocommerce' ); ?></option><?php
						foreach ( $states as $ckey => $cvalue )
							echo '<option value="' . esc_attr( $ckey ) . '" '.selected( $current_r, $ckey, false ) .'>' . __( esc_html( $cvalue ), 'woocommerce' ) .'</option>';
					?></select>

				<?php

			} else {

				// Input
				?>
				<input type="text" class="input-text" value="<?php echo esc_attr( $current_r ); ?>" placeholder="<?php _e( 'State / county', 'woocommerce' ); ?>" name="calc_shipping_state" id="calc_shipping_state" />
				<?php

			}
		?>
			<input type="text" class="input-text" value="<?php echo esc_attr( $woocommerce->customer->get_shipping_postcode() ); ?>" placeholder="<?php _e( 'Postcode / Zip', 'woocommerce' ); ?>" title="<?php _e( 'Postcode', 'woocommerce' ); ?>" name="calc_shipping_postcode" id="calc_shipping_postcode" />
			<button type="submit" name="calc_shipping" value="1" class="button"><?php _e( 'Update Totals', 'woocommerce' ); ?></button>
		<?php $woocommerce->nonce_field('cart') ?>

</form>

<?php do_action( 'woocommerce_after_shipping_calculator' ); ?>


text:
/**
 * @author ARTEMIO
 */

var label1 = Titanium.UI.createLabel({
	color:'#999',
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	textAlign:'center',
	width:'auto'
});

win1.add(label1);


text:
import { createActions } from 'spunky'
import Neon from '@cityofzion/neon-js'
import { isEmpty } from 'lodash-es'

import { toBigNumber } from '../core/math'
import { getStorage, setStorage } from '../core/storage'
import { getNode, getRPCEndpoint } from './nodeStorageActions'
import {
  findAndReturnTokenInfo,
  getImageBySymbol,
} from '../util/findAndReturnTokenInfo'

export const ID = 'pendingTransactions'
const STORAGE_KEY = 'pendingTransactions'
const MINIMUM_CONFIRMATIONS = 2
const INVALID_TX_ERROR_MESSAGE = 'Unknown transaction'

export const parseContractTransaction = async (
  transaction: PendingTransaction,
  net: string,
): Promise<Array<ParsedPendingTransaction>> => {
  const parsedData = []
  // eslint-disable-next-line camelcase
  const {
    confirmations,
    txid,
    net_fee, // eslint-disable-line camelcase
    blocktime = 0,
    sendEntries,
  } = transaction

  for (const send of sendEntries) {
    parsedData.push({
      confirmations,
      txid: txid.substring(2),
      net_fee,
      blocktime,
      amount: toBigNumber(send.amount).toString(),
      to: send.address,
      asset: await findAndReturnTokenInfo('', net, send.symbol),
    })
  }
  return parsedData
}

export const parseInvocationTransaction = (
  transaction: PendingTransaction,
): Array<ParsedPendingTransaction> => {
  const {
    confirmations,
    txid,
    // eslint-disable-next-line camelcase
    net_fee,
    blocktime = 0,
    sendEntries,
  } = transaction

  // things get tricky during invocation transactions as there is no vout array
  // and it is not straight forward parsing the produced script. Instead we
  // use the original send entries array.
  return sendEntries.map(send => ({
    confirmations,
    txid: txid.substring(2),
    net_fee,
    blocktime,
    amount: toBigNumber(send.amount).toString(),
    to: send.address,
    asset: {
      symbol: send.symbol,
      image: getImageBySymbol(send.symbol),
    },
  }))
}

export const parseTransactionInfo = async (
  pendingTransactionsInfo: Array<PendingTransaction>,
  net: string,
) => {
  const parsedData: Array<ParsedPendingTransaction> = []
  for (const transaction of pendingTransactionsInfo) {
    if (transaction) {
      if (transaction.type === 'InvocationTransaction') {
        parsedData.push(...parseInvocationTransaction(transaction))
      } else {
        parsedData.push(...(await parseContractTransaction(transaction, net)))
      }
    }
  }
  const sortedByBlockTime = (
    a: ParsedPendingTransaction,
    b: ParsedPendingTransaction,
  ) => b.blocktime - a.blocktime
  const sorted: Array<ParsedPendingTransaction> = parsedData.sort(
    sortedByBlockTime,
  )
  return sorted
}

const getPendingTransactions = async (): Promise<PendingTransactions> =>
  getStorage(STORAGE_KEY)

const setPendingTransactions = async (
  pendingTransactions: PendingTransactions,
): Promise<any> => setStorage(STORAGE_KEY, pendingTransactions)

export const pruneConfirmedOrStaleTransaction = async (
  address: string,
  txId: string,
) => {
  const storage = await getPendingTransactions()
  if (Array.isArray(storage[address])) {
    storage[address] = storage[address].filter(
      // use includes here to be indifferent to 0x prefix
      transaction => transaction.hash && !transaction.hash.includes(txId),
    )
  }
  await setPendingTransactions(storage)
}

export const fetchTransactionInfo = async (
  transactions: PendingTransactions = {},
  address: string,
  net: string,
) => {
  if (Array.isArray(transactions[address]) && transactions[address].length) {
    let url = await getNode(net)
    if (isEmpty(url)) {
      url = await getRPCEndpoint(net)
    }
    const client = Neon.create.rpcClient(url)
    const pendingTransactionInfo = []

    for (const transaction of transactions[address]) {
      if (transaction) {
        const result = await client
          .getRawTransaction(transaction.hash, 1)
          .catch(async e => {
            console.error(
              e,
              `Error performing getRawTransaction for txid: ${
                transaction.hash
              }`,
            )
            if (e.message === INVALID_TX_ERROR_MESSAGE) {
              await pruneConfirmedOrStaleTransaction(address, transaction.hash)
            }
          })

        if (result) {
          if (result.confirmations >= MINIMUM_CONFIRMATIONS) {
            await pruneConfirmedOrStaleTransaction(address, transaction.hash)
          } else {
            pendingTransactionInfo.push({ ...result, ...transaction })
          }
        }
      }
    }

    return parseTransactionInfo(pendingTransactionInfo, net)
  }
  return []
}

export const getPendingTransactionsFromStorage = createActions(
  ID,
  () => async () => {
    const pendingTransactions = await getPendingTransactions()
    return pendingTransactions
  },
)

export const addPendingTransaction = createActions(
  ID,
  ({ address, tx, net }) => async (): Promise<
    Array<ParsedPendingTransaction>,
  > => {
    const transactions = await getPendingTransactions()
    if (
      Array.isArray(transactions[address]) &&
      !transactions[address].find(pendingTx => pendingTx.hash === tx.hash)
    ) {
      transactions[address].push(tx)
    } else {
      transactions[address] = [tx]
    }
    await setPendingTransactions(transactions)
    return fetchTransactionInfo(transactions, address, net)
  },
)

export const getPendingTransactionInfo = createActions(
  ID,
  ({ address, net }) => async (): Promise<Array<Object>> => {
    const transactions = await getPendingTransactions()
    return fetchTransactionInfo(transactions, address, net)
  },
)