text:
package net.jforum.dao.generic;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import net.jforum.JForumExecutionContext;
import net.jforum.SessionFacade;
import net.jforum.dao.DataAccessDriver;
import net.jforum.dao.ForumDAO;
import net.jforum.dao.PollDAO;
import net.jforum.dao.PostDAO;
import net.jforum.dao.TopicDAO;
import net.jforum.entities.KarmaStatus;
import net.jforum.entities.Topic;
import net.jforum.entities.User;
import net.jforum.exceptions.DatabaseException;
import net.jforum.repository.ForumRepository;
import net.jforum.search.SearchArgs;
import net.jforum.search.SearchResult;
import net.jforum.util.DbUtils;
import net.jforum.util.SafeHtml;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;

/**
 * @author Rafael Steil
 * @version $Id$
 */
public class GenericTopicDAO extends AutoKeys implements TopicDAO
{
	private static final String USER_ID = "user_id";
	/**
	 * @see net.jforum.dao.TopicDAO#findTopicsByDateRange(net.jforum.search.SearchArgs)
	 */
	public SearchResult<Topic> findTopicsByDateRange(final SearchArgs args)
	{
		SearchResult<Topic> result = null;

		PreparedStatement pstmt = null;
		ResultSet resultSet = null;

		try {
			pstmt = JForumExecutionContext.getConnection().prepareStatement(
				SystemGlobals.getSql("TopicModel.findTopicsByDateRange"));

			pstmt.setTimestamp(1, new Timestamp(args.getFromDate().getTime()));
			pstmt.setTimestamp(2, new Timestamp(args.getToDate().getTime()));

			resultSet = pstmt.executeQuery();
			final List<Integer> list = new ArrayList<Integer>();

			int counter = 0;

			while (resultSet.next()) {
				if (counter >= args.startFrom() && counter < args.startFrom() + args.fetchCount()) {
					list.add(Integer.valueOf(resultSet.getInt(1)));
				}

				counter++;
			}

			result = new SearchResult<Topic>(this.newMessages(list), counter);
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(resultSet, pstmt);
		}

		return result;
	}

	/**
	 * @see net.jforum.dao.TopicDAO#fixFirstLastPostId(int)
	 */
	public void fixFirstLastPostId(final int topicId)
	{
		PreparedStatement pstmt = null;
		ResultSet resultSet = null;
		try {
			pstmt = JForumExecutionContext.getConnection().prepareStatement(
					SystemGlobals.getSql("TopicModel.getFirstLastPostId"));
			pstmt.setInt(1, topicId);

			resultSet = pstmt.executeQuery();
			if (resultSet.next()) {
				final int first = resultSet.getInt("first_post_id");
				final int last = resultSet.getInt("last_post_id");

				resultSet.close();
				pstmt.close();

				pstmt = JForumExecutionContext.getConnection().prepareStatement(
						SystemGlobals.getSql("TopicModel.fixFirstLastPostId"));
				pstmt.setInt(1, first);
				pstmt.setInt(2, last);
				pstmt.setInt(3, topicId);
				pstmt.executeUpdate();
			}
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(resultSet, pstmt);
		}
	}

	/**
	 * @see net.jforum.dao.TopicDAO#selectById(int)
	 */
	public Topic selectById(final int topicId)
	{
		PreparedStatement pstmt = null;
		try {
			pstmt = JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("TopicModel.selectById"));
			pstmt.setInt(1, topicId);

			Topic topic = new Topic();
			final List<Topic> list = this.fillTopicsData(pstmt);

			if (!list.isEmpty()) {
				topic = (Topic) list.get(0);
			}

			return topic;
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(pstmt);
		}
	}

	/**
	 * @see net.jforum.dao.TopicDAO#selectRaw(int)
	 */
	public Topic selectRaw(final int topicId)
	{
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			pstmt = JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("TopicModel.selectRaw"));
			pstmt.setInt(1, topicId);

			Topic topic = new Topic();
			rs = pstmt.executeQuery();
			if (rs.next()) {
				topic = this.getBaseTopicData(rs);
			}

			return topic;
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(rs, pstmt);
		}
	}

	/**
	 * @see net.jforum.dao.TopicDAO#delete(net.jforum.entities.Topic, boolean)
	 */
	public void delete(final Topic topic, final boolean fromModeration)
	{
		final List<Topic> list = new ArrayList<Topic>();
		list.add(topic);
		this.deleteTopics(list, fromModeration);
	}

	public void deleteTopics(List<Topic> topics, boolean fromModeration)
	{
		// Topic
		PreparedStatement pstmt = null;
		try {
			pstmt = JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("TopicModel.delete"));

			ForumDAO forumDao = DataAccessDriver.getInstance().newForumDAO();
			PostDAO postDao = DataAccessDriver.getInstance().newPostDAO();
			PollDAO pollDao = DataAccessDriver.getInstance().newPollDAO();

			for (Iterator<Topic> iter = topics.iterator(); iter.hasNext();) {
				Topic topic = (Topic) iter.next();

				// Remove watches
				this.removeSubscriptionByTopic(topic.getId());

				// Remove the messages
				postDao.deleteByTopic(topic.getId());

				// Remove the poll
				pollDao.deleteByTopicId(topic.getId());

				// Delete the topic itself
				pstmt.setInt(1, topic.getId());
				pstmt.executeUpdate();

				if (!fromModeration) {
					forumDao.decrementTotalTopics(topic.getForumId(), 1);
				}
			}
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(pstmt);
		}

	}

	/**
	 * @see net.jforum.dao.TopicDAO#deleteByForum(int)
	 */
	public void deleteByForum(int forumId)
	{
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		try {
			pstmt = JForumExecutionContext.getConnection().prepareStatement(
					SystemGlobals.getSql("TopicModel.deleteByForum"));
			pstmt.setInt(1, forumId);

			rs = pstmt.executeQuery();
			List<Topic> topics = new ArrayList<Topic>();

			while (rs.next()) {
				Topic topic = new Topic();
				topic.setId(rs.getInt("topic_id"));
				topic.setForumId(forumId);

				topics.add(topic);
			}

			this.deleteTopics(topics, true);
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(rs, pstmt);
		}
	}

	/**
	 * @see net.jforum.dao.TopicDAO#update(net.jforum.entities.Topic)
	 */
	public void update(Topic topic)
	{
		PreparedStatement pstmt = null;
		try {
			pstmt = JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("TopicModel.update"));

			pstmt.setString(1, topic.getTitle());
			pstmt.setInt(2, topic.getLastPostId());
			pstmt.setInt(3, topic.getFirstPostId());
			pstmt.setInt(4, topic.getType());
			pstmt.setInt(5, topic.isModerated() ? 1 : 0);
			pstmt.setInt(6, topic.getVoteId());
			pstmt.setInt(7, topic.getId());
			pstmt.executeUpdate();
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(pstmt);
		}

	}

	/**
	 * @see net.jforum.dao.TopicDAO#addNew(net.jforum.entities.Topic)
	 */
	public int addNew(Topic topic)
	{
		PreparedStatement pstmt = null;

		try {
			pstmt = this.getStatementForAutoKeys("TopicModel.addNew");

			pstmt.setInt(1, topic.getForumId());
			pstmt.setString(2, topic.getTitle());
			pstmt.setInt(3, topic.getPostedBy().getId());
			pstmt.setTimestamp(4, new Timestamp(topic.getTime().getTime()));
			pstmt.setInt(5, topic.getFirstPostId());
			pstmt.setInt(6, topic.getLastPostId());
			pstmt.setInt(7, topic.getType());
			pstmt.setInt(8, topic.isModerated() ? 1 : 0);

			this.setAutoGeneratedKeysQuery(SystemGlobals.getSql("TopicModel.lastGeneratedTopicId"));

			int topicId = this.executeAutoKeysQuery(pstmt);

			topic.setId(topicId);

			return topicId;
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(pstmt);
		}
	}

	/**
	 * @see net.jforum.dao.TopicDAO#incrementTotalViews(int)
	 */
	public void incrementTotalViews(int topicId)
	{
		PreparedStatement pstmt = null;
		try {
			pstmt = JForumExecutionContext.getConnection().prepareStatement(
				SystemGlobals.getSql("TopicModel.incrementTotalViews"));
			pstmt.setInt(1, topicId);
			pstmt.executeUpdate();
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(pstmt);
		}
	}

	/**
	 * @see net.jforum.dao.TopicDAO#incrementTotalReplies(int)
	 */
	public void incrementTotalReplies(int topicId)
	{
		PreparedStatement pstmt = null;
		try {
			pstmt = JForumExecutionContext.getConnection().prepareStatement(
					SystemGlobals.getSql("TopicModel.incrementTotalReplies"));
			pstmt.setInt(1, topicId);
			pstmt.executeUpdate();
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(pstmt);
		}
	}

	/**
	 * @see net.jforum.dao.TopicDAO#decrementTotalReplies(int)
	 */
	public void decrementTotalReplies(int topicId)
	{
		PreparedStatement pstmt = null;
		try {
			pstmt = JForumExecutionContext.getConnection().prepareStatement(
					SystemGlobals.getSql("TopicModel.decrementTotalReplies"));
			pstmt.setInt(1, topicId);
			pstmt.executeUpdate();
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(pstmt);
		}
	}

	/**
	 * @see net.jforum.dao.TopicDAO#setLastPostId(int, int)
	 */
	public void setLastPostId(int topicId, int postId)
	{
		PreparedStatement pstmt = null;
		try {
			pstmt = JForumExecutionContext.getConnection().prepareStatement(
					SystemGlobals.getSql("TopicModel.setLastPostId"));
			pstmt.setInt(1, postId);
			pstmt.setInt(2, topicId);
			pstmt.executeUpdate();
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(pstmt);
		}
	}

	/**
	 * @see net.jforum.dao.TopicDAO#selectAllByForum(int)
	 */
	public List<Topic> selectAllByForum(int forumId)
	{
		return this.selectAllByForumByLimit(forumId, 0, Integer.MAX_VALUE);
	}

	/**
	 * @see net.jforum.dao.TopicDAO#selectAllByForumByLimit(int, int, int)
	 */
	public List<Topic> selectAllByForumByLimit(int forumId, int startFrom, int count)
	{
		String sql = SystemGlobals.getSql("TopicModel.selectAllByForumByLimit");

		PreparedStatement pstmt = null;

		try {
			pstmt = JForumExecutionContext.getConnection().prepareStatement(sql);
			pstmt.setInt(1, forumId);
			pstmt.setInt(2, forumId);
			pstmt.setInt(3, startFrom);
			pstmt.setInt(4, count);

			return this.fillTopicsData(pstmt);
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(pstmt);
		}
	}

	/**
	 * @see net.jforum.dao.TopicDAO#selectByUserByLimit(int, int, int)
	 */
	public List<Topic> selectByUserByLimit(int userId, int startFrom, int count)
	{
		PreparedStatement pstmt = null;
		try {
			pstmt = JForumExecutionContext.getConnection().prepareStatement(
					SystemGlobals.getSql("TopicModel.selectByUserByLimit").replaceAll(":fids:",
							ForumRepository.getListAllowedForums()));

			pstmt.setInt(1, userId);
			pstmt.setInt(2, startFrom);
			pstmt.setInt(3, count);

			return this.fillTopicsData(pstmt);
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(pstmt);
		}
	}

	/**
	 * @see net.jforum.dao.TopicDAO#countUserTopics(int)
	 */
	public int countUserTopics(int userId)
	{
		int total = 0;

		PreparedStatement pstmt = null;
		ResultSet resultSet = null;
		try {
			pstmt = JForumExecutionContext.getConnection().prepareStatement(
					SystemGlobals.getSql("TopicModel.countUserTopics").replaceAll(":fids:",
							ForumRepository.getListAllowedForums()));
			pstmt.setInt(1, userId);

			resultSet = pstmt.executeQuery();

			if (resultSet.next()) {
				total = resultSet.getInt(1);
			}

			return total;
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(resultSet, pstmt);
		}
	}

	protected Topic getBaseTopicData(ResultSet rs) throws SQLException
	{
		Topic topic = new Topic();

		topic.setTitle(rs.getString("topic_title"));
		topic.setId(rs.getInt("topic_id"));
		topic.setTime(new Date(rs.getTimestamp("topic_time").getTime()));
		topic.setStatus(rs.getInt("topic_status"));
		topic.setTotalViews(rs.getInt("topic_views"));
		topic.setTotalReplies(rs.getInt("topic_replies"));
		topic.setFirstPostId(rs.getInt("topic_first_post_id"));
		topic.setLastPostId(rs.getInt("topic_last_post_id"));
		topic.setType(rs.getInt("topic_type"));
		topic.setForumId(rs.getInt("forum_id"));
		topic.setModerated(rs.getInt("moderated") == 1);
		topic.setVoteId(rs.getInt("topic_vote_id"));
		topic.setMovedId(rs.getInt("topic_moved_id"));

		User user = new User();
		user.setId(rs.getInt(USER_ID));

		topic.setPostedBy(user);

		return topic;
	}

	/**
	 * @see net.jforum.dao.TopicDAO#getMaxPostId(int)
	 */
	public int getMaxPostId(int topicId)
	{
		int id = -1;

		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			pstmt = JForumExecutionContext.getConnection()
					.prepareStatement(SystemGlobals.getSql("TopicModel.getMaxPostId"));
			pstmt.setInt(1, topicId);

			rs = pstmt.executeQuery();
			if (rs.next()) {
				id = rs.getInt("post_id");
			}

			return id;
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(rs, pstmt);
		}
	}

	/**
	 * @see net.jforum.dao.TopicDAO#getTotalPosts(int)
	 */
	public int getTotalPosts(int topicId)
	{
		int total = 0;

		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			pstmt = JForumExecutionContext.getConnection().prepareStatement(
					SystemGlobals.getSql("TopicModel.getTotalPosts"));
			pstmt.setInt(1, topicId);

			rs = pstmt.executeQuery();
			if (rs.next()) {
				total = rs.getInt("total");
			}

			return total;
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(rs, pstmt);
		}
	}

	/**
	 * @see net.jforum.dao.TopicDAO#notifyUsers(net.jforum.entities.Topic)
	 */
	public List<User> notifyUsers(Topic topic)
	{
		int posterId = SessionFacade.getUserSession().getUserId();
		int anonUser = SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID);

		PreparedStatement pstmt = null;
		ResultSet rs = null;

		try {
			pstmt = JForumExecutionContext.getConnection().prepareStatement(
					SystemGlobals.getSql("TopicModel.notifyUsers"));

			pstmt.setInt(1, topic.getId());
			pstmt.setInt(2, posterId); // don't notify the poster
			pstmt.setInt(3, anonUser); // don't notify the anonymous user

			rs = pstmt.executeQuery();

			List<User> users = new ArrayList<User>();

			while (rs.next()) {
				User user = new User();

				user.setId(rs.getInt(USER_ID));
				user.setEmail(rs.getString("user_email"));
				user.setUsername(rs.getString("username"));
				user.setLang(rs.getString("user_lang"));
				user.setNotifyText(rs.getInt("user_notify_text") == 1);

				users.add(user);
			}

			rs.close();
			pstmt.close();

			// Set read status to false
			pstmt = JForumExecutionContext.getConnection().prepareStatement(
				SystemGlobals.getSql("TopicModel.markAllAsUnread"));
			pstmt.setInt(1, topic.getId());
			pstmt.setInt(2, posterId); // don't notify the poster
			pstmt.setInt(3, anonUser); // don't notify the anonymous user

			pstmt.executeUpdate();

			return users;
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(rs, pstmt);
		}
	}

	/**
	 * @see net.jforum.dao.TopicDAO#subscribeUsers(int, java.util.List)
	 */
	public void subscribeUsers(int topicId, List<User> users)
	{
		PreparedStatement pstmt = null;

		try {
			pstmt = JForumExecutionContext.getConnection().prepareStatement(
				SystemGlobals.getSql("TopicModel.subscribeUser"));

			pstmt.setInt(1, topicId);

			for (Iterator<User> iter = users.iterator(); iter.hasNext(); ) {
				int userId = iter.next().getId();

				pstmt.setInt(2, userId);
				pstmt.executeUpdate();
			}
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(pstmt);
		}
	}

	/**
	 * @see net.jforum.dao.TopicDAO#subscribeUser(int, int)
	 */
	public void subscribeUser(int topicId, int userId)
	{
		User user = new User();
		user.setId(userId);

		List<User> l = new ArrayList<User>();
		l.add(user);

		this.subscribeUsers(topicId, l);
	}

	/**
	 * @see net.jforum.dao.TopicDAO#isUserSubscribed(int, int)
	 */
	public boolean isUserSubscribed(int topicId, int userId)
	{
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		try {
			pstmt = JForumExecutionContext.getConnection().prepareStatement(
				SystemGlobals.getSql("TopicModel.isUserSubscribed"));

			pstmt.setInt(1, topicId);
			pstmt.setInt(2, userId);

			rs = pstmt.executeQuery();

			return rs.next() && rs.getInt(1) > 0;
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(rs, pstmt);
		}
	}

	/**
	 * @see net.jforum.dao.TopicDAO#removeSubscription(int, int)
	 */
	public void removeSubscription(int topicId, int userId)
	{
		PreparedStatement pstmt = null;
		try {
			pstmt = JForumExecutionContext.getConnection().prepareStatement(
					SystemGlobals.getSql("TopicModel.removeSubscription"));
			pstmt.setInt(1, topicId);
			pstmt.setInt(2, userId);

			pstmt.executeUpdate();
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(pstmt);
		}
	}

	/**
	 * @see net.jforum.dao.TopicDAO#removeSubscriptionByTopic(int)
	 */
	public void removeSubscriptionByTopic(int topicId)
	{
		PreparedStatement pstmt = null;
		try {
			pstmt = JForumExecutionContext.getConnection().prepareStatement(
					SystemGlobals.getSql("TopicModel.removeSubscriptionByTopic"));
			pstmt.setInt(1, topicId);

			pstmt.executeUpdate();
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(pstmt);
		}
	}

	/**
	 * @see net.jforum.dao.TopicDAO#updateReadStatus(int, int, boolean)
	 */
	public void updateReadStatus(int topicId, int userId, boolean read)
	{
		if (this.isUserSubscribed(topicId, userId)) {
			PreparedStatement pstmt = null;
			try {
				pstmt = JForumExecutionContext.getConnection().prepareStatement(
						SystemGlobals.getSql("TopicModel.updateReadStatus"));
				pstmt.setInt(1, read ? 1 : 0);
				pstmt.setInt(2, topicId);
				pstmt.setInt(3, userId);

				pstmt.executeUpdate();
			}
			catch (SQLException e) {
				throw new DatabaseException(e);
			}
			finally {
				DbUtils.close(pstmt);
			}
		}
	}

	/**
	 * @see net.jforum.dao.TopicDAO#lockUnlock(int[], int)
	 */
	public void lockUnlock(int[] topicId, int status)
	{
		PreparedStatement pstmt = null;
		try {
			pstmt = JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("TopicModel.lockUnlock"));
			pstmt.setInt(1, status);

			for (int i = 0; i < topicId.length; i++) {
				pstmt.setInt(2, topicId[i]);
				pstmt.executeUpdate();
			}
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(pstmt);
		}
	}

	private List<Topic> newMessages(List<Integer> topicIds)
	{
		if (topicIds.isEmpty()) {
			return new ArrayList<Topic>();
		}

		PreparedStatement pstmt = null;

		try {
			String sql = SystemGlobals.getSql("TopicModel.selectForNewMessages");

			StringBuilder sb = new StringBuilder();

			for (Iterator<Integer> iter = topicIds.iterator(); iter.hasNext(); ) {
				sb.append(iter.next()).append(',');
			}

			sb.append("-1");

			sql = sql.replaceAll(":topicIds:", sb.toString());

			pstmt = JForumExecutionContext.getConnection().prepareStatement(sql);

			return this.fillTopicsData(pstmt);
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(pstmt);
		}
	}

	/**
	 * Fills all topic data. The method will try to get all fields from the topics table, as well
	 * information about the user who made the first and the last post in the topic. <br>
	 * <b>The method <i>will</i> close the <i>PreparedStatement</i></b>
	 *
	 * @param pstmt the PreparedStatement to execute
	 * @return A list with all topics found
	 * @throws SQLException
	 */
	public List<Topic> fillTopicsData(PreparedStatement pstmt)
	{
		List<Topic> l = new ArrayList<Topic>();
		ResultSet rs = null;
		PreparedStatement pstmt2 = null;

		try {
			rs = pstmt.executeQuery();

			SimpleDateFormat df = new SimpleDateFormat(SystemGlobals.getValue(ConfigKeys.DATE_TIME_FORMAT), Locale.getDefault());

			StringBuilder sbFirst = new StringBuilder(128);
			StringBuilder sbLast = new StringBuilder(128);

			while (rs.next()) {
				Topic topic = this.getBaseTopicData(rs);

				// Posted by
				User user = new User();
				user.setId(rs.getInt(USER_ID));
				topic.setPostedBy(user);

				// Last post by
				user = new User();
				user.setId(rs.getInt("last_user_id"));
				topic.setLastPostBy(user);

				topic.setHasAttach(rs.getInt("attach") > 0);
				topic.setFirstPostTime(df.format(rs.getTimestamp("topic_time")));
				topic.setLastPostTime(df.format(rs.getTimestamp("post_time")));
				topic.setLastPostDate(new Date(rs.getTimestamp("post_time").getTime()));

				l.add(topic);

				sbFirst.append(rs.getInt(USER_ID)).append(',');
				sbLast.append(rs.getInt("last_user_id")).append(',');
			}

			rs.close();

			// Users
			if (sbFirst.length() > 0) {
				sbLast.delete(sbLast.length() - 1, sbLast.length());

				String sql = SystemGlobals.getSql("TopicModel.getUserInformation");
				sql = sql.replaceAll("#ID#", sbFirst.toString() + sbLast.toString());

				Map<Integer, String> users = new HashMap<Integer, String>();

				pstmt2 = JForumExecutionContext.getConnection().prepareStatement(sql);
				rs = pstmt2.executeQuery();

				while (rs.next()) {
					users.put(Integer.valueOf(rs.getInt(USER_ID)), rs.getString("username"));
				}

				for (Iterator<Topic> iter = l.iterator(); iter.hasNext();) {
					Topic topic = (Topic) iter.next();
					topic.getPostedBy().setUsername(users.get(Integer.valueOf(topic.getPostedBy().getId())));
					topic.getLastPostBy().setUsername(users.get(Integer.valueOf(topic.getLastPostBy().getId())));
				}
			}

			return l;
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(rs);
			DbUtils.close(pstmt2);
		}
	}

	/**
	 * @see net.jforum.dao.TopicDAO#selectRecentTopics(int)
	 */
	public List<Topic> selectRecentTopics(int limit)
	{
		PreparedStatement pstmt = null;
		try {
			pstmt = JForumExecutionContext.getConnection().prepareStatement(
				SystemGlobals.getSql("TopicModel.selectRecentTopicsByLimit"));
			pstmt.setInt(1, limit);

			return this.fillTopicsData(pstmt);
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(pstmt);
		}
	}

	/**
	 * @see net.jforum.dao.TopicDAO#selectHottestTopics(int)
	 */
	public List<Topic> selectHottestTopics(int limit)
	{
	    PreparedStatement pstmt = null;
	    try {
	        pstmt = JForumExecutionContext.getConnection().prepareStatement(
	        	SystemGlobals.getSql("TopicModel.selectHottestTopicsByLimit"));
	        pstmt.setInt(1, limit);

	        return this.fillTopicsData(pstmt);
	    }
	    catch (SQLException e) {
	        throw new DatabaseException(e);
	    }
	    finally {
	        DbUtils.close(pstmt);
	    }
	}

	/**
	 * @see net.jforum.dao.TopicDAO#setFirstPostId(int, int)
	 */
	public void setFirstPostId(int topicId, int postId)
	{
		PreparedStatement pstmt = null;
		try {
			pstmt = JForumExecutionContext.getConnection().prepareStatement(
					SystemGlobals.getSql("TopicModel.setFirstPostId"));
			pstmt.setInt(1, postId);
			pstmt.setInt(2, topicId);
			pstmt.executeUpdate();
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(pstmt);
		}
	}

	/**
	 * @see net.jforum.dao.TopicDAO#getMinPostId(int)
	 */
	public int getMinPostId(int topicId)
	{
		int id = -1;

		PreparedStatement pstmt = null;
		try {
			pstmt = JForumExecutionContext.getConnection()
					.prepareStatement(SystemGlobals.getSql("TopicModel.getMinPostId"));
			pstmt.setInt(1, topicId);

			ResultSet rs = pstmt.executeQuery();
			if (rs.next()) {
				id = rs.getInt("post_id");
			}

			return id;
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(pstmt);
		}
	}

	/**
	 * @see net.jforum.dao.TopicDAO#setModerationStatus(int, boolean)
	 */
	public void setModerationStatus(int forumId, boolean status)
	{
		PreparedStatement pstmt = null;
		try {
			pstmt = JForumExecutionContext.getConnection().prepareStatement(
					SystemGlobals.getSql("TopicModel.setModerationStatus"));
			pstmt.setInt(1, status ? 1 : 0);
			pstmt.setInt(2, forumId);
			pstmt.executeUpdate();
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(pstmt);
		}
	}

	/**
	 * @see net.jforum.dao.TopicDAO#setModerationStatusByTopic(int, boolean)
	 */
	public void setModerationStatusByTopic(int topicId, boolean status)
	{
		PreparedStatement pstmt = null;
		try {
			pstmt = JForumExecutionContext.getConnection().prepareStatement(
					SystemGlobals.getSql("TopicModel.setModerationStatusByTopic"));
			pstmt.setInt(1, status ? 1 : 0);
			pstmt.setInt(2, topicId);
			pstmt.executeUpdate();
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(pstmt);
		}
	}

	/**
	 * @see net.jforum.dao.TopicDAO#selectTopicTitlesByIds(java.util.Collection)
	 */
	public List<Map<String, Object>> selectTopicTitlesByIds(Collection<?> idList)
	{
		List<Map<String, Object>> l = new ArrayList<Map<String, Object>>();
		String sql = SystemGlobals.getSql("TopicModel.selectTopicTitlesByIds");

		StringBuilder sb = new StringBuilder(idList.size() * 2);
		for (Iterator<?> iter = idList.iterator(); iter.hasNext();) {
			sb.append(iter.next()).append(',');
		}

		int len = sb.length();
		sql = sql.replaceAll(":ids:", len > 0 ? sb.toString().substring(0, len - 1) : "0");
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			pstmt = JForumExecutionContext.getConnection().prepareStatement(sql);

			rs = pstmt.executeQuery();
			while (rs.next()) {
				Map<String, Object> m = new HashMap<String, Object>();
				m.put("id", Integer.valueOf(rs.getInt("topic_id")));
				m.put("title", rs.getString("topic_title"));

				l.add(m);
			}
			return l;
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(rs, pstmt);
		}
	}

	/**
	 * @see net.jforum.dao.TopicDAO#topicPosters(int)
	 */
	public Map<Integer, User> topicPosters(int topicId)
	{
		Map<Integer, User> m = new HashMap<Integer, User>();

		PreparedStatement pstmt = null;
		ResultSet rs = null;

		try {
			StringBuilder sql = new StringBuilder(SystemGlobals.getSql("TopicModel.topicPosters"));

			pstmt = JForumExecutionContext.getConnection().prepareStatement(
				SystemGlobals.getSql("TopicModel.distinctPosters"));
			pstmt.setInt(1, topicId);

			rs = pstmt.executeQuery();

			StringBuilder sb = new StringBuilder();

			while (rs.next()) {
				sb.append(rs.getInt(USER_ID)).append(',');
			}

			rs.close();
			pstmt.close();

			int index = sql.indexOf(":ids:");
			if (index > -1) {
				sql.replace(index, index + 5, sb.substring(0, sb.length() - 1));
			}

			pstmt = JForumExecutionContext.getConnection().prepareStatement(sql.toString());
			rs = pstmt.executeQuery();

			while (rs.next()) {
				User user = new User();

				user.setId(rs.getInt(USER_ID));
				user.setUsername(rs.getString("username"));
				user.setKarma(new KarmaStatus(user.getId(), rs.getDouble("user_karma")));
				user.setAvatar(rs.getString("user_avatar"));
				user.setAvatarEnabled(rs.getInt("user_allowavatar") == 1);
				user.setRegistrationDate(new Date(rs.getTimestamp("user_regdate").getTime()));
				user.setTotalPosts(rs.getInt("user_posts"));
				user.setFrom(rs.getString("user_from"));
				user.setEmail(rs.getString("user_email"));
				user.setRankId(rs.getInt("rank_id"));
				user.setViewEmailEnabled(rs.getInt("user_viewemail") == 1);
				user.setIcq(rs.getString("user_icq"));
				user.setTwitter(rs.getString("user_twitter"));
				user.setAttachSignatureEnabled(rs.getInt("user_attachsig") == 1);
				user.setMsnm(rs.getString("user_msnm"));
				user.setYim(rs.getString("user_yim"));
				user.setWebSite(rs.getString("user_website"));
				user.setAim(rs.getString("user_aim"));
				user.setSignature(rs.getString("user_sig"));

				m.put(Integer.valueOf(user.getId()), user);
			}

			return m;
		}
		catch (SQLException e) {
			throw new DatabaseException(e);
		}
		finally {
			DbUtils.close(rs, pstmt);
		}
	}

    /**
    * Returns all topics that are watched by a given user.
    * @param userId The user id
    */
    public List<Map<String, Object>> selectWatchesByUser(int userID) {
        List<Map<String, Object>> l = new ArrayList<Map<String, Object>>();
        PreparedStatement p = null;
        ResultSet rs = null;
        try {
            p = JForumExecutionContext.getConnection().prepareStatement(
                    SystemGlobals.getSql("TopicModel.selectWatchesByUser"));
            p.setInt(1, userID);
            rs = p.executeQuery();
            while (rs.next()) {
            	Map<String, Object> m = new HashMap<String, Object>();
                m.put("id", new Integer(rs.getInt("topic_id")));
                m.put("title", SafeHtml.escapeUnsafe(rs.getString("topic_title")));
                m.put("forumName", rs.getString("forum_name"));
                l.add(m);
            }
            return l;
        } catch (SQLException e) {
            throw new DatabaseException(e);
        } finally {
            DbUtils.close(p);
        }
    }

}


text:
<?php
error_reporting(E_ALL);

require_once dirname(__DIR__).'/vendor/autoload.php';

PHPUnit_Framework_Error_Notice::$enabled = true;

redpajama_set_name: RedPajamaGithub


text:
namespace content {

void WebRtcContentBrowserTestBase::SetUpCommandLine(
    base::CommandLine* command_line) {
  base::CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnforceWebRtcIPPermissionCheck);

  // Loopback interface is the non-default local address. They should only be in
  // the candidate list if the ip handling policy is "default" AND the media
  // permission is granted.
  base::CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kAllowLoopbackInPeerConnection);
}

void WebRtcContentBrowserTestBase::SetUp() {
  // We need pixel output when we dig pixels out of video tags for verification.
  EnablePixelOutput();
#if BUILDFLAG(IS_CHROMEOS_ASH)
  ash::CrasAudioClient::InitializeFake();
  ash::CrasAudioHandler::InitializeForTesting();
#endif
  ContentBrowserTest::SetUp();
  ASSERT_TRUE(base::CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kUseFakeDeviceForMediaStream));
}

void WebRtcContentBrowserTestBase::TearDown() {
  ContentBrowserTest::TearDown();
#if BUILDFLAG(IS_CHROMEOS_ASH)
  ash::CrasAudioHandler::Shutdown();
  ash::CrasAudioClient::Shutdown();
#endif
}

void WebRtcContentBrowserTestBase::AppendUseFakeUIForMediaStreamFlag() {
  base::CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kUseFakeUIForMediaStream);
}

// Executes |javascript|. The script is required to use
// window.domAutomationController.send to send a string value back to here.
std::string WebRtcContentBrowserTestBase::ExecuteJavascriptAndReturnResult(
    const std::string& javascript) {
  return EvalJs(shell(), javascript, EXECUTE_SCRIPT_USE_MANUAL_REPLY)
      .ExtractString();
}

void WebRtcContentBrowserTestBase::MakeTypicalCall(
    const std::string& javascript,
    const std::string& html_file) {
  if (!embedded_test_server()->Started())
    ASSERT_TRUE(embedded_test_server()->Start());

  GURL url(embedded_test_server()->GetURL(html_file));
  EXPECT_TRUE(NavigateToURL(shell(), url));

  ExecuteJavascriptAndWaitForOk(javascript);
}

void WebRtcContentBrowserTestBase::ExecuteJavascriptAndWaitForOk(
    const std::string& javascript) {
  std::string result = ExecuteJavascriptAndReturnResult(javascript);
  if (result != "OK") {
    if (result.empty())
      result = "(nothing)";
    printf("From javascript: %s\nWhen executing '%s'\n", result.c_str(),
           javascript.c_str());
    FAIL();
  }
 }

 std::string WebRtcContentBrowserTestBase::GenerateGetUserMediaCall(
     const char* function_name,
     int min_width,
     int max_width,
     int min_height,
     int max_height,
     int min_frame_rate,
     int max_frame_rate) const {
   return base::StringPrintf(
       "%s({video: {mandatory: {minWidth: %d, maxWidth: %d, "
       "minHeight: %d, maxHeight: %d, minFrameRate: %d, maxFrameRate: %d}, "
       "optional: []}});",
       function_name, min_width, max_width, min_height, max_height,
       min_frame_rate, max_frame_rate);
}

// static
bool WebRtcContentBrowserTestBase::HasAudioOutputDevices() {
  bool has_devices = false;
  base::RunLoop run_loop;
  auto audio_system = CreateAudioSystemForAudioService();
  audio_system->HasOutputDevices(base::BindOnce(
      [](base::OnceClosure finished_callback, bool* result, bool received) {
        *result = received;
        std::move(finished_callback).Run();
      },
      run_loop.QuitClosure(), &has_devices));
  run_loop.Run();
  return has_devices;
}

}  // namespace content


text:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Tag extends Model
{
    use SoftDeletes;

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['deleted_at'];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'tag', 'title', 'subtitle', 'meta_description'
    ];

    /**
     * Get all of the articles that are assigned this tag.
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorpheByMany
     */
    public function articles()
    {
        return $this->morphedByMany(Article::class, 'taggable');
    }

    /**
     * Get all of the discussions that are assigned this tag.
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorpheBymany
     */
    public function discussions()
    {
        return $this->morphedByMany(Discussion::class, 'taggable');
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Herb. Fr. 10: tab. 435 (1790)

#### Original name
Lycoperdon gossypinum Bull.

### Remarks
null


text:
package org.apache.kafka.connect.util;

import org.apache.kafka.clients.producer.ProducerRecord;
import org.easymock.EasyMock;
import org.easymock.IArgumentMatcher;

import java.util.Arrays;

public class ByteArrayProducerRecordEquals implements IArgumentMatcher {
    private ProducerRecord<byte[], byte[]> record;

    public static ProducerRecord<byte[], byte[]> eqProducerRecord(ProducerRecord<byte[], byte[]> in) {
        EasyMock.reportMatcher(new ByteArrayProducerRecordEquals(in));
        return null;
    }

    public ByteArrayProducerRecordEquals(ProducerRecord<byte[], byte[]> record) {
        this.record = record;
    }

    @Override
    public boolean matches(Object argument) {
        if (!(argument instanceof ProducerRecord))
            return false;
        ProducerRecord<byte[], byte[]> other = (ProducerRecord<byte[], byte[]>) argument;
        return record.topic().equals(other.topic()) &&
                record.partition() != null ? record.partition().equals(other.partition()) : other.partition() == null &&
                record.key() != null ? Arrays.equals(record.key(), other.key()) : other.key() == null &&
                record.value() != null ? Arrays.equals(record.value(), other.value()) : other.value() == null;
    }

    @Override
    public void appendTo(StringBuffer buffer) {
        buffer.append(record.toString());
    }
}


text:
#region Imports

using System;
using System.Collections.Generic;
using System.Linq;
#endregion

namespace P3Net.Kraken.Collections
{
    /// Provides extension methods for arrays.
    public static class ArrayExtensions
    {
        /// Gets the enumerable value if it is not <see langword="null"/> or an empty list otherwise.
        /// <typeparam name="T">The type of the enumerable items.</typeparam>
        /// <param name="source">The source.</param>
        /// <returns>The source if it is not <see langword="null"/> or an empty list otherwise.</returns>
        /// <example>
        ///
        /// public void ProcessItems ( Item[] items )
        /// {
        ///    foreach (var item in items.GetValueOrEmpty())
        ///       ProcessItem(item);
        /// }
        ///
        ///
        /// Sub ProcessItems ( items As Item() )
        ///
        ///    For Each item In items.GetValueOrEmpty()
        ///       ProcessItem(item)
        ///    Next
        /// End Sub
        ///
        /// </example>
        public static T[] GetValueOrEmpty<T> ( this T[] source )
        {
            return source ?? new T[0];
        }

        /// Gets the index of the given item, if found.
        /// <typeparam name="T">The type of the array elements.</typeparam>
        /// <param name="source">The source array.</param>
        /// <param name="item">The item to find.</param>
        /// <returns>The zero-based index or -1 if the item is not found.</returns>
        public static int IndexOf<T> ( this T[] source, T item )
        {
            return Array.IndexOf(source, item);
        }
    }
}


text:
u"""
:Copyright:

 Copyright 2006 - 2017
 Andr\xe9 Malo or his licensors, as applicable

:License:

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

================================================
 TDI - The next evolutional step for templating
================================================

TDI - The next evolutional step for templating.
"""
__author__ = u"Andr\xe9 Malo"
__docformat__ = "restructuredtext en"

import os as _os
import posixpath as _posixpath

# pylint: disable = no-name-in-module, import-error
from distutils import ccompiler as _ccompiler
from distutils import core as _core
from distutils import log as _log
from distutils.command import build_ext as _build_ext
import setuptools as _setuptools

# pylint: disable = invalid-name

def _doc(filename):
    """ Read docs file """
    try:
        with open(_os.path.join('docs', filename)) as fp:
            return fp.read()
    except IOError:
        return None

def _lines(multiline):
    """ Split multiline string into single line % empty and comments """
    return [line for line in (
        line.strip() for line in multiline.splitlines(False)
    ) if line and not line.startswith('#')]

package = dict(
    name='tdi3',
    top='tdi',
    pathname='tdi',
    provides=_doc('PROVIDES'),
    desc=_doc('SUMMARY').strip(),
    longdesc=_doc('DESCRIPTION'),
    author=__author__,
    email='nd@perlig.de',
    license="Apache License, Version 2.0",
    keywords=_lines(_doc('KEYWORDS')),
    url='http://opensource.perlig.de/tdi/',
    classifiers=_lines(_doc('CLASSIFIERS') or ''),

    install_requires=_lines("""
    """),
)

class build_ext(_build_ext.build_ext):  # pylint: disable = no-init
    """ Improved extension building code """

    def build_extension(self, ext):
        """
        Build C extension - with extended functionality

        The following features are added here:

        - The macros ``EXT_PACKAGE`` and ``EXT_MODULE`` will be filled (or
          unset) depending on the extensions name, but only if they are not
          already defined.

        - "." is added to the include directories (for cext.h)

        :Parameters:
          `ext` : `Extension`
            The extension to build

        :Return: whatever ``distutils.command.build_ext.build_ext`` returns
        :Rtype: any
        """
        # handle name macros
        macros = dict(ext.define_macros or ())
        tup = ext.name.split('.')
        if len(tup) == 1:
            pkg, mod = None, tup[0]
        else:
            pkg, mod = '.'.join(tup[:-1]), tup[-1]
        if pkg is not None and 'EXT_PACKAGE' not in macros:
            ext.define_macros.append(('EXT_PACKAGE', pkg))
        if 'EXT_MODULE' not in macros:
            ext.define_macros.append(('EXT_MODULE', mod))
        if pkg is None:
            macros = dict(ext.undef_macros or ())
            if 'EXT_PACKAGE' not in macros:
                ext.undef_macros.append('EXT_PACKAGE')

        return _build_ext.build_ext.build_extension(self, ext)

class Extension(_core.Extension):
    """ improved functionality """

    def __init__(self, *args, **kwargs):
        """ Initialization """
        self.depends = []
        if 'depends' in kwargs:
            self.depends = kwargs['depends']
        _core.Extension.__init__(self, *args, **kwargs)

        # add include path
        included = '.'
        if included not in self.include_dirs:
            self.include_dirs.append(included)

        # add cext.h to the dependencies
        cext_h = _posixpath.normpath(_posixpath.join(included, 'cext.h'))
        for item in self.depends:
            if _posixpath.normpath(item) == cext_h:
                break
        else:
            self.depends.append(cext_h)

EXTENSIONS = [Extension('tdi.c._tdi_impl', [
    "tdi/c/main.c",

    "tdi/c/markup/attr.c",
    "tdi/c/markup/text/decoder.c",
    "tdi/c/markup/text/encoder.c",
], depends=[
    "tdi/c/include/bytestr.h",
    "tdi/c/include/length.h",
    "tdi/c/include/markup/attr.h",
    "tdi/c/include/markup/text/decoder.h",
    "tdi/c/include/markup/text/encoder.h",
], include_dirs=[
    "tdi/c/include",
])]

def setup():
    """ Main """
    with open('%(pathname)s/__init__.py' % package) as fp:
        for line in fp:  # pylint: disable = redefined-outer-name
            if line.startswith('__version__'):
                version = line.split('=', 1)[1].strip()
                if version.startswith(("'", '"')):
                    version = version[1:-1].strip()
                break
        else:
            raise RuntimeError("Version not found")

    gcov = False
    if _os.environ.get('CFLAGS') is None:
        compiler = _ccompiler.get_default_compiler()
        try:
            with open("debug.%s.cflags" % compiler) as fp:
                cflags = ' '.join([
                    line for line in (line.strip() for line in fp)
                    if line and not line.startswith('#')
                ]) or None
        except IOError:
            pass
        else:
            if cflags is not None:
                # pylint: disable = unsupported-membership-test
                if 'coverage' in cflags:
                    gcov = True
                _log.info("Setting CFLAGS to %r", cflags)
                _os.environ['CFLAGS'] = cflags

    if gcov:
        for ext in EXTENSIONS:
            ext.libraries.append('gcov')

    packages = [package['top']] + [
        '%s.%s' % (package['top'], item)
        for item in
        _setuptools.find_packages(package['pathname'])
    ]

    _core.setup(
        cmdclass={'build_ext': build_ext},
        name=package['name'],
        author=package['author'],
        author_email=package['email'],
        license=package['license'],
        classifiers=package['classifiers'],
        description=package['desc'],
        long_description=package['longdesc'],
        url=package['url'],
        ext_modules=EXTENSIONS,
        install_requires=package['install_requires'],
        packages=packages,
        version=version,
        zip_safe=False,
    )

if __name__ == '__main__':
    setup()


text:
<?php
$this->startSetup();

$tableName  = $this->getTable('pulchqueue/labour');
$adapter    = $this->getConnection();

$adapter->changeColumn(
    $tableName,
    'execute_at',
    'execute_at',
    'int(10) unsigned DEFAULT NULL COMMENT "Execute at"'
);

$adapter->changeColumn(
    $tableName,
    'created_at',
    'created_at',
    'int(10) unsigned DEFAULT NULL COMMENT "Created at"'
);

$adapter->changeColumn(
    $tableName,
    'updated_at',
    'updated_at',
    'int(10) unsigned DEFAULT NULL COMMENT "Updated at"'
);

$adapter->changeColumn(
    $tableName,
    'started_at',
    'started_at',
    'int(10) unsigned DEFAULT NULL COMMENT "Started at"'
);

$adapter->changeColumn(
    $tableName,
    'finished_at',
    'finished_at',
    'int(10) unsigned DEFAULT NULL COMMENT "Finished at"'
);

$adapter->changeColumn(
    $tableName,
    'retries',
    'attempts',
    'int(10) unsigned DEFAULT NULL COMMENT "Attempt"'
);

$this->endSetup();


text:
import express = require("express");

var app=express();

app.get("/",function (req,res) {
	res.send("Hello")
})

app.listen(3000,function(){
	console.log("server listen in 3000")
})


text:
@interface ReminderViewController ()

@property (nonatomic, weak) IBOutlet UIDatePicker *datePicker;

@end

@implementation ReminderViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {
        self.tabBarItem.title = @"Reminder";

        UIImage *i = [UIImage imageNamed:@"Time.png"];
        self.tabBarItem.image = i;
    }

    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    NSLog(@"ReminderViewController loaded its view.");
}

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

    self.datePicker.minimumDate = [NSDate dateWithTimeIntervalSinceNow:60];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (IBAction)addReminder:(id)sender
{
    NSDate *date = self.datePicker.date;
    NSLog(@"Setting a reminder for %@", date);

    UILocalNotification *note = [[UILocalNotification alloc] init];
    note.alertBody = @"Hypnotize me!";
    note.fireDate = date;

    [[UIApplication sharedApplication] scheduleLocalNotification:note];
}

@end


text:
<template name="demoListCardOver">
    <list-card-over>

Demo for list-card-over

            <paper-button raised id="nextDemo">View Next Demo</paper-button>

    </list-card-over>
</template>

<template name="demoNavCard">

        <paper-material>

Demo for nav-card

            <paper-button raised id="nextDemo">View Next Demo</paper-button>
        </paper-material>
        <paper-material></paper-material>
        <paper-material></paper-material>
        <paper-material></paper-material>
        <paper-material></paper-material>
        <paper-material></paper-material>
        <paper-material></paper-material>

</template>

<template name="demoNavListDetail">

Demo for nav-list-detail

        <paper-button raised id="nextDemo">View Next Demo</paper-button>

</template>

<template name="demoNavView">

Demo for nav-view

        <paper-button raised id="nextDemo">View Next Demo</paper-button>

</template>


text:
This repository is home to all the source files to gists written in posts for [codeofdan.com](http://codeofdan.com)

Writing code in this repo makes it easier to develop and test in an IDE. Individual files are then uploaded as a separate gist once they are completed. Each "project" should only be one file so they can be easily run and compiled.

## Usage

Each class should be compilable by itself, for example to compile the, "Hello World" example you would do the following:

    $ cd src/main/java/
    $ javac com/codeofdan/hello/HelloWorld.java

The source has now been compiled and you can run it as so:

    $ java com.codeofdan.hello.HelloWorld
    Hello World!

An argument can be added to customise the greeting:

    $ java com.codeofdan.hello.HelloWorld Dan
    Hello Dan!


text:
using base::ASCIIToUTF16;
using base::UTF8ToUTF16;
using base::UTF16ToUTF8;

using testing::Contains;

namespace ui {

template <typename ClipboardTraits>
class ClipboardTest : public PlatformTest {
 public:
#if defined(USE_AURA)
  ClipboardTest()
      : event_source_(PlatformEventSource::CreateDefault()),
        clipboard_(ClipboardTraits::Create()) {}
#else
  ClipboardTest() : clipboard_(ClipboardTraits::Create()) {}
#endif

  ~ClipboardTest() override { ClipboardTraits::Destroy(clipboard_); }

 protected:
  Clipboard& clipboard() { return *clipboard_; }

  std::vector<base::string16> GetAvailableTypes(ClipboardType type) {
    bool contains_filenames;
    std::vector<base::string16> types;
    clipboard().ReadAvailableTypes(type, &types, &contains_filenames);
    return types;
  }

 private:
  base::MessageLoopForUI message_loop_;
#if defined(USE_AURA)
  scoped_ptr<PlatformEventSource> event_source_;
#endif
  // ui::Clipboard has a protected destructor, so scoped_ptr doesn't work here.
  Clipboard* const clipboard_;
};

// Hack for tests that need to call static methods of ClipboardTest.
struct NullClipboardTraits {
  static Clipboard* Create() { return nullptr; }
  static void Destroy(Clipboard*) {}
};

TYPED_TEST_CASE(ClipboardTest, TypesToTest);

TYPED_TEST(ClipboardTest, ClearTest) {
  {
    ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE);
    clipboard_writer.WriteText(ASCIIToUTF16("clear me"));
  }

  this->clipboard().Clear(CLIPBOARD_TYPE_COPY_PASTE);

  EXPECT_TRUE(this->GetAvailableTypes(CLIPBOARD_TYPE_COPY_PASTE).empty());
  EXPECT_FALSE(this->clipboard().IsFormatAvailable(
      Clipboard::GetPlainTextWFormatType(), CLIPBOARD_TYPE_COPY_PASTE));
  EXPECT_FALSE(this->clipboard().IsFormatAvailable(
      Clipboard::GetPlainTextFormatType(), CLIPBOARD_TYPE_COPY_PASTE));
}

TYPED_TEST(ClipboardTest, TextTest) {
  base::string16 text(ASCIIToUTF16("This is a base::string16!#$")), text_result;
  std::string ascii_text;

  {
    ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE);
    clipboard_writer.WriteText(text);
  }

  EXPECT_THAT(this->GetAvailableTypes(CLIPBOARD_TYPE_COPY_PASTE),
              Contains(ASCIIToUTF16(Clipboard::kMimeTypeText)));
  EXPECT_TRUE(this->clipboard().IsFormatAvailable(
      Clipboard::GetPlainTextWFormatType(), CLIPBOARD_TYPE_COPY_PASTE));
  EXPECT_TRUE(this->clipboard().IsFormatAvailable(
      Clipboard::GetPlainTextFormatType(), CLIPBOARD_TYPE_COPY_PASTE));
  this->clipboard().ReadText(CLIPBOARD_TYPE_COPY_PASTE, &text_result);

  EXPECT_EQ(text, text_result);
  this->clipboard().ReadAsciiText(CLIPBOARD_TYPE_COPY_PASTE, &ascii_text);
  EXPECT_EQ(UTF16ToUTF8(text), ascii_text);
}

TYPED_TEST(ClipboardTest, HTMLTest) {
  base::string16 markup(ASCIIToUTF16("<string>Hi!</string>")), markup_result;
  base::string16 plain(ASCIIToUTF16("Hi!")), plain_result;
  std::string url("http://www.example.com/"), url_result;

  {
    ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE);
    clipboard_writer.WriteText(plain);
    clipboard_writer.WriteHTML(markup, url);
  }

  EXPECT_THAT(this->GetAvailableTypes(CLIPBOARD_TYPE_COPY_PASTE),
              Contains(ASCIIToUTF16(Clipboard::kMimeTypeHTML)));
  EXPECT_TRUE(this->clipboard().IsFormatAvailable(
      Clipboard::GetHtmlFormatType(), CLIPBOARD_TYPE_COPY_PASTE));
  uint32 fragment_start;
  uint32 fragment_end;
  this->clipboard().ReadHTML(CLIPBOARD_TYPE_COPY_PASTE, &markup_result,
                             &url_result, &fragment_start, &fragment_end);
  EXPECT_LE(markup.size(), fragment_end - fragment_start);
  EXPECT_EQ(markup,
            markup_result.substr(fragment_end - markup.size(), markup.size()));
#if defined(OS_WIN)
  // TODO(playmobil): It's not clear that non windows clipboards need to support
  // this.
  EXPECT_EQ(url, url_result);
#endif  // defined(OS_WIN)
}

TYPED_TEST(ClipboardTest, RTFTest) {
  std::string rtf =
      "{\\rtf1\\ansi{\\fonttbl\\f0\\fswiss Helvetica;}\\f0\\pard\n"
      "This is some {\\b bold} text.\\par\n"
      "}";

  {
    ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE);
    clipboard_writer.WriteRTF(rtf);
  }

  EXPECT_THAT(this->GetAvailableTypes(CLIPBOARD_TYPE_COPY_PASTE),
              Contains(ASCIIToUTF16(Clipboard::kMimeTypeRTF)));
  EXPECT_TRUE(this->clipboard().IsFormatAvailable(Clipboard::GetRtfFormatType(),
                                                  CLIPBOARD_TYPE_COPY_PASTE));
  std::string result;
  this->clipboard().ReadRTF(CLIPBOARD_TYPE_COPY_PASTE, &result);
  EXPECT_EQ(rtf, result);
}

// TODO(dnicoara) Enable test once Ozone implements clipboard support:
// crbug.com/361707
#if defined(OS_LINUX) && !defined(OS_CHROMEOS) && !defined(USE_OZONE)
TYPED_TEST(ClipboardTest, MultipleBufferTest) {
  base::string16 text(ASCIIToUTF16("Standard")), text_result;
  base::string16 markup(ASCIIToUTF16("<string>Selection</string>"));
  std::string url("http://www.example.com/"), url_result;

  {
    ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE);
    clipboard_writer.WriteText(text);
  }

  {
    ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_SELECTION);
    clipboard_writer.WriteHTML(markup, url);
  }

  EXPECT_THAT(this->GetAvailableTypes(CLIPBOARD_TYPE_COPY_PASTE),
              Contains(ASCIIToUTF16(Clipboard::kMimeTypeText)));
  EXPECT_THAT(this->GetAvailableTypes(CLIPBOARD_TYPE_SELECTION),
              Contains(ASCIIToUTF16(Clipboard::kMimeTypeHTML)));

  EXPECT_TRUE(this->clipboard().IsFormatAvailable(
      Clipboard::GetPlainTextFormatType(), CLIPBOARD_TYPE_COPY_PASTE));
  EXPECT_FALSE(this->clipboard().IsFormatAvailable(
      Clipboard::GetPlainTextFormatType(), CLIPBOARD_TYPE_SELECTION));

  EXPECT_FALSE(this->clipboard().IsFormatAvailable(
      Clipboard::GetHtmlFormatType(), CLIPBOARD_TYPE_COPY_PASTE));
  EXPECT_TRUE(this->clipboard().IsFormatAvailable(
      Clipboard::GetHtmlFormatType(), CLIPBOARD_TYPE_SELECTION));

  this->clipboard().ReadText(CLIPBOARD_TYPE_COPY_PASTE, &text_result);
  EXPECT_EQ(text, text_result);

  base::string16 markup_result;
  uint32 fragment_start;
  uint32 fragment_end;
  this->clipboard().ReadHTML(CLIPBOARD_TYPE_SELECTION, &markup_result,
                             &url_result, &fragment_start, &fragment_end);
  EXPECT_LE(markup.size(), fragment_end - fragment_start);
  EXPECT_EQ(markup,
            markup_result.substr(fragment_end - markup.size(), markup.size()));
}
#endif

TYPED_TEST(ClipboardTest, TrickyHTMLTest) {
  base::string16 markup(ASCIIToUTF16("Bye!")),
      markup_result;
  std::string url, url_result;
  base::string16 plain(ASCIIToUTF16("Bye!")), plain_result;

  {
    ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE);
    clipboard_writer.WriteText(plain);
    clipboard_writer.WriteHTML(markup, url);
  }

  EXPECT_THAT(this->GetAvailableTypes(CLIPBOARD_TYPE_COPY_PASTE),
              Contains(ASCIIToUTF16(Clipboard::kMimeTypeHTML)));
  EXPECT_TRUE(this->clipboard().IsFormatAvailable(
      Clipboard::GetHtmlFormatType(), CLIPBOARD_TYPE_COPY_PASTE));
  uint32 fragment_start;
  uint32 fragment_end;
  this->clipboard().ReadHTML(CLIPBOARD_TYPE_COPY_PASTE, &markup_result,
                             &url_result, &fragment_start, &fragment_end);
  EXPECT_LE(markup.size(), fragment_end - fragment_start);
  EXPECT_EQ(markup,
            markup_result.substr(fragment_end - markup.size(), markup.size()));
#if defined(OS_WIN)
  // TODO(playmobil): It's not clear that non windows clipboards need to support
  // this.
  EXPECT_EQ(url, url_result);
#endif  // defined(OS_WIN)
}

// Some platforms store HTML as UTF-8 internally. Make sure fragment indices are
// adjusted appropriately when converting back to UTF-16.
TYPED_TEST(ClipboardTest, UnicodeHTMLTest) {
  base::string16 markup(UTF8ToUTF16("
A \xc3\xb8 \xe6\xb0\xb4
")),
      markup_result;
  std::string url, url_result;

  {
    ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE);
    clipboard_writer.WriteHTML(markup, url);
  }

  EXPECT_THAT(this->GetAvailableTypes(CLIPBOARD_TYPE_COPY_PASTE),
              Contains(ASCIIToUTF16(Clipboard::kMimeTypeHTML)));
  EXPECT_TRUE(this->clipboard().IsFormatAvailable(
      Clipboard::GetHtmlFormatType(), CLIPBOARD_TYPE_COPY_PASTE));
  uint32 fragment_start;
  uint32 fragment_end;
  this->clipboard().ReadHTML(CLIPBOARD_TYPE_COPY_PASTE, &markup_result,
                             &url_result, &fragment_start, &fragment_end);
  EXPECT_LE(markup.size(), fragment_end - fragment_start);
  EXPECT_EQ(markup,
            markup_result.substr(fragment_end - markup.size(), markup.size()));
#if defined(OS_WIN)
  EXPECT_EQ(url, url_result);
#endif
}

// TODO(estade): Port the following test (decide what target we use for urls)
#if !defined(OS_POSIX) || defined(OS_MACOSX)
TYPED_TEST(ClipboardTest, BookmarkTest) {
  base::string16 title(ASCIIToUTF16("The Example Company")), title_result;
  std::string url("http://www.example.com/"), url_result;

  {
    ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE);
    clipboard_writer.WriteBookmark(title, url);
  }

  EXPECT_TRUE(this->clipboard().IsFormatAvailable(
      Clipboard::GetUrlWFormatType(), CLIPBOARD_TYPE_COPY_PASTE));
  this->clipboard().ReadBookmark(&title_result, &url_result);
  EXPECT_EQ(title, title_result);
  EXPECT_EQ(url, url_result);
}
#endif  // !defined(OS_POSIX) || defined(OS_MACOSX)

TYPED_TEST(ClipboardTest, MultiFormatTest) {
  base::string16 text(ASCIIToUTF16("Hi!")), text_result;
  base::string16 markup(ASCIIToUTF16("Hi!</string>")), markup_result;
  std::string url("http://www.example.com/"), url_result;
  std::string ascii_text;

  {
    ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE);
    clipboard_writer.WriteHTML(markup, url);
    clipboard_writer.WriteText(text);
  }

  EXPECT_THAT(this->GetAvailableTypes(CLIPBOARD_TYPE_COPY_PASTE),
              Contains(ASCIIToUTF16(Clipboard::kMimeTypeHTML)));
  EXPECT_THAT(this->GetAvailableTypes(CLIPBOARD_TYPE_COPY_PASTE),
              Contains(ASCIIToUTF16(Clipboard::kMimeTypeText)));
  EXPECT_TRUE(this->clipboard().IsFormatAvailable(
      Clipboard::GetHtmlFormatType(), CLIPBOARD_TYPE_COPY_PASTE));
  EXPECT_TRUE(this->clipboard().IsFormatAvailable(
      Clipboard::GetPlainTextWFormatType(), CLIPBOARD_TYPE_COPY_PASTE));
  EXPECT_TRUE(this->clipboard().IsFormatAvailable(
      Clipboard::GetPlainTextFormatType(), CLIPBOARD_TYPE_COPY_PASTE));
  uint32 fragment_start;
  uint32 fragment_end;
  this->clipboard().ReadHTML(CLIPBOARD_TYPE_COPY_PASTE, &markup_result,
                             &url_result, &fragment_start, &fragment_end);
  EXPECT_LE(markup.size(), fragment_end - fragment_start);
  EXPECT_EQ(markup,
            markup_result.substr(fragment_end - markup.size(), markup.size()));
#if defined(OS_WIN)
  // TODO(playmobil): It's not clear that non windows clipboards need to support
  // this.
  EXPECT_EQ(url, url_result);
#endif  // defined(OS_WIN)
  this->clipboard().ReadText(CLIPBOARD_TYPE_COPY_PASTE, &text_result);
  EXPECT_EQ(text, text_result);
  this->clipboard().ReadAsciiText(CLIPBOARD_TYPE_COPY_PASTE, &ascii_text);
  EXPECT_EQ(UTF16ToUTF8(text), ascii_text);
}

TYPED_TEST(ClipboardTest, URLTest) {
  base::string16 url(ASCIIToUTF16("http://www.google.com/"));

  {
    ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE);
    clipboard_writer.WriteURL(url);
  }

  EXPECT_THAT(this->GetAvailableTypes(CLIPBOARD_TYPE_COPY_PASTE),
              Contains(ASCIIToUTF16(Clipboard::kMimeTypeText)));
  EXPECT_TRUE(this->clipboard().IsFormatAvailable(
      Clipboard::GetPlainTextWFormatType(), CLIPBOARD_TYPE_COPY_PASTE));
  EXPECT_TRUE(this->clipboard().IsFormatAvailable(
      Clipboard::GetPlainTextFormatType(), CLIPBOARD_TYPE_COPY_PASTE));
  base::string16 text_result;
  this->clipboard().ReadText(CLIPBOARD_TYPE_COPY_PASTE, &text_result);

  EXPECT_EQ(text_result, url);

  std::string ascii_text;
  this->clipboard().ReadAsciiText(CLIPBOARD_TYPE_COPY_PASTE, &ascii_text);
  EXPECT_EQ(UTF16ToUTF8(url), ascii_text);

#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID) && \
    !defined(OS_CHROMEOS)
  ascii_text.clear();
  this->clipboard().ReadAsciiText(CLIPBOARD_TYPE_SELECTION, &ascii_text);
  EXPECT_EQ(UTF16ToUTF8(url), ascii_text);
#endif
}

static void TestBitmapWrite(Clipboard* clipboard,
                            const gfx::Size& size,
                            const uint32* bitmap_data) {
  {
    ScopedClipboardWriter scw(CLIPBOARD_TYPE_COPY_PASTE);
    SkBitmap bitmap;
    ASSERT_TRUE(bitmap.setInfo(
        SkImageInfo::MakeN32Premul(size.width(), size.height())));
    bitmap.setPixels(
        const_cast<void*>(reinterpret_cast<const void*>(bitmap_data)));
    scw.WriteImage(bitmap);
  }

  EXPECT_TRUE(clipboard->IsFormatAvailable(Clipboard::GetBitmapFormatType(),
                                           CLIPBOARD_TYPE_COPY_PASTE));
  const SkBitmap& image = clipboard->ReadImage(CLIPBOARD_TYPE_COPY_PASTE);
  EXPECT_EQ(size, gfx::Size(image.width(), image.height()));
  SkAutoLockPixels image_lock(image);
  for (int j = 0; j < image.height(); ++j) {
    const uint32* row_address = image.getAddr32(0, j);
    for (int i = 0; i < image.width(); ++i) {
      int offset = i + j * image.width();
      EXPECT_EQ(bitmap_data[offset], row_address[i]) << "i = " << i
                                                     << ", j = " << j;
    }
  }
}

TYPED_TEST(ClipboardTest, SharedBitmapTest) {
  const uint32 fake_bitmap_1[] = {
      0x46061626, 0xf69f5988, 0x793f2937, 0xfa55b986,
      0x78772152, 0x87692a30, 0x36322a25, 0x4320401b,
      0x91848c21, 0xc3177b3c, 0x6946155c, 0x64171952,
  };
  {
    SCOPED_TRACE("first bitmap");
    TestBitmapWrite(&this->clipboard(), gfx::Size(4, 3), fake_bitmap_1);
  }

  const uint32 fake_bitmap_2[] = {
      0x46061626, 0xf69f5988,
      0x793f2937, 0xfa55b986,
      0x78772152, 0x87692a30,
      0x36322a25, 0x4320401b,
      0x91848c21, 0xc3177b3c,
      0x6946155c, 0x64171952,
      0xa6910313, 0x8302323e,
  };
  {
    SCOPED_TRACE("second bitmap");
    TestBitmapWrite(&this->clipboard(), gfx::Size(2, 7), fake_bitmap_2);
  }
}

TYPED_TEST(ClipboardTest, DataTest) {
  const ui::Clipboard::FormatType kFormat =
      ui::Clipboard::GetFormatType("chromium/x-test-format");
  std::string payload("test string");
  Pickle write_pickle;
  write_pickle.WriteString(payload);

  {
    ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE);
    clipboard_writer.WritePickledData(write_pickle, kFormat);
  }

  ASSERT_TRUE(
      this->clipboard().IsFormatAvailable(kFormat, CLIPBOARD_TYPE_COPY_PASTE));
  std::string output;
  this->clipboard().ReadData(kFormat, &output);
  ASSERT_FALSE(output.empty());

  Pickle read_pickle(output.data(), output.size());
  PickleIterator iter(read_pickle);
  std::string unpickled_string;
  ASSERT_TRUE(iter.ReadString(&unpickled_string));
  EXPECT_EQ(payload, unpickled_string);
}

TYPED_TEST(ClipboardTest, MultipleDataTest) {
  const ui::Clipboard::FormatType kFormat1 =
      ui::Clipboard::GetFormatType("chromium/x-test-format1");
  std::string payload1("test string1");
  Pickle write_pickle1;
  write_pickle1.WriteString(payload1);

  const ui::Clipboard::FormatType kFormat2 =
      ui::Clipboard::GetFormatType("chromium/x-test-format2");
  std::string payload2("test string2");
  Pickle write_pickle2;
  write_pickle2.WriteString(payload2);

  {
    ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE);
    clipboard_writer.WritePickledData(write_pickle1, kFormat1);
    // overwrite the previous pickle for fun
    clipboard_writer.WritePickledData(write_pickle2, kFormat2);
  }

  ASSERT_TRUE(
      this->clipboard().IsFormatAvailable(kFormat2, CLIPBOARD_TYPE_COPY_PASTE));

  // Check string 2.
  std::string output2;
  this->clipboard().ReadData(kFormat2, &output2);
  ASSERT_FALSE(output2.empty());

  Pickle read_pickle2(output2.data(), output2.size());
  PickleIterator iter2(read_pickle2);
  std::string unpickled_string2;
  ASSERT_TRUE(iter2.ReadString(&unpickled_string2));
  EXPECT_EQ(payload2, unpickled_string2);

  {
    ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE);
    clipboard_writer.WritePickledData(write_pickle2, kFormat2);
    // overwrite the previous pickle for fun
    clipboard_writer.WritePickledData(write_pickle1, kFormat1);
  }

  ASSERT_TRUE(
      this->clipboard().IsFormatAvailable(kFormat1, CLIPBOARD_TYPE_COPY_PASTE));

  // Check string 1.
  std::string output1;
  this->clipboard().ReadData(kFormat1, &output1);
  ASSERT_FALSE(output1.empty());

  Pickle read_pickle1(output1.data(), output1.size());
  PickleIterator iter1(read_pickle1);
  std::string unpickled_string1;
  ASSERT_TRUE(iter1.ReadString(&unpickled_string1));
  EXPECT_EQ(payload1, unpickled_string1);
}

#if !defined(OS_MACOSX) && !defined(OS_ANDROID)
TYPED_TEST(ClipboardTest, HyperlinkTest) {
  const std::string kTitle("The <Example> Company's \"home page\"");
  const std::string kUrl("http://www.example.com?x=3&lt=3#\"'<>");
  const base::string16 kExpectedHtml(UTF8ToUTF16(
      ""
      "The <Example> Company's "home page""));

  std::string url_result;
  base::string16 html_result;
  {
    ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE);
    clipboard_writer.WriteHyperlink(ASCIIToUTF16(kTitle), kUrl);
  }

  EXPECT_TRUE(this->clipboard().IsFormatAvailable(
      Clipboard::GetHtmlFormatType(), CLIPBOARD_TYPE_COPY_PASTE));
  uint32 fragment_start;
  uint32 fragment_end;
  this->clipboard().ReadHTML(CLIPBOARD_TYPE_COPY_PASTE, &html_result,
                             &url_result, &fragment_start, &fragment_end);
  EXPECT_EQ(kExpectedHtml,
            html_result.substr(fragment_end - kExpectedHtml.size(),
                               kExpectedHtml.size()));
}
#endif

TYPED_TEST(ClipboardTest, WebSmartPasteTest) {
  {
    ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE);
    clipboard_writer.WriteWebSmartPaste();
  }

  EXPECT_TRUE(this->clipboard().IsFormatAvailable(
      Clipboard::GetWebKitSmartPasteFormatType(), CLIPBOARD_TYPE_COPY_PASTE));
}

#if defined(OS_WIN)  // Windows only tests.
void HtmlTestHelper(const std::string& cf_html,
                    const std::string& expected_html) {
  std::string html;
  ClipboardUtil::CFHtmlToHtml(cf_html, &html, NULL);
  EXPECT_EQ(html, expected_html);
}

TYPED_TEST(ClipboardTest, HtmlTest) {
  // Test converting from CF_HTML format data with  and
  //  comments, like from MS Word.
  HtmlTestHelper(
      "Version:1.0\r\n"
      "StartHTML:0000000105\r\n"
      "EndHTML:0000000199\r\n"
      "StartFragment:0000000123\r\n"
      "EndFragment:0000000161\r\n"
      "\r\n"
      "\r\n"
      "\r\n"
      "\r\n"
      "\r\n"
      "
Foo
\r\n"
      "\r\n"
      "\r\n"
      "\r\n"
      "\r\n\r\n",
      "
Foo
");

  // Test converting from CF_HTML format data without  and
  //  comments, like from OpenOffice Writer.
  HtmlTestHelper(
      "Version:1.0\r\n"
      "StartHTML:0000000105\r\n"
      "EndHTML:0000000151\r\n"
      "StartFragment:0000000121\r\n"
      "EndFragment:0000000131\r\n"
      "\r\n"
      "\r\n"
      "
Foo
\r\n"
      "\r\n"
      "\r\n\r\n",
      "
Foo
");
}
#endif  // defined(OS_WIN)

// Test writing all formats we have simultaneously.
TYPED_TEST(ClipboardTest, WriteEverything) {
  {
    ScopedClipboardWriter writer(CLIPBOARD_TYPE_COPY_PASTE);
    writer.WriteText(UTF8ToUTF16("foo"));
    writer.WriteURL(UTF8ToUTF16("foo"));
    writer.WriteHTML(UTF8ToUTF16("foo"), "bar");
    writer.WriteBookmark(UTF8ToUTF16("foo"), "bar");
    writer.WriteHyperlink(ASCIIToUTF16("foo"), "bar");
    writer.WriteWebSmartPaste();
    // Left out: WriteFile, WriteFiles, WriteBitmapFromPixels, WritePickledData.
  }

  // Passes if we don't crash.
}

// TODO(dcheng): Fix this test for Android. It's rather involved, since the
// clipboard change listener is posted to the Java message loop, and spinning
// that loop from C++ to trigger the callback in the test requires a non-trivial
// amount of additional work.
#if !defined(OS_ANDROID)
// Simple test that the sequence number appears to change when the clipboard is
// written to.
// TODO(dcheng): Add a version to test CLIPBOARD_TYPE_SELECTION.
TYPED_TEST(ClipboardTest, GetSequenceNumber) {
  const uint64 first_sequence_number =
      this->clipboard().GetSequenceNumber(CLIPBOARD_TYPE_COPY_PASTE);

  {
    ScopedClipboardWriter writer(CLIPBOARD_TYPE_COPY_PASTE);
    writer.WriteText(UTF8ToUTF16("World"));
  }

  // On some platforms, the sequence number is updated by a UI callback so pump
  // the message loop to make sure we get the notification.
  base::RunLoop().RunUntilIdle();

  const uint64 second_sequence_number =
      this->clipboard().GetSequenceNumber(CLIPBOARD_TYPE_COPY_PASTE);

  EXPECT_NE(first_sequence_number, second_sequence_number);
}
#endif

// Test that writing empty parameters doesn't try to dereference an empty data
// vector. Not crashing = passing.
TYPED_TEST(ClipboardTest, WriteTextEmptyParams) {
  ScopedClipboardWriter scw(CLIPBOARD_TYPE_COPY_PASTE);
  scw.WriteText(base::string16());
}

TYPED_TEST(ClipboardTest, WriteURLEmptyParams) {
  ScopedClipboardWriter scw(CLIPBOARD_TYPE_COPY_PASTE);
  scw.WriteURL(base::string16());
}

TYPED_TEST(ClipboardTest, WriteHTMLEmptyParams) {
  ScopedClipboardWriter scw(CLIPBOARD_TYPE_COPY_PASTE);
  scw.WriteHTML(base::string16(), std::string());
}

TYPED_TEST(ClipboardTest, WriteRTFEmptyParams) {
  ScopedClipboardWriter scw(CLIPBOARD_TYPE_COPY_PASTE);
  scw.WriteRTF(std::string());
}

TYPED_TEST(ClipboardTest, WriteBookmarkEmptyParams) {
  ScopedClipboardWriter scw(CLIPBOARD_TYPE_COPY_PASTE);
  scw.WriteBookmark(base::string16(), std::string());
}

TYPED_TEST(ClipboardTest, WriteHyperlinkEmptyParams) {
  ScopedClipboardWriter scw(CLIPBOARD_TYPE_COPY_PASTE);
  scw.WriteHyperlink(base::string16(), std::string());
}

TYPED_TEST(ClipboardTest, WritePickledData) {
  ScopedClipboardWriter scw(CLIPBOARD_TYPE_COPY_PASTE);
  scw.WritePickledData(Pickle(), Clipboard::GetPlainTextFormatType());
}

TYPED_TEST(ClipboardTest, WriteImageEmptyParams) {
  ScopedClipboardWriter scw(CLIPBOARD_TYPE_COPY_PASTE);
  scw.WriteImage(SkBitmap());
}

}  // namespace ui


text:
<Alloy>
	<!-- Notice there is no collection defined here-->
	<Window id="mainWindow" class="container">
		<TableView id="table" dataCollection="cars" dataTransform="transform" dataFilter="filter">
			<TableViewRow title="{title}" modelId="{id}" />
		</TableView>
	</Window>
</Alloy>


text:
package br.com.caelum.vraptor.observer;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;

import javax.servlet.http.HttpServletRequest;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import br.com.caelum.vraptor.Consumes;
import br.com.caelum.vraptor.controller.ControllerMethod;
import br.com.caelum.vraptor.controller.DefaultControllerMethod;
import br.com.caelum.vraptor.core.MethodInfo;
import br.com.caelum.vraptor.events.InterceptorsReady;
import br.com.caelum.vraptor.http.JavaParameterNameProvider;
import br.com.caelum.vraptor.ioc.Container;
import br.com.caelum.vraptor.serialization.Deserializer;
import br.com.caelum.vraptor.serialization.Deserializers;
import br.com.caelum.vraptor.view.Status;

public class DeserializingObserverTest {
	private DeserializingObserver observer;
	private ControllerMethod consumeXml;
	private ControllerMethod doesntConsume;
	private MethodInfo methodInfo;

	@Mock private HttpServletRequest request;
	@Mock Deserializers deserializers;
	@Mock Container container;
	@Mock private Status status;

	@Before
	public void setUp() throws Exception {
		MockitoAnnotations.initMocks(this);

		methodInfo = new MethodInfo(new JavaParameterNameProvider());

		observer = new DeserializingObserver(deserializers, container);
		consumeXml = new DefaultControllerMethod(null, DummyResource.class.getDeclaredMethod("consumeXml", String.class, String.class));
		doesntConsume = new DefaultControllerMethod(null, DummyResource.class.getDeclaredMethod("doesntConsume"));
	}

	static class DummyResource {
		@Consumes("application/xml")
		public void consumeXml(String a, String b) {}

		@Consumes()
		public void consumesAnything(String a, String b) {}

		public void doesntConsume() {}
	}

	@Test
	public void shouldOnlyAcceptMethodsWithConsumesAnnotation() throws Exception {
		observer.deserializes(new InterceptorsReady(doesntConsume), request, methodInfo, status);
		verifyZeroInteractions(request);
	}

	@Test
	public void willSetHttpStatusCode415IfTheControllerMethodDoesNotSupportTheGivenMediaTypes() throws Exception {
		when(request.getContentType()).thenReturn("image/jpeg");

		observer.deserializes(new InterceptorsReady(consumeXml), request, methodInfo, status);

		verify(status).unsupportedMediaType("Request with media type [image/jpeg]. Expecting one of [application/xml].");
	}

	@Test
	public void willSetHttpStatusCode415IfThereIsNoDeserializerButIsAccepted() throws Exception {
		when(request.getContentType()).thenReturn("application/xml");
		when(deserializers.deserializerFor("application/xml", container)).thenReturn(null);

		observer.deserializes(new InterceptorsReady(consumeXml), request, methodInfo, status);

		verify(status).unsupportedMediaType("Unable to handle media type [application/xml]: no deserializer found.");
	}

	@Test
	public void willSetMethodParametersWithDeserializationAndContinueStackAfterDeserialization() throws Exception {
		final Deserializer deserializer = mock(Deserializer.class);

		methodInfo.setControllerMethod(consumeXml);

		when(request.getContentType()).thenReturn("application/xml");
		when(deserializer.deserialize(null, consumeXml)).thenReturn(new Object[] {"abc", "def"});
		when(deserializers.deserializerFor("application/xml", container)).thenReturn(deserializer);

		observer.deserializes(new InterceptorsReady(consumeXml), request, methodInfo, status);

		assertEquals(methodInfo.getValuedParameters()[0].getValue(), "abc");
		assertEquals(methodInfo.getValuedParameters()[1].getValue(), "def");
	}

	@Test
	public void willSetMethodParametersWithDeserializationEvenIfTheContentTypeHasCharsetDeclaration() throws Exception {
		final Deserializer deserializer = mock(Deserializer.class);

		methodInfo.setControllerMethod(consumeXml);

		when(request.getContentType()).thenReturn("application/xml; charset=UTF-8");
		when(deserializer.deserialize(null, consumeXml)).thenReturn(new Object[] {"abc", "def"});
		when(deserializers.deserializerFor("application/xml", container)).thenReturn(deserializer);

		observer.deserializes(new InterceptorsReady(consumeXml), request, methodInfo, status);

		assertEquals(methodInfo.getValuedParameters()[0].getValue(), "abc");
		assertEquals(methodInfo.getValuedParameters()[1].getValue(), "def");
	}

	@Test
	public void willDeserializeForAnyContentTypeIfPossible() throws Exception {
		final ControllerMethod consumesAnything = new DefaultControllerMethod(null,
				DummyResource.class.getDeclaredMethod("consumesAnything", String.class, String.class));

		when(request.getContentType()).thenReturn("application/xml");

		methodInfo.setControllerMethod(consumesAnything);

		final Deserializer deserializer = mock(Deserializer.class);
		when(deserializer.deserialize(null, consumesAnything)).thenReturn(new Object[] {"abc", "def"});

		when(deserializers.deserializerFor("application/xml", container)).thenReturn(deserializer);
		observer.deserializes(new InterceptorsReady(consumesAnything), request, methodInfo, status);

		assertEquals(methodInfo.getValuedParameters()[0].getValue(), "abc");
		assertEquals(methodInfo.getValuedParameters()[1].getValue(), "def");
	}

	@Test
	public void shouldNotDeserializeIfHasNoContentType() throws Exception {
		final ControllerMethod consumesAnything = new DefaultControllerMethod(null, DummyResource.class.getDeclaredMethod("consumesAnything", String.class, String.class));

		when(request.getContentType()).thenReturn(null);
		methodInfo.setControllerMethod(consumesAnything);
		observer.deserializes(new InterceptorsReady(consumesAnything), request, methodInfo, status);

		assertEquals(methodInfo.getValuedParameters()[0].getValue(), null);
		assertEquals(methodInfo.getValuedParameters()[1].getValue(), null);
	}

	@Test
	public void willSetOnlyNonNullParameters() throws Exception {
		final Deserializer deserializer = mock(Deserializer.class);

		methodInfo.setControllerMethod(consumeXml);
		methodInfo.getValuedParameters()[0].setValue("original1");
		methodInfo.getValuedParameters()[1].setValue("original2");

		when(request.getContentType()).thenReturn("application/xml");
		when(deserializer.deserialize(null, consumeXml)).thenReturn(new Object[] {null, "deserialized"});

		when(deserializers.deserializerFor("application/xml", container)).thenReturn(deserializer);
		observer.deserializes(new InterceptorsReady(consumeXml), request, methodInfo, status);

		assertEquals(methodInfo.getValuedParameters()[0].getValue(), "original1");
		assertEquals(methodInfo.getValuedParameters()[1].getValue(), "deserialized");
	}
}


text:
package net.ngeor.t3;

public interface MainActivityView {
    void setHeaderText(int resourceId);

    void invalidateBoardView();
}


text:
module Policy.BoundedShortestPath
( BoundedShortestPath(..)
) where

import Algebra.Semiring

data BoundedShortestPath = BSP Int
  deriving(Eq)

instance Show BoundedShortestPath where
  show (BSP k)
    | ( k < intMu ) = show k
    | otherwise = "µ"

instance Semiring (BoundedShortestPath) where
  add (BSP x) (BSP y) = BSP (min x y)
  zero = mu

  mul (BSP x) (BSP y)
    | (x + y < 15) = BSP (x + y)
    |   otherwise  = mu
  unit = (BSP 0)

mu :: BoundedShortestPath
mu = (BSP intMu)

intMu :: Int
intMu = 7


text:
#import <Foundation/Foundation.h>

@interface shoppingCartItemEntity : NSObject
{
}
@property (nonatomic, copy) NSString *item_id;
@property (nonatomic, copy) NSString *created_at;
@property (nonatomic, copy) NSString *updated_at;
@property (nonatomic, copy) NSString *product_id;
@property (nonatomic, copy) NSString *store_id;
@property (nonatomic, copy) NSString *parent_item_id;
@property int is_virtual;
@property BOOL is_virtualSpecified;
@property (nonatomic, copy) NSString *sku;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *desc;
@property (nonatomic, copy) NSString *applied_rule_ids;
@property (nonatomic, copy) NSString *additional_data;
@property (nonatomic, copy) NSString *free_shipping;
@property (nonatomic, copy) NSString *is_qty_decimal;
@property (nonatomic, copy) NSString *no_discount;
@property double weight;
@property BOOL weightSpecified;
@property double qty;
@property BOOL qtySpecified;
@property double price;
@property BOOL priceSpecified;
@property double base_price;
@property BOOL base_priceSpecified;
@property double custom_price;
@property BOOL custom_priceSpecified;
@property double discount_percent;
@property BOOL discount_percentSpecified;
@property double discount_amount;
@property BOOL discount_amountSpecified;
@property double base_discount_amount;
@property BOOL base_discount_amountSpecified;
@property double tax_percent;
@property BOOL tax_percentSpecified;
@property double tax_amount;
@property BOOL tax_amountSpecified;
@property double base_tax_amount;
@property BOOL base_tax_amountSpecified;
@property double row_total;
@property BOOL row_totalSpecified;
@property double base_row_total;
@property BOOL base_row_totalSpecified;
@property double row_total_with_discount;
@property BOOL row_total_with_discountSpecified;
@property double row_weight;
@property BOOL row_weightSpecified;
@property (nonatomic, copy) NSString *product_type;
@property double base_tax_before_discount;
@property BOOL base_tax_before_discountSpecified;
@property double tax_before_discount;
@property BOOL tax_before_discountSpecified;
@property double original_custom_price;
@property BOOL original_custom_priceSpecified;
@property double base_cost;
@property BOOL base_costSpecified;
@property double price_incl_tax;
@property BOOL price_incl_taxSpecified;
@property double base_price_incl_tax;
@property BOOL base_price_incl_taxSpecified;
@property double row_total_incl_tax;
@property BOOL row_total_incl_taxSpecified;
@property double base_row_total_incl_tax;
@property BOOL base_row_total_incl_taxSpecified;
@property (nonatomic, copy) NSString *gift_message_id;
@property (nonatomic, copy) NSString *gift_message;
@property (nonatomic, copy) NSString *gift_message_available;
@property double weee_tax_applied;
@property BOOL weee_tax_appliedSpecified;
@property double weee_tax_applied_amount;
@property BOOL weee_tax_applied_amountSpecified;
@property double weee_tax_applied_row_amount;
@property BOOL weee_tax_applied_row_amountSpecified;
@property double base_weee_tax_applied_amount;
@property BOOL base_weee_tax_applied_amountSpecified;
@property double base_weee_tax_applied_row_amount;
@property BOOL base_weee_tax_applied_row_amountSpecified;
@property double weee_tax_disposition;
@property BOOL weee_tax_dispositionSpecified;
@property double weee_tax_row_disposition;
@property BOOL weee_tax_row_dispositionSpecified;
@property double base_weee_tax_disposition;
@property BOOL base_weee_tax_dispositionSpecified;
@property double base_weee_tax_row_disposition;
@property BOOL base_weee_tax_row_dispositionSpecified;
@property (nonatomic, copy) NSString *tax_class_id;

-(NSString*)toString:(BOOL)addNameWrap;
-(id)initWithArray:(NSArray*)array;
-(void)encodeWithCoder:(NSCoder *)encoder;
-(id)copyWithZone:(NSZone *)zone;
-(id)initWithCoder:(NSCoder *)decoder;
@end


text:
<?php

// Copyright (c) 2008, RedIRIS. All Rights Reserved.
//
// You may distribute under the terms of the GNU General Public License,
// as specified in the LICENSE file that was shipped with this distribution

// 2008.13.13: Updated for latest SimpleSAMLphp from trunk
// 2008.09.10: Case insensitive attribute names.
// 2008.09.11: Checks for SIGNOFF action and redirects to InitSLO.

require_once "crypt.php";

$config        = array();
$attr_mapping  = array();
$config_params = array(    // Name => mandatory?
	'LogFile'        => true,
	'AuthServerId'   => true,
	'TTL'            => true,
	'PrivateKey'     => true,
	'KeyLen'         => true,
	'SSP-authsource' => true,
	'Debug'          => false,
);

// If not defined, we'll use the same name as this script, but ended in '.cfg.php'
//$cfgFile = "SimpleSAMLGPoA.cfg.php";

$mv_separator = '+';

get_config();

if (!isset($_REQUEST["ACTION"]) && !isset($_REQUEST["ATTREQ"]))
	error("Unknown request. Use the PAPI 1.0 protocol");

// Modified (JAAD-2008.09.11)
if (isset($_REQUEST["ACTION"]) && $_REQUEST["ACTION"] != "SIGNOFF" && ($_REQUEST["ACTION"] != "CHECK" || !isset($_REQUEST["DATA"]) || !isset($_REQUEST["URL"])))
	error("Unknown request. Use the PAPI 1.0 protocol");

if (isset($_REQUEST["ATTREQ"]) && (!isset($_REQUEST["PAPIPOAREF"]) || !isset($_REQUEST["PAPIPOAURL"])))
	error("Unknown request. Use the PAPI 1.0 protocol");

if (isset($_REQUEST["ACTION"])) {
	$theURL = $_REQUEST["URL"];
	$theRef = $_REQUEST["DATA"];
} else {
	$theURL = $_REQUEST["PAPIPOAURL"];
	$theRef = $_REQUEST["PAPIPOAREF"];
}

// Check for signoff request (JAAD-2008.09.11)
if (isset($_REQUEST["ACTION"]) && $_REQUEST["ACTION"] == "SIGNOFF") {

	if (isset ($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')
		$protocol = 'https://';
	else
		$protocol = 'http://';

	// We need a better solution for that. Maybe using SSp stuff?
	$SLOpath = "/simplesaml/saml2/sp/initSLO.php" ;

	$redirectTo = $protocol.$_SERVER['SERVER_NAME'] . $SLOpath . "?RelayState=" . $theURL . "&ACTION=SIGNEDOFF" ;
	header("Location: $redirectTo");
	exit;
}

// Search for the PoA in the config. file
foreach ( array_keys( $config['PoA']) as $poadef) {
	if (preg_match("|".$poadef."|", $theURL)) {
		$reqPoA = $poadef;
		break;
	}
}

if ( !isset( $reqPoA))
	error("No matching PoA found for:" . $theURL);

get_config_poa( $reqPoA);

// PoA found, so we can now start with the SimpleSAML stuff
require_once('/var/simplesamlphp/lib/_autoload.php');

try {
	$ssp_as = new SimpleSAML_Auth_Simple( $config["SSP-authsource"]);
	$ssp_as->requireAuth();
	$attributes = $ssp_as->getAttributes();
} catch( Exception $e) {
	error( "simpleSAMLphp exception:" . $e->getMessage());
}

doLog( "Received attributes:");
foreach ($attributes as $key => $value)
	doLog("  $key => " . implode( "|", $value));

// Convert attribute keys to upper case (JAAD-2008.09.10)
$upattributes = array();
foreach ($attributes as $key => $value)
	$upattributes[strtoupper($key)] = $value;

// If attributes are right, we can start mapping them to requested configuration
$assertion = "";

foreach ($attr_mapping as $key => $value) {
	$fragmentValues = array();
	$vparts = explode( $mv_separator, $value);

	foreach( $vparts as $vpart) {
		// starts and ends with single or double quotes: literal
		if( preg_match("/^(['\"])(.*)\\1\$/", $vpart, $matches)) {
			$fragmentValues[] = $matches[2];
		// PHP file -> function invocation
		} else if( preg_match("/^(.*)->(.*)/", $vpart, $matches)) {
			if( file_exists( $matches[1])) {
				include_once( $matches[1]);
				if( function_exists( $matches[2]))
					$fragmentValues[] = $matches[2]( $upattributes);
			} else;
		// Direct mapping
 		} else if( isset( $upattributes[strtoupper($vpart)][0])) {
			$fragmentValues += $upattributes[strtoupper($vpart)];
		}
	}

	if( !count($fragmentValues))
		continue;
	$assertFragment = $key . "=" . implode( '|', $fragmentValues);
	if ($assertion != "")
		$assertion .= "," . $assertFragment;
	else
		$assertion = $assertFragment;
}

$assertion .= "@" . $config["AuthServerId"];
// Diego, poaCrypt class is not defined in latest svn crypt.file (as of 2007.10.08) :-)
// $poac = new poaCrypt();

$now = time();
$ext = $now + $config["TTL"];
$reply = $assertion . ":" . $ext . ":" . $now . ":" . $theRef;

// No class available, so we'll use a normal function call, instead
// $safe = $poac->openssl_encrypt($reply, $pKey);
$safe = openssl_encrypt($reply, $config["PrivateKey"], $config["KeyLen"]);

doLog( "Reply:$reply");

if (strpos($theURL, "?"))
	$redirectTo = $theURL . "&";
else
	$redirectTo = $theURL . "?";

if (isset($_REQUEST["ACTION"])) {
	$redirectTo .= "ACTION=CHECKED" . "&" . "DATA=" . urlencode($safe);
	doLog("GPoA response to " . $theURL . ": " . $reply . "SAFE: " . $safe);
}
else {
	$redirectTo .= "AS=" . $config["AuthServerId"] . "&ACTION=CHECKED" . "&" . "DATA=" . urlencode($safe);
	doLog("AS response to " . $theURL . ": " . $reply);
}

doLog( "Redirecting to:$redirectTo");
header("Location: $redirectTo");
exit;

function get_config() {
	global $cfgFile, $config, $config_params;
	$errmsg = "";

	if( !isset( $cfgFile)) {
		$path_parts = pathinfo( $_SERVER["SCRIPT_FILENAME"]);
		// The "filename" element is only present in PHP >=5.2
		$cfgFile = $path_parts["dirname"] . "/" .
			basename( $_SERVER["SCRIPT_FILENAME"],'.'.$path_parts['extension']) . ".cfg.php";
	}

	if( !file_exists( $cfgFile))
		error( "The config file does not exist:$cfgFile");

	require_once( $cfgFile);

	// Sanity check: All mandatory parameters must be present
	foreach( $config_params as $param_name => $mandatory) {
		if( $mandatory && !isset( $config[$param_name]))
			$missing[] = $param_name;
	}
	if( isset( $missing) && count( $missing))
		$errmsg .= " Missing mandatory parameters:" . implode( ',', $missing);

	// Sanity check: Detect unknown parameters
	foreach( $config as $name => $value) {
		if( $name == "PoA")
			continue;
		if( !array_key_exists( $name, $config_params))
			$unknown[] = $name;
	}
	if( isset( $unknown) && count( $unknown))
		$errmsg .= " Unknown parameters:" . implode( ',', $unknown);

	// Detect problems as soon as possible
	if( !openssl_get_privatekey( $config["PrivateKey"]))
		$errmsg .= " Cannot read PrivateKey:" . $config["PrivateKey"];

	if( $errmsg)
		error( "Fatal error reading config file ($cfgFile):$errmsg");
}

// When we know the PoA, make its settings override the global ones,
// and set attribute mapping
function get_config_poa( $poa) {
	global $config, $attr_mapping;

	// Override and/or set config. params
	if( isset( $config['PoA'][$poa]['config'])) {
		foreach( $config['PoA'][$poa]['config'] as $k => $v)
			$config[$k] = $v;
	}

	// Attribute mapping
	// TODO: Make sure there is a attr_mapping key
	$attr_mapping = $config['PoA'][$poa]['attr_mapping'];
}

function error($msg) {
	doLog($msg);
	header("HTTP/1.0 500 Server error: $msg");
	exit();
}

function debug( $msg) {
	global $config;
	if( $config["Debug"])
		doLog( $msg);
}

function doLog($msg) {
	global $config;
	if( !isset( $config["LogFile"])) {  // Before we have read config, and so LogFile
		error_log($msg);
		return;
	}
	if ($config["LogFile"] != "/dev/null") {
		$emsg = date("d-M-Y H:i:s") . ", " . $config["AuthServerId"] . ": " . $msg . "\n";
		error_log($emsg, 3, $config["LogFile"]);
	}
}
?>


text:
""" p2p-streams  (c)  2014 enen92 fightnight

    This file contains the the code for favourites used in the addon

    Functions:

	addon_favourites() -> Main menu. It parses the userdata/Favourites folder for items and lists them
	manual_add_to_favourites() -> Add a favourite to list manually
	add_to_addon_favourites(name,url,iconimage) -> Add an item to the addon favourites. Receives the name of the channel, the url and the iconimage
	remove_addon_favourites(url) -> Remove from addon favourites

"""

import xbmc,xbmcgui,xbmcplugin,xbmcvfs,sys,os
from peertopeerutils.pluginxbmc import *
from peertopeerutils.iofile import *
from peertopeerutils.directoryhandle import addDir
from random import randint

def addon_favourites():
	if os.path.exists(os.path.join(pastaperfil,"Favourites")):
		dirs, files = xbmcvfs.listdir(os.path.join(pastaperfil,"Favourites"))
		if files:
			for file in files:
				string = readfile(os.path.join(pastaperfil,"Favourites",file))
				match = string.split("|")
				try: iconimage = match[3]
				except:
					if 'acestream' in file: iconimage = addonpath + art + 'acelogofull.png'
					elif 'sop' in file: iconimage = addonpath + art + 'sopcast_logo.jpg'
					else: iconimage = ''
				addDir("[B][COLOR orange]" + match[0] + "[/B][/COLOR]",match[2],int(match[1]),iconimage,1,False)
	addDir('[B]' + translate(70022) + '[/B]',MainURL,203,addonpath + art + 'plus-menu.png',2,False)
	xbmc.executebuiltin("Container.SetViewMode(51)")

def manual_add_to_favourites():
	keyb = xbmc.Keyboard("", translate(70023))
	keyb.doModal()
	if (keyb.isConfirmed()):
		favourite_url = keyb.getText()
		if ('acestream://' in favourite_url) or ('sop://' in favourite_url) or ('.acelive' in favourite_url) or ('.torrent' in favourite_url):
			keyb = xbmc.Keyboard("", translate(70024))
			keyb.doModal()
			if (keyb.isConfirmed()):
				favourite_name = keyb.getText()
				if favourite_name: pass
				else: favourite_name = 'p2p-streams ' + str(randint(1,100))
				add_to_addon_favourites(favourite_name,favourite_url,'')
		else:
			mensagemok(translate(40000),translate(40128))

def add_to_addon_favourites(name,url,iconimage):
	name = name.replace("[b]","").replace("[/b]","").replace("[color orange]","").replace("[/color]","").replace("[B]","").replace("[/B]","")
	if "runplugin" in url:
		match = re.compile("url=(.+?)&mode=(.+?)&").findall(url.replace(";",""))
		for url,mode in match:
			favourite_text = str(name) + " (" + str(url) + ")|" + str(mode) + "|" + str(url) + '|' + str(iconimage)
			favouritetxt = os.path.join(pastaperfil,"Favourites",url.replace(":","").replace("/","") + ".txt")
			if not xbmcvfs.exists(os.path.join(pastaperfil,"Favourites")): xbmcvfs.mkdir(os.path.join(pastaperfil,"Favourites"))
			save(favouritetxt, favourite_text)
			xbmc.executebuiltin("Notification(%s,%s,%i,%s)" % (translate(40000), translate(40148), 1,addonpath+"/icon.png"))
	else:
		if "sop://" in url:
			tipo = "sopcast"
			if not iconimage: iconimage = os.path.join(addonpath,'resources','art','sopcast_logo.jpg')
		elif "acestream://" in url:
			tipo = "acestream"
			if not iconimage: iconimage = os.path.join(addonpath,'resources','art','acelogofull.jpg')
		elif ".torrent" in url:
			tipo = "acestream"
			if not iconimage: iconimage = os.path.join(addonpath,'resources','art','acelogofull.jpg')
		elif ".acelive" in url:
			tipo = "acestream"
			if not iconimage: iconimage = os.path.join(addonpath,'resources','art','acelogofull.jpg')
		else:
			if len(url) < 30: tipo = "sopcast"
			else: tipo = "acestream"
		if tipo == "sopcast":
			favourite_text = str(name) + " (" + str(url) + ")|" + str(2) + "|" + str(url) + '|' + str(iconimage)
		elif tipo == "acestream":
			favourite_text = str(name) + " (" + str(url) + ")|" + str(1) + "|" + str(url) + '|' + str(iconimage)
		favouritetxt = os.path.join(pastaperfil,"Favourites",url.replace(":","").replace("/","") + ".txt")
		if not xbmcvfs.exists(os.path.join(pastaperfil,"Favourites")): xbmcvfs.mkdir(os.path.join(pastaperfil,"Favourites"))
		save(favouritetxt, favourite_text)
		xbmc.executebuiltin("Notification(%s,%s,%i,%s)" % (translate(40000), translate(40148), 1,addonpath+"/icon.png"))
		xbmc.executebuiltin("Container.Refresh")

def remove_addon_favourites(url):
	if "runplugin" in url:
		match = re.compile("url=(.+?)&mode").findall(url.replace(";",""))
		if match: ficheiro = os.path.join(pastaperfil,"Favourites",match[0].replace("/","").replace(":","") + ".txt")
	else:
		ficheiro = os.path.join(pastaperfil,"Favourites",url.replace(":","").replace("/","") + ".txt")
	xbmcvfs.delete(ficheiro)
	xbmc.executebuiltin("Notification(%s,%s,%i,%s)" % (translate(40000), translate(40147), 1,addonpath+"/icon.png"))
	xbmc.executebuiltin("Container.Refresh")


text:
using System.Collections.Generic;
using NUnit.Framework;
using SevenDigital.Api.Schema.Packages;

namespace SevenDigital.Api.Schema.Unit.Tests.Packages
{
	[TestFixture]
	public class PackagesTests
	{
		[Test]
		public void Should_have_no_primary_package_when_there_are_no_packages()
		{
			var download = new Download();

			var primaryPackage = download.PrimaryPackage();

			Assert.That(primaryPackage, Is.Null);
		}

		[Test]
		public void Should_have_primary_package_when_there_is_one_package()
		{
			var download = new Download
			{
				Packages = new List<Package>
				{
					new Package {Id = 123}
				}
			};

			var primaryPackage = download.PrimaryPackage();

			Assert.That(primaryPackage, Is.Not.Null);
			Assert.That(primaryPackage.Id, Is.EqualTo(123));
		}

		[Test]
		public void Should_pick_standard_package_if_present()
		{
			var download = new Download
			{
				Packages = new List<Package>
				{
					new Package {Id = 123},
					new Package {Id = 456},
					new Package {Id = 2},
					new Package {Id = 789}
				}
			};

			var primaryPackage = download.PrimaryPackage();

			Assert.That(primaryPackage, Is.Not.Null);
			Assert.That(primaryPackage.Id, Is.EqualTo(2));
		}

		[Test]
		public void Should_fall_back_to_first_package()
		{
			var download = new Download
			{
				Packages = new List<Package>
				{
					new Package {Id = 123},
					new Package {Id = 456},
					new Package {Id = 789}
				}
			};

			var primaryPackage = download.PrimaryPackage();

			Assert.That(primaryPackage, Is.Not.Null);
			Assert.That(primaryPackage.Id, Is.EqualTo(123));
		}
	}
}


text:
/*
 * This file was semi-automatically converted from the public-domain USGS PROJ source.
 */
package com.jhlabs.map.proj;

public class QuarticAuthalicProjection extends STSProjection {

	public QuarticAuthalicProjection() {
		super( 2., 2., false );
	}

	public String toString() {
		return "Quartic Authalic";
	}

}


text:
using NUnit.Framework;
using Persistence;
using System;
using System.Data.SqlClient;

namespace PersistenceTest
{
    [TestFixture]
    public class DatabaseConnectionTest
    {
        [Test]
        public void CanConnectToDatabase()
        {
            using (var conn = new SqlConnection(Config.MsSqlDbConnectionString))
            {
                conn.Open();
                var cmd = new SqlCommand("select * from sys.databases", conn);

                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read()) Console.WriteLine(reader[0]);
                }
            }
        }
    }
}


text:
package tools.gsf.facade.runtag.satellite;

import tools.gsf.facade.runtag.AbstractTagRunner;

/**
 * <satellite.page>
 *
 * @author Tony Field
 * @since Mar 31, 2011
 */
public final class Page extends AbstractTagRunner {
    public Page() {
        super("satellite.page");
    }

    public void setPagename(String s) {
        set("pagename", s);
    }

}


text:
import { Package } from "../packageManager/Package";

export function GetPackagesFromVersion(version: string, runTimeDependencies: Package[], serverUrl: string, installPath: string): Package[] {
    if (!version) {
        throw new Error('Invalid version');
    }

    let versionPackages = new Array<Package>();
    for (let inputPackage of runTimeDependencies) {
        if (inputPackage.platformId) {
            versionPackages.push(SetBinaryAndGetPackage(inputPackage, serverUrl, version, installPath));
        }
    }

    return versionPackages;
}

export function SetBinaryAndGetPackage(inputPackage: Package, serverUrl: string, version: string, installPath: string): Package {
    let installBinary: string;
    if (inputPackage.platformId === "win-x86" || inputPackage.platformId === "win-x64") {
        installBinary = "OmniSharp.exe";
    }
    else {
        installBinary = "run";
    }

    return GetPackage(inputPackage, serverUrl, version, installPath, installBinary);
}

function GetPackage(inputPackage: Package, serverUrl: string, version: string, installPath: string, installBinary: string): Package {
    if (!version) {
        throw new Error('Invalid version');
    }

    let versionPackage: Package = {
        id: inputPackage.id,
        description: `${inputPackage.description}, Version = ${version}`,
        url: `${serverUrl}/releases/${version}/omnisharp-${inputPackage.platformId}.zip`,
        installPath: `${installPath}/${version}`,
        installTestPath: `./${installPath}/${version}/${installBinary}`,
        platforms: inputPackage.platforms,
        architectures: inputPackage.architectures,
        binaries: inputPackage.binaries,
        platformId: inputPackage.platformId
    };

    return versionPackage;
}