text:
/*!
    \file    drv_usb_host.c
    \brief   USB host mode low level driver

    \version 2020-08-04, V1.1.0, firmware for GD32VF103
*/

/*
    Copyright (c) 2020, GigaDevice Semiconductor Inc.

    Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice, this
       list of conditions and the following disclaimer.
    2. 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.
    3. Neither the name of the copyright holder 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 HOLDER 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.
*/

#include "drv_usb_hw.h"
#include "drv_usb_core.h"
#include "drv_usb_host.h"

const uint32_t PIPE_DPID[2] = {
    PIPE_DPID_DATA0,
    PIPE_DPID_DATA1
};

/*!
    \brief      initializes USB core for host mode
    \param[in]  pudev: pointer to selected usb host
    \param[out] none
    \retval     operation status
*/
usb_status usb_host_init (usb_core_driver *pudev)
{
    uint32_t i = 0U, inten = 0U;

    uint32_t nptxfifolen = 0U;
    uint32_t ptxfifolen = 0U;

    /* restart the PHY Clock */
    *pudev->regs.PWRCLKCTL = 0U;

    /* support FS/LS only */
    pudev->regs.hr->HCTL &= ~HCTL_SPDFSLS;

    /* configure data FIFOs size */
#ifdef USB_FS_CORE
    if (USB_CORE_ENUM_FS == pudev->bp.core_enum) {
        /* set Rx FIFO size */
        pudev->regs.gr->GRFLEN = USB_RX_FIFO_FS_SIZE;

        /* set non-periodic Tx FIFO size and address */
        nptxfifolen |= USB_RX_FIFO_FS_SIZE;
        nptxfifolen |= USB_HTX_NPFIFO_FS_SIZE << 16U;
        pudev->regs.gr->DIEP0TFLEN_HNPTFLEN = nptxfifolen;

        /* set periodic Tx FIFO size and address */
        ptxfifolen |= USB_RX_FIFO_FS_SIZE + USB_HTX_NPFIFO_FS_SIZE;
        ptxfifolen |= USB_HTX_PFIFO_FS_SIZE << 16U;
        pudev->regs.gr->HPTFLEN = ptxfifolen;
    }
#endif /* USB_FS_CORE */

#ifdef USE_OTG_MODE

    /* clear host set hnp enable in the usb_otg control register */
    pudev->regs.gr->GOTGCS &= ~GOTGCS_HHNPEN;

#endif /* USE_OTG_MODE */

    /* make sure the FIFOs are flushed */

    /* flush all Tx FIFOs in device or host mode */
    usb_txfifo_flush (&pudev->regs, 0x10U);

    /* flush the entire Rx FIFO */
    usb_rxfifo_flush (&pudev->regs);

    /* disable all interrupts */
    pudev->regs.gr->GINTEN = 0U;

    /* clear any pending USB OTG interrupts */
    pudev->regs.gr->GOTGINTF = 0xFFFFFFFFU;

    /* enable the USB wakeup and suspend interrupts */
    pudev->regs.gr->GINTF = 0xBFFFFFFFU;

    /* clear all pending host channel interrupts */
    for (i = 0U; i < pudev->bp.num_pipe; i++) {
        pudev->regs.pr[i]->HCHINTF = 0xFFFFFFFFU;
        pudev->regs.pr[i]->HCHINTEN = 0U;
    }

#ifndef USE_OTG_MODE
    usb_portvbus_switch (pudev, 1U);
#endif /* USE_OTG_MODE */

    pudev->regs.gr->GINTEN = GINTEN_WKUPIE | GINTEN_SPIE;

    /* enable host_mode-related interrupts */
    if (USB_USE_FIFO == pudev->bp.transfer_mode) {
        inten = GINTEN_RXFNEIE;
    }

    inten |= GINTEN_SESIE | GINTEN_HPIE | GINTEN_HCIE | GINTEN_ISOINCIE;

    pudev->regs.gr->GINTEN |= inten;

    inten = GINTEN_DISCIE | GINTEN_SOFIE;

    pudev->regs.gr->GINTEN &= ~inten;

    return USB_OK;
}

/*!
    \brief      control the VBUS to power
    \param[in]  pudev: pointer to selected usb host
    \param[in]  state: VBUS state
    \param[out] none
    \retval     none
*/
void usb_portvbus_switch (usb_core_driver *pudev, uint8_t state)
{
    uint32_t port = 0U;

    /* enable or disable the external charge pump */
    usb_vbus_drive (state);

    /* turn on the host port power. */
    port = usb_port_read (pudev);

    if (!(port & HPCS_PP) && (1U == state)) {
        port |= HPCS_PP;
    }

    if ((port & HPCS_PP) && (0U == state)) {
        port &= ~HPCS_PP;
    }

    *pudev->regs.HPCS = port;

    usb_mdelay (200U);
}

/*!
    \brief      reset host port
    \param[in]  pudev: pointer to usb device
    \param[out] none
    \retval     operation status
*/
uint32_t usb_port_reset (usb_core_driver *pudev)
{
    __IO uint32_t port = usb_port_read (pudev);

    *pudev->regs.HPCS = port | HPCS_PRST;

    usb_mdelay(20U); /* see note */

    *pudev->regs.HPCS = port & ~HPCS_PRST;

    usb_mdelay(20U);

    return 1U;
}

/*!
    \brief      initialize host pipe
    \param[in]  pudev: pointer to usb device
    \param[in]  pipe_num: host pipe number which is in (0..7)
    \param[out] none
    \retval     operation status
*/
usb_status usb_pipe_init (usb_core_driver *pudev, uint8_t pipe_num)
{
    usb_status status = USB_OK;

    __IO uint32_t pp_ctl = 0U;
    __IO uint32_t pp_inten = HCHINTEN_TFIE;

    usb_pipe *pp = &pudev->host.pipe[pipe_num];

    /* clear old interrupt conditions for this host channel */
    pudev->regs.pr[pipe_num]->HCHINTF = 0xFFFFFFFFU;

    if (USB_USE_DMA == pudev->bp.transfer_mode) {
        pp_inten |= HCHINTEN_DMAERIE;
    }

    if (pp->ep.dir) {
        pp_inten |= HCHINTEN_BBERIE;
    }

    /* enable channel interrupts required for this transfer */
    switch (pp->ep.type) {
    case USB_EPTYPE_CTRL:
    case USB_EPTYPE_BULK:
        pp_inten |= HCHINTEN_STALLIE | HCHINTEN_USBERIE \
                    | HCHINTEN_DTERIE | HCHINTEN_NAKIE;

        if (!pp->ep.dir) {
            pp_inten |= HCHINTEN_NYETIE;

            if (pp->ping) {
                pp_inten |= HCHINTEN_ACKIE;
            }
        }
        break;

    case USB_EPTYPE_INTR:
        pp_inten |= HCHINTEN_STALLIE | HCHINTEN_USBERIE | HCHINTEN_DTERIE \
                     | HCHINTEN_NAKIE | HCHINTEN_REQOVRIE;
        break;

    case USB_EPTYPE_ISOC:
        pp_inten |= HCHINTEN_REQOVRIE | HCHINTEN_ACKIE;

        if (pp->ep.dir) {
            pp_inten |= HCHINTEN_USBERIE;
        }
        break;

    default:
        break;
    }

    pudev->regs.pr[pipe_num]->HCHINTEN = pp_inten;

    /* enable the top level host channel interrupt */
    pudev->regs.hr->HACHINTEN |= 1U << pipe_num;

    /* make sure host channel interrupts are enabled */
    pudev->regs.gr->GINTEN |= GINTEN_HCIE;

    /* program the host channel control register */
    pp_ctl |= PIPE_CTL_DAR(pp->dev_addr);
    pp_ctl |= PIPE_CTL_EPNUM(pp->ep.num);
    pp_ctl |= PIPE_CTL_EPDIR(pp->ep.dir);
    pp_ctl |= PIPE_CTL_EPTYPE(pp->ep.type);
    pp_ctl |= PIPE_CTL_LSD(pp->dev_speed == PORT_SPEED_LOW);

    pp_ctl |= pp->ep.mps;
    pp_ctl |= ((uint32_t)(pp->ep.type == USB_EPTYPE_INTR) << 29U) & HCHCTL_ODDFRM;

    pudev->regs.pr[pipe_num]->HCHCTL = pp_ctl;

    return status;
}

/*!
    \brief      prepare host channel for transferring packets
    \param[in]  pudev: pointer to usb device
    \param[in]  pipe_num: host pipe number which is in (0..7)
    \param[out] none
    \retval     operation status
*/
usb_status usb_pipe_xfer (usb_core_driver *pudev, uint8_t pipe_num)
{
    usb_status status = USB_OK;

    uint16_t dword_len = 0U;
    uint16_t packet_count = 0U;

    __IO uint32_t pp_ctl = 0U;

    usb_pipe *pp = &pudev->host.pipe[pipe_num];

    uint16_t max_packet_len = pp->ep.mps;

    /* compute the expected number of packets associated to the transfer */
    if (pp->xfer_len > 0U) {
        packet_count = (uint16_t)((pp->xfer_len + max_packet_len - 1U) / max_packet_len);

        if (packet_count > HC_MAX_PACKET_COUNT) {
            packet_count = HC_MAX_PACKET_COUNT;
            pp->xfer_len = (uint16_t)(packet_count * max_packet_len);
        }
    } else {
        packet_count = 1U;
    }

    if (pp->ep.dir) {
        pp->xfer_len = (uint16_t)(packet_count * max_packet_len);
    }

    /* initialize the host channel transfer information */
    pudev->regs.pr[pipe_num]->HCHLEN = pp->xfer_len | pp->DPID | PIPE_XFER_PCNT(packet_count);

    if (USB_USE_DMA == pudev->bp.transfer_mode) {
        pudev->regs.pr[pipe_num]->HCHDMAADDR = (unsigned int)pp->xfer_buf;
    }

    pp_ctl = pudev->regs.pr[pipe_num]->HCHCTL;

    if (usb_frame_even(pudev)) {
        pp_ctl |= HCHCTL_ODDFRM;
    } else {
        pp_ctl &= ~HCHCTL_ODDFRM;
    }

    /* set host channel enabled */
    pp_ctl |= HCHCTL_CEN;
    pp_ctl &= ~HCHCTL_CDIS;

    pudev->regs.pr[pipe_num]->HCHCTL = pp_ctl;

    if (USB_USE_FIFO == pudev->bp.transfer_mode) {
        if ((0U == pp->ep.dir) && (pp->xfer_len > 0U)) {
            switch (pp->ep.type) {
            /* non-periodic transfer */
            case USB_EPTYPE_CTRL:
            case USB_EPTYPE_BULK:
                dword_len = (uint16_t)((pp->xfer_len + 3U) / 4U);

                /* check if there is enough space in fifo space */
                if (dword_len > (pudev->regs.gr->HNPTFQSTAT & HNPTFQSTAT_NPTXFS)) {
                    /* need to process data in nptxfempty interrupt */
                    pudev->regs.gr->GINTEN |= GINTEN_NPTXFEIE;
                }
                break;

            /* periodic transfer */
            case USB_EPTYPE_INTR:
            case USB_EPTYPE_ISOC:
                dword_len = (uint16_t)((pp->xfer_len + 3U) / 4U);

                /* check if there is enough space in fifo space */
                if (dword_len > (pudev->regs.hr->HPTFQSTAT & HPTFQSTAT_PTXFS)) {
                    /* need to process data in ptxfempty interrupt */
                    pudev->regs.gr->GINTEN |= GINTEN_PTXFEIE;
                }
                break;

            default:
                break;
            }

            /* write packet into the tx fifo. */
            usb_txfifo_write (&pudev->regs, pp->xfer_buf, pipe_num, (uint16_t)pp->xfer_len);
        }
    }

    return status;
}

/*!
    \brief      halt pipe
    \param[in]  pudev: pointer to usb device
    \param[in]  pipe_num: host pipe number which is in (0..7)
    \param[out] none
    \retval     operation status
*/
usb_status usb_pipe_halt (usb_core_driver *pudev, uint8_t pipe_num)
{
    __IO uint32_t pp_ctl = pudev->regs.pr[pipe_num]->HCHCTL;

    uint8_t ep_type = (uint8_t)((pp_ctl & HCHCTL_EPTYPE) >> 18U);

    pp_ctl |= HCHCTL_CEN | HCHCTL_CDIS;

    switch (ep_type) {
    case USB_EPTYPE_CTRL:
    case USB_EPTYPE_BULK:
        if (0U == (pudev->regs.gr->HNPTFQSTAT & HNPTFQSTAT_NPTXFS)) {
            pp_ctl &= ~HCHCTL_CEN;
        }
        break;

    case USB_EPTYPE_INTR:
    case USB_EPTYPE_ISOC:
        if (0U == (pudev->regs.hr->HPTFQSTAT & HPTFQSTAT_PTXFS)) {
            pp_ctl &= ~HCHCTL_CEN;
        }
        break;

    default:
        break;
    }

    pudev->regs.pr[pipe_num]->HCHCTL = pp_ctl;

    return USB_OK;
}

/*!
    \brief      configure host pipe to do ping operation
    \param[in]  pudev: pointer to usb device
    \param[in]  pipe_num: host pipe number which is in (0..7)
    \param[out] none
    \retval     operation status
*/
usb_status usb_pipe_ping (usb_core_driver *pudev, uint8_t pipe_num)
{
    uint32_t pp_ctl = 0U;

    pudev->regs.pr[pipe_num]->HCHLEN = HCHLEN_PING | (HCHLEN_PCNT & (1U << 19U));

    pp_ctl = pudev->regs.pr[pipe_num]->HCHCTL;

    pp_ctl |= HCHCTL_CEN;
    pp_ctl &= ~HCHCTL_CDIS;

    pudev->regs.pr[pipe_num]->HCHCTL = pp_ctl;

    return USB_OK;
}

/*!
    \brief      stop the USB host and clean up FIFO
    \param[in]  pudev: pointer to usb device
    \param[out] none
    \retval     none
*/
void usb_host_stop (usb_core_driver *pudev)
{
    uint32_t i;
    __IO uint32_t pp_ctl = 0U;

    pudev->regs.hr->HACHINTEN = 0x0U;
    pudev->regs.hr->HACHINT = 0xFFFFFFFFU;

    /* flush out any leftover queued requests. */
    for (i = 0U; i < pudev->bp.num_pipe; i++) {
        pp_ctl = pudev->regs.pr[i]->HCHCTL;

        pp_ctl &= ~(HCHCTL_CEN | HCHCTL_EPDIR);
        pp_ctl |= HCHCTL_CDIS;

        pudev->regs.pr[i]->HCHCTL = pp_ctl;
    }

    /* flush the FIFO */
    usb_rxfifo_flush (&pudev->regs);
    usb_txfifo_flush (&pudev->regs, 0x10U);
}


text:
<?php
namespace EkAndreas\Listig\Controller;

use EkAndreas\Listig\Model\ListingModel;
use EkAndreas\Listig\Route\Base;
use EkAndreas\Listig\Route\RouteInterface;

class AuthorController implements RouteInterface
{
    public static function routes()
    {
        Base::get('/author', __CLASS__ . '@all');
    }

    public function all(\WP_REST_Request $request)
    {
        $args = array(
            'orderby'      => 'display_name',
            'order'        => 'ASC',
            'fields'       => 'all',
            'who'          => 'authors'
        );
        $users = get_users($args);

        return $users;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.springframework.cloud.sleuth.instrument.web;

import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.junit.Test;
import org.springframework.cloud.sleuth.Span;
import org.springframework.cloud.sleuth.SpanTextMap;

import static org.assertj.core.api.BDDAssertions.then;

/**
 * @author Marcin Grzejszczak
 */
public class ZipkinHttpSpanInjectorTests {

	ZipkinHttpSpanInjector injector = new ZipkinHttpSpanInjector();

	@SuppressWarnings("unchecked")
	@Test
	public void should_not_override_already_existing_headers() throws Exception {
		Span span = Span.builder()
				.spanId(1L)
				.traceId(2L)
				.parent(3L)
				.baggage("foo", "bar")
				.name("span")
				.build();
		Map<String, String> holder = new HashMap<>();
		final SpanTextMap map = textMap(holder);
		holder.put(Span.SPAN_ID_NAME, Span.idToHex(10L));
		holder.put(Span.TRACE_ID_NAME, Span.idToHex(20L));
		holder.put(Span.PARENT_ID_NAME, Span.idToHex(30L));
		holder.put(Span.SPAN_NAME_NAME, "anotherSpan");

		injector.inject(span, map);

		then(map)
				.contains(new AbstractMap.SimpleEntry<String, String>(Span.SPAN_ID_NAME, Span.idToHex(10L)))
				.contains(new AbstractMap.SimpleEntry<String, String>(Span.TRACE_ID_NAME, Span.idToHex(20L)))
				.contains(new AbstractMap.SimpleEntry<String, String>(Span.PARENT_ID_NAME, Span.idToHex(30L)))
				.contains(new AbstractMap.SimpleEntry<String, String>(Span.SPAN_NAME_NAME, "anotherSpan"))
				.contains(new AbstractMap.SimpleEntry<String, String>("baggage-foo", "bar"));
	}

	private SpanTextMap textMap(Map<String, String> textMap) {
		return new SpanTextMap() {
			@Override public Iterator<Map.Entry<String, String>> iterator() {
				return textMap.entrySet().iterator();
			}

			@Override public void put(String key, String value) {
				textMap.put(key, value);
			}
		};
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/color_testing" android:state_checked="true"/>
    <item android:drawable="@color/color_testing" android:state_checked="false"/>
</selector>


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.StylusTask = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _gulp = require('gulp');

var _gulp2 = _interopRequireDefault(_gulp);

var _task = require('../base/task');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var StylusTask = exports.StylusTask = function (_Task) {
  _inherits(StylusTask, _Task);

  function StylusTask() {
    _classCallCheck(this, StylusTask);

    return _possibleConstructorReturn(this, Object.getPrototypeOf(StylusTask).apply(this, arguments));
  }

  _createClass(StylusTask, [{
    key: 'pipes',
    value: function pipes(pipe) {
      var stylus = require('gulp-stylus');
      var sourcemaps = require('gulp-sourcemaps');
      var postcss = require('gulp-postcss');

      var pAutoprefixer = require('autoprefixer');
      var pMqpacker = require('css-mqpacker');
      var pMatches = require('postcss-selector-matches');
      var pQuantity = require('postcss-quantity-queries');
      var csso = require('gulp-csso');

      // Useful stuff for docs generation: mdcss[https://github.com/jonathantneal/mdcss]

      return _get(Object.getPrototypeOf(StylusTask.prototype), 'pipes', this).call(this, pipe).pipe(sourcemaps.init()).pipe(stylus({
        pretty: true,
        'include css': true,
        compress: false
      })).pipe(postcss([pAutoprefixer({
        browsers: ['> 0.5%']
      }), pMqpacker({
        sort: true
      }), pMatches, pQuantity])).pipe(sourcemaps.write()).pipe(csso(true));
    }
  }]);

  return StylusTask;
}(_task.Task);


text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Country;

/**
 * CountrySearch represents the model behind the search form about `app\models\Country`.
 */
class CountrySearch extends Country
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['countryid'], 'integer'],
            [['iso3', 'name', 'datein', 'userin', 'dateup', 'userup'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Country::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $query->andFilterWhere([
            'countryid' => $this->countryid,
            'datein' => $this->datein,
            'dateup' => $this->dateup,
        ]);

        $query->andFilterWhere(['like', 'iso3', $this->iso3])
            ->andFilterWhere(['like', 'name', $this->name])
            ->andFilterWhere(['like', 'userin', $this->userin])
            ->andFilterWhere(['like', 'userup', $this->userup]);

        return $dataProvider;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace OpenTelemetry
{
    /// <summary>
    /// A read-only collection of tag key/value pairs.
    /// </summary>
    // Note: Does not implement IReadOnlyCollection<> or IEnumerable<> to
    // prevent accidental boxing.
    public readonly struct ReadOnlyTagCollection
    {
        private readonly string[] keys;
        private readonly object[] values;

        internal ReadOnlyTagCollection(string[]? keys, object[]? values)
        {
            this.keys = keys ?? Array.Empty<string>();
            this.values = values ?? Array.Empty<object>();

            Debug.Assert(this.keys.Length == this.values.Length, "Array length mismatch");
        }

        /// <summary>
        /// Gets the number of tags in the collection.
        /// </summary>
        public int Count => this.keys.Length;

        /// <summary>
        /// Returns an enumerator that iterates through the tags.
        /// </summary>
        /// <returns><see cref="Enumerator"/>.</returns>
        public Enumerator GetEnumerator() => new(this);

        /// <summary>
        /// Enumerates the elements of a <see cref="ReadOnlyTagCollection"/>.
        /// </summary>
        // Note: Does not implement IEnumerator<> to prevent accidental boxing.
        public struct Enumerator
        {
            private readonly ReadOnlyTagCollection source;
            private int index;

            internal Enumerator(ReadOnlyTagCollection source)
            {
                this.source = source;
                this.index = 0;
                this.Current = default;
            }

            /// <summary>
            /// Gets the tag at the current position of the enumerator.
            /// </summary>
            public KeyValuePair<string, object> Current { get; private set; }

            /// <summary>
            /// Advances the enumerator to the next element of the <see
            /// cref="ReadOnlyTagCollection"/>.
            /// </summary>
            /// <returns><see langword="true"/> if the enumerator was
            /// successfully advanced to the next element; <see
            /// langword="false"/> if the enumerator has passed the end of the
            /// collection.</returns>
            public bool MoveNext()
            {
                int index = this.index;

                if (index < this.source.Count)
                {
                    this.Current = new KeyValuePair<string, object>(
                        this.source.keys[index],
                        this.source.values[index]);

                    this.index++;
                    return true;
                }

                return false;
            }
        }
    }
}


text:
layout: post
title:  "A Volley introduction - Part 2"
date:   2013-06-06
tags: android demo
categories:
- Volley Tutorial
description: More advanced use of Volley
---
Following the previous post, a slightly more complete demo of Volley. Past the trivial make-a-JSON-request use case, this post will show what happens when you want to add headers, authentication, body... and use custom requests.

Having read the [previous post]({% post_url 2013-06-03-volley-part1 %}) is a plus, unless you already know about Volley.

All the code used here is available on github (<https://github.com/smaspe/VolleyTwitter>). This post will use the Twitter application-only API, which requires a developer key. The key goes in the `TwitterValue` class. (see <https://dev.twitter.com/docs/api/1.1>)

This demo shows how to authenticate using `OAuth2` and the bearer token, how to use a custom request to obtain a list of tweets, how to include the tweets in a `ListView`.

# Authentication

Twitter application-only authentication uses OAuth2. Details are given here <https://dev.twitter.com/docs/auth/application-only-auth>.

It is mostly a matter of making a POST request with a custom Authorization header and retrieve in the response a token that is used for the next requests in another custom Authorization header.

In order to do that, the best match in the collection of Request objects provided by Volley is `StringRequest`. It still requires to override the `getParams()` and `getHeader()` methods, as there is no setter for these values in the `StringRequest` class.

The `TokenRequest` class is as follows:

{% gist smaspe/5720280 %}

Nota: A `JsonObjectRequest` could also have been extended, but it would have also require to override `getBodyContentType()` and `getBody()`, and I fell that would quite change the meaning of the class, as a `JsonObjectRequest` is designed to have a JSON body, if any.

Getting the Bearer token from the `String` response is quite simple, simply create a `JSONObject`, get the `access_token` value, keep it somewhere.

# Loading tweets

In this example, the twitter search API is used. A GET is to be made on the search URL, with the Bearer Authorization header. The Request in this case is `TweetsRequest`, which extends `JsonObjectRequest` to add the header (in the same fashion as the `TokenRequest`).

{% gist smaspe/5720386 %}

This request object is used by the `TweetLoader` that gets the parameters for the request (the search query, the max_id from the already loaded items), receives events from the `EndlessScrollListener`, and has a `Listener<JSONObject>` to populate the `TweetAdapter` (a simple `ArrayAdapter` that uses `NetworkImageView` and `TextViews` to display the basic info of the tweet). The `TweetLoader` is rather simple, but a bit long to be pasted here, the full code is there: <https://github.com/smaspe/VolleyTwitter/blob/master/src/com/njzk2/twitterbrowser/TweetLoader.java>.

# A few more things

This demo app also uses a search dialog, as described here <http://developer.android.com/guide/topics/search/search-dialog.html>, and an `EndlessScrollListener` that allows tweets to be loaded as needed, this comes mostly from <http://benjii.me/2010/08/endless-scrolling-listview-in-android/>. The `BitmapLru` is the same as in the previous post.

# Conclusion

Volley shows a few limitations in a more complex scenario:

Adding headers is a matter of extending a `Request` class. As such, a common header used in several types of `Requests` (typically `JsonObjectRequest` and `JsonArrayRequest`) requires duplicate overriding code.

`ImageLoader` instantiate exclusively `ImageRequest`. That means it is not possible without modifying Volley to add headers to `ImageRequests`, such as Authorization headers.

Requests sub-types have apparently been designed with a specific usage in mind. In fact, `JsonArrayRequest`, for example is exclusively a GET request, without possibility to change that unless overriding several methods, including `getMethod()` method and parameters/body are passed through the constructor, without possibility to set them afterward. That means the construction of the body must either happen outside the extending class or inside the `super()` call, which is not always possible in case some formatting is required.


text:
require "sms_box/version"
require "sms_box/response_exception"
require "sms_box/xml_request"
require "sms_box/xml_response"
require "sms_box/websend_request"
require "sms_box/websend_response"
require "sms_box/client"

module SMSBox
  def self.client url, opts = {}
    Client.new.tap do |client|
      client.url = url
      opts.each do |key, value|
        m = "#{key}="
        client.send(m, value) if client.respond_to?(m)
      end
      yield(client) if block_given?
    end
  end
end


text:
import logging

def find_selector(soup, elems):
    """Given a parsed html document, find a css selector for the given element.

    # Arguments
        soup: parsed html document
        el: html element for which a css selector has to be found

    # Returns
        selector: a css selector (or None if nothing found)
    """
    css_selectors = [class_css_selector,
                     id_css_selector,
                     attribute_css_selector,
                     type_css_selector]
    for selector in css_selectors:
        for el in elems:
            css_selector = selector(el)
            if valid(soup, css_selector) and \
                    unique(soup, css_selector) and \
                    match(soup, css_selector, el):
                return css_selector
    return None

def id_css_selector(el):
    """Tries to construct a css selector of the form el#id from the element

    # Argument
        el: an html element

    # Returns
        selector: css selector of the form el#id
    """
    css_id = el.get('id', None)
    if css_id and len(css_id[0].strip()) > 0:
        return '{}#{}'.format(el.name, css_id[0])
    return None

def class_css_selector(el):
    """Tries to construct a css selector of the form el.class from the element

    # Argument
        el: an html element

    # Returns
        selector: css selector of the form el.class
    """
    css_class = el.get('class', None)
    if css_class and len(css_class[0].strip()) > 0:
        return '{}.{}'.format(el.name, css_class[0])
    return None

def attribute_css_selector(el, attribute='itemprop'):
    """Tries to construct a css selector of the form el[attribute=value]
    from the element

    # Argument
        el: an html element
        attribute: css attribute

    # Returns
        selector: css selector of the form el.class
    """
    value = el.attrs.get(attribute, None)
    if value and len(value.strip()) > 0:
        return '{}[{}={}]'.format(el.name, attribute, value)
    return None

def type_css_selector(el):
    """Tries to construct a css selector of the form el from the element

    # Argument
        el: an html element

    # Returns
        selector: css selector of the form el
    """
    if el.name:
        return '{}'.format(el.name)
    return None

def unique(soup, css_selector):
    """Checks if selecting the css selector returns a unique element.

    # Arguments
        soup: parsed html document
        css_selector: css selector to be tested

    # Returns
        unique: True if a unique element is returned
    """
    return len(list(soup.select(css_selector))) == 1

def valid(soup, css_selector):
    """Checks if the css selector is valid.

    # Arguments
        soup: parsed html document
        css_selector: css selector for which the validity has to be checked

    # Returns
        valid: True if css slector is valid
    """
    try:
        soup.select(css_selector)
        return True
    except:
        return False

def match(soup, css_selector, el):
    """Checks if the selected element by the css selector matches
    the given element.

    # Arguments
        soup: parsed html document
        css_selector: css selector that returns an element
        el: html element to be matched with
    """
    return soup.select(css_selector)[0] == el


text:
package engine

import (
	"encoding/base64"
	"io"
	"io/ioutil"
	"net"
	"net/http"
	"os"
	"path/filepath"
	"reflect"
	"strconv"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/aws/amazon-ecs-agent/agent/api"
	"github.com/aws/amazon-ecs-agent/agent/config"
	"github.com/aws/amazon-ecs-agent/agent/utils"
	"github.com/aws/amazon-ecs-agent/agent/utils/ttime"
	docker "github.com/fsouza/go-dockerclient"
)

var testRegistryHost = "127.0.0.1:51670"
var testRegistryImage = "127.0.0.1:51670/amazon/amazon-ecs-netkitten:latest"
var testAuthRegistryHost = "127.0.0.1:51671"
var testAuthRegistryImage = "127.0.0.1:51671/amazon/amazon-ecs-netkitten:latest"
var testVolumeImage = "127.0.0.1:51670/amazon/amazon-ecs-volumes-test:latest"
var testAuthUser = "user"
var testAuthPass = "swordfish"

var test_time = ttime.NewTestTime()

var taskEngine *DockerTaskEngine

var initOnce sync.Once

func setup(t *testing.T) TaskEngine {
	if testing.Short() {
		t.Skip("Skipping integ test in short mode")
	}
	if _, err := os.Stat("/var/run/docker.sock"); err != nil {
		t.Skip("Docker not running")
	}
	if os.Getenv("ECS_SKIP_ENGINE_INTEG_TEST") != "" {
		t.Skip("ECS_SKIP_ENGINE_INTEG_TEST")
	}
	initOnce.Do(func() {
		taskEngine.Init()
	})
	ttime.SetTime(test_time)
	return taskEngine
}

func discardEvents(from interface{}) func() {
	done := make(chan bool)

	go func() {
		for {
			ndx, _, _ := reflect.Select([]reflect.SelectCase{
				reflect.SelectCase{
					Dir:  reflect.SelectRecv,
					Chan: reflect.ValueOf(from),
				},
				reflect.SelectCase{
					Dir:  reflect.SelectRecv,
					Chan: reflect.ValueOf(done),
				},
			})
			if ndx == 1 {
				break
			}
		}
	}()
	return func() {
		done <- true
	}
}

func createTestContainer() *api.Container {
	return &api.Container{
		Name:          "netcat",
		Image:         testRegistryImage,
		Command:       []string{},
		Essential:     true,
		DesiredStatus: api.ContainerRunning,
		Cpu:           100,
		Memory:        80,
	}
}

func createTestTask(arn string) *api.Task {
	return &api.Task{
		Arn:           arn,
		Family:        arn,
		Version:       "1",
		DesiredStatus: api.TaskRunning,
		Containers:    []*api.Container{createTestContainer()},
	}
}

func runProxyAuthRegistry() {
	// Run a basic-auth registry that proxies through to the regular registry
	// Only need to proxy through gets (at least for now)
	http.ListenAndServe(testAuthRegistryHost, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/v1/_ping" {
			w.Write([]byte(`true`))
			return
		}

		token := r.Header.Get("Authorization")
		validToken := "123abc"
		if !strings.Contains(token, validToken) {
			// No token, check basicauth
			// Don't use .BasicAuth method to be go1.3 compatible
			user := ""
			pass := ""
			basicAuth := r.Header.Get("Authorization")
			decoded, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(basicAuth, "Basic "))
			if err == nil {
				parts := strings.Split(string(decoded), ":")
				user = parts[0]
				if len(parts) > 1 {
					pass = parts[1]
				}
			}
			if user != testAuthUser || pass != testAuthPass {
				w.WriteHeader(403)
				w.Write([]byte(`permission denied`))
				return
			}
			// Regular auth fine, set token
			tokenString := "signature=123abc,access=read"
			w.Header().Set("WWW-Authenticate", "Token "+tokenString)
			w.Header().Set("X-Docker-Token", tokenString)
		}

		// Else, proxy through
		resp, err := http.Get("http://" + testRegistryHost + r.URL.Path)
		if err != nil {
			w.WriteHeader(404)
			return
		}
		io.Copy(w, resp.Body)
	}))
}

var cfg *config.Config

func init() {
	cfg, _ = config.NewConfig()
	taskEngine = NewDockerTaskEngine(cfg)
	go runProxyAuthRegistry()
}

var endpoint = utils.DefaultIfBlank(os.Getenv(DOCKER_ENDPOINT_ENV_VARIABLE), DOCKER_DEFAULT_ENDPOINT)

func removeImage(img string) {
	endpoint := utils.DefaultIfBlank(os.Getenv(DOCKER_ENDPOINT_ENV_VARIABLE), DOCKER_DEFAULT_ENDPOINT)
	client, _ := docker.NewClient(endpoint)

	client.RemoveImage(img)
}

// TestStartStopUnpulledImage ensures that an unpulled image is successfully
// pulled, run, and stopped via docker.
func TestStartStopUnpulledImage(t *testing.T) {
	taskEngine := setup(t)
	// Ensure this image isn't pulled by deleting it
	removeImage(testRegistryImage)

	testTask := createTestTask("testStartUnpulled")

	taskEvents, contEvents := taskEngine.TaskEvents()

	defer discardEvents(contEvents)()

	go taskEngine.AddTask(testTask)

	expected_events := []api.TaskStatus{api.TaskRunning, api.TaskStopped}

	for taskEvent := range taskEvents {
		if taskEvent.TaskArn != testTask.Arn {
			continue
		}
		expected_event := expected_events[0]
		expected_events = expected_events[1:]
		if taskEvent.Status != expected_event {
			t.Error("Got event " + taskEvent.Status.String() + " but expected " + expected_event.String())
		}
		if len(expected_events) == 0 {
			break
		}
	}
}

// TestPortForward runs a container serving data on the randomly chosen port
// 24751 and verifies that when you do forward the port you can access it and if
// you don't forward the port you can't
func TestPortForward(t *testing.T) {
	taskEngine := setup(t)

	taskEvents, contEvents := taskEngine.TaskEvents()

	defer discardEvents(contEvents)()

	testArn := "testPortForwardFail"
	testTask := createTestTask(testArn)
	testTask.Containers[0].Command = []string{"-l=24751", "-serve", "ecs test container"}

	// Port not forwarded; verify we can't access it
	go taskEngine.AddTask(testTask)

	for taskEvent := range taskEvents {
		if taskEvent.TaskArn != testTask.Arn {
			continue
		}
		if taskEvent.Status == api.TaskRunning {
			break
		} else if taskEvent.Status > api.TaskRunning {
			t.Fatal("Task went straight to " + taskEvent.Status.String() + " without running")
		}
	}
	_, err := net.DialTimeout("tcp", "127.0.0.1:24751", 20*time.Millisecond)
	if err == nil {
		t.Error("Did not expect to be able to dial 127.0.0.1:24751 but didn't get error")
	}

	// Kill the existing container now to make the test run more quickly.
	containerMap, _ := taskEngine.(*DockerTaskEngine).state.ContainerMapByArn(testTask.Arn)
	cid := containerMap[testTask.Containers[0].Name].DockerId
	client, _ := docker.NewClient(endpoint)
	err = client.KillContainer(docker.KillContainerOptions{ID: cid})
	if err != nil {
		t.Error("Could not kill container", err)
	}
	for taskEvent := range taskEvents {
		if taskEvent.TaskArn != testTask.Arn {
			continue
		}
		if taskEvent.Status >= api.TaskStopped {
			break
		}
	}

	// Now forward it and make sure that works
	testArn = "testPortForwardWorking"
	testTask = createTestTask(testArn)
	testTask.Containers[0].Command = []string{"-l=24751", "-serve", "ecs test container"}
	testTask.Containers[0].Ports = []api.PortBinding{api.PortBinding{ContainerPort: 24751, HostPort: 24751}}

	go taskEngine.AddTask(testTask)

	for taskEvent := range taskEvents {
		if taskEvent.TaskArn != testTask.Arn {
			continue
		}
		if taskEvent.Status == api.TaskRunning {
			break
		} else if taskEvent.Status > api.TaskRunning {
			t.Fatal("Task went straight to " + taskEvent.Status.String() + " without running")
		}
	}

	time.Sleep(10 * time.Millisecond) // Give nc time to liseten

	conn, err := net.DialTimeout("tcp", "127.0.0.1:24751", 20*time.Millisecond)
	if err != nil {
		t.Fatal("Error dialing simple container " + err.Error())
	}

	response, err := ioutil.ReadAll(conn)
	if err != nil {
		t.Error("Error reading response", err)
	}
	if string(response) != "ecs test container" {
		t.Error("Got response: " + string(response) + " instead of 'ecs test container'")
	}

	// Stop the existing container now
	taskUpdate := *testTask
	taskUpdate.DesiredStatus = api.TaskStopped
	go taskEngine.AddTask(&taskUpdate)
	for taskEvent := range taskEvents {
		if taskEvent.TaskArn != testTask.Arn {
			continue
		}
		if taskEvent.Status == api.TaskStopped {
			break
		}
	}
}

// TestMultiplePortForwards tests that two links containers in the same task can
// both expose ports successfully
func TestMultiplePortForwards(t *testing.T) {
	taskEngine := setup(t)

	taskEvents, containerEvents := taskEngine.TaskEvents()

	defer discardEvents(containerEvents)()

	// Forward it and make sure that works
	testArn := "testMultiplePortForwards"
	testTask := createTestTask(testArn)
	testTask.Containers[0].Command = []string{"-l=24751", "-serve", "ecs test container1"}
	testTask.Containers[0].Ports = []api.PortBinding{api.PortBinding{ContainerPort: 24751, HostPort: 24751}}
	testTask.Containers[0].Essential = false
	testTask.Containers = append(testTask.Containers, createTestContainer())
	testTask.Containers[1].Name = "nc2"
	testTask.Containers[1].Command = []string{"-l=24751", "-serve", "ecs test container2"}
	testTask.Containers[1].Ports = []api.PortBinding{api.PortBinding{ContainerPort: 24751, HostPort: 24752}}

	go taskEngine.AddTask(testTask)

	for taskEvent := range taskEvents {
		if taskEvent.TaskArn != testTask.Arn {
			continue
		}
		if taskEvent.Status == api.TaskRunning {
			break
		} else if taskEvent.Status > api.TaskRunning {
			t.Fatal("Task went straight to " + taskEvent.Status.String() + " without running")
		}
	}

	time.Sleep(10 * time.Millisecond) // Give nc time to liseten

	conn, err := net.DialTimeout("tcp", "127.0.0.1:24751", 20*time.Millisecond)
	if err != nil {
		t.Fatal("Error dialing simple container 1 " + err.Error())
	}
	t.Log("Dialed first container")
	response, _ := ioutil.ReadAll(conn)
	if string(response) != "ecs test container1" {
		t.Error("Got response: " + string(response) + " instead of 'ecs test container1'")
	}
	t.Log("Read first container")
	conn, err = net.DialTimeout("tcp", "127.0.0.1:24752", 20*time.Millisecond)
	if err != nil {
		t.Fatal("Error dialing simple container 2 " + err.Error())
	}
	t.Log("Dialed second container")
	response, _ = ioutil.ReadAll(conn)
	if string(response) != "ecs test container2" {
		t.Error("Got response: " + string(response) + " instead of 'ecs test container2'")
	}
	t.Log("Read second container")

	taskUpdate := *testTask
	taskUpdate.DesiredStatus = api.TaskStopped
	go taskEngine.AddTask(&taskUpdate)
	for taskEvent := range taskEvents {
		if taskEvent.TaskArn != testTask.Arn {
			continue
		}
		if taskEvent.Status == api.TaskStopped {
			break
		}
	}
}

// TestDynamicPortForward runs a container serving data on a port chosen by the
// docker deamon and verifies that the port is reported in the state-change
func TestDynamicPortForward(t *testing.T) {
	taskEngine := setup(t)

	taskEvents, contEvents := taskEngine.TaskEvents()

	testArn := "testDynamicPortForward"
	testTask := createTestTask(testArn)
	testTask.Containers[0].Command = []string{"-l=24751", "-serve", "ecs test container"}
	// No HostPort = docker should pick
	testTask.Containers[0].Ports = []api.PortBinding{api.PortBinding{ContainerPort: 24751}}

	go taskEngine.AddTask(testTask)

	var portBindings []api.PortBinding
PortsBound:
	for {
		select {
		case contEvent := <-contEvents:
			if contEvent.TaskArn != testTask.Arn {
				continue
			}
			if contEvent.Status == api.ContainerRunning {
				portBindings = contEvent.PortBindings
				break PortsBound
			} else if contEvent.Status > api.ContainerRunning {
				t.Fatal("Container went straight to " + contEvent.Status.String() + " without running")
			}
		case taskEvent := <-taskEvents:
			if taskEvent.Status == api.TaskStopped {
				t.Fatal("Task stopped")
			}
		}
	}
	defer discardEvents(contEvents)()

	if len(portBindings) != 1 {
		t.Error("PortBindings was not set; should have been len 1", portBindings)
	}
	var bindingFor24751 uint16
	for _, binding := range portBindings {
		if binding.ContainerPort == 24751 {
			bindingFor24751 = binding.HostPort
		}
	}
	if bindingFor24751 == 0 {
		t.Error("Could not find the port mapping for 24751!")
	}

	time.Sleep(10 * time.Millisecond) // Give nc time to liseten

	conn, err := net.DialTimeout("tcp", "127.0.0.1:"+strconv.Itoa(int(bindingFor24751)), 20*time.Millisecond)
	if err != nil {
		t.Fatal("Error dialing simple container " + err.Error())
	}

	response, _ := ioutil.ReadAll(conn)
	if string(response) != "ecs test container" {
		t.Error("Got response: " + string(response) + " instead of 'ecs test container'")
	}

	// Kill the existing container now
	taskUpdate := *testTask
	taskUpdate.DesiredStatus = api.TaskStopped
	go taskEngine.AddTask(&taskUpdate)
	for taskEvent := range taskEvents {
		if taskEvent.TaskArn != testTask.Arn {
			continue
		}
		if taskEvent.Status == api.TaskStopped {
			break
		}
	}
}

func TestMultipleDynamicPortForward(t *testing.T) {
	taskEngine := setup(t)

	taskEvents, contEvents := taskEngine.TaskEvents()

	testArn := "testDynamicPortForward2"
	testTask := createTestTask(testArn)
	testTask.Containers[0].Command = []string{"-l=24751", "-serve", "ecs test container", `-loop`}
	// No HostPort or 0 hostport; docker should pick two ports for us
	testTask.Containers[0].Ports = []api.PortBinding{api.PortBinding{ContainerPort: 24751}, api.PortBinding{ContainerPort: 24751, HostPort: 0}}

	go taskEngine.AddTask(testTask)

	var portBindings []api.PortBinding
	for contEvent := range contEvents {
		if contEvent.TaskArn != testTask.Arn {
			continue
		}
		if contEvent.Status == api.ContainerRunning {
			portBindings = contEvent.PortBindings
			break
		} else if contEvent.Status > api.ContainerRunning {
			t.Fatal("Task went straight to " + contEvent.Status.String() + " without running")
		}
	}
	defer discardEvents(contEvents)()

	if len(portBindings) != 2 {
		t.Error("Could not bind to two ports from one container port", portBindings)
	}
	var bindingFor24751_1 uint16
	var bindingFor24751_2 uint16
	for _, binding := range portBindings {
		if binding.ContainerPort == 24751 {
			if bindingFor24751_1 == 0 {
				bindingFor24751_1 = binding.HostPort
			} else {
				bindingFor24751_2 = binding.HostPort
			}
		}
	}
	if bindingFor24751_1 == 0 {
		t.Error("Could not find the port mapping for 24751!")
	}
	if bindingFor24751_2 == 0 {
		t.Error("Could not find the port mapping for 24751!")
	}

	time.Sleep(10 * time.Millisecond) // Give nc time to liseten

	conn, err := net.DialTimeout("tcp", "127.0.0.1:"+strconv.Itoa(int(bindingFor24751_1)), 20*time.Millisecond)
	if err != nil {
		t.Fatal("Error dialing simple container " + err.Error())
	}

	response, _ := ioutil.ReadAll(conn)
	if string(response) != "ecs test container" {
		t.Error("Got response: " + string(response) + " instead of 'ecs test container'")
	}

	time.Sleep(10 * time.Millisecond) // Give nc time to liseten

	conn, err = net.DialTimeout("tcp", "127.0.0.1:"+strconv.Itoa(int(bindingFor24751_2)), 20*time.Millisecond)
	if err != nil {
		t.Fatal("Error dialing simple container " + err.Error())
	}

	response, _ = ioutil.ReadAll(conn)
	if string(response) != "ecs test container" {
		t.Error("Got response: " + string(response) + " instead of 'ecs test container'")
	}

	// Kill the existing container now
	taskUpdate := *testTask
	taskUpdate.DesiredStatus = api.TaskStopped
	go taskEngine.AddTask(&taskUpdate)
	for taskEvent := range taskEvents {
		if taskEvent.TaskArn != testTask.Arn {
			continue
		}
		if taskEvent.Status == api.TaskStopped {
			break
		}
	}
}

// TestLinking ensures that container linking does allow networking to go
// through to a linked container.  this test specifically starts a server that
// prints "hello linker" and then links a container that proxies that data to
// a publicly exposed port, where the tests reads it
func TestLinking(t *testing.T) {
	taskEngine := setup(t)

	testTask := createTestTask("TestLinking")
	testTask.Containers = append(testTask.Containers, createTestContainer())
	testTask.Containers[0].Command = []string{"-l=80", "-serve", "hello linker"}
	testTask.Containers[0].Name = "linkee"
	testTask.Containers[1].Command = []string{"-l=24751", "linkee_alias:80"}
	testTask.Containers[1].Links = []string{"linkee:linkee_alias"}
	testTask.Containers[1].Ports = []api.PortBinding{api.PortBinding{ContainerPort: 24751, HostPort: 24751}}

	taskEvents, contEvents := taskEngine.TaskEvents()

	defer discardEvents(contEvents)()

	go taskEngine.AddTask(testTask)

	for taskEvent := range taskEvents {
		if taskEvent.TaskArn != testTask.Arn {
			continue
		}
		if taskEvent.Status == api.TaskRunning {
			break
		} else if taskEvent.Status > api.TaskRunning {
			t.Fatal("Task went straight to " + taskEvent.Status.String() + " without running")
		}
	}

	time.Sleep(10 * time.Millisecond)

	conn, err := net.DialTimeout("tcp", "127.0.0.1:24751", 10*time.Millisecond)
	if err != nil {
		t.Error("Error dialing simple container" + err.Error())
	}

	response, err := ioutil.ReadAll(conn)
	if err != nil {
		t.Error(err)
	}
	if string(response) != "hello linker" {
		t.Error("Got response: " + string(response) + " instead of 'hello linker'")
	}

	taskUpdate := *testTask
	taskUpdate.DesiredStatus = api.TaskStopped
	go taskEngine.AddTask(&taskUpdate)

	for taskEvent := range taskEvents {
		if taskEvent.TaskArn != testTask.Arn {
			continue
		}
		if taskEvent.Status == api.TaskStopped {
			break
		}
	}
}

func TestDockerCfgAuth(t *testing.T) {
	taskEngine := setup(t)
	removeImage(testAuthRegistryImage)

	authString := base64.StdEncoding.EncodeToString([]byte(testAuthUser + ":" + testAuthPass))
	cfg.EngineAuthData = []byte(`{"http://` + testAuthRegistryHost + `/v1/":{"auth":"` + authString + `"}}`)
	cfg.EngineAuthType = "dockercfg"
	defer func() {
		cfg.EngineAuthData = nil
		cfg.EngineAuthType = ""
	}()

	testTask := createTestTask("testDockerCfgAuth")
	testTask.Containers[0].Image = testAuthRegistryImage

	taskEvents, contEvents := taskEngine.TaskEvents()

	defer discardEvents(contEvents)()

	go taskEngine.AddTask(testTask)

	expected_events := []api.TaskStatus{api.TaskRunning}

	for taskEvent := range taskEvents {
		if taskEvent.TaskArn != testTask.Arn {
			continue
		}
		expected_event := expected_events[0]
		expected_events = expected_events[1:]
		if taskEvent.Status != expected_event {
			t.Error("Got event " + taskEvent.Status.String() + " but expected " + expected_event.String())
		}
		if len(expected_events) == 0 {
			break
		}
	}

	taskUpdate := *testTask
	taskUpdate.DesiredStatus = api.TaskStopped
	go taskEngine.AddTask(&taskUpdate)
	for taskEvent := range taskEvents {
		if taskEvent.TaskArn == testTask.Arn {
			if !(taskEvent.Status >= api.TaskStopped) {
				t.Error("Expected only terminal events; got " + taskEvent.Status.String())
			}
			break
		}
	}
}

func TestDockerAuth(t *testing.T) {
	taskEngine := setup(t)
	removeImage(testAuthRegistryImage)

	cfg.EngineAuthData = []byte(`{"http://` + testAuthRegistryHost + `":{"username":"` + testAuthUser + `","password":"` + testAuthPass + `"}}`)
	cfg.EngineAuthType = "docker"
	defer func() {
		cfg.EngineAuthData = nil
		cfg.EngineAuthType = ""
	}()

	testTask := createTestTask("testDockerAuth")
	testTask.Containers[0].Image = testAuthRegistryImage

	taskEvents, contEvents := taskEngine.TaskEvents()

	defer discardEvents(contEvents)()

	go taskEngine.AddTask(testTask)

	expected_events := []api.TaskStatus{api.TaskRunning}

	for taskEvent := range taskEvents {
		if taskEvent.TaskArn != testTask.Arn {
			continue
		}
		expected_event := expected_events[0]
		expected_events = expected_events[1:]
		if taskEvent.Status != expected_event {
			t.Error("Got event " + taskEvent.Status.String() + " but expected " + expected_event.String())
		}
		if len(expected_events) == 0 {
			break
		}
	}

	taskUpdate := *testTask
	taskUpdate.DesiredStatus = api.TaskStopped
	go taskEngine.AddTask(&taskUpdate)
	for taskEvent := range taskEvents {
		if taskEvent.TaskArn == testTask.Arn {
			if !(taskEvent.Status >= api.TaskStopped) {
				t.Error("Expected only terminal events; got " + taskEvent.Status.String())
			}
			break
		}
	}
}

func TestVolumesFrom(t *testing.T) {
	taskEngine := setup(t)

	taskEvents, contEvents := taskEngine.TaskEvents()

	defer discardEvents(contEvents)()

	testTask := createTestTask("testVolumeContainer")
	testTask.Containers[0].Image = testVolumeImage
	testTask.Containers = append(testTask.Containers, createTestContainer())
	testTask.Containers[1].Name = "test2"
	testTask.Containers[1].Image = testVolumeImage
	testTask.Containers[1].VolumesFrom = []api.VolumeFrom{api.VolumeFrom{SourceContainer: testTask.Containers[0].Name}}
	testTask.Containers[1].Command = []string{"cat /data/test-file | nc -l -p 80"}
	testTask.Containers[1].Ports = []api.PortBinding{api.PortBinding{ContainerPort: 80, HostPort: 24751}}

	go taskEngine.AddTask(testTask)

	for taskEvent := range taskEvents {
		if taskEvent.TaskArn != testTask.Arn {
			continue
		}
		if taskEvent.Status == api.TaskRunning {
			break
		}
	}
	time.Sleep(10 * time.Millisecond)
	conn, err := net.DialTimeout("tcp", "127.0.0.1:24751", 10*time.Millisecond)
	if err != nil {
		t.Error("Could not dial listening container" + err.Error())
	}

	response, err := ioutil.ReadAll(conn)
	if err != nil {
		t.Error(err)
	}
	if strings.TrimSpace(string(response)) != "test" {
		t.Error("Got response: " + strings.TrimSpace(string(response)) + " instead of 'test'")
	}

	taskUpdate := *testTask
	taskUpdate.DesiredStatus = api.TaskStopped
	go taskEngine.AddTask(&taskUpdate)

	for taskEvent := range taskEvents {
		if taskEvent.TaskArn != testTask.Arn {
			continue
		}
		if taskEvent.Status == api.TaskStopped {
			break
		}
	}
}

func TestVolumesFromRO(t *testing.T) {
	taskEngine := setup(t)

	taskEvents, contEvents := taskEngine.TaskEvents()

	defer discardEvents(contEvents)()

	testTask := createTestTask("testVolumeROContainer")
	testTask.Containers[0].Image = testVolumeImage
	for i := 0; i < 3; i++ {
		cont := createTestContainer()
		cont.Name = "test" + strconv.Itoa(i)
		cont.Image = testVolumeImage
		cont.Essential = i > 0
		testTask.Containers = append(testTask.Containers, cont)
	}
	testTask.Containers[1].VolumesFrom = []api.VolumeFrom{api.VolumeFrom{SourceContainer: testTask.Containers[0].Name, ReadOnly: true}}
	testTask.Containers[1].Command = []string{"touch /data/readonly-fs || exit 42"}
	testTask.Containers[2].VolumesFrom = []api.VolumeFrom{api.VolumeFrom{SourceContainer: testTask.Containers[0].Name}}
	testTask.Containers[2].Command = []string{"touch /data/notreadonly-fs-1 || exit 42"}
	testTask.Containers[3].VolumesFrom = []api.VolumeFrom{api.VolumeFrom{SourceContainer: testTask.Containers[0].Name, ReadOnly: false}}
	testTask.Containers[3].Command = []string{"touch /data/notreadonly-fs-2 || exit 42"}

	go taskEngine.AddTask(testTask)

	for taskEvent := range taskEvents {
		if taskEvent.Status == api.TaskStopped {
			break
		}
	}

	if testTask.Containers[1].KnownExitCode == nil || *testTask.Containers[1].KnownExitCode != 42 {
		t.Error("Didn't exit due to failure to touch ro fs as expected: ", *testTask.Containers[1].KnownExitCode)
	}
	if testTask.Containers[2].KnownExitCode == nil || *testTask.Containers[2].KnownExitCode != 0 {
		t.Error("Couldn't touch with default of rw")
	}
	if testTask.Containers[3].KnownExitCode == nil || *testTask.Containers[3].KnownExitCode != 0 {
		t.Error("Couldn't touch with explicit rw")
	}
}

func TestHostVolumeMount(t *testing.T) {
	taskEngine := setup(t)

	taskEvents, contEvents := taskEngine.TaskEvents()

	defer discardEvents(contEvents)()

	tmpPath, _ := ioutil.TempDir("", "ecs_volume_test")
	defer os.RemoveAll(tmpPath)
	ioutil.WriteFile(filepath.Join(tmpPath, "test-file"), []byte("test-data"), 0644)

	testTask := createTestTask("testHostVolumeMount")
	testTask.Volumes = []api.TaskVolume{api.TaskVolume{Name: "test-tmp", Volume: &api.FSHostVolume{FSSourcePath: tmpPath}}}
	testTask.Containers[0].Image = testVolumeImage
	testTask.Containers[0].MountPoints = []api.MountPoint{api.MountPoint{ContainerPath: "/host/tmp", SourceVolume: "test-tmp"}}
	testTask.Containers[0].Command = []string{`echo -n "hi" > /host/tmp/hello-from-container; if [[ "$(cat /host/tmp/test-file)" != "test-data" ]]; then exit 4; fi; exit 42`}
	go taskEngine.AddTask(testTask)

	for taskEvent := range taskEvents {
		if taskEvent.TaskArn != testTask.Arn {
			continue
		}
		if taskEvent.Status == api.TaskStopped {
			break
		}
	}

	if testTask.Containers[0].KnownExitCode == nil || *testTask.Containers[0].KnownExitCode != 42 {
		t.Error("Wrong exit code; file contents wrong or other error", *testTask.Containers[0].KnownExitCode)
	}
	data, err := ioutil.ReadFile(filepath.Join(tmpPath, "hello-from-container"))
	if err != nil || string(data) != "hi" {
		t.Error("Could not read file container wrote: ", err, string(data))
	}
}

func TestEmptyHostVolumeMount(t *testing.T) {
	taskEngine := setup(t)

	taskEvents, contEvents := taskEngine.TaskEvents()

	defer discardEvents(contEvents)()

	testTask := createTestTask("testEmptyHostVolumeMount")
	testTask.Volumes = []api.TaskVolume{api.TaskVolume{Name: "test-tmp", Volume: &api.EmptyHostVolume{}}}
	testTask.Containers[0].Image = testVolumeImage
	testTask.Containers[0].MountPoints = []api.MountPoint{api.MountPoint{ContainerPath: "/empty", SourceVolume: "test-tmp"}}
	testTask.Containers[0].Command = []string{`while true; do [[ -f "/empty/file" ]] && exit 42; done`}
	testTask.Containers = append(testTask.Containers, createTestContainer())
	testTask.Containers[1].Name = "test2"
	testTask.Containers[1].Image = testVolumeImage
	testTask.Containers[1].MountPoints = []api.MountPoint{api.MountPoint{ContainerPath: "/alsoempty/", SourceVolume: "test-tmp"}}
	testTask.Containers[1].Command = []string{`touch /alsoempty/file`}
	testTask.Containers[1].Essential = false
	go taskEngine.AddTask(testTask)

	for taskEvent := range taskEvents {
		if taskEvent.TaskArn != testTask.Arn {
			continue
		}
		if taskEvent.Status == api.TaskStopped {
			break
		}
	}

	if testTask.Containers[0].KnownExitCode == nil || *testTask.Containers[0].KnownExitCode != 42 {
		t.Error("Wrong exit code; file probably wasn't present")
	}
}

func TestSweepContainer(t *testing.T) {
	taskEngine := setup(t)

	taskEvents, contEvents := taskEngine.TaskEvents()

	defer discardEvents(contEvents)()

	testTask := createTestTask("testSweepContainer")

	go taskEngine.AddTask(testTask)

	expected_events := []api.TaskStatus{api.TaskRunning, api.TaskStopped}

	for taskEvent := range taskEvents {
		if taskEvent.TaskArn != testTask.Arn {
			continue
		}
		expected_event := expected_events[0]
		expected_events = expected_events[1:]
		if taskEvent.Status != expected_event {
			t.Error("Got event " + taskEvent.Status.String() + " but expected " + expected_event.String())
		}
		if len(expected_events) == 0 {
			break
		}
	}

	defer discardEvents(taskEvents)()

	// Should be stopped, let's verify it's still listed...
	_, ok := taskEngine.(*DockerTaskEngine).State().TaskByArn("testSweepContainer")
	if !ok {
		t.Error("Expected task to be present still, but wasn't")
	}
	test_time.Warp(4 * time.Hour)
	for i := 0; i < 60; i++ {
		_, ok = taskEngine.(*DockerTaskEngine).State().TaskByArn("testSweepContainer")
		if !ok {
			break
		}
		time.Sleep(1 * time.Second)
	}
	if ok {
		t.Error("Expected container to have been sweept but was not")
	}
}


text:
RNCryptor PHP
-------------

[![Build Status](https://travis-ci.org/RNCryptor/RNCryptor-php.svg?branch=master)](https://travis-ci.org/RNCryptor/RNCryptor-php)

This implementation strives to be fully compatible with Rob Napier's
Objective-C implementation of RNCryptor.  It supports both encryption and
decryption of all RNCryptor schema versions through version 3.  Due to security
concerns with schemas 0 through 2, it is strongly recommended to use schema 3
wherever possible.  This is the default if none is specified.

Basic usage is seen in the examples folder.


text:
@implementation OWDailyForecast

+(NSDictionary *)JSONKeyPathsByPropertyKey {
    NSMutableDictionary *paths = [[super JSONKeyPathsByPropertyKey] mutableCopy];

    paths[@"hiTemp"] = @"temp.max";
    paths[@"loTemp"] = @"temp.min";
    paths[@"cloudCover"] = @"clouds";
    return paths;
}

@end


text:
'use strict';

var shjs = require("shelljs");
var p = require('path');

module.exports = function (options, f) {
  // @todo do not rely on "/usr/bin/env"
  var cmd = '/usr/bin/env node ' + p.resolve(__dirname, '../../node_modules/nsp/bin/nspCLI.js package');
  var ret = shjs.exec(cmd).code;

  if (ret !== 0) {
    return f(new Error('Security issue'));
  }

  f();
};


text:
using namespace swift;

TEST(ImmutableSortedSet, OneElementSets) {
  llvm::BumpPtrAllocator BPA;
  ImmutablePointerSetFactory<unsigned> F(BPA);

  unsigned *ptr1 = (unsigned *)3;
  auto *OneEltSet1 = F.get(ptr1);
  EXPECT_EQ(OneEltSet1, F.get(ptr1));
  EXPECT_EQ(OneEltSet1, F.merge(OneEltSet1, OneEltSet1));

  unsigned *ptr2 = (unsigned *)2;
  auto *OneEltSet2 = F.get(ptr2);
  EXPECT_EQ(OneEltSet2, F.get(ptr2));
  EXPECT_EQ(OneEltSet2, F.merge(OneEltSet2, OneEltSet2));
  EXPECT_NE(OneEltSet2, OneEltSet1);

  auto *Merge1 = F.merge(OneEltSet1, OneEltSet2);
  auto *Merge2 = F.merge(OneEltSet2, OneEltSet1);
  EXPECT_NE(OneEltSet1, Merge1);
  EXPECT_NE(OneEltSet2, Merge1);
  EXPECT_EQ(Merge1, Merge2);
  EXPECT_EQ(Merge1, F.merge(Merge1, Merge1));
  EXPECT_EQ(Merge2, F.merge(Merge2, Merge2));
  EXPECT_EQ(Merge1, F.merge(Merge1, OneEltSet1));
  EXPECT_EQ(Merge1, F.merge(Merge1, OneEltSet2));

  EXPECT_EQ(Merge1->size(), 2U);
  EXPECT_FALSE(Merge1->empty());
  EXPECT_EQ(*Merge1->begin(), (unsigned *)2);
  EXPECT_EQ(*std::next(Merge1->begin()), (unsigned *)3);

  EXPECT_EQ(F.getEmptySet(), F.getEmptySet());
  EXPECT_EQ(OneEltSet1, F.merge(F.getEmptySet(), OneEltSet1));
  EXPECT_EQ(OneEltSet1, F.merge(OneEltSet1, F.getEmptySet()));
}

TEST(ImmutablePointerSet, MultipleElementSets) {
  llvm::BumpPtrAllocator BPA;
  ImmutablePointerSetFactory<unsigned> F(BPA);

  unsigned *Ptr1 = (unsigned *)3;
  unsigned *Ptr2 = (unsigned *)4;
  unsigned *Ptr3 = (unsigned *)3;
  unsigned *Ptr4 = (unsigned *)5;
  unsigned *Ptr5 = (unsigned *)6;
  ArrayRef<unsigned *> Data1 = {Ptr1, Ptr2};

  auto *TwoEltSet = F.get(Data1);
  EXPECT_FALSE(TwoEltSet->empty());
  EXPECT_EQ(TwoEltSet->size(), 2u);
  EXPECT_TRUE(TwoEltSet->count(Ptr1));
  EXPECT_TRUE(TwoEltSet->count(Ptr2));
  EXPECT_TRUE(TwoEltSet->count(Ptr3));
  EXPECT_FALSE(TwoEltSet->count(Ptr4));
  EXPECT_FALSE(TwoEltSet->count(Ptr5));

  auto *ThreeEltSet = F.merge(F.get(Ptr4), TwoEltSet);
  EXPECT_FALSE(ThreeEltSet->empty());
  EXPECT_EQ(ThreeEltSet->size(), 3u);
  EXPECT_NE(*ThreeEltSet, *TwoEltSet);
  EXPECT_TRUE(ThreeEltSet->count(Ptr1));
  EXPECT_TRUE(ThreeEltSet->count(Ptr2));
  EXPECT_TRUE(ThreeEltSet->count(Ptr3));
  EXPECT_TRUE(ThreeEltSet->count(Ptr4));
  EXPECT_FALSE(ThreeEltSet->count(Ptr5));
  EXPECT_EQ(ThreeEltSet, F.merge(TwoEltSet, ThreeEltSet));

  ArrayRef<unsigned *> Data2 = {Ptr3, Ptr4, Ptr5};
  auto *PartialOverlapSet = F.get(Data2);
  EXPECT_FALSE(PartialOverlapSet->empty());
  EXPECT_EQ(PartialOverlapSet->size(), 3u);
  EXPECT_TRUE(PartialOverlapSet->count(Ptr1));
  EXPECT_FALSE(PartialOverlapSet->count(Ptr2));
  EXPECT_TRUE(PartialOverlapSet->count(Ptr3));
  EXPECT_TRUE(PartialOverlapSet->count(Ptr4));
  EXPECT_TRUE(PartialOverlapSet->count(Ptr5));
  EXPECT_NE(*PartialOverlapSet, *ThreeEltSet);
  EXPECT_NE(*PartialOverlapSet, *TwoEltSet);

  auto *MixOfThreeAndPartialOverlap = ThreeEltSet->merge(PartialOverlapSet);
  EXPECT_FALSE(MixOfThreeAndPartialOverlap->empty());
  EXPECT_EQ(MixOfThreeAndPartialOverlap->size(), 4u);
  EXPECT_TRUE(MixOfThreeAndPartialOverlap->count(Ptr1));
  EXPECT_TRUE(MixOfThreeAndPartialOverlap->count(Ptr2));
  EXPECT_TRUE(MixOfThreeAndPartialOverlap->count(Ptr3));
  EXPECT_TRUE(MixOfThreeAndPartialOverlap->count(Ptr4));
  EXPECT_TRUE(MixOfThreeAndPartialOverlap->count(Ptr5));
  EXPECT_NE(*MixOfThreeAndPartialOverlap, *PartialOverlapSet);
  EXPECT_NE(*MixOfThreeAndPartialOverlap, *ThreeEltSet);
  EXPECT_NE(*MixOfThreeAndPartialOverlap, *TwoEltSet);
}

TEST(ImmutablePointerSet, EmptyIntersectionTests) {
  llvm::BumpPtrAllocator BPA;
  ImmutablePointerSetFactory<unsigned> F(BPA);

  unsigned *Ptr1 = (unsigned *)3;
  unsigned *Ptr2 = (unsigned *)4;
  unsigned *Ptr3 = (unsigned *)3;
  unsigned *Ptr4 = (unsigned *)5;
  unsigned *Ptr5 = (unsigned *)6;

  ArrayRef<unsigned *> Data1 = {Ptr1, Ptr2};
  ArrayRef<unsigned *> Data2 = {Ptr3, Ptr2};
  ArrayRef<unsigned *> Data3 = {Ptr4, Ptr5};
  ArrayRef<unsigned *> Data4 = {Ptr2, Ptr4};

  EXPECT_FALSE(F.get(Data1)->hasEmptyIntersection(F.get(Data2)));
  EXPECT_TRUE(F.get(Data1)->hasEmptyIntersection(F.get(Data3)));
  EXPECT_FALSE(F.get(Data1)->hasEmptyIntersection(F.get(Data4)));
}


text:
package org.kie.camel.container.integration.tests.remote;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.assertj.core.api.Assertions;
import org.drools.compiler.kie.builder.impl.InternalKieModule;
import org.drools.core.util.FileManager;
import org.drools.modelcompiler.ExecutableModelProject;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.Message;
import org.kie.api.builder.model.KieModuleModel;
import org.kie.camel.container.api.ExecutionServerCommand;
import org.kie.camel.container.integration.tests.AbstractKieCamelIntegrationTest;
import org.kie.scanner.KieMavenRepository;
import org.kie.server.api.marshalling.xstream.XStreamMarshaller;
import org.kie.server.api.model.KieContainerResource;
import org.kie.server.api.model.ReleaseId;
import org.kie.server.api.model.instance.ProcessInstance;
import org.kie.server.api.model.instance.VariableInstance;

import static org.kie.scanner.KieMavenRepository.getKieMavenRepository;

public class AbstractRemoteIntegrationTest extends AbstractKieCamelIntegrationTest {

    protected static final String KJAR_RESOURCES_PATH = "/org/kie/camel/container/integration/tests/kjar/";
    protected static final String KJAR_TEST_PACKAGE_PATH = "/src/main/resources/org/test/";
    protected static final String PATH_POM = KJAR_RESOURCES_PATH + "pom.xml";
    protected static final String PROCESS_FILE_NAME = "process1.bpmn2";
    protected static final String PROCESS_WITH_SIGNAL_FILE_NAME = "processWithSignal.bpmn2";
    protected static final String PROCESS_WITH_HUMAN_TASK_FILE_NAME = "processWithHumanTask.bpmn2";
    protected static final String RULES_FILE_NAME = "rules.drl";
    protected static final String CLOUD_BALANCE_SOLVER_CONFIG = "cloudbalance-solver.xml";
    protected static final String CLOUD_BALANCE_SCORE_RULES = "cloudBalancingScoreRules.drl";
    protected static final String DMN_FUNCTION_DEFINITION = "FunctionDefinition.dmn";
    protected static final ReleaseId RELEASE_ID =
            new ReleaseId("org.drools", "camel-container-tests-kjar", "1.0.0");
    protected static final String CONTAINER_ID = "test-container";
    protected static final String PROCESS_ID = "process1";
    protected static final String PROCESS_WITH_SIGNAL_ID = "processWithSignal";
    protected static final String PROCESS_WITH_HUMAN_TASK = "processWithHumanTask";
    protected static final String SIGNAL_NAME = "signal1";
    protected static final String PROCESS_VARIABLE_NAME = "var1";
    protected static final String INITIATOR = "yoda";

    protected static final String SIMPLE_QUERY_NAME = "process-instances-query";
    protected static final String SIMPLE_QUERY_EXPRESSION = "select * from ProcessInstanceLog";
    protected static final String SIMPLE_QUERY_TARGET = "PROCESS";
    protected static final String SIMPLE_QUERY_DATASOURCE = "java:jboss/datasources/ExampleDS";

    protected static final String DEFAULT_USER = "yoda";

    @BeforeClass
    public static void createKieJar() throws IOException {
        KieServices ks = KieServices.get();
        KieFileSystem kfs = createKieFileSystemWithKProject(ks);
        kfs.writePomXML(loadResource(PATH_POM));
        kfs = addClasspathResourceToKjar(KJAR_RESOURCES_PATH + PROCESS_FILE_NAME,
                                         KJAR_TEST_PACKAGE_PATH + PROCESS_FILE_NAME, kfs);
        kfs = addClasspathResourceToKjar(KJAR_RESOURCES_PATH + PROCESS_WITH_SIGNAL_FILE_NAME,
                                         KJAR_TEST_PACKAGE_PATH + PROCESS_WITH_SIGNAL_FILE_NAME, kfs);
        kfs = addClasspathResourceToKjar(KJAR_RESOURCES_PATH + RULES_FILE_NAME,
                                         KJAR_TEST_PACKAGE_PATH + RULES_FILE_NAME, kfs);
        kfs = addClasspathResourceToKjar(KJAR_RESOURCES_PATH + PROCESS_WITH_HUMAN_TASK_FILE_NAME,
                                         KJAR_TEST_PACKAGE_PATH + PROCESS_WITH_HUMAN_TASK_FILE_NAME, kfs);
        kfs = addClasspathResourceToKjar(KJAR_RESOURCES_PATH + CLOUD_BALANCE_SOLVER_CONFIG,
                                         KJAR_TEST_PACKAGE_PATH + CLOUD_BALANCE_SOLVER_CONFIG, kfs);
        kfs = addClasspathResourceToKjar(KJAR_RESOURCES_PATH + CLOUD_BALANCE_SCORE_RULES,
                                         KJAR_TEST_PACKAGE_PATH + CLOUD_BALANCE_SCORE_RULES, kfs);
        kfs = addClasspathResourceToKjar(KJAR_RESOURCES_PATH + DMN_FUNCTION_DEFINITION,
                                         KJAR_TEST_PACKAGE_PATH + DMN_FUNCTION_DEFINITION, kfs);

        KieBuilder kieBuilder = ks.newKieBuilder(kfs);
        List<Message> messageList = kieBuilder.buildAll(ExecutableModelProject.class).getResults().getMessages();

        Assertions.assertThat(messageList).isEmpty();
        InternalKieModule kJar1 = (InternalKieModule) kieBuilder.getKieModule();

        KieMavenRepository repository = getKieMavenRepository();
        repository.installArtifact(RELEASE_ID, kJar1, createKPom());
    }

    @Before
    public void deploy() throws IOException {
        final KieContainerResource kieContainerResource = new KieContainerResource(RELEASE_ID);
        kieContainerResource.setContainerId(CONTAINER_ID);
        final ExecutionServerCommand executionServerCommand = new ExecutionServerCommand();
        executionServerCommand.setClient("kieServices");
        executionServerCommand.setOperation("createContainer");
        executionServerCommand.addParameter("id", CONTAINER_ID);
        executionServerCommand.setBodyParam("resource");
        executionServerCommand.setBody(kieContainerResource);
        runOnExecutionServer(executionServerCommand);
    }

    @After
    public void teardown() {
        final ExecutionServerCommand executionServerCommand = new ExecutionServerCommand();
        executionServerCommand.setClient("kieServices");
        executionServerCommand.setOperation("disposeContainer");
        executionServerCommand.addParameter("id", CONTAINER_ID);
        runOnExecutionServer(executionServerCommand);
    }

    protected Object runOnExecutionServer(ExecutionServerCommand executionServerCommand) {
        final XStreamMarshaller marshaller = new XStreamMarshaller(new HashSet<>(),
                                                                   AbstractRemoteIntegrationTest.class.getClassLoader());
        final String commandXML = marshaller.marshall(executionServerCommand);
        final String resultString = kieCamelTestService.runOnExecServer(commandXML);
        final Object result = marshaller.unmarshall(resultString, Object.class);

        return result;
    }

    protected Long startProcess(final String containerId, final String processId) {
        final Map<String, Object> parameters = new HashMap<>();
        parameters.put("containerId", containerId);
        parameters.put("processId", processId);
        final ExecutionServerCommand executionServerCommand = new ExecutionServerCommand();
        executionServerCommand.setClient("process");
        executionServerCommand.setOperation("startProcess");
        executionServerCommand.setParameters(parameters);

        final Object response = runOnExecutionServer(executionServerCommand);
        Assertions.assertThat(response).isNotNull();
        Assertions.assertThat(response).isInstanceOf(Long.class);

        final Long processInstanceId = (Long) response;
        Assertions.assertThat(processInstanceId).isGreaterThan(0);

        return processInstanceId;
    }

    protected Long startProcess(final String containerId, final String processId,
                                final Map<String, Object> processVariables) {
        final Map<String, Object> parameters = new HashMap<>();
        parameters.put("containerId", containerId);
        parameters.put("processId", processId);
        parameters.put("variables", processVariables);
        final ExecutionServerCommand executionServerCommand = new ExecutionServerCommand();
        executionServerCommand.setClient("process");
        executionServerCommand.setOperation("startProcess");
        executionServerCommand.setParameters(parameters);

        final Object response = runOnExecutionServer(executionServerCommand);
        Assertions.assertThat(response).isNotNull();
        Assertions.assertThat(response).isInstanceOf(Long.class);

        final Long processInstanceId = (Long) response;
        Assertions.assertThat(processInstanceId).isGreaterThan(0);

        return processInstanceId;
    }

    protected HashMap<String, String> getProcessVariables(String containerId, long processInstanceId) {
        final Map<String, Object> parameters = new HashMap<>();
        parameters.put("containerId", containerId);
        parameters.put("processInstanceId", processInstanceId);
        final ExecutionServerCommand executionServerCommand = new ExecutionServerCommand();
        executionServerCommand.setClient("process");
        executionServerCommand.setOperation("findVariablesCurrentState");
        executionServerCommand.setParameters(parameters);

        final Object response = runOnExecutionServer(executionServerCommand);
        Assertions.assertThat(response).isNotNull();
        Assertions.assertThat(response).isInstanceOf(List.class);

        final List<VariableInstance> variableInstances = (List<VariableInstance>) response;
        final HashMap<String, String> variablesMap = new HashMap<>();
        for (VariableInstance variable : variableInstances) {
            variablesMap.put(variable.getVariableName(), variable.getValue());
        }

        return variablesMap;
    }

    protected List<ProcessInstance> findActiveProcesses() {
        final List<Integer> statuses = Arrays.asList(org.kie.api.runtime.process.ProcessInstance.STATE_ACTIVE);
        final Map<String, Object> parameters = new HashMap<>();
        parameters.put("status", statuses);
        parameters.put("page", "0");
        parameters.put("pageSize", "100");
        final ExecutionServerCommand executionServerCommand = new ExecutionServerCommand();
        executionServerCommand.setClient("query");
        executionServerCommand.setOperation("findProcessInstancesByStatus");
        executionServerCommand.setParameters(parameters);

        final Object response = runOnExecutionServer(executionServerCommand);
        final List<ProcessInstance> processInstances = (List<ProcessInstance>) response;

        return processInstances;
    }

    protected void abortProcess(final String containerId, final String processInstanceId) {
        final Map<String, Object> parameters = new HashMap<>();
        parameters.put("containerId", containerId);
        parameters.put("processInstanceId", processInstanceId);
        final ExecutionServerCommand executionServerCommand = new ExecutionServerCommand();
        executionServerCommand.setClient("process");
        executionServerCommand.setOperation("abortProcessInstance");
        executionServerCommand.setParameters(parameters);
        runOnExecutionServer(executionServerCommand);
    }

    protected void sendSignalToProcessInstance(final String containerId, final Long processInstanceId,
                                             final String signalName) {
        final Map<String, Object> parameters = new HashMap<>();
        parameters.put("containerId", containerId);
        parameters.put("processInstanceId", processInstanceId);
        parameters.put("signalName", signalName);
        parameters.put("event", null);
        final ExecutionServerCommand executionServerCommand = new ExecutionServerCommand();
        executionServerCommand.setClient("process");
        executionServerCommand.setOperation("signalProcessInstance");
        executionServerCommand.setParameters(parameters);

        runOnExecutionServer(executionServerCommand);
    }

    @After
    public void abortAllProcesses() {
        final List<ProcessInstance> activeProcesses = findActiveProcesses();
        for (ProcessInstance processInstance : activeProcesses) {
            abortProcess(CONTAINER_ID, String.valueOf(processInstance.getId()));
        }
    }

    private static KieFileSystem createKieFileSystemWithKProject(KieServices ks) {
        KieModuleModel kproj = ks.newKieModuleModel();
        KieFileSystem kfs = ks.newKieFileSystem();
        kfs.writeKModuleXML(kproj.toXML());

        return kfs;
    }

    private static File createKPom() throws IOException {
        FileManager fileManager = new FileManager();
        fileManager.setUp();
        File pomFile = fileManager.newFile("pom.xml");
        fileManager.write(pomFile, loadResource(PATH_POM));
        return pomFile;
    }

    private static KieFileSystem addClasspathResourceToKjar(String classpathPath, String kjarPath, KieFileSystem kieFileSystem) {
        final String resourceContent = loadResource(classpathPath);
        return kieFileSystem.write(kjarPath, resourceContent);
    }

    private static String loadResource(String path) {
        try (InputStream inputStream = AbstractRemoteIntegrationTest.class.getResourceAsStream(path)) {
            return IOUtils.toString(inputStream);
        } catch (IOException e) {
            throw new RuntimeException("Error loading resource from classpath", e);
        }
    }
}


text:
/**
 * @file memchr.c
 */
/* Embedded Xinu, Copyright (C) 2009, 2013.  All rights reserved. */

#include <string.h>
#include <stddef.h>

/**
 * @ingroup libxc
 *
 * Returns a pointer to the first location in a region of memory at which a
 * particular byte appears.
 *
 * @param s
 *      A pointer to the memory region to search.
 * @param c
 *      The byte to locate.
 * @param n
 *      The maximum number of bytes to search.
 *
 * @return
 *      A pointer to the first occurrence of @p c in the memory region, or @c
 *      NULL if @p c was not found in the memory region.
 */
void *memchr(const void *s, int c, size_t n)
{
    const unsigned char *p = s;
    unsigned char byte = c;
    size_t i;

    for (i = 0; i < n; i++)
    {
        if (p[i] == byte)
        {
            return (void*)&p[i]; /* Cast away const */
        }
    }
    return NULL;
}