text:
<?php

if (!defined('SMF'))
	die('No direct access...');

/**
 * Get all birthdays within the given time range.
 * finds all the birthdays in the specified range of days.
 * works with birthdays set for no year, or any other year, and respects month and year boundaries.
 *
 * @param string $low_date The low end of the range, inclusive, in YYYY-MM-DD format
 * @param string $high_date The high end of the range, inclusive, in YYYY-MM-DD format
 * @return array An array of days, each of which is an array of birthday information for the context
 */
function getBirthdayRange($low_date, $high_date)
{
	global $smcFunc;

	// We need to search for any birthday in this range, and whatever year that birthday is on.
	$year_low = (int) substr($low_date, 0, 4);
	$year_high = (int) substr($high_date, 0, 4);

	// Collect all of the birthdays for this month.  I know, it's a painful query.
	$result = $smcFunc['db_query']('birthday_array', '
		SELECT id_member, real_name, YEAR(birthdate) AS birth_year, birthdate
		FROM {db_prefix}members
		WHERE YEAR(birthdate) != {string:year_one}
			AND MONTH(birthdate) != {int:no_month}
			AND DAYOFMONTH(birthdate) != {int:no_day}
			AND YEAR(birthdate) <= {int:max_year}
			AND (
				DATE_FORMAT(birthdate, {string:year_low}) BETWEEN {date:low_date} AND {date:high_date}' . ($year_low == $year_high ? '' : '
				OR DATE_FORMAT(birthdate, {string:year_high}) BETWEEN {date:low_date} AND {date:high_date}') . '
			)
			AND is_activated = {int:is_activated}',
		array(
			'is_activated' => 1,
			'no_month' => 0,
			'no_day' => 0,
			'year_one' => '0001',
			'year_low' => $year_low . '-%m-%d',
			'year_high' => $year_high . '-%m-%d',
			'low_date' => $low_date,
			'high_date' => $high_date,
			'max_year' => $year_high,
		)
	);
	$bday = array();
	while ($row = $smcFunc['db_fetch_assoc']($result))
	{
		if ($year_low != $year_high)
			$age_year = substr($row['birthdate'], 5) < substr($high_date, 5) ? $year_high : $year_low;
		else
			$age_year = $year_low;

		$bday[$age_year . substr($row['birthdate'], 4)][] = array(
			'id' => $row['id_member'],
			'name' => $row['real_name'],
			'age' => $row['birth_year'] > 4 && $row['birth_year'] <= $age_year ? $age_year - $row['birth_year'] : null,
			'is_last' => false
		);
	}
	$smcFunc['db_free_result']($result);

	// Set is_last, so the themes know when to stop placing separators.
	foreach ($bday as $mday => $array)
		$bday[$mday][count($array) - 1]['is_last'] = true;

	return $bday;
}

/**
 * Get all calendar events within the given time range.
 *
 * - finds all the posted calendar events within a date range.
 * - both the earliest_date and latest_date should be in the standard YYYY-MM-DD format.
 * - censors the posted event titles.
 * - uses the current user's permissions if use_permissions is true, otherwise it does nothing "permission specific"
 *
 * @param string $low_date The low end of the range, inclusive, in YYYY-MM-DD format
 * @param string $high_date The high end of the range, inclusive, in YYYY-MM-DD format
 * @param bool $use_permissions Whether to use permissions
 * @return array Contextual information if use_permissions is true, and an array of the data needed to build that otherwise
 */
function getEventRange($low_date, $high_date, $use_permissions = true)
{
	global $scripturl, $modSettings, $user_info, $smcFunc, $context;

	$low_date_time = sscanf($low_date, '%04d-%02d-%02d');
	$low_date_time = mktime(0, 0, 0, $low_date_time[1], $low_date_time[2], $low_date_time[0]);
	$high_date_time = sscanf($high_date, '%04d-%02d-%02d');
	$high_date_time = mktime(0, 0, 0, $high_date_time[1], $high_date_time[2], $high_date_time[0]);

	// Find all the calendar info...
	$result = $smcFunc['db_query']('', '
		SELECT
			cal.id_event, cal.start_date, cal.end_date, cal.title, cal.id_member, cal.id_topic,
			cal.id_board, b.member_groups, t.id_first_msg, t.approved, b.id_board
		FROM {db_prefix}calendar AS cal
			LEFT JOIN {db_prefix}boards AS b ON (b.id_board = cal.id_board)
			LEFT JOIN {db_prefix}topics AS t ON (t.id_topic = cal.id_topic)
		WHERE cal.start_date <= {date:high_date}
			AND cal.end_date >= {date:low_date}' . ($use_permissions ? '
			AND (cal.id_board = {int:no_board_link} OR {query_wanna_see_board})' : ''),
		array(
			'high_date' => $high_date,
			'low_date' => $low_date,
			'no_board_link' => 0,
		)
	);
	$events = array();
	while ($row = $smcFunc['db_fetch_assoc']($result))
	{
		// If the attached topic is not approved then for the moment pretend it doesn't exist
		if (!empty($row['id_first_msg']) && $modSettings['postmod_active'] && !$row['approved'])
			continue;

		// Force a censor of the title - as often these are used by others.
		censorText($row['title'], $use_permissions ? false : true);

		$start_date = sscanf($row['start_date'], '%04d-%02d-%02d');
		$start_date = max(mktime(0, 0, 0, $start_date[1], $start_date[2], $start_date[0]), $low_date_time);
		$end_date = sscanf($row['end_date'], '%04d-%02d-%02d');
		$end_date = min(mktime(0, 0, 0, $end_date[1], $end_date[2], $end_date[0]), $high_date_time);

		$lastDate = '';
		for ($date = $start_date; $date <= $end_date; $date += 86400)
		{
			// Attempt to avoid DST problems.
			// @todo Resolve this properly at some point.
			if (strftime('%Y-%m-%d', $date) == $lastDate)
				$date += 3601;
			$lastDate = strftime('%Y-%m-%d', $date);

			// If we're using permissions (calendar pages?) then just ouput normal contextual style information.
			if ($use_permissions)
				$events[strftime('%Y-%m-%d', $date)][] = array(
					'id' => $row['id_event'],
					'title' => $row['title'],
					'start_date' => $row['start_date'],
					'end_date' => $row['end_date'],
					'is_last' => false,
					'id_board' => $row['id_board'],
					'is_selected' => !empty($context['selected_event']) && $context['selected_event'] == $row['id_event'],
					'href' => $row['id_board'] == 0 ? '' : $scripturl . '?topic=' . $row['id_topic'] . '.0',
					'link' => $row['id_board'] == 0 ? $row['title'] : '' . $row['title'] . '',
					'can_edit' => allowedTo('calendar_edit_any') || ($row['id_member'] == $user_info['id'] && allowedTo('calendar_edit_own')),
					'modify_href' => $scripturl . '?action=' . ($row['id_board'] == 0 ? 'calendar;sa=post;' : 'post;msg=' . $row['id_first_msg'] . ';topic=' . $row['id_topic'] . '.0;calendar;') . 'eventid=' . $row['id_event'] . ';' . $context['session_var'] . '=' . $context['session_id'],
					'can_export' => !empty($modSettings['cal_export']) ? true : false,
					'export_href' => $scripturl . '?action=calendar;sa=ical;eventid=' . $row['id_event'] . ';' . $context['session_var'] . '=' . $context['session_id'],
				);
			// Otherwise, this is going to be cached and the VIEWER'S permissions should apply... just put together some info.
			else
				$events[strftime('%Y-%m-%d', $date)][] = array(
					'id' => $row['id_event'],
					'title' => $row['title'],
					'start_date' => $row['start_date'],
					'end_date' => $row['end_date'],
					'is_last' => false,
					'id_board' => $row['id_board'],
					'is_selected' => !empty($context['selected_event']) && $context['selected_event'] == $row['id_event'],
					'href' => $row['id_topic'] == 0 ? '' : $scripturl . '?topic=' . $row['id_topic'] . '.0',
					'link' => $row['id_topic'] == 0 ? $row['title'] : '' . $row['title'] . '',
					'can_edit' => false,
					'can_export' => !empty($modSettings['cal_export']) ? true : false,
					'topic' => $row['id_topic'],
					'msg' => $row['id_first_msg'],
					'poster' => $row['id_member'],
					'allowed_groups' => explode(',', $row['member_groups']),
				);
		}
	}
	$smcFunc['db_free_result']($result);

	// If we're doing normal contextual data, go through and make things clear to the templates ;).
	if ($use_permissions)
	{
		foreach ($events as $mday => $array)
			$events[$mday][count($array) - 1]['is_last'] = true;
	}

	return $events;
}

/**
 * Get all holidays within the given time range.
 *
 * @param string $low_date The low end of the range, inclusive, in YYYY-MM-DD format
 * @param string $high_date The high end of the range, inclusive, in YYYY-MM-DD format
 * @return array An array of days, which are all arrays of holiday names.
 */
function getHolidayRange($low_date, $high_date)
{
	global $smcFunc;

	// Get the lowest and highest dates for "all years".
	if (substr($low_date, 0, 4) != substr($high_date, 0, 4))
		$allyear_part = 'event_date BETWEEN {date:all_year_low} AND {date:all_year_dec}
			OR event_date BETWEEN {date:all_year_jan} AND {date:all_year_high}';
	else
		$allyear_part = 'event_date BETWEEN {date:all_year_low} AND {date:all_year_high}';

	// Find some holidays... ;).
	$result = $smcFunc['db_query']('', '
		SELECT event_date, YEAR(event_date) AS year, title
		FROM {db_prefix}calendar_holidays
		WHERE event_date BETWEEN {date:low_date} AND {date:high_date}
			OR ' . $allyear_part,
		array(
			'low_date' => $low_date,
			'high_date' => $high_date,
			'all_year_low' => '0004' . substr($low_date, 4),
			'all_year_high' => '0004' . substr($high_date, 4),
			'all_year_jan' => '0004-01-01',
			'all_year_dec' => '0004-12-31',
		)
	);
	$holidays = array();
	while ($row = $smcFunc['db_fetch_assoc']($result))
	{
		if (substr($low_date, 0, 4) != substr($high_date, 0, 4))
			$event_year = substr($row['event_date'], 5) < substr($high_date, 5) ? substr($high_date, 0, 4) : substr($low_date, 0, 4);
		else
			$event_year = substr($low_date, 0, 4);

		$holidays[$event_year . substr($row['event_date'], 4)][] = $row['title'];
	}
	$smcFunc['db_free_result']($result);

	return $holidays;
}

/**
 * Does permission checks to see if an event can be linked to a board/topic.
 * checks if the current user can link the current topic to the calendar, permissions et al.
 * this requires the calendar_post permission, a forum moderator, or a topic starter.
 * expects the $topic and $board variables to be set.
 * if the user doesn't have proper permissions, an error will be shown.
 */
function canLinkEvent()
{
	global $user_info, $topic, $board, $smcFunc;

	// If you can't post, you can't link.
	isAllowedTo('calendar_post');

	// No board?  No topic?!?
	if (empty($board))
		fatal_lang_error('missing_board_id', false);
	if (empty($topic))
		fatal_lang_error('missing_topic_id', false);

	// Administrator, Moderator, or owner.  Period.
	if (!allowedTo('admin_forum') && !allowedTo('moderate_board'))
	{
		// Not admin or a moderator of this board. You better be the owner - or else.
		$result = $smcFunc['db_query']('', '
			SELECT id_member_started
			FROM {db_prefix}topics
			WHERE id_topic = {int:current_topic}
			LIMIT 1',
			array(
				'current_topic' => $topic,
			)
		);
		if ($row = $smcFunc['db_fetch_assoc']($result))
		{
			// Not the owner of the topic.
			if ($row['id_member_started'] != $user_info['id'])
				fatal_lang_error('not_your_topic', 'user');
		}
		// Topic/Board doesn't exist.....
		else
			fatal_lang_error('calendar_no_topic', 'general');
		$smcFunc['db_free_result']($result);
	}
}

/**
 * Returns date information about 'today' relative to the users time offset.
 * returns an array with the current date, day, month, and year.
 * takes the users time offset into account.
 * @return array An array of info about today, based on forum time. Has 'day', 'month', 'year' and 'date' (in YYYY-MM-DD format)
 */
function getTodayInfo()
{
	return array(
		'day' => (int) strftime('%d', forum_time()),
		'month' => (int) strftime('%m', forum_time()),
		'year' => (int) strftime('%Y', forum_time()),
		'date' => strftime('%Y-%m-%d', forum_time()),
	);
}

/**
 * Provides information (link, month, year) about the previous and next month.
 * @param int $month The month to display
 * @param int $year The year
 * @param array $calendarOptions An array of calendar options
 * @param bool $is_previous Whether this is the previous month
 * @return array A large array containing all the information needed to show a calendar grid for the given month
 */
function getCalendarGrid($month, $year, $calendarOptions, $is_previous = false)
{
	global $scripturl, $modSettings;

	// Eventually this is what we'll be returning.
	$calendarGrid = array(
		'week_days' => array(),
		'weeks' => array(),
		'short_day_titles' => !empty($calendarOptions['short_day_titles']),
		'short_month_titles' => !empty($calendarOptions['short_month_titles']),
		'highlight' => array(
			'events' => !empty($calendarOptions['highlight']['events']) && !empty($calendarOptions['show_events']) ? $calendarOptions['highlight']['events'] : 0,
			'holidays' => !empty($calendarOptions['highlight']['holidays']) && !empty($calendarOptions['show_holidays']) ? $calendarOptions['highlight']['holidays'] : 0,
			'birthdays' => !empty($calendarOptions['highlight']['birthdays']) && !empty($calendarOptions['show_birthdays']) ? $calendarOptions['highlight']['birthdays'] : 0,
		),
		'current_month' => $month,
		'current_year' => $year,
		'show_next_prev' => !empty($calendarOptions['show_next_prev']),
		'show_week_links' => isset($calendarOptions['show_week_links']) ? $calendarOptions['show_week_links'] : 0,
		'previous_calendar' => array(
			'year' => $month == 1 ? $year - 1 : $year,
			'month' => $month == 1 ? 12 : $month - 1,
			'disabled' => $modSettings['cal_minyear'] > ($month == 1 ? $year - 1 : $year),
		),
		'next_calendar' => array(
			'year' => $month == 12 ? $year + 1 : $year,
			'month' => $month == 12 ? 1 : $month + 1,
			'disabled' => $modSettings['cal_maxyear'] < ($month == 12 ? $year + 1 : $year),
		),
		'size' => empty($modSettings['cal_display_type']) ? 'large' : 'small',
	);

	// Get today's date.
	$today = getTodayInfo();

	// Get information about this month.
	$month_info = array(
		'first_day' => array(
			'day_of_week' => (int) strftime('%w', mktime(0, 0, 0, $month, 1, $year)),
			'week_num' => (int) strftime('%U', mktime(0, 0, 0, $month, 1, $year)),
			'date' => strftime('%Y-%m-%d', mktime(0, 0, 0, $month, 1, $year)),
		),
		'last_day' => array(
			'day_of_month' => (int) strftime('%d', mktime(0, 0, 0, $month == 12 ? 1 : $month + 1, 0, $month == 12 ? $year + 1 : $year)),
			'date' => strftime('%Y-%m-%d', mktime(0, 0, 0, $month == 12 ? 1 : $month + 1, 0, $month == 12 ? $year + 1 : $year)),
		),
		'first_day_of_year' => (int) strftime('%w', mktime(0, 0, 0, 1, 1, $year)),
		'first_day_of_next_year' => (int) strftime('%w', mktime(0, 0, 0, 1, 1, $year + 1)),
	);

	// The number of days the first row is shifted to the right for the starting day.
	$nShift = $month_info['first_day']['day_of_week'];

	$calendarOptions['start_day'] = empty($calendarOptions['start_day']) ? 0 : (int) $calendarOptions['start_day'];

	// Starting any day other than Sunday means a shift...
	if (!empty($calendarOptions['start_day']))
	{
		$nShift -= $calendarOptions['start_day'];
		if ($nShift < 0)
			$nShift = 7 + $nShift;
	}

	// Number of rows required to fit the month.
	$nRows = floor(($month_info['last_day']['day_of_month'] + $nShift) / 7);
	if (($month_info['last_day']['day_of_month'] + $nShift) % 7)
		$nRows++;

	// Fetch the arrays for birthdays, posted events, and holidays.
	$bday = $calendarOptions['show_birthdays'] ? getBirthdayRange($month_info['first_day']['date'], $month_info['last_day']['date']) : array();
	$events = $calendarOptions['show_events'] ? getEventRange($month_info['first_day']['date'], $month_info['last_day']['date']) : array();
	$holidays = $calendarOptions['show_holidays'] ? getHolidayRange($month_info['first_day']['date'], $month_info['last_day']['date']) : array();

	// Days of the week taking into consideration that they may want it to start on any day.
	$count = $calendarOptions['start_day'];
	for ($i = 0; $i < 7; $i++)
	{
		$calendarGrid['week_days'][] = $count;
		$count++;
		if ($count == 7)
			$count = 0;
	}

	// Iterate through each week.
	$calendarGrid['weeks'] = array();
	for ($nRow = 0; $nRow < $nRows; $nRow++)
	{
		// Start off the week - and don't let it go above 52, since that's the number of weeks in a year.
		$calendarGrid['weeks'][$nRow] = array(
			'days' => array(),
		);

		// And figure out all the days.
		for ($nCol = 0; $nCol < 7; $nCol++)
		{
			$nDay = ($nRow * 7) + $nCol - $nShift + 1;

			if ($nDay < 1 || $nDay > $month_info['last_day']['day_of_month'])
				$nDay = 0;

			$date = sprintf('%04d-%02d-%02d', $year, $month, $nDay);

			$calendarGrid['weeks'][$nRow]['days'][$nCol] = array(
				'day' => $nDay,
				'date' => $date,
				'is_today' => $date == $today['date'],
				'is_first_day' => !empty($calendarOptions['show_week_num']) && (($month_info['first_day']['day_of_week'] + $nDay - 1) % 7 == $calendarOptions['start_day']),
				'is_first_of_month' => $nDay === 1,
				'holidays' => !empty($holidays[$date]) ? $holidays[$date] : array(),
				'events' => !empty($events[$date]) ? $events[$date] : array(),
				'birthdays' => !empty($bday[$date]) ? $bday[$date] : array(),
			);
		}
	}

	// What is the last day of the month?
	if ($is_previous === true)
		$calendarGrid['last_of_month'] = $month_info['last_day']['day_of_month'];

	// We'll use the shift in the template.
	$calendarGrid['shift'] = $nShift;

	// Set the previous and the next month's links.
	$calendarGrid['previous_calendar']['href'] = $scripturl . '?action=calendar;year=' . $calendarGrid['previous_calendar']['year'] . ';month=' . $calendarGrid['previous_calendar']['month'];
	$calendarGrid['next_calendar']['href'] = $scripturl . '?action=calendar;year=' . $calendarGrid['next_calendar']['year'] . ';month=' . $calendarGrid['next_calendar']['month'];

	return $calendarGrid;
}

/**
 * Returns the information needed to show a calendar for the given week.
 * @param int $month The month
 * @param int $year The year
 * @param int $day The day
 * @param array $calendarOptions An array of calendar options
 * @return array An array of information needed to display the grid for a single week on the calendar
 */
function getCalendarWeek($month, $year, $day, $calendarOptions)
{
	global $scripturl, $modSettings, $txt;

	// Get today's date.
	$today = getTodayInfo();

	// What is the actual "start date" for the passed day.
	$calendarOptions['start_day'] = empty($calendarOptions['start_day']) ? 0 : (int) $calendarOptions['start_day'];
	$day_of_week = (int) strftime('%w', mktime(0, 0, 0, $month, $day, $year));
	if ($day_of_week != $calendarOptions['start_day'])
	{
		// Here we offset accordingly to get things to the real start of a week.
		$date_diff = $day_of_week - $calendarOptions['start_day'];
		if ($date_diff < 0)
			$date_diff += 7;
		$new_timestamp = mktime(0, 0, 0, $month, $day, $year) - $date_diff * 86400;
		$day = (int) strftime('%d', $new_timestamp);
		$month = (int) strftime('%m', $new_timestamp);
		$year = (int) strftime('%Y', $new_timestamp);
	}

	// Now start filling in the calendar grid.
	$calendarGrid = array(
		'show_next_prev' => !empty($calendarOptions['show_next_prev']),
		// Previous week is easy - just step back one day.
		'previous_week' => array(
			'year' => $day == 1 ? ($month == 1 ? $year - 1 : $year) : $year,
			'month' => $day == 1 ? ($month == 1 ? 12 : $month - 1) : $month,
			'day' => $day == 1 ? 28 : $day - 1,
			'disabled' => $day < 7 && $modSettings['cal_minyear'] > ($month == 1 ? $year - 1 : $year),
		),
		'next_week' => array(
			'disabled' => $day > 25 && $modSettings['cal_maxyear'] < ($month == 12 ? $year + 1 : $year),
		),
		'size' => empty($modSettings['cal_display_type']) ? 'large' : 'small',
	);

	// The next week calculation requires a bit more work.
	$curTimestamp = mktime(0, 0, 0, $month, $day, $year);
	$nextWeekTimestamp = $curTimestamp + 604800;
	$calendarGrid['next_week']['day'] = (int) strftime('%d', $nextWeekTimestamp);
	$calendarGrid['next_week']['month'] = (int) strftime('%m', $nextWeekTimestamp);
	$calendarGrid['next_week']['year'] = (int) strftime('%Y', $nextWeekTimestamp);

	// Fetch the arrays for birthdays, posted events, and holidays.
	$startDate = strftime('%Y-%m-%d', $curTimestamp);
	$endDate = strftime('%Y-%m-%d', $nextWeekTimestamp);
	$bday = $calendarOptions['show_birthdays'] ? getBirthdayRange($startDate, $endDate) : array();
	$events = $calendarOptions['show_events'] ? getEventRange($startDate, $endDate) : array();
	$holidays = $calendarOptions['show_holidays'] ? getHolidayRange($startDate, $endDate) : array();

	// An adjustment value to apply to all calculated week numbers.
	if (!empty($calendarOptions['show_week_num']))
	{
		$first_day_of_year = (int) strftime('%w', mktime(0, 0, 0, 1, 1, $year));
		$first_day_of_next_year = (int) strftime('%w', mktime(0, 0, 0, 1, 1, $year + 1));
		$last_day_of_last_year = (int) strftime('%w', mktime(0, 0, 0, 12, 31, $year - 1));

		$timestamp = mktime(0, 0, 0, $month, $day, $year);
		$calendarGrid['week_title'] = sprintf($txt['calendar_week_beginning'], date('F', $timestamp), date('j', $timestamp), date('Y', $timestamp));
	}

	// This holds all the main data - there is at least one month!
	$calendarGrid['months'] = array();
	$lastDay = 99;
	$curDay = $day;
	$curDayOfWeek = $calendarOptions['start_day'];
	for ($i = 0; $i < 7; $i++)
	{
		// Have we gone into a new month (Always happens first cycle too)
		if ($lastDay > $curDay)
		{
			$curMonth = $lastDay == 99 ? $month : ($month == 12 ? 1 : $month + 1);
			$curYear = $lastDay == 99 ? $year : ($curMonth == 1 && $month == 12 ? $year + 1 : $year);
			$calendarGrid['months'][$curMonth] = array(
				'current_month' => $curMonth,
				'current_year' => $curYear,
				'days' => array(),
			);
		}

		// Add todays information to the pile!
		$date = sprintf('%04d-%02d-%02d', $curYear, $curMonth, $curDay);

		$calendarGrid['months'][$curMonth]['days'][$curDay] = array(
			'day' => $curDay,
			'day_of_week' => $curDayOfWeek,
			'date' => $date,
			'is_today' => $date == $today['date'],
			'holidays' => !empty($holidays[$date]) ? $holidays[$date] : array(),
			'events' => !empty($events[$date]) ? $events[$date] : array(),
			'birthdays' => !empty($bday[$date]) ? $bday[$date] : array()
		);

		// Make the last day what the current day is and work out what the next day is.
		$lastDay = $curDay;
		$curTimestamp += 86400;
		$curDay = (int) strftime('%d', $curTimestamp);

		// Also increment the current day of the week.
		$curDayOfWeek = $curDayOfWeek >= 6 ? 0 : ++$curDayOfWeek;
	}

	// Set the previous and the next week's links.
	$calendarGrid['previous_week']['href'] = $scripturl . '?action=calendar;viewweek;year=' . $calendarGrid['previous_week']['year'] . ';month=' . $calendarGrid['previous_week']['month'] . ';day=' . $calendarGrid['previous_week']['day'];
	$calendarGrid['next_week']['href'] = $scripturl . '?action=calendar;viewweek;year=' . $calendarGrid['next_week']['year'] . ';month=' . $calendarGrid['next_week']['month'] . ';day=' . $calendarGrid['next_week']['day'];

	return $calendarGrid;
}

/**
 * Retrieve all events for the given days, independently of the users offset.
 * cache callback function used to retrieve the birthdays, holidays, and events between now and now + days_to_index.
 * widens the search range by an extra 24 hours to support time offset shifts.
 * used by the cache_getRecentEvents function to get the information needed to calculate the events taking the users time offset into account.
 *
 * @param int $days_to_index How many days' worth of info to index
 * @return array An array containing the data that was cached as well as an expression to calculate whether the data should be refreshed and when it expires
 */
function cache_getOffsetIndependentEvents($days_to_index)
{
	$low_date = strftime('%Y-%m-%d', forum_time(false) - 24 * 3600);
	$high_date = strftime('%Y-%m-%d', forum_time(false) + $days_to_index * 24 * 3600);

	return array(
		'data' => array(
			'holidays' => getHolidayRange($low_date, $high_date),
			'birthdays' => getBirthdayRange($low_date, $high_date),
			'events' => getEventRange($low_date, $high_date, false),
		),
		'refresh_eval' => 'return \'' . strftime('%Y%m%d', forum_time(false)) . '\' != strftime(\'%Y%m%d\', forum_time(false)) || (!empty($modSettings[\'calendar_updated\']) && ' . time() . ' < $modSettings[\'calendar_updated\']);',
		'expires' => time() + 3600,
	);
}

/**
 * cache callback function used to retrieve the upcoming birthdays, holidays, and events within the given period, taking into account the users time offset.
 * Called from the BoardIndex to display the current day's events on the board index
 * used by the board index and SSI to show the upcoming events.
 * @param array $eventOptions An array of event options. Only 'num_days_shown' is used here
 * @return array An array containing the info that was cached as well as a few other relevant things
 */
function cache_getRecentEvents($eventOptions)
{
	// With the 'static' cached data we can calculate the user-specific data.
	$cached_data = cache_quick_get('calendar_index', 'Subs-Calendar.php', 'cache_getOffsetIndependentEvents', array($eventOptions['num_days_shown']));

	// Get the information about today (from user perspective).
	$today = getTodayInfo();

	$return_data = array(
		'calendar_holidays' => array(),
		'calendar_birthdays' => array(),
		'calendar_events' => array(),
	);

	// Set the event span to be shown in seconds.
	$days_for_index = $eventOptions['num_days_shown'] * 86400;

	// Get the current member time/date.
	$now = forum_time();

	// Holidays between now and now + days.
	for ($i = $now; $i < $now + $days_for_index; $i += 86400)
	{
		if (isset($cached_data['holidays'][strftime('%Y-%m-%d', $i)]))
			$return_data['calendar_holidays'] = array_merge($return_data['calendar_holidays'], $cached_data['holidays'][strftime('%Y-%m-%d', $i)]);
	}

	// Happy Birthday, guys and gals!
	for ($i = $now; $i < $now + $days_for_index; $i += 86400)
	{
		$loop_date = strftime('%Y-%m-%d', $i);
		if (isset($cached_data['birthdays'][$loop_date]))
		{
			foreach ($cached_data['birthdays'][$loop_date] as $index => $dummy)
				$cached_data['birthdays'][strftime('%Y-%m-%d', $i)][$index]['is_today'] = $loop_date === $today['date'];
			$return_data['calendar_birthdays'] = array_merge($return_data['calendar_birthdays'], $cached_data['birthdays'][$loop_date]);
		}
	}

	$duplicates = array();
	for ($i = $now; $i < $now + $days_for_index; $i += 86400)
	{
		// Determine the date of the current loop step.
		$loop_date = strftime('%Y-%m-%d', $i);

		// No events today? Check the next day.
		if (empty($cached_data['events'][$loop_date]))
			continue;

		// Loop through all events to add a few last-minute values.
		foreach ($cached_data['events'][$loop_date] as $ev => $event)
		{
			// Create a shortcut variable for easier access.
			$this_event = &$cached_data['events'][$loop_date][$ev];

			// Skip duplicates.
			if (isset($duplicates[$this_event['topic'] . $this_event['title']]))
			{
				unset($cached_data['events'][$loop_date][$ev]);
				continue;
			}
			else
				$duplicates[$this_event['topic'] . $this_event['title']] = true;

			// Might be set to true afterwards, depending on the permissions.
			$this_event['can_edit'] = false;
			$this_event['is_today'] = $loop_date === $today['date'];
			$this_event['date'] = $loop_date;
		}

		if (!empty($cached_data['events'][$loop_date]))
			$return_data['calendar_events'] = array_merge($return_data['calendar_events'], $cached_data['events'][$loop_date]);
	}

	// Mark the last item so that a list separator can be used in the template.
	for ($i = 0, $n = count($return_data['calendar_birthdays']); $i < $n; $i++)
		$return_data['calendar_birthdays'][$i]['is_last'] = !isset($return_data['calendar_birthdays'][$i + 1]);
	for ($i = 0, $n = count($return_data['calendar_events']); $i < $n; $i++)
		$return_data['calendar_events'][$i]['is_last'] = !isset($return_data['calendar_events'][$i + 1]);

	return array(
		'data' => $return_data,
		'expires' => time() + 3600,
		'refresh_eval' => 'return \'' . strftime('%Y%m%d', forum_time(false)) . '\' != strftime(\'%Y%m%d\', forum_time(false)) || (!empty($modSettings[\'calendar_updated\']) && ' . time() . ' < $modSettings[\'calendar_updated\']);',
		'post_retri_eval' => '
			global $context, $scripturl, $user_info;

			foreach ($cache_block[\'data\'][\'calendar_events\'] as $k => $event)
			{
				// Remove events that the user may not see or wants to ignore.
				if ((count(array_intersect($user_info[\'groups\'], $event[\'allowed_groups\'])) === 0 && !allowedTo(\'admin_forum\') && !empty($event[\'id_board\'])) || in_array($event[\'id_board\'], $user_info[\'ignoreboards\']))
					unset($cache_block[\'data\'][\'calendar_events\'][$k]);
				else
				{
					// Whether the event can be edited depends on the permissions.
					$cache_block[\'data\'][\'calendar_events\'][$k][\'can_edit\'] = allowedTo(\'calendar_edit_any\') || ($event[\'poster\'] == $user_info[\'id\'] && allowedTo(\'calendar_edit_own\'));

					// The added session code makes this URL not cachable.
					$cache_block[\'data\'][\'calendar_events\'][$k][\'modify_href\'] = $scripturl . \'?action=\' . ($event[\'topic\'] == 0 ? \'calendar;sa=post;\' : \'post;msg=\' . $event[\'msg\'] . \';topic=\' . $event[\'topic\'] . \'.0;calendar;\') . \'eventid=\' . $event[\'id\'] . \';\' . $context[\'session_var\'] . \'=\' . $context[\'session_id\'];
				}
			}

			if (empty($params[0][\'include_holidays\']))
				$cache_block[\'data\'][\'calendar_holidays\'] = array();
			if (empty($params[0][\'include_birthdays\']))
				$cache_block[\'data\'][\'calendar_birthdays\'] = array();
			if (empty($params[0][\'include_events\']))
				$cache_block[\'data\'][\'calendar_events\'] = array();

			$cache_block[\'data\'][\'show_calendar\'] = !empty($cache_block[\'data\'][\'calendar_holidays\']) || !empty($cache_block[\'data\'][\'calendar_birthdays\']) || !empty($cache_block[\'data\'][\'calendar_events\']);',
	);
}

/**
 * Makes sure the calendar post is valid.
 */
function validateEventPost()
{
	global $modSettings, $smcFunc;

	if (!isset($_POST['deleteevent']))
	{
		// No month?  No year?
		if (!isset($_POST['month']))
			fatal_lang_error('event_month_missing', false);
		if (!isset($_POST['year']))
			fatal_lang_error('event_year_missing', false);

		// Check the month and year...
		if ($_POST['month'] < 1 || $_POST['month'] > 12)
			fatal_lang_error('invalid_month', false);
		if ($_POST['year'] < $modSettings['cal_minyear'] || $_POST['year'] > $modSettings['cal_maxyear'])
			fatal_lang_error('invalid_year', false);
	}

	// Make sure they're allowed to post...
	isAllowedTo('calendar_post');

	if (isset($_POST['span']))
	{
		// Make sure it's turned on and not some fool trying to trick it.
		if (empty($modSettings['cal_allowspan']))
			fatal_lang_error('no_span', false);
		if ($_POST['span'] < 1 || $_POST['span'] > $modSettings['cal_maxspan'])
			fatal_lang_error('invalid_days_numb', false);
	}

	// There is no need to validate the following values if we are just deleting the event.
	if (!isset($_POST['deleteevent']))
	{
		// No day?
		if (!isset($_POST['day']))
			fatal_lang_error('event_day_missing', false);
		if (!isset($_POST['evtitle']) && !isset($_POST['subject']))
			fatal_lang_error('event_title_missing', false);
		elseif (!isset($_POST['evtitle']))
			$_POST['evtitle'] = $_POST['subject'];

		// Bad day?
		if (!checkdate($_POST['month'], $_POST['day'], $_POST['year']))
			fatal_lang_error('invalid_date', false);

		// No title?
		if ($smcFunc['htmltrim']($_POST['evtitle']) === '')
			fatal_lang_error('no_event_title', false);
		if ($smcFunc['strlen']($_POST['evtitle']) > 100)
			$_POST['evtitle'] = $smcFunc['substr']($_POST['evtitle'], 0, 100);
		$_POST['evtitle'] = str_replace(';', '', $_POST['evtitle']);
	}
}

/**
 * Get the event's poster.
 *
 * @param int $event_id The ID of the event
 * @return int|bool The ID of the poster or false if the event was not found
 */
function getEventPoster($event_id)
{
	global $smcFunc;

	// A simple database query, how hard can that be?
	$request = $smcFunc['db_query']('', '
		SELECT id_member
		FROM {db_prefix}calendar
		WHERE id_event = {int:id_event}
		LIMIT 1',
		array(
			'id_event' => $event_id,
		)
	);

	// No results, return false.
	if ($smcFunc['db_num_rows'] === 0)
		return false;

	// Grab the results and return.
	list ($poster) = $smcFunc['db_fetch_row']($request);
	$smcFunc['db_free_result']($request);
	return (int) $poster;
}

/**
 * Consolidating the various INSERT statements into this function.
 * inserts the passed event information into the calendar table.
 * allows to either set a time span (in days) or an end_date.
 * does not check any permissions of any sort.
 *
 * @param array $eventOptions An array of event options ('title', 'span', 'start_date', 'end_date', etc.)
 */
function insertEvent(&$eventOptions)
{
	global $smcFunc, $context;

	// Add special chars to the title.
	$eventOptions['title'] = $smcFunc['htmlspecialchars']($eventOptions['title'], ENT_QUOTES);

	// Add some sanity checking to the span.
	$eventOptions['span'] = isset($eventOptions['span']) && $eventOptions['span'] > 0 ? (int) $eventOptions['span'] : 0;

	// Make sure the start date is in ISO order.
	// @todo $year, $month, and $day are not set
	if (($num_results = sscanf($eventOptions['start_date'], '%d-%d-%d', $year, $month, $day)) !== 3)
		trigger_error('modifyEvent(): invalid start date format given', E_USER_ERROR);

	// Set the end date (if not yet given)
	// @todo $year, $month, and $day are not set
	if (!isset($eventOptions['end_date']))
		$eventOptions['end_date'] = strftime('%Y-%m-%d', mktime(0, 0, 0, $month, $day, $year) + $eventOptions['span'] * 86400);

	// If no topic and board are given, they are not linked to a topic.
	$eventOptions['board'] = isset($eventOptions['board']) ? (int) $eventOptions['board'] : 0;
	$eventOptions['topic'] = isset($eventOptions['topic']) ? (int) $eventOptions['topic'] : 0;

	$event_columns = array(
		'id_board' => 'int', 'id_topic' => 'int', 'title' => 'string-60', 'id_member' => 'int',
		'start_date' => 'date', 'end_date' => 'date',
	);
	$event_parameters = array(
		$eventOptions['board'], $eventOptions['topic'], $eventOptions['title'], $eventOptions['member'],
		$eventOptions['start_date'], $eventOptions['end_date'],
	);

	call_integration_hook('integrate_create_event', array(&$eventOptions, &$event_columns, &$event_parameters));

	// Insert the event!
	$smcFunc['db_insert']('',
		'{db_prefix}calendar',
		$event_columns,
		$event_parameters,
		array('id_event')
	);

	// Store the just inserted id_event for future reference.
	$eventOptions['id'] = $smcFunc['db_insert_id']('{db_prefix}calendar', 'id_event');

	// If this isn't tied to a topic, we need to notify people about it.
	if (empty($eventOptions['topic']))
	{
		$smcFunc['db_insert']('insert',
			'{db_prefix}background_tasks',
			array('task_file' => 'string', 'task_class' => 'string', 'task_data' => 'string', 'claimed_time' => 'int'),
			array('$sourcedir/tasks/EventNew-Notify.php', 'EventNew_Notify_Background', serialize(array(
				'event_title' => $eventOptions['title'],
				'event_id' => $eventOptions['id'],
				'sender_id' => $eventOptions['member'],
				'sender_name' => $eventOptions['member'] == $context['user']['id'] ? $context['user']['name'] : '',
				'time' => time(),
			)), 0),
			array('id_task')
		);
	}

	// Update the settings to show something calendar-ish was updated.
	updateSettings(array(
		'calendar_updated' => time(),
	));
}

/**
 * modifies an event.
 * allows to either set a time span (in days) or an end_date.
 * does not check any permissions of any sort.
 *
 * @param int $event_id The ID of the event
 * @param array $eventOptions An array of event information
 */
function modifyEvent($event_id, &$eventOptions)
{
	global $smcFunc;

	// Properly sanitize the title.
	$eventOptions['title'] = $smcFunc['htmlspecialchars']($eventOptions['title'], ENT_QUOTES);

	// Scan the start date for validity and get its components.
	if (($num_results = sscanf($eventOptions['start_date'], '%d-%d-%d', $year, $month, $day)) !== 3)
		trigger_error('modifyEvent(): invalid start date format given', E_USER_ERROR);

	// Default span to 0 days.
	$eventOptions['span'] = isset($eventOptions['span']) ? (int) $eventOptions['span'] : 0;

	// Set the end date to the start date + span (if the end date wasn't already given).
	if (!isset($eventOptions['end_date']))
		$eventOptions['end_date'] = strftime('%Y-%m-%d', mktime(0, 0, 0, $month, $day, $year) + $eventOptions['span'] * 86400);

	$event_columns = array(
		'start_date' => '{date:start_date}',
		'end_date' => '{date:end_date}',
		'title' => 'SUBSTRING({string:title}, 1, 60)',
		'id_board' => '{int:id_board}',
		'id_topic' => '{int:id_topic}'
	);
	$event_parameters = array(
		'start_date' => $eventOptions['start_date'],
		'end_date' => $eventOptions['end_date'],
		'title' => $eventOptions['title'],
		'id_board' => isset($eventOptions['board']) ? (int) $eventOptions['board'] : 0,
		'id_topic' => isset($eventOptions['topic']) ? (int) $eventOptions['topic'] : 0,
	);

	// This is to prevent hooks to modify the id of the event
	$real_event_id = $event_id;
	call_integration_hook('integrate_modify_event', array($event_id, &$eventOptions, &$event_columns, &$event_parameters));

	$column_clauses = array();
	foreach ($event_columns as $col => $crit)
		$column_clauses[] = $col . ' = ' . $crit;

	$smcFunc['db_query']('', '
		UPDATE {db_prefix}calendar
		SET
			' . implode(', ', $column_clauses) . '
		WHERE id_event = {int:id_event}',
		array_merge(
			$event_parameters,
			array(
				'id_event' => $real_event_id
			)
		)
	);

	updateSettings(array(
		'calendar_updated' => time(),
	));
}

/**
 * Remove an event
 * removes an event.
 * does no permission checks.
 *
 * @param int $event_id The ID of the event to remove
 */
function removeEvent($event_id)
{
	global $smcFunc;

	$smcFunc['db_query']('', '
		DELETE FROM {db_prefix}calendar
		WHERE id_event = {int:id_event}',
		array(
			'id_event' => $event_id,
		)
	);

	call_integration_hook('integrate_remove_event', array($event_id));

	updateSettings(array(
		'calendar_updated' => time(),
	));
}

/**
 * Gets all the events properties
 *
 * @param int $event_id The ID of the event
 * @return array An array of event information
 */
function getEventProperties($event_id)
{
	global $smcFunc;

	$request = $smcFunc['db_query']('', '
		SELECT
			c.id_event, c.id_board, c.id_topic, MONTH(c.start_date) AS month,
			DAYOFMONTH(c.start_date) AS day, YEAR(c.start_date) AS year,
			(TO_DAYS(c.end_date) - TO_DAYS(c.start_date)) AS span, c.id_member, c.title,
			t.id_first_msg, t.id_member_started,
			mb.real_name, m.modified_time
		FROM {db_prefix}calendar AS c
			LEFT JOIN {db_prefix}topics AS t ON (t.id_topic = c.id_topic)
			LEFT JOIN {db_prefix}members AS mb ON (mb.id_member = t.id_member_started)
			LEFT JOIN {db_prefix}messages AS m ON (m.id_msg  = t.id_first_msg)
		WHERE c.id_event = {int:id_event}',
		array(
			'id_event' => $event_id,
		)
	);

	// If nothing returned, we are in poo, poo.
	if ($smcFunc['db_num_rows']($request) === 0)
		return false;

	$row = $smcFunc['db_fetch_assoc']($request);
	$smcFunc['db_free_result']($request);

	$return_value = array(
		'boards' => array(),
		'board' => $row['id_board'],
		'new' => 0,
		'eventid' => $event_id,
		'year' => $row['year'],
		'month' => $row['month'],
		'day' => $row['day'],
		'title' => $row['title'],
		'span' => 1 + $row['span'],
		'member' => $row['id_member'],
		'realname' => $row['real_name'],
		'sequence' => $row['modified_time'],
		'topic' => array(
			'id' => $row['id_topic'],
			'member_started' => $row['id_member_started'],
			'first_msg' => $row['id_first_msg'],
		),
	);

	$return_value['last_day'] = (int) strftime('%d', mktime(0, 0, 0, $return_value['month'] == 12 ? 1 : $return_value['month'] + 1, 0, $return_value['month'] == 12 ? $return_value['year'] + 1 : $return_value['year']));

	return $return_value;
}

/**
 * Gets all of the holidays for the listing
 *
 * @param int $start The item to start with (for pagination purposes)
 * @param int $items_per_page How many items to show on each page
 * @param string $sort A string indicating how to sort the results
 * @return array An array of holidays, each of which is an array containing the id, year, month, day and title of the holiday
 */
function list_getHolidays($start, $items_per_page, $sort)
{
	global $smcFunc;

	$request = $smcFunc['db_query']('', '
		SELECT id_holiday, YEAR(event_date) AS year, MONTH(event_date) AS month, DAYOFMONTH(event_date) AS day, title
		FROM {db_prefix}calendar_holidays
		ORDER BY {raw:sort}
		LIMIT ' . $start . ', ' . $items_per_page,
		array(
			'sort' => $sort,
		)
	);
	$holidays = array();
	while ($row = $smcFunc['db_fetch_assoc']($request))
		$holidays[] = $row;
	$smcFunc['db_free_result']($request);

	return $holidays;
}

/**
 * Helper function to get the total number of holidays
 *
 * @return int The total number of holidays
 */
function list_getNumHolidays()
{
	global $smcFunc;

	$request = $smcFunc['db_query']('', '
		SELECT COUNT(*)
		FROM {db_prefix}calendar_holidays',
		array(
		)
	);
	list($num_items) = $smcFunc['db_fetch_row']($request);
	$smcFunc['db_free_result']($request);

	return (int) $num_items;
}

/**
 * Remove a holiday from the calendar
 *
 * @param array $holiday_ids An array of IDs of holidays to delete
 */
function removeHolidays($holiday_ids)
{
	global $smcFunc;

	$smcFunc['db_query']('', '
		DELETE FROM {db_prefix}calendar_holidays
		WHERE id_holiday IN ({array_int:id_holiday})',
		array(
			'id_holiday' => $holiday_ids,
		)
	);

	updateSettings(array(
		'calendar_updated' => time(),
	));
}

?>


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Class: AI::CSP::Problem</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <link rel="stylesheet" href="../../.././rdoc-style.css" type="text/css" media="screen" />

          Class
          AI::CSP::Problem

            In:

                ai/csp/problem.rb

            Parent:

                Object

Problem

For modeling CSP problems in terms of variables
(which have domains) and constraints over those variables.

See AI::CSP::Variable and AI::CSP::Constraint. Also, see AI::CSP for an overview and examples.

Methods

      add_constraint
      each_constraint
      each_uninstantiated_variable
      new
      to_s

Attributes

          constraints
           [R]

          variables
           [R]

Public Class methods

          new(variables)

Public Instance methods

          add_constraint(*variables, &block)

one of:

  add_constraint(constraint)
  add_constraint(v1, v2, ...) {|a,b,..| ...}
  add_constraint(vname1, vname2. ...) {|a,b,...| ...}

          each_constraint(variable=nil, &block)

Calls block with each constraint in the problem. If a variable is
specified, restricts this to constraints involving that variable.

          each_uninstantiated_variable() {|variable unless variable.instantiated?| ...}

Calls provided block with each variable in the problem that is currently
uninstantiated.

          to_s()

[Validate]

redpajama_set_name: RedPajamaGithub


text:
module Auth::Controllers::Sessions
  class Failure
    include Auth::Action

    def call(params)
      redirect_to '/'
    end
  end
end


text:
require "securerandom"

module AccessTokens
  class Create < Mutations::Command

    VALID_INTERNAL_SCOPES = ['user', 'owner']

    required do
      model :user
    end

    optional do
      array :scopes, class: String
      string :scope
      integer :expires_in, nils: true, empty_is_nil: true
      boolean :refreshable, default: true
      boolean :with_code, default: false
      model :current_access_token
      string :token
      string :refresh_token
      string :description, nils: true, empty_is_nil: true
    end

    def validate
      # Accept standard comma separated scope or array
      scopes = self.scope.to_s.gsub(/\s+/, '').split(',')
      if self.scopes.nil? || self.scopes.empty?
        self.scopes = scopes
      end

      if !self.token && self.scopes.any?{|scope| !VALID_INTERNAL_SCOPES.include?(scope)}
        add_error(:scope, :invalid, 'Invalid scope')
      end

      # Scope is always required
      if self.scopes.empty?
        add_error(:scope, :empty, 'Missing scope')
      end

      # Do not allow creating higher privilege tokens
      if self.current_access_token
        if self.scopes.include?('user') && !self.current_access_token.scopes.include?('user')
          add_error(:scope, :invalid, 'Invalid scope')
        end

        if self.scopes.include?('owner') && !self.current_access_token.scopes.include?('owner')
          add_error(:scope, :invalid, 'Invalid scope')
        end

        # TODO: Add other level checks
      end
    end

    def execute
      expires_at = self.expires_in.to_i > 0 ? Time.now.utc + self.expires_in : nil
      attrs = {
        user: self.user,
        scopes: self.scopes,
        expires_at: expires_at,
        with_code: self.with_code,
        description: self.description
      }

      if self.token
        attrs[:internal] = false
        attrs[:token] = self.token
        attrs[:refresh_token] = self.refresh_token
      end

      AccessToken.create!(attrs)
    end
  end
end


text:
var loadState = {
    preload: function () {
        var loadLabel = game.add.text(game.world.centerX, game.world.centerY, "Loading...", {
            font: "35px Impact",
            fill: "#ffffff"
        });
        loadLabel.anchor.setTo(0.5, 0.5);

        var progressBar = game.add.sprite(game.world.centerX, game.world.centerY + 50, 'progressBar');
        progressBar.anchor.setTo(0.5, 0.5);
        game.load.setPreloadSprite(progressBar);

        var spritebgText = "Sprite and Background assets from opengameart.com [bevouliin.com].\n";
        this.spritebgAssets = game.add.text(game.world.centerX, game.world.centerY + 150, spritebgText, {
            font: "16px 'Comic Sans MS'",
            fill: "#ffffff"
        });
        this.spritebgAssets.anchor.setTo(0.5, 0.5);

        var soundcredText = "Sound assets from freesound.org.\n";
        this.soundAssets = game.add.text(game.world.centerX, game.world.centerY + 180, soundcredText, {
            font: "16px 'Comic Sans MS'",
            fill: "#ffffff"
        });
        this.soundAssets.anchor.setTo(0.5, 0.5);

        game.load.image('chutiyalogo', 'http://fatpixels.me/games/ChutiyaChidiya/assets/chutiyalogo.png');
        game.load.spritesheet('chutiya', 'http://fatpixels.me/games/ChutiyaChidiya/assets/chutiyasheet.png', 118, 84);
        game.load.image('pipe', 'http://fatpixels.me/games/ChutiyaChidiya/assets/pipe.png');
        game.load.image('star', 'http://fatpixels.me/games/ChutiyaChidiya/assets/star.png');
        game.load.image('chutiyabg', 'http://fatpixels.me/games/ChutiyaChidiya/assets/chutiyabg.png');
        game.load.spritesheet('muteButtons', 'http://fatpixels.me/games/ChutiyaChidiya/assets/mutesheet.png', 64, 64);
        game.load.audio('chutiyajump', 'http://fatpixels.me/games/ChutiyaChidiya/assets/sounds/breathing_jumping.wav');
        game.load.audio('chutiyamelody', 'http://fatpixels.me/games/ChutiyaChidiya/assets/sounds/singing_melody.wav');
        game.load.audio('chutiyadead', 'http://fatpixels.me/games/ChutiyaChidiya/assets/sounds/death_blood_splatter.mp3');
        game.load.audio('chutiyahorn', 'http://fatpixels.me/games/ChutiyaChidiya/assets/sounds/bike_horn.wav');
    },

    create: function () {
        this.chutiyaMelody = game.add.audio('chutiyamelody', 0.3, true);
        this.chutiyaMelody.play();
        game.time.events.add(1000, this.nextState, this);
    },

    nextState: function () {
        game.state.start('menu');
    }

};


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.

#include <cstdint>
#include <functional>
#include <memory>
#include <vector>

#include <gtest/gtest.h>

#include "arrow/testing/gtest_common.h"
#include "arrow/testing/gtest_util.h"

#include "arrow/compute/context.h"
#include "arrow/compute/kernel.h"
#include "arrow/compute/kernels/boolean.h"
#include "arrow/compute/kernels/util-internal.h"
#include "arrow/compute/test-util.h"

using std::shared_ptr;
using std::vector;

namespace arrow {
namespace compute {

using BinaryKernelFunc =
    std::function<Status(FunctionContext*, const Datum&, const Datum&, Datum* out)>;

class TestBooleanKernel : public ComputeFixture, public TestBase {
 public:
  void TestArrayBinary(const BinaryKernelFunc& kernel, const std::shared_ptr<Array>& left,
                       const std::shared_ptr<Array>& right,
                       const std::shared_ptr<Array>& expected) {
    Datum result;
    ASSERT_OK(kernel(&this->ctx_, left, right, &result));
    ASSERT_EQ(Datum::ARRAY, result.kind());
    std::shared_ptr<Array> result_array = result.make_array();
    ASSERT_ARRAYS_EQUAL(*expected, *result_array);
  }

  void TestChunkedArrayBinary(const BinaryKernelFunc& kernel,
                              const std::shared_ptr<ChunkedArray>& left,
                              const std::shared_ptr<ChunkedArray>& right,
                              const std::shared_ptr<ChunkedArray>& expected) {
    Datum result;
    std::shared_ptr<Array> result_array;
    ASSERT_OK(kernel(&this->ctx_, left, right, &result));
    ASSERT_EQ(Datum::CHUNKED_ARRAY, result.kind());
    std::shared_ptr<ChunkedArray> result_ca = result.chunked_array();
    ASSERT_TRUE(result_ca->Equals(expected));
  }

  void TestBinaryKernel(const BinaryKernelFunc& kernel, const std::vector<bool>& values1,
                        const std::vector<bool>& values2,
                        const std::vector<bool>& values3,
                        const std::vector<bool>& values3_nulls) {
    auto type = boolean();
    auto a1 = _MakeArray<BooleanType, bool>(type, values1, {});
    auto a2 = _MakeArray<BooleanType, bool>(type, values2, {});
    auto a3 = _MakeArray<BooleanType, bool>(type, values3, {});
    auto a1_nulls = _MakeArray<BooleanType, bool>(type, values1, values1);
    auto a2_nulls = _MakeArray<BooleanType, bool>(type, values2, values2);
    auto a3_nulls = _MakeArray<BooleanType, bool>(type, values3, values3_nulls);

    TestArrayBinary(kernel, a1, a2, a3);
    TestArrayBinary(kernel, a1_nulls, a2_nulls, a3_nulls);
    TestArrayBinary(kernel, a1->Slice(1), a2->Slice(1), a3->Slice(1));
    TestArrayBinary(kernel, a1_nulls->Slice(1), a2_nulls->Slice(1), a3_nulls->Slice(1));

    // ChunkedArray
    std::vector<std::shared_ptr<Array>> ca1_arrs = {a1, a1->Slice(1)};
    auto ca1 = std::make_shared<ChunkedArray>(ca1_arrs);
    std::vector<std::shared_ptr<Array>> ca2_arrs = {a2, a2->Slice(1)};
    auto ca2 = std::make_shared<ChunkedArray>(ca2_arrs);
    std::vector<std::shared_ptr<Array>> ca3_arrs = {a3, a3->Slice(1)};
    auto ca3 = std::make_shared<ChunkedArray>(ca3_arrs);
    TestChunkedArrayBinary(kernel, ca1, ca2, ca3);

    // ChunkedArray with different chunks
    std::vector<std::shared_ptr<Array>> ca4_arrs = {a1->Slice(0, 1), a1->Slice(1),
                                                    a1->Slice(1, 1), a1->Slice(2)};
    auto ca4 = std::make_shared<ChunkedArray>(ca4_arrs);
    TestChunkedArrayBinary(kernel, ca4, ca2, ca3);
  }
};

TEST_F(TestBooleanKernel, Invert) {
  vector<bool> values1 = {true, false, true, false};
  vector<bool> values2 = {false, true, false, true};

  auto type = boolean();
  auto a1 = _MakeArray<BooleanType, bool>(type, values1, {true, true, true, false});
  auto a2 = _MakeArray<BooleanType, bool>(type, values2, {true, true, true, false});

  // Plain array
  Datum result;
  ASSERT_OK(Invert(&this->ctx_, a1, &result));
  ASSERT_EQ(Datum::ARRAY, result.kind());
  ASSERT_ARRAYS_EQUAL(*a2, *result.make_array());

  // Array with offset
  ASSERT_OK(Invert(&this->ctx_, a1->Slice(1), &result));
  ASSERT_EQ(Datum::ARRAY, result.kind());
  ASSERT_ARRAYS_EQUAL(*a2->Slice(1), *result.make_array());

  // ChunkedArray
  std::vector<std::shared_ptr<Array>> ca1_arrs = {a1, a1->Slice(1)};
  auto ca1 = std::make_shared<ChunkedArray>(ca1_arrs);
  std::vector<std::shared_ptr<Array>> ca2_arrs = {a2, a2->Slice(1)};
  auto ca2 = std::make_shared<ChunkedArray>(ca2_arrs);
  ASSERT_OK(Invert(&this->ctx_, ca1, &result));
  ASSERT_EQ(Datum::CHUNKED_ARRAY, result.kind());
  std::shared_ptr<ChunkedArray> result_ca = result.chunked_array();
  ASSERT_ARRAYS_EQUAL(*ca2, *result_ca);
}

TEST_F(TestBooleanKernel, InvertEmptyArray) {
  auto type = boolean();
  std::vector<std::shared_ptr<Buffer>> data_buffers(2);
  Datum input;
  input.value = ArrayData::Make(boolean(), 0 /* length */, std::move(data_buffers),
                                0 /* null_count */);

  Datum result;
  ASSERT_OK(Invert(&this->ctx_, input, &result));
  ASSERT_ARRAYS_EQUAL(*input.make_array(), *result.make_array());
}

TEST_F(TestBooleanKernel, BinaryOpOnEmptyArray) {
  auto type = boolean();
  std::vector<std::shared_ptr<Buffer>> data_buffers(2);
  Datum input;
  input.value = ArrayData::Make(boolean(), 0 /* length */, std::move(data_buffers),
                                0 /* null_count */);

  Datum result;
  ASSERT_OK(And(&this->ctx_, input, input, &result));
  // Result should be empty as well.
  ASSERT_ARRAYS_EQUAL(*input.make_array(), *result.make_array());
}

TEST_F(TestBooleanKernel, And) {
  vector<bool> values1 = {true, false, true, false, true, true};
  vector<bool> values2 = {true, true, false, false, true, false};
  vector<bool> values3 = {true, false, false, false, true, false};
  TestBinaryKernel(And, values1, values2, values3, values3);
}

TEST_F(TestBooleanKernel, Or) {
  vector<bool> values1 = {true, false, true, false, true, true};
  vector<bool> values2 = {true, true, false, false, true, false};
  vector<bool> values3 = {true, true, true, false, true, true};
  vector<bool> values3_nulls = {true, false, false, false, true, false};
  TestBinaryKernel(Or, values1, values2, values3, values3_nulls);
}

TEST_F(TestBooleanKernel, Xor) {
  vector<bool> values1 = {true, false, true, false, true, true};
  vector<bool> values2 = {true, true, false, false, true, false};
  vector<bool> values3 = {false, true, true, false, false, true};
  vector<bool> values3_nulls = {true, false, false, false, true, false};
  TestBinaryKernel(Xor, values1, values2, values3, values3_nulls);
}

}  // namespace compute
}  // namespace arrow


text:
$: << File.dirname(__FILE__)
require 'test_helper'

class GeoIPISPTest < Minitest::Test
  ISP = {
    :isp => "AT&T Services"
  }

  ISP_IP = '12.87.118.0'

  def assert_look_up(db, expected = ISP, lookup = ISP_IP)
    hash = db.look_up(lookup)
    assert_kind_of(Hash, hash)
    assert_equal(expected, hash)
  end

  def test_construction_default
    db = GeoIP::ISP.new(ISP_DB)
    assert_raises_type_error(db)
    assert_look_up(db)
  end

  # def test_construction_index
  #   db = GeoIP::ISP.new(ISP_DB, :index)
  #   assert_look_up(db, ISP_IP, :isp, 'Bell Aliant')
  # end

  def test_construction_filesystem
    db = GeoIP::ISP.new(ISP_DB, :filesystem)
    assert_raises_type_error(db)
    assert_look_up(db)
  end

  def test_construction_memory
    db = GeoIP::ISP.new(ISP_DB, :memory)
    assert_raises_type_error(db)
    assert_look_up(db)
  end

  def test_construction_filesystem_check
    db = GeoIP::ISP.new(ISP_DB, :filesystem, true)
    assert_raises_type_error(db)
    assert_look_up(db)
  end

  def test_bad_db_file
    assert_raises Errno::ENOENT do
      GeoIP::ISP.new('/supposed-to-fail')
    end
  end
end


text:
package org.apache.cassandra.io.util;

import java.io.IOException;
import java.nio.ByteBuffer;

import org.apache.cassandra.utils.ByteBufferUtil;

/**
 * An implementation of the DataOutputStream interface using a FastByteArrayOutputStream and exposing
 * its buffer so copies can be avoided.
 *
 * This class is completely thread unsafe.
 */
public final class DataOutputByteBuffer extends AbstractDataOutput
{

    final ByteBuffer buffer;
    public DataOutputByteBuffer(ByteBuffer buffer)
    {
        this.buffer = buffer;
    }

    @Override
    public void write(int b)
    {
        buffer.put((byte) b);
    }

    @Override
    public void write(byte[] b, int off, int len)
    {
        buffer.put(b, off, len);
    }

    public void write(ByteBuffer buffer) throws IOException
    {
        int len = buffer.remaining();
        ByteBufferUtil.arrayCopy(buffer, buffer.position(), this.buffer, this.buffer.position(), len);
        this.buffer.position(this.buffer.position() + len);
    }
}


text:
title: Plugin Development - Accessing the datastore
book: plugin_dev
chapter: 5
---

## Introduction

Kong interacts with the model layer through classes we refer to as "DAOs". This chapter will detail the available API to interact with the datastore.

As of `0.8.0`, Kong supports two primary datastores: [Cassandra {{site.data.kong_latest.dependencies.cassandra}}](http://cassandra.apache.org/) and [PostgreSQL {{site.data.kong_latest.dependencies.postgres}}](http://www.postgresql.org/).

---

## The DAO Factory

All entities in Kong are represented by:

- A schema that describes which table the entity relates to in the datastore, constraints on its fields such as foreign keys, non-null constraints etc... This schema is a table described in the [plugin configuration]({{page.book.chapters.plugin-configuration}}) chapter.
- An instance of the `DAO` class mapping to the database currently in use (Cassandra or PostgreSQL). This class' methods consume the schema and expose methods to insert, update, find and delete entities of that type.

The core entities in Kong are: Apis, Consumers and Plugins. Each of these entities can be interacted with through their corresponding DAO instance, available through the **DAO Factory** instance. The DAO Factory is responsible for loading these core entities' DAOs as well as any additional entities, provided for example by plugins.

The DAO Factory is a singleton instance in Kong and thus, is accessible through the `singletons` module:

```lua
local singletons = require "kong.singletons"

-- Core DAOs
local apis_dao = singletons.dao.apis
local consumers_dao = singletons.dao.consumers
local plugins_dao = singletons.dao.plugins
```

---

## The DAO Lua API

The DAO class is responsible for the operations executed on a given table in the datastore, generally mapping to an entity in Kong. All the underlying supported databases (currently Cassandra and PostgreSQL) comply to the same interface, thus making the DAO compatible with all of them.

The DAO interface is documented in the [Public Lua API][public interface] as the [kong.dao] module.

For example, inserting an API is as easy as:

```lua
local singletons = require "kong.singletons"
local dao = singletons.dao

local inserted_api, err = dao.apis:insert({
  name = "mockbin",
  upstream_url = "http://mockbin.com",
  request_host = "mockbin.com"
})
```

---

Next: [Custom Entities ›]({{page.book.next}})

[kong.dao]: /{{page.kong_version}}/lua-reference/modules/kong.dao
[public interface]: /{{page.kong_version}}/lua-reference/modules/kong.dao.cassandra.base_dao/#Public_interface


text:
const path = require('path');
const fs = require('fs');

const INCLUDE_RE = /!{3}\s*include(.+?)!{3}/i;
const BRACES_RE = /\((.+?)\)/i;

const include_plugin = (md, options) => {
  const defaultOptions = {
    root: '.',
    getRootDir: (pluginOptions/*, state, startLine, endLine*/) => pluginOptions.root,
    includeRe: INCLUDE_RE,
    throwError: true,
    bracesAreOptional: false,
    notFoundMessage: 'File \'{{FILE}}\' not found.',
    circularMessage: 'Circular reference between \'{{FILE}}\' and \'{{PARENT}}\'.'
  };

  if (typeof options === 'string') {
    options = {
      ...defaultOptions,
      root: options
    };
  } else {
    options = {
      ...defaultOptions,
      ...options
    };
  }

  const _replaceIncludeByContent = (src, rootdir, parentFilePath, filesProcessed) => {
    filesProcessed = filesProcessed ? filesProcessed.slice() : []; // making a copy
    let cap, filePath, mdSrc, errorMessage;

    // store parent file path to check circular references
    if (parentFilePath) {
      filesProcessed.push(parentFilePath);
    }
    while ((cap = options.includeRe.exec(src))) {
      let includePath = cap[1].trim();
      const sansBracesMatch = BRACES_RE.exec(includePath);

      if (!sansBracesMatch && !options.bracesAreOptional) {
        errorMessage = `INCLUDE statement '${src.trim()}' MUST have '()' braces around the include path ('${includePath}')`;
      } else if (sansBracesMatch) {
        includePath = sansBracesMatch[1].trim();
      } else if (!/^\s/.test(cap[1])) {
        // path SHOULD have been preceeded by at least ONE whitespace character!
        /* eslint max-len: "off" */
        errorMessage = `INCLUDE statement '${src.trim()}': when not using braces around the path ('${includePath}'), it MUST be preceeded by at least one whitespace character to separate the include keyword and the include path.`;
      }

      if (!errorMessage) {
        filePath = path.resolve(rootdir, includePath);

        // check if child file exists or if there is a circular reference
        if (!fs.existsSync(filePath)) {
          // child file does not exist
          errorMessage = options.notFoundMessage.replace('{{FILE}}', filePath);
        } else if (filesProcessed.indexOf(filePath) !== -1) {
          // reference would be circular
          errorMessage = options.circularMessage.replace('{{FILE}}', filePath).replace('{{PARENT}}', parentFilePath);
        }
      }

      // check if there were any errors
      if (errorMessage) {
        if (options.throwError) {
          throw new Error(errorMessage);
        }
        mdSrc = `\n\n# INCLUDE ERROR: ${errorMessage}\n\n`;
      } else {
        // get content of child file
        mdSrc = fs.readFileSync(filePath, 'utf8');
        // check if child file also has includes
        mdSrc = _replaceIncludeByContent(mdSrc, path.dirname(filePath), filePath, filesProcessed);
        // remove one trailing newline, if it exists: that way, the included content does NOT
        // automatically terminate the paragraph it is in due to the writer of the included
        // part having terminated the content with a newline.
        // However, when that snippet writer terminated with TWO (or more) newlines, these, minus one,
        // will be merged with the newline after the #include statement, resulting in a 2-NL paragraph
        // termination.
        const len = mdSrc.length;
        if (mdSrc[len - 1] === '\n') {
          mdSrc = mdSrc.substring(0, len - 1);
        }
      }

      // replace include by file content
      src = src.slice(0, cap.index) + mdSrc + src.slice(cap.index + cap[0].length, src.length);
    }
    return src;
  };

  const _includeFileParts = (state, startLine, endLine/*, silent*/) => {
    state.src = _replaceIncludeByContent(state.src, options.getRootDir(options, state, startLine, endLine));
  };

  md.core.ruler.before('normalize', 'include', _includeFileParts);
};

module.exports = include_plugin;


text:
FROM ubuntu:14.04
MAINTAINER chenjian "chenjian158978@gmail.com"

# Set the locale
RUN locale-gen zh_CN.UTF-8
ENV LANG zh_CN.UTF-8
ENV LANGUAGE zh_CN:zh
ENV LC_ALL zh_CN.UTF-8

# set timezone
RUN echo "Asia/Shanghai" > /etc/timezone
RUN dpkg-reconfigure -f noninteractive tzdata

# 换源
ADD sources.list /
RUN cp /etc/apt/sources.list /etc/apt/sources.list_backup
RUN rm -rf /etc/apt/sources.list
ADD sources.list /etc/apt/sources.list
############################################

RUN apt-get clean
RUN apt-get update
RUN apt-get -y upgrade

RUN apt-get install -y python-dev
RUN apt-get install -y build-essential
RUN apt-get install -y python-pip

ADD librdkafka /librdkafka
WORKDIR /librdkafka
RUN ./configure
RUN make
RUN make install
RUN ldconfig

RUN pip install confluent-kafka

RUN apt-get clean

WORKDIR /
ADD confluentkafka.py /
ADD whilerun.py /


text:
<?php

namespace ManipleEvents\Entity;

class EventTaxon implements TaxonInterface
{
    /**
     * @var int
     */
    protected $id;

    /**
     * @var \ManipleEvents\Entity\Event
     */
    protected $event;

    /**
     * @var \ManipleEvents\Entity\Taxon
     */
    protected $tag;

    /**
     * Taxon priority
     * @var int
     */
    protected $priority;
}


text:
package org.jitsi.impl.osgi.framework;

import java.util.*;

import org.osgi.framework.*;

/**
 *
 * @author Lyubomir Marinov
 */
public class ServiceRegistrationImpl
    implements ServiceRegistration
{
    private static final Comparator<String> CASE_INSENSITIVE_COMPARATOR
        = new Comparator<String>()
        {
            public int compare(String s1, String s2)
            {
                return s1.compareToIgnoreCase(s2);
            }
        };

    private static final Map<String, Object> EMPTY_PROPERTIES
        = newCaseInsensitiveMapInstance();

    private final BundleImpl bundle;

    private final String[] classNames;

    private final Map<String, Object> properties;

    private Object service;

    private final Long serviceId;

    private final ServiceReferenceImpl serviceReference
        = new ServiceReferenceImpl();

    public ServiceRegistrationImpl(
            BundleImpl bundle,
            long serviceId,
            String[] classNames,
            Object service,
            Dictionary<String, ?> properties)
    {
        this.bundle = bundle;
        this.serviceId = serviceId;
        this.classNames = classNames;
        this.service = service;

        if ((properties == null) || properties.isEmpty())
                this.properties = EMPTY_PROPERTIES;
        else
        {
            Enumeration<String> keys = properties.keys();
            Map<String, Object> thisProperties
                = newCaseInsensitiveMapInstance();

            while (keys.hasMoreElements())
            {
                String key = keys.nextElement();

                if (Constants.OBJECTCLASS.equalsIgnoreCase(key)
                        || Constants.SERVICE_ID.equalsIgnoreCase(key))
                    continue;
                else if (thisProperties.containsKey(key))
                    throw new IllegalArgumentException(key);
                else
                    thisProperties.put(key, properties.get(key));
            }

            this.properties
                = thisProperties.isEmpty()
                    ? EMPTY_PROPERTIES
                    : thisProperties;
        }
    }

    public ServiceReferenceImpl getReference()
    {
        return serviceReference;
    }

    public ServiceReference getReference(Class<?> clazz)
    {
        return serviceReference;
    }

    private static Map<String, Object> newCaseInsensitiveMapInstance()
    {
        return new TreeMap<String, Object>(CASE_INSENSITIVE_COMPARATOR);
    }

    public void setProperties(Dictionary properties)
    {
        // TODO Auto-generated method stub
    }

    public void unregister()
    {
        bundle.getFramework().unregisterService(bundle, this);
    }

    class ServiceReferenceImpl
        implements ServiceReference
    {
        public int compareTo(Object other)
        {
            Long thisServiceId = ServiceRegistrationImpl.this.serviceId;
            Long otherServiceId = ((ServiceRegistrationImpl) other).serviceId;

            return otherServiceId.compareTo(thisServiceId);
        }

        public Bundle getBundle()
        {
            return bundle;
        }

        public Object getProperty(String key)
        {
            Object value;

            if (Constants.OBJECTCLASS.equalsIgnoreCase(key))
                value = classNames;
            else if (Constants.SERVICE_ID.equalsIgnoreCase(key))
                value = serviceId;
            else
                synchronized (properties)
                {
                    value = properties.get(key);
                }
            return value;
        }

        public String[] getPropertyKeys()
        {
            synchronized (properties)
            {
                String[] keys = new String[2 + properties.size()];
                int index = 0;

                keys[index++] = Constants.OBJECTCLASS;
                keys[index++] = Constants.SERVICE_ID;

                for (String key : properties.keySet())
                    keys[index++] = key;
                return keys;
            }
        }

        Object getService()
        {
            return service;
        }

        public Bundle[] getUsingBundles()
        {
            // TODO Auto-generated method stub
            return null;
        }

        public boolean isAssignableTo(Bundle bundle, String className)
        {
            // TODO Auto-generated method stub
            return false;
        }
    }
}


text:
@font-face {
  font-family: 'Inconsolata';
  font-weight: 400;
  font-style: normal;
  src: url('../fonts/Inconsolata-regular/Inconsolata-regular.eot');
  src: url('../fonts/Inconsolata-regular/Inconsolata-regular.eot?#iefix') format('embedded-opentype'),
       local('Inconsolata'),
       local('Inconsolata-regular'),
       url('../fonts/Inconsolata-regular/Inconsolata-regular.woff2') format('woff2'),
       url('../fonts/Inconsolata-regular/Inconsolata-regular.woff') format('woff'),
       url('../fonts/Inconsolata-regular/Inconsolata-regular.ttf') format('truetype'),
       url('../fonts/Inconsolata-regular/Inconsolata-regular.svg#Inconsolata') format('svg');
}

body {
  background-color: #FFFFFF;
}

#error {
  position: fixed;
  width: 100%;
  height: 100%;
}

#error, #error-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

#error-content {
  font-family: 'Inconsolata', sans-serif;
  font-size: 40px;
  text-transform: uppercase;;
  padding: 0.5em;
  line-height: 1.5;
  color: rgba(255, 255, 255, 0.8);
  background-color: rgba(0, 0, 0, 0.8);
}

.code {
  font-size: 60px;
}

.message {
  text-align: center;
}


text:
static inline VALUE
rb_GetErrno(char* name)
{
  return rb_const_get(rb_const_get(rb_cObject, rb_intern("Errno")),
                      rb_intern(name));
}

#define rb_raise_sdl_error() \
  rb_raise(rb_eStarRubyError, "%s", SDL_GetError())
#define rb_raise_sdl_mix_error() \
  rb_raise(rb_eStarRubyError, "%s", Mix_GetError())
#define rb_raise_sdl_ttf_error() \
  rb_raise(rb_eStarRubyError, "%s", TTF_GetError())
#define rb_raise_opengl_error() \
  rb_raise(rb_eStarRubyError, "OpenGL Error: 0x%x", glGetError());

#endif


text:
namespace ngraph
{
    namespace pass
    {
        class NGRAPH_API ConvertOpset3To1 : public NodePass
        {
        public:
            ///
            /// \brief    Constructor for the Opv1 downgrade transformation pass.
            ///
            /// \details  This transformation pass iterates over all nodes in a graph
            /// and updates version 3 ops to their version 1 equivalents.
            /// All ops in the final graph have op version 1.
            ConvertOpset3To1() = default;
            bool run_on_node(std::shared_ptr<ngraph::Node> node) override;
        };
    }
}


text:
package de.hub.emffrag.fragmentation;

import org.junit.Before;
import org.junit.Test;

import de.hub.emffrag.EmfFragActivator;
import de.hub.emffrag.EmfFragActivator.IdBehaviour;
import de.hub.emffrag.EmfFragActivator.IndexedValueSetBahaviour;
import de.hub.emffrag.testmodels.frag.testmodel.TestObject;
import de.hub.emffrag.testmodels.frag.testmodel.TestObjectWithIndexes;

import junit.framework.Assert;

public class ConfigurationTests extends AbstractFragmentationTests {

	@Before
	public void ensureDefaultConfiguration() {
		EmfFragActivator.instance.indexedValueSetBahaviour = IndexedValueSetBahaviour.strict;
		EmfFragActivator.instance.idBehaviour = IdBehaviour.strict;
		EmfFragActivator.instance.defaultModelForIdBehavior = null;
	}

	@Override
	protected TestObject createTestObject(int id) {
		return Assertions.createTestObjectWithIndexes(id);
	}

	@Test
	public void testNeverContainsBehavior() {
		EmfFragActivator.instance.indexedValueSetBahaviour = IndexedValueSetBahaviour.neverContains;
		model.root().getContents().add(object1);
		try {
			Assert.assertFalse("Wrong result.", ((TestObjectWithIndexes)object1).getIndexedReferences().contains("something"));
		} catch (Exception e) {
			e.printStackTrace();
			Assert.fail("Exception thrown: " + e.getClass().getCanonicalName());
		}
	}

	@Test
	public void testStrictContainsBehavior() {
		model.root().getContents().add(object1);
		try {
			 ((TestObjectWithIndexes)object1).getIndexedReferences().contains("something");
		} catch (UnsupportedOperationException e) {
			return;
		} catch (Exception e) {
			e.printStackTrace();
			Assert.fail("Wrong exception thrown: " + e.getClass().getCanonicalName());
		}
		Assert.fail("Exception not thrown");
	}

	@Test
	public void testStrictIdBehavior() {
		model.root().getContents().add(object1);
		try {
			object1.getCrossReferences().add(object2);
		} catch (NotInAFragmentedModelException e) {
			return;
		} catch (Exception e) {
			e.printStackTrace();
			Assert.fail("Wrong exception thrown: " + e.getClass().getCanonicalName());
		}
		Assert.fail("Exception not thrown");
	}

	@Test
	public void testPreliminaryIdBehavior() {
		EmfFragActivator.instance.idBehaviour = IdBehaviour.preliminary;

		model.root().getContents().add(object1);
		try {
			object1.getCrossReferences().add(object2);
			Assert.assertTrue("Object has not a preliminary id.", FInternalObjectImpl.isPreliminary(((FObjectImpl)object2).fInternalObject().getId(false)));
		} catch (Exception e) {
			Assert.fail("Exception thrown: " + e.getClass().getCanonicalName());
		}
		object1.getFragmentedContents().add(object2);

		model.save(null);
		reinitializeModel();

		Assertions.root(model).getCrossReferences().assertSize(1).get(0).assertId(2);
		Assertions.root(model).getFragmentedContents().assertSize(1).get(0).assertId(2);
	}

	@Test
	public void testDefaultModelIdBehavior1() {
		EmfFragActivator.instance.idBehaviour = IdBehaviour.defaultModel;
		EmfFragActivator.instance.defaultModelForIdBehavior = model;

		model.root().getContents().add(object1);
		try {
			object1.getCrossReferences().add(object2);
			boolean preliminaryId = FInternalObjectImpl.isPreliminary(((FObjectImpl)object2).fInternalObject().getId(false));
			Assert.assertNotNull("Id is null.", preliminaryId);
			Assert.assertFalse("Object has a preliminary id.", preliminaryId);
		} catch (Exception e) {
			Assert.fail("Exception thrown: " + e.getClass().getCanonicalName());
		}
		object1.getFragmentedContents().add(object2);

		model.save(null);
		reinitializeModel();

		Assertions.root(model).getCrossReferences().assertSize(1).get(0).assertId(2);
		Assertions.root(model).getFragmentedContents().assertSize(1).get(0).assertId(2);
	}

	@Test
	public void testDefaultModelIdBehavior2() {
		EmfFragActivator.instance.idBehaviour = IdBehaviour.defaultModel;
		EmfFragActivator.instance.defaultModelForIdBehavior = model;

		model.root().getContents().add(object1);
		try {
			object1.getCrossReferences().add(object2);
			boolean preliminaryId = FInternalObjectImpl.isPreliminary(((FObjectImpl)object2).fInternalObject().getId(false));
			Assert.assertNotNull("Id is null.", preliminaryId);
			Assert.assertFalse("Object has a preliminary id.", preliminaryId);
		} catch (Exception e) {
			Assert.fail("Exception thrown: " + e.getClass().getCanonicalName());
		}
		object1.getRegularContents().add(object2);

		model.save(null);
		reinitializeModel();

		Assertions.root(model).getCrossReferences().assertSize(1).get(0).assertId(2);
		Assertions.root(model).getRegularContents().assertSize(1).get(0).assertId(2);
	}
}


text:
package net.safedata.java8.training.bi.functional.interfaces;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;

/**
 * A few bi- functional interfaces usage samples
 */
public class BiFunctionalInterfacesMain {

    public static void main(String[] args) {
        biPredicatesSamples();

        biFunctionsSamples();

        biConsumersSamples();
    }

    private static void biPredicatesSamples() {
        final BiPredicate<String, Integer> biPredicate = (first, second) ->
                first.length() > 10 && second > 0; // whatever the business logic requires
        System.out.println(biPredicate.test("something", 5));
    }

    private static void biFunctionsSamples() {
        final BiFunction<String, Integer, String> biFunction =
                (first, second) -> "The value of " + first + " and " + second;
        System.out.println(biFunction.apply("another one", 20));

        // new methods added in the Map interface
        final Map<Integer, String> months = getMonths();

        months.compute(4, (key, value) -> "April or something else");

        months.computeIfPresent(2, (key, value) -> "The shortest month");

        months.replaceAll((key, value) -> {
            if (key > 2) {
                return value.toUpperCase();
            } else {
                final String theNewValue = value + " added something";
                return theNewValue;
            }
        });
    }

    private static void biConsumersSamples() {
        final Map<Integer, String> months = getMonths();

        // iteration - imperative mode
        final Set<Map.Entry<Integer, String>> entries = months.entrySet();
        for (Map.Entry<Integer, String> entry : entries) {
            processEntry(entry);
        }

        // iteration - functional mode
        months.forEach((key, value) -> System.out.println(key + " -> " + value)); // easier iteration
    }

    private static void processEntry(final Map.Entry<Integer, String> entry) {
        System.out.println(entry.getKey() + " -> " + entry.getValue());
    }

    private static Map<Integer, String> getMonths() {
        final Map<Integer, String> months = new HashMap<>();

        months.put(1, "January");
        months.put(2, "February");
        months.put(3, "March");

        return months;
    }
}


text:
"""
Implementation of enums.
"""
import operator

from .imputils import (lower_builtin, lower_getattr, lower_getattr_generic,
                       lower_cast, lower_constant, impl_ret_untracked)
from .. import types

@lower_builtin(operator.eq, types.EnumMember, types.EnumMember)
def enum_eq(context, builder, sig, args):
    tu, tv = sig.args
    u, v = args
    res = context.generic_compare(builder, operator.eq,
                                  (tu.dtype, tv.dtype), (u, v))
    return impl_ret_untracked(context, builder, sig.return_type, res)

@lower_builtin(operator.is_, types.EnumMember, types.EnumMember)
def enum_is(context, builder, sig, args):
    tu, tv = sig.args
    u, v = args
    if tu == tv:
        res = context.generic_compare(builder, operator.eq,
                                      (tu.dtype, tv.dtype), (u, v))
    else:
        res = context.get_constant(sig.return_type, False)
    return impl_ret_untracked(context, builder, sig.return_type, res)

@lower_builtin(operator.ne, types.EnumMember, types.EnumMember)
def enum_ne(context, builder, sig, args):
    tu, tv = sig.args
    u, v = args
    res = context.generic_compare(builder, operator.ne,
                                  (tu.dtype, tv.dtype), (u, v))
    return impl_ret_untracked(context, builder, sig.return_type, res)

@lower_getattr(types.EnumMember, 'value')
def enum_value(context, builder, ty, val):
    return val

@lower_cast(types.IntEnumMember, types.Integer)
def int_enum_to_int(context, builder, fromty, toty, val):
    """
    Convert an IntEnum member to its raw integer value.
    """
    return context.cast(builder, val, fromty.dtype, toty)

@lower_constant(types.EnumMember)
def enum_constant(context, builder, ty, pyval):
    """
    Return a LLVM constant representing enum member *pyval*.
    """
    return context.get_constant_generic(builder, ty.dtype, pyval.value)

@lower_getattr_generic(types.EnumClass)
def enum_class_getattr(context, builder, ty, val, attr):
    """
    Return an enum member by attribute name.
    """
    member = getattr(ty.instance_class, attr)
    return context.get_constant_generic(builder, ty.dtype, member.value)

@lower_builtin('static_getitem', types.EnumClass, types.StringLiteral)
def enum_class_getitem(context, builder, sig, args):
    """
    Return an enum member by index name.
    """
    enum_cls_typ, idx = sig.args
    member = enum_cls_typ.instance_class[idx.literal_value]
    return context.get_constant_generic(builder, enum_cls_typ.dtype,
                                        member.value)


text:
package cmd

import (
	"github.com/spf13/cobra"
)

// topicsCmd represents the topics command
var topicsCmd = &cobra.Command{
	Use:   "topics",
	Short: "Topics",
	Long:  `Topics`,
	Run: func(cmd *cobra.Command, args []string) {

	},
}

func init() {
	RootCmd.AddCommand(topicsCmd)
}


text:
from django.contrib import admin
from voxel_globe.world.models import WorldBorder

class WorldBorderAdmin(admin.ModelAdmin):
  list_display = ('name', 'lat', 'lon', 'closeToUS');

# Register your models here.
admin.site.register(WorldBorder, WorldBorderAdmin)


text:
module RailsSlickgrid
  module DataExtractor
    extend self

    def from_data(data)
      return from_ar(data) if data.first.is_a? ActiveRecord::Base
      return data
    end

    def from_ar(data)
      data.collect(&:attributes)
    end
  end
end


text:
package windows

import (
	"context"
	"fmt"
	"strings"
	"time"

	"github.com/onsi/ginkgo/v2"
	"github.com/onsi/gomega"
	v1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/fields"
	"k8s.io/apimachinery/pkg/util/uuid"
	clientset "k8s.io/client-go/kubernetes"
	"k8s.io/kubernetes/pkg/kubelet/events"
	"k8s.io/kubernetes/test/e2e/framework"
	e2epod "k8s.io/kubernetes/test/e2e/framework/pod"
	testutils "k8s.io/kubernetes/test/utils"
	imageutils "k8s.io/kubernetes/test/utils/image"
	admissionapi "k8s.io/pod-security-admission/api"
)

const runAsUserNameContainerName = "run-as-username-container"

var _ = SIGDescribe("[Feature:Windows] SecurityContext", func() {
	f := framework.NewDefaultFramework("windows-run-as-username")
	f.NamespacePodSecurityEnforceLevel = admissionapi.LevelPrivileged

	ginkgo.It("should be able create pods and run containers with a given username", func() {
		ginkgo.By("Creating 2 pods: 1 with the default user, and one with a custom one.")
		podDefault := runAsUserNamePod(nil)
		f.TestContainerOutput("check default user", podDefault, 0, []string{"ContainerUser"})

		podUserName := runAsUserNamePod(toPtr("ContainerAdministrator"))
		f.TestContainerOutput("check set user", podUserName, 0, []string{"ContainerAdministrator"})
	})

	ginkgo.It("should not be able to create pods with unknown usernames at Pod level", func() {
		ginkgo.By("Creating a pod with an invalid username")
		podInvalid := f.PodClient().Create(runAsUserNamePod(toPtr("FooLish")))

		failedSandboxEventSelector := fields.Set{
			"involvedObject.kind":      "Pod",
			"involvedObject.name":      podInvalid.Name,
			"involvedObject.namespace": podInvalid.Namespace,
			"reason":                   events.FailedCreatePodSandBox,
		}.AsSelector().String()
		hcsschimError := "The user name or password is incorrect."

		// Hostprocess updated the cri to pass RunAsUserName to sandbox: https://github.com/kubernetes/kubernetes/pull/99576/commits/51a02fdb80cb7ba042a66362eb76facd2fd82401
		// Some runtimes might use that and set the username on the podsandbox. Containerd 1.6+ is known to do this.
		// If there is an error when creating the pod sandbox then the pod stays in pending state by design
		// See https://github.com/kubernetes/kubernetes/issues/104635
		// Not all runtimes use the sandbox information.  This means the test needs to check if the pod
		// sandbox failed or workload pod failed.
		framework.Logf("Waiting for pod %s to enter the error state.", podInvalid.Name)
		gomega.Eventually(func() bool {
			failedSandbox, err := eventOccurred(f.ClientSet, podInvalid.Namespace, failedSandboxEventSelector, hcsschimError)
			if err != nil {
				framework.Logf("Error retrieving events for pod. Ignoring...")
			}
			if failedSandbox {
				framework.Logf("Found Expected Event 'Failed to Create Pod Sandbox' with message containing: %s", hcsschimError)
				return true
			}

			framework.Logf("No Sandbox error found. Looking for failure in workload pods")
			pod, err := f.PodClient().Get(context.Background(), podInvalid.Name, metav1.GetOptions{})
			if err != nil {
				framework.Logf("Error retrieving pod: %s", err)
				return false
			}

			podTerminatedReason := testutils.TerminatedContainers(pod)[runAsUserNameContainerName]
			podFailedToStart := podTerminatedReason == "ContainerCannotRun" || podTerminatedReason == "StartError"
			if pod.Status.Phase == v1.PodFailed && podFailedToStart {
				framework.Logf("Found terminated workload Pod that could not start")
				return true
			}

			return false
		}, framework.PodStartTimeout, 1*time.Second).Should(gomega.BeTrue())
	})

	ginkgo.It("should not be able to create pods with unknown usernames at Container level", func() {
		ginkgo.By("Creating a pod with an invalid username at container level and pod running as ContainerUser")
		p := runAsUserNamePod(toPtr("FooLish"))
		p.Spec.SecurityContext.WindowsOptions.RunAsUserName = toPtr("ContainerUser")
		podInvalid := f.PodClient().Create(p)

		framework.Logf("Waiting for pod %s to enter the error state.", podInvalid.Name)
		framework.ExpectNoError(e2epod.WaitForPodTerminatedInNamespace(f.ClientSet, podInvalid.Name, "", f.Namespace.Name))

		podInvalid, _ = f.PodClient().Get(context.TODO(), podInvalid.Name, metav1.GetOptions{})
		podTerminatedReason := testutils.TerminatedContainers(podInvalid)[runAsUserNameContainerName]
		if podTerminatedReason != "ContainerCannotRun" && podTerminatedReason != "StartError" {
			framework.Failf("The container terminated reason was supposed to be: 'ContainerCannotRun' or 'StartError', not: '%q'", podTerminatedReason)
		}
	})

	ginkgo.It("should override SecurityContext username if set", func() {
		ginkgo.By("Creating a pod with 2 containers with different username configurations.")

		pod := runAsUserNamePod(toPtr("ContainerAdministrator"))
		pod.Spec.Containers[0].SecurityContext.WindowsOptions.RunAsUserName = toPtr("ContainerUser")
		pod.Spec.Containers = append(pod.Spec.Containers, v1.Container{
			Name:    "run-as-username-new-container",
			Image:   imageutils.GetE2EImage(imageutils.NonRoot),
			Command: []string{"cmd", "/S", "/C", "echo %username%"},
		})

		f.TestContainerOutput("check overridden username", pod, 0, []string{"ContainerUser"})
		f.TestContainerOutput("check pod SecurityContext username", pod, 1, []string{"ContainerAdministrator"})
	})

	ginkgo.It("should ignore Linux Specific SecurityContext if set", func() {
		ginkgo.By("Creating a pod with SELinux options")
		// It is sufficient to show that the pod comes up here. Since we're stripping the SELinux and other linux
		// security contexts in apiserver and not updating the pod object in the apiserver, we cannot validate the
		// the pod object to not have those security contexts. However the pod coming to running state is a sufficient
		// enough condition for us to validate since prior to https://github.com/kubernetes/kubernetes/pull/93475
		// the pod would have failed to come up.
		windowsPodWithSELinux := createTestPod(f, windowsBusyBoximage, windowsOS)
		windowsPodWithSELinux.Spec.Containers[0].Args = []string{"test-webserver-with-selinux"}
		windowsPodWithSELinux.Spec.SecurityContext = &v1.PodSecurityContext{}
		containerUserName := "ContainerAdministrator"
		windowsPodWithSELinux.Spec.SecurityContext.SELinuxOptions = &v1.SELinuxOptions{Level: "s0:c24,c9"}
		windowsPodWithSELinux.Spec.Containers[0].SecurityContext = &v1.SecurityContext{
			SELinuxOptions: &v1.SELinuxOptions{Level: "s0:c24,c9"},
			WindowsOptions: &v1.WindowsSecurityContextOptions{RunAsUserName: &containerUserName}}
		windowsPodWithSELinux.Spec.Tolerations = []v1.Toleration{{Key: "os", Value: "Windows"}}
		windowsPodWithSELinux, err := f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(),
			windowsPodWithSELinux, metav1.CreateOptions{})
		framework.ExpectNoError(err)
		framework.Logf("Created pod %v", windowsPodWithSELinux)
		framework.ExpectNoError(e2epod.WaitForPodNameRunningInNamespace(f.ClientSet, windowsPodWithSELinux.Name,
			f.Namespace.Name), "failed to wait for pod %s to be running", windowsPodWithSELinux.Name)
	})

	ginkgo.It("should not be able to create pods with containers running as ContainerAdministrator when runAsNonRoot is true", func() {
		ginkgo.By("Creating a pod")

		p := runAsUserNamePod(toPtr("ContainerAdministrator"))
		p.Spec.SecurityContext.RunAsNonRoot = &trueVar

		podInvalid, err := f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), p, metav1.CreateOptions{})
		framework.ExpectNoError(err, "Error creating pod")

		ginkgo.By("Waiting for pod to finish")
		event, err := f.PodClient().WaitForErrorEventOrSuccess(podInvalid)
		framework.ExpectNoError(err)
		framework.ExpectNotEqual(event, nil, "event should not be empty")
		framework.Logf("Got event: %v", event)
		expectedEventError := "container's runAsUserName (ContainerAdministrator) which will be regarded as root identity and will break non-root policy"
		framework.ExpectEqual(true, strings.Contains(event.Message, expectedEventError), "Event error should indicate non-root policy caused container to not start")
	})

	ginkgo.It("should not be able to create pods with containers running as CONTAINERADMINISTRATOR when runAsNonRoot is true", func() {
		ginkgo.By("Creating a pod")

		p := runAsUserNamePod(toPtr("CONTAINERADMINISTRATOR"))
		p.Spec.SecurityContext.RunAsNonRoot = &trueVar

		podInvalid, err := f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), p, metav1.CreateOptions{})
		framework.ExpectNoError(err, "Error creating pod")

		ginkgo.By("Waiting for pod to finish")
		event, err := f.PodClient().WaitForErrorEventOrSuccess(podInvalid)
		framework.ExpectNoError(err)
		framework.ExpectNotEqual(event, nil, "event should not be empty")
		framework.Logf("Got event: %v", event)
		expectedEventError := "container's runAsUserName (CONTAINERADMINISTRATOR) which will be regarded as root identity and will break non-root policy"
		framework.ExpectEqual(true, strings.Contains(event.Message, expectedEventError), "Event error should indicate non-root policy caused container to not start")
	})
})

func runAsUserNamePod(username *string) *v1.Pod {
	podName := "run-as-username-" + string(uuid.NewUUID())
	return &v1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name: podName,
		},
		Spec: v1.PodSpec{
			NodeSelector: map[string]string{"kubernetes.io/os": "windows"},
			Containers: []v1.Container{
				{
					Name:    runAsUserNameContainerName,
					Image:   imageutils.GetE2EImage(imageutils.NonRoot),
					Command: []string{"cmd", "/S", "/C", "echo %username%"},
					SecurityContext: &v1.SecurityContext{
						WindowsOptions: &v1.WindowsSecurityContextOptions{
							RunAsUserName: username,
						},
					},
				},
			},
			SecurityContext: &v1.PodSecurityContext{
				WindowsOptions: &v1.WindowsSecurityContextOptions{
					RunAsUserName: username,
				},
			},
			RestartPolicy: v1.RestartPolicyNever,
		},
	}
}

func toPtr(s string) *string {
	return &s
}

func eventOccurred(c clientset.Interface, namespace, eventSelector, msg string) (bool, error) {
	options := metav1.ListOptions{FieldSelector: eventSelector}

	events, err := c.CoreV1().Events(namespace).List(context.TODO(), options)
	if err != nil {
		return false, fmt.Errorf("got error while getting events: %v", err)
	}
	for _, event := range events.Items {
		if strings.Contains(event.Message, msg) {
			return true, nil
		}
	}
	return false, nil
}