text:
package org.apache.ibatis.session.defaults;

import com.fc.platform.commons.page.Page;
import com.fc.platform.commons.page.PageImpl;
import com.fc.platform.commons.page.PageRequest;
import com.fc.platform.commons.page.Pageable;
import org.apache.ibatis.binding.BindingException;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.exceptions.ExceptionFactory;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.apache.ibatis.executor.BatchResult;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.result.DefaultMapResultHandler;
import org.apache.ibatis.executor.result.DefaultResultContext;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;

/**
 *
 * The default implementation for {@link SqlSession}.
 * Note that this class is not Thread-Safe.
 *
 * @author Clinton Begin
 */
public class DefaultSqlSession implements SqlSession {

  private Configuration configuration;
  private Executor executor;

  private boolean autoCommit;
  private boolean dirty;

  public DefaultSqlSession(Configuration configuration, Executor executor, boolean autoCommit) {
    this.configuration = configuration;
    this.executor = executor;
    this.dirty = false;
    this.autoCommit = autoCommit;
  }

  public DefaultSqlSession(Configuration configuration, Executor executor) {
    this(configuration, executor, false);
  }

  @Override
  public <T> T selectOne(String statement) {
    return this.<T>selectOne(statement, null);
  }

  @Override
  public <T> T selectOne(String statement, Object parameter) {
    // Popular vote was to return null on 0 results and throw exception on too many.
    List<T> list = this.<T>selectList(statement, parameter);
    if (list.size() == 1) {
      return list.get(0);
    } else if (list.size() > 1) {
      throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
    } else {
      return null;
    }
  }

  @Override
  public <K, V> Map<K, V> selectMap(String statement, String mapKey) {
    return this.selectMap(statement, null, mapKey, RowBounds.DEFAULT);
  }

  @Override
  public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey) {
    return this.selectMap(statement, parameter, mapKey, RowBounds.DEFAULT);
  }

  @Override
  public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) {
    final List<? extends V> list = selectList(statement, parameter, rowBounds);
    final DefaultMapResultHandler<K, V> mapResultHandler = new DefaultMapResultHandler<K, V>(mapKey,
        configuration.getObjectFactory(), configuration.getObjectWrapperFactory(), configuration.getReflectorFactory());
    final DefaultResultContext<V> context = new DefaultResultContext<V>();
    for (V o : list) {
      context.nextResultObject(o);
      mapResultHandler.handleResult(context);
    }
    return mapResultHandler.getMappedResults();
  }

  @Override
  public <E> List<E> selectList(String statement) {
    return this.selectList(statement, null);
  }

  @Override
  public <E> List<E> selectList(String statement, Object parameter) {
    return this.selectList(statement, parameter, RowBounds.DEFAULT);
  }

  @Override
  public <E> Page<E> selectListPage(String statement, Object parameter) {
    List<E> objects = this.selectList(statement, parameter);
    if (parameter instanceof MapperMethod.ParamMap) {
      MapperMethod.ParamMap<Object> paramMap = (MapperMethod.ParamMap) parameter;
      Iterator<Map.Entry<String, Object>> iterator = paramMap.entrySet().iterator();
      while (iterator.hasNext()) {
        Map.Entry<String, Object> entry = iterator.next();
        if (entry.getValue() instanceof Pageable) {
          PageRequest pageRequest = (PageRequest)entry.getValue();
          return new PageImpl<E>(objects, (Pageable)pageRequest , pageRequest.getTotalElements());
        }
      }
    }
    return null;
  }

  @Override
  public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
    try {
      MappedStatement ms = configuration.getMappedStatement(statement);
      return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

  @Override
  public void select(String statement, Object parameter, ResultHandler handler) {
    select(statement, parameter, RowBounds.DEFAULT, handler);
  }

  @Override
  public void select(String statement, ResultHandler handler) {
    select(statement, null, RowBounds.DEFAULT, handler);
  }

  @Override
  public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
    try {
      MappedStatement ms = configuration.getMappedStatement(statement);
      executor.query(ms, wrapCollection(parameter), rowBounds, handler);
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

  @Override
  public int insert(String statement) {
    return insert(statement, null);
  }

  @Override
  public int insert(String statement, Object parameter) {
    return update(statement, parameter);
  }

  @Override
  public int update(String statement) {
    return update(statement, null);
  }

  @Override
  public int update(String statement, Object parameter) {
    try {
      dirty = true;
      MappedStatement ms = configuration.getMappedStatement(statement);
      return executor.update(ms, wrapCollection(parameter));
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error updating database.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

  @Override
  public int delete(String statement) {
    return update(statement, null);
  }

  @Override
  public int delete(String statement, Object parameter) {
    return update(statement, parameter);
  }

  @Override
  public void commit() {
    commit(false);
  }

  @Override
  public void commit(boolean force) {
    try {
      executor.commit(isCommitOrRollbackRequired(force));
      dirty = false;
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error committing transaction.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

  @Override
  public void rollback() {
    rollback(false);
  }

  @Override
  public void rollback(boolean force) {
    try {
      executor.rollback(isCommitOrRollbackRequired(force));
      dirty = false;
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error rolling back transaction.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

  @Override
  public List<BatchResult> flushStatements() {
    try {
      return executor.flushStatements();
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error flushing statements.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

  @Override
  public void close() {
    try {
      executor.close(isCommitOrRollbackRequired(false));
      dirty = false;
    } finally {
      ErrorContext.instance().reset();
    }
  }

  @Override
  public Configuration getConfiguration() {
    return configuration;
  }

  @Override
  public <T> T getMapper(Class<T> type) {
    return configuration.<T>getMapper(type, this);
  }

  @Override
  public Connection getConnection() {
    try {
      return executor.getTransaction().getConnection();
    } catch (SQLException e) {
      throw ExceptionFactory.wrapException("Error getting a new connection.  Cause: " + e, e);
    }
  }

  @Override
  public void clearCache() {
    executor.clearLocalCache();
  }

  private boolean isCommitOrRollbackRequired(boolean force) {
    return (!autoCommit && dirty) || force;
  }

  private Object wrapCollection(final Object object) {
    if (object instanceof Collection) {
      StrictMap<Object> map = new StrictMap<Object>();
      map.put("collection", object);
      if (object instanceof List) {
        map.put("list", object);
      }
      return map;
    } else if (object != null && object.getClass().isArray()) {
      StrictMap<Object> map = new StrictMap<Object>();
      map.put("array", object);
      return map;
    }
    return object;
  }

  public static class StrictMap<V> extends HashMap<String, V> {

    private static final long serialVersionUID = -5741767162221585340L;

    @Override
    public V get(Object key) {
      if (!super.containsKey(key)) {
        throw new BindingException("Parameter '" + key + "' not found. Available parameters are " + this.keySet());
      }
      return super.get(key);
    }

  }

}


text:
/**
 * @namespace allure
 * @global
 */

/**
 * @function allure.createStep
 *
 * @param {string} name Step name
 * @param {function} step Step represented as function
 *
 * @return {*} Whatever step has returned
 */

/**
 * @function allure.createAttachment
 *
 * @param {string} name
 * @param {string|buffer|function} content Attachment content. If you pass Buffer or String, it will be saved to file
 *   immediately. If you are passing Function, you will get decorated function and you can call it several times to
 *   trigger attachment. General purpose of the second case is an ability to create utility function to take screenshot.
 *   You can define function for you test framework only once and then call it each time you need a screenshot.
 * @param {string} [type] Attachment MIME-type. If you omit this argument we'll try to detect type automatically via
 *   {@link https://github.com/sindresorhus/file-type file-type} library
 *
 * @return {allure.createAttachment~callback|undefined}
 */

/**
 * @callback allure.createAttachment~callback
 *
 * @param {string} name Attachment name with `{index}`-format substitution points, e.g. "Screenshot of {1} taken at {0}"
 * @param {...string} parameters Substitution parameters
 */

/**
 * Sets test description.
 *
 * @function allure.description
 *
 * @param {string} description
 */

/**
 * Sets test severity, one of: blocker, critical, normal, minor, trivial. You can also use constants like
 * allure.SEVERITY.BLOCKER.
 *
 * @function allure.severity
 *
 * @param {allure.SEVERITY|string} severity
 */

/**
 * @name allure.SEVERITY
 * @enum
 * @readonly
 *
 * @property {allure.SEVERITY} BLOCKER
 * @property {allure.SEVERITY} CRITICAL
 * @property {allure.SEVERITY} NORMAL
 * @property {allure.SEVERITY} MINOR
 * @property {allure.SEVERITY} TRIVIAL
 */

/**
 * Assigns feature to test.
 *
 * @function allure.feature
 *
 * @param {string} feature
 */

/**
 * Assigns story to test.
 *
 * @function allure.story
 *
 * @param {string} story
 */

/**
 * Provides custom argument which had been used in test. Unlike other languages, javascript test methods usually doesn't
 * have special arguments (only callbacks), so developers use other way to populate parameters to test. This method is
 * to provide them to Allure.
 *
 * @function allure.addArgument
 *
 * @param {string} name
 * @param {*} value
 */

/**
 * Saves environment value. It is similar to `addArgument` method, but it is designed to store more verbose data,
 * like HTTP-links to test page or used package version.
 *
 * @function allure.addEnvironment
 *
 * @param {string} name
 * @param {string} value
 */

redpajama_set_name: RedPajamaGithub


text:
package com.navercorp.pinpoint.profiler.plugin;

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

/**
 * @author Woonduk Kang(emeroad)
 */
public class ClassNameFilterChain implements ClassNameFilter {

    private final List<ClassNameFilter> filterChain;

    public ClassNameFilterChain(List<ClassNameFilter> filterChain) {
        if (filterChain == null) {
            throw new NullPointerException("filterChain must not be null");
        }
        this.filterChain = new ArrayList<ClassNameFilter>(filterChain);
    }

    @Override
    public boolean accept(String className) {
        for (ClassNameFilter classNameFilter : this.filterChain) {
            if (!classNameFilter.accept(className)) {
                return REJECT;
            }
        }
        return ACCEPT;
    }
}


text:
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using EntityFrameworkCoreSample;

namespace EntityFrameworkCoreSample.Migrations
{
    [DbContext(typeof(DataProtectionKeyContext))]
    [Migration("20181219214311_AddDataProtectionKeys")]
    partial class AddDataProtectionKeys
    {
        protected override void BuildTargetModel(ModelBuilder modelBuilder)
        {
#pragma warning disable 612, 618
            modelBuilder
                .HasAnnotation("ProductVersion", "2.2.0")
                .HasAnnotation("Relational:MaxIdentifierLength", 128)
                .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

            modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                    b.Property<string>("FriendlyName");

                    b.Property<string>("Xml");

                    b.HasKey("Id");

                    b.ToTable("DataProtectionKeys");
                });
#pragma warning restore 612, 618
        }
    }
}


text:
package com.intellij.uiDesigner.radComponents;

import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.uiDesigner.GridChangeUtil;
import com.intellij.uiDesigner.UIFormXmlConstants;
import com.intellij.uiDesigner.XmlWriter;
import com.intellij.uiDesigner.FormEditingUtil;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.designSurface.*;
import com.intellij.util.IncorrectOperationException;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yole
 */
public abstract class RadAbstractGridLayoutManager extends RadLayoutManager {
  protected final Map<RadComponent, MyPropertyChangeListener> myListenerMap = new HashMap<RadComponent, MyPropertyChangeListener>();

  @Override
  public boolean isGrid() {
    return true;
  }

  public abstract int getGridRowCount(RadContainer container);
  public abstract int getGridColumnCount(RadContainer container);

  public int getGridCellCount(RadContainer container, boolean isRow) {
    return isRow ? getGridRowCount(container) : getGridColumnCount(container);
  }

  public int getGridRowAt(RadContainer container, int y) {
    return getGridCellAt(container, y, true);
  }

  public int getGridColumnAt(RadContainer container, int x) {
    return getGridCellAt(container, x, false);
  }

  private int getGridCellAt(final RadContainer container, final int coord, final boolean isRow) {
    int[] coords = getGridCellCoords(container, isRow);
    int[] sizes = getGridCellSizes(container, isRow);
    for (int i = 0; i < coords.length; i++) {
      if (coords[i] <= coord && coord <= coords[i] + sizes[i]) {
        return i;
      }
    }
    return -1;
  }

  public abstract int[] getHorizontalGridLines(RadContainer container);
  public abstract int[] getVerticalGridLines(RadContainer container);
  public abstract int[] getGridCellCoords(RadContainer container, boolean isRow);
  public abstract int[] getGridCellSizes(RadContainer container, boolean isRow);

  @Nullable
  public CustomPropertiesPanel getRowColumnPropertiesPanel(RadContainer container, boolean isRow, int[] selectedIndices) {
    return null;
  }

  @Nullable
  public static RadComponent getComponentAtGrid(RadContainer container, final int row, final int column) {
    // If the target cell is not empty does not allow drop.
    for(int i=0; i<container.getComponentCount(); i++){
      final RadComponent component = container.getComponent(i);
      if (component.isDragging()) {
        continue;
      }
      final GridConstraints constraints=component.getConstraints();
      if(
        constraints.getRow() <= row && row < constraints.getRow()+constraints.getRowSpan() &&
        constraints.getColumn() <= column && column < constraints.getColumn()+constraints.getColSpan()
      ){
        return component;
      }
    }
    return null;
  }

  public int getGridLineNear(RadContainer container, boolean isRow, Point pnt, int epsilon) {
    int coord = isRow ? pnt.y : pnt.x;
    int[] gridLines = isRow ? getHorizontalGridLines(container) : getVerticalGridLines(container);
    for(int col = 1; col <gridLines.length; col++) {
      if (coord < gridLines [col]) {
        if (coord - gridLines [col-1] < epsilon) {
          return col-1;
        }
        if (gridLines [col] - coord < epsilon) {
          return col;
        }
        return -1;
      }
    }
    if (coord - gridLines [gridLines.length-1] < epsilon) {
      return gridLines.length-1;
    }
    return -1;
  }

  public Rectangle getGridCellRangeRect(RadContainer container, int startRow, int startCol, int endRow, int endCol) {
    int[] xs = getGridCellCoords(container, false);
    int[] ys = getGridCellCoords(container, true);
    int[] widths = getGridCellSizes(container, false);
    int[] heights = getGridCellSizes(container, true);
    return new Rectangle(xs[startCol],
                         ys[startRow],
                         xs[endCol] + widths[endCol] - xs[startCol],
                         ys[endRow] + heights[endRow] - ys[startRow]);
  }

  public boolean canCellGrow(RadContainer container, boolean isRow, int i) {
    return false;
  }

  @Nullable
  public ActionGroup getCaptionActions() {
    return null;
  }

  public void paintCaptionDecoration(final RadContainer container, final boolean isRow, final int i, final Graphics2D g,
                                     final Rectangle rc) {
    if (canCellGrow(container, isRow, i)) {
      drawGrowMarker(isRow, g, rc);
    }
  }

  /**
   * @return the number of inserted rows or columns
   */
  public int insertGridCells(final RadContainer grid, final int cellIndex, final boolean isRow, final boolean isBefore, final boolean grow) {
    GridChangeUtil.insertRowOrColumn(grid, cellIndex, isRow, isBefore);
    return 1;
  }

  public void copyGridCells(RadContainer source, final RadContainer destination, final boolean isRow, int cellIndex, int cellCount, int targetIndex) {
    for(int i=0; i< cellCount; i++) {
      insertGridCells(destination, cellIndex, isRow, false, false);
    }
  }

  /**
   * @return the number of deleted rows or columns
   */
  public int deleteGridCells(final RadContainer grid, final int cellIndex, final boolean isRow) {
    GridChangeUtil.deleteCell(grid, cellIndex, isRow);
    return 1;
  }

  public void processCellsMoved(final RadContainer container, final boolean isRow, final int[] cells, final int targetCell) {
    GridChangeUtil.moveCells(container, isRow, cells, targetCell);
  }

  public int getGapCellCount() {
    return 0;
  }

  public int getGapCellSize(final RadContainer container, boolean isRow) {
    return 0;
  }

  public boolean isGapCell(RadContainer grid, boolean isRow, int cellIndex) {
    return false;
  }

  public int getCellIndexBase() {
    return 0;
  }

  public boolean canSpanningAllowed() {
    return true;
  }

  public boolean canResizeCells() {
    return true;
  }

  @Nullable
  public String getCellResizeTooltip(RadContainer container, boolean isRow, int cell, int newSize) {
    return null;
  }
  public void processCellResized(RadContainer container, final boolean isRow, final int cell, final int newSize) {
  }

  public abstract void copyGridSection(final RadContainer source, final RadContainer destination, final Rectangle rc);

  public LayoutManager copyLayout(LayoutManager layout, int rowDelta, int columnDelta) {
    return layout;
  }

  /**
   * Returns true if the dimensions of the grid in the container are defined by the coordinates of the components
   * in the grid (and therefore it must not be validated that an inserted component fits the grid bounds).
   */
  public boolean isGridDefinedByComponents() {
    return false;
  }

  protected static void writeGridConstraints(final XmlWriter writer, final RadComponent child) {
    // Constraints in Grid layout
    writer.startElement("grid");
    try {
      final GridConstraints constraints = child.getConstraints();
      writer.addAttribute("row",constraints.getRow());
      writer.addAttribute("column",constraints.getColumn());
      writer.addAttribute("row-span",constraints.getRowSpan());
      writer.addAttribute("col-span",constraints.getColSpan());
      writer.addAttribute("vsize-policy",constraints.getVSizePolicy());
      writer.addAttribute("hsize-policy",constraints.getHSizePolicy());
      writer.addAttribute("anchor",constraints.getAnchor());
      writer.addAttribute("fill",constraints.getFill());
      writer.addAttribute(UIFormXmlConstants.ATTRIBUTE_INDENT, constraints.getIndent());
      writer.addAttribute(UIFormXmlConstants.ATTRIBUTE_USE_PARENT_LAYOUT, constraints.isUseParentLayout());

      // preferred size
      writer.writeDimension(constraints.myMinimumSize,"minimum-size");
      writer.writeDimension(constraints.myPreferredSize,"preferred-size");
      writer.writeDimension(constraints.myMaximumSize,"maximum-size");
    } finally {
      writer.endElement(); // grid
    }
  }

  @Override @Nonnull
  public ComponentDropLocation getDropLocation(RadContainer container, @Nullable final Point location) {
    if (container.getGridRowCount() == 1 && container.getGridColumnCount() == 1 &&
        getComponentAtGrid(container, 0, 0) == null) {
      final Rectangle rc = getGridCellRangeRect(container, 0, 0, 0, 0);
      if (location == null) {
        return new FirstComponentInsertLocation(container, rc, 0, 0);
      }
      return new FirstComponentInsertLocation(container, location, rc);
    }

    if (location == null) {
      if (getComponentAtGrid(container, 0, 0) == null) {
        return new GridDropLocation(container, 0, 0);
      }
      return new GridInsertLocation(container, getLastNonSpacerRow(container), 0, GridInsertMode.RowAfter);
    }

    int[] xs = getGridCellCoords(container, false);
    int[] ys = getGridCellCoords(container, true);
    int[] widths = getGridCellSizes(container, false);
    int[] heights = getGridCellSizes(container, true);

    int[] horzGridLines = getHorizontalGridLines(container);
    int[] vertGridLines = getVerticalGridLines(container);

    int row=ys.length-1;
    int col=xs.length-1;
    for(int i=0; i<xs.length; i++) {
      if (location.x < xs[i] + widths[i]) {
        col=i;
        break;
      }
    }
    for(int i=0; i<ys.length; i++) {
      if (location.getY() < ys [i]+heights [i]) {
        row=i;
        break;
      }
    }

    GridInsertMode mode = null;

    int EPSILON = 4;
    int dy = (int)(location.getY() - ys [row]);
    if (dy < EPSILON) {
      mode = GridInsertMode.RowBefore;
    }
    else if (heights [row] - dy < EPSILON) {
      mode = GridInsertMode.RowAfter;
    }

    int dx = location.x - xs[col];
    if (dx < EPSILON) {
      mode = GridInsertMode.ColumnBefore;
    }
    else if (widths [col] - dx < EPSILON) {
      mode = GridInsertMode.ColumnAfter;
    }

    boolean spanInsertMode = canSpanningAllowed() && mode == null;
    boolean normalize = true;
    final int cellWidth = vertGridLines[col + 1] - vertGridLines[col];
    final int cellHeight = horzGridLines[row + 1] - horzGridLines[row];
    if (mode == null) {
      RadComponent component = getComponentAtGrid(container, row, col);
      if (component != null) {
        Rectangle rc = component.getBounds();
        rc.translate(-xs [col], -ys [row]);

        int right = rc.x + rc.width + GridInsertLocation.INSERT_RECT_MIN_SIZE;
        int bottom = rc.y + rc.height + GridInsertLocation.INSERT_RECT_MIN_SIZE;

        if (dy < rc.y - GridInsertLocation.INSERT_RECT_MIN_SIZE) {
          mode = GridInsertMode.RowBefore;
        }
        else if (dy > bottom && dy < cellHeight) {
          mode = GridInsertMode.RowAfter;
        }
        if (dx < rc.x - GridInsertLocation.INSERT_RECT_MIN_SIZE) {
          mode = GridInsertMode.ColumnBefore;
        }
        else if (dx > right && dx < cellWidth) {
          mode = GridInsertMode.ColumnAfter;
        }

        normalize = false;
      }
    }

    if (mode != null) {
      GridInsertLocation dropLocation = new GridInsertLocation(container, row, col, mode);
      dropLocation.setSpanInsertMode(spanInsertMode);
      return normalize ? dropLocation.normalize() : dropLocation;
    }
    if (getComponentAtGrid(container, row, col) instanceof RadVSpacer ||
        getComponentAtGrid(container, row, col) instanceof RadHSpacer) {
      return new GridReplaceDropLocation(container, row, col);
    }
    return new GridDropLocation(container, row, col);
  }

  private int getLastNonSpacerRow(final RadContainer container) {
    int lastRow = getGridRowCount(container)-1;
    for(int col=0; col<getGridColumnCount(container); col++) {
      RadComponent c = getComponentAtGrid(container, lastRow, col);
      if (c != null && !(c instanceof RadHSpacer) && !(c instanceof RadVSpacer)) {
        return lastRow;
      }
    }
    return lastRow-1;
  }

  protected static void drawGrowMarker(final boolean isRow, final Graphics2D g2d, final Rectangle rc) {
    g2d.setColor(Color.BLACK);
    if (!isRow) {
      int maxX = (int) rc.getMaxX();
      int midY = (int) rc.getCenterY()+3;
      final int xStart = Math.max(maxX - 10, rc.x + 2);
      final int xEnd = maxX - 2;
      g2d.drawLine(xStart, midY, xEnd, midY);
      g2d.drawLine(xStart, midY, xStart+2, midY-2);
      g2d.drawLine(xStart, midY, xStart+2, midY+2);
      g2d.drawLine(xEnd, midY, xEnd-2, midY-2);
      g2d.drawLine(xEnd, midY, xEnd-2, midY+2);
    }
    else {
      int maxY = (int) rc.getMaxY();
      int midX = (int) rc.getCenterX()+3;
      final int yStart = Math.max(maxY - 10, rc.y + 2);
      final int yEnd = maxY - 2;
      g2d.drawLine(midX, yStart, midX, yEnd);
      g2d.drawLine(midX, yStart, midX-2, yStart+2);
      g2d.drawLine(midX, yStart, midX+2, yStart+2);
      g2d.drawLine(midX, yEnd, midX-2, yEnd-2);
      g2d.drawLine(midX, yEnd, midX+2, yEnd-2);
    }
  }

  @Override
  public void changeContainerLayout(RadContainer container) throws IncorrectOperationException {
    if (container.getLayoutManager().isGrid()) {
      RadAbstractGridLayoutManager grid = container.getGridLayoutManager();
      List<Boolean> canRowsGrow = collectCanCellsGrow(grid, container, true);
      List<Boolean> canColumnsGrow = collectCanCellsGrow(grid, container, false);
      List<RadComponent> contents = collectComponents(container);

      changeLayoutFromGrid(container, contents, canRowsGrow, canColumnsGrow);

      int oldGapMultiplier = grid.getGapCellCount()+1;
      int gapMultiplier = getGapCellCount()+1;
      for(RadComponent c: contents) {
        GridConstraints gc = c.getConstraints();
        gc.setRow(gc.getRow() * gapMultiplier / oldGapMultiplier);
        gc.setColumn(gc.getColumn() * gapMultiplier / oldGapMultiplier);
        container.addComponent(c);
      }
    }
    else if (container.getLayoutManager().isIndexed()) {
      List<RadComponent> components = collectComponents(container);
      changeLayoutFromIndexed(container, components);

      int gapMultiplier = getGapCellCount()+1;
      for(int i=0; i<components.size(); i++) {
        GridConstraints gc = components.get(i).getConstraints();
        gc.setRow(0);
        gc.setColumn(i*gapMultiplier);
        gc.setRowSpan(1);
        gc.setColSpan(1);
        container.addComponent(components.get(i));
      }
    }
    else if (container.getComponentCount() == 0) {
      container.setLayoutManager(this);
    }
    else {
      throw new IncorrectOperationException("Cannot change from " + container.getLayout() + " to grid layout");
    }
  }

  protected void changeLayoutFromGrid(final RadContainer container, final List<RadComponent> contents, final List<Boolean> canRowsGrow,
                                    final List<Boolean> canColumnsGrow) {
    container.setLayoutManager(this);
  }

  protected void changeLayoutFromIndexed(final RadContainer container, final List<RadComponent> components) {
    container.setLayoutManager(this);
  }

  private static List<Boolean> collectCanCellsGrow(final RadAbstractGridLayoutManager grid, final RadContainer container, final boolean isRow) {
    List<Boolean> result = new ArrayList<Boolean>();
    for(int i=0; i<grid.getGridCellCount(container, isRow); i++) {
      if (!grid.isGapCell(container, isRow, i)) {
        result.add(grid.canCellGrow(container, isRow, i));
      }
    }
    return result;
  }

  private static List<RadComponent> collectComponents(final RadContainer container) {
    List<RadComponent> contents = new ArrayList<RadComponent>();
    for(int i=container.getComponentCount()-1; i >= 0; i--) {
      final RadComponent component = container.getComponent(i);
      if (!(component instanceof RadHSpacer) && !(component instanceof RadVSpacer)) {
        contents.add(0, component);
      }
      container.removeComponent(component);
    }
    return contents;
  }

  public boolean canMoveComponent(RadComponent c, int rowDelta, int colDelta, final int rowSpanDelta, final int colSpanDelta) {
    final int newRow = getNewRow(c, rowDelta);
    final int newCol = getNewColumn(c, colDelta);
    final int newRowSpan = getNewRowSpan(c, rowSpanDelta);
    final int newColSpan = getNewColSpan(c, colSpanDelta);
    if (newRow < 0 || newCol < 0 || newRowSpan < 1 || newColSpan < 1 ||
        newRow + newRowSpan > c.getParent().getGridRowCount() ||
        newCol + newColSpan > c.getParent().getGridColumnCount()) {
      return false;
    }
    c.setDragging(true);
    final RadComponent overlap = c.getParent().findComponentInRect(newRow, newCol, newRowSpan, newColSpan);
    c.setDragging(false);
    if (overlap != null) {
      return false;
    }
    return true;
  }

  private static int getNewRow(final RadComponent c, final int rowDelta) {
    return FormEditingUtil.adjustForGap(c.getParent(), c.getConstraints().getRow() + rowDelta, true, rowDelta);
  }

  private static int getNewColumn(final RadComponent c, final int colDelta) {
    return FormEditingUtil.adjustForGap(c.getParent(), c.getConstraints().getColumn() + colDelta, false, colDelta);
  }

  private static int getNewRowSpan(final RadComponent c, final int rowSpanDelta) {
    int gapCount = c.getParent().getGridLayoutManager().getGapCellCount();
    return c.getConstraints().getRowSpan() + rowSpanDelta * (gapCount+1);
  }

  private static int getNewColSpan(final RadComponent c, final int colSpanDelta) {
    int gapCount = c.getParent().getGridLayoutManager().getGapCellCount();
    return c.getConstraints().getColSpan() + colSpanDelta * (gapCount+1);
  }

  @Override
  public void moveComponent(RadComponent c, int rowDelta, int colDelta, final int rowSpanDelta, final int colSpanDelta) {
    GridConstraints constraints = c.getConstraints();
    GridConstraints oldConstraints = (GridConstraints)constraints.clone();
    constraints.setRow(getNewRow(c, rowDelta));
    constraints.setColumn(getNewColumn(c, colDelta));
    constraints.setRowSpan(getNewRowSpan(c, rowSpanDelta));
    constraints.setColSpan(getNewColSpan(c, colSpanDelta));
    c.fireConstraintsChanged(oldConstraints);
  }

  public int getMinCellCount() {
    return 1;
  }

  @Override
  public void addComponentToContainer(RadContainer container, RadComponent component, int index) {
    MyPropertyChangeListener listener = new MyPropertyChangeListener(component);
    myListenerMap.put(component, listener);
    component.addPropertyChangeListener(listener);
  }

  @Override
  public void removeComponentFromContainer(final RadContainer container, final RadComponent component) {
    final MyPropertyChangeListener listener = myListenerMap.get(component);
    if (listener != null) {
      component.removePropertyChangeListener(listener);
      myListenerMap.remove(component);
    }
    super.removeComponentFromContainer(container, component);
  }

  protected void updateConstraints(RadComponent component) {
    component.getParent().revalidate();
  }

  private class MyPropertyChangeListener implements PropertyChangeListener {
    private final RadComponent myComponent;

    public MyPropertyChangeListener(final RadComponent component) {
      myComponent = component;
    }

    public void propertyChange(PropertyChangeEvent evt) {
      if (evt.getPropertyName().equals(RadComponent.PROP_CONSTRAINTS)) {
        updateConstraints(myComponent);
      }
    }
  }
}


text:
<?php

namespace Sylius\Bundle\ResourceBundle\Controller;

use Sylius\Component\Resource\Model\ResourceInterface;
use Sylius\Component\Resource\ResourceActions;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\RouterInterface;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
class RedirectHandler implements RedirectHandlerInterface
{
    /**
     * @var RouterInterface
     */
    private $router;

    /**
     * @param RouterInterface $router
     */
    public function __construct(RouterInterface $router)
    {
        $this->router = $router;
    }

    /**
     * {@inheritdoc}
     */
    public function redirectToResource(RequestConfiguration $configuration, ResourceInterface $resource)
    {
        $routes = $this->router->getRouteCollection();
        $redirectRouteName = $configuration->getRedirectRoute(ResourceActions::SHOW);

        if (null === $routes->get($redirectRouteName)) {
            $redirectRouteName = $configuration->getRedirectRoute(ResourceActions::INDEX);
        }

        return $this->redirectToRoute(
            $configuration,
            $redirectRouteName,
            $configuration->getRedirectParameters($resource)
        );
    }

    /**
     * {@inheritdoc}
     */
    public function redirectToIndex(RequestConfiguration $configuration, ResourceInterface $resource = null)
    {
        return $this->redirectToRoute(
            $configuration,
            $configuration->getRedirectRoute('index'),
            $configuration->getRedirectParameters($resource)
        );
    }

    /**
     * {@inheritdoc}
     */
    public function redirectToRoute(RequestConfiguration $configuration, $route, array $parameters = [])
    {
        if ('referer' === $route) {
            return $this->redirectToReferer($configuration);
        }

        return $this->redirect($configuration, $this->router->generate($route, $parameters));
    }

    /**
     * {@inheritdoc}
     */
    public function redirect(RequestConfiguration $configuration, $url, $status = 302)
    {
        if ($configuration->isHeaderRedirection()) {
            return new Response('', 200, [
                'X-SYLIUS-LOCATION' => $url.$configuration->getRedirectHash(),
            ]);
        }

        return new RedirectResponse($url.$configuration->getRedirectHash(), $status);
    }

    /**
     * {@inheritdoc}
     */
    public function redirectToReferer(RequestConfiguration $configuration)
    {
        return $this->redirect($configuration, $configuration->getRedirectReferer());
    }
}


text:
/* https://github.com/tlseabra */

/* Heavily based on http://www.graemeboy.com/string-permutations */
function strPerm(rest, soFar) {
    var next,
        remaining,
        i;

    if (rest == "")
        console.log(soFar);

    else {
        for (i = 0; i < rest.length; i++) {
            remaining = rest.substr(0,i) + rest.substr(i+1,rest.length-1);
            next = soFar + rest[i];

            strPerm(remaining, next);     //recursion is weird
        }
    }
}


text:
package io.undertow.server.handlers.proxy.mod_cluster;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * {@code VHost}
 *

 * This class is a representation of the virtual host
 *

 * Created on Jun 12, 2012 at 3:33:21 PM
 *
 * @author Nabil Benothman
 */
public class VHost {

    private final String name;
    private final String JVMRoute;
    private long id;

    /**
     * The list of aliases
     */
    private final List<String> aliases;

    /**
     * Create a new instance of {@code VirtualHost}
     */
     VHost(VHostBuilder b) {
        this.name = b.name;
        this.JVMRoute = b.JVMRoute;
        this.aliases = Collections.unmodifiableList(new ArrayList<String>(b.aliases));
    }

    /**
     * Getter for aliases list
     *
     * @return the list of aliases
     */
    public List<String> getAliases() {
        return aliases;
    }

    /**
     * Getter for name
     *
     * @return the name
     */
    public String getName() {
        return this.name;
    }

    public String getJVMRoute() {
        return JVMRoute;
    }
    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public static VHostBuilder builder() {
        return new VHostBuilder();
    }

    public static class VHostBuilder {

        private String name;
        private String JVMRoute;
        private long id;

        /**
         * The list of aliases
         */
        private final List<String> aliases = new ArrayList<String>();

        VHostBuilder() {

        }

        public void setName(String name) {
            this.name = name;
        }

        public void setJVMRoute(String JVMRoute) {
            this.JVMRoute = JVMRoute;
        }

        public void setId(long id) {
            this.id = id;
        }

        /**
         * Add the collection of aliases to the list
         *
         * @param c
         *            the collection to add
         * @return <tt>true</tt> if the aliases was added successfully else
         *         <tt>false</tt>
         */
        public boolean addAliases(Collection<String> c) {
            return this.aliases.addAll(c);
        }

        /**
         * Remove the specified alias from the list of aliases
         *
         * @param alias
         *            the alias to be removed
         * @return <tt>true</tt> if the {@code alias} was removed else
         *         <tt>false</tt>
         */
        public boolean removeAlias(String alias) {
            return this.aliases.remove(alias);
        }

        public VHost build() {
            return new VHost(this);
        }
    }

}


text:
==========================================
Contributing to EMC VMAX SMI-S Library
==========================================

Introduction
============
Contributions are developed using test-driven development, code reviews and per-issue branches. Each unit of work is defined in an issue in the issue tracker and developed on a branch. Code is written using test-driven development. The issue is closed by merging the branch (via a GitHub pull request). Before a branch is merged it must pass code review.

- The code reviewer ensures that the pull request:
- Follows the coding standard (Python's PEP 8).
- Includes appropriate documentation.
- Has full test coverage (unit tests and functional tests).
- Resolves the issue.
- Talk to Us

Have questions or need help?
============================
You can open an account there to file issues, but we're also happy to accept Github Issues with feature requests or bug reports. You can also join us on the #emccorp channel on the irc.freenode.net IRC network.


text:
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;

import com.sun.jdmk.comm.HtmlAdaptorServer;

public class HelloDynamicAgent {
	private static String DOMAIN = "MyDynamicMBean";
	/**
	 * @param args
	 * @throws NullPointerException
	 * @throws MalformedObjectNameException
	 * @throws NotCompliantMBeanException
	 * @throws MBeanRegistrationException
	 * @throws InstanceAlreadyExistsException
	 */
	public static void main(String[] args) throws MalformedObjectNameException, NullPointerException, InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException {
		//´´½¨Ò»¸öMBean·þÎñ¶ÔÏó£¬DOMAINÀàËÆÓÚjavaÀïÃæµÄ¹«¹²package²¿·Ö
		MBeanServer server = MBeanServerFactory.createMBeanServer(DOMAIN);
		//´´½¨DynamicMBean¶ÔÏó
		HelloDynamic hello = new HelloDynamic();
		//´´½¨Ò»¸öwebÊÊÅäÆ÷·þÎñÆ÷£¬±íʾÎÒÃÇMBean·þÎñͨ¹ýwebÐÎʽÀ´Ìṩ¸øÓû§¹ÜÀí
		HtmlAdaptorServer htmlserver = new HtmlAdaptorServer();
		htmlserver.setPort(9999);
		//ObjctName¶ÔÏóÀàËÆÓÚÍêÕûµÄpackage
		ObjectName helloname = new ObjectName(DOMAIN + ":name=HelloDynamic");
		ObjectName htmlname = new ObjectName(DOMAIN + ":name=HtmlAdaptor");
		server.registerMBean(hello, helloname);
		server.registerMBean(htmlserver, htmlname);

		htmlserver.start();
	}
/**
 *
ÔËÐгÌÐò£¬´ò¿ªä¯ÀÀÆ÷£¬ÊäÈëhttp://localhost:9999£¬
¼´¿É·ÃÎʹÜÀíÒ³Ã棬ҳÃæÏ·½µã»÷name=HelloDynamic£¬
½øÈëMBean View£¬È»ºóÔÙ²Ù×÷Öеã»÷print·½·¨£¬Ôٴλص½MBean
ViewÒ³ÃæÄã»á·¢ÏÖ¶àÁËÒ»¸ödynamicPrint·½·¨£¬Õâ¸ö·½·¨¾ÍÊÇÎÒÃǽøÐÐprint²Ù×÷ʱ¶¯Ì¬Éú³ÉµÄ¡£
 */
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using DataAccessLayer;
using Newtonsoft.Json;

namespace ConcreteDataStore
{
    /// Abstraction of an OData association value.
    internal class ODataAssociationValue
    {
        /// Lookup table of indexes into the odata association value.
        private readonly Dictionary<string, int> odataAssociationValueLU = new Dictionary<string, int>
            {
                { "TargetEntityId", 0 },
                { "TargetExternalType", 1 },
                { "ExternalName", 2 }
            };

        /// The delimiter for association value fields.
        private const string ODataValueDelimiter = "||";

        /// The delimiter between value groups in an association collection.
        private const string ODataValueCollectionDelimiter = "}{";

        /// The field strings.
        private readonly string[] valueFields;

        /// The raw odata value.
        private readonly string odataValueJson;

        /// Initializes a new instance of the <see cref="ODataAssociationValue"/> class.
        /// <param name="odataValue">The odata value.</param>
        public ODataAssociationValue(string odataValue)
        {
            this.odataValueJson = odataValue;

            // This is safe even if it is json. We won't be using this.valueFields in that scenario
            this.valueFields = odataValue.Split(new[] { ODataValueDelimiter }, StringSplitOptions.None);
        }

        /// Gets TargetEntityId.
        public EntityId TargetEntityId
        {
            get
            {
                var id = this.TryExtractLegacyValueField("TargetEntityId");
                return id != null ? new EntityId(id) : null;
            }
        }

        /// Gets TargetExternalType.
        public string TargetExternalType
        {
            get { return this.TryExtractLegacyValueField("TargetExternalType"); }
        }

        /// Gets ExternalName.
        public string ExternalName
        {
            get { return this.TryExtractLegacyValueField("ExternalName"); }
        }

        /// Gets TargetEntityIds.
        public EntityId[] TargetEntityIds
        {
            get
            {
                return this.TryExtractTargetIds();
            }
        }

        /// Serialize an association group target id list to an odata value.
        /// <param name="targetEntityIds">The target id's in the association group.</param>
        /// <returns>odata value.</returns>
        public static string SerializeAssociationGroup(EntityId[] targetEntityIds)
        {
            var idStrings = targetEntityIds.Select(id => id.ToString()).ToArray();
            return JsonConvert.SerializeObject(idStrings);
        }

        /// Split an odata value representing an association collection into individual association values.
        /// <param name="odataValue">The odata collection value.</param>
        /// <returns>A list of individual association values</returns>
        public static IList<string> SplitCollectionValues(string odataValue)
        {
            return odataValue.Split(new[] { ODataValueCollectionDelimiter }, StringSplitOptions.None).ToList();
        }

        /// Extract TargetIds from json in odata value.
        /// <returns>Id array or null if fail.</returns>
        [SuppressMessage("Microsoft.Design", "CA1031", Justification = "Try pattern.")]
        private EntityId[] TryExtractTargetIds()
        {
            try
            {
                return JsonConvert.DeserializeObject<string[]>(this.odataValueJson)
                    .Select(id => new EntityId(id)).ToArray();
            }
            catch (Exception)
            {
            }

            return null;
        }

        /// Extract fields by name from legacy associations.
        /// <param name="valueName">The name of the field.</param>
        /// <returns>The field value or null if fail.</returns>
        [SuppressMessage("Microsoft.Design", "CA1031", Justification = "Try pattern.")]
        private string TryExtractLegacyValueField(string valueName)
        {
            try
            {
                // There is no supported scenario where a legacy association could have only one field
                if (this.valueFields.Length <= 1)
                {
                    return null;
                }

                return this.valueFields[this.odataAssociationValueLU[valueName]];
            }
            catch (Exception)
            {
            }

            return null;
        }
    }
}


text:
#ifndef CONNECTION_H_
#define CONNECTION_H_

#include <QObject>
#include <QTcpSocket>
#include <bb/cascades/Application>

namespace truphone
{
namespace test
{
namespace cascades
{
    /*!
     * \brief The Connection class is a wrapper around the clients connection
     * to the server and listens for requests from the client, looks up the
     * command and executes it.
     *
     * @since test-cascades 1.0.0
     */
    class Connection : public QObject
    {
        Q_OBJECT
        public:
            /*!
             * \brief Connection Create a new connection
             *
             * \param clientSocket The TCP socket associated with the client
             * \param parent The parent object
             *
             * @since test-cascades 1.0.0
             */
            Connection(
                    QTcpSocket * const clientSocket,
                    QObject* parent = 0);
            /*!
             * \brief ~Connection Destroy the connection
             *
             * @since test-cascades 1.0.0
             */
            ~Connection();
            /*!
             * \brief close Closes the connection
             *
             * @since test-cascades 1.0.0
             */
            void close()
            {
                if (this->socket)
                {
                    this->socket->close();
                }
            }
            /*!
             * \brief write Write data out on the connection
             *
             * \param data The data you wish to send
             * \return The amount of data sent in bytes
             *
             * @since test-cascades 1.1.0
             */
            qint64 write(const QString& data);
            /*!
             * \brief flush Flush the socket
             *
             * \return
             *
             * @since test-cascades 1.0.1
             */
            bool flush(void);

        signals:
            /*!
             * \brief packetReceived Signal emitted when a new packet is received
             *
             * \param connection The connection that received the packet
             * \param packet The packet itself
             *
             * @since test-cascades 1.0.1
             */
            void packetReceived(Connection* connection, const QString& packet);
        protected:
        private:
            /*!
             * \brief socket Client socket
             */
            QTcpSocket * const socket;
        Q_SIGNALS:
            /*!
             * \brief disconnected Signal emitted when the client disconnects
             *
             * \param connection The connection that has terminated
             *
             * @since test-cascades 1.0.0
             */
            void disconnected(Connection * const connection);
        private slots:
            /*!
             * \brief connectionDied Slot called from the socket when it is terminated
             *
             * @since test-cascades 1.0.0
             */
            void connectionDied(void);
            /*!
             * \brief processPacket Slot called from the socket when new data arrives
             *
             * @since test-cascades 1.0.0
             */
            void processPacket(void);
            /*!
             * \brief write Write data out on the connection
             *
             * \param data The data you wish to send
             * \return The amount of data sent in bytes
             *
             * @since test-cascades 1.0.1
             */
            qint64 write(const char * const data);
    };
}  // namespace cascades
}  // namespace test
}  // namespace truphone

#endif  // CONNECTION_H_


text:
/*!
 * \file bound_deducer.cc
 * \brief Utility to deduce bound of expression
 */
#include <tvm/runtime/registry.h>
#include <tvm/te/tensor.h>
#include <tvm/tir/expr.h>
#include <tvm/tir/stmt_functor.h>

#include <unordered_map>
#include <unordered_set>

namespace tvm {
namespace arith {

using namespace tir;

// Find Read region of the tensor in the stmt.
class BufferTouchedDomain final : public StmtExprVisitor {
 public:
  BufferTouchedDomain(const Buffer& buffer, bool consider_loads, bool consider_stores)
      : buffer_(buffer), consider_loads_(consider_loads), consider_stores_(consider_stores) {}

  Region Find(const Stmt& stmt) {
    operator()(stmt);
    Region ret;
    Range none;
    for (size_t i = 0; i < bounds_.size(); ++i) {
      ret.push_back(arith::Union(bounds_[i]).CoverRange(none));
    }
    return ret;
  }

  void VisitStmt_(const ForNode* op) final {
    const VarNode* var = op->loop_var.get();
    dom_map_[var] = IntSet::FromRange(Range::FromMinExtent(op->min, op->extent));
    StmtExprVisitor::VisitStmt_(op);
    dom_map_.erase(var);
  }

  void VisitStmt_(const LetStmtNode* op) final {
    dom_map_[op->var.get()] = arith::EvalSet(op->value, dom_map_);
    StmtExprVisitor::VisitStmt_(op);
    dom_map_.erase(op->var.get());
  }

  /* TODO: Thread extent unitest not generated.*/
  void VisitStmt_(const AttrStmtNode* op) final {
    if (op->attr_key == tir::attr::thread_extent) {
      const IterVarNode* thread_axis = op->node.as<IterVarNode>();
      ICHECK(thread_axis);
      const VarNode* var = thread_axis->var.get();
      dom_map_[var] = IntSet::FromRange(Range(make_zero(op->value.dtype()), op->value));
      StmtExprVisitor::VisitStmt_(op);
      dom_map_.erase(var);
    } else {
      StmtExprVisitor::VisitStmt_(op);
    }
  }

  void VisitExpr_(const BufferLoadNode* op) final {
    if (consider_loads_ && buffer_.same_as(op->buffer)) {
      Touch(op->indices);
    }
    StmtExprVisitor::VisitExpr_(op);
  }

  void VisitStmt_(const BufferStoreNode* op) final {
    if (consider_stores_ && buffer_.same_as(op->buffer)) {
      Touch(op->indices);
    }
    StmtExprVisitor::VisitStmt_(op);
  }

 private:
  void Touch(const Array<PrimExpr>& args) {
    if (args.size() > bounds_.size()) {
      bounds_.resize(args.size());
    }
    for (size_t i = 0; i < args.size(); ++i) {
      bounds_[i].emplace_back(EvalSet(args[i], dom_map_));
    }
  }

  const Buffer& buffer_;
  bool consider_loads_, consider_stores_;
  std::vector<std::vector<IntSet> > bounds_;
  std::unordered_map<const VarNode*, IntSet> dom_map_;
};

Region DomainTouched(const Stmt& stmt, const Buffer& buffer, bool consider_loads,
                     bool consider_stores) {
  return BufferTouchedDomain(buffer, consider_loads, consider_stores).Find(stmt);
}

TVM_REGISTER_GLOBAL("arith.DomainTouched").set_body_typed(DomainTouched);

}  // namespace arith
}  // namespace tvm


text:
class Treetop::Runtime::SyntaxNode
  def cascade(env)
    elements.each { |e| e.build env if e.respond_to? :build }  if elements.is_a? Array
    env
  end

  def build(env)
    cascade env
  end
end

class Treetop::Runtime::CompiledParser
  def failure_message
    o = lambda {|i, *args| i }
    return nil unless (tf = terminal_failures) && tf.size > 0
    msg = "on line #{failure_line}: expected " + (
      tf.size == 1 ?
        o[tf[0].expected_string, :yellow] :
        "one of #{o[tf.map {|f| f.expected_string }.uniq * ' ', :yellow]}"
    )
    f = input[failure_index]
    got = case f
      when "\n" then o['\n',  :cyan]
      when nil  then o["EOF", :cyan]
      when ' '  then o["white-space", :cyan]
      else           o[f.chr, :yellow]
    end
    msg += " got #{got}" # after:\n\n#{input[index...failure_index]}\n"
  end
end


text:
package jp.eisbahn.oauth2.server.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import org.apache.commons.codec.binary.Base64;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * This class provides some utility methods.
 *
 * @author Yoichiro Tanaka
 *
 */
public class Util {

	/**
	 * Decode the URL encoded string.
	 * @param source The URL encoded string.
	 * @return The decoded original string.
	 */
	public static String decodeParam(String source) {
		try {
			return URLDecoder.decode(source, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new IllegalStateException(e);
		}
	}

	/**
	 * Decode the BASE64 encoded string.
	 * @param source The BASE64 string.
	 * @return The decoded original string.
	 */
	public static String decodeBase64(String source) {
		try {
			return new String(Base64.decodeBase64(source), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new IllegalStateException(e);
		}
	}

	/**
	 * Encode the object to JSON format string.
	 * @param source The object that you want to change to JSON string.
	 * @return The JSON encoded string.
	 * @throws IllegalStateException If the translation failed.
	 */
	public static String toJson(Object source) {
		try {
			ObjectMapper mapper = new ObjectMapper();
			return mapper.writeValueAsString(source);
		} catch (JsonGenerationException e) {
			throw new IllegalStateException(e);
		} catch (JsonMappingException e) {
			throw new IllegalStateException(e);
		} catch (IOException e) {
			throw new IllegalStateException(e);
		}
	}

}


text:
package com.farmerbb.taskbar.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import com.farmerbb.taskbar.activity.HomeActivity;
import com.farmerbb.taskbar.util.U;

import static com.farmerbb.taskbar.util.Constants.*;

public class EnableHomeReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        SharedPreferences pref = U.getSharedPreferences(context);
        if(intent.hasExtra(EXTRA_SECONDSCREEN) && pref.getBoolean(PREF_LAUNCHER, false))
            pref.edit().putBoolean(PREF_SKIP_DISABLE_HOME_RECEIVER, true).apply();
        else if(U.canDrawOverlays(context)) {
            SharedPreferences.Editor editor = pref.edit();
            editor.putBoolean(PREF_LAUNCHER, true);
            editor.apply();

            U.setComponentEnabled(context, HomeActivity.class, true);
            U.sendBroadcast(context, ACTION_LAUNCHER_PREF_CHANGED);
        }
    }
}


text:
const redis = require('redis');
const client = redis.createClient();

class Publisher {
  constructor(queueName) {
    this.queueName = queueName;
  }

  enqueue(vaule) {
    client.lpush(this.queueName, value);
  }
}

module.exports = Publisher;


text:
layout: post
title: Blog 9
---

### 1. What is the purpose of metadata? What are the categories of metadata?
Metadata is the word used to describe data that exists to describe other data. However it's meaning can also extend to describe data that is associated with other data.

Metadata comes in many categories including:

* Structural
    - Data that describes the structure of other data
        + file formats
        + file sizes
* Descriptive data
    - Data that enables the identification of other data through description
        + author
        + date of creation
        + date of modification
        + title
        + genre
* Administrative data
    - Describes data with descriptions relevant to administration
        + date of modification
        + modifier
        + owner
        + copyright agreement

---

### 2. What is a controlled vocabulary? How is a controlled vocabulary beneficial to a web site and/or organisation?
A controlled vocabulary is a list of words that are relevant within your context. These benefit websites and organizations by offering consistency. They also make it possible to relate terms and improve discover-ability.

---

### 3. List the four main types of controlled vocabularies.

* Synonym rings.
* Classification Schemes.
* Thesauri.
* Authority files.

---

### 4. What is the purpose of a synonym ring? Give examples of terms that would be considered equivalent under a synonym ring. What might happened during a search if you didn't use a synonym ring? (Give an example.)
A synonym ring is a set of words that are considered equivalent. Synonym rings can contain exclusively synonyms or can additionally contain common misspellings of words (although this is usually handled through other means such as finding all mutations of a word on a Directed Acyclic Word Graph within a certain Levenshtein distance).

* Truck
* Ute
* Lorry
* Pickup

If a search were to exclude the use of a synonym ring an Englishman who comes overseas to Australia may search for a _Lorry_ on an Australian car website but be returned no results. As where with a synonym ring active he may be returned the results he was looking for despite the unfamiliar wording.

---

### 5. What is the purpose of an authority file? Describe how an authority file can educate users during search.
An authority file is a file that lists preferred terms for a or a group of other terms. They are similar to synonym rings as the terms in the group should be considered equivalent to each other. However, in a authority file there is a single term that is preferred over the others. The use of authority files typically results in the users search term being substituted with the preferred term and can improve the quality of results. This technique can even educate the user occasionally with the _proper_ term for what they are after.

---

### 6. Create an authority file for abbreviations of the Australian states and territories.

```
QLD -> Queensland
NSW -> New South Wales
SA  -> South Australia
ACT -> Australian Capitol Territory
VIC -> Victoria
WA  -> Western Australia
NT  -> Northern Territory
TAS -> Tasmania
```

---

### 7. Describe the purpose of a classification scheme. How does a web site benefit from a classification scheme?
Classification Schemes organize terms into hierarchies. These allows the classification of terms into groupings, these groupings can then also be classified into groupings. This allows tree style hierarchies to form linking terms to one another.

---

### 8. Create a classification scheme for several major dog breeds based on whether the dog is toy, small, medium, large, or giant.

    Toy     |   Small       |   Medium   |   Large   |   Giant
------------|---------------|------------|-----------|----------------
Toy Poodle  | Jack Russell  | Beagle     | Labrador  | Great Dane
Chihuahua   | Pomeranian    | Corgi      | Greyhound | Tibetan Mastiff

---

### 11. What topics would the following codes retrieve under Dewey Decimal Classification:

* 025.524
    - Library Operations
* 787.87092
    - Stringed Instruments _(Chordophones)_
* 641.623
    - Food & Drink
* 634.772
    - Orchards, fruits, forestry
* 522.29
    - Techniques, equipment, materials

---

### 16. What is the purpose of thesauri? How is a thesaurus beneficial to searching on a web site?
Thesauri represent networks of linked terms. Synonyms, homonyms, broader/narrower and related terms may be included. They help users get relevant results by including terms related to the users term.

---

### 19. Consider the preferred term _car_. List a variant term(s), broader term, narrower term, and related term(s).

* Variant
    - Automobile
* Broader
    - Vehicle
    - Transport
* Narrower
    - BMW
* Related
    - Tires

---

### 20. Consider the preferred term _sword_. List a variant term(s), broader term, narrower term, and related term(s).

* Variant
    - Blade
* Broader
    - Weapon
* Narrower
   -  Saber
* Related
    - Fighting

---

### 30. Design a  controlled vocabulary for your proposed Drupal web site.

#TODO


text:
CKEDITOR.editorConfig = function( config )
{
	// Define changes to default configuration here. For example:
	// config.language = 'fr';

	config.uiColor = '#aeaeae';
	config.resize_enabled = false;
	config.toolbar = 'MyToolbar';
	config.contentsCss = ['/assets/core/resources/css/main/rte.css', '/assets/core/resources/css/main/custom.css'];
	config.serverPreviewURL = '/previewDocument.php';
	config.templates_files = ['/assets/core/resources/templates/document_templates.js'];
	config.disableNativeSpellChecker = false;
	config.smiley_path='/assets/core/resources/images/emoticons/';
	config.smiley_images=['smiley.gif','teeth.gif','giggle.gif','laugh.gif','greed.gif','wink.gif','suprise.gif','surprise.gif','tongue.gif','blank.gif','worried.gif','frown.gif','cry.gif','mad.gif','toothless.gif','smoke.gif','sick.gif','satan.gif','alien.gif','vampire.gif','dead.gif','flame.gif','heart.gif','star.gif'];
	config.smiley_descriptions=[':)',';)',':D',':giggle:',':lol:','$$-)',':o',':O',':p',':|',':/',':(',':((',':@',':-B',':-Q',':sick:',':devil:',':alien:',':vampire:',':dead:',':flame:',':heart:',':star:'];
	config.toolbar_MyToolbar =
	[
    ['AjaxSave','AjaxSaveAs','NewPage','SonetPreview','-','SonetTemplateChooser'],
    ['Print', 'SpellChecker', 'Scayt'],
    ['SelectAll','Cut','Copy','Paste','PasteText','PasteFromWord'],
    ['Undo','Redo','-','Find','Replace'],
    ['Source','-','Maximize', 'ShowBlocks'],
    ['Component','AuthContent','GroupContent','RCComponent','Toggler','Smartlink','DocumentAttribute'],
    '/',
    ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
    ['BidiLtr', 'BidiRtl'],
    ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
    ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote','CreateDiv'],
    ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'],
    ['Iframe'],
    '/',
    ['Styles','Format','Font','FontSize'],
    ['TextColor','BGColor','-','RemoveFormat'],
    ['Link','Unlink','Anchor'],
    ['Image','Table','Flash'],
    ['HorizontalRule','Smiley','SpecialChar','PageBreak']
    ];

	config.extraPlugins = 'sonet_ajaxsave,sonet_ajaxsaveas,sonet_preview,sonet_template_chooser,iframe,sonet_component,sonet_rc_component,sonet_auth_content,sonet_group_content,sonet_toggler,sonet_smartlink,sonet_document_attribute';
};


text:
import sublime

class ThreadProgress():
    """
    Animates an indicator, [=   ], in the status area while a thread runs

    :param thread:
        The thread to track for activity

    :param message:
        The message to display next to the activity indicator

    :param success_message:
        The message to display once the thread is complete
    """

    def __init__(self, thread, message, success_message):
        self.thread = thread
        self.message = message
        self.success_message = success_message
        self.addend = 1
        self.size = 8
        sublime.set_timeout(lambda: self.run(0), 100)

    def run(self, i):
        if not self.thread.is_alive():
            if hasattr(self.thread, 'result') and not self.thread.result:
                sublime.status_message('')
                return
            sublime.status_message(self.success_message)
            return

        before = i % self.size
        after = (self.size - 1) - before

        sublime.status_message('%s [%s=%s]' % \
            (self.message, ' ' * before, ' ' * after))

        if not after:
            self.addend = -1
        if not before:
            self.addend = 1
        i += self.addend

        sublime.set_timeout(lambda: self.run(i), 100)


text:
#ifndef ALIJETHISTOS_H
#define ALIJETHISTOS_H

//---------------------------------------------------------------------
// Jet Histos class
// Creates and fills a few cummon histograms for jet analysis
//
//---------------------------------------------------------------------

class TList;
class TClonesArray;
class TH1I;
class TH1F;

class AliJetHistos : public TObject {
 public:
  AliJetHistos();
  ~AliJetHistos();

  void CreateHistos();
  void AddHistosToList(TList *list) const;
  void FillHistos(TClonesArray *jets);

 private:
  void SetProperties(TH1* h,const char* x, const char* y) const;
  AliJetHistos(const AliJetHistos &det);
  AliJetHistos &operator=(const AliJetHistos &det);

 private:

  TH1I *fNJetsH;           // distribution of number of jets
  TH1F *fPtH;              // pt spectra
  TH1F *fEtaH;             // eta distribution
  TH1F *fEneH;             // energy distribution
  TH1F *fPhiH;             // phi distribution

  ClassDef(AliJetHistos,2) // some jet histos

};

#endif


text:
import os
import sys
import unittest
from nose.plugins.capture import Capture
from nose.plugins import PluginTester

support = os.path.join(os.path.dirname(__file__), 'support')

class TestIssue649(PluginTester, unittest.TestCase):
    activate = ''
    args = ['-v']
    plugins = [Capture()]
    suitepath = os.path.join(support, 'issue649')

    def runTest(self):
        print str(self.output)
        assert 'UnicodeDecodeError' not in self.output


text:
package vnmr.ui.shuf;

import java.io.*;
import java.util.*;
import java.text.*;

import vnmr.ui.*;
import vnmr.bo.*;
import vnmr.util.*;

/********************************************************** <pre>
 * Summary: Contain info about one trash entry
 *
 * @author  Glenn Sullivan
 * Details:
 *   -
 *
 </pre> **********************************************************/

public class TrashInfo implements  Serializable {

    public String filename;  // Filename without extension
    public String fullpath;  // Full path of trash dir for this file (direct)
    public String hostFullpath;
    public String origFullpath;  // Orig full path of trashed file (direct)
    public String origHostFullpath;// Orig hostFullpath of trashed file (direct)
    public String objType;   // Spotter type
    public String dhost;  // Host name where trash file actually exists
    public String owner;
    public String parFile;  // For protocols only and then only sometimes
    public String dparPath;   // For protocols, path where par came from
    public Date   dateTrashed;
    public boolean protocolBrowser; // trash request originated in Protocol Browser

    /**************************************************
     * Summary: constructor, Fill member variables from args and set
     *          date equal to current date.
     <**************************************************/
    public TrashInfo(String fName, String ofpath, String oType, String hName,
                     String own, String ohfpath, boolean protBrowser) {

        filename = fName;
        origFullpath = ofpath;
        objType = oType;
        dhost = hName;
        origHostFullpath = ohfpath;
        owner = own;
        parFile = null;
        dparPath = null;
        dateTrashed = new Date();
        protocolBrowser = protBrowser;

    }

    /**************************************************
     * Summary: constructor, Fill all member variables from args and set
     *          date from arg also.
     *
     <**************************************************/
    public TrashInfo(String fName, String fPath, String hfPath, String oType,
                     String hName, String own, String ofpath, String ohfpath,
                     String par, String pPath, Date date) {

        filename = fName;
        fullpath = fPath;
        objType = oType;
        dhost = hName;
        hostFullpath = hfPath;
        origFullpath = ofpath;
        origHostFullpath = ohfpath;
        parFile = par;
        dparPath = pPath;
        owner = own;
        dateTrashed = date;
        protocolBrowser = false;
    }
    /**************************************************
     * Summary: Write a TrashInfo file for this item.
     *
     *
     **************************************************/
    public boolean writeTrashInfoFile(String filepath) {
	PrintWriter out;

	try {
	    // Write out the file in plain text
            UNFile file = new UNFile(filepath);
	    out = new PrintWriter(new FileWriter(file));
	    // Write out a header line
	    out.println("TrashInfo");
            out.println(toString());
	    out.close();
	}
	catch (Exception e) {
            Messages.postError("Problem creating " + filepath);
	    Messages.writeStackTrace(e);
            return false;
	}

        return true;
    }

    /**************************************************
     * Summary: Read the file and create a TrashInfo item.
     *
     *
     **************************************************/
    static public TrashInfo readTrashInfoFile(String filepath) {
	BufferedReader in;
	String var;
	String value;
	String line;
	QuotedStringTokenizer tok;
        TrashInfo trashInfo;
        String name=null;  // filename
        String path=null;  // fullpath
        String type=null;  // objType
        String host=null;  // hostName
        String hfpath=null; //hostFullpath
        String own=null;   // owner
        String ofpath=null; // orig fullpath
        String ohfpath=null; // orig hostfullpath
        String pFile=null;  // par file name
        String pPath=null;   // par file full path
        Date   date=null;  // dateTrashed
        boolean protocolBrowser=false;
        String mpathW;

	try {

            // If file does not exist, return null
            UNFile file = new UNFile(filepath + File.separator + "trashinfo");
            if(!file.isFile())
                return null;

	    in = new BufferedReader(new FileReader(file));

	    // The file must start with HoldingData or ignore the rest.
	    line = in.readLine();
	    if(line != null) {
		tok = new QuotedStringTokenizer(line, " \t");
		if (tok.hasMoreTokens()) {
		    var = tok.nextToken();
		    if(!var.equals("TrashInfo")) {
                        throw(new Exception(filepath +
                                            " is not a TrashInfo file."));
		    }
		}
		else
		    throw(new Exception(filepath +
                                        " is not a TrashInfo file."));
	    }
	    while ((line = in.readLine()) != null) {
		tok = new QuotedStringTokenizer(line, " \t");
		if (tok.hasMoreTokens())
		    var = tok.nextToken();
		else
		    continue;

                if (tok.hasMoreTokens())
		    value = tok.nextToken();
		else
		    value = "";

                if (var.equals("filename"))
                    name = value;
                else if (var.equals("fullpath"))
                    path = value;
                else if (var.equals("objType"))
                    type = value;
                else if (var.equals("hostName"))
                    host = value;
                else if (var.equals("owner"))
                    own = value;
                else if (var.equals("origFullpath"))
                    ofpath = value;
                else if (var.equals("origHostFullpath"))
                    ohfpath = value;
                else if (var.equals("hostFullpath"))
                    hfpath = value;
                // Allow pFile and pPath to be null references.
                else if (var.equals("parFile")) {
                    if(!value.equals("null"))
                        pFile = value;
                }
                else if (var.equals("parPath")) {
                    if(!value.equals("null"))
                        pPath = value;
                }
                else if (var.equals("dateTrashed")) {
                    SimpleDateFormat df;
                    df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
                    date = df.parse(value);
                }
                else if (var.equals("protocolBrowser")) {
                    if(value.equals("true"))
                        protocolBrowser = true;
                }

	    }
            in.close();

            // Test to see that all necessary values were obtained
            // Allow pFile and pPath to be null.
            if(name == null || path == null || type == null || host == null
                            || own == null || date == null || ofpath == null
                            || hfpath == null || ohfpath == null) {
                Messages.postError(filepath + " Not a complete transinfo file");
                return null;
            }

	}
 	catch (Exception e) {
            Messages.postError("Problem reading " + filepath);
	    Messages.writeStackTrace(e);
            return null;
	}
        trashInfo = new TrashInfo(name, path, hfpath, type, host, own,
                                  ofpath, ohfpath, pFile, pPath, date);
        return trashInfo;
    }

    public String toString() {
        SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        return("filename " + filename + "\n" +
               "fullpath " + fullpath + "\n" +
               "objType " + objType  + "\n" +
               "hostName " + dhost + "\n" +
               "hostFullpath " + hostFullpath + "\n" +
               "owner " + owner  + "\n" +
               "parFile " + parFile + "\n" +
               "parPath " + dparPath + "\n" +
               "origFullpath " + origFullpath  + "\n" +
               "origHostFullpath " + origHostFullpath  + "\n" +
               "dateTrashed \"" + df.format(dateTrashed)  + "\"\n");
    }

}


text:
We prepared several tests in order to maintain the quality and correct functionality of the module.

## How to run?
Easy, from the main folder, run this
```bash
python tests/run.py
```

This will try to covert all the cases included in the module.


text:
LayerPanel = OpenLayers.Class({

    /**
    * Constructor: LayerPanel
    *
    * Parameters:
    * options - {Object} Options for panel.
    */
    initialize: function(options) {
        this.init(options);
        this.draw();
    },

    init: function(options) {
        this.layers = options.layers;
        this.div = jQuery(options.div);
        this.events = new OpenLayers.Events(this, this.div.get(0), null, true);
        this.showLayerTmpl = jQuery.trim(jQuery('#showLayerTmpl').html());
        this.hideLayerTmpl = jQuery.trim(jQuery('#hideLayerTmpl').html());
        this.showHeaderTmpl = jQuery.trim(jQuery('#showHeaderTmpl').html());
        this.hideHeaderTmpl = jQuery.trim(jQuery('#hideHeaderTmpl').html());
    },

    draw: function() {
        var panel = this;
        var tmpl = jQuery('#treeTmpl').html();
        var treeElm = jQuery.mustache(tmpl, jQuery.extend(this.layers, FISH_MAP.tmplView));

        this.div.append(treeElm);

        this.div.find('input').change(function() {
            panel.events.triggerEvent("layerchange", {layer: this.value, state: this.checked});
        });

        this.div.find('h3').click(function() {
            jQuery(this).toggleClass('collapsed').siblings().toggle();
        }).click().first().click();

        this.addTooltips();

        return this.div;
    },

    addTooltips: function() {
        var panel = this;

        function setLayerTooltip(input) {
            var elm = jQuery(input),
            label = jQuery("label[for='" + input.id + "']");
            elm.add(label).attr('title', panel.getLayerTooltip(label.text(), input.checked));
        }

        function setHeaderTooltip(header) {
            var elm = jQuery(header);
            elm.attr('title', panel.getHeaderTooltip(elm.text(), (elm.hasClass('collapsed') === false)));
        }

        // NOTE: Use :not([title]) to only target elements that we have not
        // already added the behaviour to (don't have a title attribute)

        jQuery('ul.tree input:checkbox:not([title])', this.div).change(function() {
            setLayerTooltip(this);
        }).each(function () {
            setLayerTooltip(this);
        });

        jQuery('ul.tree h3:not([title])', this.div).click(function() {
            setHeaderTooltip(this);
        }).each(function () {
            setHeaderTooltip(this);
        });
    },

    getLayerTooltip: function(text, checked) {
        var tmpl = (checked) ? this.hideLayerTmpl : this.showLayerTmpl;
        return jQuery.mustache(tmpl, {"text": text});
    },

    getHeaderTooltip: function(text, open) {
        var tmpl = (open) ? this.hideHeaderTmpl : this.showHeaderTmpl;
        return jQuery.mustache(tmpl, {"text": text});
    }

});


text:
require "assert"
require "assert/assertions"

module Assert::Assertions
  class AssertRaisesTests < Assert::Context
    include Assert::Test::TestHelpers

    desc "`assert_raises`"
    subject do
      desc = desc1
      Factory.test do
        assert_raises(StandardError, RuntimeError){ raise(StandardError) }
        assert_raises(StandardError, RuntimeError, desc){ raise(Exception) }
        assert_raises(RuntimeError, desc){ raise(StandardError) }
        assert_raises(RuntimeError, desc){ true }
        assert_raises(desc){ true }
      end
    end

    let(:desc1){ "assert raises fail desc" }

    should "produce results as expected" do
      subject.run(&test_run_callback)

      assert_that(test_run_result_count).equals(5)
      assert_that(test_run_result_count(:pass)).equals(1)
      assert_that(test_run_result_count(:fail)).equals(4)

      exp =
        [
          "#{desc1}\nStandardError or RuntimeError exception expected, not:",
          "#{desc1}\nRuntimeError exception expected, not:",
          "#{desc1}\nRuntimeError exception expected but nothing raised.",
          "#{desc1}\nAn exception expected but nothing raised.",
        ]
      messages = test_run_results(:fail).map(&:message)
      messages.each_with_index do |msg, n|
        assert_that(msg).matches(/^#{exp[n]}/)
      end
    end

    should "return any raised exception instance" do
      error     = nil
      error_msg = Factory.string

      test =
        Factory.test do
          error = assert_raises(RuntimeError){ raise(error_msg) }
        end
      test.run

      assert_that(error).is_not_nil
      assert_that(error).is_kind_of(RuntimeError)
      assert_that(error.message).equals(error_msg)

      test = Factory.test{ error = assert_raises(RuntimeError){} }
      test.run

      assert_that(error).is_nil
    end
  end

  class AssertNothingRaisedTests < Assert::Context
    include Assert::Test::TestHelpers

    desc "`assert_nothing_raised`"
    subject do
      desc = desc1
      Factory.test do
        assert_nothing_raised(StandardError, RuntimeError, desc) do
          raise(StandardError)
        end
        assert_nothing_raised(RuntimeError){ raise(StandardError) }
        assert_nothing_raised(desc){ raise(RuntimeError) }
        assert_nothing_raised{ true }
      end
    end

    let(:desc1){ "assert nothing raised fail desc" }

    should "produce results as expected" do
      subject.run(&test_run_callback)

      assert_that(test_run_result_count).equals(4)
      assert_that(test_run_result_count(:pass)).equals(2)
      assert_that(test_run_result_count(:fail)).equals(2)

      exp =
        [
          "#{desc1}\nStandardError or RuntimeError exception not expected, "\
          "but raised:",
          "#{desc1}\nAn exception not expected, but raised:",
        ]
      messages = test_run_results(:fail).map(&:message)
      messages.each_with_index do |msg, n|
        assert_that(msg).matches(/^#{exp[n]}/)
      end
    end
  end
end


text:
package org.zstack.sdk;

public class PowerOnBaremetalChassisResult {

}


text:
__author__ = """Chris Tabor (dxdstudio@gmail.com)"""

if __name__ == '__main__':
    from os import getcwd
    from os import sys
    sys.path.append(getcwd())

from MOAL.helpers.display import Section

DEBUG = True if __name__ == '__main__' else False

class Cell:

    programmed_cell_death = True

    def mitosis(self):
        raise NotImplementedError

    def mutate(self):
        raise NotImplementedError

    def copy_dna(self):
        raise NotImplementedError

class CancerCell(Cell):
    """Duck Typing, with a twist - it looks like a cell, moves like a cell...
    but it has a little surprise!"""

    programmed_cell_death = False

class Skin:

    tissue_type = 'skin'

class Teratoma(Skin):

    tissue_type = 'eyeball + teeth'

class VitalOrgan:
    """Fun side note - when an organ or part of the body is forming,
    it uses cell apoptosis to effectively 'carve out' the shape by killing
    off cells in a programmatic process -- amazing!

    See: https://en.wikipedia.org/wiki/Programmed_cell_death
    """

    def __init__(self, cells=[]):
        self.cells = cells
        self.differentiation_pattern = {}  # This would contain data

    def replenish(self, cells):
        self.cells += cells

    def differentiate(self):
        """Not to be confused with cell differentiation."""
        print('Differentiating!')

class ApoptosisManager:

    def autophagy(self, tissue):
        print('Autophagy: cleaning up old cells!')
        for cell in tissue.cells:
            if cell.programmed_cell_death:
                print('Killing off cell!')
            else:
                print('I AM A CANCER CELL - I WILL NOT DIE')

if DEBUG:
    with Section('Type theory - Duck Typing'):
        # Okay, so here's the rundown;
        # 1. New cells are created out of thin air, for something.
        # 2. They are associated with a vital organ -- that is to say,
        # they ARE the vital organ -- they make up the parts of it.
        # 3. An autophagy manager comes along as a process, to deal with cleanup
        # and delegation (a bit of a creative interpretation here).
        # 4. Manager attempts to clean up at the request of the organ,
        # only to find there is a hidden cancer cell hiding underneath.
        apoptos = ApoptosisManager()
        organ = VitalOrgan(cells=[Cell() for _ in range(5)] + [CancerCell()])
        apoptos.autophagy(organ)

        some_skin = Skin()
        some_other_skin = Teratoma()
        print(some_skin.tissue_type)
        # Oh god, wtf!
        print(some_other_skin.tissue_type)


text:
<!DOCTYPE html>
<html lang='en'>
<head>
	<meta charset='UTF-8'>
	<title>筋斗云</title>

	<meta charset='UTF-8'>
	<meta name='viewport' content='width=device-width, initial-scale=1'>

	<meta name ="keywords" content="relationships,entertainment,human,sport,health,run,walk,competitions">
	<meta name="description" content="text/html;This page is about the sport management,sport competition and social intercourse.">

	<script src='http://libs.baidu.com/jquery/2.1.4/jquery.min.js'></script>
	<script src='http://cdn.bootcss.com/bootstrap/3.3.0/js/bootstrap.min.js'></script>
	<script src=<?php echo site_url("application/views/fullPage/jquery.fullPage.js") ?> ></script>
	<script src=<?php echo site_url("application/views/js/Utility.js") ?> ></script>

	<link rel='stylesheet' href='http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css'>
	<link rel='shortcut icon' href=<?php echo site_url("application/views/images/logo.jpg") ?> />
	<link rel='stylesheet' href=<?php echo site_url("application/views/css/base.css") ?> />
	<link rel='stylesheet' href='https://static.codoon.com/css/codoon.css?v=001' />
	<link rel='stylesheet' href='https://static.codoon.com/css/messages.css?v=001' />
	<link rel='stylesheet' href='http://tb1.bdstatic.com/??/tb/_/pb_author_18b6216.css'/>
	<link rel="stylesheet" href=<?php echo site_url("application/views/register/register.css")?> >
	<link rel="stylesheet" type="text/css" href=<?php echo site_url("application/views/fullPage/jquery.fullPage.css") ?> />
	<link rel='stylesheet' href=<?php echo site_url("application/views/css/all.css") ?> />


text:
#include "SudokuGrid.h"
#include <string>

struct DLXColumn;

struct DLXItem {
  DLXItem *prevCol;
  DLXItem *nextCol;
  DLXItem *prevRow;
  DLXItem *nextRow;
  // Refers to the single column header object in this column
  DLXColumn *columnHeader;

  DLXItem() : columnHeader(NULL) {
    prevCol = nextCol = prevRow = nextRow = this;
  }
  void insertColumn(DLXItem *before);
  void insertRow(DLXItem *before);
  void removeCol();
  void replaceCol();
  void removeRow();
  void replaceRow();
};

struct DLXColumn : public DLXItem {
  int columnSum;

  DLXColumn() : columnSum(0) { columnHeader = this; }
  virtual ~DLXColumn() {}

  enum ColumnType { Position, Value };
  virtual ColumnType type() = 0;
};

struct DLXColumnPos : public DLXColumn {
  int x;
  int y;

  DLXColumnPos(int x, int y) : x(x), y(y) {}
  virtual ~DLXColumnPos() {}
  virtual ColumnType type() { return Position; }
};

struct DLXColumnValue : public DLXColumn {
  int value;

  explicit DLXColumnValue(int v) : value(v) {}
  virtual ~DLXColumnValue() {}
  virtual ColumnType type() { return Value; }
};

class SudokuSolverException : public SudokuGridException {
public:
  SudokuSolverException(const SudokuSolverException &other)
      : SudokuGridException(other) {}
  SudokuSolverException(const char *what) : SudokuGridException(what) {}
};

class DLX {
public:
  DLX(const SudokuGrid &src);
  ~DLX();

  bool solve();

  int stepsTaken;
  bool solutionFound;
  bool uniqueSolution;
  SudokuGrid solution;

protected:
  bool solveAll();
  SudokuGrid currentSolution;
  DLXColumn *m_root;
};


text:
import numpy as np

import cv2 as cv

import matplotlib  # isort:skip
matplotlib.use('Agg')
import chainercv  # isort:skip

class VOC(chainercv.datasets.VOCDetectionDataset):

    LABELS = ('__background__',  # always index 0
              'aeroplane', 'bicycle', 'bird', 'boat',
              'bottle', 'bus', 'car', 'cat', 'chair',
              'cow', 'diningtable', 'dog', 'horse',
              'motorbike', 'person', 'pottedplant',
              'sheep', 'sofa', 'train', 'tvmonitor')
    IMG_TARGET_SIZE = 600
    IMG_MAX_SIZE = 1000

    def __init__(self, mode='train', use_difficult=False):
        super(VOC, self).__init__(mode, use_difficult=use_difficult)
        self.mean = np.array([[[103.939, 116.779, 123.68]]])  # BGR

    def get_example(self, i):
        img, bbox, label = super(VOC, self).get_example(i)
        img = img.transpose(1, 2, 0)
        img -= self.mean

        # Scaling
        im_size_min = np.min(img.shape[:2])
        im_size_max = np.max(img.shape[:2])
        im_scale = float(self.IMG_TARGET_SIZE) / float(im_size_min)

        # Prevent the biggest axis from being more than MAX_SIZE
        if np.round(im_scale * im_size_max) > self.IMG_MAX_SIZE:
            im_scale = float(self.IMG_MAX_SIZE) / float(im_size_max)
        img = cv.resize(img, None, None, fx=im_scale, fy=im_scale,
                        interpolation=cv.INTER_CUBIC)
        img = img.transpose(2, 0, 1).astype(np.float32)
        bbox *= im_scale
        bbox = np.concatenate(
            (bbox, label[:, None]), axis=1).astype(np.float32)
        return img, np.asarray(img.shape[1:]), bbox

if __name__ == '__main__':
    dataset = VOC('train')
    img, im_info, gt_boxes = dataset[0]
    print(img.shape)
    print(im_info)
    print(gt_boxes)
    print('len:', len(dataset))

    dataset = VOC('val')
    img, im_info, gt_boxes = dataset[0]
    print(img.shape)
    print(im_info)
    print(gt_boxes)
    print('len:', len(dataset))


text:
function RefreshPage() {
	location.reload();
}


text:
"""
"""
import pygame

from . import container
from . import layout

class _document_widget:
    def __init__(self,w,align=None):
        #w.rect.w,w.rect.h = w.resize()
        #self.rect = w.rect
        self.widget = w
        if align != None: self.align = align

class Document(container.Container):
    """A document is a container that structures widgets in a left-to-right flow."""

    def __init__(self,**params):
        params.setdefault('cls','document')
        container.Container.__init__(self,**params)
        self.layout =  layout.Layout(pygame.Rect(0,0,self.rect.w,self.rect.h))

    def add(self,e,align=None):
        """Add a widget to the document flow.

        Arguments:
            e -- widget
            align -- alignment (None,-1,0,1)

        """
        dw = _document_widget(e,align)
        self.layout.add(dw)
        e.container = self
        e._c_dw = dw
        self.widgets.append(e)
        self.chsize()

    def remove(self,e):
        self.layout._widgets.remove(e._c_dw)
        self.widgets.remove(e)
        self.chsize()

    def block(self,align):
        """Start a new block given the alignment (-1, 0, 1)"""
        self.layout.add(align)

    def space(self, size):
        """Add a spacer given the size."""
        self.layout.add(size)

    def br(self,height):
        """Add a line break, given the height."""
        self.layout.add((0, height))

    def resize(self,width=None,height=None):
        if self.style.width: width = self.style.width
        if self.style.height: height = self.style.height

        for w in self.widgets:
            w.rect.w,w.rect.h = w.resize()

            if (width != None and w.rect.w > width) or (height != None and w.rect.h > height):
                w.rect.w,w.rect.h = w.resize(width,height)

            dw = w._c_dw
            dw.rect = pygame.Rect(0,0,w.rect.w,w.rect.h)

        if width == None: width = 65535
        self.layout.rect = pygame.Rect(0,0,width,0)
        self.layout.resize()

        _max_w = 0

        for w in self.widgets:
            #xt,xl,xb,xr = w.getspacing()
            dw = w._c_dw
            w.style.x,w.style.y,w.rect.w,w.rect.h = dw.rect.x,dw.rect.y,dw.rect.w,dw.rect.h
            #w.resize()
            w.rect.x,w.rect.y = w.style.x,w.style.y
            _max_w = max(_max_w,w.rect.right)

        #self.rect.w = _max_w #self.layout.rect.w
        #self.rect.h = self.layout.rect.h
        #print 'document',_max_w,self.layout.rect.h
        return _max_w,self.layout.rect.h


text:
package com.badlogic.gdx.controllers.android;

import android.view.InputDevice;
import android.view.InputDevice.MotionRange;

import com.badlogic.gdx.controllers.ControlType;
import com.badlogic.gdx.controllers.Controller;
import com.badlogic.gdx.controllers.ControllerListener;
import com.badlogic.gdx.controllers.PovDirection;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.IntFloatMap;
import com.badlogic.gdx.utils.IntIntMap;

public class AndroidController implements Controller {
	private final int deviceId;
	private boolean attached;
	private final String name;
	protected final IntIntMap buttons = new IntIntMap();
	protected final float[] axes;
	protected final int[] axesIds;
	private final Array<ControllerListener> listeners = new Array<ControllerListener>();

	public AndroidController(int deviceId, String name) {
		this.deviceId = deviceId;
		this.name = name;

		InputDevice device = InputDevice.getDevice(deviceId);
		int numAxes = 0;
		for (MotionRange range : device.getMotionRanges()) {
			if ((range.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
				numAxes += 1;
			}
		}

		axesIds = new int[numAxes];
		axes = new float[numAxes];
		int i = 0;
		for (MotionRange range : device.getMotionRanges()) {
			if ((range.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
				axesIds[i++] = range.getAxis();
			}
		}
	}

	public boolean isAttached () {
		return attached;
	}

	public void setAttached (boolean attached) {
		this.attached = attached;
	}

	public int getDeviceId () {
		return deviceId;
	}

	@Override
	public boolean getSliderX (int sliderIndex) {
		return false;
	}

	@Override
	public boolean getSliderY (int sliderIndex) {
		return false;
	}

	@Override
	public Vector3 getAccelerometer (int accelerometerIndex) {
		return Vector3.Zero;
	}

	@Override
	public void setAccelerometerSensitivity (float sensitivity) {
	}

	@Override
	public void addListener (ControllerListener listener) {
		this.listeners.add(listener);
	}

	@Override
	public void removeListener (ControllerListener listener) {
		this.listeners.removeValue(listener, true);
	}

	public Array<ControllerListener> getListeners() {
		return this.listeners;
	}

	@Override
	public boolean getButton (int buttonIndex) {
		return buttons.containsKey(buttonIndex);
	}

	@Override
	public float getAxis (int axisIndex) {
		if(axisIndex < 0 || axisIndex >= axes.length) return 0;
		return axes[axisIndex];
	}

	@Override
	public PovDirection getPov (int povIndex) {
		return PovDirection.center;
	}

	@Override
	public String getName () {
		return name;
	}
}


text:
IPFS as a project, including js-ipfs and all of its modules, follows the [standard IPFS Community contributing guidelines](https://github.com/ipfs/community/blob/master/CONTRIBUTING.md).

We also adhere to the [IPFS JavaScript Community contributing guidelines](https://github.com/ipfs/community/blob/master/CONTRIBUTING_JS.md) which provide additional information of how to collaborate and contribute in the JavaScript implementation of IPFS.

We appreciate your time and attention for going over these. Please open an issue on [ipfs/community](https://github.com/ipfs/community) if you have any question.

Thank you.


text:
package io.github.jeddict.jpa.modeler.widget.flow.relation;

import io.github.jeddict.jpa.modeler.initializer.JPAModelerScene;
import org.netbeans.modeler.specification.model.document.IModelerScene;
import static io.github.jeddict.jpa.modeler.initializer.JPAModelerUtil.MTOR_SOURCE_ANCHOR_SHAPE;
import static io.github.jeddict.jpa.modeler.initializer.JPAModelerUtil.MTOR_TARGET_ANCHOR_SHAPE;
import org.netbeans.modeler.anchorshape.IconAnchorShape;
import org.netbeans.modeler.widget.edge.info.EdgeWidgetInfo;

/**
 *
 * @author Gaurav Gupta
 */
public abstract class MTORelationFlowWidget extends HierarchicalRelationFlowWidget {

    private static final IconAnchorShape SOURCE_ANCHOR_SHAPE = new IconAnchorShape(MTOR_SOURCE_ANCHOR_SHAPE, true);
    private static final IconAnchorShape TARGET_ANCHOR_SHAPE = new IconAnchorShape(MTOR_TARGET_ANCHOR_SHAPE, true);

    public MTORelationFlowWidget(JPAModelerScene scene, EdgeWidgetInfo edge) {
        super(scene, edge);
        setSourceAnchorShape(SOURCE_ANCHOR_SHAPE);
        setTargetAnchorShape(TARGET_ANCHOR_SHAPE);
    }

}


text:
layout: "post"
title: "Installing a Previous Ansible Release on Ubuntu"
date: "2016-06-02 18:34"
---

If you are installing the latest version of Ansible on Ubuntu you can utilize
the Ansible ppa (Personal Package Archives) and apt-get to complete the install
process without any hassle.

```shell
$ sudo apt-get install software-properties-common
$ sudo apt-add-repository ppa:ansible/ansible
$ sudo apt-get update
$ sudo apt-get install ansible
```

However, things get a bit tricker if you are trying to install a previous release.
Traditionally, you could utilize `sudo apt-get install package=version` to install
the required version but the Ansible ppa only houses the latest package available.
Or does it?

Thanks to some filtering magic on the ppa you can pull up [103 previous versions](https://launchpad.net/~ansible/+archive/ubuntu/ansible/+packages?field.name_filter=&field.status_filter=&field.series_filter=) of Ansible. From there you can use wget to download the version
you are looking for and complete the installation with the following:

```shell
$ sudo dpkg -i previous_version.deb
$ sudo apt-get -f install
```

Once thats completed you will be up and running and can delete the downloaded
.deb package.