text:
<?php
# MantisBT - A PHP based bugtracking system

# MantisBT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# MantisBT is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with MantisBT.  If not, see <http://www.gnu.org/licenses/>.

require_api( 'authentication_api.php' );
require_api( 'bug_api.php' );
require_api( 'bugnote_api.php' );
require_api( 'config_api.php' );
require_api( 'constant_inc.php' );
require_api( 'current_user_api.php' );
require_api( 'database_api.php' );
require_api( 'error_api.php' );
require_api( 'helper_api.php' );
require_api( 'lang_api.php' );
require_api( 'print_api.php' );
require_api( 'project_api.php' );
require_api( 'string_api.php' );
require_api( 'user_api.php' );

# @global array $g_cache_access_matrix
$g_cache_access_matrix = array();

# @global array $g_cache_access_matrix_project_ids
$g_cache_access_matrix_project_ids = array();

# @global array $g_cache_access_matrix_user_ids
$g_cache_access_matrix_user_ids = array();

/**
 * Function to be called when a user is attempting to access a page that
 * he/she is not authorised to.  This outputs an access denied message then
 * re-directs to the mainpage.
 *
 * @return void
 */
function access_denied() {
	if( !auth_is_user_authenticated() ) {
		if( basename( $_SERVER['SCRIPT_NAME'] ) != 'login_page.php' ) {
			$t_return_page = $_SERVER['SCRIPT_NAME'];
			if( isset( $_SERVER['QUERY_STRING'] ) ) {
				$t_return_page .= '?' . $_SERVER['QUERY_STRING'];
			}
			$t_return_page = string_url( string_sanitize_url( $t_return_page ) );
			print_header_redirect( 'login_page.php?return=' . $t_return_page );
		}
	} else {
		if( current_user_is_anonymous() ) {
			if( basename( $_SERVER['SCRIPT_NAME'] ) != 'login_page.php' ) {
				$t_return_page = $_SERVER['SCRIPT_NAME'];
				if( isset( $_SERVER['QUERY_STRING'] ) ) {
					$t_return_page .= '?' . $_SERVER['QUERY_STRING'];
				}
				$t_return_page = string_url( string_sanitize_url( $t_return_page ) );
				echo '
' . error_string( ERROR_ACCESS_DENIED ) . '

';
				print_link_button( helper_mantis_url( 'login_page.php' ) . '?return=' . $t_return_page, lang_get( 'click_to_login' ) );
				echo '

';
				print_link_button(
					helper_mantis_url( config_get( 'default_home_page' ) ),
					lang_get( 'proceed' )
				);
				echo '
';
			}
		} else {
			layout_page_header();
			layout_admin_page_begin();
			echo '

';
			html_operation_failure(
				helper_mantis_url( config_get( 'default_home_page' ) ),
				error_string( ERROR_ACCESS_DENIED )
			);
			layout_admin_page_end();
		}
	}
	exit;
}

/**
 * retrieves and returns access matrix for a project from cache or caching if required.
 * @param integer $p_project_id Integer representing project identifier.
 * @return array returns an array of users->accesslevel for the given user
 * @access private
 */
function access_cache_matrix_project( $p_project_id ) {
	global $g_cache_access_matrix, $g_cache_access_matrix_project_ids;

	if( ALL_PROJECTS == (int)$p_project_id ) {
		return array();
	}

	if( !in_array( (int)$p_project_id, $g_cache_access_matrix_project_ids ) ) {
		db_param_push();
		$t_query = 'SELECT user_id, access_level FROM {project_user_list} WHERE project_id=' . db_param();
		$t_result = db_query( $t_query, array( (int)$p_project_id ) );
		while( $t_row = db_fetch_array( $t_result ) ) {
			$g_cache_access_matrix[(int)$t_row['user_id']][(int)$p_project_id] = (int)$t_row['access_level'];
		}

		$g_cache_access_matrix_project_ids[] = (int)$p_project_id;
	}

	$t_results = array();

	foreach( $g_cache_access_matrix as $t_user ) {
		if( isset( $t_user[(int)$p_project_id] ) ) {
			$t_results[(int)$p_project_id] = $t_user[(int)$p_project_id];
		}
	}

	return $t_results;
}

/**
 * retrieves and returns access matrix for a user from cache or caching if required.
 * @param integer $p_user_id Integer representing user identifier.
 * @return array returns an array of projects->accesslevel for the given user
 * @access private
 */
function access_cache_matrix_user( $p_user_id ) {
	global $g_cache_access_matrix, $g_cache_access_matrix_user_ids;

	if( !in_array( (int)$p_user_id, $g_cache_access_matrix_user_ids ) ) {
		db_param_push();
		$t_query = 'SELECT project_id, access_level FROM {project_user_list} WHERE user_id=' . db_param();
		$t_result = db_query( $t_query, array( (int)$p_user_id ) );

		# make sure we always have an array to return
		$g_cache_access_matrix[(int)$p_user_id] = array();

		while( $t_row = db_fetch_array( $t_result ) ) {
			$g_cache_access_matrix[(int)$p_user_id][(int)$t_row['project_id']] = (int)$t_row['access_level'];
		}

		$g_cache_access_matrix_user_ids[] = (int)$p_user_id;
	}

	return $g_cache_access_matrix[(int)$p_user_id];
}

/**
 * Check the a user's access against the given "threshold" and return true
 * if the user can access, false otherwise.
 * $p_threshold may be a single value, or an array. If it is a single
 * value, treat it as a threshold so return true if user is >= threshold.
 * If it is an array, look for exact matches to one of the values
 * @param integer       $p_user_access_level User access level.
 * @param integer|array $p_threshold         Access threshold, defaults to NOBODY.
 * @return boolean true or false depending on whether given access level matches the threshold
 * @access public
 */
function access_compare_level( $p_user_access_level, $p_threshold = NOBODY ) {
	if( is_array( $p_threshold ) ) {
		return( in_array( $p_user_access_level, $p_threshold ) );
	} else {
		return( $p_user_access_level >= $p_threshold );
	}
}

/**
 * This function only checks the user's global access level, ignoring any
 * overrides they might have at a project level
 * @param integer|null $p_user_id Integer representing user identifier, defaults to null to use current user.
 * @return integer global access level
 * @access public
 */
function access_get_global_level( $p_user_id = null ) {
	if( $p_user_id === null ) {
		$p_user_id = auth_get_current_user_id();
	}

	# Deal with not logged in silently in this case
	# @@@ we may be able to remove this and just error
	#     and once we default to anon login, we can remove it for sure
	if( empty( $p_user_id ) && !auth_is_user_authenticated() ) {
		return false;
	}

	return user_get_field( $p_user_id, 'access_level' );
}

/**
 * Check the current user's access against the given value and return true
 * if the user's access is equal to or higher, false otherwise.
 * @param integer      $p_access_level Integer representing access level.
 * @param integer|null $p_user_id      Integer representing user id, defaults to null to use current user.
 * @return boolean whether user has access level specified
 * @access public
 */
function access_has_global_level( $p_access_level, $p_user_id = null ) {
	# Short circuit the check in this case
	if( NOBODY == $p_access_level ) {
		return false;
	}

	if( $p_user_id === null ) {
		$p_user_id = auth_get_current_user_id();
	}

	$t_access_level = access_get_global_level( $p_user_id );

	return access_compare_level( $t_access_level, $p_access_level );
}

/**
 * Check if the user has the specified global access level
 * and deny access to the page if not
 * @see access_has_global_level
 * @param integer      $p_access_level Integer representing access level.
 * @param integer|null $p_user_id      Integer representing user id, defaults to null to use current user.
 * @access public
 * @return void
 */
function access_ensure_global_level( $p_access_level, $p_user_id = null ) {
	if( !access_has_global_level( $p_access_level, $p_user_id ) ) {
		access_denied();
	}
}

/**
 * This function checks the project access level first (for the current project
 * if none is specified) and if the user is not listed, it falls back on the
 * user's global access level.
 * @param integer      $p_project_id Integer representing project id to check access against.
 * @param integer|null $p_user_id    Integer representing user id, defaults to null to use current user.
 * @return integer access level user has to given project
 * @access public
 */
function access_get_project_level( $p_project_id = null, $p_user_id = null ) {
	if( null === $p_user_id ) {
		$p_user_id = auth_get_current_user_id();
	}

	# Deal with not logged in silently in this case
	# @todo we may be able to remove this and just error and once we default to anon login, we can remove it for sure
	if( empty( $p_user_id ) && !auth_is_user_authenticated() ) {
		return ANYBODY;
	}

	if( null === $p_project_id ) {
		$p_project_id = helper_get_current_project();
	}

	$t_global_access_level = access_get_global_level( $p_user_id );

	if( ALL_PROJECTS == $p_project_id || user_is_administrator( $p_user_id ) ) {
		return $t_global_access_level;
	} else {
		$t_project_access_level = access_get_local_level( $p_user_id, $p_project_id );
		$t_project_view_state = project_get_field( $p_project_id, 'view_state' );

		# Try to use the project access level.
		# If the user is not listed in the project, then try to fall back
		#  to the global access level
		if( false === $t_project_access_level ) {
			# If the project is private and the user isn't listed, then they
			# must have the private_project_threshold access level to get in.
			if( VS_PRIVATE == $t_project_view_state ) {
				if( access_compare_level( $t_global_access_level, config_get( 'private_project_threshold', null, null, ALL_PROJECTS ) ) ) {
					return $t_global_access_level;
				} else {
					return ANYBODY;
				}
			} else {
				# project access not set, but the project is public
				return $t_global_access_level;
			}
		} else {
			# project specific access was set
			return $t_project_access_level;
		}
	}
}

/**
 * Check the current user's access against the given value and return true
 * if the user's access is equal to or higher, false otherwise.
 * @param integer|array $p_access_level Threshold representing an access level.
 * @param integer       $p_project_id   Integer representing project id to check access against.
 * @param integer|null  $p_user_id      Integer representing user id, defaults to null to use current user.
 * @return boolean whether user has access level specified
 * @access public
 */
function access_has_project_level( $p_access_level, $p_project_id = null, $p_user_id = null ) {
	# Short circuit the check in this case
	if( NOBODY == $p_access_level ) {
		return false;
	}

	if( null === $p_user_id ) {
		$p_user_id = auth_get_current_user_id();
	}
	if( null === $p_project_id ) {
		$p_project_id = helper_get_current_project();
	}

	$t_access_level = access_get_project_level( $p_project_id, $p_user_id );

	return access_compare_level( $t_access_level, $p_access_level );
}

/**
 * Check the current user's access against the given value, in each of the provided projects,
 * and return true if the user's access is equal to or higher in any of the projects, false otherwise.
 * @param integer|array|string  $p_access_level Parameter representing access level threshold, may be:
 *                                              - integer: for a simple threshold
 *                                              - array: for an array threshold
 *                                              - string: for a threshold option which will be evaluated
 *                                                 for each project context
 * @param array                 $p_project_ids  Array of project ids to check access against, default to null
 *                                               to use all user accesible projects
 * @param integer|null          $p_user_id      Integer representing user id, defaults to null to use current user.
 * @return boolean whether user has access level specified
 * @access public
 */
function access_has_any_project_level( $p_access_level, array $p_project_ids = null, $p_user_id = null ) {
	# Short circuit the check in this case
	if( NOBODY == $p_access_level ) {
		return false;
	}

	if( null === $p_user_id ) {
		$p_user_id = auth_get_current_user_id();
	}
	if( null === $p_project_ids ) {
		$p_project_ids = user_get_all_accessible_projects( $p_user_id );
	}

	# if config will be evaluated for each project, prepare a default value
	if( is_string( $p_access_level ) ) {
		$t_default = config_get( $p_access_level, null, $p_user_id, ALL_PROJECTS );
		if( null === $t_default ) {
			$t_default = config_get_global( $p_access_level );
		}
	}

	$t_check_level = $p_access_level;
	$t_has_access = false;
	foreach( $p_project_ids as $t_project_id ) {
		# If a config string is provided, evaluate for each project
		if( is_string( $p_access_level ) ) {
			$t_check_level = config_get( $p_access_level, $t_default, $p_user_id, $t_project_id );
		}
		if( access_has_project_level( $t_check_level, $t_project_id, $p_user_id ) ) {
			$t_has_access = true;
			break;
		}
	}

	return $t_has_access;
}

/**
 * Check if the user has the specified access level in any of the given projects
 * Refer to access_has_any_project_level() for detailed parameter information
 * @param integer|array|string $p_access_level  Parameter representing access level threshold
 * @param array $p_project_ids                  Array of project ids to check access against
 * @param integer|null $p_user_id
 */
function access_ensure_any_project_level( $p_access_level, array $p_project_ids = null, $p_user_id = null ) {
	if( !access_has_any_project_level( $p_access_level, $p_project_ids, $p_user_id ) ) {
		access_denied();
	}
}

/**
 * Check if the user has the specified access level for the given project
 * and deny access to the page if not
 * @see access_has_project_level
 * @param integer      $p_access_level Integer representing access level.
 * @param integer|null $p_project_id   Integer representing project id to check access against, defaults to null to use current project.
 * @param integer|null $p_user_id      Integer representing user identifier, defaults to null to use current user.
 * @access public
 * @return void
 */
function access_ensure_project_level( $p_access_level, $p_project_id = null, $p_user_id = null ) {
	if( !access_has_project_level( $p_access_level, $p_project_id, $p_user_id ) ) {
		access_denied();
	}
}

/**
 * Check whether the user has the specified access level for any project project
 * @param integer      $p_access_level Integer representing access level.
 * @param integer|null $p_user_id      Integer representing user id, defaults to null to use current user.
 * @return boolean whether user has access level specified
 * @access public
 */
function access_has_any_project( $p_access_level, $p_user_id = null ) {
	# Short circuit the check in this case
	if( NOBODY == $p_access_level ) {
		return false;
	}

	if( null === $p_user_id ) {
		$p_user_id = auth_get_current_user_id();
	}

	$t_projects = project_get_all_rows();
	foreach( $t_projects as $t_project ) {
		if( access_has_project_level( $p_access_level, $t_project['id'], $p_user_id ) ) {
			return true;
		}
	}

	return false;
}

/**
 * Check the current user's access against the given value and return true
 * if the user's access is equal to or higher, false otherwise.
 * This function looks up the bug's project and performs an access check
 * against that project
 * @param integer      $p_access_level Integer representing access level.
 * @param integer      $p_bug_id       Integer representing bug id to check access against.
 * @param integer|null $p_user_id      Integer representing user id, defaults to null to use current user.
 * @return boolean whether user has access level specified
 * @access public
 */
function access_has_bug_level( $p_access_level, $p_bug_id, $p_user_id = null ) {
	if( $p_user_id === null ) {
		$p_user_id = auth_get_current_user_id();
	}

	# Deal with not logged in silently in this case
	# @@@ we may be able to remove this and just error
	#     and once we default to anon login, we can remove it for sure
	if( empty( $p_user_id ) && !auth_is_user_authenticated() ) {
		return false;
	}

	$t_project_id = bug_get_field( $p_bug_id, 'project_id' );
	$t_bug_is_user_reporter = bug_is_user_reporter( $p_bug_id, $p_user_id );
	$t_access_level = access_get_project_level( $t_project_id, $p_user_id );

	# check limit_Reporter (Issue #4769)
	# reporters can view just issues they reported
	$t_limit_reporters = config_get( 'limit_reporters', null, $p_user_id, $t_project_id );
	if( $t_limit_reporters && !$t_bug_is_user_reporter ) {
		# Here we only need to check that the current user has an access level
		# higher than the lowest needed to report issues (report_bug_threshold).
		# To improve performance, esp. when processing for several projects, we
		# build a static array holding that threshold for each project
		static $s_thresholds = array();
		if( !isset( $s_thresholds[$t_project_id] ) ) {
			$t_report_bug_threshold = config_get( 'report_bug_threshold', null, $p_user_id, $t_project_id );
			if( empty( $t_report_bug_threshold ) ) {
				$s_thresholds[$t_project_id] = NOBODY;
			} else {
				$s_thresholds[$t_project_id] = access_threshold_min_level( $t_report_bug_threshold ) + 1;
			}
		}
		if( !access_compare_level( $t_access_level, $s_thresholds[$t_project_id] ) ) {
			return false;
		}
	}

	# If the bug is private and the user is not the reporter, then
	# they must also have higher access than private_bug_threshold
	if( !$t_bug_is_user_reporter && bug_get_field( $p_bug_id, 'view_state' ) == VS_PRIVATE ) {
		$t_private_bug_threshold = config_get( 'private_bug_threshold', null, $p_user_id, $t_project_id );
		return access_compare_level( $t_access_level, $t_private_bug_threshold )
			&& access_compare_level( $t_access_level, $p_access_level );
	}

	return access_compare_level( $t_access_level, $p_access_level );
}

/**
 * Filter the provided array of user ids to those who has the specified access level for the
 * specified bug.
 * @param  int $p_access_level   The access level.
 * @param  int $p_bug_id         The bug id.
 * @param  array $p_user_ids     The array of user ids.
 * @return array filtered array of user ids.
 */
function access_has_bug_level_filter( $p_access_level, $p_bug_id, $p_user_ids ) {
	$t_users_ids_with_access = array();
	foreach( $p_user_ids as $t_user_id ) {
		if( access_has_bug_level( $p_access_level, $p_bug_id, $t_user_id ) ) {
			$t_users_ids_with_access[] = $t_user_id;
		}
	}

	return $t_users_ids_with_access;
}

/**
 * Check if the user has the specified access level for the given bug
 * and deny access to the page if not
 * @see access_has_bug_level
 * @param integer      $p_access_level Integer representing access level.
 * @param integer      $p_bug_id       Integer representing bug id to check access against.
 * @param integer|null $p_user_id      Integer representing user id, defaults to null to use current user.
 * @return void
 * @access public
 */
function access_ensure_bug_level( $p_access_level, $p_bug_id, $p_user_id = null ) {
	if( !access_has_bug_level( $p_access_level, $p_bug_id, $p_user_id ) ) {
		access_denied();
	}
}

/**
 * Check the current user's access against the given value and return true
 * if the user's access is equal to or higher, false otherwise.
 * This function looks up the bugnote's bug and performs an access check
 * against that bug
 * @param integer      $p_access_level Integer representing access level.
 * @param integer      $p_bugnote_id   Integer representing bugnote id to check access against.
 * @param integer|null $p_user_id      Integer representing user id, defaults to null to use current user.
 * @return boolean whether user has access level specified
 * @access public
 */
function access_has_bugnote_level( $p_access_level, $p_bugnote_id, $p_user_id = null ) {
	if( null === $p_user_id ) {
		$p_user_id = auth_get_current_user_id();
	}

	$t_bug_id = bugnote_get_field( $p_bugnote_id, 'bug_id' );
	$t_project_id = bug_get_field( $t_bug_id, 'project_id' );

	# If the bug is private and the user is not the reporter, then the
	# the user must also have higher access than private_bug_threshold
	if( bugnote_get_field( $p_bugnote_id, 'view_state' ) == VS_PRIVATE && !bugnote_is_user_reporter( $p_bugnote_id, $p_user_id ) ) {
		$t_private_bugnote_threshold = config_get( 'private_bugnote_threshold', null, $p_user_id, $t_project_id );
		$p_access_level = max( $p_access_level, $t_private_bugnote_threshold );
	}

	return access_has_bug_level( $p_access_level, $t_bug_id, $p_user_id );
}

/**
 * Filter the provided array of user ids to those who has the specified access level for the
 * specified bugnote.
 * @param  int $p_access_level   The access level.
 * @param  int $p_bugnote_id     The bugnote id.
 * @param  array $p_user_ids     The array of user ids.
 * @return array filtered array of user ids.
 */
function access_has_bugnote_level_filter( $p_access_level, $p_bugnote_id, $p_user_ids ) {
	$t_users_ids_with_access = array();
	foreach( $p_user_ids as $t_user_id ) {
		if( access_has_bugnote_level( $p_access_level, $p_bugnote_id, $t_user_id ) ) {
			$t_users_ids_with_access[] = $t_user_id;
		}
	}

	return $t_users_ids_with_access;
}

/**
 * Check if the user has the specified access level for the given bugnote
 * and deny access to the page if not
 * @see access_has_bugnote_level
 * @param integer      $p_access_level Integer representing access level.
 * @param integer      $p_bugnote_id   Integer representing bugnote id to check access against.
 * @param integer|null $p_user_id      Integer representing user id, defaults to null to use current user.
 * @access public
 * @return void
 */
function access_ensure_bugnote_level( $p_access_level, $p_bugnote_id, $p_user_id = null ) {
	if( !access_has_bugnote_level( $p_access_level, $p_bugnote_id, $p_user_id ) ) {
		access_denied();
	}
}

/**
 * Check if the specified bug can be closed
 * @param BugData      $p_bug     Bug to check access against.
 * @param integer|null $p_user_id Integer representing user id, defaults to null to use current user.
 * @return boolean true if user can close the bug
 * @access public
 */
function access_can_close_bug( BugData $p_bug, $p_user_id = null ) {
	if( bug_is_closed( $p_bug->id ) ) {
		# Can't close a bug that's already closed
		return false;
	}

	if( null === $p_user_id ) {
		$p_user_id = auth_get_current_user_id();
	}

	# If allow_reporter_close is enabled, then reporters can close their own bugs
	# if they are in resolved status
	if( ON == config_get( 'allow_reporter_close', null, null, $p_bug->project_id )
		&& bug_is_user_reporter( $p_bug->id, $p_user_id )
		&& bug_is_resolved( $p_bug->id )
	) {
		return true;
	}

	$t_closed_status = config_get( 'bug_closed_status_threshold', null, null, $p_bug->project_id );
	$t_closed_status_threshold = access_get_status_threshold( $t_closed_status, $p_bug->project_id );
	return access_has_bug_level( $t_closed_status_threshold, $p_bug->id, $p_user_id );
}

/**
 * Make sure that the user can close the specified bug
 * @see access_can_close_bug
 * @param BugData      $p_bug     Bug to check access against.
 * @param integer|null $p_user_id Integer representing user id, defaults to null to use current user.
 * @access public
 * @return void
 */
function access_ensure_can_close_bug( BugData $p_bug, $p_user_id = null ) {
	if( !access_can_close_bug( $p_bug, $p_user_id ) ) {
		access_denied();
	}
}

/**
 * Check if the specified bug can be reopened
 * @param BugData      $p_bug     Bug to check access against.
 * @param integer|null $p_user_id Integer representing user id, defaults to null to use current user.
 * @return boolean whether user has access to reopen bugs
 * @access public
 */
function access_can_reopen_bug( BugData $p_bug, $p_user_id = null ) {
	if( !bug_is_resolved( $p_bug->id ) ) {
		# Can't reopen a bug that's not resolved
		return false;
	}

	if( $p_user_id === null ) {
		$p_user_id = auth_get_current_user_id();
	}

	$t_reopen_status = config_get( 'bug_reopen_status', null, null, $p_bug->project_id );

	# Reopen status must be reachable by workflow
	if( !bug_check_workflow( $p_bug->status, $t_reopen_status ) ) {
		return false;
	}

	# If allow_reporter_reopen is enabled, then reporters can always reopen
	# their own bugs as long as their access level is reporter or above
	if( ON == config_get( 'allow_reporter_reopen', null, null, $p_bug->project_id )
		&& bug_is_user_reporter( $p_bug->id, $p_user_id )
		&& access_has_project_level( config_get( 'report_bug_threshold', null, $p_user_id, $p_bug->project_id ), $p_bug->project_id, $p_user_id )
	) {
		return true;
	}

	# Other users's access level must allow them to reopen bugs
	$t_reopen_bug_threshold = config_get( 'reopen_bug_threshold', null, null, $p_bug->project_id );
	if( access_has_bug_level( $t_reopen_bug_threshold, $p_bug->id, $p_user_id ) ) {

		# User must be allowed to change status to reopen status
		$t_reopen_status_threshold = access_get_status_threshold( $t_reopen_status, $p_bug->project_id );
		return access_has_bug_level( $t_reopen_status_threshold, $p_bug->id, $p_user_id );
	}

	return false;
}

/**
 * Make sure that the user can reopen the specified bug.
 * Calls access_denied if user has no access to terminate script
 * @see access_can_reopen_bug
 * @param BugData      $p_bug     Bug to check access against.
 * @param integer|null $p_user_id Integer representing user id, defaults to null to use current user.
 * @access public
 * @return void
 */
function access_ensure_can_reopen_bug( BugData $p_bug, $p_user_id = null ) {
	if( !access_can_reopen_bug( $p_bug, $p_user_id ) ) {
		access_denied();
	}
}

/**
 * get the user's access level specific to this project.
 * return false (0) if the user has no access override here
 * @param integer $p_user_id    Integer representing user id.
 * @param integer $p_project_id Integer representing project id.
 * @return boolean|integer returns false (if no access) or an integer representing level of access
 * @access public
 */
function access_get_local_level( $p_user_id, $p_project_id ) {
	global $g_cache_access_matrix, $g_cache_access_matrix_project_ids;

	$p_project_id = (int)$p_project_id;
	$p_user_id = (int)$p_user_id;

	if( in_array( $p_project_id, $g_cache_access_matrix_project_ids ) ) {
		if( isset( $g_cache_access_matrix[$p_user_id][$p_project_id] ) ) {
			return $g_cache_access_matrix[$p_user_id][$p_project_id];
		} else {
			return false;
		}
	}

	$t_project_level = access_cache_matrix_user( $p_user_id );

	if( isset( $t_project_level[$p_project_id] ) ) {
		return $t_project_level[$p_project_id];
	} else {
		return false;
	}
}

/**
 * get the access level required to change the issue to the new status
 * If there is no specific differentiated access level, use the
 * generic update_bug_status_threshold.
 * @param integer $p_status     Status.
 * @param integer $p_project_id Default value ALL_PROJECTS.
 * @return integer integer representing user level e.g. DEVELOPER
 * @access public
 */
function access_get_status_threshold( $p_status, $p_project_id = ALL_PROJECTS ) {
	$t_thresh_array = config_get( 'set_status_threshold', null, null, $p_project_id );
	if( isset( $t_thresh_array[(int)$p_status] ) ) {
		return (int)$t_thresh_array[(int)$p_status];
	} else {
		if( $p_status == config_get( 'bug_submit_status', null, null, $p_project_id ) ) {
			return config_get( 'report_bug_threshold', null, null, $p_project_id );
		} else {
			return config_get( 'update_bug_status_threshold', null, null, $p_project_id );
		}
	}
}

/**
 * Given a access level, return the appropriate string for it
 * @param integer $p_access_level
 * @return string
 */
function access_level_get_string( $p_access_level ) {
	if( $p_access_level > ANYBODY ) {
		$t_access_level_string = get_enum_element( 'access_levels', $p_access_level );
	} else {
		$t_access_level_string = lang_get( 'no_access' );
	}
	return $t_access_level_string;
}

/**
 * Return the minimum access level, as integer, that matches the threshold.
 * $p_threshold may be a single value, or an array. If it is a single
 * value, returns that number. If it is an array, return the value of the
 * smallest element
 * @param integer|array $p_threshold         Access threshold
 * @return integer		Integer value for an access level.
 */
function access_threshold_min_level( $p_threshold ) {
	if( is_array( $p_threshold ) ) {
		if( empty( $p_threshold ) ) {
			return NOBODY;
		} else {
			sort( $p_threshold );
			return( reset( $p_threshold ) );
		}
	} else {
		return $p_threshold;
	}

}


text:
package com.technobitia.vimeo.response;

import java.util.Date;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonIgnoreProperties
public class AlbumInfoData {

    private String id;

    @JsonProperty("created_on")
    private Date creationDate;

    @JsonProperty("last_modified")
    private Date lastModified;

    private String title;
    private String description;
    private String url;
    private String thumbnail;

    @JsonProperty("total_videos")
    private int noVideos;

    @JsonProperty("user_id")
    private String userId;

    @JsonProperty("user_display_name")
    private String userName;

    @JsonProperty("user_url")
    private String userUrl;

    public String getId() {
        return id;
    }

    public Date getCreationDate() {
        return creationDate;
    }

    public Date getLastModified() {
        return lastModified;
    }

    public String getTitle() {
        return title;
    }

    public String getDescription() {
        return description;
    }

    public String getUrl() {
        return url;
    }

    public String getThumbnail() {
        return thumbnail;
    }

    public int getNoVideos() {
        return noVideos;
    }

    public String getUserId() {
        return userId;
    }

    public String getUserName() {
        return userName;
    }

    public String getUserUrl() {
        return userUrl;
    }

}

redpajama_set_name: RedPajamaGithub


text:
use strict;
use warnings;
package Mo::Golf;

our $VERSION = '0.31';

use PPI;

# This is the mapping of common names to shorter forms that still make some
# sense.
my %short_names = (
    (
        map {($_, substr($_, 0, 1))}
        qw(
            args builder class default exports features
            import method MoPKG name options self
        )
    ),
    build_subs => 'B',
    old_constructor => 'C',
    caller_pkg => 'P',
);

my %hands_off = map {($_,1)} qw'&import *import';

sub import {
    return unless @_ == 2 and $_[1] eq 'golf';
    binmode STDOUT;
    my $text = do { local $/; <> };
    print STDOUT golf( $text );
};

sub golf {
    my ( $text ) = @_;

    my $tree = PPI::Document->new( \$text );

    my %finder_subs = _finder_subs();

    my @order = qw( comments duplicate_whitespace whitespace trailing_whitespace );

    for my $name ( @order ) {
        my $elements = $tree->find( $finder_subs{$name} );
        die $@ if !defined $elements;
        $_->delete for @{ $elements || [] };
    }

    $tree->find( $finder_subs{$_} )
      for qw( del_superfluous_concat del_last_semicolon_in_block separate_version shorten_var_names );
    die $@ if $@;

    for my $name ( 'double_semicolon' ) {
        my $elements = $tree->find( $finder_subs{$name} );
        die $@ if !defined $elements;
        $_->delete for @{ $elements || [] };
    }

    return $tree->serialize . "\n";
}

sub tok { "PPI::Token::$_[0]" }

sub _finder_subs {
    return (
        comments => sub { $_[1]->isa( tok 'Comment' ) },

        duplicate_whitespace => sub {
            my ( $top, $current ) = @_;
            return 0 if !$current->isa( tok 'Whitespace' );

            $current->set_content(' ') if 1 < length $current->content;

            return 0 if !$current->next_token;
            return 0 if !$current->next_token->isa( tok 'Whitespace' );
            return 1;
        },

        whitespace => sub {
            my ( $top, $current ) = @_;
            return 0 if !$current->isa( tok 'Whitespace' );
            my $prev = $current->previous_token;
            my $next = $current->next_token;

            return 1 if $prev->isa( tok 'Number' ) and $next->isa( tok 'Operator' ) and $next->content =~ /^\W/; # my $P
            return 1 if $prev->isa( tok 'Word' )   and $next->isa( tok 'Operator' ) and $next->content =~ /^\W/; # my $P

            return 1 if $prev->isa( tok 'Symbol' )     and $next->isa( tok 'Operator' );         # $VERSION =
            return 1 if $prev->isa( tok 'Word' )       and $next->isa( tok 'Symbol' );           # my $P
            return 1 if $prev->isa( tok 'Word' )       and $next->isa( tok 'Structure' );        # sub {
            return 1 if $prev->isa( tok 'Word' )       and $next->isa( tok 'Quote::Double' );    # eval "
            return 1 if $prev->isa( tok 'Symbol' )     and $next->isa( tok 'Structure' );        # %a )
            return 1 if $prev->isa( tok 'ArrayIndex' ) and $next->isa( tok 'Operator' );         # $#_ ?
            return 1 if $prev->isa( tok 'Word' )       and $next->isa( tok 'Cast' );             # exists &$_
            return 0;
        },

        trailing_whitespace => sub {
            my ( $top, $current ) = @_;
            return 0 if !$current->isa( tok 'Whitespace' );
            my $prev = $current->previous_token;

            return 1 if $prev->isa( tok 'Structure' );                                           # ;[\n\s]
            return 1 if $prev->isa( tok 'Operator' ) and $prev->content =~ /\W$/;                # = 0.24
            return 1 if $prev->isa( tok 'Quote::Double' );                                       # " .
            return 1 if $prev->isa( tok 'Quote::Single' );                                       # ' }

            return 0;
        },

        double_semicolon => sub {
            my ( $top, $current ) = @_;
            return 0 if !$current->isa( tok 'Structure' );
            return 0 if $current->content ne ';';

            my $prev = $current->previous_token;

            return 0 if !$prev->isa( tok 'Structure' );
            return 0 if $prev->content ne ';';

            return 1;
        },

        del_last_semicolon_in_block => sub {
            my ( $top, $current ) = @_;
            return 0 if !$current->isa( 'PPI::Structure::Block' );

            my $last = $current->last_token;

            return 0 if !$last->isa( tok 'Structure' );
            return 0 if $last->content ne '}';

            my $maybe_semi = $last->previous_token;

            return 0 if !$maybe_semi->isa( tok 'Structure' );
            return 0 if $maybe_semi->content ne ';';

            $maybe_semi->delete;

            return 1;
        },

        del_superfluous_concat => sub {
            my ( $top, $current ) = @_;
            return 0 if !$current->isa( tok 'Operator' );

            my $prev = $current->previous_token;
            my $next = $current->next_token;

            return 0 if $current->content ne '.';
            return 0 if !$prev->isa( tok 'Quote::Double' );
            return 0 if !$next->isa( tok 'Quote::Double' );

            $current->delete;
            $prev->set_content( $prev->{separator} . $prev->string . $next->string . $prev->{separator} );
            $next->delete;

            return 1;
        },

        separate_version => sub {
            my ( $top, $current ) = @_;
            return 0 if !$current->isa( 'PPI::Statement' );

            my $first = $current->first_token;
            return 0 if $first->content ne '$VERSION';

            $current->$_( PPI::Token::Whitespace->new( "\n" ) ) for qw( insert_before insert_after );

            return 1;
        },

        shorten_var_names => sub {
            my ( $top, $current ) = @_;
            return 0 if !$current->isa( tok 'Symbol' );

            my $long_name = $current->canonical;

            return 1 if $hands_off{$long_name};
            (my $name = $long_name) =~ s/^([\$\@\%])// or die $long_name;
            my $sigil = $1;
            die "variable $long_name conflicts with shortened var name"
                if grep {
                    $name eq $_
                } values %short_names;

            my $short_name = $short_names{$name};
            $current->set_content( "$sigil$short_name" ) if $short_name;

            return 1;
        },
    );
}

=head1 SYNOPSIS

    perl -MMo::Golf=golf < src/Mo/foo.pm > lib/Mo/foo.pm

=head1 DESCRIPTION

This is the module that is respeonsible for taking Mo code (which is
documented and fairly readable) and reducing it to a single undecipherable
line.


text:
package com.perforce.p4java.tests.dev.unit.features123;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import com.perforce.p4java.tests.MockCommandCallback;
import com.perforce.p4java.tests.dev.UnitTestDevServerManager;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import com.perforce.p4java.client.IClient;
import com.perforce.p4java.exception.P4JavaException;
import com.perforce.p4java.option.server.LoginOptions;
import com.perforce.p4java.server.CmdSpec;
import com.perforce.p4java.server.IOptionsServer;
import com.perforce.p4java.server.ServerFactory;
import com.perforce.p4java.server.callback.ICommandCallback;
import com.perforce.p4java.tests.dev.annotations.Jobs;
import com.perforce.p4java.tests.dev.annotations.TestId;
import com.perforce.p4java.tests.dev.unit.P4JavaTestCase;

/**
 * Test progress indicator (p4 -I <command>). Currently, only certain Perforce
 * commands have progress indicator support. And, it only works with Perforce
 * server 12.2 or above.
 */
@Jobs({ "job057603" })
@TestId("Dev123_ProgressIndicatorTest")
public class ProgressIndicatorTest extends P4JavaTestCase {

	IOptionsServer server = null;
	IClient client = null;

	/**
	 * @BeforeClass annotation to a method to be run before all the tests in a
	 *              class.
	 */
	@BeforeClass
	public static void oneTimeSetUp() {
		// one-time initialization code (before all the tests).
		// p4ic4idea: use local server
		UnitTestDevServerManager.INSTANCE.startTestClass();
	}

	/**
	 * @AfterClass annotation to a method to be run after all the tests in a
	 *             class.
	 */
	@AfterClass
	public static void oneTimeTearDown() {
		// one-time cleanup code (after all the tests).
		// p4ic4idea: use local server
		UnitTestDevServerManager.INSTANCE.endTestClass();
	}

	/**
	 * @Before annotation to a method to be run before each test in a class.
	 */
	@Before
	public void setUp() {
		// initialization code (before each test).
		try {
			Properties props = new Properties();

			props.put("enableProgress", "true");

			server = ServerFactory
					.getOptionsServer(getServerUrlString(), props);
			assertNotNull(server);

			// Register callback
			server.registerCallback(new MockCommandCallback());
			// Connect to the server.
			server.connect();
			if (server.isConnected()) {
				if (server.supportsUnicode()) {
					server.setCharsetName("utf8");
				}
			}

			// Set the server user
			server.setUserName(this.userName);

			// Login using the normal method
			server.login(this.password, new LoginOptions());

			client = getDefaultClient(server);
			assertNotNull(client);
			server.setCurrentClient(client);
		} catch (P4JavaException e) {
			fail("Unexpected exception: " + e.getLocalizedMessage());
		} catch (URISyntaxException e) {
			fail("Unexpected exception: " + e.getLocalizedMessage());
		}
	}

	/**
	 * @After annotation to a method to be run after each test in a class.
	 */
	@After
	public void tearDown() {
		// cleanup code (after each test).
		if (server != null) {
			this.endServerSession(server);
		}
	}

	/**
	 * Test progress indicator (p4 -I <command>) using execMapCmd().
	 */
	@Test
	public void testProgressIndicatorMapCmd() {

		try {
			Map<String, Object>[] result = server.execMapCmd(
					CmdSpec.SYNC.toString(), new String[] { "-q", "-f",
							"//depot/112Dev/CopyFilesTest/..." }, null);
			assertNotNull(result);
			assertTrue(result.length > 0);

			assertNotNull(result[result.length-1]);
			assertTrue(result[result.length-1].containsKey("handle"));
			assertNotNull(result[result.length-1].get("handle"));
			assertEquals((String)result[result.length-1].get("handle"), "progress");

		} catch (P4JavaException e) {
			fail("Unexpected exception: " + e.getLocalizedMessage());
		}
	}

	/**
	 * Test progress indicator (p4 -I <command>) using execStreamCmd().
	 *
	 * test "p4 -I sync -q"
	 */
	@Test
	public void testProgressIndicatorStreamCmd() {

		InputStream is = null;
		try {
			is = server.execStreamCmd(CmdSpec.SYNC.toString(), new String[] {
					"-q", "-f", "//depot/112Dev/CopyFilesTest/..." });
			assertNotNull(is);
			BufferedReader br = new BufferedReader(new InputStreamReader(is));

			// Capture lines
			List<String> lines = new ArrayList<String>();
			String line;
			while ((line = br.readLine()) != null) {
				lines.add(line);
			}
			br.close();

			// Should contain at least one line
			assertTrue(lines.size() > 0);

			assertNotNull(lines.get(lines.size()-1));
			assertTrue(lines.get(lines.size()-1).contains("finishing"));

		} catch (P4JavaException e) {
			fail("Unexpected exception: " + e.getLocalizedMessage());
		} catch (IOException e) {
			fail("Unexpected exception: " + e.getLocalizedMessage());
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					// Can't do anything else here...
				}
			}
		}
	}
}


text:
<?php

namespace Doctrine\ODM\MongoDB\Tests\Functional\Ticket;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

/**
 * @author Vadim Tyukov <brainreflex@gmail.com>
 * @since 6/26/12
 */
class GH232Test extends \Doctrine\ODM\MongoDB\Tests\BaseTest
{
    public function testReferencedDocumentInsideEmbeddedDocument()
    {
        /* PARENT DOCUMENT */
        $product = new Product('Product');
        /* END PARENT DOCUMENT */

        /* ADD EMBEDDED DOCUMENT */
        $sub_product = new SubProduct();
        $product->subproducts->add($sub_product);

        $price = new Price();
        $sub_product->prices->add($price);
        /* END ADD EMBEDDED DOCUMENT */

        // persist & double flush
        $this->dm->persist($product);
        $this->dm->flush();
        $this->dm->flush();
        $this->dm->clear();

        $product = $this->dm->getRepository(__NAMESPACE__ . '\Product')->findOneByName('Product');

        $this->assertEquals(1, $product->subproducts->count());
        $this->assertEquals(1, $product->subproducts[0]->prices->count());
    }
}

/** @ODM\Document */
class Product
{
    /** @ODM\Id */
    protected $id;

    /** @ODM\String */
    public $name;

    /** @ODM\EmbedMany(targetDocument="Price") */
    public $prices = array();

    /** @ODM\EmbedMany(targetDocument="SubProduct") */
    public $subproducts = array();

    public function __construct($name)
    {
        $this->name = $name;
        $this->subproducts = new ArrayCollection();
    }
}

/** @ODM\EmbeddedDocument */
class SubProduct
{
    /** @ODM\EmbedMany(targetDocument="Price") */
    public $prices = array();

    public function __construct()
    {
        $this->prices = new ArrayCollection();
    }
}

/** @ODM\EmbeddedDocument */
class Price
{
    /** @ODM\String */
    public $price;
}


text:
package org.apache.synapse.samples.framework.tests.transport;

import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.synapse.samples.framework.SynapseTestCase;
import org.apache.synapse.samples.framework.clients.BasicHttpClient;
import org.apache.synapse.samples.framework.clients.HttpResponse;

import java.util.List;
import java.util.Map;

public class Sample10101 extends SynapseTestCase {

    public static final byte[] TEST_PAYLOAD = "<test>foo</test>".getBytes();

    public Sample10101() {
        super(10101);
    }

    public void testChunking() throws Exception {
        BasicHttpClient client = new BasicHttpClient();
        HttpResponse response = client.doPost("http://127.0.0.1:8280/test/chunked",
                TEST_PAYLOAD, "application/xml");
        assertEquals(HttpStatus.SC_OK, response.getStatus());
        Map<String,List<String>> headers = response.getBodyAsMap();
        assertTrue(headers.containsKey(HttpHeaders.TRANSFER_ENCODING));
        assertFalse(headers.containsKey(HttpHeaders.CONTENT_LENGTH));
        assertEquals("chunked", headers.get(HttpHeaders.TRANSFER_ENCODING).get(0));
    }

    public void testDisableChunking() throws Exception {
        BasicHttpClient client = new BasicHttpClient();
        HttpResponse response = client.doPost("http://127.0.0.1:8280/test/content_length",
                TEST_PAYLOAD, "application/xml");
        assertEquals(HttpStatus.SC_OK, response.getStatus());
        Map<String,List<String>> headers = response.getBodyAsMap();
        assertFalse(headers.containsKey(HttpHeaders.TRANSFER_ENCODING));
        assertTrue(headers.containsKey(HttpHeaders.CONTENT_LENGTH));
        assertEquals(TEST_PAYLOAD.length, Integer.parseInt(headers.get(
                HttpHeaders.CONTENT_LENGTH).get(0)));
    }

}


text:
@implementation Song

@synthesize artist, title, album, highUrl, stationId, nrating,
  albumUrl, artistUrl, titleUrl, art, token, medUrl, lowUrl, playDate;

#pragma mark - NSObject

- (BOOL) isEqual:(id)object {
  return [token isEqual:[object token]];
}

- (NSString *)description {
  return [NSString stringWithFormat:@"<%@ %p %@ - %@>", NSStringFromClass(self.class), self, self.artist, self.title];
}

#pragma mark - NSCoding

- (id) initWithCoder: (NSCoder *)coder {
  if ((self = [super init])) {
    [self setArtist:[coder decodeObjectForKey:@"artist"]];
    [self setTitle:[coder decodeObjectForKey:@"title"]];
    [self setAlbum:[coder decodeObjectForKey:@"album"]];
    [self setArt:[coder decodeObjectForKey:@"art"]];
    [self setHighUrl:[coder decodeObjectForKey:@"highUrl"]];
    [self setMedUrl:[coder decodeObjectForKey:@"medUrl"]];
    [self setLowUrl:[coder decodeObjectForKey:@"lowUrl"]];
    [self setStationId:[coder decodeObjectForKey:@"stationId"]];
    [self setNrating:[coder decodeObjectForKey:@"nrating"]];
    [self setAlbumUrl:[coder decodeObjectForKey:@"albumUrl"]];
    [self setArtistUrl:[coder decodeObjectForKey:@"artistUrl"]];
    [self setTitleUrl:[coder decodeObjectForKey:@"titleUrl"]];
    [self setToken:[coder decodeObjectForKey:@"token"]];
    [self setPlayDate:[coder decodeObjectForKey:@"playDate"]];
  }
  return self;
}

- (void) encodeWithCoder: (NSCoder *)coder {
  NSDictionary *info = [self toDictionary];
  for(id key in info) {
    [coder encodeObject:info[key] forKey:key];
  }
}

#pragma mark - NSDistributedNotification user info

- (NSDictionary*) toDictionary {
  NSMutableDictionary *info = [NSMutableDictionary dictionary];
  [info setValue:artist forKey:@"artist"];
  [info setValue:title forKey:@"title"];
  [info setValue:album forKey:@"album"];
  [info setValue:art forKey:@"art"];
  [info setValue:lowUrl forKey:@"lowUrl"];
  [info setValue:medUrl forKey:@"medUrl"];
  [info setValue:highUrl forKey:@"highUrl"];
  [info setValue:stationId forKey:@"stationId"];
  [info setValue:nrating forKey:@"nrating"];
  [info setValue:albumUrl forKey:@"albumUrl"];
  [info setValue:artistUrl forKey:@"artistUrl"];
  [info setValue:titleUrl forKey:@"titleUrl"];
  [info setValue:token forKey:@"token"];
  [info setValue:playDate forKey:@"playDate"];
  return info;
}

#pragma mark - Object Specifier

- (NSScriptObjectSpecifier *) objectSpecifier {
  NSScriptClassDescription *appDesc =
  [NSScriptClassDescription classDescriptionForClass:[NSApp class]];

  // currently, the only way to get a reference to a song
  // - if the playback history gets exposed, then publish it differently
  return [[NSPropertySpecifier alloc]
          initWithContainerClassDescription:appDesc containerSpecifier:nil key:@"currentSong"];
}

#pragma mark - Reference to station

- (Station*) station {
  return [Station stationForToken:[self stationId]];
}

#pragma mark - Formatted play date

- (NSString *)playDateString {
  if (self.playDate == nil)
    return nil;

  static NSDateFormatter *songDateFormatter = nil;
  if (songDateFormatter == nil) {
    songDateFormatter = [[NSDateFormatter alloc] init];
    songDateFormatter.dateStyle = NSDateFormatterShortStyle;
    songDateFormatter.timeStyle = NSDateFormatterShortStyle;
    songDateFormatter.doesRelativeDateFormatting = YES;
  }

  return [songDateFormatter stringFromDate:playDate];
}

@end


text:
using System.Collections.Generic;

namespace ClouDeveloper.OpenAPI.KolisNet.Search
{
    /// <summary>
    /// KolisSearchResponse
    /// </summary>
    public class KolisSearchResponse : List<BibliographyInfo>
    {
        /// <summary>
        /// Gets or sets the total.
        /// </summary>
        /// <value>
        /// The total.
        /// </value>
        public int Total { get; set; }
    }
}


text:
using Cofoundry.Core.ResourceFiles;
using System.Reflection;

namespace Cofoundry.Domain;

/// <summary>
/// A file source for files embedded in an assembly.
/// </summary>
/// <inheritdoc/>
public class EmbeddedResourceFileSource : IFileSource
{
    /// <summary>
    /// Creates a new EmbeddedResourceFileSource instance.
    /// </summary>
    /// <param name="assembly">The assembly containing the embedded resource file.</param>
    /// <param name="path">
    /// <para>
    /// The path to the embedded resource without the file name. An embedded resource
    /// path is usually formed from the default assembly namespace and the folder
    /// path, delimited by '.' (period) e.g. "Cofoundry.Domain.ExampleParentFolder.ExampleChildFolder"
    /// </para>
    /// <para>
    /// Note that special characters such as spaces and dashes are replaced by underscores
    /// in embedded resource names, however this conversion is done automatically for you
    /// during construction.
    /// </para>
    /// </param>
    /// <param name="fileName">
    /// <para>
    /// The file name including file extensions e.g. "myFile.jpg".
    /// </para>
    /// </param>
    public EmbeddedResourceFileSource(
        Assembly assembly,
        string path,
        string fileName
        )
    {
        ArgumentNullException.ThrowIfNull(assembly);
        ArgumentEmptyException.ThrowIfNullOrWhitespace(path);
        ArgumentEmptyException.ThrowIfNullOrWhitespace(fileName);

        Assembly = assembly;
        FileName = fileName;
        FullPath = EmbeddedResourcePathFormatter.CleanPath(path) + "." + fileName;
    }

    /// <summary>
    /// Creates a new EmbeddedResourceFileSource instance.
    /// </summary>
    /// <param name="assembly">The assembly containing the embedded resource file.</param>
    /// <param name="fileName">The name of the file with an extention e.g. "MyFile.txt".</param>
    /// <param name="fullPath">The full embedded resource path e.g. "MyAssembly.MyFolder.MyFile.txt"</param>
    /// <param name="mimeType">The mime type of the file.</param>
    public EmbeddedResourceFileSource(
        Assembly assembly,
        string fileName,
        string fullPath,
        string mimeType
        )
    {
        ArgumentNullException.ThrowIfNull(assembly);
        ArgumentEmptyException.ThrowIfNullOrWhitespace(fileName);
        ArgumentEmptyException.ThrowIfNullOrWhitespace(fileName);

        Assembly = assembly;
        FileName = fileName;
        FullPath = fullPath;
        MimeType = mimeType;
    }

    /// <summary>
    /// The name of the file including file extension.
    /// </summary>
    public string FileName { get; private set; }

    /// <summary>
    /// Optional mime/content type associated with the file, if it is known. For
    /// embedded resources this is not often known.
    /// </summary>
    public string MimeType { get; private set; }

    /// <summary>
    /// The full embedded resource path including the namespace, folder
    /// path and file name e.g. "MyAssembly.MyFolder.MyFile.txt".
    /// </summary>
    public string FullPath { get; private set; }

    /// <summary>
    /// The assembly containing the embedded resource file.
    /// </summary>
    public Assembly Assembly { get; private set; }

    /// <summary>
    /// Opens a new stream of the file contents. The callee is responsible for
    /// disposing of the stream.
    /// </summary>
    public Task<Stream> OpenReadStreamAsync()
    {
        return Task.FromResult(Assembly.GetManifestResourceStream(FullPath));
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.hive;

import com.facebook.presto.hive.metastore.Storage;
import com.facebook.presto.hive.metastore.StorageFormat;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import io.airlift.units.DataSize;
import org.testng.annotations.Test;

import java.util.Optional;
import java.util.OptionalInt;

import static com.facebook.presto.hive.CacheQuotaRequirement.NO_CACHE_REQUIREMENT;
import static com.facebook.presto.hive.CacheQuotaScope.PARTITION;
import static com.facebook.presto.hive.TestHivePageSink.getColumnHandles;
import static com.facebook.presto.spi.schedule.NodeSelectionStrategy.NO_PREFERENCE;
import static com.facebook.presto.testing.assertions.Assert.assertEquals;

public class TestHivePageSourceProvider
{
    private static final String SCHEMA_NAME = "schema";
    private static final String TABLE_NAME = "table";
    private static final String PARTITION_NAME = "partition";

    @Test
    public void testGenerateCacheQuota()
    {
        HiveClientConfig config = new HiveClientConfig();

        HiveSplit split = new HiveSplit(
                SCHEMA_NAME,
                TABLE_NAME,
                PARTITION_NAME,
                "file://test",
                0,
                10,
                10,
                new Storage(
                        StorageFormat.create(config.getHiveStorageFormat().getSerDe(), config.getHiveStorageFormat().getInputFormat(), config.getHiveStorageFormat().getOutputFormat()),
                        "location",
                        Optional.empty(),
                        false,
                        ImmutableMap.of(),
                        ImmutableMap.of()),
                ImmutableList.of(),
                ImmutableList.of(),
                OptionalInt.empty(),
                OptionalInt.empty(),
                NO_PREFERENCE,
                getColumnHandles().size(),
                TableToPartitionMapping.empty(),
                Optional.empty(),
                false,
                Optional.empty(),
                NO_CACHE_REQUIREMENT,
                Optional.empty(),
                ImmutableMap.of(),
                ImmutableSet.of());

        CacheQuota cacheQuota = HivePageSourceProvider.generateCacheQuota(split);
        CacheQuota expectedCacheQuota = new CacheQuota(".", Optional.empty());
        assertEquals(cacheQuota, expectedCacheQuota);

        split = new HiveSplit(
                SCHEMA_NAME,
                TABLE_NAME,
                PARTITION_NAME,
                "file://test",
                0,
                10,
                10,
                new Storage(
                        StorageFormat.create(config.getHiveStorageFormat().getSerDe(), config.getHiveStorageFormat().getInputFormat(), config.getHiveStorageFormat().getOutputFormat()),
                        "location",
                        Optional.empty(),
                        false,
                        ImmutableMap.of(),
                        ImmutableMap.of()),
                ImmutableList.of(),
                ImmutableList.of(),
                OptionalInt.empty(),
                OptionalInt.empty(),
                NO_PREFERENCE,
                getColumnHandles().size(),
                TableToPartitionMapping.empty(),
                Optional.empty(),
                false,
                Optional.empty(),
                new CacheQuotaRequirement(PARTITION, Optional.of(DataSize.succinctDataSize(1, DataSize.Unit.MEGABYTE))),
                Optional.empty(),
                ImmutableMap.of(),
                ImmutableSet.of());

        cacheQuota = HivePageSourceProvider.generateCacheQuota(split);
        expectedCacheQuota = new CacheQuota(SCHEMA_NAME + "." + TABLE_NAME + "." + PARTITION_NAME, Optional.of(DataSize.succinctDataSize(1, DataSize.Unit.MEGABYTE)));
        assertEquals(cacheQuota, expectedCacheQuota);
    }
}


text:
#include <aws/codestar/model/UserProfileSummary.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace CodeStar
{
namespace Model
{

UserProfileSummary::UserProfileSummary() :
    m_userArnHasBeenSet(false),
    m_displayNameHasBeenSet(false),
    m_emailAddressHasBeenSet(false),
    m_sshPublicKeyHasBeenSet(false)
{
}

UserProfileSummary::UserProfileSummary(const JsonValue& jsonValue) :
    m_userArnHasBeenSet(false),
    m_displayNameHasBeenSet(false),
    m_emailAddressHasBeenSet(false),
    m_sshPublicKeyHasBeenSet(false)
{
  *this = jsonValue;
}

UserProfileSummary& UserProfileSummary::operator =(const JsonValue& jsonValue)
{
  if(jsonValue.ValueExists("userArn"))
  {
    m_userArn = jsonValue.GetString("userArn");

    m_userArnHasBeenSet = true;
  }

  if(jsonValue.ValueExists("displayName"))
  {
    m_displayName = jsonValue.GetString("displayName");

    m_displayNameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("emailAddress"))
  {
    m_emailAddress = jsonValue.GetString("emailAddress");

    m_emailAddressHasBeenSet = true;
  }

  if(jsonValue.ValueExists("sshPublicKey"))
  {
    m_sshPublicKey = jsonValue.GetString("sshPublicKey");

    m_sshPublicKeyHasBeenSet = true;
  }

  return *this;
}

JsonValue UserProfileSummary::Jsonize() const
{
  JsonValue payload;

  if(m_userArnHasBeenSet)
  {
   payload.WithString("userArn", m_userArn);

  }

  if(m_displayNameHasBeenSet)
  {
   payload.WithString("displayName", m_displayName);

  }

  if(m_emailAddressHasBeenSet)
  {
   payload.WithString("emailAddress", m_emailAddress);

  }

  if(m_sshPublicKeyHasBeenSet)
  {
   payload.WithString("sshPublicKey", m_sshPublicKey);

  }

  return payload;
}

} // namespace Model
} // namespace CodeStar
} // namespace Aws


text:
/*
 *  eXist SQL Module Extension GetJNDIConnectionFunction
 *  Copyright (C) 2008 Adam Retter <adam@exist-db.org>
 *  www.adamretter.co.uk
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *  $Id: GetConnectionFunction.java 4126 2006-09-18 21:20:17 +0000 (Mon, 18 Sep 2006) deliriumsky $
 */

package org.exist.xquery.modules.sql;

import java.sql.Connection;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import org.exist.dom.QName;
import org.exist.xquery.BasicFunction;
import org.exist.xquery.Cardinality;
import org.exist.xquery.FunctionSignature;
import org.exist.xquery.XPathException;
import org.exist.xquery.XQueryContext;
import org.exist.xquery.value.IntegerValue;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.SequenceType;
import org.exist.xquery.value.Type;

/**
 * eXist SQL Module Extension GetJNDIConnectionFunction
 *
 * Get a connection to a SQL Database via JNDI
 *
 * @author Adam Retter <adam@exist-db.org>
 * @serial 2008-05-19
 * @version 1.2
 *
 * @see org.exist.xquery.BasicFunction#BasicFunction(org.exist.xquery.XQueryContext,
 *      org.exist.xquery.FunctionSignature)
 */
public class GetJNDIConnectionFunction extends BasicFunction {

	public final static FunctionSignature[] signatures = {
			new FunctionSignature(
					new QName("get-jndi-connection", SQLModule.NAMESPACE_URI,
							SQLModule.PREFIX),
					"Open's a connection to a SQL Database. Expects a JNDI name in $a. Returns an xs:long representing the connection handle.",
					new SequenceType[] {
							new SequenceType(Type.STRING,
									Cardinality.EXACTLY_ONE),
							new SequenceType(Type.STRING,
									Cardinality.EXACTLY_ONE) },
					new SequenceType(Type.LONG, Cardinality.ZERO_OR_ONE)),

			new FunctionSignature(
					new QName("get-jndi-connection", SQLModule.NAMESPACE_URI,
							SQLModule.PREFIX),
					"Open's a connection to a SQL Database. Expects a JNDI name in $a, a username in $b and a password in $c. Returns an xs:long representing the connection handle.",
					new SequenceType[] {
							new SequenceType(Type.STRING,
									Cardinality.EXACTLY_ONE),
							new SequenceType(Type.STRING,
									Cardinality.EXACTLY_ONE),
							new SequenceType(Type.STRING,
									Cardinality.EXACTLY_ONE) },
					new SequenceType(Type.LONG, Cardinality.ZERO_OR_ONE)) };

	/**
	 * GetJNDIConnectionFunction Constructor
	 *
	 * @param context
	 *            The Context of the calling XQuery
	 */
	public GetJNDIConnectionFunction(XQueryContext context,
			FunctionSignature signature) {
		super(context, signature);
	}

	/**
	 * evaluate the call to the xquery get-jndi-connection() function, it is
	 * really the main entry point of this class
	 *
	 * @param args
	 *            arguments from the get-jndi-connection() function call
	 * @param contextSequence
	 *            the Context Sequence to operate on (not used here internally!)
	 * @return A xs:long representing a handle to the connection
	 *
	 * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[],
	 *      org.exist.xquery.value.Sequence)
	 */
	public Sequence eval(Sequence[] args, Sequence contextSequence)
			throws XPathException {
		// was a JNDI name specified?
		if (args[0].isEmpty())
			return Sequence.EMPTY_SEQUENCE;

		try {
			Connection con = null;

			// get the JNDI source
			String jndiName = args[0].getStringValue();
			Context ctx = new InitialContext();
			DataSource ds = (DataSource) ctx.lookup(jndiName);

			// try and get the connection
			if (args.length == 1) {
				con = ds.getConnection();
			}
			if (args.length == 3) {
				String jndiUser = args[1].getStringValue();
				String jndiPassword = args[2].getStringValue();

				con = ds.getConnection(jndiUser, jndiPassword);
			}

			// store the connection and return the uid handle of the connection
			return new IntegerValue(SQLModule.storeConnection(context, con));
		} catch (Exception e) {
			throw new XPathException(e.getMessage());
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<project name="Kata 1" default="phpunit">

    <target name="composer"
            description="Composer install">
        <exec executable="composer">
            <arg value="install"/>
        </exec>
    </target>

    <target name="phpunit"
            description="Run unit tests using PHPUnit">
        <exec executable="vendor/bin/phpunit">
            <arg value="-c"/>
            <arg value="phpunit.xml.dist"/>
        </exec>
    </target>

    <target name="cs" description="">
        <parallel>
            <exec executable="php-cs-fixer">
                <arg line="fix src --level=symfony"/>
            </exec>
            <exec executable="php-cs-fixer">
                <arg line="fix tests --level=symfony"/>
            </exec>
        </parallel>
        <parallel>
            <exec executable="php-formatter">
                <arg line="formatter:header:fix src"/>
            </exec>
            <exec executable="php-formatter">
                <arg line="formatter:header:fix tests"/>
            </exec>
        </parallel>
        <parallel>
            <exec executable="php-formatter">
                <arg line="formatter:use:sort src"/>
            </exec>
            <exec executable="php-formatter">
                <arg line="formatter:use:sort tests"/>
            </exec>
        </parallel>
    </target>
</project>