text:
<?php

if (!defined('SITE_DIR'))
{
	exit;
}

if ($mode == 'register' && $bb_cfg['new_user_reg_disabled'])
{
	message_die(GENERAL_MESSAGE, $lang['new_user_reg_disabled']);
}

if ($mode == 'register') {
    message_die(GENERAL_MESSAGE, 'Регистрация новых пользователей закрыта');
}

if( isset($_SERVER['HTTP_PROVIDER']) && $_SERVER['HTTP_PROVIDER'] != 'local' && $mode == 'register' )
{
	message_die(GENERAL_MESSAGE, 'Регистрация доступна только из локальной сети Билайн-Калуга.');
}

array_deep($_POST, 'trim');

$unhtml_specialchars_match = array('#>#', '#<#', '#"#', '#&#');
$unhtml_specialchars_replace = array('>', '<', '"', '&');

$default_user_opt = array(
	'viewemail'        => 0,
	'attachsig'        => 1,
	'hide_porn_forums' => 0,
);

// ---------------------------------------
// Load agreement template since user has not yet
// agreed to registration conditions/coppa
//
function show_coppa()
{
	global $userdata, $template, $lang;

	$template->assign_vars(array(
		'REGISTRATION' => $lang['Registration'],
		"AGREE_OVER_13" => $lang['Agree_over_13'],
		'DO_NOT_AGREE' => $lang['Agree_not'],

		"U_AGREE_OVER13" => append_sid("profile.php?mode=register&agreed=true"),
	));

	print_page('agreement.tpl');
}
//
// ---------------------------------------

$user_actkey = $signature = $username = $cur_password = $confirm_code = $email = '';
$error = FALSE;
$error_msg = '';

$template->assign_vars(array(
	'PAGE_TITLE' => ($mode == 'editprofile') ? $lang['Edit_profile'] : $lang['REGISTER'],
));

if ( $mode == 'register' && !isset($_POST['agreed']) && !isset($_GET['agreed']) )
{
	show_coppa();
}

$coppa = ( empty($_POST['coppa']) && empty($_GET['coppa']) ) ? 0 : TRUE;

//
// Check and initialize some variables if needed
//
if (
	isset($_POST['submit']) ||
	isset($_POST['avatargallery']) ||
	isset($_POST['submitavatar']) ||
	isset($_POST['cancelavatar']) ||
	$mode == 'register' )
{
	require SITE_DIR . 'includes/functions_validate.php';
	require SITE_DIR . 'includes/bbcode.php';
	require SITE_DIR . 'includes/functions_post.php';

	if ( $mode == 'editprofile' )
	{
		$user_id = intval($_POST['user_id']);
		$current_email = trim(htmlspecialchars($_POST['current_email']));
	}

	$strip_var_list = array('email' => 'email', 'icq' => 'icq', 'aim' => 'aim', 'msn' => 'msn', 'yim' => 'yim', 'website' => 'website', 'location' => 'location', 'occupation' => 'occupation', 'interests' => 'interests', 'confirm_code' => 'cfmcd');

	// Strip all tags from data ... may p**s some people off, bah, strip_tags is
	// doing the job but can still break HTML output ... have no choice, have
	// to use htmlspecialchars ... be prepared to be moaned at.
	foreach ($strip_var_list as $var => $param)
	{
		$$var = '';
		if ( !empty($_POST[$param]) )
		{
			$$var = trim(htmlspecialchars($_POST[$param]));
		}
	}

	$username = ( !empty($_POST['username']) ) ? phpbb_clean_username($_POST['username']) : '';

	$trim_var_list = array('cur_password' => 'cur_password', 'new_password' => 'new_password', 'password_confirm' => 'password_confirm', 'signature' => 'signature');

	foreach ($trim_var_list as $var => $param)
	{
		$$var = '';
		if ( !empty($_POST[$param]) )
		{
			$$var = trim($_POST[$param]);
		}
	}

	$signature = str_replace('
', "\n", $signature);

	// Run some validation on the optional fields. These are pass-by-ref, so they'll be changed to
	// empty strings if they fail.
	validate_optional_fields($icq, $aim, $msn, $yim, $website, $location, $occupation, $interests, $signature);

	$allowviewonline = ( isset($_POST['hideonline']) ) ? ( ($_POST['hideonline']) ? 0 : TRUE ) : TRUE;
	$notifyreply = ( isset($_POST['notifyreply']) ) ? ( ($_POST['notifyreply']) ? TRUE : 0 ) : 0;
	$notifypm = ( isset($_POST['notifypm']) ) ? ( ($_POST['notifypm']) ? TRUE : 0 ) : TRUE;
	$sid = (isset($_POST['sid'])) ? $_POST['sid'] : 0;

	if ($mode == 'register')
	{
		$viewemail = !empty($_POST['viewemail']) ? 1 : $default_user_opt['viewemail'];
		$attachsig = !empty($_POST['attachsig']) ? 1 : $default_user_opt['attachsig'];
		$hide_porn_forums = $_POST['hide_porn_forums'] = $default_user_opt['hide_porn_forums'];
	}
	else
	{
		$viewemail = !empty($_POST['viewemail']);
		$attachsig = !empty($_POST['attachsig']);
		$hide_porn_forums = !empty($_POST['hide_porn_forums']);
	}

	// language
	$user_lang = $bb_cfg['board_lang'];

	if ($mode == 'editprofile' && !empty($_POST['language']))
	{
		if (preg_match('/^[a-z_]+$/i', $_POST['language']))
		{
			if ($_POST['language'] != $bb_cfg['board_lang'])
			{
				$user_lang = $_POST['language'];
			}
		}
	}

	$user_timezone = ( isset($_POST['timezone']) ) ? str_replace(',', '.', doubleval($_POST['timezone'])) : $bb_cfg['board_timezone'];

// FLAGHACK-start
	$user_flag = (@$_POST['user_flag'] && $_POST['user_flag'] != 'blank.gif') ? $_POST['user_flag'] : '';
// FLAGHACK-end

	// dateformat
	$user_dateformat = '';

	if ($mode == 'editprofile' && !empty($_POST['dateformat']))
	{
		if (preg_match('/^[ a-z\-:]+$/i', $_POST['dateformat']))
		{
			if ($_POST['dateformat'] != $bb_cfg['board_dateformat'])
			{
				$user_dateformat = $_POST['dateformat'];
			}
		}
	}

	$user_avatar_local = ( isset($_POST['avatarselect']) && !empty($_POST['submitavatar']) && $bb_cfg['allow_avatar_local'] ) ? htmlspecialchars($_POST['avatarselect']) : ( ( isset($_POST['avatarlocal'])  ) ? htmlspecialchars($_POST['avatarlocal']) : '' );
	$user_avatar_category = ( isset($_POST['avatarcatname']) && $bb_cfg['allow_avatar_local'] ) ? htmlspecialchars($_POST['avatarcatname']) : '' ;

	$user_avatar_remoteurl = ( !empty($_POST['avatarremoteurl']) ) ? trim(htmlspecialchars($_POST['avatarremoteurl'])) : '';
	$user_avatar_upload = ( !empty($_POST['avatarurl']) ) ? trim($_POST['avatarurl']) : ( ( !empty($_FILES['avatar']) && $_FILES['avatar']['tmp_name'] != "none") ? $_FILES['avatar']['tmp_name'] : '' );
	$user_avatar_name = ( !empty($_FILES['avatar']['name']) ) ? $_FILES['avatar']['name'] : '';
	$user_avatar_size = ( !empty($_FILES['avatar']['size']) ) ? $_FILES['avatar']['size'] : 0;
	$user_avatar_filetype = ( !empty($_FILES['avatar']['type']) ) ? $_FILES['avatar']['type'] : '';

	$user_avatar = ( empty($user_avatar_local) && $mode == 'editprofile' ) ? $userdata['user_avatar'] : '';
	$user_avatar_type = ( empty($user_avatar_local) && $mode == 'editprofile' ) ? $userdata['user_avatar_type'] : '';

	if ( (isset($_POST['avatargallery']) || isset($_POST['submitavatar']) || isset($_POST['cancelavatar'])) && (!isset($_POST['submit'])) )
	{
		$cur_password = htmlspecialchars($cur_password);
		$new_password = htmlspecialchars($new_password);
		$password_confirm = htmlspecialchars($password_confirm);

		$signature = htmlspecialchars($signature);

		if ( !isset($_POST['cancelavatar']))
		{
			$user_avatar = $user_avatar_category . '/' . $user_avatar_local;
			$user_avatar_type = USER_AVATAR_GALLERY;
		}
	}
}

//
// Let's make sure the user isn't logged in while registering,
// and ensure that they were trying to register a second time
// (Prevents double registrations)
//
if ($mode == 'register' && ($userdata['session_logged_in'] || $username == $userdata['username']))
{
	message_die(GENERAL_MESSAGE, $lang['Username_taken'], '', __LINE__, __FILE__);
}

$available_badges = [];

if ($mode == 'editprofile' && $userdata['session_logged_in'])
{
	/* Выбор лычки */
	$sql = '
		SELECT DISTINCT
			r.rank_id,
			r.rank_title,
			r.rank_image
		FROM
			bb_user_group ug
		LEFT JOIN
			bb_groups g ON (g.group_id = ug.group_id)
		LEFT JOIN
			bb_ranks r ON (r.rank_id = g.rank_id)
		WHERE
			ug.user_id = ' . $userdata['user_id'] . '
		AND
			g.rank_id > 0
		AND
			r.rank_image != ""';
	$result = $db->sql_query($sql);

	while ($row = $db->sql_fetchrow($result))
	{
		$available_badges[$row['rank_id']] = 1;

		$template->assign_block_vars('available_badges', [
			'ID'    => $row['rank_id'],
			'TITLE' => $row['rank_title'],
			'IMAGE' => $row['rank_image'],
		]);
	}

	$db->sql_freeresult($result);
}

//
// Did the user submit? In this case build a query to update the users profile in the DB
//
if ( isset($_POST['submit']) )
{
	require SITE_DIR . 'includes/ucp/usercp_avatar.php';

	// session id check
	if ($sid == '' || $sid != $userdata['session_id'])
	{
		$error = true;
		$error_msg .= ( ($error_msg) ? '
' : '' ) . $lang['Session_Expired'];
	}

	$passwd_sql = '';
	if ( $mode == 'editprofile' )
	{
		if ( $user_id != $userdata['user_id'] )
		{
			$error = TRUE;
			$error_msg .= ( ($error_msg) ? '
' : '' ) . $lang['Wrong_Profile'];
		}
	}
	else if ( $mode == 'register' )
	{
		if ( empty($username) || empty($new_password) || empty($password_confirm) || empty($email) )
		{
			$error = TRUE;
			$error_msg .= ( ($error_msg) ? '
' : '' ) . $lang['Fields_empty'];
		}
	}

	if ($bb_cfg['enable_confirm'] && $mode == 'register')
	{
		if (empty($_POST['confirm_id']))
		{
			$error = TRUE;
			$error_msg .= ( ($error_msg) ? '
' : '' ) . $lang['Confirm_code_wrong'];
		}
		else
		{
			$confirm_id = htmlspecialchars($_POST['confirm_id']);
			if (!preg_match('/^[A-Za-z0-9]+$/', $confirm_id))
			{
				$confirm_id = '';
			}

			$sql = "SELECT code
				FROM bb_confirm
				WHERE confirm_id = '$confirm_id'
					AND session_id = '" . $userdata['session_id'] . "'";
			if (!($result = $db->sql_query($sql)))
			{
				message_die(GENERAL_ERROR, 'Could not obtain confirmation code', '', __LINE__, __FILE__, $sql);
			}

			if ($row = $db->sql_fetchrow($result))
			{
				// Only compare one char if the zlib-extension is not loaded
				if (!@extension_loaded('zlib'))
				{
					$row['code'] = substr($row['code'], -1);
				}

				if (strtolower($row['code']) != strtolower($confirm_code))
				{
					$error = TRUE;
					$error_msg .= ( ($error_msg) ? '
' : '' ) . $lang['Confirm_code_wrong'];
				}
				else
				{
					$sql = "DELETE FROM bb_confirm
						WHERE confirm_id = '$confirm_id'
							AND session_id = '" . $userdata['session_id'] . "'";
					if (!$db->sql_query($sql))
					{
						message_die(GENERAL_ERROR, 'Could not delete confirmation code', '', __LINE__, __FILE__, $sql);
					}
				}
			}
			else
			{
				$error = TRUE;
				$error_msg .= ( ($error_msg) ? '
' : '' ) . $lang['Confirm_code_wrong'];
			}
			$db->sql_freeresult($result);
		}
	}

	$passwd_sql = '';
	if ( !empty($new_password) && !empty($password_confirm) )
	{
		if ( $new_password != $password_confirm )
		{
			$error = TRUE;
			$error_msg .= ( ($error_msg) ? '
' : '' ) . $lang['Password_mismatch'];
		}
		else if ( strlen($new_password) > 32 )
		{
			$error = TRUE;
			$error_msg .= ( ($error_msg) ? '
' : '' ) . $lang['Password_long'];
		}
		else
		{
			if ( $mode == 'editprofile' )
			{
				$sql = "SELECT user_password
					FROM bb_users
					WHERE user_id = $user_id";
				if ( !($result = $db->sql_query($sql)) )
				{
					message_die(GENERAL_ERROR, 'Could not obtain user_password information', '', __LINE__, __FILE__, $sql);
				}

				$row = $db->sql_fetchrow($result);

				if ( $row['user_password'] != md5($cur_password) )
				{
					$error = TRUE;
					$error_msg .= ( ($error_msg) ? '
' : '' ) . $lang['Current_password_mismatch'];
				}
			}

			if ( !$error )
			{
				$new_password = md5($new_password);
				$passwd_sql = "user_password = '$new_password', ";
			}
		}
	}
	else if ( ( empty($new_password) && !empty($password_confirm) ) || ( !empty($new_password) && empty($password_confirm) ) )
	{
		$error = TRUE;
		$error_msg .= ( ($error_msg) ? '
' : '' ) . $lang['Password_mismatch'];
	}

	//
	// Do a ban check on this email address
	//
	if ( $email != $userdata['user_email'] || $mode == 'register' )
	{
		$result = validate_email($email);
		if ( $result['error'] )
		{
			$email = $userdata['user_email'];

			$error = TRUE;
			$error_msg .= ( ($error_msg) ? '
' : '' ) . $result['error_msg'];
		}

		if ( $mode == 'editprofile' )
		{
			$sql = "SELECT user_password
				FROM bb_users
				WHERE user_id = $user_id";
			if ( !($result = $db->sql_query($sql)) )
			{
				message_die(GENERAL_ERROR, 'Could not obtain user_password information', '', __LINE__, __FILE__, $sql);
			}

			$row = $db->sql_fetchrow($result);

			if ( $row['user_password'] != md5($cur_password) )
			{
				$email = $userdata['user_email'];

				$error = TRUE;
				$error_msg .= ( ($error_msg) ? '
' : '' ) . $lang['Current_password_mismatch'];
			}
		}
	}

	$username_sql = $signature_bbcode_uid = '';
	if ( $bb_cfg['allow_namechange'] || $mode == 'register' )
	{
		if ( empty($username) )
		{
			// Error is already triggered, since one field is empty.
			$error = TRUE;
		}
		else if ( $username != $userdata['username'] || $mode == 'register' )
		{
			if (strtolower($username) != strtolower($userdata['username']) || $mode == 'register')
			{
				$result = validate_username($username);
				if ( $result['error'] )
				{
					$error = TRUE;
					$error_msg .= ( ($error_msg) ? '
' : '' ) . $result['error_msg'];
				}
			}

			if (!$error)
			{
				$username_sql = "username = '" . str_replace("\'", "''", $username) . "', ";
			}
		}
	}

	if ( $signature != '' )
	{
		if ( strlen($signature) > $bb_cfg['max_sig_chars'] )
		{
			$error = TRUE;
			$error_msg .= ( ($error_msg) ? '
' : '' ) . $lang['Signature_too_long'];
		}

		$signature_bbcode_uid = ( $bb_cfg['allow_bbcode'] ) ? make_bbcode_uid() : '';
		$signature = prepare_message($signature, $bb_cfg['allow_bbcode'], $bb_cfg['allow_smilies'], $signature_bbcode_uid);
	}

	if ( $website != '' )
	{
		rawurlencode($website);
	}

	$avatar_sql = '';

	if ( isset($_POST['avatardel']) && $mode == 'editprofile' )
	{
		$avatar_sql = user_avatar_delete($userdata['user_avatar_type'], $userdata['user_avatar']);
	}
	else
	if ( ( !empty($user_avatar_upload) || !empty($user_avatar_name) ) && $bb_cfg['allow_avatar_upload'] )
	{
		if ( !empty($user_avatar_upload) )
		{
			$avatar_mode = (empty($user_avatar_name)) ? 'remote' : 'local';
			$avatar_sql = user_avatar_upload($mode, $avatar_mode, $userdata['user_avatar'], $userdata['user_avatar_type'], $error, $error_msg, $user_avatar_upload, $user_avatar_name, $user_avatar_size, $user_avatar_filetype);
		}
		else if ( !empty($user_avatar_name) )
		{
			$l_avatar_size = sprintf($lang['Avatar_filesize'], round($bb_cfg['avatar_filesize'] / 1024));

			$error = true;
			$error_msg .= ( ( !empty($error_msg) ) ? '
' : '' ) . $l_avatar_size;
		}
	}
	else if ( $user_avatar_remoteurl != '' && $bb_cfg['allow_avatar_remote'] )
	{
		user_avatar_delete($userdata['user_avatar_type'], $userdata['user_avatar']);
		$avatar_sql = user_avatar_url($mode, $error, $error_msg, $user_avatar_remoteurl);
	}
	else if ( $user_avatar_local != '' && $bb_cfg['allow_avatar_local'] )
	{
		user_avatar_delete($userdata['user_avatar_type'], $userdata['user_avatar']);
		$avatar_sql = user_avatar_gallery($mode, $error, $error_msg, $user_avatar_local, $user_avatar_category);
	}

	if ( !$error )
	{
		if ( $avatar_sql == '' )
		{
			$avatar_sql = ( $mode == 'editprofile' ) ? '' : "'', " . USER_AVATAR_NONE;
		}

		$update_user_opt = array(
			'viewemail',
			'attachsig',
			'hide_porn_forums',
		);
		$user_opt = $userdata['user_opt'];

		foreach ($update_user_opt as $opt)
		{
			setbit($user_opt, $bf['user_opt'][$opt], !empty($_POST[$opt]));
		}

		if ( $mode == 'editprofile' )
		{
			if ( $email != $userdata['user_email'] && $bb_cfg['require_activation'] != USER_ACTIVATION_NONE && !IS_ADMIN )
			{
				$user_active = 0;
				$user_actkey = make_rand_str(12);

				if ( $userdata['session_logged_in'] )
				{
					$user->session_end();
				}
			}
			else
			{
				$user_active = 1;
				$user_actkey = '';
			}

			if ($user_lang == $bb_cfg['board_lang'])
			{
				$user_lang = '';
			}

			$user_rank = intval(trim(htmlspecialchars($_POST['badge'])));

			if ($user_rank > 0)
			{
				$user_rank = $user_rank != $userdata['user_rank'] && isset($available_badges[$user_rank]) ? $user_rank : $userdata['user_rank'];
			}

			$sql = "UPDATE bb_users
				SET " . $username_sql . $passwd_sql . "
					user_opt = $user_opt,
					user_email = '" . str_replace("\'", "''", $email) ."',
					user_icq = '" . str_replace("\'", "''", $icq) . "',
					user_website = '" . str_replace("\'", "''", $website) . "',
					user_occ = '" . str_replace("\'", "''", $occupation) . "',
					user_from = '" . str_replace("\'", "''", $location) . "',
					user_from_flag = '$user_flag',
					user_interests = '" . str_replace("\'", "''", $interests) . "',
					user_sig = '" . str_replace("\'", "''", $signature) . "',
					user_sig_bbcode_uid = '$signature_bbcode_uid',
					user_aim = '" . str_replace("\'", "''", str_replace(' ', '+', $aim)) . "',
					user_yim = '" . str_replace("\'", "''", $yim) . "',
					user_msnm = '" . str_replace("\'", "''", $msn) . "',
					user_rank = $user_rank,

					user_allow_viewonline = $allowviewonline,
					user_notify = $notifyreply,
					user_notify_pm = $notifypm,

					user_timezone = '$user_timezone',
					user_dateformat = '" . str_replace("\'", "''", $user_dateformat) . "',
					user_lang = '" . str_replace("\'", "''", $user_lang) . "',
					user_active = $user_active,
					user_actkey = '" . str_replace("\'", "''", $user_actkey) . "'" . $avatar_sql . "
				WHERE user_id = $user_id";
			if ( !($result = $db->sql_query($sql)) )
			{
				message_die(GENERAL_ERROR, 'Could not update users table', '', __LINE__, __FILE__, $sql);
			}

			if ( !$user_active )
			{
				//
				// The users account has been deactivated, send them an email with a new activation key
				//
				require SITE_DIR . 'includes/emailer.php';
				$emailer = new emailer($bb_cfg['smtp_delivery']);

 				if ( $bb_cfg['require_activation'] != USER_ACTIVATION_ADMIN )
 				{
				$emailer->from($bb_cfg['board_email']);
				$emailer->replyto($bb_cfg['board_email']);

				$emailer->use_template('user_activate', $user_lang);
				$emailer->email_address($email);
				$emailer->set_subject($lang['Reactivate']);

				$emailer->assign_vars(array(
					'SITENAME' => $bb_cfg['sitename'],
					'USERNAME' => preg_replace($unhtml_specialchars_match, $unhtml_specialchars_replace, mb_substr(str_replace("\'", "'", $username), 0, 25)),
					'EMAIL_SIG' => (!empty($bb_cfg['board_email_sig'])) ? str_replace('
', "\n", "-- \n" . $bb_cfg['board_email_sig']) : '',

 						'U_ACTIVATE' => $server_url . '?mode=activate&' . POST_USERS_URL . '=' . $user_id . '&act_key=' . $user_actkey)
 					);
 					$emailer->send();
 					$emailer->reset();
 				}
 				else if ( $bb_cfg['require_activation'] == USER_ACTIVATION_ADMIN )
 				{
 					$sql = 'SELECT user_email, user_lang
 						FROM bb_users
 						WHERE user_level = ' . ADMIN;

 					if ( !($result = $db->sql_query($sql)) )
 					{
 						message_die(GENERAL_ERROR, 'Could not select Administrators', '', __LINE__, __FILE__, $sql);
 					}

 					while ($row = $db->sql_fetchrow($result))
 					{
 						$emailer->from($bb_cfg['board_email']);
 						$emailer->replyto($bb_cfg['board_email']);

 						$emailer->email_address(trim($row['user_email']));
 						$emailer->use_template("admin_activate", $row['user_lang']);
 						$emailer->set_subject($lang['Reactivate']);

 						$emailer->assign_vars(array(
 							'USERNAME' => preg_replace($unhtml_specialchars_match, $unhtml_specialchars_replace, mb_substr(str_replace("\'", "'", $username), 0, 25)),
 							'EMAIL_SIG' => str_replace('
', "\n", "-- \n" . $bb_cfg['board_email_sig']),

 							'U_ACTIVATE' => $server_url . '?mode=activate&' . POST_USERS_URL . '=' . $user_id . '&act_key=' . $user_actkey)
 						);
 						$emailer->send();
 						$emailer->reset();
 					}
 					$db->sql_freeresult($result);
 				}

				$message = $lang['Profile_updated_inactive'] . '

' . sprintf($lang['Click_return_index'],  '', '');
			}
			else
			{
				$message = $lang['Profile_updated'] . '

' . sprintf($lang['Click_return_index'],  '', '');
			}

			message_die(GENERAL_MESSAGE, $message);
		}
		else
		{
			if ($user_lang == $bb_cfg['board_lang'])
			{
				$user_lang = '';
			}
			$avatar_type = USER_AVATAR_NONE;

			$sql_ary = array_merge([
				'user_regdate'          => time(),
				'user_password'         => $new_password,
				'user_email'            => $email,
				'user_icq'              => $icq,
				'user_website'          => $website,
				'user_occ'              => $occupation,
				'user_from'             => $location,
				'user_from_flag'        => $user_flag,
				'user_interests'        => $interests,
				'user_sig'              => $signature,
				'user_sig_bbcode_uid'   => $signature_bbcode_uid,
				'user_avatar'           => '',
				'user_avatar_type'      => $avatar_type,
				'user_allow_viewonline' => $allowviewonline,
				'user_notify'           => $notifyreply,
				'user_notify_pm'        => $notifypm,
				'user_level'            => 0,
				'user_allow_pm'         => 1,
			], compact('user_opt', 'username', 'user_timezone', 'user_dateformat', 'user_lang'));

			if ($bb_cfg['require_activation'] == USER_ACTIVATION_SELF || $bb_cfg['require_activation'] == USER_ACTIVATION_ADMIN || $coppa)
			{
				$user_actkey = make_rand_str(12);
				$sql_ary['user_active'] = 0;
				$sql_ary['user_actkey'] = $user_actkey;
			}
			else
			{
				$sql_ary['user_active'] = 1;
			}

			$sql = 'INSERT INTO bb_users ' . $app['db']->build_array('INSERT', $sql_ary);
			$app['db']->query($sql);
			$user_id = $app['db']->insert_id();

			require SITE_DIR . 'includes/functions_torrent.php';
			generate_passkey($user_id, 1);

			if ( $coppa )
			{
				$message = $lang['COPPA'];
				$email_template = 'coppa_welcome_inactive';
			}
			else if ( $bb_cfg['require_activation'] == USER_ACTIVATION_SELF )
			{
				$message = $lang['Account_inactive'];
				$email_template = 'user_welcome_inactive';
			}
			else if ( $bb_cfg['require_activation'] == USER_ACTIVATION_ADMIN )
			{
				$message = $lang['Account_inactive_admin'];
				$email_template = 'admin_welcome_inactive';
			}
			else
			{
				$message = $lang['Account_added'];
				$email_template = 'user_welcome';
			}

			require SITE_DIR . 'includes/emailer.php';
			$emailer = new emailer($bb_cfg['smtp_delivery']);

			$emailer->from($bb_cfg['board_email']);
			$emailer->replyto($bb_cfg['board_email']);

			$emailer->use_template($email_template, $user_lang);
			$emailer->email_address($email);
			$emailer->set_subject(sprintf($lang['Welcome_subject'], $bb_cfg['sitename']));

			if( $coppa )
			{
				$emailer->assign_vars(array(
					'SITENAME' => $bb_cfg['sitename'],
					'WELCOME_MSG' => sprintf($lang['Welcome_subject'], $bb_cfg['sitename']),
					'USERNAME' => preg_replace($unhtml_specialchars_match, $unhtml_specialchars_replace, mb_substr(str_replace("\'", "'", $username), 0, 25)),
					'PASSWORD' => $password_confirm,
					'EMAIL_SIG' => str_replace('
', "\n", "-- \n" . $bb_cfg['board_email_sig']),

					'MAIL_INFO' => $bb_cfg['coppa_mail'],
					'EMAIL_ADDRESS' => $email,
					'ICQ' => $icq,
					'AIM' => $aim,
					'YIM' => $yim,
					'MSN' => $msn,
					'WEB_SITE' => $website,
					'FROM' => $location,
					'OCC' => $occupation,
					'INTERESTS' => $interests,
					'SITENAME' => $bb_cfg['sitename']));
			}
			else
			{
				$emailer->assign_vars(array(
					'SITENAME' => $bb_cfg['sitename'],
					'WELCOME_MSG' => sprintf($lang['Welcome_subject'], $bb_cfg['sitename']),
					'USERNAME' => preg_replace($unhtml_specialchars_match, $unhtml_specialchars_replace, mb_substr(str_replace("\'", "'", $username), 0, 25)),
					'PASSWORD' => $password_confirm,
					'EMAIL_SIG' => str_replace('
', "\n", "-- \n" . $bb_cfg['board_email_sig']),

					'U_ACTIVATE' => $server_url . '?mode=activate&' . POST_USERS_URL . '=' . $user_id . '&act_key=' . $user_actkey)
				);
			}

			$emailer->send();
			$emailer->reset();

			if ( $bb_cfg['require_activation'] == USER_ACTIVATION_ADMIN )
			{
				$sql = "SELECT user_email, user_lang
					FROM bb_users
					WHERE user_level = " . ADMIN;

				if ( !($result = $db->sql_query($sql)) )
				{
					message_die(GENERAL_ERROR, 'Could not select Administrators', '', __LINE__, __FILE__, $sql);
				}

				while ($row = $db->sql_fetchrow($result))
				{
					$emailer->from($bb_cfg['board_email']);
					$emailer->replyto($bb_cfg['board_email']);

					$emailer->email_address(trim($row['user_email']));
					$emailer->use_template("admin_activate", $row['user_lang']);
					$emailer->set_subject($lang['New_account_subject']);

					$emailer->assign_vars(array(
						'USERNAME' => preg_replace($unhtml_specialchars_match, $unhtml_specialchars_replace, mb_substr(str_replace("\'", "'", $username), 0, 25)),
						'EMAIL_SIG' => str_replace('
', "\n", "-- \n" . $bb_cfg['board_email_sig']),

						'U_ACTIVATE' => $server_url . '?mode=activate&' . POST_USERS_URL . '=' . $user_id . '&act_key=' . $user_actkey)
					);
					$emailer->send();
					$emailer->reset();
				}
				$db->sql_freeresult($result);
			}

			/* Переадресация на тему "Как качать?" */
			// redirect('viewtopic.php?t=262');

			$message = $message . '

' . sprintf($lang['Click_return_index'],  '', '');

			message_die(GENERAL_MESSAGE, $message);
		} // if mode == register
	}
} // End of submit

if ( $error )
{
	//
	// If an error occured we need to stripslashes on returned data
	//
	$new_password = '';
	$password_confirm = '';

	$signature = ($signature_bbcode_uid != '') ? preg_replace("/:(([a-z0-9]+:)?)$signature_bbcode_uid(=|\])/si", '\\3', $signature) : $signature;
}
else if ( $mode == 'editprofile' && !isset($_POST['avatargallery']) && !isset($_POST['submitavatar']) && !isset($_POST['cancelavatar']) )
{
	$user_id = $userdata['user_id'];
	$username = $userdata['username'];
	$email = $userdata['user_email'];
	$new_password = '';
	$password_confirm = '';

	$icq = $userdata['user_icq'];
	$aim = str_replace('+', ' ', $userdata['user_aim']);
	$msn = $userdata['user_msnm'];
	$yim = $userdata['user_yim'];

	$website = $userdata['user_website'];
	$location = $userdata['user_from'];
	$user_flag = $userdata['user_from_flag'];
	$occupation = $userdata['user_occ'];
	$interests = $userdata['user_interests'];
	$signature_bbcode_uid = $userdata['user_sig_bbcode_uid'];
	$signature = ($signature_bbcode_uid != '') ? preg_replace("/:(([a-z0-9]+:)?)$signature_bbcode_uid(=|\])/si", '\\3', $userdata['user_sig']) : $userdata['user_sig'];

	$viewemail = bf($userdata['user_opt'], 'user_opt', 'viewemail');
	$attachsig = bf($userdata['user_opt'], 'user_opt', 'attachsig');
	$hide_porn_forums = bf($userdata['user_opt'], 'user_opt', 'hide_porn_forums');
	$notifypm = $userdata['user_notify_pm'];
	$notifyreply = $userdata['user_notify'];
	$allowviewonline = $userdata['user_allow_viewonline'];

	$user_avatar = ( $userdata['user_allowavatar'] ) ? $userdata['user_avatar'] : '';
	$user_avatar_type = ( $userdata['user_allowavatar'] ) ? $userdata['user_avatar_type'] : USER_AVATAR_NONE;

	$user_timezone   = $userdata['user_timezone'];
	$user_lang       = ($userdata['user_lang']) ? $userdata['user_lang'] : $bb_cfg['board_lang'];
	$user_dateformat = ($userdata['user_dateformat']) ? $userdata['user_dateformat'] : $bb_cfg['default_dateformat'];
}

//
// Default pages
//
if ( $mode == 'editprofile' )
{
	if ( $user_id != $userdata['user_id'] )
	{
		$error = TRUE;
		$error_msg = $lang['Wrong_Profile'];
	}
}

if( isset($_POST['avatargallery']) && !$error )
{
	require SITE_DIR . 'includes/ucp/usercp_avatar.php';

	$avatar_category = ( !empty($_POST['avatarcategory']) ) ? htmlspecialchars($_POST['avatarcategory']) : '';

	$template->set_filenames(array(
		'body' => 'usercp_avatar_gallery.tpl')
	);

	$allowviewonline = !$allowviewonline;

	display_avatar_gallery($mode, $avatar_category, $user_id, $email, $current_email, $coppa, $username, $email, $new_password, $cur_password, $password_confirm, $icq, $aim, $msn, $yim, $website, $location, $user_flag, $occupation, $interests, $signature, $viewemail, $notifypm, $notifyreply, $attachsig, $allowviewonline, 1, $user_lang, $user_timezone, $user_dateformat, $userdata['session_id']);
}
else
{
	require SITE_DIR . 'includes/functions_selects.php';

	if ( !isset($coppa) )
	{
		$coppa = FALSE;
	}

	$avatar_img = '';
	if ( $user_avatar_type )
	{
		switch( $user_avatar_type )
		{
			case USER_AVATAR_UPLOAD:
				$avatar_img = ( $bb_cfg['allow_avatar_upload'] ) ? '' : '';
				break;
			case USER_AVATAR_REMOTE:
				$avatar_img = ( $bb_cfg['allow_avatar_remote'] ) ? '' : '';
				break;
			case USER_AVATAR_GALLERY:
				$avatar_img = ( $bb_cfg['allow_avatar_local'] ) ? '' : '';
				break;
		}
	}

	$s_hidden_fields = '<input type="hidden" name="mode" value="' . $mode . '" /><input type="hidden" name="agreed" value="true" /><input type="hidden" name="coppa" value="' . $coppa . '" />';
	$s_hidden_fields .= '<input type="hidden" name="sid" value="' . $userdata['session_id'] . '" />';
	if( $mode == 'editprofile' )
	{
		$s_hidden_fields .= '<input type="hidden" name="user_id" value="' . $userdata['user_id'] . '" />';
		//
		// Send the users current email address. If they change it, and account activation is turned on
		// the user account will be disabled and the user will have to reactivate their account.
		//
		$s_hidden_fields .= '<input type="hidden" name="current_email" value="' . $userdata['user_email'] . '" />';
	}

	if ( !empty($user_avatar_local) )
	{
		$s_hidden_fields .= '<input type="hidden" name="avatarlocal" value="' . $user_avatar_local . '" /><input type="hidden" name="avatarcatname" value="' . $user_avatar_category . '" />';
	}

	$bbcode_status = ($bb_cfg['allow_bbcode']) ? $lang['BBCode_is_ON'] : $lang['BBCode_is_OFF'];
	$smilies_status = ($bb_cfg['allow_smilies']) ? $lang['Smilies_are_ON'] : $lang['Smilies_are_OFF'];

	if ( $error )
	{
		$template->assign_vars(array('ERROR_MESSAGE' => $error_msg));
	}

	$template->set_filenames(array(
		'body' => 'usercp_register.tpl')
	);

	if ( $mode == 'editprofile' )
	{
		$template->assign_block_vars('switch_edit_profile', array());
		$template->assign_vars(array(
			'EDIT_PROFILE'    => true,
			'SHOW_LANG'       => $bb_cfg['allow_change']['language'],
			'SHOW_DATEFORMAT' => $bb_cfg['allow_change']['dateformat'],
		));
	}

// FLAGHACK-start
	// query to get the list of flags
	$sql = "SELECT *
		FROM bb_flags
		ORDER BY flag_name";
	if(!$flags_result = $db->sql_query($sql))
	{
		message_die(GENERAL_ERROR, "Couldn't obtain flags information.", "", __LINE__, __FILE__, $sql);
	}
	$flag_row = $db->sql_fetchrowset($flags_result);
	$num_flags = $db->sql_numrows($flags_result);
	// build the html select statement
	$flag_start_image = 'blank.gif' ;
	$selected = ( isset($user_flag) ) ? '' : HTML_SELECTED;
	$flag_select = "<select name=\"user_flag\" onChange=\"document.images['user_flag'].src = '//ivacuum.org/i/flags/48/' + this.value;\" >";
	$flag_select .= "<option value=\"blank.gif\"$selected>" . $lang['Select_Country'] . "</option>";
	for ($i = 0; $i < $num_flags; $i++)
	{
		$flag_name = $flag_row[$i]['flag_name'];
		$flag_image = $flag_row[$i]['flag_image'];
		$selected = ( isset( $user_flag) ) ? (($user_flag == $flag_image) ? HTML_SELECTED : '' ) : '' ;
		$flag_select .= "\t<option value=\"$flag_image\"$selected>$flag_name</option>";
		if ( isset( $user_flag) && ($user_flag == $flag_image))
		{
			$flag_start_image = $flag_image ;
		}
	}
	$flag_select .= '</select>';
// FLAGHACK-end

	if ( ($mode == 'register') || ($bb_cfg['allow_namechange']) )
	{
		$template->assign_block_vars('switch_namechange_allowed', array());
	}
	else
	{
		$template->assign_block_vars('switch_namechange_disallowed', array());
	}

	// Visual Confirmation
	$confirm_image = '';

	//
	// Let's do an overall check for settings/versions which would prevent
	// us from doing file uploads....
	//
	$ini_val = ( phpversion() >= '4.0.0' ) ? 'ini_get' : 'get_cfg_var';
	$form_enctype = ( @$ini_val('file_uploads') == '0' || strtolower(@$ini_val('file_uploads') == 'off') || phpversion() == '4.0.4pl1' || !$bb_cfg['allow_avatar_upload'] || ( phpversion() < '4.0.3' && @$ini_val('open_basedir') != '' ) ) ? '' : 'enctype="multipart/form-data"';

	$template->assign_vars(array(
		'USERNAME' => $username,
		'CUR_PASSWORD' => '',
		'NEW_PASSWORD' => '',
		'PASSWORD_CONFIRM' => '',
		'EMAIL' => $email,
		'CONFIRM_IMG' => $confirm_image,
		'YIM' => $yim,
		'ICQ' => $icq,
		'MSN' => $msn,
		'AIM' => $aim,
		'OCCUPATION' => $occupation,
		'INTERESTS' => $interests,
		'LOCATION' => $location,

		'L_FLAG' => $lang['Country_Flag'],
		'FLAG_SELECT' => $flag_select,
		'FLAG_START' => $flag_start_image,

		'WEBSITE' => $website,
		'SIGNATURE' => str_replace('
', "\n", $signature),
		'VIEW_EMAIL_YES' => ( $viewemail ) ? 'checked="checked"' : '',
		'VIEW_EMAIL_NO' => ( !$viewemail ) ? 'checked="checked"' : '',
		'HIDE_USER_YES' => ( !$allowviewonline ) ? 'checked="checked"' : '',
		'HIDE_USER_NO' => ( $allowviewonline ) ? 'checked="checked"' : '',
		'NOTIFY_PM_YES' => ( $notifypm ) ? 'checked="checked"' : '',
		'NOTIFY_PM_NO' => ( !$notifypm ) ? 'checked="checked"' : '',
		'ALWAYS_ADD_SIGNATURE_YES' => ( $attachsig ) ? 'checked="checked"' : '',
		'ALWAYS_ADD_SIGNATURE_NO' => ( !$attachsig ) ? 'checked="checked"' : '',
		'HIDE_PORN_FORUMS_YES' => ( $hide_porn_forums ) ? 'checked="checked"' : '',
		'HIDE_PORN_FORUMS_NO' => ( !$hide_porn_forums ) ? 'checked="checked"' : '',
		'NOTIFY_REPLY_YES' => ( $notifyreply ) ? 'checked="checked"' : '',
		'NOTIFY_REPLY_NO' => ( !$notifyreply ) ? 'checked="checked"' : '',
		'ALLOW_AVATAR' => $bb_cfg['allow_avatar_upload'],
		'AVATAR' => $avatar_img,
		'AVATAR_SIZE' => $bb_cfg['avatar_filesize'],
		'LANGUAGE_SELECT' => language_select($user_lang, 'language'),
		'TIMEZONE_SELECT' => tz_select($user_timezone, 'timezone'),
		'DATE_FORMAT' => htmlCHR($user_dateformat),
		'BBCODE_STATUS' => sprintf($bbcode_status, '', ''),
		'SMILIES_STATUS' => $smilies_status,

		'L_CURRENT_PASSWORD' => $lang['Current_password'],
		'T_NEW_PASSWORD' => ( $mode == 'register' ) ? $lang['PASSWORD'] : $lang['NEW_PASSWORD'],
		'L_CONFIRM_PASSWORD' => $lang['Confirm_password'],
		'L_CONFIRM_PASSWORD_EXPLAIN' => ( $mode == 'editprofile' ) ? $lang['Confirm_password_explain'] : '',
		'L_PASSWORD_IF_CHANGED' => ( $mode == 'editprofile' ) ? $lang['password_if_changed'] : '',
		'L_PASSWORD_CONFIRM_IF_CHANGED' => ( $mode == 'editprofile' ) ? $lang['password_confirm_if_changed'] : '',
		'L_OCCUPATION' => $lang['Occupation'],
		'L_BOARD_LANGUAGE' => $lang['Board_lang'],
		'L_BOARD_STYLE' => $lang['Board_style'],
		'L_TIMEZONE' => $lang['Timezone'],
		'L_DATE_FORMAT' => $lang['Date_format'],
		'L_DATE_FORMAT_EXPLAIN' => $lang['Date_format_explain'],
		'L_INTERESTS' => $lang['Interests'],
		'L_HIDE_USER' => $lang['Hide_user'],
		'L_ALWAYS_ADD_SIGNATURE' => $lang['Always_add_sig'],

		'L_AVATAR_PANEL' => $lang['Avatar_panel'],
		'L_AVATAR_EXPLAIN' => sprintf($lang['Avatar_explain'], $bb_cfg['avatar_max_width'], $bb_cfg['avatar_max_height'], (round($bb_cfg['avatar_filesize'] / 1024))),
		'L_UPLOAD_AVATAR_FILE' => $lang['Upload_Avatar_file'],
		'L_UPLOAD_AVATAR_URL' => $lang['Upload_Avatar_URL'],
		'L_UPLOAD_AVATAR_URL_EXPLAIN' => $lang['Upload_Avatar_URL_explain'],
		'L_AVATAR_GALLERY' => $lang['Select_from_gallery'],
		'L_SHOW_GALLERY' => $lang['View_avatar_gallery'],
		'L_LINK_REMOTE_AVATAR' => $lang['Link_remote_Avatar'],
		'L_LINK_REMOTE_AVATAR_EXPLAIN' => $lang['Link_remote_Avatar_explain'],
		'L_DELETE_AVATAR' => $lang['Delete_Image'],
		'L_CURRENT_IMAGE' => $lang['Current_Image'],

		'L_SIGNATURE' => $lang['Signature'],
		'L_SIGNATURE_EXPLAIN' => sprintf($lang['Signature_explain'], $bb_cfg['max_sig_chars']),
		'L_NOTIFY_ON_REPLY' => $lang['Always_notify'],
		'L_NOTIFY_ON_REPLY_EXPLAIN' => $lang['Always_notify_explain'],
		'L_NOTIFY_ON_PRIVMSG' => $lang['Notify_on_privmsg'],
		'L_PREFERENCES' => $lang['Preferences'],
		'L_PUBLIC_VIEW_EMAIL' => $lang['Public_view_email'],
		'L_ITEMS_REQUIRED' => $lang['Items_required'],
		'L_REGISTRATION_INFO' => $lang['Registration_info'],
		'L_PROFILE_INFO' => $lang['Profile_info'],
		'L_PROFILE_INFO_NOTICE' => $lang['Profile_info_warn'],
		'L_EMAIL_ADDRESS' => $lang['Email_address'],

		'L_CONFIRM_CODE_IMPAIRED'	=> sprintf($lang['Confirm_code_impaired'], '', ''),
		'L_CONFIRM_CODE'			=> $lang['Confirm_code'],
		'L_CONFIRM_CODE_EXPLAIN'	=> $lang['Confirm_code_explain'],

		'S_ALLOW_AVATAR_UPLOAD' => $bb_cfg['allow_avatar_upload'],
		'S_ALLOW_AVATAR_LOCAL' => $bb_cfg['allow_avatar_local'],
		'S_ALLOW_AVATAR_REMOTE' => $bb_cfg['allow_avatar_remote'],
		'S_HIDDEN_FIELDS' => $s_hidden_fields,
		'S_FORM_ENCTYPE' => $form_enctype,
		'S_PROFILE_ACTION' => append_sid("profile.php"),

		'U_RESET_AUTOLOGIN'      => "login.php?logout=1&reset_autologin=1&sid={$userdata['session_id']}",
		'L_AUTOLOGIN'            => $lang['Autologin'],
		'L_RESET_AUTOLOGIN'      => $lang['Reset_autologin'],
		'L_RESET_AUTOLOGIN_EXPL' => $lang['Reset_autologin_expl'],
	));

	//
	// This is another cheat using the block_var capability
	// of the templates to 'fake' an IF...ELSE...ENDIF solution
	// it works well :)
	//
	if ( $mode != 'register' )
	{
		if ( $userdata['user_allowavatar'] && ( $bb_cfg['allow_avatar_upload'] || $bb_cfg['allow_avatar_local'] || $bb_cfg['allow_avatar_remote'] ) )
		{
			$template->assign_block_vars('switch_avatar_block', array() );

			if ( $bb_cfg['allow_avatar_upload'] && file_exists(@phpbb_realpath('./' . $bb_cfg['avatar_path'])) )
			{
				if ( $form_enctype != '' )
				{
					$template->assign_block_vars('switch_avatar_block.switch_avatar_local_upload', array() );
				}
				$template->assign_block_vars('switch_avatar_block.switch_avatar_remote_upload', array() );
			}

			if ( $bb_cfg['allow_avatar_remote'] )
			{
				$template->assign_block_vars('switch_avatar_block.switch_avatar_remote_link', array() );
			}

			if ( $bb_cfg['allow_avatar_local'] && file_exists(@phpbb_realpath('./' . $bb_cfg['avatar_gallery_path'])) )
			{
				$template->assign_block_vars('switch_avatar_block.switch_avatar_local_gallery', array() );
			}
		}
	}
}

//bt
if ($mode == 'editprofile' && $userdata['session_logged_in'])
{
	$template->assign_block_vars('switch_bittorrent', array());

	$sql = 'SELECT auth_key
		FROM bb_bt_users
		WHERE user_id = '. $userdata['user_id'];

	if (!$result = $db->sql_query($sql))
	{
		message_die(GENERAL_ERROR, 'Could not query users passkey', '', __LINE__, __FILE__, $sql);
	}

	$row = $db->sql_fetchrow($result);
	$curr_passkey = ($row['auth_key']) ? $row['auth_key'] : '';

	$template->assign_vars(array(
		'L_GEN_PASSKEY'           => $lang['Bt_Gen_Passkey'],
		'L_GEN_PASSKEY_EXPLAIN'   => $lang['Bt_Gen_Passkey_Explain'],
		'L_GEN_PASSKEY_EXPLAIN_2' => $lang['Bt_Gen_Passkey_Explain_2'],
		'S_GEN_PASSKEY'           => "' . $lang['Bt_Gen_Passkey_Url'] . '',
		'L_CURR_PASSKEY'          => $lang['Curr_passkey'],
		'CURR_PASSKEY'            => $curr_passkey,
	));

	if ($userdata['user_rank'])
	{
		$sql = '
			SELECT
				rank_image
			FROM
				bb_ranks
			WHERE
				rank_id = ' . $userdata['user_rank'];
		$result = $db->sql_query($sql);
		$row = $db->sql_fetchrow($result);
		$db->sql_freeresult($result);
		$template->assign_vars(['RANK_IMAGE' => $row ? '/' . $row['rank_image'] : '']);
	}

	$template->assign_vars(['RANK_ID' => $userdata['user_rank']]);
}
//bt end

require PAGE_HEADER;

$template->pparse('body');

require PAGE_FOOTER;


text:
<?php

namespace PierresBlondes\FrontBundle\Repository;

/**
 * GoldenBookMessageRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class GoldenBookMessageRepository extends \Doctrine\ORM\EntityRepository
{
}

redpajama_set_name: RedPajamaGithub


text:
POSTGRES_USER=postgres
POSTGRES_DB=postgres
POSTGIS_INSTANCE=${1:-"osmdb"}
POSTGIS_PASSWORD=${2:-$(cat /dev/urandom| tr -dc _A-Z-a-z-0-9 | head -c12)}
docker run --name ${POSTGIS_INSTANCE} \
    -e POSTGRES_PASSWORD=${POSTGIS_PASSWORD} \
    -e POSTGRES_USER=${POSTGRES_USER} \
    -e POSTGRES_DB=${POSTGRES_DB} \
    -d osmtw/postgis


text:
#include "../../SDL_internal.h"

#if SDL_VIDEO_DRIVER_WAYLAND

#include "SDL_video.h"
#include "SDL_mouse.h"
#include "SDL_stdinc.h"
#include "../../events/SDL_events_c.h"

#include "SDL_waylandvideo.h"
#include "SDL_waylandevents_c.h"
#include "SDL_waylandwindow.h"
#include "SDL_waylandopengles.h"
#include "SDL_waylandmouse.h"
#include "SDL_waylandtouch.h"

#include <fcntl.h>
#include <xkbcommon/xkbcommon.h>

#include "SDL_waylanddyn.h"
#include <wayland-util.h>

#define WAYLANDVID_DRIVER_NAME "wayland"

/* Initialization/Query functions */
static int
Wayland_VideoInit(_THIS);

static void
Wayland_GetDisplayModes(_THIS, SDL_VideoDisplay *sdl_display);
static int
Wayland_SetDisplayMode(_THIS, SDL_VideoDisplay *display, SDL_DisplayMode *mode);

static void
Wayland_VideoQuit(_THIS);

/* Wayland driver bootstrap functions */
static int
Wayland_Available(void)
{
    struct wl_display *display = NULL;
    if (SDL_WAYLAND_LoadSymbols()) {
        display = WAYLAND_wl_display_connect(NULL);
        if (display != NULL) {
            WAYLAND_wl_display_disconnect(display);
        }
        SDL_WAYLAND_UnloadSymbols();
    }

    return (display != NULL);
}

static void
Wayland_DeleteDevice(SDL_VideoDevice *device)
{
    SDL_free(device);
    SDL_WAYLAND_UnloadSymbols();
}

static SDL_VideoDevice *
Wayland_CreateDevice(int devindex)
{
    SDL_VideoDevice *device;

    if (!SDL_WAYLAND_LoadSymbols()) {
        return NULL;
    }

    /* Initialize all variables that we clean on shutdown */
    device = SDL_calloc(1, sizeof(SDL_VideoDevice));
    if (!device) {
        SDL_WAYLAND_UnloadSymbols();
        SDL_OutOfMemory();
        return NULL;
    }

    /* Set the function pointers */
    device->VideoInit = Wayland_VideoInit;
    device->VideoQuit = Wayland_VideoQuit;
    device->SetDisplayMode = Wayland_SetDisplayMode;
    device->GetDisplayModes = Wayland_GetDisplayModes;
    device->GetWindowWMInfo = Wayland_GetWindowWMInfo;

    device->PumpEvents = Wayland_PumpEvents;

    device->GL_SwapWindow = Wayland_GLES_SwapWindow;
    device->GL_GetSwapInterval = Wayland_GLES_GetSwapInterval;
    device->GL_SetSwapInterval = Wayland_GLES_SetSwapInterval;
    device->GL_MakeCurrent = Wayland_GLES_MakeCurrent;
    device->GL_CreateContext = Wayland_GLES_CreateContext;
    device->GL_LoadLibrary = Wayland_GLES_LoadLibrary;
    device->GL_UnloadLibrary = Wayland_GLES_UnloadLibrary;
    device->GL_GetProcAddress = Wayland_GLES_GetProcAddress;
    device->GL_DeleteContext = Wayland_GLES_DeleteContext;

    device->CreateWindow = Wayland_CreateWindow;
    device->ShowWindow = Wayland_ShowWindow;
    device->SetWindowFullscreen = Wayland_SetWindowFullscreen;
    device->SetWindowSize = Wayland_SetWindowSize;
    device->DestroyWindow = Wayland_DestroyWindow;
    device->SetWindowHitTest = Wayland_SetWindowHitTest;

    device->free = Wayland_DeleteDevice;

    return device;
}

VideoBootStrap Wayland_bootstrap = {
    WAYLANDVID_DRIVER_NAME, "SDL Wayland video driver",
    Wayland_Available, Wayland_CreateDevice
};

static void
display_handle_geometry(void *data,
                        struct wl_output *output,
                        int x, int y,
                        int physical_width,
                        int physical_height,
                        int subpixel,
                        const char *make,
                        const char *model,
                        int transform)

{
    SDL_VideoDisplay *display = data;

    display->name = strdup(model);
    display->driverdata = output;
}

static void
display_handle_mode(void *data,
                    struct wl_output *output,
                    uint32_t flags,
                    int width,
                    int height,
                    int refresh)
{
    SDL_VideoDisplay *display = data;
    SDL_DisplayMode mode;

    SDL_zero(mode);
    mode.w = width;
    mode.h = height;
    mode.refresh_rate = refresh / 1000; // mHz to Hz
    SDL_AddDisplayMode(display, &mode);

    if (flags & WL_OUTPUT_MODE_CURRENT) {
        display->current_mode = mode;
        display->desktop_mode = mode;
    }
}

static void
display_handle_done(void *data,
                    struct wl_output *output)
{
    SDL_VideoDisplay *display = data;
    SDL_AddVideoDisplay(display);
    SDL_free(display->name);
    SDL_free(display);
}

static void
display_handle_scale(void *data,
                     struct wl_output *output,
                     int32_t factor)
{
    // TODO: do HiDPI stuff.
}

static const struct wl_output_listener output_listener = {
    display_handle_geometry,
    display_handle_mode,
    display_handle_done,
    display_handle_scale
};

static void
Wayland_add_display(SDL_VideoData *d, uint32_t id)
{
    struct wl_output *output;
    SDL_VideoDisplay *display = SDL_malloc(sizeof *display);
    if (!display) {
        SDL_OutOfMemory();
        return;
    }
    SDL_zero(*display);

    output = wl_registry_bind(d->registry, id, &wl_output_interface, 2);
    if (!output) {
        SDL_SetError("Failed to retrieve output.");
        return;
    }

    wl_output_add_listener(output, &output_listener, display);
}

#ifdef SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH
static void
windowmanager_hints(void *data, struct qt_windowmanager *qt_windowmanager,
        int32_t show_is_fullscreen)
{
}

static void
windowmanager_quit(void *data, struct qt_windowmanager *qt_windowmanager)
{
    SDL_SendQuit();
}

static const struct qt_windowmanager_listener windowmanager_listener = {
    windowmanager_hints,
    windowmanager_quit,
};
#endif /* SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH */

static void
display_handle_global(void *data, struct wl_registry *registry, uint32_t id,
                      const char *interface, uint32_t version)
{
    SDL_VideoData *d = data;

    if (strcmp(interface, "wl_compositor") == 0) {
        d->compositor = wl_registry_bind(d->registry, id, &wl_compositor_interface, 1);
    } else if (strcmp(interface, "wl_output") == 0) {
        Wayland_add_display(d, id);
    } else if (strcmp(interface, "wl_seat") == 0) {
        Wayland_display_add_input(d, id);
    } else if (strcmp(interface, "wl_shell") == 0) {
        d->shell = wl_registry_bind(d->registry, id, &wl_shell_interface, 1);
    } else if (strcmp(interface, "wl_shm") == 0) {
        d->shm = wl_registry_bind(registry, id, &wl_shm_interface, 1);
        d->cursor_theme = WAYLAND_wl_cursor_theme_load(NULL, 32, d->shm);
        d->default_cursor = WAYLAND_wl_cursor_theme_get_cursor(d->cursor_theme, "left_ptr");

#ifdef SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH
    } else if (strcmp(interface, "qt_touch_extension") == 0) {
        Wayland_touch_create(d, id);
    } else if (strcmp(interface, "qt_surface_extension") == 0) {
        d->surface_extension = wl_registry_bind(registry, id,
                &qt_surface_extension_interface, 1);
    } else if (strcmp(interface, "qt_windowmanager") == 0) {
        d->windowmanager = wl_registry_bind(registry, id,
                &qt_windowmanager_interface, 1);
        qt_windowmanager_add_listener(d->windowmanager, &windowmanager_listener, d);
#endif /* SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH */
    }
}

static const struct wl_registry_listener registry_listener = {
    display_handle_global
};

int
Wayland_VideoInit(_THIS)
{
    SDL_VideoData *data = SDL_malloc(sizeof *data);
    if (data == NULL)
        return SDL_OutOfMemory();
    memset(data, 0, sizeof *data);

    _this->driverdata = data;

    data->display = WAYLAND_wl_display_connect(NULL);
    if (data->display == NULL) {
        return SDL_SetError("Failed to connect to a Wayland display");
    }

    data->registry = wl_display_get_registry(data->display);
    if (data->registry == NULL) {
        return SDL_SetError("Failed to get the Wayland registry");
    }

    wl_registry_add_listener(data->registry, &registry_listener, data);

    // First roundtrip to receive all registry objects.
    WAYLAND_wl_display_roundtrip(data->display);

    // Second roundtrip to receive all output events.
    WAYLAND_wl_display_roundtrip(data->display);

    data->xkb_context = WAYLAND_xkb_context_new(0);
    if (!data->xkb_context) {
        return SDL_SetError("Failed to create XKB context");
    }

    Wayland_InitMouse();

    WAYLAND_wl_display_flush(data->display);

    return 0;
}

static void
Wayland_GetDisplayModes(_THIS, SDL_VideoDisplay *sdl_display)
{
    // Nothing to do here, everything was already done in the wl_output
    // callbacks.
}

static int
Wayland_SetDisplayMode(_THIS, SDL_VideoDisplay *display, SDL_DisplayMode *mode)
{
    return SDL_Unsupported();
}

void
Wayland_VideoQuit(_THIS)
{
    SDL_VideoData *data = _this->driverdata;
    int i;

    Wayland_FiniMouse ();

    for (i = 0; i < _this->num_displays; ++i) {
        SDL_VideoDisplay *display = &_this->displays[i];
        wl_output_destroy(display->driverdata);
        display->driverdata = NULL;
    }

    Wayland_display_destroy_input(data);

    if (data->xkb_context) {
        WAYLAND_xkb_context_unref(data->xkb_context);
        data->xkb_context = NULL;
    }
#ifdef SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH
    if (data->windowmanager)
        qt_windowmanager_destroy(data->windowmanager);

    if (data->surface_extension)
        qt_surface_extension_destroy(data->surface_extension);

    Wayland_touch_destroy(data);
#endif /* SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH */

    if (data->shm)
        wl_shm_destroy(data->shm);

    if (data->cursor_theme)
        WAYLAND_wl_cursor_theme_destroy(data->cursor_theme);

    if (data->shell)
        wl_shell_destroy(data->shell);

    if (data->compositor)
        wl_compositor_destroy(data->compositor);

    if (data->registry)
        wl_registry_destroy(data->registry);

    if (data->display) {
        WAYLAND_wl_display_flush(data->display);
        WAYLAND_wl_display_disconnect(data->display);
    }

    free(data);
    _this->driverdata = NULL;
}

#endif /* SDL_VIDEO_DRIVER_WAYLAND */

/* vi: set ts=4 sw=4 expandtab: */


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _postcss = require('postcss');

var _postcss2 = _interopRequireDefault(_postcss);

var _postcssValueParser = require('postcss-value-parser');

var _postcssValueParser2 = _interopRequireDefault(_postcssValueParser);

var _has = require('has');

var _has2 = _interopRequireDefault(_has);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/*
 * Constants (parser usage)
 */

const SINGLE_QUOTE = '\''.charCodeAt(0);
const DOUBLE_QUOTE = '"'.charCodeAt(0);
const BACKSLASH = '\\'.charCodeAt(0);
const NEWLINE = '\n'.charCodeAt(0);
const SPACE = ' '.charCodeAt(0);
const FEED = '\f'.charCodeAt(0);
const TAB = '\t'.charCodeAt(0);
const CR = '\r'.charCodeAt(0);

const WORD_END = /[ \n\t\r\f'"\\]/g;

/*
 * Constants (node type strings)
 */

const C_STRING = 'string';
const C_ESCAPED_SINGLE_QUOTE = 'escapedSingleQuote';
const C_ESCAPED_DOUBLE_QUOTE = 'escapedDoubleQuote';
const C_SINGLE_QUOTE = 'singleQuote';
const C_DOUBLE_QUOTE = 'doubleQuote';
const C_NEWLINE = 'newline';
const C_SINGLE = 'single';

/*
 * Literals
 */

const L_SINGLE_QUOTE = `'`;
const L_DOUBLE_QUOTE = `"`;
const L_NEWLINE = `\\\n`;

/*
 * Parser nodes
 */

const T_ESCAPED_SINGLE_QUOTE = { type: C_ESCAPED_SINGLE_QUOTE, value: `\\'` };
const T_ESCAPED_DOUBLE_QUOTE = { type: C_ESCAPED_DOUBLE_QUOTE, value: `\\"` };
const T_SINGLE_QUOTE = { type: C_SINGLE_QUOTE, value: L_SINGLE_QUOTE };
const T_DOUBLE_QUOTE = { type: C_DOUBLE_QUOTE, value: L_DOUBLE_QUOTE };
const T_NEWLINE = { type: C_NEWLINE, value: L_NEWLINE };

function stringify(ast) {
    return ast.nodes.reduce((str, { value }) => {
        // Collapse multiple line strings automatically
        if (value === L_NEWLINE) {
            return str;
        }

        return str + value;
    }, '');
}

function parse(str) {
    let code, next, value;
    let pos = 0;
    let len = str.length;

    const ast = {
        nodes: [],
        types: {
            escapedSingleQuote: 0,
            escapedDoubleQuote: 0,
            singleQuote: 0,
            doubleQuote: 0
        },
        quotes: false
    };

    while (pos < len) {
        code = str.charCodeAt(pos);

        switch (code) {
            case SPACE:
            case TAB:
            case CR:
            case FEED:
                next = pos;

                do {
                    next += 1;
                    code = str.charCodeAt(next);
                } while (code === SPACE || code === NEWLINE || code === TAB || code === CR || code === FEED);

                ast.nodes.push({
                    type: 'space',
                    value: str.slice(pos, next)
                });
                pos = next - 1;
                break;
            case SINGLE_QUOTE:
                ast.nodes.push(T_SINGLE_QUOTE);
                ast.types[C_SINGLE_QUOTE]++;
                ast.quotes = true;
                break;
            case DOUBLE_QUOTE:
                ast.nodes.push(T_DOUBLE_QUOTE);
                ast.types[C_DOUBLE_QUOTE]++;
                ast.quotes = true;
                break;
            case BACKSLASH:
                next = pos + 1;

                if (str.charCodeAt(next) === SINGLE_QUOTE) {
                    ast.nodes.push(T_ESCAPED_SINGLE_QUOTE);
                    ast.types[C_ESCAPED_SINGLE_QUOTE]++;
                    ast.quotes = true;
                    pos = next;
                    break;
                } else if (str.charCodeAt(next) === DOUBLE_QUOTE) {
                    ast.nodes.push(T_ESCAPED_DOUBLE_QUOTE);
                    ast.types[C_ESCAPED_DOUBLE_QUOTE]++;
                    ast.quotes = true;
                    pos = next;
                    break;
                } else if (str.charCodeAt(next) === NEWLINE) {
                    ast.nodes.push(T_NEWLINE);
                    pos = next;
                    break;
                }
            /*
             * We need to fall through here to handle the token as
             * a whole word. The missing 'break' is intentional.
             */
            default:
                WORD_END.lastIndex = pos + 1;
                WORD_END.test(str);

                if (WORD_END.lastIndex === 0) {
                    next = len - 1;
                } else {
                    next = WORD_END.lastIndex - 2;
                }

                value = str.slice(pos, next + 1);

                ast.nodes.push({
                    type: C_STRING,
                    value
                });

                pos = next;
        }
        pos++;
    }

    return ast;
}

function changeWrappingQuotes(node, ast) {
    const { types } = ast;

    if (types[C_SINGLE_QUOTE] || types[C_DOUBLE_QUOTE]) {
        return;
    }

    if (node.quote === L_SINGLE_QUOTE && types[C_ESCAPED_SINGLE_QUOTE] > 0 && !types[C_ESCAPED_DOUBLE_QUOTE]) {
        node.quote = L_DOUBLE_QUOTE;
    }

    if (node.quote === L_DOUBLE_QUOTE && types[C_ESCAPED_DOUBLE_QUOTE] > 0 && !types[C_ESCAPED_SINGLE_QUOTE]) {
        node.quote = L_SINGLE_QUOTE;
    }

    ast.nodes = ast.nodes.reduce((newAst, child) => {
        if (child.type === C_ESCAPED_DOUBLE_QUOTE && node.quote === L_SINGLE_QUOTE) {
            return [...newAst, T_DOUBLE_QUOTE];
        }

        if (child.type === C_ESCAPED_SINGLE_QUOTE && node.quote === L_DOUBLE_QUOTE) {
            return [...newAst, T_SINGLE_QUOTE];
        }

        return [...newAst, child];
    }, []);
}

function normalize(value, preferredQuote) {
    if (!value || !value.length) {
        return value;
    }

    return (0, _postcssValueParser2.default)(value).walk(child => {
        if (child.type !== C_STRING) {
            return;
        }

        const ast = parse(child.value);

        if (ast.quotes) {
            changeWrappingQuotes(child, ast);
        } else if (preferredQuote === C_SINGLE) {
            child.quote = L_SINGLE_QUOTE;
        } else {
            child.quote = L_DOUBLE_QUOTE;
        }

        child.value = stringify(ast);
    }).toString();
}

const params = {
    rule: 'selector',
    decl: 'value',
    atrule: 'params'
};

exports.default = _postcss2.default.plugin('postcss-normalize-string', opts => {
    const { preferredQuote } = Object.assign({}, {
        preferredQuote: 'double'
    }, opts);

    return css => {
        const cache = {};

        css.walk(node => {
            const { type } = node;

            if ((0, _has2.default)(params, type)) {
                const param = params[type];
                const key = node[param] + '|' + preferredQuote;

                if (cache[key]) {
                    node[param] = cache[key];

                    return;
                }

                const result = normalize(node[param], preferredQuote);

                node[param] = result;
                cache[key] = result;
            }
        });
    };
});
module.exports = exports['default'];


text:
logfile="/var/log/cosmic/agent/patch_systemvm.log"

mkdir -p /var/log/cosmic/agent

# Extract systemvm.zip package to install_directory.
patch_systemvm() {
   local install_directory=/opt/cosmic/agent
   local patchfile=$1
   rm -rf $install_directory
   mkdir -p $install_directory

   echo "All" | unzip $patchfile -d $install_directory >$logfile 2>&1

   find $install_directory -name \*.sh | xargs chmod 555

   [ -f /etc/udev/rules.d/70-persistent-net.rules ] && sudo rm -f /etc/udev/rules.d/70-persistent-net.rules
   [ -f /etc/udev/rules.d/75-persistent-net-generator.rules ] && sudo rm -f /etc/udev/rules.d/75-persistent-net-generator.rules
   return 0
}

consoleproxy_svcs() {
   chkconfig cloud on
   chkconfig postinit on
   chkconfig cloud-passwd-srvr off
   chkconfig haproxy off ;
   chkconfig dnsmasq off
   chkconfig ssh on
   chkconfig apache2 off
   chkconfig nfs-common off
   chkconfig portmap off
   chkconfig keepalived off
   chkconfig conntrackd off
   echo "cloud postinit ssh" > /var/cache/cloud/enabled_svcs
   echo "cloud-passwd-srvr haproxy dnsmasq apache2 nfs-common portmap" > /var/cache/cloud/disabled_svcs
}

secstorage_svcs() {
   chkconfig cloud on
   chkconfig postinit on
   chkconfig cloud-passwd-srvr off
   chkconfig haproxy off ;
   chkconfig dnsmasq off
   chkconfig portmap on
   chkconfig nfs-common on
   chkconfig ssh on
   chkconfig apache2 off
   chkconfig keepalived off
   chkconfig conntrackd off
   echo "cloud postinit ssh nfs-common portmap" > /var/cache/cloud/enabled_svcs
   echo "cloud-passwd-srvr haproxy dnsmasq" > /var/cache/cloud/disabled_svcs
}

routing_svcs() {
   grep "redundant_router=1" /var/cache/cloud/cmdline > /dev/null
   RROUTER=$?
   chkconfig cloud off
   chkconfig haproxy on ;
   chkconfig ssh on
   chkconfig nfs-common off
   chkconfig portmap off
   echo "ssh haproxy apache2" > /var/cache/cloud/enabled_svcs
   echo "cloud nfs-common portmap" > /var/cache/cloud/disabled_svcs
   if [ $RROUTER -eq 0 ]
   then
       chkconfig dnsmasq off
       chkconfig cloud-passwd-srvr off
       chkconfig keepalived on
       chkconfig conntrackd on
       chkconfig postinit on
       echo "keepalived conntrackd postinit" >> /var/cache/cloud/enabled_svcs
       echo "dnsmasq cloud-passwd-srvr" >> /var/cache/cloud/disabled_svcs
   else
       chkconfig dnsmasq on
       chkconfig cloud-passwd-srvr on
       chkconfig keepalived off
       chkconfig conntrackd off
       echo "dnsmasq cloud-passwd-srvr " >> /var/cache/cloud/enabled_svcs
       echo "keepalived conntrackd " >> /var/cache/cloud/disabled_svcs
   fi
}

dhcpsrvr_svcs() {
   chkconfig cloud off
   chkconfig cloud-passwd-srvr on ;
   chkconfig haproxy off ;
   chkconfig dnsmasq on
   chkconfig ssh on
   chkconfig nfs-common off
   chkconfig portmap off
   chkconfig keepalived off
   chkconfig conntrackd off
   echo "ssh dnsmasq cloud-passwd-srvr apache2" > /var/cache/cloud/enabled_svcs
   echo "cloud nfs-common haproxy portmap" > /var/cache/cloud/disabled_svcs
}

enable_pcihotplug() {
   sed -i -e "/acpiphp/d" /etc/modules
   sed -i -e "/pci_hotplug/d" /etc/modules
   echo acpiphp >> /etc/modules
   echo pci_hotplug >> /etc/modules
}

enable_serial_console() {
   sed -i -e "/^serial.*/d" /boot/grub/grub.conf
   sed -i -e "/^terminal.*/d" /boot/grub/grub.conf
   sed -i -e "/^default.*/a\serial --unit=0 --speed=115200 --parity=no --stop=1" /boot/grub/grub.conf
   sed -i -e "/^serial.*/a\terminal --timeout=0 serial console" /boot/grub/grub.conf
   sed -i -e "s/\(^kernel.* ro\) \(console.*\)/\1 console=tty0 console=ttyS0,115200n8/" /boot/grub/grub.conf
   sed -i -e "/^s0:2345:respawn.*/d" /etc/inittab
   sed -i -e "/6:23:respawn/a\s0:2345:respawn:/sbin/getty -L 115200 ttyS0 vt102" /etc/inittab
}

CMDLINE=$(cat /var/cache/cloud/cmdline)
TYPE="router"
PATCH_MOUNT=$1
Hypervisor=$2

for i in $CMDLINE
  do
    # search for foo=bar pattern and cut out foo
    KEY=$(echo $i | cut -d= -f1)
    VALUE=$(echo $i | cut -d= -f2)
    case $KEY in
      type)
        TYPE=$VALUE
        ;;
      *)
        ;;
    esac
done

if ([ "$TYPE" == "consoleproxy" ] || [ "$TYPE" == "secstorage" ])  && [ -f ${PATCH_MOUNT}/systemvm.zip ]
then
  patch_systemvm ${PATCH_MOUNT}/systemvm.zip
  if [ $? -gt 0 ]
  then
    printf "Failed to apply patch systemvm\n" >$logfile
    exit 5
  fi
fi

#empty known hosts
echo "" > /root/.ssh/known_hosts

if [ "$Hypervisor" == "kvm" ]
then
   enable_pcihotplug
   enable_serial_console
fi

if [ "$TYPE" == "router" ] || [ "$TYPE" == "vpcrouter" ]
then
  routing_svcs
  if [ $? -gt 0 ]
  then
    printf "Failed to execute routing_svcs\n" >$logfile
    exit 6
  fi
fi

if [ "$TYPE" == "dhcpsrvr" ]
then
  dhcpsrvr_svcs
  if [ $? -gt 0 ]
  then
    printf "Failed to execute dhcpsrvr_svcs\n" >$logfile
    exit 6
  fi
fi

if [ "$TYPE" == "consoleproxy" ]
then
  consoleproxy_svcs
  if [ $? -gt 0 ]
  then
    printf "Failed to execute consoleproxy_svcs\n" >$logfile
    exit 7
  fi
fi

if [ "$TYPE" == "secstorage" ]
then
  secstorage_svcs
  if [ $? -gt 0 ]
  then
    printf "Failed to execute secstorage_svcs\n" >$logfile
    exit 8
  fi
fi

exit $?


text:
/* eslint-env node, mocha */
import { assert } from 'chai'
import onRejected from '../src/on-rejected'

describe('on-rejected', () => {
  it('must work', (done) => {
    const decorator = onRejected((err) => {
      return `msg: ${err.message}`
    })
    const func = decorator(() => Promise.reject(new Error('oh no')))
    func()
      .then(function (res) {
        assert.equal(res, 'msg: oh no')
        done()
      })
  })
})


text:
#import "NSObject.h"

@class NSString;

// Not exported
@interface _UIAutologgingDeallocSentinel : NSObject
{
    _Bool _called;
    NSString *_message;
}

@property(nonatomic) _Bool called; // @synthesize called=_called;
@property(retain, nonatomic) NSString *message; // @synthesize message=_message;
- (void)dealloc;

@end


text:
import http from 'http';
import WebSocket from 'ws';

export default function createMockRNServer(port = 8081) {
  const server = http.createServer((req, res) => {
    if (req.method === 'GET' && req.url === '/debugger-ui') {
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.end('<html></html>');
    }
  });
  const wss = new WebSocket.Server({ server });
  server.listen(port);
  return { server, wss };
}


text:
require 'spec_helper'

RSpec.describe Gitlab::Client do
  describe '.broadcast_messages' do
    before do
      stub_get('/broadcast_messages', 'broadcast_messages')
      @broadcast_messages = Gitlab.broadcast_messages
    end

    it 'gets the correct resource' do
      expect(a_get('/broadcast_messages')).to have_been_made
    end

    it 'returns a paginated response of broadcast messages' do
      expect(@broadcast_messages).to be_a Gitlab::PaginatedResponse
    end
  end

  describe '.broadcast_message' do
    before do
      stub_get('/broadcast_messages/1', 'broadcast_message')
      @broadcast_message = Gitlab.broadcast_message(1)
    end

    it 'gets the correct resource' do
      expect(a_get('/broadcast_messages/1')).to have_been_made
    end

    it 'returns correct information about the broadcast message' do
      expect(@broadcast_message.id).to eq 1
    end
  end

  describe '.create_broadcast_message' do
    before do
      stub_post('/broadcast_messages', 'broadcast_message')
      @broadcast_message = Gitlab.create_broadcast_message('Deploy in progress', color: '#cecece')
    end

    it 'gets the correct resource' do
      expect(a_post('/broadcast_messages')
        .with(body: { message: 'Deploy in progress', color: '#cecece' })).to have_been_made
    end

    it 'returns correct information about the broadcast message created' do
      expect(@broadcast_message.message).to eq 'Deploy in progress'
      expect(@broadcast_message.color).to eq '#cecece'
    end
  end

  describe '.edit_broadcast_message' do
    before do
      stub_put('/broadcast_messages/1', 'broadcast_message')
      @broadcast_message = Gitlab.edit_broadcast_message(1, font: '#FFFFFF')
    end

    it 'gets the correct resource' do
      expect(a_put('/broadcast_messages/1')
        .with(body: { font: '#FFFFFF' })).to have_been_made
    end

    it 'returns correct information about the edited broadcast message' do
      expect(@broadcast_message.font).to eq '#FFFFFF'
    end
  end

  describe '.delete_broadcast_message' do
    before do
      stub_delete('/broadcast_messages/1', 'empty')
      @broadcast_message = Gitlab.delete_broadcast_message(1)
    end

    it 'gets the correct resource' do
      expect(a_delete('/broadcast_messages/1')).to have_been_made
    end
  end
end


text:
package com.vladkel.dametenebra;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

import com.vladkel.dametenebra.ihm.IhmCategory;
import com.vladkel.dametenebra.ihm.IhmLink;
import com.vladkel.dametenebra.ihm.IhmOwner;
import com.vladkel.dametenebra.ihm.IhmPhoto;
import com.vladkel.dametenebra.utils.properties.Property;

/**
 * @author eliott
 *
 */
public class DameTenebra implements ActionListener{

	private IhmCategory category;
	private IhmPhoto photo;
	private IhmOwner owner;
	private IhmLink link;

	/* ihm */
	private JFrame jf;
	private JPanel p;

	private JButton add_category;
	private JButton consult_category;
	private JButton add_photo;
	private JButton consult_photo;
	private JButton add_owner;
	private JButton consult_owner;
	private JButton add_link;
	private JButton consult_link;

	public static final String server = Property.getInstance().getProperties().getProperty("prog.target");

	public DameTenebra(){

		category = new IhmCategory();
		photo = new IhmPhoto();
		owner = new IhmOwner();
		link = new IhmLink();

		jf = new JFrame();
		jf.setTitle("DameTénébra - Version 4.0.1 -  \u00A9 Eliott Laversin");
		jf.setSize(500, 185);
		jf.setResizable(false);
		jf.setLocationRelativeTo(null);
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		p = new JPanel();
		jf.setContentPane(p);

		Dimension d = new Dimension(240, 30);

		add_category = new JButton("Ajouter une catégorie");
		add_category.setPreferredSize(d);
		consult_category = new JButton("Consulter les catégories");
		consult_category.setPreferredSize(d);
		add_photo = new JButton("Ajouter une photo");
		add_photo.setPreferredSize(d);
		consult_photo = new JButton("Consulter les photos");
		consult_photo.setPreferredSize(d);
		add_owner = new JButton("Ajouter un photographe");
		add_owner.setPreferredSize(d);
		consult_owner = new JButton("Consulter les photographes");
		consult_owner.setPreferredSize(d);
		add_link = new JButton("Ajouter un lien");
		add_link.setPreferredSize(d);
		consult_link = new JButton("Consulter les liens");
		consult_link.setPreferredSize(d);

		p.add(add_category);
		p.add(consult_category);
		p.add(add_photo);
		p.add(consult_photo);
		p.add(add_owner);
		p.add(consult_owner);
		p.add(add_link);
		p.add(consult_link);

		add_category.addActionListener(this);
		consult_category.addActionListener(this);
		add_photo.addActionListener(this);
		consult_photo.addActionListener(this);
		add_owner.addActionListener(this);
		consult_owner.addActionListener(this);
		add_link.addActionListener(this);
		consult_link.addActionListener(this);

		jf.setVisible(true);
	}

	public void actionPerformed(ActionEvent e) {

		/* Category */
		if(e.getSource() == add_category){
			category.create();
		}
		if(e.getSource() == consult_category){
			category.displayAll();
		}

		/* Photo */
		if(e.getSource() == add_photo){
			photo.create();
		}
		if(e.getSource() == consult_photo){
			photo.displayAll();
		}

		/* Owner */
		if(e.getSource() == add_owner){
			owner.create();
		}
		if(e.getSource() == consult_owner){
			owner.displayAll();
		}

		/* Link */
		if(e.getSource() == add_link){
			link.create();
		}
		if(e.getSource() == consult_link){
			link.displayAll();
		}

	}

	public static void main(String[] args) {

		new DameTenebra();
	}

}


text:
package mx.emite.sdk.clientes.operaciones.ef;

import mx.emite.sdk.clientes.ClienteJson;
import mx.emite.sdk.clientes.operaciones.Operacion;
import mx.emite.sdk.ef.request.FacturaEmiteRequest;
import mx.emite.sdk.ef.response.FacturaEmiteResponse;
import mx.emite.sdk.enums.Proveedor;
import mx.emite.sdk.enums.Rutas;
import mx.emite.sdk.errores.ApiException;

public class FacturaEmite extends Operacion<FacturaEmiteRequest,FacturaEmiteResponse>{

	@Deprecated
	public FacturaEmite(final ClienteJson cliente) {
		super(cliente,Proveedor.SCOT,Rutas.FACTURAEMITE);
	}

	@Override
	@Deprecated
	public FacturaEmiteResponse ejecuta(FacturaEmiteRequest request) throws ApiException{
		final String ruta = creaRuta(request);
		return procesa(this.getCliente().post(ruta,request,FacturaEmiteResponse.class));
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.imagepicker"
    android:versionCode="1"
    android:versionName="0.18.4" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="22" />

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-feature
        android:name="android.hardware.camera"
        android:required="false" />
    <uses-feature android:name="android.hardware.camera.autofocus" />

</manifest>


text:
using namespace std;

namespace dynet {

ExecutionEngine::~ExecutionEngine() {}

void SimpleExecutionEngine::invalidate() {
  num_nodes_evaluated = 0;
}

void SimpleExecutionEngine::invalidate(unsigned i) {
  num_nodes_evaluated = i;
}

const Tensor& SimpleExecutionEngine::forward() {
  const VariableIndex node_max_index = (VariableIndex)(cg.nodes.size() - 1);
  return forward(node_max_index);
}

const Tensor& SimpleExecutionEngine::forward(VariableIndex i) {
  invalidate();
  return incremental_forward(i);
}

const Tensor& SimpleExecutionEngine::get_value(VariableIndex i) {
  DYNET_ASSERT(i < cg.nodes.size(), "Out-of-bounds variable access in SimpleExecutionEngine::get_value()");
  if (i >= num_nodes_evaluated) {
    incremental_forward();
  }
  return nfxs[i];
}

const Tensor& SimpleExecutionEngine::incremental_forward() {
  const VariableIndex node_max_index = (VariableIndex)(cg.nodes.size() - 1);
  return incremental_forward(node_max_index);
}

const Tensor& SimpleExecutionEngine::incremental_forward(VariableIndex i) {
  DYNET_ASSERT(i < cg.nodes.size(), "Out-of-bounds variable access in SimpleExecutionEngine::incremental_forward()");

  // free any old memory if this is a new CG
  if (num_nodes_evaluated == 0)
    for(Device* dev : dynet::devices)
      dev->pools[(int)DeviceMempool::FXS]->free();

  if (i >= num_nodes_evaluated) {
    nfxs.resize(i + 1);

    //vector<string> dummy(5, "x");
    vector<const Tensor*> xs(16);
    for (; num_nodes_evaluated <= i; ++num_nodes_evaluated) {
      const Node* node = cg.nodes[num_nodes_evaluated];
      xs.resize(node->arity());
      unsigned ai = 0;
      for (VariableIndex arg : node->args) {
        xs[ai] = &nfxs[arg];
        ++ai;
      }
      nfxs[num_nodes_evaluated].d = node->dim;
      // Get the device
      DYNET_ASSERT(node->device != nullptr, "Attempt to access null device in SimpleExecutionEngine::incremental_forward");
      nfxs[num_nodes_evaluated].device = node->device;
      // Get the memory
      nfxs[num_nodes_evaluated].v = static_cast<float*>(nfxs[num_nodes_evaluated].device->pools[(int)DeviceMempool::FXS]->allocate(node->dim.size() * sizeof(float)));
      if (nfxs[num_nodes_evaluated].v == nullptr)
        DYNET_RUNTIME_ERR("Ran out of memory when executing node " << num_nodes_evaluated);
      void* aux_mem = nullptr;
      size_t aux_size = node->aux_storage_size();
      if (aux_size) {
        aux_mem = nfxs[num_nodes_evaluated].device->pools[(int)DeviceMempool::FXS]->allocate(aux_size);
        if (!aux_mem)
          DYNET_RUNTIME_ERR("Ran out of auxiliary memory when executing node " << num_nodes_evaluated);
      }
      node->aux_mem = aux_mem;

      node->forward(xs, nfxs[num_nodes_evaluated]);
    }
  }
  return nfxs[i];
}

void SimpleExecutionEngine::backward() {
  DYNET_ASSERT(nfxs.size() >= cg.nodes.size(), "Mismatched array sizes in SimpleExecutionEngine::backward");
  backward((VariableIndex)(cg.nodes.size()-1));
}

// TODO what is happening with parameter nodes if from_where > param_node_id ?
void SimpleExecutionEngine::backward(VariableIndex from_where) {
  if(!(from_where < nfxs.size()))
    incremental_forward(from_where);
  if (nfxs[from_where].d.size() != 1)
    DYNET_INVALID_ARG("backward() can only be called on scalar nodes, but node " << from_where << " has dimension: " << nfxs[from_where].d);

  const unsigned num_nodes = from_where+1;
  ndEdfs.resize(num_nodes);
  for(Device* device : devices)
    device->pools[(int)DeviceMempool::DEDFS]->free();
  for (unsigned i = 0; i < num_nodes; ++i) {
    const auto dim = nfxs[i].d;
    ndEdfs[i].d = dim;
    ndEdfs[i].device = nfxs[i].device;
    ndEdfs[i].v = static_cast<float*>(ndEdfs[i].device->pools[(int)DeviceMempool::DEDFS]->allocate(dim.size() * sizeof(float)));
    if (!ndEdfs[i].v)
      DYNET_RUNTIME_ERR("out of memory while attempting to allocate space for derivatives of node " << i);
  }
  for(Device* device : devices)
    device->pools[(int)DeviceMempool::DEDFS]->zero_allocated_memory();
  // initialize dE/dE = 1
  ndEdfs.back().v = kSCALAR_ONE;

  // here we find constant paths to avoid doing extra work
  // by default, a node is constant unless
  //   1) it is a parameter node
  //   2) it depends on a non-constant node
  // (thus, functions of constants and inputs end up being
  //  false in this computation)
  vector<bool> needs_derivative(num_nodes, false);
  for (auto i : cg.parameter_nodes)
    needs_derivative[i] = true;

  for (unsigned ni = 0; ni < num_nodes; ++ni) {
    bool nd = needs_derivative[ni];
    for (auto arg : cg.nodes[ni]->args)
      nd |= needs_derivative[arg];
    needs_derivative[ni] = nd;
  }

  // loop in reverse topological order
  // consider only nodes that participate in the computation.
  vector<bool> in_computation(num_nodes, false);
  in_computation[num_nodes - 1] = true;
  vector<const Tensor*> xs;
  for (int i = num_nodes - 1; i >= 0; --i) {
    if (!in_computation[i]) continue;
    const Node* node = cg.nodes[i];
    xs.resize(node->arity());
    unsigned ai = 0;
    for (VariableIndex arg : node->args) {
      in_computation[arg] = true;
      xs[ai] = &nfxs[arg];
      ++ai;
    }
    ai = 0;
    for (VariableIndex arg : node->args) {
      if (needs_derivative[arg]) {
        node->backward(xs, nfxs[i], ndEdfs[i], ai, ndEdfs[arg]);
      }
      ++ai;
    }
  }

  // accumulate gradients into parameters
  // this is simpler than you might find in some other frameworks
  // since we assume parameters come into the graph as a "function"
  // that returns the current value of the parameters
  for (VariableIndex i : cg.parameter_nodes)
    static_cast<ParameterNodeBase*>(cg.nodes[i])->accumulate_grad(ndEdfs[i]);
}

} // namespace dynet


text:
<?php

// Clean out everything already in the table.
\Drupal::database()->delete('entity_subqueue__items')->execute();


text:
#include "sdk/android/src/jni/videodecoderwrapper.h"

#include BOSS_WEBRTC_U_api__video__video_frame_h //original-code:"api/video/video_frame.h"
#include BOSS_WEBRTC_U_modules__video_coding__include__video_codec_interface_h //original-code:"modules/video_coding/include/video_codec_interface.h"
#include BOSS_WEBRTC_U_modules__video_coding__utility__vp8_header_parser_h //original-code:"modules/video_coding/utility/vp8_header_parser.h"
#include BOSS_WEBRTC_U_modules__video_coding__utility__vp9_uncompressed_header_parser_h //original-code:"modules/video_coding/utility/vp9_uncompressed_header_parser.h"
#include BOSS_WEBRTC_U_rtc_base__logging_h //original-code:"rtc_base/logging.h"
#include "sdk/android/generated_video_jni/jni/VideoDecoderWrapper_jni.h"
#include "sdk/android/generated_video_jni/jni/VideoDecoder_jni.h"
#include "sdk/android/native_api/jni/java_types.h"
#include "sdk/android/src/jni/encodedimage.h"
#include "sdk/android/src/jni/videocodecstatus.h"
#include "sdk/android/src/jni/videoframe.h"

namespace webrtc {
namespace jni {

namespace {
// RTP timestamps are 90 kHz.
const int64_t kNumRtpTicksPerMillisec = 90000 / rtc::kNumMillisecsPerSec;

template <typename Dst, typename Src>
inline absl::optional<Dst> cast_optional(const absl::optional<Src>& value) {
  return value ? absl::optional<Dst>(rtc::dchecked_cast<Dst, Src>(*value))
               : absl::nullopt;
}
}  // namespace

VideoDecoderWrapper::VideoDecoderWrapper(JNIEnv* jni,
                                         const JavaRef<jobject>& decoder)
    : decoder_(jni, decoder),
      implementation_name_(JavaToStdString(
          jni,
          Java_VideoDecoder_getImplementationName(jni, decoder))),
      initialized_(false),
      qp_parsing_enabled_(true)  // QP parsing starts enabled and we disable it
                                 // if the decoder provides frames.

{
  decoder_thread_checker_.DetachFromThread();
}

VideoDecoderWrapper::~VideoDecoderWrapper() = default;

int32_t VideoDecoderWrapper::InitDecode(const VideoCodec* codec_settings,
                                        int32_t number_of_cores) {
  RTC_DCHECK_RUN_ON(&decoder_thread_checker_);
  JNIEnv* jni = AttachCurrentThreadIfNeeded();
  codec_settings_ = *codec_settings;
  number_of_cores_ = number_of_cores;
  return InitDecodeInternal(jni);
}

int32_t VideoDecoderWrapper::InitDecodeInternal(JNIEnv* jni) {
  ScopedJavaLocalRef<jobject> settings = Java_Settings_Constructor(
      jni, number_of_cores_, codec_settings_.width, codec_settings_.height);

  ScopedJavaLocalRef<jobject> callback =
      Java_VideoDecoderWrapper_createDecoderCallback(jni,
                                                     jlongFromPointer(this));

  int32_t status = JavaToNativeVideoCodecStatus(
      jni, Java_VideoDecoder_initDecode(jni, decoder_, settings, callback));
  RTC_LOG(LS_INFO) << "initDecode: " << status;
  if (status == WEBRTC_VIDEO_CODEC_OK) {
    initialized_ = true;
  }

  // The decoder was reinitialized so re-enable the QP parsing in case it stops
  // providing QP values.
  qp_parsing_enabled_ = true;

  return status;
}

int32_t VideoDecoderWrapper::Decode(
    const EncodedImage& image_param,
    bool missing_frames,
    const CodecSpecificInfo* codec_specific_info,
    int64_t render_time_ms) {
  RTC_DCHECK_RUN_ON(&decoder_thread_checker_);
  if (!initialized_) {
    // Most likely initializing the codec failed.
    return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;
  }

  // Make a mutable copy so we can modify the timestamp.
  EncodedImage input_image(image_param);
  // We use RTP timestamp for capture time because capture_time_ms_ is always 0.
  input_image.capture_time_ms_ =
      input_image._timeStamp / kNumRtpTicksPerMillisec;

  FrameExtraInfo frame_extra_info;
  frame_extra_info.timestamp_ns =
      input_image.capture_time_ms_ * rtc::kNumNanosecsPerMillisec;
  frame_extra_info.timestamp_rtp = input_image._timeStamp;
  frame_extra_info.timestamp_ntp = input_image.ntp_time_ms_;
  frame_extra_info.qp =
      qp_parsing_enabled_ ? ParseQP(input_image) : absl::nullopt;
  {
    rtc::CritScope cs(&frame_extra_infos_lock_);
    frame_extra_infos_.push_back(frame_extra_info);
  }

  JNIEnv* env = AttachCurrentThreadIfNeeded();
  ScopedJavaLocalRef<jobject> jinput_image =
      NativeToJavaEncodedImage(env, input_image);
  ScopedJavaLocalRef<jobject> decode_info;
  ScopedJavaLocalRef<jobject> ret =
      Java_VideoDecoder_decode(env, decoder_, jinput_image, decode_info);
  return HandleReturnCode(env, ret, "decode");
}

int32_t VideoDecoderWrapper::RegisterDecodeCompleteCallback(
    DecodedImageCallback* callback) {
  RTC_DCHECK_RUNS_SERIALIZED(&callback_race_checker_);
  callback_ = callback;
  return WEBRTC_VIDEO_CODEC_OK;
}

int32_t VideoDecoderWrapper::Release() {
  JNIEnv* jni = AttachCurrentThreadIfNeeded();
  int32_t status = JavaToNativeVideoCodecStatus(
      jni, Java_VideoDecoder_release(jni, decoder_));
  RTC_LOG(LS_INFO) << "release: " << status;
  {
    rtc::CritScope cs(&frame_extra_infos_lock_);
    frame_extra_infos_.clear();
  }
  initialized_ = false;
  // It is allowed to reinitialize the codec on a different thread.
  decoder_thread_checker_.DetachFromThread();
  return status;
}

bool VideoDecoderWrapper::PrefersLateDecoding() const {
  JNIEnv* jni = AttachCurrentThreadIfNeeded();
  return Java_VideoDecoder_getPrefersLateDecoding(jni, decoder_);
}

const char* VideoDecoderWrapper::ImplementationName() const {
  return implementation_name_.c_str();
}

void VideoDecoderWrapper::OnDecodedFrame(
    JNIEnv* env,
    const JavaRef<jobject>& j_caller,
    const JavaRef<jobject>& j_frame,
    const JavaRef<jobject>& j_decode_time_ms,
    const JavaRef<jobject>& j_qp) {
  RTC_DCHECK_RUNS_SERIALIZED(&callback_race_checker_);
  const int64_t timestamp_ns = GetJavaVideoFrameTimestampNs(env, j_frame);

  FrameExtraInfo frame_extra_info;
  {
    rtc::CritScope cs(&frame_extra_infos_lock_);

    do {
      if (frame_extra_infos_.empty()) {
        RTC_LOG(LS_WARNING)
            << "Java decoder produced an unexpected frame: " << timestamp_ns;
        return;
      }

      frame_extra_info = frame_extra_infos_.front();
      frame_extra_infos_.pop_front();
      // If the decoder might drop frames so iterate through the queue until we
      // find a matching timestamp.
    } while (frame_extra_info.timestamp_ns != timestamp_ns);
  }

  VideoFrame frame =
      JavaToNativeFrame(env, j_frame, frame_extra_info.timestamp_rtp);
  frame.set_ntp_time_ms(frame_extra_info.timestamp_ntp);

  absl::optional<int32_t> decoding_time_ms =
      JavaToNativeOptionalInt(env, j_decode_time_ms);

  absl::optional<uint8_t> decoder_qp =
      cast_optional<uint8_t, int32_t>(JavaToNativeOptionalInt(env, j_qp));
  // If the decoder provides QP values itself, no need to parse the bitstream.
  // Enable QP parsing if decoder does not provide QP values itself.
  qp_parsing_enabled_ = !decoder_qp.has_value();
  callback_->Decoded(frame, decoding_time_ms,
                     decoder_qp ? decoder_qp : frame_extra_info.qp);
}

VideoDecoderWrapper::FrameExtraInfo::FrameExtraInfo() = default;
VideoDecoderWrapper::FrameExtraInfo::FrameExtraInfo(const FrameExtraInfo&) =
    default;
VideoDecoderWrapper::FrameExtraInfo::~FrameExtraInfo() = default;

int32_t VideoDecoderWrapper::HandleReturnCode(JNIEnv* jni,
                                              const JavaRef<jobject>& j_value,
                                              const char* method_name) {
  int32_t value = JavaToNativeVideoCodecStatus(jni, j_value);
  if (value >= 0) {  // OK or NO_OUTPUT
    return value;
  }

  RTC_LOG(LS_WARNING) << method_name << ": " << value;
  if (value == WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE ||
      value == WEBRTC_VIDEO_CODEC_UNINITIALIZED) {  // Critical error.
    RTC_LOG(LS_WARNING) << "Java decoder requested software fallback.";
    return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;
  }

  // Try resetting the codec.
  if (Release() == WEBRTC_VIDEO_CODEC_OK &&
      InitDecodeInternal(jni) == WEBRTC_VIDEO_CODEC_OK) {
    RTC_LOG(LS_WARNING) << "Reset Java decoder.";
    return WEBRTC_VIDEO_CODEC_ERROR;
  }

  RTC_LOG(LS_WARNING) << "Unable to reset Java decoder.";
  return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;
}

absl::optional<uint8_t> VideoDecoderWrapper::ParseQP(
    const EncodedImage& input_image) {
  if (input_image.qp_ != -1) {
    return input_image.qp_;
  }

  absl::optional<uint8_t> qp;
  switch (codec_settings_.codecType) {
    case kVideoCodecVP8: {
      int qp_int;
      if (vp8::GetQp(input_image._buffer, input_image._length, &qp_int)) {
        qp = qp_int;
      }
      break;
    }
    case kVideoCodecVP9: {
      int qp_int;
      if (vp9::GetQp(input_image._buffer, input_image._length, &qp_int)) {
        qp = qp_int;
      }
      break;
    }
    case kVideoCodecH264: {
      h264_bitstream_parser_.ParseBitstream(input_image._buffer,
                                            input_image._length);
      int qp_int;
      if (h264_bitstream_parser_.GetLastSliceQp(&qp_int)) {
        qp = qp_int;
      }
      break;
    }
    default:
      break;  // Default is to not provide QP.
  }
  return qp;
}

std::unique_ptr<VideoDecoder> JavaToNativeVideoDecoder(
    JNIEnv* jni,
    const JavaRef<jobject>& j_decoder) {
  const jlong native_decoder =
      Java_VideoDecoder_createNativeVideoDecoder(jni, j_decoder);
  VideoDecoder* decoder;
  if (native_decoder == 0) {
    decoder = new VideoDecoderWrapper(jni, j_decoder);
  } else {
    decoder = reinterpret_cast<VideoDecoder*>(native_decoder);
  }
  return std::unique_ptr<VideoDecoder>(decoder);
}

}  // namespace jni
}  // namespace webrtc


text:
#include "video/call_stats.h"

#include <algorithm>
#include <memory>

#include "absl/algorithm/container.h"
#include "modules/utility/include/process_thread.h"
#include "rtc_base/checks.h"
#include "rtc_base/location.h"
#include "rtc_base/task_utils/to_queued_task.h"
#include "system_wrappers/include/metrics.h"

namespace webrtc {
namespace {

void RemoveOldReports(int64_t now, std::list<CallStats::RttTime>* reports) {
  static constexpr const int64_t kRttTimeoutMs = 1500;
  reports->remove_if(
      [&now](CallStats::RttTime& r) { return now - r.time > kRttTimeoutMs; });
}

int64_t GetMaxRttMs(const std::list<CallStats::RttTime>& reports) {
  int64_t max_rtt_ms = -1;
  for (const CallStats::RttTime& rtt_time : reports)
    max_rtt_ms = std::max(rtt_time.rtt, max_rtt_ms);
  return max_rtt_ms;
}

int64_t GetAvgRttMs(const std::list<CallStats::RttTime>& reports) {
  RTC_DCHECK(!reports.empty());
  int64_t sum = 0;
  for (std::list<CallStats::RttTime>::const_iterator it = reports.begin();
       it != reports.end(); ++it) {
    sum += it->rtt;
  }
  return sum / reports.size();
}

int64_t GetNewAvgRttMs(const std::list<CallStats::RttTime>& reports,
                       int64_t prev_avg_rtt) {
  if (reports.empty())
    return -1;  // Reset (invalid average).

  int64_t cur_rtt_ms = GetAvgRttMs(reports);
  if (prev_avg_rtt == -1)
    return cur_rtt_ms;  // New initial average value.

  // Weight factor to apply to the average rtt.
  // We weigh the old average at 70% against the new average (30%).
  constexpr const float kWeightFactor = 0.3f;
  return prev_avg_rtt * (1.0f - kWeightFactor) + cur_rtt_ms * kWeightFactor;
}

// This class is used to de-register a Module from a ProcessThread to satisfy
// threading requirements of the Module (CallStats).
// The guarantee offered by TemporaryDeregistration is that while its in scope,
// no calls to |TimeUntilNextProcess| or |Process()| will occur and therefore
// synchronization with those methods, is not necessary.
class TemporaryDeregistration {
 public:
  TemporaryDeregistration(Module* module,
                          ProcessThread* process_thread,
                          bool thread_running)
      : module_(module),
        process_thread_(process_thread),
        deregistered_(thread_running) {
    if (thread_running)
      process_thread_->DeRegisterModule(module_);
  }
  ~TemporaryDeregistration() {
    if (deregistered_)
      process_thread_->RegisterModule(module_, RTC_FROM_HERE);
  }

 private:
  Module* const module_;
  ProcessThread* const process_thread_;
  const bool deregistered_;
};

}  // namespace

CallStats::CallStats(Clock* clock, ProcessThread* process_thread)
    : clock_(clock),
      last_process_time_(clock_->TimeInMilliseconds()),
      max_rtt_ms_(-1),
      avg_rtt_ms_(-1),
      sum_avg_rtt_ms_(0),
      num_avg_rtt_(0),
      time_of_first_rtt_ms_(-1),
      process_thread_(process_thread),
      process_thread_running_(false) {
  RTC_DCHECK(process_thread_);
  process_thread_checker_.Detach();
}

CallStats::~CallStats() {
  RTC_DCHECK_RUN_ON(&construction_thread_checker_);
  RTC_DCHECK(!process_thread_running_);
  RTC_DCHECK(observers_.empty());

  UpdateHistograms();
}

int64_t CallStats::TimeUntilNextProcess() {
  RTC_DCHECK_RUN_ON(&process_thread_checker_);
  return last_process_time_ + kUpdateIntervalMs - clock_->TimeInMilliseconds();
}

void CallStats::Process() {
  RTC_DCHECK_RUN_ON(&process_thread_checker_);
  int64_t now = clock_->TimeInMilliseconds();
  last_process_time_ = now;

  // |avg_rtt_ms_| is allowed to be read on the process thread since that's the
  // only thread that modifies the value.
  int64_t avg_rtt_ms = avg_rtt_ms_;
  RemoveOldReports(now, &reports_);
  max_rtt_ms_ = GetMaxRttMs(reports_);
  avg_rtt_ms = GetNewAvgRttMs(reports_, avg_rtt_ms);
  {
    rtc::CritScope lock(&avg_rtt_ms_lock_);
    avg_rtt_ms_ = avg_rtt_ms;
  }

  // If there is a valid rtt, update all observers with the max rtt.
  if (max_rtt_ms_ >= 0) {
    RTC_DCHECK_GE(avg_rtt_ms, 0);
    for (CallStatsObserver* observer : observers_)
      observer->OnRttUpdate(avg_rtt_ms, max_rtt_ms_);
    // Sum for Histogram of average RTT reported over the entire call.
    sum_avg_rtt_ms_ += avg_rtt_ms;
    ++num_avg_rtt_;
  }
}

void CallStats::ProcessThreadAttached(ProcessThread* process_thread) {
  RTC_DCHECK_RUN_ON(&construction_thread_checker_);
  RTC_DCHECK(!process_thread || process_thread_ == process_thread);
  process_thread_running_ = process_thread != nullptr;

  // Whether we just got attached or detached, we clear the
  // |process_thread_checker_| so that it can be used to protect variables
  // in either the process thread when it starts again, or UpdateHistograms()
  // (mutually exclusive).
  process_thread_checker_.Detach();
}

void CallStats::RegisterStatsObserver(CallStatsObserver* observer) {
  RTC_DCHECK_RUN_ON(&construction_thread_checker_);
  TemporaryDeregistration deregister(this, process_thread_,
                                     process_thread_running_);

  if (!absl::c_linear_search(observers_, observer))
    observers_.push_back(observer);
}

void CallStats::DeregisterStatsObserver(CallStatsObserver* observer) {
  RTC_DCHECK_RUN_ON(&construction_thread_checker_);
  TemporaryDeregistration deregister(this, process_thread_,
                                     process_thread_running_);
  observers_.remove(observer);
}

int64_t CallStats::LastProcessedRtt() const {
  // TODO(tommi): This currently gets called from the construction thread of
  // Call as well as from the process thread. Look into restricting this to
  // allow only reading this from the process thread (or TQ once we get there)
  // so that the lock isn't necessary.

  rtc::CritScope cs(&avg_rtt_ms_lock_);
  return avg_rtt_ms_;
}

void CallStats::OnRttUpdate(int64_t rtt) {
  RTC_DCHECK_RUN_ON(&process_thread_checker_);

  int64_t now_ms = clock_->TimeInMilliseconds();
  reports_.push_back(RttTime(rtt, now_ms));
  if (time_of_first_rtt_ms_ == -1)
    time_of_first_rtt_ms_ = now_ms;

  // Make sure Process() will be called and deliver the updates asynchronously.
  last_process_time_ -= kUpdateIntervalMs;
  process_thread_->WakeUp(this);
}

void CallStats::UpdateHistograms() {
  RTC_DCHECK_RUN_ON(&construction_thread_checker_);
  RTC_DCHECK(!process_thread_running_);

  // The extra scope is because we have two 'dcheck run on' thread checkers.
  // This is a special case since it's safe to access variables on the current
  // thread that normally are only touched on the process thread.
  // Since we're not attached to the process thread and/or the process thread
  // isn't running, it's OK to touch these variables here.
  {
    // This method is called on the ctor thread (usually from the dtor, unless
    // a test calls it). It's a requirement that the function be called when
    // the process thread is not running (a condition that's met at destruction
    // time), and thanks to that, we don't need a lock to synchronize against
    // it.
    RTC_DCHECK_RUN_ON(&process_thread_checker_);

    if (time_of_first_rtt_ms_ == -1 || num_avg_rtt_ < 1)
      return;

    int64_t elapsed_sec =
        (clock_->TimeInMilliseconds() - time_of_first_rtt_ms_) / 1000;
    if (elapsed_sec >= metrics::kMinRunTimeInSeconds) {
      int64_t avg_rtt_ms = (sum_avg_rtt_ms_ + num_avg_rtt_ / 2) / num_avg_rtt_;
      RTC_HISTOGRAM_COUNTS_10000(
          "WebRTC.Video.AverageRoundTripTimeInMilliseconds", avg_rtt_ms);
    }
  }
}

}  // namespace webrtc


text:
=======
Credits
=======

Development Lead
----------------

* Joe Sacher <sacherjj@gmail.com>

Contributors
------------

* Gustavo Siqueira <rsiqueira.gustavo@gmail.com>


text:
class AudioCallback
{
public:
    static int interleaved(void *outputBuffer, void *inputBuffer,
                            unsigned int hwFrameCount, double streamTime,
                            RtAudioStreamStatus status, void *streamer );
};

#endif // AUDIOCALLBACK_H