text:
<?php
/**
 * Dashboard page class: WP_Smush_Dashboard extends WP_Smush_View.
 *
 * @since 2.9.0
 * @package WP_Smush
 */

/**
 * Class WP_Smush_Dashboard
 */
class WP_Smush_Dashboard extends WP_Smush_View {

	/**
	 * Settings group for resize options.
	 *
	 * @var array
	 */
	private $resize_group = array(
		'detection',
	);

	/**
	 * Settings group for full size image options.
	 *
	 * @var array
	 */
	private $full_size_group = array(
		'backup',
	);

	/**
	 * Settings group for integration options.
	 *
	 * @var array
	 */
	private $integration_group = array();

	/**
	 * Settings group for CDN options.
	 *
	 * @var array
	 */
	private $cdn_group = array();

	/**
	 * Register page action hooks
	 */
	public function add_action_hooks() {
		parent::add_action_hooks();

		add_action( 'smush_setting_column_right_inside', array( $this, 'settings_desc' ), 10, 2 );
		add_action( 'smush_setting_column_right_inside', array( $this, 'image_sizes' ), 15, 2 );
		add_action( 'smush_setting_column_right_inside', array( $this, 'resize_settings' ), 20, 2 );
		add_action( 'smush_setting_column_right_outside', array( $this, 'full_size_options' ), 20, 2 );
		add_action( 'smush_setting_column_right_outside', array( $this, 'detect_size_options' ), 25, 2 );

		// Add stats to stats box.
		add_action( 'stats_ui_after_resize_savings', array( $this, 'pro_savings_stats' ), 15 );
		add_action( 'stats_ui_after_resize_savings', array( $this, 'conversion_savings_stats' ), 15 );
		add_action( 'stats_ui_after_resize_savings', array( $this, 'directory_stats_ui' ), 10 );

		// Icons in the submenu.
		add_filter( 'wp_smush_admin_after_tab_' . $this->get_slug(), array( $this, 'after_tab' ) );
	}

	/**
	 * Function triggered when the page is loaded before render any content.
	 */
	public function on_load() {
		// Hook into settings.
		$this->integration_group = apply_filters( 'wp_smush_integration_settings', array() );
		$this->cdn_group         = apply_filters( 'wp_smush_cdn_settings', array() );

		// If a free user, update the limits.
		if ( ! WP_Smush::is_pro() ) {
			// Reset transient.
			WP_Smush_Core::check_bulk_limit( true );
		}

		// Init the tabs.
		$this->tabs = apply_filters(
			'smush_setting_tabs',
			array(
				'bulk'         => __( 'Bulk Smush', 'wp-smushit' ),
				'directory'    => __( 'Directory Smush', 'wp-smushit' ),
				'integrations' => __( 'Integrations', 'wp-smushit' ),
				'cdn'          => __( 'CDN', 'wp-smushit' ),
				'settings'     => __( 'Settings', 'wp-smushit' ),
			)
		);

		$networkwide = $this->settings->is_network_enabled();

		// Tabs that can be shown in network admin networkwide (bulk, integrations, cdn).
		if ( is_multisite() && $networkwide && is_network_admin() ) {
			unset( $this->tabs['directory'] );
		}

		// Tabs that can be shown in subsites if networkwide (bulk and directory).
		if ( is_multisite() && $networkwide && ! is_network_admin() ) {
			unset( $this->tabs['integrations'] );
		}
	}

	/**
	 * Register meta boxes.
	 */
	public function register_meta_boxes() {
		$is_pro         = WP_Smush::is_pro();
		$is_network     = is_network_admin();
		$is_networkwide = $this->settings->is_network_enabled();

		if ( ! $is_network ) {
			$this->add_meta_box(
				'meta-boxes/summary',
				null,
				array( $this, 'dashboard_summary_metabox' ),
				null,
				null,
				'summary',
				array(
					'box_class'         => 'sui-box sui-summary sui-summary-smush',
					'box_content_class' => false,
				)
			);

			// If not a pro user.
			if ( ! $is_pro ) {
				/**
				 * Allows to hook in additional containers after stats box for free version
				 * Pro Version has a full width settings box, so we don't want to do it there.
				 */
				do_action( 'wp_smush_after_stats_box' );
			}
		}

		// Class for box.
		$settings_class = $is_pro ? 'smush-settings-wrapper wp-smush-pro' : 'smush-settings-wrapper';

		if ( $is_network && ! $is_networkwide ) {
			$this->add_meta_box(
				'meta-boxes/bulk-settings',
				__( 'Settings', 'wp-smushit' ),
				array( $this, 'bulk_settings_metabox' ),
				null,
				null,
				'bulk',
				array(
					'box_class' => "sui-box {$settings_class}",
				)
			);

			return;
		}

		switch ( $this->get_current_tab() ) {
			case 'directory':
				$this->add_meta_box(
					'meta-boxes/directory',
					__( 'Directory Smush', 'wp-smushit' ),
					array( $this, 'directory_smush_metabox' ),
					null,
					null,
					'directory'
				);

				break;

			case 'integrations':
				// Show integrations box.
				$class          = $is_pro ? 'smush-integrations-wrapper wp-smush-pro' : 'smush-integrations-wrapper';
				$box_body_class = $is_pro ? '' : 'sui-upsell-items';

				$this->add_meta_box(
					'meta-boxes/integrations',
					__( 'Integrations', 'wp-smushit' ),
					array( $this, 'integrations_metabox' ),
					null,
					array( $this, 'integrations_metabox_footer' ),
					'integrations',
					array(
						'box_class'         => "sui-box {$class}",
						'box_content_class' => "sui-box-body {$box_body_class}",
					)
				);

				break;

			case 'bulk':
			default:
				if ( ! $is_network ) {
					// Show bulk smush box if a subsite admin.
					// Class for bulk smush box.
					$class = $is_pro ? 'bulk-smush-wrapper wp-smush-pro-install' : 'bulk-smush-wrapper';

					$this->add_meta_box(
						'meta-boxes/bulk',
						__( 'Bulk Smush', 'wp-smushit' ),
						array( $this, 'bulk_smush_metabox' ),
						null,
						null,
						'bulk',
						array(
							'box_class' => "sui-box {$class}",
						)
					);
				}

				if ( $is_network || ! $is_networkwide ) {
					$this->add_meta_box(
						'meta-boxes/bulk-settings',
						__( 'Settings', 'wp-smushit' ),
						array( $this, 'bulk_settings_metabox' ),
						null,
						null,
						'bulk',
						array(
							'box_class' => "sui-box {$settings_class}",
						)
					);
				}

				// Do not show if pro user.
				if ( ! $is_pro && ( ! is_network_admin() || $is_networkwide ) ) {
					$this->add_meta_box(
						'meta-boxes/pro-features',
						__( 'Pre Features', 'wp-smushit' ),
						array( $this, 'pro_features_metabox' ),
						array( $this, 'pro_features_metabox_header' ),
						null,
						'bulk'
					);
				}

				break;

			case 'cdn':
				if ( ! $is_pro ) {
					$this->add_meta_box(
						'meta-boxes/cdn-upsell',
						__( 'CDN', 'wp-smushit' ),
						array( $this, 'cdn_upsell_metabox' ),
						array( $this, 'cdn_upsell_metabox_header' ),
						null,
						'cdn'
					);
				} else {
					if ( ! $this->settings->get( 'cdn' ) ) {
						$this->add_meta_box(
							'meta-boxes/cdn/disabled',
							__( 'CDN', 'wp-smushit' ),
							null,
							array( $this, 'cdn_metabox_header' ),
							null,
							'cdn'
						);
					} else {
						$this->add_meta_box(
							'meta-boxes/cdn',
							__( 'CDN', 'wp-smushit' ),
							array( $this, 'cdn_metabox' ),
							array( $this, 'cdn_metabox_header' ),
							null,
							'cdn'
						);
					}
				}

				break;

			case 'settings':
				$this->add_meta_box(
					'meta-boxes/settings',
					__( 'Settings', 'wp-smushit' ),
					array( $this, 'settings_metabox' ),
					null,
					null,
					'settings'
				);
				break;
		}
	}

	/**
	 * Add remaining count to bulk smush tab.
	 *
	 * @param string $tab  Current tab.
	 */
	public function after_tab( $tab ) {
		if ( 'bulk' === $tab ) {
			$remaining = WP_Smush::get_instance()->core()->remaining_count;
			if ( 0 < $remaining ) {
				echo '' . absint( $remaining ) . '';
			} else {
				echo '';
			}
		} elseif ( 'cdn' === $tab ) {
			$status = $this->settings->get_setting( WP_SMUSH_PREFIX . 'cdn_status' );
			$cdn    = $this->settings->get( 'cdn' );

			if ( $cdn && isset( $status->cdn_enabled ) && $status->cdn_enabled ) {
				if ( WP_Smush::get_instance()->core()->mod->cdn->get_status() ) {
					echo '';
				} else {
					echo '';
				}
			}

			if ( $cdn && isset( $status->cdn_enabled ) && ! $status->cdn_enabled ) {
				echo '';
			}
		}
	}

	/**
	 * Prints Dimensions required for Resizing
	 *
	 * @param string $name Setting name.
	 * @param string $class_prefix Custom class prefix.
	 */
	public function resize_settings( $name = '', $class_prefix = '' ) {
		// Add only to full size settings.
		if ( 'resize' !== $name ) {
			return;
		}

		// Dimensions.
		$resize_sizes = $this->settings->get_setting(
			WP_SMUSH_PREFIX . 'resize_sizes',
			array(
				'width'  => '',
				'height' => '',
			)
		);

		// Set default prefix is custom prefix is empty.
		$prefix = empty( $class_prefix ) ? WP_SMUSH_PREFIX : $class_prefix;

		// Get max dimensions.
		$max_sizes = WP_Smush::get_instance()->core()->get_max_image_dimensions();

		$setting_status = $this->settings->get( 'resize' );
		?>
		<div class="wp-smush-resize-settings-wrap<?php echo $setting_status ? '' : ' sui-hidden'; ?>">

					<label aria-labelledby="<?php echo esc_attr( $prefix ); ?>label-max-width" for="<?php echo esc_attr( $prefix ) . esc_attr( $name ) . '_width'; ?>" class="sui-label">
						<?php esc_html_e( 'Max width', 'wp-smushit' ); ?>

					<input aria-required="true" type="number" class="sui-form-control wp-smush-resize-input"
							aria-describedby="<?php echo esc_attr( $prefix ); ?>resize-note"
							id="<?php echo esc_attr( $prefix ) . esc_attr( $name ) . '_width'; ?>"
							name="<?php echo esc_attr( WP_SMUSH_PREFIX ) . esc_attr( $name ) . '_width'; ?>"
							value="<?php echo isset( $resize_sizes['width'] ) && ! empty( $resize_sizes['width'] ) ? absint( $resize_sizes['width'] ) : 2048; ?>">

					<label aria-labelledby="<?php echo esc_attr( $prefix ); ?>label-max-height" for="<?php echo esc_attr( $prefix . $name ) . '_height'; ?>" class="sui-label">
						<?php esc_html_e( 'Max height', 'wp-smushit' ); ?>

					<input aria-required="true" type="number" class="sui-form-control wp-smush-resize-input"
							aria-describedby="<?php echo esc_attr( $prefix ); ?>resize-note"
							id="<?php echo esc_attr( $prefix . $name ) . '_height'; ?>"
							name="<?php echo esc_attr( WP_SMUSH_PREFIX . $name ) . '_height'; ?>"
							value="<?php echo isset( $resize_sizes['height'] ) && ! empty( $resize_sizes['height'] ) ? absint( $resize_sizes['height'] ) : 2048; ?>">

			<div class="sui-description" id="<?php echo esc_attr( $prefix ); ?>resize-note">
				<?php
				printf(
					/* translators: %1$s: strong tag, %2$d: max width size, %3$s: tag, %4$d: max height size, %5$s: closing strong tag  */
					esc_html__( 'Currently, your largest image size is set at %1$s%2$dpx wide %3$s %4$dpx high%5$s.', 'wp-smushit' ),
					'',
					esc_html( $max_sizes['width'] ),
					'×',
					esc_html( $max_sizes['height'] ),
					''
				);
				?>

				<?php esc_html_e( "Just to let you know, the width you've entered is less than your largest image and may result in pixelation.", 'wp-smushit' ); ?>

				<?php esc_html_e( 'Just to let you know, the height you've entered is less than your largest image and may result in pixelation.', 'wp-smushit' ); ?>

			<?php
			printf(
				/* translators: %s: link to gifgifs.com */
				esc_html__(
					'Note: Image resizing happens automatically when you upload attachments. To support
				retina devices, we recommend using 2x the dimensions of your image size. Animated GIFs will not be
				resized as they will lose their animation, please use a tool such as %s to resize
				then re-upload.',
					'wp-smushit'
				),
				'http://gifgifs.com/resizer/'
			);
			?>

		<?php
	}

	/**
	 * Show super smush stats in stats section.
	 *
	 * If a pro member and super smush is enabled, show super smushed
	 * stats else show message that encourage them to enable super smush.
	 * If free user show the avg savings that can be achived using Pro.
	 *
	 * @return void
	 */
	public function pro_savings_stats() {
		$core = WP_Smush::get_instance()->core();

		if ( ! WP_Smush::is_pro() ) {
			if ( empty( $core->stats ) || empty( $core->stats['pro_savings'] ) ) {
				$core->set_pro_savings();
			}
			$pro_savings      = $core->stats['pro_savings'];
			$show_pro_savings = $pro_savings['savings'] > 0 ? true : false;
			if ( $show_pro_savings ) {
				?>

					<?php esc_html_e( 'Pro Savings', 'wp-smushit' ); ?>
						<span class="sui-tag sui-tag-pro sui-tooltip sui-tooltip-constrained" data-tooltip="<?php esc_html_e( 'Join WPMU DEV to unlock multi-pass lossy compression', 'wp-smushit' ); ?>">
							<?php esc_html_e( 'PRO', 'wp-smushit' ); ?>

						<?php echo esc_html( $pro_savings['savings'] ); ?>
						/
						<?php echo esc_html( $pro_savings['percent'] ); ?>%

				<?php
			}
		} else {
			$compression_savings = 0;
			if ( ! empty( $core->stats ) && ! empty( $core->stats['bytes'] ) ) {
				$compression_savings = $core->stats['bytes'] - $core->stats['resize_savings'];
			}
			?>

					<?php esc_html_e( 'Super-Smush Savings', 'wp-smushit' ); ?>
					<?php if ( ! $core->mod->smush->lossy_enabled ) { ?>

							<?php
							$link_class = 'wp-smush-lossy-enable-link';
							if ( is_multisite() && $this->settings->is_network_enabled() ) {
								$settings_link = WP_Smush::get_instance()->admin()->settings_link( array(), true, true ) . '#enable-lossy';
							} elseif ( 'bulk' !== $this->get_current_tab() ) {
								$settings_link = WP_Smush::get_instance()->admin()->settings_link( array(), true ) . '#enable-lossy';
							} else {
								$settings_link = '#';
								$link_class    = 'wp-smush-lossy-enable';
							}
							printf(
								/* translators: %1$s; starting a tag, %2$s: ending a tag */
								esc_html__( 'Compress images up to 2x more than regular smush with almost no visible drop in quality. %1$sEnable Super-smush%2$s', 'wp-smushit' ),
								'',
								'' . esc_html__( 'Clicking this link will toggle the Super Smush checkbox.', 'wp-smushit' ) . ''
							);
							?>

					<?php } ?>

				<?php if ( $core->mod->smush->lossy_enabled ) { ?>

							<?php echo esc_html( size_format( $compression_savings, 1 ) ); ?>

				<?php } ?>

			<?php
		}
	}

	/**
	 * Show conversion savings stats in stats section.
	 *
	 * Show Png to Jpg conversion savings in stats box if the
	 * settings enabled or savings found.
	 *
	 * @return void
	 */
	public function conversion_savings_stats() {
		$core = WP_Smush::get_instance()->core();

		if ( WP_Smush::is_pro() && ! empty( $core->stats['conversion_savings'] ) && $core->stats['conversion_savings'] > 0 ) {
			?>

					<?php esc_html_e( 'PNG to JPEG savings', 'wp-smushit' ); ?>

					<?php echo $core->stats['conversion_savings'] > 0 ? esc_html( size_format( $core->stats['conversion_savings'], 1 ) ) : '0 MB'; ?>

			<?php
		}
	}

	/**
	 * Set directory smush stats to stats box.
	 *
	 * @return void
	 */
	public function directory_stats_ui() {
		$dir_smush_stats = get_option( 'dir_smush_stats' );
		$human           = 0;
		if ( ! empty( $dir_smush_stats ) && ! empty( $dir_smush_stats['dir_smush'] ) ) {
			$human = ! empty( $dir_smush_stats['dir_smush']['bytes'] ) && $dir_smush_stats['dir_smush']['bytes'] > 0 ? $dir_smush_stats['dir_smush']['bytes'] : 0;
		}
		?>

			<?php esc_html_e( 'Directory Smush Savings', 'wp-smushit' ); ?>
				<?php if ( $human <= 0 ) { ?>

						<?php esc_html_e( "Smush images that aren't located in your uploads folder.", 'wp-smushit' ); ?>
						<a href="<?php echo esc_url( admin_url( 'admin.php?page=smush&view=directory' ) ); ?>" class="wp-smush-dir-link"
							title="<?php esc_attr_e( "Select a directory you'd like to Smush.", 'wp-smushit' ); ?>">
							<?php esc_html_e( 'Choose directory', 'wp-smushit' ); ?>

				<?php } ?>

				<i class="sui-icon-loader sui-loading" aria-hidden="true" title="<?php esc_attr_e( 'Updating Stats', 'wp-smushit' ); ?>">

				/

		<?php
	}

	/**
	 * Single settings row html content.
	 *
	 * @param string $setting_m_key  Setting key.
	 * @param string $label          Setting label.
	 * @param string $name           Setting name.
	 * @param mixed  $setting_val    Setting value.
	 * @param bool   $disable        Disable the setting.
	 * @param bool   $upsell         Gray out row to show upsell.
	 *
	 * @return void
	 */
	public function settings_row( $setting_m_key, $label, $name, $setting_val, $disable = false, $upsell = false ) {
		?>
		<div class="sui-box-settings-row wp-smush-basic <?php echo $upsell ? 'sui-disabled' : ''; ?>">

				<span class="sui-settings-label <?php echo 'gutenberg' === $name ? 'sui-settings-label-with-tag' : ''; ?>">
					<?php echo esc_html( $label ); ?>

					<?php echo WP_Smush::get_instance()->core()->settings[ $name ]['desc']; ?>

			<div class="sui-box-settings-col-2" id="column-<?php echo esc_attr( $setting_m_key ); ?>">

						<input type="checkbox" aria-describedby="<?php echo esc_attr( $setting_m_key . '-desc' ); ?>" id="<?php echo esc_attr( $setting_m_key ); ?>" name="<?php echo esc_attr( $setting_m_key ); ?>" <?php checked( $setting_val, 1, true ); ?> value="1" <?php disabled( $disable ); ?>>

					<label for="<?php echo esc_attr( $setting_m_key ); ?>">
						<?php echo esc_html( WP_Smush::get_instance()->core()->settings[ $name ]['label'] ); ?>

					<?php do_action( 'smush_setting_column_right_inside', $name ); ?>

				<?php do_action( 'smush_setting_column_right_outside', $name ); ?>

		<?php
	}

	/**
	 * Show additional descriptions for settings.
	 *
	 * @param string $setting_key Setting key.
	 */
	public function settings_desc( $setting_key = '' ) {
		if ( empty( $setting_key ) || ! in_array(
			$setting_key,
			array(
				'resize',
				'original',
				'strip_exif',
				'png_to_jpg',
				's3',
			),
			true
		) ) {
			return;
		}
		?>
		<span class="sui-description sui-toggle-description" id="<?php echo esc_attr( WP_SMUSH_PREFIX . $setting_key . '-desc' ); ?>">
			<?php
			switch ( $setting_key ) {
				case 'resize':
					esc_html_e(
						'Save a ton of space by not storing over-sized images on your server. Set a maximum height
						and width for all images uploaded to your site so that any unnecessarily large images are
						automatically resized before they are added to the media gallery. This setting does not apply
						to images smushed using Directory Smush feature.',
						'wp-smushit'
					);
					break;
				case 'original':
					esc_html_e(
						'By default, bulk smush will ignore your original uploads and only compress the
					thumbnail sizes your theme outputs. Enable this setting to also smush your original uploads. We
					recommend storing copies of your originals (below) in case you ever need to restore them.',
						'wp-smushit'
					);
					break;
				case 'strip_exif':
					esc_html_e(
						'Note: This data adds to the size of the image. While this information might be
					important to photographers, it's unnecessary for most users and safe to remove.',
						'wp-smushit'
					);
					break;
				case 'png_to_jpg':
					esc_html_e(
						'Note: Any PNGs with transparency will be ignored. Smush will only convert PNGs
					if it results in a smaller file size. The resulting file will have a new filename and extension
					(JPEG), and any hard-coded URLs on your site that contain the original PNG filename will need
					to be updated.',
						'wp-smushit'
					);
					break;
				case 's3':
					esc_html_e( 'Note: For this process to happen automatically you need automatic smushing enabled.', 'wp-smushit' );
					break;
				case 'default':
					break;
			}
			?>

		<?php
	}

	/**
	 * Prints all the registered image sizes, to be selected/unselected for smushing.
	 *
	 * @param string $name Setting key.
	 *
	 * @return void
	 */
	public function image_sizes( $name = '' ) {
		// Add only to auto smush settings.
		if ( 'auto' !== $name ) {
			return;
		}

		// Additional Image sizes.
		$image_sizes = $this->settings->get_setting( WP_SMUSH_PREFIX . 'image_sizes', false );
		$sizes       = WP_Smush::get_instance()->core()->image_dimensions();

		/**
		 * Add an additional item for full size.
		 * Do not use intermediate_image_sizes filter.
		 */
		$sizes['full'] = array();

		$is_pro   = WP_Smush::is_pro();
		$disabled = '';

		$setting_status = $this->settings->get( 'auto' );

		if ( ! empty( $sizes ) ) {
			?>

			<div class="wp-smush-image-size-list <?php echo $setting_status ? '' : ' sui-hidden'; ?>">

					<?php
					esc_html_e(
						'Every time you upload an image to your site, WordPress generates a
					resized version of that image for every default and/or custom image size that your theme has
					registered. This means there are multiple versions of your images in your media library. Choose
					the images sizes below that you would like optimized:',
						'wp-smushit'
					);
					?>

				<?php
				foreach ( $sizes as $size_k => $size ) {
					// If image sizes array isn't set, mark all checked ( Default Values ).
					if ( false === $image_sizes ) {
						$checked = true;
					} else {
						// WPMDUDEV hosting support: cast $size_k to string to properly work with object cache.
						$checked = is_array( $image_sizes ) ? in_array( (string) $size_k, $image_sizes, true ) : false;
					}
					// For free users, remove full size option.
					if ( 'full' === $size_k ) {
						continue;
					}
					?>

						<input type="checkbox" id="wp-smush-size-<?php echo esc_attr( $size_k ); ?>" <?php checked( $checked, true ); ?> name="wp-smush-image_sizes[]" value="<?php echo esc_attr( $size_k ); ?>" <?php echo esc_attr( $disabled ); ?>>

						<?php if ( isset( $size['width'], $size['height'] ) ) : ?>

								<?php echo esc_html( $size_k . ' (' . $size['width'] . 'x' . $size['height'] . ') ' ); ?>

						<?php else : ?>
							<?php echo esc_attr( $size_k ); ?>
								<?php if ( ! $is_pro ) : ?>
									<span class="sui-tag sui-tag-pro sui-tooltip sui-tooltip-constrained" data-tooltip="<?php esc_html_e( 'Join WPMU DEV to unlock multi-pass lossy compression', 'wp-smushit' ); ?>">
										<?php esc_html_e( 'PRO', 'wp-smushit' ); ?>

								<?php endif; ?>

						<?php endif; ?>

					<?php
				}
				?>

			<?php
		}
	}

	/**
	 * Prints Resize, Smush Original, and Backup settings.
	 *
	 * @param string $name  Name of the current setting being processed.
	 */
	public function full_size_options( $name = '' ) {
		// Continue only if original image option.
		if ( 'original' !== $name || ! WP_Smush::is_pro() ) {
			return;
		}

		foreach ( $this->full_size_group as $name ) {
			$setting_val = $this->settings->get( $name );
			$setting_key = WP_SMUSH_PREFIX . $name;
			?>

					<input type="checkbox" aria-describedby="<?php echo esc_attr( $setting_key ); ?>-desc" id="<?php echo esc_attr( $setting_key ); ?>" name="<?php echo esc_attr( $setting_key ); ?>" <?php checked( $setting_val, 1 ); ?> value="1">

					<label class="toggle-label <?php echo esc_attr( $setting_key . '-label' ); ?>" for="<?php echo esc_attr( $setting_key ); ?>" aria-hidden="true">

				<label for="<?php echo esc_attr( $setting_key ); ?>">
					<?php echo esc_html( WP_Smush::get_instance()->core()->settings[ $name ]['label'] ); ?>

					<?php echo esc_html( WP_Smush::get_instance()->core()->settings[ $name ]['desc'] ); ?>

			<?php
		}
	}

	/**
	 * Prints front end image size detection option.
	 *
	 * @param string $name  Name of the current setting being processed.
	 */
	public function detect_size_options( $name ) {
		// Only add to resize setting.
		if ( 'resize' !== $name ) {
			return;
		}

		foreach ( $this->resize_group as $name ) {
			$setting_val = $this->settings->get( $name );
			$setting_key = WP_SMUSH_PREFIX . $name;
			?>

					<input type="checkbox" aria-describedby="<?php echo esc_attr( $setting_key ); ?>-desc" id="<?php echo esc_attr( $setting_key ); ?>" name="<?php echo esc_attr( $setting_key ); ?>" <?php checked( $setting_val, 1, true ); ?> value="1">

					<label class="toggle-label <?php echo esc_attr( $setting_key . '-label' ); ?>" for="<?php echo esc_attr( $setting_key ); ?>" aria-hidden="true">

				<label for="<?php echo esc_attr( $setting_key ); ?>">
					<?php echo esc_html( WP_Smush::get_instance()->core()->settings[ $name ]['label'] ); ?>

					<?php echo esc_html( WP_Smush::get_instance()->core()->settings[ $name ]['desc'] ); ?>
					<?php if ( 'detection' === $name && $setting_val ) : ?>

								<?php
								printf(
									/* translators: %1$s: opening a tag, %2$s: closing a tag */
									esc_html__(
										'Incorrect image size highlighting is active. %1$sView the
									frontend%2$s of your website to see which images aren\'t the correct size
									for their containers.',
										'wp-smushit'
									),
									'',
									''
								);
								?>

					<?php elseif ( 'detection' === $name ) : ?>

								<?php
								esc_html_e(
									'Almost there! To finish activating this feature you must
								save your settings.',
									'wp-smushit'
								);
								?>

					<?php endif; ?>

			<?php
		}
	}

	/**
	 * Show directory smush result notice.
	 *
	 * If we are redirected from a directory smush finish page,
	 * show the result notice if success/fail count is available.
	 *
	 * @since 2.9.0
	 */
	public function smush_result_notice() {
		// Get the counts from transient.
		$items          = get_transient( 'wp-smush-show-dir-scan-notice' );
		$failed_items   = get_transient( 'wp-smush-dir-scan-failed-items' );
		$notice_message = esc_html__( 'All images failed to optimize.', 'wp-smushit' );
		$notice_class   = 'sui-notice-error';

		// Not all images optimized.
		if ( ! empty( $failed_items ) && ! empty( $items ) ) {
			$notice_message = sprintf(
				/* translators: %1$d: number of images smushed and %1$d number of failed. */
				esc_html__( '%1$d images were successfully optimized and %2$d images failed.', 'wp-smushit' ),
				absint( $items ),
				absint( $failed_items )
			);
			$notice_class = 'sui-notice-warning';
		} elseif ( ! empty( $items ) && empty( $failed_items ) ) {
			// Yay! All images were optimized.
			$notice_message = sprintf(
				/* translators: %d: number of images */
				esc_html__( '%d images were successfully optimized.', 'wp-smushit' ),
				absint( $items )
			);
			$notice_class = 'sui-notice-success';
		}

		// If we have counts, show the notice.
		if ( ! empty( $items ) || ! empty( $failed_items ) ) {
			// Delete the transients.
			delete_transient( 'wp-smush-show-dir-scan-notice' );
			delete_transient( 'wp-smush-dir-scan-failed-items' );
			?>
			<div class="sui-notice-top sui-can-dismiss <?php echo esc_attr( $notice_class ); ?>">

					<?php echo $notice_message; ?>

					<a role="button" href="#" aria-label="<?php esc_attr_e( 'Dismiss', 'wp-smushit' ); ?>" class="sui-icon-check">

			<?php
		}
	}

	/**************************
	 * META BOXES
	 */

	/**
	 * Summary meta box.
	 */
	public function dashboard_summary_metabox() {
		$core = WP_Smush::get_instance()->core();

		$resize_count = $core->mod->db->resize_savings( false, false, true );

		// Split human size to get format and size.
		$human = explode( ' ', $core->stats['human'] );

		$resize_savings = 0;
		// Get current resize savings.
		if ( ! empty( $core->stats['resize_savings'] ) && $core->stats['resize_savings'] > 0 ) {
			$resize_savings = size_format( $core->stats['resize_savings'], 1 );
		}

		$this->view(
			'meta-boxes/summary/meta-box',
			array(
				'human_format'    => empty( $human[1] ) ? 'B' : $human[1],
				'human_size'      => empty( $human[0] ) ? '0' : $human[0],
				'networkwide'     => $this->settings->is_network_enabled(),
				'remaining'       => $core->remaining_count,
				'resize_count'    => ! $resize_count ? 0 : $resize_count,
				'resize_enabled'  => (bool) $this->settings->get( 'resize' ),
				'resize_savings'  => $resize_savings,
				'stats_percent'   => $core->stats['percent'] > 0 ? number_format_i18n( $core->stats['percent'], 1 ) : 0,
				'total_optimized' => $core->stats['total_images'],
			)
		);
	}

	/**
	 * Bulk smush meta box.
	 *
	 * Container box to handle bulk smush actions. Show progress bars,
	 * bulk smush action buttons etc. in this box.
	 */
	public function bulk_smush_metabox() {
		$core = WP_Smush::get_instance()->core();

		$upgrade_url = add_query_arg(
			array(
				'utm_source'   => 'smush',
				'utm_medium'   => 'plugin',
				'utm_campaign' => 'smush_stats_enable_lossy',
			),
			$core->upgrade_url
		);

		$bulk_upgrade_url = add_query_arg(
			array(
				'utm_source'   => 'smush',
				'utm_medium'   => 'plugin',
				'utm_campaign' => 'smush_bulksmush_limit_notice',
			),
			$core->upgrade_url
		);

		$pro_upgrade_url = add_query_arg(
			array(
				'utm_source'   => 'smush',
				'utm_medium'   => 'plugin',
				'utm_campaign' => 'smush_bulksmush_upsell_notice',
			),
			$core->upgrade_url
		);

		$this->view(
			'meta-boxes/bulk/meta-box',
			array(
				'all_done'         => $core->smushed_count === $core->total_count && empty( $core->resmush_ids ),
				'bulk_upgrade_url' => $bulk_upgrade_url,
				'core'             => $core,
				'hide_pagespeed'   => get_site_option( WP_SMUSH_PREFIX . 'hide_pagespeed_suggestion' ),
				'is_pro'           => WP_Smush::is_pro(),
				'lossy_enabled'    => $core->mod->smush->lossy_enabled,
				'pro_upgrade_url'  => $pro_upgrade_url,
				'upgrade_url'      => $upgrade_url,
			)
		);
	}

	/**
	 * Settings meta box.
	 *
	 * Free and pro version settings are shown in same section. For free users, pro settings won't be shown.
	 * To print full size smush, resize and backup in group, we hook at `smush_setting_column_right_end`.
	 */
	public function bulk_settings_metabox() {
		// Get all grouped settings that can be skipped.
		$grouped_settings = array_merge( $this->resize_group, $this->full_size_group, $this->integration_group, array( 'webp', 'auto_resize' ) );

		$this->view(
			'meta-boxes/bulk-settings/meta-box',
			array(
				'basic_features'      => WP_Smush_Core::$basic_features,
				'cdn_enabled'         => $this->settings->get( 'cdn' ),
				'grouped_settings'    => $grouped_settings,
				'opt_networkwide_val' => $this->settings->is_network_enabled(),
				'settings'            => $this->settings->get(),
				'settings_data'       => WP_Smush::get_instance()->core()->settings,
			)
		);
	}

	/**
	 * Pro features list box to show after settings.
	 */
	public function pro_features_metabox() {
		// Upgrade url for upsell.
		$upsell_url = add_query_arg(
			array(
				'utm_source'   => 'smush',
				'utm_medium'   => 'plugin',
				'utm_campaign' => 'smush-advanced-settings-upsell',
			),
			WP_Smush::get_instance()->core()->upgrade_url
		);

		$this->view(
			'meta-boxes/pro-features/meta-box',
			array(
				'upsell_url' => $upsell_url,
			)
		);
	}

	/**
	 * Pro features meta box header.
	 */
	public function pro_features_metabox_header() {
		// Upgrade url with analytics keys.
		$upgrade_url = add_query_arg(
			array(
				'utm_source'   => 'smush',
				'utm_medium'   => 'plugin',
				'utm_campaign' => 'smush_advancedsettings_profeature_tag',
			),
			WP_Smush::get_instance()->core()->upgrade_url
		);

		$this->view(
			'meta-boxes/pro-features/meta-box-header',
			array(
				'title'       => __( 'Pre Features', 'wp-smushit' ),
				'upgrade_url' => $upgrade_url,
			)
		);
	}

	/**
	 * Directory Smush meta box.
	 */
	public function directory_smush_metabox() {
		// Reset the bulk limit transient.
		if ( ! WP_Smush::is_pro() ) {
			WP_Smush_Core::check_bulk_limit( true, 'dir_sent_count' );
		}

		$core = WP_Smush::get_instance()->core();

		$upgrade_url = add_query_arg(
			array(
				'utm_source'   => 'smush',
				'utm_medium'   => 'plugin',
				'utm_campaign' => 'smush_directorysmush_limit_notice',
			),
			$core->upgrade_url
		);

		$errors = 0;
		$images = array();
		if ( isset( $_GET['scan'] ) && 'done' === sanitize_text_field( wp_unslash( $_GET['scan'] ) ) ) {
			$images = $core->mod->dir->get_image_errors();
			$errors = $core->mod->dir->get_image_errors_count();
		}

		$this->view(
			'meta-boxes/directory/meta-box',
			array(
				'errors'      => $errors,
				'images'      => $images,
				'root_path'   => $core->mod->dir->get_root_path(),
				'upgrade_url' => $upgrade_url,
			)
		);
	}

	/**
	 * Integrations meta box.
	 *
	 * Free and pro version settings are shown in same section. For free users, pro settings won't be shown.
	 * To print full size smush, resize and backup in group, we hook at `smush_setting_column_right_end`.
	 */
	public function integrations_metabox() {
		$core = WP_Smush::get_instance()->core();

		$upsell_url = add_query_arg(
			array(
				'utm_source'   => 'smush',
				'utm_medium'   => 'plugin',
				'utm_campaign' => 'smush-nextgen-settings-upsell',
			),
			$core->upgrade_url
		);

		$this->view(
			'meta-boxes/integrations/meta-box',
			array(
				'basic_features'    => WP_Smush_Core::$basic_features,
				'is_pro'            => WP_Smush::is_pro(),
				'integration_group' => $this->integration_group,
				'settings'          => $this->settings->get(),
				'settings_data'     => $core->settings,
				'upsell_url'        => $upsell_url,
			)
		);
	}

	/**
	 * Integrations meta box footer.
	 */
	public function integrations_metabox_footer() {
		/**
		 * Filter to enable/disable submit button in integration settings.
		 *
		 * @param bool $show_submit Should show submit?
		 */
		$this->view(
			'meta-boxes/integrations/meta-box-footer',
			array(
				'show_submit' => apply_filters( 'wp_smush_integration_show_submit', false ),
			)
		);
	}

	/**
	 * CDN meta box (for free users).
	 *
	 * @since 3.0
	 */
	public function cdn_upsell_metabox() {
		$upgrade_url = add_query_arg(
			array(
				'utm_source'   => 'smush',
				'utm_medium'   => 'plugin',
				'utm_campaign' => 'smush_cdn_upgrade_button',
			),
			WP_Smush::get_instance()->core()->upgrade_url
		);

		$this->view(
			'meta-boxes/cdn/upsell-meta-box',
			array(
				'upgrade_url' => $upgrade_url,
			)
		);
	}

	/**
	 * Upsell meta box header.
	 *
	 * @since 3.0
	 */
	public function cdn_upsell_metabox_header() {
		$this->view(
			'meta-boxes/cdn/upsell-meta-box-header',
			array(
				'title' => __( 'CDN', 'wp-smushit' ),
			)
		);
	}

	/**
	 * CDN meta box.
	 *
	 * @since 3.0
	 */
	public function cdn_metabox() {
		// Available values: warning (inactive), success (active) or error (expired).
		$status_msg = array(
			'warning' => __( 'CDN is not yet active. Configure your settings below and click Activate.', 'wp-smushit' ),
			'notice'  => __(
				'Your settings have been saved and changes are now propagating to the CDN. Changes can take up to 30
				minutes to take effect but your images will continue to be served in the mean time, please be patient.',
				'wp-smushit'
			),
			'info'    => __( 'Your media is currently being served from the WPMU DEV CDN.', 'wp-smushit' ),
			'error'   => __(
				'CDN is inactive. You have gone over your 30 day cap so we've stopped serving your images.
					Upgrade your plan now to reactivate this service.',
				'wp-smushit'
			),
		);

		$cdn_status = 'warning';

		$cdn = $this->settings->get_setting( WP_SMUSH_PREFIX . 'cdn_status' );
		if ( $cdn->cdn_enabled && WP_Smush::get_instance()->core()->mod->cdn->get_status() ) {
			// 1073741824 = 1024 (kb) * 1024 (mb) * 1024 (gb)
			$cdn_status = $cdn->bandwidth / 1073741824 < $cdn->bandwidth_plan ? 'info' : 'error';
		}

		if ( isset( $cdn->cdn_enabling ) && $cdn->cdn_enabling ) {
			$cdn_status = 'notice';
		}

		$this->view(
			'meta-boxes/cdn/meta-box',
			array(
				'cdn'           => $cdn,
				'cdn_group'     => $this->cdn_group,
				'settings'      => $this->settings->get(),
				'settings_data' => WP_Smush::get_instance()->core()->settings,
				'status'        => $cdn_status,
				'status_msg'    => $status_msg,
			)
		);
	}

	/**
	 * CDN meta box header.
     *
     * @since 3.0
	 */
	public function cdn_metabox_header() {
	    $this->view(
            'meta-boxes/cdn/meta-box-header',
            array(
                'title'   => __( 'CDN', 'wp-smushit' ),
                'tooltip' => __( 'This feature is likely to work without issue, however our CDN is in beta stage and some issues are still present.', 'wp-smushit' ),
            )
        );
    }

	/**
	 * Settings meta box.
	 *
	 * @since 3.0
	 */
	public function settings_metabox() {
		$link = WP_Smush::is_pro() ? 'https://premium.wpmudev.org/translate/projects/wp-smushit/' : 'https://translate.wordpress.org/projects/wp-plugins/wp-smushit';

		$site_locale = get_locale();

		if ( 'en_US' === $site_locale ) {
			$site_language = 'English';
		} else {
			require_once ABSPATH . 'wp-admin/includes/translation-install.php';
			$translations  = wp_get_available_translations();
			$site_language = $translations[ $site_locale ]['native_name'];
		}

		$this->view(
			'meta-boxes/settings/meta-box',
			array(
				'site_language'    => $site_language,
				'translation_link' => $link,
			)
		);
	}

}


text:
<?php

use Baethon\Phln as p;

class PathEqTest extends \PHPUnit\Framework\TestCase
{
    public function test_it_checks_value()
    {
        $foo = ['bar' => ['baz' => 1]];
        $this->assertTrue(p\path_eq($foo, 'bar.baz', 1));
    }
}

redpajama_set_name: RedPajamaGithub


text:
if (WIN32)
	# With a Windows build the debug and release libraries are different
	# The standard paths are also different from a linux system

	# Find the header directory
	find_path(MSGPACK_INCLUDE_DIR msgpack.h
	  	HINTS ${CMAKE_SOURCE_DIR}/../msgpack-c/include)

	# Find the release library
  	find_library(MSGPACK_LIBRARY_RELEASE msgpack
               ${MSGPACK_INCLUDE_DIR}/../build/Release
               /usr/local/lib
               /usr/lib)

    # Find the debug library
  	find_library(MSGPACK_LIBRARY_DEBUG msgpack
               ${MSGPACK_INCLUDE_DIR}/../build/Debug
               /usr/local/lib
               /usr/lib)

else ()
	# With a Linux build use PkgConfig to help find the correct parameters
	find_package(PkgConfig)
	pkg_check_modules(PC_MSGPACK QUIET msgpack)
	set(MSGPACK_DEFINITIONS ${PC_MSGPACK_CFLAGS_OTHER})

	# Find the header directory
	find_path(MSGPACK_INCLUDE_DIR msgpack.h
	  HINTS ${PC_MSGPACK_INCLUDE_DIR} ${PC_MSGPACK_INCLUDE_DIRS}
	  PATH_SUFFIXES msgpack)

	# Get the GCC compiler version
	exec_program(${CMAKE_CXX_COMPILER}
	            ARGS ${CMAKE_CXX_COMPILER_ARG1} -dumpversion
	            OUTPUT_VARIABLE _gcc_COMPILER_VERSION
	            OUTPUT_STRIP_TRAILING_WHITESPACE )

	# Try to find a library that was compiled with the same compiler version as we currently use.
	find_library(MSGPACK_LIBRARY_RELEASE
		NAMES libjson_linux-gcc-${_gcc_COMPILER_VERSION}_libmt.so libmsgpack.so
		HINTS ${PC_MSGPACK_LIBDIR} ${PC_MSGPACK_LIBRARY_DIRS}
		PATHS /usr/lib /usr/local/lib)

	if (MSGPACK_LIBRARY_RELEASE)
		# create the debug library path variable so that it can be set manually if needed
		set(MSGPACK_LIBRARY_DEBUG ${MSGPACK_LIBRARY_RELEASE} CACHE FILEPATH "")
	endif ()

endif ()

if (MSGPACK_INCLUDE_DIR)
	# set the correct variable name for the header directories
	set(MSGPACK_INCLUDE_DIRS ${MSGPACK_INCLUDE_DIR})

	# needed to use find_package_handle_standard_args
	include(FindPackageHandleStandardArgs)

    if (MSGPACK_LIBRARY_RELEASE AND MSGPACK_LIBRARY_DEBUG)
    	# set the libaries varible to use the release and debug versions
    	find_package_handle_standard_args(MSGPACK DEFAULT_MSG MSGPACK_INCLUDE_DIR MSGPACK_LIBRARY_RELEASE MSGPACK_LIBRARY_DEBUG)
		set(MSGPACK_LIBRARIES optimized ${MSGPACK_LIBRARY_RELEASE} debug ${MSGPACK_LIBRARY_DEBUG})

	elseif (MSGPACK_LIBRARY_RELEASE)
		# only the release library is available
		find_package_handle_standard_args(MSGPACK DEFAULT_MSG MSGPACK_INCLUDE_DIR MSGPACK_LIBRARY_RELEASE)
		set(MSGPACK_LIBRARIES optimized ${MSGPACK_LIBRARY_RELEASE})

	elseif (MSGPACK_LIBRARY_DEBUG)
		# only the debug library is available
		find_package_handle_standard_args(MSGPACK DEFAULT_MSG MSGPACK_INCLUDE_DIR MSGPACK_LIBRARY_DEBUG)
		set(MSGPACK_LIBRARIES debug ${MSGPACK_LIBRARY_DEBUG})

    else ()
    	# neither library is available - give standard error message
		find_package_handle_standard_args(MSGPACK DEFAULT_MSG MSGPACK_INCLUDE_DIR MSGPACK_LIBRARY_RELEASE MSGPACK_LIBRARY_DEBUG)

    endif ()
else ()
	# Didn't find the headers - give a standard error message
	find_package_handle_standard_args(MSGPACK DEFAULT_MSG MSGPACK_INCLUDE_DIR)
endif ()

mark_as_advanced(MSGPACK_INCLUDE_DIR MSGPACK_LIBRARY_RELEASE MSGPACK_LIBRARY_DEBUG)


text:
<!DOCTYPE html>

<link rel="stylesheet" href="/adorn/adorn.css" />

hello.api( me )

Listen to the event "auth.login", and call hello( network ).api( 'me' ).then( handler )

Demo

<button id='google' class="profile">google</button>
<button id='facebook' class="profile">facebook</button>
<button id='windows' class="profile">windows</button>
<button id='twitter' class="profile">twitter</button>

Code


text:
import { Component, OnInit } from '@angular/core';
import { ApiService } from '../../services/api/api.service';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {

  twitchievements: any
  twitchievementsKeys: any
  userTwitchievements: any
  userTwitchievementsKeys: any
  username: any
  emoteFetch: any
  error: any

  constructor(public apiService: ApiService) {

    this.apiService.getStats()
    .subscribe(res => {
      this.twitchievements = res.streamTwitchievements;
      this.userTwitchievements = res.userTwitchievements;

      // Finally set our twitchievements keys
      this.twitchievementsKeys = [];
      if (this.twitchievements) {
        this.twitchievementsKeys = Object.keys(this.twitchievements);
      }
      this.userTwitchievementsKeys = [];
      if(this.userTwitchievements) {
        this.userTwitchievementsKeys = Object.keys(this.userTwitchievements);
      }
    }, err => {
      this.error = err.error;
    });

    this.username = localStorage.getItem('twitchUsername');
  }

  ngOnInit() {
  }

  getDate(dateString) {
    return new Date(dateString).toLocaleDateString();
  }

}


text:
from nanpy.arduinotree import ArduinoTree
from nanpy.serialmanager import SerialManager

def fw_check():
    connection = SerialManager()
    a = ArduinoTree(connection=connection)

    print('Firmware classes enabled in cfg.h:')
    print('  ' + '\n  '.join(a.connection.classinfo.firmware_name_list))

    d = a.define.as_dict
    print(
        '\nYour firmware was built on:\n  %s %s' %
        (d.get('__DATE__'), d.get('__TIME__')))

if __name__ == '__main__':
    fw_check()


text:
<?php

namespace backend\models;

use Yii;

/**
 * This is the model class for table "f_news".
 *
 * @property integer $id
 * @property string $title
 * @property string $descr
 * @property string $text
 * @property string $img
 * @property integer $id_champ
 * @property integer $id_country
 * @property integer $id_club
 * @property integer $id_soccer
 * @property integer $counter
 * @property integer $count_comment
 * @property integer $like
 * @property string $liked_users
 * @property integer $dislike
 * @property string $dislike_users
 * @property integer $date
 * @property integer $status
 */
class News extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'f_news';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'descr', 'text', 'date', 'status'], 'required'],
            [['descr', 'text', 'liked_users', 'dislike_users'], 'string'],
            [['id_champ', 'id_country', 'id_club', 'id_soccer', 'counter', 'count_comment', 'like', 'dislike', 'date', 'status'], 'integer'],
            [['title', 'img'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'title' => Yii::t('app', 'Nomi'),
            'descr' => Yii::t('app', 'Qisqacha mazmuni'),
            'text' => Yii::t('app', 'Yangilik'),
            'img' => Yii::t('app', 'Rasm'),
            'id_champ' => Yii::t('app', 'Championat'),
            'id_country' => Yii::t('app', 'Davlat'),
            'id_club' => Yii::t('app', 'Klub'),
            'id_soccer' => Yii::t('app', 'O`yinchi'),
            'counter' => Yii::t('app', 'Hisoblagich'),
            'counter' => Yii::t('app', 'Counter'),
            'count_comment' => Yii::t('app', 'Count Comment'),
            'like' => Yii::t('app', 'Like'),
            'liked_users' => Yii::t('app', 'Liked Users'),
            'dislike' => Yii::t('app', 'Dislike'),
            'dislike_users' => Yii::t('app', 'Dislike Users'),
            'date' => Yii::t('app', 'Kun vaqt'),
            'status' => Yii::t('app', 'Status'),
        ];
    }

    public function getMatches()
    {
        //return $this->hasMany(Order::className(), ['customer_id' => 'id']);
        return $this->hasMany(Matches::className(), ['id_champ' => 'id']);
    }

    /**
     * @inheritdoc
     */

    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            $this->date = strtotime($this->date);
            $this->counter=$this->counter+1;
            return true;
        } else {
            return false;
        }
    }

    public static function getLast3News(){
        $model = static::findAll([1,2,3]);//->orderBy('id')->all();
        if ($model !== null) {
            return $model;
        } else {
            throw new \yii\web\NotFoundHttpException('The requested post does not exist.');
        }
    }

    public function getClubs()
    {
        return $this->hasOne(Clubs::className(), ['id' => 'id_club']);
    }

    public function getChamp()
    {
        return $this->hasOne(Champs::className(), ['id' => 'id_champ']);
    }

    public function getCountry()
    {
        return $this->hasOne(Countries::className(), ['id' => 'id_country']);
    }

    public function getSoccer()
    {
        return $this->hasOne(Soccers::className(), ['id' => 'id_soccer']);
    }
}


text:
package org.zstack.test.kvm;

import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.componentloader.ComponentLoader;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.header.configuration.DiskOfferingInventory;
import org.zstack.header.identity.SessionInventory;
import org.zstack.header.vm.VmInstanceInventory;
import org.zstack.header.volume.VolumeInventory;
import org.zstack.kvm.KVMAgentCommands.AttachDataVolumeCmd;
import org.zstack.kvm.KVMAgentCommands.StartVmCmd;
import org.zstack.kvm.KVMAgentCommands.VolumeTO;
import org.zstack.kvm.KVMGlobalConfig;
import org.zstack.simulator.kvm.KVMSimulatorConfig;
import org.zstack.test.Api;
import org.zstack.test.ApiSenderException;
import org.zstack.test.DBUtil;
import org.zstack.test.WebBeanConstructor;
import org.zstack.test.deployer.Deployer;
import org.zstack.test.storage.backup.sftp.TestSftpBackupStorageDeleteImage2;
import org.zstack.utils.Utils;
import org.zstack.utils.logging.CLogger;

public class TestKvmVolumeCacheMode1 {
    CLogger logger = Utils.getLogger(TestSftpBackupStorageDeleteImage2.class);
    Deployer deployer;
    Api api;
    ComponentLoader loader;
    CloudBus bus;
    DatabaseFacade dbf;
    SessionInventory session;
    KVMSimulatorConfig config;
    String mode = "writethrough";

    @Before
    public void setUp() throws Exception {
        DBUtil.reDeployDB();
        WebBeanConstructor con = new WebBeanConstructor();
        deployer = new Deployer("deployerXml/kvm/TestKvmVolumeCacheMode1.xml", con);
        deployer.addSpringConfig("KVMRelated.xml");
        deployer.load();

        loader = deployer.getComponentLoader();
        bus = loader.getComponent(CloudBus.class);
        dbf = loader.getComponent(DatabaseFacade.class);

        KVMGlobalConfig.LIBVIRT_CACHE_MODE.updateValue(mode);

        deployer.build();
        api = deployer.getApi();
        config = loader.getComponent(KVMSimulatorConfig.class);
        session = api.loginAsAdmin();
    }

	@Test
	public void test() throws ApiSenderException {
        StartVmCmd cmd = config.startVmCmd;
        for (VolumeTO to : cmd.getDataVolumes()) {
            Assert.assertEquals(mode, to.getCacheMode());
        }
        Assert.assertEquals(mode, cmd.getRootVolume().getCacheMode());

        DiskOfferingInventory dinv = deployer.diskOfferings.get("DiskOffering");
        VolumeInventory vol = api.createDataVolume("data", dinv.getUuid());
        VmInstanceInventory vm = deployer.vms.get("TestVm");
        api.attachVolumeToVm(vm.getUuid(), vol.getUuid());
        Assert.assertEquals(1, config.attachDataVolumeCmds.size());
        AttachDataVolumeCmd acmd = config.attachDataVolumeCmds.get(0);
        Assert.assertEquals(mode, acmd.getVolume().getCacheMode());
	}
}


text:
.. py:currentmodule:: cantera

Chemical Kinetics
=================

.. autoclass:: Kinetics(infile='', phaseid='', phases=())

.. autoclass:: ReactionPathDiagram(Kinetics kin, str element)


text:
CREATE DATABASE users_prod;
CREATE DATABASE users_stage;
CREATE DATABASE users_dev;
CREATE DATABASE users_test;


text:
title: Get support.
buttons:
  - text: See hours
    url: hours
---
##UNIX Lab Tutors
Stuck on labs? Get peer help. Unix Lab tutors are available everyday for any computer science question.


text:
import _ from 'lodash';
import cookie from 'react-cookie';

const tweets = [
	{
		id:"1",
		messageText: 'Hello World',
		retweet: 1,
		likes: 2

	},
	{
		id:"2",
		messageText: 'This is a new message',
		retweet: 10,
		likes: 42
	},
	{
		id:"2",
		messageText: 'I am Margot , girlfriend of Lupin',
		retweet: 14,
		likes: 22
	},
];
const facebookStatuses = [
	{
		id:"3",
		messageText: 'Hello from Facebook',
		shares: 3,
		likes: 1
	},
	{
		id:"4",
		messageText: 'Bla bla bla',
		shares: 22,
		likes: 4
	},
	{
		id:"5",
		messageText: 'Hello, I am Dylan..Bob Dylan',
		shares: 12,
		likes: 34
	},
];

const users = [
	{
		id: "1",
		username: "nicola",
		password: "password",
		age: 39,
		city: "Asti"
	},
	{
		id: "2",
		username: "mario",
		password: "mario123",
		age: 24,
		city: "Torino"
	},
];

export function getTweets(){
	return new Promise((resolve, reject) => {
		setTimeout(resolve.bind(null, tweets), 2000);
	});
}

export function getFacebookStatuses(){
	return new Promise((resolve, reject) => {
		setTimeout(resolve.bind(null, facebookStatuses), 5000);
	});
}

export function getTweet(myId){
	return new Promise((resolve, reject) => {
		const message = _.find(tweets, {id: myId});

		if (message){
			resolve(message);
		}else{
			reject("Message not found");
		}

	});
}

export function getFacebookStatus(myId){
	return new Promise((resolve, reject) => {

		const message = _.find(facebookStatuses, {id:myId});
		if (message){
			resolve(message);
		}else{
			reject("Message not found");
		}

	});
}

export function logout(){
	return new Promise((resolve, reject) => {
		const cookieAuthentication = 'cookieMonster';
		cookie.remove(cookieAuthentication);
		resolve();
	});
}

export function login(username, password){
	return new Promise((resolve, reject) => {
		const user = _.find(users, {username: username, password: password});

		if(user){
			console.log("User Login: ",user.username,user.password);
			const cookieAuthentication = 'cookieMonster';
			cookie.save(cookieAuthentication, 'myBeautifulCookie');
			resolve();
		}else{
			reject("Username / password are invalid");
		}
	});
}

export function getUser(username){
	return new Promise((resolve, reject) => {
		const user = _.find(users, {username: username});
		console.log("Get User",user.username );
		if(user){
			resolve(user);
		}else{
			reject("User cannot be retrieved....");
		}
	});
}


text:
package api_test

import (
	"encoding/json"
	"flag"
	"fmt"
	"reflect"
	"testing"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	_ "github.com/GoogleCloudPlatform/kubernetes/pkg/api/v1beta1"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
	"github.com/fsouza/go-dockerclient"
	"github.com/google/gofuzz"
)

var fuzzIters = flag.Int("fuzz_iters", 50, "How many fuzzing iterations to do.")

// apiObjectFuzzer can randomly populate api objects.
var apiObjectFuzzer = fuzz.New().NilChance(.5).NumElements(1, 1).Funcs(
	func(j *api.JSONBase, c fuzz.Continue) {
		// We have to customize the randomization of JSONBases because their
		// APIVersion and Kind must remain blank in memory.
		j.APIVersion = ""
		j.Kind = ""
		j.ID = c.RandString()
		// TODO: Fix JSON/YAML packages and/or write custom encoding
		// for uint64's. Somehow the LS *byte* of this is lost, but
		// only when all 8 bytes are set.
		j.ResourceVersion = c.RandUint64() >> 8
		j.SelfLink = c.RandString()

		var sec, nsec int64
		c.Fuzz(&sec)
		c.Fuzz(&nsec)
		j.CreationTimestamp = util.Unix(sec, nsec).Rfc3339Copy()
	},
	func(intstr *util.IntOrString, c fuzz.Continue) {
		// util.IntOrString will panic if its kind is set wrong.
		if c.RandBool() {
			intstr.Kind = util.IntstrInt
			intstr.IntVal = int(c.RandUint64())
			intstr.StrVal = ""
		} else {
			intstr.Kind = util.IntstrString
			intstr.IntVal = 0
			intstr.StrVal = c.RandString()
		}
	},
	func(u64 *uint64, c fuzz.Continue) {
		// TODO: uint64's are NOT handled right.
		*u64 = c.RandUint64() >> 8
	},
	func(pb map[docker.Port][]docker.PortBinding, c fuzz.Continue) {
		// This is necessary because keys with nil values get omitted.
		// TODO: Is this a bug?
		pb[docker.Port(c.RandString())] = []docker.PortBinding{
			{c.RandString(), c.RandString()},
			{c.RandString(), c.RandString()},
		}
	},
	func(pm map[string]docker.PortMapping, c fuzz.Continue) {
		// This is necessary because keys with nil values get omitted.
		// TODO: Is this a bug?
		pm[c.RandString()] = docker.PortMapping{
			c.RandString(): c.RandString(),
		}
	},
)

func objDiff(a, b interface{}) string {
	ab, err := json.Marshal(a)
	if err != nil {
		panic("a")
	}
	bb, err := json.Marshal(b)
	if err != nil {
		panic("b")
	}
	return util.StringDiff(string(ab), string(bb))

	// An alternate diff attempt, in case json isn't showing you
	// the difference. (reflect.DeepEqual makes a distinction between
	// nil and empty slices, for example.)
	return util.StringDiff(
		fmt.Sprintf("%#v", a),
		fmt.Sprintf("%#v", b),
	)
}

func runTest(t *testing.T, source interface{}) {
	name := reflect.TypeOf(source).Elem().Name()
	apiObjectFuzzer.Fuzz(source)
	j, err := api.FindJSONBase(source)
	if err != nil {
		t.Fatalf("Unexpected error %v for %#v", err, source)
	}
	j.SetKind("")
	j.SetAPIVersion("")

	data, err := api.Encode(source)
	if err != nil {
		t.Errorf("%v: %v (%#v)", name, err, source)
		return
	}

	obj2, err := api.Decode(data)
	if err != nil {
		t.Errorf("%v: %v", name, err)
		return
	} else {
		if !reflect.DeepEqual(source, obj2) {
			t.Errorf("1: %v: diff: %v", name, objDiff(source, obj2))
			return
		}
	}
	obj3 := reflect.New(reflect.TypeOf(source).Elem()).Interface()
	err = api.DecodeInto(data, obj3)
	if err != nil {
		t.Errorf("2: %v: %v", name, err)
		return
	} else {
		if !reflect.DeepEqual(source, obj3) {
			t.Errorf("3: %v: diff: %v", name, objDiff(source, obj3))
			return
		}
	}
}

func TestTypes(t *testing.T) {
	table := []interface{}{
		&api.PodList{},
		&api.Pod{},
		&api.ServiceList{},
		&api.Service{},
		&api.ReplicationControllerList{},
		&api.ReplicationController{},
		&api.MinionList{},
		&api.Minion{},
		&api.Status{},
		&api.ServerOpList{},
		&api.ServerOp{},
		&api.ContainerManifestList{},
		&api.Endpoints{},
		&api.Binding{},
	}
	for _, item := range table {
		// Try a few times, since runTest uses random values.
		for i := 0; i < *fuzzIters; i++ {
			runTest(t, item)
		}
	}
}

func TestEncode_NonPtr(t *testing.T) {
	pod := api.Pod{
		Labels: map[string]string{"name": "foo"},
	}
	obj := interface{}(pod)
	data, err := api.Encode(obj)
	obj2, err2 := api.Decode(data)
	if err != nil || err2 != nil {
		t.Fatalf("Failure: '%v' '%v'", err, err2)
	}
	if _, ok := obj2.(*api.Pod); !ok {
		t.Fatalf("Got wrong type")
	}
	if !reflect.DeepEqual(obj2, &pod) {
		t.Errorf("Expected:\n %#v,\n Got:\n %#v", &pod, obj2)
	}
}

func TestEncode_Ptr(t *testing.T) {
	pod := &api.Pod{
		Labels: map[string]string{"name": "foo"},
	}
	obj := interface{}(pod)
	data, err := api.Encode(obj)
	obj2, err2 := api.Decode(data)
	if err != nil || err2 != nil {
		t.Fatalf("Failure: '%v' '%v'", err, err2)
	}
	if _, ok := obj2.(*api.Pod); !ok {
		t.Fatalf("Got wrong type")
	}
	if !reflect.DeepEqual(obj2, pod) {
		t.Errorf("Expected:\n %#v,\n Got:\n %#v", &pod, obj2)
	}
}

func TestBadJSONRejection(t *testing.T) {
	badJSONMissingKind := []byte(`{ }`)
	if _, err := api.Decode(badJSONMissingKind); err == nil {
		t.Errorf("Did not reject despite lack of kind field: %s", badJSONMissingKind)
	}
	badJSONUnknownType := []byte(`{"kind": "bar"}`)
	if _, err1 := api.Decode(badJSONUnknownType); err1 == nil {
		t.Errorf("Did not reject despite use of unknown type: %s", badJSONUnknownType)
	}
	/*badJSONKindMismatch := []byte(`{"kind": "Pod"}`)
	if err2 := DecodeInto(badJSONKindMismatch, &Minion{}); err2 == nil {
		t.Errorf("Kind is set but doesn't match the object type: %s", badJSONKindMismatch)
	}*/
}


text:
+++

categories="article"
date="2012-05-29T01:14:53+03:00"
issue="2012-01"
issue_name="2012 - #01"
issue_id="1"
number="10"
file = "https://static.nuclear-power-engineering.ru/articles/2012/01/10.pdf"
first_page="80"
last_page="90"
udc="621.039.534"
title="Experimental Study of Flow Hydrodynamics Lead Coolant and Water through the Experimental Section «Throttle Clearance-Ring"
original_title="Экспериментальное исследование гидродинамики течения свинцового теплоносителя и воды через экспериментальный участок «дроссель-кольцевой зазор»"
authors=["BeznosovAV", "AntonenkovMA", "BokovaTA", "YarmonovMV", "MakhovKA", "MolodtsovAA"]
rubric = "thermalphysics"
rubric_name = "Thermal physics and thermal hydraulics"
outputs=["HTML", "DOI"]
doi="https://doi.org/10.26583/npe.2012.1.10"

+++

A research and comparison of the hydraulic characteristics of the water and lead coolant (T = 400–500°С) flow in the system of local hydraulic resistances «throttle-annular gap» have been done at the Alekseev Nizhny Novgorod State Technical University. During the experiments the magnitude of the relative clearance (2Д/d = 0,018; 0,036; 0,056) was varied with the static and rotated shaft. The average speed inside the annular gap ranged between 0,01 and 0,1 m/sec, the coolant was saturated with the oxygen.

A slider bearing working in the medium of the heavy liquid metal coolants is one of the main elements which influence the efficiency of the main circulating pumps in the reactor loops with HLMC.

The operating efficiency of the slider bearing is mainly determined with the correct choice of its constructive relation: a relative annular gap, relative width, angle of contact.

The results of the experimental research have shown that the difference between hydraulic characteristics of water and HLMC coolants in the experimental plot «throttle-annular gap» exists. It makes the usage of the traditional lubricating fluid in the methods of analysis of the hydrostatic sliding bearings for the pumps in the HLMC incorrect.


text:
@interface HYBSecondDemoController ()

@property (weak, nonatomic) IBOutlet UIButton *constraitButton;
@property (weak, nonatomic) IBOutlet UIButton *noneConstraitButton;
@property (weak, nonatomic) IBOutlet UIButton *avgButton1;
@property (weak, nonatomic) IBOutlet UIButton *avgButton2;

@property (weak, nonatomic) IBOutlet UIButton *avgButton3;

- (IBAction)changeAvg:(id)sender;
@property (nonatomic, assign) BOOL isAnimating;
@property (nonatomic, assign) BOOL isSelected;

@property (weak, nonatomic) IBOutlet UILabel *label1;
@property (weak, nonatomic) IBOutlet UILabel *label2;
@property (weak, nonatomic) IBOutlet UIView *bgView;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UILabel *scLabel;

@end

@implementation HYBSecondDemoController

- (void)viewDidLoad {
    [super viewDidLoad];

  self.view.backgroundColor = [UIColor whiteColor];

  WS(self);
  [self.constraitButton mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.mas_equalTo(20);
    make.right.mas_equalTo(-20);
    make.top.mas_equalTo(100);
  }];

  // 左边对齐,等宽/高,上下相关20px
  [self.noneConstraitButton mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.right.height.equalTo(self.constraitButton);
        make.top.equalTo(self.constraitButton.mas_bottom).offset(20);
  }];

  // 让三个按钮平分
  [self.avgButton1 mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.mas_equalTo(20);
    make.height.mas_equalTo(30);
    make.top.mas_equalTo(weakObject.noneConstraitButton.mas_bottom).offset(100);
    make.width.mas_equalTo((kScreenWidth - 40 - 40) / 3);
  }];

//  [self.avgButton2 mas_makeConstraints:^(MASConstraintMaker *make) {
//    make.width.top.height.mas_equalTo(weakObject.avgButton1);
//    make.left.mas_equalTo(weakObject.avgButton1.mas_right).offset(20);
//  }];

  [self.avgButton3 mas_makeConstraints:^(MASConstraintMaker *make) {
    make.width.top.height.mas_equalTo(weakObject.avgButton1);
    make.right.mas_equalTo(weakObject.view).offset(-20);
  }];

  [self.avgButton2 mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.height.mas_equalTo(weakObject.avgButton1);
    make.left.mas_equalTo(weakObject.avgButton1.mas_right).offset(20);
    make.right.mas_equalTo(weakObject.avgButton3.mas_left).offset(-20);
  }];

  self.isSelected = NO;

// //
  //
//  self.label1.text = @"mas_remakeConstraints is similar to mas_updateConstraints, but instead of updating constant values, it will remove all of its contraints before installing them again. This lets you provide different constraints without having to keep around references to ones which you want to remove.";
//  self.label2.text = @"label2 label2 label2";
//
//  [self.label1 mas_makeConstraints:^(MASConstraintMaker *make) {
//    make.left.top.mas_equalTo(10);
//    make.right.mas_equalTo(-10);
//  }];
//  [self.label2 mas_makeConstraints:^(MASConstraintMaker *make) {
//    make.left.right.equalTo(weakObject.label1);
//    make.top.equalTo(weakObject.label1.mas_bottom).offset(20);
//    make.bottom.equalTo(weakObject.bgView.mas_bottom).offset(-20);
//  }];
//  self.label2.userInteractionEnabled = YES;
//  UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTap:)];
//  [self.label2 addGestureRecognizer:tap];
//
//  [self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {
//    make.left.mas_equalTo(10);
//    make.right.mas_equalTo(-10);
//    make.top.mas_equalTo(160);
//  }];

  // scrollview
  self.scLabel.text = @"mas_remakeConstraints is similar to mas_updateConstraints, but instead of updating constant values, it will remove all of its contraints before installing them again. This lets you provide different constraints without having to keep around references to ones which you want to remove.";
  self.scLabel.numberOfLines = 0;
[self.scLabel mas_makeConstraints:^(MASConstraintMaker *make) {
  make.left.mas_equalTo(10);
  make.width.mas_equalTo(kScreenWidth);
//  make.right.mas_equalTo(-10);
  make.top.mas_equalTo(100);
}];
  self.scLabel.backgroundColor = [UIColor redColor];
  self.scrollView.backgroundColor = [UIColor greenColor];
  [self.view bringSubviewToFront:self.scrollView];

  [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
//    make.left.mas_equalTo(10);
//    make.right.mas_equalTo(-10);
//    make.top.mas_equalTo(100);
    make.edges.mas_equalTo(UIEdgeInsetsMake(10, 10, 10, 10));
    make.bottom.equalTo(weakObject.scLabel.mas_bottom).offset(20);
    make.right.equalTo(weakObject.scLabel.mas_right);
  }];
}

- (void)onTap:(UITapGestureRecognizer *)sender {
  self.label2.text = @"mas_remakeConstraints is similar to mas_updateConstraints, but instead of updating constant values, it will remove all of its contraints before installing them again. This lets you provide different constraints without having to keep around references to ones which you want to remove.";
}

- (IBAction)changeAvg:(UIButton *)sender {
  if (self.isAnimating) {
    return;
  }

  self.isAnimating = YES;
  WS(self);
  if (!self.isSelected) {
    [UIView animateWithDuration:3.0 animations:^{
      [weakObject.avgButton1 mas_remakeConstraints:^(MASConstraintMaker *make) {
        // 加and其实就是获取约束本身
        make.left.right.and.height.equalTo(weakObject.noneConstraitButton);
        make.top.equalTo(weakObject.noneConstraitButton.mas_bottom).offset(80);
      }];

      [weakObject.avgButton2 mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.equalTo(weakObject.noneConstraitButton);
        make.top.equalTo(weakObject.avgButton1.mas_bottom).offset(30);
      }];

      [weakObject.avgButton3 mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.equalTo(weakObject.noneConstraitButton);
        make.top.equalTo(weakObject.avgButton2.mas_bottom).offset(30);
      }];
    } completion:^(BOOL finished) {
      weakObject.isAnimating = !finished;
      weakObject.isSelected = !weakObject.isSelected;
    }];
  } else {
    [UIView animateWithDuration:3.0 animations:^{
      // 让三个按钮平分
      [weakObject.avgButton1 mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.height.mas_equalTo(30);
        make.top.mas_equalTo(weakObject.noneConstraitButton.mas_bottom).offset(100);
        make.width.mas_equalTo((kScreenWidth - 40 - 40) / 3);
      }];

      [self.avgButton2 mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.width.top.height.mas_equalTo(weakObject.avgButton1);
        make.left.mas_equalTo(weakObject.avgButton1.mas_right).offset(20);
      }];

      [self.avgButton3 mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.width.top.height.mas_equalTo(weakObject.avgButton1);
        make.left.mas_equalTo(weakObject.avgButton2.mas_right).offset(20);
      }];
    } completion:^(BOOL finished) {
      weakObject.isAnimating = !finished;
      weakObject.isSelected = !weakObject.isSelected;
    }];
  }

}
@end


text:
package com.mkl.eu.client.service.socket;

import com.google.gson.Gson;
import com.mkl.eu.client.service.vo.diff.DiffResponse;

import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;

/**
 * Encoder for DiffResponse in order to communicate throw web sockets.
 *
 * @author MKL.
 */
public class DiffResponseEncoder implements Encoder.Text<DiffResponse> {
    /** Configuration. */
    private static Gson gson = new Gson();

    /** {@inheritDoc} */
    @Override
    public String encode(DiffResponse object) throws EncodeException {
        return gson.toJson(object);
    }

    /** {@inheritDoc} */
    @Override
    public void init(EndpointConfig config) {

    }

    /** {@inheritDoc} */
    @Override
    public void destroy() {

    }

    /**
     * Decoder for DiffResponse to use by the client.
     *
     * @param message the diffResponse in json format.
     * @return a DiffResponse object.
     */
    public static DiffResponse decode(String message) {
        return gson.fromJson(message, DiffResponse.class);
    }
}


text:
#include <malloc.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>

#include "fileio.h"
#include "storage_data.h"

#define  SUBDIM_UNUSED_FILE_VALUE 10000
const char *ENV_FILE_PATH = "AMD_CLBLAS_STORAGE_PATH";
const char *FileID  = "CBS";
const char *FileExt = "kdb";
const char *FileExtTmp = "kdb.tmp";
const int fileVersion = 3;

POSFILE
findPattern(HfInfo* file, const char* name)
{
	const int bufSize = 1024*64;
	char  buffer[1024*64];
	POSFILE fpos = 0;
	int ib;
	int in;
	int bufRead;
	int nameLen = (int)strlen(name);

	hfJump(file, 1);
	in = 0;

	do {
		hfGetCurentPosition(file, &fpos);
		bufRead = hfReadWithoutCRC(file, buffer, bufSize);
		for (ib = 0; ib < bufRead; ++ib) {
			if (name[in] == buffer[ib]) {
				in++;
				if (in >= nameLen) {
					fpos += + ib - nameLen + 1 - sizeof(unsigned int);
					hfJump(file, fpos);
					return true;
				}
			}else{
				in = 0;
			}

		}
	} while (bufRead == bufSize);

	return 0;
}

bool
checkFile(HfInfo* file, size_t pos2, int status)
{
    POSFILE pos;

    hfGetCurentPosition(file, &pos);
    if ((POSFILE)pos2 == pos && status == FILE_OK) {
        return true;
    }
    return false;
}

// PATTERN
void
calcPatternOffset(BlasPatternInfo*  bPatt, POSFILE* offset)
{
    unsigned int len = (unsigned int)strlen(bPatt->name) + 1;

    bPatt->size  = sizeof(len);
    bPatt->size += len;
    bPatt->size += sizeof(bPatt->numExtra);
    bPatt->size += sizeof(TYPECRC);

    bPatt->offset = (OFFSET)*offset;
    *offset += (POSFILE)bPatt->size;
}

// PARAM
void
calcParamOffset(BlasParamInfo* bParam, POSFILE* offset)
{
    bParam->size  = sizeof(unsigned int) * 5 * MAX_SUBDIMS;
    bParam->size += sizeof(PGranularity);
    bParam->size += sizeof(POSFILE)*MAX_CLBLAS_KERNELS_PER_STEP;
    bParam->size += sizeof(bParam->kSize);
    bParam->size += sizeof(double);
    bParam->size += sizeof(TYPECRC);
    bParam->offset = (OFFSET)*offset;
    *offset += (POSFILE)bParam->size;
}

int
loadParamData(HfInfo* file, BlasParamInfo* bParam)
{
    int status = 0;
    int i = 0;
    int ret = 0;
    bool dimExist = true;

    for (i =0; i < MAX_SUBDIMS; i++){
        unsigned int temp;
        status+= hfRead(file, &temp, 1, sizeof(temp));
        bParam->sDim[i].x = (size_t)temp;
        status+= hfRead(file, &temp, 1, sizeof(temp));
        bParam->sDim[i].y = (size_t)temp;
        status+= hfRead(file, &temp, 1, sizeof(temp));
        bParam->sDim[i].itemX = (temp >= SUBDIM_UNUSED_FILE_VALUE)
            ? SUBDIM_UNUSED
            : (size_t)temp;
        status+= hfRead(file, &temp, 1, sizeof(temp));
        bParam->sDim[i].itemY = (temp >= SUBDIM_UNUSED_FILE_VALUE)
            ? SUBDIM_UNUSED
            : (size_t)temp;
        status+= hfRead(file, &temp, 1, sizeof(temp));
        bParam->sDim[i].bwidth = (size_t)temp;

    }

    status += hfRead(file, &bParam->pGran, 1, sizeof(PGranularity));
    status += hfRead(file, bParam->kernel, 1, sizeof(POSFILE) * MAX_CLBLAS_KERNELS_PER_STEP);
    status += hfRead(file, bParam->kSize,  1, sizeof(bParam->kSize));
    status += hfRead(file, &bParam->time,  1, sizeof(double) );

    if ((status == FILE_OK) && (bParam->sDim[0].y == 0)) {
        dimExist = false;
    }

    status += hfCheckCRC(file);

    if (!dimExist && (status == FILE_ERROR_CRC)) {
        ret = 1;    // file is valid but doesn't have actual data
    }
    else if (!checkFile(file, (size_t)bParam->offset + bParam->size, status)) {
        ret = -1;   // file is corrupted
    }
    else if (bParam->time > 10000.0) {
        ret = 1;
    }

    if (ret) {
        memset(bParam->sDim, 0, sizeof(SubproblemDim) * MAX_SUBDIMS);
        memset(&bParam->pGran, 0, sizeof(PGranularity) );
        memset(bParam->kernel, 0, sizeof(POSFILE) * MAX_CLBLAS_KERNELS_PER_STEP );
        memset(bParam->kSize, 0, sizeof(unsigned int) * MAX_CLBLAS_KERNELS_PER_STEP );

        bParam->time = 1e50; // any large number;
    }

    return ret;
}

// EXTRA DATA

void
calcExtraOffset(BlasExtraInfo* bExtra, POSFILE* offset)
{
    bExtra->size  = sizeof(unsigned int);
    bExtra->size += sizeof(unsigned int);
    bExtra->size += sizeof(unsigned int);
    bExtra->size += sizeof(TYPECRC);
    bExtra->offset = (OFFSET)*offset;
    *offset += (OFFSET)bExtra->size;
}

bool
readExtraData(
	HfInfo* file,
	BlasExtraInfo*  bExtra,
	int numParam)
{
	int param;
	int ret = 0;
        if (bExtra->param == NULL)
            return false;

	for (param = 0; param < numParam; ++ param) {
		BlasParamInfo* bpi = &bExtra->param[param];
		ret += loadParamData(file, bpi);
		if (ret == 0) {
			bpi->sstatus = SS_CORRECT_DATA;
		}

	}

	if (ret == 0) {
		bExtra->sstatus = SS_CORRECT_DATA;
	}
	return false;
}

bool
loadPatternDataFromFile(
	HfInfo * file,
	char** name,
	unsigned int* len,
	unsigned int* numExtra)
{
    int  status = 0;

    status += hfRead(file, len, 1, sizeof(*len));
    *name = malloc((*len)* sizeof(char));
    status += hfRead(file, *name, 1, *len);
    status += hfRead(file, numExtra, 1, sizeof(unsigned int));
    status += hfCheckCRC (file);

    return status == FILE_OK;
}

int
readExtaDataHeader (
	HfInfo * file,
	unsigned int* dtype,
	unsigned int* flags,
	unsigned int* numParam)
{
    int  status = 0;

    status += hfRead(file, dtype, 1, sizeof(unsigned int));
    status += hfRead(file, flags, 1, sizeof(unsigned int));

    status += hfRead(file, numParam, 1, sizeof(unsigned int));
    status += hfCheckCRC(file);

    return status;
}

bool
readPatternData(
		HfInfo* file,
		BlasPatternInfo*  bPatt,
		int numExtra)
{
    unsigned int dtype;
    unsigned int flags;
    unsigned int numParam;
	int  ief = 0;
	int  ied = 0;
	int ret;
	POSFILE extraSize = 0;

	if (numExtra > 2) {
		extraSize = bPatt->extra[1].offset - bPatt->extra[0].offset;
	}

	for (ief = 0; ief < numExtra; ++ief) {
		BlasExtraInfo* bExtra = &bPatt->extra[ied];
		POSFILE curPos;

		ied++;
		hfGetCurentPosition(file, &curPos);
		ret = readExtaDataHeader(file, &dtype, &flags, &numParam);
		if (ret != FILE_OK) {
			hfJump(file, curPos + extraSize);
			continue;
		}
		bExtra->sstatus	= SS_CORRECT_DATA;
		if ((bExtra->dtype == dtype) &&
			(bExtra->flags == flags)) {
			readExtraData(file, bExtra, numParam);
		}
		else {

		}
	}

	return true;
}

int
loadHeader(HfInfo* file)
{
	int version;
    int status = 0;
    unsigned blasFunctionNumber;
    POSFILE posFile;

    status =  hfReadConst(file, FileID, strlen(FileID));
    status += hfRead(file, &version, 1, sizeof(version));
    status += hfRead(file, &blasFunctionNumber, 1,
    		sizeof(blasFunctionNumber));
    status += hfRead(file, &posFile, 1, sizeof(posFile));
    status += hfCheckCRC(file);

    return (status == 0)? version:0;
}

void
saveHeader(HfInfo* file, unsigned int blasFunctionNumber, POSFILE binData)
{
    int status = 0;

    status =  hfWrite(file, FileID, strlen(FileID));
    status += hfWrite(file, &fileVersion, sizeof(fileVersion));
    status += hfWrite(file, &blasFunctionNumber, sizeof(blasFunctionNumber));
    status += hfWrite(file, &binData, sizeof(binData));
    status += hfWriteCRC(file);

}
bool
checkOffset(BlasFunctionInfo* functionInfo)
{
    unsigned int func;
    unsigned int patt;
    unsigned int extra;
    unsigned int param;
    bool ret = false;

    for (func =0; func < BLAS_FUNCTIONS_NUMBER; ++ func) {
        BlasFunctionInfo* bFunc = &functionInfo[func];
        for (patt =0; patt < bFunc->numPatterns; ++ patt) {
            BlasPatternInfo* bPatt = &bFunc->pattInfo[patt];

            ret |= (bPatt->offset == 0);
            for (extra =0; extra < bPatt->numExtra; ++ extra) {
                BlasExtraInfo* bExtra = &bPatt->extra[extra];

                ret |= (bExtra->offset == 0 );
                for (param =0; param < bExtra->numParam; ++ param) {
                    BlasParamInfo* bParam = &bExtra->param[param];

                    ret |= (bParam->offset == 0 );
                }
            }
        }
    }
    return ret;
}

void
loadDataFromFile(StorageCacheImpl* cache)
{
    bool structIsCorrect = true;
    char* name = NULL;
    unsigned int nameLen;
    unsigned int numExtra;
    unsigned int curFunc = 0;
    unsigned int curPatt = 0;
    unsigned int func;
    unsigned int patt;
    HfInfo file;

    if ( hfOpenRead(&file, cache->fpath) == FILE_NOT_FOUND ) {
        cache->isPopulate = false;
        return;
    }

    // Read file Header
    loadHeader(&file);

    // Read pattern header
    structIsCorrect &= loadPatternDataFromFile(&file, &name, &nameLen,
    		&numExtra);

    while (structIsCorrect)
    {
        unsigned int func = curFunc;
        unsigned int patt = curPatt;
        bool ret;
        BlasPatternInfo* bPatt = getPatternInfo(cache, func, patt);

        while (bPatt != NULL && memcmp(name, bPatt->name, nameLen) != 0 ) {
            nextPattern(cache, &func, &patt);
            bPatt = getPatternInfo(cache, func, patt);
        }

        if (bPatt != NULL) {
            bPatt->sstatus = SS_CORRECT_DATA;

            // Read pattern data
        	ret = readPatternData(&file, bPatt, numExtra);

        	// go to next pattern
        	nextPattern(cache, &func, &patt);
        	// if the pattern is read witch error or not completely
        	if (!ret) {
        		bPatt = getPatternInfo(cache, func, patt);
        	    hfJump(&file, bPatt->offset);
        	}

        	curFunc = func;
            curPatt = patt;
        }
        free(name);
        name = NULL;
        structIsCorrect &= loadPatternDataFromFile(&file, &name, &nameLen,
    			&numExtra );
    }

    for (func =0; func < BLAS_FUNCTIONS_NUMBER; ++ func) {
    	BlasFunctionInfo* bFunc = &cache->functionInfo[func];

    	for (patt =0; patt < bFunc->numPatterns; ++ patt){
    		BlasPatternInfo* bPatt = &bFunc->pattInfo[patt];
    		if (bPatt->sstatus == SS_NOLOAD) {
    			POSFILE ret = findPattern(&file, bPatt->name);
    			if (ret != 0) {
    				loadPatternDataFromFile(&file, &name, &nameLen,
    	    			&numExtra );
    				readPatternData(&file, bPatt, numExtra);
    			}
    		}
    	}
    }

    free(name);
    cache->isPopulate = true;
    hfClose(&file);
    checkOffset(cache->functionInfo);
}

char *
createFullPatch(const char * name, bool tmp)
{
    char* path = getenv(ENV_FILE_PATH);
    const char * ext = (tmp)? FileExtTmp: FileExt;

    if (path == NULL) {
        return NULL;
    }

	return hfCreateFullPatch(path, name, ext);
}

OFFSET
calcOffset(BlasFunctionInfo* functionInfo)
{
    unsigned int func;
    unsigned int patt;
    unsigned int extra;
    unsigned int param;
    POSFILE pos = 0;

    pos += (POSFILE)strlen(FileID);
    pos += sizeof(int);    // Version
    pos += sizeof(unsigned int);  // Func Count;
    pos += sizeof(POSFILE);    // Func Count;
    pos += sizeof(TYPECRC);

    for (func =0; func < BLAS_FUNCTIONS_NUMBER; ++ func) {
        BlasFunctionInfo* bFunc = &functionInfo[func];
        for (patt =0; patt < bFunc->numPatterns; ++ patt) {
            BlasPatternInfo* bPatt = &bFunc->pattInfo[patt];

            calcPatternOffset(bPatt, &pos);
            for (extra =0; extra < bPatt->numExtra; ++ extra) {
                BlasExtraInfo* bExtra = &bPatt->extra[extra];
                calcExtraOffset(bExtra, &pos);

                for (param =0; param < bExtra->numParam; ++ param) {
                    BlasParamInfo* bParam = &bExtra->param[param];
                    calcParamOffset(bParam, &pos);
                }
            }
        }
    }
    return (OFFSET)pos;
}

void
loadKernelData(
    HfInfo* file,
    BlasParamInfo* bParam,
    unsigned char** buffer,
    size_t* sizeBuffer)
{
    int k;
    int status = FILE_ERROR_READ_DATA;

    for (k =0; k < MAX_CLBLAS_KERNELS_PER_STEP; ++k) {
        sizeBuffer[k] = bParam->kSize[k];

        if (sizeBuffer[k] != 0 && bParam->kernel[k] != 0) {
            buffer[k] = malloc(sizeBuffer[k]);

            hfJump(file, bParam->kernel[k]);
            hfRead(file, buffer[k], 1, sizeBuffer[k]);
            status = hfCheckCRC(file);
        }

        if (status != FILE_OK)
        {
            sizeBuffer[k] = 0;
            buffer[k] = NULL;
        }
    }
}

void
loadKernelsFromFile(
    StorageCacheImpl* cache,
    BlasParamInfo* bParam,
    unsigned char** buffer,
    size_t* sizeBuffer)
{
    HfInfo file;

    hfOpenRead(&file, cache->fpath);
    loadKernelData(&file, bParam, buffer, sizeBuffer);
    hfClose(&file);
}

void
saveKernelData (
    StorageCacheImpl* cacheImpl,
    HfInfo* file,
    unsigned char** buffer,
    size_t* sizeBuffer)
{
    int  status;
    POSFILE pos;
    unsigned int k;

    for (k =0; k < MAX_CLBLAS_KERNELS_PER_STEP; ++k) {
        pos = cacheImpl->endFile;
        status = hfJump(file, pos);
        status += hfWrite(file, &sizeBuffer[k], sizeof(size_t));
        status += hfWrite(file, buffer[k], sizeBuffer[k]);
        status += hfWriteCRC(file);

        status += hfGetCurentPosition(file, &pos);
        if (status == FILE_OK) {
            cacheImpl->endFile = (OFFSET)pos;
        }
    }
}

bool
copyKernalData(
    StorageCacheImpl* cacheImpl,
    HfInfo* oldfile,
    HfInfo* newfile,
    BlasParamInfo* bParam)
{
    int k;
    unsigned char* buffer[MAX_CLBLAS_KERNELS_PER_STEP];
    size_t sizeBuffer[MAX_CLBLAS_KERNELS_PER_STEP];

    loadKernelData(oldfile, bParam, buffer, sizeBuffer);
    saveKernelData(cacheImpl, newfile, buffer, sizeBuffer);

    for (k =0; k < MAX_CLBLAS_KERNELS_PER_STEP; ++k) {
        free (buffer[k]);
    }
    return false;
}

bool
saveParamData (HfInfo* file, BlasParamInfo* bParam)
{
    int  status;
    int  i;

    status = hfJump(file, bParam->offset);
    for (i =0; i < MAX_SUBDIMS; i++){
        unsigned int temp;

        temp = (unsigned int)bParam->sDim[i].x;
        status+= hfWrite(file, &temp, sizeof(temp));

        temp = (unsigned int)bParam->sDim[i].y;
        status+= hfWrite(file, &temp, sizeof(temp));

        temp = (bParam->sDim[i].itemX == SUBDIM_UNUSED)
            ? SUBDIM_UNUSED_FILE_VALUE
            : (unsigned int)bParam->sDim[i].itemX;
        status+= hfWrite(file, &temp, sizeof(temp));

        temp = (bParam->sDim[i].itemY == SUBDIM_UNUSED)
            ? SUBDIM_UNUSED_FILE_VALUE
            : (unsigned int)bParam->sDim[i].itemY;
        status+= hfWrite(file, &temp, sizeof(temp));

        temp = (unsigned int)bParam->sDim[i].bwidth;
        status+= hfWrite(file, &temp, sizeof(temp));
    }

    status += hfWrite(file, &bParam->pGran, sizeof(PGranularity));
    status += hfWrite(file, bParam->kernel,
            sizeof(POSFILE)*MAX_CLBLAS_KERNELS_PER_STEP);
    status += hfWrite(file, bParam->kSize,  sizeof(bParam->kSize));
    status += hfWrite(file, &bParam->time,   sizeof(double));
    status += hfWriteCRC(file);

    return checkFile(file, (unsigned int) (bParam->offset + bParam->size), status);
}

bool
saveExtraHeader(HfInfo* file, BlasExtraInfo* bExtra)
{
    unsigned int dtype = (unsigned int)bExtra->dtype;
    unsigned int flags = (unsigned int)bExtra->flags;

    int  status = hfJump(file, bExtra->offset);

    status += hfWrite(file, &dtype, sizeof(unsigned int));
    status += hfWrite(file, &flags, sizeof(unsigned int));
    status += hfWrite(file, &bExtra->numParam, sizeof(unsigned int));
    status += hfWriteCRC(file);

    return checkFile(file, (size_t)bExtra->offset + bExtra->size, status);
}

bool
savePatternHeader(HfInfo* file, BlasPatternInfo*  bPatt)
{
    unsigned int len;
    int  status = hfJump(file, bPatt->offset);

    len = (unsigned int)strlen(bPatt->name) + 1;
    status += hfWrite(file, &len, sizeof(len));
    status += hfWrite(file, bPatt->name, len);
    status += hfWrite(file, &bPatt->numExtra, sizeof(bPatt->numExtra));
    status += hfWriteCRC(file);

    return checkFile(file, (size_t)bPatt->offset + bPatt->size, status);
}

static void
printErrorMessage (int i, const char* filename)
{
    switch (i) {
    case FILE_NOT_FOUND:
        printf("File \'%s\' not found\n", filename);
        break;
    case FILE_ERROR_CRC:
    case FILE_ERROR_INDALID_KERNAL_SIZE:
        printf("File \'%s\' is corrupted.\n", filename);
        break;
    case FILE_ERROR_OPEN_FOR_WRITING:
        printf("Can't open file \'%s\' for writing.\n", filename);
        break;
    case FILE_ERROR_BUFFER_MISMATCH:
        printf("Out of memory to read the file \'%s\'.\n", filename);
        break;
    }
    fflush(stdout);
}

///
void
writeStorageCache(TargetDevice* tdev)
{
	int func;
	unsigned int patt;
	unsigned int extra;
	unsigned int param;
	int fret;
	HfInfo outfile;
    HfInfo infile;

    StorageCacheImpl* cache = getStorageCache(tdev, true);

    // Open file for save
    fret = hfOpenWrite(&infile, cache->fpath);
    if (fret) {
        printErrorMessage(fret, cache->fpath);
        exit(2);
    }
    fret = hfOpenWrite(&outfile, cache->fpath_tmp);
    if (fret) {
        printErrorMessage(fret, cache->fpath_tmp);
        exit(2);
    }

    saveHeader(&outfile, BLAS_FUNCTIONS_NUMBER, 0);

    // For each function
    for (func =0; func < BLAS_FUNCTIONS_NUMBER; ++ func) {
        BlasFunctionInfo* bFunc = &cache->functionInfo[func];

        // For each pattern
        for (patt =0; patt < bFunc->numPatterns; ++ patt){
            BlasPatternInfo* bPatt = &bFunc->pattInfo[patt];

            // Save pattern header
            savePatternHeader(&outfile, bPatt);

            for (extra =0; extra < bPatt->numExtra; ++ extra){
                BlasExtraInfo* bExtra = &bPatt->extra[extra];

                saveExtraHeader(&outfile, bExtra);

                //
                for (param =0; param < bExtra->numParam; ++param){
                    BlasParamInfo* bParam = &bExtra->param[param];

                    saveParamData(&outfile, bParam);
                }
            }
        }
    }
    hfClose(&infile);
    hfClose(&outfile);

    // rename file
    fret = remove(cache->fpath);
    if (fret == 0) {
        fret = rename(cache->fpath_tmp, cache->fpath);
    }

    // Re-init storage cache
    destroyStorageCache ();
    initStorageCache();
}

//Saving of the best parameter. It is running at tuning of subproblem dimension.
//The parameter saving in in advance selected place.

void
saveBestParam(TargetDevice* tdev, BlasParamInfo* bParam)
{
	HfInfo file;
	int    status;
    StorageCacheImpl* cache;

    cache = getStorageCache(tdev, false);
    hfInit(&file);
	status = hfOpenReWrite(&file, cache->fpath);
	if (status == FILE_OK) {
		POSFILE pos = bParam->offset;
		hfJump(&file, pos);
		saveParamData(&file, bParam);
		bParam->sstatus = SS_CORRECT_DATA;
	}
	hfClose(&file);
}


text:
namespace media {

// Helper function to print HRESULT to std::string.
const auto PrintHr = logging::SystemErrorCodeToString;

// Helper macro for DVLOG with function name and this pointer.
#define DVLOG_FUNC(level) DVLOG(level) << __func__ << ": (" << this << ") "

// Macros that contain return statements can make code harder to read. Only use
// these when necessary, e.g. in places where we deal with a lot of Windows API
// calls, for each of which we have to check the returned HRESULT.
// See discussion thread at:
// https://groups.google.com/a/chromium.org/d/msg/cxx/zw5Xmcs--S4/r7Fwb-TsCAAJ

#define RETURN_IF_FAILED(expr)                                          \
  do {                                                                  \
    HRESULT hresult = (expr);                                           \
    if (FAILED(hresult)) {                                              \
      DLOG(ERROR) << __func__ << ": failed with \"" << PrintHr(hresult) \
                  << "\"";                                              \
      return hresult;                                                   \
    }                                                                   \
  } while (0)

#define RETURN_ON_FAILURE(success, log, ret) \
  do {                                       \
    if (!(success)) {                        \
      DLOG(ERROR) << log;                    \
      return ret;                            \
    }                                        \
  } while (0)

#define RETURN_ON_HR_FAILURE(hresult, log, ret) \
  RETURN_ON_FAILURE(SUCCEEDED(hresult), log << ", " << PrintHr(hresult), ret);

// Creates a Media Foundation sample with one buffer of length |buffer_length|
// on a |align|-byte boundary. Alignment must be a perfect power of 2 or 0.
MF_INITIALIZER_EXPORT Microsoft::WRL::ComPtr<IMFSample>
CreateEmptySampleWithBuffer(uint32_t buffer_length, int align);

// Provides scoped access to the underlying buffer in an IMFMediaBuffer
// instance.
class MF_INITIALIZER_EXPORT MediaBufferScopedPointer {
 public:
  explicit MediaBufferScopedPointer(IMFMediaBuffer* media_buffer);
  ~MediaBufferScopedPointer();

  uint8_t* get() { return buffer_; }
  DWORD current_length() const { return current_length_; }

 private:
  Microsoft::WRL::ComPtr<IMFMediaBuffer> media_buffer_;
  uint8_t* buffer_;
  DWORD max_length_;
  DWORD current_length_;

  DISALLOW_COPY_AND_ASSIGN(MediaBufferScopedPointer);
};

// Wrap around the usage of device handle from |device_manager|.
class MF_INITIALIZER_EXPORT DXGIDeviceScopedHandle {
 public:
  explicit DXGIDeviceScopedHandle(IMFDXGIDeviceManager* device_manager);
  ~DXGIDeviceScopedHandle();

  HRESULT LockDevice(REFIID riid, void** device_out);

 private:
  Microsoft::WRL::ComPtr<IMFDXGIDeviceManager> device_manager_;

  HANDLE device_handle_ = INVALID_HANDLE_VALUE;
};

}  // namespace media

#endif  // MEDIA_BASE_WIN_MF_HELPERS_H_


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>snmp_stats module — Nitro  documentation</title>

    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="Nitro  documentation" href="index.html" />
    <link rel="up" title="snmp package" href="nssrc.com.citrix.netscaler.nitro.resource.stat.snmp.html" />
    <link rel="next" title="spillover package" href="nssrc.com.citrix.netscaler.nitro.resource.stat.spillover.html" />
    <link rel="prev" title="snmp package" href="nssrc.com.citrix.netscaler.nitro.resource.stat.snmp.html" />

Navigation

          index

          next |

          previous |

Nitro  documentation »

config package »

snmp package »

snmp_stats module¶

class <tt class="descname">snmp_stats</tt>¶

Bases: <tt class="xref py py-class docutils literal">nssrc.com.citrix.netscaler.nitro.resource.base.base_resource.base_resource</tt>

<tt class="descname">clearstats</tt>¶

Clear the statsistics / counters.<br/>Possible values = basic, full.

<tt class="descname">snmpdecryptionerrors</tt>¶

SNMP packets that were dropped because they could not be decrypted.

<tt class="descname">snmptotresponses</tt>¶

SNMP Get-Response PDUs that have been generated by the NetScaler.

<tt class="descname">snmptotbadcommuse</tt>¶

The total number of SNMP Messages received that represented an SNMP operation which was not allowed by the SNMP community named in the Message.

<tt class="descname">snmptoterrreqdropped</tt>¶

SNMP requests dropped.

<tt class="descname">snmpgetnextreqsrate</tt>¶

Rate (/s) counter for snmptotgetnextreqs.

<tt class="descname">snmptotbadversions</tt>¶

Number of SNMP messages received, which were for an unsupported SNMP version.

<tt class="descname">snmptotrxpkts</tt>¶

SNMP packets received.

<tt class="descname">snmptxpktsrate</tt>¶

Rate (/s) counter for snmptottxpkts.

<tt class="descname">snmpresponsesrate</tt>¶

Rate (/s) counter for snmptotresponses.

<tt class="descname">snmpgetreqsrate</tt>¶

Rate (/s) counter for snmptotgetreqs.

<tt class="descname">snmptotbadcommname</tt>¶

SNMP messages received, which used an SNMP community name not known to the NetScaler.

<tt class="descname">snmptotgetnextreqs</tt>¶

SNMP Get-Next PDUs that have been accepted and processed.

<tt class="descname">snmptottxpkts</tt>¶

SNMP packets transmitted.

<tt class="descname">snmpunknownengineids</tt>¶

SNMP packets that were dropped because they referenced an SNMP engine ID that was not known to the NetScaler.

<tt class="descname">snmpwrongdigests</tt>¶

SNMP packets that were dropped because they did not contain the expected digest value.

<tt class="descname">snmpgetbulkreqsrate</tt>¶

Rate (/s) counter for snmptotgetbulkreqs.

<tt class="descname">snmpnotintimewindow</tt>¶

SNMP packets that were dropped because they appeared outside of the authoritative SNMP engine’s window.

<tt class="descname">snmptotgetbulkreqs</tt>¶

SNMP Get-Bulk PDUs that have been accepted and proZcessed.

<tt class="descname">snmptotparseerrs</tt>¶

Number of ASN.1 or BER errors encountered when decoding received SNMP Messages.

<tt class="descname">snmpunknownusername</tt>¶

SNMP packets that were dropped because they referenced a user that was  not  known to the SNMP engine.

<tt class="descname">snmpunsupportedsecuritylevel</tt>¶

SNMP packets that were dropped because they requested a security level that was
unknown to the NetScaler or otherwise unavailable.

<tt class="descname">snmptotgetreqs</tt>¶

SNMP Get-Request PDUs that have been accepted and processed.

<tt class="descname">snmprxpktsrate</tt>¶

Rate (/s) counter for snmptotrxpkts.

<tt class="descname">snmptottraps</tt>¶

SNMP Trap PDUs that have been generated by the NetScaler.

classmethod <tt class="descname">get</tt><big>(</big>service, name='', option_=''<big>)</big>¶

Use this API to fetch the statistics of all snmp_stats resources that are configured on netscaler.

class <tt class="descname">Clearstats</tt>¶

<tt class="descname">basic</tt> = 'basic'¶

<tt class="descname">full</tt> = 'full'¶

class <tt class="descname">snmp_response</tt><big>(</big>length=1<big>)</big>¶

Bases: <tt class="xref py py-class docutils literal">nssrc.com.citrix.netscaler.nitro.resource.base.base_response.base_response</tt>

Nitro exception Package

Base Package

Service Package

Util Package

Config Package

Stat Package

aaa

appflow

appfw

appqoe

audit

authentication

authorization

autoscale

basic

ca

cache

cluster

cmp

cr

cs

dns

dos

feo

gslb

ha

ipsec

lb

lldp

network

ns

pq

protocol

qos

responder

rewrite

sc

snmp

snmp_stats

spillover

ssl

stream

system

tm

transform

vpn

Previous topic

snmp package

Next topic

spillover package

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

        © Copyright © 1999-2014 Citrix Systems, Inc. All Rights Reserved.
      Created using Sphinx 1.2.