text:
package org.xtuml.bp.ui.graphics.policies;

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

import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.MarginBorder;
import org.eclipse.draw2d.PolylineConnection;
import org.eclipse.draw2d.PositionConstants;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.PointList;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.GraphicalEditPart;
import org.eclipse.gef.Handle;
import org.eclipse.gef.Request;
import org.eclipse.gef.editparts.AbstractGraphicalEditPart;
import org.eclipse.gef.editpolicies.ResizableEditPolicy;
import org.eclipse.gef.handles.MoveHandle;
import org.eclipse.gef.handles.ResizableHandleKit;
import org.eclipse.gef.handles.ResizeHandle;
import org.eclipse.gef.requests.ChangeBoundsRequest;
import org.eclipse.swt.SWT;

import org.xtuml.bp.core.End_c;
import org.xtuml.bp.ui.canvas.FloatingText_c;
import org.xtuml.bp.ui.graphics.parts.ConnectorEditPart;
import org.xtuml.bp.ui.graphics.parts.TextEditPart;
import org.xtuml.bp.ui.graphics.requests.TextEditPartChangeBoundsRequest;
import org.xtuml.bp.ui.graphics.trackers.TextDragEditPartsTracker;
import org.xtuml.bp.ui.graphics.trackers.TextResizeTracker;

public class TextResizableEditPolicy extends ResizableEditPolicy {

	PolylineConnection connection = null;
	private Rectangle fInitialBounds;

	@Override
	public void showSourceFeedback(Request request) {
		super.showSourceFeedback(request);
		if (request.getType().equals(REQ_MOVE)) {
			TextEditPart part = (TextEditPart) ((TextEditPartChangeBoundsRequest) request)
					.getTarget();
			// include a line to the point on the
			// parent connector
			if (connection == null) {
				connection = getConnection();
				getFeedbackLayer().add(connection);
			}
			setPoints(part);
		}
	}

	private void setPoints(TextEditPart part) {
		// the points are from the center of the
		// feedback figure to a location on the
		// connector
		Point connectionPoint = null;
		if (part.getParent() instanceof ConnectorEditPart) {
			PolylineConnection figure = (PolylineConnection) ((AbstractGraphicalEditPart) part
					.getParent()).getFigure();
			connectionPoint = getPointOnConnection(figure, part);
		} else {
			connectionPoint = part.getFigure().getParent().getBounds()
					.getCenter();
		}
		Point textCenter = getHostFigure().getBounds().getCenter();
		getHostFigure().translateToAbsolute(connectionPoint);
		getHostFigure().translateToAbsolute(textCenter);
		getFeedbackLayer().translateToRelative(connectionPoint);
		getFeedbackLayer().translateToRelative(textCenter);
		connection.setPoints(new PointList(new int[] { textCenter.x,
				textCenter.y, connectionPoint.x, connectionPoint.y }));
	}

	private Point getPointOnConnection(IFigure figure, TextEditPart part) {
		FloatingText_c text = (FloatingText_c) part.getModel();
		Point point = null;
		switch (text.getEnd()) {
		case End_c.Start:
			point = ((PolylineConnection) figure).getPoints().getFirstPoint()
					.getCopy();
			break;
		case End_c.End:
			point = ((PolylineConnection) figure).getPoints().getLastPoint()
					.getCopy();
			break;
		case End_c.Middle:
			point = ((PolylineConnection) figure).getPoints().getMidpoint()
					.getCopy();
			break;
		default:
			break;
		}
		return point;
	}

	private PolylineConnection getConnection() {
		PolylineConnection poly = new PolylineConnection();
		poly.setLineStyle(SWT.LINE_DOT);
		poly.setForegroundColor(ColorConstants.gray);
		return poly;
	}

	@Override
	protected IFigure createDragSourceFeedbackFigure() {
		return getHostFigure();
	}

	@Override
	protected void eraseChangeBoundsFeedback(ChangeBoundsRequest request) {
		super.eraseChangeBoundsFeedback(request);
		if (connection != null) {
			getFeedbackLayer().remove(connection);
			connection = null;
		}
		fInitialBounds = null;
	}

	@Override
	protected void addFeedback(IFigure figure) {
		// do not add
	}

	@Override
	protected void showChangeBoundsFeedback(ChangeBoundsRequest request) {
		getFeedbackLayer().translateToAbsolute(request.getMoveDelta());
		getFeedbackLayer().translateToAbsolute(request.getSizeDelta());
		getHostFigure().translateToRelative(request.getMoveDelta());
		getHostFigure().translateToRelative(request.getSizeDelta());
		Rectangle bounds = getHostFigure().getBounds().getCopy();
		Point newLocation = new Point(getInitialFeedbackBounds().x
				+ request.getMoveDelta().x, getInitialFeedbackBounds().y
				+ request.getMoveDelta().y);
		bounds.setLocation(newLocation);
		if (request.getResizeDirection() != 0) {
			Dimension newSize = new Dimension(getInitialFeedbackBounds().width
					+ request.getSizeDelta().width,
					getInitialFeedbackBounds().height
							+ request.getSizeDelta().height);
			bounds.setSize(newSize);
		}
		getHostFigure().setBounds(bounds);
		getHostFigure().revalidate();
	}

	@Override
	protected Rectangle getInitialFeedbackBounds() {
		if (fInitialBounds == null)
			fInitialBounds = super.getInitialFeedbackBounds().getCopy();
		return fInitialBounds;
	}

	@Override
	protected List<Handle> createSelectionHandles() {
		List<Handle> list = new ArrayList<Handle>();
		MoveHandle moveHandle = new MoveHandle((GraphicalEditPart) getHost());
		moveHandle.setDragTracker(new TextDragEditPartsTracker(getHost()));
		list.add(moveHandle);
		ResizableHandleKit.addHandle((GraphicalEditPart) getHost(), list,
				PositionConstants.EAST);
		ResizeHandle handle = (ResizeHandle) list.get(1);
		handle.setDragTracker(new TextResizeTracker(
				(GraphicalEditPart) getHost(), PositionConstants.EAST));
		Label label = new Label(
				"Drag this handle, east or west, to adjust\n the floating text format.");
		label.setBorder(new MarginBorder(3, 3, 3, 3));
		handle.setToolTip(label);
		return list;
	}

	@Override
	public boolean understandsRequest(Request request) {
		if (request instanceof ChangeBoundsRequest) {
			if (request instanceof TextEditPartChangeBoundsRequest) {
				if (((TextEditPartChangeBoundsRequest) request).getTarget() == getHost()) {
					return true;
				} else {
					return false;
				}
			} else {
				return false;
			}
		}
		return super.understandsRequest(request);
	}

}


text:
package de.eimb.testlink.synchronize.citrus.citrus;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.eimb.testlink.synchronize.citrus.CitrusTestLinkBean;
import de.eimb.testlink.synchronize.citrus.CitrusTestLinkFileBean;
import de.eimb.testlink.synchronize.citrus.CitrusTestLinkFileHandler;
import de.eimb.testlink.synchronize.citrus.utils.ConvertUtils;
import de.eimb.testlink.synchronize.citrus.utils.FileUtils;

/**
 * Implementation of writing / reading a CITRUS test case result into / from a file, using JSON. Use
 * the JSON implementation of CITRUS.
 *
 * @author Matthias Beil
 * @since TestLink-Synchronize 1.0.0
 */
public class CitrusTestLinkFileHandlerImpl implements CitrusTestLinkFileHandler {

    // ~ Static fields/initializers --------------------------------------------------------------

    /** LOGGER. */
    private static final Logger LOGGER = LoggerFactory.getLogger(CitrusTestLinkFileHandlerImpl.class);

    /** BEAN_ID. */
    private static final String BEAN_ID = "beanId";

    /** BEAN_TEST_CASE_ID. */
    private static final String BEAN_TEST_CASE_ID = "testCaseId";

    /** BEAN_TEST_CASE_INTERNAL_ID. */
    private static final String BEAN_TEST_CASE_INTERNAL_ID = "testCaseInternalId";

    /** BEAN_TEST_PLAN_ID. */
    private static final String BEAN_TEST_PLAN_ID = "testPlanId";

    /** BEAN_BUILD_ID. */
    private static final String BEAN_BUILD_ID = "buildId";

    /** BEAN_BUILD_NAME. */
    private static final String BEAN_BUILD_NAME = "buildName";

    /** BEAN_SUCCESS. */
    private static final String BEAN_SUCCESS = "success";

    /** BEAN_NOTES_SUCCESS. */
    private static final String BEAN_NOTES_SUCCESS = "notesSuccess";

    /** BEAN_NOTES_FAILURE. */
    private static final String BEAN_NOTES_FAILURE = "notesFailure";

    /** BEAN_PLATFORM. */
    private static final String BEAN_PLATFORM = "platform";

    /** BEAN_START_TIME. */
    private static final String BEAN_START_TIME = "startTime";

    /** BEAN_END_TIME. */
    private static final String BEAN_END_TIME = "endTime";

    /** FILE_NAME_REG_EXP. */
    private static final String FILE_NAME_REG_EXP = "^[\\w-]+(success|failure)\\.json$";

    // ~ Constructors ----------------------------------------------------------------------------

    /**
     * Constructor for {@code CitrusTestLinkFileHandlerImpl} class.
     */
    public CitrusTestLinkFileHandlerImpl() {

        super();
    }

    // ~ Methods ---------------------------------------------------------------------------------

    /**
     * {@inheritDoc}
     */
    @Override
    public List<CitrusTestLinkFileBean> readFromDirectory(final String directory) {

        final List<CitrusTestLinkFileBean> result = new ArrayList<CitrusTestLinkFileBean>();

        try {

            final List<File> fileList = FileUtils.readFiles(FileUtils.readDirectory(directory),
                    FILE_NAME_REG_EXP);

            for (final File file : fileList) {

                if (FileUtils.isValidFile(file)) {

                    final String json = this.readJsonFromFile(file);
                    final CitrusTestLinkBean bean = this.jsonToTest(json);

                    if (null != bean) {

                        result.add(new CitrusTestLinkFileBean(bean, file));
                    }
                }
            }
        } catch (final Exception ex) {

            LOGGER.error("Exception caught for directory [ " + directory + " ]", ex);
        }

        return result;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void writeToFile(final CitrusTestLinkBean bean, final String directory) {

        // make sure bean is valid, directory is tested later
        if (null == bean) {

            // this might not happen, so just return
            return;
        }

        try {

            // build file from bean and directory
            final File file = this.buildFile(bean, directory);

            // build JSON string from bean
            final String json = this.testToJson(bean);

            // make sure there was no error
            if ((null == file) || ((null == json) || (json.isEmpty()))) {

                // there should be some error message previously
                return;
            }

            // write JSON content to file
            this.writeJsonToFile(file, json);
        } catch (final Exception ex) {

            LOGGER.error("Exception caught while trying to write CITRUS test case [ " + bean
                    + " ] to directory [ " + directory + " ]", ex);
        }
    }

    /**
     * DOCUMENT ME!
     *
     * @param file
     *            DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    private String readJsonFromFile(final File file) {

        FileInputStream fis = null;
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();

        try {

            fis = new FileInputStream(file);

            int content;

            while ((content = fis.read()) != -1) {

                baos.write(content);
            }
        } catch (final Exception ex) {

            LOGGER.error("Exception caught for file [ " + file + " ]", ex);
        } finally {

            FileUtils.close(fis);
        }

        return baos.toString();
    }

    /**
     * Write the created JSON string to the given file.
     *
     * @param file
     *            File to write JSON string too.
     * @param json
     *            JSON string to write.
     *
     * @throws IOException
     *             Thrown in case of some IO error.
     */
    private void writeJsonToFile(final File file, final String json) throws IOException {

        FileOutputStream fos = null;

        try {

            fos = new FileOutputStream(file);
            fos.write(json.getBytes());

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Writing JSON [ {} ] to file [ {} ]", json, file);
            }
        } finally {

            FileUtils.close(fos);
        }
    }

    /**
     * Build from the values in the CITRUS bean and the given directory the new file.
     *
     * @param bean
     *            Bean holding information to build the filename.
     * @param directory
     *            Directory where to store the file.
     *
     * @return Newly created file for this test case.
     *
     * @throws IOException
     *             Thrown in case the file already exists-
     */
    private File buildFile(final CitrusTestLinkBean bean, final String directory) throws IOException {

        // in case of an error an IOException will be thrown
        final File folder = FileUtils.createDirectory(directory);

        final StringBuilder builder = new StringBuilder(bean.getCitrusTestCase().getName());

        builder.append("-");
        builder.append(FileUtils.dateAsString(new Date()));

        if (bean.getSuccess().booleanValue()) {

            builder.append("-success");
        } else {

            builder.append("-failure");
        }

        builder.append(".json");

        final File file = new File(folder, builder.toString());

        if (file.exists()) {

            throw new IOException("File [ " + file.getAbsolutePath() + " ] already exists!");
        }

        return file;
    }

    /**
     * Convert bean content to a JSON string.
     *
     * @param bean
     *            Bean holding all data to be stored in the JSON string.
     *
     * @return String holding the bean content as a JSON string.
     */
    private String testToJson(final CitrusTestLinkBean bean) {

        final Map<String, Object> jsonMap = new HashMap<String, Object>();

        jsonMap.put(BEAN_ID, bean.getId());
        jsonMap.put(BEAN_BUILD_ID, bean.getBuildId());
        jsonMap.put(BEAN_BUILD_NAME, bean.getBuildName());
        jsonMap.put(BEAN_NOTES_FAILURE, bean.getNotesFailure());
        jsonMap.put(BEAN_NOTES_SUCCESS, bean.getNotesSuccess());
        jsonMap.put(BEAN_PLATFORM, bean.getPlatform());
        jsonMap.put(BEAN_SUCCESS, bean.getSuccess());
        jsonMap.put(BEAN_TEST_CASE_ID, bean.getTestCaseId());
        jsonMap.put(BEAN_TEST_CASE_INTERNAL_ID, bean.getTestCaseInternalId());
        jsonMap.put(BEAN_TEST_PLAN_ID, bean.getTestPlanId());
        jsonMap.put(BEAN_START_TIME, Long.valueOf(bean.getStartTime()));
        jsonMap.put(BEAN_END_TIME, Long.valueOf(bean.getEndTime()));

        return JSONObject.toJSONString(jsonMap);
    }

    /**
     * Convert JSON string back to a CITRUS test case element.
     *
     * @param json
     *            JSON string.
     *
     * @return Newly created CITRUS test case element.
     */
    private CitrusTestLinkBean jsonToTest(final String json) {

        if ((null == json) || (json.isEmpty())) {

            return null;
        }

        final JSONParser parser = new JSONParser();
        CitrusTestLinkBean bean = null;

        try {

            final Object obj = parser.parse(json);

            if (obj instanceof Map<?, ?>) {

                @SuppressWarnings("unchecked")
                final Map<String, Object> jsonMap = (Map<String, Object>) obj;

                if (!jsonMap.isEmpty()) {

                    bean = new CitrusTestLinkBean();

                    for (final Entry<String, Object> entry : jsonMap.entrySet()) {

                        final String key = entry.getKey();

                        if (BEAN_ID.equals(key)) {

                            bean.setId(ConvertUtils.convertToString(entry.getValue()));
                        } else if (BEAN_BUILD_ID.equals(key)) {

                            bean.setBuildId(ConvertUtils.convertToInteger(entry.getValue()));
                        } else if (BEAN_BUILD_NAME.equals(key)) {

                            bean.setBuildName(ConvertUtils.convertToString(entry.getValue()));
                        } else if (BEAN_NOTES_FAILURE.equals(key)) {

                            bean.setNotesFailure(ConvertUtils.convertToString(entry.getValue()));
                        } else if (BEAN_NOTES_SUCCESS.equals(key)) {

                            bean.setNotesSuccess(ConvertUtils.convertToString(entry.getValue()));
                        } else if (BEAN_PLATFORM.equals(key)) {

                            bean.setPlatform(ConvertUtils.convertToString(entry.getValue()));
                        } else if (BEAN_SUCCESS.equals(key)) {

                            bean.setSuccess(ConvertUtils.convertToBoolean(entry.getValue()));
                        } else if (BEAN_TEST_CASE_ID.equals(key)) {

                            bean.setTestCaseId(ConvertUtils.convertToInteger(entry.getValue()));
                        } else if (BEAN_TEST_CASE_INTERNAL_ID.equals(key)) {

                            bean.setTestCaseInternalId(ConvertUtils.convertToInteger(entry.getValue()));
                        } else if (BEAN_TEST_PLAN_ID.equals(key)) {

                            bean.setTestPlanId(ConvertUtils.convertToInteger(entry.getValue()));
                        } else if (BEAN_START_TIME.equals(key)) {

                            bean.setStartTime(ConvertUtils.convertToLong(entry.getValue())
                                    .longValue());
                        } else if (BEAN_END_TIME.equals(key)) {

                            bean.setEndTime(ConvertUtils.convertToLong(entry.getValue()).longValue());

                        } else {

                            LOGGER.error("Unknown entry [ {} ]", entry);
                        }
                    }
                } else {

                    LOGGER.error("Empty JSON object [ {} ]", json);
                }
            } else {

                LOGGER.error("JSON object [ {} ] is not of type [ JSONObject ]", obj);
            }
        } catch (final Exception ex) {

            LOGGER.error("Exception caught for JSON string [ " + json + " ]", ex);
        }

        return bean;
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * @class Recursive shadowcasting algorithm
 * Currently only supports 4/8 topologies, not hexagonal.
 * Based on Peter Harkins' implementation of Björn Bergström's algorithm described here: http://www.roguebasin.com/index.php?title=FOV_using_recursive_shadowcasting
 * @augments ROT.FOV
 */
ROT.FOV.RecursiveShadowcasting = function(lightPassesCallback, options) {
	ROT.FOV.call(this, lightPassesCallback, options);
};
ROT.FOV.RecursiveShadowcasting.extend(ROT.FOV);

/** Octants used for translating recursive shadowcasting offsets */
ROT.FOV.RecursiveShadowcasting.OCTANTS = [
	[-1,  0,  0,  1],
	[ 0, -1,  1,  0],
	[ 0, -1, -1,  0],
	[-1,  0,  0, -1],
	[ 1,  0,  0, -1],
	[ 0,  1, -1,  0],
	[ 0,  1,  1,  0],
	[ 1,  0,  0,  1]
];

/**
 * Compute visibility for a 360-degree circle
 * @param {int} x
 * @param {int} y
 * @param {int} R Maximum visibility radius
 * @param {function} callback
 */
ROT.FOV.RecursiveShadowcasting.prototype.compute = function(x, y, R, callback) {
	//You can always see your own tile
	callback(x, y, 0, 1);
	for(var i = 0; i < ROT.FOV.RecursiveShadowcasting.OCTANTS.length; i++) {
		this._renderOctant(x, y, ROT.FOV.RecursiveShadowcasting.OCTANTS[i], R, callback);
	}
};

/**
 * Compute visibility for a 180-degree arc
 * @param {int} x
 * @param {int} y
 * @param {int} R Maximum visibility radius
 * @param {int} dir Direction to look in (expressed in a ROT.DIRS value);
 * @param {function} callback
 */
ROT.FOV.RecursiveShadowcasting.prototype.compute180 = function(x, y, R, dir, callback) {
	//You can always see your own tile
	callback(x, y, 0, 1);
	var previousOctant = (dir - 1 + 8) % 8; //Need to retrieve the previous octant to render a full 180 degrees
	var nextPreviousOctant = (dir - 2 + 8) % 8; //Need to retrieve the previous two octants to render a full 180 degrees
	var nextOctant = (dir+ 1 + 8) % 8; //Need to grab to next octant to render a full 180 degrees
	this._renderOctant(x, y, ROT.FOV.RecursiveShadowcasting.OCTANTS[nextPreviousOctant], R, callback);
	this._renderOctant(x, y, ROT.FOV.RecursiveShadowcasting.OCTANTS[previousOctant], R, callback);
	this._renderOctant(x, y, ROT.FOV.RecursiveShadowcasting.OCTANTS[dir], R, callback);
	this._renderOctant(x, y, ROT.FOV.RecursiveShadowcasting.OCTANTS[nextOctant], R, callback);
};

/**
 * Compute visibility for a 90-degree arc
 * @param {int} x
 * @param {int} y
 * @param {int} R Maximum visibility radius
 * @param {int} dir Direction to look in (expressed in a ROT.DIRS value);
 * @param {function} callback
 */
ROT.FOV.RecursiveShadowcasting.prototype.compute90 = function(x, y, R, dir, callback) {
	//You can always see your own tile
	callback(x, y, 0, 1);
	var previousOctant = (dir - 1 + 8) % 8; //Need to retrieve the previous octant to render a full 90 degrees
	this._renderOctant(x, y, ROT.FOV.RecursiveShadowcasting.OCTANTS[dir], R, callback);
	this._renderOctant(x, y, ROT.FOV.RecursiveShadowcasting.OCTANTS[previousOctant], R, callback);
};

/**
 * Render one octant (45-degree arc) of the viewshed
 * @param {int} x
 * @param {int} y
 * @param {int} octant Octant to be rendered
 * @param {int} R Maximum visibility radius
 * @param {function} callback
 */
ROT.FOV.RecursiveShadowcasting.prototype._renderOctant = function(x, y, octant, R, callback) {
	//Radius incremented by 1 to provide same coverage area as other shadowcasting radiuses
	this._castVisibility(x, y, 1, 1.0, 0.0, R + 1, octant[0], octant[1], octant[2], octant[3], callback);
};

/**
 * Actually calculates the visibility
 * @param {int} startX The starting X coordinate
 * @param {int} startY The starting Y coordinate
 * @param {int} row The row to render
 * @param {float} visSlopeStart The slope to start at
 * @param {float} visSlopeEnd The slope to end at
 * @param {int} radius The radius to reach out to
 * @param {int} xx
 * @param {int} xy
 * @param {int} yx
 * @param {int} yy
 * @param {function} callback The callback to use when we hit a block that is visible
 */
ROT.FOV.RecursiveShadowcasting.prototype._castVisibility = function(startX, startY, row, visSlopeStart, visSlopeEnd, radius, xx, xy, yx, yy, callback) {
	if(visSlopeStart < visSlopeEnd) { return; }
	for(var i = row; i <= radius; i++) {
		var dx = -i - 1;
		var dy = -i;
		var blocked = false;
		var newStart = 0;

		//'Row' could be column, names here assume octant 0 and would be flipped for half the octants
		while(dx <= 0) {
			dx += 1;

			//Translate from relative coordinates to map coordinates
			var mapX = startX + dx * xx + dy * xy;
			var mapY = startY + dx * yx + dy * yy;

			//Range of the row
			var slopeStart = (dx - 0.5) / (dy + 0.5);
			var slopeEnd = (dx + 0.5) / (dy - 0.5);

			//Ignore if not yet at left edge of Octant
			if(slopeEnd > visSlopeStart) { continue; }

			//Done if past right edge
			if(slopeStart < visSlopeEnd) { break; }

			//If it's in range, it's visible
			if((dx * dx + dy * dy) < (radius * radius)) {
				callback(mapX, mapY, i, 1);
			}

			if(!blocked) {
				//If tile is a blocking tile, cast around it
				if(!this._lightPasses(mapX, mapY) && i < radius) {
					blocked = true;
					this._castVisibility(startX, startY, i + 1, visSlopeStart, slopeStart, radius, xx, xy, yx, yy, callback);
					newStart = slopeEnd;
				}
			} else {
				//Keep narrowing if scanning across a block
				if(!this._lightPasses(mapX, mapY)) {
					newStart = slopeEnd;
					continue;
				}

				//Block has ended
				blocked = false;
				visSlopeStart = newStart;
			}
		}
		if(blocked) { break; }
	}
};


text:
<?php

namespace VBot\Bot;

use VBot\Game\Game;

/**
 * Random Bot
 *
 * @author Nicolas Dupont <nicolas@akeneo.com>
 */
class RandomBot implements BotInterface
{
    /**
     * {@inheritDoc}
     */
    public function move(Game $game)
    {
        $dirs = array('Stay', 'North', 'South', 'East', 'West');

        return $dirs[array_rand($dirs)];
    }
}


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.service.project;

import org.jetbrains.annotations.ApiStatus;

/**
 * Custom modification model for custom model that isn't stored or indirectly stored in workspace model.
 */
@ApiStatus.Experimental
public interface ModifiableModel {
  /**
   * Applies all modifications from this model into model that is being modified.
   */
  void commit();

  /**
   * Discard all modification and dispose resources from this model.
   */
  void dispose();
}


text:
import React from 'react';
import {connect} from 'react-redux';
import Component from '../components/layout/mobile-navbar';
import {goTo} from '../modules/navigation/actions';

function mapStateToProps(state, props) {
   return {};
}

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    goTo(path) {
      dispatch(goTo(path));
    }
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(Component);


text:
package net.hamnaberg.json;

import net.hamnaberg.json.extension.Extended;

import java.util.LinkedHashMap;
import java.util.Map;
import javaslang.control.Option;

import java.net.URI;

public final class Error extends Extended<Error> {
    public static final Error EMPTY = Error.create(Option.<String>none(), Option.<String>none(), Option.<String>none());

    Error(Json.JObject delegate) {
        super(delegate);
    }

    @Override
    protected Error copy(Json.JObject value) {
        return new Error(value);
    }

    public String getTitle() {
        return getAsString("title");
    }

    public String getCode() {
        return getAsString("code");
    }

    public String getMessage() {
        return getAsString("message");
    }

    @Override
    public void validate() {
    }

    public Collection toCollection(URI href) {
        return Collection.builder(href).withError(this).build();
    }

    public static Error create(String title, String code, String message) {
        return create(Option.of(title), Option.of(code), Option.of(message));
    }

    public static Error create(Option<String> title, Option<String> code, Option<String> message) {
        final Map<String, Json.JValue> obj = new LinkedHashMap<>();
        title.forEach(value -> obj.put("title", Json.jString(value)));
        code.forEach(value -> obj.put("code", Json.jString(value)));
        message.forEach(value -> obj.put("message", Json.jString(value)));
        return new Error(Json.jObject(obj));
    }

    @Override
    public String toString() {
        return "Error{" +
                "title='" + getTitle() + '\'' +
                ", code='" + getCode() + '\'' +
                ", message='" + getMessage() + '\'' +
                '}';
    }
}


text:
title: "Haskell diary #5"
tags: software fp haskell diary
---

*I'm learning functional programming and writing things down as I go. Some of my understanding may be incomplete or wrong, and I expect to refine it in the fullness of time.*

As I was working through various Haskell exercises, I realised that while I enjoyed Haskell as a language, I was no closer to understanding how *practical* it is. So yesterday I decided to try approaching it from a different angle. Instead of writing small console programs, my goal for the day would be to write a minimal web application which connects to a PostgreSQL database and pulls some data out.

I'd done some research on Haskell web frameworks previously, and it looked like the best options (i.e. actively maintained, mature and reasonably popular) were [Yesod](http://yesodweb.com) and [Scotty](https://github.com/scotty-web/scotty).

I mostly structure my web apps to render the UI on the client, with the server primarily providing a JSON interface to the data. This happens to be the general trend in web development. However, from my cursory look at Yesod, it appears to be geared towards server side page generation, which felt a bit antiquated.

Scotty, being a minimal framework, seemed to fit my needs quite a bit better, so that's what I used.

I primarily relied on two articles while making this web app:

- [Making a website with Haskell](http://adit.io/posts/2013-04-15-making-a-website-with-haskell.html)
- [*Persistent* chapter in the Yesod book](http://www.yesodweb.com/book/persistent)

There are three main points I took from this experiment.

## 1. Insane dependency build times

For my tiny web app, `cabal-install` performed half an hour of furious compiling (on a newish Macbook Pro) and produced 300MB of output. That was not encouraging!

Apparently, it causes difficulties with deployment too. For example, Heroku allows Haskell deployment, but it has a cutoff (15 minutes?) for build times, which means that some trickery (like using an external build service) is needed to deploy apps.

## 2. Haskell SQL abstractions are as bad as any ORM

Just like ORMs in other languages, Haskell libraries for dealing with databases suffer from the issue of reinventing the SQL syntax (poorly). I get that the goal is to provide type checked queries, but I still want to write normal SQL and have *that* statically checked against the DB schema.

Here is an example of a query in Persist (which is sort of the Haskell analog to ActiveRecord):

{% highlight haskell %}
people <- selectList
   (       [PersonAge >. 25, PersonAge <=. 30]
       ||. [PersonFirstName /<-. ["Adam", "Bonny"]]
       ||. ([PersonAge ==. 50] ||. [PersonAge ==. 60])
   )
{% endhighlight %}

It looks pretty ugly in my opinion, and as usual, reinvents SQL only partially, providing an escape hatch to raw SQL. I quickly ran into limitations even in my tiny, useless web app: it turns out that Persist doesn't support the `hstore` column type.

Or take a look at a query in Esqueleto, another library building on top of Persist. To express a query like this:

{% highlight sql %}
SELECT *
FROM Person
WHERE age >= 18
{% endhighlight %}

you need to write this:

{% highlight haskell %}
select $
from $ \p -> do
where_ (p ^. PersonAge >=. just (val 18))
return p
{% endhighlight %}

This is just nuts. I count **9** bits of syntax I have to remember in this trivial query. It's like it tries hard to get into the uncanny valley where it looks *almost* like SQL, except it fails miserably.

I suppose the problem of interfacing programming languages with relational databases remains unresolved, unless I just haven't found the right Haskell library.

## 3. Haskell doesn't allow learning from the top down

I think quite a lot of web developers started creating web apps with the Ruby on Rails framework before learning the intricacies of Ruby. I'm pretty sure I only figured out Ruby metaprogramming after unknowingly using it in Rails.

Haskell doesn't allow this kind of frivolity. For example, I spent a lot of time just to go from connecting to SQLite (as in the article I was using) to connecting to Postgres. This is the function in question:

{% highlight haskell %}
runDb :: SqlPersistT (LoggingT IO) a -> IO a
runDb query = do
    runStderrLoggingT . withPostgresqlConn "postgres://a:a@localhost:5432/osm" $ runSqlConn query
{% endhighlight %}

Also, here is the list of imports for my app, which tells something about the complexity:

{% highlight haskell %}
{-# LANGUAGE OverloadedStrings #-}
import Web.Scotty
import Text.Blaze.Html5 hiding(map)
import Text.Blaze.Html5.Attributes
import qualified Web.Scotty as S
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
import Text.Blaze.Html.Renderer.Text

import Data.Text (Text)
import Data.Time (UTCTime, getCurrentTime)
import qualified Data.Text as T
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Logger (runStderrLoggingT)

import Network.Wai.Middleware.Static

import Database.Persist hiding(get)
import Database.Persist.Sql hiding(get)
import Database.Persist.Postgresql (withPostgresqlConn)

import Control.Monad (forM_)
import Control.Applicative
import Control.Monad.Logger
{% endhighlight %}

I also think a working understanding of monads would be extremely helpful. I don't have it yet, so I was floundering when I tried to deviate from example code and get my web app to output something different.

## Conclusion

I came away from this experiment disappointed. Regrettably, I think I have to come back to web apps later, when I learn some more Haskell concepts.


text:
package com.graphhopper.util;

import com.graphhopper.GHResponse;
import com.graphhopper.routing.Path;

import java.util.List;

/**
 * This class merges a list of points into one point recognizing the specified places.
 * <p>
 * @author Peter Karich
 * @author ratrun
 */
public class PathMerger
{
    private boolean enableInstructions = true;
    private boolean simplifyResponse = true;
    private DouglasPeucker douglasPeucker;
    private boolean calcPoints = true;

    public void doWork( GHResponse rsp, List<Path> paths, Translation tr )
    {
        int origPoints = 0;
        long fullTimeInMillis = 0;
        double fullWeight = 0;
        double fullDistance = 0;
        boolean allFound = true;

        InstructionList fullInstructions = new InstructionList(tr);
        PointList fullPoints = PointList.EMPTY;
        for (int pathIndex = 0; pathIndex < paths.size(); pathIndex++)
        {
            Path path = paths.get(pathIndex);
            fullTimeInMillis += path.getTime();
            fullDistance += path.getDistance();
            fullWeight += path.getWeight();
            if (enableInstructions)
            {
                InstructionList il = path.calcInstructions(tr);

                if (!il.isEmpty())
                {
                    if (fullPoints.isEmpty())
                    {
                        PointList pl = il.get(0).getPoints();
                        // do a wild guess about the total number of points to avoid reallocation a bit
                        fullPoints = new PointList(il.size() * Math.min(10, pl.size()), pl.is3D());
                    }

                    for (Instruction i : il)
                    {
                        if (simplifyResponse)
                        {
                            origPoints += i.getPoints().size();
                            douglasPeucker.simplify(i.getPoints());
                        }
                        fullInstructions.add(i);
                        fullPoints.add(i.getPoints());
                    }

                    // if not yet reached finish replace with 'reached via'
                    if (pathIndex + 1 < paths.size())
                    {
                        ViaInstruction newInstr = new ViaInstruction(fullInstructions.get(fullInstructions.size() - 1));
                        newInstr.setViaCount(pathIndex + 1);
                        fullInstructions.replaceLast(newInstr);
                    }
                }

            } else if (calcPoints)
            {
                PointList tmpPoints = path.calcPoints();
                if (fullPoints.isEmpty())
                    fullPoints = new PointList(tmpPoints.size(), tmpPoints.is3D());

                if (simplifyResponse)
                {
                    origPoints = tmpPoints.getSize();
                    douglasPeucker.simplify(tmpPoints);
                }
                fullPoints.add(tmpPoints);
            }

            allFound = allFound && path.isFound();
        }

        if (!fullPoints.isEmpty())
        {
            String debug = rsp.getDebugInfo() + ", simplify (" + origPoints + "->" + fullPoints.getSize() + ")";
            rsp.setDebugInfo(debug);
        }

        if (enableInstructions)
            rsp.setInstructions(fullInstructions);

        if (!allFound)
        {
            rsp.addError(new RuntimeException("Connection between locations not found"));
        }

        rsp.setPoints(fullPoints).
                setRouteWeight(fullWeight).
                setDistance(fullDistance).setTime(fullTimeInMillis);
    }

    public PathMerger setCalcPoints( boolean calcPoints )
    {
        this.calcPoints = calcPoints;
        return this;
    }

    public PathMerger setDouglasPeucker( DouglasPeucker douglasPeucker )
    {
        this.douglasPeucker = douglasPeucker;
        return this;
    }

    public PathMerger setSimplifyResponse( boolean simplifyRes )
    {
        this.simplifyResponse = simplifyRes;
        return this;
    }

    public PathMerger setEnableInstructions( boolean enableInstructions )
    {
        this.enableInstructions = enableInstructions;
        return this;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/cpg/vicarious-work-for-the-dead</sem:subject>
    <sem:predicate>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</sem:predicate>
    <sem:object datatype="sem:iri">http://www.w3.org/2004/02/skos/core#Concept</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/cpg/vicarious-work-for-the-dead</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/curriculum-planning-guide</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/cpg/vicarious-work-for-the-dead</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object xml:lang="eng" datatype="xsd:string">Vicarious work for the dead</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/cpg/vicarious-work-for-the-dead</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#narrower</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept/cpg/family-history-and-temple-work</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/cpg/vicarious-work-for-the-dead</sem:subject>
    <sem:predicate>http://www.lds.org/core#relCount</sem:predicate>
    <sem:object datatype="xsd:integer">1</sem:object>
  </sem:triple>
</sem:triples>


text:
<?php

/**
 * An interface description for Microsoft_Http_Client_Adapter_Stream classes.
 *
 * This interface decribes Microsoft_Http_Client_Adapter which supports streaming.
 *
 * @category   Microsoft
 * @package    Microsoft_Http
 * @subpackage Client_Adapter
 * @copyright  Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
interface Microsoft_Http_Client_Adapter_Stream
{
    /**
     * Set output stream
     *
     * This function sets output stream where the result will be stored.
     *
     * @param resource $stream Stream to write the output to
     *
     */
    function setOutputStream($stream);
}


text:
package cct.tools.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;

import cct.tools.Utils;

/**
 *
Title:

 *
 *
Description:

 *
 *
Copyright: Copyright (c) 2007

 *
 *
Company: ANU

 *
 * @author Dr. V. Vasilyev
 * @version 1.0
 */
public class PostMessagePanel
    extends JPanel {

  static final String nameKey = "name";
  static final String emailKey = "email";

  private JLabel jLabel1 = new JLabel();
  private JTextField nameTextField = new JTextField();
  private JTextArea messageTextArea = new JTextArea();
  private JLabel jLabel2 = new JLabel();
  private JTextField emailTextField = new JTextField();
  private GridBagLayout gridBagLayout1 = new GridBagLayout();

  boolean initialized = false;
  private MyMouseAdapter mouseAdapter = null;
  private JScrollPane jScrollPane1 = new JScrollPane();
  private JPanel jPanel1 = new JPanel();
  private BorderLayout borderLayout1 = new BorderLayout();

  private boolean nameIsOptional = true;

  public PostMessagePanel() {
    try {
      jbInit();
    }
    catch (Exception exception) {
      exception.printStackTrace();
    }
  }

  private void jbInit() throws Exception {
    this.setLayout(gridBagLayout1);
    jLabel1.setToolTipText("");
    jLabel1.setText("Your Name " + (nameIsOptional ? "(Optional)" : ""));
    jLabel2.setToolTipText("");
    jLabel2.setText("Your e-mail (Optional)");
    nameTextField.setToolTipText("Your Name");
    emailTextField.setToolTipText("Your e-mail address");
    messageTextArea.setMinimumSize(new Dimension(20, 20));
    messageTextArea.setColumns(50);
    messageTextArea.setLineWrap(true);
    messageTextArea.setRows(10);
    jPanel1.setLayout(borderLayout1);
    jPanel1.setBorder(BorderFactory.createEmptyBorder());
    jScrollPane1.setBorder(new TitledBorder(BorderFactory.createLineBorder(new Color(127, 157, 185), 1), "Your Message"));
    this.add(nameTextField, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0
        , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
    this.add(jLabel1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
                                             , GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
    this.add(jLabel2, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0
                                             , GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
    this.add(emailTextField, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0
        , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
    jScrollPane1.getViewport().add(jPanel1);
    this.add(jScrollPane1, new GridBagConstraints(0, 2, 2, 1, 1.0, 1.0
                                                  , GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0,
                                                  0));
    jPanel1.add(messageTextArea, BorderLayout.CENTER);
    Font currentFont = messageTextArea.getFont();
    int size = currentFont.getSize();
    int style = currentFont.getStyle();
    String fontName = currentFont.getFontName();
    if (size < 12) {
      size = 12;
      Font newFont = new Font(fontName, style, size);
      messageTextArea.setFont(newFont);
    }

    String name = Utils.getPreference(this, nameKey);
    name = Utils.getPreference(this, emailKey);
  }

  public void savePreferences() {
    Utils.savePreference(this, emailKey, emailTextField.getText());
    Utils.savePreference(this, nameKey, nameTextField.getText());
  }

  public void setMessage(String text) {
    initialized = true;
    if (mouseAdapter != null) {
      messageTextArea.removeMouseListener(mouseAdapter);
    }
    messageTextArea.setText(text);
  }

  public void appendMessage(String text) {
    initialized = true;
    if (mouseAdapter != null) {
      messageTextArea.removeMouseListener(mouseAdapter);
    }
    messageTextArea.append(text);
  }

  public void setInitialText(String text) {
    if (initialized) {
      return;
    }
    messageTextArea.setText(text);
    mouseAdapter = new MyMouseAdapter(this);
    messageTextArea.addMouseListener(mouseAdapter);
  }

  public String getMessage() {

    if (!initialized) {
      return "";
    }
    return messageTextArea.getText();
  }

  public void messageTextArea_mouseClicked(MouseEvent e) {
    initialized = true;
    messageTextArea.setText("");
    messageTextArea.removeMouseListener(mouseAdapter);
  }

  public String getEmailAddress() {
    return emailTextField.getText().trim();
  }

  public String getUserName() {
    return nameTextField.getText().trim();
  }

  class MyMouseAdapter
      extends MouseAdapter {
    private PostMessagePanel adaptee;
    MyMouseAdapter(PostMessagePanel adaptee) {
      this.adaptee = adaptee;
    }

    @Override
    public void mouseClicked(MouseEvent e) {
      adaptee.messageTextArea_mouseClicked(e);
    }
  }

}


text:
using HomeSeerAPI;
using Hspi.Devices;
using Nito.AsyncEx;
using NullGuard;
using System.Threading;

namespace Hspi.Connector
{
    [NullGuard(ValidationFlags.Arguments | ValidationFlags.NonPublic)]
    internal class GlobalMacrosDeviceControlManager : DeviceControlManagerCore
    {
        public GlobalMacrosDeviceControlManager(IHSApplication HS,
                    IConnectionProvider connectionProvider, CancellationToken shutdownToken) :
            base(HS, "Global Macros", DeviceType.GlobalMacros, shutdownToken)
        {
            this.connectionProvider = connectionProvider;
        }

        public override DeviceControl Create(AsyncProducerConsumerQueue<DeviceCommand> commandQueue,
                                             AsyncProducerConsumerQueue<FeedbackValue> feedbackQueue)
        {
            return new GlobalMacros(Name, connectionProvider, commandQueue, feedbackQueue);
        }

        private readonly IConnectionProvider connectionProvider;
    }
}


text:
package org.jkiss.dbeaver.ext.postgresql.ui.config;

import org.jkiss.dbeaver.ext.postgresql.PostgreMessages;
import org.jkiss.dbeaver.ext.postgresql.model.PostgreAttribute;
import org.jkiss.dbeaver.ext.postgresql.model.PostgreTableConstraint;
import org.jkiss.dbeaver.ext.postgresql.model.PostgreTableConstraintColumn;
import org.jkiss.dbeaver.model.edit.DBEObjectConfigurator;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.struct.DBSEntityAttribute;
import org.jkiss.dbeaver.model.struct.DBSEntityConstraintType;
import org.jkiss.dbeaver.ui.UITask;
import org.jkiss.dbeaver.ui.editors.object.struct.EditConstraintPage;

import java.util.Map;

/**
 * Postgre constraint configurator
 */
public class PostgreConstraintConfigurator implements DBEObjectConfigurator<PostgreTableConstraint> {

    @Override
    public PostgreTableConstraint configureObject(DBRProgressMonitor monitor, Object parent, PostgreTableConstraint constraint, Map<String, Object> options) {
        return UITask.run(() -> {
            EditConstraintPage editPage = new EditConstraintPage(
                PostgreMessages.edit_constraint_page_add_constraint,
                constraint,
                new DBSEntityConstraintType[] {
                    DBSEntityConstraintType.PRIMARY_KEY,
                    DBSEntityConstraintType.UNIQUE_KEY,
                    DBSEntityConstraintType.CHECK });
            if (!editPage.edit()) {
                return null;
            }

            constraint.setName(editPage.getConstraintName());
            constraint.setConstraintType(editPage.getConstraintType());
            if (constraint.getConstraintType().isCustom()) {
                constraint.setSource(editPage.getConstraintExpression());
            } else {
                int colIndex = 1;
                for (DBSEntityAttribute tableColumn : editPage.getSelectedAttributes()) {
                    constraint.addColumn(
                        new PostgreTableConstraintColumn(
                            constraint,
                            (PostgreAttribute) tableColumn,
                            colIndex++));
                }
            }
            return constraint;
        });
    }
}


text:
using System.IO;
using Xunit;

namespace System.Diagnostics.TextWriterTraceListenerTests
{
    public class TextWriterTraceListener_WriteTestsCtorFileName : TextWriterTraceListener_WriteTestsBase
    {
        public TextWriterTraceListener_WriteTestsCtorFileName()
        {
            CommonUtilities.DeleteFile(_fileName);
        }

        public override TextWriterTraceListener GetListener()
        {
            return new TextWriterTraceListener(_fileName);
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }
    }

    public class TextWriterTraceListener_WriteTestsCtorStream : TextWriterTraceListener_WriteTestsBase
    {
        private readonly Stream _stream;
        public TextWriterTraceListener_WriteTestsCtorStream()
        {
            CommonUtilities.DeleteFile(_fileName);
            _stream = new FileStream(_fileName, FileMode.OpenOrCreate, FileAccess.Write);
        }

        public override TextWriterTraceListener GetListener()
        {
            return new TextWriterTraceListener(_stream);
        }

        [Fact]
        public void TestWriterPropery()
        {
            var testWriter = new StreamWriter(_stream);
            using (var target = new TextWriterTraceListener())
            {
                Assert.Null(target.Writer);
                target.Writer = testWriter;
                Assert.NotNull(target.Writer);
                Assert.Same(testWriter, target.Writer);
            }
        }

        protected override void Dispose(bool disposing)
        {
            _stream.Dispose();
            base.Dispose(disposing);
        }
    }

    public abstract class TextWriterTraceListener_WriteTestsBase : FileCleanupTestBase
    {
        protected readonly string _fileName;
        private const string TestMessage = "HelloWorld";

        public TextWriterTraceListener_WriteTestsBase()
        {
            _fileName = $"{GetTestFilePath()}.xml";
        }

        public abstract TextWriterTraceListener GetListener();

        [Fact]
        public void TestWrite()
        {
            using (var target = GetListener())
            {
                target.Write(TestMessage);
            }

            Assert.Contains(TestMessage, File.ReadAllText(_fileName));
        }

        [Fact]
        public void TestWriteLine()
        {
            using (var target = GetListener())
            {
                target.WriteLine(TestMessage);
            }

            string expected = TestMessage + Environment.NewLine;
            Assert.Contains(expected, File.ReadAllText(_fileName));
        }

        [Fact]
        public void TestFlush()
        {
            using (var target = GetListener())
            {
                target.Write(TestMessage);
                target.Flush();
            }
        }

        [Fact]
        public void TestWriteAfterDisposeShouldNotThrow()
        {
            var target = GetListener();
            target.Dispose();

            target.WriteLine(TestMessage);
            target.Write(TestMessage);
            target.Flush();
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }
    }
}


text:
<?php
namespace Baskets\Pages\Bids;
class Adder
{

	public static function adder() {
		\Baskets\Pages\Framework::page_header('Add Bid | Baskets');
?>

 Add Bid

		<a href='<?=MY_URL?>/bids/list' class='add-button'>List Bids

	<form class='form'>

			Supplier: <input type='text' name='supplier'>

			Bid: <input type='text' name='bid'>

			Valid: <input type='date' name='validstart' value="<?=date('Y-m-d')?>"> to <input type='date' name='validend' value="<?=date('Y-m-d', strtotime('+1 year'))?>">

				<input type='text' name='supplierPartID' placeholder='Part ID'>
				<input type='text' name='partid' placeholder='Part Name'>
				<input type='text' name='description' placeholder='Description'>
				<input type='number' min='0' step='0.01' name='price' placeholder='Price'>

			<input type='submit'>

	</form>

<?
	\Baskets\Pages\Framework::page_footer();
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>CloverWorker</title>
<meta name="date" content="2015-03-06">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.jetel.graph.runtime

Class CloverWorker

java.lang.Object

org.jetel.graph.runtime.CloverWorker

All Implemented Interfaces:

java.lang.Runnable, java.lang.Thread.UncaughtExceptionHandler

public abstract class CloverWorker
extends java.lang.Object
implements java.lang.Runnable, java.lang.Thread.UncaughtExceptionHandler

This implementation of Runnable interface should be use for each thread inside a
 component.

See Also:

ContextProvider

Field Summary

Fields

Modifier and Type
Field and Description

protected java.lang.Exception
exception

Exception thrown by user defined method work().

protected boolean
runIt

Similar to runIt in a component
 It tells the implementing class whether

Constructor Summary

Constructors

Constructor and Description

CloverWorker(Node node,
            java.lang.String name)

Method Summary

Methods

Modifier and Type
Method and Description

void
addCloverWorkerListener(CloverWorkerListener l)

java.lang.Exception
getException()

java.lang.String
getName()

Node
getNode()

java.lang.Thread
getThread()

void
removeCloverWorkerListener(CloverWorkerListener l)

void
run()

java.lang.Thread
startWorker()

static <T extends CloverWorker>
FutureOfRunnable<T>
startWorker(T cloverWorker)

void
uncaughtException(java.lang.Thread t,
                 java.lang.Throwable e)

void
waitForStartup()

abstract void
work()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

runIt

protected boolean runIt

Similar to runIt in a component
 It tells the implementing class whether

exception

protected java.lang.Exception exception

Exception thrown by user defined method work().

Constructor Detail

CloverWorker

public CloverWorker(Node node,
            java.lang.String name)

Method Detail

run

public void run()

Specified by:

run in interface java.lang.Runnable

waitForStartup

public void waitForStartup()

getNode

public Node getNode()

work

public abstract void work()
                   throws java.lang.Exception,
                          java.lang.InterruptedException

Throws:

java.lang.Exception

java.lang.InterruptedException

startWorker

public java.lang.Thread startWorker()

startWorker

public static <T extends CloverWorker> FutureOfRunnable<T> startWorker(T cloverWorker)

getThread

public java.lang.Thread getThread()

getName

public java.lang.String getName()

addCloverWorkerListener

public void addCloverWorkerListener(CloverWorkerListener l)

removeCloverWorkerListener

public void removeCloverWorkerListener(CloverWorkerListener l)

getException

public java.lang.Exception getException()

Returns:

exception thrown in work() method if any

uncaughtException

public void uncaughtException(java.lang.Thread t,
                     java.lang.Throwable e)

Specified by:

uncaughtException in interface java.lang.Thread.UncaughtExceptionHandler

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

				<address>Copyright © 2002-2015 Javlin a.s.</address>


text:
#include "src/core/lib/security/credentials/plugin/plugin_credentials.h"

#include <string.h>

#include "src/core/lib/surface/api_trace.h"

#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/sync.h>

typedef struct {
  void *user_data;
  grpc_credentials_metadata_cb cb;
} grpc_metadata_plugin_request;

static void plugin_destruct(grpc_call_credentials *creds) {
  grpc_plugin_credentials *c = (grpc_plugin_credentials *)creds;
  if (c->plugin.state != NULL && c->plugin.destroy != NULL) {
    c->plugin.destroy(c->plugin.state);
  }
}

static void plugin_md_request_metadata_ready(void *request,
                                             const grpc_metadata *md,
                                             size_t num_md,
                                             grpc_status_code status,
                                             const char *error_details) {
  /* called from application code */
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  grpc_metadata_plugin_request *r = (grpc_metadata_plugin_request *)request;
  if (status != GRPC_STATUS_OK) {
    if (error_details != NULL) {
      gpr_log(GPR_ERROR, "Getting metadata from plugin failed with error: %s",
              error_details);
    }
    r->cb(&exec_ctx, r->user_data, NULL, 0, GRPC_CREDENTIALS_ERROR,
          error_details);
  } else {
    size_t i;
    bool seen_illegal_header = false;
    grpc_credentials_md *md_array = NULL;
    for (i = 0; i < num_md; i++) {
      if (!grpc_header_key_is_legal(md[i].key, strlen(md[i].key))) {
        gpr_log(GPR_ERROR, "Plugin added invalid metadata key: %s", md[i].key);
        seen_illegal_header = true;
        break;
      } else if (!grpc_is_binary_header(md[i].key, strlen(md[i].key)) &&
                 !grpc_header_nonbin_value_is_legal(md[i].value,
                                                    md[i].value_length)) {
        gpr_log(GPR_ERROR, "Plugin added invalid metadata value.");
        seen_illegal_header = true;
        break;
      }
    }
    if (seen_illegal_header) {
      r->cb(&exec_ctx, r->user_data, NULL, 0, GRPC_CREDENTIALS_ERROR,
            "Illegal metadata");
    } else if (num_md > 0) {
      md_array = gpr_malloc(num_md * sizeof(grpc_credentials_md));
      for (i = 0; i < num_md; i++) {
        md_array[i].key = grpc_slice_from_copied_string(md[i].key);
        md_array[i].value =
            grpc_slice_from_copied_buffer(md[i].value, md[i].value_length);
      }
      r->cb(&exec_ctx, r->user_data, md_array, num_md, GRPC_CREDENTIALS_OK,
            NULL);
      for (i = 0; i < num_md; i++) {
        grpc_slice_unref(md_array[i].key);
        grpc_slice_unref(md_array[i].value);
      }
      gpr_free(md_array);
    } else if (num_md == 0) {
      r->cb(&exec_ctx, r->user_data, NULL, 0, GRPC_CREDENTIALS_OK, NULL);
    }
  }
  gpr_free(r);
  grpc_exec_ctx_finish(&exec_ctx);
}

static void plugin_get_request_metadata(grpc_exec_ctx *exec_ctx,
                                        grpc_call_credentials *creds,
                                        grpc_polling_entity *pollent,
                                        grpc_auth_metadata_context context,
                                        grpc_credentials_metadata_cb cb,
                                        void *user_data) {
  grpc_plugin_credentials *c = (grpc_plugin_credentials *)creds;
  if (c->plugin.get_metadata != NULL) {
    grpc_metadata_plugin_request *request = gpr_malloc(sizeof(*request));
    memset(request, 0, sizeof(*request));
    request->user_data = user_data;
    request->cb = cb;
    c->plugin.get_metadata(c->plugin.state, context,
                           plugin_md_request_metadata_ready, request);
  } else {
    cb(exec_ctx, user_data, NULL, 0, GRPC_CREDENTIALS_OK, NULL);
  }
}

static grpc_call_credentials_vtable plugin_vtable = {
    plugin_destruct, plugin_get_request_metadata};

grpc_call_credentials *grpc_metadata_credentials_create_from_plugin(
    grpc_metadata_credentials_plugin plugin, void *reserved) {
  grpc_plugin_credentials *c = gpr_malloc(sizeof(*c));
  GRPC_API_TRACE("grpc_metadata_credentials_create_from_plugin(reserved=%p)", 1,
                 (reserved));
  GPR_ASSERT(reserved == NULL);
  memset(c, 0, sizeof(*c));
  c->base.type = plugin.type;
  c->base.vtable = &plugin_vtable;
  gpr_ref_init(&c->base.refcount, 1);
  c->plugin = plugin;
  return &c->base;
}


text:
<?php

include("../db.php");
global $dblink;
$allusers = mysqli_query($dblink,"SELECT * FROM `user`");
?>
<!doctype html>

    <meta charset="utf-8">
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Klarna Invoice</title>

    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700'
          rel='stylesheet'
          type='text/css'>
    <link rel="stylesheet" href="../styles/foundation.min.css">
    <link rel="stylesheet" href="../styles/main.css">

<?php include 'menu.php'; ?>

        <?php
        while($user = mysqli_fetch_assoc($allusers))
        {
            echo '
';
            echo ''.$user["email"].'';
            echo "
";
        }
        ?>


text:
package org.usfirst.frc5329.ProperRobot.commands;

import org.usfirst.frc5329.ProperRobot.Robot;

import edu.wpi.first.wpilibj.PIDController;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.PIDCommand;

/**
 *
 */
public class DriveXForward extends PIDCommand {
	private double nFeet;
	private final double tolerance = 0.1;
	private double speed;
	private final double MIN_SPEED = 0.22;
	private final double MAX_SPEED = 0.55;
	private double lastSpeed;
	private final double rampUpLimit = 0.05;
	private final double rampDownLimit = 0.3;

	//path Correction parameters
	private final double pathKp = 0.1;  //This is not a true Kp.  It's a reduction factor for the over-contributing motor
	private final double lastErrorWeight=0.2;
	private double lastError;
	private double initialHeader;

    public DriveXForward(double feet) {
    	super(0.2, 0, 0.5);
    	requires(Robot.drivetrain);
    	nFeet = feet;

    }

    // Called just before this Command runs the first time
    protected void initialize() {
    	System.out.println("Normal Drive");
    	Robot.drivetrain.resetEncoders();
    	speed = 0.25;
    	setSetpoint(nFeet);
    	initialHeader = Robot.navx.getYaw();

    }
    protected void execute() {
    	//double speed = rampSpeed(limitSpeed());
    	double speed = rampSpeed(this.speed);
    	System.out.println(speed);
    	lastSpeed = speed;
    	this.speed = speed;
    	//this error should be between -1 and 1 but could go all the way to -2 to t2
    	double error = (Robot.navx.getYaw() - initialHeader)/180 + lastError*lastErrorWeight;

    	if (error < -1) error = -1;
    	if (error >1) error = 1;
    	lastError = error;
    	double leftSpeed = speed;
    	double rightSpeed = speed;
    	//whichever side is leading, reduce the speed by a factor times the error;
    	if (error<0) rightSpeed -= pathKp*(1+error);
    	if (error>0) leftSpeed -=pathKp* (1-error);

    	Robot.drivetrain.setSpeed(leftSpeed, -rightSpeed);
    	/*if (rightSpeed < 0){
    		Robot.drivetrain.setRightEncoderNegative();
    	} else {
    		Robot.drivetrain.setRightEncoderPositive();
    	}*/
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
    	double distance = returnPIDInput();
    	System.out.println(speed + " " + Math.abs(distance-nFeet));
    	return Math.abs(distance - nFeet) <= tolerance;

    }

    protected void end() {
    }

    protected void interrupted() {
    }

	@Override
	protected double returnPIDInput() {
		return (Robot.drivetrain.getRightEncoder());
	}

	@Override
	protected void usePIDOutput(double output) {
		if (output<0)
			this.speed = output - MIN_SPEED;
		if (output > 0) this.speed = output+MIN_SPEED;
		if (output>MAX_SPEED) output = MAX_SPEED;
		if (output<-MAX_SPEED) output = -MAX_SPEED;
	}

	private double limitSpeed(){
		double maxSpeed = 1;
		double minSpeed = MIN_SPEED;
		double constraintDistance = 4;

		double calcSpeed = (maxSpeed-minSpeed)*Math.abs(returnPIDInput() -nFeet)/constraintDistance + minSpeed;
		System.out.println("Calc: " + calcSpeed);
		if (Math.abs(calcSpeed) < speed){
			System.out.println("Constrained");

			if (returnPIDInput() -nFeet<0) return calcSpeed;
			else return -calcSpeed;
		}

		return speed;
	}
	private double rampSpeed(double speed){
		double rampSpeed;
		if (speed-lastSpeed > rampUpLimit){
			rampSpeed = lastSpeed+rampUpLimit;
			System.out.println("Ramp up");
		}
		else if (speed-lastSpeed < -rampDownLimit){
			rampSpeed = lastSpeed-rampDownLimit;
			System.out.println("Ramp Down");
		}
		else{
			System.out.println("No Ramp");
			rampSpeed = speed;
		}
		return rampSpeed;
	}

}


text:
'use strict';

/**
 * This file/module contains all configuration for code standards and styling
 */

/*
 * Both linting and jscs should use the same files
 */
var jsCodes = function(options) {
  return {
    options: options,
    src: [
      '<%= appFiles.js %>',
    ],
    test: [
      '<%= appFiles.jsunit %>'
    ],
    grunt: [
      'grunt/*.js'
    ],
    gruntfile: [
      'Gruntfile.js'
    ]
  };
};

// Return the codes
module.exports = {

  /**
   * `jshint` defines the rules of our linter as well as which files we
   * should check. This file, all javascript sources, and all our unit tests
   * are linted based on the policies listed in `options`. But we can also
   * specify exclusionary patterns by prefixing them with an exclamation
   * point (!); this is useful when code comes from a third party but is
   * nonetheless inside `src/`.
   */
  jshint: jsCodes({jshintrc: '.jshintrc', reporter: require('jshint-stylish')}),

  // Some code standards
  jscs: jsCodes({config: '.jscsrc'}),

  // Angular html validate
  htmlangular: {
    options: {
      tmplext: 'html.tmpl',
      customattrs: [
        'job-*',
        'site-*',
        'provider-*',
        'placeholder',
        'start-*',
        'uib-*',
        'auto-close',
        'show-errors',
        'notification-center',
        'app-click',
        'pantheon-app-click',
        'site',
        'select-on-click',
        'switch'
      ],
      relaxerror: [
        'Empty heading.',
        'Element "img" is missing required attribute "src"',
        'Element "browser" not allowed as child of element "li" in this ' +
        'context',
        'Element "switch" not allowed as child of element "div" in this ' +
        'context',
        'The "for" attribute of the "label" element must refer to a ' +
        'non-hidden form control'
      ]
    },
    files: {
      src: ['<%= appFiles.atpl %>']
    }
  }
};


text: Simple Library to normalize mouse and touch events for all browsers & platforms.


text:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
#endregion

/// <summary>
/// Interface for game states managed by a GameStateManager. Game states
/// should control all the GameObjects and data relevant to a single screen
/// in the game.
/// </summary>
public class IGameState : MonoBehaviour {

	#region Fields and Properties

	/// <summary>
	/// The name used by the GameStateManager to identify this game state.
	/// </summary>
	public string id;

	/// <summary>
	/// The GameStateManager this game state is managed by.
	/// </summary>
	public GameStateManager Manager {get; set;}

	/// <summary>
	/// Dictionary of hideable interface elements present on this state.
	/// </summary>
	private Dictionary<string, HideableInterfaceElement> hideableElements;

	/// <summary>
	/// Dictionary of child game states that need to be intiialized, updated,
	/// and communicated with by this master game state.
	/// </summary>
	private Dictionary<string, IGameStateChild> stateChildren;

	/// <summary>
	/// The amount of time spent waiting.
	/// </summary>
	private float waitingTime = 0;

	/// <summary>
	/// The GUI canvas used to draw the user interface for this screen.
	/// </summary>
	public Canvas GuiCanvas { get; protected set; }

	#endregion

	#region Game State Management

	/// <summary>
	/// Update this instance.
	/// </summary>
	public void Update () {
		OnUpdateState ();
	}

	/// <summary>
	/// Raises the initialize state event.
	/// </summary>
	public virtual void OnInitializeState () {
		hideableElements = new Dictionary<string, HideableInterfaceElement> ();
		GuiCanvas = transform.FindChild ("GUI Canvas").GetComponent<Canvas> ();

		// Find and initialize children game states.
		stateChildren = new Dictionary<string, IGameStateChild> ();
		Component[] children = GetComponentsInChildren<IGameStateChild> (true);
		foreach (IGameStateChild child in children) {
			child.OnInitializeState (this);
			stateChildren.Add (child.name, child);
		}
	}

	/// <summary>
	/// Raises the update state event.
	/// </summary>
	public virtual void OnUpdateState () {

		// Update children.
		foreach (IGameStateChild child in stateChildren.Values) {
			child.OnUpdateState ();
		}
	}

	/// <summary>
	/// Raises the exit state event.
	/// </summary>
	public virtual void OnExitState () {
		// Exit children.
		if (stateChildren != null) {
			foreach (IGameStateChild child in stateChildren.Values) {
				child.OnExitState ();
			}
		}
	}

	/// <summary>
	/// Transitions to a new game state from the current one via the
	/// attached manager. Wipes all states currently on the game state
	/// stack.
	/// </summary>
	/// <param id="id">State id.</param>
	public void SwitchState (string id) {
		Manager.SwitchState (id);
	}

	/// <summary>
	/// Pushes a new state on top of this one on the game state stack.
	/// </summary>
	/// <param name="id">Identifier.</param>
	public void PushState (string id) {
		Manager.PushState (id);
	}

	/// <summary>
	/// Pushes a new state on top of this one, and returns a reference to it.
	/// </summary>
	/// <returns>Reference to the game state pushed.</returns>
	/// <param name="id">Identifier.</param>
	public IGameState GetPushState (string id) {
		return Manager.PushState (id);
	}

	/// <summary>
	/// Pops this state off of the screen stack.
	/// </summary>
	public void PopState () {
		Manager.PopState ();
	}

	#endregion

	#region Initializing GUI Elements

	/// <summary>
	/// Shows the hideable element with the given name.
	/// </summary>
	/// <param name="name">Name.</param>
	protected void ShowGUIElement (string name) {
		hideableElements[name].Show ();
	}

	/// <summary>
	/// Hides the hideable element with the given name.
	/// </summary>
	/// <param name="name">Name.</param>
	protected void HideGUIElement (string name) {
		hideableElements[name].Hide ();
	}

	/// <summary>
	/// Gets the hideable element with the given name.
	/// </summary>
	/// <param name="name">Name.</param>
	protected HideableInterfaceElement GetGUIElement (string name) {
		return hideableElements[name];
	}

	/// <summary>
	/// Adds and initializes a hideable element.
	/// Assumed child of guiCanvas, hidden by default.
	/// </summary>
	/// <param name="name">Name of GameObject.</param>
	protected void AddHideableElement (string name) {
		AddHideableElement (name, GuiCanvas.transform, true);
	}

	/// <summary>
	/// Adds and initializes a hideable element.
	/// Hidden by default.
	/// </summary>
	/// <param name="name">Name of GameObject.</param>
	/// <param name="parent">Parent Transform.</param>
	protected void AddHideableElement (string name, Transform parent) {
		AddHideableElement (name, parent, true);
	}

	/// <summary>
	/// Adds and initializes a hideable element.
	/// Hidden by default.
	/// </summary>
	/// <param name="name">Name of GameObject.</param>
	/// <param name="startsHidden">If set to <c>true</c>, starts hidden.</param>
	protected void AddHideableElement (string name, bool startsHidden) {
		AddHideableElement (name, GuiCanvas.transform, startsHidden);
	}

	/// <summary>
	/// Adds and initializes a hideable element.
	/// </summary>
	/// <param name="name">Name of GameObject.</param>
	/// <param name="parent">Parent Transform.</param>
	/// <param name="startsHidden">If set to <c>true</c>, starts hidden.</param>
	protected void AddHideableElement (string name, Transform parent, bool startsHidden) {
		HideableInterfaceElement element = parent.FindChild (name).GetComponent<HideableInterfaceElement> ();
		hideableElements.Add (name, element);
		if (startsHidden) element.HideImmediate ();
		element.CanvasGroup.alpha = 0;
	}

	/// <summary>
	/// Searches for and adds and initializes a hideable element.
	/// </summary>
	/// <param name="name">Name of GameObject.</param>
	/// <param name="startsHidden">If set to <c>true</c> starts hidden.</param>
	/// <param name="deepSearch">If set to <c>true</c> depth first search.</param>
	protected void SearchHideableElement (string name, bool startsHidden = true, bool deepSearch = false) {
		HideableInterfaceElement element;

		if (deepSearch) {
			element = GuiCanvas.transform.DepthFirstSearchChildren (name).GetComponent<HideableInterfaceElement> ();
		}
		else {
			element = GuiCanvas.transform.BreadthFirstSearchChildren (name).GetComponent<HideableInterfaceElement> ();
		}

		hideableElements.Add (name, element);
		if (startsHidden) element.HideImmediate ();
	}

	#endregion

	#region Children

	/// <summary>
	/// Gets a game state child by it's game object name.
	/// </summary>
	/// <param name="name">Name of game object.</param>
	protected IGameStateChild GetChild (string name) {
		return stateChildren [name];
	}

           	#endregion
}


text:
static void Int32DictInt_Resize(struct Int32DictInt *self, Int32 newLen)
{
	struct Int32DictNode *newHeap, *oldHeap;
	Int32 *newBuckets, *oldBuckets;
	Int32 i, oldLen, newMask, oldBucketIndex, newBucketIndex, oldNodeIndex;

	// Get the old heap info.
	oldLen = self->mask + 1;
	oldHeap = self->heap;
	oldBuckets = self->buckets;

	// Construct a new heap and buckets twice as large as the old ones.
	if ((PtrInt)newLen > PtrIntMax / sizeof(struct Int32DictNode)) Smile_Abort_OutOfMemory();
	newBuckets = GC_MALLOC_RAW_ARRAY(Int32, newLen);
	if (newBuckets == NULL) Smile_Abort_OutOfMemory();
	newHeap = GC_MALLOC_STRUCT_ARRAY(struct Int32DictNode, newLen);
	if (newHeap == NULL) Smile_Abort_OutOfMemory();

	// The new buckets start out empty.  This runs in O(n) time.
	for (i = 0; i < newLen; i++) {
		newBuckets[i] = -1;
	}

	// Spin over the nodes in the old heap and insert them into a new set of buckets twice as large
	// as the old set of buckets, which keeps the average bucket size <= 1 node, guaranteeing amortized
	// O(1) read time.
	newMask = newLen - 1;
	i = 0;

	// The outer loop spins over O(n) buckets.
	for (oldBucketIndex = 0; oldBucketIndex < oldLen; oldBucketIndex++) {

		// This inner loop runs in O(1) amortized time, assuming reasonable random distribution of the keys.
		for (oldNodeIndex = oldBuckets[oldBucketIndex]; oldNodeIndex >= 0; oldNodeIndex = oldHeap[oldNodeIndex].next) {
			newBucketIndex = oldHeap[oldNodeIndex].key & newMask;

			newHeap[i].next = newBuckets[newBucketIndex];
			newHeap[i].key = oldHeap[oldNodeIndex].key;
			newHeap[i].value = oldHeap[oldNodeIndex].value;
			newBuckets[newBucketIndex] = i++;

			oldHeap[oldNodeIndex].value = NULL;		// Help the GC out by breaking references.
		}
	}

	// The new buckets and new heap are now the canonical data, so replace this dictionary's content
	// with them.
	self->heap = newHeap;
	self->buckets = newBuckets;
	self->mask = newMask;

	// Everything has been inserted into the new buckets and new heap, but the new heap still needs
	// the rest of its free nodes to be created, if there's any unused space at the end.  This runs
	// in O(n) time, since the callers guarantee the number of free nodes is always proportional to
	// the number of allocated nodes.
	self->firstFree = (i < newLen ? i : -1);
	for (; i < newLen - 1; i++) {
		newHeap[i].next = i + 1;
		newHeap[i].key = 0;
		newHeap[i].value = NULL;
	}
	newHeap[i].next = -1;
	newHeap[i].key = 0;
	newHeap[i].value = NULL;
}

//-------------------------------------------------------------------------------------------------
//  Semi-Private interface

/// <summary>
/// Append a new key/value pair to the end of the dictionary.  The key must not already exist
/// as a member of the dictionary.
/// </summary>
/// <param name="self">The casted pointer to the implementation of the dictionary.</param>
/// <param name="key">The key for the new key/value pair to add.</param>
/// <param name="value">The value for the new key/value pair to add.</param>
Int32 Int32DictInt_Append(struct Int32DictInt *self, Int32 key, const void *value)
{
	struct Int32DictNode *heap;
	Int32 nodeIndex, bucketIndex;

	if (self->firstFree < 0) {
		Int32DictInt_Resize(self, (self->mask + 1) * 2);
	}

	heap = self->heap;

	nodeIndex = self->firstFree;
	bucketIndex = key & self->mask;
	self->firstFree = heap[nodeIndex].next;

	heap[nodeIndex].next = self->buckets[bucketIndex];
	heap[nodeIndex].key = key;
	heap[nodeIndex].value = (void *)value;

	self->buckets[bucketIndex] = nodeIndex;
	self->count++;

	return nodeIndex;
}

//-------------------------------------------------------------------------------------------------
//  Public interface

/// <summary>
/// Make a perfect clone of this dictionary.
/// </summary>
/// <param name="intDict">The dictionary to make a clone of.</param>
/// <param name="valueCloner">An optional "cloner" function that can correctly duplicate each value.
/// This method will be passed the key, the original value, and a custom parameter, and should
/// return the new value for that key.  If this function is a NULL pointer, the value will be shallow-copied as-is.</param>
/// <param name="param">A custom parameter to pass to the "cloner" function.  If the "cloner" function
/// is NULL, this should also be NULL.</param>
/// <returns>The cloned dictionary.</returns>
Int32Dict Int32Dict_Clone(Int32Dict intDict, Int32Dict_ValueCloner valueCloner, void *param)
{
	struct Int32DictInt *newIntDict;
	struct Int32DictInt *oldIntDict = (struct Int32DictInt *)intDict;
	Int32 newSize, bucket, nodeIndex, nextNodeIndex, key;
	Int32 *buckets;
	struct Int32DictNode *oldHeap, *newHeap;

	newIntDict = GC_MALLOC_STRUCT(struct Int32DictInt);
	if (newIntDict == NULL) Smile_Abort_OutOfMemory();

	newSize = oldIntDict->mask + 1;

	newIntDict->count = oldIntDict->count;
	newIntDict->firstFree = oldIntDict->firstFree;
	newIntDict->mask = oldIntDict->mask;

	newIntDict->buckets = buckets = (Int32 *)GC_MALLOC_ATOMIC(sizeof(Int32) * newSize);
	if (buckets == NULL) Smile_Abort_OutOfMemory();

	MemCpy(buckets, oldIntDict->buckets, sizeof(Int32) * newSize);

	newIntDict->heap = newHeap = GC_MALLOC_STRUCT_ARRAY(struct Int32DictNode, newSize);
	if (newHeap == NULL) Smile_Abort_OutOfMemory();

	oldHeap = oldIntDict->heap;

	if (valueCloner != NULL) {
		for (bucket = 0; bucket <= oldIntDict->mask; bucket++) {
			nodeIndex = buckets[bucket];
			while (nodeIndex >= 0) {
				newHeap[nodeIndex].key = key = oldHeap[nodeIndex].key;
				newHeap[nodeIndex].value = valueCloner(key, oldHeap[nodeIndex].value, param);
				newHeap[nodeIndex].next = nextNodeIndex = oldHeap[nodeIndex].next;
				nodeIndex = nextNodeIndex;
			}
		}
	}
	else {
		for (bucket = 0; bucket <= oldIntDict->mask; bucket++) {
			nodeIndex = buckets[bucket];
			while (nodeIndex >= 0) {
				newHeap[nodeIndex].key = oldHeap[nodeIndex].key;
				newHeap[nodeIndex].value = oldHeap[nodeIndex].value;
				newHeap[nodeIndex].next = nextNodeIndex = oldHeap[nodeIndex].next;
				nodeIndex = nextNodeIndex;
			}
		}
	}

	nodeIndex = oldIntDict->firstFree;

	while (nodeIndex >= 0) {
		newHeap[nodeIndex].key = oldHeap[nodeIndex].key;
		newHeap[nodeIndex].value = oldHeap[nodeIndex].value;
		newHeap[nodeIndex].next = nextNodeIndex = oldHeap[nodeIndex].next;
		nodeIndex = nextNodeIndex;
	}

	return (Int32Dict)newIntDict;
}

/// <summary>
/// Get the "first" key/value pair from the dictionary.  As dictionaries are UNORDERED,
/// this function is really only useful if you have a dictionary that you know contains
/// one item.  This will run in AMORTIZED O(1) time, and does not allocate heap memory.
/// </summary>
/// <param name="intDict">A pointer to the dictionary.</param>
/// <returns>The "first" key/value pairs in the dictionary.  If the dictionary contains
/// more than one key/value pair, this will be a randomly-chosen entry.  If the dictionary
/// is empty, this will contain "0" and "NULL" for the key and value, respectively.</returns>
Int32DictKeyValuePair Int32Dict_GetFirst(Int32Dict intDict)
{
	struct Int32DictInt *self;
	Int32 bucket, nodeIndex;
	Int32 *buckets;
	Int32DictKeyValuePair result;
	struct Int32DictNode *heap, *node;

	self = (struct Int32DictInt *)intDict;

	buckets = self->buckets;
	heap = self->heap;

	for (bucket = 0; bucket <= self->mask; bucket++) {
		nodeIndex = buckets[bucket];
		while (nodeIndex >= 0) {
			node = heap + nodeIndex;

			result.key = node->key;
			result.value = node->value;
			return result;
		}
	}

	result.key = 0;
	result.value = NULL;
	return result;
}

/// <summary>
/// Get all key/value pairs from the dictionary.
/// </summary>
/// <param name="intDict">A pointer to the dictionary.</param>
/// <returns>An array containing all of the key/value pairs in the dictionary, in no specific order.
/// This will be the same length as returned by Int32Dict_GetCount().</returns>
Int32DictKeyValuePair *Int32Dict_GetAll(Int32Dict intDict)
{
	struct Int32DictInt *self;
	Int32 bucket, nodeIndex;
	Int32 *buckets;
	Int32DictKeyValuePair *pairs, *dest;
	struct Int32DictNode *heap, *node;

	self = (struct Int32DictInt *)intDict;

	pairs = GC_MALLOC_STRUCT_ARRAY(Int32DictKeyValuePair, self->count);
	if (pairs == NULL) Smile_Abort_OutOfMemory();

	buckets = self->buckets;
	dest = pairs;
	heap = self->heap;

	for (bucket = 0; bucket <= self->mask; bucket++) {
		nodeIndex = buckets[bucket];
		while (nodeIndex >= 0) {
			node = heap + nodeIndex;
			dest->key = node->key;
			dest->value = node->value;
			dest++;
			nodeIndex = node->next;
		}
	}

	return pairs;
}

/// <summary>
/// Get all keys from the dictionary.
/// </summary>
/// <param name="intDict">A pointer to the dictionary.</param>
/// <returns>An array containing all of the keys in the dictionary, in no specific order.
/// This will be the same length as returned by Int32Dict_GetCount().</returns>
Int32 *Int32Dict_GetKeys(Int32Dict intDict)
{
	struct Int32DictInt *self;
	Int32 bucket, nodeIndex;
	Int32 *buckets;
	Int32 *keys, *dest;
	struct Int32DictNode *heap, *node;

	self = (struct Int32DictInt *)intDict;

	keys = GC_MALLOC_RAW_ARRAY(Int32, self->count);
	if (keys == NULL) Smile_Abort_OutOfMemory();

	buckets = self->buckets;
	dest = keys;
	heap = self->heap;

	for (bucket = 0; bucket <= self->mask; bucket++) {
		nodeIndex = buckets[bucket];
		while (nodeIndex >= 0) {
			node = heap + nodeIndex;
			*dest++ = node->key;
			nodeIndex = node->next;
		}
	}

	return keys;
}

/// <summary>
/// Get all values from the dictionary.
/// </summary>
/// <param name="intDict">A pointer to the dictionary.</param>
/// <returns>An array containing all of the values in the dictionary, in no specific order.
/// This will be the same length as returned by Int32Dict_GetCount().</returns>
void **Int32Dict_GetValues(Int32Dict intDict)
{
	struct Int32DictInt *self;
	Int32 bucket, nodeIndex;
	Int32 *buckets;
	void **values, **dest;
	struct Int32DictNode *heap, *node;

	self = (struct Int32DictInt *)intDict;

	values = GC_MALLOC_STRUCT_ARRAY(void *, self->count);
	if (values == NULL) Smile_Abort_OutOfMemory();

	buckets = self->buckets;
	dest = values;
	heap = self->heap;

	for (bucket = 0; bucket <= self->mask; bucket++) {
		nodeIndex = buckets[bucket];
		while (nodeIndex >= 0) {
			node = heap + nodeIndex;
			*dest++ = node->value;
			nodeIndex = node->next;
		}
	}

	return values;
}

/// <summary>
/// Delete all key/value pairs in the dictionary, resetting it back to its initial state.
/// </summary>
/// <param name="newSize">The new allocation size of the dictionary, which is the number of
/// items the dictionary can hold without it needing to invoke another reallocation.</param>
void Int32Dict_ClearWithSize(Int32Dict intDict, Int32 newSize)
{
	struct Int32DictInt *self;
	struct Int32DictNode *heap;
	Int32 *buckets;
	Int32 i;

	if (newSize < 0x10) newSize = 0x10;
	if (newSize > 0x1000000) newSize = 0x1000000;

	newSize = NextPowerOfTwo32(newSize);

	self = (struct Int32DictInt *)intDict;

	self->buckets = buckets = GC_MALLOC_RAW_ARRAY(Int32, newSize);
	if (buckets == NULL) Smile_Abort_OutOfMemory();
	self->heap = heap = GC_MALLOC_STRUCT_ARRAY(struct Int32DictNode, newSize);
	if (heap == NULL) Smile_Abort_OutOfMemory();
	self->firstFree = 0;
	self->count = 0;
	self->mask = newSize - 1;

	for (i = 0; i < newSize; i++) {
		buckets[i] = -1;
	}

	for (i = 0; i < newSize - 1; i++) {
		heap[i].next = i + 1;
		heap[i].key = 0;
		heap[i].value = NULL;
	}

	heap[i].next = -1;
	heap[i].key = 0;
	heap[i].value = NULL;
}

/// <summary>
/// Remove a specific key/value pair from the dictionary, by key.
/// </summary>
/// <param name="intDict">A pointer to the dictionary.</param>
/// <param name="key">The key to remove.</param>
/// <returns>True if the key was found (and thus removed), False if the key was not found.</returns>
Bool Int32Dict_Remove(Int32Dict intDict, Int32 key)
{
	struct Int32DictInt *self;
	struct Int32DictNode *heap;
	Int32 *buckets;
	Int32 nodeIndex, prevIndex;
	Int32 mask;

	self = (struct Int32DictInt *)intDict;
	heap = self->heap;
	buckets = self->buckets;

	mask = self->mask;
	nodeIndex = buckets[key & mask];
	prevIndex = -1;

	while (nodeIndex >= 0) {
		if (heap[nodeIndex].key == key) {
			if (prevIndex >= 0)
				heap[prevIndex].next = heap[nodeIndex].next;
			else
				buckets[key & mask] = heap[nodeIndex].next;

			heap[nodeIndex].key = 0;
			heap[nodeIndex].value = NULL;
			heap[nodeIndex].next = self->firstFree;

			self->firstFree = nodeIndex;
			self->count--;

			if (self->count <= ((mask + 1) >> 2) && (mask + 1) > 16) {
				Int32DictInt_Resize(self, (mask + 1) >> 1);
			}
			return True;
		}

		prevIndex = nodeIndex;
		nodeIndex = heap[nodeIndex].next;
	}

	return False;
}

/// <summary>
/// Compute statistics on this dictionary.
/// </summary>
/// <param name="intDict">A pointer to the dictionary.</param>
SMILE_API_FUNC DictStats Int32Dict_ComputeStats(Int32Dict intDict)
{
	struct Int32DictInt *self;
	struct Int32DictNode *heap;
	Int32 bucketIndex, nodeIndex, numInThisBucket;
	Int32 *buckets;
	DictStats stats;

	self = (struct Int32DictInt *)intDict;
	heap = self->heap;
	buckets = self->buckets;

	stats = GC_MALLOC_STRUCT(struct DictStatsStruct);

	stats->heapTotal = self->mask + 1;
	stats->heapAlloc = self->count;
	stats->heapFree = self->mask + 1 - self->count;

	stats->bucketStats = SimpleStats_Create();
	stats->keyStats = SimpleStats_Create();

	for (bucketIndex = 0; bucketIndex <= self->mask; bucketIndex++) {
		numInThisBucket = 0;
		for (nodeIndex = buckets[bucketIndex]; nodeIndex >= 0; nodeIndex = heap[nodeIndex].next) {
			numInThisBucket++;
			SimpleStats_Add(stats->keyStats, 1);
		}
		SimpleStats_Add(stats->bucketStats, numInThisBucket);
	}

	return stats;
}

Bool Int32Dict_ForEach(Int32Dict intDict, Bool (*func)(Int32 key, void *value, void *param), void *param)
{
	struct Int32DictInt *self;
	Int32 bucket, nodeIndex;
	Int32 *buckets;
	struct Int32DictNode *heap, *node;

	self = (struct Int32DictInt *)intDict;

	buckets = self->buckets;
	heap = self->heap;

	for (bucket = 0; bucket <= self->mask; bucket++) {
		nodeIndex = buckets[bucket];
		while (nodeIndex >= 0) {
			node = heap + nodeIndex;
			if (!func(node->key, node->value, param))
				return False;
			nodeIndex = node->next;
		}
	}

	return True;
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Syll. fung. (Abellini) 8: 336 (1906)

#### Original name
Mollisia culmina Sacc., 1906

### Remarks
null