text:
<?php
/**
 * @package WPSEO\Internals
 */

if ( ! defined( 'WPSEO_VERSION' ) ) {
	header( 'Status: 403 Forbidden' );
	header( 'HTTP/1.1 403 Forbidden' );
	exit();
}

/**
 * Adds an SEO admin bar menu with several options. If the current user is an admin he can also go straight to several settings menu's from here.
 */
function wpseo_admin_bar_menu() {
	// If the current user can't write posts, this is all of no use, so let's not output an admin menu.
	if ( ! current_user_can( 'edit_posts' ) ) {
		return;
	}

	global $wp_admin_bar, $post;

	$admin_menu = current_user_can( 'manage_options' );
	if ( ! $admin_menu && is_multisite() ) {
		$options    = get_site_option( 'wpseo_ms' );
		$admin_menu = ( $options['access'] === 'superadmin' && is_super_admin() );
	}

	$focuskw = '';
	$score   = '';
	$seo_url = '';

	$analysis_seo = new WPSEO_Metabox_Analysis_SEO();
	$analysis_readability = new WPSEO_Metabox_Analysis_Readability();

	if ( ( is_singular() || ( is_admin() && in_array( $GLOBALS['pagenow'], array(
					'post.php',
					'post-new.php',
				), true ) ) ) && isset( $post ) && is_object( $post ) && apply_filters( 'wpseo_use_page_analysis', true ) === true
	) {
		$focuskw    = WPSEO_Meta::get_value( 'focuskw', $post->ID );

		if ( $analysis_seo->is_enabled() ) {
			$score = wpseo_adminbar_seo_score();
		}
		elseif ( $analysis_readability->is_enabled() ) {
			$score = wpseo_adminbar_content_score();
		}

		$seo_url = get_edit_post_link( $post->ID );
	}

	if ( is_category() || is_tag() || (WPSEO_Taxonomy::is_term_edit( $GLOBALS['pagenow'] ) && ! WPSEO_Taxonomy::is_term_overview( $GLOBALS['pagenow'] ) )  || is_tax() ) {
		if ( $analysis_seo->is_enabled() ) {
			$score = wpseo_tax_adminbar_seo_score();
		}
		elseif ( $analysis_readability->is_enabled() ) {
			$score = wpseo_tax_adminbar_content_score();
		}

		$seo_url    = get_edit_tag_link( filter_input( INPUT_GET, 'tag_ID' ), 'category' );
	}

	// Never display notifications for network admin.
	$counter = '';

	if ( $admin_menu ) {

		$seo_url = get_admin_url( null, 'admin.php?page=' . WPSEO_Admin::PAGE_IDENTIFIER );

		if ( '' === $score ) {

			// Notification information.
			$notification_center     = Yoast_Notification_Center::get();
			$notification_count      = $notification_center->get_notification_count();
			$new_notifications       = $notification_center->get_new_notifications();
			$new_notifications_count = count( $new_notifications );

			if ( $notification_count > 0 ) {
				// Always show Alerts page when clicking on the main link.
				/* translators: %s: number of notifications */
				$counter_screen_reader_text = sprintf( _n( '%s notification', '%s notifications', $notification_count ), number_format_i18n( $notification_count ) );
				$counter = sprintf( '
%d%s
', $notification_count, $counter_screen_reader_text );
			}

			if ( $new_notifications_count ) {
				$notification = sprintf(
					/* translators: %d resolves to the number of alerts being added. */
					_n( 'You have a new issue concerning your SEO!', 'You have %d new issues concerning your SEO!', $new_notifications_count, 'wordpress-seo' ),
					$new_notifications_count
				);
				$counter .= '
' . $notification . '
';
			}
		}
	}

	// Yoast Icon.
	$icon_svg = WPSEO_Utils::get_icon_svg();
	$title = '
' . __( 'SEO', 'wordpress-seo' ) . '
';

	$wp_admin_bar->add_menu( array(
		'id'    => 'wpseo-menu',
		'title' => $title . $score . $counter,
		'href'  => $seo_url,
	) );
	if ( ! empty( $notification_count ) ) {
		$wp_admin_bar->add_menu( array(
			'parent' => 'wpseo-menu',
			'id'     => 'wpseo-notifications',
			'title'  => __( 'Notifications', 'wordpress-seo' ) . $counter,
			'href'   => $seo_url,
		) );
	}
	$wp_admin_bar->add_menu( array(
		'parent' => 'wpseo-menu',
		'id'     => 'wpseo-kwresearch',
		'title'  => __( 'Keyword Research', 'wordpress-seo' ),
		'meta'   => array( 'tabindex' => '0' ),
	) );
	$wp_admin_bar->add_menu( array(
		'parent' => 'wpseo-kwresearch',
		'id'     => 'wpseo-adwordsexternal',
		'title'  => __( 'AdWords External', 'wordpress-seo' ),
		'href'   => 'http://adwords.google.com/keywordplanner',
		'meta'   => array( 'target' => '_blank' ),
	) );
	$wp_admin_bar->add_menu( array(
		'parent' => 'wpseo-kwresearch',
		'id'     => 'wpseo-googleinsights',
		'title'  => __( 'Google Trends', 'wordpress-seo' ),
		'href'   => 'https://www.google.com/trends/explore#q=' . urlencode( $focuskw ),
		'meta'   => array( 'target' => '_blank' ),
	) );
	$wp_admin_bar->add_menu( array(
		'parent' => 'wpseo-kwresearch',
		'id'     => 'wpseo-wordtracker',
		'title'  => __( 'SEO Book', 'wordpress-seo' ),
		'href'   => 'http://tools.seobook.com/keyword-tools/seobook/?keyword=' . urlencode( $focuskw ),
		'meta'   => array( 'target' => '_blank' ),
	) );

	if ( ! is_admin() ) {
		$url = WPSEO_Frontend::get_instance()->canonical( false );

		if ( is_string( $url ) ) {
			$wp_admin_bar->add_menu( array(
				'parent' => 'wpseo-menu',
				'id'     => 'wpseo-analysis',
				'title'  => __( 'Analyze this page', 'wordpress-seo' ),
				'meta'   => array( 'tabindex' => '0' ),
			) );
			$wp_admin_bar->add_menu( array(
				'parent' => 'wpseo-analysis',
				'id'     => 'wpseo-inlinks-ose',
				'title'  => __( 'Check Inlinks (OSE)', 'wordpress-seo' ),
				'href'   => '//moz.com/researchtools/ose/links?site=' . urlencode( $url ),
				'meta'   => array( 'target' => '_blank' ),
			) );
			$wp_admin_bar->add_menu( array(
				'parent' => 'wpseo-analysis',
				'id'     => 'wpseo-kwdensity',
				'title'  => __( 'Check Keyword Density', 'wordpress-seo' ),
				'href'   => '//www.zippy.co.uk/keyworddensity/index.php?url=' . urlencode( $url ) . '&keyword=' . urlencode( $focuskw ),
				'meta'   => array( 'target' => '_blank' ),
			) );
			$wp_admin_bar->add_menu( array(
				'parent' => 'wpseo-analysis',
				'id'     => 'wpseo-cache',
				'title'  => __( 'Check Google Cache', 'wordpress-seo' ),
				'href'   => '//webcache.googleusercontent.com/search?strip=1&q=cache:' . urlencode( $url ),
				'meta'   => array( 'target' => '_blank' ),
			) );
			$wp_admin_bar->add_menu( array(
				'parent' => 'wpseo-analysis',
				'id'     => 'wpseo-header',
				'title'  => __( 'Check Headers', 'wordpress-seo' ),
				'href'   => '//quixapp.com/headers/?r=' . urlencode( $url ),
				'meta'   => array( 'target' => '_blank' ),
			) );
			$wp_admin_bar->add_menu( array(
				'parent' => 'wpseo-analysis',
				'id'     => 'wpseo-richsnippets',
				'title'  => __( 'Check Rich Snippets', 'wordpress-seo' ),
				'href'   => '//www.google.com/webmasters/tools/richsnippets?q=' . urlencode( $url ),
				'meta'   => array( 'target' => '_blank' ),
			) );
			$wp_admin_bar->add_menu( array(
				'parent' => 'wpseo-analysis',
				'id'     => 'wpseo-facebookdebug',
				'title'  => __( 'Facebook Debugger', 'wordpress-seo' ),
				'href'   => '//developers.facebook.com/tools/debug/og/object?q=' . urlencode( $url ),
				'meta'   => array( 'target' => '_blank' ),
			) );
			$wp_admin_bar->add_menu( array(
				'parent' => 'wpseo-analysis',
				'id'     => 'wpseo-pinterestvalidator',
				'title'  => __( 'Pinterest Rich Pins Validator', 'wordpress-seo' ),
				'href'   => '//developers.pinterest.com/rich_pins/validator/?link=' . urlencode( $url ),
				'meta'   => array( 'target' => '_blank' ),
			) );
			$wp_admin_bar->add_menu( array(
				'parent' => 'wpseo-analysis',
				'id'     => 'wpseo-htmlvalidation',
				'title'  => __( 'HTML Validator', 'wordpress-seo' ),
				'href'   => '//validator.w3.org/check?uri=' . urlencode( $url ),
				'meta'   => array( 'target' => '_blank' ),
			) );
			$wp_admin_bar->add_menu( array(
				'parent' => 'wpseo-analysis',
				'id'     => 'wpseo-cssvalidation',
				'title'  => __( 'CSS Validator', 'wordpress-seo' ),
				'href'   => '//jigsaw.w3.org/css-validator/validator?uri=' . urlencode( $url ),
				'meta'   => array( 'target' => '_blank' ),
			) );
			$wp_admin_bar->add_menu( array(
				'parent' => 'wpseo-analysis',
				'id'     => 'wpseo-pagespeed',
				'title'  => __( 'Google Page Speed Test', 'wordpress-seo' ),
				'href'   => '//developers.google.com/speed/pagespeed/insights/?url=' . urlencode( $url ),
				'meta'   => array( 'target' => '_blank' ),
			) );
			$wp_admin_bar->add_menu( array(
				'parent' => 'wpseo-analysis',
				'id'     => 'wpseo-modernie',
				'title'  => __( 'Modern IE Site Scan', 'wordpress-seo' ),
				'href'   => '//www.modern.ie/en-us/report#' . urlencode( $url ),
				'meta'   => array( 'target' => '_blank' ),
			) );
			$wp_admin_bar->add_menu( array(
				'parent' => 'wpseo-analysis',
				'id'     => 'wpseo-google-mobile-friendly',
				'title'  => __( 'Mobile-Friendly Test', 'wordpress-seo' ),
				'href'   => 'https://www.google.com/webmasters/tools/mobile-friendly/?url=' . urlencode( $url ),
				'meta'   => array( 'target' => '_blank' ),
			) );
		}
	}

	// @todo: add links to bulk title and bulk description edit pages.
	if ( $admin_menu ) {
		$wp_admin_bar->add_menu( array(
			'parent' => 'wpseo-menu',
			'id'     => 'wpseo-settings',
			'title'  => __( 'SEO Settings', 'wordpress-seo' ),
			'meta'   => array( 'tabindex' => '0' ),
		) );
		$wp_admin_bar->add_menu( array(
			'parent' => 'wpseo-settings',
			'id'     => 'wpseo-general',
			'title'  => __( 'Dashboard', 'wordpress-seo' ),
			'href'   => admin_url( 'admin.php?page=wpseo_dashboard' ),
		) );
		$wp_admin_bar->add_menu( array(
			'parent' => 'wpseo-settings',
			'id'     => 'wpseo-titles',
			'title'  => __( 'Titles & Metas', 'wordpress-seo' ),
			'href'   => admin_url( 'admin.php?page=wpseo_titles' ),
		) );
		$wp_admin_bar->add_menu( array(
			'parent' => 'wpseo-settings',
			'id'     => 'wpseo-social',
			'title'  => __( 'Social', 'wordpress-seo' ),
			'href'   => admin_url( 'admin.php?page=wpseo_social' ),
		) );
		$wp_admin_bar->add_menu( array(
			'parent' => 'wpseo-settings',
			'id'     => 'wpseo-xml',
			'title'  => __( 'XML Sitemaps', 'wordpress-seo' ),
			'href'   => admin_url( 'admin.php?page=wpseo_xml' ),
		) );
		$wp_admin_bar->add_menu( array(
			'parent' => 'wpseo-settings',
			'id'     => 'wpseo-wpseo-advanced',
			'title'  => __( 'Advanced', 'wordpress-seo' ),
			'href'   => admin_url( 'admin.php?page=wpseo_advanced' ),
		) );
		$wp_admin_bar->add_menu( array(
			'parent' => 'wpseo-settings',
			'id'     => 'wpseo-tools',
			'title'  => __( 'Tools', 'wordpress-seo' ),
			'href'   => admin_url( 'admin.php?page=wpseo_tools' ),
		) );
		$wp_admin_bar->add_menu( array(
			'parent' => 'wpseo-settings',
			'id'     => 'wpseo-search-console',
			'title'  => __( 'Search Console', 'wordpress-seo' ),
			'href'   => admin_url( 'admin.php?page=wpseo_search_console' ),
		) );
		$wp_admin_bar->add_menu( array(
			'parent' => 'wpseo-settings',
			'id'     => 'wpseo-licenses',
			'title'  => '' . __( 'Extensions', 'wordpress-seo' ) . '',
			'href'   => admin_url( 'admin.php?page=wpseo_licenses' ),
		) );
	}

}

/**
 * Returns the SEO score element for the adminbar.
 *
 * @return string
 */
function wpseo_adminbar_seo_score() {
	$rating = WPSEO_Meta::get_value( 'linkdex', get_the_ID() );

	return wpseo_adminbar_score( $rating );
}

/**
 * Returns the content score element for the adminbar.
 *
 * @return string
 */
function wpseo_adminbar_content_score() {
	$rating = WPSEO_Meta::get_value( 'content_score', get_the_ID() );

	return wpseo_adminbar_score( $rating );
}

/**
 * Returns the SEO score element for the adminbar.
 *
 * @return string
 */
function wpseo_tax_adminbar_seo_score() {
	$rating = 0;

	if ( is_tax() || is_category() || is_tag() ) {
		$rating = WPSEO_Taxonomy_Meta::get_meta_without_term( 'linkdex' );
	}

	return wpseo_adminbar_score( $rating );
}

/**
 * Returns the Content score element for the adminbar.
 *
 * @return string
 */
function wpseo_tax_adminbar_content_score() {
	$rating = 0;

	if ( is_tax() || is_category() || is_tag() ) {
		$rating = WPSEO_Taxonomy_Meta::get_meta_without_term( 'content_score' );
	}

	return wpseo_adminbar_score( $rating );
}

/**
 * Takes The SEO score and makes the score icon for the adminbar with it.
 *
 * @param int $score The 0-100 rating of the score. Can be either SEO score or content score.
 *
 * @return string $score_adminbar_element
 */
function wpseo_adminbar_score( $score ) {
	$score = WPSEO_Utils::translate_score( $score );

	$score_adminbar_element = '

';
	return $score_adminbar_element;
}

add_action( 'admin_bar_menu', 'wpseo_admin_bar_menu', 95 );

/**
 * Enqueue CSS to format the Yoast SEO adminbar item.
 */
function wpseo_admin_bar_style() {
	if ( ! is_user_logged_in() ) {
		return;
	}

	$asset_manager = new WPSEO_Admin_Asset_Manager();
	$asset_manager->register_assets();
	$asset_manager->enqueue_style( 'adminbar' );
}

add_action( 'wp_enqueue_scripts', 'wpseo_admin_bar_style' );
add_action( 'admin_enqueue_scripts', 'wpseo_admin_bar_style' );

/**
 * Allows editing of the meta fields through weblog editors like Marsedit.
 *
 * @param array $allcaps Capabilities that must all be true to allow action.
 * @param array $cap     Array of capabilities to be checked, unused here.
 * @param array $args    List of arguments for the specific cap to be checked.
 *
 * @return array $allcaps
 */
function allow_custom_field_edits( $allcaps, $cap, $args ) {
	// $args[0] holds the capability.
	// $args[2] holds the post ID.
	// $args[3] holds the custom field.
	// Make sure the request is to edit or add a post meta (this is usually also the second value in $cap,
	// but this is safer to check).
	if ( in_array( $args[0], array( 'edit_post_meta', 'add_post_meta' ) ) ) {
		// Only allow editing rights for users who have the rights to edit this post and make sure
		// the meta value starts with _yoast_wpseo (WPSEO_Meta::$meta_prefix).
		if ( ( isset( $args[2] ) && current_user_can( 'edit_post', $args[2] ) ) && ( ( isset( $args[3] ) && $args[3] !== '' ) && strpos( $args[3], WPSEO_Meta::$meta_prefix ) === 0 ) ) {
			$allcaps[ $args[0] ] = true;
		}
	}

	return $allcaps;
}

add_filter( 'user_has_cap', 'allow_custom_field_edits', 0, 3 );

/********************** DEPRECATED FUNCTIONS **********************/

/**
 * Set the default settings.
 *
 * @deprecated 1.5.0
 * @deprecated use WPSEO_Options::initialize()
 * @see        WPSEO_Options::initialize()
 */
function wpseo_defaults() {
	_deprecated_function( __FUNCTION__, 'WPSEO 1.5.0', 'WPSEO_Options::initialize()' );
	WPSEO_Options::initialize();
}

/**
 * Translates a decimal analysis score into a textual one.
 *
 * @deprecated 1.5.6.1
 * @deprecated use WPSEO_Utils::translate_score()
 * @see        WPSEO_Utils::translate_score()
 *
 * @param int  $val       The decimal score to translate.
 * @param bool $css_value Whether to return the i18n translated score or the CSS class value.
 *
 * @return string
 */
function wpseo_translate_score( $val, $css_value = true ) {
	_deprecated_function( __FUNCTION__, 'WPSEO 1.5.6.1', 'WPSEO_Utils::translate_score()' );

	return WPSEO_Utils::translate_score();
}

/**
 * Check whether file editing is allowed for the .htaccess and robots.txt files
 *
 * @deprecated 1.5.6.1
 * @deprecated use WPSEO_Utils::allow_system_file_edit()
 * @see        WPSEO_Utils::allow_system_file_edit()
 *
 * @internal   current_user_can() checks internally whether a user is on wp-ms and adjusts accordingly.
 *
 * @return bool
 */
function wpseo_allow_system_file_edit() {
	_deprecated_function( __FUNCTION__, 'WPSEO 1.5.6.1', 'WPSEO_Utils::allow_system_file_edit()' );

	return WPSEO_Utils::allow_system_file_edit();
}

/**
 * Test whether force rewrite should be enabled or not.
 *
 * @deprecated 3.3
 *
 * @return void
 */
function wpseo_title_test() {
	_deprecated_function( __FUNCTION__, 'WPSEO 3.3.0' );
}

/**
 * Test whether the active theme contains a <meta> description tag.
 *
 * @since 1.4.14 Moved from dashboard.php and adjusted - see changelog
 *
 * @deprecated 3.3
 *
 * @return void
 */
function wpseo_description_test() {
	_deprecated_function( __FUNCTION__, 'WPSEO 3.3.0' );
}

/**
 * Check if the current theme was updated and if so, test the updated theme
 * for the title and meta description tag
 *
 * @since    1.4.14
 *
 * @deprecated 3.3
 *
 * @param WP_Upgrader $upgrader_object Upgrader object instance.
 * @param array       $context_array   Context data array.
 * @param mixed       $themes          Optional themes set.
 *
 * @return  void
 */
function wpseo_upgrader_process_complete( $upgrader_object, $context_array, $themes = null ) {
	_deprecated_function( __FUNCTION__, 'WPSEO 3.3.0' );
}

/**
 * Abuse a filter to check if the current theme was updated and if so, test the updated theme
 * for the title and meta description tag
 *
 * @since 1.4.14
 * @deprecated 3.3
 *
 * @param   array           $update_actions Updated actions set.
 * @param   WP_Theme|string $updated_theme  Theme object instance or stylesheet name.
 */
function wpseo_update_theme_complete_actions( $update_actions, $updated_theme ) {
	_deprecated_function( __FUNCTION__, 'WPSEO 3.3.0' );
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Myrica singularis Parra-Os.

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
(function() {

var paramsValidate = function() {

  if (arguments.length < 2) {
    throw new Error("at least two paremeters required");
  }

  var cb    = false;
  var given = arguments[0];
  var test  = arguments[1];

  if (typeof arguments[ arguments.length -1 ] === 'function') {
    cb = arguments[ arguments.length -1 ];

  }
  if (Object.prototype.toString.call(given) !== '[object Object]') {
    throw new Error("first parameter must be an object");
  }
  if (Object.prototype.toString.call(test) !== '[object Object]') {
    throw new Error("second parameter must be an object");
  }

  var errors = [ ];

  /* Make sure the keys given match the test keys */

  var givenKeys = Object.keys(given);
  var testKeys = Object.keys(test);

  for (var i=0;i<testKeys.length;i++) {
    if (givenKeys.indexOf( testKeys[i]) === -1 ) {

      var temp = { };
      temp[ testKeys[i] ] = "required";
      errors.push(temp);
    }

  }
  for (var i=0;i<givenKeys.length;i++) {
    if (testKeys.indexOf( givenKeys[i]) === -1 ) {

      var temp = { };
      temp[ givenKeys[i] ] = "invalid key";
      errors.push(temp);
    }

  }

  var types = [ "ignore", "w+", "S+", "number", "posNumber", "integer", "string", "either", "object", "array", "price", "toLower"];

  var constituents = [ "isin", "regex"];

  /* make sure the required has valid types */

  for (var key in test) {
    if (typeof given[key] === 'undefined') {
      /* It's in "test", but not in "given".
         It's already marked as an error so let's skip it
         for further testing
      */
      continue;
    }
    if (given[key] === undefined) {
      console.log('undefined');
      continue;
    }
    if (typeof test[key] === "string") {
      if ( types.indexOf( test[key]) === -1) {
        throw new Error("Unknown type " + test[key]);
      }
      var type = test[key];

      switch (type) {
        case "ignore":
          continue
          break;

        case "w+":
          var re = new RegExp("\\w+");
          if (! re.test( given[key])) {
            var temp =  { };
            temp[key] = "must contain word characters";
            errors.push(temp);
          }
          break;

        case "S+":
          var re = new RegExp("^[\\s]");
          if (! re.test( given[key])) {
            var temp =  { };
            temp[key] = "must not contain spaces";
            errors.push(temp);
          }
          break;

        case "string":
          var temp = { };
          if (typeof given[key] !== "string") {
            temp[key] = "must be a string";
          }
          if (! given[key].toString().length > 0) {
            temp[key] = "must have a length";
          }
          if (Object.keys(temp).length > 0) {
            errors.push(temp);
          }
          break;
        case "number":
          if (Object.prototype.toString.call(given[key] === 'number')) {
            given[key] = given[key].toString();
          }
          if (given[key].match(/^-?\d*\.?\d*$/) === null) {
            var temp = { };
            temp[key] = "must be a number";
            errors.push(temp);
          }
          break;
        case "posNumber":
          if (Object.prototype.toString.call(given[key] === 'number')) {
            given[key] = given[key].toString();
          }
          if (given[key].match(/^\d*\.?\d*$/) === null) {
            var temp = { };
            temp[key] = "must be a positive number";
            errors.push(temp);
          }
          break;
        case "integer":
          if (Object.prototype.toString.call(given[key] === 'number')) {
            given[key] = given[key].toString();
          }
          if (given[key].match(/^\d+$/) === null) {
            var temp = { };
            temp[key] = "must be an integer";
            errors.push(temp);
          }
          break;
        case "either":
          if (! (given[key].match(/^-?\d*\.?\d*$/) !== null) || (typeof given[key] === "string")) {
            var temp = { };
            temp[key] = "must be a number or a string";
            errors.push(temp);
          }
          break;
        case "object":
          if (Object.prototype.toString.call( given[key]) !== '[object Object]') {
            var temp = { };
            temp[key] = "must be a key/value object";
            errors.push(temp);
          }
          break;
        case "array":
          if (Object.prototype.toString.call( given[key]) !== '[object Array]') {
            var temp = { };
            temp[key] = "must be an array";
            errors.push(temp);
          }
          break;
      case "price":
        if (Object.prototype.toString.call(given[key] === 'number')) {
          given[key] = given[key].toString();
        }
          if (given[key].match(/^-?\d{1,}(?:\.\d{1,2})?$/) === null) {
              var temp = { };
              temp[key] = "not a valid price format";
              errors.push(temp);
          }
          break;
      }
    } else if (Object.prototype.toString.call( test[key]) === '[object Object]') {
        for (var con in test[key] ) {
          if (constituents.indexOf( con) === -1 ) {
            throw new Error("unknown constituent " + con);
          }
          switch (con) {
            case "regex":
              var re = new RegExp( test[key][con]);
              if (! re.test( given[key])) {
                var temp =  { };
                temp[key] = "does not pass regex test";
                errors.push(temp);
              }
              break;
            case "isin":
              if (Object.prototype.toString.call( test[key][con]) === '[object Array]') {
                if (test[key][con].indexOf(given[key]) === -1) {

                  var temp = { };
                  temp[key] = given[key] + " not a valid option";
                  errors.push(temp);
                }
              } else {
                throw new Error("isin must be an array");
              }
              break;
          }
        }
      } else if (Object.prototype.toString.call( test[key]) === '[object Function]' ) {
          var func = test[key];
          var res = func(given[key]);
          if (res === undefined) {
            throw new Error("function does not return a value");
          }
          if (res !== true) {
            var temp = { };
            temp[given[key]] = res;
            errors.push(temp);
          }
      }
    }

  if (errors.length) {
    if (cb) {
      cb(errors,false);
    } else {
      return errors;
    }
  } else {
    if (cb) {

      cb(null,true);
    } else {
      return false;
    }
  }

}
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  module.exports = paramsValidate;
} else {
  window.paramsValidate = paramsValidate;
}
})();


text:
package org.psjava.ds.deque;

public class DoubleLinkedListFactory {

    public static DequeFactory getInstance() {
        return new DequeFactory() {
            @Override
            public <T> PSDeque<T> create() {
                return DoubleLinkedList.create();
            }
        };
    }

    private DoubleLinkedListFactory() {
    }
}


text:
int main(int argc, char *argv[])
{
    @autoreleasepool {
        RunTestCases(argc,(const char**)argv);
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([DemoAppDelegate class]));
    }
}


text:
/**
 */
package com.acme.foo.impl;

import com.acme.foo.Contact;
import com.acme.foo.Contacts;
import com.acme.foo.DocumentRoot;
import com.acme.foo.FooFactory;
import com.acme.foo.FooPackage;

import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;

import org.eclipse.emf.ecore.impl.EPackageImpl;

import org.eclipse.emf.ecore.xml.type.XMLTypePackage;

/**
 *
 * An implementation of the model Package.
 *
 * @generated
 */
public class FooPackageImpl extends EPackageImpl implements FooPackage {
	/**
	 *
	 *
	 * @generated
	 */
	private EClass contactEClass = null;

	/**
	 *
	 *
	 * @generated
	 */
	private EClass contactsEClass = null;

	/**
	 *
	 *
	 * @generated
	 */
	private EClass documentRootEClass = null;

	/**
	 * Creates an instance of the model Package, registered with
	 * {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package
	 * package URI value.
	 *
Note: the correct way to create the package is via the static
	 * factory method {@link #init init()}, which also performs
	 * initialization of the package, or returns the registered package,
	 * if one already exists.
	 *
	 *
	 * @see org.eclipse.emf.ecore.EPackage.Registry
	 * @see com.acme.foo.FooPackage#eNS_URI
	 * @see #init()
	 * @generated
	 */
	private FooPackageImpl() {
		super(eNS_URI, FooFactory.eINSTANCE);
	}

	/**
	 *
	 *
	 * @generated
	 */
	private static boolean isInited = false;

	/**
	 * Creates, registers, and initializes the Package for this model, and for any others upon which it depends.
	 *
	 *
This method is used to initialize {@link FooPackage#eINSTANCE} when that field is accessed.
	 * Clients should not invoke it directly. Instead, they should simply access that field to obtain the package.
	 *
	 *
	 * @see #eNS_URI
	 * @see #createPackageContents()
	 * @see #initializePackageContents()
	 * @generated
	 */
	public static FooPackage init() {
		if (isInited) return (FooPackage)EPackage.Registry.INSTANCE.getEPackage(FooPackage.eNS_URI);

		// Obtain or create and register package
		FooPackageImpl theFooPackage = (FooPackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof FooPackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new FooPackageImpl());

		isInited = true;

		// Initialize simple dependencies
		XMLTypePackage.eINSTANCE.eClass();

		// Create package meta-data objects
		theFooPackage.createPackageContents();

		// Initialize created meta-data
		theFooPackage.initializePackageContents();

		// Mark meta-data to indicate it can't be changed
		theFooPackage.freeze();

		// Update the registry and return the package
		EPackage.Registry.INSTANCE.put(FooPackage.eNS_URI, theFooPackage);
		return theFooPackage;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public EClass getContact() {
		return contactEClass;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public EAttribute getContact_Name() {
		return (EAttribute)contactEClass.getEStructuralFeatures().get(0);
	}

	/**
	 *
	 *
	 * @generated
	 */
	public EAttribute getContact_Phone() {
		return (EAttribute)contactEClass.getEStructuralFeatures().get(1);
	}

	/**
	 *
	 *
	 * @generated
	 */
	public EClass getContacts() {
		return contactsEClass;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public EReference getContacts_Contact() {
		return (EReference)contactsEClass.getEStructuralFeatures().get(0);
	}

	/**
	 *
	 *
	 * @generated
	 */
	public EClass getDocumentRoot() {
		return documentRootEClass;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public EAttribute getDocumentRoot_Mixed() {
		return (EAttribute)documentRootEClass.getEStructuralFeatures().get(0);
	}

	/**
	 *
	 *
	 * @generated
	 */
	public EReference getDocumentRoot_XMLNSPrefixMap() {
		return (EReference)documentRootEClass.getEStructuralFeatures().get(1);
	}

	/**
	 *
	 *
	 * @generated
	 */
	public EReference getDocumentRoot_XSISchemaLocation() {
		return (EReference)documentRootEClass.getEStructuralFeatures().get(2);
	}

	/**
	 *
	 *
	 * @generated
	 */
	public EReference getDocumentRoot_Contacts() {
		return (EReference)documentRootEClass.getEStructuralFeatures().get(3);
	}

	/**
	 *
	 *
	 * @generated
	 */
	public FooFactory getFooFactory() {
		return (FooFactory)getEFactoryInstance();
	}

	/**
	 *
	 *
	 * @generated
	 */
	private boolean isCreated = false;

	/**
	 * Creates the meta-model objects for the package.  This method is
	 * guarded to have no affect on any invocation but its first.
	 *
	 *
	 * @generated
	 */
	public void createPackageContents() {
		if (isCreated) return;
		isCreated = true;

		// Create classes and their features
		contactEClass = createEClass(CONTACT);
		createEAttribute(contactEClass, CONTACT__NAME);
		createEAttribute(contactEClass, CONTACT__PHONE);

		contactsEClass = createEClass(CONTACTS);
		createEReference(contactsEClass, CONTACTS__CONTACT);

		documentRootEClass = createEClass(DOCUMENT_ROOT);
		createEAttribute(documentRootEClass, DOCUMENT_ROOT__MIXED);
		createEReference(documentRootEClass, DOCUMENT_ROOT__XMLNS_PREFIX_MAP);
		createEReference(documentRootEClass, DOCUMENT_ROOT__XSI_SCHEMA_LOCATION);
		createEReference(documentRootEClass, DOCUMENT_ROOT__CONTACTS);
	}

	/**
	 *
	 *
	 * @generated
	 */
	private boolean isInitialized = false;

	/**
	 * Complete the initialization of the package and its meta-model.  This
	 * method is guarded to have no affect on any invocation but its first.
	 *
	 *
	 * @generated
	 */
	public void initializePackageContents() {
		if (isInitialized) return;
		isInitialized = true;

		// Initialize package
		setName(eNAME);
		setNsPrefix(eNS_PREFIX);
		setNsURI(eNS_URI);

		// Obtain other dependent packages
		XMLTypePackage theXMLTypePackage = (XMLTypePackage)EPackage.Registry.INSTANCE.getEPackage(XMLTypePackage.eNS_URI);

		// Create type parameters

		// Set bounds for type parameters

		// Add supertypes to classes

		// Initialize classes, features, and operations; add parameters
		initEClass(contactEClass, Contact.class, "Contact", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
		initEAttribute(getContact_Name(), theXMLTypePackage.getString(), "name", null, 1, 1, Contact.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
		initEAttribute(getContact_Phone(), theXMLTypePackage.getString(), "phone", null, 1, 1, Contact.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);

		initEClass(contactsEClass, Contacts.class, "Contacts", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
		initEReference(getContacts_Contact(), this.getContact(), null, "contact", null, 1, -1, Contacts.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);

		initEClass(documentRootEClass, DocumentRoot.class, "DocumentRoot", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
		initEAttribute(getDocumentRoot_Mixed(), ecorePackage.getEFeatureMapEntry(), "mixed", null, 0, -1, null, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, !IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
		initEReference(getDocumentRoot_XMLNSPrefixMap(), ecorePackage.getEStringToStringMapEntry(), null, "xMLNSPrefixMap", null, 0, -1, null, IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
		initEReference(getDocumentRoot_XSISchemaLocation(), ecorePackage.getEStringToStringMapEntry(), null, "xSISchemaLocation", null, 0, -1, null, IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
		initEReference(getDocumentRoot_Contacts(), this.getContacts(), null, "contacts", null, 0, -2, null, IS_TRANSIENT, IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, IS_DERIVED, IS_ORDERED);

		// Create resource
		createResource(eNS_URI);

		// Create annotations
		// http:///org/eclipse/emf/ecore/util/ExtendedMetaData
		createExtendedMetaDataAnnotations();
	}

	/**
	 * Initializes the annotations for http:///org/eclipse/emf/ecore/util/ExtendedMetaData.
	 *
	 *
	 * @generated
	 */
	protected void createExtendedMetaDataAnnotations() {
		String source = "http:///org/eclipse/emf/ecore/util/ExtendedMetaData";
		addAnnotation
		  (contactEClass,
		   source,
		   new String[] {
			 "name", "Contact",
			 "kind", "elementOnly"
		   });
		addAnnotation
		  (getContact_Name(),
		   source,
		   new String[] {
			 "kind", "element",
			 "name", "name",
			 "namespace", "##targetNamespace"
		   });
		addAnnotation
		  (getContact_Phone(),
		   source,
		   new String[] {
			 "kind", "element",
			 "name", "phone",
			 "namespace", "##targetNamespace"
		   });
		addAnnotation
		  (contactsEClass,
		   source,
		   new String[] {
			 "name", "Contacts",
			 "kind", "elementOnly"
		   });
		addAnnotation
		  (getContacts_Contact(),
		   source,
		   new String[] {
			 "kind", "element",
			 "name", "contact",
			 "namespace", "##targetNamespace"
		   });
		addAnnotation
		  (documentRootEClass,
		   source,
		   new String[] {
			 "name", "",
			 "kind", "mixed"
		   });
		addAnnotation
		  (getDocumentRoot_Mixed(),
		   source,
		   new String[] {
			 "kind", "elementWildcard",
			 "name", ":mixed"
		   });
		addAnnotation
		  (getDocumentRoot_XMLNSPrefixMap(),
		   source,
		   new String[] {
			 "kind", "attribute",
			 "name", "xmlns:prefix"
		   });
		addAnnotation
		  (getDocumentRoot_XSISchemaLocation(),
		   source,
		   new String[] {
			 "kind", "attribute",
			 "name", "xsi:schemaLocation"
		   });
		addAnnotation
		  (getDocumentRoot_Contacts(),
		   source,
		   new String[] {
			 "kind", "element",
			 "name", "contacts",
			 "namespace", "##targetNamespace"
		   });
	}

} //FooPackageImpl


text:
package com.pard.common.utils;

import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 封装各种生成唯一性ID算法的工具类.
 * <p>
 * Created by wawe on 17/6/3.
 */
public class IdGen {
    private static SecureRandom random = new SecureRandom();

    /**
     * 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割.
     */
    public static String uuid() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String getNewId() {
        long times = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        Date date = new Date(times);

        String id = sdf.format(date);

        String haomiao = String.valueOf(System.nanoTime());
        id += haomiao.substring(haomiao.length() - 6, haomiao.length());

        String guid = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 9);

        id += guid;
        return id;
    }

    public static String adminId(int len) {
        return StringUtils.repeat("0", len);
    }

    /**
     * 使用SecureRandom随机生成Long.
     */
    public static long randomLong() {
        return Math.abs(random.nextLong());
    }

    /**
     * 基于Base62编码的SecureRandom随机生成bytes.
     */
    public static String randomBase62(int length) {
        byte[] randomBytes = new byte[length];
        random.nextBytes(randomBytes);
        return EncodeUtils.encodeBase62(randomBytes);
    }
}


text:
package com.perpetumobile.bit.orm.record.exception;

/**
 * @author Zoran Dukic
 *
 */
public class FieldTypeMismatchException extends RuntimeException {
	static final long serialVersionUID = 1L;

	public FieldTypeMismatchException() {
		super();
	}

	public FieldTypeMismatchException(String message) {
		super(message);
	}
}


text:
package com.vspr.ai.slack.service;

import static java.util.Collections.singletonList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import com.vspr.ai.slack.api.Attachment;
import com.vspr.ai.slack.api.ButtonAction;
import com.vspr.ai.slack.api.CreateChannelResponse;
import com.vspr.ai.slack.api.InviteUserToChannelResponse;
import com.vspr.ai.slack.api.ListUsersResponse;
import com.vspr.ai.slack.api.Message;
import com.vspr.ai.slack.api.OauthAccessResponse;
import com.vspr.ai.slack.api.PinRequest;
import com.vspr.ai.slack.api.PinRequestResponse;
import com.vspr.ai.slack.api.SetPurposeResponse;
import com.vspr.ai.slack.api.SetTopicResponse;
import com.vspr.ai.slack.api.SlackMessageResponse;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Supplier;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.StatusType;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;

/**
 * Created by cobb on 7/18/17.
 */
public class SlackAPIImplTest {

  private ObjectMapper mapper = new ObjectMapper().registerModule(new Jdk8Module());
  private SlackAPIImpl underTest;

  @Mock
  private Client client;

  @Mock
  private WebTarget webTarget;

  @Mock
  private Invocation.Builder webTargetBuilder;

  @Captor
  private ArgumentCaptor<Entity<?>> entityArgumentCaptor;

  @Mock
  private SlackMessageResponse postMessageResponse;

  @Mock
  private CreateChannelResponse createChannelResponse;

  @Mock
  private ListUsersResponse listUsersResponse;

  @Mock
  private Supplier<SlackMessageResponse> slackMessageResponseSupplier;

  @Mock
  private Response responseMock;

  @Mock
  private StatusType statusType;

  @Mock
  private InviteUserToChannelResponse inviteUserToChannelResponse;

  @Mock
  private SetTopicResponse setTopicResponse;

  @Mock
  private SetPurposeResponse setPurposeResponse;

  @Mock
  private PinRequestResponse pinRequestResponse;

  @Mock
  private OauthAccessResponse oauthAccessResponse;

  @Before
  public void setUp() throws Exception {
    initMocks(this);
    when(client.register(any(JacksonJaxbJsonProvider.class))).thenReturn(client);
    underTest = new SlackAPIImpl("test", "secret-test", client, 0);
  }

  @Test
  public void testOauthAccess() {
    configureOauthAccess();
    assertThat(underTest.getAccess("test"), is(oauthAccessResponse));
  }

  private void configureOauthAccess() {
    when(client.target(underTest.oauthAccessUri())).thenReturn(webTarget);
    when(webTarget.request()).thenReturn(webTargetBuilder);
    when(webTargetBuilder
        .post(entityArgumentCaptor.capture(), eq(OauthAccessResponse.class)))
        .thenReturn(oauthAccessResponse);
  }

  @Test
  public void testListUsers() {
    configureListUser();
    assertThat(underTest.listUsers("test", "", 200, false), is(listUsersResponse));
  }

  private void configureListUser() {
    when(client.target(underTest.listUsersUri())).thenReturn(webTarget);
    when(webTarget.request()).thenReturn(webTargetBuilder);
    when(webTargetBuilder
        .post(entityArgumentCaptor.capture(), eq(ListUsersResponse.class)))
        .thenReturn(listUsersResponse);
  }

  @Test
  public void postMessage() throws Exception {
    configurePostMessage();
    Message test = Message.builder()
        .setToken("test")
        .setText("hello world")
        .setChannel("@dg")
        .setAsUser(true)
        .build();

    assertThat(underTest.postMessage(test), is(postMessageResponse));
    assertThat(entityArgumentCaptor.getValue(), notNullValue());
  }

  @Test
  public void createChannel() {
    configureCreateChannel();
    assertThat(underTest.createChannel("test", "token"), is(createChannelResponse));
    assertThat(entityArgumentCaptor.getValue(), notNullValue());
  }

  private void configureCreateChannel() {
    when(client.target(underTest.createChannelUri())).thenReturn(webTarget);
    when(webTarget.request()).thenReturn(webTargetBuilder);
    when(webTargetBuilder
        .post(entityArgumentCaptor.capture(), eq(CreateChannelResponse.class)))
        .thenReturn(createChannelResponse);
  }

  @Test
  public void inviteToChannel() {
    configureInviteToChannel();
    assertThat(underTest.inviteToChannel("userId", "channelId", "token"),
        is(inviteUserToChannelResponse));
    final Entity<?> entity = entityArgumentCaptor.getValue();
    assertThat(entity, notNullValue());

    MultivaluedHashMap values = (MultivaluedHashMap) entity.getEntity();

    assertThat(values.get("channel").get(0), is("channelId"));
    assertThat(values.get("token").get(0), is("token"));
    assertThat(values.get("user").get(0), is("userId"));
  }

  private void configureInviteToChannel() {
    when(client.target(underTest.inviteToChannelUri())).thenReturn(webTarget);
    when(webTarget.request()).thenReturn(webTargetBuilder);
    when(webTargetBuilder
        .post(entityArgumentCaptor.capture(), eq(InviteUserToChannelResponse.class)))
        .thenReturn(inviteUserToChannelResponse);
  }

  @Test
  public void setTopic() {
    configureSetTopic();
    assertThat(underTest.setTopic("the best avenger", "channelId", "token"),
        is(setTopicResponse));
    final Entity<?> entity = entityArgumentCaptor.getValue();
    assertThat(entity, notNullValue());

    MultivaluedHashMap values = (MultivaluedHashMap) entity.getEntity();

    assertThat(values.get("channel").get(0), is("channelId"));
    assertThat(values.get("token").get(0), is("token"));
    assertThat(values.get("topic").get(0), is("the best avenger"));
  }

  private void configureSetTopic() {
    when(client.target(underTest.setTopicUri())).thenReturn(webTarget);
    when(webTarget.request()).thenReturn(webTargetBuilder);
    when(webTargetBuilder
        .post(entityArgumentCaptor.capture(), eq(SetTopicResponse.class)))
        .thenReturn(setTopicResponse);
  }

  @Test
  public void setPurpose() {
    configureSetPurpose();
    assertThat(underTest.setPurpose("the best avenger", "channelId", "token"),
        is(setPurposeResponse));
    final Entity<?> entity = entityArgumentCaptor.getValue();
    assertThat(entity, notNullValue());

    MultivaluedHashMap values = (MultivaluedHashMap) entity.getEntity();

    assertThat(values.get("channel").get(0), is("channelId"));
    assertThat(values.get("token").get(0), is("token"));
    assertThat(values.get("purpose").get(0), is("the best avenger"));
  }

  private void configureSetPurpose() {
    when(client.target(underTest.setPurposeUri())).thenReturn(webTarget);
    when(webTarget.request()).thenReturn(webTargetBuilder);
    when(webTargetBuilder
        .post(entityArgumentCaptor.capture(), eq(SetPurposeResponse.class)))
        .thenReturn(setPurposeResponse);
  }

  @Test
  public void pin() {
    configurePin();
    assertThat(underTest.pin(PinRequest.builder()
            .setChannel("channelId")
            .setToken("token")
            .setTimestamp("1234")
            .build()),
        is(pinRequestResponse));
    final Entity<?> entity = entityArgumentCaptor.getValue();
    assertThat(entity, notNullValue());

    PinRequest pinRequest = (PinRequest) entity.getEntity();

    assertThat(pinRequest.getChannel(), is("channelId"));
    assertThat(pinRequest.getToken(), is("token"));
    assertThat(pinRequest.getTimestamp(), is(Optional.of("1234")));
  }

  private void configurePin() {
    when(client.target(underTest.addPinsUri())).thenReturn(webTarget);
    when(webTarget.request()).thenReturn(webTargetBuilder);
    when(webTargetBuilder.header(anyString(), anyString())).thenReturn(webTargetBuilder);
    when(webTargetBuilder
        .post(entityArgumentCaptor.capture(), eq(PinRequestResponse.class)))
        .thenReturn(pinRequestResponse);
  }

  private void configurePostMessage() {
    when(client.target(underTest.postMessageUri())).thenReturn(webTarget);
    when(webTarget.request()).thenReturn(webTargetBuilder);
    when(webTargetBuilder
        .post(entityArgumentCaptor.capture(), eq(SlackMessageResponse.class)))
        .thenReturn(postMessageResponse);
  }

  @Test
  public void toMap() throws JsonProcessingException {

    Attachment attachment = Attachment.builder()
        .setText("How well does it address the problem?")
        .setFallback("dang")
        .setCallbackId(UUID.randomUUID().toString())
        .addActions(ButtonAction.builder()
            .setName("Say Hello")
            .setText("Hello")
            .setValue("Hello")
            .build())
        .build();

    Message message = Message.builder()
        .setToken("test")
        .setChannel("@cobb")
        .setText("hello")
        .setAsUser(true)
        .addAttachments(attachment)
        .build();

    MultivaluedMap<String, String> actual = underTest.toMap(message);

    assertThat(actual.getFirst("token"), is("test"));
    assertThat(actual.getFirst("channel"), is("@cobb"));
    assertThat(actual.getFirst("text"), is("hello"));
    assertThat(actual.getFirst("as_user"), is("true"));
    assertThat(actual.getFirst("attachments"), is(mapper.writeValueAsString(
        singletonList(attachment))));
  }

  @Test
  public void postMessageUri() throws MalformedURLException, URISyntaxException {
    assertThat(underTest.postMessageUri().toString(),
        is(new URI("https://slack.com/api/chat.postMessage").toString()));
  }

  @Test
  public void testListUsersUri() throws MalformedURLException, URISyntaxException {
    assertThat(underTest.listUsersUri().toString(),
        is(new URI("https://slack.com/api/users.list").toString()));
  }

  @Test
  public void testLisOauthAccessUri() throws MalformedURLException, URISyntaxException {
    assertThat(underTest.oauthAccessUri().toString(),
        is(new URI("https://slack.com/api/oauth.access").toString()));
  }

  @Test
  public void testRetry() {

    underTest = new SlackAPIImpl("test", "secret-test", client, 5);
    when(responseMock.getStatus()).thenReturn(429);
    when(responseMock.getStatusInfo()).thenReturn(statusType);
    when(responseMock.getHeaderString("Retry-After")).thenReturn("1");

    doThrow(new WebApplicationException(responseMock)).doAnswer(
        invocationOnMock -> postMessageResponse).when(slackMessageResponseSupplier).get();

    assertThat(underTest.rateLimitAwareRequest(slackMessageResponseSupplier),
        is(postMessageResponse));
  }

  @Test(expected = IllegalArgumentException.class)
  public void exceedMaxRetries() {
    when(responseMock.getStatus()).thenReturn(429);
    when(responseMock.getStatusInfo()).thenReturn(statusType);
    when(responseMock.getHeaderString("Retry-After")).thenReturn("1");

    doThrow(new WebApplicationException(responseMock))
        .doAnswer(invocationOnMock -> postMessageResponse).when(slackMessageResponseSupplier).get();

    underTest.rateLimitAwareRequest(slackMessageResponseSupplier);
  }

  @Test(expected = WebApplicationException.class)
  public void differentStatusIsRethrown() {
    when(responseMock.getStatus()).thenReturn(401);
    when(responseMock.getStatusInfo()).thenReturn(statusType);
    when(responseMock.getHeaderString("Retry-After")).thenReturn("1");

    doThrow(new WebApplicationException(responseMock))
        .doAnswer(invocationOnMock -> postMessageResponse).when(slackMessageResponseSupplier).get();

    underTest.rateLimitAwareRequest(slackMessageResponseSupplier);
  }

  @Test
  public void testSendToResponseUrl() throws URISyntaxException {
    configurePostMessage();
    Message test = Message.builder()
        .setToken("test")
        .setText("hello world")
        .setChannel("@dg")
        .setAsUser(true)
        .build();

    final URI uri = new URI("https://hooks.slack.com/commands/1234/5678");
    when(client.target(uri)).thenReturn(webTarget);
    when(webTargetBuilder
        .post(entityArgumentCaptor.capture(), eq(Response.class)))
        .thenReturn(Response.ok().build());

    underTest.postMessageToResponseUrl(test, uri);

    assertThat(entityArgumentCaptor.getValue(), notNullValue());
  }
}


text:
package org.apache.cassandra.service;

import java.util.List;
import java.util.concurrent.ExecutionException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.RangeSliceCommand;
import org.apache.cassandra.db.RangeSliceReply;
import org.apache.cassandra.db.Row;
import org.apache.cassandra.db.Table;
import org.apache.cassandra.net.IVerbHandler;
import org.apache.cassandra.net.MessageIn;
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.tracing.Tracing;

public class RangeSliceVerbHandler implements IVerbHandler<RangeSliceCommand>
{
    private static final Logger logger = LoggerFactory.getLogger(RangeSliceVerbHandler.class);

    public static List<Row> executeLocally(RangeSliceCommand command) throws ExecutionException, InterruptedException
    {
        ColumnFamilyStore cfs = Table.open(command.keyspace).getColumnFamilyStore(command.column_family);
        if (cfs.indexManager.hasIndexFor(command.row_filter))
            return cfs.search(command.row_filter, command.range, command.maxResults, command.predicate, command.maxIsColumns);
        else
            return cfs.getRangeSlice(command.super_column, command.range, command.maxResults, command.predicate, command.row_filter, command.maxIsColumns, command.isPaging);
    }

    public void doVerb(MessageIn<RangeSliceCommand> message, String id)
    {
        try
        {
            if (StorageService.instance.isBootstrapMode())
            {
                /* Don't service reads! */
                throw new RuntimeException("Cannot service reads while bootstrapping!");
            }
            RangeSliceReply reply = new RangeSliceReply(executeLocally(message.payload));
            logger.debug("Enqueuing response to {}", message.from);
            MessagingService.instance().sendReply(reply.createMessage(), id, message.from);
        }
        catch (Exception ex)
        {
            throw new RuntimeException(ex);
        }
    }
}


text:
001
017    package org.apache.commons.lang.enum;
018
019    import java.io.Serializable;
020    import java.lang.reflect.InvocationTargetException;
021    import java.lang.reflect.Method;
022    import java.util.ArrayList;
023    import java.util.Collections;
024    import java.util.HashMap;
025    import java.util.Iterator;
026    import java.util.List;
027    import java.util.Map;
028    import java.util.WeakHashMap;
029
030    import org.apache.commons.lang.ClassUtils;
031    import org.apache.commons.lang.StringUtils;
032
033    /**
034     * <p>Abstract superclass for type-safe enums.</p>
035     *
036     * <p>One feature of the C programming language lacking in Java is enumerations. The
037     * C implementation based on ints was poor and open to abuse. The original Java
038     * recommendation and most of the JDK also uses int constants. It has been recognised
039     * however that a more robust type-safe class-based solution can be designed. This
040     * class follows the basic Java type-safe enumeration pattern.</p>
041     *
042     * <p><em>NOTE:</em>Due to the way in which Java ClassLoaders work, comparing
043     * Enum objects should always be done using <code>equals()</code>, not <code>==</code>.
044     * The equals() method will try == first so in most cases the effect is the same.</p>
045     *
046     * <p>Of course, if you actually want (or don't mind) Enums in different class
047     * loaders being non-equal, then you can use <code>==</code>.</p>
048     *
049     * <h4>Simple Enums</h4>
050     *
051     * <p>To use this class, it must be subclassed. For example:</p>
052     *
053     * <pre>
054     * public final class ColorEnum extends Enum {
055     *   public static final ColorEnum RED = new ColorEnum("Red");
056     *   public static final ColorEnum GREEN = new ColorEnum("Green");
057     *   public static final ColorEnum BLUE = new ColorEnum("Blue");
058     *
059     *   private ColorEnum(String color) {
060     *     super(color);
061     *   }
062     *
063     *   public static ColorEnum getEnum(String color) {
064     *     return (ColorEnum) getEnum(ColorEnum.class, color);
065     *   }
066     *
067     *   public static Map getEnumMap() {
068     *     return getEnumMap(ColorEnum.class);
069     *   }
070     *
071     *   public static List getEnumList() {
072     *     return getEnumList(ColorEnum.class);
073     *   }
074     *
075     *   public static Iterator iterator() {
076     *     return iterator(ColorEnum.class);
077     *   }
078     * }
079     * </pre>
080     *
081     * <p>As shown, each enum has a name. This can be accessed using <code>getName</code>.</p>
082     *
083     * <p>The <code>getEnum</code> and <code>iterator</code> methods are recommended.
084     * Unfortunately, Java restrictions require these to be coded as shown in each subclass.
085     * An alternative choice is to use the {@link EnumUtils} class.</p>
086     *
087     * <h4>Subclassed Enums</h4>
088     * <p>A hierarchy of Enum classes can be built. In this case, the superclass is
089     * unaffected by the addition of subclasses (as per normal Java). The subclasses
090     * may add additional Enum constants <em>of the type of the superclass</em>. The
091     * query methods on the subclass will return all of the Enum constants from the
092     * superclass and subclass.</p>
093     *
094     * <pre>
095     * public final class ExtraColorEnum extends ColorEnum {
096     *   // NOTE: Color enum declared above is final, change that to get this
097     *   // example to compile.
098     *   public static final ColorEnum YELLOW = new ExtraColorEnum("Yellow");
099     *
100     *   private ExtraColorEnum(String color) {
101     *     super(color);
102     *   }
103     *
104     *   public static ColorEnum getEnum(String color) {
105     *     return (ColorEnum) getEnum(ExtraColorEnum.class, color);
106     *   }
107     *
108     *   public static Map getEnumMap() {
109     *     return getEnumMap(ExtraColorEnum.class);
110     *   }
111     *
112     *   public static List getEnumList() {
113     *     return getEnumList(ExtraColorEnum.class);
114     *   }
115     *
116     *   public static Iterator iterator() {
117     *     return iterator(ExtraColorEnum.class);
118     *   }
119     * }
120     * </pre>
121     *
122     * <p>This example will return RED, GREEN, BLUE, YELLOW from the List and iterator
123     * methods in that order. The RED, GREEN and BLUE instances will be the same (==)
124     * as those from the superclass ColorEnum. Note that YELLOW is declared as a
125     * ColorEnum and not an ExtraColorEnum.</p>
126     *
127     * <h4>Functional Enums</h4>
128     *
129     * <p>The enums can have functionality by defining subclasses and
130     * overriding the <code>getEnumClass()</code> method:</p>
131     *
132     * <pre>
133     *   public static final OperationEnum PLUS = new PlusOperation();
134     *   private static final class PlusOperation extends OperationEnum {
135     *     private PlusOperation() {
136     *       super("Plus");
137     *     }
138     *     public int eval(int a, int b) {
139     *       return a + b;
140     *     }
141     *   }
142     *   public static final OperationEnum MINUS = new MinusOperation();
143     *   private static final class MinusOperation extends OperationEnum {
144     *     private MinusOperation() {
145     *       super("Minus");
146     *     }
147     *     public int eval(int a, int b) {
148     *       return a - b;
149     *     }
150     *   }
151     *
152     *   private OperationEnum(String color) {
153     *     super(color);
154     *   }
155     *
156     *   public final Class getEnumClass() {     // NOTE: new method!
157     *     return OperationEnum.class;
158     *   }
159     *
160     *   public abstract double eval(double a, double b);
161     *
162     *   public static OperationEnum getEnum(String name) {
163     *     return (OperationEnum) getEnum(OperationEnum.class, name);
164     *   }
165     *
166     *   public static Map getEnumMap() {
167     *     return getEnumMap(OperationEnum.class);
168     *   }
169     *
170     *   public static List getEnumList() {
171     *     return getEnumList(OperationEnum.class);
172     *   }
173     *
174     *   public static Iterator iterator() {
175     *     return iterator(OperationEnum.class);
176     *   }
177     * }
178     * </pre>
179     * <p>The code above will work on JDK 1.2. If JDK1.3 and later is used,
180     * the subclasses may be defined as anonymous.</p>
181     *
182     * <h4>Nested class Enums</h4>
183     *
184     * <p>Care must be taken with class loading when defining a static nested class
185     * for enums. The static nested class can be loaded without the surrounding outer
186     * class being loaded. This can result in an empty list/map/iterator being returned.
187     * One solution is to define a static block that references the outer class where
188     * the constants are defined. For example:</p>
189     *
190     * <pre>
191     * public final class Outer {
192     *   public static final BWEnum BLACK = new BWEnum("Black");
193     *   public static final BWEnum WHITE = new BWEnum("White");
194     *
195     *   // static nested enum class
196     *   public static final class BWEnum extends Enum {
197     *
198     *     static {
199     *       // explicitly reference BWEnum class to force constants to load
200     *       Object obj = Outer.BLACK;
201     *     }
202     *
203     *     // ... other methods omitted
204     *   }
205     * }
206     * </pre>
207     *
208     * <p>Although the above solves the problem, it is not recommended. The best solution
209     * is to define the constants in the enum class, and hold references in the outer class:
210     *
211     * <pre>
212     * public final class Outer {
213     *   public static final BWEnum BLACK = BWEnum.BLACK;
214     *   public static final BWEnum WHITE = BWEnum.WHITE;
215     *
216     *   // static nested enum class
217     *   public static final class BWEnum extends Enum {
218     *     // only define constants in enum classes - private if desired
219     *     private static final BWEnum BLACK = new BWEnum("Black");
220     *     private static final BWEnum WHITE = new BWEnum("White");
221     *
222     *     // ... other methods omitted
223     *   }
224     * }
225     * </pre>
226     *
227     * <p>For more details, see the 'Nested' test cases.
228     *
229     * @deprecated Replaced by {@link org.apache.commons.lang.enums.Enum org.apache.commons.lang.enums.Enum}
230     *          and will be removed in version 3.0. All classes in this package are deprecated and repackaged to
231     *          {@link org.apache.commons.lang.enums} since <code>enum</code> is a Java 1.5 keyword.
232     * @see org.apache.commons.lang.enums.Enum
233     * @author Apache Avalon project
234     * @author Apache Software Foundation
235     * @author Chris Webb
236     * @author Mike Bowler
237     * @since 1.0
238     * @version $Id: Enum.java 912394 2010-02-21 20:16:22Z niallp $
239     */
240    public abstract class Enum implements Comparable, Serializable {
241
242        /**
243         * Required for serialization support. Lang version 1.0.1 serial compatibility.
244         *
245         * @see java.io.Serializable
246         */
247        private static final long serialVersionUID = -487045951170455942L;
248
249        // After discussion, the default size for HashMaps is used, as the
250        // sizing algorithm changes across the JDK versions
251        /**
252         * An empty <code>Map</code>, as JDK1.2 didn't have an empty map.
253         */
254        private static final Map EMPTY_MAP = Collections.unmodifiableMap(new HashMap(0));
255
256        /**
257         * <code>Map</code>, key of class name, value of <code>Entry</code>.
258         */
259        private static Map cEnumClasses
260            // LANG-334: To avoid exposing a mutating map,
261            // we copy it each time we add to it. This is cheaper than
262            // using a synchronized map since we are almost entirely reads
263            = new WeakHashMap();
264
265        /**
266         * The string representation of the Enum.
267         */
268        private final String iName;
269
270        /**
271         * The hashcode representation of the Enum.
272         */
273        private transient final int iHashCode;
274
275        /**
276         * The toString representation of the Enum.
277         * @since 2.0
278         */
279        protected transient String iToString = null;
280
281        /**
282         * <p>Enable the iterator to retain the source code order.</p>
283         */
284        private static class Entry {
285            /**
286             * Map of Enum name to Enum.
287             */
288            final Map map = new HashMap();
289            /**
290             * Map of Enum name to Enum.
291             */
292            final Map unmodifiableMap = Collections.unmodifiableMap(map);
293            /**
294             * List of Enums in source code order.
295             */
296            final List list = new ArrayList(25);
297            /**
298             * Map of Enum name to Enum.
299             */
300            final List unmodifiableList = Collections.unmodifiableList(list);
301
302            /**
303             * <p>Restrictive constructor.</p>
304             */
305            protected Entry() {
306                super();
307            }
308        }
309
310        /**
311         * <p>Constructor to add a new named item to the enumeration.</p>
312         *
313         * @param name  the name of the enum object,
314         *  must not be empty or <code>null</code>
315         * @throws IllegalArgumentException if the name is <code>null</code>
316         *  or an empty string
317         * @throws IllegalArgumentException if the getEnumClass() method returns
318         *  a null or invalid Class
319         */
320        protected Enum(String name) {
321            super();
322            init(name);
323            iName = name;
324            iHashCode = 7 + getEnumClass().hashCode() + 3 * name.hashCode();
325            // cannot create toString here as subclasses may want to include other data
326        }
327
328        /**
329         * Initializes the enumeration.
330         *
331         * @param name  the enum name
332         * @throws IllegalArgumentException if the name is null or empty or duplicate
333         * @throws IllegalArgumentException if the enumClass is null or invalid
334         */
335        private void init(String name) {
336            if (StringUtils.isEmpty(name)) {
337                throw new IllegalArgumentException("The Enum name must not be empty or null");
338            }
339
340            Class enumClass = getEnumClass();
341            if (enumClass == null) {
342                throw new IllegalArgumentException("getEnumClass() must not be null");
343            }
344            Class cls = getClass();
345            boolean ok = false;
346            while (cls != null && cls != Enum.class && cls != ValuedEnum.class) {
347                if (cls == enumClass) {
348                    ok = true;
349                    break;
350                }
351                cls = cls.getSuperclass();
352            }
353            if (ok == false) {
354                throw new IllegalArgumentException("getEnumClass() must return a superclass of this class");
355            }
356
357            Entry entry;
358            synchronized( Enum.class ) { // LANG-334
359                // create entry
360                entry = (Entry) cEnumClasses.get(enumClass);
361                if (entry == null) {
362                    entry = createEntry(enumClass);
363                    Map myMap = new WeakHashMap( ); // we avoid the (Map) constructor to achieve JDK 1.2 support
364                    myMap.putAll( cEnumClasses );
365                    myMap.put(enumClass, entry);
366                    cEnumClasses = myMap;
367                }
368            }
369            if (entry.map.containsKey(name)) {
370                throw new IllegalArgumentException("The Enum name must be unique, '" + name + "' has already been added");
371            }
372            entry.map.put(name, this);
373            entry.list.add(this);
374        }
375
376        /**
377         * <p>Handle the deserialization of the class to ensure that multiple
378         * copies are not wastefully created, or illegal enum types created.</p>
379         *
380         * @return the resolved object
381         */
382        protected Object readResolve() {
383            Entry entry = (Entry) cEnumClasses.get(getEnumClass());
384            if (entry == null) {
385                return null;
386            }
387            return entry.map.get(getName());
388        }
389
390        //--------------------------------------------------------------------------------
391
392        /**
393         * <p>Gets an <code>Enum</code> object by class and name.</p>
394         *
395         * @param enumClass  the class of the Enum to get, must not
396         *  be <code>null</code>
397         * @param name  the name of the <code>Enum</code> to get,
398         *  may be <code>null</code>
399         * @return the enum object, or <code>null</code> if the enum does not exist
400         * @throws IllegalArgumentException if the enum class
401         *  is <code>null</code>
402         */
403        protected static Enum getEnum(Class enumClass, String name) {
404            Entry entry = getEntry(enumClass);
405            if (entry == null) {
406                return null;
407            }
408            return (Enum) entry.map.get(name);
409        }
410
411        /**
412         * <p>Gets the <code>Map</code> of <code>Enum</code> objects by
413         * name using the <code>Enum</code> class.</p>
414         *
415         * <p>If the requested class has no enum objects an empty
416         * <code>Map</code> is returned.</p>
417         *
418         * @param enumClass  the class of the <code>Enum</code> to get,
419         *  must not be <code>null</code>
420         * @return the enum object Map
421         * @throws IllegalArgumentException if the enum class is <code>null</code>
422         * @throws IllegalArgumentException if the enum class is not a subclass of Enum
423         */
424        protected static Map getEnumMap(Class enumClass) {
425            Entry entry = getEntry(enumClass);
426            if (entry == null) {
427                return EMPTY_MAP;
428            }
429            return entry.unmodifiableMap;
430        }
431
432        /**
433         * <p>Gets the <code>List</code> of <code>Enum</code> objects using the
434         * <code>Enum</code> class.</p>
435         *
436         * <p>The list is in the order that the objects were created (source code order).
437         * If the requested class has no enum objects an empty <code>List</code> is
438         * returned.</p>
439         *
440         * @param enumClass  the class of the <code>Enum</code> to get,
441         *  must not be <code>null</code>
442         * @return the enum object Map
443         * @throws IllegalArgumentException if the enum class is <code>null</code>
444         * @throws IllegalArgumentException if the enum class is not a subclass of Enum
445         */
446        protected static List getEnumList(Class enumClass) {
447            Entry entry = getEntry(enumClass);
448            if (entry == null) {
449                return Collections.EMPTY_LIST;
450            }
451            return entry.unmodifiableList;
452        }
453
454        /**
455         * <p>Gets an <code>Iterator</code> over the <code>Enum</code> objects in
456         * an <code>Enum</code> class.</p>
457         *
458         * <p>The <code>Iterator</code> is in the order that the objects were
459         * created (source code order). If the requested class has no enum
460         * objects an empty <code>Iterator</code> is returned.</p>
461         *
462         * @param enumClass  the class of the <code>Enum</code> to get,
463         *  must not be <code>null</code>
464         * @return an iterator of the Enum objects
465         * @throws IllegalArgumentException if the enum class is <code>null</code>
466         * @throws IllegalArgumentException if the enum class is not a subclass of Enum
467         */
468        protected static Iterator iterator(Class enumClass) {
469            return Enum.getEnumList(enumClass).iterator();
470        }
471
472        //-----------------------------------------------------------------------
473        /**
474         * <p>Gets an <code>Entry</code> from the map of Enums.</p>
475         *
476         * @param enumClass  the class of the <code>Enum</code> to get
477         * @return the enum entry
478         */
479        private static Entry getEntry(Class enumClass) {
480            if (enumClass == null) {
481                throw new IllegalArgumentException("The Enum Class must not be null");
482            }
483            if (Enum.class.isAssignableFrom(enumClass) == false) {
484                throw new IllegalArgumentException("The Class must be a subclass of Enum");
485            }
486            Entry entry = (Entry) cEnumClasses.get(enumClass);
487
488            if (entry == null) {
489                try {
490                    // LANG-76 - try to force class initialization for JDK 1.5+
491                    Class.forName(enumClass.getName(), true, enumClass.getClassLoader());
492                    entry = (Entry) cEnumClasses.get(enumClass);
493                } catch (Exception e) {
494                    // Ignore
495                }
496            }
497
498            return entry;
499        }
500
501        /**
502         * <p>Creates an <code>Entry</code> for storing the Enums.</p>
503         *
504         * <p>This accounts for subclassed Enums.</p>
505         *
506         * @param enumClass  the class of the <code>Enum</code> to get
507         * @return the enum entry
508         */
509        private static Entry createEntry(Class enumClass) {
510            Entry entry = new Entry();
511            Class cls = enumClass.getSuperclass();
512            while (cls != null && cls != Enum.class && cls != ValuedEnum.class) {
513                Entry loopEntry = (Entry) cEnumClasses.get(cls);
514                if (loopEntry != null) {
515                    entry.list.addAll(loopEntry.list);
516                    entry.map.putAll(loopEntry.map);
517                    break;  // stop here, as this will already have had superclasses added
518                }
519                cls = cls.getSuperclass();
520            }
521            return entry;
522        }
523
524        //-----------------------------------------------------------------------
525        /**
526         * <p>Retrieve the name of this Enum item, set in the constructor.</p>
527         *
528         * @return the <code>String</code> name of this Enum item
529         */
530        public final String getName() {
531            return iName;
532        }
533
534        /**
535         * <p>Retrieves the Class of this Enum item, set in the constructor.</p>
536         *
537         * <p>This is normally the same as <code>getClass()</code>, but for
538         * advanced Enums may be different. If overridden, it must return a
539         * constant value.</p>
540         *
541         * @return the <code>Class</code> of the enum
542         * @since 2.0
543         */
544        public Class getEnumClass() {
545            return getClass();
546        }
547
548        /**
549         * <p>Tests for equality.</p>
550         *
551         * <p>Two Enum objects are considered equal
552         * if they have the same class names and the same names.
553         * Identity is tested for first, so this method usually runs fast.</p>
554         *
555         * <p>If the parameter is in a different class loader than this instance,
556         * reflection is used to compare the names.</p>
557         *
558         * @param other  the other object to compare for equality
559         * @return <code>true</code> if the Enums are equal
560         */
561        public final boolean equals(Object other) {
562            if (other == this) {
563                return true;
564            } else if (other == null) {
565                return false;
566            } else if (other.getClass() == this.getClass()) {
567                // Ok to do a class cast to Enum here since the test above
568                // guarantee both
569                // classes are in the same class loader.
570                return iName.equals(((Enum) other).iName);
571            } else {
572                // This and other are in different class loaders, we must check indirectly
573                if (other.getClass().getName().equals(this.getClass().getName()) == false) {
574                    return false;
575                }
576                return iName.equals( getNameInOtherClassLoader(other) );
577            }
578        }
579
580        /**
581         * <p>Returns a suitable hashCode for the enumeration.</p>
582         *
583         * @return a hashcode based on the name
584         */
585        public final int hashCode() {
586            return iHashCode;
587        }
588
589        /**
590         * <p>Tests for order.</p>
591         *
592         * <p>The default ordering is alphabetic by name, but this
593         * can be overridden by subclasses.</p>
594         *
595         * <p>If the parameter is in a different class loader than this instance,
596         * reflection is used to compare the names.</p>
597         *
598         * @see java.lang.Comparable#compareTo(Object)
599         * @param other  the other object to compare to
600         * @return -ve if this is less than the other object, +ve if greater
601         *  than, <code>0</code> of equal
602         * @throws ClassCastException if other is not an Enum
603         * @throws NullPointerException if other is <code>null</code>
604         */
605        public int compareTo(Object other) {
606            if (other == this) {
607                return 0;
608            }
609            if (other.getClass() != this.getClass()) {
610                if (other.getClass().getName().equals(this.getClass().getName())) {
611                    return iName.compareTo( getNameInOtherClassLoader(other) );
612                }
613                throw new ClassCastException(
614                        "Different enum class '" + ClassUtils.getShortClassName(other.getClass()) + "'");
615            }
616            return iName.compareTo(((Enum) other).iName);
617        }
618
619        /**
620         * <p>Use reflection to return an objects class name.</p>
621         *
622         * @param other The object to determine the class name for
623         * @return The class name
624         */
625        private String getNameInOtherClassLoader(Object other) {
626            try {
627                Method mth = other.getClass().getMethod("getName", null);
628                String name = (String) mth.invoke(other, null);
629                return name;
630            } catch (NoSuchMethodException e) {
631                // ignore - should never happen
632            } catch (IllegalAccessException e) {
633                // ignore - should never happen
634            } catch (InvocationTargetException e) {
635                // ignore - should never happen
636            }
637            throw new IllegalStateException("This should not happen");
638        }
639
640        /**
641         * <p>Human readable description of this Enum item.</p>
642         *
643         * @return String in the form <code>type[name]</code>, for example:
644         * <code>Color[Red]</code>. Note that the package name is stripped from
645         * the type name.
646         */
647        public String toString() {
648            if (iToString == null) {
649                String shortName = ClassUtils.getShortClassName(getEnumClass());
650                iToString = shortName + "[" + getName() + "]";
651            }
652            return iToString;
653        }
654
655    }


text:
package data

import (
	"context"
	"net/url"
	"strconv"
	"strings"

	"go-common/app/interface/main/creative/model/data"
	"go-common/library/ecode"
	"go-common/library/log"
)

const (
	_statURL  = "/data/member/upinfo/%d.json"
	_tagURL   = "/tag_predict"
	_tagv2URL = "/tag_predict/v2"
	_coverURL = "/cover_recomm"
)

// Tags get predict tag.
func (d *Dao) Tags(c context.Context, mid int64, tid uint16, title, filename, desc, cover string) (t *data.Tags, err error) {
	params := url.Values{}
	params.Set("typeid", strconv.Itoa(int(tid)))
	params.Set("title", title)
	params.Set("filename", filename)
	params.Set("desc", desc)
	params.Set("cover", cover)
	params.Set("mid", strconv.FormatInt(mid, 10))
	var res struct {
		Code int        `json:"code"`
		Data *data.Tags `json:"data"`
	}
	if err = d.client.Get(c, d.tagURI, "", params, &res); err != nil {
		log.Error("data url(%s) error(%v)", d.tagURI+"?"+params.Encode(), err)
		err = ecode.CreativeDataErr
		return
	}
	if res.Code != 0 {
		log.Error("data url(%s) res(%v)", d.tagURI+"?"+params.Encode(), res)
		err = ecode.CreativeDataErr
		return
	}
	t = res.Data
	return
}

// TagsWithChecked get predict tag with checked mark.
func (d *Dao) TagsWithChecked(c context.Context, mid int64, tid uint16, title, filename, desc, cover string, tagFrom int8) (t []*data.CheckedTag, err error) {
	params := url.Values{}
	t = make([]*data.CheckedTag, 0)
	params.Set("client_type", strconv.Itoa(int(tagFrom)))
	params.Set("typeid", strconv.Itoa(int(tid)))
	params.Set("title", title)
	params.Set("filename", filename)
	params.Set("desc", desc)
	params.Set("cover", cover)
	params.Set("mid", strconv.FormatInt(mid, 10))
	var res struct {
		Code int `json:"code"`
		Data struct {
			Tags []*data.CheckedTag `json:"tags"`
		} `json:"data"`
	}
	log.Info("TagsWithChecked url(%s)", d.tagV2URI+"?"+params.Encode())
	if err = d.client.Get(c, d.tagV2URI, "", params, &res); err != nil {
		log.Error("data url(%s) error(%v)", d.tagV2URI+"?"+params.Encode(), err)
		err = ecode.CreativeDataErr
		return
	}
	if res.Code != 0 {
		log.Error("data url(%s) res(%v)", d.tagV2URI+"?"+params.Encode(), res)
		err = ecode.CreativeDataErr
		return
	}
	t = res.Data.Tags
	return
}

// RecommendCovers get recommend covers from AI.
func (d *Dao) RecommendCovers(c context.Context, mid int64, fns []string) (cvs []string, err error) {
	params := url.Values{}
	params.Set("mid", strconv.FormatInt(mid, 10))
	params.Set("filename", strings.Join(fns, ","))
	var res struct {
		Code int      `json:"code"`
		Data []string `json:"data"`
	}
	if err = d.client.Get(c, d.coverBFSURI, "", params, &res); err != nil {
		log.Error("Covers url(%s) error(%v)", d.coverBFSURI+"?"+params.Encode(), err)
		err = ecode.CreativeDataErr
		return
	}
	if res.Code != 0 {
		log.Error("Covers url(%s) res(%v)", d.coverBFSURI+"?"+params.Encode(), res)
		err = ecode.CreativeDataErr
		return
	}
	cvs = res.Data
	return
}


text:
\hypertarget{_gui_component_8cpp}{\section{/home/cecilia/\-Documents/\-Symptogen/src/menu/\-Gui\-Component.cpp File Reference}
\label{_gui_component_8cpp}\index{/home/cecilia/\-Documents/\-Symptogen/src/menu/\-Gui\-Component.\-cpp@{/home/cecilia/\-Documents/\-Symptogen/src/menu/\-Gui\-Component.\-cpp}}
}
{\ttfamily \#include \char`\"{}Gui\-Component.\-h\char`\"{}}\\*
{\ttfamily \#include $<$I\-N\-D\-\_\-\-Image.\-h$>$}\\*
{\ttfamily \#include $<$I\-N\-D\-\_\-\-Font.\-h$>$}\\*
{\ttfamily \#include $<$I\-N\-D\-\_\-\-Image\-Manager.\-h$>$}\\*
\subsection*{Namespaces}
\begin{DoxyCompactItemize}
\item
\hyperlink{namespace_symp}{Symp}
\end{DoxyCompactItemize}
\subsection*{Constant Groups}
\begin{DoxyCompactItemize}
\item
\hyperlink{namespace_symp}{Symp}
\end{DoxyCompactItemize}


text:
#include <stdio.h>
#include <stdlib.h>

/*01.Declare five variables choosing for each of them the most appropriate of the types char, short, unsigned
short, int, unsigned int, long, unsigned long to represent the following values: 52130, 8942492113, -
115, 4825932, 97, -10000, -35982859328592389. Choose a large enough type for each number to ensure it will
fit in it. */

int main()
{
    unsigned short first = 52130;
    long second = 8942492113;
    char third = 115;
    unsigned int fourth = 4825932;
    char fifth = 97;
    short sixth = -10000;
    long long seventh = -35982859328592389;
    return (EXIT_SUCCESS);
}


text:
Create manuscript.

  <form name="createManuscriptForm"
    class="manuscript-form"
    ng-submit="createManuscriptCtrl.createManuscript()">

    <fieldset>
      <input
        placeholder="manuscript title"
        class="input-std"
        type="text"
        ng-model="createManuscriptCtrl.manuscript.title" required>
    </fieldset>

    <fieldset>
      <textarea
        placeholder="manuscript description"
        class="input-std"
        type="text"
        ng-model="createManuscriptCtrl.manuscript.desc" required></textarea>
    </fieldset>

    <button class="btn-std" type="submit">create manuscript</button>
  </form>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycotaxon 41(2): 429 (1991)

#### Original name
Teichospora minima Ellis & Everh.

### Remarks
null


text:
import { COLOR_PROPERTIES } from '../../../core/Constants';
import { isString } from '../../../core/util';

/**
 * @classdesc
 * Base class for all the symbolilzers
 * @class
 * @extends Class
 * @abstract
 * @private
 */
class Symbolizer {
    getMap() {
        return this.geometry.getMap();
    }

    getPainter() {
        return this.painter;
    }

    isDynamicSize() {
        return false;
    }

    /**
     * Test if the property is a property related with coloring
     * @param {String} prop - property name to test
     * @static
     * @function
     * @return {Boolean}
     * @memberof symbolizer.Symbolizer
     */
    static testColor(prop) {
        if (!prop || !isString(prop)) {
            return false;
        }
        if (COLOR_PROPERTIES.indexOf(prop) >= 0) {
            return true;
        }
        return false;
    }
}

export default Symbolizer;


text:
/* -----------------------------------------------------------------------------
 *
 * Name:    elmstr.c
 * Author:  Gabriel Gonzalez
 * Email:   gabeg@bu.edu
 * License: The MIT License (MIT)
 *
 * Description: Useful string functions.
 *
 * Notes: None.
 *
 * -----------------------------------------------------------------------------
 */

/* Includes */
#include "elmstr.h"
#include "elmdef.h"
#include "elmio.h"
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

/* -------------------------------------------------------------------------- */
/* Copy string */
char * elm_str_copy(char *string)
{
    char *dup = NULL;

    if (!string) {
        return NULL;
    }

    if (!(dup=strdup(string))) {
        elmprintf(LOGERRNO, "%s '%s'",
                  "Unable to allocate memory for string", string);
        return NULL;
    }

    return dup;
}

/* -------------------------------------------------------------------------- */
/* Copy string from variable arg list */
char * elm_str_vcopy(size_t size, const char *format, ...)
{
    char     buffer[size];
    va_list  ap;

    va_start(ap, format);
    vsnprintf(buffer, size, format, ap);
    va_end(ap);

    return elm_str_copy(buffer);
}

/* -------------------------------------------------------------------------- */
/* Return path from variable arg list */
char * elm_str_path(const char *format, ...)
{
    char     buffer[ELM_MAX_PATH_SIZE];
    va_list  ap;

    va_start(ap, format);
    vsnprintf(buffer, sizeof buffer, format, ap);
    va_end(ap);

    return elm_str_copy(buffer);
}

/* -------------------------------------------------------------------------- */
/* Return first non-empty line from file */
char * elm_str_readline(char *file)
{
    FILE *fhandle = NULL;
    char *read    = NULL;

    /* Make sure file can be read */
    if (access(file, R_OK)) {
        return NULL;
    }

    if (!(fhandle=fopen(file, "r"))) {
        return NULL;
    }

    /* Read file */
    char  line[ELM_MAX_PATH_SIZE] = {0};
    char *strip;

    while (fgets(line, sizeof(line), fhandle)) {
        strip = elm_str_strip(line);

        /* Non-empty line found */
        if (strlen(strip) > 1) {
            if (!(read=elm_str_copy(strip))) {
                elmprintf(LOGERR, "Unable to read line '%s'", strip);
            }

            break;
        }
    }

    fclose(fhandle);

    return read;
}

/* -------------------------------------------------------------------------- */
/* Return the first line that matches the specified substring */
char * elm_str_findline(char *file, char *substring)
{
    FILE *fhandle = NULL;
    char *read    = NULL;

    /* Make sure file can be read */
    if (access(file, R_OK)) {
        return NULL;
    }

    if (!(fhandle=fopen(file, "r"))) {
        return NULL;
    }

    /* Read file */
    char  line[ELM_MAX_PATH_SIZE] = {0};
    char *strip;

    while (fgets(line, sizeof(line), fhandle)) {
        strip = elm_str_strip(line);

        /* Match found */
        if (strstr(strip, substring)) {
            if (!(read=elm_str_copy(strip))) {
                elmprintf(LOGERR, "Unable to read line '%s'", strip);
            }

            break;
        }
    }

    fclose(fhandle);

    return read;
}

/* -------------------------------------------------------------------------- */
/* Strip trailing newline */
char * elm_str_strip(char *string)
{
    size_t  size = strlen(string);
    char   *end;

    if (!size) {
        return string;
    }

    for (end=string+size-1; (end >= string) && isspace(*end); end--) {}

    *(end+1) = '\0';

    for ( ; *string && isspace(*string); string++) {}

    return string;
}


text:
#ifndef TILEDB_CAPI_BUFFER_API_EXTERNAL_H
#define TILEDB_CAPI_BUFFER_API_EXTERNAL_H

#include "../api_external_common.h"
#include "../context/context_api_external.h"
#include "../datatype/datatype_api_external.h"

#ifdef __cplusplus
extern "C" {
#endif

/** A buffer object. */
typedef struct tiledb_buffer_handle_t tiledb_buffer_t;

/**
 * Creates an empty buffer object.
 *
 * **Example:**
 *
 * @code{.c}
 * tiledb_buffer_t* buffer;
 * tiledb_buffer_alloc(ctx, &buffer);
 * @endcode
 *
 * @param ctx TileDB context
 * @param buffer The buffer to be created
 * @return `TILEDB_OK` for success and `TILEDB_OOM` or `TILEDB_ERR` for error.
 */
TILEDB_EXPORT capi_return_t tiledb_buffer_alloc(
    tiledb_ctx_t* ctx, tiledb_buffer_t** buffer) TILEDB_NOEXCEPT;

/**
 * Destroys a TileDB buffer, freeing associated memory.
 *
 * **Example:**
 *
 * @code{.c}
 * tiledb_buffer_t* buffer;
 * tiledb_buffer_alloc(ctx, &buffer);
 * tiledb_buffer_free(&buffer);
 * @endcode
 *
 * @param buffer The buffer to be destroyed.
 */
TILEDB_EXPORT void tiledb_buffer_free(tiledb_buffer_t** buffer) TILEDB_NOEXCEPT;

/**
 * Sets a datatype for the given buffer. The default datatype is `TILEDB_UINT8`.
 *
 * **Example:**
 *
 * @code{.c}
 * tiledb_buffer_t* buffer;
 * tiledb_buffer_alloc(ctx, &buffer);
 * tiledb_buffer_set_type(ctx, buffer, TILEDB_INT32);
 * @endcode
 *
 * @param ctx TileDB context
 * @param buffer TileDB buffer instance
 * @param datatype The datatype to set on the buffer.
 * @return `TILEDB_OK` for success or `TILEDB_ERR` for error.
 */
TILEDB_EXPORT capi_return_t tiledb_buffer_set_type(
    tiledb_ctx_t* ctx,
    tiledb_buffer_t* buffer,
    tiledb_datatype_t datatype) TILEDB_NOEXCEPT;

/**
 * Gets the datatype from the given buffer.
 *
 * **Example:**
 *
 * @code{.c}
 * tiledb_datatype_t type;
 * tiledb_buffer_get_type(ctx, buffer, &type);
 * @endcode
 *
 * @param ctx TileDB context
 * @param buffer TileDB buffer instance
 * @param datatype Set to the datatype of the buffer.
 * @return `TILEDB_OK` for success or `TILEDB_ERR` for error.
 */
TILEDB_EXPORT capi_return_t tiledb_buffer_get_type(
    tiledb_ctx_t* ctx,
    const tiledb_buffer_t* buffer,
    tiledb_datatype_t* datatype) TILEDB_NOEXCEPT;

/**
 * Gets a pointer to the current allocation and the current number of bytes in
 * the specified buffer object.
 *
 * @note For string buffers allocated by TileDB, the number of bytes includes
 * the terminating NULL byte.
 *
 * **Example:**
 *
 * @code{.c}
 * tiledb_buffer_t* buffer;
 * tiledb_buffer_alloc(ctx, &buffer);
 * void* data;
 * uint64_t num_bytes;
 * tiledb_buffer_get_data(ctx, buffer, &data, num_bytes);
 * // data == NULL and num_bytes == 0 because the buffer is currently empty.
 * tiledb_buffer_free(&buffer);
 * @endcode
 *
 * @param ctx TileDB context
 * @param buffer TileDB buffer instance
 * @param data The pointer to the data to be retrieved.
 * @param num_bytes Set to the number of bytes in the buffer.
 * @return `TILEDB_OK` for success or `TILEDB_ERR` for error.
 */
TILEDB_EXPORT capi_return_t tiledb_buffer_get_data(
    tiledb_ctx_t* ctx,
    const tiledb_buffer_t* buffer,
    void** data,
    uint64_t* num_bytes) TILEDB_NOEXCEPT;

/**
 * Sets (wraps) a pre-allocated region of memory with the given buffer object.
 * This does not perform a copy.
 *
 * @note The TileDB buffer object does not take ownership of the allocation
 * set with this function. That means the call to `tiledb_buffer_free` will not
 * free a user allocation set via `tiledb_buffer_set_buffer`.
 *
 * **Example:**
 *
 * @code{.c}
 * tiledb_buffer_t* buffer;
 * tiledb_buffer_alloc(ctx, &buffer);
 *
 * void* my_data = malloc(100);
 * tiledb_buffer_set_data(ctx, buffer, my_data, 100);
 *
 * void* data;
 * uint64_t num_bytes;
 * tiledb_buffer_get_data(ctx, buffer, &data, num_bytes);
 * assert(data == my_data);
 * assert(num_bytes == 100);
 *
 * tiledb_buffer_free(&buffer);
 * free(my_data);
 * @endcode
 *
 * @param ctx TileDB context
 * @param buffer TileDB buffer instance
 * @param data Pre-allocated region of memory to wrap with this buffer.
 * @param size Size (in bytes) of the region pointed to by data.
 * @return `TILEDB_OK` for success or `TILEDB_ERR` for error.
 */
TILEDB_EXPORT capi_return_t tiledb_buffer_set_data(
    tiledb_ctx_t* ctx, tiledb_buffer_t* buffer, void* data, uint64_t size);

#ifdef __cplusplus
}
#endif

#endif  // TILEDB_CAPI_BUFFER_API_EXTERNAL_H


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Führ. Pilzk. (Zwickau) 92 (1871)

#### Original name
Agaricus multiformis Schaeff., 1774

### Remarks
null


text:
using System;
using System.Collections.Generic;

// ReSharper disable once CheckNamespace
namespace NullDesk.Extensions.Mailer.Core
{
    /// <summary>
    ///     Factory class for obtaining mailer instances.
    ///     Factory class for obtaining mailer instances.
    /// </summary>
    public interface IMailerFactory
    {
        /// <summary>
        ///     Gets a collection of registered mailer functions.
        /// </summary>
        /// <value>The mailers.</value>
        List<Func<IMailer>> MailerRegistrations { get; }

        /// <summary>
        /// Gets an instance of the first registered standard mailer.
        /// </summary>
        /// <returns>IMailer.</returns>
        IMailer GetMailer();

        /// <summary>
        ///     Registers a function that can be use to create a configured mailer instance.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="mailerFunc">The mailer function.</param>
        void Register<T>(Func<T> mailerFunc) where T : class, IMailer;

        /// <summary>
        /// Gets an instance of a registered mailer for the specified type.
        /// </summary>
        /// <typeparam name="T">The type of mailer instance you wish to create</typeparam>
        /// <returns>IMailer.</returns>
        /// <remarks>If more than one function for the mailer type exists, will use the first matching function.</remarks>
        IMailer GetMailer<T>() where T : class, IMailer;
    }
}


text:
<?php

namespace Phlexible\Bundle\MessageBundle\RoleProvider;

use Phlexible\Bundle\GuiBundle\Security\RoleProvider\RoleProvider;

/**
 * Message role provider
 *
 * @author Stephan Wentz <sw@brainbits.net>
 */
class MessageRoleProvider extends RoleProvider
{
    /**
     * {@inheritdoc}
     */
    public function provideRoles()
    {
        return [
            'ROLE_MESSAGES',
            'ROLE_MESSAGE_FILTERS',
            'ROLE_MESSAGE_SUBSCRIPTIONS',
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function exposeRoles()
    {
        return $this->provideRoles();
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta name="description" content=""/>
    <meta name="author" content=""/>

    <title th:text="#{application.title}"/>

    <link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css" rel="stylesheet"/>

    <link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap-responsive.css" rel="stylesheet"/>

    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://getbootstrap.com/2.3.2/assets/ico/apple-touch-icon-144-precomposed.png"/>
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="http://getbootstrap.com/2.3.2/assets/ico/apple-touch-icon-114-precomposed.png"/>
      <link rel="apple-touch-icon-precomposed" sizes="72x72" href="http://getbootstrap.com/2.3.2/assets/ico/apple-touch-icon-72-precomposed.png"/>
                    <link rel="apple-touch-icon-precomposed" href="http://getbootstrap.com/2.3.2/assets/ico/apple-touch-icon-57-precomposed.png"/>
                                   <link rel="shortcut icon" href="http://getbootstrap.com/2.3.2/assets/ico/favicon.png"/>

          <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">

          </button>

            <form class="navbar-form pull-right">
              <input class="span2" type="text" placeholder="Email"/>
              <input class="span2" type="password" placeholder="Password"/>
              <button type="submit" class="btn">Sign in</button>
            </form>

				/

				/

			<form id="entity" name="entity" enctype="multipart/form-data" class="form-horizontal border-example" th:action="@{ ${'createForm' == command_method} ? ${model_information.getTopLevelMapping()}+'/new'+${command_extension} : ${model_information.getTopLevelMapping()}+'/'+${command_id_path}+'/edit'+${command_extension}  }" th:object="${model_entity}" method="post"  >

				<input type="hidden" name="_method" th:value="${'updateForm' == command_method} ? 'put' : 'post' "/>

						<input type="text" th:field="*{__${attr['name']}__}" th:readonly="${attr['id'] and ('createForm' != command_method) } ? 'readonly'"/>

				    	<button class="btn"  type="submit" th:text="#{application.save}"/>
				    	<button class="btn"  type="reset" th:text="#{application.reset}"/>

			</form>

© Company 2013