text:
/**
 * @fileoverview Library for creating scrollbars.
 * @author fraser@google.com (Neil Fraser)
 */
'use strict';

goog.provide('Blockly.Scrollbar');
goog.provide('Blockly.ScrollbarPair');

goog.require('goog.userAgent');

/**
 * Class for a pair of scrollbars.  Horizontal and vertical.
 * @param {!Blockly.Workspace} workspace Workspace to bind the scrollbars to.
 * @constructor
 */
Blockly.ScrollbarPair = function(workspace, hasScrollbars) {
  this.workspace_ = workspace;
  this.oldHostMetrics_ = null;
  this.hScroll = null;

  if (hasScrollbars === true) {
    hasScrollbars = 'both';
  }
  if (hasScrollbars && hasScrollbars !== 'vertical') {
    this.hScroll = new Blockly.Scrollbar(workspace, true, hasScrollbars === 'both');
  }
  this.vScroll = null;
  if (hasScrollbars && hasScrollbars !== 'horizontal') {
    this.vScroll = new Blockly.Scrollbar(workspace, false, hasScrollbars === 'both');
  }
  if (hasScrollbars === 'both') {
    this.corner_ = Blockly.createSvgElement('rect', {
      'class': 'blocklyScrollbarCorner',
      'height': Blockly.Scrollbar.scrollbarThickness,
      'width': Blockly.Scrollbar.scrollbarThickness
    }, null);
    Blockly.Scrollbar.insertAfter_(this.corner_, workspace.getBubbleCanvas());
  }
};

/**
 * Dispose of this pair of scrollbars.
 * Unlink from all DOM elements to prevent memory leaks.
 */
Blockly.ScrollbarPair.prototype.dispose = function() {
  Blockly.unbindEvent_(this.onResizeWrapper_);
  this.onResizeWrapper_ = null;
  goog.dom.removeNode(this.corner_);
  this.corner_ = null;
  this.workspace_ = null;
  this.oldHostMetrics_ = null;
  if (this.hscroll) {
    this.hScroll.dispose();
    this.hScroll = null;
  }
  if (this.vscroll) {
    this.vScroll.dispose();
    this.vScroll = null;
  }
};

/**
 * Recalculate both of the scrollbars' locations and lengths.
 * Also reposition the corner rectangle.
 */
Blockly.ScrollbarPair.prototype.resize = function() {
  // Look up the host metrics once, and use for both scrollbars.
  var hostMetrics = this.workspace_.getMetrics();
  if (!hostMetrics) {
    // Host element is likely not visible.
    return;
  }

  // Only change the scrollbars if there has been a change in metrics.
  var resizeH = false;
  var resizeV = false;
  if (!this.oldHostMetrics_ ||
      this.oldHostMetrics_.viewWidth != hostMetrics.viewWidth ||
      this.oldHostMetrics_.viewHeight != hostMetrics.viewHeight ||
      this.oldHostMetrics_.absoluteTop != hostMetrics.absoluteTop ||
      this.oldHostMetrics_.absoluteLeft != hostMetrics.absoluteLeft) {
    // The window has been resized or repositioned.
    resizeH = true;
    resizeV = true;
  } else {
    // Has the content been resized or moved?
    if (!this.oldHostMetrics_ ||
        this.oldHostMetrics_.contentWidth != hostMetrics.contentWidth ||
        this.oldHostMetrics_.viewLeft != hostMetrics.viewLeft ||
        this.oldHostMetrics_.contentLeft != hostMetrics.contentLeft) {
      resizeH = true;
    }
    if (!this.oldHostMetrics_ ||
        this.oldHostMetrics_.contentHeight != hostMetrics.contentHeight ||
        this.oldHostMetrics_.viewTop != hostMetrics.viewTop ||
        this.oldHostMetrics_.contentTop != hostMetrics.contentTop) {
      resizeV = true;
    }
  }
  if (resizeH && this.hScroll) {
    this.hScroll.resize(hostMetrics);
  }
  if (resizeV && this.vScroll) {
    this.vScroll.resize(hostMetrics);
  }

  // Reposition the corner square.
  if (this.corner_) {
    if (!this.oldHostMetrics_ ||
        this.oldHostMetrics_.viewWidth != hostMetrics.viewWidth ||
        this.oldHostMetrics_.absoluteLeft != hostMetrics.absoluteLeft) {
      this.corner_.setAttribute('x', this.vScroll.xCoordinate);
    }
    if (!this.oldHostMetrics_ ||
        this.oldHostMetrics_.viewHeight != hostMetrics.viewHeight ||
        this.oldHostMetrics_.absoluteTop != hostMetrics.absoluteTop) {
      this.corner_.setAttribute('y', this.hScroll.yCoordinate);
    }
  }

  // Cache the current metrics to potentially short-cut the next resize event.
  this.oldHostMetrics_ = hostMetrics;
};

/**
 * Set the sliders of both scrollbars to be at a certain position.
 * @param {number} x Horizontal scroll value.
 * @param {number} y Vertical scroll value.
 */
Blockly.ScrollbarPair.prototype.set = function(x, y) {
  /* HACK:
   Two scrollbars are about to have their sliders moved.  Moving a scrollbar
   will normally result in its onScroll function being called.  That function
   will update the contents.  At issue is what happens when two scrollbars are
   moved.  Calling onScroll twice may result in two rerenderings of the content
   and increase jerkiness during dragging.
   In the case of native scrollbars (currently used only by Firefox), onScroll
   is called as an event, which means two separate renderings of the content are
   performed.  However in the case of SVG scrollbars (currently used by all
   other browsers), onScroll is called as a function and the browser only
   rerenders the contents once at the end of the thread.
  */
  if (Blockly.Scrollbar === Blockly.ScrollbarNative) {
    // Native scrollbar mode.
    // Set both scrollbars and suppress their two separate onScroll events.
    if (this.hScroll) {
      this.hScroll.set(x, false);
    }
    if (this.vScroll) {
      this.vScroll.set(y, false);
    }
    // Redraw the surface once with the new settings for both scrollbars.
    var xyRatio = {};
    xyRatio.x = (this.hScroll.outerDiv_.scrollLeft /
                 this.hScroll.innerImg_.offsetWidth) || 0;
    xyRatio.y = (this.vScroll.outerDiv_.scrollTop /
                 this.vScroll.innerImg_.offsetHeight) || 0;
    this.workspace_.setMetrics(xyRatio);
  } else {
    // SVG scrollbars.
    // Set both scrollbars and allow each to call a separate onScroll execution.
    if (this.hScroll) {
      this.hScroll.set(x, true);
    }
    if (this.vScroll) {
      this.vScroll.set(y, true);
    }
  }
};

// --------------------------------------------------------------------

/**
 * Class for a pure SVG scrollbar.
 * This technique offers a scrollbar that is guaranteed to work, but may not
 * look or behave like the system's scrollbars.
 * @param {!Blockly.Workspace} workspace Workspace to bind the scrollbar to.
 * @param {boolean} horizontal True if horizontal, false if vertical.
 * @param {boolean} opt_pair True if the scrollbar is part of a horiz/vert pair.
 * @constructor
 */
Blockly.Scrollbar = function(workspace, horizontal, opt_pair) {
  this.workspace_ = workspace;
  this.pair_ = opt_pair || false;
  this.horizontal_ = horizontal;

  this.createDom_();

  if (horizontal) {
    this.svgBackground_.setAttribute('height',
        Blockly.Scrollbar.scrollbarThickness);
    this.svgKnob_.setAttribute('height',
        Blockly.Scrollbar.scrollbarThickness - 6);
    this.svgKnob_.setAttribute('y', 3);
  } else {
    this.svgBackground_.setAttribute('width',
        Blockly.Scrollbar.scrollbarThickness);
    this.svgKnob_.setAttribute('width',
        Blockly.Scrollbar.scrollbarThickness - 6);
    this.svgKnob_.setAttribute('x', 3);
  }
  var scrollbar = this;
  this.onMouseDownBarWrapper_ = Blockly.bindEvent_(this.svgBackground_,
      'mousedown', scrollbar, scrollbar.onMouseDownBar_);
  this.onMouseDownKnobWrapper_ = Blockly.bindEvent_(this.svgKnob_,
      'mousedown', scrollbar, scrollbar.onMouseDownKnob_);
};

/**
 * Width of vertical scrollbar or height of horizontal scrollbar.
 */
Blockly.Scrollbar.scrollbarThickness = 15;

/**
 * Dispose of this scrollbar.
 * Unlink from all DOM elements to prevent memory leaks.
 */
Blockly.Scrollbar.prototype.dispose = function() {
  this.onMouseUpKnob_();
  if (this.onResizeWrapper_) {
    Blockly.unbindEvent_(this.onResizeWrapper_);
    this.onResizeWrapper_ = null;
  }
  Blockly.unbindEvent_(this.onMouseDownBarWrapper_);
  this.onMouseDownBarWrapper_ = null;
  Blockly.unbindEvent_(this.onMouseDownKnobWrapper_);
  this.onMouseDownKnobWrapper_ = null;

  goog.dom.removeNode(this.svgGroup_);
  this.svgGroup_ = null;
  this.svgBackground_ = null;
  this.svgKnob_ = null;
  this.workspace_ = null;
};

/**
 * Recalculate the scrollbar's location and its length.
 * @param {Object=} opt_metrics A data structure of from the describing all the
 * required dimensions.  If not provided, it will be fetched from the host
 * object.
 */
Blockly.Scrollbar.prototype.resize = function(opt_metrics) {
  // Determine the location, height and width of the host element.
  var hostMetrics = opt_metrics;
  if (!hostMetrics) {
    hostMetrics = this.workspace_.getMetrics();
    if (!hostMetrics) {
      // Host element is likely not visible.
      return;
    }
  }
  /* hostMetrics is an object with the following properties.
   * .viewHeight: Height of the visible rectangle,
   * .viewWidth: Width of the visible rectangle,
   * .contentHeight: Height of the contents,
   * .contentWidth: Width of the content,
   * .viewTop: Offset of top edge of visible rectangle from parent,
   * .viewLeft: Offset of left edge of visible rectangle from parent,
   * .contentTop: Offset of the top-most content from the y=0 coordinate,
   * .contentLeft: Offset of the left-most content from the x=0 coordinate,
   * .absoluteTop: Top-edge of view.
   * .absoluteLeft: Left-edge of view.
   */
  if (this.horizontal_) {
    var outerLength = hostMetrics.viewWidth;
    if (this.pair_) {
      // Shorten the scrollbar to make room for the corner square.
      outerLength -= Blockly.Scrollbar.scrollbarThickness;
    } else {
      // Only show the scrollbar if needed.
      // Ideally this would also apply to scrollbar pairs, but that's a bigger
      // headache (due to interactions with the corner square).
      this.setVisible(outerLength < hostMetrics.contentWidth);
    }
    this.ratio_ = outerLength / hostMetrics.contentWidth;
    if (this.ratio_ === -Infinity || this.ratio_ === Infinity ||
        isNaN(this.ratio_)) {
      this.ratio_ = 0;
    }
    var innerLength = hostMetrics.viewWidth * this.ratio_;
    var innerOffset = (hostMetrics.viewLeft - hostMetrics.contentLeft) *
        this.ratio_;
    this.svgKnob_.setAttribute('width', Math.max(0, innerLength));
    this.xCoordinate = hostMetrics.absoluteLeft;
    if (this.pair_ && Blockly.RTL) {
      this.xCoordinate += hostMetrics.absoluteLeft +
          Blockly.Scrollbar.scrollbarThickness;
    }
    this.yCoordinate = hostMetrics.absoluteTop + hostMetrics.viewHeight -
        Blockly.Scrollbar.scrollbarThickness;
    this.svgGroup_.setAttribute('transform',
        'translate(' + this.xCoordinate + ', ' + this.yCoordinate + ')');
    this.svgBackground_.setAttribute('width', Math.max(0, outerLength));
    this.svgKnob_.setAttribute('x', this.constrainKnob_(innerOffset));
  } else {
    var outerLength = hostMetrics.viewHeight;
    if (this.pair_) {
      // Shorten the scrollbar to make room for the corner square.
      outerLength -= Blockly.Scrollbar.scrollbarThickness;
    } else {
      // Only show the scrollbar if needed.
      this.setVisible(outerLength < hostMetrics.contentHeight);
    }
    this.ratio_ = outerLength / hostMetrics.contentHeight;
    if (this.ratio_ === -Infinity || this.ratio_ === Infinity ||
        isNaN(this.ratio_)) {
      this.ratio_ = 0;
    }
    var innerLength = hostMetrics.viewHeight * this.ratio_;
    var innerOffset = (hostMetrics.viewTop - hostMetrics.contentTop) *
        this.ratio_;
    this.svgKnob_.setAttribute('height', Math.max(0, innerLength));
    this.xCoordinate = hostMetrics.absoluteLeft;
    if (!Blockly.RTL) {
      this.xCoordinate += hostMetrics.viewWidth -
          Blockly.Scrollbar.scrollbarThickness;
    }
    this.yCoordinate = hostMetrics.absoluteTop;
    this.svgGroup_.setAttribute('transform',
        'translate(' + this.xCoordinate + ', ' + this.yCoordinate + ')');
    this.svgBackground_.setAttribute('height', Math.max(0, outerLength));
    this.svgKnob_.setAttribute('y', this.constrainKnob_(innerOffset));
  }
  // Resizing may have caused some scrolling.
  this.onScroll_();
};

/**
 * Create all the DOM elements required for a scrollbar.
 * The resulting widget is not sized.
 * @private
 */
Blockly.Scrollbar.prototype.createDom_ = function() {
  /* Create the following DOM:
  <g>
    <rect class="blocklyScrollbarBackground" />
    <rect class="blocklyScrollbarKnob" rx="7" ry="7" />
  </g>
  */
  this.svgGroup_ = Blockly.createSvgElement('g', {}, null);
  this.svgBackground_ = Blockly.createSvgElement('rect',
      {'class': 'blocklyScrollbarBackground'}, this.svgGroup_);
  var radius = Math.floor((Blockly.Scrollbar.scrollbarThickness - 6) / 2);
  this.svgKnob_ = Blockly.createSvgElement('rect',
      {'class': 'blocklyScrollbarKnob', 'rx': radius, 'ry': radius},
      this.svgGroup_);
  Blockly.Scrollbar.insertAfter_(this.svgGroup_,
                                 this.workspace_.getBubbleCanvas());
};

/**
 * Is the scrollbar visible.  Non-paired scrollbars disappear when they aren't
 * needed.
 * @return {boolean} True if visible.
 */
Blockly.Scrollbar.prototype.isVisible = function() {
  return this.svgGroup_.getAttribute('display') != 'none';
};

/**
 * Set whether the scrollbar is visible.
 * Only applies to non-paired scrollbars.
 * @param {boolean} visible True if visible.
 */
Blockly.Scrollbar.prototype.setVisible = function(visible) {
  if (visible == this.isVisible()) {
    return;
  }
  // Ideally this would also apply to scrollbar pairs, but that's a bigger
  // headache (due to interactions with the corner square).
  if (this.pair_) {
    throw 'Unable to toggle visibility of paired scrollbars.';
  }
  if (visible) {
    this.svgGroup_.setAttribute('display', 'block');
  } else {
    // Hide the scrollbar.
    this.workspace_.setMetrics({x: 0, y: 0});
    this.svgGroup_.setAttribute('display', 'none');
  }
};

/**
 * Scroll by one pageful.
 * Called when scrollbar background is clicked.
 * @param {!Event} e Mouse down event.
 * @private
 */
Blockly.Scrollbar.prototype.onMouseDownBar_ = function(e) {
  this.onMouseUpKnob_();
  if (Blockly.isRightButton(e)) {
    // Right-click.
    // Scrollbars have no context menu.
    e.stopPropagation();
    return;
  }
  var mouseXY = Blockly.mouseToSvg(e);
  var mouseLocation = this.horizontal_ ? mouseXY.x : mouseXY.y;

  var knobXY = Blockly.getSvgXY_(this.svgKnob_);
  var knobStart = this.horizontal_ ? knobXY.x : knobXY.y;
  var knobLength = parseFloat(
      this.svgKnob_.getAttribute(this.horizontal_ ? 'width' : 'height'));
  var knobValue = parseFloat(
      this.svgKnob_.getAttribute(this.horizontal_ ? 'x' : 'y'));

  var pageLength = knobLength * 0.95;
  if (mouseLocation <= knobStart) {
    // Decrease the scrollbar's value by a page.
    knobValue -= pageLength;
  } else if (mouseLocation >= knobStart + knobLength) {
    // Increase the scrollbar's value by a page.
    knobValue += pageLength;
  }
  this.svgKnob_.setAttribute(this.horizontal_ ? 'x' : 'y',
                             this.constrainKnob_(knobValue));
  this.onScroll_();
  e.stopPropagation();
};

/**
 * Start a dragging operation.
 * Called when scrollbar knob is clicked.
 * @param {!Event} e Mouse down event.
 * @private
 */
Blockly.Scrollbar.prototype.onMouseDownKnob_ = function(e) {
  this.onMouseUpKnob_();
  if (Blockly.isRightButton(e)) {
    // Right-click.
    // Scrollbars have no context menu.
    e.stopPropagation();
    return;
  }
  // Look up the current translation and record it.
  this.startDragKnob = parseFloat(
      this.svgKnob_.getAttribute(this.horizontal_ ? 'x' : 'y'));
  // Record the current mouse position.
  this.startDragMouse = this.horizontal_ ? e.clientX : e.clientY;
  Blockly.Scrollbar.onMouseUpWrapper_ = Blockly.bindEvent_(document,
      'mouseup', this, this.onMouseUpKnob_);
  Blockly.Scrollbar.onMouseMoveWrapper_ = Blockly.bindEvent_(document,
      'mousemove', this, this.onMouseMoveKnob_);
  e.stopPropagation();
};

/**
 * Drag the scrollbar's knob.
 * @param {!Event} e Mouse up event.
 * @private
 */
Blockly.Scrollbar.prototype.onMouseMoveKnob_ = function(e) {
  var currentMouse = this.horizontal_ ? e.clientX : e.clientY;
  var mouseDelta = currentMouse - this.startDragMouse;
  var knobValue = this.startDragKnob + mouseDelta;
  // Position the bar.
  this.svgKnob_.setAttribute(this.horizontal_ ? 'x' : 'y',
                             this.constrainKnob_(knobValue));
  this.onScroll_();
};

/**
 * Stop binding to the global mouseup and mousemove events.
 * @private
 */
Blockly.Scrollbar.prototype.onMouseUpKnob_ = function() {
  Blockly.removeAllRanges();
  Blockly.hideChaff(true);
  if (Blockly.Scrollbar.onMouseUpWrapper_) {
    Blockly.unbindEvent_(Blockly.Scrollbar.onMouseUpWrapper_);
    Blockly.Scrollbar.onMouseUpWrapper_ = null;
  }
  if (Blockly.Scrollbar.onMouseMoveWrapper_) {
    Blockly.unbindEvent_(Blockly.Scrollbar.onMouseMoveWrapper_);
    Blockly.Scrollbar.onMouseMoveWrapper_ = null;
  }
};

/**
 * Constrain the knob's position within the minimum (0) and maximum
 * (length of scrollbar) values allowed for the scrollbar.
 * @param {number} value Value that is potentially out of bounds.
 * @return {number} Constrained value.
 * @private
 */
Blockly.Scrollbar.prototype.constrainKnob_ = function(value) {
  if (value <= 0 || isNaN(value)) {
    value = 0;
  } else {
    var axis = this.horizontal_ ? 'width' : 'height';
    var barLength = parseFloat(this.svgBackground_.getAttribute(axis));
    var knobLength = parseFloat(this.svgKnob_.getAttribute(axis));
    value = Math.min(value, barLength - knobLength);
  }
  return value;
};

/**
 * Called when scrollbar is moved.
 * @private
 */
Blockly.Scrollbar.prototype.onScroll_ = function() {
  var knobValue = parseFloat(
      this.svgKnob_.getAttribute(this.horizontal_ ? 'x' : 'y'));
  var barLength = parseFloat(
      this.svgBackground_.getAttribute(this.horizontal_ ? 'width' : 'height'));
  var ratio = knobValue / barLength;
  if (isNaN(ratio)) {
    ratio = 0;
  }
  var xyRatio = {};
  if (this.horizontal_) {
    xyRatio.x = ratio;
  } else {
    xyRatio.y = ratio;
  }
  this.workspace_.setMetrics(xyRatio);
};

/**
 * Set the scrollbar slider's position.
 * @param {number} value The distance from the top/left end of the bar.
 * @param {boolean} fireEvents True if onScroll events should be fired.
 */
Blockly.Scrollbar.prototype.set = function(value, fireEvents) {
  // Move the scrollbar slider.
  this.svgKnob_.setAttribute(this.horizontal_ ? 'x' : 'y', value * this.ratio_);

  if (fireEvents) {
    this.onScroll_();
  }
};

/**
 * Insert a node after a reference node.
 * Contrast with node.insertBefore function.
 * @param {!Element} newNode New element to insert.
 * @param {!Element} refNode Existing element to precede new node.
 * @private
 */
Blockly.Scrollbar.insertAfter_ = function(newNode, refNode) {
  var siblingNode = refNode.nextSibling;
  var parentNode = refNode.parentNode;
  if (!parentNode) {
    throw 'Reference node has no parent.';
  }
  if (siblingNode) {
    parentNode.insertBefore(newNode, siblingNode);
  } else {
    parentNode.appendChild(newNode);
  }
};


text:
package com.coolweather.smtq.setting;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.ColorInt;
import android.support.annotation.NonNull;

import com.afollestad.materialdialogs.color.ColorChooserDialog;
import com.coolweather.smtq.R;
import com.coolweather.smtq.base.BaseActivity;
import com.coolweather.smtq.event.ThemeChangedEvent;
import com.coolweather.smtq.util.SettingsUtil;
import com.coolweather.smtq.util.ThemeUtil;

import org.greenrobot.eventbus.EventBus;

public class SettingActivity extends BaseActivity implements ColorChooserDialog.ColorCallback {

    @Override
    protected int getLayoutId() {
        return R.layout.activity_setting_2;
    }

    @Override
    protected int getMenuId() {
        return 0;
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setDisplayHomeAsUpEnabled(true);
    }

    @Override
    protected void loadData() {
        getFragmentManager().beginTransaction().replace(R.id.contentLayout, new SettingFragment()).commit();
    }

    @Override
    public void onColorSelection(@NonNull ColorChooserDialog dialog, @ColorInt int selectedColor) {
        if (selectedColor == ThemeUtil.getThemeColor(this, R.attr.colorPrimary))
            return;
        toolbar.setBackgroundColor(selectedColor);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(selectedColor);
        }
        if (selectedColor == getResources().getColor(R.color.lapis_blue)) {
            setTheme(R.style.LapisBlueTheme);
            SettingsUtil.setTheme(0);
        } else if (selectedColor == getResources().getColor(R.color.pale_dogwood)) {
            setTheme(R.style.PaleDogwoodTheme);
            SettingsUtil.setTheme(1);
        } else if (selectedColor == getResources().getColor(R.color.greenery)) {
            setTheme(R.style.GreeneryTheme);
            SettingsUtil.setTheme(2);
        } else if (selectedColor == getResources().getColor(R.color.primrose_yellow)) {
            setTheme(R.style.PrimroseYellowTheme);
            SettingsUtil.setTheme(3);
        } else if (selectedColor == getResources().getColor(R.color.flame)) {
            setTheme(R.style.FlameTheme);
            SettingsUtil.setTheme(4);
        } else if (selectedColor == getResources().getColor(R.color.island_paradise)) {
            setTheme(R.style.IslandParadiseTheme);
            SettingsUtil.setTheme(5);
        } else if (selectedColor == getResources().getColor(R.color.kale)) {
            setTheme(R.style.KaleTheme);
            SettingsUtil.setTheme(6);
        } else if (selectedColor == getResources().getColor(R.color.pink_yarrow)) {
            setTheme(R.style.PinkYarrowTheme);
            SettingsUtil.setTheme(7);
        } else if (selectedColor == getResources().getColor(R.color.niagara)) {
            setTheme(R.style.NiagaraTheme);
            SettingsUtil.setTheme(8);
        }
        getFragmentManager().beginTransaction().replace(R.id.contentLayout, new SettingFragment()).commit();
        EventBus.getDefault().post(new ThemeChangedEvent(selectedColor));
    }
}

redpajama_set_name: RedPajamaGithub


text:
function result = set_concat(varargin)
% Concatenate continuous signals across time.
% Result = set_joinepos(Set1, Set2, ...)
%
% In:
%   SetK   : The k'th data set to concatenate.
%
% Out:
%   Result : A new data set that is the concatenation of all input sets. The following changes are made:
%            * .data and all other time-series fields are concatenated across time (2nd dimension)
%            * .event is joined and .latency fields are updated appropriately
%            * .xmax/.pnts are updated
%
% Notes:
%   This function returns a new data set with meta-data set to that of the first input set, and the
%   time series field sjoined across all sets. No checks for meta-data consistency are done. There
%   is a heavy-duty function for merging inconsistent sets called set_merge, which can merge cats
%   and dogs. This function does not attempt to keep miscellaneous EEGLAB meta-data consistent,
%   including: setname,filename,filepath,subject,group,condition,session,comments,urevent,reject,stats,history,etc
%
% Examples:
%   % concatenate data sets eegA, eegB and eegC across time
%   eeg = set_concat(eegA,eegB,eegC)
%
% See also:
%   set_joinepos, set_merge
%
%                                Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
%                                2010-03-31

% set_joinepos_version<1.0> -- for the cache

if ~exp_beginfun('editing') return; end

declare_properties('name','Concatenate','independent_channels',true,'independent_trials',false);

if ~isempty(varargin)
    if any(cellfun(@(x)isfield(x,'epoch') && ~isempty(x.epoch),varargin))
        error('Only continuous data can be concatenated with set_concat -- use set_joinepos for epoched data.'); end
    result = varargin{1};
    if length(varargin) > 1
        % concatenate time series fields
        for field = utl_timeseries_fields(result)
            data = cellfun(@(x)x.(field{1}),varargin,'UniformOutput',false);
            result.(field{1}) = cat(2,data{:});
            if isempty(result.(field{1}))
                result.(field{1}) = []; end
        end
        % count events, epochs and samples in each set
        event_count = cellfun(@(x)length(x.event),varargin);
        sample_count = cellfun(@(x)x.pnts,varargin);
        % concatenate .event and .epoch fields
        event = cellfun(@(x)x.event,varargin,'UniformOutput',false); result.event = [event{:}];
        % shift event latencies based on cumulative sample counts
        if ~isempty(result.event)
            [result.event.latency] = arraydeal([result.event.latency]+replicate(cumsum(sample_count)-sample_count,event_count)); end
        % update misc fields
        [result.nbchan,result.pnts,result.trials,extra_dims] = size(result.data); %#ok<NASGU>
        result.xmax = result.xmin + (result.pnts-1)/result.srate;
    end
else
    result = eeg_emptyset;
end

exp_endfun;

function result = replicate(values,counts)
% Replicate each element Values(k) by Count(k) times.
result = zeros(1,sum(counts));
k = 0;
for p=find(counts)
    result(k+(1:counts(p))) = values(p);
    k = k+counts(p);
end


text:
<!doctype html>

    <meta charset="utf-8">

<title>Empirically fit point spread functions - My Homepage</title>

<meta name="description" content="For deconvolving z-stacks of DIC images.">

<meta name="author" content="Ben Collyer">

<meta property="og:locale" content="en">
<meta property="og:site_name" content="My Homepage">
<meta property="og:title" content="Empirically fit point spread functions">

  <link rel="canonical" href="http://localhost:4000/psf/">
  <meta property="og:url" content="http://localhost:4000/psf/">

  <meta property="og:description" content="For deconvolving z-stacks of DIC images.">

<link href="http://localhost:4000/feed.xml" type="application/atom+xml" rel="alternate" title="My Homepage Feed">

<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="http://localhost:4000/assets/css/main.css">

<meta http-equiv="cleartype" content="on">

        My Homepage

About

DIC microscopy

Machine learning

        <button>

</button>

          Empirically fit point spread functions

For deconvolving z-stacks of DIC images.

Ben Collyer

        Post-doctoral research fellow at the Zeeman Institute

    <button class="btn btn--inverse">Follow</button>

           University of Warwick

            <meta itemprop="email" content="benjamin.collyer@gmail.com" />
             Email

             GitHub

  <input id="ac-toc" name="accordion-toc" type="checkbox" />
  Toggle Menu

          DIC microscopy

Introduction

Synthetic DIC

Basic Integration

Detecting lengthscale

Sine-series method

PSF fit

    <meta itemprop="headline" content="Empirically fit point spread functions">
    <meta itemprop="description" content="For deconvolving z-stacks of DIC images.">

    <meta itemprop="dateModified" content="November 03, 2016">

 On This Page

If  is the 3D optical path length (OPL) distribution, then we can model the formation of the DIC image  as a convolution of the OPL with the microscope's 3D point-spread function (PSF) :

$$\varphi * h = I.$$

From this model it is clear that if  is a Dirac-delta function centred at the origin then:

$$\delta * h = h = I_h, $$

so  can be obtained by imaging an object that is approximately a delta function. The closest physical object to a delta function that we can conceivably image is a micro-bead. Below is a montage created from a z-stack of such a bead.

The above image slices are noisy and contain certain biases - for the best results in a deconvolution routine we should attempt remove them. The way we do this is to fit a parametric PSF model to the image. I've created a simple least-squares algorithm that fits a Gaussian DIC PSF (with 9 parameters) to the bead data. The output to the fit of the above data is

 Updated: <time datetime="2016-11-03">November 03, 2016</time>

Follow:

 GitHub

 Feed

© 2017 Ben Collyer. Powered by Jekyll & Minimal Mistakes.


text:
import Backbone from 'backbone';
import { bindAll, isArray, isUndefined, debounce } from 'underscore';
import { camelCase } from 'utils/mixins';
import { includes, each } from 'underscore';

const clearProp = 'data-clear-style';

export default Backbone.View.extend({
  template(model) {
    const pfx = this.pfx;
    return `

        ${this.templateLabel(model)}

        ${this.templateInput(model)}

    `;
  },

  templateLabel(model) {
    const { pfx, em } = this;
    const { parent } = model;
    const { icon = '', info = '', id, name } = model.attributes;
    const label = (em && em.t(`styleManager.properties.${id}`)) || name;

    return `

        ${label}

      ${!parent ? `<b class="${pfx}clear" ${clearProp}>⨯</b>` : ''}
    `;
  },

  templateInput(model) {
    return `

        <input placeholder="${model.getDefaultValue()}"/>

    `;
  },

  events: {
    change: 'inputValueChanged',
    [`click [${clearProp}]`]: 'clear'
  },

  initialize(o = {}) {
    bindAll(this, 'targetUpdated');
    this.config = o.config || {};
    const em = this.config.em;
    this.em = em;
    this.pfx = this.config.stylePrefix || '';
    this.ppfx = this.config.pStylePrefix || '';
    this.target = o.target || {};
    this.propTarget = o.propTarget || {};
    this.onChange = o.onChange;
    this.onInputRender = o.onInputRender || {};
    this.customValue = o.customValue || {};
    const model = this.model;
    this.property = model.get('property');
    this.input = null;
    const pfx = this.pfx;
    this.inputHolderId = '#' + pfx + 'input-holder';
    this.sector = model.collection && model.collection.sector;
    model.view = this;

    if (!model.get('value')) {
      model.set('value', model.getDefaultValue());
    }

    em && em.on(`update:component:style:${this.property}`, this.targetUpdated);
    //em && em.on(`styleable:change:${this.property}`, this.targetUpdated);

    // Listening to changes of properties in this.requires, so that styleable
    // changes based on other properties are propagated
    const requires = model.get('requires');
    requires &&
      Object.keys(requires).forEach(property => {
        em && em.on(`component:styleUpdate:${property}`, this.targetUpdated);
      });

    this.listenTo(
      this.propTarget,
      'update styleManager:update',
      this.targetUpdated
    );
    this.listenTo(model, 'destroy remove', this.remove);
    this.listenTo(model, 'change:value', this.modelValueChanged);
    this.listenTo(model, 'targetUpdated', this.targetUpdated);
    this.listenTo(model, 'change:visible', this.updateVisibility);
    this.listenTo(model, 'change:status', this.updateStatus);
    this.listenTo(
      model,
      'change:name change:className change:full',
      this.render
    );

    const init = this.init && this.init.bind(this);
    init && init();
  },

  /**
   * Triggers when the status changes. The status indicates if the value of
   * the proprerty is changed or inherited
   * @private
   */
  updateStatus() {
    const { model } = this;
    const status = model.get('status');
    const parent = model.parent;
    const pfx = this.pfx;
    const ppfx = this.ppfx;
    const config = this.config;
    const updatedCls = `${ppfx}four-color`;
    const computedCls = `${ppfx}color-warn`;
    const labelEl = this.$el.children(`.${pfx}label`);
    const clearStyleEl = this.getClearEl();
    const clearStyle = clearStyleEl ? clearStyleEl.style : {};
    labelEl.removeClass(`${updatedCls} ${computedCls}`);
    clearStyle.display = 'none';

    switch (status) {
      case 'updated':
        !parent && labelEl.addClass(updatedCls);

        if (config.clearProperties) {
          clearStyle.display = 'inline';
        }
        break;
      case 'computed':
        labelEl.addClass(computedCls);
        break;
    }
  },

  /**
   * Clear the property from the target
   */
  clear(ev) {
    ev && ev.stopPropagation();
    this.model.clearValue();
    // Skip one stack with setTimeout to avoid inconsistencies (eg. visible on padding composite clear)
    setTimeout(() => this.targetUpdated());
  },

  /**
   * Get clear element
   * @return {HTMLElement}
   */
  getClearEl() {
    if (!this.clearEl) {
      this.clearEl = this.el.querySelector(`[${clearProp}]`);
    }

    return this.clearEl;
  },

  /**
   * Returns selected target which should have 'style' property
   * @return {Model|null}
   */
  getTarget() {
    return this.getTargetModel();
  },

  getTargets() {
    const { targets } = this.propTarget;
    return targets || [this.getTarget()];
  },

  /**
   * Returns Styleable model
   * @return {Model|null}
   */
  getTargetModel() {
    return this.propTarget && this.propTarget.model;
  },

  /**
   * Returns helper Styleable model
   * @return {Model|null}
   */
  getHelperModel() {
    return this.propTarget && this.propTarget.helper;
  },

  /**
   * Triggers when the value of element input/s is changed, so have to update
   * the value of the model which will propogate those changes to the target
   */
  inputValueChanged(ev) {
    ev && ev.stopPropagation();
    this.model.setValueFromInput(this.getInputValue());
    this.elementUpdated();
  },

  /**
   * Fired when the element of the property is updated
   */
  elementUpdated() {
    this.setStatus('updated');
  },

  setStatus(value) {
    this.model.set('status', value);
    const parent = this.model.parent;
    parent && value == 'updated' && parent.set('status', value);
  },

  emitUpdateTarget: debounce(function() {
    const em = this.config.em;
    em && em.trigger('styleManager:update:target', this.getTarget());
  }),

  _getTargetData() {
    const { model, config } = this;
    const targetValue = this.getTargetValue({ ignoreDefault: 1 });
    const defaultValue = model.getDefaultValue();
    const computedValue = this.getComputedValue();
    let value = '';
    let status = '';

    if (targetValue) {
      value = targetValue;

      if (config.highlightChanged) {
        status = 'updated';
      }
    } else if (
      computedValue &&
      config.showComputed &&
      computedValue != defaultValue
    ) {
      value = computedValue;

      if (config.highlightComputed) {
        status = 'computed';
      }
    } else {
      value = defaultValue;
      status = '';
    }

    return {
      value,
      status,
      targetValue,
      defaultValue,
      computedValue
    };
  },

  /**
   * Fired when the target is changed
   * */
  targetUpdated(mod, val, opts = {}) {
    this.emitUpdateTarget();

    if (!this.checkVisibility()) {
      return;
    }

    const config = this.config;
    const em = config.em;
    const { model } = this;
    const property = model.get('property');
    const { status, value, ...targetData } = this._getTargetData();
    const data = {
      status,
      value,
      ...targetData
    };

    this.setStatus(status);
    model.setValue(value, 0, { fromTarget: 1, ...opts });

    if (em) {
      em.trigger('styleManager:change', this, property, value, data);
      em.trigger(`styleManager:change:${property}`, this, value, data);
      this._emitUpdate(data);
    }

    return data;
  },

  _emitUpdate(addData = {}) {
    const { em, model } = this;
    if (!em) return;
    const property = model.get('property');
    const data = { ...this._getEventData(), ...addData };
    const { id } = data;

    em.trigger('style:update', data);
    em.trigger(`style:update:${property}`, data);
    property !== id && em.trigger(`style:update:${id}`, data);
  },

  _getEventData() {
    const { model } = this;

    return {
      propertyView: this,
      targets: this.getTargets(),
      value: model.getFullValue(),
      property: model,
      id: model.get('id'),
      name: model.get('property')
    };
  },

  checkVisibility() {
    var result = 1;

    // Check if need to hide the property
    if (this.config.hideNotStylable) {
      if (!this.isTargetStylable() || !this.isComponentStylable()) {
        this.hide();
        result = 0;
      } else {
        this.show();
      }
      // Sector is not passed to Composite and Stack types
      if (this.sector) {
        this.sector.trigger('updateVisibility');
      }
    }

    return result;
  },

  /**
   * Get the value of this property from the target (eg, Component, CSSRule)
   * @param {Object} [opts] Options
   * @param {Boolean} [options.fetchFromFunction]
   * @param {Boolean} [options.ignoreDefault]
   * @return string
   * @private
   */
  getTargetValue(opts = {}) {
    let result;
    const { model } = this;
    const target = this.getTargetModel();
    const customFetchValue = this.customValue;

    if (!target) {
      return result;
    }

    result = target.getStyle()[model.get('property')];

    if (!result && !opts.ignoreDefault) {
      result = model.getDefaultValue();
    }

    if (typeof customFetchValue == 'function' && !opts.ignoreCustomValue) {
      let index = model.collection.indexOf(model);
      let customValue = customFetchValue(this, index, result);

      if (customValue) {
        result = customValue;
      }
    }

    return result;
  },

  /**
   * Returns computed value
   * @return {String}
   * @private
   */
  getComputedValue() {
    const target = this.propTarget;
    const computed = target.computed || {};
    const computedDef = target.computedDefault || {};
    const avoid = this.config.avoidComputed || [];
    const property = this.model.get('property');
    const notToSkip = avoid.indexOf(property) < 0;
    const value = computed[property];
    const valueDef = computedDef[camelCase(property)];
    return (computed && notToSkip && valueDef !== value && value) || '';
  },

  /**
   * Returns value from input
   * @return {string}
   */
  getInputValue() {
    const input = this.getInputEl();
    return input ? input.value : '';
  },

  /**
   * Triggers when the `value` of the model changes, so the target and
   * the input element should be updated
   * @param {Object} e  Event
   * @param {Mixed} val  Value
   * @param {Object} opt  Options
   * */
  modelValueChanged(e, val, opt = {}) {
    const model = this.model;
    const value = model.getFullValue();

    // Avoid element update if the change comes from it
    if (!opt.fromInput) {
      this.setValue(value);
    }

    // Avoid target update if the changes comes from it
    if (!opt.fromTarget) {
      this.getTargets().forEach(target => this.__updateTarget(target, opt));
    }
  },

  __updateTarget(target, opt = {}) {
    const { model } = this;
    const { em } = this.config;
    const prop = model.get('property');
    const value = model.getFullValue();
    const onChange = this.onChange;

    // Check if component is allowed to be styled
    if (
      !target ||
      !this.isTargetStylable(target) ||
      !this.isComponentStylable()
    ) {
      return;
    }

    // Avoid target update if the changes comes from it
    if (!opt.fromTarget) {
      // The onChange is used by Composite/Stack properties, so I'd avoid sending
      // it back if the change comes from one of those
      if (onChange && !opt.fromParent) {
        onChange(target, this, opt);
      } else {
        this.updateTargetStyle(value, null, { ...opt, target });
      }
    }

    // TODO: use target if componentFirst
    const component = em && em.getSelected();

    if (em && component) {
      !opt.noEmit && em.trigger('component:update', component);
      em.trigger('component:styleUpdate', component, prop);
      em.trigger(`component:styleUpdate:${prop}`, component);
    }

    this._emitUpdate();
  },

  /**
   * Update target style
   * @param  {string} value
   * @param  {string} name
   * @param  {Object} opts
   */
  updateTargetStyle(value, name = '', opts = {}) {
    const property = name || this.model.get('property');
    const target = opts.target || this.getTarget();
    const style = target.getStyle();

    if (value) {
      style[property] = value;
    } else {
      delete style[property];
    }

    // Forces to trigger the change (for UndoManager)
    if (opts.avoidStore) {
      style.__ = 1;
    } else {
      delete style.__;
    }

    target.setStyle(style, opts);

    // Helper is used by `states` like ':hover' to show its preview
    const helper = this.getHelperModel();
    helper && helper.setStyle(style, opts);
  },

  /**
   * Check if target is stylable with this property
   * The target could be the Component as the CSS Rule
   * @return {Boolean}
   */
  isTargetStylable(target) {
    const trg = target || this.getTarget();
    const model = this.model;
    const id = model.get('id');
    const property = model.get('property');
    const toRequire = model.get('toRequire');
    const unstylable = trg.get('unstylable');
    const stylableReq = trg.get('stylable-require');
    const requires = model.get('requires');
    const requiresParent = model.get('requiresParent');
    const sectors = this.sector ? this.sector.collection : null;
    const selected = this.em ? this.em.getSelected() : null;
    let stylable = trg.get('stylable');

    // Stylable could also be an array indicating with which property
    // the target could be styled
    if (isArray(stylable)) {
      stylable = stylable.indexOf(property) >= 0;
    }

    // Check if the property was signed as unstylable
    if (isArray(unstylable)) {
      stylable = unstylable.indexOf(property) < 0;
    }

    // Check if the property is available only if requested
    if (toRequire) {
      stylable =
        !target ||
        (stylableReq &&
          (stylableReq.indexOf(id) >= 0 || stylableReq.indexOf(property) >= 0));
    }

    // Check if the property is available based on other property's values
    if (sectors && requires) {
      const properties = Object.keys(requires);
      sectors.each(sector => {
        sector.get('properties').each(model => {
          if (includes(properties, model.id)) {
            const values = requires[model.id];
            stylable = stylable && includes(values, model.get('value'));
          }
        });
      });
    }

    // Check if the property is available based on parent's property values
    if (requiresParent) {
      const parent = selected && selected.parent();
      const parentEl = parent && parent.getEl();
      if (parentEl) {
        const styles = window.getComputedStyle(parentEl);
        each(requiresParent, (values, property) => {
          stylable =
            stylable && styles[property] && includes(values, styles[property]);
        });
      } else {
        stylable = false;
      }
    }

    return stylable;
  },

  /**
   * Check if the selected component is stylable with this property
   * The target could be the Component as the CSS Rule
   * @return {Boolean}
   */
  isComponentStylable() {
    const em = this.em;
    const component = em && em.getSelected();

    if (!component) {
      return true;
    }

    return this.isTargetStylable(component);
  },

  /**
   * Passed a raw value you have to update the input element, generally
   * is the value fetched from targets, so you can receive values with
   * functions, units, etc. (eg. `rotateY(45deg)`)
   * get also
   * @param {string} value
   * @private
   */
  setRawValue(value) {
    this.setValue(this.model.parseValue(value));
  },

  /**
   * Update the element input.
   * Usually the value is a result of `model.getFullValue()`
   * @param {String} value The value from the model
   * */
  setValue(value) {
    const model = this.model;
    let val = isUndefined(value) ? model.getDefaultValue() : value;
    const input = this.getInputEl();
    input && (input.value = val);
  },

  getInputEl() {
    if (!this.input) {
      this.input = this.el.querySelector('input');
    }

    return this.input;
  },

  updateVisibility() {
    this.el.style.display = this.model.get('visible') ? 'block' : 'none';
  },

  show() {
    this.model.set('visible', 1);
  },

  hide() {
    this.model.set('visible', 0);
  },

  /**
   * Clean input
   * */
  cleanValue() {
    this.setValue('');
  },

  clearCached() {
    this.clearEl = null;
    this.input = null;
    this.$input = null;
  },

  render() {
    this.clearCached();
    const pfx = this.pfx;
    const model = this.model;
    const el = this.el;
    const property = model.get('property');
    const full = model.get('full');
    const cls = model.get('className') || '';
    const className = `${pfx}property`;
    el.innerHTML = this.template(model);
    el.className = `${className} ${pfx}${model.get(
      'type'
    )} ${className}__${property} ${cls}`.trim();
    el.className += full ? ` ${className}--full` : '';
    this.updateStatus();

    const onRender = this.onRender && this.onRender.bind(this);
    onRender && onRender();
    this.setValue(model.get('value'), { fromTarget: 1 });
  }
});


text:
<?php
/*
Plugin Name: Floating Publish Button
Plugin URI: http://wordpress.org/plugins/floating-publish-button/
Description: A WordPress plugin that alters the position and behavior of the Publish button, making it stick to the top of the page when scrolling down the page.
Version: 1.0.4
Author: Do Ha Son
Author URI: http://www.dollaa.com/
License: GPLv2 or later
*/
add_action( 'admin_enqueue_scripts', 'fpb_enqueue_scripts', 20 );
add_action( 'personal_options', 'fpb_options' );
add_action( 'personal_options_update', 'fpb_options_update' );
add_action( 'edit_user_profile_update', 'fpb_options_update' );

function fpb_options_update( $user_id ) {

	if ( !current_user_can( 'edit_user', $user_id ) )
		return;

	update_user_meta( $user_id, 'floating_publish_button', intval( isset( $_POST[ 'floating_publish_button' ] ) ) );

}

function fpb_enqueue_scripts() {

	$plugin = get_plugin_data( __FILE__, false, false );

	// float menu, unless explicitly turned off in user profile
	if ( get_user_meta( get_current_user_id(), 'floating_publish_button', true ) !== '0' ) {
		wp_register_script( 'floating-publish-button-hstick', plugin_dir_url( __FILE__ ) . 'jquery.hcsticky-min.js', array( 'jquery' ), $plugin[ 'Version' ] );
		wp_register_script( 'floating-publish-button', plugin_dir_url( __FILE__ ) . 'floating-publish-button.js', array( 'jquery' ), $plugin[ 'Version' ] );
		wp_enqueue_script( 'floating-publish-button-hstick' );
		wp_enqueue_script( 'floating-publish-button' );
	}

}

function fpb_options( $profileuser ) {
?>

		<?php _e( 'Publish/Update button', 'floating-publish-button' ); ?>

			<fieldset>
				<legend class="screen-reader-text"><?php _e( 'Update button', 'floating-publish-button' ); ?></legend>

					<input type="checkbox" name="floating_publish_button" id="floating_publish_button" value="1"<?php checked( get_user_meta( $profileuser->ID, 'floating_publish_button', true ) !== '0' ); ?> />
					<?php _e( 'Float the Update button', 'floating-publish-button' ); ?>

			</fieldset>

<?php
}


text:
#pragma once

#include <QtWidgets>

/**
 * A static class to help manage stylesheets for soccer
 */
class StyleSheetManager {
private:
    /**
     * Sets the style sheet to the qt style file specified by path
     *
     * @param window the QMainWindow to apply the style to
     * @param path The path to the style file to apply
     * Should be relative to the run directory.
     *
     * @see changeStyleSheet()
     */
    static void setStyleSheet(QMainWindow* window, const QString& path);

public:
    /**
     * Changes the style sheet to the style specified by name
     *
     * @param window the window to apply the style to
     * @param name the name of the style to apply. We must know about this style
     * To add new styles, add them to the hashmap in StyleSheetManager
     */
    static void changeStyleSheet(QMainWindow* window, const QString& name);
};


text:
int main()
{
    std::string what_arg("test message");
    std::system_error se(static_cast<int>(std::errc::not_a_directory),
                         std::generic_category(), what_arg);
    assert(se.code() == std::make_error_code(std::errc::not_a_directory));
    std::string what_message(se.what());
    assert(what_message.find(what_arg) != std::string::npos);
    assert(what_message.find("Not a directory") != std::string::npos);
}


text:
package com.inja.barberside.adapters;

/**
 * Created by sinasix on 10/12/15.
 */
import android.content.Context;
import android.database.Cursor;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.inja.barberside.R;

/**
 * Created by skyfishjy on 10/31/14.
 */
public class MyListCursorAdapter extends CursorRecyclerViewAdapter<MyListCursorAdapter.ViewHolder>{

    public MyListCursorAdapter(Context context,Cursor cursor){
        super(context,cursor);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.customer_view, parent, false);
        ViewHolder vh = new ViewHolder(itemView);
        return vh;
    }

    @Override
    public void onBindViewHolder(ViewHolder viewHolder, Cursor cursor) {
        //MyListItem myListItem = MyListItem.fromCursor(cursor);
        //viewHolder.mTextView.setText(myListItem.getName());
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView mTextView;
        public ViewHolder(View view) {
            super(view);
            //mTextView = view.findViewById(R.id.text);
        }
    }
}


text:
/**
 * @module ol/layer/Image
 */
import {inherits} from '../util.js';
import LayerType from '../LayerType.js';
import Layer from '../layer/Layer.js';

/**
 * @typedef {Object} Options
 * @property {number} [opacity=1] Opacity (0, 1).
 * @property {boolean} [visible=true] Visibility.
 * @property {module:ol/extent~Extent} [extent] The bounding extent for layer rendering.  The layer will not be
 * rendered outside of this extent.
 * @property {number} [zIndex=0] The z-index for layer rendering.  At rendering time, the layers
 * will be ordered, first by Z-index and then by position.
 * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be
 * visible.
 * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will
 * be visible.
 * @property {module:ol/PluggableMap} [map] Sets the layer as overlay on a map. The map will not manage
 * this layer in its layers collection, and the layer will be rendered on top. This is useful for
 * temporary layers. The standard way to add a layer to a map and have it managed by the map is to
 * use {@link module:ol/Map#addLayer}.
 * @property {module:ol/source/Image} [source] Source for this layer.
 */

/**
 * @classdesc
 * Server-rendered images that are available for arbitrary extents and
 * resolutions.
 * Note that any property set in the options is set as a {@link module:ol/Object~BaseObject}
 * property on the layer object; for example, setting `title: 'My Title'` in the
 * options means that `title` is observable, and has get/set accessors.
 *
 * @constructor
 * @extends {module:ol/layer/Layer}
 * @fires module:ol/render/Event~RenderEvent
 * @param {module:ol/layer/Image~Options=} opt_options Layer options.
 * @api
 */
const ImageLayer = function(opt_options) {
  const options = opt_options ? opt_options : {};
  Layer.call(this,  /** @type {module:ol/layer/Layer~Options} */ (options));

  /**
   * The layer type.
   * @protected
   * @type {module:ol/LayerType}
   */
  this.type = LayerType.IMAGE;

};

inherits(ImageLayer, Layer);

/**
 * Return the associated {@link module:ol/source/Image source} of the image layer.
 * @function
 * @return {module:ol/source/Image} Source.
 * @api
 */
ImageLayer.prototype.getSource;
export default ImageLayer;


text:
package org.springframework.boot.context.event;

import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

/**
 * Event published as when a {@link SpringApplication} is starting up and the
 * {@link ApplicationContext} is fully prepared but not refreshed. The bean definitions
 * will be loaded and the {@link Environment} is ready for use at this stage.
 *
 * @author Dave Syer
 */
@SuppressWarnings("serial")
public class ApplicationPreparedEvent extends SpringApplicationEvent {

	private final ConfigurableApplicationContext context;

	/**
	 * Create a new {@link ApplicationPreparedEvent} instance.
	 * @param application the current application
	 * @param args the argumemts the application is running with
	 * @param context the ApplicationContext about to be refreshed
	 */
	public ApplicationPreparedEvent(SpringApplication application, String[] args,
			ConfigurableApplicationContext context) {
		super(application, args);
		this.context = context;
	}

	/**
	 * Return the application context.
	 * @return the context
	 */
	public ConfigurableApplicationContext getApplicationContext() {
		return this.context;
	}

}


text:
function Verb-Noun {
    <#
        .SYNOPSIS
        Summary

        .DESCRIPTION
        Detailed description

        .PARAMETER Name
        Specifies the name of a thing

        .PARAMETER OptionalParam
        Specifies the name of an optional thing

        .INPUTS
        System.String

        .OUTPUTS
        System.Management.Automation.PSCustomObject

        .EXAMPLE
        Verb-Noun

        Returns all things.

        .EXAMPLE
        Verb-Noun -Name 'Thing01'

        Returns a single thing.

        .EXAMPLE
        Verb-Noun -Name 'Thing01', 'Thing02'

        Returns multiple things.

        .NOTES
        Author: Adam Rush
        GitHub: adamrushuk
        Twitter: @adamrushuk
    #>
    [CmdletBinding()]
    [OutputType('System.Management.Automation.PSCustomObject')]
    param (
        [Parameter(Mandatory = $false, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [ValidateNotNullOrEmpty()]
        [string[]]
        $Name,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [PSCustomObject]
        $OptionalParam
    )

    Begin {}

    Process {

        try {

            if ($PSBoundParameters.ContainsKey('OptionalParam')){
                # Do something
            }

            foreach ($Item in $Collection) {

                # Do something
                $Object = $Item | Get-Stuff

                # Output to pipeline
                [PSCustomObject]@{
                    Name          = $Object.Name
                    Id            = $Object.Id
                }

            }

        }
        catch [exception] {

            throw $_

        }

    } # End process

} # End function


text:
This library provides easy access to the [Sending Domains](https://www.sparkpost.com/api#/reference/sending-domains/) Resource.

## Methods
* **all(callback)**
  List an overview of all sending domains in the account.
  * `callback` - executed after task is completed. **required**
    * standard `callback(err, data)`
    * `err` - any error that occurred
    * `data` - full response from request client
* **find(domain, callback)**
  Retrieve a sending domain by its domain name
  * `domain` - the name of the domain you want to look up **required**
  * `callback` - see all function
* **create(domainBody, callback)**
  Create a new sending domain
  * `domainBody` - a sending domain object **required**
  * `callback` - see all function
* **update(domainBody, callback)**
  Update an existing sending domain
  * `domainBody` - a sending domain object **required**
  * `callback` - see all function
* **delete(domain, callback)**
  Delete an existing sending domain
  * `domain` - the name of the domain you want to delete **required**
  * `callback` - see all function
* **verify(options, callback)**
  Validate the specified verification field types for a sending domain
  * `options.domain` - the name of the domain you want to verify **required**
  * `options.verifyDKIM` - initiates a check against the DKIM record default: `true`
  * `options.verifySPF` - initiates a check against the SPF record default: `true`

## Examples

```js
var SparkPost = require('sparkpost');
var client = new SparkPost('YOUR_API_KEY');

client.sendingDomains.all(function(err, data) {
  if(err) {
    console.log(err);
    return;
  }

  console.log(data.body);
});

```

Check out all the examples provided [here](/examples/sendingDomains).


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using Amazon.Lambda.Core;
using Amazon.Lambda.S3Events;
using Amazon.S3;
using Amazon.S3.Util;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]

namespace S3EventFunction
{
    public class Function
    {
        IAmazonS3 S3Client { get; set; }

        /// <summary>
        /// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment
        /// the AWS credentials will come from the IAM role associated with the function and the AWS region will be set to the
        /// region the Lambda function is executed in.
        /// </summary>
        public Function()
        {
            S3Client = new AmazonS3Client();
        }

        /// <summary>
        /// Constructs an instance with a preconfigured S3 client. This can be used for testing the outside of the Lambda environment.
        /// </summary>
        /// <param name="s3Client"></param>
        public Function(IAmazonS3 s3Client)
        {
            this.S3Client = s3Client;
        }

        /// <summary>
        /// This method is called for every Lambda invocation. This method takes in an S3 event object and can be used
        /// to respond to S3 notifications.
        /// </summary>
        /// <param name="evnt"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public void FunctionHandler(S3Event evnt, ILambdaContext context)
        {

            foreach (var record in evnt.Records)
            {
                context.Logger.LogLine($"Processing {record.S3.Object.Key}");
                if (string.Equals("error.txt", record.S3.Object.Key))
                {
                    throw new Exception("Simulated Failure");
                }
            }
        }
    }
}


text: #import "MDCProgressView.h"


text:
using Moen.KanColle.Dentan.Data;
using System;

namespace Moen.KanColle.Dentan.Api.Parser.Factory
{
    [Api("api_req_kousyou/destroyitem2")]
    class EquipmentDiscardingParser : ApiParser
    {
        public override void Process()
        {
            var rEquipmentIDs = Array.ConvertAll(Request["api_slotitem_ids"].Split(','), int.Parse);

            foreach (var rID in rEquipmentIDs)
                Game.Equipments.Remove(rID);

            Game.UpdateEquipments();

            Quest.Progresses[613].Current++;
        }
    }
}


text:
package org.apache.tomcat.dbcp.pool2.impl;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;

import org.apache.tomcat.dbcp.pool2.PooledObject;

/**
 * Implementation of object that is used to provide information on pooled
 * objects via JMX.
 *
 * @since 2.0
 */
public class DefaultPooledObjectInfo implements DefaultPooledObjectInfoMBean {

    private final PooledObject<?> pooledObject;

    /**
     * Create a new instance for the given pooled object.
     *
     * @param pooledObject The pooled object that this instance will represent
     */
    public DefaultPooledObjectInfo(PooledObject<?> pooledObject) {
        this.pooledObject = pooledObject;
    }

    @Override
    public long getCreateTime() {
        return pooledObject.getCreateTime();
    }

    @Override
    public String getCreateTimeFormatted() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
        return sdf.format(Long.valueOf(pooledObject.getCreateTime()));
    }

    @Override
    public long getLastBorrowTime() {
        return pooledObject.getLastBorrowTime();
    }

    @Override
    public String getLastBorrowTimeFormatted() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
        return sdf.format(Long.valueOf(pooledObject.getLastBorrowTime()));
    }

    @Override
    public String getLastBorrowTrace() {
        StringWriter sw = new StringWriter();
        pooledObject.printStackTrace(new PrintWriter(sw));
        return sw.toString();
    }

    @Override
    public long getLastReturnTime() {
        return pooledObject.getLastReturnTime();
    }

    @Override
    public String getLastReturnTimeFormatted() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
        return sdf.format(Long.valueOf(pooledObject.getLastReturnTime()));
    }

    @Override
    public String getPooledObjectType() {
        return pooledObject.getObject().getClass().getName();
    }

    @Override
    public String getPooledObjectToString() {
        return pooledObject.getObject().toString();
    }

    @Override
    public long getBorrowedCount() {
        // TODO Simplify this once getBorrowedCount has been added to PooledObject
        if (pooledObject instanceof DefaultPooledObject) {
            return ((DefaultPooledObject<?>) pooledObject).getBorrowedCount();
        } else {
            return -1;
        }
    }
}


text:
<?php

namespace Mvs\SampleBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class MvsSampleBundle extends Bundle
{
}


text:
#ifndef CDSLIB_OS_FREE_BSD_ALLOC_ALIGNED_H
#define CDSLIB_OS_FREE_BSD_ALLOC_ALIGNED_H

#include <cds/os/posix/alloc_aligned.h>

#endif // #ifndef CDSLIB_OS_FREE_BSD_ALLOC_ALIGNED_H


text:
package jp.canetrash.vicuna.web.controller;

import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author tfunato
 *
 */
@Controller
public class Dashbord {

	@RequestMapping("/dashboard")
	public String dashbord(Map<String, Object> model) {
		model.put("dashbordMenuActive", true);
		return "dashboard";
	}
}


text:
namespace mx
{
    namespace core
    {
        TiedAttributes::TiedAttributes()
        :type( StartStopContinue::start )
        ,number()
        ,lineType( LineType::solid )
        ,dashLength()
        ,spaceLength()
        ,defaultX()
        ,defaultY()
        ,relativeX()
        ,relativeY()
        ,placement( AboveBelow::below )
        ,orientation()
        ,bezierOffset()
        ,bezierOffset2()
        ,bezierX()
        ,bezierY()
        ,bezierX2()
        ,bezierY2()
        ,color()
        ,hasType( true )
        ,hasNumber( false )
        ,hasLineType( false )
        ,hasDashLength( false )
        ,hasSpaceLength( false )
        ,hasDefaultX( false )
        ,hasDefaultY( false )
        ,hasRelativeX( false )
        ,hasRelativeY( false )
        ,hasPlacement( false )
        ,hasOrientation( false )
        ,hasBezierOffset( false )
        ,hasBezierOffset2( false )
        ,hasBezierX( false )
        ,hasBezierY( false )
        ,hasBezierX2( false )
        ,hasBezierY2( false )
        ,hasColor( false )
        {}

        bool TiedAttributes::hasValues() const
        {
            return hasType ||
            hasNumber ||
            hasLineType ||
            hasDashLength ||
            hasSpaceLength ||
            hasDefaultX ||
            hasDefaultY ||
            hasRelativeX ||
            hasRelativeY ||
            hasPlacement ||
            hasOrientation ||
            hasBezierOffset ||
            hasBezierOffset2 ||
            hasBezierX ||
            hasBezierY ||
            hasBezierX2 ||
            hasBezierY2 ||
            hasColor;
        }

        std::ostream& TiedAttributes::toStream( std::ostream& os ) const
        {
            if ( hasValues() )
            {
                streamAttribute( os, type, "type", hasType );
                streamAttribute( os, number, "number", hasNumber );
                streamAttribute( os, lineType, "line-type", hasLineType );
                streamAttribute( os, dashLength, "dash-length", hasDashLength );
                streamAttribute( os, spaceLength, "space-length", hasSpaceLength );
                streamAttribute( os, defaultX, "default-x", hasDefaultX );
                streamAttribute( os, defaultY, "default-y", hasDefaultY );
                streamAttribute( os, relativeX, "relative-x", hasRelativeX );
                streamAttribute( os, relativeY, "relative-y", hasRelativeY );
                streamAttribute( os, placement, "placement", hasPlacement );
                streamAttribute( os, orientation, "orientation", hasOrientation );
                streamAttribute( os, bezierOffset, "bezier-offset", hasBezierOffset );
                streamAttribute( os, bezierOffset2, "bezier-offset2", hasBezierOffset2 );
                streamAttribute( os, bezierX, "bezier-x", hasBezierX );
                streamAttribute( os, bezierY, "bezier-y", hasBezierY );
                streamAttribute( os, bezierX2, "bezier-x2", hasBezierX2 );
                streamAttribute( os, bezierY2, "bezier-y2", hasBezierY2 );
                streamAttribute( os, color, "color", hasColor );
            }
            return os;
        }

        bool TiedAttributes::fromXElementImpl( std::ostream& message, ::ezxml::XElement& xelement )
        {
            const char* const className = "TiedAttributes";
            bool isSuccess = true;
            bool isTypeFound = false;

            auto it = xelement.attributesBegin();
            auto endIter = xelement.attributesEnd();

            for( ; it != endIter; ++it )
            {
                if( parseAttribute( message, it, className, isSuccess, type, isTypeFound, "type", &parseStartStopContinue ) ) { continue; }
                if( parseAttribute( message, it, className, isSuccess, number, hasNumber, "number" ) ) { continue; }
                if( parseAttribute( message, it, className, isSuccess, lineType, hasLineType, "line-type", &parseLineType ) ) { continue; }
                if( parseAttribute( message, it, className, isSuccess, dashLength, hasDashLength, "dash-length" ) ) { continue; }
                if( parseAttribute( message, it, className, isSuccess, spaceLength, hasSpaceLength, "space-length" ) ) { continue; }
                if( parseAttribute( message, it, className, isSuccess, defaultX, hasDefaultX, "default-x" ) ) { continue; }
                if( parseAttribute( message, it, className, isSuccess, defaultY, hasDefaultY, "default-y" ) ) { continue; }
                if( parseAttribute( message, it, className, isSuccess, relativeX, hasRelativeX, "relative-x" ) ) { continue; }
                if( parseAttribute( message, it, className, isSuccess, relativeY, hasRelativeY, "relative-y" ) ) { continue; }
                if( parseAttribute( message, it, className, isSuccess, placement, hasPlacement, "placement", &parseAboveBelow ) ) { continue; }
                if( parseAttribute( message, it, className, isSuccess, orientation, hasOrientation, "orientation", &parseOverUnder ) ) { continue; }
                if( parseAttribute( message, it, className, isSuccess, bezierOffset, hasBezierOffset, "bezier-offset" ) ) { continue; }
                if( parseAttribute( message, it, className, isSuccess, bezierOffset2, hasBezierOffset2, "bezier-offset-2" ) ) { continue; }
                if( parseAttribute( message, it, className, isSuccess, bezierX, hasBezierX, "bezier-x" ) ) { continue; }
                if( parseAttribute( message, it, className, isSuccess, bezierY, hasBezierY, "bezier-y" ) ) { continue; }
                if( parseAttribute( message, it, className, isSuccess, bezierX2, hasBezierX2, "bezier-x-2" ) ) { continue; }
                if( parseAttribute( message, it, className, isSuccess, bezierY2, hasBezierY2, "bezier-y-2" ) ) { continue; }
                if( parseAttribute( message, it, className, isSuccess, color, hasColor, "color" ) ) { continue; }
            }

            if( !isTypeFound )
            {
                isSuccess = false;
                message << className << ": 'number' is a required attribute but was not found" << std::endl;
            }

            MX_RETURN_IS_SUCCESS;
        }

    }
}


text:
- Getting started
  - [Quick Start](getting-started.md)
- Customization
  - [Configuration](configuration.md)
  - [API Configuration](API-configuration.md)
  - [I18n](i18n.md)
  - [Layout](layout.md)
  - [Request](request.md)
- Guide
  - [Deploy](deploy.md)
- [Change Log](change-log.md)
- [FAQ](faq.md)


text:
import {Action} from "@ngrx/store";
import {USER_SAVE_ACTION, SaveUserAction} from "../actions/user.actions";
import {StoreData} from "../state/storeData.state";

export function storeData(state: StoreData , action: Action): StoreData {

  switch (action.type) {
    case USER_SAVE_ACTION: {
      return handleSaveUserAction(action);
    }

    default:
      return state;
  }
}

function handleSaveUserAction(action: SaveUserAction): StoreData {
  return { currentUser: action.payload };
}


text:
{% extends "base.html" %}
{% block title %}iSwift-用户文件管理{% endblock %}
{% block headinfo %}
欢迎,

    {{ username }}

空间使用率:60%

        退出平台

{% endblock %}
{% block content %}

{% include "_messages.html" %}

    {% block leftmenu %}
    {% include "logined/privatefiles/left_menu.html" %}
    {% endblock %}
    {% block maininfo %}
    {% include "logined/privatefiles/right_display.html" %}
    {% endblock %}

<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>

上传文件

<form action="/privatefiles/file/create/{% if file_loaction %}{% for paths  in file_loaction %}{{ paths.name }}/{%endfor%}{%endif%}" enctype="multipart/form-data" method="post" id="b_form_test">

    <input value="$csrf_token" name="csrfmiddlewaretoken" id="csrf_token" type="hidden">

<fieldset id="id_fieldset1">

<input name="id_object_file" id="id_object_file" type="file">
</fieldset>

<input data-loading-text="Loading..." class="btn btn-primary" value="提交" type="submit">
<button class="btn" data-dismiss="modal" aria-hidden="true">关闭</button>

</form>

{% endblock %}


text:
/* eslint-env mocha */

import chai from 'chai'
import chaiBytes from 'chai-bytes'
import dirtyChai from 'dirty-chai'

import Bool from '../../src/lowlevel/Bool'
import { rawValue } from '../../src/lowlevel/common'

const expect = chai
  .use(chaiBytes)
  .use(dirtyChai)
  .expect

describe('Bool', function () {
  it('should declare byteLength 1', () => {
    expect(Bool.typeLength()).to.equal(1)
  })

  it('should declare true contant', () => {
    expect(rawValue(Bool.TRUE)).to.be.true()
  })

  it('should declare false contant', () => {
    expect(rawValue(Bool.FALSE)).to.be.false()
  })

  describe('constructor', () => {
    it('should accept JS boolean', () => {
      let x = new Bool(true)
      expect(rawValue(x)).to.be.true()
      x = new Bool(false)
      expect(rawValue(x)).to.be.false()
    })

    it('should accept another Bool', () => {
      let x = new Bool(Bool.TRUE)
      expect(rawValue(x)).to.be.true()
      x = new Bool(Bool.FALSE)
      expect(rawValue(x)).to.be.false()
    })

    it('should not accept anything else', () => {
      const unacceptable = [
        [], {}, () => {}, null, undefined, '', 'true', 5, NaN
      ]

      unacceptable.forEach(x => {
        expect(() => new Bool(x)).to.throw(/cannot construct Bool/i)
      })
    })
  })

  describe('serialize', () => {
    it('should serialize false as [0]', () => {
      expect(Bool.FALSE.serialize()).to.equalBytes('00')
    })

    it('should serialize true as [1]', () => {
      expect(Bool.TRUE.serialize()).to.equalBytes('01')
    })
  })

  describe('toJSON', () => {
    it('should return raw value', () => {
      expect(Bool.TRUE.toJSON()).to.be.true()
      expect(Bool.FALSE.toJSON()).to.be.false()
    })
  })
})


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.machinelearning.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

/** Forecasting specific parameters. */
@Fluent
public final class ForecastingSettings {
    /*
     * Country or region for holidays for forecasting tasks.
     * These should be ISO 3166 two-letter country/region codes, for example 'US' or 'GB'.
     */
    @JsonProperty(value = "countryOrRegionForHolidays")
    private String countryOrRegionForHolidays;

    /*
     * Number of periods between the origin time of one CV fold and the next fold. For
     * example, if `CVStepSize` = 3 for daily data, the origin time for each fold will be
     * three days apart.
     */
    @JsonProperty(value = "cvStepSize")
    private Integer cvStepSize;

    /*
     * Flag for generating lags for the numeric features with 'auto' or null.
     */
    @JsonProperty(value = "featureLags")
    private FeatureLags featureLags;

    /*
     * The desired maximum forecast horizon in units of time-series frequency.
     */
    @JsonProperty(value = "forecastHorizon")
    private ForecastHorizon forecastHorizon;

    /*
     * When forecasting, this parameter represents the period with which the forecast is desired, for example daily,
     * weekly, yearly, etc. The forecast frequency is dataset frequency by default.
     */
    @JsonProperty(value = "frequency")
    private String frequency;

    /*
     * Set time series seasonality as an integer multiple of the series frequency.
     * If seasonality is set to 'auto', it will be inferred.
     */
    @JsonProperty(value = "seasonality")
    private Seasonality seasonality;

    /*
     * The parameter defining how if AutoML should handle short time series.
     */
    @JsonProperty(value = "shortSeriesHandlingConfig")
    private ShortSeriesHandlingConfiguration shortSeriesHandlingConfig;

    /*
     * The function to be used to aggregate the time series target column to conform to a user specified frequency.
     * If the TargetAggregateFunction is set i.e. not 'None', but the freq parameter is not set, the error is raised.
     * The possible target aggregation functions are: "sum", "max", "min" and "mean".
     */
    @JsonProperty(value = "targetAggregateFunction")
    private TargetAggregationFunction targetAggregateFunction;

    /*
     * The number of past periods to lag from the target column.
     */
    @JsonProperty(value = "targetLags")
    private TargetLags targetLags;

    /*
     * The number of past periods used to create a rolling window average of the target column.
     */
    @JsonProperty(value = "targetRollingWindowSize")
    private TargetRollingWindowSize targetRollingWindowSize;

    /*
     * The name of the time column. This parameter is required when forecasting to specify the datetime column in the
     * input data used for building the time series and inferring its frequency.
     */
    @JsonProperty(value = "timeColumnName")
    private String timeColumnName;

    /*
     * The names of columns used to group a timeseries. It can be used to create multiple series.
     * If grain is not defined, the data set is assumed to be one time-series. This parameter is used with task type
     * forecasting.
     */
    @JsonProperty(value = "timeSeriesIdColumnNames")
    private List<String> timeSeriesIdColumnNames;

    /*
     * Configure STL Decomposition of the time-series target column.
     */
    @JsonProperty(value = "useStl")
    private UseStl useStl;

    /** Creates an instance of ForecastingSettings class. */
    public ForecastingSettings() {
    }

    /**
     * Get the countryOrRegionForHolidays property: Country or region for holidays for forecasting tasks. These should
     * be ISO 3166 two-letter country/region codes, for example 'US' or 'GB'.
     *
     * @return the countryOrRegionForHolidays value.
     */
    public String countryOrRegionForHolidays() {
        return this.countryOrRegionForHolidays;
    }

    /**
     * Set the countryOrRegionForHolidays property: Country or region for holidays for forecasting tasks. These should
     * be ISO 3166 two-letter country/region codes, for example 'US' or 'GB'.
     *
     * @param countryOrRegionForHolidays the countryOrRegionForHolidays value to set.
     * @return the ForecastingSettings object itself.
     */
    public ForecastingSettings withCountryOrRegionForHolidays(String countryOrRegionForHolidays) {
        this.countryOrRegionForHolidays = countryOrRegionForHolidays;
        return this;
    }

    /**
     * Get the cvStepSize property: Number of periods between the origin time of one CV fold and the next fold. For
     * example, if `CVStepSize` = 3 for daily data, the origin time for each fold will be three days apart.
     *
     * @return the cvStepSize value.
     */
    public Integer cvStepSize() {
        return this.cvStepSize;
    }

    /**
     * Set the cvStepSize property: Number of periods between the origin time of one CV fold and the next fold. For
     * example, if `CVStepSize` = 3 for daily data, the origin time for each fold will be three days apart.
     *
     * @param cvStepSize the cvStepSize value to set.
     * @return the ForecastingSettings object itself.
     */
    public ForecastingSettings withCvStepSize(Integer cvStepSize) {
        this.cvStepSize = cvStepSize;
        return this;
    }

    /**
     * Get the featureLags property: Flag for generating lags for the numeric features with 'auto' or null.
     *
     * @return the featureLags value.
     */
    public FeatureLags featureLags() {
        return this.featureLags;
    }

    /**
     * Set the featureLags property: Flag for generating lags for the numeric features with 'auto' or null.
     *
     * @param featureLags the featureLags value to set.
     * @return the ForecastingSettings object itself.
     */
    public ForecastingSettings withFeatureLags(FeatureLags featureLags) {
        this.featureLags = featureLags;
        return this;
    }

    /**
     * Get the forecastHorizon property: The desired maximum forecast horizon in units of time-series frequency.
     *
     * @return the forecastHorizon value.
     */
    public ForecastHorizon forecastHorizon() {
        return this.forecastHorizon;
    }

    /**
     * Set the forecastHorizon property: The desired maximum forecast horizon in units of time-series frequency.
     *
     * @param forecastHorizon the forecastHorizon value to set.
     * @return the ForecastingSettings object itself.
     */
    public ForecastingSettings withForecastHorizon(ForecastHorizon forecastHorizon) {
        this.forecastHorizon = forecastHorizon;
        return this;
    }

    /**
     * Get the frequency property: When forecasting, this parameter represents the period with which the forecast is
     * desired, for example daily, weekly, yearly, etc. The forecast frequency is dataset frequency by default.
     *
     * @return the frequency value.
     */
    public String frequency() {
        return this.frequency;
    }

    /**
     * Set the frequency property: When forecasting, this parameter represents the period with which the forecast is
     * desired, for example daily, weekly, yearly, etc. The forecast frequency is dataset frequency by default.
     *
     * @param frequency the frequency value to set.
     * @return the ForecastingSettings object itself.
     */
    public ForecastingSettings withFrequency(String frequency) {
        this.frequency = frequency;
        return this;
    }

    /**
     * Get the seasonality property: Set time series seasonality as an integer multiple of the series frequency. If
     * seasonality is set to 'auto', it will be inferred.
     *
     * @return the seasonality value.
     */
    public Seasonality seasonality() {
        return this.seasonality;
    }

    /**
     * Set the seasonality property: Set time series seasonality as an integer multiple of the series frequency. If
     * seasonality is set to 'auto', it will be inferred.
     *
     * @param seasonality the seasonality value to set.
     * @return the ForecastingSettings object itself.
     */
    public ForecastingSettings withSeasonality(Seasonality seasonality) {
        this.seasonality = seasonality;
        return this;
    }

    /**
     * Get the shortSeriesHandlingConfig property: The parameter defining how if AutoML should handle short time series.
     *
     * @return the shortSeriesHandlingConfig value.
     */
    public ShortSeriesHandlingConfiguration shortSeriesHandlingConfig() {
        return this.shortSeriesHandlingConfig;
    }

    /**
     * Set the shortSeriesHandlingConfig property: The parameter defining how if AutoML should handle short time series.
     *
     * @param shortSeriesHandlingConfig the shortSeriesHandlingConfig value to set.
     * @return the ForecastingSettings object itself.
     */
    public ForecastingSettings withShortSeriesHandlingConfig(
        ShortSeriesHandlingConfiguration shortSeriesHandlingConfig) {
        this.shortSeriesHandlingConfig = shortSeriesHandlingConfig;
        return this;
    }

    /**
     * Get the targetAggregateFunction property: The function to be used to aggregate the time series target column to
     * conform to a user specified frequency. If the TargetAggregateFunction is set i.e. not 'None', but the freq
     * parameter is not set, the error is raised. The possible target aggregation functions are: "sum", "max", "min" and
     * "mean".
     *
     * @return the targetAggregateFunction value.
     */
    public TargetAggregationFunction targetAggregateFunction() {
        return this.targetAggregateFunction;
    }

    /**
     * Set the targetAggregateFunction property: The function to be used to aggregate the time series target column to
     * conform to a user specified frequency. If the TargetAggregateFunction is set i.e. not 'None', but the freq
     * parameter is not set, the error is raised. The possible target aggregation functions are: "sum", "max", "min" and
     * "mean".
     *
     * @param targetAggregateFunction the targetAggregateFunction value to set.
     * @return the ForecastingSettings object itself.
     */
    public ForecastingSettings withTargetAggregateFunction(TargetAggregationFunction targetAggregateFunction) {
        this.targetAggregateFunction = targetAggregateFunction;
        return this;
    }

    /**
     * Get the targetLags property: The number of past periods to lag from the target column.
     *
     * @return the targetLags value.
     */
    public TargetLags targetLags() {
        return this.targetLags;
    }

    /**
     * Set the targetLags property: The number of past periods to lag from the target column.
     *
     * @param targetLags the targetLags value to set.
     * @return the ForecastingSettings object itself.
     */
    public ForecastingSettings withTargetLags(TargetLags targetLags) {
        this.targetLags = targetLags;
        return this;
    }

    /**
     * Get the targetRollingWindowSize property: The number of past periods used to create a rolling window average of
     * the target column.
     *
     * @return the targetRollingWindowSize value.
     */
    public TargetRollingWindowSize targetRollingWindowSize() {
        return this.targetRollingWindowSize;
    }

    /**
     * Set the targetRollingWindowSize property: The number of past periods used to create a rolling window average of
     * the target column.
     *
     * @param targetRollingWindowSize the targetRollingWindowSize value to set.
     * @return the ForecastingSettings object itself.
     */
    public ForecastingSettings withTargetRollingWindowSize(TargetRollingWindowSize targetRollingWindowSize) {
        this.targetRollingWindowSize = targetRollingWindowSize;
        return this;
    }

    /**
     * Get the timeColumnName property: The name of the time column. This parameter is required when forecasting to
     * specify the datetime column in the input data used for building the time series and inferring its frequency.
     *
     * @return the timeColumnName value.
     */
    public String timeColumnName() {
        return this.timeColumnName;
    }

    /**
     * Set the timeColumnName property: The name of the time column. This parameter is required when forecasting to
     * specify the datetime column in the input data used for building the time series and inferring its frequency.
     *
     * @param timeColumnName the timeColumnName value to set.
     * @return the ForecastingSettings object itself.
     */
    public ForecastingSettings withTimeColumnName(String timeColumnName) {
        this.timeColumnName = timeColumnName;
        return this;
    }

    /**
     * Get the timeSeriesIdColumnNames property: The names of columns used to group a timeseries. It can be used to
     * create multiple series. If grain is not defined, the data set is assumed to be one time-series. This parameter is
     * used with task type forecasting.
     *
     * @return the timeSeriesIdColumnNames value.
     */
    public List<String> timeSeriesIdColumnNames() {
        return this.timeSeriesIdColumnNames;
    }

    /**
     * Set the timeSeriesIdColumnNames property: The names of columns used to group a timeseries. It can be used to
     * create multiple series. If grain is not defined, the data set is assumed to be one time-series. This parameter is
     * used with task type forecasting.
     *
     * @param timeSeriesIdColumnNames the timeSeriesIdColumnNames value to set.
     * @return the ForecastingSettings object itself.
     */
    public ForecastingSettings withTimeSeriesIdColumnNames(List<String> timeSeriesIdColumnNames) {
        this.timeSeriesIdColumnNames = timeSeriesIdColumnNames;
        return this;
    }

    /**
     * Get the useStl property: Configure STL Decomposition of the time-series target column.
     *
     * @return the useStl value.
     */
    public UseStl useStl() {
        return this.useStl;
    }

    /**
     * Set the useStl property: Configure STL Decomposition of the time-series target column.
     *
     * @param useStl the useStl value to set.
     * @return the ForecastingSettings object itself.
     */
    public ForecastingSettings withUseStl(UseStl useStl) {
        this.useStl = useStl;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (forecastHorizon() != null) {
            forecastHorizon().validate();
        }
        if (seasonality() != null) {
            seasonality().validate();
        }
        if (targetLags() != null) {
            targetLags().validate();
        }
        if (targetRollingWindowSize() != null) {
            targetRollingWindowSize().validate();
        }
    }
}


text:
//
//  LFHSegmentedControl.m
//  LoveFlyHome
//
//  Created by Lefeng on 16/6/1.
//  Copyright © 2016年 Lefeng. All rights reserved.
//

#import "LFHSegmentedControl.h"
@interface LFHSegmentedControl ()<LFHSegmentedControlDelegate>
{
    CGFloat widthFloat;
    UIView *buttonDownView;
    NSInteger selectSegument;
}
@end
@implementation LFHSegmentedControl
- (instancetype)initWithFrame:(CGRect)frame
{
    if(self==[super initWithFrame:frame])
    {
        self.btnTitleSource=[NSMutableArray array];
        selectSegument=0;

    }
    return self;

}
+ (LFHSegmentedControl *)segmentedControlFrame:(CGRect)frame titleDataSource:(NSArray *)titleDataSouece backgroundColor:(UIColor *)backgroundColor titleColor:(UIColor *)titleColor titleFont:(UIFont *)titleFont selectColor:(UIColor *)selectColor buttonDownColor:(UIColor *)buttonDownColor  Delegate:(id)delegate
{
    LFHSegmentedControl *segmentCtrl=[[self alloc] initWithFrame:frame];
    segmentCtrl.backgroundColor=backgroundColor;
    segmentCtrl.buttonDownColor=buttonDownColor;

    segmentCtrl.titleColor=titleColor;
    segmentCtrl.titleFont=titleFont;
    segmentCtrl.selectColor=selectColor;

    segmentCtrl.delegate=delegate;
    [segmentCtrl AddSegumentArray:titleDataSouece];

    return segmentCtrl;

}

- (void)AddSegumentArray:(NSArray *)segmentArray
{
    /**按钮的个数**/
    NSInteger segmentNumber=segmentArray.count;
    /**按钮的宽度**/
    widthFloat=(self.bounds.size.width)/segmentNumber;
    /**创建按钮**/
    for(int i=0;i<segmentArray.count;i++)
    {
        UIButton * btn = [[UIButton alloc] initWithFrame:CGRectMake(i * widthFloat, 0, widthFloat, self.bounds.size.height - 2)];
        [btn setTitle:segmentArray[i] forState:UIControlStateNormal];
        [btn.titleLabel setFont:self.titleFont];
        [btn setTitleColor:self.titleColor forState:UIControlStateNormal];
        [btn setTitleColor:self.selectColor forState:UIControlStateSelected];
        btn.tag = i + 1;
        [btn addTarget:self action:@selector(changeSegumentAction:) forControlEvents:UIControlEventTouchUpInside];
        if (i == 0) {
            buttonDownView =[[UIView alloc]initWithFrame:CGRectMake(i * widthFloat, self.bounds.size.height - 2, widthFloat, 2)];
            [buttonDownView setBackgroundColor:self.buttonDownColor];

            [self addSubview:buttonDownView];
        }
        [self addSubview:btn];

        [self.btnTitleSource addObject:btn];
    }
    [[self.btnTitleSource firstObject] setSelected:YES];

}

- (void)changeSegumentAction:(UIButton *)btn{
    [self selectTheSegument:btn.tag - 1];
}

-(void)selectTheSegument:(NSInteger)segument{

    if (selectSegument != segument) {

        [self.btnTitleSource[selectSegument] setSelected:NO];
        [self.btnTitleSource[segument] setSelected:YES];

        [UIView animateWithDuration:0.2 animations:^{

            [buttonDownView setFrame:CGRectMake(segument * widthFloat,self.bounds.size.height - 2, widthFloat, 2)];
        }];
        selectSegument = segument;
        [self.delegate segMentSelectedChange:selectSegument];
    }
}

@end


text:
const traverse = require("../lib").default;
const assert = require("assert");
const parse = require("babylon").parse;

describe("path/family", function () {
  describe("getBindingIdentifiers", function () {
    const ast = parse("var a = 1, {b} = c, [d] = e; function f() {}");
    let nodes = {}, paths = {}, outerNodes = {}, outerPaths = {};
    traverse(ast, {
      VariableDeclaration(path) {
        nodes = path.getBindingIdentifiers();
        paths = path.getBindingIdentifierPaths();
      },
      FunctionDeclaration(path) {
        outerNodes = path.getOuterBindingIdentifiers();
        outerPaths = path.getOuterBindingIdentifierPaths();
      },
    });

    it("should contain keys of nodes in paths", function () {
      Object.keys(nodes).forEach((id) => {
        assert.strictEqual(hop(paths, id), true, "Node's keys exists in paths");
      });
    });

    it("should contain outer bindings", function () {
      Object.keys(outerNodes).forEach((id) => {
        assert.strictEqual(hop(outerPaths, id), true, "Has same outer keys");
      });
    });

    it("should return paths", function () {
      Object.keys(paths).forEach((id) => {
        assert.strictEqual(!!paths[id].node, true, "Has a property node that's not falsy");
        assert.strictEqual(paths[id].type, paths[id].node.type, "type matches");
      });

      Object.keys(outerPaths).forEach((id) => {
        assert.strictEqual(!!outerPaths[id].node, true, "has property node");
        assert.strictEqual(outerPaths[id].type, outerPaths[id].node.type, "type matches");
      });
    });

    it("should match paths and nodes returned for the same ast", function () {
      Object.keys(nodes).forEach((id) => {
        assert.strictEqual(nodes[id], paths[id].node, "Nodes match");
      });
    });

    it("should match paths and nodes returned for outer Bindings", function () {
      Object.keys(outerNodes).forEach((id) => {
        assert.strictEqual(outerNodes[id], outerPaths[id].node, "nodes match");
      });
    });

  });
  describe("getSibling", function () {
    const ast = parse("var a = 1, {b} = c, [d] = e; function f() {} function g() {}");
    let sibling = {}, lastSibling = {};
    traverse(ast, {
      VariableDeclaration(path) {
        sibling = path.getSibling(path.key);
        lastSibling = sibling.getNextSibling().getNextSibling();
      },
    });

    it("should return traverse sibling nodes", function () {
      assert.ok(sibling.getNextSibling().node, "has property node");
      assert.ok(lastSibling.getPrevSibling().node, "has property node");
      assert.equal(!!sibling.getPrevSibling().node, false, "out of scope");
      assert.equal(!!lastSibling.getNextSibling().node, false, "out of scope");
    });

    it("should return all preceding and succeeding sibling nodes", function () {
      assert.ok(sibling.getAllNextSiblings().length, "Has next sibling");
      assert.ok(lastSibling.getAllPrevSiblings().length, "Has prev sibling");
      assert.equal(sibling.getAllNextSiblings().length, 2, "Has 2 succeeding sibling");
      assert.equal(lastSibling.getAllPrevSiblings().length, 2, "Has 2 preceeding sibling");
    });
  });
});

function hop(o, key) {
  return Object.hasOwnProperty.call(o, key);
}


text:
from modularodm import Q

PREREG_CAMPAIGNS = {
    'prereg': 'Prereg Challenge',
    'erpc': 'Election Research Preacceptance Competition',
}

def drafts_for_user(user, campaign):
    from website import models  # noqa

    PREREG_CHALLENGE_METASCHEMA = get_prereg_schema(campaign)
    return models.DraftRegistration.objects.filter(
        registration_schema=PREREG_CHALLENGE_METASCHEMA,
        approval=None,
        registered_node=None,
        branched_from__in=models.Node.objects.filter(
            is_deleted=False,
            contributor__admin=True,
            contributor__user=user).values_list('id', flat=True))

def get_prereg_schema(campaign='prereg'):
    from website.models import MetaSchema  # noqa
    if campaign not in PREREG_CAMPAIGNS:
        raise ValueError('campaign must be one of: {}'.format(', '.join(PREREG_CAMPAIGNS.keys())))
    schema_name = PREREG_CAMPAIGNS[campaign]

    return MetaSchema.find_one(
        Q('name', 'eq', schema_name) &
        Q('schema_version', 'eq', 2)
    )


text:
using System;
using System.ComponentModel;
using System.Windows.Input;

namespace Casimodo.Lib.ComponentModel
{
    public class DelegateCommand<T> : XDelegateCommand<T>, ICommand, ICommandEx, INotifyPropertyChanged
    {
        protected static readonly PropertyChangedEventArgs TextChangedArgs = new PropertyChangedEventArgs("Text");

        public DelegateCommand(Action<T> executeMethod)
            : base(executeMethod)
        { }

        public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod)
            : base(executeMethod, canExecuteMethod)
        { }

        public event EventHandler Executed;

        public override void Execute(T parameter)
        {
            base.Execute(parameter);

            var handler = Executed;
            if (handler != null)
                handler(this, EventArgs.Empty);
        }

        public string Text
        {
            get { return _text; }
            set
            {
                if (string.Equals(_text, value, StringComparison.Ordinal))
                    return;

                _text = value;

                var handler = PropertyChanged;
                if (handler != null)
                    handler(this, TextChangedArgs);
            }
        }

        string _text;

        public event PropertyChangedEventHandler PropertyChanged;
    }
}


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Threading
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Structure
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax

Namespace Microsoft.CodeAnalysis.VisualBasic.Structure
    Friend Class NamespaceDeclarationStructureProvider
        Inherits AbstractSyntaxNodeStructureProvider(Of NamespaceStatementSyntax)

        Protected Overrides Sub CollectBlockSpans(namespaceDeclaration As NamespaceStatementSyntax,
                                                  spans As ArrayBuilder(Of BlockSpan),
                                                  options As OptionSet,
                                                  cancellationToken As CancellationToken)
            CollectCommentsRegions(namespaceDeclaration, spans)

            Dim block = TryCast(namespaceDeclaration.Parent, NamespaceBlockSyntax)
            If Not block?.EndNamespaceStatement.IsMissing Then
                spans.AddIfNotNull(CreateBlockSpanFromBlock(
                    block, bannerNode:=namespaceDeclaration, autoCollapse:=False,
                    type:=BlockTypes.Namespace, isCollapsible:=True))

                CollectCommentsRegions(block.EndNamespaceStatement, spans)
            End If
        End Sub

        Protected Overrides Function SupportedInWorkspaceKind(kind As String) As Boolean
            Return True
        End Function
    End Class
End Namespace


text:
namespace Swashbuckle.AspNetCore.SwaggerGen
{
    internal static class StringExtensions
    {
        internal static string ToCamelCase(this string value)
        {
            if (string.IsNullOrEmpty(value)) return value;
            return char.ToLowerInvariant(value[0]) + value.Substring(1);
        }

        internal static string ToTitleCase(this string value)
        {
            if (string.IsNullOrEmpty(value)) return value;
            return char.ToUpperInvariant(value[0]) + value.Substring(1);
        }
    }
}


text:
require 'test/unit'
require 'contest'
require 'pg'
require 'active_support/cache'
require 'active_support/cache/memory_store'
require_relative '../lib/bananasplit'
ActiveRecord::Base.establish_connection(
  :adapter => "postgresql",
  :database => "bananasplit-test")
ActiveRecord::Schema.define do
  create_table "experiments", :force => true do |t|
    t.string "test_name"
    t.string "status"
    t.timestamps
  end

  add_index "experiments", "test_name"
  #add_index "experiments", "created_on"

  create_table "alternatives", :force => true do |t|
    t.integer :experiment_id
    t.string :content
    t.string :lookup, :limit => 32
    t.integer :weight, :default => 1
    t.integer :participants, :default => 0
    t.integer :conversions, :default => 0
  end

  add_index "alternatives", "experiment_id"
  add_index "alternatives", "lookup"  #Critical for speed, since we'll primarily be updating by that.
end
BananaSplit.cache = ActiveSupport::Cache::MemoryStore.new