text:
************
Bytecode API
************

* Constants: :data:`__version__`, :data:`UNSET`
* Abstract bytecode: :class:`Label`, :class:`Instr`, :class:`Bytecode`
* Line number: :class:`SetLineno`
* Arguments: :class:`CellVar`, :class:`Compare`, :class:`FreeVar`
* Concrete bytecode: :class:`ConcreteInstr`, :class:`ConcreteBytecode`
* Control Flow Graph (CFG): :class:`BasicBlock`, :class:`ControlFlowGraph`
* Base class: :class:`BaseBytecode`

Constants
=========

.. data:: __version__

   Module version string (ex: ``'0.1'``).

.. data:: UNSET

   Singleton used to mark the lack of value. It is different than ``None``.

Functions
=========

.. function:: dump_bytecode(bytecode, \*, lineno=False)

   Dump a bytecode to the standard output. :class:`ConcreteBytecode`,
   :class:`Bytecode` and :class:`ControlFlowGraph` are accepted for *bytecode*.

   If *lineno* is true, show also line numbers and instruction index/offset.

   This function is written for debug purpose.

Instruction classes
===================

Instr
---------

.. class:: Instr(name: str, arg=UNSET, \*, lineno: int=None)

   Abstract instruction.

   The type of the *arg* parameter (and the :attr:`arg` attribute) depends on
   the operation:

   * If the operation has a jump argument (:meth:`has_jump`, ex:
     ``JUMP_ABSOLUTE``): *arg* must be a :class:`Label` (if the instruction is
     used in :class:`Bytecode`) or a :class:`BasicBlock` (used in
     :class:`ControlFlowGraph`).
   * If the operation has a cell or free argument (ex: ``LOAD_DEREF``): *arg*
     must be a :class:`CellVar` or :class:`FreeVar` instance.
   * If the operation has a local variable (ex: ``LOAD_FAST``): *arg* must be a
     variable name, type ``str``.
   * If the operation has a constant argument (``LOAD_CONST``): *arg* must not
     be a :class:`Label` or :class:`BasicBlock` instance.
   * If the operation has a compare argument (``COMPARE_OP``):
     *arg* must be a :class:`Compare` enum.
   * If the operation has no argument (ex: ``DUP_TOP``), *arg* must not be set.
   * Otherwise (the operation has an argument, ex: ``CALL_FUNCTION``), *arg*
     must be an integer (``int``) in the range ``0``..\ ``2,147,483,647``.

   To replace the operation name and the argument, the :meth:`set` method must
   be used instead of modifying the :attr:`name` attribute and then the
   :attr:`arg` attribute. Otherwise, an exception is be raised if the previous
   operation requires an argument and the new operation has no argument (or the
   opposite).

   Attributes:

   .. attribute:: arg

      Argument value.

      It can be :data:`UNSET` if the instruction has no argument.

   .. attribute:: lineno

      Line number (``int >= 1``), or ``None``.

   .. attribute:: name

      Operation name (``str``). Setting the name updates the :attr:`opcode`
      attibute.

   .. attribute:: opcode

      Operation code (``int``). Setting the operation code updates the
      :attr:`name` attribute.

   .. versionchanged:: 0.3
      The ``op`` attribute was renamed to :attr:`opcode`.

   Methods:

   .. method:: copy()

      Create a copy of the instruction.

   .. method:: is_final() -> bool

      Is the operation a final operation?

      Final operations:

      * RETURN_VALUE
      * RAISE_VARARGS
      * BREAK_LOOP
      * CONTINUE_LOOP
      * unconditional jumps: :meth:`is_uncond_jump`

   .. method:: has_jump() -> bool

      Does the operation have a jump argument?

      More general than :meth:`is_cond_jump` and :meth:`is_uncond_jump`, it
      includes other operations. Examples:

      * FOR_ITER
      * SETUP_EXCEPT
      * CONTINUE_LOOP

   .. method:: is_cond_jump() -> bool

      Is the operation an conditional jump?

      Conditional jumps:

      * JUMP_IF_FALSE_OR_POP
      * JUMP_IF_TRUE_OR_POP
      * POP_JUMP_IF_FALSE
      * POP_JUMP_IF_TRUE

   .. method:: is_uncond_jump() -> bool

      Is the operation an unconditional jump?

      Unconditional jumps:

      * JUMP_FORWARD
      * JUMP_ABSOLUTE

   .. method:: set(name: str, arg=UNSET)

      Modify the instruction in-place: replace :attr:`name` and :attr:`arg`
      attributes, and update the :attr:`opcode` attribute.

      .. versionchanged:: 0.3
         The *lineno* parameter has been removed.

   .. method:: stack_effect(jump: bool = None) -> int

      Operation effect on the stack size as computed by
      :func:`dis.stack_effect`.

      The *jump* argument takes one of three values.  None (the default)
      requests the largest stack effect.  This works fine with most
      instructions.  True returns the stack effect for taken branches.  False
      returns the stack effect for non-taken branches.

      .. versionchanged:: 0.8
         ``stack_method`` was changed from a property to a method in order to
         add the keyword argument *jump*.

ConcreteInstr
-------------

.. class:: ConcreteInstr(name: str, arg=UNSET, \*, lineno: int=None)

   Concrete instruction Inherit from :class:`Instr`.

   If the operation requires an argument, *arg* must be an integer (``int``) in
   the range ``0``..\ ``2,147,483,647``. Otherwise, *arg* must not by set.

   Concrete instructions should only be used in :class:`ConcreteBytecode`.

   Attributes:

   .. attribute:: arg

      Argument value: an integer (``int``) in the range ``0``..\
      ``2,147,483,647``, or :data:`UNSET`. Setting the argument value can
      change the instruction size (:attr:`size`).

   .. attribute:: size

      Read-only size of the instruction in bytes (``int``): between ``1`` byte
      (no agument) and ``6`` bytes (extended argument).

   Static method:

   .. staticmethod:: disassemble(code: bytes, offset: int) -> ConcreteInstr

      Create a concrete instruction from a bytecode string.

   Methods:

   .. method:: get_jump_target(instr_offset: int) -> int or None

      Get the absolute target offset of a jump. Return ``None`` if the
      instruction is not a jump.

      The *instr_offset* parameter is the offset of the instruction. It is
      required by relative jumps.

   .. method:: assemble() -> bytes

      Assemble the instruction to a bytecode string.

Compare
-------

.. class:: Compare

   Enum for the argument of the ``COMPARE_OP`` instruction.

   Equality test:

   * ``Compare.EQ`` (``2``): ``x == y``
   * ``Compare.NE`` (``3``): ``x != y``
   * ``Compare.IS`` (``8``): ``x is y``
   * ``Compare.IS_NOT`` (``9``): ``x is not y``

   Inequality test:

   * ``Compare.LT`` (``0``): ``x < y``
   * ``Compare.LE`` (``1``): ``x <= y``
   * ``Compare.GT`` (``4``): ``x > y``
   * ``Compare.GE`` (``5``): ``x >= y``

   Other tests:

   * ``Compare.IN`` (``6``): ``x in y``
   * ``Compare.NOT_IN`` (``7``): ``x not in y``
   * ``Compare.EXC_MATCH`` (``10``): used to compare exceptions
     in ``except:`` blocks

Label
-----

.. class:: Label

   Pseudo-instruction used as targets of jump instructions.

   Label targets are "resolved" by :class:`Bytecode.to_concrete_bytecode`.

   Labels must only be used in :class:`Bytecode`.

SetLineno
---------

.. class:: SetLineno(lineno: int)

   Pseudo-instruction to set the line number of following instructions.

   *lineno* must be greater or equal than ``1``.

   .. attribute:: lineno

      Line number (``int``), read-only attribute.

Bytecode classes
================

BaseBytecode
------------

.. class:: BaseBytecode

   Base class of bytecode classes.

   Attributes:

   .. attribute:: argcount

      Argument count (``int``), default: ``0``.

   .. attribute:: cellvars

      Names of the cell variables (``list`` of ``str``), default: empty list.

   .. attribute:: docstring

      Documentation string aka "docstring" (``str``), ``None``, or
      :data:`UNSET`.  Default: :data:`UNSET`.

      If set, it is used by :meth:`ConcreteBytecode.to_code` as the first
      constant of the created Python code object.

   .. attribute:: filename

      Code filename (``str``), default: ``'<string>'``.

   .. attribute:: first_lineno

      First line number (``int``), default: ``1``.

   .. attribute:: flags

      Flags (``int``).

   .. attribute:: freevars

      List of free variable names (``list`` of ``str``), default: empty list.

   .. attribute:: kwonlyargcount

      Keyword-only argument count (``int``), default: ``0``.

   .. attribute:: name

      Code name (``str``), default: ``'<module>'``.

   .. versionchanged:: 0.3
      Attribute ``kw_only_argcount`` renamed to :attr:`kwonlyargcount`.

Bytecode
--------

.. class:: Bytecode

   Abstract bytecode: list of abstract instructions (:class:`Instr`).
   Inherit from :class:`BaseBytecode` and :class:`list`.

   A bytecode must only contain objects of the 4 following types:

   * :class:`Label`
   * :class:`SetLineno`
   * :class:`Instr`
   * :class:`ConcreteInstr`

   It is possible to use concrete instructions (:class:`ConcreteInstr`), but
   abstract instructions are preferred.

   Attributes:

   .. attribute:: argnames

      List of the argument names (``list`` of ``str``), default: empty list.

   Static methods:

   .. staticmethod:: from_code(code) -> Bytecode

      Create an abstract bytecode from a Python code object.

   Methods:

   .. method:: to_concrete_bytecode(compute_jumps_passes: int = None) -> ConcreteBytecode

      Convert to concrete bytecode with concrete instructions.

      Resolve jump targets: replace abstract labels (:class:`Label`) with
      concrete instruction offsets (relative or absolute, depending on the
      jump operation).  It will also add EXTENDED_ARG prefixes to jump
      instructions to ensure that the target instructions can be reached.

      If *compute_jumps_passes* is not None, it sets the upper limit for the
      number of passes that can be made to generate EXTENDED_ARG prefixes for
      jump instructions. If None then an internal default is used.  The number
      of passes is, in theory, limited only by the number of input
      instructions, however a much smaller default is used because the
      algorithm converges quickly on most code.  For example, running CPython
      3.6.5 unittests on OS X 11.13 results in 264996 compiled methods, only
      one of which requires 5 passes, and none requiring more.

   .. method:: to_code(compute_jumps_passes: int = None, stacksize: int = None) -> types.CodeType

      Convert to a Python code object.

      It is based on :meth:`to_concrete_bytecode` and so resolve jump targets.

      *compute_jumps_passes*: see :meth:`to_concrete_bytecode`

      *stacksize*: see :meth:`ConcreteBytecode.to_code`

   .. method:: compute_stacksize() -> int

      Compute the stacksize needed to execute the code. Will raise an
      exception if the bytecode is invalid.

      This computation requires to build the control flow graph associated with
      the code.

    .. method:: update_flags(is_async: bool = False)

      Update the object flags by calling :py:func:infer_flags on itself.

ConcreteBytecode
----------------

.. class:: ConcreteBytecode

   List of concrete instructions (:class:`ConcreteInstr`).
   Inherit from :class:`BaseBytecode`.

   A concrete bytecode must only contain objects of the 2 following types:

   * :class:`SetLineno`
   * :class:`ConcreteInstr`

   :class:`Label` and :class:`Instr` must not be used in concrete bytecode.

   Attributes:

   .. attribute:: consts

      List of constants (``list``), default: empty list.

   .. attribute:: names

      List of names (``list`` of ``str``), default: empty list.

   .. attribute:: varnames

      List of variable names (``list`` of ``str``), default: empty list.

   Static methods:

   .. staticmethod:: from_code(code, \*, extended_arg=false) -> ConcreteBytecode

      Create a concrete bytecode from a Python code object.

      If *extended_arg* is true, create ``EXTENDED_ARG`` instructions.
      Otherwise, concrete instruction use extended argument (size of ``6``
      bytes rather than ``3`` bytes).

   Methods:

   .. method:: to_code(stacksize: int = None) -> types.CodeType

      Convert to a Python code object.

      On Python older than 3.6, raise an exception on negative line number
      delta.

      *stacksize* Allows caller to explicitly specify a stacksize.  If not
      specified a ControlFlowGraph is created internally in order to call
      ControlFlowGraph.compute_stacksize().  It's cheaper to pass a value if
      the value is known.

   .. method:: to_bytecode() -> Bytecode

      Convert to abstract bytecode with abstract instructions.

   .. method:: compute_stacksize() -> int

      Compute the stacksize needed to execute the code. Will raise an
      exception if the bytecode is invalid.

      This computation requires to build the control flow graph associated with
      the code.

   .. method:: update_flags(is_async: bool = False)

      Update the object flags by calling :py:func:infer_flags on itself.

BasicBlock
----------

.. class:: BasicBlock

   `Basic block <https://en.wikipedia.org/wiki/Basic_block>`_. Inherit from
   :class:`list`.

   A basic block is a straight-line code sequence of abstract instructions
   (:class:`Instr`) with no branches in except to the entry and no branches out
   except at the exit.

   A block must only contain objects of the 3 following types:

   * :class:`SetLineno`
   * :class:`Instr`
   * :class:`ConcreteInstr`

   It is possible to use concrete instructions (:class:`ConcreteInstr`) in
   blocks, but abstract instructions (:class:`Instr`) are preferred.

   Only the last instruction can have a jump argument, and the jump argument
   must be a basic block (:class:`BasicBlock`).

   Labels (:class:`Label`) must not be used in blocks.

   Attributes:

   .. attribute:: next_block

      Next basic block (:class:`BasicBlock`), or ``None``.

   Methods:

   .. method:: get_jump()

      Get the target block (:class:`BasicBlock`) of the jump if the basic block
      ends with an instruction with a jump argument. Otherwise, return
      ``None``.

ControlFlowGraph
----------------

.. class:: ControlFlowGraph

   `Control flow graph (CFG)
   <https://en.wikipedia.org/wiki/Control_flow_graph>`_: list of basic blocks
   (:class:`BasicBlock`). A basic block is a straight-line code sequence of
   abstract instructions (:class:`Instr`) with no branches in except to the
   entry and no branches out except at the exit. Inherit from
   :class:`BaseBytecode`.

   Labels (:class:`Label`) must not be used in blocks.

   This class is not designed to emit code, but to analyze and modify existing
   code. Use :class:`Bytecode` to emit code.

   Attributes:

   .. attribute:: argnames

      List of the argument names (``list`` of ``str``), default: empty list.

   Methods:

   .. staticmethod:: from_bytecode(bytecode: Bytecode) -> ControlFlowGraph

      Convert a :class:`Bytecode` object to a :class:`ControlFlowGraph` object:
      convert labels to blocks.

      Splits blocks after final instructions (:meth:`Instr.is_final`) and after
      conditional jumps (:meth:`Instr.is_cond_jump`).

   .. method:: add_block(instructions=None) -> BasicBlock

      Add a new basic block. Return the newly created basic block.

   .. method:: get_block_index(block: BasicBlock) -> int

      Get the index of a block in the bytecode.

      Raise a :exc:`ValueError` if the block is not part of the bytecode.

      .. versionadded:: 0.3

   .. method:: split_block(block: BasicBlock, index: int) -> BasicBlock

      Split a block into two blocks at the specific instruction. Return
      the newly created block, or *block* if index equals ``0``.

   .. method:: to_bytecode() -> Bytecode

      Convert to a bytecode object using labels.

   .. method:: compute_stacksize() -> int

      Compute the stack size required by a bytecode object. Will raise an
      exception if the bytecode is invalid.

   .. method:: update_flags(is_async: bool = False)

      Update the object flags by calling :py:func:infer_flags on itself.

   .. method:: to_code(stacksize: int = None)

      Convert to a Python code object.  Refer to descriptions of
      :meth:`Bytecode.to_code` and :meth:`ConcreteBytecode.to_code`.

Cell and Free Variables
=======================

CellVar
-------

.. class:: CellVar(name: str)

   Cell variable used for instruction argument by operations taking a cell or
   free variable name.

   Attributes:

   .. attribute:: name

      Name of the cell variable (``str``).

FreeVar
-------

.. class:: FreeVar(name: str)

   Free variable used for instruction argument by operations taking a cell or
   free variable name.

   Attributes:

   .. attribute:: name

      Name of the free variable (``str``).

Line Numbers
============

The line number can set directly on an instruction using the ``lineno``
parameter of the constructor. Otherwise, the line number if inherited from the
previous instruction, starting at ``first_lineno`` of the bytecode.

:class:`SetLineno` pseudo-instruction can be used to set the line number of
following instructions.

Compiler Flags
==============

.. class:: CompilerFlags()

    .. attribute:: OPTIMIZED

        Set if a code object only uses fast locals

    .. attribute:: NEWLOCALS

        Set if the code execution should be done with a new local scope

    .. attribute:: VARARGS

        Set if a code object expects variable number of positional arguments

    .. attribute:: VARKEYWORDS

        Set if a code object expects variable number of keyword arguments

    .. attribute:: NESTED

        Set if a code object correspond to function defined in another function

    .. attribute:: GENERATOR

        Set if a code object is a generator (contains yield instructions)

    .. attribute:: NOFREE

        Set if a code object does not use free variables

    .. attribute:: COROUTINE

        Set if a code object is a coroutine. New in Python 3.5

    .. attribute:: ITERABLE_COROUTINE

        Set if a code object is an iterable coroutine. New in Python 3.5

    .. attribute:: ASYNC_GENERATOR

        Set if a code object is an asynchronous generator. New in Python 3.6

    .. attribute:: FUTURE_GENERATOR_STOP

        Set if a code object is defined in a context in which generator_stop
        has been imported from \_\_future\_\_

.. function:: infer_flags(bytecode, async: bool = False) -> CompilerFlags

    Infer the correct values for the compiler flags for a given bytecode based
    on the instructions. The flags that can be inferred are :

    - OPTIMIZED
    - GENRATOR
    - NOFREE
    - COROUTINE
    - ASYNC_GENERATOR

    The async optional keyword allow to force a detected generator to be turned
    into a generator. A code will be marked as a COROUTINE only if it contains
    an async related instruction.


text:
package annis.sqlgen;

import static annis.sqlgen.SqlConstraints.in;
import static annis.sqlgen.TableAccessStrategy.NODE_TABLE;
import static annis.sqlgen.TableAccessStrategy.RANK_TABLE;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import annis.model.QueryNode;
import annis.ql.parser.QueryData;
import java.util.LinkedList;

/**
 *
 * @author thomas
 */
public class MetaDataAndCorpusWhereClauseGenerator
  extends TableAccessStrategyFactory
  implements WhereClauseSqlGenerator<QueryData>
{

  @Override
  public Set<String> whereConditions(QueryData queryData,
    List<QueryNode> alternative, String indent)
  {
    Set<String> conditions = new HashSet<>();
    List<Long> corpusList = queryData.getCorpusList();
    List<Long> documents = queryData.getDocuments();

    if (documents == null && corpusList == null)
    {
      return new HashSet<>();
    }

    for (QueryNode node : alternative)
    {
      // FIXME: where condition comment should be optional
      // conditions.add("-- select documents by metadata and toplevel corpus");
      if (documents != null)
      {
        List<String> emptyList = new LinkedList<>();
        emptyList.add("NULL");

        conditions.add(in(tables(node).aliasedColumn(NODE_TABLE, "corpus_ref"),
          documents.isEmpty() ? emptyList : documents));
      }

      if (corpusList != null && !corpusList.isEmpty())
      {
        conditions.add(in(tables(node).aliasedColumn(NODE_TABLE,
          "toplevel_corpus"),
          corpusList));
        if(tables(node).usesRankTable() && !tables(node).isMaterialized(RANK_TABLE, NODE_TABLE))
        {
          conditions.add(in(tables(node).aliasedColumn(RANK_TABLE,
            "toplevel_corpus"),
            corpusList));
        }
      }
    }

    return conditions;
  }
}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Biblthca Mycol. 47: 116 (1976)

#### Original name
Boletus badius var. glaber Grund & K.A. Harrison

### Remarks
null


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context=".MainActivity">

  <item android:id="@+id/action_add"
        android:title="@string/add_product"
        android:icon="@drawable/ic_add_white_24dp"
        android:orderInCategory="1"
        app:showAsAction="ifRoom"/>

  <item android:id="@+id/action_clear_shopping_list"
        android:title="@string/clear_shopping_list"
        android:icon="@drawable/ic_clear_all_white_24dp"
        android:orderInCategory="2"
        app:showAsAction="never"/>

  <item android:id="@+id/action_export"
        android:title="@string/export_data"
        android:icon="@drawable/ic_file_upload_white_24dp"
        android:orderInCategory="3"
        app:showAsAction="never"/>

  <item android:id="@+id/action_import"
        android:title="@string/import_data"
        android:icon="@drawable/ic_file_download_white_24dp"
        android:orderInCategory="4"
        app:showAsAction="never"/>

  <item android:id="@+id/action_settings"
        android:title="@string/settings"
        android:icon="@drawable/ic_settings_white_24dp"
        android:orderInCategory="5"
        app:showAsAction="never"/>

</menu>


text:
const Code = require('@hapi/code');
const Hapi = require('@hapi/hapi');
const Hoek = require('@hapi/hoek');
const Inert = require('@hapi/inert');
const Joi = require('joi');
const Lab = require('@hapi/lab');
const Vision = require('@hapi/vision');
const { resolve } = require('path');
const HapiSwagger = require('../../lib/index.js');
const Helper = require('../helper.js');
const Validate = require('../../lib/validate.js');

const expect = Code.expect;
const lab = (exports.lab = Lab.script());

lab.experiment('plugin', () => {
  const routes = [
    {
      method: 'POST',
      path: '/store/',
      options: {
        handler: Helper.defaultHandler,
        tags: ['api'],
        validate: {
          payload: Joi.object({
            a: Joi.number(),
            b: Joi.number(),
            operator: Joi.string(),
            equals: Joi.number()
          })
        }
      }
    }
  ];

  lab.test('plug-in register no vision dependency', async () => {
    try {
      const server = new Hapi.Server();
      await server.register([Inert, HapiSwagger]);
      server.route(routes);
      await server.start();
    } catch (err) {
      expect(err.message).to.equal('Plugin hapi-swagger missing dependency @hapi/vision');
    }
  });

  lab.test('plug-in register no inert dependency', async () => {
    try {
      const server = new Hapi.Server();
      await server.register([Vision, HapiSwagger]);
      server.route(routes);
      await server.start();
    } catch (err) {
      expect(err.message).to.equal('Plugin hapi-swagger missing dependency @hapi/inert');
    }
  });

  lab.test('plug-in register no options', async () => {
    try {
      const server = new Hapi.Server();
      await server.register([Inert, Vision, HapiSwagger]);
      server.route(routes);
      await server.start();
      expect(server).to.be.an.object();
    } catch (err) {
      expect(err).to.equal(undefined);
    }
  });

  lab.test('fail plug-in register with bad options', async () => {
    const badOptions = {
      validate: 42
    };
    try {
      await Helper.createServer(badOptions, routes);
    } catch (err) {
      expect(err).to.exist();
      expect(err.name).to.equal('ValidationError');
      expect(err.details).to.have.length(1)
      expect(err.details[0].message).to.equal('"validate" must be of type object')
    }
  });

  lab.test('plug-in register test', async () => {
    const server = await Helper.createServer({}, routes);
    const response = await server.inject({ method: 'GET', url: '/swagger.json' });
    expect(response.statusCode).to.equal(200);
    expect(response.result.paths).to.have.length(1);
  });

  lab.test('plug-in register with validate option', async () => {
    const goodOptions = {
      validate: {
        headers: true
      }
    };
    const server = await Helper.createServer(goodOptions, routes);
    const response = await server.inject({ method: 'GET', url: '/swagger.json' });
    expect(response.statusCode).to.equal(200);
    expect(response.result.paths).to.have.length(1);
  });

  lab.test('plug-in register with server validation options', async () => {
    const serverOptions = {
      routes: {
        validate: {
          failAction: (request, h, err) => {
            Hoek.ignore(request, h)
            throw err
          },
          headers: Joi.object({
            authorization: Joi.string().required()
          })
            .required()
        }
      }
    };
    const server = await Helper.createServer(undefined, routes, serverOptions);
    const response = await server.inject({ method: 'GET', url: '/swagger.json' });
    expect(response.statusCode).to.equal(400);
    expect(response.statusMessage).to.equal('Bad Request');
    expect(response.result.statusCode).to.equal(400);
    expect(response.result.error).to.equal('Bad Request');
    expect(response.result.message).to.equal('"authorization" is required');
  });

  lab.test('plug-in register and overrride server validation options', async () => {
    const serverOptions = {
      routes: {
        validate: {
          failAction: (request, h, err) => {
            Hoek.ignore(request, h)
            throw err
          },
          headers: Joi.object({
            authorization: Joi.string().required()
          })
            .required()
        }
      }
    };
    const pluginOptions = {
      validate: {
        headers: true
      }
    }
    const server = await Helper.createServer(pluginOptions, routes, serverOptions);
    const response = await server.inject({ method: 'GET', url: '/swagger.json' });
    expect(response.statusCode).to.equal(200);
    expect(response.result.paths).to.have.length(1);
  });

  lab.test('default jsonPath url', async () => {
    const server = await Helper.createServer({}, routes);
    const response = await server.inject({ method: 'GET', url: '/swagger.json' });
    expect(response.statusCode).to.equal(200);
  });

  lab.test('default documentationPath url', async () => {
    const server = await Helper.createServer({}, routes);
    const response = await server.inject({ method: 'GET', url: '/documentation' });
    expect(response.statusCode).to.equal(200);
  });

  lab.test('default swaggerUIPath url', async () => {
    const server = await Helper.createServer({}, routes);
    const response = await server.inject({ method: 'GET', url: '/swaggerui/swagger-ui.js' });
    expect(response.statusCode).to.equal(200);
  });

  lab.test('swaggerUIPath + extend.js remapping', async () => {
    const server = await Helper.createServer({}, routes);
    const response = await server.inject({ method: 'GET', url: '/swaggerui/extend.js' });
    expect(response.statusCode).to.equal(200);
  });

  const swaggerOptions = {
    jsonPath: '/test.json',
    documentationPath: '/testdoc',
    swaggerUIPath: '/testui/'
  };

  lab.test('repathed jsonPath url', async () => {
    const server = await Helper.createServer(swaggerOptions, routes);
    const response = await server.inject({ method: 'GET', url: '/test.json' });
    expect(response.statusCode).to.equal(200);
  });

  lab.test('repathed jsonPath url and jsonRoutePath', async () => {
    const jsonRoutePath = '/testRoute/test.json';

    const server = await Helper.createServer(
      {
        ...swaggerOptions,
        jsonRoutePath
      },
      routes
    );

    const notFoundResponse = await server.inject({ method: 'GET', url: '/test.json' });

    expect(notFoundResponse.statusCode).to.equal(404);

    const okResponse = await server.inject({ method: 'GET', url: jsonRoutePath });

    expect(okResponse.statusCode).to.equal(200);
  });

  lab.test('repathed documentationPath url', async () => {
    const server = await Helper.createServer(swaggerOptions, routes);
    const response = await server.inject({ method: 'GET', url: '/testdoc' });
    expect(response.statusCode).to.equal(200);
  });

  lab.test('repathed assets url', async () => {
    const server = await Helper.createServer(swaggerOptions, routes);
    const response = await server.inject({ method: 'GET', url: '/testdoc' });

    expect(response.statusCode).to.equal(200);

    const assets = Helper.getAssetsPaths(response.result);

    assets.forEach(asset => {
      expect(asset).to.contain(swaggerOptions.swaggerUIPath);
    });

    const responses = await Promise.all(
      assets.map(asset => {
        return server.inject({ method: 'GET', url: asset });
      })
    );

    responses.forEach(assetResponse => {
      expect(assetResponse.statusCode).to.equal(200);
    });
  });

  lab.test('repathed assets url and reoutes path', async () => {
    const routesBasePath = '/testRoute/';
    const server = await Helper.createServer(
      {
        ...swaggerOptions,
        routesBasePath
      },
      routes
    );
    const response = await server.inject({ method: 'GET', url: '/testdoc' });

    expect(response.statusCode).to.equal(200);

    const assets = Helper.getAssetsPaths(response.result);

    assets.forEach(asset => {
      expect(asset).to.contain(swaggerOptions.swaggerUIPath);
    });

    const notFoundResponses = await Promise.all(
      assets.map(asset => {
        return server.inject({ method: 'GET', url: asset });
      })
    );

    notFoundResponses.forEach(assetResponse => {
      expect(assetResponse.statusCode).to.equal(404);
    });

    const okResponses = await Promise.all(
      assets.map(asset => {
        return server.inject({ method: 'GET', url: asset.replace(swaggerOptions.swaggerUIPath, routesBasePath) });
      })
    );

    okResponses.forEach(assetResponse => {
      expect(assetResponse.statusCode).to.equal(200);
    });
  });

  lab.test('disable documentation path', async () => {
    const swaggerOptions = {
      documentationPage: false
    };

    const server = await Helper.createServer(swaggerOptions, routes);
    const response = await server.inject({ method: 'GET', url: '/documentation' });
    expect(response.statusCode).to.equal(404);
  });

  lab.test('disable swagger UI', async () => {
    const swaggerOptions = {
      swaggerUI: false,
      documentationPage: false
    };

    const server = await Helper.createServer(swaggerOptions, routes);
    const response = await server.inject({ method: 'GET', url: '/swaggerui/swagger-ui.js' });
    expect(response.statusCode).to.equal(404);
  });

  lab.test('disable swagger UI overridden by documentationPage', async () => {
    const swaggerOptions = {
      swaggerUI: false,
      documentationPage: true
    };

    const server = await Helper.createServer(swaggerOptions, routes);
    const response = await server.inject({ method: 'GET', url: '/swaggerui/swagger-ui.js' });
    expect(response.statusCode).to.equal(200);
  });

  lab.test('should take the plugin route prefix into account when rendering the UI', async () => {
    const server = new Hapi.Server();
    await server.register([
      Inert,
      Vision,
      {
        plugin: HapiSwagger,
        routes: {
          prefix: '/implicitPrefix'
        },
        options: {}
      }
    ]);

    server.route(routes);
    await server.start();
    const response = await server.inject({ method: 'GET', url: '/implicitPrefix/documentation' });
    expect(response.statusCode).to.equal(200);
    const htmlContent = response.result;
    expect(htmlContent).to.contain(['/implicitPrefix/swaggerui/swagger-ui-bundle.js', '/implicitPrefix/swagger.json']);
  });

  lab.test('should use templates options to render ui', async () => {
    const server = new Hapi.Server();
    await server.register([
      Inert,
      Vision,
      {
        plugin: HapiSwagger,
        options: {
          templates: resolve(__dirname, 'templates')
        }
      }
    ]);

    server.route(routes);
    await server.start();
    const response = await server.inject({ method: 'GET', url: '/documentation' });
    expect(response.statusCode).to.equal(200);
    const htmlContent = response.result;
    expect(htmlContent).to.contain(['swagger-ui-userland']);
  });

  lab.test('enable cors settings, should return headers with origin settings', async () => {
    const swaggerOptions = {
      cors: true
    };

    const server = await Helper.createServer(swaggerOptions, routes);
    const response = await server.inject({ method: 'GET', url: '/swagger.json' });

    expect(response.statusCode).to.equal(200);
    // https://stackoverflow.com/questions/25329405/why-isnt-vary-origin-response-set-on-a-cors-miss
    expect(response.headers.vary).to.equal('origin');
    expect(response.result.paths['/store/'].post.parameters.length).to.equal(1);
    expect(response.result.paths['/store/'].post.parameters[0].name).to.equal('body');
  });

  lab.test('disable cors settings, should return headers without origin settings', async () => {
    const swaggerOptions = {
      cors: false
    };

    const server = await Helper.createServer(swaggerOptions, routes);
    const response = await server.inject({ method: 'GET', url: '/swagger.json' });
    expect(response.statusCode).to.equal(200);
    expect(response.headers.vary).to.not.equal('origin');
    expect(response.result.paths['/store/'].post.parameters.length).to.equal(1);
    expect(response.result.paths['/store/'].post.parameters[0].name).to.equal('body');
  });

  lab.test('default cors settings as false, should return headers without origin settings', async () => {
    const swaggerOptions = {};

    const server = await Helper.createServer(swaggerOptions, routes);
    const response = await server.inject({ method: 'GET', url: '/swagger.json' });
    expect(response.statusCode).to.equal(200);
    expect(response.headers.vary).to.not.equal('origin,accept-encoding');
    expect(response.result.paths['/store/'].post.parameters.length).to.equal(1);
    expect(response.result.paths['/store/'].post.parameters[0].name).to.equal('body');
  });

  lab.test('payloadType = form global', async () => {
    const swaggerOptions = {
      payloadType: 'json'
    };

    const server = await Helper.createServer(swaggerOptions, routes);
    const response = await server.inject({ method: 'GET', url: '/swagger.json' });
    expect(response.statusCode).to.equal(200);
    expect(response.result.paths['/store/'].post.parameters.length).to.equal(1);
    expect(response.result.paths['/store/'].post.parameters[0].name).to.equal('body');
  });

  lab.test('payloadType = json global', async () => {
    const swaggerOptions = {
      payloadType: 'form'
    };

    const server = await Helper.createServer(swaggerOptions, routes);
    const response = await server.inject({ method: 'GET', url: '/swagger.json' });
    expect(response.statusCode).to.equal(200);
    expect(response.result.paths['/store/'].post.parameters.length).to.equal(4);
    expect(response.result.paths['/store/'].post.parameters[0].name).to.equal('a');
  });

  lab.test('pathPrefixSize global', async () => {
    const swaggerOptions = {
      pathPrefixSize: 2
    };

    const prefixRoutes = [
      {
        method: 'GET',
        path: '/foo/bar/extra',
        options: {
          handler: Helper.defaultHandler,
          tags: ['api']
        }
      }
    ];

    const server = await Helper.createServer(swaggerOptions, prefixRoutes);
    const response = await server.inject({ method: 'GET', url: '/swagger.json' });
    expect(response.statusCode).to.equal(200);
    expect(response.result.paths['/foo/bar/extra'].get.tags[0]).to.equal('foo/bar');
  });

  lab.test('expanded none', async () => {
    // TODO find a way to test impact of property change
    const server = await Helper.createServer({ expanded: 'none' });
    const response = await server.inject({ method: 'GET', url: '/swagger.json' });
    expect(response.statusCode).to.equal(200);
  });

  lab.test('expanded list', async () => {
    const server = await Helper.createServer({ expanded: 'list' });
    const response = await server.inject({ method: 'GET', url: '/swagger.json' });
    expect(response.statusCode).to.equal(200);
  });

  lab.test('expanded full', async () => {
    const server = await Helper.createServer({ expanded: 'full' }, routes);
    const response = await server.inject({ method: 'GET', url: '/swagger.json' });
    expect(response.statusCode).to.equal(200);
  });

  lab.test('pass through of tags querystring', async () => {
    const server = await Helper.createServer({}, routes);
    const response = await server.inject({ method: 'GET', url: '/documentation?tags=reduced' });
    expect(response.statusCode).to.equal(200);
    expect(response.result.indexOf('swagger.json?tags=reduced') > -1).to.equal(true);
  });

  lab.test('tryItOutEnabled true', async () => {
    const server = await Helper.createServer({ tryItOutEnabled: true });
    const response = await server.inject({ method: 'GET', url: '/swagger.json' });
    expect(response.statusCode).to.equal(200);
  });

  lab.test('tryItOutEnabled false', async () => {
    const server = await Helper.createServer({ tryItOutEnabled: false });
    const response = await server.inject({ method: 'GET', url: '/swagger.json' });
    expect(response.statusCode).to.equal(200);
  });

  lab.test('test route x-meta appears in swagger', async () => {
    const testRoutes = [
      {
        method: 'POST',
        path: '/test/',
        options: {
          handler: Helper.defaultHandler,
          tags: ['api'],
          plugins: {
            'hapi-swagger': {
              'x-meta': {
                test1: true,
                test2: 'test',
                test3: {
                  test: true
                }
              }
            }
          }
        }
      }
    ];
    const server = await Helper.createServer({}, testRoutes);
    const response = await server.inject({ method: 'GET', url: '/swagger.json' });
    expect(response.result.paths['/test/'].post['x-meta']).to.equal({
      test1: true,
      test2: 'test',
      test3: {
        test: true
      }
    });
  });

  lab.test('test arbitrary vendor extensions (x-*) appears in swagger', async () => {
    const testRoutes = [
      {
        method: 'POST',
        path: '/test/',
        options: {
          handler: Helper.defaultHandler,
          tags: ['api'],
          plugins: {
            'hapi-swagger': {
              'x-code-samples': {
                lang: 'JavaScript',
                source: 'console.log("Hello World");'
              },
              'x-custom-string': 'some string'
            }
          }
        }
      }
    ];
    const server = await Helper.createServer({}, testRoutes);
    const response = await server.inject({ method: 'GET', url: '/swagger.json' });
    expect(response.result.paths['/test/'].post['x-code-samples']).to.equal({
      lang: 'JavaScript',
      source: 'console.log("Hello World");'
    });
    expect(response.result.paths['/test/'].post['x-custom-string']).to.equal('some string');
  });

  lab.test('test {disableDropdown: true} in swagger', async () => {
    const testRoutes = [
      {
        method: 'POST',
        path: '/test/',
        options: {
          handler: Helper.defaultHandler,
          tags: ['api'],
          validate: {
            payload: Joi.object({
              a: Joi.number()
                .integer()
                .allow(0)
                .meta({ disableDropdown: true })
            })
          }
        }
      }
    ];
    const server = await Helper.createServer({}, testRoutes);
    const response = await server.inject({ method: 'GET', url: '/swagger.json' });

    expect(response.result.definitions).to.equal({
      Model1: {
        type: 'object',
        properties: {
          a: {
            type: 'integer',
            'x-meta': {
              disableDropdown: true
            }
          }
        }
      }
    });
  });
});

lab.experiment('multiple plugins', () => {
  const routes = [
    {
      method: 'POST',
      path: '/store/',
      options: {
        handler: Helper.defaultHandler,
        tags: ['store-api'],
        validate: {
          payload: Joi.object({
            a: Joi.number(),
            b: Joi.number(),
            operator: Joi.string(),
            equals: Joi.number()
          })
        }
      }
    },
    {
      method: 'POST',
      path: '/shop/',
      options: {
        handler: Helper.defaultHandler,
        tags: ['shop-api'],
        validate: {
          payload: Joi.object({
            c: Joi.number(),
            d: Joi.number(),
            operator: Joi.string(),
            equals: Joi.number()
          })
        }
      }
    }
  ];

  lab.test('multiple plugins can co-exist', async () => {
    const swaggerOptions1 = {
      routeTag: 'store-api',
      info: {
        description: 'This is the store API docs'
      }
    };
    const swaggerOptions2 = {
      routeTag: 'shop-api',
      info: {
        description: 'This is the shop API docs'
      }
    };
    const server = await Helper.createServerMultiple(swaggerOptions1, swaggerOptions2, routes);

    const response1 = await server.inject({ method: 'GET', url: '/store-api/swagger.json' });
    expect(response1.statusCode).to.equal(200);
    const isValid1 = await Validate.test(response1.result);
    expect(isValid1).to.be.true();
    expect(response1.result.info.description).to.equal('This is the store API docs');
    expect(response1.result.paths['/store/'].post.operationId).to.equal('postStore');

    const response2 = await server.inject({ method: 'GET', url: '/shop-api/swagger.json' });
    expect(response2.statusCode).to.equal(200);
    const isValid2 = await Validate.test(response2.result);
    expect(isValid2).to.be.true();
    expect(response2.result.info.description).to.equal('This is the shop API docs');
    expect(response2.result.paths['/shop/'].post.operationId).to.equal('postShop');

    const document1 = await server.inject({ method: 'GET', url: '/store-api/documentation' });
    expect(document1.statusCode).to.equal(200);
    expect(document1.result).to.include('/store-api/');
    expect(document1.result).not.to.include('/shop-api/');

    const document2 = await server.inject({ method: 'GET', url: '/shop-api/documentation' });
    expect(document2.statusCode).to.equal(200);
    expect(document2.result).to.include('/shop-api/');
    expect(document2.result).not.to.include('/store-api/');
  });
});


text:
angular.module('mobilehope', ['ionic', 'mobilehope.controllers'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);

    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
  });
})

.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider

    .state('app', {
    url: '/app',
    abstract: true,
    templateUrl: 'templates/menu.html',
    controller: 'AppCtrl'
  })

  .state('app.search', {
    url: '/search',
    views: {
      'menuContent': {
        templateUrl: 'templates/search.html'
      }
    }
  })

  .state('app.browse', {
      url: '/browse',
      views: {
        'menuContent': {
          templateUrl: 'templates/browse.html'
        }
      }
    })
    .state('app.inventory', {
      url: '/inventory',
      views: {
        'menuContent': {
          templateUrl: 'templates/inventory.html',
          controller: 'InventoryCtrl'
        }
      }
    })

  .state('app.single', {
    url: '/category/:categoryId',
    views: {
      'menuContent': {
        templateUrl: 'templates/category.html',
        controller: 'CategoryCtrl'
      }
    }
  });
  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/app/inventory');
});


text:
package com.mindcognition.mindraider.application.model.tag;

/**
 * Descriptor of the resource being tagged.
 */
public class TaggedResourceEntry {

    public String conceptUri;
    public String conceptLabel;
    public long conceptTimestamp;

    public String notebookUri;
    public String notebookLabel;
    public String conceptPath;

    /**
     * Constructor.
     *
     * @param conceptUri
     * @param conceptLabel
     * @param conceptTimestamp
     */
    public TaggedResourceEntry(
            String notebookUri, String notebookLabel,
            String conceptUri, String conceptLabel, long conceptTimestamp, String conceptPath) {
        this.notebookUri=notebookUri;
        this.notebookLabel=notebookLabel;
        this.conceptUri=conceptUri;
        this.conceptLabel=conceptLabel;
        this.conceptTimestamp=conceptTimestamp;
        this.conceptPath=conceptPath;
    }

    /*
     * (non-Javadoc)
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        final TaggedResourceEntry other = (TaggedResourceEntry) obj;
        if (conceptUri == null) {
            if (other.conceptUri != null)
                return false;
        } else if (!conceptUri.equals(other.conceptUri))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return conceptUri;
    }

}


text:
layout: piece
title: Three Poems
author: Sarah Francoise
date: 2016-06-22 16:00:00
category: june2016
---
**Untitled**

I was a fountain choreographer

in purple sheets, given to glass worship.

I was statues, too, broken down to chips,

when the rumor died down at the altar.

Elle ordered me (again) to Love My Hair,

when France and Russia fought over warships,

when we were two people meant to Ketchup;

but wasn't that your job? (I mean, the hair).

Back when I spent my money on Moleskines -

they still write, to ask me if I want more.

I don't know how to answer such questions,

so instead I tell them I want more skin,

because we stretched the rumor till it tore,

and then left it to yellow in the sun.

**Marbles**

The morning after the cow lost her calf,

the symptoms set in.

The planarian split into two,

3.4 miles from shore.

The slanted city/a spineless island,

sent the marbles on a downward roll.

Then with the drill (it's a hands-on city):

don't fix the shelves, please, just fill in the hole.

When I fell, I felled the topography.

You misunderstood me a hundred times,

yet here I am again, infralapsing.

So: there was your way and there was mine,

respecting our original parting.

Buried under a tree came back bolder:

that bell I found. Remember? I told you.

**Windows**

They are all talking about

the storm windows

but none of them saw

the note on the sink,

the one that kept it to storms,

on how to condition the storms

for storms.

And while they sign off in the copse,

through their talk of squalls

comes our daughter's voice,

supplicating the raspberries,

those that dilly-dallied into September,

so old they taste like jam.

The woman who lived here

made her nest in a town

kept honest by wood.

Now an auctioneer codes

a shovel full of buttons

rested on a child's sled

and a julep Rabbit,

68,000 miles tired.

It reminds me of a cabinet

where birds were laid to rest

in cotton balls.

No one is really from this town

and the only wood to ever come from here

was splintered, dipped in sulphur,

and inflamed against diminutive

adirondack chairs.

Our daughter pockets an acorn,

convincing us both she has taken

something valuable.


text:
namespace MassTransit.Tests
{
    using System;
    using System.Threading.Tasks;
    using MassTransit.Testing;
    using Microsoft.Extensions.DependencyInjection;
    using NUnit.Framework;
    using TestFramework;
    using TestFramework.Messages;

    [TestFixture]
    public class Using_a_request_filter_with_request_client
    {
        [Test]
        public async Task Should_fault_instead_of_timeout()
        {
            await using var provider = new ServiceCollection()
                .AddMassTransitTestHarness(x =>
                {
                    x.AddConsumer<PingConsumer>();

                    x.UsingInMemory((context, cfg) =>
                    {
                        cfg.UseConsumeFilter(typeof(RequestValidationScopedFilter<>), context);

                        cfg.ConfigureEndpoints(context);
                    });
                })
                .BuildServiceProvider(true);

            var harness = provider.GetTestHarness();

            await harness.Start();

            IRequestClient<PingMessage> client = harness.GetRequestClient<PingMessage>();

            Assert.That(async () =>
                await client.GetResponse<PongMessage>(new
                {
                    CorrelationId = InVar.Id,
                }), Throws.TypeOf<RequestFaultException>());
        }

        public class PingConsumer :
            IConsumer<PingMessage>
        {
            public Task Consume(ConsumeContext<PingMessage> context)
            {
                return context.RespondAsync(new PongMessage(context.Message.CorrelationId));
            }
        }

        public class RequestValidationScopedFilter<T> :
            IFilter<ConsumeContext<T>>
            where T : class
        {
            public void Probe(ProbeContext context)
            {
                context.CreateFilterScope("RequestValidationScopedFilter<TMessage> scope");
            }

            public async Task Send(ConsumeContext<T> context, IPipe<ConsumeContext<T>> next)
            {
                try
                {
                    throw new IntentionalTestException("Failed to validate request");
                }
                catch (Exception exception)
                {
                    await context.NotifyFaulted(context.ReceiveContext.ElapsedTime, TypeCache<RequestValidationScopedFilter<T>>.ShortName, exception)
                        .ConfigureAwait(false);

                    throw;
                }
            }
        }
    }
}


text:
namespace _01.MobilePhoneDeviceClasses
{
    using System;
    using System.Collections.Generic;

    public class GSM
    {
        private const string DefaultModel = "Nokia 1100";
        private const string DefaultManufacturer = "Nokia";
        private static GSM iPhone4S = new GSM("IPhone4S", "Apple", 1999, "Me", new Battery(), new Display());
        private string model;
        private string manufacturer;
        private int price;
        private string owner;
        private Battery battery;
        private Display display;
        private IList<Call> callHistory;

        public GSM(string model, string manufacturer)
        {
            this.Model = model;
            this.Manufacturer = manufacturer;
            this.CallHistory = new List<Call>();
        }

        public GSM(string model, string manufacturer, int price, string owner, Battery battery, Display display)
            : this(model, manufacturer)
        {
            this.Price = price;
            this.Owner = owner;
            this.BatteryInfo = battery;
            this.DisplayInfo = display;
            this.CallHistory = new List<Call>();
        }

        public GSM()
            : this(DefaultModel, DefaultManufacturer, 0, null, null, null)
        {
            this.CallHistory = new List<Call>();
        }

        public static GSM IPhone4S
        {
            get
            {
                return iPhone4S;
            }

            set
            {
                iPhone4S = value;
            }
        }

        public string Model
        {
            get
            {
                return this.model;
            }

            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    throw new ArgumentOutOfRangeException(string.Empty);
                }

                if (value.Length < 2)
                {
                    throw new ArgumentException("Model too short! It should be at least 2 letters");
                }

                if (value.Length >= 50)
                {
                    throw new ArgumentException("Model too long! It should be less than 50 letters");
                }

                this.model = value;
            }
        }

        public string Manufacturer
        {
            get
            {
                return this.manufacturer;
            }

            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    throw new ArgumentException("Model cannot be empty!");
                }

                if (value.Length < 2)
                {
                    throw new ArgumentException("Model too short! It should be at least 2 letters");
                }

                if (value.Length >= 50)
                {
                    throw new ArgumentException("Model too long! It should be less than 50 letters");
                }

                foreach (char ch in value)
                {
                    if (!this.IsLetterAllowedInNames(ch))
                    {
                        throw new ArgumentException("Invalid name! Use only letters, space and hyphen");
                    }
                }

                this.manufacturer = value;
            }
        }

        public int Price
        {
            get
            {
                return this.price;
            }

            set
            {
                if (value < 0)
                {
                    throw new ArgumentException("The value must be greater than 0");
                }

                this.price = value;
            }
        }

        public string Owner
        {
            get
            {
                return this.owner;
            }

            set
            {
                if (value == string.Empty)
                {
                    throw new ArgumentException("Owner cannot be empty!");
                }

                if (value.Length < 2)
                {
                    throw new ArgumentException("Owner too short! It should be at least 2 letters");
                }

                if (value.Length >= 50)
                {
                    throw new ArgumentException("Owner too long! It should be less than 50 letters");
                }

                foreach (char ch in value)
                {
                    if (!this.IsLetterAllowedInNames(ch))
                    {
                        throw new ArgumentException("Invalid name! Use only letters, space and hyphen");
                    }
                }

                this.owner = value;
            }
        }

        public Battery BatteryInfo
        {
            get
            {
                return this.battery;
            }

            set
            {
                if (value == null)
                {
                    throw new ArgumentNullException("Baterry is null.");
                }

                this.battery = value;
            }
        }

        public Display DisplayInfo
        {
            get
            {
                return this.display;
            }

            set
            {
                if (value == null)
                {
                    throw new ArgumentNullException("Display is null.");
                }

                this.display = value;
            }
        }

        public IList<Call> CallHistory
        {
            get
            {
                return this.callHistory;
            }

            set
            {
                this.callHistory = value;
            }
        }

        public override string ToString()
        {
            return string.Format("===GSM===\nModel: {0}\nManufacturer: {1}\nOwner: {2}\nPrice: {3}\n{4}\n{5}", this.Model, this.Manufacturer, this.Owner, this.Price, this.BatteryInfo.ToString(), this.DisplayInfo.ToString());
        }

        public void AddCall(Call call)
        {
            this.CallHistory.Add(call);
        }

        public bool RemoveCall(Call call)
        {
            return this.CallHistory.Remove(call);
        }

        public void ClearCallHistory()
        {
            this.CallHistory.Clear();
        }

        public double CalculateCallsPrice(double priceOfOneMinuteCall)
        {
            double price = 0;

            foreach (var call in this.callHistory)
            {
                price += priceOfOneMinuteCall * call.Duration / 60;
            }

            return price;
        }

        private bool IsLetterAllowedInNames(char ch)
        {
            bool isAllowed =
                char.IsLetter(ch) || ch == '-' || ch == ' ';
            return isAllowed;
        }
    }
}


text:
if [ -z $1 ]
then
 # no input
 echo "(1) No folder choosed"
 echo "Example: /var/www/project.com/"
 exit
fi

cd "$1"
find -type f -name "*.jpg" -exec jpegoptim --strip-all {} \;
find -type f -name "*.png" -exec optipng {} \;


text:
//---------------------------------------------------------------------
// <copyright file="StreamReferenceValueReaderAtomTests.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.Test.Taupo.OData.Reader.Tests.Atom
{
    #region Namespaces
    using System.Collections.Generic;
    using System.Linq;
    using Microsoft.OData.Core;
    using Microsoft.Test.Taupo.Astoria.Contracts.OData;
    using Microsoft.Test.Taupo.Common;
    using Microsoft.Test.Taupo.Execution;
    using Microsoft.Test.Taupo.OData.Common;
    using Microsoft.Test.Taupo.OData.Contracts;
    using Microsoft.Test.Taupo.OData.Reader.Tests;
    using Microsoft.Test.Taupo.OData.Reader.Tests.Common;
    using Microsoft.Test.Taupo.OData.Reader.Tests.Reader;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    #endregion Namespaces

    /// <summary>
    /// Test reading of named streams in ATOM.
    /// </summary>
    [TestClass, TestCase]
    public class StreamReferenceValueReaderAtomTests : ODataReaderTestCase
    {
        [InjectDependency]
        public IPayloadGenerator PayloadGenerator { get; set; }

        [InjectDependency]
        public PayloadReaderTestDescriptor.Settings Settings { get; set; }

        [TestMethod, TestCategory("Reader.Atom"), Variation(Description = "Verifies correct reading of stream properties without metadata.")]
        public void StreamPropertyNoMetadataAtomTest()
        {
            IEnumerable<PayloadReaderTestDescriptor> testDescriptors = new PayloadReaderTestDescriptor[]
            {
                #region only href
                // read link with only href.
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", "http://odata.org/readlink", null, null, null),
                },

                // edit-link with only href.
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", null, "http://odata.org/editlink", null, null),
                },

                // read link with only href. - two links - case sensitive difference.
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity()
                        .StreamProperty("StreamProperty", "http://odata.org/readlink", null, null, null)
                        .StreamProperty("StreampRoperty", "http://odata.org/readlink2", null, null, null),
                },
                // edit-link with only href. - two links - case sensitive difference.
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity()
                        .StreamProperty("StreamProperty", null, "http://odata.org/editlink", null, null)
                        .StreamProperty("sTreamProperty", null, "http://odata.org/editlink2", null, null),
                },
                #endregion

                #region missing content type
                // read link with missing content type.
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", "http://odata.org/readlink", null, null, null),
                },

                // edit-link with missing content type.
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", null, "http://odata.org/editlink", null, null),
                },

                // edit-link with content type in different namespace.
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", null, "http://odata.org/editlink", null, null)
                        .XmlRepresentation(@"<entry xmlns:foo='http://www.w3.org/SomeNamespace'>
                                              <link rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty'
                                                href='http://odata.org/editlink' foo:type='application/atom+xml' />
                                             </entry>"),
                },
                #endregion

                #region content type on both
                // both read and edit link with the same content type, read link first
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", "http://odata.org/readlink", "http://odata.org/editlink", "mime/type")
                        .XmlRepresentation(@"<entry>
                                              <link rel='http://docs.oasis-open.org/odata/ns/mediaresource/StreamProperty' href='http://odata.org/readlink' type='mime/type'/>
                                              <link rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty' href='http://odata.org/editlink' type='mime/type'/>
                                             </entry>"),
                },
                // both read and edit link with the same content type, edit link first
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", "http://odata.org/readlink", "http://odata.org/editlink", "mime/type")
                        .XmlRepresentation(@"<entry>
                                              <link rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty' href='http://odata.org/editlink' type='mime/type'/>
                                              <link rel='http://docs.oasis-open.org/odata/ns/mediaresource/StreamProperty' href='http://odata.org/readlink' type='mime/type'/>
                                             </entry>"),
                },
                #endregion

                #region etag
                // verify that read link discards etag.
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", "http://odata.org/readlink", null, null, null)
                        .XmlRepresentation(@"<entry>
                                              <link rel='http://docs.oasis-open.org/odata/ns/mediaresource/StreamProperty'
                                                  href='http://odata.org/readlink' m:etag='someetag'/>
                                             </entry>"),
                },
                #endregion etag

                #region all possible valid attributes
                // edit-link with href, content type and etag.
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", null, "http://odata.org/editlink", "application/atom+xml", "some_etag"),
                },
                // read link with href and content type.
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", "http://odata.org/readlink", null, "application/atom+xml", null),
                },
                #endregion

                #region extra attributes
                // extra attributes in the read link.
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", "http://odata.org/readlink")
                        .XmlRepresentation(@"<entry>
                                                <link rel='http://docs.oasis-open.org/odata/ns/mediaresource/StreamProperty'  foo1='bar1' href='http://odata.org/readlink' foo='bar'/>
                                             </entry>"),
                },
                // extra attributes in the edit-link.
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty",null, "http://odata.org/editlink")
                        .XmlRepresentation(@"<entry>
                                                <link rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty' foo1='bar1' href='http://odata.org/editlink' foo='bar'/>
                                             </entry>"),
                },
                #endregion

                #region missing rel
                // missing rel
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity()
                        .XmlRepresentation(@"<entry>
                                                <link href='http://odata.org/editlink' type='application/atom+xml'/>
                                            </entry>"),
                },
                // rel attribute in different namespace
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity()
                        .XmlRepresentation(@"<entry xmlns:foo='http://www.w3.org/SomeNamespace'>
                                                <link href='http://odata.org/editlink' type='application/atom+xml' foo:rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty'/>
                                            </entry>"),
                },
                #endregion missing rel

                #region name prefix
                // verify that invalid stream name prefix is discarded.
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity()
                        .XmlRepresentation(@"<entry>
                                                <link rel='http://docs.oasis-open.org/odata/ns/data/somename/StreamProperty' href='http://odata.org/readlink' />
                                             </entry>"),
                },
                // verify that stream name prefix is case-sensitive.
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity()
                        .XmlRepresentation(@"<entry>
                                                <link rel='http://docs.oasis-open.org/odata/ns/Mediaresource/StreamProperty' href='http://odata.org/readlink' type='application/atom+xml'/>
                                             </entry>"),
                },
                // verify that incomplete rel is not recognized as stream property (missing the last slash in read link)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity()
                        .XmlRepresentation(@"<entry>
                                                <link rel='http://docs.oasis-open.org/odata/ns/mediaresource' href='http://odata.org/readlink' />
                                             </entry>"),
                },
                // verify that incomplete rel is not recognized as stream property (missing the last slash in edit link)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity()
                        .XmlRepresentation(@"<entry>
                                                <link rel='http://docs.oasis-open.org/odata/ns/edit-media' href='http://odata.org/editlink' />
                                             </entry>"),
                },
                #endregion

                #region order of the attributes and link
                // edit link first.
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity()
                        .StreamProperty("StreamProperty1", null, "http://odata.org/editlink", null, null)
                        .StreamProperty("StreamProperty2", "http://odata.org/readlink", null, null, null),
                },
                // read link first.
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity()
                        .StreamProperty("StreamProperty1", "http://odata.org/readlink", null, null, null)
                        .StreamProperty("StreamProperty2", null, "http://odata.org/editlink", null, null),
                },
                // rel after etag, href and type.
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", null, "http://odata.org/editlink", "application/atom+xml", "some_etag")
                        .XmlRepresentation(@"<entry>
                                                <link m:etag='some_etag' href='http://odata.org/editlink' type='application/atom+xml' rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty'/>
                                            </entry>"),
                },
                #endregion order of the attributes and link

                #region content inside link element
                // verify that all contents inside link element are skipped.
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity()
                        .StreamProperty("StreamProperty", null, "http://odata.org/editlink", "application/atom+xml", null)
                        .XmlRepresentation(@"<entry>
                                                <link href='http://odata.org/editlink' type='application/atom+xml' rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty'>
                                                <m:unknown>some text</m:unknown>
                                                <!-- Some comments -->
                                                <d:unknown/>
                                                <ns:someelement xmlns:ns='somenamespace'/>
                                                <![CDATA[cdata]]>
                                                </link>
                                            </entry>"),
                },
                #endregion content inside link element
            };

            #region empty or missing etag
            KeyValuePair<string, string>[] etags = new KeyValuePair<string, string>[]
            {
                new KeyValuePair<string, string>(string.Empty, "m:etag=''"),  // empty etag
                new KeyValuePair<string, string>("some_etag", "m:etag='some_etag'"), // valid etag
                new KeyValuePair<string, string>(null, "foo:etag='some_etag'"), // etag in a different namespace
            };

            testDescriptors = testDescriptors.Concat(etags.Select(etag =>

                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty", null, "http://odata.org/editlink", null, etag.Key)
                        .XmlRepresentation(string.Format(@"<entry xmlns:foo='http://www.w3.org/SomeNamespace'>
                                                             <link rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty'
                                                                href='http://odata.org/editlink' {0} />
                                                           </entry>", etag.Value)),
                }));
            #endregion empty or missing etag

            // WCF DS client, server and default ODataLib show the same behavior for stream properties.
            this.CombinatorialEngineProvider.RunCombinations(
               TestReaderUtils.ODataBehaviorKinds,
               testDescriptors,
               this.ReaderTestConfigurationProvider.AtomFormatConfigurations,
               (behaviorKind, testDescriptor, testConfiguration) =>
               {
                   if (testConfiguration.IsRequest)
                   {
                       testDescriptor = new PayloadReaderTestDescriptor(testDescriptor)
                       {
                           ExpectedException = null,
                           ExpectedResultPayloadElement = tc => RemoveStreamPropertyPayloadElementNormalizer.Normalize(testDescriptor.PayloadElement.DeepCopy())
                       };
                   }

                   testDescriptor.RunTest(testConfiguration.CloneAndApplyBehavior(behaviorKind));
               });
        }

        [TestMethod, TestCategory("Reader.Atom"), Variation(Description = "Verifies error cases for stream properties.")]
        public void StreamPropertyErrorAtomTest()
        {
            IEnumerable<PayloadReaderTestDescriptor> testDescriptors = new PayloadReaderTestDescriptor[]
            {
                #region multiple attributes
                // same stream property, multiple edit-links
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity()
                        .XmlRepresentation(@"<entry>
                                                <link rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty' href='http://odata.org/editlink'/>
                                                <link rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty' href='http://odata.org/editlink'/>
                                                </entry>"),
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomEntryAndFeedDeserializer_StreamPropertyWithMultipleEditLinks", "StreamProperty"),
                },
                // same stream property, multiple read links
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity()
                        .XmlRepresentation(@"<entry>
                                                <link rel='http://docs.oasis-open.org/odata/ns/mediaresource/StreamProperty' href='http://odata.org/readlink'/>
                                                <link rel='http://docs.oasis-open.org/odata/ns/mediaresource/StreamProperty' href='http://odata.org/readlink'/>
                                                </entry>"),
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomEntryAndFeedDeserializer_StreamPropertyWithMultipleReadLinks", "StreamProperty"),
                },
                // same stream property, multiple and different content types
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity()
                        .XmlRepresentation(@"<entry>
                                                <link rel='http://docs.oasis-open.org/odata/ns/mediaresource/StreamProperty' href='http://odata.org/readlink' type='application/atom+xml'/>
                                                <link rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty' href='http://odata.org/readlink' type='application/atom+xml+foo'/>
                                                </entry>"),
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomEntryAndFeedDeserializer_StreamPropertyWithMultipleContentTypes", "StreamProperty"),
                },
                #endregion

                #region property name collision
                // multiple properties with the same name.
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity().NavigationProperty("StreamProperty", "http://odata.org/link")
                        .XmlRepresentation(@"<entry>
                                                <link rel='http://docs.oasis-open.org/odata/ns/related/StreamProperty' href='http://odata.org/link' type='application/atom+xml'/>
                                                <link href='http://odata.org/editlink' type='application/atom+xml' rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty'/>
                                            </entry>"),
                    ExpectedException = ODataExpectedExceptions.ODataException("DuplicatePropertyNamesChecker_DuplicatePropertyNamesNotAllowed", "StreamProperty")
                },
                // multiple properties with the same name. read link. (stream property first)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity().PrimitiveProperty("StreamProperty", "foo")
                        .XmlRepresentation(@"<entry>
                                                <link rel='http://docs.oasis-open.org/odata/ns/mediaresource/StreamProperty' href='http://odata.org/link'/>
                                                <content type='application/xml'><m:properties><d:StreamProperty>foo</d:StreamProperty></m:properties></content>
                                            </entry>"),
                    ExpectedException = ODataExpectedExceptions.ODataException("DuplicatePropertyNamesChecker_DuplicatePropertyNamesNotAllowed", "StreamProperty")
                },
                // multiple properties with the same name. read link. (normal property first)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity().PrimitiveProperty("StreamProperty", "foo")
                        .XmlRepresentation(@"<entry>
                                                <content type='application/xml'><m:properties><d:StreamProperty>foo</d:StreamProperty></m:properties></content>
                                                <link rel='http://docs.oasis-open.org/odata/ns/mediaresource/StreamProperty' href='http://odata.org/link'/>
                                            </entry>"),
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomEntryAndFeedDeserializer_StreamPropertyDuplicatePropertyName", "StreamProperty")
                },
                // multiple properties with the same name. edit link. (stream property first)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity().PrimitiveProperty("StreamProperty", "foo")
                        .XmlRepresentation(@"<entry>
                                                <link rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty' href='http://odata.org/link'/>
                                                <content type='application/xml'><m:properties><d:StreamProperty>foo</d:StreamProperty></m:properties></content>
                                            </entry>"),
                    ExpectedException = ODataExpectedExceptions.ODataException("DuplicatePropertyNamesChecker_DuplicatePropertyNamesNotAllowed", "StreamProperty")
                },
                // multiple properties with the same name. edit link. (normal property first)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity().PrimitiveProperty("StreamProperty", "foo")
                        .XmlRepresentation(@"<entry>
                                                <content type='application/xml'><m:properties><d:StreamProperty>foo</d:StreamProperty></m:properties></content>
                                                <link rel='http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty' href='http://odata.org/link'/>
                                            </entry>"),
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomEntryAndFeedDeserializer_StreamPropertyDuplicatePropertyName", "StreamProperty")
                },
                #endregion property name collision

                #region empty name
                // empty name on the read link of a stream property
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity()
                        .XmlRepresentation(@"<entry>
                                                <link rel='http://docs.oasis-open.org/odata/ns/mediaresource/' href='http://odata.org/link' type='application/atom+xml'/>
                                            </entry>"),
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomEntryAndFeedDeserializer_StreamPropertyWithEmptyName")
                },
                // empty name on the edit link of a stream property
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity()
                        .XmlRepresentation(@"<entry>
                                                <link rel='http://docs.oasis-open.org/odata/ns/edit-media/' href='http://odata.org/link' type='application/atom+xml'/>
                                            </entry>"),
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomEntryAndFeedDeserializer_StreamPropertyWithEmptyName")
                },
                #endregion
            };

            #region missing href
            string[] hrefs = new string[]
            {
                string.Empty, // missing href
                "foo:href='http://odata.org/differentNamespace'", // href in different namespace
            };

            string[] links = new string[]
            {
                "http://docs.oasis-open.org/odata/ns/mediaresource/StreamProperty",
                "http://docs.oasis-open.org/odata/ns/edit-media/StreamProperty"
            };

            testDescriptors = testDescriptors.Concat(hrefs.SelectMany(href => links.Select(link =>
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity().StreamProperty("StreamProperty")
                        .XmlRepresentation(string.Format(
                                                @"<entry xmlns:foo='http://www.w3.org/SomeNamespace'>
                                                        <link rel='{0}' {1}/>
                                                    </entry>", link, href)),
                })));
            #endregion missing href

            // WCF DS client, server and default ODataLib show the same behavior for stream properties.
            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                TestReaderUtils.ODataBehaviorKinds,
                this.ReaderTestConfigurationProvider.AtomFormatConfigurations,
                (testDescriptor, behaviorKind, testConfiguration) =>
                {
                    if (testConfiguration.IsRequest)
                    {
                        testDescriptor = new PayloadReaderTestDescriptor(testDescriptor)
                        {
                            ExpectedException = null,
                            ExpectedResultPayloadElement = tc => RemoveStreamPropertyPayloadElementNormalizer.Normalize(testDescriptor.PayloadElement.DeepCopy())
                        };
                    }

                    testDescriptor.RunTest(testConfiguration.CloneAndApplyBehavior(behaviorKind));
                });
        }

        [TestMethod, TestCategory("Reader.Atom"), Variation(Description = "Verifies correct reading of stream properties with metadata.")]
        public void StreamPropertyWithMetadataTests()
        {
            IEnumerable<PayloadReaderTestDescriptor> testDescriptors =
                StreamReferenceValueReaderTests.CreateStreamPropertyMetadataTestDescriptors(this.Settings).SelectMany(td => this.PayloadGenerator.GenerateReaderPayloads(td));

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.AtomFormatConfigurations,
                (testDescriptor, testConfiguration) =>
                {
                    if (testConfiguration.IsRequest)
                    {
                        testDescriptor = new PayloadReaderTestDescriptor(testDescriptor)
                        {
                            ExpectedException = null,
                            ExpectedResultPayloadElement = tc => RemoveStreamPropertyPayloadElementNormalizer.Normalize(testDescriptor.PayloadElement.DeepCopy())
                        };
                    }

                    testDescriptor.RunTest(testConfiguration);
                });
        }
    }
}


text:
package org.olat.search.service.indexer.repository;

import java.io.IOException;
import java.util.List;

import org.olat.core.gui.components.tree.TreeNode;
import org.olat.core.id.Identity;
import org.olat.core.id.IdentityEnvironment;
import org.olat.core.id.Roles;
import org.olat.core.id.context.BusinessControl;
import org.olat.core.id.context.ContextEntry;
import org.olat.core.logging.AssertException;
import org.olat.core.logging.OLog;
import org.olat.core.logging.StartupException;
import org.olat.core.logging.Tracing;
import org.olat.core.util.nodes.INode;
import org.olat.course.CourseFactory;
import org.olat.course.CourseModule;
import org.olat.course.ICourse;
import org.olat.course.nodes.CourseNode;
import org.olat.course.run.navigation.NavigationHandler;
import org.olat.course.run.userview.NodeEvaluation;
import org.olat.course.run.userview.TreeEvaluation;
import org.olat.course.run.userview.UserCourseEnvironment;
import org.olat.course.run.userview.UserCourseEnvironmentImpl;
import org.olat.repository.RepositoryEntry;
import org.olat.repository.RepositoryEntryStatus;
import org.olat.repository.RepositoryManager;
import org.olat.search.service.SearchResourceContext;
import org.olat.search.service.indexer.Indexer;
import org.olat.search.service.indexer.OlatFullIndexer;
import org.olat.search.service.indexer.repository.course.CourseNodeIndexer;
import org.olat.search.service.indexer.repository.course.CourseNodeIndexerFactory;

/**
 * Index a hole course.
 *
 * @author Christian Guretzki
 */
public class CourseIndexer implements Indexer {
	private static final OLog log = Tracing.createLoggerFor(CourseIndexer.class);

	public final static String TYPE = "type.repository.entry.CourseModule";

	private final RepositoryManager repositoryManager;

	public CourseIndexer() {
		repositoryManager = RepositoryManager.getInstance();
	}

	/**
	 *
	 */
	@Override
	public String getSupportedTypeName() {
		return CourseModule.getCourseTypeName();
	}

	/**
	 * @see org.olat.repository.handlers.RepositoryHandler#supportsDownload()
	 */

	@Override
	public void doIndex(final SearchResourceContext parentResourceContext, final Object parentObject, final OlatFullIndexer indexWriter) {
		final RepositoryEntry repositoryEntry = (RepositoryEntry) parentObject;
		if (log.isDebug()) {
			log.debug("Analyse Course... repositoryEntry=" + repositoryEntry);
		}
		try {
			final RepositoryEntryStatus status = RepositoryManager.getInstance().createRepositoryEntryStatus(repositoryEntry.getStatusCode());
			if (status.isClosed()) {
				if (log.isDebug()) {
					log.debug("Course not indexed because it's closed: repositoryEntry=" + repositoryEntry);
				}
				return;
			}

			final ICourse course = CourseFactory.loadCourse(repositoryEntry.getOlatResource());
			// course.getCourseTitle(); // do not index title => index root-node
			parentResourceContext.setParentContextType(TYPE);
			parentResourceContext.setParentContextName(course.getCourseTitle());
			doIndexCourse(parentResourceContext, course, course.getRunStructure().getRootNode(), indexWriter);
		} catch (final Exception ex) {
			log.warn("Can not index repositoryEntry=" + repositoryEntry, ex);
		}
	}

	public void doIndexCourse(final SearchResourceContext repositoryResourceContext, final ICourse course, final CourseNode courseNode, final OlatFullIndexer indexWriter)
			throws IOException, InterruptedException {
		// loop over all child nodes
		final int childCount = courseNode.getChildCount();
		for (int i = 0; i < childCount; i++) {
			final INode childCourseNode = courseNode.getChildAt(i);
			if (childCourseNode instanceof CourseNode) {
				if (log.isDebug()) {
					log.debug("Analyse CourseNode child ... childCourseNode=" + childCourseNode);
				}
				// go further with resource
				final CourseNodeIndexer courseNodeIndexer = CourseNodeIndexerFactory.getInstance().getCourseNodeIndexer((CourseNode) childCourseNode);
				if (courseNodeIndexer != null) {
					if (log.isDebug()) {
						log.debug("courseNodeIndexer=" + courseNodeIndexer);
					}
					try {
						courseNodeIndexer.doIndex(repositoryResourceContext, course, (CourseNode) childCourseNode, indexWriter);
					} catch (final Exception e) {
						log.warn("Can not index course node=" + childCourseNode.getIdent(), e);
					}
				} else {
					if (log.isDebug()) {
						log.debug("No CourseNodeIndexer for " + childCourseNode);
					}
					// go further, index my child nodes
					doIndexCourse(repositoryResourceContext, course, (CourseNode) childCourseNode, indexWriter);
				}
			} else {
				if (log.isDebug()) {
					log.debug("ChildNode is no CourseNode, " + childCourseNode);
				}
			}
		}
	}

	/**
	 * Bean setter method used by spring.
	 *
	 * @param indexerList
	 */
	public void setIndexerList(final List<CourseNodeIndexer> indexerList) {
		if (indexerList == null) { throw new AssertException("null value for indexerList not allowed."); }

		try {
			for (final CourseNodeIndexer courseNodeIndexer : indexerList) {
				CourseNodeIndexerFactory.getInstance().registerIndexer(courseNodeIndexer);
				if (log.isDebug()) {
					log.debug("Adding indexer from configuraton: ");
				}
			}
		} catch (final ClassCastException cce) {
			throw new StartupException("Configured indexer is not of type RepositoryEntryIndexer", cce);
		}
	}

	@Override
	public boolean checkAccess(final ContextEntry contextEntry, final BusinessControl businessControl, final Identity identity, final Roles roles) {
		final ContextEntry bcContextEntry = businessControl.popLauncherContextEntry();
		if (bcContextEntry == null) {
			// no context-entry anymore, the repository entry itself is the context entry,
			// not a course node of course we have access to the course metadata
			return true;
		}
		if (log.isDebug()) {
			log.debug("Start identity=" + identity + "  roles=" + roles);
		}
		final Long repositoryKey = contextEntry.getOLATResourceable().getResourceableId();
		final RepositoryEntry repositoryEntry = repositoryManager.lookupRepositoryEntry(repositoryKey);
		if (log.isDebug()) {
			log.debug("repositoryEntry=" + repositoryEntry);
		}

		final Long nodeId = bcContextEntry.getOLATResourceable().getResourceableId();
		if (log.isDebug()) {
			log.debug("nodeId=" + nodeId);
		}

		final ICourse course = CourseFactory.loadCourse(repositoryEntry.getOlatResource());
		final IdentityEnvironment ienv = new IdentityEnvironment();
		ienv.setIdentity(identity);
		ienv.setRoles(roles);
		final UserCourseEnvironment userCourseEnv = new UserCourseEnvironmentImpl(ienv, course.getCourseEnvironment());
		if (log.isDebug()) {
			log.debug("userCourseEnv=" + userCourseEnv + "ienv=" + ienv);
		}

		final CourseNode rootCn = userCourseEnv.getCourseEnvironment().getRunStructure().getRootNode();

		final String nodeIdS = nodeId.toString();
		final CourseNode courseNode = course.getRunStructure().getNode(nodeIdS);
		if (log.isDebug()) {
			log.debug("courseNode=" + courseNode);
		}

		final TreeEvaluation treeEval = new TreeEvaluation();
		final NodeEvaluation rootNodeEval = rootCn.eval(userCourseEnv.getConditionInterpreter(), treeEval);
		if (log.isDebug()) {
			log.debug("rootNodeEval=" + rootNodeEval);
		}

		final TreeNode newCalledTreeNode = treeEval.getCorrespondingTreeNode(courseNode);
		if (newCalledTreeNode == null) {
			// TreeNode no longer visible
			return false;
		}
		// go further
		final NodeEvaluation nodeEval = (NodeEvaluation) newCalledTreeNode.getUserObject();
		if (log.isDebug()) {
			log.debug("nodeEval=" + nodeEval);
		}
		if (nodeEval.getCourseNode() != courseNode) { throw new AssertException("error in structure"); }
		if (!nodeEval.isVisible()) { throw new AssertException("node eval not visible!!"); }
		if (log.isDebug()) {
			log.debug("call mayAccessWholeTreeUp...");
		}
		final boolean mayAccessWholeTreeUp = NavigationHandler.mayAccessWholeTreeUp(nodeEval);
		if (log.isDebug()) {
			log.debug("call mayAccessWholeTreeUp=" + mayAccessWholeTreeUp);
		}

		if (mayAccessWholeTreeUp) {
			final CourseNodeIndexer courseNodeIndexer = CourseNodeIndexerFactory.getInstance().getCourseNodeIndexer(courseNode);
			return courseNodeIndexer.checkAccess(bcContextEntry, businessControl, identity, roles);
		} else {
			return false;
		}
	}

}