text:
<?php

class Avada_Layout {

	public $sidebars = array();

	/**
	 * The class constructor
	 */
	public function __construct() {
		add_action( 'wp', array( $this, 'add_sidebar' ), 20 );
		// add_action( 'wp', array( $this, 'get_content_width' ), 20 ); WIP ITEM FOR #746
	}

	/**
	 * Add sidebar(s) to the pages
	 *
	 * @return void
	 */
	public function add_sidebar() {
		// Get the sidebars and assign to public variable
		$this->sidebars = $this->get_sidebar_settings( $this->sidebar_options() );

		// Set styling to content and sidebar divs
		$this->layout_structure_styling( $this->sidebars );

		// Append sidebar to after content div
		if ( Avada()->template->has_sidebar() && ! Avada()->template->double_sidebars() ) {
			add_action( 'fusion_after_content', array( $this, 'append_sidebar_single' ) );
		} elseif ( Avada()->template->double_sidebars() ) {
			add_action( 'fusion_after_content', array( $this, 'append_sidebar_double' ) );
		} elseif ( ! Avada()->template->has_sidebar() && ( is_page_template( 'side-navigation.php') || is_singular( 'tribe_events' ) ) ) {
			add_action( 'fusion_after_content', array( $this, 'append_sidebar_single' ) );
		}

	}

	/**
	 * Get sidebar settings based on the page type
	 *
	 * @return array
	 */
	public function sidebar_options() {
		if ( is_home() ) {
			$sidebars = array(
				'global'    => '1',
				'sidebar_1' => Avada()->settings->get( 'blog_archive_sidebar' ),
				'sidebar_2' => Avada()->settings->get( 'blog_archive_sidebar_2' ),
				'position'  => Avada()->settings->get( 'blog_sidebar_position' ),
			);
		} elseif ( is_bbpress() ) {
			$sidebars = array(
				'global'    => Avada()->settings->get( 'bbpress_global_sidebar' ),
				'sidebar_1' => Avada()->settings->get( 'ppbress_sidebar' ),
				'sidebar_2' => Avada()->settings->get( 'ppbress_sidebar_2' ),
				'position'  => Avada()->settings->get( 'bbpress_sidebar_position' ),
			);

			if ( bbp_is_forum_archive() || bbp_is_topic_archive() || bbp_is_user_home() || bbp_is_search() ) {
				$sidebars = array(
					'global'    => '1',
					'sidebar_1' => Avada()->settings->get( 'ppbress_sidebar' ),
					'sidebar_2' => Avada()->settings->get( 'ppbress_sidebar_2' ),
					'position'  => Avada()->settings->get( 'bbpress_sidebar_position' ),
				);
			}
		} elseif ( is_buddypress() ) {
			$sidebars = array(
				'global'    => Avada()->settings->get( 'bbpress_global_sidebar' ),
				'sidebar_1' => Avada()->settings->get( 'ppbress_sidebar' ),
				'sidebar_2' => Avada()->settings->get( 'ppbress_sidebar_2' ),
				'position'  => Avada()->settings->get( 'bbpress_sidebar_position' ),
			);
		} elseif ( class_exists( 'WooCommerce' ) && ( is_product() || is_shop() ) ) {
			$sidebars = array(
				'global'    => Avada()->settings->get( 'woo_global_sidebar' ),
				'sidebar_1' => Avada()->settings->get( 'woo_sidebar' ),
				'sidebar_2' => Avada()->settings->get( 'woo_sidebar_2' ),
				'position'  => Avada()->settings->get( 'woo_sidebar_position' ),
			);
		} elseif ( class_exists( 'WooCommerce' ) && ( is_product_category() || is_product_tag() || is_tax( 'product_brand' ) || is_tax( 'images_collections' ) ) ) {
			$sidebars = array(
				'global'    => '1',
				'sidebar_1' => Avada()->settings->get( 'woocommerce_archive_sidebar' ),
				'sidebar_2' => Avada()->settings->get( 'woocommerce_archive_sidebar_2' ),
				'position'  => Avada()->settings->get( 'woo_sidebar_position' ),
			);
		} elseif ( is_page() ) {
			$sidebars = array(
				'global'    => Avada()->settings->get( 'pages_global_sidebar' ),
				'sidebar_1' => Avada()->settings->get( 'pages_sidebar' ),
				'sidebar_2' => Avada()->settings->get( 'pages_sidebar_2' ),
				'position'  => Avada()->settings->get( 'default_sidebar_pos' ),
			);
		} elseif ( is_single() ) {
			$sidebars = array(
				'global'    => Avada()->settings->get( 'posts_global_sidebar' ),
				'sidebar_1' => Avada()->settings->get( 'posts_sidebar' ),
				'sidebar_2' => Avada()->settings->get( 'posts_sidebar_2' ),
				'position'  => Avada()->settings->get( 'blog_sidebar_position' ),
			);

			if ( is_singular( 'avada_portfolio' ) ) {
				$sidebars = array(
					'global'    => Avada()->settings->get( 'portfolio_global_sidebar' ),
					'sidebar_1' => Avada()->settings->get( 'portfolio_sidebar' ),
					'sidebar_2' => Avada()->settings->get( 'portfolio_sidebar_2' ),
					'position'  => Avada()->settings->get( 'portfolio_sidebar_position' ),
				);
			} else if ( is_singular( 'tribe_events' ) || is_singular( 'tribe_organizer' ) || is_singular( 'tribe_venue' ) ) {
				$sidebars = array(
					'global'    => Avada()->settings->get( 'ec_global_sidebar' ),
					'sidebar_1' => Avada()->settings->get( 'ec_sidebar' ),
					'sidebar_2' => Avada()->settings->get( 'ec_sidebar_2' ),
					'position'  => Avada()->settings->get( 'ec_sidebar_pos' ),
				);
			}

			if ( is_singular( 'tribe_organizer' ) || is_singular( 'tribe_venue' ) ) {
				$sidebars['global'] = 1;
			}
		} elseif ( is_archive() ) {
			$sidebars = array(
				'global'    => '1',
				'sidebar_1' => Avada()->settings->get( 'blog_archive_sidebar' ),
				'sidebar_2' => Avada()->settings->get( 'blog_archive_sidebar_2' ),
				'position'  => Avada()->settings->get( 'blog_sidebar_position' ),
			);

			if ( is_post_type_archive( 'avada_portfolio' ) || is_tax( 'portfolio_category' ) || is_tax( 'portfolio_skills' ) || is_tax( 'portfolio_tags' ) ) {
				$sidebars = array(
					'global'    => '1',
					'sidebar_1' => Avada()->settings->get( 'portfolio_archive_sidebar' ),
					'sidebar_2' => Avada()->settings->get( 'portfolio_archive_sidebar_2' ),
					'position'  => Avada()->settings->get( 'portfolio_sidebar_position' ),
				);
			}
		} elseif ( is_search() ) {
			$sidebars = array(
				'global'    => '1',
				'sidebar_1' => Avada()->settings->get( 'search_sidebar' ),
				'sidebar_2' => Avada()->settings->get( 'search_sidebar_2' ),
				'position'  => Avada()->settings->get( 'search_sidebar_position' ),
			);
		} else {
			$sidebars = array(
				'global'    => Avada()->settings->get( 'pages_global_sidebar' ),
				'sidebar_1' => Avada()->settings->get( 'pages_sidebar' ),
				'sidebar_2' => Avada()->settings->get( 'pages_sidebar_2' ),
				'position'  => Avada()->settings->get( 'default_sidebar_pos' ),
			);
		}

		if ( is_events_archive() ) {
			$sidebars = array(
				'global'    => '1',
				'sidebar_1' => Avada()->settings->get( 'ec_sidebar' ),
				'sidebar_2' => Avada()->settings->get( 'ec_sidebar_2' ),
				'position'  => Avada()->settings->get( 'ec_sidebar_pos' ),
			);
		}

		// Remove sidebars from the certain woocommerce pages
		if ( class_exists( 'WooCommerce' ) ) {
			if ( is_cart() || is_checkout() || is_account_page() || ( get_option( 'woocommerce_thanks_page_id' ) && is_page( get_option( 'woocommerce_thanks_page_id' ) ) ) ) {
				$sidebars = array();
			}
		}

		return $sidebars;
	}

	/**
	 * Get the sidebars
	 *
	 * @param array $sidebar_options
	 *
	 * @return array
	 */
	public function get_sidebar_settings( $sidebar_options = array() ) {
		// Post options
		$sidebar_1                    = get_post_meta( Avada::c_pageID(), 'sbg_selected_sidebar_replacement', true );
		$sidebar_2                    = get_post_meta( Avada::c_pageID(), 'sbg_selected_sidebar_2_replacement', true );
		$sidebar_position_post_option = strtolower( get_post_meta( Avada::c_pageID(), 'pyre_sidebar_position', true ) );
		$sidebar_position_metadata    = metadata_exists( 'post', Avada::c_pageID(), 'pyre_sidebar_position' );

		if ( is_array( $sidebar_1 ) && '0' === $sidebar_1[0] ) {
			$sidebar_1 = array( 'Blog Sidebar' );
		}

		if ( is_array( $sidebar_2 ) && '0' === $sidebar_2[0] ) {
			$sidebar_2 = array( 'Blog Sidebar' );
		}

		// Theme options
		$sidebar_position_theme_option = array_key_exists( 'position', $sidebar_options ) ? strtolower( $sidebar_options['position'] ) : '';

		// Set default sidebar position
		$sidebar_position = $sidebar_position_post_option;

		// Get sidebars and position from theme options if it's being forced globally
		if ( array_key_exists( 'global', $sidebar_options ) && $sidebar_options['global'] ) {
			$sidebar_1 = array( ( 'None' != $sidebar_options['sidebar_1'] ) ? $sidebar_options['sidebar_1'] : '' );
			$sidebar_2 = array( ( 'None' != $sidebar_options['sidebar_2'] ) ? $sidebar_options['sidebar_2'] : '' );

			$sidebar_position = $sidebar_position_theme_option;
		}

		// If sidebar position is default OR no entry in database exists
		if ( 'default' == $sidebar_position || ! $sidebar_position_metadata ) {
			$sidebar_position = $sidebar_position_theme_option;
		}

		// Reverse sidebar position if double sidebars are used and position is right
		if ( Avada()->template->double_sidebars() && 'right' == $sidebar_position ) {
			$sidebar_1_placeholder = $sidebar_1;
			$sidebar_2_placeholder = $sidebar_2;

			// Reverse the sidebars
			$sidebar_1 = $sidebar_2_placeholder;
			$sidebar_2 = $sidebar_1_placeholder;
		}

		$return = array( 'position' => $sidebar_position );

		if ( $sidebar_1 ) {
			$return['sidebar_1'] = $sidebar_1[0];
		}

		if ( $sidebar_2 ) {
			$return['sidebar_2'] = $sidebar_2[0];
		}

		return $return;
	}

	/**
	 * Apply inline styling and classes to the structure
	 *
	 * @param array $sidebars
	 *
	 * @return void
	 */
	public function layout_structure_styling( $sidebars ) {

		// Add sidebar class
		add_filter( 'fusion_sidebar_1_class', array( $this, 'sidebar_class' ) );
		add_filter( 'fusion_sidebar_2_class', array( $this, 'sidebar_class' ) );

		// Check for sidebar location and apply styling to the content or sidebar div
		if ( ! Avada()->template->has_sidebar() && ! ( is_page_template( 'side-navigation.php') || is_singular( 'tribe_events' ) ) ) {
			add_filter( 'fusion_content_style', array( $this, 'full_width_content_style' ) );

			if ( is_archive() || is_home() ) {
				add_filter( 'fusion_content_class', array( $this, 'full_width_content_class' ) );
			}
		} elseif ( 'left' == $sidebars['position'] ) {
			add_filter( 'fusion_content_style', array( $this, 'float_right_style' ) );
			add_filter( 'fusion_sidebar_1_style', array( $this, 'float_left_style' ) );
			add_filter( 'fusion_sidebar_1_class', array( $this, 'side_nav_left_class' ) );
		} elseif ( 'right' == $sidebars['position'] ) {
			add_filter( 'fusion_content_style', array( $this, 'float_left_style' ) );
			add_filter( 'fusion_sidebar_1_style', array( $this, 'float_right_style' ) );
			add_filter( 'fusion_sidebar_1_class', array( $this, 'side_nav_right_class' ) );
		}

		// Page has a single sidebar
		// if ( Avada()->template->has_sidebar() && ! Avada()->template->double_sidebars() ) {}

		// Page has double sidebars
		if ( Avada()->template->double_sidebars() ) {
			add_filter( 'fusion_content_style', array( $this, 'float_left_style' ) );
			add_filter( 'fusion_sidebar_1_style', array( $this, 'float_left_style' ) );
			add_filter( 'fusion_sidebar_2_style', array( $this, 'float_left_style' ) );

			if ( 'right' == $sidebars['position'] ) {
				add_filter( 'fusion_sidebar_2_class', array( $this, 'side_nav_right_class' ) );
			}
		}

	}

	/**
	 * Append single sidebar to a page
	 *
	 * @return void
	 */
	public function append_sidebar_single() {
		get_template_part( 'templates/sidebar', '1' );
	}

	/**
	 * Append double sidebar to a page
	 *
	 * @return void
	 */
	public function append_sidebar_double() {
		get_template_part( 'templates/sidebar', '1' );
		get_template_part( 'templates/sidebar', '2' );
	}

	/**
	 * Join the elements
	 *
	 * @param string $filter_id
	 * @param string $sanitize
	 * @param string $join_separator
	 *
	 * @return string
	 */
	public function join( $filter_id = null, $sanitize = 'esc_attr', $join_separator = ' ' ) {

		// Get the elements using a filter
		$elements = apply_filters( 'fusion_' . $filter_id, array() );

		// Make sure each element is properly sanitized
		$elements = array_map( $sanitize, $elements );

		// Make sure there are no duplicate items
		$elements = array_unique( $elements );

		// Combine the elements of the array and return the combined string
		return join( $join_separator, $elements );

	}

	/**
	 * Filter to add inline styling
	 *
	 * @return void
	 */
	public function add_style( $filter ) {
		echo 'style="' . $this->join( $filter ) . '"';
	}

	/**
	 * Filter to add class
	 *
	 * @return void
	 */
	public function add_class( $filter ) {
		echo 'class="' . $this->join( $filter ) . '"';
	}

	/**
	 * Full width page inline styling
	 *
	 * @return array
	 */
	public function full_width_content_style( $styles ) {
		$styles[] = 'width: 100%;';
		return $styles;
	}

	/**
	 * Full width class
	 *
	 * @return array
	 */
	public function full_width_content_class( $classes ) {
		$classes[] = 'full-width';
		return $classes;
	}

	/**
	 * Float right styling
	 *
	 * @return array
	 */
	public function float_right_style( $styles ) {
		$styles[] = 'float: right;';
		return $styles;
	}

	/**
	 * Float left styling
	 *
	 * @return array
	 */
	public function float_left_style( $styles ) {
		$styles[] = 'float: left;';
		return $styles;
	}

	/**
	 * Add sidebar class to the sidebars
	 *
	 * @return array
	 */
	public function sidebar_class( $classes ) {
		$classes[] = 'sidebar fusion-widget-area fusion-content-widget-area';
		return $classes;
	}

	/**
	 * Add side nav right class when sidebar position is right
	 *
	 * @return array
	 */
	public function side_nav_right_class( $classes ) {
		if ( is_page_template( 'side-navigation.php' ) ) {
			$classes[] = 'side-nav-right';
		}
		return $classes;
	}

	/**
	 * Add side nav left class when sidebar position is left
	 *
	 * @return array
	 */
	public function side_nav_left_class( $classes ) {
		if ( is_page_template( 'side-navigation.php' ) ) {
			$classes[] = 'side-nav-left';
		}
		return $classes;
	}

	/**
	 * Checks is the current page is a 100% width page.
	 *
	 * @param integer $page_id     A custom page ID.
	 * @return bool
	 */
	public function is_hundred_percent_template( $page_id = false ) {
		if ( ! $page_id ) {
			$page_id = $c_pageID = Avada()->c_pageID();
		}

		$page_template = '';

		if ( function_exists( 'is_woocommerce' ) && is_woocommerce() ) {
			$custom_fields = get_post_custom_values( '_wp_page_template', $c_pageID );
			$page_template = ( is_array( $custom_fields ) && ! empty( $custom_fields ) ) ? $custom_fields[0] : '';
		}

		if ( 'tribe_events' == get_post_type( $c_pageID ) && '100-width.php' == tribe_get_option( 'tribeEventsTemplate', 'default' ) ) {
			$page_template = '100-width.php';
		}

		if (
			'100%' == Avada()->settings->get( 'site_width' ) ||
			is_page_template( '100-width.php' ) ||
			is_page_template( 'blank.php' ) ||
			'100-width.php' == $page_template ||
			( ( '1' == fusion_get_option( 'portfolio_width_100', 'portfolio_width_100', $c_pageID ) || 'yes' == fusion_get_option( 'portfolio_width_100', 'portfolio_width_100', $c_pageID ) ) && is_singular( 'avada_portfolio' ) ) ||
			( ( '1' == fusion_get_option( 'blog_width_100', 'portfolio_width_100', $c_pageID ) || 'yes' == fusion_get_option( 'blog_width_100', 'portfolio_width_100', $c_pageID ) ) && is_singular( 'post' ) ) ||
			( 'yes' == fusion_get_page_option( 'portfolio_width_100', $c_pageID ) && ! is_singular( array( 'post', 'avada_portfolio' ) ) ) ||
			( avada_is_portfolio_template() && 'yes' == get_post_meta( $c_pageID, 'pyre_portfolio_width_100', true ) )
		) {
			return true;
		} else {
			return false;
		}
	}

	public function is_current_wrapper_hundred_percent() {
		if ( $this->is_hundred_percent_template() ) {
			global $fusion_fwc_type;

			if ( ! isset( $fusion_fwc_type ) ||
				 ( isset( $fusion_fwc_type ) && ( '' == $fusion_fwc_type || 'fullwidth' == $fusion_fwc_type ) )
			) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}

	}

	/**
	 * Get column width of the current page.
	 *
	 * @param integer|string $site_width     A custom site width.
	 * @return integer
	 */
	public function get_content_width( $site_width = 0 ) {
		/**
		 * The content width
		 */
		$options = get_option( Avada::get_option_name() );
		$page_padding = 0;

		if ( ! $site_width ) {
			$site_width = ( isset( $options['site_width'] ) ) ? $options['site_width'] : '1100px';

			if ( $this->is_current_wrapper_hundred_percent() ) {

				$site_width = '100%';

				// Get 100% Width Left/Right Padding
				$page_padding = ( isset( $options['hundredp_padding'] ) ) ? $options['hundredp_padding'] : '0';

				// 100% Width Left/Right Padding is using %
				if ( false !== strpos( $page_padding, '%' ) ) {
					$page_padding = Avada_Helper::percent_to_pixels( $page_padding );
				}
				// 100% Width Left/Right Padding is using ems
				elseif ( false !== strpos( $page_padding, 'em' ) ) {
					$page_padding = Avada_Helper::ems_to_pixels( $page_padding );
				}

			}

		}

		if ( intval( $site_width ) ) {
			// Site width is using %
			if ( false !== strpos( $site_width, '%' ) ) {
				$site_width = Avada_Helper::percent_to_pixels( $site_width );

				// Subtract side header width from remaining content width
				$side_header_width = ( 'Top' == Avada()->settings->get( 'header_position' ) ) ? 0 : intval( Avada()->settings->get( 'side_header_width' ) );
				$site_width -= $side_header_width;
			}
			// Site width is using ems
			elseif ( false !== strpos( $site_width, 'em' ) ) {
				$site_width = Avada_Helper::ems_to_pixels( $site_width );
			}
		} else {
			// fallback to 1100px
			$site_width = 1100;
		}

		$site_width -= 2 * $page_padding;

		/**
		 * Sidebars width
		 */
		$sidebar_1_width = 0;
		$sidebar_2_width = 0;
		if ( Avada()->template->has_sidebar() && ! Avada()->template->double_sidebars() ) {
			if ( 'tribe_events' == get_post_type() ) {
				$sidebar_1_width = Avada()->settings->get( 'ec_sidebar_width' );
			} else {
				$sidebar_1_width = Avada()->settings->get( 'sidebar_width' );
			}
		} elseif ( Avada()->template->double_sidebars() ) {
			if ( 'tribe_events' == get_post_type() ) {
				$sidebar_1_width = Avada()->settings->get( 'ec_sidebar_2_1_width' );
				$sidebar_2_width = Avada()->settings->get( 'ec_sidebar_2_2_width' );
			} else {
				$sidebar_1_width = Avada()->settings->get( 'sidebar_2_1_width' );
				$sidebar_2_width = Avada()->settings->get( 'sidebar_2_2_width' );
			}
		} elseif ( ! Avada()->template->has_sidebar() && ( is_page_template( 'side-navigation.php') || is_singular( 'tribe_events' ) ) ) {
			if ( 'tribe_events' == get_post_type() ) {
				$sidebar_1_width = Avada()->settings->get( 'ec_sidebar_width' );
			} else {
				$sidebar_1_width = Avada()->settings->get( 'sidebar_width' );
			}
		}

		if ( $sidebar_1_width ) {
			if ( false !== strpos( $sidebar_1_width, '%' ) ) {
				$sidebar_1_width = Avada_Helper::percent_to_pixels( $sidebar_1_width, $site_width );
			} elseif ( false !== strpos( $sidebar_1_width, 'em' ) ) {
				$sidebar_1_width = Avada_Helper::ems_to_pixels( $sidebar_1_width );
			} else {
				$sidebar_1_width = intval( $sidebar_1_width );
			}
		}

		if ( $sidebar_2_width ) {
			if ( false !== strpos( $sidebar_2_width, '%' ) ) {
				$sidebar_2_width = Avada_Helper::percent_to_pixels( $sidebar_2_width, $site_width );
			} elseif ( false !== strpos( $sidebar_1_width, 'em' ) ) {
				$sidebar_2_width = Avada_Helper::ems_to_pixels( $sidebar_2_width );
			} else {
				$sidebar_2_width = intval( $sidebar_2_width );
			}
		}

		$columns = 1;
		if ( $site_width && $sidebar_1_width && $sidebar_2_width ) {
			$columns = 3;
		} elseif ( $site_width && $sidebar_1_width ) {
			$columns = 2;
		}
		$gutter = ( 1 < $columns ) ? 80 : 0;
		$extra_gutter = $gutter;

		$sidebar_1_width = (int) $sidebar_1_width;
		$sidebar_2_width = (int) $sidebar_2_width;

		$content_width = $site_width - $sidebar_1_width - $sidebar_2_width - $extra_gutter;

		return $content_width;
	}

	public function get_relative_width( $columns = 1, $gutter = 0 ) {
		$columns = intval( $columns );
		$gutter  = intval( $gutter );
		// Get the total content width
		$total_width = $this->get_content_width();
		if ( 1 >= $columns ) {
			return $total_width;
		}
		// Get the total size of our gutters
		$total_gutter = ( $columns - 1 ) * $gutter;
		// Get the useful width
		$useful_width = $total_width - $total_gutter;
		if ( 0 == intval( $useful_width ) ) {
			return $total_width;
		}
		// return the width per column
		return absint( $useful_width / $columns );
	}

}

// Omit closing PHP tag to avoid "Headers already sent" issues.

redpajama_set_name: RedPajamaGithub


text:
package galileo.util;

import java.io.File;

/**
 * Utility class for working with file names.
 *
 * @author malensek
 */
public class FileNames {

    public static Pair<String, String> splitExtension(File file) {
        String name = file.getName();
        int lastDot = name.lastIndexOf('.');

        if (lastDot == -1) {
            return new Pair<>(name, "");
        }

        String pre = name.substring(0, lastDot);
        String ext = name.substring(lastDot + 1);

        return new Pair<>(pre, ext);
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<TITLE
>Indexes on Expressions</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REV="MADE"
HREF="mailto:pgsql-docs@postgresql.org"><LINK
REL="HOME"
TITLE="PostgreSQL 9.2.8 Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="Indexes"
HREF="indexes.html"><LINK
REL="PREVIOUS"
TITLE="Unique Indexes"
HREF="indexes-unique.html"><LINK
REL="NEXT"
TITLE="Partial Indexes"
HREF="indexes-partial.html"><LINK
REL="STYLESHEET"
TYPE="text/css"
HREF="stylesheet.css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=ISO-8859-1"><META
NAME="creation"
CONTENT="2014-03-17T19:46:29">

PostgreSQL 9.2.8 Documentation

Prev	Up	Chapter 11. Indexes	Next

11.7. Indexes on Expressions

   An index column need not be just a column of the underlying table,
   but can be a function or scalar expression computed from one or
   more columns of the table.  This feature is useful to obtain fast
   access to tables based on the results of computations.

   For example, a common way to do case-insensitive comparisons is to
   use the lower function:

SELECT * FROM test1 WHERE lower(col1) = 'value';

   This query can use an index if one has been
   defined on the result of the <TT
CLASS="LITERAL"
>lower(col1)</TT
>
   function:

CREATE INDEX test1_lower_col1_idx ON test1 (lower(col1));

   If we were to declare this index <TT
CLASS="LITERAL"
>UNIQUE</TT
>, it would prevent
   creation of rows whose <TT
CLASS="LITERAL"
>col1</TT
> values differ only in case,
   as well as rows whose <TT
CLASS="LITERAL"
>col1</TT
> values are actually identical.
   Thus, indexes on expressions can be used to enforce constraints that
   are not definable as simple unique constraints.

   As another example, if one often does queries like:

SELECT * FROM people WHERE (first_name || ' ' || last_name) = 'John Smith';

   then it might be worth creating an index like this:

CREATE INDEX people_names ON people ((first_name || ' ' || last_name));

   The syntax of the <TT
CLASS="COMMAND"
>CREATE INDEX</TT
> command normally requires
   writing parentheses around index expressions, as shown in the second
   example.  The parentheses can be omitted when the expression is just
   a function call, as in the first example.

   Index expressions are relatively expensive to maintain, because the
   derived expression(s) must be computed for each row upon insertion
   and whenever it is updated.  However, the index expressions are
   not recomputed during an indexed search, since they are
   already stored in the index.  In both examples above, the system
   sees the query as just <TT
CLASS="LITERAL"
>WHERE indexedcolumn = 'constant'</TT
>
   and so the speed of the search is equivalent to any other simple index
   query.  Thus, indexes on expressions are useful when retrieval speed
   is more important than insertion and update speed.

Prev	Home	Next

Unique Indexes	Up	Partial Indexes


text:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Spotify API Example</title>

        <link rel="stylesheet" href="../../css/style.css">
        <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/styles/default.min.css">

Spotify API Example

Accessing the Spotify Web API for retrieving public information is actually extremely simple. For a basic level of access (that may be rate limited) you do not even need to supply an API key. The endpoints you can use are listed in the API documentation here. For example, to search for artists with a particular name and print the results to the console:

// Function that will process the response from the API
var processResponse = function() {
    var data = JSON.parse(this.response);
    // Replace this code with code that
    // does something with the response
    console.log(data);
}

// Function to ensure parameters used in request are encoded correctly
var encodeParameters = function(params) {
    // join all key value pairs and store in an array
    var strArray = [];
    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var paramString = encodeURIComponent(key) + "=" + encodeURIComponent(params[key]);
            strArray.push(paramString);
        }
    }
    // join everything in the array together
    return strArray.join("&");
}

// the parameters for the API request
var parameters = {
    q: "Public Service Broadcasting",
    type: "artist"
}

// construct the URL to call
var base_url = 'https://api.spotify.com/v1/search';
var query_url = base_url + '?' + encodeParameters(parameters);
console.log(query_url);

// create an XMLHttpRequest object, add a listener to
// tell it what to do if successful, tell it which URL
// to GET, and then make ('send') the call
var xhttp = new XMLHttpRequest();
xhttp.addEventListener('load', processResponse);
xhttp.open('GET', query_url);
xhttp.send();

You can retrieve lots more information about an artist. For instance, once we know the Spotify ID (by extracting it from the search response above perhaps), we can retrieve all the artist's albums that are available in Great Britain:

                        // Function that will process the response from the API
                        var processResponse = function() {
                            var data = JSON.parse(this.response);
                            // Replace this code with code that
                            // does something with the response
                            console.log(data);
                        }

                        // Function to ensure parameters used in request are encoded correctly
                        var encodeParameters = function(params) {
                            // join all key value pairs and store in an array
                            var strArray = [];
                            for(var key in params) {
                                if(params.hasOwnProperty(key)) {
                                    var paramString = encodeURIComponent(key) + "=" + encodeURIComponent(params[key]);
                                    strArray.push(paramString);
                                }
                            }
                            // join everything in the array together
                            return strArray.join("&");
                        }

                        // the parameters for the API request
                        var parameters = {
                            market: "GB",
                        }
                        var artist_id = "6VsiDFMZJlJ053P1uO4A6h";

                        // construct the URL to call
                        var base_url = 'https://api.spotify.com/v1/artists/' + artist_id + '/albums';
                        var query_url = base_url + '?' + encodeParameters(parameters);
                        console.log(query_url);

                        // create an XMLHttpRequest object, add a listener to
                        // tell it what to do if successful, tell it which URL
                        // to GET, and then make ('send') the call
                        var xhttp = new XMLHttpRequest();
                        xhttp.addEventListener('load', processResponse);
                        xhttp.open('GET', query_url);
                        xhttp.send();

IMPORTANT NOTE! This is NOT ENOUGH to pass Coursework 2 for CMT112 - you will need to add some extra functionality and presentation of data. I will not be impressed if your submission consists only of the code presented here!

Back to home


text:
<html title="sankey">

<style>
.node rect {
  cursor: move;
  fill-opacity: .9;
  shape-rendering: crispEdges;
}
.node text {
  pointer-events: none;
  text-shadow: 0 1px 0 #fff;
}
.link {
  fill: none;
  stroke: #000;
  stroke-opacity: .2;
}
.link:hover {
  stroke-opacity: .5;
}
</style>
<title>opengov2001-48-all.Component</title>
<body>
<p id="chart">
<script type="text/javascript" src="http://d3js.org/d3.v2.min.js"></script>
<script type="text/javascript" src="https://rawgithub.com/d3/d3-plugins/master/sankey/sankey.js"></script>
<script>
var units = "Messages";

var margin = {top: 10, right: 10, bottom: 10, left: 10},
    width = 800 - margin.left - margin.right,
    height = 200 - margin.top - margin.bottom;

var formatNumber = d3.format(",.0f"),    // zero decimal places
    format = function(d) { return formatNumber(d) + " " + units; },
    color = d3.scale.category20();

// append the svg canvas to the page
var svg = d3.select("#chart").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

// Set the sankey diagram properties
var sankey = d3.sankey()
    .nodeWidth(36)
    .nodePadding(40)
    .size([width, height]);

var path = sankey.link();

graph = JSON.parse('{"nodes":[{"name":"expressionFunction"},{"name":"expressionFilter"},{"name":"TemporalJoin_TickerAndContractData"},{"name":"Partitioner"},{"name":"fileOutput"},{"name":"contractSource"},{"name":"tickerSource"}],"links":[{"source":6,"value":1951840,"target":3},{"source":3,"value":1897820,"target":0},{"source":5,"value":681711,"target":2},{"source":1,"value":528345,"target":2},{"source":0,"value":1897820,"target":1},{"source":2,"value":39405,"target":4}]}');

  sankey
      .nodes(graph.nodes)
      .links(graph.links)
      .layout(32);

// add in the links
  var link = svg.append("g").selectAll(".link")
      .data(graph.links)
    .enter().append("path")
      .attr("class", "link")
      .attr("d", path)
      .style("stroke-width", function(d) { return Math.max(1, d.dy); })
      .sort(function(a, b) { return b.dy - a.dy; });

// add the link titles
  link.append("title")
        .text(function(d) {
            return d.source.name + " → " +
                d.target.name + "\n" + format(d.value); });

// add in the nodes
  var node = svg.append("g").selectAll(".node")
      .data(graph.nodes)
    .enter().append("g")
      .attr("class", "node")
      .attr("transform", function(d) {
          return "translate(" + d.x + "," + d.y + ")"; })
    .call(d3.behavior.drag()
      .origin(function(d) { return d; })
      .on("dragstart", function() {
          this.parentNode.appendChild(this); })
      .on("drag", dragmove));

// add the rectangles for the nodes
  node.append("rect")
      .attr("height", function(d) { return d.dy; })
      .attr("width", sankey.nodeWidth())
      .style("fill", function(d) {
          return d.color = color(d.name.replace(/ .*/, "")); })
      .style("stroke", function(d) {
          return d3.rgb(d.color).darker(2); })
    .append("title")
      .text(function(d) {
          return d.name + "\n" + format(d.value); });

// add in the title for the nodes
  node.append("text")
      .attr("x", -6)
      .attr("y", function(d) { return d.dy / 2; })
      .attr("dy", ".35em")
      .attr("text-anchor", "end")
      .attr("transform", null)
      .text(function(d) { return d.name; })
    .filter(function(d) { return d.x < width / 2; })
      .attr("x", 6 + sankey.nodeWidth())
      .attr("text-anchor", "start");

// the function for moving the nodes
  function dragmove(d) {
    d3.select(this).attr("transform",
        "translate(" + (
            d.x = Math.max(0, Math.min(width - d.dx, d3.event.x))
        )
        + "," + (
            d.y = Math.max(0, Math.min(height - d.dy, d3.event.y))
        ) + ")");
    sankey.relayout();
    link.attr("d", path);
  }

</script>
</body>
</html>


text:
import Box from '@mui/joy/Box';
import Slider from '@mui/joy/Slider';
import * as React from 'react';

function valueText(value) {
  return `${value}°C`;
}

export default function RangeSlider() {
  const [value, setValue] = React.useState([20, 37]);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  return (
    <Box sx={{ width: 300 }}>
      <Slider
        getAriaLabel={() => 'Temperature range'}
        value={value}
        onChange={handleChange}
        valueLabelDisplay="auto"
        getAriaValueText={valueText}
      />
    </Box>
  );
}


text:
"""Behave BDD integration for Django"""

__version__ = '1.4.0'


text:
<?php
/**
 * Configuration file for the "yii asset" console command.
 */

// In the console environment, some path aliases may not exist. Please define these:
Yii::setAlias('@webroot', __DIR__ . '/frontend/web');
Yii::setAlias('@web', '/');
Yii::setAlias('@common', __DIR__ . '/common');

return [
    // Adjust command/callback for JavaScript files compressing:
    'jsCompressor' => 'java -jar console/jar/compiler.jar --js {from} --js_output_file {to}',
    // Adjust command/callback for CSS files compressing:
    'cssCompressor' => 'java -jar console/jar/yuicompressor.jar --type css {from} -o {to}',
    // The list of asset bundles to compress:
    'bundles' => [
        'frontend\assets\AppAsset',
        'frontend\assets\TestAsset'
    ],
    // Asset bundle for compression output:
    'targets' => [
        'all' => [
            'class' => 'yii\web\AssetBundle',
            'basePath' => '@webroot/assets',
            'baseUrl' => '@web/assets',
            'js' => 'js/all-{hash}.js',
            'css' => 'css/all-{hash}.css',
        ],
        'base' => [
            'class' => 'yii\web\AssetBundle',
            'basePath' => '@webroot/assets',
            'baseUrl' => '@web/assets',
            'js' => 'js/base-{hash}.js',
            'css' => 'css/base-{hash}.css',
            'depends' => ['frontend\assets\TestAsset'],
        ],
    ],
    // Asset manager configuration:
    'assetManager' => [
        'basePath' => '@webroot/assets',
        'baseUrl' => '@web/assets',
    ],
];


text:
package org.genericsystem.kernel;

import java.lang.invoke.MethodHandles;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.genericsystem.common.AbstractBackEnd;
import org.genericsystem.common.AbstractCache;
import org.genericsystem.common.AbstractWebSocketsServer;
import org.genericsystem.common.EnginesDeploymentConfig;
import org.genericsystem.common.EnginesDeploymentConfig.DefaultPathSingleEngineDeployment;
import org.genericsystem.common.GSBuffer;
import org.genericsystem.common.Protocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.ServerWebSocket;

/**
 * @author Nicolas Feybesse
 *
 */
public class EngineServer extends AbstractBackEnd {

	private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
	private Set<AbstractCache> caches = Collections.newSetFromMap(new ConcurrentHashMap<AbstractCache, Boolean>());

	public static void main(String[] args) {
		new EngineServer(new DefaultPathSingleEngineDeployment("/", null)).start();
	}

	public EngineServer(EnginesDeploymentConfig options) {
		super(options.getHost(), options.getPort());
		logger.info("Load config : \n{}", options.encodePrettily());
		if (options.getEnginePaths().isEmpty()) {
			AbstractServer defaultRoot = buildRoot(null, Collections.emptyList());
			roots.put("/", defaultRoot);
			logger.info("Starts engine with path : / and persistence repository path : null");
		} else
			for (String path : options.getEnginePaths()) {
				AbstractServer root = buildRoot(options.getPersistentDirectoryPath(path), options.getClasses(path));
				roots.put(path, root);
				logger.info("Starts engine with path: {} and persistence repository path: {}.", path, options.getPersistentDirectoryPath(path));
			}
	}

	protected AbstractServer buildRoot(String persistentDirectoryPath, List<Class<?>> userClasses) {
		return new Engine(persistentDirectoryPath, userClasses.stream().toArray(Class[]::new));
	}

	protected Buffer getReplyBuffer(int methodId, int op, AbstractServer root, GSBuffer gsBuffer) {
		GSBuffer replyBuffer = new GSBuffer().appendInt(op);
		// logger.debug("REPLY BUFFER : {} {}", methodId, op);
		switch (methodId) {
			case Protocol.PICK_NEW_TS:
				return replyBuffer.appendLongThrowException(() -> root.pickNewTs());
			case Protocol.GET_DEPENDENCIES:
				return replyBuffer.appendGSVertexArrayThrowException(() -> root.getDependencies(gsBuffer.getLong(), gsBuffer.getLong()));
			case Protocol.GET_VERTEX:
				return replyBuffer.appendGSVertexThrowException(() -> root.getVertex(gsBuffer.getLong()));
			case Protocol.APPLY:
				return replyBuffer.appendLongThrowException(() -> {
					root.apply(gsBuffer.getLong(), gsBuffer.getGSLongArray(), gsBuffer.getGSVertexArray());
					return 0L;
				});
			default:
				return replyBuffer.appendLongThrowException(() -> {
					throw new IllegalStateException("unable to find method:" + methodId + " ");
				});
		}
	}

	private class WebSocketsServer extends AbstractWebSocketsServer {

		public WebSocketsServer(String host, int port) {
			super(host, port);
		}

		@Override
		public Handler<Buffer> getHandler(String path, ServerWebSocket socket) {
			AbstractServer root = (AbstractServer) roots.get(path);
			if (root == null)
				throw new IllegalStateException("Unable to find database :" + path);

			AbstractCache cache = root.newCache();
			return buffer -> {
				GSBuffer gsBuffer = new GSBuffer(buffer);
				int methodId = gsBuffer.getInt();
				int op = gsBuffer.getInt();
				cache.safeExecute(() -> socket.writeBinaryMessage(getReplyBuffer(methodId, op, root, gsBuffer)));
			};
		}

		@Override
		public void addHttpHandler(HttpServer httpServer) {
			// TODO Auto-generated method stub

		}

		@Override
		public Handler<Void> getCloseHandler(ServerWebSocket socket) {
			return (v) -> logger.info("Close socket");
		}
	}

	@Override
	protected WebSocketsServer buildWebSocketsServer(String host, int port) {
		return new WebSocketsServer(host, port);
	}
}


text:
{% load i18n %}
{% load tapeforms %}

	{{ formset.management_form }}

	{% for form in formset %}

					{% if form.instance.pk %}
						{{ form.instance }}
					{% else %}
						{% trans 'New item' %}
					{% endif %}

				{% block delete_button %}
					{% if formset.can_delete %}

							{{ form.DELETE }}

					{% endif %}
				{% endblock %}

				{% block form %}
					{% form form %}
				{% endblock %}

	{% endfor %}


text:
layout: post
date: 2017-08-20
title: "The Couture Gallery Calanthe & Celosia"
category: The Couture Gallery
tags: [The Couture Gallery]
---
### The Couture Gallery Calanthe & Celosia
Just **$379.99**
###

BRANDS	The Couture Gallery

Buy it: [https://www.readybrides.com/en/the-couture-gallery/47041-the-couture-gallery-calanthe-celosia.html](https://www.readybrides.com/en/the-couture-gallery/47041-the-couture-gallery-calanthe-celosia.html)


text:
<?php
namespace Concrete\Core\Area\Layout\Preset\Provider;

use Concrete\Core\Area\Layout\Preset\UserPreset;

class UserProvider implements ProviderInterface
{

    public function getPresets()
    {
        $list = UserPreset::getList();
        $presets = array();
        foreach($list as $preset) {
            $p = $preset->getPresetObject();
            $presets[] = $p;
        }
        return $presets;
    }

    public function getName()
    {
        return t('Saved Presets');
    }

}


text:
package com.khmelenko.lab.varis.log;

import java.util.Stack;

/**
 * Parser for ANSI escape sequences.
 *
 * @see Wikipedia
 **/
class AnsiParser {

    private Stack<TextLeaf> mResult = new Stack<>();
    private FormattingOptions mOptions = FormattingOptions.fromAnsiCodes();

    /**
     * Parses the given log for ANSI escape sequences and builds a list of text chunks, which
     * share the same color and text formatting.
     */
    public static Stack<TextLeaf> parseText(String text) {
        return new AnsiParser().parse(text);
    }

    /**
     * @see #parseText(String)
     */
    private Stack<TextLeaf> parse(String text) {
        // Remove character when followed by a BACKSPACE character
        while (text.contains("\b")) {
            text = text.replaceAll("^\b+|[^\b]\b", "");
        }

        int controlStartPosition;
        int lastControlPosition = 0;
        int controlEndPosition;
        while (true) {
            controlStartPosition = text.indexOf("\033[", lastControlPosition);
            if (controlStartPosition == -1) {
                break;
            }

            String textBeforeEscape = text.substring(lastControlPosition, controlStartPosition);
            emitText(textBeforeEscape);

            if (isResetLineEscape(text, controlStartPosition)) {
                controlEndPosition = text.indexOf('K', controlStartPosition + 2);
                removeCurrentLine();
                mOptions = FormattingOptions.fromAnsiCodes();
            } else {
                controlEndPosition = text.indexOf('m', controlStartPosition + 2);
                if (controlEndPosition == -1) {
                    break;
                }
                String matchingData = text.substring(controlStartPosition + 2, controlEndPosition);
                String[] ansiStates = matchingData.split(";");
                mOptions = FormattingOptions.fromAnsiCodes(ansiStates);
            }

            lastControlPosition = controlEndPosition + 1;
        }

        emitText(text.substring(lastControlPosition));
        if (mResult.isEmpty()) {
            mResult.push(new TextLeaf());
        }
        return mResult;
    }

    private void emitText(String text) {
        if (!text.isEmpty()) {
            mResult.push(new TextLeaf(text, mOptions));
        }
    }

    private void removeCurrentLine() {
        if (mResult.isEmpty()) {
            return;
        }
        TextLeaf textLeaf = mResult.peek();
        int i;
        while (true) {
            i = Math.max(textLeaf.getText().lastIndexOf("\r"), textLeaf.getText().lastIndexOf("\n"));
            if (i != -1) {
                break;
            }
            mResult.pop();
            if (mResult.isEmpty()) {
                break;
            }
            textLeaf = mResult.peek();
        }
        if (textLeaf.getText().length() > i && i > 0) {
            String end = textLeaf.getText().substring(i - 1, i + 1);
            textLeaf.setText(textLeaf.getText().substring(0, i));
            if (end.equals("\r\n") || end.equals("\n\r")) {
                textLeaf.setText(textLeaf.getText().substring(0, i - 1));
            }
        } else {
            textLeaf.setText("");
        }
    }

    private boolean isResetLineEscape(String str, int controlStartPosition) {
        final String substring = str.substring(controlStartPosition);
        return substring.startsWith("\033[0K") || substring.startsWith("\033[K");
    }
}


text:
(function() {
    'use strict';

    angular
        .module('sentryApp')
        .controller('PrivilegeDialogController', PrivilegeDialogController);

    PrivilegeDialogController.$inject = ['$timeout', '$scope', '$stateParams', '$uibModalInstance', 'entity', 'Privilege'];

    function PrivilegeDialogController ($timeout, $scope, $stateParams, $uibModalInstance, entity, Privilege) {
        var vm = this;

        vm.privilege = entity;
        vm.clear = clear;
        vm.save = save;

        $timeout(function (){
            angular.element('.form-group:eq(1)>input').focus();
        });

        function clear () {
            $uibModalInstance.dismiss('cancel');
        }

        function save () {
            vm.isSaving = true;
            if (vm.privilege.id !== null) {
                Privilege.update(vm.privilege, onSaveSuccess, onSaveError);
            } else {
                Privilege.save(vm.privilege, onSaveSuccess, onSaveError);
            }
        }

        function onSaveSuccess (result) {
            $scope.$emit('sentryApp:privilegeUpdate', result);
            $uibModalInstance.close(result);
            vm.isSaving = false;
        }

        function onSaveError () {
            vm.isSaving = false;
        }

    }
})();


text:
package com.twitter.finagle.memcached.protocol.text

import com.twitter.finagle.memcached.protocol.ClientError
import com.twitter.finagle.memcached.util.ChannelBufferUtils._
import com.twitter.io.Charsets
import org.jboss.netty.buffer.{ChannelBuffer, ChannelBufferIndexFinder, ChannelBuffers}
import org.jboss.netty.channel._
import org.jboss.netty.handler.codec.frame.FrameDecoder

object AbstractDecoder {
  private val Delimiter = ChannelBuffers.wrappedBuffer("\r\n".getBytes(Charsets.Utf8))
  private val DelimiterLength = Delimiter.capacity
  private val FindCRLF = new ChannelBufferIndexFinder() {
    def find(buffer: ChannelBuffer, guessedIndex: Int): Boolean = {
      val enoughBytesForDelimeter = guessedIndex + Delimiter.readableBytes
      if (buffer.writerIndex < enoughBytesForDelimeter) return false

      buffer.getByte(guessedIndex) == '\r' &&
        buffer.getByte(guessedIndex + 1) == '\n'
    }
  }
}

abstract class AbstractDecoder extends FrameDecoder {
  import AbstractDecoder._

  override def channelOpen(ctx: ChannelHandlerContext, e: ChannelStateEvent): Unit = {
    start()
    super.channelOpen(ctx, e)
  }

  override def exceptionCaught(ctx: ChannelHandlerContext, e: ExceptionEvent): Unit = {
    start()
    super.exceptionCaught(ctx, e)
  }

  /**
   * @param needsData return the number of bytes needed, or `-1` if no more bytes
   *                  are necessary.
   */
  protected def decodeLine(
    buffer: ChannelBuffer,
    needsData: Seq[ChannelBuffer] => Int
  )(continue: Seq[ChannelBuffer] => Decoding
  ): Decoding = {
    val frameLength = buffer.bytesBefore(FindCRLF)
    if (frameLength < 0) {
      null
    } else {
      val frame = buffer.slice(buffer.readerIndex, frameLength)
      buffer.skipBytes(frameLength + DelimiterLength)

      val tokens = frame.split
      val bytesNeeded = if (tokens.nonEmpty) needsData(tokens) else -1
      if (bytesNeeded == -1) {
        start()
        continue(tokens)
      } else {
        awaitData(tokens, bytesNeeded)
        null
      }
    }
  }

  protected def decodeData(
    bytesNeeded: Int,
    buffer: ChannelBuffer
  )(continue: ChannelBuffer => Decoding
  ): Decoding = {
    if (buffer.readableBytes < (bytesNeeded + DelimiterLength))
      null
    else {
      if (!FindCRLF.find(buffer, bytesNeeded + buffer.readerIndex))
        throw new ClientError("Missing delimiter")

      val data = buffer.slice(buffer.readerIndex, bytesNeeded)
      buffer.skipBytes(bytesNeeded + DelimiterLength)

      start()
      // Shared rather than wrapped to avoid caching data outside the reader/writer mark.
      continue(ChannelBuffers.copiedBuffer(data))
    }
  }

  protected[memcached] def start(): Unit
  protected[memcached] def awaitData(tokens: Seq[ChannelBuffer], bytesNeeded: Int): Unit
}


text:
from Model.DataObject.BaseDataObject import catch_format_error
from Model.DataObject.SendingData.BaseDataSending import BaseDataSending

__author__ = 'RoboCupULaval'

class SendingTactic(BaseDataSending):
    def __init__(self, data_in=None):
        super().__init__(data_in)
        self._format_data()

    @catch_format_error
    def _check_obligatory_data(self):
        assert isinstance(self.data, dict), \
            "data: {} n'est pas un dictionnaire.".format(type(self.data))
        keys = self.data.keys()
        assert 'tactic' in keys, \
            "data['tactic'] n'existe pas."
        assert isinstance(self.data['tactic'], str), \
            "data['tactic']: {} n'est pas le type attendu (str)".format(type(self.data['tactic']))
        assert 'id' in keys, \
            "data['id'] n'existe pas."
        assert isinstance(self.data['id'], int), \
            "data['id']: {} n'a pas le format attendu (int)".format(type(self.data['id']))

    @catch_format_error
    def _check_optional_data(self):
        keys = self.data.keys()
        if 'target' in keys:
            assert self._point_is_valid(self.data['target']), \
                "data['target']: {} n'est pas un point valide (int, int)".format(self.data['target'])
        else:
            self._data['data']['target'] = 0, 0

        if 'goal' in keys:
            assert self._point_is_valid(self.data['goal']), \
                "data['goal']: {} n'est pas un point valide (int, int)".format(self.data['goal'])
        else:
            self._data['data']['goal'] = 0, 0

        if 'args' in keys:
            assert isinstance(self.data['args'], list), \
                "data['args'] n'a pas le format attendu (list(str))"
        else:
            self._data['data']['args'] = []

    @staticmethod
    def get_default_data_dict():
        """ Retourne une dictionnaire de données par défaut """
        return dict(zip(['tactic', 'id'],
                        ['TacticHelloWorld', 0]))

    @staticmethod
    def get_type():
        return 5003


text:
<?php
	$url = base_url().$ro->core['slug'].'/'.$ro->core['id'];
	$title = $ro->core['title'];
    $id = $ro->core['id'];

    $params = [
        'url' => $url,
        'title' => $title,
        'id' => $id
    ];

    $params = http_build_query($params);
?>


text:
Getting up and running with the web server is easier than ever. Just include the plugin into your project, new up the object and start/stop the server at will. The namespace for the web server is `BeardedManStudios.Forge.MVCWebServer`, so if you need to include using statements or view things in the object browser, take a look in this namespace.

## Including plugin into project
You will notice a **MVCWebServer.dll** file in the unzipped folder for the web server. You just need to copy this file into your **Bearded Man Studios Inc/Plugins** folder. That is it, you've installed the web server plugin to your project.

## Starting a Web Server
Starting a web server is as simple as calling 2 lines of code as seen below.

```csharp
ForgeWebServer ws = new ForgeWebServer(server, pages, ForgeWebServer.DEFAULT_PORT);
ws.Start();
```

I know what you are saying, "what is server... and what are pages?". Good questions; see below:
- **server**: This is the `NetWorker` for the server
- **pages**: This is a `Dictionary<string, string>()` of web pages (html). The key string is the name of the page, like **"index"** and the value is the html of the page. The pages you add here will be viewable from the web interface. So let's say you add a page **cat** and the html `<h1>Hello World</h1>`. Then if you went to `locahost:15942/cat` in any web browser, you would see a big bold **Hello World** heading on the page.

We have added a few default pages as part of the package in the **Resources** folder. If you want a magical function that automatically maps all the pages you put into this folder, well... here you go:

```csharp
string pathToFiles = "fnwww/html";
Dictionary<string, string> pages = new Dictionary<string, string>();
TextAsset[] assets = Resources.LoadAll<TextAsset>(pathToFiles);
foreach (TextAsset a in assets)
    pages.Add(a.name, a.text);

ForgeWebServer ws = new ForgeWebServer(server, pages, ForgeWebServer.DEFAULT_PORT);
ws.Start();

// ...
```

## Stopping a Web Server
When you are closing your connection/application that has a running web server, you will want to close the connection for the web server as well. You can see how to close the connection to the web server below:

```csharp
ForgeWebServer ws = new ForgeWebServer(server, pages, ForgeWebServer.DEFAULT_PORT);
ws.Start();

// ...

ws.Stop();
```

## Notices & Warnings!
**STOP, BEFORE YOU LEAVE THIS PAGE!** There are a few things to keep in mind when using the web server.
1. If you disconnect your server, you **MUST** disconnect your web server as well. Since this is a plugin system, you need to remember to do this.
2. You **MUST** remember to close the web server on application quit.
3. The commands are run on a separate thread so you need to use [MainThreadManager](/UnityIntegration/running-unity-specific-code-on-the-main-thread.md) for any code that requires to be on the main thread


text:
/* jshint node: false, browser: true, jquery: true */
/* global define, alert */

require.config({
    paths: {
        "text"      : "vendor/require-text"
    }
});

define(function () { // require) {
    "use strict";

    var CONNECTION_RETRY_DELAY = 1000;

    var _ws = null,
        _commandId = 0,
        _deferreds = [];

    function sendCommand(command) {
        if (_ws.readyState !== WebSocket.OPEN) {
            alert("Not connected");
            return;
        }
        var id = _commandId++,
            deferred = $.Deferred();

        _ws.send(JSON.stringify({id: id, command: command}));
        _deferreds[id] = deferred;

        deferred.always(function () {
            delete _deferreds[id];
        });

        deferred.fail(function (err) {
            $("#results").prepend("
Error: " + err + "
");
        });

        return deferred.promise();
    }

    function displayStatus(status) {
        $("#websocket-status").text(status);
    }

    function receiveMessage(message) {
        var result = JSON.parse(message.data);
        if (result.hasOwnProperty("id") && _deferreds[result.id]) {
            if (result.hasOwnProperty("result")) {
                _deferreds[result.id].resolve(result.result);
            } else if (result.hasOwnProperty("error")) {
                _deferreds[result.id].reject(result.error);
            } else {
                _deferreds[result.id].reject("no result body");
            }
        } else {
            $("#results").prepend("
Error: don't know what to do with message: " + message + "
");
        }
    }

    function createWebSocketConnection() {
        displayStatus("connecting...");

        var wsUrl = window.location.protocol === "https:" ?
            "wss://" + window.location.host + "/" :
            "ws://" + window.location.host + "/";

        // create the websocket and immediately bind handlers
        _ws = new WebSocket(wsUrl);

        _ws.onopen = function () { displayStatus("connected"); };
        _ws.onmessage = receiveMessage;
        _ws.onclose = function () {
            displayStatus("closed");
            setTimeout(createWebSocketConnection, CONNECTION_RETRY_DELAY);
        };
    }

    function initUI() {
        $("#op-doc-info").on("click", function () {
            sendCommand("docinfo").then(function (docinfo) {
                var $docinfo = $("

");
                $docinfo.text(JSON.stringify(docinfo, null, "  "));
                $("#results").prepend($docinfo);
            });
        });

        $("#op-first-bounds").on("click", function () {
            sendCommand("firstbounds").then(function (bounds) {
                var $bounds = $("

");
                $bounds.text(JSON.stringify(bounds, null, "  "));
                $("#results").prepend($bounds);
            });
        });

        $("#op-first-shape").on("click", function () {
            sendCommand("firstshape").then(function (shape) {
                var $shape = $("

");
                $shape.text(JSON.stringify(shape, null, "  "));
                $("#results").prepend($shape);
            });
        });

        $("#op-set-doc-settings").on("click", function () {
            sendCommand("setdocsettings").then(function (result) {
                var $result = $("

");
                $result.text(JSON.stringify(result, null, "  "));
                $("#results").prepend($result);
            });
        });

        $("#op-clear").on("click", function () {
            $("#results").html("");
        });
    }

    function init() {
        initUI();
        createWebSocketConnection();
    }

    $(init);

});


text:
UserDataBase-Heroku
===================

The Runs-Everywhere-With-Heroku-Hosting version of my UserDataBase (udb) program, created for Code Fellows.
Makes, stores, edits and deletes user profiles with HTML+Django.

This program was developed as an admissions test for Code Fellows'
    Python developer accelerator with no previous Django experience
    and the help of the official Django tutorial and StackOverflow, et al.
    Mostly StackOverflow.

It might still be running at http://udb.herokuapp.com/


text:
package org.yi.happy.archive.key;

import org.yi.happy.annotate.ExternalName;

/**
 * the key types.
 */
public class KeyType {
    private KeyType() {
        // nothing
    }

    /**
     * the type name for a content type key
     */
    @ExternalName
    public static final String CONTENT_HASH = "content-hash";

    /**
     * the type name for a name type key
     */
    @ExternalName
    public static final String NAME_HASH = "name-hash";

    /**
     * the type name for a blob type key
     */
    public static final String BLOB = "blob";

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using sGridServer.Code.DataAccessLayer.Models;
using sGridServer.Code.Security;
using sGridServer.Code.GridProviders;
using System.Reflection;

namespace sGrid
{
    public class ClientApi : IClientApi
    {
        /// <summary>
        /// Gets information about the grid project the client
        /// should attach to and also returns authentication data
        /// for the communication with the grid provider.
        /// Note: if the user is not attached to any project, null
        /// will be returned.
        /// </summary>
        /// <param name="authentication">The data used to identify
        /// the client at the server.</param>
        /// <returns>Information and an authentication token for
        /// the project the client should attach to.</returns>
        public ProjectData GetCurrentProject(Credential authentication)
        {
            User user = GetUser(authentication);
            GridProjectDescription project = new GridProviderManager(user).CurrentProject;
            if (project == null)
            {
                return null;
            }
            String token = GridProvider.GetAuthTokenForUser(user, project).AuthenticationInfo;
            return new ProjectData(new SerializableGridProjectDescription(project), token);
        }

        /// <summary>
        /// Gets information and authentication data about the grid
        /// project the client has to authenticate at.
        /// Note: if no project with the given name exists, null
        /// will be returned.
        /// </summary>
        /// <param name="authentication">The data used to identify
        /// the client at the server.</param>
        /// <param name="projectName">The name identifying the
        /// project the token is wanted for</param>
        /// <returns>Information and authentication tokens for the
        /// project the client has to authenticate to.</returns>
        public ProjectData GetTokenForProject(Credential authentication, String projectName)
        {
            GridProjectDescription project = GridProviderManager.ProjectForName(projectName);
            if (project == null)
            {
                return null;
            }
            String token = GridProvider.GetAuthTokenForUser(GetUser(authentication), project).AuthenticationInfo;
            return new ProjectData(new SerializableGridProjectDescription(project), token);
        }

        /// <summary>
        /// Gets the User object associated with the authentication
        /// credentials. If the authentication is wrong an exception
        /// is thrown.
        /// </summary>
        /// <param name="authentication">The data used to identify
        /// the client at the server.</param>
        /// <returns>The User object associated with the Credential.</returns>
        public User GetUser(Credential authentication)
        {
            User user = (User)new MemberManager().ValidateAuthToken(
                authentication.AuthenticationToken, authentication.UserId);
            if (user == null)
            {
                throw new ArgumentException("invalid Credential");
            }
            return user;
        }

        /// <summary>
        /// Notifies the server that the client has finished
        /// calculating a package and sends a StatusMessage.
        /// </summary>
        /// <param name="message">A message giving information
        /// about the client state and the calculated package.</param>
        public void PackageFinished(StatusMessage message)
        {
            GridProjectDescription project = GridProviderManager.ProjectForName(message.ProjectShortName);
            if (project != null)
            {
                GridProvider provider = project.Provider.CreateProvider();

                CalculatedResult result = new CalculatedResult();
                result.EndTime = DateTime.Now;
                result.ProjectShortName = message.ProjectShortName;
                result.StartTime = message.StartTime;
                result.UserId = GetUser(message.Authentication).Id;
                result.Valid = false;
                provider.RegisterResultsSent(result);
            }
        }

        /// <summary>
        /// Tests if the client is in an consistant state.
        /// That is to say: if the credential is correct
        /// and the clientversion is the newest one.
        /// </summary>
        /// <param name="authentication">The credential to be tested.</param>
        /// <returns>True, if the credential is associated with a user.</returns>
        public TestResult TestClient(Credential authentication, int clientversion)
        {
            //try
           //{
                User user = (User)new MemberManager().ValidateAuthToken(
                    authentication.AuthenticationToken, authentication.UserId);
                if (user == null) return TestResult.WrongCredential;
                if (clientversion < 1) return TestResult.WrongCredential;
                return TestResult.Correct;
            //}
            //catch (ReflectionTypeLoadException ex)
            //{
            //    StringBuilder sb = new StringBuilder();

            //    foreach (Exception e in ex.LoaderExceptions)
            //    {
            //        sb.AppendLine();
            //        sb.AppendLine(e.GetType().ToString() + ":");
            //        sb.AppendLine(e.Message);
            //        sb.AppendLine(e.StackTrace);
            //    }

            //    System.IO.File.WriteAllText("C:\\DWASFiles\\Sites\\sgridservice\\VirtualDirectory0\\site\\wwwroot\\asdflog.txt", sb.ToString());
            //}

            //return TestResult.WrongCredential;
        }
    }
}


text:
require 'spec_helper'

# NOTE: Spain has the full case specs.
#       Do not apply all checks to all countries for suite speed.
describe ValidatesZipcode, '#validate_each' do
  TEST_DATA.each do |country_code, values|
    context country_code do
      context 'validates with valid zipcodes' do
        values[:valid].each do |zipcode|
          it zipcode do
            record = build_record(zipcode, country_code)
            zipcode_should_be_valid(record)
          end
        end
      end

      context 'does not validate with invalid zipcodes' do
        values[:invalid].each do |zipcode|
          display_name = zipcode.nil? ? 'nil' : zipcode.blank? ? 'blank' : zipcode

          it display_name.to_s do
            record = build_record(zipcode, country_code)
            zipcode_should_be_invalid(record, nil)
          end
        end
      end
    end
  end

  context 'unknown country' do
    it 'does not add errors with a any zipcode' do
      record = build_record('A1J2Z9', 'ZZ')
      zipcode_should_be_valid(record)
    end
  end

  context 'Excluded existing country code' do
    context 'Panama' do
      it 'validates with a valid zipcode' do
        %w[0800 6369].each do |zipcode|
          record = build_record(zipcode, 'PA')
          zipcode_should_be_valid(record, excluded_country_codes: %w[PA])
        end
      end

      it 'validates with an invalid zipcode' do
        %w[10800 369 A341].each do |zipcode|
          record = build_record(zipcode, 'PA')
          zipcode_should_be_valid(record, excluded_country_codes: %w[PA])
        end
      end
    end
  end

  context 'with formatting' do
    it 'is true with a valid zipcode for a given country code' do
      zipcode_should_be_valid(build_record('28 108', 'ES'), format: true)
      zipcode_should_be_invalid(build_record('28 108', 'ES'), nil)
      zipcode_should_be_invalid(build_record('28 108', 'ES'), nil, format: false)

      zipcode_should_be_valid(build_record('V2r-1c8', 'CA'), format: true)
      zipcode_should_be_invalid(build_record('V2r-1c8', 'CA'), nil)
      zipcode_should_be_invalid(build_record('V2r-1c8', 'CA'), nil, format: false)
    end
  end
end

describe ValidatesZipcode, '.valid?' do
  context 'Spain' do
    it 'is true with a valid zipcode for a given country code' do
      expect(ValidatesZipcode.valid?('93108', 'ES')).to eq(true)
    end

    it 'is false with an invalid zipcode for a given country code' do
      ['1234', '12345-12345', 'D0D0D0', 'invalid_zip'].each do |zipcode|
        expect(ValidatesZipcode.valid?(zipcode, 'ES')).to eq(false)
      end
    end

    it "is true with an unknown country code -  we don't have all!" do
      expect(ValidatesZipcode.valid?('12345', 'ZZ')).to eq(true)
    end

    it "is true with an excluded country code -  we don't want those to fail and nil is hairy" do
      expect(ValidatesZipcode.valid?('XXXX!!!XXXX', 'PA', excluded_country_codes: %w[PA])).to eq(true)
    end
  end

  context 'with formatting' do
    it 'is true with a valid zipcode for a given country code' do
      expect(ValidatesZipcode.valid?('28 108', 'ES', format: true)).to eq(true)
      expect(ValidatesZipcode.valid?('28 108', 'ES', format: false)).to eq(false)

      expect(ValidatesZipcode.valid?('V2r-1c8', 'CA', format: true)).to eq(true)
      expect(ValidatesZipcode.valid?('V2r-1c8', 'CA', format: false)).to eq(false)
    end
  end
end

describe ValidatesZipcode, '.format' do
  it 'formats valid zipcodes' do
    expect(ValidatesZipcode.format('Ka9 2dj', 'UK')).to eq('KA9 2DJ')
  end

  it 'raises for invalid zipcodes' do
    expect { ValidatesZipcode.format('KA9 1tr', 'DE') }.to raise_error(ValidatesZipcode::InvalidZipcodeError)
  end
end

def zipcode_should_be_valid(record, options = {})
  ValidatesZipcode::Validator.new(options.merge(attributes: :zipcode)).validate(record)

  expect(record.errors).to be_empty
end

def zipcode_should_be_invalid(record, _zipcode, options = {})
  ValidatesZipcode::Validator.new(options.merge(attributes: :zipcode)).validate(record)

  expect(record.errors.size).to eq 1
  expect(record.errors.messages[:zipcode]).to include 'Zipcode is invalid'
end

def zipcode_should_be_invalid_with_custom_message(record, _zipcode, options = {})
  custom_message = 'is really wrong'
  ValidatesZipcode::Validator.new(options.merge(attributes: :zipcode, message: custom_message)).validate(record)

  expect(record.errors.size).to eq 1
  expect(record.errors.messages[:zipcode]).to include custom_message
end

def build_record(zipcode, country_alpha2)
  ValidationDummyClass.new.tap do |object|
    object.country_alpha2 = country_alpha2
    object.zipcode = zipcode
  end
end

class ValidationDummyClass
  include ::ActiveModel::Validations
  attr_accessor :zipcode, :country_alpha2

  def self.name
    'TestClass'
  end
end


text:
<?php

interface CommentRepositoryInterface
{
    public function all();

    public function find($id);

    public function create($input);

}


text:
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.ValueGeneration;

namespace Beetle.Tests.IntegrationCore.Models {

    public class TestEntities : DbContext {

        public TestEntities(DbContextOptions options) : base(options) {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder) {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<Entity>().Property(e => e.ShortId).HasValueGenerator<IntGenerator>();
            modelBuilder.Entity<Order>().Property(o => o.Id).ValueGeneratedNever();
            modelBuilder.Entity<OrderDetail>().Property(od => od.Id).ValueGeneratedNever();
        }

        public DbSet<Entity> Entities { get; set; }
        public DbSet<Address> Addresses { get; set; }
        public DbSet<NamedEntity> NamedEntities { get; set; }
        public DbSet<Company> Companies { get; set; }
        public DbSet<NamedEntityType> NamedEntityTypes { get; set; }
        public DbSet<OrderDetail> OrderDetails { get; set; }
        public DbSet<Order> Orders { get; set; }
    }

    public class IntGenerator: ValueGenerator<int> {
        private static int _nextValue = 1;

        public override bool GeneratesTemporaryValues => false;

        public override int Next(EntityEntry entry) {
            return _nextValue++;
        }
    }
}


text:
namespace jnc {
namespace ct {

class FunctionType;
class FunctionPtrType;

//..............................................................................

// ordered from the worst to the best

enum CastKind {
	CastKind_None,
	CastKind_Dynamic,
	CastKind_Explicit,
	CastKind_ImplicitCrossFamily,
	CastKind_ImplicitCrossConst,
	CastKind_Implicit,
	CastKind_Identitiy,
};

// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

err::Error
setCastError(
	const Value& opValue,
	Type* type,
	CastKind castKind = CastKind_None
);

err::Error
setUnsafeCastError(
	Type* srcType,
	Type* dstType
);

// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

// these are sometimes needed for inlining casts before jnc_Module.h is included

bool
castOperator(
	Module* module,
	const Value& opValue,
	Type* type,
	Value* resultValue
);

JNC_INLINE
bool
castOperator(
	Module* module,
	Value* opValue,
	Type* type
) {
	return castOperator(module, *opValue, type, opValue);
}

//..............................................................................

class CastOperator {
	friend class OperatorMgr;

protected:
	Module* m_module;
	uint_t m_opFlags;

public:
	CastOperator();

	Module*
	getModule() {
		return m_module;
	}

	int
	getOpFlags() {
		return m_opFlags;
	}

	virtual
	CastKind
	getCastKind(
		const Value& opValue,
		Type* type
	) = 0;

	virtual
	bool
	constCast(
		const Value& opValue,
		Type* type,
		void* dst
	) {
		return false;
	}

	virtual
	bool
	llvmCast(
		const Value& opValue,
		Type* type,
		Value* resultValue
	) = 0;

	bool
	cast(
		const Value& opValue,
		Type* type,
		Value* resultValue
	);
};

//..............................................................................

// fail by default

class Cast_Default: public CastOperator {
public:
	virtual
	CastKind
	getCastKind(
		const Value& opValue,
		Type* type
	) {
		return CastKind_None;
	}

	virtual
	bool
	llvmCast(
		const Value& opValue,
		Type* type,
		Value* resultValue
	) {
		setCastError(opValue, type);
		return false;
	}
};

//..............................................................................

// we keep typedef shadows during code-assist

class Cast_Typedef: public CastOperator {
public:
	virtual
	CastKind
	getCastKind(
		const Value& opValue,
		Type* type
	);

	virtual
	bool
	constCast(
		const Value& opValue,
		Type* type,
		void* dst
	);

	virtual
	bool
	llvmCast(
		const Value& opValue,
		Type* type,
		Value* resultValue
	);
};

//..............................................................................

// cast to void

class Cast_Void: public CastOperator {
public:
	virtual
	CastKind
	getCastKind(
		const Value& opValue,
		Type* type
	) {
		return opValue.getType()->cmp(type) == 0 ? CastKind_Identitiy : CastKind_Implicit;
	}

	virtual
	bool
	constCast(
		const Value& opValue,
		Type* type,
		void* dst
	) {
		return true;
	}

	virtual
	bool
	llvmCast(
		const Value& opValue,
		Type* type,
		Value* resultValue
	) {
		resultValue->setVoid(m_module);
		return true;
	}
};

//..............................................................................

// simple copy

class Cast_Copy: public CastOperator {
public:
	virtual
	CastKind
	getCastKind(
		const Value& opValue,
		Type* type
	) {
		return opValue.getType()->cmp(type) == 0 ? CastKind_Identitiy : CastKind_Implicit;
	}

	virtual
	bool
	constCast(
		const Value& opValue,
		Type* type,
		void* dst
	);

	virtual
	bool
	llvmCast(
		const Value& opValue,
		Type* type,
		Value* resultValue
	);
};

//..............................................................................

// master cast chooses particular implementation

class Cast_Master: public CastOperator {
public:
	virtual
	CastKind
	getCastKind(
		const Value& opValue,
		Type* type
	);

	virtual
	bool
	constCast(
		const Value& opValue,
		Type* type,
		void* dst
	);

	virtual
	bool
	llvmCast(
		const Value& opValue,
		Type* type,
		Value* resultValue
	);

	virtual
	CastOperator*
	getCastOperator(
		const Value& opValue,
		Type* type
	) = 0;
};

//..............................................................................

// master cast capable of performing superposition of casts

class Cast_SuperMaster: public CastOperator {
public:
	virtual
	CastKind
	getCastKind(
		const Value& opValue,
		Type* type
	);

	virtual
	bool
	constCast(
		const Value& opValue,
		Type* type,
		void* dst
	);

	virtual
	bool
	llvmCast(
		const Value& opValue,
		Type* type,
		Value* resultValue
	);

	virtual
	bool
	getCastOperators(
		const Value& opValue,
		Type* type,
		CastOperator** operator1,
		CastOperator** operator2,
		Type** intermediateType
	) = 0;
};

//..............................................................................

} // namespace ct
} // namespace jnc


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Configurator.MacroDef
</TITLE>

<META NAME="date" CONTENT="2013-01-10">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.ivy.util

Class Configurator.MacroDef

java.lang.Object
  org.apache.ivy.util.Configurator.MacroDef

Enclosing class:
Configurator

public static class Configurator.MacroDef
extends java.lang.Object

Constructor Summary

Configurator.MacroDef(java.lang.String macroName)

Method Summary

 void
addAttribute(java.lang.String attName,
             java.lang.String attDefaultValue)

 void
addConfiguredAttribute(Configurator.Attribute att)

 void
addConfiguredElement(Configurator.Element elt)

 void
addElement(java.lang.String elementName,
           boolean optional)

 Configurator.Macro
createMacro()

 Configurator.Attribute
getAttribute(java.lang.String attributeName)

 java.lang.String
getName()

 java.lang.Object
play(Configurator conf,
     java.util.Map attValues,
     java.util.Map macroRecords)

 Configurator.MacroRecord
recordCreateChild(java.lang.String name)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Configurator.MacroDef

public Configurator.MacroDef(java.lang.String macroName)

Method Detail

getAttribute

public Configurator.Attribute getAttribute(java.lang.String attributeName)

play

public java.lang.Object play(Configurator conf,
                             java.util.Map attValues,
                             java.util.Map macroRecords)

getName

public java.lang.String getName()

addConfiguredAttribute

public void addConfiguredAttribute(Configurator.Attribute att)

addConfiguredElement

public void addConfiguredElement(Configurator.Element elt)

createMacro

public Configurator.Macro createMacro()

addAttribute

public void addAttribute(java.lang.String attName,
                         java.lang.String attDefaultValue)

addElement

public void addElement(java.lang.String elementName,
                       boolean optional)

recordCreateChild

public Configurator.MacroRecord recordCreateChild(java.lang.String name)

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
<project name="nuxeo" default="package" basedir=".">
    <description> collectionspace nuxeo </description>
    <!-- set global properties for this build -->
    <property name="services.trunk" value="../.."/>
    <!-- environment should be declared before reading build.properties -->
    <property environment="env"/>
    <property file="${services.trunk}/build.properties"/>
    <property name="mvn.opts" value="-V"/>
    <property name="src" location="src"/>
    <property name="build" location="build"/>
    <property name="dist" location="dist"/>

    <condition property="osfamily-unix">
        <os family="unix"/>
    </condition>
    <condition property="osfamily-windows">
        <os family="windows"/>
    </condition>

    <target name="init">
        <!-- Create the time stamp -->
        <tstamp/>
        <!-- Create the build directory structure used by compile -->
        <mkdir dir="${build}"/>
    </target>

    <target name="package" depends="package-unix,package-windows"
        description="Package CollectionSpace Services"/>
    <target name="package-unix" if="osfamily-unix">
        <exec executable="mvn" failonerror="true">
            <arg value="package"/>
            <arg value="-Dmaven.test.skip=true"/>
            <arg value="-f"/>
            <arg value="${basedir}/pom.xml"/>
            <arg value="-N"/>
            <arg value="${mvn.opts}"/>
        </exec>
    </target>
    <target name="package-windows" if="osfamily-windows">
        <exec executable="cmd" failonerror="true">
            <arg value="/c"/>
            <arg value="mvn.bat"/>
            <arg value="package"/>
            <arg value="-Dmaven.test.skip=true"/>
            <arg value="-f"/>
            <arg value="${basedir}/pom.xml"/>
            <arg value="-N"/>
            <arg value="${mvn.opts}"/>
        </exec>
    </target>

    <target name="install" depends="package,install-unix,install-windows" description="Install"/>
    <target name="install-unix" if="osfamily-unix">
        <exec executable="mvn" failonerror="true">
            <arg value="install"/>
            <arg value="-Dmaven.test.skip=true"/>
            <arg value="-f"/>
            <arg value="${basedir}/pom.xml"/>
            <arg value="-N"/>
            <arg value="${mvn.opts}"/>
        </exec>
    </target>
    <target name="install-windows" if="osfamily-windows">
        <exec executable="cmd" failonerror="true">
            <arg value="/c"/>
            <arg value="mvn.bat"/>
            <arg value="install"/>
            <arg value="-Dmaven.test.skip=true"/>
            <arg value="-f"/>
            <arg value="${basedir}/pom.xml"/>
            <arg value="-N"/>
            <arg value="${mvn.opts}"/>
        </exec>
    </target>

    <target name="clean" depends="clean-unix,clean-windows" description="Delete target directories">
        <delete dir="${build}"/>
    </target>
    <target name="clean-unix" if="osfamily-unix">
        <exec executable="mvn" failonerror="true">
            <arg value="clean"/>
            <arg value="${mvn.opts}"/>
        </exec>
    </target>
    <target name="clean-windows" if="osfamily-windows">
        <exec executable="cmd" failonerror="true">
            <arg value="/c"/>
            <arg value="mvn.bat"/>
            <arg value="clean"/>
            <arg value="${mvn.opts}"/>
        </exec>
    </target>

    <target name="test" depends="test-unix,test-windows" description="Run tests"/>
    <target name="test-unix" if="osfamily-unix">
        <exec executable="mvn" failonerror="true">
            <arg value="test"/>
            <arg value="${mvn.opts}"/>
        </exec>
    </target>
    <target name="test-windows" if="osfamily-windows">
        <exec executable="cmd" failonerror="true">
            <arg value="/c"/>
            <arg value="mvn.bat"/>
            <arg value="test"/>
            <arg value="${mvn.opts}"/>
        </exec>
    </target>

    <target name="deploy" depends="package"
        description="deploy nuxeo server libs to ${jee.server.cspace}">
        <copy todir="${jee.server.cspace}/nuxeo-server">
            <fileset dir="${basedir}/nuxeo-server/${nuxeo.release}">
                <exclude name="**/config/proto-*-config.xml"/>
            </fileset>
        </copy>
        <echo message="Copying Nuxeo prototype repo config file ..."/>
        <copy todir="${jee.server.cspace}/cspace/config/services" overwrite="true">
            <fileset file="${basedir}/nuxeo-server/${nuxeo.release}/config/proto-repo-config.xml"/>
            <filterset>
                <filter token="DB_NUXEO_NAME" value="${db.nuxeo.name}"/>
                <!-- The actual database name will be substituted during system -->
                <!-- startup, within each repository-specific config file that is 'cloned' from the -->
                <!-- prototype repo config file being written to here. -->
                <filter token="DB_SERVER_HOSTNAME" value="${db.host}"/>
                <filter token="DB_PORT" value="${db.port}"/>
                <filter token="DB_JDBC_OPTIONS" value="${db.jdbc.urloptions.encoded}"/>
                <filter token="XA_DATASOURCE" value="${db.xaDataSource}"/>
                <filter token="NUXEO_USER" value="${db.nuxeo.user}"/>
                <filter token="NUXEO_PW" value="${db.nuxeo.user.password}"/>
            </filterset>
        </copy>
        <copy todir="${jee.server.cspace}/cspace/config/services" overwrite="true">
            <fileset file="${basedir}/nuxeo-server/${nuxeo.release}/config/proto-datasource-config.xml"/>
            <filterset>
                <filter token="DB_SERVER_HOSTNAME" value="${db.host}"/>
                <filter token="DB_PORT" value="${db.port}"/>
                <filter token="DB_JDBC_OPTIONS" value="${db.jdbc.urloptions.encoded}"/>
                <filter token="NUXEO_USER" value="${db.nuxeo.user}"/>
                <filter token="NUXEO_PW" value="${db.nuxeo.user.password}"/>
            </filterset>
        </copy>

        <ant antfile="nuxeo-platform-collectionspace/build.xml" target="deploy" inheritall="false"/>
        <ant antfile="nuxeo-platform-listener/build.xml" target="deploy" inheritall="false"/>
        <!-- Disabled due to integration issues between ImageMagick and Ghostscript on Linux systems
        <ant antfile="nuxeo-platform-thumbnail/build.xml" target="deploy" inheritall="false"/>
        -->
    </target>

    <target name="undeploy" description="undeploy nuxeo server libs from ${jee.server.cspace}">
        <delete dir="${jee.server.cspace}/nuxeo-server/bundles"/>
        <delete dir="${jee.server.cspace}/nuxeo-server/config"/>
        <delete dir="${jee.server.cspace}/nuxeo-server/lib"/>
        <delete file="${jee.server.cspace}/cspace/config/services/proto-repo-config.xml" failonerror="false"/>
        <delete file="${jee.server.cspace}/cspace/config/services/proto-datasource-config.xml" failonerror="false"/>
        <ant antfile="nuxeo-platform-collectionspace/build.xml" target="undeploy" inheritall="false"/>
        <ant antfile="nuxeo-platform-listener/build.xml" target="undeploy" inheritall="false"/>
        <ant antfile="nuxeo-platform-quote/build.xml" target="undeploy" inheritall="false"/>
        <ant antfile="nuxeo-platform-quote-api/build.xml" target="undeploy" inheritall="false"/>
        <!-- Disabled due to integration issues between ImageMagick and Ghostscript on Linux systems
		<ant antfile="nuxeo-platform-thumbnail/build.xml" target="undeploy" inheritall="false"/>
		-->
    </target>

    <target name="dist" description="generate distribution for nuxeo server libs" depends="package">
        <copy todir="${services.trunk}/${dist.server.cspace}/nuxeo-server">
            <fileset dir="${basedir}/nuxeo-server"/>
        </copy>
    </target>

</project>


text:
package jeo.common.structure.tree;

import java.util.Collection;

import jeo.common.structure.ExtendedList;
import jeo.common.structure.tree.node.AVLBinaryNode;

public class AVLTreeMap<K extends Comparable<K>, V>
	extends BinaryTree<K, V, AVLBinaryNode<K, V>>
{
	////////////////////////////////////////////////////////////////////////////
	// ATTRIBUTE(S)
	////////////////////////////////////////////////////////////////////////////

	/**
	 * Generated serial version ID.
	 */
	private static final long serialVersionUID = 4744421447337482103L;

	////////////////////////////////////////////////////////////////////////////
	// CONSTRUCTOR(S)
	////////////////////////////////////////////////////////////////////////////

	public AVLTreeMap()
	{
		super();
	}

	////////////////////////////////////////////////////////////////////////////
	// INSERT
	////////////////////////////////////////////////////////////////////////////

	/**
	 * Associates the specified value with the specified key in this tree. If
	 * this tree previously contained a mapping for the key, the old value is
	 * replaced.
	 *

	 * @param key   key with which the specified value is to be associated
	 * @param value value to be associated with the specified key
	 *

	 * @return the previous value associated with {@code key}, or {@code null}
	 *         if there was no mapping for {@code key}. (A {@code null} return
	 *         can also indicate that this tree previously associated
	 *         {@code null} with {@code key}.)
	 *

	 * @throws ClassCastException   if the specified key cannot be compared with
	 *                              the keys currently in this tree
	 * @throws NullPointerException if the specified key is null and this tree
	 *                              uses natural ordering, or its comparator
	 *                              does not permit null keys
	 */
	@Override
	public V put(final K key, final V value)
	{
		AVLBinaryNode<K, V> treeRoot = root;
		// If the root is null
		if (root == null)
		{
			// The root is set to a new node containing the given key and value
			setRoot(new AVLBinaryNode<K, V>(key, value));
		}
		// Else browse this tree
		else
		{
			int cmp;
			AVLBinaryNode<K, V> parent;
			do
			{
				cmp = key.compareTo(treeRoot.key);
				// If the key is less than the key of the current node
				if (cmp < 0)
				{
					parent = treeRoot;
					treeRoot = treeRoot.left;
				}
				// If the key is greater than the key of the current node
				else if (cmp > 0)
				{
					parent = treeRoot;
					treeRoot = treeRoot.right;
				}
				else
				{
					// Replace and return the previous value of the node
					return treeRoot.setValue(value);
				}
			}
			while (treeRoot != null);
			// Create a new node containing the given key and value
			final AVLBinaryNode<K, V> newNode = new AVLBinaryNode<K, V>(key, value);
			if (cmp < 0)
			{
				// The new node is the left node of parent
				parent.setLeftNode(newNode);
			}
			else
			{
				// The new node is the right node of parent
				parent.setRightNode(newNode);
			}
			// Balance if necessary
			balance(newNode);
		}
		// Increase the size of this tree
		++size;
		// Return null since no previous value exists
		return null;
	}

	////////////////////////////////////////////////////////////////////////////
	// DELETE
	////////////////////////////////////////////////////////////////////////////

	/**
	 * Removes the specified node from this tree.
	 *

	 * @param node the node to be removed
	 */
	@Override
	protected void removeNode(final AVLBinaryNode<K, V> node)
	{
		// Get the parent and the successor of the specified node
		final AVLBinaryNode<K, V> parentNode = node.parent;
		// 0 or 1 child (this tree is guaranteed to be balanced)
		if ((node.left == null) || (node.right == null))
		{
			// Get the child if present
			AVLBinaryNode<K, V> childNode;
			if (node.left != null)
			{
				childNode = node.left;
			}
			else if (node.right != null)
			{
				childNode = node.right;
			}
			else
			{
				childNode = null;
			}
			// Update the parent
			if (parentNode == null)
			{
				setRoot(childNode);
			}
			else if (node.isLeft)
			{
				parentNode.setLeftNode(childNode);
			}
			else
			{
				parentNode.setRightNode(childNode);
			}
		}
		// 2 children (this tree is not guaranteed to be balanced)
		else
		{
			// Get the successor of the node to be removed
			// Note: the successor cannot be null since the node has a right node
			final AVLBinaryNode<K, V> successor = getSuccessor(node);
			// Remove the successor from this tree
			removeNode(successor);
			// Override the key and value of the node with the successor
			node.key = successor.key;
			node.value = successor.value;
			// Balance this tree from the node
			balanceAfterDeletion(node);
		}
		// Decrement the number of nodes
		--size;
	}

	////////////////////////////////////////////////////////////////////////////
	// BALANCE
	////////////////////////////////////////////////////////////////////////////

	private void balance(AVLBinaryNode<K, V> treeRoot)
	{
		AVLBinaryNode<K, V> parent = treeRoot;
		do
		{
			treeRoot = parent;
			// Get the balance of the node
			final long balance = treeRoot.balance;
			// Check the balance
			// - If the balance is equal to -2
			if (balance == -2)
			{
				// Get the left node of the specified node
				// Note: the left node cannot be null since the balance is negative
				final AVLBinaryNode<K, V> leftNode = treeRoot.left;
				// LL imbalance
				if (getHeight(leftNode.left) >= getHeight(leftNode.right))
				{
					treeRoot = rotateRight(treeRoot);
				}
				// LR imbalance
				else
				{
					treeRoot = rotateLeftRight(treeRoot);
				}
			}
			// - If the balance is equal to 2
			else if (balance == 2)
			{
				// Get the right node of the specified node
				// Note: the right node cannot be null since the balance is positive
				final AVLBinaryNode<K, V> rightNode = treeRoot.right;
				// RR imbalance
				if (getHeight(rightNode.right) >= getHeight(rightNode.left))
				{
					treeRoot = rotateLeft(treeRoot);
				}
				// RL imbalance
				else
				{
					treeRoot = rotateRightLeft(treeRoot);
				}
			}
			parent = treeRoot.parent;
		}
		while (parent != null);
		// The node has no parent, set the root of this tree
		setRoot(treeRoot);
	}

	/**
	 * Balances the tree whose root is {@code treeRoot} after insertion.
	 *

	 * @param treeRoot the root of the tree to be balanced
	 */
	@Override
	protected void balanceAfterInsertion(final AVLBinaryNode<K, V> treeRoot)
	{
		balance(treeRoot);
	}

	/**
	 * Balances the tree whose root is {@code treeRoot} after deletion.
	 *

	 * @param treeRoot the root of the tree to be balanced
	 */
	@Override
	protected void balanceAfterDeletion(final AVLBinaryNode<K, V> treeRoot)
	{
		balance(treeRoot);
	}

	////////////////////////////////////////////////////////////////////////////
	// GETTER(S)
	////////////////////////////////////////////////////////////////////////////

	/**
	 * Gets the height of the specified node.
	 *

	 * @param node the node with the height to be gotten
	 *

	 * @return the height of the specified node, or {@code -1} if the node is
	 *         {@code null}
	 */
	protected long getHeight(final AVLBinaryNode<K, V> node)
	{
		return node == null ? -1 : node.height;
	}

	////////////////////////////////////////////////////////////////////////////
	// SETTER(S)
	////////////////////////////////////////////////////////////////////////////

	/**
	 * Sets the root of this tree.
	 *

	 * @param node the root to set
	 */
	@Override
	protected void setRoot(final AVLBinaryNode<K, V> node)
	{
		root = node;
		if (root != null)
		{
			root.parent = null;
		}
	}

	////////////////////////////////////////////////////////////////////////////
	// BINARY TREE
	////////////////////////////////////////////////////////////////////////////

	/**
	 * Rotates the tree whose root is {@code treeRoot} to the left.
	 *

	 * @param treeRoot the root of the tree to be rotated
	 *

	 * @return the root of the rotated tree
	 */
	@Override
	protected AVLBinaryNode<K, V> rotateLeft(final AVLBinaryNode<K, V> treeRoot)
	{
		AVLBinaryNode.isNecessaryToUpdate(false);
		final AVLBinaryNode<K, V> rotatedTreeRoot = super.rotateLeft(treeRoot);
		AVLBinaryNode.isNecessaryToUpdate(true);
		treeRoot.updateHeightAndBalance();
		treeRoot.updateParentNodes();
		return rotatedTreeRoot;
	}

	/**
	 * Rotates the tree whose root is {@code treeRoot} to the right.
	 *

	 * @param treeRoot the root of the tree to be rotated
	 *

	 * @return the root of the rotated tree
	 */
	@Override
	protected AVLBinaryNode<K, V> rotateRight(final AVLBinaryNode<K, V> treeRoot)
	{
		AVLBinaryNode.isNecessaryToUpdate(false);
		final AVLBinaryNode<K, V> rotatedTreeRoot = super.rotateRight(treeRoot);
		AVLBinaryNode.isNecessaryToUpdate(true);
		treeRoot.updateHeightAndBalance();
		treeRoot.updateParentNodes();
		return rotatedTreeRoot;
	}

	////////////////////////////////////////////////////////////////////////////
	// STATISTICS
	////////////////////////////////////////////////////////////////////////////

	protected void updateHeightsAndBalances()
	{
		updateHeightsAndBalances(root);
	}

	protected void updateHeightsAndBalances(final AVLBinaryNode<K, V> node)
	{
		if (node != null)
		{
			node.updateHeightsAndBalances();
			updateHeightsAndBalances(node.left);
			updateHeightsAndBalances(node.right);
		}
	}

	public Collection<Long> getBalances()
	{
		updateHeightsAndBalances();
		return getBalances(root, new ExtendedList<Long>(size));
	}

	protected Collection<Long> getBalances(final AVLBinaryNode<K, V> node, final Collection<Long> collection)
	{
		if (node != null)
		{
			collection.add(node.balance);
			getBalances(node.left, collection);
			getBalances(node.right, collection);
		}
		return collection;
	}

	////////////////////////////////////////////////////////////////////////////
	// OBJECT
	////////////////////////////////////////////////////////////////////////////

	@Override
	public Object clone()
		throws CloneNotSupportedException
	{
		return super.clone();
	}
}


text:
<?php

namespace Imagine\Test\Image\Palette\Color;

use Imagine\Image\Palette\Color\Gray;
use Imagine\Image\Palette\Color\ColorInterface;
use Imagine\Image\Palette\Grayscale;

class GrayTest extends AbstractColorTest
{
    public function provideOpaqueColors()
    {
        return array(
            array(new Gray(new Grayscale(), array(12), 100)),
            array(new Gray(new Grayscale(), array(0), 100)),
            array(new Gray(new Grayscale(), array(255), 100)),
        );
    }
    public function provideNotOpaqueColors()
    {
        return array(
            array($this->getColor()),
            array(new Gray(new Grayscale(), array(12), 23)),
            array(new Gray(new Grayscale(), array(0), 45)),
            array(new Gray(new Grayscale(), array(255), 0)),
        );
    }

    public function provideGrayscaleData()
    {
        return array(
            array('#0c0c0c', $this->getColor()),
        );
    }

    public function provideColorAndAlphaTuples()
    {
        return array(
            array(14, $this->getColor())
        );
    }

    protected function getColor()
    {
        return new Gray(new Grayscale(), array(12), 14);
    }

    public function provideColorAndValueComponents()
    {
        return array(
            array(array(
                ColorInterface::COLOR_GRAY => 12,
            ), $this->getColor()),
        );
    }
}


text:
import { Mongo } from 'meteor/mongo';

export const History = new Mongo.Collection('history');


text:
namespace Ferrari
{
    public class Ferrari : ICar
    {
        public string DriverName
        {
            get;
        }

        public string Model
        {
            get;
        }

        public string Brakes()
        {
            return "Brakes!";
        }

        public string GasPedal()
        {
            return "Zadu6avam sA!";
        }

        public Ferrari(string model, string driverName)
        {
            this.Model = model;
            this.DriverName = driverName;
        }

        public override string ToString()
        {
            return $"{this.Model}/{this.Brakes()}/{this.GasPedal()}/{this.DriverName}";
        }
    }
}


text:
<?php

use Bunny\Channel;
use Bunny\Async\Client;
use Bunny\Message;
use Bunny\Protocol\MethodQueueDeclareOkFrame;
use React\EventLoop\Factory;

require '../../vendor/autoload.php';

$loop = Factory::create();

$binding_keys = array_slice($argv, 1);
if(empty($binding_keys )) {
    file_put_contents('php://stderr', "Usage: $argv[0] [binding_key]\n");
    exit(1);
}

(new Client($loop))->connect()->then(function (Client $client) {
    return $client->channel();
})->then(function (Channel $channel) use ($binding_keys) {
    return $channel->exchangeDeclare('topic_logs', 'topic')->then(function () use ($channel, $binding_keys) {
        return $channel->queueDeclare('', false, false, true, false);
    })->then(function (MethodQueueDeclareOkFrame $frame) use ($channel, $binding_keys) {
        $promises = [];

        foreach($binding_keys as $binding_key) {
            $promises[] = $channel->queueBind($frame->queue, 'topic_logs', $binding_key);
        }

        return \React\Promise\all($promises)->then(function () use ($frame) {
            return $frame;
        });
    })->then(function (MethodQueueDeclareOkFrame $frame) use ($channel) {
        echo ' [*] Waiting for logs. To exit press CTRL+C', "\n";
        $channel->consume(
            function (Message $message, Channel $channel, Client $client) {
                echo ' [x] ', $message->content, "\n";
            },
            $frame->queue,
            '',
            false,
            true
        );
    });
});

$loop->run();