text:
from core.domain import exp_services
from core.domain import exp_services_test
from core.domain import rights_manager
from core.domain import summary_services
from core.domain import user_services
from core.tests import test_utils
import feconf

class ExplorationDisplayableSummariesTest(
        exp_services_test.ExplorationServicesUnitTests):
    """Test functions for getting displayable exploration summary dicts."""

    ALBERT_EMAIL = 'albert@example.com'
    BOB_EMAIL = 'bob@example.com'
    ALBERT_NAME = 'albert'
    BOB_NAME = 'bob'

    USER_C_NAME = 'c'
    USER_D_NAME = 'd'
    USER_C_EMAIL = 'c@example.com'
    USER_D_EMAIL = 'd@example.com'

    USER_C_PROFILE_PICTURE = 'c_profile_picture'

    EXP_ID_1 = 'eid1'
    EXP_ID_2 = 'eid2'
    EXP_ID_3 = 'eid3'
    EXP_ID_4 = 'eid4'
    EXP_ID_5 = 'eid5'

    EXPECTED_VERSION_1 = 4
    EXPECTED_VERSION_2 = 2

    def setUp(self):
        """Populate the database of explorations and their summaries.

        The sequence of events is:
        - (1) Albert creates EXP_ID_1.
        - (2) Bob edits the title of EXP_ID_1.
        - (3) Albert creates EXP_ID_2.
        - (4) Albert edits the title of EXP_ID_1.
        - (5) Albert edits the title of EXP_ID_2.
        - (6) Bob reverts Albert's last edit to EXP_ID_1.
        - Bob tries to publish EXP_ID_2, and is denied access.
        - (7) Albert publishes EXP_ID_2.
        - (8) Albert creates EXP_ID_3
        - (9) Albert publishes EXP_ID_3
        - (10) Albert deletes EXP_ID_3

        - (1) User_3 (has a profile_picture) creates EXP_ID_4.
        - (2) User_4 edits the title of EXP_ID_4.
        - (3) User_4 edits the title of EXP_ID_4.
        """

        super(ExplorationDisplayableSummariesTest, self).setUp()

        self.albert_id = self.get_user_id_from_email(self.ALBERT_EMAIL)
        self.bob_id = self.get_user_id_from_email(self.BOB_EMAIL)
        self.signup(self.ALBERT_EMAIL, self.ALBERT_NAME)
        self.signup(self.BOB_EMAIL, self.BOB_NAME)

        self.save_new_valid_exploration(self.EXP_ID_1, self.albert_id)

        exp_services.update_exploration(
            self.bob_id, self.EXP_ID_1, [{
                'cmd': 'edit_exploration_property',
                'property_name': 'title',
                'new_value': 'Exploration 1 title'
            }], 'Changed title.')

        self.save_new_valid_exploration(self.EXP_ID_2, self.albert_id)

        exp_services.update_exploration(
            self.albert_id, self.EXP_ID_1, [{
                'cmd': 'edit_exploration_property',
                'property_name': 'title',
                'new_value': 'Exploration 1 Albert title'
            }], 'Changed title to Albert1 title.')

        exp_services.update_exploration(
            self.albert_id, self.EXP_ID_2, [{
                'cmd': 'edit_exploration_property',
                'property_name': 'title',
                'new_value': 'Exploration 2 Albert title'
            }], 'Changed title to Albert2 title.')

        exp_services.revert_exploration(self.bob_id, self.EXP_ID_1, 3, 2)

        with self.assertRaisesRegexp(
            Exception, 'This exploration cannot be published'
            ):
            rights_manager.publish_exploration(self.bob_id, self.EXP_ID_2)

        rights_manager.publish_exploration(self.albert_id, self.EXP_ID_2)

        self.save_new_valid_exploration(self.EXP_ID_3, self.albert_id)
        rights_manager.publish_exploration(self.albert_id, self.EXP_ID_3)
        exp_services.delete_exploration(self.albert_id, self.EXP_ID_3)

        self.user_c_id = self.get_user_id_from_email(self.USER_C_EMAIL)
        self.user_d_id = self.get_user_id_from_email(self.USER_D_EMAIL)
        self.signup(self.USER_C_EMAIL, self.USER_C_NAME)
        self.signup(self.USER_D_EMAIL, self.USER_D_NAME)
        user_services.update_profile_picture_data_url(
            self.user_c_id, self.USER_C_PROFILE_PICTURE)

        self.save_new_valid_exploration(self.EXP_ID_4, self.user_c_id)
        exp_services.update_exploration(
            self.user_d_id, self.EXP_ID_4, [{
                'cmd': 'edit_exploration_property',
                'property_name': 'title',
                'new_value': 'Exploration updated title'
            }], 'Changed title once.')

        exp_services.update_exploration(
            self.user_d_id, self.EXP_ID_4, [{
                'cmd': 'edit_exploration_property',
                'property_name': 'title',
                'new_value': 'Exploration updated title again'
            }], 'Changed title twice.')

        self.save_new_valid_exploration(self.EXP_ID_5, self.bob_id)

    def test_get_human_readable_contributors_summary(self):
        contributors_summary = {self.albert_id: 10, self.bob_id: 13}
        self.assertEqual({
            self.ALBERT_NAME: {
                'num_commits': 10,
                'profile_picture_data_url': (
                    user_services.DEFAULT_IDENTICON_DATA_URL)
            },
            self.BOB_NAME: {
                'num_commits': 13,
                'profile_picture_data_url': (
                    user_services.DEFAULT_IDENTICON_DATA_URL)
            }
        }, summary_services.get_human_readable_contributors_summary(
            contributors_summary))

        contributors_summary = {self.user_c_id: 1, self.user_d_id: 2}
        self.assertEqual({
            self.USER_C_NAME: {
                'num_commits': 1,
                'profile_picture_data_url': self.USER_C_PROFILE_PICTURE
            },
            self.USER_D_NAME: {
                'num_commits': 2,
                'profile_picture_data_url': (
                    user_services.DEFAULT_IDENTICON_DATA_URL)
            }
        }, summary_services.get_human_readable_contributors_summary(
            contributors_summary))

    def test_get_displayable_exp_summary_dicts_matching_ids(self):
        # A list of exp_id's are passed in:
        # EXP_ID_1 -- private exploration owned by Albert
        # EXP_ID_2 -- pubished exploration owned by Albert
        # EXP_ID_3 -- deleted exploration
        # EXP_ID_5 -- private exploration owned by Bob
        # Should only return [EXP_ID_2]

        displayable_summaries = (
            summary_services.get_displayable_exp_summary_dicts_matching_ids(
                [self.EXP_ID_1, self.EXP_ID_2, self.EXP_ID_3, self.EXP_ID_5]))
        expected_summary = {
            'category': u'A category',
            'community_owned': False,
            'human_readable_contributors_summary': {
                self.ALBERT_NAME: {
                    'num_commits': 2,
                    'profile_picture_data_url': (
                        user_services.DEFAULT_IDENTICON_DATA_URL)
                }
            },
            'id': self.EXP_ID_2,
            'language_code': feconf.DEFAULT_LANGUAGE_CODE,
            'num_views': 0,
            'objective': u'An objective',
            'ratings': feconf.get_empty_ratings(),
            'status': 'public',
            'tags': [],
            'thumbnail_bg_color': '#a33f40',
            'thumbnail_icon_url': '/images/subjects/Lightbulb.svg',
            'title': u'Exploration 2 Albert title',
        }
        self.assertIn('last_updated_msec', displayable_summaries[0])
        self.assertDictContainsSubset(expected_summary,
                                      displayable_summaries[0])

    def test_get_public_and_filtered_private_summary_dicts_for_creator(self):
        # If a new exploration is created by another user (Bob) and not public,
        # then Albert cannot see it when querying for explorations.
        displayable_summaries = (
            summary_services.get_displayable_exp_summary_dicts_matching_ids(
                [self.EXP_ID_1, self.EXP_ID_2, self.EXP_ID_3, self.EXP_ID_5],
                editor_user_id=self.albert_id))

        self.assertEqual(len(displayable_summaries), 2)
        self.assertEqual(displayable_summaries[0]['id'], self.EXP_ID_1)
        self.assertEqual(displayable_summaries[1]['id'], self.EXP_ID_2)

        # However, if Albert is granted editor access to Bob's exploration,
        # then Albert has access to the corresponding summary.
        rights_manager.assign_role_for_exploration(
            self.bob_id, self.EXP_ID_5, self.albert_id,
            rights_manager.ROLE_EDITOR)

        displayable_summaries = (
            summary_services.get_displayable_exp_summary_dicts_matching_ids(
                [self.EXP_ID_1, self.EXP_ID_2, self.EXP_ID_3, self.EXP_ID_5],
                editor_user_id=self.albert_id))

        self.assertEqual(len(displayable_summaries), 3)
        self.assertEqual(displayable_summaries[0]['status'], 'private')
        self.assertEqual(displayable_summaries[0]['id'], self.EXP_ID_1)

        self.assertEqual(displayable_summaries[1]['status'], 'public')
        self.assertEqual(displayable_summaries[1]['id'], self.EXP_ID_2)

        self.assertEqual(displayable_summaries[2]['status'], 'private')
        self.assertEqual(displayable_summaries[2]['id'], self.EXP_ID_5)

class LibraryGroupsTest(exp_services_test.ExplorationServicesUnitTests):
    """Test functions for getting summary dicts for library groups."""

    def setUp(self):
        """Populate the database of explorations and their summaries.

        The sequence of events is:
        - (1) Admin logs in.
        - (2) Admin access admin page.
        - (3) Admin reloads exploration with id '2'.
        - (4) Admin logs out.
        """

        super(LibraryGroupsTest, self).setUp()
        self.login(self.ADMIN_EMAIL, is_super_admin=True)
        response = self.testapp.get('/admin')
        csrf_token = self.get_csrf_token_from_response(response)
        self.post_json('/adminhandler', {
            'action': 'reload_exploration',
            'exploration_id': '2'
        }, csrf_token)
        self.logout()

    def test_get_library_groups(self):
        """The exploration with id '2' is an exploration in the Mathematics
        category. The call to get_library_groups() should return the
        exploration as part of the Mathematics & Statistics group.
        """
        library_groups = summary_services.get_library_groups([])
        expected_exploration_summary_dict = {
            'category': u'Algorithms',
            'community_owned': True,
            'human_readable_contributors_summary': {},
            'id': '2',
            'language_code': feconf.DEFAULT_LANGUAGE_CODE,
            'num_views': 0,
            'objective': u'discover the binary search algorithm',
            'ratings': feconf.get_empty_ratings(),
            'status': u'public',
            'tags': [],
            'title':  u'The Lazy Magician',
            'thumbnail_bg_color': '#d0982a',
            'thumbnail_icon_url': '/images/subjects/Algorithms.svg',
        }
        expected_group = {
            'categories': ['Algorithms', 'Computing', 'Programming'],
            'header': 'Computing',
        }

        self.assertEqual(len(library_groups), 1)
        self.assertDictContainsSubset(expected_group, library_groups[0])
        self.assertEqual(
            len(library_groups[0]['activity_summary_dicts']), 1)
        actual_exploration_summary_dict = (
            library_groups[0]['activity_summary_dicts'][0])
        self.assertDictContainsSubset(expected_exploration_summary_dict, (
            actual_exploration_summary_dict))

class FeaturedExplorationDisplayableSummariesTest(
        test_utils.GenericTestBase):
    """Test functions for getting displayable featured exploration
    summary dicts.
    """

    ALBERT_NAME = 'albert'
    ALBERT_EMAIL = 'albert@example.com'

    EXP_ID_1 = 'eid1'
    EXP_ID_2 = 'eid2'

    def setUp(self):
        """Populate the database of explorations and their summaries.

        The sequence of events is:
        - (1) Albert creates EXP_ID_1.
        - (2) Albert creates EXP_ID_2.
        - (3) Albert publishes EXP_ID_1.
        - (4) Albert publishes EXP_ID_2.
        - (5) Admin user is set up.
        """

        super(FeaturedExplorationDisplayableSummariesTest, self).setUp()

        self.admin_id = self.get_user_id_from_email(self.ADMIN_EMAIL)
        self.albert_id = self.get_user_id_from_email(self.ALBERT_EMAIL)
        self.signup(self.ADMIN_EMAIL, self.ADMIN_USERNAME)
        self.signup(self.ALBERT_EMAIL, self.ALBERT_NAME)

        self.save_new_valid_exploration(self.EXP_ID_1, self.albert_id)
        self.save_new_valid_exploration(self.EXP_ID_2, self.albert_id)

        rights_manager.publish_exploration(self.albert_id, self.EXP_ID_1)
        rights_manager.publish_exploration(self.albert_id, self.EXP_ID_2)

        self.set_admins([self.ADMIN_USERNAME])

    def test_for_featured_explorations(self):
        """Note that EXP_ID_1 is public, and EXP_ID_2 is publicized.
        The call to get_featured_explorations() should only return
        [EXP_ID_2].
        """

        rights_manager.publicize_exploration(self.admin_id, self.EXP_ID_2)

        featured_exploration_summaries = (
            summary_services.get_featured_exploration_summary_dicts([
                feconf.DEFAULT_LANGUAGE_CODE]))
        expected_summary = {
            'status': u'publicized',
            'thumbnail_bg_color': '#a33f40',
            'community_owned': False,
            'tags': [],
            'thumbnail_icon_url': '/images/subjects/Lightbulb.svg',
            'language_code': feconf.DEFAULT_LANGUAGE_CODE,
            'id': self.EXP_ID_2,
            'category': u'A category',
            'ratings': feconf.get_empty_ratings(),
            'title': u'A title',
            'num_views': 0,
            'objective': u'An objective'
        }
        self.assertDictContainsSubset(
            expected_summary, featured_exploration_summaries[0])


text:
{% extends 'base_no_angular.html' %}
{% block title %}login{% endblock %}
{% block head-appendix %}
	<link type="text/css" rel="stylesheet" href="{{STATIC_URL}}css/openid.css" />

{% endblock %}

{% block content %}

Sign in with your OpenID

{% if form.errors %}

Please correct errors below:

    {% if form.openid_identifier.errors %}
    {{ form.openid_identifier.errors|join:", " }}
    {% endif %}
    {% if form.next.errors %}
    {{ form.next.errors|join:", " }}
    {% endif %}

{% endif %}
<form id="openid_form" name="fopenid" action="{{ action }}" method="post">
    {% csrf_token %}

Please click your account provider:

            OpenID:

            {{ form.openid_identifier }}
            <input id="openid_submit" name="bsignin" type="submit" value="Sign in"/>

 {% if next %}
        <input type="hidden" name="next" value="{{ next }}" />
 {% endif %}
</form>
{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
/*
 * walkers.c
 *
 *  Created on: Feb 8, 2011
 *      Author: siva
 */

#include "postgres.h"

#include "catalog/pg_collation.h"
#include "miscadmin.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/walkers.h"
#include "optimizer/var.h"

/**
 * Plan node walker related methods.
 */

/* Initialize a plan_tree_base_prefix during planning. */
void planner_init_plan_tree_base(plan_tree_base_prefix *base, PlannerInfo *root)
{
	base->node = (Node*)root;
}

/* Initialize a plan_tree_base_prefix after planning. */
void exec_init_plan_tree_base(plan_tree_base_prefix *base, PlannedStmt *stmt)
{
	base->node = (Node*)stmt;
}

static bool walk_scan_node_fields(Scan *scan, bool (*walker) (), void *context);
static bool walk_join_node_fields(Join *join, bool (*walker) (), void *context);

/* ----------------------------------------------------------------------- *
 * Plan Tree Walker Framework
 * ----------------------------------------------------------------------- *
 */

/* Function walk_plan_node_fields is a subroutine used by plan_tree_walker()
 * to walk the fields of Plan nodes.  Plan is actually an abstract superclass
 * of all plan nodes and this function encapsulates the common structure.
 *
 * Most specific walkers won't need to call this function, but complicated
 * ones may find it a useful utility.
 *
 * Caution: walk_scan_node_fields and walk_join_node_fields call this
 * function.  Use only the most specific function.
 */
bool
walk_plan_node_fields(Plan *plan,
					  bool (*walker) (),
					  void *context)
{
	/* target list to be computed at this node */
	if (walker((Node *) (plan->targetlist), context))
		return true;

	/* implicitly ANDed qual conditions */
	if (walker((Node *) (plan->qual), context))
		return true;

	/* input plan tree(s) */
	if (walker((Node *) (plan->lefttree), context))
		return true;

	/* target list to be computed at this node */
	if (walker((Node *) (plan->righttree), context))
		return true;

	/* Init Plan nodes (uncorrelated expr subselects */
	if (walker((Node *) (plan->initPlan), context))
		return true;

	/* Greenplum Database Flow node */
	if (walker((Node *) (plan->flow), context))
		return true;

	return false;
}

/* Function walk_scan_node_fields is a subroutine used by plan_tree_walker()
 * to walk the fields of Scan nodes.  Scan is actually an abstract superclass
 * of all scan nodes and a subclass of Plan.  This function encapsulates the
 * common structure.
 *
 * Most specific walkers won't need to call this function, but complicated
 * ones may find it a useful utility.
 *
 * Caution: This function calls walk_plan_node_fields so callers shouldn't,
 * else they will walk common plan fields twice.
 */
bool
walk_scan_node_fields(Scan *scan,
					  bool (*walker) (),
					  void *context)
{
	/* A Scan node is a kind of Plan node. */
	if (walk_plan_node_fields((Plan *) scan, walker, context))
		return true;

	/* The only additional field is an Index so no extra walking. */
	return false;
}

/* Function walk_join_node_fields is a subroutine used by plan_tree_walker()
 * to walk the fields of Join nodes.  Join is actually an abstract superclass
 * of all join nodes and a subclass of Plan.  This function encapsulates the
 * common structure.
 *
 * Most specific walkers won't need to call this function, but complicated
 * ones may find it a useful utility.
 *
 * Caution: This function calls walk_plan_node_fields so callers shouldn't,
 * else they will walk common plan fields twice.
 */
bool
walk_join_node_fields(Join *join,
					  bool (*walker) (),
					  void *context)
{
	/* A Join node is a kind of Plan node. */
	if (walk_plan_node_fields((Plan *) join, walker, context))
		return true;

	return walker((Node *) (join->joinqual), context);
}

/* Function plan_tree_walker is a general walker for Plan trees.
 *
 * It is based on (and uses) the expression_tree_walker() framework from
 * src/backend/optimizer/util/clauses.c.  See the comments there for more
 * insight into how this function works.
 *
 * The basic idea is that this function (and its helpers) walk plan-specific
 * nodes and delegate other nodes to expression_tree_walker().	The caller
 * may supply a specialized walker
 */
bool
plan_tree_walker(Node *node,
				 bool (*walker) (),
				 void *context,
				 bool recurse_into_subplans)
{
	/*
	 * The walker has already visited the current node, and so we need
	 * only recurse into any sub-nodes it has.
	 *
	 * We assume that the walker is not interested in List nodes per se, so
	 * when we expect a List we just recurse directly to self without
	 * bothering to call the walker.
	 */
	if (node == NULL)
		return false;

	/* Guard against stack overflow due to overly complex expressions */
	check_stack_depth();

	switch (nodeTag(node))
	{
			/*
			 * Plan nodes aren't handled by expression_tree_walker, so we need
			 * to do them here.
			 */
		case T_Plan:
			/* Abstract: really should see only subclasses. */
			return walk_plan_node_fields((Plan *) node, walker, context);

		case T_Result:
			if (walk_plan_node_fields((Plan *) node, walker, context))
				return true;
			if (walker((Node *) ((Result *) node)->resconstantqual, context))
				return true;
			break;

		case T_PartitionSelector:
			if (walk_plan_node_fields((Plan *) node, walker, context))
				return true;
			if (walker((Node *) ((PartitionSelector *) node)->levelEqExpressions, context))
				return true;
			if (walker((Node *) ((PartitionSelector *) node)->levelExpressions, context))
				return true;
			if (walker(((PartitionSelector *) node)->residualPredicate, context))
				return true;
			if (walker(((PartitionSelector *) node)->propagationExpression, context))
				return true;
			if (walker(((PartitionSelector *) node)->partTabTargetlist, context))
				return true;
			break;

		case T_Append:
			if (walk_plan_node_fields((Plan *) node, walker, context))
				return true;
			if (walker((Node *) ((Append *) node)->appendplans, context))
				return true;
			break;

		case T_MergeAppend:
			if (walk_plan_node_fields((Plan *) node, walker, context))
				return true;
			if (walker((Node *) ((MergeAppend *) node)->mergeplans, context))
				return true;
			break;

		case T_RecursiveUnion:
			if (walk_plan_node_fields((Plan *) node, walker, context))
				return true;
			break;

		case T_Sequence:
			if (walk_plan_node_fields((Plan *) node, walker, context))
				return true;
			if (walker((Node *) ((Sequence *) node)->subplans, context))
				return true;
			break;

		case T_BitmapAnd:
            if (walk_plan_node_fields((Plan *) node, walker, context))
                return true;
            if (walker((Node *) ((BitmapAnd *) node)->bitmapplans, context))
                return true;
            break;
        case T_BitmapOr:
            if (walk_plan_node_fields((Plan *) node, walker, context))
                return true;
            if (walker((Node *) ((BitmapOr *) node)->bitmapplans, context))
                return true;
            break;

		case T_Scan:
			/* Abstract: really should see only subclasses. */
			return walk_scan_node_fields((Scan *) node, walker, context);

		case T_SeqScan:
		case T_SampleScan:
		case T_DynamicSeqScan:
		case T_BitmapHeapScan:
		case T_DynamicBitmapHeapScan:
		case T_WorkTableScan:
			if (walk_scan_node_fields((Scan *) node, walker, context))
				return true;
			break;

		case T_ForeignScan:
			if (walk_scan_node_fields((Scan *) node, walker, context))
				return true;
			if (walker(((ForeignScan *) node)->fdw_exprs, context))
				return true;
			break;

		case T_CustomScan:
			if (walk_scan_node_fields((Scan *) node, walker, context))
				return true;
			if (walker(((CustomScan *) node)->custom_plans, context))
				return true;
			if (walker(((CustomScan *) node)->custom_exprs, context))
				return true;
			if (walker(((CustomScan *) node)->custom_private, context))
				return true;
			if (walker(((CustomScan *) node)->custom_scan_tlist, context))
				return true;
			break;

		case T_ValuesScan:
			if (walker((Node *) ((ValuesScan *) node)->values_lists, context))
				return true;
			if (walk_scan_node_fields((Scan *) node, walker, context))
				return true;
			break;

		case T_TableFunctionScan:
			if (walker((Node *) ((TableFunctionScan *) node)->function, context))
				return true;
			if (walk_scan_node_fields((Scan *) node, walker, context))
				return true;
			break;

		case T_FunctionScan:
			if (walker((Node *) ((FunctionScan *) node)->functions, context))
				return true;
			if (walker((Node *) ((FunctionScan *) node)->param, context))
				return true;
			if (walk_scan_node_fields((Scan *) node, walker, context))
				return true;
			break;

		case T_IndexScan:
		case T_DynamicIndexScan:
			if (walk_scan_node_fields((Scan *) node, walker, context))
				return true;
			if (walker((Node *) ((IndexScan *) node)->indexqual, context))
				return true;
			/* Other fields are lists of basic items, nothing to walk. */
			break;

		case T_IndexOnlyScan:
			if (walk_scan_node_fields((Scan *) node, walker, context))
				return true;
			if (walker((Node *) ((IndexOnlyScan *) node)->indexqual, context))
				return true;
			break;

		case T_BitmapIndexScan:
		case T_DynamicBitmapIndexScan:
			if (walk_scan_node_fields((Scan *) node, walker, context))
				return true;
			if (walker((Node *) ((BitmapIndexScan *) node)->indexqual, context))
				return true;
			/* Other fields are lists of basic items, nothing to walk. */
			break;

		case T_TidScan:
			if (walk_scan_node_fields((Scan *) node, walker, context))
				return true;
			if (walker((Node *) ((TidScan *) node)->tidquals, context))
				return true;
			break;

		case T_SubqueryScan:
			if (walk_scan_node_fields((Scan *) node, walker, context))
				return true;
			if (walker((Node *) ((SubqueryScan *) node)->subplan, context))
				return true;
			break;

		case T_Join:
			/* Abstract: really should see only subclasses. */
			return walk_join_node_fields((Join *) node, walker, context);

		case T_NestLoop:
			if (walk_join_node_fields((Join *) node, walker, context))
				return true;
			break;

		case T_MergeJoin:
			if (walk_join_node_fields((Join *) node, walker, context))
				return true;
			if (walker((Node *) ((MergeJoin *) node)->mergeclauses, context))
				return true;
			break;

		case T_HashJoin:
			if (walk_join_node_fields((Join *) node, walker, context))
				return true;
			if (walker((Node *) ((HashJoin *) node)->hashclauses, context))
				return true;
			if (walker((Node *) ((HashJoin *) node)->hashqualclauses, context))
				return true;
			break;

		case T_Material:
			if (walk_plan_node_fields((Plan *) node, walker, context))
				return true;
			break;

		case T_Sort:
			if (walk_plan_node_fields((Plan *) node, walker, context))
				return true;
			/* Other fields are simple counts and lists of indexes and oids. */
			break;

		case T_Agg:
			if (walk_plan_node_fields((Plan *) node, walker, context))
				return true;
			/* Other fields are simple items and lists of simple items. */
			break;

		case T_TupleSplit:
			if (walk_plan_node_fields((Plan *) node, walker, context))
				return true;
			if (expression_tree_walker((Node *)((TupleSplit *)node)->dqa_expr_lst, walker, context))
				return true;
			/* Other fields are simple items and lists of simple items. */
			break;

        case T_DQAExpr:
	        if (walker(((DQAExpr *)node)->agg_filter, context))
		        return true;
			/* Other fields are simple items and lists of simple items. */
			break;

		case T_WindowAgg:
			if (walk_plan_node_fields((Plan *) node, walker, context))
				return true;
			if (walker(((WindowAgg *) node)->startOffset, context))
				return true;
			if (walker(((WindowAgg *) node)->endOffset, context))
				return true;
			break;

		case T_Unique:
			if (walk_plan_node_fields((Plan *) node, walker, context))
				return true;
			/* Other fields are simple items and lists of simple items. */
			break;

		case T_Gather:
			if (walk_plan_node_fields((Plan *) node, walker, context))
				return true;
			/* Other fields are simple items. */
			break;

		case T_Hash:
			if (walk_plan_node_fields((Plan *) node, walker, context))
				return true;
			/* Other info is in parent HashJoin node. */
			break;

		case T_SetOp:
			if (walk_plan_node_fields((Plan *) node, walker, context))
				return true;
			/* Other fields are simple items and lists of simple items. */
			break;

		case T_Limit:

			if (walk_plan_node_fields((Plan *) node, walker, context))
				return true;

			/* Greenplum Database Limit Count */
			if (walker((Node *) (((Limit*) node)->limitCount), context))
					return true;

			/* Greenplum Database Limit Offset */
			if (walker((Node *) (((Limit*) node)->limitOffset), context))
					return true;

			/* Other fields are simple items and lists of simple items. */
			break;

		case T_Motion:
			if (walk_plan_node_fields((Plan *) node, walker, context))
				return true;

			if (walker((Node *) ((Motion *)node)->hashExprs, context))
				return true;

			break;

		case T_ShareInputScan:
		case T_CteScan:
			if (walk_plan_node_fields((Plan *) node, walker, context))
				return true;
			break;

		case T_Flow:
			/* Nothing to walk in Flow nodes at present. */
			break;

		case T_SubPlan:

			/*
			 * SubPlan is handled by expression_tree_walker() , but that
			 * walker doesn't recur into the plan itself.  Here, we do so
			 * by using information in the prefix structure defined in
			 * cdbplan.h.
			 *
			 * NB Callers usually don't have to take special account of
			 *    the range table, but should be sure to understand what
			 *    stage of processing they occur in (e.g., early planning,
			 *    late planning, dispatch, or execution) since this affects
			 *    what value are available.
			 */
			{
				SubPlan    *subplan = (SubPlan *) node;
				Plan	   *subplan_plan = plan_tree_base_subplan_get_plan(context, subplan);

				Assert(subplan_plan);

				/* recurse into the exprs list */
				if (expression_tree_walker((Node *) subplan->testexpr,
										   walker, context))
					return true;

				/* recurse into the subplan's plan, a kind of Plan node */
				if (recurse_into_subplans && walker((Node *) subplan_plan, context))
					return true;

				/* also examine args list */
				if (expression_tree_walker((Node *) subplan->args,
										   walker, context))
					return true;
			}
			break;

		case T_IntList:
		case T_OidList:

			/*
			 * Note that expression_tree_walker handles T_List but not these.
			 * No contained stuff, so just succeed.
			 */
			break;

		case T_ModifyTable:
			if (walk_plan_node_fields((Plan *) node, walker, context))
				return true;
			if (walker((Node *) ((ModifyTable *) node)->plans, context))
				return true;
			if (walker((Node *) ((ModifyTable *) node)->withCheckOptionLists, context))
				return true;
			if (walker((Node *) ((ModifyTable *) node)->onConflictSet, context))
				return true;
			if (walker((Node *) ((ModifyTable *) node)->onConflictWhere, context))
				return true;
			if (walker((Node *) ((ModifyTable *) node)->returningLists, context))
				return true;

			break;

		case T_LockRows:
			if (walk_plan_node_fields((Plan *) node, walker, context))
				return true;
			break;

		case T_SplitUpdate:
		case T_AssertOp:
			if (walk_plan_node_fields((Plan *) node, walker, context))
				return true;
			break;

			/*
			 * Query nodes are handled by the Postgres query_tree_walker. We
			 * just use it without setting any ignore flags.  The caller must
			 * handle query nodes specially to get other behavior, e.g. by
			 * calling query_tree_walker directly.
			 */
		case T_Query:
			return query_tree_walker((Query *) node, walker, context, 0);

			/*
			 * The following cases are handled by expression_tree_walker.  In
			 * addition, we let expression_tree_walker handle unrecognized
			 * nodes.
			 *
			 * TODO: Identify node types that should never appear in plan trees
			 * and disallow them here by issuing an error or asserting false.
			 */
		case T_Var:
		case T_Const:
		case T_Param:
		case T_CoerceToDomainValue:
		case T_CaseTestExpr:
		case T_SetToDefault:
		case T_CurrentOfExpr:
		case T_RangeTblRef:
		case T_Aggref:
		case T_ArrayRef:
		case T_FuncExpr:
		case T_OpExpr:
		case T_DistinctExpr:
		case T_ScalarArrayOpExpr:
		case T_BoolExpr:
		case T_SubLink:
		case T_FieldSelect:
		case T_FieldStore:
		case T_RelabelType:
		case T_CaseExpr:
		case T_ArrayExpr:
		case T_RowExpr:
		case T_CoalesceExpr:
		case T_NullIfExpr:
		case T_NullTest:
		case T_BooleanTest:
		case T_CoerceToDomain:
		case T_TargetEntry:
		case T_List:
		case T_FromExpr:
		case T_JoinExpr:
		case T_SetOperationStmt:
		case T_SpecialJoinInfo:
		case T_TableValueExpr:
		case T_PartSelectedExpr:
		case T_PartDefaultExpr:
		case T_PartBoundExpr:
		case T_PartBoundInclusionExpr:
		case T_PartBoundOpenExpr:
		case T_PartListRuleExpr:
		case T_PartListNullTestExpr:

		default:
			return expression_tree_walker(node, walker, context);
	}
	return false;
}

/* Return the plan associated with a SubPlan node in a walker.  (This is used by
 * framework, not by users of the framework.)
 */
Plan *plan_tree_base_subplan_get_plan(plan_tree_base_prefix *base, SubPlan *subplan)
{
	if (!base)
		return NULL;
	else if (IsA(base->node, PlannedStmt))
		return exec_subplan_get_plan((PlannedStmt*)base->node, subplan);
	else if (IsA(base->node, PlannerInfo))
		return planner_subplan_get_plan((PlannerInfo*)base->node, subplan);
	else if (IsA(base->node, PlannerGlobal))
	{
		PlannerInfo rootdata;
		rootdata.glob = (PlannerGlobal*)base->node;
		return planner_subplan_get_plan(&rootdata, subplan);
	}
	Insist(false);
	return NULL;
}

/* Rewrite the plan associated with a SubPlan node in a mutator.  (This is used by
 * framework, not by users of the framework.)
 */
void plan_tree_base_subplan_put_plan(plan_tree_base_prefix *base, SubPlan *subplan, Plan *plan)
{
	Assert(base);
	if (IsA(base->node, PlannedStmt))
	{
		exec_subplan_put_plan((PlannedStmt*)base->node, subplan, plan);
		return;
	}
	else if (IsA(base->node, PlannerInfo))
	{
		planner_subplan_put_plan((PlannerInfo*)base->node, subplan, plan);
		return;
	}
	Assert(false && "Must provide relevant base info.");
}

/**
 * These are helpers to retrieve nodes from plans.
 */
typedef struct extract_context
{
	plan_tree_base_prefix base; /* Required prefix for plan_tree_walker/mutator */
 	bool descendIntoSubqueries;
	NodeTag  nodeTag;
	List *nodes;
} extract_context;

static bool extract_nodes_walker(Node *node, extract_context *context);
static bool extract_nodes_expression_walker(Node *node, extract_context *context);

/**
 * Extract nodes with specific tag.
 */
List *extract_nodes(PlannerGlobal *glob, Node *node, int nodeTag)
{
	extract_context context;
	context.base.node = (Node *) glob;
	context.nodes = NULL;
	context.nodeTag = nodeTag;
	context.descendIntoSubqueries = false;
	extract_nodes_walker(node, &context);
	return context.nodes;
}

/**
 * Extract nodes with specific tag.
 * Same as above, but starts off a Plan node rather than a PlannedStmt
 *
 */
List *extract_nodes_plan(Plan *pl, int nodeTag, bool descendIntoSubqueries)
{
	extract_context context;
	Assert(pl);
	context.base.node = NULL;
	context.nodes = NULL;
	context.nodeTag = nodeTag;
	context.descendIntoSubqueries = descendIntoSubqueries;
	extract_nodes_walker((Node *)pl, &context);
	return context.nodes;
}

static bool
extract_nodes_walker(Node *node, extract_context *context)
{
	if (node == NULL)
		return false;
	if (nodeTag(node) == context->nodeTag)
	{
		context->nodes = lappend(context->nodes, node);
	}
	if (nodeTag(node) == T_SubPlan)
	{
		SubPlan	   *subplan = (SubPlan *) node;

		/*
		 * SubPlan has both of expressions and subquery.  In case the caller wants
		 * non-subquery version, still we need to walk through its expressions.
		 * NB: Since we're not going to descend into SUBPLANs anyway (see below),
		 * look at the SUBPLAN node here, even if descendIntoSubqueries is false
		 * lest we miss some nodes there.
		 */
		if (extract_nodes_walker((Node *) subplan->testexpr,
								 context))
			return true;
		if (expression_tree_walker((Node *) subplan->args,
								   extract_nodes_walker, context))
			return true;

		/*
		 * Do not descend into subplans.
		 * Even if descendIntoSubqueries indicates the caller wants to descend into
		 * subqueries, SubPlan seems special; Some partitioning code assumes this
		 * should return immediately without descending.  See MPP-17168.
		 */
		return false;
	}
	if (nodeTag(node) == T_SubqueryScan
		&& !context->descendIntoSubqueries)
	{
		/* Do not descend into subquery scans. */
		return false;
	}
	if (nodeTag(node) == T_TableFunctionScan
		&& !context->descendIntoSubqueries)
	{
		/* Do not descend into table function subqueries */
		return false;
	}

	return plan_tree_walker(node, extract_nodes_walker,
							(void *) context,
							true);
}

/**
 * Extract nodes with specific tag.
 * Same as above, but starts off a scalar expression node rather than a PlannedStmt
 *
 */
List *extract_nodes_expression(Node *node, int nodeTag, bool descendIntoSubqueries)
{
	extract_context context;
	Assert(node);
	context.base.node = NULL;
	context.nodes = NULL;
	context.nodeTag = nodeTag;
	context.descendIntoSubqueries = descendIntoSubqueries;
	extract_nodes_expression_walker(node, &context);

	return context.nodes;
}

static bool
extract_nodes_expression_walker(Node *node, extract_context *context)
{
	if (NULL == node)
	{
		return false;
	}

	if (nodeTag(node) == context->nodeTag)
	{
		context->nodes = lappend(context->nodes, node);
	}

	if (nodeTag(node) == T_Query && context->descendIntoSubqueries)
	{
		Query *query = (Query *) node;
		if (expression_tree_walker((Node *)query->targetList, extract_nodes_expression_walker, (void *) context))
		{
			return true;
		}

		if (query->jointree != NULL &&
		   expression_tree_walker(query->jointree->quals, extract_nodes_expression_walker, (void *) context))
		{
			return true;
		}

		return expression_tree_walker(query->havingQual, extract_nodes_expression_walker, (void *) context);
	}

	return expression_tree_walker(node, extract_nodes_expression_walker, (void *) context);
}

/**
 * These are helpers to find node in queries
 */
typedef struct find_nodes_context
{
	List *nodeTags;
	int foundNode;
} find_nodes_context;

static bool find_nodes_walker(Node *node, find_nodes_context *context);

/**
 * Looks for nodes that belong to the given list.
 * Returns the index of the first such node that it encounters, or -1 if none
 */
int find_nodes(Node *node, List *nodeTags)
{
	find_nodes_context context;
	Assert(NULL != node);
	context.nodeTags = nodeTags;
	context.foundNode = -1;
	find_nodes_walker(node, &context);

	return context.foundNode;
}

static bool
find_nodes_walker(Node *node, find_nodes_context *context)
{
	if (NULL == node)
	{
		return false;
	}

	if (IsA(node, Query))
	{
		/* Recurse into subselects */
		return query_tree_walker((Query *) node, find_nodes_walker, (void *) context, 0 /* flags */);
	}

	ListCell *lc;
	int i = 0;
	foreach(lc, context->nodeTags)
	{
		NodeTag nodeTag = (NodeTag) lfirst_int(lc);
		if (nodeTag(node) == nodeTag)
		{
			context->foundNode = i;
			return true;
		}

		i++;
	}

	return expression_tree_walker(node, find_nodes_walker, (void *) context);
}

/**
 * GPDB_91_MERGE_FIXME: collation
 * Look for nodes with non-default collation; return 1 if any exist, -1
 * otherwise.
 */
typedef struct check_collation_context
{
	int foundNonDefaultCollation;
} check_collation_context;

static bool check_collation_walker(Node *node, check_collation_context *context);

int check_collation(Node *node)
{
	check_collation_context context;
	Assert(NULL != node);
	context.foundNonDefaultCollation = -1;
	check_collation_walker(node, &context);

	return context.foundNonDefaultCollation;
}

static void
check_collation_in_list(List *colllist, check_collation_context *context)
{
	ListCell *lc;
	foreach (lc, colllist)
	{
		Oid coll = lfirst_oid(lc);
		if (InvalidOid != coll && DEFAULT_COLLATION_OID != coll)
		{
			context->foundNonDefaultCollation = 1;
			break;
		}
	}
}

static bool
check_collation_walker(Node *node, check_collation_context *context)
{
	Oid collation, inputCollation;

	if (NULL == node)
	{
		return false;
	}

	if (IsA(node, Query))
	{
		/* Recurse into subselects */
		return query_tree_walker((Query *) node, check_collation_walker, (void *) context, 0 /* flags */);
	}

	switch (nodeTag(node))
	{
		case T_Var:
		case T_Const:
		case T_OpExpr:
		case T_ScalarArrayOpExpr:
		case T_DistinctExpr:
		case T_BoolExpr:
		case T_BooleanTest:
		case T_CaseExpr:
		case T_CaseTestExpr:
		case T_CoalesceExpr:
		case T_MinMaxExpr:
		case T_FuncExpr:
		case T_Aggref:
		case T_WindowFunc:
		case T_NullTest:
		case T_NullIfExpr:
		case T_RelabelType:
		case T_CoerceToDomain:
		case T_CoerceViaIO:
		case T_ArrayCoerceExpr:
		case T_SubLink:
		case T_ArrayExpr:
		case T_ArrayRef:
		case T_RowExpr:
		case T_RowCompareExpr:
		case T_FieldSelect:
		case T_FieldStore:
		case T_CoerceToDomainValue:
		case T_CurrentOfExpr:
		case T_NamedArgExpr:
		case T_ConvertRowtypeExpr:
		case T_CollateExpr:
		case T_TableValueExpr:
		case T_XmlExpr:
		case T_SetToDefault:
		case T_PlaceHolderVar:
		case T_Param:
		case T_SubPlan:
		case T_AlternativeSubPlan:
		case T_GroupingFunc:
		case T_DMLActionExpr:
		case T_PartBoundExpr:
			collation = exprCollation(node);
			inputCollation = exprInputCollation(node);
			if ((InvalidOid != collation && DEFAULT_COLLATION_OID != collation) ||
				(InvalidOid != inputCollation && DEFAULT_COLLATION_OID != inputCollation))
			{
				context->foundNonDefaultCollation = 1;
			}
			break;
		case T_CollateClause:
			/* unsupported */
			context->foundNonDefaultCollation = 1;
			break;
		case T_ColumnDef:
			collation = ((ColumnDef *) node)->collOid;
			if (InvalidOid != collation && DEFAULT_COLLATION_OID != collation)
			{
				context->foundNonDefaultCollation = 1;
			}
			break;
		case T_IndexElem:
			if (NIL != ((IndexElem *) node)->collation)
			{
				context->foundNonDefaultCollation = 1;
			}
			break;
		case T_RangeTblEntry:
			check_collation_in_list(((RangeTblEntry *) node)->values_collations, context);
			check_collation_in_list(((RangeTblEntry *) node)->ctecolcollations, context);
			break;
		case T_RangeTblFunction:
			check_collation_in_list(((RangeTblFunction *) node)->funccolcollations, context);
			break;
		case T_CommonTableExpr:
			check_collation_in_list(((CommonTableExpr *) node)->ctecolcollations, context);
			break;
		case T_SetOperationStmt:
			check_collation_in_list(((SetOperationStmt *) node)->colCollations, context);
			break;
		default:
			/* make compiler happy */
			break;
	}

	if (context->foundNonDefaultCollation == 1)
	{
		/* end recursion */
		return true;
	}
	else
	{
		return expression_tree_walker(node, check_collation_walker, (void *) context);
	}
}


text:
package be.jvb.ipv6;

import org.junit.Test;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Random;

import static be.jvb.ipv6.IPv6Address.fromInetAddress;
import static be.jvb.ipv6.IPv6Address.fromString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/**
 * @author Jan Van Besien
 */
public class IPv6AddressTest
{
    @Test
    public void parseFromAllZeroes()
    {
        assertEquals("::", fromString("0000:0000:0000:0000:0000:0000:0000:0000").toString());
    }

    @Test
    public void parseFromAllZeroesShortNotation()
    {
        assertEquals("::", fromString("::").toString());
    }

    @Test
    public void parseSomeRealAddresses()
    {
        assertEquals("::1", fromString("0000:0000:0000:0000:0000:0000:0000:0001").toString());
        assertEquals("::1:0", fromString("0000:0000:0000:0000:0000:0000:0001:0000").toString());
        assertEquals("1::1:0:0:0", fromString("0001:0000:0000:0000:0001:0000:0000:0000").toString());
        assertEquals("::ffff", fromString("0000:0000:0000:0000:0000:0000:0000:ffff").toString());
        assertEquals("ffff::", fromString("ffff:0000:0000:0000:0000:0000:0000:0000").toString());
        assertEquals("2001:db8:85a3::8a2e:370:7334", fromString("2001:0db8:85a3:0000:0000:8a2e:0370:7334").toString());
    }

    @Test
    public void parseSomeRealAddressesShortNotation()
    {
        assertEquals("::1", fromString("::1").toString());
        assertEquals("::1:0", fromString("::1:0").toString());
        assertEquals("1::1:0:0:0", fromString("1::1:0:0:0").toString());
        assertEquals("::ffff", fromString("::ffff").toString());
        assertEquals("ffff::", fromString("ffff::").toString());
        assertEquals("2001:db8:85a3::8a2e:370:7334", fromString("2001:db8:85a3::8a2e:370:7334").toString());
    }

    @Test(expected = IllegalArgumentException.class)
    public void parseInvalid_1()
    {
        fromString(":");
    }

    @Test(expected = IllegalArgumentException.class)
    public void parseInvalid_2()
    {
        fromString(":a");
    }

    @Test(expected = IllegalArgumentException.class)
    public void parseInvalidTooShort_1()
    {
        fromString("a:");
    }

    @Test(expected = IllegalArgumentException.class)
    public void parseInvalidTooShort_2()
    {
        fromString("a:a:");
    }

    @Test(expected = IllegalArgumentException.class)
    public void parseInvalidTooLong()
    {
        fromString("a:a:a:a:a:a:a:a:a:a:a:a");
    }

    @Test
    public void constructFromInet6Address() throws UnknownHostException
    {
        final InetAddress inetAddress = Inet6Address.getByName("2001:0db8:85a3:0000:0000:8a2e:0370:7334");
        assertEquals("2001:db8:85a3::8a2e:370:7334", fromInetAddress(inetAddress).toString());
    }

    @Test
    public void convertToInet6Address() throws UnknownHostException
    {
        final InetAddress inetAddress = Inet6Address.getByName("2001:0db8:85a3:0000:0000:8a2e:0370:7334");
        assertEquals(inetAddress, fromString("2001:0db8:85a3:0000:0000:8a2e:0370:7334").toInetAddress());
    }

    @Test
    public void toStringCanBeUsedInFromStringAndViceVersa()
    {
        final int nTests = 10000;
        final Random rg = new Random();

        for (int i = 0; i < nTests; i++)
        {
            final IPv6Address address = new IPv6Address(rg.nextLong(), rg.nextLong());
            assertEquals(address, fromString(address.toString()));
        }
    }

    @Test
    public void addition()
    {
        assertEquals(fromString("::2"), fromString("::1").add(1));
        assertEquals(fromString("::1:0:0:0"), fromString("::ffff:ffff:ffff").add(1));
        assertEquals(fromString("::1:0:0:0:0"), fromString("::ffff:ffff:ffff:ffff").add(1));
        assertEquals(fromString("::1:0:0:0:1"), fromString("::ffff:ffff:ffff:ffff").add(2));
        assertEquals(fromString("::").add(Integer.MAX_VALUE).add(Long.MAX_VALUE), fromString("::").add(Long.MAX_VALUE).add(
                Integer.MAX_VALUE));
    }

    @Test
    public void additionOverflow()
    {
        assertEquals(fromString("::"), fromString("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff").add(1));
    }

    @Test
    public void subtraction()
    {
        assertEquals(fromString("::1"), fromString("::2").subtract(1));
        assertEquals(fromString("::ffff:ffff:ffff:ffff"), fromString("::0001:0:0:0:0").subtract(1));
        assertEquals(fromString("::ffff:ffff:ffff:fffe"), fromString("::0001:0:0:0:0").subtract(2));
        assertEquals(fromString("::").subtract(Integer.MAX_VALUE).subtract(Long.MAX_VALUE), fromString("::").subtract(
                Long.MAX_VALUE).subtract(
                Integer.MAX_VALUE));
    }

    @Test
    public void subtractionVersusAdditionWithRandomAddresses()
    {
        final Random random = new Random();
        final long randomLong = random.nextLong();
        final IPv6Address randomAddress = new IPv6Address(random.nextLong(), random.nextLong());
        assertEquals(randomAddress, randomAddress.add(randomLong).subtract(randomLong));
    }

    @Test
    public void subtractionVersusAdditionCornerCases()
    {
        final Random random = new Random();
        final IPv6Address randomAddress = new IPv6Address(random.nextLong(), random.nextLong());
        assertEquals(randomAddress, randomAddress.add(Integer.MAX_VALUE).subtract(Integer.MAX_VALUE));
        assertEquals(randomAddress, randomAddress.add(Integer.MIN_VALUE).subtract(Integer.MIN_VALUE));
        assertEquals(randomAddress, randomAddress.add(Long.MAX_VALUE).subtract(Long.MAX_VALUE));
        assertEquals(randomAddress, randomAddress.add(Long.MIN_VALUE).subtract(Long.MIN_VALUE));
    }

    @Test
    public void subtractionUnderflow()
    {
        assertEquals(fromString("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"), fromString("::").subtract(1));
    }

    @Test
    public void compare()
    {
        assertTrue(0 == fromString("::").compareTo(fromString("::")));
        assertTrue(0 > fromString("::").compareTo(fromString("::1")));
        assertTrue(0 < fromString("::1").compareTo(fromString("::")));

        assertTrue(0 > fromString("::").compareTo(fromString("::ffff:ffff:ffff:ffff")));
        assertTrue(0 > fromString("::efff:ffff:ffff:ffff").compareTo(fromString("::ffff:ffff:ffff:ffff")));
        assertTrue(0 > fromString("efff:ffff:ffff:ffff:0:1:2:3").compareTo(fromString("ffff:ffff:ffff:ffff:4:5:6:7")));
    }

    @Test
    public void maskWithPrefixLength()
    {
        assertEquals(fromString("2001:0db8:85a3:0000:0000:8a2e:0370:7334"),
                     fromString("2001:0db8:85a3:0000:0000:8a2e:0370:7334").maskWithPrefixLength(128));
        assertEquals(fromString("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ff00"),
                     fromString("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff").maskWithPrefixLength(120));
        assertEquals(fromString("2001:0db8:85a3:0000:0000:8a2e:0370:7300"),
                     fromString("2001:0db8:85a3:0000:0000:8a2e:0370:7334").maskWithPrefixLength(120));
        assertEquals(fromString("2001:0db8:85a3::"), fromString("2001:0db8:85a3:0000:0000:8a2e:0370:7334").maskWithPrefixLength(64));
        assertEquals(fromString("2000::"), fromString("2001:0db8:85a3:0000:0000:8a2e:0370:7334").maskWithPrefixLength(15));
        assertEquals(fromString("8000::"),
                     fromString("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff").maskWithPrefixLength(1));
    }

    @Test
    public void maximumAddressWithPrefixLength()
    {
        assertEquals(fromString("2001:0db8:85a3:0000:0000:8a2e:0370:7334"),
                     fromString("2001:0db8:85a3:0000:0000:8a2e:0370:7334").maximumAddressWithPrefixLength(128));
        assertEquals(fromString("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"),
                     fromString("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ff00").maximumAddressWithPrefixLength(120));
        assertEquals(fromString("2001:0db8:85a3:0000:0000:8a2e:0370:73ff"),
                     fromString("2001:0db8:85a3:0000:0000:8a2e:0370:7300").maximumAddressWithPrefixLength(120));
        assertEquals(fromString("2001:0db8:85a3:0000:ffff:ffff:ffff:ffff"),
                     fromString("2001:0db8:85a3:0000:0000:8a2e:0370:7334").maximumAddressWithPrefixLength(64));
        assertEquals(fromString("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"),
                     fromString("8000::").maximumAddressWithPrefixLength(1));
        assertEquals(fromString("7fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"),
                     fromString("7fff::").maximumAddressWithPrefixLength(1));
    }

    @Test
    public void numberOfTrailingOnes()
    {
        assertEquals(0, fromString("::").numberOfTrailingOnes());
        assertEquals(1, fromString("::1").numberOfTrailingOnes());
        assertEquals(4, fromString("::f").numberOfTrailingOnes());

        final IPv6Address addressWithLowBitsEqualToLongMaxValue = fromString("::7fff:ffff:ffff:ffff");
        assertEquals(Long.MAX_VALUE, addressWithLowBitsEqualToLongMaxValue.getLowBits());
        assertEquals(63, addressWithLowBitsEqualToLongMaxValue.numberOfTrailingOnes());
    }

}


text:
from HQMFIntervalUtil import HQMFIntervalUtil
import sqlparse

def strip_quotes(s):
    if (isinstance(s, str) and
        len(s) > 0 and
        s[0] == '"' and
        s[-1]) == '"':
        return s[1:-1]
    else:
        return s

def strip_all_quotes(s):
    if not isinstance(s, str):
        return s
    while len(s) > 0 and s[0] in ('"', "'") and s[-1] == s[0]:
        s = s[1:-1]
    return s

def string_to_boolean(sval):
    sval = strip_quotes(sval)
    if sval == 'true':
        return True
    if sval == 'false':
        return False
    elif sval == 'null':
        return  None
    else:
        raise ValueError("bad value for cname : " + str(sval))

def sql_to_string(sql, pretty=False):
    result=str(sql.compile(compile_kwargs={"literal_binds": True}, dialect=HQMFIntervalUtil.get_dialect()))
    if pretty:
        result=sqlparse.format(result, reindent=True)
    return result


text:
{% extends "layout.html" %}
{% block title %}
    Members
{% endblock %}

{% block main %}

This is the Members only page.

You are logged in... SHHHHHHHH!

{% endblock %}


text:
#ifndef _MITK_SPLINE_VTK_MAPPER_3D__H
#define _MITK_SPLINE_VTK_MAPPER_3D__H

#include "mitkPointSetVtkMapper3D.h"
#include "MitkMapperExtExports.h"

class vtkActor;
class vtkAssembly;

namespace mitk
{
  //##Documentation
  //## @brief Vtk-based mapper for Splines
  //##
  //## properties looked for:
  //## "line width" = with of the spline
  //## @ingroup Mapper

  /************************************************************************/
  /*
  *   - \b "line width": (FloatProperty) line width of the spline

  */
  /************************************************************************/
class MitkMapperExt_EXPORT SplineVtkMapper3D : public PointSetVtkMapper3D
{
public:

    mitkClassMacro( SplineVtkMapper3D, PointSetVtkMapper3D );

    itkFactorylessNewMacro(Self)
    itkCloneMacro(Self)

    virtual vtkProp* GetVtkProp(mitk::BaseRenderer *renderer);
    virtual void UpdateVtkTransform(mitk::BaseRenderer *renderer);

    bool SplinesAreAvailable();

    vtkPolyData* GetSplinesPolyData();

    vtkActor* GetSplinesActor();

    virtual void UpdateSpline();

    itkSetMacro( SplineResolution, unsigned int );

    itkGetMacro( SplineResolution, unsigned int );

protected:

    SplineVtkMapper3D();

    virtual ~SplineVtkMapper3D();

    virtual void GenerateDataForRenderer(mitk::BaseRenderer * renderer);

    virtual void ApplyAllProperties(BaseRenderer *renderer, vtkActor *actor);

    vtkActor* m_SplinesActor;

    vtkPropAssembly* m_SplineAssembly;

    bool m_SplinesAvailable;

    bool m_SplinesAddedToAssembly;

    unsigned int m_SplineResolution;

    itk::TimeStamp m_SplineUpdateTime;
};

} //namespace mitk

#endif


text:
package org.commonjava.emb.internal.plexus.fixture;

import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;

@Component( role = SingletonLiteralOwner.class )
public class SingletonLiteralOwner
{

    @Requirement( role = Child.class, hint = "simple_" )
    private Child singletonLiteral;

    public Child singletonLiteral()
    {
        return singletonLiteral;
    }

}


text:
@interface LogInBindIphoneViewController : XSViewController{
    NSMutableArray *arrayUserBuindNumber;//用来保存用户绑定的手机号
}
@property(nonatomic,retain) NSString *userName;
@property(nonatomic,retain) NSString *password;
@property(nonatomic,retain) NSString *deviceId;
@property(nonatomic, retain) NSString *numberPhone;
@property(nonatomic,copy)NSString  *userPowerString;

@end


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UDBase.UI.Common;

public class ModeSelectButton : ActionButton {

	public GameMode Mode;

	public override bool IsVisible() {
		return true;
	}

	public override bool IsInteractable() {
		return true;
	}

	public override void OnClick() {
		Game.SelectMode(Mode);
	}
}


text:
/// <reference path="../../node.d.ts" />

export = HttpRequestedRangeNotSatisfiableException;

import HttpException = require('./HttpException');

'use strict';

/**
 * HTTPエラー。Requested Range Not Satisfiable.
 */
class HttpRequestedRangeNotSatisfiableException extends HttpException {

	/**
	 * @constructor
	 * @public
	 * @param {number} status
	 * @param {string} code=null
	 * @param {string} message=""
	 */
	constructor(status:number, code:string=null, message:string="") {
		super(status, code, message == null || message == "" ? "HTTPエラー。Requested Range Not Satisfiable." : message);
	}

}


text:
About

At Submerge, you will dive deeper into:

College

Deciding where to attend college is one of the most important decisions you're going to make.

We would love for every student to consider attending a Bible college; for valuable preparation to further God's Kingdom in a ministry career, or to gain a foundation for future studies.

Come submerge yourself in SLCC's campus to get a taste of what Bible college is all about.

City

We LOVE our city! And we think you will too.

We will spend a portion of Saturday working on a project in the city with LOVEtheLOU, and learn how they fulfill their mission:

"Where there is nothing we will create.
Where there is brokenness we will heal.
Where there is good we will join."

Come submerge yourself in the city of St. Louis as we partner with local organization, LOVEtheLOU, founded by 2003 graduate, Lucas Rouggly.

Christ

At the center of everything is Christ.

This is a time of year when the passion and excitement which was cultivated over the summer can easily be overshadowed by the struggles of day-to-day life. We want to help you bring your focus back onto Christ.

Come submerge yourself in Christ and be taught, challenged, and used to further His Kindom.

Join

us at

Submerge!


text:
import logging
import unittest

import environment
import keyspace_util
import utils

from vtproto import query_pb2

from vtdb import vtgate_client

shard_0_master = None
shard_1_master = None
lookup_master = None

keyspace_env = None

create_sharded_message = '''create table sharded_message(
time_scheduled bigint,
id bigint,
time_next bigint,
epoch bigint,
time_created bigint,
time_acked bigint,
message varchar(128),
primary key(time_scheduled, id),
unique index id_idx(id),
index next_idx(time_next, epoch)
) comment 'vitess_message,vt_ack_wait=1,vt_purge_after=3,vt_batch_size=2,vt_cache_size=10,vt_poller_interval=1'
'''

create_unsharded_message = '''create table unsharded_message(
time_scheduled bigint,
id bigint,
time_next bigint,
epoch bigint,
time_created bigint,
time_acked bigint,
message varchar(128),
primary key(time_scheduled, id),
unique index id_idx(id),
index next_idx(time_next, epoch)
) comment 'vitess_message,vt_ack_wait=1,vt_purge_after=3,vt_batch_size=2,vt_cache_size=10,vt_poller_interval=1'
'''

vschema = {
    'user': '''{
      "sharded": true,
      "vindexes": {
        "hash_index": {
          "type": "hash"
        }
      },
      "tables": {
        "sharded_message": {
          "column_vindexes": [
            {
              "column": "id",
              "name": "hash_index"
            }
          ]
        }
      }
    }''',
    'lookup': '''{
      "sharded": false,
      "tables": {
        "unsharded_message": {
          "type": "sequence"
        }
      }
    }''',
}

def setUpModule():
  global keyspace_env
  global shard_0_master
  global shard_1_master
  global lookup_master
  logging.debug('in setUpModule')

  try:
    environment.topo_server().setup()
    logging.debug('Setting up tablets')
    keyspace_env = keyspace_util.TestEnv()
    keyspace_env.launch(
        'user',
        shards=['-80', '80-'],
        ddls=[
            create_sharded_message,
            ],
        )
    keyspace_env.launch(
        'lookup',
        ddls=[
            create_unsharded_message,
            ],
        )
    shard_0_master = keyspace_env.tablet_map['user.-80.master']
    shard_1_master = keyspace_env.tablet_map['user.80-.master']
    lookup_master = keyspace_env.tablet_map['lookup.0.master']

    utils.apply_vschema(vschema)
    utils.VtGate().start(
        tablets=[shard_0_master, shard_1_master, lookup_master])
    utils.vtgate.wait_for_endpoints('user.-80.master', 1)
    utils.vtgate.wait_for_endpoints('user.80-.master', 1)
    utils.vtgate.wait_for_endpoints('lookup.0.master', 1)
  except:
    tearDownModule()
    raise

def tearDownModule():
  logging.debug('in tearDownModule')
  utils.required_teardown()
  if utils.options.skip_teardown:
    return
  logging.debug('Tearing down the servers and setup')
  if keyspace_env:
    keyspace_env.teardown()

  environment.topo_server().teardown()

  utils.kill_sub_processes()
  utils.remove_tmp_files()

def get_connection(timeout=15.0):
  protocol, endpoint = utils.vtgate.rpc_endpoint(python=True)
  try:
    return vtgate_client.connect(protocol, endpoint, timeout)
  except Exception:
    logging.exception('Connection to vtgate (timeout=%s) failed.', timeout)
    raise

class TestMessaging(unittest.TestCase):

  def test_sharded(self):
    self._test_messaging('sharded_message', 'user')

  def test_unsharded(self):
    self._test_messaging('unsharded_message', 'lookup')

  def _test_messaging(self, name, keyspace):
    vtgate_conn = get_connection()
    cursor = vtgate_conn.cursor(
        tablet_type='master', keyspace=None, writable=True)

    query = 'insert into %s(id, message) values(:id, :message)'%(name)
    cursor.begin()
    # If sharded, these will go to two different shards.
    # If unsharded, they'll both be sent as a batch, but there's
    # no way to verify this because the vtgate_conn API abstracts
    # that part out and issues only one row at a time. However,
    # there are unit tests for that part.
    cursor.execute(query, {'id': 1, 'message': 'hello world 1'})
    cursor.execute(query, {'id': 4, 'message': 'hello world 4'})
    cursor.commit()

    (it, fields) = vtgate_conn.message_stream(
        keyspace, name)
    self.assertEqual(
        fields,
        [
          ('id', query_pb2.INT64),
          ('time_scheduled', query_pb2.INT64),
          ('message', query_pb2.VARCHAR),
        ])

    # We should get both messages.
    result = {}
    for _ in xrange(2):
      row = it.next()
      result[row[0]] = row[2]
    self.assertEqual(result, {1: 'hello world 1', 4: 'hello world 4'})

    # After ack, we should get only one message.
    count = vtgate_conn.message_ack(name, [4])
    self.assertEqual(count, 1)
    result = {}
    for _ in xrange(2):
      row = it.next()
      result[row[0]] = row[2]
    self.assertEqual(result, {1: 'hello world 1'})
    # Only one should be acked.
    count = vtgate_conn.message_ack(name, [1, 4])
    self.assertEqual(count, 1)

if __name__ == '__main__':
  utils.main()


text:
package cbedoy.amazingviews.gui.view.category;

import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

import cbedoy.amazingviews.R;
import cbedoy.amazingviews.domain.Category;
import cbedoy.amazingviews.domain.CategoryItem;
import cbedoy.amazingviews.gui.view.adapter.CategoryGridAdapter;

/**
 * A MainCategoryView is a FrameLayout and used to show and animate each category, it has a GridView
 * that shows each "shop item".
 * @author Par Amsen, www.trixigt.com
 *
 */
public class MainCategoryView extends FrameLayout{
    protected static final String TAG = "MainCategoryView";
    private View container;
    private Category currentCategory;
    private GridView gridView;
    private CategoryGridAdapter adapter;
    private FrameLayout contentContainer;

    private View viewItemContainer;

    private int systemShortAnimTime;
    private boolean animateClipping = false;

    private Rect rect;

    private View currentCategoryItemInGrid;

    private View currentMainMenuCategoryView;

    private View root;
    private DisplayMetrics dm;
    private ImageView navigationImageView;

    public MainCategoryView(Context context, View root) {
        super(context);
        init(context, root);
    }

    public void init(final Context context, View root) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.main_category, this, true);
        this.root = root;
        dm = context.getResources().getDisplayMetrics();
        systemShortAnimTime = context.getResources().getInteger(android.R.integer.config_shortAnimTime);

        gridView = (GridView) findViewById(R.id.grid_main_category);
        adapter = new CategoryGridAdapter(context, new ArrayList<CategoryItem>());
        container = findViewById(R.id.container_main_category);
        contentContainer = (FrameLayout) findViewById(R.id.container_main_category_content);

        viewItemContainer = contentContainer.findViewById(R.id.container_main_category_item_showed);

        gridView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View v, int position,
                                    long id) {
                if(currentCategoryItemInGrid == null) {
                    viewCategoryItem(context, v, currentCategory.getItems().get(position));
                }
            }
        });

        navigationImageView = (ImageView) container.findViewById(R.id.img_main_category_navigation);

        navigationImageView.setOnClickListener( new OnClickListener() {

            @Override
            public void onClick(View v) {
                if(currentCategoryItemInGrid != null) {
                    closeCategoryItem();
                    switchNavigationIcon(getResources().getDrawable(R.drawable.ico_home));
                } else {
                    switchNavigationIcon(getResources().getDrawable(R.drawable.ico_home));
                    playOutro();
                }
            }
        });
    }

    /**
     * Switch the top navigation icon with a rotation transition.
     * @param icon
     */
    private void switchNavigationIcon(final Drawable icon) {
        AnimatorSet set = new AnimatorSet();

        ObjectAnimator rotateIn = ObjectAnimator.ofFloat(navigationImageView, View.ROTATION_Y, 0, 90);
        ObjectAnimator rotateOut = ObjectAnimator.ofFloat(navigationImageView, View.ROTATION_Y, 90, 0);

        rotateIn.setInterpolator(new AccelerateInterpolator());
        rotateOut.setInterpolator(new DecelerateInterpolator());

        rotateIn.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                navigationImageView.setImageDrawable(icon);
            }
        });

        set.playSequentially(rotateIn, rotateOut);
        set.setDuration(systemShortAnimTime);

        set.start();
    }

    /**
     * Expands a "shop item" in the grid.
     * @param context
     * @param itemInGrid
     * @param item
     */
    public void viewCategoryItem(Context context, View itemInGrid, CategoryItem item) {
        //check so that a CategoryItem isn't already being viewed
        if(currentCategoryItemInGrid == null) {
            switchNavigationIcon(getResources().getDrawable(R.drawable.ico_back));

            //assigned the clicked item to be able to retrieve it later
            currentCategoryItemInGrid = itemInGrid;

            viewItemContainer.setVisibility(View.VISIBLE);

            final TextView title = (TextView) viewItemContainer.findViewById(R.id.txt_main_category_item_title);
            final TextView price = (TextView) viewItemContainer.findViewById(R.id.txt_main_category_item_price);
            final View purchase = viewItemContainer.findViewById(R.id.txt_main_category_item_purchase);
            final ImageView image = (ImageView) viewItemContainer.findViewById(R.id.img_main_category_item_showed);

            title.setText(item.getTitle());
            price.setText(item.getPrice());
            image.setImageDrawable(item.getIcon());

            title.setY(title.getY()+50);
            price.setY(price.getY()+50);
            purchase.setY(purchase.getY()+50);

            title.setAlpha(0f);
            price.setAlpha(0f);
            purchase.setAlpha(0f);
            viewItemContainer.setAlpha(0f);

            gridView.setAlpha(1);

            gridView.animate().alpha(0f).setDuration(systemShortAnimTime).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    gridView.setVisibility(View.GONE);
                    title.animate().alpha(1f).setStartDelay(30).setDuration(systemShortAnimTime).start();
                    price.animate().alpha(1f).setStartDelay(30).setDuration(systemShortAnimTime).start();
                    purchase.animate().alpha(1f).setStartDelay(30).setDuration(systemShortAnimTime).start();

                    viewItemContainer.animate().alpha(1f).setDuration(systemShortAnimTime).start();

                    title.animate().yBy(-50).setStartDelay(30).setDuration(systemShortAnimTime).start();
                    price.animate().yBy(-50).setStartDelay(30).setDuration(systemShortAnimTime).start();
                    purchase.animate().yBy(-50).setStartDelay(30).setDuration(systemShortAnimTime).start();
                }
            }).start();
        }
    }

    /**
     * Minimize/hide the expanded CategoryItem.
     */
    public void closeCategoryItem() {
        //if a category item is currently being viewed, close it.
        if(currentCategoryItemInGrid != null) {
            switchNavigationIcon(getResources().getDrawable(R.drawable.ico_home));

            gridView.setVisibility(View.VISIBLE);
            gridView.setAlpha(0f);

            final TextView title = (TextView) viewItemContainer.findViewById(R.id.txt_main_category_item_title);
            final TextView price = (TextView) viewItemContainer.findViewById(R.id.txt_main_category_item_price);
            final View purchase = viewItemContainer.findViewById(R.id.txt_main_category_item_purchase);

            title.animate().alpha(0f).setStartDelay(30).setDuration(systemShortAnimTime).start();
            price.animate().alpha(0f).setStartDelay(30).setDuration(systemShortAnimTime).start();
            purchase.animate().alpha(0f).setStartDelay(30).setDuration(systemShortAnimTime).start();

            title.animate().yBy(50).setStartDelay(30).setDuration(systemShortAnimTime).start();
            price.animate().yBy(50).setStartDelay(30).setDuration(systemShortAnimTime).start();
            purchase.animate().yBy(50).setStartDelay(30).setDuration(systemShortAnimTime).start();

            AnimatorSet setGrid = new AnimatorSet();
            setGrid.play(ObjectAnimator.ofFloat(gridView, View.ALPHA, 0f, 1f));
            setGrid.setDuration(systemShortAnimTime);
            setGrid.setStartDelay(30+systemShortAnimTime);
            setGrid.start();

            AnimatorSet set = new AnimatorSet();
            set.play(ObjectAnimator.ofFloat(viewItemContainer, View.ALPHA, 1f, 0f));
            set.setDuration(systemShortAnimTime);
            set.setStartDelay(30+systemShortAnimTime);
            set.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    viewItemContainer.setVisibility(View.GONE);
                    title.setY(title.getY()-50);
                    price.setY(price.getY()-50);
                    purchase.setY(purchase.getY()-50);
                }
            });

            set.start();

            //reset the currently opened category item as it has been closed/hidden.
            currentCategoryItemInGrid = null;
        }
    }

    /**
     * Set which Category to present, changing Category updates the background color and
     * GridView with the new CategoryItems to display.
     * @param category
     * @param mainMenuCategoryView
     */
    public void setCurrentCategory(Category category, View mainMenuCategoryView) {
        adapter.clear();
        adapter.addAll(category.getItems());
        gridView.setAdapter(adapter);

        container.setBackgroundColor(category.getCategoryBackgroundColor());

        currentCategory = category;

        currentMainMenuCategoryView = mainMenuCategoryView;
    }

    /**
     * Play the intro animations/transitions, i.e. expanding the View from the bounds
     * of the clicked button in the main menu, expand the content View from the upper left and
     * perform a cool transition on the Views in the GridView.
     * @param listener
     */
    public void playIntro(AnimatorListener listener) {
        setVisibility(VISIBLE);

        //bounds of the main-menu button to expand from
        final Rect startRect = new Rect();
        //bounds of this View to expand to
        final Rect endRect = new Rect();

        navigationImageView.setAlpha(0f);

        //assign the bounds of the main menu button to startRect
        currentMainMenuCategoryView.getGlobalVisibleRect(startRect);
        //assign bounds of endRect to cover the whole Window area
        endRect.set(0, 0, root.getWidth(), root.getHeight());

        // calculate the offset from the top of the Window, i.e. the ActionBars height.
        int topOffset = dm.heightPixels - root.getMeasuredHeight();

        //assign offset to the startRect to get correct bounds of the main menu button
        // opening this category
        startRect.offset(0, -(topOffset));

        //assign the startRect to the rect used to draw this View in dispatchDraw(Canvas)
        rect = startRect;

        //when animateClipping is true the Rect rect is used to draw this View in dispatchDraw(Canvas)
        animateClipping = true;

        //init objects to perform animations and transitions
        //PropertyValuesHolder holderTop = PropertyValuesHolder.ofInt("top", startRect.top, endRect.top);
        //PropertyValuesHolder holderBottom = PropertyValuesHolder.ofInt("bottom", startRect.bottom, endRect.bottom);

        //final ValueAnimator clipRectAnim = ValueAnimator.ofPropertyValuesHolder(holderTop, holderBottom);
        ObjectAnimator containerAlphaAnim = ObjectAnimator.ofFloat(this, View.ALPHA, 0, 1);
        final ObjectAnimator navigationAlphaAnim = ObjectAnimator.ofFloat(navigationImageView, View.ALPHA, 0, 1);

        contentContainer.setPivotX(0f);
        contentContainer.setPivotY(0f);
        contentContainer.setScaleX(0f);
        contentContainer.setScaleY(0f);

        final ObjectAnimator contentContainerXAnim = ObjectAnimator.ofFloat(contentContainer, View.SCALE_X, 0f, 1f);
        final ObjectAnimator contentContainerYAnim = ObjectAnimator.ofFloat(contentContainer, View.SCALE_Y, 0f, 1f);

        clipRectAnim.setDuration(200);
        clipRectAnim.setStartDelay(100);
        containerAlphaAnim.setDuration(200);
        navigationAlphaAnim.setDuration(200);

        contentContainerXAnim.setDuration(10000);
        contentContainerYAnim.setDuration(10000);

        // on each update/frame of the clipRectAnim, update the field Rect rect with the new top/bottom coordinates
        clipRectAnim.addUpdateListener(new AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int top = ((Integer) clipRectAnim.getAnimatedValue("top")).intValue();
                int bottom = ((Integer) clipRectAnim.getAnimatedValue("bottom")).intValue();

                rect.top = top;
                rect.bottom = bottom / 2;
                // call invalidate() to perform a call to onDraw(Canvas) and dispatchDraw(Canvas) in the near future,
                // dispatchDraw(Canvas) is called before the View draws its children.
                invalidate();
            }
        });

        clipRectAnim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                animateClipping = false;
                rect = endRect;
                //perform the navigation icon animation, i.e. rotate it 180 degrees
                switchNavigationIcon(getResources().getDrawable(R.drawable.ico_home));
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                animateClipping = false;
                rect = endRect;
            }
        });

        AnimatorSet set = new AnimatorSet();
        set.playTogether(containerAlphaAnim, clipRectAnim);

        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator arg0) {
                fadeCategoryItems();

                AnimatorSet setContentContainer = new AnimatorSet();
                setContentContainer.playTogether(contentContainerXAnim, contentContainerYAnim, navigationAlphaAnim);
                setContentContainer.setStartDelay(50);
                setContentContainer.addListener(new AnimatorListenerAdapter() {

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        playCategoryItemsIntro();
                    }
                });

                setContentContainer.start();
            }
        });

        set.start();
    }

    /**
     * Set the items in the GridView to 0 alpha.
     */
    public void fadeCategoryItems() {
        for(int i = 0 ; i < gridView.getChildCount() ; i++) {
            View child = gridView.getChildAt(i);
            child.setAlpha(0f);
        }
    }

    /**
     * Play intro for category items, fade in and slide diagonally left and up 30 units.
     */
    public void playCategoryItemsIntro() {
        for(int i = 1 ; i <= gridView.getChildCount() ; i++) {
            View child = gridView.getChildAt(i-1);
            child.setTranslationX(30f);
            child.setTranslationY(30f);

            child.animate().setStartDelay(20*i).setInterpolator(new AccelerateDecelerateInterpolator()).setDuration(500).alpha(1f).start();
            child.animate().setStartDelay(70*i).setInterpolator(new AccelerateDecelerateInterpolator()).setDuration(200).translationXBy(-30f).translationYBy(-30f).start();
        }
    }

    /**
     * dispatchDraw(Canvas) is overriden in order to perform the intro/outro expand/minimize, on each
     * call to onDraw(Canvas) dispatchDraw(Canvas) is called before the View draws its children.
     * View animations.
     */
    @Override
    protected void dispatchDraw(Canvas canvas) {
        if(animateClipping) {
            canvas.save();
            canvas.clipRect(rect);
        }

        super.dispatchDraw(canvas);

        if(animateClipping) {
            canvas.restore();
        }
    }

    /**
     * Play the outro animation, i.e. minimize the View to the button for this MainCategoryView
     * in the main menu View etc.
     */
    public void playOutro() {
        ObjectAnimator anim = ObjectAnimator.ofFloat(contentContainer, View.ALPHA, 1f, 0f);
        anim.setDuration(systemShortAnimTime).addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationEnd(Animator animation) {

                final Rect startRect = new Rect();
                final Rect endRect = new Rect();
                Point globalOffset = new Point();

                currentMainMenuCategoryView.getGlobalVisibleRect(endRect, globalOffset);
                startRect.set(0, 0, root.getWidth(), root.getHeight());

                int topOffset = dm.heightPixels - root.getMeasuredHeight();

                endRect.offset(0, -(topOffset));

                rect = startRect;

                animateClipping = true;

                PropertyValuesHolder holderTop = PropertyValuesHolder.ofInt("top", startRect.top, endRect.top);
                PropertyValuesHolder holderBottom = PropertyValuesHolder.ofInt("bottom", startRect.bottom, endRect.bottom);

                final ValueAnimator clipRectAnim = ValueAnimator.ofPropertyValuesHolder(holderTop, holderBottom);
                ObjectAnimator containerAlphaAnim = ObjectAnimator.ofFloat(MainCategoryView.this, View.ALPHA, 1, 0);

                clipRectAnim.setDuration(150);
                containerAlphaAnim.setStartDelay(120);
                containerAlphaAnim.setDuration(30);

                clipRectAnim.addUpdateListener(new AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator animation) {
                        int top = ((Integer) clipRectAnim.getAnimatedValue("top")).intValue();
                        int bottom = ((Integer) clipRectAnim.getAnimatedValue("bottom")).intValue();

                        rect.top = top;
                        rect.bottom = bottom;
                        invalidate();
                    }
                });

                clipRectAnim.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        animateClipping = false;
                        rect = endRect;

                        setVisibility(View.GONE);
                        contentContainer.setAlpha(1f);
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {
                        animateClipping = false;
                        rect = endRect;

                        setVisibility(View.GONE);
                        contentContainer.setAlpha(1f);
                    }
                });

                clipRectAnim.start();
                containerAlphaAnim.start();

            }
        });

        anim.start();
    }
}


text:
import styled from 'styled-components';
import colors from 'themes/colors';

const AddPhoto = styled.div`
  position: relative;
  width: 180px;
  height: 180px;
  cursor: pointer;
  background-color: ${colors.white};
  margin-bottom: 15px;
  padding: 10px;
  font-size: 14px;
  font-weight: 600;
  color: ${colors.base3};
`;

export default AddPhoto;


text:
package com.rumblesan.reaktor

import scalaz._, Scalaz._
import scalaz.concurrent.{ Actor, Strategy }

object EventSink {

  def apply[InputEvent](
    handler: InputEvent => Unit
  )(
    implicit strategy: Strategy
  ): EventStream[InputEvent] = new EventStream(handler)

}


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

<TITLE>
VideoMode
</TITLE>

<META NAME="date" CONTENT="2013-05-29">

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

      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.openni

Class VideoMode

java.lang.Object
  org.openni.VideoMode

public class VideoMode
extends java.lang.Object

 Encapsulates a group of settings for a VideoStream. Settings stored include frame rate,
 resolution, and pixel format.

 This class is used as an input for changing the settings of a VideoStream, as well as an
 output for reporting the current settings of that class. It is also used by SensorInfo to
 report available video modes of a stream.

 Recommended practice is to use SensorInfo.getSupportedVideoModes() to obtain a
 list of valid video modes, and then to use items from that list to pass new settings to
 VideoStream. This is much less likely to produce an invalid video mode than instantiating
 and manually changing objects of this class.

Constructor Summary

VideoMode()

          Default constructor, creates an empty VideoMode object.

VideoMode(int resX,
          int resY,
          int fps,
          int pixelFormat)

Method Summary

 int
getFps()

          Getter function for the frame rate of this VideoMode.

 PixelFormat
getPixelFormat()

          Getter function for the pixel format of this VideoMode.

 int
getResolutionX()

          Getter function for the X resolution of this VideoMode.

 int
getResolutionY()

          Getter function for the Y resolution of this VideoMode.

 void
setFps(int fps)

          Setter function for the frame rate.

 void
setPixelFormat(PixelFormat format)

          Setter function for the pixel format of this VideoMode.

 void
setResolution(int resolutionX,
              int resolutionY)

          Setter function for the resolution of this VideoMode.

Methods inherited from class java.lang.Object

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

Constructor Detail

VideoMode

public VideoMode()

Default constructor, creates an empty VideoMode object. Application programs should, in most
 cases, use the copy constructor to copy an existing valid video mode. This is much less error
 prone that creating and attempting to configure a new VideoMode from scratch.

VideoMode

public VideoMode(int resX,
                 int resY,
                 int fps,
                 int pixelFormat)

Method Detail

getPixelFormat

public PixelFormat getPixelFormat()

Getter function for the pixel format of this VideoMode.

Returns:
Current pixel format setting of this VideoMode.

getResolutionX

public int getResolutionX()

Getter function for the X resolution of this VideoMode.

Returns:
Current horizontal resolution of this VideoMode, in pixels.

getResolutionY

public int getResolutionY()

Getter function for the Y resolution of this VideoMode.

Returns:
Current vertical resolution of this VideoMode, in pixels.

getFps

public int getFps()

Getter function for the frame rate of this VideoMode.

Returns:
Current frame rate, measured in frames per second.

setPixelFormat

public void setPixelFormat(PixelFormat format)

Setter function for the pixel format of this VideoMode. Application use of this function is not
 recommended. Instead, use SensorInfo.getSupportedVideoModes() to obtain a
 list of valid video modes.

Parameters:
format - Desired new pixel format for this VideoMode.

setResolution

public void setResolution(int resolutionX,
                          int resolutionY)

Setter function for the resolution of this VideoMode. Application use of this function is not
 recommended. Instead, use SensorInfo.getSupportedVideoModes() to obtain a
 list of valid video modes.

Parameters:
resolutionX - Desired new horizontal resolution in pixels.
resolutionY - Desired new vertical resolution in pixels.

setFps

public void setFps(int fps)

Setter function for the frame rate. Application use of this function is not recommended.
 Instead, use SensorInfo.getSupportedVideoModes() to obtain a list of valid
 video modes.

Parameters:
fps - Desired new frame rate, measured in frames per second.

      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:
namespace AngleSharp.Css.Dom
{
    using AngleSharp.Css.Parser;
    using AngleSharp.Text;
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.IO;

    /// <summary>
    /// Represents the base class for all style-rule similar rules.
    /// </summary>
    abstract class CssDeclarationRule : CssRule, ICssProperties
    {
        #region Fields

        private readonly List<ICssProperty> _declarations;
        private readonly HashSet<String> _contained;
        private readonly String _name;

        #endregion

        #region ctor

        internal CssDeclarationRule(ICssStyleSheet owner, CssRuleType type, String name, HashSet<String> contained)
            : base(owner, type)
        {
            _declarations = new List<ICssProperty>();
            _contained = contained;
            _name = name;
        }

        #endregion

        #region Properties

        public String this[String propertyName] => GetValue(propertyName);

        public Int32 Length => _declarations.Count;

        #endregion

        #region Methods

        public ICssProperty GetProperty(String propertyName) =>
            _declarations.Find(m => m.Name.Is(propertyName));

        public String GetPropertyValue(String propertyName) => GetValue(propertyName);

        public String GetPropertyPriority(String propertyName) => null;

        public void SetProperty(String propertyName, String propertyValue, String priority = null) =>
            SetValue(propertyName, propertyValue);

        public String RemoveProperty(String propertyName)
        {
            for (var i = 0; i < _declarations.Count; i++)
            {
                var declaration = _declarations[i];

                if (declaration.Name.Is(propertyName))
                {
                    _declarations.RemoveAt(i);
                    return declaration.Value;
                }
            }

            return null;
        }

        public IEnumerator<ICssProperty> GetEnumerator() => _declarations.GetEnumerator();

        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();

        public override void ToCss(TextWriter writer, IStyleFormatter formatter)
        {
            var block = formatter.BlockDeclarations(_declarations);
            writer.Write(formatter.Rule(_name, null, block));
        }

        #endregion

        #region Helpers

        private ICssProperty CreateNewProperty(String propertyName)
        {
            if (_contained.Contains(propertyName))
            {
                return Owner.Context.CreateProperty(propertyName);
            }

            return null;
        }

        protected String GetValue(String propertyName)
        {
            foreach (var declaration in _declarations)
            {
                if (declaration.Name.Is(propertyName))
                {
                    return declaration.Value;
                }
            }

            return String.Empty;
        }

        protected void SetValue(String propertyName, String valueText)
        {
            if (!String.IsNullOrEmpty(valueText))
            {
                foreach (var declaration in _declarations)
                {
                    if (declaration.Name.Is(propertyName))
                    {
                        declaration.Value = valueText;
                        return;
                    }
                }

                var property = CreateNewProperty(propertyName);

                if (property != null)
                {
                    property.Value = valueText;
                    _declarations.Add(property);
                }
            }
            else
            {
                RemoveProperty(propertyName);
            }
        }

        #endregion
    }
}


text:
layout: post
title: Japanese lebian schoolgirl in bondage
titleinfo: pornvd
desc: Watch Japanese lebian schoolgirl in bondage. Pornhub is the ultimate xxx porn and sex site.
---

Japanese lebian schoolgirl in bondage

Watch Japanese lebian schoolgirl in bondage. Pornhub is the ultimate xxx porn and sex site.


text:
    #pragma hdrstop
#endif

#if wxUSE_STATBMP

#include "wx/statbmp.h"

#ifndef WX_PRECOMP
    #include "wx/dc.h"
    #include "wx/icon.h"
    #include "wx/validate.h"
#endif

#include "wx/univ/renderer.h"
#include "wx/univ/theme.h"

// ============================================================================
// implementation
// ============================================================================

// ----------------------------------------------------------------------------
// wxStaticBitmap
// ----------------------------------------------------------------------------

bool wxStaticBitmap::Create(wxWindow *parent,
                            wxWindowID id,
                            const wxBitmap &label,
                            const wxPoint &pos,
                            const wxSize &size,
                            long style,
                            const wxString &name)
{
    if ( !wxControl::Create(parent, id, pos, size, style, wxDefaultValidator, name) )
        return false;

    // set bitmap first
    SetBitmap(label);

    // and adjust our size to fit it after this
    SetInitialSize(size);

    return true;
}

// ----------------------------------------------------------------------------
// bitmap/icon setting/getting and converting between
// ----------------------------------------------------------------------------

void wxStaticBitmap::SetBitmap(const wxBitmap& bitmap)
{
    m_bitmap = bitmap;
}

void wxStaticBitmap::SetIcon(const wxIcon& icon)
{
#ifdef __WXMSW__
    m_bitmap.CopyFromIcon(icon);
#else
    m_bitmap = (const wxBitmap&)icon;
#endif
}

wxIcon wxStaticBitmap::GetIcon() const
{
    wxIcon icon;
#ifdef __WXMSW__
    icon.CopyFromBitmap(m_bitmap);
#else
    icon = (const wxIcon&)m_bitmap;
#endif
    return icon;
}

// ----------------------------------------------------------------------------
// drawing
// ----------------------------------------------------------------------------

void wxStaticBitmap::DoDraw(wxControlRenderer *renderer)
{
    wxControl::DoDraw(renderer);
    renderer->DrawBitmap(GetBitmap());
}

#endif // wxUSE_STATBMP


text:
<!DOCTYPE html>

<html lang="en" ng-app="myApp" class="no-js">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>My AngularJS App</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="bower_components/html5-boilerplate/css/normalize.css">
  <link rel="stylesheet" href="bower_components/html5-boilerplate/css/main.css">
  <link rel="stylesheet" href="app.css">
  <script src="bower_components/html5-boilerplate/js/vendor/modernizr-2.6.2.min.js"></script>
</head>
<body>
  <div ng-view></div>

  <script src="bower_components/angular/angular.js"></script>
  <script src="bower_components/angular-route/angular-route.js"></script>
  <script src="https://cdn.firebase.com/js/client/1.0.18/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/0.8.0/angularfire.min.js"></script>
<script src="https://cdn.firebase.com/js/simple-login/1.6.2/firebase-simple-login.js"></script>
  <script src="app.js"></script>
  <script src="home/home.js"></script>
  <script src="components/version/version.js"></script>
  <script src="components/version/version-directive.js"></script>
  <script src="components/version/interpolate-filter.js"></script>
</body>
</html>


text:
<?php

class Insight_Plugin_Page extends Insight_Plugin_API {

    public function console() {
        return $this->message->api('Insight_Plugin_Console')->meta(array(
            'context' => 'page',
            'target' => 'console'
        ));
    }

}


text:
from django.urls import reverse
import pytest

from .utils import create_question

@pytest.mark.django_db
def test_no_questions_gives_a_message_in_the_index(client):
    response = client.get(reverse('polls:index'))

    assert response.status_code == 200
    assert b"No polls are available." in response.content

@pytest.mark.django_db
def test_past_questions_get_displayed(client):
    question_1 = create_question('Do you even lift?', 3)
    question_2 = create_question('What is love?', 12)

    response = client.get(reverse('polls:index'))

    assert response.status_code == 200
    # This actually doesn't check if anything is displayed, it relies on the template
    # to be correct, which is uncomfortable for me, so I'll add a better assertion next.
    # This is just so that I remember about that you introspect contexts in Django.
    assert list(response.context['latest_questions']) == [question_1, question_2]

    # This is something that doesn't depend on the template necessary being correct, but at the
    # same it it doesn't assert anything about the layout of the page (template's responsibility)
    # as well.
    assert question_1.text.encode() in response.content
    assert question_2.text.encode() in response.content

@pytest.mark.django_db
def test_future_questions_dont_get_displayed(client):
    visible_question_text = 'see me'
    invisible_question_text = "you don't know me"
    create_question(visible_question_text)
    create_question(invisible_question_text, days_old=-4)

    response = client.get(reverse('polls:index'))

    assert visible_question_text.encode() in response.content
    assert invisible_question_text.encode() not in response.content


text:
<?php

class Course_Type_Handler extends Type_Handler
{
	/**
	 * Constructor
	 *
	 * @param 	void
	 * @return 	void
	 */
	public function __construct($item, $crtId)
	{
		parent::__construct($item, $crtId);
	}

	public function handle()
	{
		require_once \Component::path('com_storefront') . DS . 'models' . DS . 'Memberships.php';
		$ms = new \Components\Storefront\Models\Memberships();

		// Get current registration
		$membership = $ms->getMembershipInfo($this->crtId, $this->item['info']->pId);
		$expiration = $membership['crtmExpires'];

		// Get course ID
		$courseId = $this->item['meta']['courseId'];

		// Get user ID for the cart
		require_once dirname(dirname(dirname(__DIR__))) . DS . 'models' . DS . 'Cart.php';
		$userId = \Components\Cart\Models\Cart::getCartUser($this->crtId);

		// Load courses model and register
		// registerForCourse($userId, $courseId, $expiration);

		require_once \Component::path('com_courses') . DS . 'models' . DS . 'course.php';

		$course = \Components\Courses\Models\Course::getInstance($this->item['meta']['courseId']);

		if (!$course->offerings()->count()) {
			// error enrolling
		}
		else
		{
			// Get to the first and probably the only offering
			//$offering = $course->offerings()->current();
			$offering = $course->offering($this->item['meta']['offeringId']);

			$offering->add($userId);
			//$offering->remove($userId);
		}
	}
}


text:
<?
require_once 'base.php';

class FlipBooleanTestCase extends TestServiceTestCase {

    public function test_null() {
        $this->assertEquals($this->service->flip_boolean(null), true);
    }

    public function test_numeric() {
        $this->assertEquals($this->service->flip_boolean(0), true);
    }

    public function test() {
        $this->assertEquals($this->service->flip_boolean(true), false);
        $this->assertEquals($this->service->flip_boolean(false), true);
    }
}


text:
package gov.hhs.fha.nhinc.patientcorrelation.nhinc.proxy;

import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import org.hl7.v3.AddPatientCorrelationResponseType;
import org.hl7.v3.PRPAIN201301UV02;
import org.hl7.v3.PRPAIN201309UV02;
import org.hl7.v3.RetrievePatientCorrelationsResponseType;

/**
 *
 * @author jhoppesc
 */
public class PatientCorrelationProxyNoOpImpl implements PatientCorrelationProxy {

    public RetrievePatientCorrelationsResponseType retrievePatientCorrelations(PRPAIN201309UV02 request,
            AssertionType assertion) {
        RetrievePatientCorrelationsResponseType resp = new RetrievePatientCorrelationsResponseType();

        return resp;
    }

    public AddPatientCorrelationResponseType addPatientCorrelation(PRPAIN201301UV02 request, AssertionType assertion) {
        AddPatientCorrelationResponseType resp = new AddPatientCorrelationResponseType();

        return resp;
    }

}