                   GNU LESSER GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

  This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.

  0. Additional Definitions.

  As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.

  "The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.

  An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.

  A "Combined Work" is a work produced by combining or linking an
Application with the Library.  The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".

  The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.

  The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.

  1. Exception to Section 3 of the GNU GPL.

  You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.

  2. Conveying Modified Versions.

  If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:

   a) under this License, provided that you make a good faith effort to
   ensure that, in the event an Application does not supply the
   function or data, the facility still operates, and performs
   whatever part of its purpose remains meaningful, or

   b) under the GNU GPL, with none of the additional permissions of
   this License applicable to that copy.

  3. Object Code Incorporating Material from Library Header Files.

  The object code form of an Application may incorporate material from
a header file that is part of the Library.  You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:

   a) Give prominent notice with each copy of the object code that the
   Library is used in it and that the Library and its use are
   covered by this License.

   b) Accompany the object code with a copy of the GNU GPL and this license
   document.

  4. Combined Works.

  You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:

   a) Give prominent notice with each copy of the Combined Work that
   the Library is used in it and that the Library and its use are
   covered by this License.

   b) Accompany the Combined Work with a copy of the GNU GPL and this license
   document.

   c) For a Combined Work that displays copyright notices during
   execution, include the copyright notice for the Library among
   these notices, as well as a reference directing the user to the
   copies of the GNU GPL and this license document.

   d) Do one of the following:

       0) Convey the Minimal Corresponding Source under the terms of this
       License, and the Corresponding Application Code in a form
       suitable for, and under terms that permit, the user to
       recombine or relink the Application with a modified version of
       the Linked Version to produce a modified Combined Work, in the
       manner specified by section 6 of the GNU GPL for conveying
       Corresponding Source.

       1) Use a suitable shared library mechanism for linking with the
       Library.  A suitable mechanism is one that (a) uses at run time
       a copy of the Library already present on the user's computer
       system, and (b) will operate properly with a modified version
       of the Library that is interface-compatible with the Linked
       Version.

   e) Provide Installation Information, but only if you would otherwise
   be required to provide such information under section 6 of the
   GNU GPL, and only to the extent that such information is
   necessary to install and execute a modified version of the
   Combined Work produced by recombining or relinking the
   Application with a modified version of the Linked Version. (If
   you use option 4d0, the Installation Information must accompany
   the Minimal Corresponding Source and Corresponding Application
   Code. If you use option 4d1, you must provide the Installation
   Information in the manner specified by section 6 of the GNU GPL
   for conveying Corresponding Source.)

  5. Combined Libraries.

  You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:

   a) Accompany the combined library with a copy of the same work based
   on the Library, uncombined with any other library facilities,
   conveyed under the terms of this License.

   b) Give prominent notice with the combined library that part of it
   is a work based on the Library, and explaining where to find the
   accompanying uncombined form of the same work.

  6. Revised Versions of the GNU Lesser General Public License.

  The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.

  Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.

  If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.


// RUN: %clang_cc1 -ffreestanding  -triple=x86_64-apple-darwin -target-cpu skx %s -emit-llvm -o - | FileCheck %s
#include <xmmintrin.h>
// This test is complimented by the .ll test under llvm/test/MC/X86/.
// At this level we can only check if the constarints are passed correctly
// from inline asm to llvm IR.

// CHECK-LABEL: @f_Ym
void f_Ym(__m64 m)
  {
  // CHECK: movq  $0, %mm1
  // CHECK-SAME: "=^Ym,~{dirflag},~{fpsr},~{flags}"
  __asm__ volatile ("movq %0, %%mm1\n\t"
          :"=Ym" (m));
}

// CHECK-LABEL: f_Yi
void f_Yi(__m128 x, __m128 y, __m128 z)
  {
  // CHECK: vpaddq
  // CHECK-SAME: "=^Yi,^Yi,^Yi,~{dirflag},~{fpsr},~{flags}"
  __asm__ volatile ("vpaddq %0, %1, %2\n\t"
          :"=Yi" (x)
          :"Yi" (y),"Yi"(z));
}

// CHECK-LABEL: f_Yt
void f_Yt(__m128 x, __m128 y, __m128 z)
  {
  // CHECK: vpaddq
  // CHECK-SAME: "=^Yt,^Yt,^Yt,~{dirflag},~{fpsr},~{flags}"
  __asm__ volatile ("vpaddq %0, %1, %2\n\t"
          :"=Yt" (x)
          :"Yt" (y),"Yt"(z));
}

// CHECK-LABEL: f_Y2
void f_Y2(__m128 x, __m128 y, __m128 z)
    {
  // CHECK: vpaddq
  // CHECK-SAME: "=^Y2,^Y2,^Y2,~{dirflag},~{fpsr},~{flags}"
  __asm__ volatile ("vpaddq %0, %1, %2\n\t"
            :"=Y2" (x)
            :"Y2" (y),"Y2"(z));
}

// CHECK-LABEL: f_Yz
void f_Yz(__m128 x, __m128 y, __m128 z)
  {
  // CHECK: vpaddq
  // CHECK-SAME: vpaddq
  // CHECK-SAME: "=^Yi,=^Yz,^Yi,0,~{dirflag},~{fpsr},~{flags}"
  __asm__ volatile ("vpaddq %0,%2,%1\n\t"
       "vpaddq %1,%0,%2\n\t"
          :"+Yi"(z),"=Yz" (x)
          :"Yi" (y) );
}

// CHECK-LABEL: f_Y0
void f_Y0(__m128 x, __m128 y, __m128 z)
  {
  // CHECK: vpaddq
  // CHECK-SAME: "=^Yi,=^Y0,^Yi,0,~{dirflag},~{fpsr},~{flags}"
  __asm__ volatile ("vpaddq %0,%2,%1\n\t"
          "vpaddq %1,%0,%2\n\t"
          :"+Yi"(z),"=Y0" (x)
          :"Yi" (y) );
}


/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is JavaScript Engine testing utilities.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communication Corporation.
 * Portions created by the Initial Developer are Copyright (C) 1998
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

/**
   File Name:          lexical-022
   Corresponds To      7.4.3-15-n.js
   ECMA Section:       7.4.3

   Description:
   The following words are used as keywords in proposed extensions and are
   therefore reserved to allow for the possibility of future adoption of
   those extensions.

   FutureReservedWord :: one of
   case    debugger    export      super
   catch   default     extends     switch
   class   do          finally     throw
   const   enum        import      try

   Author:             christine@netscape.com
   Date:               12 november 1997
*/
var SECTION = "lexical-022.js";
var VERSION = "ECMA_1";
var TITLE   = "Future Reserved Words";

startTest();
writeHeaderToLog( SECTION + " "+ TITLE);

var result = "Failed";
var exception = "No exception thrown";
var expect = "Passed";

try {
  eval("import = true;");
} catch ( e ) {
  result = expect;
  exception = e.toString();
}

new TestCase(
  SECTION,
  "import = true" +
  " (threw " + exception +")",
  expect,
  result );

test();


multipipe

pipe streams with centralized error handling


--TEST--
Strings, basic
--INPUT--
SELECT "'FOO'";
--EXPECTED--
E SELECT
s "'FOO'"
; ;


title: Řetězcové funkce a metody
style: md
attribution:
- Pro PyLadies Brno napsal Petr Viktorin, 2014-2019.
license: cc-by-sa-40


import smart_imports

smart_imports.all()

class NewsAdmin(django_admin.ModelAdmin):
    list_display = ('id', 'caption', 'emailed', 'created_at')

    readonly_fields = ('forum_thread',)

django_admin.site.register(models.News, NewsAdmin)


using System;
using System.Reflection;

public static class Program {
    public static void Main (string[] args) {
        Console.WriteLine("No public modifier");
        Common.Util.ListMethods(
            typeof(T),
            BindingFlags.Instance | BindingFlags.DeclaredOnly
        );

        Console.WriteLine("NonPublic");
        Common.Util.ListMethods(
            typeof(T),
            BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.NonPublic
        );

        Console.WriteLine("Public");
        Common.Util.ListMethods(
            typeof(T),
            BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public
        );

        Console.WriteLine("NonPublic | Public");
        Common.Util.ListMethods(
            typeof(T),
            BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public
        );
    }
}

public class T {
    private void A () {
        Console.WriteLine("A()");
    }

    protected void A (object o) {
        Console.WriteLine("A(object)");
    }

    public void A (int i) {
        Console.WriteLine("A(int)");
    }

    public void B (string s) {
        Console.WriteLine("B(string)");
    }
}


'use strict';

module.exports.definition = {
    set: function (v) {
        this._setProperty('-webkit-region-break-inside', v);
    },
    get: function () {
        return this.getPropertyValue('-webkit-region-break-inside');
    },
    enumerable: true,
    configurable: true
};


HTTP | id.orig_p:49204 status_code:200 method:POST request_body_len:110 id.resp_p:80 orig_mime_types:["text\/plain"] uri:/wp-content/themes/grizzly/img5.php?u=ka6nnuvccqlw9 tags:[] uid:C6NKjA4tt5Xc1a6uzd resp_mime_types:["text\/plain"] trans_depth:1 orig_fuids:["Fr5Cg02TcSAxFeYoBh"] host:comarksecurity.com status_msg:OK id.orig_h:192.168.138.158 response_body_len:14 user_agent:Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0) ts:1537304979.801853 id.resp_h:72.34.49.86 resp_fuids:["FQcLCtotjacEmeBEf"]


//
// posix/basic_stream_descriptor.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2016 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef BOOST_ASIO_POSIX_BASIC_STREAM_DESCRIPTOR_HPP
#define BOOST_ASIO_POSIX_BASIC_STREAM_DESCRIPTOR_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include <boost/asio/detail/config.hpp>

#if defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) \
  || defined(GENERATING_DOCUMENTATION)

#include <cstddef>
#include <boost/asio/detail/handler_type_requirements.hpp>
#include <boost/asio/detail/throw_error.hpp>
#include <boost/asio/error.hpp>
#include <boost/asio/posix/basic_descriptor.hpp>
#include <boost/asio/posix/stream_descriptor_service.hpp>

#include <boost/asio/detail/push_options.hpp>

namespace boost {
namespace asio {
namespace posix {

/// Provides stream-oriented descriptor functionality.
/**
 * The posix::basic_stream_descriptor class template provides asynchronous and
 * blocking stream-oriented descriptor functionality.
 *
 * @par Thread Safety
 * @e Distinct @e objects: Safe.@n
 * @e Shared @e objects: Unsafe.
 *
 * @par Concepts:
 * AsyncReadStream, AsyncWriteStream, Stream, SyncReadStream, SyncWriteStream.
 */
template <typename StreamDescriptorService = stream_descriptor_service>
class basic_stream_descriptor
  : public basic_descriptor<StreamDescriptorService>
{
public:
  /// (Deprecated: Use native_handle_type.) The native representation of a
  /// descriptor.
  typedef typename StreamDescriptorService::native_handle_type native_type;

  /// The native representation of a descriptor.
  typedef typename StreamDescriptorService::native_handle_type
    native_handle_type;

  /// Construct a basic_stream_descriptor without opening it.
  /**
   * This constructor creates a stream descriptor without opening it. The
   * descriptor needs to be opened and then connected or accepted before data
   * can be sent or received on it.
   *
   * @param io_service The io_service object that the stream descriptor will
   * use to dispatch handlers for any asynchronous operations performed on the
   * descriptor.
   */
  explicit basic_stream_descriptor(boost::asio::io_service& io_service)
    : basic_descriptor<StreamDescriptorService>(io_service)
  {
  }

  /// Construct a basic_stream_descriptor on an existing native descriptor.
  /**
   * This constructor creates a stream descriptor object to hold an existing
   * native descriptor.
   *
   * @param io_service The io_service object that the stream descriptor will
   * use to dispatch handlers for any asynchronous operations performed on the
   * descriptor.
   *
   * @param native_descriptor The new underlying descriptor implementation.
   *
   * @throws boost::system::system_error Thrown on failure.
   */
  basic_stream_descriptor(boost::asio::io_service& io_service,
      const native_handle_type& native_descriptor)
    : basic_descriptor<StreamDescriptorService>(io_service, native_descriptor)
  {
  }

#if defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
  /// Move-construct a basic_stream_descriptor from another.
  /**
   * This constructor moves a stream descriptor from one object to another.
   *
   * @param other The other basic_stream_descriptor object from which the move
   * will occur.
   *
   * @note Following the move, the moved-from object is in the same state as if
   * constructed using the @c basic_stream_descriptor(io_service&) constructor.
   */
  basic_stream_descriptor(basic_stream_descriptor&& other)
    : basic_descriptor<StreamDescriptorService>(
        BOOST_ASIO_MOVE_CAST(basic_stream_descriptor)(other))
  {
  }

  /// Move-assign a basic_stream_descriptor from another.
  /**
   * This assignment operator moves a stream descriptor from one object to
   * another.
   *
   * @param other The other basic_stream_descriptor object from which the move
   * will occur.
   *
   * @note Following the move, the moved-from object is in the same state as if
   * constructed using the @c basic_stream_descriptor(io_service&) constructor.
   */
  basic_stream_descriptor& operator=(basic_stream_descriptor&& other)
  {
    basic_descriptor<StreamDescriptorService>::operator=(
        BOOST_ASIO_MOVE_CAST(basic_stream_descriptor)(other));
    return *this;
  }
#endif // defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)

  /// Write some data to the descriptor.
  /**
   * This function is used to write data to the stream descriptor. The function
   * call will block until one or more bytes of the data has been written
   * successfully, or until an error occurs.
   *
   * @param buffers One or more data buffers to be written to the descriptor.
   *
   * @returns The number of bytes written.
   *
   * @throws boost::system::system_error Thrown on failure. An error code of
   * boost::asio::error::eof indicates that the connection was closed by the
   * peer.
   *
   * @note The write_some operation may not transmit all of the data to the
   * peer. Consider using the @ref write function if you need to ensure that
   * all data is written before the blocking operation completes.
   *
   * @par Example
   * To write a single data buffer use the @ref buffer function as follows:
   * @code
   * descriptor.write_some(boost::asio::buffer(data, size));
   * @endcode
   * See the @ref buffer documentation for information on writing multiple
   * buffers in one go, and how to use it with arrays, boost::array or
   * std::vector.
   */
  template <typename ConstBufferSequence>
  std::size_t write_some(const ConstBufferSequence& buffers)
  {
    boost::system::error_code ec;
    std::size_t s = this->get_service().write_some(
        this->get_implementation(), buffers, ec);
    boost::asio::detail::throw_error(ec, "write_some");
    return s;
  }

  /// Write some data to the descriptor.
  /**
   * This function is used to write data to the stream descriptor. The function
   * call will block until one or more bytes of the data has been written
   * successfully, or until an error occurs.
   *
   * @param buffers One or more data buffers to be written to the descriptor.
   *
   * @param ec Set to indicate what error occurred, if any.
   *
   * @returns The number of bytes written. Returns 0 if an error occurred.
   *
   * @note The write_some operation may not transmit all of the data to the
   * peer. Consider using the @ref write function if you need to ensure that
   * all data is written before the blocking operation completes.
   */
  template <typename ConstBufferSequence>
  std::size_t write_some(const ConstBufferSequence& buffers,
      boost::system::error_code& ec)
  {
    return this->get_service().write_some(
        this->get_implementation(), buffers, ec);
  }

  /// Start an asynchronous write.
  /**
   * This function is used to asynchronously write data to the stream
   * descriptor. The function call always returns immediately.
   *
   * @param buffers One or more data buffers to be written to the descriptor.
   * Although the buffers object may be copied as necessary, ownership of the
   * underlying memory blocks is retained by the caller, which must guarantee
   * that they remain valid until the handler is called.
   *
   * @param handler The handler to be called when the write operation completes.
   * Copies will be made of the handler as required. The function signature of
   * the handler must be:
   * @code void handler(
   *   const boost::system::error_code& error, // Result of operation.
   *   std::size_t bytes_transferred           // Number of bytes written.
   * ); @endcode
   * Regardless of whether the asynchronous operation completes immediately or
   * not, the handler will not be invoked from within this function. Invocation
   * of the handler will be performed in a manner equivalent to using
   * boost::asio::io_service::post().
   *
   * @note The write operation may not transmit all of the data to the peer.
   * Consider using the @ref async_write function if you need to ensure that all
   * data is written before the asynchronous operation completes.
   *
   * @par Example
   * To write a single data buffer use the @ref buffer function as follows:
   * @code
   * descriptor.async_write_some(boost::asio::buffer(data, size), handler);
   * @endcode
   * See the @ref buffer documentation for information on writing multiple
   * buffers in one go, and how to use it with arrays, boost::array or
   * std::vector.
   */
  template <typename ConstBufferSequence, typename WriteHandler>
  BOOST_ASIO_INITFN_RESULT_TYPE(WriteHandler,
      void (boost::system::error_code, std::size_t))
  async_write_some(const ConstBufferSequence& buffers,
      BOOST_ASIO_MOVE_ARG(WriteHandler) handler)
  {
    // If you get an error on the following line it means that your handler does
    // not meet the documented type requirements for a WriteHandler.
    BOOST_ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check;

    return this->get_service().async_write_some(this->get_implementation(),
        buffers, BOOST_ASIO_MOVE_CAST(WriteHandler)(handler));
  }

  /// Read some data from the descriptor.
  /**
   * This function is used to read data from the stream descriptor. The function
   * call will block until one or more bytes of data has been read successfully,
   * or until an error occurs.
   *
   * @param buffers One or more buffers into which the data will be read.
   *
   * @returns The number of bytes read.
   *
   * @throws boost::system::system_error Thrown on failure. An error code of
   * boost::asio::error::eof indicates that the connection was closed by the
   * peer.
   *
   * @note The read_some operation may not read all of the requested number of
   * bytes. Consider using the @ref read function if you need to ensure that
   * the requested amount of data is read before the blocking operation
   * completes.
   *
   * @par Example
   * To read into a single data buffer use the @ref buffer function as follows:
   * @code
   * descriptor.read_some(boost::asio::buffer(data, size));
   * @endcode
   * See the @ref buffer documentation for information on reading into multiple
   * buffers in one go, and how to use it with arrays, boost::array or
   * std::vector.
   */
  template <typename MutableBufferSequence>
  std::size_t read_some(const MutableBufferSequence& buffers)
  {
    boost::system::error_code ec;
    std::size_t s = this->get_service().read_some(
        this->get_implementation(), buffers, ec);
    boost::asio::detail::throw_error(ec, "read_some");
    return s;
  }

  /// Read some data from the descriptor.
  /**
   * This function is used to read data from the stream descriptor. The function
   * call will block until one or more bytes of data has been read successfully,
   * or until an error occurs.
   *
   * @param buffers One or more buffers into which the data will be read.
   *
   * @param ec Set to indicate what error occurred, if any.
   *
   * @returns The number of bytes read. Returns 0 if an error occurred.
   *
   * @note The read_some operation may not read all of the requested number of
   * bytes. Consider using the @ref read function if you need to ensure that
   * the requested amount of data is read before the blocking operation
   * completes.
   */
  template <typename MutableBufferSequence>
  std::size_t read_some(const MutableBufferSequence& buffers,
      boost::system::error_code& ec)
  {
    return this->get_service().read_some(
        this->get_implementation(), buffers, ec);
  }

  /// Start an asynchronous read.
  /**
   * This function is used to asynchronously read data from the stream
   * descriptor. The function call always returns immediately.
   *
   * @param buffers One or more buffers into which the data will be read.
   * Although the buffers object may be copied as necessary, ownership of the
   * underlying memory blocks is retained by the caller, which must guarantee
   * that they remain valid until the handler is called.
   *
   * @param handler The handler to be called when the read operation completes.
   * Copies will be made of the handler as required. The function signature of
   * the handler must be:
   * @code void handler(
   *   const boost::system::error_code& error, // Result of operation.
   *   std::size_t bytes_transferred           // Number of bytes read.
   * ); @endcode
   * Regardless of whether the asynchronous operation completes immediately or
   * not, the handler will not be invoked from within this function. Invocation
   * of the handler will be performed in a manner equivalent to using
   * boost::asio::io_service::post().
   *
   * @note The read operation may not read all of the requested number of bytes.
   * Consider using the @ref async_read function if you need to ensure that the
   * requested amount of data is read before the asynchronous operation
   * completes.
   *
   * @par Example
   * To read into a single data buffer use the @ref buffer function as follows:
   * @code
   * descriptor.async_read_some(boost::asio::buffer(data, size), handler);
   * @endcode
   * See the @ref buffer documentation for information on reading into multiple
   * buffers in one go, and how to use it with arrays, boost::array or
   * std::vector.
   */
  template <typename MutableBufferSequence, typename ReadHandler>
  BOOST_ASIO_INITFN_RESULT_TYPE(ReadHandler,
      void (boost::system::error_code, std::size_t))
  async_read_some(const MutableBufferSequence& buffers,
      BOOST_ASIO_MOVE_ARG(ReadHandler) handler)
  {
    // If you get an error on the following line it means that your handler does
    // not meet the documented type requirements for a ReadHandler.
    BOOST_ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check;

    return this->get_service().async_read_some(this->get_implementation(),
        buffers, BOOST_ASIO_MOVE_CAST(ReadHandler)(handler));
  }
};

} // namespace posix
} // namespace asio
} // namespace boost

#include <boost/asio/detail/pop_options.hpp>

#endif // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
       //   || defined(GENERATING_DOCUMENTATION)

#endif // BOOST_ASIO_POSIX_BASIC_STREAM_DESCRIPTOR_HPP


/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#ifndef VIDEO_VIDEO_RECEIVE_STREAM_H_
#define VIDEO_VIDEO_RECEIVE_STREAM_H_

#include <memory>
#include <vector>

#include "call/rtp_packet_sink_interface.h"
#include "call/syncable.h"
#include "call/video_receive_stream.h"
#include "common_video/libyuv/include/webrtc_libyuv.h"
#include "modules/rtp_rtcp/include/flexfec_receiver.h"
#include "modules/video_coding/frame_buffer2.h"
#include "modules/video_coding/video_coding_impl.h"
#include "rtc_base/sequenced_task_checker.h"
#include "system_wrappers/include/clock.h"
#include "video/receive_statistics_proxy.h"
#include "video/rtp_streams_synchronizer.h"
#include "video/rtp_video_stream_receiver.h"
#include "video/transport_adapter.h"
#include "video/video_stream_decoder.h"

namespace webrtc {

class CallStats;
class IvfFileWriter;
class ProcessThread;
class RTPFragmentationHeader;
class RtpStreamReceiverInterface;
class RtpStreamReceiverControllerInterface;
class RtxReceiveStream;
class VCMTiming;
class VCMJitterEstimator;

namespace internal {

class VideoReceiveStream : public webrtc::VideoReceiveStream,
                           public rtc::VideoSinkInterface<VideoFrame>,
                           public EncodedImageCallback,
                           public NackSender,
                           public KeyFrameRequestSender,
                           public video_coding::OnCompleteFrameCallback,
                           public Syncable,
                           public CallStatsObserver {
 public:
  VideoReceiveStream(RtpStreamReceiverControllerInterface* receiver_controller,
                     int num_cpu_cores,
                     PacketRouter* packet_router,
                     VideoReceiveStream::Config config,
                     ProcessThread* process_thread,
                     CallStats* call_stats);
  ~VideoReceiveStream() override;

  const Config& config() const { return config_; }

  void SignalNetworkState(NetworkState state);
  bool DeliverRtcp(const uint8_t* packet, size_t length);

  void SetSync(Syncable* audio_syncable);

  // Implements webrtc::VideoReceiveStream.
  void Start() override;
  void Stop() override;

  webrtc::VideoReceiveStream::Stats GetStats() const override;

  // Takes ownership of the file, is responsible for closing it later.
  // Calling this method will close and finalize any current log.
  // Giving rtc::kInvalidPlatformFileValue disables logging.
  // If a frame to be written would make the log too large the write fails and
  // the log is closed and finalized. A |byte_limit| of 0 means no limit.
  void EnableEncodedFrameRecording(rtc::PlatformFile file,
                                   size_t byte_limit) override;

  void AddSecondarySink(RtpPacketSinkInterface* sink) override;
  void RemoveSecondarySink(const RtpPacketSinkInterface* sink) override;

  // Implements rtc::VideoSinkInterface<VideoFrame>.
  void OnFrame(const VideoFrame& video_frame) override;

  // Implements EncodedImageCallback.
  EncodedImageCallback::Result OnEncodedImage(
      const EncodedImage& encoded_image,
      const CodecSpecificInfo* codec_specific_info,
      const RTPFragmentationHeader* fragmentation) override;

  // Implements NackSender.
  void SendNack(const std::vector<uint16_t>& sequence_numbers) override;

  // Implements KeyFrameRequestSender.
  void RequestKeyFrame() override;

  // Implements video_coding::OnCompleteFrameCallback.
  void OnCompleteFrame(
      std::unique_ptr<video_coding::EncodedFrame> frame) override;

  // Implements CallStatsObserver::OnRttUpdate
  void OnRttUpdate(int64_t avg_rtt_ms, int64_t max_rtt_ms) override;

  // Implements Syncable.
  int id() const override;
  absl::optional<Syncable::Info> GetInfo() const override;
  uint32_t GetPlayoutTimestamp() const override;
  void SetMinimumPlayoutDelay(int delay_ms) override;

 private:
  static void DecodeThreadFunction(void* ptr);
  bool Decode();

  rtc::SequencedTaskChecker worker_sequence_checker_;
  rtc::SequencedTaskChecker module_process_sequence_checker_;

  TransportAdapter transport_adapter_;
  const VideoReceiveStream::Config config_;
  const int num_cpu_cores_;
  ProcessThread* const process_thread_;
  Clock* const clock_;

  rtc::PlatformThread decode_thread_;

  CallStats* const call_stats_;

  // Shared by media and rtx stream receivers, since the latter has no RtpRtcp
  // module of its own.
  const std::unique_ptr<ReceiveStatistics> rtp_receive_statistics_;

  std::unique_ptr<VCMTiming> timing_;  // Jitter buffer experiment.
  vcm::VideoReceiver video_receiver_;
  std::unique_ptr<rtc::VideoSinkInterface<VideoFrame>> incoming_video_stream_;
  ReceiveStatisticsProxy stats_proxy_;
  RtpVideoStreamReceiver rtp_video_stream_receiver_;
  std::unique_ptr<VideoStreamDecoder> video_stream_decoder_;
  RtpStreamsSynchronizer rtp_stream_sync_;

  rtc::CriticalSection ivf_writer_lock_;
  std::unique_ptr<IvfFileWriter> ivf_writer_ RTC_GUARDED_BY(ivf_writer_lock_);

  // Members for the new jitter buffer experiment.
  std::unique_ptr<VCMJitterEstimator> jitter_estimator_;
  std::unique_ptr<video_coding::FrameBuffer> frame_buffer_;

  std::unique_ptr<RtpStreamReceiverInterface> media_receiver_;
  std::unique_ptr<RtxReceiveStream> rtx_receive_stream_;
  std::unique_ptr<RtpStreamReceiverInterface> rtx_receiver_;

  // Whenever we are in an undecodable state (stream has just started or due to
  // a decoding error) we require a keyframe to restart the stream.
  bool keyframe_required_ = true;

  // If we have successfully decoded any frame.
  bool frame_decoded_ = false;

  int64_t last_keyframe_request_ms_ = 0;
};
}  // namespace internal
}  // namespace webrtc

#endif  // VIDEO_VIDEO_RECEIVE_STREAM_H_


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Capture.Hook.DX11
{
    // Copyright (c) 2013 Justin Stenning
    // Adapted from original code by Alexandre Mutel
    //
    //----------------------------------------------------------------------------
    // Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
    //
    // Permission is hereby granted, free of charge, to any person obtaining a copy
    // of this software and associated documentation files (the "Software"), to deal
    // in the Software without restriction, including without limitation the rights
    // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    // copies of the Software, and to permit persons to whom the Software is
    // furnished to do so, subject to the following conditions:
    //
    // The above copyright notice and this permission notice shall be included in
    // all copies or substantial portions of the Software.
    //
    // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    // THE SOFTWARE.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    using SharpDX.Direct3D;
    using SharpDX.Direct3D11;

    public class DeviceManager : SharpDX.Component
    {
        // Direct3D Objects
        protected SharpDX.Direct3D11.Device d3dDevice;
        protected SharpDX.Direct3D11.DeviceContext d3dContext;

        /// <summary>
        /// Gets the Direct3D11 device.
        /// </summary>
        public SharpDX.Direct3D11.Device Direct3DDevice { get { return d3dDevice; } }

        /// <summary>
        /// Gets the Direct3D11 immediate context.
        /// </summary>
        public SharpDX.Direct3D11.DeviceContext Direct3DContext { get { return d3dContext; } }

        public DeviceManager(Device device)
        {
            d3dDevice = device;
            d3dContext = device.ImmediateContext;
        }
    }
}


\new ChoirStaff <<
  \new Staff \withLyrics <<
    \global \clef "treble" \includeNotes "vcanto"
  >> \includeLyrics "lyrics1"
  \new Staff \withLyrics <<
    \global \clef "treble" \includeNotes "valto"
  >> \includeLyrics "lyrics2"
  \new Staff \withLyrics <<
    \global \clef "G_8" \includeNotes "vtenore"
  >> \includeLyrics "lyrics3"
  \new Staff \withLyrics <<
    \global \clef "bass" \includeNotes "vbasso"
  >> \includeLyrics "lyrics4"
>>


# Basic Operators

This document explains some of the most common operators used in ReactiveCocoa,
and includes examples demonstrating their use.

Note that “operators”, in this context, refers to functions that transform
[signals][] and [signal producers][], _not_ custom Swift operators. In other
words, these are composable primitives provided by ReactiveCocoa for working
with event streams.

This document will use the term “event stream” when dealing with concepts that
apply to both `Signal` and `SignalProducer`. When the distinction matters, the
types will be referred to by name.

**[Performing side effects with event streams](#performing-side-effects-with-event-streams)**

  1. [Observation](#observation)
  1. [Injecting effects](#injecting-effects)

**[Operator composition](#operator-composition)**

  1. [Lifting](#lifting)

**[Transforming event streams](#transforming-event-streams)**

  1. [Mapping](#mapping)
  1. [Filtering](#filtering)
  1. [Aggregating](#aggregating)

**[Combining event streams](#combining-event-streams)**

  1. [Combining latest values](#combining-latest-values)
  1. [Zipping](#zipping)

**[Flattening producers](#flattening-producers)**

  1. [Merging](#merging)
  1. [Concatenating](#concatenating)
  1. [Switching to the latest](#switching-to-the-latest)

**[Handling failures](#handling-failures)**

  1. [Catching failures](#catching-failures)
  1. [Retrying](#retrying)
  1. [Mapping errors](#mapping-errors)
  1. [Promote](#promote)

## Performing side effects with event streams

### Observation

`Signal`s can be observed with the `observe` function. It takes an `Observer` as argument to which any future events are sent.

```Swift
signal.observe(Signal.Observer { event in
    switch event {
    case let .Next(next):
        print("Next: \(next)")
    case let .Failed(error):
        print("Failed: \(error)")
    case .Completed:
        print("Completed")
    case .Interrupted:
        print("Interrupted")
    }
})
```

Alternatively, callbacks for the `Next`, `Failed`, `Completed` and `Interrupted` events can be provided which will be called when a corresponding event occurs.

```Swift
signal.observeNext { next in
  print("Next: \(next)")
}
signal.observeFailed { error in
  print("Failed: \(error)")
}
signal.observeCompleted {
  print("Completed")
}
signal.observeInterrupted {
  print("Interrupted")
}
```

Note that it is not necessary to observe all four types of event - all of them are optional, you only need to provide callbacks for the events you care about.

### Injecting effects

Side effects can be injected on a `SignalProducer` with the `on` operator without actually subscribing to it.

```Swift
let producer = signalProducer
    .on(started: {
        print("Started")
    }, event: { event in
        print("Event: \(event)")
    }, failed: { error in
        print("Failed: \(error)")
    }, completed: {
        print("Completed")
    }, interrupted: {
        print("Interrupted")
    }, terminated: {
        print("Terminated")
    }, disposed: {
        print("Disposed")
    }, next: { value in
        print("Next: \(value)")
    })
```

Similar to `observe`, all the parameters are optional and you only need to provide callbacks for the events you care about.

Note that nothing will be printed until `producer` is started (possibly somewhere else).

## Operator composition

### Lifting

`Signal` operators can be _lifted_ to operate upon `SignalProducer`s using the
`lift` method.

This will create a new `SignalProducer` which will apply the given operator to
_every_ `Signal` created, just as if the operator had been applied to each
produced `Signal` individually.

## Transforming event streams

These operators transform an event stream into a new stream.

### Mapping

The `map` operator is used to transform the values in an event stream, creating
a new stream with the results.

```Swift
let (signal, observer) = Signal<String, NoError>.pipe()

signal
    .map { string in string.uppercaseString }
    .observeNext { next in print(next) }

observer.sendNext("a")     // Prints A
observer.sendNext("b")     // Prints B
observer.sendNext("c")     // Prints C
```

[Interactive visualisation of the `map` operator.](http://neilpa.me/rac-marbles/#map)

### Filtering

The `filter` operator is used to only include values in an event stream that
satisfy a predicate.

```Swift
let (signal, observer) = Signal<Int, NoError>.pipe()

signal
    .filter { number in number % 2 == 0 }
    .observeNext { next in print(next) }

observer.sendNext(1)     // Not printed
observer.sendNext(2)     // Prints 2
observer.sendNext(3)     // Not printed
observer.sendNext(4)     // prints 4
```

[Interactive visualisation of the `filter` operator.](http://neilpa.me/rac-marbles/#filter)

### Aggregating

The `reduce` operator is used to aggregate a event stream’s values into a single
combined value. Note that the final value is only sent after the input stream
completes.

```Swift
let (signal, observer) = Signal<Int, NoError>.pipe()

signal
    .reduce(1) { $0 * $1 }
    .observeNext { next in print(next) }

observer.sendNext(1)     // nothing printed
observer.sendNext(2)     // nothing printed
observer.sendNext(3)     // nothing printed
observer.sendCompleted()   // prints 6
```

The `collect` operator is used to aggregate a event stream’s values into
a single array value. Note that the final value is only sent after the input
stream completes.

```Swift
let (signal, observer) = Signal<Int, NoError>.pipe()

signal
    .collect()
    .observeNext { next in print(next) }

observer.sendNext(1)     // nothing printed
observer.sendNext(2)     // nothing printed
observer.sendNext(3)     // nothing printed
observer.sendCompleted()   // prints [1, 2, 3]
```

[Interactive visualisation of the `reduce` operator.](http://neilpa.me/rac-marbles/#reduce)

## Combining event streams

These operators combine values from multiple event streams into a new, unified
stream.

### Combining latest values

The `combineLatest` function combines the latest values of two (or more) event
streams.

The resulting stream will only send its first value after each input has sent at
least one value. After that, new values on any of the inputs will result in
a new value on the output.

```Swift
let (numbersSignal, numbersObserver) = Signal<Int, NoError>.pipe()
let (lettersSignal, lettersObserver) = Signal<String, NoError>.pipe()

let signal = combineLatest(numbersSignal, lettersSignal)
signal.observeNext { next in print("Next: \(next)") }
signal.observeCompleted { print("Completed") }

numbersObserver.sendNext(0)      // nothing printed
numbersObserver.sendNext(1)      // nothing printed
lettersObserver.sendNext("A")    // prints (1, A)
numbersObserver.sendNext(2)      // prints (2, A)
numbersObserver.sendCompleted()  // nothing printed
lettersObserver.sendNext("B")    // prints (2, B)
lettersObserver.sendNext("C")    // prints (2, C)
lettersObserver.sendCompleted()  // prints "Completed"
```

The `combineLatestWith` operator works in the same way, but as an operator.

[Interactive visualisation of the `combineLatest` operator.](http://neilpa.me/rac-marbles/#combineLatest)

### Zipping

The `zip` function joins values of two (or more) event streams pair-wise. The
elements of any Nth tuple correspond to the Nth elements of the input streams.

That means the Nth value of the output stream cannot be sent until each input
has sent at least N values.

```Swift
let (numbersSignal, numbersObserver) = Signal<Int, NoError>.pipe()
let (lettersSignal, lettersObserver) = Signal<String, NoError>.pipe()

let signal = zip(numbersSignal, lettersSignal)
signal.observeNext { next in print("Next: \(next)") }
signal.observeCompleted { print("Completed") }

numbersObserver.sendNext(0)      // nothing printed
numbersObserver.sendNext(1)      // nothing printed
lettersObserver.sendNext("A")    // prints (0, A)
numbersObserver.sendNext(2)      // nothing printed
numbersObserver.sendCompleted()  // nothing printed
lettersObserver.sendNext("B")    // prints (1, B)
lettersObserver.sendNext("C")    // prints (2, C) & "Completed"

```

The `zipWith` operator works in the same way, but as an operator.

[Interactive visualisation of the `zip` operator.](http://neilpa.me/rac-marbles/#zip)

## Flattening producers

The `flatten` operator transforms a stream-of-streams into a single stream - where values are forwarded from the inner stream in accordance with the provided `FlattenStrategy`. The flattened result becomes that of the outer stream type - i.e. a `SignalProducer`-of-`SignalProducer`s or `SignalProducer`-of-`Signal`s gets flattened to a `SignalProducer`, and likewise a `Signal`-of-`SignalProducer`s or `Signal`-of-`Signal`s gets flattened to a `Signal`.

To understand why there are different strategies and how they compare to each other, take a look at this example and imagine the column offsets as time:

```Swift
let values = [
// imagine column offset as time
[ 1,    2,      3 ],
   [ 4,      5,     6 ],
         [ 7,     8 ],
]

let merge =
[ 1, 4, 2, 7,5, 3,8,6 ]

let concat =
[ 1,    2,      3,4,      5,     6,7,     8]

let latest =
[ 1, 4,    7,     8 ]
```

Note, how the values interleave and which values are even included in the resulting array.

### Merging

The `.Merge` strategy immediately forwards every value of the inner `SignalProducer`s to the outer `SignalProducer`. Any failure sent on the outer producer or any inner producer is immediately sent on the flattened producer and terminates it.

```Swift
let (producerA, lettersObserver) = SignalProducer<String, NoError>.buffer(5)
let (producerB, numbersObserver) = SignalProducer<String, NoError>.buffer(5)
let (signal, observer) = SignalProducer<SignalProducer<String, NoError>, NoError>.buffer(5)

signal.flatten(.Merge).startWithNext { next in print(next) }

observer.sendNext(producerA)
observer.sendNext(producerB)
observer.sendCompleted()

lettersObserver.sendNext("a")    // prints "a"
numbersObserver.sendNext("1")    // prints "1"
lettersObserver.sendNext("b")    // prints "b"
numbersObserver.sendNext("2")    // prints "2"
lettersObserver.sendNext("c")    // prints "c"
numbersObserver.sendNext("3")    // prints "3"
```

[Interactive visualisation of the `flatten(.Merge)` operator.](http://neilpa.me/rac-marbles/#merge)

### Concatenating

The `.Concat` strategy is used to serialize work of the inner `SignalProducer`s. The outer producer is started immediately. Each subsequent producer is not started until the preceeding one has completed. Failures are immediately forwarded to the flattened producer.

```Swift
let (producerA, lettersObserver) = SignalProducer<String, NoError>.buffer(5)
let (producerB, numbersObserver) = SignalProducer<String, NoError>.buffer(5)
let (signal, observer) = SignalProducer<SignalProducer<String, NoError>, NoError>.buffer(5)

signal.flatten(.Concat).startWithNext { next in print(next) }

observer.sendNext(producerA)
observer.sendNext(producerB)
observer.sendCompleted()

numbersObserver.sendNext("1")    // nothing printed
lettersObserver.sendNext("a")    // prints "a"
lettersObserver.sendNext("b")    // prints "b"
numbersObserver.sendNext("2")    // nothing printed
lettersObserver.sendNext("c")    // prints "c"
lettersObserver.sendCompleted()    // prints "1", "2"
numbersObserver.sendNext("3")    // prints "3"
numbersObserver.sendCompleted()
```

[Interactive visualisation of the `flatten(.Concat)` operator.](http://neilpa.me/rac-marbles/#concat)

### Switching to the latest

The `.Latest` strategy forwards only values from the latest input `SignalProducer`.

```Swift
let (producerA, observerA) = SignalProducer<String, NoError>.buffer(5)
let (producerB, observerB) = SignalProducer<String, NoError>.buffer(5)
let (producerC, observerC) = SignalProducer<String, NoError>.buffer(5)
let (signal, observer) = SignalProducer<SignalProducer<String, NoError>, NoError>.buffer(5)

signal.flatten(.Latest).startWithNext { next in print(next) }

observer.sendNext(producerA)   // nothing printed
observerC.sendNext("X")        // nothing printed
observerA.sendNext("a")        // prints "a"
observerB.sendNext("1")        // nothing printed
observer.sendNext(producerB)   // prints "1"
observerA.sendNext("b")        // nothing printed
observerB.sendNext("2")        // prints "2"
observerC.sendNext("Y")        // nothing printed
observerA.sendNext("c")        // nothing printed
observer.sendNext(producerC)   // prints "X", "Y"
observerB.sendNext("3")        // nothing printed
observerC.sendNext("Z")        // prints "Z"
```

## Handling failures

These operators are used to handle failures that might occur on an event stream.

### Catching failures

The `flatMapError` operator catches any failure that may occur on the input `SignalProducer`, then starts a new `SignalProducer` in its place.

```Swift
let (producer, observer) = SignalProducer<String, NSError>.buffer(5)
let error = NSError(domain: "domain", code: 0, userInfo: nil)

producer
    .flatMapError { _ in SignalProducer<String, NoError>(value: "Default") }
    .startWithNext { next in print(next) }

observer.sendNext("First")     // prints "First"
observer.sendNext("Second")    // prints "Second"
observer.sendFailed(error)     // prints "Default"
```

### Retrying

The `retry` operator will restart the original `SignalProducer` on failure up to `count` times.

```Swift
var tries = 0
let limit = 2
let error = NSError(domain: "domain", code: 0, userInfo: nil)
let producer = SignalProducer<String, NSError> { (observer, _) in
    if tries++ < limit {
        observer.sendFailed(error)
    } else {
        observer.sendNext("Success")
        observer.sendCompleted()
    }
}

producer
    .on(failed: {e in print("Failure")})    // prints "Failure" twice
    .retry(2)
    .start { event in
        switch event {
        case let .Next(next):
            print(next)                     // prints "Success"
        case let .Failed(error):
            print("Failed: \(error)")
        case .Completed:
            print("Completed")
        case .Interrupted:
            print("Interrupted")
        }
    }
```

If the `SignalProducer` does not succeed after `count` tries, the resulting `SignalProducer` will fail. E.g., if  `retry(1)` is used in the example above instead of `retry(2)`, `"Signal Failure"` will be printed instead of `"Success"`.

### Mapping errors

The `mapError` operator transforms the error of any failure in an event stream into a new error.

```Swift
enum CustomError: String, ErrorType {
    case Foo = "Foo"
    case Bar = "Bar"
    case Other = "Other"

    var nsError: NSError {
        return NSError(domain: "CustomError.\(rawValue)", code: 0, userInfo: nil)
    }

    var description: String {
        return "\(rawValue) Error"
    }
}

let (signal, observer) = Signal<String, NSError>.pipe()

signal
    .mapError { (error: NSError) -> CustomError in
        switch error.domain {
        case "com.example.foo":
            return .Foo
        case "com.example.bar":
            return .Bar
        default:
            return .Other
        }
    }
    .observeFailed { error in
        print(error)
    }

observer.sendFailed(NSError(domain: "com.example.foo", code: 42, userInfo: nil))    // prints "Foo Error"
```

### Promote

The `promoteErrors` operator promotes an event stream that does not generate failures into one that can.

```Swift
let (numbersSignal, numbersObserver) = Signal<Int, NoError>.pipe()
let (lettersSignal, lettersObserver) = Signal<String, NSError>.pipe()

numbersSignal
    .promoteErrors(NSError)
    .combineLatestWith(lettersSignal)
```

The given stream will still not _actually_ generate failures, but this is useful
because some operators to [combine streams](#combining-event-streams) require
the inputs to have matching error types.

[Signals]: FrameworkOverview.md#signals
[Signal Producers]: FrameworkOverview.md#signal-producers
[Observation]: FrameworkOverview.md#observation


/*
 * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include "ScriptMgr.h"
#include "CharacterCache.h"
#include "Chat.h"
#include "DatabaseEnv.h"
#include "DB2Stores.h"
#include "GroupMgr.h"
#include "Language.h"
#include "LFG.h"
#include "Map.h"
#include "MotionMaster.h"
#include "ObjectAccessor.h"
#include "ObjectMgr.h"
#include "PhasingHandler.h"
#include "Player.h"
#include "RBAC.h"
#include "WorldSession.h"

class group_commandscript : public CommandScript
{
public:
    group_commandscript() : CommandScript("group_commandscript") { }

    std::vector<ChatCommand> GetCommands() const override
    {
        static std::vector<ChatCommand> groupSetCommandTable =
        {
            { "leader",     rbac::RBAC_PERM_COMMAND_GROUP_LEADER,     false, &HandleGroupLeaderCommand,     "" },
            { "assistant",  rbac::RBAC_PERM_COMMAND_GROUP_ASSISTANT,  false, &HandleGroupAssistantCommand,  "" },
            { "maintank",   rbac::RBAC_PERM_COMMAND_GROUP_MAINTANK,   false, &HandleGroupMainTankCommand,   "" },
            { "mainassist", rbac::RBAC_PERM_COMMAND_GROUP_MAINASSIST, false, &HandleGroupMainAssistCommand, "" },
        };

        static std::vector<ChatCommand> groupCommandTable =
        {
            { "set",     rbac::RBAC_PERM_COMMAND_GROUP_SET,     false, nullptr,                    "", groupSetCommandTable },
            { "leader",  rbac::RBAC_PERM_COMMAND_GROUP_LEADER,  false, &HandleGroupLeaderCommand,  "" },
            { "disband", rbac::RBAC_PERM_COMMAND_GROUP_DISBAND, false, &HandleGroupDisbandCommand, "" },
            { "remove",  rbac::RBAC_PERM_COMMAND_GROUP_REMOVE,  false, &HandleGroupRemoveCommand,  "" },
            { "join",    rbac::RBAC_PERM_COMMAND_GROUP_JOIN,    false, &HandleGroupJoinCommand,    "" },
            { "list",    rbac::RBAC_PERM_COMMAND_GROUP_LIST,    false, &HandleGroupListCommand,    "" },
            { "summon",  rbac::RBAC_PERM_COMMAND_GROUP_SUMMON,  false, &HandleGroupSummonCommand,  "" },
        };

        static std::vector<ChatCommand> commandTable =
        {
            { "group", rbac::RBAC_PERM_COMMAND_GROUP, false, nullptr, "", groupCommandTable },
        };
        return commandTable;
    }

    // Summon group of player
    static bool HandleGroupSummonCommand(ChatHandler* handler, char const* args)
    {
        Player* target;
        if (!handler->extractPlayerTarget((char*)args, &target))
            return false;

        // check online security
        if (handler->HasLowerSecurity(target, ObjectGuid::Empty))
            return false;

        Group* group = target->GetGroup();

        std::string nameLink = handler->GetNameLink(target);

        if (!group)
        {
            handler->PSendSysMessage(LANG_NOT_IN_GROUP, nameLink.c_str());
            return false;
        }

        Player* gmPlayer = handler->GetSession()->GetPlayer();
        Map* gmMap = gmPlayer->GetMap();
        bool toInstance = gmMap->Instanceable();
        bool onlyLocalSummon = false;

        // make sure people end up on our instance of the map, disallow far summon if intended destination is different from actual destination
        // note: we could probably relax this further by checking permanent saves and the like, but eh
        // :close enough:
        if (toInstance)
        {
            Player* groupLeader = ObjectAccessor::GetPlayer(gmMap, group->GetLeaderGUID());
            if (!groupLeader || (groupLeader->GetMapId() != gmMap->GetId()) || (groupLeader->GetInstanceId() != gmMap->GetInstanceId()))
            {
                handler->SendSysMessage(LANG_PARTIAL_GROUP_SUMMON);
                onlyLocalSummon = true;
            }
        }

        for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next())
        {
            Player* player = itr->GetSource();

            if (!player || player == gmPlayer || !player->GetSession())
                continue;

            // check online security
            if (handler->HasLowerSecurity(player, ObjectGuid::Empty))
                continue;

            std::string plNameLink = handler->GetNameLink(player);

            if (player->IsBeingTeleported())
            {
                handler->PSendSysMessage(LANG_IS_TELEPORTED, plNameLink.c_str());
                continue;
            }

            if (toInstance)
            {
                Map* playerMap = player->GetMap();

                if (
                    (onlyLocalSummon || (playerMap->Instanceable() && playerMap->GetId() == gmMap->GetId())) && // either no far summon allowed or we're in the same map as player (no map switch)
                    ((playerMap->GetId() != gmMap->GetId()) || (playerMap->GetInstanceId() != gmMap->GetInstanceId())) // so we need to be in the same map and instance of the map, otherwise skip
                    )
                {
                    // cannot summon from instance to instance
                    handler->PSendSysMessage(LANG_CANNOT_SUMMON_INST_INST, plNameLink.c_str());
                    continue;
                }
            }

            handler->PSendSysMessage(LANG_SUMMONING, plNameLink.c_str(), "");
            if (handler->needReportToTarget(player))
                ChatHandler(player->GetSession()).PSendSysMessage(LANG_SUMMONED_BY, handler->GetNameLink().c_str());

            // stop flight if need
            if (player->IsInFlight())
            {
                player->GetMotionMaster()->MovementExpired();
                player->CleanupAfterTaxiFlight();
            }
            // save only in non-flight case
            else
                player->SaveRecallPosition();

            // before GM
            float x, y, z;
            gmPlayer->GetClosePoint(x, y, z, player->GetCombatReach());
            player->TeleportTo(gmPlayer->GetMapId(), x, y, z, player->GetOrientation());
        }

        return true;
    }

    static bool HandleGroupLeaderCommand(ChatHandler* handler, char const* args)
    {
        Player* player = nullptr;
        Group* group = nullptr;
        ObjectGuid guid;
        char* nameStr = strtok((char*)args, " ");

        if (!handler->GetPlayerGroupAndGUIDByName(nameStr, player, group, guid))
            return false;

        if (!group)
        {
            handler->PSendSysMessage(LANG_GROUP_NOT_IN_GROUP, player->GetName().c_str());
            handler->SetSentErrorMessage(true);
            return false;
        }

        if (group->GetLeaderGUID() != guid)
        {
            group->ChangeLeader(guid);
            group->SendUpdate();
        }

        return true;
    }

    static bool GroupFlagCommand(ChatHandler* handler, char const* args, GroupMemberFlags flag, const char* what)
    {
        Player* player = nullptr;
        Group* group = nullptr;
        ObjectGuid guid;
        char* nameStr = strtok((char*)args, " ");

        if (!handler->GetPlayerGroupAndGUIDByName(nameStr, player, group, guid))
            return false;

        if (!group)
        {
            handler->PSendSysMessage(LANG_GROUP_NOT_IN_GROUP, player->GetName().c_str());
            handler->SetSentErrorMessage(true);
            return false;
        }

        if (!group->isRaidGroup())
        {
            handler->PSendSysMessage(LANG_GROUP_NOT_IN_RAID_GROUP, player->GetName().c_str());
            handler->SetSentErrorMessage(true);
            return false;
        }

        if (flag == MEMBER_FLAG_ASSISTANT && group->IsLeader(guid))
        {
            handler->PSendSysMessage(LANG_LEADER_CANNOT_BE_ASSISTANT, player->GetName().c_str());
            handler->SetSentErrorMessage(true);
            return false;
        }

        if (group->GetMemberFlags(guid) & flag)
        {
            group->SetGroupMemberFlag(guid, false, flag);
            handler->PSendSysMessage(LANG_GROUP_ROLE_CHANGED, player->GetName().c_str(), "no longer", what);
        }
        else
        {
            group->SetGroupMemberFlag(guid, true, flag);
            handler->PSendSysMessage(LANG_GROUP_ROLE_CHANGED, player->GetName().c_str(), "now", what);
        }
        return true;
    }

    static bool HandleGroupAssistantCommand(ChatHandler* handler, char const* args)
    {
        return GroupFlagCommand(handler, args, MEMBER_FLAG_ASSISTANT, "Assistant");
    }

    static bool HandleGroupMainTankCommand(ChatHandler* handler, char const* args)
    {
        return GroupFlagCommand(handler, args, MEMBER_FLAG_MAINTANK, "Main Tank");
    }

    static bool HandleGroupMainAssistCommand(ChatHandler* handler, char const* args)
    {
        return GroupFlagCommand(handler, args, MEMBER_FLAG_MAINASSIST, "Main Assist");
    }

    static bool HandleGroupDisbandCommand(ChatHandler* handler, char const* args)
    {
        Player* player = nullptr;
        Group* group = nullptr;
        ObjectGuid guid;
        char* nameStr = strtok((char*)args, " ");

        if (!handler->GetPlayerGroupAndGUIDByName(nameStr, player, group, guid))
            return false;

        if (!group)
        {
            handler->PSendSysMessage(LANG_GROUP_NOT_IN_GROUP, player->GetName().c_str());
            handler->SetSentErrorMessage(true);
            return false;
        }

        group->Disband();
        return true;
    }

    static bool HandleGroupRemoveCommand(ChatHandler* handler, char const* args)
    {
        Player* player = nullptr;
        Group* group = nullptr;
        ObjectGuid guid;
        char* nameStr = strtok((char*)args, " ");

        if (!handler->GetPlayerGroupAndGUIDByName(nameStr, player, group, guid))
            return false;

        if (!group)
        {
            handler->PSendSysMessage(LANG_GROUP_NOT_IN_GROUP, player->GetName().c_str());
            handler->SetSentErrorMessage(true);
            return false;
        }

        group->RemoveMember(guid);
        return true;
    }

    static bool HandleGroupJoinCommand(ChatHandler* handler, char const* args)
    {
        if (!*args)
            return false;

        Player* playerSource = nullptr;
        Player* playerTarget = nullptr;
        Group* groupSource = nullptr;
        Group* groupTarget = nullptr;
        ObjectGuid guidSource;
        ObjectGuid guidTarget;
        char* nameplgrStr = strtok((char*)args, " ");
        char* nameplStr = strtok(nullptr, " ");

        if (!handler->GetPlayerGroupAndGUIDByName(nameplgrStr, playerSource, groupSource, guidSource, true))
            return false;

        if (!groupSource)
        {
            handler->PSendSysMessage(LANG_GROUP_NOT_IN_GROUP, playerSource->GetName().c_str());
            handler->SetSentErrorMessage(true);
            return false;
        }

        if (!handler->GetPlayerGroupAndGUIDByName(nameplStr, playerTarget, groupTarget, guidTarget, true))
            return false;

        if (groupTarget || playerTarget->GetGroup() == groupSource)
        {
            handler->PSendSysMessage(LANG_GROUP_ALREADY_IN_GROUP, playerTarget->GetName().c_str());
            handler->SetSentErrorMessage(true);
            return false;
        }

        if (groupSource->IsFull())
        {
            handler->PSendSysMessage(LANG_GROUP_FULL);
            handler->SetSentErrorMessage(true);
            return false;
        }

        groupSource->AddMember(playerTarget);
        groupSource->BroadcastGroupUpdate();
        handler->PSendSysMessage(LANG_GROUP_PLAYER_JOINED, playerTarget->GetName().c_str(), playerSource->GetName().c_str());
        return true;
    }

    static bool HandleGroupListCommand(ChatHandler* handler, char const* args)
    {
        // Get ALL the variables!
        Player* playerTarget;
        ObjectGuid guidTarget;
        std::string nameTarget;
        std::string zoneName;
        const char* onlineState = "";

        // Parse the guid to uint32...
        ObjectGuid parseGUID = ObjectGuid::Create<HighGuid::Player>(strtoull(args, nullptr, 10));

        // ... and try to extract a player out of it.
        if (sCharacterCache->GetCharacterNameByGuid(parseGUID, nameTarget))
        {
            playerTarget = ObjectAccessor::FindPlayer(parseGUID);
            guidTarget = parseGUID;
        }
        // If not, we return false and end right away.
        else if (!handler->extractPlayerTarget((char*)args, &playerTarget, &guidTarget, &nameTarget))
            return false;

        // Next, we need a group. So we define a group variable.
        Group* groupTarget = nullptr;

        // We try to extract a group from an online player.
        if (playerTarget)
            groupTarget = playerTarget->GetGroup();

        // If not, we extract it from the SQL.
        if (!groupTarget)
        {
            CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_GROUP_MEMBER);
            stmt->setUInt64(0, guidTarget.GetCounter());
            PreparedQueryResult resultGroup = CharacterDatabase.Query(stmt);
            if (resultGroup)
                groupTarget = sGroupMgr->GetGroupByDbStoreId((*resultGroup)[0].GetUInt32());
        }

        // If both fails, players simply has no party. Return false.
        if (!groupTarget)
        {
            handler->PSendSysMessage(LANG_GROUP_NOT_IN_GROUP, nameTarget.c_str());
            handler->SetSentErrorMessage(true);
            return false;
        }

        // We get the group members after successfully detecting a group.
        Group::MemberSlotList const& members = groupTarget->GetMemberSlots();

        // To avoid a cluster fuck, namely trying multiple queries to simply get a group member count...
        handler->PSendSysMessage(LANG_GROUP_TYPE, (groupTarget->isRaidGroup() ? "raid" : "party"), std::to_string(members.size()).c_str());
        // ... we simply move the group type and member count print after retrieving the slots and simply output it's size.

        // While rather dirty codestyle-wise, it saves space (if only a little). For each member, we look several informations up.
        for (Group::MemberSlotList::const_iterator itr = members.begin(); itr != members.end(); ++itr)
        {
            // Define temporary variable slot to iterator.
            Group::MemberSlot const& slot = *itr;

            // Check for given flag and assign it to that iterator
            std::string flags;
            if (slot.flags & MEMBER_FLAG_ASSISTANT)
                flags = "Assistant";

            if (slot.flags & MEMBER_FLAG_MAINTANK)
            {
                if (!flags.empty())
                    flags.append(", ");
                flags.append("MainTank");
            }

            if (slot.flags & MEMBER_FLAG_MAINASSIST)
            {
                if (!flags.empty())
                    flags.append(", ");
                flags.append("MainAssist");
            }

            if (flags.empty())
                flags = "None";

            // Check if iterator is online. If is...
            Player* p = ObjectAccessor::FindPlayer((*itr).guid);
            std::string phases;
            if (p)
            {
                // ... than, it prints information like "is online", where he is, etc...
                onlineState = "online";
                phases = PhasingHandler::FormatPhases(p->GetPhaseShift());

                AreaTableEntry const* area = sAreaTableStore.LookupEntry(p->GetAreaId());
                if (area)
                {
                    AreaTableEntry const* zone = sAreaTableStore.LookupEntry(area->ParentAreaID);
                    if (zone)
                        zoneName = zone->AreaName[handler->GetSessionDbcLocale()];
                }
            }
            else
            {
                // ... else, everything is set to offline or neutral values.
                zoneName    = "<ERROR>";
                onlineState = "Offline";
            }

            // Now we can print those informations for every single member of each group!
            handler->PSendSysMessage(LANG_GROUP_PLAYER_NAME_GUID, slot.name.c_str(), onlineState,
                zoneName.c_str(), phases.c_str(), slot.guid.ToString().c_str(), flags.c_str(),
                lfg::GetRolesString(slot.roles).c_str());
        }

        // And finish after every iterator is done.
        return true;
    }
};

void AddSC_group_commandscript()
{
    new group_commandscript();
}


<?xml version="1.0" encoding="UTF-8"?>
<semantic:definitions xmlns="https://www.drools.org/kie-dmn"
                      xmlns:dc="http://www.omg.org/spec/DMN/20180521/DC/"
                      xmlns:di="http://www.omg.org/spec/DMN/20180521/DI/"
                      xmlns:dmndi="http://www.omg.org/spec/DMN/20180521/DMNDI/"
                      xmlns:feel="http://www.omg.org/spec/DMN/20180521/FEEL/"
                      xmlns:kie="https://www.drools.org/kie-dmn"
                      xmlns:semantic="http://www.omg.org/spec/DMN/20180521/MODEL/"
                      id="_0019_flight_rebooking"
                      name="0019-flight-rebooking"
                      namespace="https://www.drools.org/kie-dmn">
   <semantic:itemDefinition id="_tFlight" name="tFlight">
      <semantic:itemComponent id="_tFlight_Flight" name="Flight Number">
         <semantic:typeRef>string</semantic:typeRef>
      </semantic:itemComponent>
      <semantic:itemComponent id="_tFlight_From" name="From">
         <semantic:typeRef>string</semantic:typeRef>
      </semantic:itemComponent>
      <semantic:itemComponent id="_tFlight_To" name="To">
         <semantic:typeRef>string</semantic:typeRef>
      </semantic:itemComponent>
      <semantic:itemComponent id="_tFlight_Dep" name="Departure">
         <semantic:typeRef>dateTime</semantic:typeRef>
      </semantic:itemComponent>
      <semantic:itemComponent id="_tFlight_Arr" name="Arrival">
         <semantic:typeRef>dateTime</semantic:typeRef>
      </semantic:itemComponent>
      <semantic:itemComponent id="_tFlight_Capacity" name="Capacity">
         <semantic:typeRef>number</semantic:typeRef>
      </semantic:itemComponent>
      <semantic:itemComponent id="_tFlight_Status" name="Status">
         <semantic:typeRef>string</semantic:typeRef>
      </semantic:itemComponent>
   </semantic:itemDefinition>
   <semantic:itemDefinition id="_tFlightTable" isCollection="true" name="tFlightTable">
      <semantic:typeRef>tFlight</semantic:typeRef>
   </semantic:itemDefinition>
   <semantic:itemDefinition id="_tPassenger" name="tPassenger">
      <semantic:itemComponent id="_tPassenger_Name" name="Name">
         <semantic:typeRef>string</semantic:typeRef>
      </semantic:itemComponent>
      <semantic:itemComponent id="_tPassenger_Status" name="Status">
         <semantic:typeRef>string</semantic:typeRef>
      </semantic:itemComponent>
      <semantic:itemComponent id="_tPassenger_Miles" name="Miles">
         <semantic:typeRef>number</semantic:typeRef>
      </semantic:itemComponent>
      <semantic:itemComponent id="_tPassenger_Flight" name="Flight Number">
         <semantic:typeRef>string</semantic:typeRef>
      </semantic:itemComponent>
   </semantic:itemDefinition>
   <semantic:itemDefinition id="_tPassengerTable" isCollection="true" name="tPassengerTable">
      <semantic:typeRef>tPassenger</semantic:typeRef>
   </semantic:itemDefinition>
   <semantic:itemDefinition id="_tFlightNumberList"
                            isCollection="true"
                            name="tFlightNumberList">
      <semantic:typeRef>string</semantic:typeRef>
   </semantic:itemDefinition>
   <semantic:inputData id="i_Flight_List" name="Flight List">
      <semantic:variable name="Flight List" typeRef="tFlightTable"/>
   </semantic:inputData>
   <semantic:inputData id="i_Passenger_List" name="Passenger List">
      <semantic:variable name="Passenger List" typeRef="tPassengerTable"/>
   </semantic:inputData>
   <semantic:decision name="Prioritized Waiting List" id="d_PrioritizedWaitingList">
      <semantic:variable name="Prioritized Waiting List" typeRef="tPassengerTable"/>
      <semantic:informationRequirement>
         <semantic:requiredInput href="#i_Passenger_List"/>
      </semantic:informationRequirement>
      <semantic:informationRequirement>
         <semantic:requiredInput href="#i_Flight_List"/>
      </semantic:informationRequirement>
      <semantic:knowledgeRequirement>
         <semantic:requiredKnowledge href="#b_PassengerPriority"/>
      </semantic:knowledgeRequirement>
      <semantic:context>
         <semantic:contextEntry>
            <semantic:variable name="Cancelled Flights" typeRef="tFlightNumberList"/>
            <semantic:literalExpression>
               <semantic:text>Flight List[ Status = "cancelled" ].Flight Number</semantic:text>
            </semantic:literalExpression>
         </semantic:contextEntry>
         <semantic:contextEntry>
            <semantic:variable name="Waiting List" typeRef="tPassengerTable"/>
            <semantic:literalExpression>
               <semantic:text>Passenger List[ list contains( Cancelled Flights, Flight Number ) ]</semantic:text>
            </semantic:literalExpression>
         </semantic:contextEntry>
         <semantic:contextEntry>
            <semantic:literalExpression>
               <semantic:text>sort( Waiting List, passenger priority )</semantic:text>
            </semantic:literalExpression>
         </semantic:contextEntry>
      </semantic:context>
   </semantic:decision>
   <semantic:decision name="Rebooked Passengers" id="d_RebookedPassengers">
      <semantic:variable name="Rebooked Passengers" typeRef="tPassengerTable"/>
      <semantic:informationRequirement>
         <semantic:requiredDecision href="#d_PrioritizedWaitingList"/>
      </semantic:informationRequirement>
      <semantic:informationRequirement>
         <semantic:requiredInput href="#i_Flight_List"/>
      </semantic:informationRequirement>
      <semantic:knowledgeRequirement>
         <semantic:requiredKnowledge href="#b_ReassignNextPassenger"/>
      </semantic:knowledgeRequirement>
      <semantic:invocation>
         <semantic:literalExpression>
            <semantic:text>reassign next passenger</semantic:text>
         </semantic:literalExpression>
         <semantic:binding>
            <semantic:parameter name="Waiting List"/>
            <semantic:literalExpression>
               <semantic:text>Prioritized Waiting List</semantic:text>
            </semantic:literalExpression>
         </semantic:binding>
         <semantic:binding>
            <semantic:parameter name="Reassigned Passengers List"/>
            <semantic:literalExpression>
               <semantic:text>[]</semantic:text>
            </semantic:literalExpression>
         </semantic:binding>
         <semantic:binding>
            <semantic:parameter name="Flights"/>
            <semantic:literalExpression>
               <semantic:text>Flight List</semantic:text>
            </semantic:literalExpression>
         </semantic:binding>
      </semantic:invocation>
   </semantic:decision>
   <semantic:businessKnowledgeModel id="b_PassengerPriority" name="passenger priority">
      <semantic:variable name="passenger priority" typeRef="boolean"/>
      <semantic:encapsulatedLogic>
         <semantic:formalParameter name="Passenger1" typeRef="tPassenger"/>
         <semantic:formalParameter name="Passenger2" typeRef="tPassenger"/>
         <semantic:decisionTable hitPolicy="UNIQUE">
            <semantic:input id="b_Passenger_Priority_dt_i_P1_Status" label="Passenger1.Status">
               <semantic:inputExpression typeRef="string">
                  <semantic:text>Passenger1.Status</semantic:text>
               </semantic:inputExpression>
               <semantic:inputValues>
                  <semantic:text>"gold", "silver", "bronze"</semantic:text>
               </semantic:inputValues>
            </semantic:input>
            <semantic:input id="b_Passenger_Priority_dt_i_P2_Status" label="Passenger2.Status">
               <semantic:inputExpression typeRef="string">
                  <semantic:text>Passenger2.Status</semantic:text>
               </semantic:inputExpression>
               <semantic:inputValues>
                  <semantic:text>"gold", "silver", "bronze"</semantic:text>
               </semantic:inputValues>
            </semantic:input>
            <semantic:input id="b_Passenger_Priority_dt_i_P1_Miles" label="Passenger1.Miles">
               <semantic:inputExpression typeRef="string">
                  <semantic:text>Passenger1.Miles</semantic:text>
               </semantic:inputExpression>
            </semantic:input>
            <semantic:output id="b_Status_Priority_dt_o" label="Passenger1 has priority">
               <semantic:outputValues>
                  <semantic:text>true, false</semantic:text>
               </semantic:outputValues>
               <semantic:defaultOutputEntry>
                  <semantic:text>false</semantic:text>
               </semantic:defaultOutputEntry>
            </semantic:output>
            <semantic:rule id="b_Passenger_Priority_dt_r1">
               <semantic:inputEntry id="b_Passenger_Priority_dt_r1_i1">
                  <semantic:text>"gold"</semantic:text>
               </semantic:inputEntry>
               <semantic:inputEntry id="b_Passenger_Priority_dt_r1_i2">
                  <semantic:text>"gold"</semantic:text>
               </semantic:inputEntry>
               <semantic:inputEntry id="b_Passenger_Priority_dt_r1_i3">
                  <semantic:text>>= Passenger2.Miles</semantic:text>
               </semantic:inputEntry>
               <semantic:outputEntry id="b_Passenger_Priority_dt_r1_o1">
                  <semantic:text>true</semantic:text>
               </semantic:outputEntry>
            </semantic:rule>
            <semantic:rule id="b_Passenger_Priority_dt_r2">
               <semantic:inputEntry id="b_Passenger_Priority_dt_r2_i1">
                  <semantic:text>"gold"</semantic:text>
               </semantic:inputEntry>
               <semantic:inputEntry id="b_Passenger_Priority_dt_r2_i2">
                  <semantic:text>"silver","bronze"</semantic:text>
               </semantic:inputEntry>
               <semantic:inputEntry id="b_Passenger_Priority_dt_r2_i3">
                  <semantic:text>-</semantic:text>
               </semantic:inputEntry>
               <semantic:outputEntry id="b_Passenger_Priority_dt_r2_o1">
                  <semantic:text>true</semantic:text>
               </semantic:outputEntry>
            </semantic:rule>
            <semantic:rule id="b_Passenger_Priority_dt_r3">
               <semantic:inputEntry id="b_Passenger_Priority_dt_r3_i1">
                  <semantic:text>"silver"</semantic:text>
               </semantic:inputEntry>
               <semantic:inputEntry id="b_Passenger_Priority_dt_r3_i2">
                  <semantic:text>"silver"</semantic:text>
               </semantic:inputEntry>
               <semantic:inputEntry id="b_Passenger_Priority_dt_r3_i3">
                  <semantic:text>>= Passenger2.Miles</semantic:text>
               </semantic:inputEntry>
               <semantic:outputEntry id="b_Passenger_Priority_dt_r3_o1">
                  <semantic:text>true</semantic:text>
               </semantic:outputEntry>
            </semantic:rule>
            <semantic:rule id="b_Passenger_Priority_dt_r4">
               <semantic:inputEntry id="b_Passenger_Priority_dt_r4_i1">
                  <semantic:text>"silver"</semantic:text>
               </semantic:inputEntry>
               <semantic:inputEntry id="b_Passenger_Priority_dt_r4_i2">
                  <semantic:text>"bronze"</semantic:text>
               </semantic:inputEntry>
               <semantic:inputEntry id="b_Passenger_Priority_dt_r4_i3">
                  <semantic:text>-</semantic:text>
               </semantic:inputEntry>
               <semantic:outputEntry id="b_Passenger_Priority_dt_r4_o1">
                  <semantic:text>true</semantic:text>
               </semantic:outputEntry>
            </semantic:rule>
            <semantic:rule id="b_Passenger_Priority_dt_r5">
               <semantic:inputEntry id="b_Passenger_Priority_dt_r5_i1">
                  <semantic:text>"bronze"</semantic:text>
               </semantic:inputEntry>
               <semantic:inputEntry id="b_Passenger_Priority_dt_r5_i2">
                  <semantic:text>"bronze"</semantic:text>
               </semantic:inputEntry>
               <semantic:inputEntry id="b_Passenger_Priority_dt_r5_i3">
                  <semantic:text>>= Passenger2.Miles</semantic:text>
               </semantic:inputEntry>
               <semantic:outputEntry id="b_Passenger_Priority_dt_r5_o1">
                  <semantic:text>true</semantic:text>
               </semantic:outputEntry>
            </semantic:rule>
         </semantic:decisionTable>
      </semantic:encapsulatedLogic>
   </semantic:businessKnowledgeModel>
   <semantic:businessKnowledgeModel id="b_ReassignNextPassenger" name="reassign next passenger">
      <semantic:variable name="reassign next passenger" typeRef="tPassengerTable"/>
      <semantic:encapsulatedLogic>
         <semantic:formalParameter name="Waiting List" typeRef="tPassengerTable"/>
         <semantic:formalParameter name="Reassigned Passengers List" typeRef="tPassengerTable"/>
         <semantic:formalParameter name="Flights" typeRef="tFlightTable"/>
         <semantic:context>
            <semantic:contextEntry>
               <semantic:variable name="Next Passenger" typeRef="tPassenger"/>
               <semantic:literalExpression>
                  <semantic:text>Waiting List[1]</semantic:text>
               </semantic:literalExpression>
            </semantic:contextEntry>
            <semantic:contextEntry>
               <semantic:variable name="Original Flight" typeRef="tFlight"/>
               <semantic:literalExpression>
                  <semantic:text>Flights[ Flight Number = Next Passenger.Flight Number ][1]</semantic:text>
               </semantic:literalExpression>
            </semantic:contextEntry>
            <semantic:contextEntry>
               <semantic:variable name="Best Alternate Flight" typeRef="tFlight"/>
               <semantic:literalExpression>
                  <semantic:text>Flights[ From = Original Flight.From and
							           To = Original Flight.To and
							           Departure > Original Flight.Departure and
						               Status = "scheduled" and
						               has capacity( item, Reassigned Passengers List ) ][1]</semantic:text>
               </semantic:literalExpression>
            </semantic:contextEntry>
            <semantic:contextEntry>
               <semantic:variable name="Reassigned Passenger" typeRef="tPassenger"/>
               <semantic:context>
                  <semantic:contextEntry>
                     <semantic:variable name="Name" typeRef="string"/>
                     <semantic:literalExpression>
                        <semantic:text>Next Passenger.Name</semantic:text>
                     </semantic:literalExpression>
                  </semantic:contextEntry>
                  <semantic:contextEntry>
                     <semantic:variable name="Status" typeRef="string"/>
                     <semantic:literalExpression>
                        <semantic:text>Next Passenger.Status</semantic:text>
                     </semantic:literalExpression>
                  </semantic:contextEntry>
                  <semantic:contextEntry>
                     <semantic:variable name="Miles" typeRef="number"/>
                     <semantic:literalExpression>
                        <semantic:text>Next Passenger.Miles</semantic:text>
                     </semantic:literalExpression>
                  </semantic:contextEntry>
                  <semantic:contextEntry>
                     <semantic:variable name="Flight Number" typeRef="string"/>
                     <semantic:literalExpression>
                        <semantic:text>Best Alternate Flight.Flight Number</semantic:text>
                     </semantic:literalExpression>
                  </semantic:contextEntry>
               </semantic:context>
            </semantic:contextEntry>
            <semantic:contextEntry>
               <semantic:variable name="Remaining Waiting List" typeRef="tPassengerTable"/>
               <semantic:literalExpression>
                  <semantic:text>remove( Waiting List, 1 )</semantic:text>
               </semantic:literalExpression>
            </semantic:contextEntry>
            <semantic:contextEntry>
               <semantic:variable name="Updated Reassigned Passengers List" typeRef="tPassengerTable"/>
               <semantic:literalExpression>
                  <semantic:text>append( Reassigned Passengers List, Reassigned Passenger )</semantic:text>
               </semantic:literalExpression>
            </semantic:contextEntry>
            <semantic:contextEntry>
               <semantic:literalExpression>
                  <semantic:text>if count( Remaining Waiting List ) > 0
							  then
							       reassign next passenger( Remaining Waiting List,
							                                Updated Reassigned Passengers List,
							                                Flights )
							  else
							       Updated Reassigned Passengers List
						</semantic:text>
               </semantic:literalExpression>
            </semantic:contextEntry>
         </semantic:context>
      </semantic:encapsulatedLogic>
      <semantic:knowledgeRequirement>
         <semantic:requiredKnowledge href="#b_HasCapacity"/>
      </semantic:knowledgeRequirement>
   </semantic:businessKnowledgeModel>
   <semantic:businessKnowledgeModel id="b_HasCapacity" name="has capacity">
      <semantic:variable name="has capacity" typeRef="boolean"/>
      <semantic:encapsulatedLogic>
         <semantic:formalParameter name="flight" typeRef="tFlight"/>
         <semantic:formalParameter name="rebooked list" typeRef="tPassengerTable"/>
         <semantic:literalExpression>
            <semantic:text> flight.Capacity > count( rebooked list[ Flight Number = flight.Flight Number ] ) </semantic:text>
         </semantic:literalExpression>
      </semantic:encapsulatedLogic>
   </semantic:businessKnowledgeModel>
</semantic:definitions>


// MyWindows.h

#ifndef __MYWINDOWS_H
#define __MYWINDOWS_H

#ifdef _WIN32

#include <windows.h>

#define CHAR_PATH_SEPARATOR '\\'
#define WCHAR_PATH_SEPARATOR L'\\'
#define STRING_PATH_SEPARATOR "\\"
#define WSTRING_PATH_SEPARATOR L"\\"

#else

#define CHAR_PATH_SEPARATOR '/'
#define WCHAR_PATH_SEPARATOR L'/'
#define STRING_PATH_SEPARATOR "/"
#define WSTRING_PATH_SEPARATOR L"/"

#include <stddef.h> // for wchar_t
#include <string.h>

#include "MyGuidDef.h"

typedef char CHAR;
typedef unsigned char UCHAR;

#undef BYTE
typedef unsigned char BYTE;

typedef short SHORT;
typedef unsigned short USHORT;

#undef WORD
typedef unsigned short WORD;
typedef short VARIANT_BOOL;

typedef int INT;
typedef Int32 INT32;
typedef unsigned int UINT;
typedef UInt32 UINT32;
typedef INT32 LONG;   // LONG, ULONG and DWORD must be 32-bit
typedef UINT32 ULONG;

#undef DWORD
typedef UINT32 DWORD;

typedef Int64 LONGLONG;
typedef UInt64 ULONGLONG;

typedef struct LARGE_INTEGER { LONGLONG QuadPart; }LARGE_INTEGER;
typedef struct _ULARGE_INTEGER { ULONGLONG QuadPart;} ULARGE_INTEGER;

typedef const CHAR *LPCSTR;
typedef CHAR TCHAR;
typedef const TCHAR *LPCTSTR;
typedef wchar_t WCHAR;
typedef WCHAR OLECHAR;
typedef const WCHAR *LPCWSTR;
typedef OLECHAR *BSTR;
typedef const OLECHAR *LPCOLESTR;
typedef OLECHAR *LPOLESTR;

typedef struct _FILETIME
{
  DWORD dwLowDateTime;
  DWORD dwHighDateTime;
}FILETIME;

#define HRESULT LONG
#define FAILED(Status) ((HRESULT)(Status)<0)
typedef ULONG PROPID;
typedef LONG SCODE;

#define S_OK    ((HRESULT)0x00000000L)
#define S_FALSE ((HRESULT)0x00000001L)
#define E_NOTIMPL ((HRESULT)0x80004001L)
#define E_NOINTERFACE ((HRESULT)0x80004002L)
#define E_ABORT ((HRESULT)0x80004004L)
#define E_FAIL ((HRESULT)0x80004005L)
#define STG_E_INVALIDFUNCTION ((HRESULT)0x80030001L)
#define E_OUTOFMEMORY ((HRESULT)0x8007000EL)
#define E_INVALIDARG ((HRESULT)0x80070057L)

#ifdef _MSC_VER
#define STDMETHODCALLTYPE __stdcall
#else
#define STDMETHODCALLTYPE
#endif

#define STDMETHOD_(t, f) virtual t STDMETHODCALLTYPE f
#define STDMETHOD(f) STDMETHOD_(HRESULT, f)
#define STDMETHODIMP_(type) type STDMETHODCALLTYPE
#define STDMETHODIMP STDMETHODIMP_(HRESULT)

#define PURE = 0

#define MIDL_INTERFACE(x) struct

#ifdef __cplusplus

DEFINE_GUID(IID_IUnknown,
0x00000000, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46);
struct IUnknown
{
  STDMETHOD(QueryInterface) (REFIID iid, void **outObject) PURE;
  STDMETHOD_(ULONG, AddRef)() PURE;
  STDMETHOD_(ULONG, Release)() PURE;
  #ifndef _WIN32
  virtual ~IUnknown() {}
  #endif
};

typedef IUnknown *LPUNKNOWN;

#endif

#define VARIANT_TRUE ((VARIANT_BOOL)-1)
#define VARIANT_FALSE ((VARIANT_BOOL)0)

enum VARENUM
{
  VT_EMPTY = 0,
  VT_NULL = 1,
  VT_I2 = 2,
  VT_I4 = 3,
  VT_R4 = 4,
  VT_R8 = 5,
  VT_CY = 6,
  VT_DATE = 7,
  VT_BSTR = 8,
  VT_DISPATCH = 9,
  VT_ERROR = 10,
  VT_BOOL = 11,
  VT_VARIANT = 12,
  VT_UNKNOWN = 13,
  VT_DECIMAL = 14,
  VT_I1 = 16,
  VT_UI1 = 17,
  VT_UI2 = 18,
  VT_UI4 = 19,
  VT_I8 = 20,
  VT_UI8 = 21,
  VT_INT = 22,
  VT_UINT = 23,
  VT_VOID = 24,
  VT_HRESULT = 25,
  VT_FILETIME = 64
};

typedef unsigned short VARTYPE;
typedef WORD PROPVAR_PAD1;
typedef WORD PROPVAR_PAD2;
typedef WORD PROPVAR_PAD3;

#ifdef __cplusplus

typedef struct tagPROPVARIANT
{
  VARTYPE vt;
  PROPVAR_PAD1 wReserved1;
  PROPVAR_PAD2 wReserved2;
  PROPVAR_PAD3 wReserved3;
  union
  {
    CHAR cVal;
    UCHAR bVal;
    SHORT iVal;
    USHORT uiVal;
    LONG lVal;
    ULONG ulVal;
    INT intVal;
    UINT uintVal;
    LARGE_INTEGER hVal;
    ULARGE_INTEGER uhVal;
    VARIANT_BOOL boolVal;
    SCODE scode;
    FILETIME filetime;
    BSTR bstrVal;
  };
} PROPVARIANT;

typedef PROPVARIANT tagVARIANT;
typedef tagVARIANT VARIANT;
typedef VARIANT VARIANTARG;

MY_EXTERN_C HRESULT VariantClear(VARIANTARG *prop);
MY_EXTERN_C HRESULT VariantCopy(VARIANTARG *dest, VARIANTARG *src);

#endif

MY_EXTERN_C BSTR SysAllocStringByteLen(LPCSTR psz, UINT len);
MY_EXTERN_C BSTR SysAllocString(const OLECHAR *sz);
MY_EXTERN_C void SysFreeString(BSTR bstr);
MY_EXTERN_C UINT SysStringByteLen(BSTR bstr);
MY_EXTERN_C UINT SysStringLen(BSTR bstr);

MY_EXTERN_C DWORD GetLastError();
MY_EXTERN_C LONG CompareFileTime(const FILETIME* ft1, const FILETIME* ft2);

#define CP_ACP    0
#define CP_OEMCP  1

typedef enum tagSTREAM_SEEK
{
  STREAM_SEEK_SET = 0,
  STREAM_SEEK_CUR = 1,
  STREAM_SEEK_END = 2
} STREAM_SEEK;

#endif
#endif


// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing

var d{
class C<T{
let g
class B<T where g:d{class a


// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

syntax = "proto3";

package google.protobuf;

option csharp_namespace = "Google.Protobuf.WellKnownTypes";
option go_package = "google.golang.org/protobuf/types/known/anypb";
option java_package = "com.google.protobuf";
option java_outer_classname = "AnyProto";
option java_multiple_files = true;
option objc_class_prefix = "GPB";

// `Any` contains an arbitrary serialized protocol buffer message along with a
// URL that describes the type of the serialized message.
//
// Protobuf library provides support to pack/unpack Any values in the form
// of utility functions or additional generated methods of the Any type.
//
// Example 1: Pack and unpack a message in C++.
//
//     Foo foo = ...;
//     Any any;
//     any.PackFrom(foo);
//     ...
//     if (any.UnpackTo(&foo)) {
//       ...
//     }
//
// Example 2: Pack and unpack a message in Java.
//
//     Foo foo = ...;
//     Any any = Any.pack(foo);
//     ...
//     if (any.is(Foo.class)) {
//       foo = any.unpack(Foo.class);
//     }
//
//  Example 3: Pack and unpack a message in Python.
//
//     foo = Foo(...)
//     any = Any()
//     any.Pack(foo)
//     ...
//     if any.Is(Foo.DESCRIPTOR):
//       any.Unpack(foo)
//       ...
//
//  Example 4: Pack and unpack a message in Go
//
//      foo := &pb.Foo{...}
//      any, err := anypb.New(foo)
//      if err != nil {
//        ...
//      }
//      ...
//      foo := &pb.Foo{}
//      if err := any.UnmarshalTo(foo); err != nil {
//        ...
//      }
//
// The pack methods provided by protobuf library will by default use
// 'type.googleapis.com/full.type.name' as the type URL and the unpack
// methods only use the fully qualified type name after the last '/'
// in the type URL, for example "foo.bar.com/x/y.z" will yield type
// name "y.z".
//
//
// JSON
// ====
// The JSON representation of an `Any` value uses the regular
// representation of the deserialized, embedded message, with an
// additional field `@type` which contains the type URL. Example:
//
//     package google.profile;
//     message Person {
//       string first_name = 1;
//       string last_name = 2;
//     }
//
//     {
//       "@type": "type.googleapis.com/google.profile.Person",
//       "firstName": <string>,
//       "lastName": <string>
//     }
//
// If the embedded message type is well-known and has a custom JSON
// representation, that representation will be embedded adding a field
// `value` which holds the custom JSON in addition to the `@type`
// field. Example (for message [google.protobuf.Duration][]):
//
//     {
//       "@type": "type.googleapis.com/google.protobuf.Duration",
//       "value": "1.212s"
//     }
//
message Any {
  // A URL/resource name that uniquely identifies the type of the serialized
  // protocol buffer message. This string must contain at least
  // one "/" character. The last segment of the URL's path must represent
  // the fully qualified name of the type (as in
  // `path/google.protobuf.Duration`). The name should be in a canonical form
  // (e.g., leading "." is not accepted).
  //
  // In practice, teams usually precompile into the binary all types that they
  // expect it to use in the context of Any. However, for URLs which use the
  // scheme `http`, `https`, or no scheme, one can optionally set up a type
  // server that maps type URLs to message definitions as follows:
  //
  // * If no scheme is provided, `https` is assumed.
  // * An HTTP GET on the URL must yield a [google.protobuf.Type][]
  //   value in binary format, or produce an error.
  // * Applications are allowed to cache lookup results based on the
  //   URL, or have them precompiled into a binary to avoid any
  //   lookup. Therefore, binary compatibility needs to be preserved
  //   on changes to types. (Use versioned type names to manage
  //   breaking changes.)
  //
  // Note: this functionality is not currently available in the official
  // protobuf release, and it is not used for type URLs beginning with
  // type.googleapis.com.
  //
  // Schemes other than `http`, `https` (or the empty scheme) might be
  // used with implementation specific semantics.
  //
  string type_url = 1;

  // Must be a valid serialized protocol buffer of the above specified type.
  bytes value = 2;
}


some avg10=3.12 avg60=1.40 avg300=0.03 total=16030
full avg10=0.00 avg60=0.00 avg300=0.00 total=7200