text:
package io.yawp.servlet.hierarchy;

import io.yawp.commons.utils.ServletTestCase;
import io.yawp.repository.models.hierarchy.AnotherObjectSubClass;
import io.yawp.repository.models.hierarchy.ObjectSubClass;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class HierarchyTransformerTest extends ServletTestCase {

    @Test
    public void testAllObjectsTransformer() {
        post("/hierarchy_subclasses/1", "{ \"name\": \"john\" }");

        String json = get("/hierarchy_subclasses/1", params("t", "allObjectsUpperCase"));
        ObjectSubClass object = from(json, ObjectSubClass.class);

        assertEquals("JOHN + SUPERCLASS HOOK", object.getName());
    }

    @Test
    public void testSuperClassTransformer() {
        post("/hierarchy_subclasses/1", "{ \"name\": \"john\" }");

        String json = get("/hierarchy_subclasses/1", params("t", "upperCase"));
        ObjectSubClass object = from(json, ObjectSubClass.class);

        assertEquals("JOHN + SUPERCLASS HOOK", object.getName());
    }

    @Test
    public void testMoreSpecificSubClassTransformer() {
        post("/hierarchy_another-subclasses/1", "{ \"name\": \"john\" }");

        String json = get("/hierarchy_another-subclasses/1", params("t", "upperCase"));
        AnotherObjectSubClass object = from(json, AnotherObjectSubClass.class);

        assertEquals("john + more specific hook + transformer", object.getName());
    }

}

redpajama_set_name: RedPajamaGithub


text:
<img
  alt="Flow Logo"
  src="https://raw.githubusercontent.com/flowtype/flow-typed/master/flow-typed-logo.png"
  width="400"
/>

[![Travis](https://img.shields.io/travis/flowtype/flow-typed.svg)](https://travis-ci.org/flowtype/flow-typed) [![npm](https://img.shields.io/npm/dm/flow-typed.svg)](https://www.npmjs.com/package/flow-typed)

`flow-typed` is a [repository](https://github.com/flowtype/flow-typed/tree/master/definitions) of third-party
[library interface definitions](http://flowtype.org/docs/third-party.html)
for use with [Flow](http://flowtype.org/).

You can grab definitions directly from this GitHub repo, or you can use the CLI (currently in beta) to install a libdef for a given library:
```bash
$ npm install -g flow-typed

$ cd /path/to/my/project
$ npm install
$ flow-typed install
'rxjs_v5.0.x.js' installed at /path/to/my/project/flow-typed/npm/rxjs_v5.0.xjs
```

## Huh?

When you start a project with Flow, **you likely want to use some third-party
libraries that were *not* written with Flow**. By default, Flow will just ignore
these libraries **leaving them untyped**. As a result, Flow can't give errors if
you accidentally mis-use the library (nor will it be able to auto-complete the
library).

To address this, **Flow supports
[library definitions](http://flowtype.org/docs/third-party.html)** which allow
you to describe the interface of a module or library separate from the
implementation of that module/library.

**The `flow-typed` repo is a collection of high-quality library definitions**,
tests to ensure that definitions remain high quality, and tooling to make it
as easy as possible to import them into your project.

All you have to do when you add a one or more new dependencies to your project
is run `flow-typed install`. This will search the libdef repo and download all
the libdefs that are relevant for your project and install them for you. After
that, **simply check them in** and be on your way!

## Why do I need to commit the libdefs that `flow-typed` installs for my project?

Libdefs in flow-typed are tagged at both Flow and library version when they are
installed, but libdefs themselves can improve over time. For example, they may
have a bug or there may be an improvement to their accuracy or completeness.

When a libdef is improved or updated in flow-*typed*, there's some chance that
the change could introduce new Flow errors into your project. As good as it is
to find new issues, **we also want to make sure that Flow-errors in your project
are consistent and predictable over time**.

So if/when you wish to upgrade a libdef that you've already checked in to your
project's version control, you can do so explicitly with the
`flow-typed install --overwrite` command.

## How Do I Contribute Library Definitions?

Just send a pull request!

All definitions sit under the
[/definitions](https://github.com/flowtype/flow-typed/tree/master/definitions)
directory. They all must follow the following directory structure and naming
format:

```
└ definitions/npm/
  ├ yargs_v4.x.x/           # <-- The name of the library, followed by _v<VERSION>
  | |
  | ├ flow_v0.23.x/         # <-- A folder containing libdefs tested against the
  | | |                     #     specified version(s) of Flow (v0.23.x in this
  | | |                     #     case).
  | | |
  | | └ yargs_v4.x.x.js     # <-- The libdef file meant for the Flow version
  | |                       #     specified by the containing directory's name.
  | |                       #     Must be named `<LIB>_v<VERSION>.js`.
  | |
  | ├ flow_v0.19.x-v0.22.x/ # <-- A folder containing libdefs tested against a
  | | |                     #     different range of Flow versions:
  | | |                     #     Anything from v0.19.x to v0.22.x (inclusive)
  | | |
  | | ├ yargs_v4.x.x.js     # <-- The libdef file for versions of Flow from
  | | |                     #     v0.19.x to v0.22.x (inclusive)
  | | |
  | | └ test_yargs.js       # <-- Tests in this directory only apply to the
  | |                       #     adjacent libdef (and thus, are specific to
  | |                       #     the libdefs for this specific Flow version)
  | |
  | └ test_yargs.js         # <-- Tests in this directory apply to libdefs for
  |                         #     all versions of Flow.
  ├ color_v0.7.x/
  ├ ...
```

Versions are semver versions with some restrictions:

* All of MAJOR, MINOR, and PATCH versions must be specified. It's acceptable to
  specify `x` in place of a number for MINOR and PATCH, but MAJOR cannot be `x`.
* Library versions may not specify a semver range, but Flow versions can of the
  following forms:
  * **`flow_v0.22.x-`**: Flow v0.22.x and above
  * **`flow_v0.22.x-v0.28.x`**: Flow versions v0.22.x up to v0.28.x (inclusive)
  * **`flow_-v0.22.x`**: Every version under (and including) Flow v0.22.x

**We structure files this way to enable automated testing and tooling.**
Tests ensure that library definitions continue to work as expected and the
`flow-typed` tooling ensures that it's as easy as possible to find and install
library definitions.

#### Writing LibDef Tests

**When you contribute a new library definition (or make a change to an existing
one), you must include tests with your change.**

Tests are simply `test_*.js` files that sit next to the library definition
file. They are normal @flow-ified .js files that import from and use the types
declared in the libdef in a way they are expected to be used. Flow-typed CI will
then run all applicable versions of Flow against the test file to be sure that
only *expected* errors occur.

In order to write code where you expect an error, you can put `// $ExpectError`
on the line above one of the lines listed in the error. This tells the test
runner to ignore errors that mention that line. **We require at least 1
// $ExpectError in each test**. This helps to ensure that the test is actually
exercising types like the author expects it to be.

## FAQs

### When I install the `flow-typed` CLI, I get an error that mentions `OpenSSL or Libgcrypt`

You may need to install Libgcrypt. Try setting up
[homebrew](http://brew.sh/index.html) and running `brew install libgcrypt`.

This issue was first reported here:
[#336](https://github.com/flowtype/flow-typed/issues/336)

### When I install the `flow-typed` CLI, I get an error immediately after `[configuring libssh2]`

You may need to install OpenSSL. Try setting up
[homebrew](http://brew.sh/index.html) and running `brew install openssl`.

This issue was first reported here:
[331](https://github.com/flowtype/flow-typed/issues/331)

## `flow-typed` CLI

The `flow-typed` npm package provides a CLI that provides several commands for
working with this repository:

##### `flow-typed validate-defs`

Verifies that all files under the `/definitions/` directory are structured and
named properly. **It does not run tests**, it only asserts that file and
directory names match the expected conventions.

This command is run during CI.

##### `flow-typed run-tests [optional-pattern]`

For each libdef, find each test and run it with all compatible versions of Flow.
If any errors arise that are not *`// $ExpectError`*, the test has failed.

Note that this command assumes that the `/definitions/` directory is correctly
structured. It should be run *after* running
[`flow-typed validate-defs`](#flow-typed-validate-defs).

##### `flow-typed update-cache [--debug]`

By default flow-typed retrieves all available libdefs from its related upstream
repository. To make this process more efficient, those libdefs are cached once
on your local filesystem. Usually, the cache will automatically be updated after
a short grace period during a libdef installation, but sometimes it is useful to
do this update manually. Use this command if you want to download the most
recent definitions into the cache for yourself.

The debug flag will output additional (error) information, which can be useful for
bug-reports.


text:
International Buyers  Please Note:

                               - Import duties, taxes and charges are not included in the item price or shipping charges. These charges are the buyer responsibility. §

                              - Please check with your country customs office to determine what these additional costs will be prior to bidding/buying.

                               - Einfuhrzoll, Steuern und Abgaben sind nicht im Artikel- Preis oder den Versandkosten enthalten. Diese Abgaben sind vom K?ufer zu tragen.

                              - Bitte kl?ren Sie mit Ihrem Zollamt wie hoch diese  Abgaben sind, bevor Sie mitbieten b.z.w. kaufen.

		<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="158" height="1500">
          <param name="movie" value="http://www.tinxi.com.cn/Foto7/left.swf" />
          <param name="quality" value="high" />
          <embed src="http://www.tinxi.com.cn/Foto7/left.swf" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="158" height="1500"></embed>
	    </object>

[ArtikelOnlinebezeichnungD.Bezeichnung1]

Artikel-Nr.:[Artikel.Artikelnummer]

  [ArtikelOnlinebezeichnungD.Bezeichnung4]

		<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="943" height="200">
          <param name="quality" value="high"><param name="SRC" value="http://www.trifoo.com/images/ad0.swf">
          <embed src="http://www.trifoo.com/images/ad0.swf" width="943" height="200" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"></embed>
	    </object>

		<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="943" height="142">
          <param name="quality" value="high"><param name="SRC" value="http://www.trifoo.com/images/ad.swf">
          <embed src="http://www.trifoo.com/images/ad.swf" width="943" height="142" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"></embed>
	    </object>

	  <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="945" height="707">
        <param name="movie" value="http://www.trifoo.com/images/policy.swf">
        <param name="quality" value="high">
        <embed src="http://www.trifoo.com/images/policy.swf" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="945" height="707"></embed>
      </object>

<map id="Map" name="Map">
<area shape="RECT" coords="30,9,178,50" href="#zahlung">
<area shape="RECT" coords="398,9,550,51" href="#zahlung">
<area shape="RECT" coords="211,8,361,49" href="#zahlung">
<area shape="RECT" coords="583,11,732,52" href="#zahlung">
<area shape="RECT" coords="768,10,920,51" href="#zahlung">
</map><map name="Map2">
<area shape="RECT" coords="5,31,164,53" href="http://stores.ebay.de/trifoo-online_Speicherkarte_W0QQcolZ4QQdirZ1QQfsubZ249143419QQftidZ2QQtZkm">
<area shape="RECT" coords="3,58,177,80" href="http://stores.ebay.de/trifoo-online_Konverter_W0QQcolZ4QQdirZ1QQfsubZ249341819QQftidZ2QQtZkm">
<area shape="RECT" coords="4,84,162,105" href="http://stores.ebay.de/trifoo-online_Kabel_W0QQcolZ4QQdirZ1QQfsubZ249143519QQftidZ2QQtZkm">
<area shape="RECT" coords="2,108,166,133" href="http://stores.ebay.de/trifoo-online_Netzwerk-Wlan_W0QQcolZ4QQdirZ1QQfsubZ249143619QQftidZ2QQtZkm">
<area shape="RECT" coords="3,135,169,160" href="http://stores.ebay.de/trifoo-online_DVB-T_W0QQcolZ4QQdirZ1QQfsubZ249341919QQftidZ2QQtZkm">
<area shape="RECT" coords="1,162,174,186" href="http://stores.ebay.de/trifoo-online_Video-Bearbeitung_W0QQcolZ4QQdirZ1QQfsubZ249342019QQftidZ2QQtZkm">
<area shape="RECT" coords="2,188,188,214" href="http://stores.ebay.de/trifoo-online_Eingabegerate_W0QQcolZ4QQdirZ1QQfsubZ249342119QQftidZ2QQtZkm">
<area shape="RECT" coords="2,215,176,239" href="http://stores.ebay.de/trifoo-online_Floppy_W0QQcolZ4QQdirZ1QQfsubZ249342219QQftidZ2QQtZkm">
<area shape="RECT" coords="2,242,191,267" href="http://stores.ebay.de/trifoo-online_RAM_W0QQcolZ4QQdirZ1QQfsubZ249342819QQftidZ2QQtZkm">
<area shape="RECT" coords="1,270,194,294" href="http://stores.ebay.de/trifoo-online_Festplatte_W0QQcolZ4QQdirZ1QQfsubZ249342919QQftidZ2QQtZkm">
<area shape="RECT" coords="1,295,171,320" href="http://stores.ebay.de/trifoo-online_Notebook-Zubehor_W0QQcolZ4QQdirZ1QQfsubZ249343019QQftidZ2QQtZkm">
<area shape="RECT" coords="1,321,170,345" href="http://stores.ebay.de/trifoo-online_USB-Stick_W0QQcolZ4QQdirZ1QQfsubZ249143319QQftidZ2QQtZkm">
<area shape="RECT" coords="1,346,182,372" href="http://stores.ebay.de/trifoo-online_Handy_W0QQcolZ4QQdirZ1QQfsubZ249343119QQftidZ2QQtZkm">
<area shape="RECT" coords="2,374,186,398" href="http://stores.ebay.de/trifoo-online_Handy-Zubehor_W0QQcolZ4QQdirZ1QQfsubZ249343219QQftidZ2QQtZkm">
<area shape="RECT" coords="2,400,177,426" href="http://stores.ebay.de/trifoo-online_Fur-Autos_W0QQcolZ4QQdirZ1QQfsubZ249343819QQftidZ2QQtZkm">
<area shape="RECT" coords="1,427,175,451" href="http://stores.ebay.de/trifoo-online_MP3-MP4-Player_W0QQcolZ4QQdirZ1QQfsubZ249343919QQftidZ2QQtZkm">
<area shape="RECT" coords="1,453,170,478" href="http://stores.ebay.de/trifoo-online_Web-Cam_W0QQcolZ4QQdirZ1QQfsubZ249344019QQftidZ2QQtZkm">
<area shape="RECT" coords="1,480,168,505" href="http://stores.ebay.de/trifoo-online_Multimedia_W0QQcolZ4QQdirZ1QQfsubZ249344119QQftidZ2QQtZkm">
<area shape="RECT" coords="2,506,166,531" href="http://stores.ebay.de/trifoo-online_Spieler-Zubehor_W0QQcolZ4QQdirZ1QQfsubZ249344219QQftidZ2QQtZkm">
<area shape="RECT" coords="2,534,167,559" href="http://stores.ebay.de/trifoo-online_Sonstige_W0QQcolZ4QQdirZ1QQfsubZ1QQftidZ2QQtZkm">
</map>


text:
CONNECT_PORT=8083
declare -a connectors=("hive")
connectorslen=${#connectors[@]}

for (( i=0; i<${connectorslen}; i++ )); do
    CONNECTOR=${connectors[$i]}
    echo "Running integration tests for $CONNECTOR"

    CONNECTOR_PROJECT="kafka-connect-$CONNECTOR"
    echo "Connector path = $CONNECTOR_PROJECT"

    IT_PATH="$CONNECTOR_PROJECT/it"
    echo "IT test path = $IT_PATH"

    COMPOSE_FILE="$IT_PATH/docker-compose.yml"
    echo "Compose file = $COMPOSE_FILE"

    # if docker is present for this component, start it up, and wait for kafka connect to initialize
    if [ -e "$COMPOSE_FILE" ]
    then
        echo "Docker compose has been detected for $CONNECTOR; starting up as daemon"
        docker-compose -f $COMPOSE_FILE up -d -t 30

        for (( i=0 ; i<60 ; i++ )); do
            sleep 5
            curl "http://localhost:$CONNECT_PORT/connector-plugins" | grep "FileStream" && break
        done
    fi

    ./gradlew -Pintegration-tests $CONNECTOR_PROJECT:it:check

    # if docker is present for this component, shut it down
    if [ -e "$COMPOSE_FILE" ]
    then
        docker-compose -f $COMPOSE_FILE stop -v
    fi

    echo "Completed integration tests for $CONNECTOR"
done


text:
import copy

import netaddr
from oslo_config import cfg
from oslo_log import log as logging
from oslo_policy import policy as oslo_policy
from oslo_utils import excutils
import six
import webob.exc

from neutron.api import api_common
from neutron.api.rpc.agentnotifiers import dhcp_rpc_agent_api
from neutron.api.v2 import attributes
from neutron.api.v2 import resource as wsgi_resource
from neutron.common import constants as const
from neutron.common import exceptions
from neutron.common import rpc as n_rpc
from neutron.i18n import _LE, _LI
from neutron import policy
from neutron import quota

LOG = logging.getLogger(__name__)

FAULT_MAP = {exceptions.NotFound: webob.exc.HTTPNotFound,
             exceptions.Conflict: webob.exc.HTTPConflict,
             exceptions.InUse: webob.exc.HTTPConflict,
             exceptions.BadRequest: webob.exc.HTTPBadRequest,
             exceptions.ServiceUnavailable: webob.exc.HTTPServiceUnavailable,
             exceptions.NotAuthorized: webob.exc.HTTPForbidden,
             netaddr.AddrFormatError: webob.exc.HTTPBadRequest,
             oslo_policy.PolicyNotAuthorized: webob.exc.HTTPForbidden
             }

class Controller(object):
    LIST = 'list'
    SHOW = 'show'
    CREATE = 'create'
    UPDATE = 'update'
    DELETE = 'delete'

    def __init__(self, plugin, collection, resource, attr_info,
                 allow_bulk=False, member_actions=None, parent=None,
                 allow_pagination=False, allow_sorting=False):
        if member_actions is None:
            member_actions = []
        self._plugin = plugin
        self._collection = collection.replace('-', '_')
        self._resource = resource.replace('-', '_')
        self._attr_info = attr_info
        self._allow_bulk = allow_bulk
        self._allow_pagination = allow_pagination
        self._allow_sorting = allow_sorting
        self._native_bulk = self._is_native_bulk_supported()
        self._native_pagination = self._is_native_pagination_supported()
        self._native_sorting = self._is_native_sorting_supported()
        self._policy_attrs = [name for (name, info) in self._attr_info.items()
                              if info.get('required_by_policy')]
        self._notifier = n_rpc.get_notifier('network')
        # use plugin's dhcp notifier, if this is already instantiated
        agent_notifiers = getattr(plugin, 'agent_notifiers', {})
        self._dhcp_agent_notifier = (
            agent_notifiers.get(const.AGENT_TYPE_DHCP) or
            dhcp_rpc_agent_api.DhcpAgentNotifyAPI()
        )
        if cfg.CONF.notify_nova_on_port_data_changes:
            from neutron.notifiers import nova
            self._nova_notifier = nova.Notifier()
        self._member_actions = member_actions
        self._primary_key = self._get_primary_key()
        if self._allow_pagination and self._native_pagination:
            # Native pagination need native sorting support
            if not self._native_sorting:
                raise exceptions.Invalid(
                    _("Native pagination depend on native sorting")
                )
            if not self._allow_sorting:
                LOG.info(_LI("Allow sorting is enabled because native "
                             "pagination requires native sorting"))
                self._allow_sorting = True

        if parent:
            self._parent_id_name = '%s_id' % parent['member_name']
            parent_part = '_%s' % parent['member_name']
        else:
            self._parent_id_name = None
            parent_part = ''
        self._plugin_handlers = {
            self.LIST: 'get%s_%s' % (parent_part, self._collection),
            self.SHOW: 'get%s_%s' % (parent_part, self._resource)
        }
        for action in [self.CREATE, self.UPDATE, self.DELETE]:
            self._plugin_handlers[action] = '%s%s_%s' % (action, parent_part,
                                                         self._resource)

    def _get_primary_key(self, default_primary_key='id'):
        for key, value in six.iteritems(self._attr_info):
            if value.get('primary_key', False):
                return key
        return default_primary_key

    def _is_native_bulk_supported(self):
        native_bulk_attr_name = ("_%s__native_bulk_support"
                                 % self._plugin.__class__.__name__)
        return getattr(self._plugin, native_bulk_attr_name, False)

    def _is_native_pagination_supported(self):
        native_pagination_attr_name = ("_%s__native_pagination_support"
                                       % self._plugin.__class__.__name__)
        return getattr(self._plugin, native_pagination_attr_name, False)

    def _is_native_sorting_supported(self):
        native_sorting_attr_name = ("_%s__native_sorting_support"
                                    % self._plugin.__class__.__name__)
        return getattr(self._plugin, native_sorting_attr_name, False)

    def _exclude_attributes_by_policy(self, context, data):
        """Identifies attributes to exclude according to authZ policies.

        Return a list of attribute names which should be stripped from the
        response returned to the user because the user is not authorized
        to see them.
        """
        attributes_to_exclude = []
        for attr_name in data.keys():
            attr_data = self._attr_info.get(attr_name)
            if attr_data and attr_data['is_visible']:
                if policy.check(
                    context,
                    '%s:%s' % (self._plugin_handlers[self.SHOW], attr_name),
                    data,
                    might_not_exist=True,
                    pluralized=self._collection):
                    # this attribute is visible, check next one
                    continue
            # if the code reaches this point then either the policy check
            # failed or the attribute was not visible in the first place
            attributes_to_exclude.append(attr_name)
        return attributes_to_exclude

    def _view(self, context, data, fields_to_strip=None):
        """Build a view of an API resource.

        :param context: the neutron context
        :param data: the object for which a view is being created
        :param fields_to_strip: attributes to remove from the view

        :returns: a view of the object which includes only attributes
        visible according to API resource declaration and authZ policies.
        """
        fields_to_strip = ((fields_to_strip or []) +
                           self._exclude_attributes_by_policy(context, data))
        return self._filter_attributes(context, data, fields_to_strip)

    def _filter_attributes(self, context, data, fields_to_strip=None):
        if not fields_to_strip:
            return data
        return dict(item for item in six.iteritems(data)
                    if (item[0] not in fields_to_strip))

    def _do_field_list(self, original_fields):
        fields_to_add = None
        # don't do anything if fields were not specified in the request
        if original_fields:
            fields_to_add = [attr for attr in self._policy_attrs
                             if attr not in original_fields]
            original_fields.extend(self._policy_attrs)
        return original_fields, fields_to_add

    def __getattr__(self, name):
        if name in self._member_actions:
            def _handle_action(request, id, **kwargs):
                arg_list = [request.context, id]
                # Ensure policy engine is initialized
                policy.init()
                # Fetch the resource and verify if the user can access it
                try:
                    resource = self._item(request, id, True)
                except oslo_policy.PolicyNotAuthorized:
                    msg = _('The resource could not be found.')
                    raise webob.exc.HTTPNotFound(msg)
                body = kwargs.pop('body', None)
                # Explicit comparison with None to distinguish from {}
                if body is not None:
                    arg_list.append(body)
                # It is ok to raise a 403 because accessibility to the
                # object was checked earlier in this method
                policy.enforce(request.context,
                               name,
                               resource,
                               pluralized=self._collection)
                return getattr(self._plugin, name)(*arg_list, **kwargs)
            return _handle_action
        else:
            raise AttributeError()

    def _get_pagination_helper(self, request):
        if self._allow_pagination and self._native_pagination:
            return api_common.PaginationNativeHelper(request,
                                                     self._primary_key)
        elif self._allow_pagination:
            return api_common.PaginationEmulatedHelper(request,
                                                       self._primary_key)
        return api_common.NoPaginationHelper(request, self._primary_key)

    def _get_sorting_helper(self, request):
        if self._allow_sorting and self._native_sorting:
            return api_common.SortingNativeHelper(request, self._attr_info)
        elif self._allow_sorting:
            return api_common.SortingEmulatedHelper(request, self._attr_info)
        return api_common.NoSortingHelper(request, self._attr_info)

    def _items(self, request, do_authz=False, parent_id=None):
        """Retrieves and formats a list of elements of the requested entity."""
        # NOTE(salvatore-orlando): The following ensures that fields which
        # are needed for authZ policy validation are not stripped away by the
        # plugin before returning.
        original_fields, fields_to_add = self._do_field_list(
            api_common.list_args(request, 'fields'))
        filters = api_common.get_filters(request, self._attr_info,
                                         ['fields', 'sort_key', 'sort_dir',
                                          'limit', 'marker', 'page_reverse'])
        kwargs = {'filters': filters,
                  'fields': original_fields}
        sorting_helper = self._get_sorting_helper(request)
        pagination_helper = self._get_pagination_helper(request)
        sorting_helper.update_args(kwargs)
        sorting_helper.update_fields(original_fields, fields_to_add)
        pagination_helper.update_args(kwargs)
        pagination_helper.update_fields(original_fields, fields_to_add)
        if parent_id:
            kwargs[self._parent_id_name] = parent_id
        obj_getter = getattr(self._plugin, self._plugin_handlers[self.LIST])
        obj_list = obj_getter(request.context, **kwargs)
        obj_list = sorting_helper.sort(obj_list)
        obj_list = pagination_helper.paginate(obj_list)
        # Check authz
        if do_authz:
            # FIXME(salvatore-orlando): obj_getter might return references to
            # other resources. Must check authZ on them too.
            # Omit items from list that should not be visible
            obj_list = [obj for obj in obj_list
                        if policy.check(request.context,
                                        self._plugin_handlers[self.SHOW],
                                        obj,
                                        plugin=self._plugin,
                                        pluralized=self._collection)]
        # Use the first element in the list for discriminating which attributes
        # should be filtered out because of authZ policies
        # fields_to_add contains a list of attributes added for request policy
        # checks but that were not required by the user. They should be
        # therefore stripped
        fields_to_strip = fields_to_add or []
        if obj_list:
            fields_to_strip += self._exclude_attributes_by_policy(
                request.context, obj_list[0])
        collection = {self._collection:
                      [self._filter_attributes(
                          request.context, obj,
                          fields_to_strip=fields_to_strip)
                       for obj in obj_list]}
        pagination_links = pagination_helper.get_links(obj_list)
        if pagination_links:
            collection[self._collection + "_links"] = pagination_links
        return collection

    def _item(self, request, id, do_authz=False, field_list=None,
              parent_id=None):
        """Retrieves and formats a single element of the requested entity."""
        kwargs = {'fields': field_list}
        action = self._plugin_handlers[self.SHOW]
        if parent_id:
            kwargs[self._parent_id_name] = parent_id
        obj_getter = getattr(self._plugin, action)
        obj = obj_getter(request.context, id, **kwargs)
        # Check authz
        # FIXME(salvatore-orlando): obj_getter might return references to
        # other resources. Must check authZ on them too.
        if do_authz:
            policy.enforce(request.context,
                           action,
                           obj,
                           pluralized=self._collection)
        return obj

    def _send_dhcp_notification(self, context, data, methodname):
        if cfg.CONF.dhcp_agent_notification:
            if self._collection in data:
                for body in data[self._collection]:
                    item = {self._resource: body}
                    self._dhcp_agent_notifier.notify(context, item, methodname)
            else:
                self._dhcp_agent_notifier.notify(context, data, methodname)

    def _send_nova_notification(self, action, orig, returned):
        if hasattr(self, '_nova_notifier'):
            self._nova_notifier.send_network_change(action, orig, returned)

    def index(self, request, **kwargs):
        """Returns a list of the requested entity."""
        parent_id = kwargs.get(self._parent_id_name)
        # Ensure policy engine is initialized
        policy.init()
        return self._items(request, True, parent_id)

    def show(self, request, id, **kwargs):
        """Returns detailed information about the requested entity."""
        try:
            # NOTE(salvatore-orlando): The following ensures that fields
            # which are needed for authZ policy validation are not stripped
            # away by the plugin before returning.
            field_list, added_fields = self._do_field_list(
                api_common.list_args(request, "fields"))
            parent_id = kwargs.get(self._parent_id_name)
            # Ensure policy engine is initialized
            policy.init()
            return {self._resource:
                    self._view(request.context,
                               self._item(request,
                                          id,
                                          do_authz=True,
                                          field_list=field_list,
                                          parent_id=parent_id),
                               fields_to_strip=added_fields)}
        except oslo_policy.PolicyNotAuthorized:
            # To avoid giving away information, pretend that it
            # doesn't exist
            msg = _('The resource could not be found.')
            raise webob.exc.HTTPNotFound(msg)

    def _emulate_bulk_create(self, obj_creator, request, body, parent_id=None):
        objs = []
        try:
            for item in body[self._collection]:
                kwargs = {self._resource: item}
                if parent_id:
                    kwargs[self._parent_id_name] = parent_id
                fields_to_strip = self._exclude_attributes_by_policy(
                    request.context, item)
                objs.append(self._filter_attributes(
                    request.context,
                    obj_creator(request.context, **kwargs),
                    fields_to_strip=fields_to_strip))
            return objs
        # Note(salvatore-orlando): broad catch as in theory a plugin
        # could raise any kind of exception
        except Exception:
            with excutils.save_and_reraise_exception():
                for obj in objs:
                    obj_deleter = getattr(self._plugin,
                                          self._plugin_handlers[self.DELETE])
                    try:
                        kwargs = ({self._parent_id_name: parent_id}
                                  if parent_id else {})
                        obj_deleter(request.context, obj['id'], **kwargs)
                    except Exception:
                        # broad catch as our only purpose is to log the
                        # exception
                        LOG.exception(_LE("Unable to undo add for "
                                          "%(resource)s %(id)s"),
                                      {'resource': self._resource,
                                       'id': obj['id']})
                # TODO(salvatore-orlando): The object being processed when the
                # plugin raised might have been created or not in the db.
                # We need a way for ensuring that if it has been created,
                # it is then deleted

    def create(self, request, body=None, **kwargs):
        """Creates a new instance of the requested entity."""
        parent_id = kwargs.get(self._parent_id_name)
        self._notifier.info(request.context,
                            self._resource + '.create.start',
                            body)
        body = Controller.prepare_request_body(request.context, body, True,
                                               self._resource, self._attr_info,
                                               allow_bulk=self._allow_bulk)
        action = self._plugin_handlers[self.CREATE]
        # Check authz
        if self._collection in body:
            # Have to account for bulk create
            items = body[self._collection]
            deltas = {}
            bulk = True
        else:
            items = [body]
            bulk = False
        # Ensure policy engine is initialized
        policy.init()
        for item in items:
            self._validate_network_tenant_ownership(request,
                                                    item[self._resource])
            policy.enforce(request.context,
                           action,
                           item[self._resource],
                           pluralized=self._collection)
            try:
                tenant_id = item[self._resource]['tenant_id']
                count = quota.QUOTAS.count(request.context, self._resource,
                                           self._plugin, self._collection,
                                           tenant_id)
                if bulk:
                    delta = deltas.get(tenant_id, 0) + 1
                    deltas[tenant_id] = delta
                else:
                    delta = 1
                kwargs = {self._resource: count + delta}
            except exceptions.QuotaResourceUnknown as e:
                # We don't want to quota this resource
                LOG.debug(e)
            else:
                quota.QUOTAS.limit_check(request.context,
                                         item[self._resource]['tenant_id'],
                                         **kwargs)

        def notify(create_result):
            notifier_method = self._resource + '.create.end'
            self._notifier.info(request.context,
                                notifier_method,
                                create_result)
            self._send_dhcp_notification(request.context,
                                         create_result,
                                         notifier_method)
            return create_result

        kwargs = {self._parent_id_name: parent_id} if parent_id else {}
        if self._collection in body and self._native_bulk:
            # plugin does atomic bulk create operations
            obj_creator = getattr(self._plugin, "%s_bulk" % action)
            objs = obj_creator(request.context, body, **kwargs)
            # Use first element of list to discriminate attributes which
            # should be removed because of authZ policies
            fields_to_strip = self._exclude_attributes_by_policy(
                request.context, objs[0])
            return notify({self._collection: [self._filter_attributes(
                request.context, obj, fields_to_strip=fields_to_strip)
                for obj in objs]})
        else:
            obj_creator = getattr(self._plugin, action)
            if self._collection in body:
                # Emulate atomic bulk behavior
                objs = self._emulate_bulk_create(obj_creator, request,
                                                 body, parent_id)
                return notify({self._collection: objs})
            else:
                kwargs.update({self._resource: body})
                obj = obj_creator(request.context, **kwargs)
                self._send_nova_notification(action, {},
                                             {self._resource: obj})
                return notify({self._resource: self._view(request.context,
                                                          obj)})

    def delete(self, request, id, **kwargs):
        """Deletes the specified entity."""
        self._notifier.info(request.context,
                            self._resource + '.delete.start',
                            {self._resource + '_id': id})
        action = self._plugin_handlers[self.DELETE]

        # Check authz
        policy.init()
        parent_id = kwargs.get(self._parent_id_name)
        obj = self._item(request, id, parent_id=parent_id)
        try:
            policy.enforce(request.context,
                           action,
                           obj,
                           pluralized=self._collection)
        except oslo_policy.PolicyNotAuthorized:
            # To avoid giving away information, pretend that it
            # doesn't exist
            msg = _('The resource could not be found.')
            raise webob.exc.HTTPNotFound(msg)

        obj_deleter = getattr(self._plugin, action)
        obj_deleter(request.context, id, **kwargs)
        notifier_method = self._resource + '.delete.end'
        self._notifier.info(request.context,
                            notifier_method,
                            {self._resource + '_id': id})
        result = {self._resource: self._view(request.context, obj)}
        self._send_nova_notification(action, {}, result)
        self._send_dhcp_notification(request.context,
                                     result,
                                     notifier_method)

    def update(self, request, id, body=None, **kwargs):
        """Updates the specified entity's attributes."""
        parent_id = kwargs.get(self._parent_id_name)
        try:
            payload = body.copy()
        except AttributeError:
            msg = _("Invalid format: %s") % request.body
            raise exceptions.BadRequest(resource='body', msg=msg)
        payload['id'] = id
        self._notifier.info(request.context,
                            self._resource + '.update.start',
                            payload)
        body = Controller.prepare_request_body(request.context, body, False,
                                               self._resource, self._attr_info,
                                               allow_bulk=self._allow_bulk)
        action = self._plugin_handlers[self.UPDATE]
        # Load object to check authz
        # but pass only attributes in the original body and required
        # by the policy engine to the policy 'brain'
        field_list = [name for (name, value) in six.iteritems(self._attr_info)
                      if (value.get('required_by_policy') or
                          value.get('primary_key') or
                          'default' not in value)]
        # Ensure policy engine is initialized
        policy.init()
        orig_obj = self._item(request, id, field_list=field_list,
                              parent_id=parent_id)
        orig_object_copy = copy.copy(orig_obj)
        orig_obj.update(body[self._resource])
        # Make a list of attributes to be updated to inform the policy engine
        # which attributes are set explicitly so that it can distinguish them
        # from the ones that are set to their default values.
        orig_obj[const.ATTRIBUTES_TO_UPDATE] = body[self._resource].keys()
        try:
            policy.enforce(request.context,
                           action,
                           orig_obj,
                           pluralized=self._collection)
        except oslo_policy.PolicyNotAuthorized:
            with excutils.save_and_reraise_exception() as ctxt:
                # If a tenant is modifying it's own object, it's safe to return
                # a 403. Otherwise, pretend that it doesn't exist to avoid
                # giving away information.
                if request.context.tenant_id != orig_obj['tenant_id']:
                    ctxt.reraise = False
            msg = _('The resource could not be found.')
            raise webob.exc.HTTPNotFound(msg)

        obj_updater = getattr(self._plugin, action)
        kwargs = {self._resource: body}
        if parent_id:
            kwargs[self._parent_id_name] = parent_id
        obj = obj_updater(request.context, id, **kwargs)
        result = {self._resource: self._view(request.context, obj)}
        notifier_method = self._resource + '.update.end'
        self._notifier.info(request.context, notifier_method, result)
        self._send_dhcp_notification(request.context,
                                     result,
                                     notifier_method)
        self._send_nova_notification(action, orig_object_copy, result)
        return result

    @staticmethod
    def _populate_tenant_id(context, res_dict, is_create):

        if (('tenant_id' in res_dict and
             res_dict['tenant_id'] != context.tenant_id and
             not context.is_admin)):
            msg = _("Specifying 'tenant_id' other than authenticated "
                    "tenant in request requires admin privileges")
            raise webob.exc.HTTPBadRequest(msg)

        if is_create and 'tenant_id' not in res_dict:
            if context.tenant_id:
                res_dict['tenant_id'] = context.tenant_id
            else:
                msg = _("Running without keystone AuthN requires "
                        " that tenant_id is specified")
                raise webob.exc.HTTPBadRequest(msg)

    @staticmethod
    def prepare_request_body(context, body, is_create, resource, attr_info,
                             allow_bulk=False):
        """Verifies required attributes are in request body.

        Also checking that an attribute is only specified if it is allowed
        for the given operation (create/update).

        Attribute with default values are considered to be optional.

        body argument must be the deserialized body.
        """
        collection = resource + "s"
        if not body:
            raise webob.exc.HTTPBadRequest(_("Resource body required"))

        LOG.debug("Request body: %(body)s", {'body': body})
        try:
            if collection in body:
                if not allow_bulk:
                    raise webob.exc.HTTPBadRequest(_("Bulk operation "
                                                     "not supported"))
                if not body[collection]:
                    raise webob.exc.HTTPBadRequest(_("Resources required"))
                bulk_body = [
                    Controller.prepare_request_body(
                        context, item if resource in item
                        else {resource: item}, is_create, resource, attr_info,
                        allow_bulk) for item in body[collection]
                ]
                return {collection: bulk_body}
            res_dict = body.get(resource)
        except (AttributeError, TypeError):
            msg = _("Body contains invalid data")
            raise webob.exc.HTTPBadRequest(msg)
        if res_dict is None:
            msg = _("Unable to find '%s' in request body") % resource
            raise webob.exc.HTTPBadRequest(msg)

        Controller._populate_tenant_id(context, res_dict, is_create)
        Controller._verify_attributes(res_dict, attr_info)

        if is_create:  # POST
            for attr, attr_vals in six.iteritems(attr_info):
                if attr_vals['allow_post']:
                    if ('default' not in attr_vals and
                        attr not in res_dict):
                        msg = _("Failed to parse request. Required "
                                "attribute '%s' not specified") % attr
                        raise webob.exc.HTTPBadRequest(msg)
                    res_dict[attr] = res_dict.get(attr,
                                                  attr_vals.get('default'))
                else:
                    if attr in res_dict:
                        msg = _("Attribute '%s' not allowed in POST") % attr
                        raise webob.exc.HTTPBadRequest(msg)
        else:  # PUT
            for attr, attr_vals in six.iteritems(attr_info):
                if attr in res_dict and not attr_vals['allow_put']:
                    msg = _("Cannot update read-only attribute %s") % attr
                    raise webob.exc.HTTPBadRequest(msg)

        for attr, attr_vals in six.iteritems(attr_info):
            if (attr not in res_dict or
                res_dict[attr] is attributes.ATTR_NOT_SPECIFIED):
                continue
            # Convert values if necessary
            if 'convert_to' in attr_vals:
                res_dict[attr] = attr_vals['convert_to'](res_dict[attr])
            # Check that configured values are correct
            if 'validate' not in attr_vals:
                continue
            for rule in attr_vals['validate']:
                res = attributes.validators[rule](res_dict[attr],
                                                  attr_vals['validate'][rule])
                if res:
                    msg_dict = dict(attr=attr, reason=res)
                    msg = _("Invalid input for %(attr)s. "
                            "Reason: %(reason)s.") % msg_dict
                    raise webob.exc.HTTPBadRequest(msg)
        return body

    @staticmethod
    def _verify_attributes(res_dict, attr_info):
        extra_keys = set(res_dict.keys()) - set(attr_info.keys())
        if extra_keys:
            msg = _("Unrecognized attribute(s) '%s'") % ', '.join(extra_keys)
            raise webob.exc.HTTPBadRequest(msg)

    def _validate_network_tenant_ownership(self, request, resource_item):
        # TODO(salvatore-orlando): consider whether this check can be folded
        # in the policy engine
        if (request.context.is_admin or request.context.is_advsvc or
                self._resource not in ('port', 'subnet')):
            return
        network = self._plugin.get_network(
            request.context,
            resource_item['network_id'])
        # do not perform the check on shared networks
        if network.get('shared'):
            return

        network_owner = network['tenant_id']

        if network_owner != resource_item['tenant_id']:
            msg = _("Tenant %(tenant_id)s not allowed to "
                    "create %(resource)s on this network")
            raise webob.exc.HTTPForbidden(msg % {
                "tenant_id": resource_item['tenant_id'],
                "resource": self._resource,
            })

def create_resource(collection, resource, plugin, params, allow_bulk=False,
                    member_actions=None, parent=None, allow_pagination=False,
                    allow_sorting=False):
    controller = Controller(plugin, collection, resource, params, allow_bulk,
                            member_actions=member_actions, parent=parent,
                            allow_pagination=allow_pagination,
                            allow_sorting=allow_sorting)

    return wsgi_resource.Resource(controller, FAULT_MAP)


text:
{% extends "layout.html" %}

{% block page_title %}
  Question page
{% endblock %}

{% block content %}

      Back

        Passport with a foreign embassy

      <form class="form">

      Which country is your visa for?

<input class="form-control" id="full-name-f1" type="text">

      <form class="form">

<form class="form">

      What is your visa application reference number? (optional)

If unsure leave blank

<input class="form-control" id="full-name-f1" type="text">

      <form class="form">

      <form class="form">

        <fieldset class="form-group">
        When did you submit your visa application reference number (optional)

          <legend class="visuallyhidden">Date of birth</legend>

If unsure leave blank

For example, 31 3 2016

              Day
              <input class="form-control" id="dob-day" name="dob-day" type="number" pattern="[0-9]*" min="0" max="31">

              Month
              <input class="form-control" id="dob-month" name="dob-month" type="number" pattern="[0-9]*" min="0" max="12">

              Year
              <input class="form-control" id="dob-year" name="dob-year" type="number" pattern="[0-9]*" min="0" max="2014">

         </fieldset>

        next

      </form>

{% endblock %}


text:
package org.apache.lucene.codecs.lucene41;

import java.io.IOException;

import org.apache.lucene.codecs.PostingsBaseFormat;
import org.apache.lucene.codecs.PostingsReaderBase;
import org.apache.lucene.codecs.PostingsWriterBase;
import org.apache.lucene.index.SegmentReadState;
import org.apache.lucene.index.SegmentWriteState;

/**
 * Provides a {@link PostingsReaderBase} and {@link
 * PostingsWriterBase}.
 *
 * @lucene.experimental */

// TODO: should these also be named / looked up via SPI?
public final class Lucene41PostingsBaseFormat extends PostingsBaseFormat {

  /** Sole constructor. */
  public Lucene41PostingsBaseFormat() {
    super("Lucene41");
  }

  @Override
  public PostingsReaderBase postingsReaderBase(SegmentReadState state) throws IOException {
    return new Lucene41PostingsReader(state.directory, state.fieldInfos, state.segmentInfo, state.context, state.segmentSuffix);
  }

  @Override
  public PostingsWriterBase postingsWriterBase(SegmentWriteState state) throws IOException {
    return new Lucene41PostingsWriter(state);
  }
}


text:
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations;

namespace Stripe.Client.Sdk.Models.Filters
{
    public class ApplicationFeeRefundListFilter : ListFilter
    {
        /// <summary>
        ///     The ID of the application fee whose refunds will be retrieved.
        /// </summary>
        /// <value>
        ///     The identifier.
        /// </value>
        [Required]
        [JsonIgnore]
        public string ApplicationFeeId { get; set; }
    }
}


text:
/*
 * EIoSessionEvent.cpp
 *
 *  Created on: 2016-6-16
 *      Author: cxxjava@lotuseed.com
 */

#include "../inc/EIoSessionEvent.hh"

namespace efc {
namespace eio {

sp<ELogger> EIoSessionEvent::logger = ELoggerManager::getLogger("EIoSessionEvent");

EIoSessionEvent::EIoSessionEvent(EIoFilter::NextFilter* nextFilter, sp<EIoSession>& session, EIoSessionEventType::TYPE type) {
	this->nextFilter = nextFilter;
	this->session = session;
	this->type = type;
}

EIoSessionEvent::EIoSessionEvent(EIoFilter::NextFilter* nextFilter,
		sp<EIoSession>& session, EIdleStatus status) {
	this->nextFilter = nextFilter;
	this->session = session;
	this->type = EIoSessionEventType::IDLE;
	this->status = status;
}

void EIoSessionEvent::deliverEvent() {
	logger->debug__(__FILE__, __LINE__, "Delivering event {%s}", toString().c_str());
	deliverEvent(this->nextFilter, this->session, this->type, this->status);
}

EString EIoSessionEvent::toString() {
	EString sb("EIoSessionEvent");
	sb.append('@');
	sb.append(EInteger::toHexString(hashCode()));
	sb.append(" - [ ").append(session->toString());
	sb.append(", ").append((int)type);
	sb.append(']');
	return sb;
}

EIdleStatus EIoSessionEvent::getStatus() {
	return status;
}

EIoFilter::NextFilter* EIoSessionEvent::getNextFilter() {
	return nextFilter;
}

sp<EIoSession> EIoSessionEvent::getSession() {
	return session;
}

EIoSessionEventType::TYPE EIoSessionEvent::getType() {
	return type;
}

void EIoSessionEvent::deliverEvent(EIoFilter::NextFilter* nextFilter, sp<EIoSession>& session,
			EIoSessionEventType::TYPE type, EIdleStatus status) {
	switch (type) {
	case EIoSessionEventType::CREATED:
		nextFilter->sessionCreated(session);
		break;
	case EIoSessionEventType::OPENED:
		nextFilter->sessionOpened(session);
		break;
	case EIoSessionEventType::IDLE:
		nextFilter->sessionIdle(session, status);
		break;
	case EIoSessionEventType::CLOSED:
		nextFilter->sessionClosed(session);
		break;
	}
}

} /* namespace eio */
} /* namespace efc */


text:
<?php

namespace Aws\Rds\Exception;

/**
 * Exception that occurs when a AuthorizationQuotaExceededException error is encountered
 */
class AuthorizationQuotaExceededException extends RdsException {}


text:
<?php

namespace Page;

use Behat\Mink\Element\NodeElement;
use Behat\Mink\Session;
use Page\UserPageElement\GroupList;
use SensioLabs\Behat\PageObjectExtension\PageObject\Exception\ElementNotFoundException;
use WebDriver\Exception\NoSuchElement;
use WebDriver\Exception\ElementNotVisible;
use WebDriver\Exception\StaleElementReference;

/**
 * Users page.
 */
class UsersPage extends OwncloudPage {

	/**
	 *
	 * @var string $path
	 */
	protected $path = '/index.php/settings/users';

	protected $userTrXpath = ".//table[@id='userlist']/tbody/tr";

	protected $quotaSelectXpath = ".//select[@class='quota-user']";

	protected $quotaOptionXpath = "//option[contains(text(), '%s')]";

	protected $emailColumnXpath = "//td[@class='mailAddress']";
	protected $passwordColumnXpath = "//td[@class='password']";
	protected $quotaColumnXpath = "//td[@class='quota']";
	protected $storageLocationColumnXpath = "//td[@class='storageLocation']";
	protected $lastLoginXpath = "//td[@class='lastLogin']";

	protected $manualQuotaInputXpath
		= "//input[contains(@data-original-title,'Please enter storage quota')]";
	protected $settingsBtnXpath = ".//*[@id='app-settings-header']/button";
	protected $settingContentId = "app-settings-content";
	protected $labelMailOnUserCreateXpath
		= ".//label[@for='CheckboxMailOnUserCreate']";
	protected $settingByTextXpath
		= ".//*[@id='userlistoptions']//label[normalize-space()='%s']";
	protected $newUserUsernameFieldId = "newusername";
	protected $newUserPasswordFieldId = "newuserpassword";
	protected $newUserEmailFieldId = "newemail";
	protected $createUserBtnXpath = ".//*[@id='newuser']/input[@type='submit']";
	protected $newUserGroupsDropDownXpath
		= ".//*[@id='newuser']//div[@class='groupsListContainer multiselect button']";
	protected $newUserGroupsDropDownListTag = "li";
	protected $newUserGroupsSelectedClass = "selected";
	protected $newUserGroupsListXpath
		= ".//*[@id='newuser']//ul[@class='multiselectoptions down']";
	protected $newUserGroupXpath
		= ".//*[@id='newuser']//ul[@class='multiselectoptions down']//label[@title='%s']/..";
	protected $newUserAddGroupBtnXpath
		= ".//*[@id='newuser']//ul[@class='multiselectoptions down']//li[@title='add group']";
	protected $createGroupWithNewUserInputXpath
		= ".//*[@id='newuser']//ul[@class='multiselectoptions down']//input[@type='text']";
	protected $groupListId = "usergrouplist";
	protected $disableUserCheckboxXpath = "//input[@type='checkbox']";
	protected $deleteUserBtnXpath
		= ".//td[@class='remove']/a[@class='action delete']";
	protected $deleteConfirmBtnXpath
		= ".//div[contains(@class, 'oc-dialog-buttonrow twobuttons') and not(ancestor::div[contains(@style, 'display: none')])]//button[text()='Yes']";
	protected $deleteNotConfirmBtnXpath
		= ".//div[contains(@class, 'oc-dialog-buttonrow twobuttons') and not(ancestor::div[contains(@style, 'display: none')])]//button[text()='No']";

	protected $userNameFieldCss = ".name";

	protected $editUserDisplayNameBtnXpath = ".//td[@class='displayName']/img";
	protected $editUserDisplayNameFieldXpath = "/td[@class='displayName']/input";

	protected $editPasswordBtnXpath = ".//td[@class='password']/img";
	protected $editPasswordInputXpath = "/td[@class='password']/input";

	protected $editEmailBtnXpath = ".//td[@class='mailAddress']/img";
	protected $editEmailInputXpath = "/td[@class='mailAddress']/input";

	protected $groupsFieldXpath = ".//td[@class='groups']";
	protected $userGroupsInputXpath = "./div[@class='groupsListContainer multiselect button']";
	protected $groupLabelInInputXpath = ".//ul[@class='multiselectoptions down']/li/label[@title='%s']";
	protected $groupInputXpath = ".//ul[@class='multiselectoptions down']/li/input[@id='%s']";
	protected $activeDropDownXpath = "//div[@class='multiselect button active down']";
	protected $groupUserCountXpath = "//li[@data-gid='%s']//span[@class='usercount']";

	/**
	 * @param string $username
	 *
	 * @return NodeElement for the requested user in the table
	 * @throws \Exception
	 */
	public function findUserInTable($username) {
		$userTrs = $this->findAll('xpath', $this->userTrXpath);

		foreach ($userTrs as $userTr) {
			$user = $userTr->find("css", $this->userNameFieldCss);
			if ($this->getTrimmedText($user) === $username) {
				return $userTr;
			}
		}
		throw new \Exception("Could not find user '$username'");
	}

	/**
	 * @param string $username
	 *
	 * @return string text describing the quota
	 * @throws ElementNotFoundException
	 */
	public function getQuotaOfUser($username) {
		$userTr = $this->findUserInTable($username);
		$selectField = $userTr->find('xpath', $this->quotaSelectXpath);

		if ($selectField === null) {
			throw new ElementNotFoundException(
				__METHOD__ .
				" xpath $this->quotaSelectXpath " .
				"could not find quota select element"
			);
		}

		$xpathLocator = "//option[@value='" . $selectField->getValue() . "']";
		$selectField = $selectField->find('xpath', $xpathLocator);

		if ($selectField === null) {
			throw new ElementNotFoundException(
				__METHOD__ .
				" xpath $xpathLocator " .
				"could not find quota element"
			);
		}

		return $this->getTrimmedText($selectField);
	}

	/**
	 * @param string $username
	 *
	 * @return string email of user
	 * @throws ElementNotFoundException
	 */
	public function getEmailOfUser($username) {
		$userTr = $this->findUserInTable($username);
		$userEmail = $userTr->find('xpath', $this->emailColumnXpath);

		if ($userEmail === null) {
			throw new ElementNotFoundException(
				__METHOD__ .
				" xpath $this->emailColumnXpath " .
				"email of user " . $username . " not found"
			);
		}

		if (!$userEmail->isVisible()) {
			throw new ElementNotVisible(
				__METHOD__ .
				" email of user " . $username . " is not visible"
			);
		};

		return $this->getTrimmedText($userEmail);
	}

	/**
	 * @param string $username
	 *
	 * @return bool
	 * @throws \Exception
	 */
	public function isPasswordColumnOfUserVisible($username) {
		$userTr = $this->findUserInTable($username);
		$userPassword = $userTr->find('xpath', $this->passwordColumnXpath);

		if ($userPassword === null) {
			throw new ElementNotFoundException(
				__METHOD__ .
				" xpath $this->passwordColumnXpath " .
				"password column of user " . $username . " not found"
			);
		}

		if (!$userPassword->isVisible()) {
			return false;
		}

		return true;
	}

	/**
	 * @param string $username
	 *
	 * @return bool
	 * @throws \Exception
	 */
	public function isQuotaColumnOfUserVisible($username) {
		$userTr = $this->findUserInTable($username);
		$userQuota = $userTr->find('xpath', $this->quotaColumnXpath);

		if ($userQuota === null) {
			throw new ElementNotFoundException(
				__METHOD__ .
				" xpath $this->quotaColumnXpath " .
				"quota column of user " . $username . " not found"
			);
		}

		if (!$userQuota->isVisible()) {
			return false;
		}
		return true;
	}

	/**
	 * @param string $username
	 *
	 * @return string storage location of user
	 * @throws ElementNotFoundException
	 */
	public function getStorageLocationOfUser($username) {
		$userTr = $this->findUserInTable($username);
		$userStorageLocation = $userTr->find(
			'xpath',
			$this->storageLocationColumnXpath
		);

		if ($userStorageLocation === null) {
			throw new ElementNotFoundException(
				__METHOD__ .
				" xpath $this->storageLocationColumnXpath " .
				"storage location of user " . $username . " not found"
			);
		}

		if (!$userStorageLocation->isVisible()) {
			throw new ElementNotVisible(
				__METHOD__ .
				" storage location of user " . $username . " is not visible"
			);
		};

		return $this->getTrimmedText($userStorageLocation);
	}

	/**
	 * @param string $username
	 *
	 * @return string last login of a user
	 * @throws ElementNotFoundException
	 */
	public function getLastLoginOfUser($username) {
		$userTr = $this->findUserInTable($username);
		$userLastLogin = $userTr->find(
			'xpath',
			$this->lastLoginXpath
		);

		if ($userLastLogin === null) {
			throw new ElementNotFoundException(
				__METHOD__ .
				" xpath $this->lastLoginXpath " .
				"last login of user " . $username . " not found"
			);
		}

		if (!$userLastLogin->isVisible()) {
			throw new ElementNotVisible(
				__METHOD__ .
				" last login of user " . $username . " is not visible"
			);
		};

		return $this->getTrimmedText($userLastLogin);
	}

	/**
	 * Open the settings menu
	 *
	 * @return void
	 * @throws ElementNotFoundException
	 */
	public function openAppSettingsMenu() {
		$settingsBtn = $this->find("xpath", $this->settingsBtnXpath);
		if ($settingsBtn === null) {
			throw new ElementNotFoundException(
				__METHOD__ .
				" xpath $this->settingsBtnXpath " .
				"could not find settings button"
			);
		}
		$settingsBtn->click();
		// At this point isVisible() on the settings menu returns true
		// But the settings menu animation is happening.
		// If we try to click a setting before the animation is finished
		// then the click is not effective.
		// This results in intermittent test fails, because the expected
		// setting does not happen.
		// Ref: https://github.com/owncloud/core/issues/34689
		\sleep(1);
	}

	/**
	 * sets a setting in the settings menu
	 *
	 * @param string $setting the human readable setting string
	 * @param boolean $value
	 *
	 * @return void
	 * @throws ElementNotFoundException
	 */
	public function setSetting($setting, $value = true) {
		$settingContent = $this->findById($this->settingContentId);
		if ($settingContent === null) {
			throw new ElementNotFoundException(
				__METHOD__ .
				" id $this->settingContentId " .
				"could not find setting content"
			);
		}

		try {
			$settingContentIsVisible = $settingContent->isVisible();
		} catch (NoSuchElement $e) {
			// Somehow on Edge this can throw NoSuchElement even though
			// we just found the element.
			// TODO: Edge - if it keeps happening then find out why.
			\error_log(
				__METHOD__
				. " NoSuchElement while doing settingContent->isVisible()"
				. "\n-------------------------\n"
				. $e->getMessage()
				. "\n-------------------------\n"
			);
			$settingContentIsVisible = false;
		}

		if (!$settingContentIsVisible) {
			$this->openAppSettingsMenu();
		}

		$xpathLocator = \sprintf($this->settingByTextXpath, $setting);
		$settingLabel = $this->find("xpath", $xpathLocator);
		if ($settingLabel === null) {
			throw new ElementNotFoundException(
				__METHOD__ .
				" xpath $xpathLocator " .
				"could not find setting '" . $setting . "'"
			);
		}
		//the checkbox is not visible, but we need it to find the status
		$checkBoxId = $settingLabel->getAttribute("for");
		$checkBox = $this->findById($checkBoxId);
		if ($checkBox === null) {
			throw new ElementNotFoundException(
				__METHOD__ .
				" could not find checkbox with the id '" . $checkBoxId . "'"
			);
		}
		if ($checkBox->isChecked() !== $value) {
			$settingLabel->click();
		}
	}

	/**
	 * creates a user and adds it to the required groups
	 * if group does not exist it will be created
	 *
	 * @param Session $session
	 * @param string $username
	 * @param string $password
	 * @param string $email
	 * @param string[] $groups
	 *
	 * @return void
	 * @throws ElementNotFoundException
	 */
	public function createUser(
		Session $session, $username, $password, $email = null, $groups = null
	) {
		$this->setSetting("Set password for new users", $password !== null);
		$this->fillField($this->newUserUsernameFieldId, $username);
		if ($password !== null) {
			$this->fillField($this->newUserPasswordFieldId, $password);
		}
		if ($email !== null) {
			$this->setSetting("Show email address", true);
			$this->fillField($this->newUserEmailFieldId, $email);
		}
		$createUserBtn = $this->find("xpath", $this->createUserBtnXpath);
		if ($createUserBtn === null) {
			throw new ElementNotFoundException(
				__METHOD__ .
				" xpath $this->createUserBtnXpath " .
				"could not find create user button"
			);
		}
		$newUserGroupsDropDown = $this->find(
			"xpath", $this->newUserGroupsDropDownXpath
		);
		if ($newUserGroupsDropDown === null) {
			throw new ElementNotFoundException(
				__METHOD__ .
				" xpath $this->newUserGroupsDropDownXpath " .
				"could not find groups dropdown for new user"
			);
		}
		$newUserGroupsDropDown->click();
		$groupDropDownList = $this->find("xpath", $this->newUserGroupsListXpath);
		if ($groupDropDownList === null) {
			throw new ElementNotFoundException(
				__METHOD__ .
				" xpath $this->newUserGroupsListXpath " .
				"could not find groups dropdown list"
			);
		}
		$groupsInDropDown = $groupDropDownList->findAll(
			"xpath", $this->newUserGroupsDropDownListTag
		);

		//uncheck all selected groups
		foreach ($groupsInDropDown as $groupLi) {
			if ($groupLi->getAttribute("class") === $this->newUserGroupsSelectedClass) {
				$groupLi->click();
			}
		}

		//now select all groups that we need to have
		if (\is_array($groups)) {
			foreach ($groups as $group) {
				$groupItem = $this->find(
					"xpath", \sprintf($this->newUserGroupXpath, $group)
				);
				if ($groupItem !== null) {
					$groupItem->click();
				} else {
					$newUserAddGroupBtn = $this->find(
						"xpath", $this->newUserAddGroupBtnXpath
					);
					if ($newUserAddGroupBtn === null) {
						throw new ElementNotFoundException(
							__METHOD__ .
							" xpath $this->newUserAddGroupBtnXpath " .
							"could not find add-group button while creating a new user"
						);
					}
					$newUserAddGroupBtn->click();
					$createUserInput = $this->find(
						"xpath", $this->createGroupWithNewUserInputXpath
					);
					if ($createUserInput === null) {
						throw new ElementNotFoundException(
							__METHOD__ .
							" xpath $this->createGroupWithNewUserInputXpath " .
							"could not find add-group input while creating a new user"
						);
					}
					try {
						$createUserInput->setValue($group . "\n");
					} catch (NoSuchElement $e) {
						// this seems to be a bug in MinkSelenium2Driver.
						// Actually all that we need does happen,
						// so we just don't do anything
					}
				}
			}
		}

		$createUserBtn->click();
		$this->waitForAjaxCallsToStartAndFinish($session);
	}

	/**
	 * @param string $username
	 * @param string $quota text form of quota to be input
	 * @param Session $session
	 * @param boolean $valid is the set quota expected to be valid
	 *
	 * @return void
	 * @throws ElementNotFoundException
	 */
	public function setQuotaOfUserTo(
		$username, $quota, Session $session, $valid = true
	) {
		$userTr = $this->findUserInTable($username);
		$selectField = $userTr->find('xpath', $this->quotaSelectXpath);

		if ($selectField === null) {
			throw new ElementNotFoundException(
				__METHOD__ .
				" xpath $this->quotaSelectXpath " .
				"could not find quota select element for user $username"
			);
		}
		$selectField->click();
		$selectOption = $selectField->find(
			'xpath', \sprintf($this->quotaOptionXpath, $quota)
		);
		if ($selectOption === null) {
			$xpathLocator = \sprintf($this->quotaOptionXpath, "Other");
			$selectOption = $selectField->find('xpath', $xpathLocator);

			if ($selectOption === null) {
				throw new ElementNotFoundException(
					__METHOD__ .
					" xpath $xpathLocator " .
					"could not find quota option element for user $username"
				);
			}

			$selectOption->click();
			$manualQuotaInputElement = $this->find(
				'xpath', $this->manualQuotaInputXpath
			);

			if ($manualQuotaInputElement === null) {
				throw new ElementNotFoundException(
					__METHOD__ .
					" xpath $this->manualQuotaInputXpath " .
					"could not find manual quota input element for user $username"
				);
			}

			$manualQuotaInputElement->setValue($quota);
		} else {
			$selectOption->click();
		}
		//a valid quota will be send by AJAX to the server
		//invalid quotas are checked by JS, so we just wait for the notification to appear
		if ($valid === true) {
			$this->waitForAjaxCallsToStartAndFinish($session);
		} else {
			try {
				$this->waitTillXpathIsVisible(
					"//*[@id='$this->notificationId']", 1000
				);
			} catch (\Exception $e) {
				// Sometimes the notification is not "noticed".
				// Later steps are responsible for caring if a notification
				// is actually seen, so just output some information
				$message = __METHOD__ . " INFORMATION: notificationId '" .
					$this->notificationId . "' did not become visible";
				echo $message;
				\error_log($message);
			}
		}
	}

	/**
	 *
	 * @return GroupList
	 * @throws ElementNotFoundException
	 */
	private function getGroupListElement() {
		$groupListElement = $this->findById($this->groupListId);
		if ($groupListElement === null) {
			throw new ElementNotFoundException(
				__METHOD__ .
				" id $this->groupListId " .
				"could not find group list element"
			);
		}

		/**
		 *
		 * @var GroupList $groupList
		 */
		$groupList = $this->getPage("UserPageElement\\GroupList");
		$groupList->setElement($groupListElement);
		return $groupList;
	}

	/**
	 * returns all group names as an array
	 *
	 * @return string[]
	 */
	public function getAllGroups() {
		$groupList = $this->getGroupListElement();
		return $groupList->namesToArray();
	}

	/**
	 *
	 * @param string $name
	 * @param Session $session
	 * @param bool $confirm true is to delete and false is not to delete
	 *
	 * @return void
	 */
	public function deleteGroup($name, Session $session, $confirm = false) {
		$groupList = $this->getGroupListElement();
		$groupList->deleteGroup($name, $confirm);
		$this->waitForAjaxCallsToStartAndFinish($session);
	}

	/**
	 *
	 * @param string $groupName
	 * @param Session $session
	 *
	 * @return void
	 */
	public function addGroup($groupName, Session $session) {
		$groupList = $this->getGroupListElement();
		$groupList->addGroup($groupName);
		$this->waitForAjaxCallsToStartAndFinish($session);
	}

	/**
	 *
	 * @param string $username
	 *
	 * @return void
	 */
	public function disableUser($username) {
		$userTr = $this->findUserInTable($username);
		$userTr->find("xpath", $this->disableUserCheckboxXpath)->click();
	}

	/**
	 *
	 * @param string $username
	 * @param bool $confirm
	 * @param Session $session
	 *
	 * @return void
	 */
	public function deleteUser($username, $confirm, Session $session) {
		$userTr = $this->findUserInTable($username);
		$deleteBtn = $userTr->find("xpath", $this->deleteUserBtnXpath);
		if ($deleteBtn === null) {
			throw new ElementNotFoundException(
				__METHOD__ .
				" xpath $this->deleteUserBtnXpath " .
				"could not find delete user field for user $username"
			);
		}
		$deleteBtn->click();
		$this->waitForAjaxCallsToStartAndFinish($session);

		if ($confirm) {
			$confirmBtn = $this->waitTillXpathIsVisible($this->deleteConfirmBtnXpath);
		} else {
			$confirmBtn = $this->waitTillXpathIsVisible($this->deleteNotConfirmBtnXpath);
		}

		if ($confirmBtn === null) {
			$xpathSelector = ($confirm) ? $this->deleteConfirmBtnXpath : $this->deleteNotConfirmBtnXpath;
			throw new ElementNotFoundException(
				__METHOD__ .
				" xpath $xpathSelector " .
				"could not find delete confirm button for user $username"
			);
		}

		$confirmBtn->click();
	}

	/**
	 * @param Session $session
	 * @param string $username
	 * @param string $displayName
	 *
	 * @return void
	 */
	public function setDisplayNameofUserTo(Session $session, $username, $displayName) {
		$userTr = $this->findUserInTable($username);
		$editDisplayNameBtn = $userTr->find("xpath", $this->editUserDisplayNameBtnXpath);
		if ($editDisplayNameBtn === null) {
			throw new ElementNotFoundException(
				__METHOD__ .
				" xpath $this->editDisplayNameBtn " .
				"could not find edit button for user $username"
			);
		}
		$editDisplayNameBtn->focus();
		$editDisplayNameBtn->click();
		$this->waitForAjaxCallsToStartAndFinish($session);
		$editDisplayNameInput = $userTr->find("xpath", $this->editUserDisplayNameFieldXpath);
		if ($editDisplayNameInput === null) {
			throw new ElementNotFoundException(
				__METHOD__ .
				" xpath $this->editDisplayNameInput " .
				"could not find display name field for user $username"
			);
		}
		try {
			$editDisplayNameInput->focus();
			$editDisplayNameInput->setValue($displayName . "\n");
			$this->waitForAjaxCallsToStartAndFinish($session);
		} catch (StaleElementReference $e) {
		}
	}

	/**
	 * @param Session $session
	 * @param string $user
	 * @param string $password
	 *
	 * @return void
	 */
	public function changeUserPassword(Session $session, $user, $password) {
		$userTr = $this->findUserInTable($user);
		$editPasswordBtn = $userTr->find("xpath", $this->editPasswordBtnXpath);
		if ($editPasswordBtn === null) {
			throw new ElementNotFoundException(
				__METHOD__ .
				" xpath $this->editPasswordBtnXpath " .
				"could not find edit button for user $user"
			);
		}
		$editPasswordBtn->focus();
		$editPasswordBtn->click();
		$this->waitForAjaxCallsToStartAndFinish($session);
		$editPasswordInput = $userTr->find("xpath", $this->editPasswordInputXpath);
		if ($editPasswordInput === null) {
			throw new ElementNotFoundException(
				__METHOD__ .
				" xpath $this->editPasswordInputXpath " .
				"could not find password field for user $user"
			);
		}
		try {
			$editPasswordInput->focus();
			$editPasswordInput->setValue($password . "\n");
		} catch (StaleElementReference $e) {
		}
		$this->waitForAjaxCallsToStartAndFinish($session);
	}

	/**
	 * @param Session $session
	 * @param string $user
	 * @param string $email
	 *
	 * @return void
	 */
	public function changeUserEmail(Session $session, $user, $email) {
		$userTr = $this->findUserInTable($user);
		$editEmailBtn = $userTr->find("xpath", $this->editEmailBtnXpath);
		$this->assertElementNotNull(
			$editEmailBtn,
			__METHOD__ .
			" xpath $this->editEmailBtnXpath " .
			"could not find edit button "
		);
		$editEmailBtn->focus();
		$editEmailBtn->click();
		$this->waitForAjaxCallsToStartAndFinish($session);
		$editEmailInput = $userTr->find("xpath", $this->editEmailInputXpath);
		$this->assertElementNotNull(
			$editEmailInput,
			__METHOD__ .
			" xpath $this->editEmailInputXpath " .
			"could not find email field "
		);
		// editing email throws StaleElementReference
		// Because the input element disappears as soon as the value is set
		try {
			$editEmailInput->focus();
			$editEmailInput->setValue($email . "\n");
			$this->waitForAjaxCallsToStartAndFinish($session);
		} catch (StaleElementReference $e) {
		}
	}

	/**
	 * @param Session $session
	 * @param string $user
	 * @param string $group
	 * @param boolean $add Boolean value to specify wether to add or remove user from the group
	 *
	 * @return void
	 * @throws ElementNotFoundException
	 */
	public function addOrRemoveUserToGroup(Session $session, $user, $group, $add = true) {
		$userTr = $this->findUserInTable($user);
		$groupsField = $userTr->find('xpath', $this->groupsFieldXpath);
		$userGroupsInput = $groupsField->find("xpath", $this->userGroupsInputXpath);
		if ($userGroupsInput !== null) {
			$userGroupsInput->focus();
			$userGroupsInput->click();
		}
		$this->waitForAjaxCallsToStartAndFinish($session);
		$groupLabel = $groupsField->find('xpath', \sprintf($this->groupLabelInInputXpath, $group));
		if ($groupLabel === null) {
			throw new ElementNotFoundException(
				__METHOD__ .
				" xpath $this->groupLabelInInputXpath " .
				"could not find groups input for user $user"
			);
		}
		$groupInput = $groupsField->find(
			'xpath',
			\sprintf($this->groupInputXpath, $groupLabel->getAttribute('for'))
		);
		if ($groupInput === null) {
			throw new ElementNotFoundException(
				__METHOD__ .
				" xpath $this->groupInputXpath " .
				"could not find input for group $group"
			);
		}
		$status = $groupInput->getValue() === "on";
		// while adding to group only click if the checkbox is not already selected
		// while removing from group only click if the checkbox is already selected
		if ($status xor $add) {
			$groupLabel->focus();
			$groupLabel->click();
			$this->waitForAjaxCallsToStartAndFinish($session);
		}
		$activeDropDown = $this->find('xpath', $this->activeDropDownXpath);
		$this->assertElementNotNull(
			$activeDropDown,
			__METHOD__ .
			" xpath $this->activeDropDownXpath " .
			"could not find any active drop down"
		);
		$activeDropDown->click();
	}

	/**
	 *
	 * @param Session $session
	 * @param int $timeout_msec
	 *
	 * @return void
	 * @throws \Exception
	 */
	public function waitTillPageIsLoaded(
		Session $session,
		$timeout_msec = STANDARD_UI_WAIT_TIMEOUT_MILLISEC
	) {
		// There is always at least the "admin" user in the displayed list of users
		// So wait for the user list to have at least 1 real user in it
		$currentTime = \microtime(true);
		$end = $currentTime + ($timeout_msec / 1000);
		while ($currentTime <= $end) {
			$userTrs = $this->findAll('xpath', $this->userTrXpath);
			foreach ($userTrs as $userTr) {
				$user = $userTr->find("css", $this->userNameFieldCss);
				if ($this->getTrimmedText($user) !== '') {
					// We have found a real user
					// (note that there is a hidden empty "template" row)
					break 2;
				}
			}
			\usleep(STANDARD_SLEEP_TIME_MICROSEC);
			$currentTime = \microtime(true);
		}

		if ($currentTime > $end) {
			throw new \Exception(
				__METHOD__ . " timeout waiting for user list to load on users page"
			);
		}
	}

	/**
	 * @param string $group
	 *
	 * @return int|null
	 * @throws ElementNotFoundException
	 */
	public function getUserCountOfGroup($group) {
		$groupUserCountXpath = \sprintf($this->groupUserCountXpath, $group);
		$groupUserCount = $this->find('xpath', $groupUserCountXpath);
		$this->assertElementNotNull(
			$groupUserCount,
			__METHOD__ .
			" xpath $groupUserCountXpath " .
			"could not find user count for group $group"
		);
		$groupUserCount = \trim($groupUserCount->getText());
		if ($groupUserCount === "") {
			return null;
		}
		return (int) $groupUserCount;
	}
}


text:
<?php

namespace ShopwareCli\Services;

use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Symfony\Component\Console\Question\Question;

/**
 * Class IoService
 * @package ShopwareCli\Services
 */
class IoService
{
    /**
     * @var InputInterface
     */
    private $input;

    /**
     * @var OutputInterface
     */
    private $output;

    /**
     * @var QuestionHelper
     */
    private $questionHelper;

    /**
     * @param InputInterface  $input
     * @param OutputInterface $output
     * @param QuestionHelper  $questionHelper
     */
    public function __construct(
        InputInterface $input,
        OutputInterface $output,
        QuestionHelper $questionHelper
    ) {
        $this->input = $input;
        $this->output = $output;
        $this->questionHelper = $questionHelper;
    }

    /**
     * Returns true if the input is interactive
     *
     * @return bool
     */
    public function isInteractive()
    {
        return $this->input->isInteractive();
    }

    /**
     * Returns true if output is quiet
     *
     * @return bool
     */
    public function isQuiet()
    {
        return $this->output->getVerbosity() === OutputInterface::VERBOSITY_QUIET;
    }

    /**
     * Return true if output is verbose (or more verbose)
     *
     * @return bool
     */
    public function isVerbose()
    {
        return $this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE;
    }

    /**
     * Return true if output is ver verbose (or debug)
     * @return bool
     */
    public function isVeryVerbose()
    {
        return $this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE;
    }

    /**
     * Return true if output is debug
     *
     * @return bool
     */
    public function isDebug()
    {
        return $this->output->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG;
    }

    /**
     * Write a message to STDOUT without trailing newline
     *
     * @param string $message
     */
    public function write($message)
    {
        $this->output->write($message);
    }

    /**
     * Write a message to STDOUT with trailing newline
     *
     * @param $message
     */
    public function writeln($message)
    {
        $this->output->write($message, true);
    }

    /**
     * Ask a $question
     *
     * @param  string|Question $question
     * @param  null            $default
     * @return string
     */
    public function ask($question, $default = null)
    {
        $question = $question instanceof Question ? $question : new Question($question, $default);

        return $this->questionHelper->ask($this->input, $this->output, $question);
    }

    /**
     * Ask for confirmation
     *
     * @param  string|Question $question
     * @param  null            $default
     * @return string
     */
    public function askConfirmation($question, $default = null)
    {
        $question = $question instanceof ConfirmationQuestion
            ? $question
            : new ConfirmationQuestion($question, $default);

        return $this->questionHelper->ask($this->input, $this->output, $question);
    }

    /**
     * Ask a question and validate the result
     *
     * @param string|Question $question
     * @param bool|callable   $validator
     * @param bool|int        $attempts
     * @param null|string     $default
     *
     * @return string
     */
    public function askAndValidate($question, $validator = false, $attempts = false, $default = null)
    {
        $question = $question instanceof Question ? $question : new Question($question, $default);

        if ($attempts) {
            $question->setMaxAttempts($attempts);
        }

        if ($validator) {
            $question->setValidator($validator);
        }

        return $this->questionHelper->ask($this->input, $this->output, $question);
    }

    /**
     * @param  int         $max Maximum steps (0 if unknown)
     * @return ProgressBar
     */
    public function createProgressBar($max = 0)
    {
        return new ProgressBar($this->output, $max);
    }

    /**
     * Clears the screen in the terminal
     */
    public function cls()
    {
        if (!$this->input->isInteractive()) {
            return;
        }

        // http://en.wikipedia.org/wiki/ANSI_escape_code
        $this->output->write(chr(27) . "[2J"); // ED – Erase Display
        $this->output->write(chr(27) . "[1;1H"); // CUP – Set Cursor Position to upper left
    }
}


text:
Param(
  [int]$vmIndex=0
)

$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path

# Visual Studio 2013 x64 and x86 redists
$VS2013_x64 = Join-Path $ScriptDir "vcredist_x64.exe"
Start-Process -File "$VS2013_x64" -Arg '/i /q /norestart' -Wait -Verb RunAs

$VS2013_x86 = Join-Path $ScriptDir "vcredist_x86.exe"
Start-Process -File "$VS2013_x86" -Arg '/i /q /norestart' -Wait -Verb RunAs

# Install MSMPI
$MPIInstaller = Join-Path $ScriptDir "MSMpiSetup.exe"
Start-Process $MPIInstaller -Arg "-unattend" -Wait
Start-Service MsMpiLaunchSvc
Set-Service MsMpiLaunchSvc -StartupType Automatic

$env:MSMPI_BIN = [Environment]::GetEnvironmentVariable("MSMPI_BIN", "Machine")
[Environment]::SetEnvironmentVariable("PATH", $env:PATH + $env:MSMPI_BIN + ";", "Machine")

netsh advfirewall firewall add rule name="ephemeral-tcp" dir=in action=allow localport=49152-65535 protocol=tcp
netsh advfirewall firewall add rule name="ephemeral-udp" dir=in action=allow localport=49152-65535 protocol=udp

# Setup SMB
if ($vmIndex -eq 0) {
    New-Item "D:\shared" -type directory
    New-SmbShare -Name shared -Path D:\shared -FullAccess Everyone
}
cmd /c mklink /D C:\shared \\N0\shared

# SSH setup
$OpenSSHArchive = Join-Path $ScriptDir "OpenSSH-Win64.zip"

$Destination = "C:\"
$OpenSSHDir = Join-Path $Destination "OpenSSH-Win64"

Add-Type -assembly "system.io.compression.filesystem"

[io.compression.zipfile]::ExtractToDirectory($OpenSSHArchive, $Destination)

New-NetFirewallRule -Protocol TCP -LocalPort 22 -Direction Inbound -Action Allow -DisplayName SSH

Start-Process "ssh-keygen.exe" -ArgumentList "-A" -WorkingDirectory $OpenSSHDir -Wait

Start-Process "sshd.exe" -ArgumentList "install" -WorkingDirectory $OpenSSHDir -Wait

$sshd_config = Join-Path $OpenSSHDir "sshd_config"
$sftp_server = Join-Path $OpenSSHDir "sftp-server.exe"

(Get-Content $sshd_config) | Select-String -Pattern '^Subsystem\s+.+$' -NotMatch | Set-Content $sshd_config
Add-Content $sshd_config "`nSubsystem sftp $sftp_server`n"

Start-Service sshd
Set-Service sshd -StartupType Automatic


text:
package cmd

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"

	"github.com/spf13/cobra"

	"github.com/open-policy-agent/opa/format"
	fileurl "github.com/open-policy-agent/opa/internal/file/url"
)

type fmtCommandParams struct {
	overwrite bool
	list      bool
	diff      bool
	fail      bool
}

var fmtParams = fmtCommandParams{}

var formatCommand = &cobra.Command{
	Use:   "fmt [path [...]]",
	Short: "Format Rego source files",
	Long: `Format Rego source files.

The 'fmt' command takes a Rego source file and outputs a reformatted version. If no file path
is provided - this tool will use stdin.
The format of the output is not defined specifically; whatever this tool outputs
is considered correct format (with the exception of bugs).

If the '-w' option is supplied, the 'fmt' command with overwrite the source file
instead of printing to stdout.

If the '-d' option is supplied, the 'fmt' command will output a diff between the
original and formatted source.

If the '-l' option is supplied, the 'fmt' command will output the names of files
that would change if formatted. The '-l' option will suppress any other output
to stdout from the 'fmt' command.

If the '--fail' option is supplied, the 'fmt' command will return a non zero exit
code if a file would be reformatted.`,
	Run: func(cmd *cobra.Command, args []string) {
		os.Exit(opaFmt(args))
	},
}

func opaFmt(args []string) int {

	if len(args) == 0 {
		if err := formatStdin(os.Stdin, os.Stdout); err != nil {
			fmt.Fprintln(os.Stderr, err)
			return 1
		}
		return 0
	}

	for _, filename := range args {

		var err error
		filename, err = fileurl.Clean(filename)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			return 1
		}
		err = filepath.Walk(filename, func(path string, info os.FileInfo, err error) error {
			return formatFile(&fmtParams, os.Stdout, path, info, err)
		})
		if err != nil {
			switch err := err.(type) {
			case fmtError:
				fmt.Fprintln(os.Stderr, err.msg)
				return err.code
			default:
				fmt.Fprintln(os.Stderr, err.Error())
				return 1
			}
		}
	}

	return 0
}

func formatFile(params *fmtCommandParams, out io.Writer, filename string, info os.FileInfo, err error) error {
	if err != nil {
		return err
	}

	if info.IsDir() {
		return nil
	}

	if filepath.Ext(filename) != ".rego" {
		return nil
	}

	contents, err := ioutil.ReadFile(filename)
	if err != nil {
		return newError("failed to open file: %v", err)
	}

	formatted, err := format.Source(filename, contents)
	if err != nil {
		return newError("failed to parse Rego source file: %v", err)
	}

	changed := !bytes.Equal(contents, formatted)

	if params.fail {
		if changed {
			return newError("unexpected diff")
		}
	}

	if params.list {
		if changed {
			fmt.Fprintln(out, filename)
		}
		return nil
	}

	if params.diff {
		if changed {
			stdout, stderr, err := doDiff(contents, formatted)
			if err != nil && stdout.Len() == 0 {
				fmt.Fprintln(os.Stderr, stderr.String())
				return newError("failed to diff formatting: %v", err)
			}

			fmt.Fprintln(out, stdout.String())
		}
		return nil
	}

	if params.overwrite {
		outfile, err := os.OpenFile(filename, os.O_WRONLY|os.O_TRUNC, info.Mode().Perm())
		if err != nil {
			return newError("failed to open file for writing: %v", err)
		}
		defer outfile.Close()
		out = outfile
	}

	_, err = out.Write(formatted)
	if err != nil {
		return newError("failed writing formatted contents: %v", err)
	}

	return nil
}

func formatStdin(r io.Reader, w io.Writer) error {

	contents, err := ioutil.ReadAll(r)
	if err != nil {
		return err
	}

	formatted, err := format.Source("stdin", contents)
	if err != nil {
		return err
	}

	_, err = w.Write(formatted)
	return err
}

func doDiff(old, new []byte) (stdout, stderr bytes.Buffer, err error) {
	o, err := ioutil.TempFile("", ".opafmt")
	if err != nil {
		return stdout, stderr, err
	}
	defer os.Remove(o.Name())
	defer o.Close()

	n, err := ioutil.TempFile("", ".opafmt")
	if err != nil {
		return stdout, stderr, err
	}
	defer os.Remove(n.Name())
	defer n.Close()

	_, err = o.Write(old)
	if err != nil {
		return stdout, stderr, err
	}
	_, err = n.Write(new)
	if err != nil {
		return stdout, stderr, err
	}

	cmd := exec.Command("diff", "-u", o.Name(), n.Name())
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr
	return stdout, stderr, cmd.Run()
}

type fmtError struct {
	msg  string
	code int
}

func (e fmtError) Error() string {
	return fmt.Sprintf("%s (%d)", e.msg, e.code)
}

func newError(msg string, a ...interface{}) fmtError {
	return fmtError{
		msg:  fmt.Sprintf(msg, a...),
		code: 2,
	}
}

func init() {
	formatCommand.Flags().BoolVarP(&fmtParams.overwrite, "write", "w", false, "overwrite the original source file")
	formatCommand.Flags().BoolVarP(&fmtParams.list, "list", "l", false, "list all files who would change when formatted")
	formatCommand.Flags().BoolVarP(&fmtParams.diff, "diff", "d", false, "only display a diff of the changes")
	formatCommand.Flags().BoolVar(&fmtParams.fail, "fail", false, "non zero exit code on reformat")
	RootCommand.AddCommand(formatCommand)
}


text:
package com.khs.sherpa.servlet.request;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public interface SherpaRequest {

	public Object getAttribute(String name);
	public void setAttribute(String name, Object object);

	public void doService(HttpServletRequest request, HttpServletResponse response);
}


text:
/*
 *  ofxBulletHollowSphere.h
 *  Bullet
 *
 *
 */

#ifndef OFXBULLET_HOLLOW_SPHERE
#define OFXBULLET_HOLLOW_SPHERE

#include "ofxBullet.h"
#include "ofxBulletRigidBody.h"

#include "ofMain.h"

class ofxBulletHollowSphere
{

public:

	ofxBulletHollowSphere();

	void create(btDiscreteDynamicsWorld* world, float radius, ofVec3f position, int resolution);

	void translate(ofVec3f position);
	void rotate(ofVec3f position);
	void setCollisionFlags();
	void draw();

	vector<ofxBulletRigidBody*> getChildren() { return m_children; }

private:

	btDiscreteDynamicsWorld* m_world;
	vector<ofxBulletRigidBody*> m_children;

};

#endif


text:
"""Django settings for drf_json_schema project."""

import os
from typing import List

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "wsnbdo@-13+42-vw4l9sw5c^bu5b1^7y8@c)j=b_=oy7i_o!o$"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS: List[str] = []

# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "drf_json_schema.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "APP_DIRS": True,
        "OPTIONS": {"context_processors": [os.path.join(BASE_DIR, "templates")]},
    }
]

WSGI_APPLICATION = "drf_json_schema.wsgi.application"

# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": os.path.join(BASE_DIR, "db.sqlite3"),
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"
    },
    {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
    {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
    {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
]

# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_L10N = True

USE_TZ = True

REST_FRAMEWORK = {
    "TEST_REQUEST_DEFAULT_FORMAT": "vnd.api+json",
    "TEST_REQUEST_RENDERER_CLASSES": (
        "rest_framework_json_schema.renderers.JSONAPITestRenderer",
    ),
}

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/

STATIC_URL = "/static/"


text:
'use strict';

var expect = require('expect');

var path = require('path');
var fixturesDir = path.join(__dirname, 'fixtures/config');

var headLines = require('gulp-test-tools').headLines;
var eraseTime = require('gulp-test-tools').eraseTime;
var runner = require('gulp-test-tools').gulpRunner().basedir(fixturesDir);

describe('config: flags.gulpfile', function() {

  it('Should configure with a .gulp.* file', function(done) {
    runner
      .chdir('flags/gulpfile')
      .gulp()
      .run(cb);

    function cb(err, stdout, stderr) {
      expect(err).toEqual(null);
      expect(stderr).toEqual('');
      stdout = headLines(stdout, 2, 2);
      expect(stdout).toEqual(
        'This gulpfile : ' +
          path.join(fixturesDir, 'flags/gulpfile/is/here/mygulpfile.js') +
          '\n' +
        'The current directory : ' + path.join(fixturesDir, 'flags/gulpfile')
      );
      done(err);
    }
  });

  it('Should configure with a .gulp.* file in the directory specified by ' +
  '\n\t--cwd', function(done) {
    runner
      .gulp('--cwd ./flags/gulpfile')
      .run(cb);

    function cb(err, stdout, stderr) {
      expect(err).toEqual(null);
      expect(stderr).toEqual('');
      stdout = headLines(stdout, 2, 3);
      expect(stdout).toEqual(
        'This gulpfile : ' +
          path.join(fixturesDir, 'flags/gulpfile/is/here/mygulpfile.js') +
          '\n' +
        'The current directory : ' + path.join(fixturesDir, 'flags/gulpfile')
      );
      done(err);
    }
  });

  it('Should ignore a ./gulp.* file if another directory is specified by ' +
  '\n\t--cwd', function(done) {
    runner
      .chdir('./flags/gulpfile')
      .gulp('--cwd ./cwd')
      .run(cb);

    function cb(err, stdout, stderr) {
      expect(err).toEqual(null);
      expect(stderr).toEqual('');
      stdout = headLines(stdout, 1, 3);
      expect(stdout).toEqual(
        'Another gulpfile : ' +
          path.join(fixturesDir, 'flags/gulpfile/cwd/gulpfile.js')
      );
      done(err);
    }
  });

  it('Should ignore a ./.gulp.* file if another gulpfile is specified by ' +
  '\n\t--gulpfile', function(done) {
    runner
      .chdir('./flags/gulpfile')
      .gulp('--gulpfile ./cwd/gulpfile.js')
      .run(cb);

    function cb(err, stdout, stderr) {
      expect(err).toEqual(null);
      expect(stderr).toEqual('');
      stdout = headLines(stdout, 1, 3);
      expect(stdout).toEqual(
        'Another gulpfile : ' +
          path.join(fixturesDir, 'flags/gulpfile/cwd/gulpfile.js')
      );
      done(err);
    }
  });

  it('Should overridden by cli flag: --gulpfile', function(done) {
    runner
      .chdir('./flags/gulpfile/override-by-cliflag')
      .gulp('--gulpfile mygulpfile.js')
      .run(cb);

    function cb(err, stdout, stderr) {
      expect(err).toEqual(null);
      expect(stderr).toEqual('');
      stdout = headLines(stdout, 1, 2);
      expect(stdout).toEqual('Gulpfile : ' + path.join(fixturesDir, 'flags/gulpfile/override-by-cliflag/mygulpfile.js'));
      done(err);
    }
  });

  it('Should autoload a module for loading a specified gulpfile', function(done) {
    this.timeout(0);

    runner
      .chdir('flags/gulpfile/autoload')
      .gulp('dist')
      .run(cb);

    function cb(err, stdout, stderr) {
      expect(err).toEqual(null);
      expect(stderr).toEqual('');

      var requiring = eraseTime(headLines(stdout, 1));
      expect(requiring).toEqual('Requiring external module babel-register');
      var clean = eraseTime(headLines(stdout, 1, 4));
      expect(clean).toEqual('clean!');
      var build = eraseTime(headLines(stdout, 1, 7));
      expect(build).toEqual('build!');

      done(err);
    }
  });

});


text:
package org.lvcp.eepperly.exception;

/**
 * Created by eepperly16 on 2/8/16.
 */
public class ExprTypeException extends Exception {
	public ExprTypeException(String message){
		super(message);
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. Pap. 140: 142 (1976)

#### Original name
Cercospora cryptolepidis Pandotra & Ganguly

### Remarks
null