text:
package org.apache.wss4j.dom.message;

import org.apache.wss4j.dom.WSConstants;
import org.apache.wss4j.common.ext.WSSecurityException;
import org.apache.wss4j.common.util.UsernameTokenUtil;
import org.apache.wss4j.common.util.WSCurrentTimeSource;
import org.apache.wss4j.common.util.WSTimeSource;
import org.apache.wss4j.dom.message.token.UsernameToken;
import org.apache.wss4j.dom.util.WSSecurityUtil;
import org.apache.xml.security.exceptions.Base64DecodingException;
import org.apache.xml.security.utils.Base64;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * Builds a WS UsernameToken.
 *
 * Refer to the WS specification, UsernameToken profile
 */
public class WSSecUsernameToken extends WSSecBase {
    private static final org.slf4j.Logger LOG =
        org.slf4j.LoggerFactory.getLogger(WSSecUsernameToken.class);

    private String passwordType = WSConstants.PASSWORD_DIGEST;
    private UsernameToken ut;
    private boolean nonce;
    private boolean created;
    private boolean useDerivedKey;
    private boolean useMac;
    private byte[] saltValue;
    private int iteration = UsernameToken.DEFAULT_ITERATION;
    private boolean passwordsAreEncoded;
    private boolean precisionInMilliSeconds = true;
    private WSTimeSource wsTimeSource = new WSCurrentTimeSource();

    public WSSecUsernameToken() {
        super();
    }

    /**
     * Defines how to construct the password element of the
     * UsernameToken.
     *
     * @param pwType
     *            contains the password type. Only allowed values are
     *            {@link WSConstants#PASSWORD_DIGEST} and
     *            {@link WSConstants#PASSWORD_TEXT}.
     *            or null when no password is needed.
     */
    public void setPasswordType(String pwType) {
        this.passwordType = pwType;
    }

    /**
     * Add a Nonce element to the UsernameToken.
     */
    public void addNonce() {
        nonce = true;
    }

    /**
     * Add a Created element to the UsernameToken.
     */
    public void addCreated() {
        created = true;
    }

    /**
     * Add a derived key to the UsernameToken
     * @param useMac whether the derived key is to be used for a MAC or not
     * @param saltValue The salt value to use
     * @param iteration The number of iterations to use in deriving a key
     */
    public void addDerivedKey(boolean useMac, byte[] saltValue, int iteration) {
        passwordType = null;
        useDerivedKey = true;
        this.useMac = useMac;
        this.saltValue = saltValue;
        if (iteration > 0) {
            this.iteration = iteration;
        }
    }

    /**
     * Get the derived key.
     *
     * After the prepare() method was called use this method
     * to compute a derived key. The generation of this secret key is according
     * to the UsernameTokenProfile 1.1 specification (section 4 - Key Derivation).
     *
     * @return Return the derived key of this token or null if prepare()
     * was not called before.
     */
    public byte[] getDerivedKey() throws WSSecurityException {
        if (ut == null || !useDerivedKey) {
            return null;
        }
        if (passwordsAreEncoded) {
            try {
                return UsernameTokenUtil.generateDerivedKey(Base64.decode(password), saltValue, iteration);
            } catch (Base64DecodingException e) {
                throw new WSSecurityException(
                    WSSecurityException.ErrorCode.FAILURE, e, "decoding.general"
                );
            }
        } else {
            return UsernameTokenUtil.generateDerivedKey(password, saltValue, iteration);
        }
    }

    /**
     * @param passwordsAreEncoded
     * whether passwords are encoded
     */
    public void setPasswordsAreEncoded(boolean passwordsAreEncoded) {
        this.passwordsAreEncoded = passwordsAreEncoded;
    }

    /**
     * @return whether passwords are encoded
     */
    public boolean getPasswordsAreEncoded() {
        return passwordsAreEncoded;
    }

    /**
     * Get the id generated during prepare().
     *
     * Returns the the value of wsu:Id attribute of this UsernameToken.
     *
     * @return Return the wsu:Id of this token or null if prepare()
     * was not called before.
     */
    public String getId() {
        if (ut == null) {
            return null;
        }
        return ut.getID();
    }

    /**
     * Creates a Username token.
     *
     * The method prepares and initializes a WSSec UsernameToken structure after
     * the relevant information was set. A Before calling
     * prepare() all parameters such as user, password,
     * passwordType etc. must be set. A complete UsernameToken is
     * constructed.
     *
     * @param doc The SOAP envelope as W3C document
     */
    public void prepare(Document doc) {
        ut = new UsernameToken(precisionInMilliSeconds, doc, wsTimeSource, passwordType);
        ut.setPasswordsAreEncoded(passwordsAreEncoded);
        ut.setName(user);
        if (useDerivedKey) {
            saltValue = ut.addSalt(doc, saltValue, useMac);
            ut.addIteration(doc, iteration);
        } else {
            ut.setPassword(password);
        }
        if (nonce) {
            ut.addNonce(doc);
        }
        if (created) {
            ut.addCreated(precisionInMilliSeconds, wsTimeSource, doc);
        }
        ut.setID(getIdAllocator().createId("UsernameToken-", ut));
    }

    /**
     * Prepends the UsernameToken element to the elements already in the
     * Security header.
     *
     * The method can be called any time after prepare().
     * This allows to insert the UsernameToken element at any position in the
     * Security header.
     *
     * @param secHeader The security header that holds the Signature element.
     */
    public void prependToHeader(WSSecHeader secHeader) {
        WSSecurityUtil.prependChildElement(secHeader.getSecurityHeader(), ut.getElement());
    }

    /**
     * Appends the UsernameToken element to the elements already in the
     * Security header.
     *
     * The method can be called any time after prepare().
     * This allows to insert the UsernameToken element at any position in the
     * Security header.
     *
     * @param secHeader The security header that holds the Signature element.
     */
    public void appendToHeader(WSSecHeader secHeader) {
        Element secHeaderElement = secHeader.getSecurityHeader();
        secHeaderElement.appendChild(ut.getElement());
    }

    /**
     * Adds a new UsernameToken to a soap envelope.
     *
     * Before calling build() all parameters such as user,
     * password, passwordType etc. must be set. A complete
     * UsernameToken is constructed and added to the
     * wsse:Security header.
     *
     * @param doc The SOAP envelope as W3C document
     * @param secHeader The security header inside the SOAP envelope
     * @return Document with UsernameToken added
     */
    public Document build(Document doc, WSSecHeader secHeader) {
        LOG.debug("Begin add username token...");

        prepare(doc);
        prependToHeader(secHeader);

        return doc;
    }

    /**
     * Returns the UsernameToken element.
     *
     * The method can be called any time after prepare().
     * This allows to insert the UsernameToken element at any position in the
     * Security header.
     *
     * @return the Username Token element
     */
    public Element getUsernameTokenElement() {
       return ut.getElement();
    }

    public boolean isPrecisionInMilliSeconds() {
        return precisionInMilliSeconds;
    }

    public void setPrecisionInMilliSeconds(boolean precisionInMilliSeconds) {
        this.precisionInMilliSeconds = precisionInMilliSeconds;
    }

    public WSTimeSource getWsTimeSource() {
        return wsTimeSource;
    }

    public void setWsTimeSource(WSTimeSource wsTimeSource) {
        this.wsTimeSource = wsTimeSource;
    }
}


text:
using Epi.Cloud.Common.Criteria;

namespace Epi.Cloud.Common.Message
{
    /// <summary>
    /// Represents a SurveyInfo request message from client.
    /// </summary>
    public class FormsInfoRequest
    {
        public FormsInfoRequest()
        {
            this.Criteria = new FormInfoCriteria();

        }

        /// <summary>
        /// Selection criteria and sort order
        /// </summary>
        public FormInfoCriteria Criteria;
    }
}

redpajama_set_name: RedPajamaGithub


text:
(function() { 'use strict';

/************************************************************************************
* @ngdoc controller
* @name PageController
* @module metricapp
* @requires $scope
* @requires $location
*
* @description
* Manages the navbar for all users.
* Realizes the control layer for {navbar.view}.
************************************************************************************/

angular.module('metricapp')

.controller("QuestionUpdateCtrl", QuestionUpdateCtrl);

QuestionUpdateCtrl.$inject = ['$window', '$location', 'QuestionStorageFactory', 'QuestionsCrudFactory'];

function QuestionUpdateCtrl($window, $location, QuestionStorageFactory, QuestionsCrudFactory){

    var ctrl = this;

    ctrl.question = angular.copy(QuestionStorageFactory.getQuestion());
    ctrl.isCommitted = false;

    ctrl.reset = function(){
        ctrl.question = angular.copy(QuestionStorageFactory.getQuestion());
    };

    ctrl.updateQuestion = function(){

        if(ctrl.question.metadata.state == QuestionsCrudFactory.STATES.CREATED){
            ctrl.question.metadata.state = QuestionsCrudFactory.STATES.ONUPDATE;
        }
        else if(ctrl.question.metadata.state == QuestionsCrudFactory.STATES.REJECTED){
            ctrl.question.meteadata.state = QuestionsCrudFactory.STATES.ONUPDATE;
        }

        $window.alert(ctrl.question.metadata.state);
        QuestionsCrudFactory.update(ctrl.question).then(
            function(data, status){
                QuestionStorageFactory.setQuestion(data.data.questionList[0]);
                ctrl.question = angular.copy(QuestionStorageFactory.getQuestion());
                $window.alert("update committed");
                ctrl.isCommitted = true;
            },

            function(data, status){
                $window.alert("Error: status " + status);
            }
        );
    };

    // ctrl.finalizeQuestion = function(){

    //     if(ctrl.question.metadata.state == QuestionsCrudFactory.STATES.CREATED || !ctrl.isCommitted){
    //         $window.alert("You have to commit the update first!");
    //         return;
    //     }
    //     else if(ctrl.question.metadata.state == QuestionsCrudFactory.STATES.ONUPDATE){
    //         ctrl.question.metadata.state = QuestionsCrudFactory.STATES.PENDING;
    //     }

    //     QuestionsCrudFactory.update(ctrl.question).then(
    //         function(data, status){
    //             $window.alert("Question Finalized");
    //             $location.path('/dashboardQuestioner');
    //         },

    //         function(data, status){
    //             $window.alert("Error: status " + status);
    //         }
    //     );
    // };

    ctrl.getTags = function(){
        return ctrl.question.metadata.tags.join();
    };

    ctrl.addTagToQuestion = function() {
        ctrl.question.metadata.tags.push(ctrl.newTag);
    };

    ctrl.removeTagFromQuestion = function(index){
        ctrl.question.metadata.tags.splice(index, 1);
    };

    ctrl.getStates = function(){
        return QuestionsCrudFactory.STATES;
    };
}

})();


text:
package org.jabref.logic.util;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

public class UnknownFileType implements FileType {

    private final List<String> extensions;

    public UnknownFileType(String... extensions) {
        for (int i = 0; i < extensions.length; i++) {
            if (extensions[i].contains(".")) {
                extensions[i] = extensions[i].substring(extensions[i].indexOf('.') + 1);
            }
            extensions[i] = extensions[i].toLowerCase(Locale.ROOT);
        }
        this.extensions = Arrays.asList(extensions);
    }

    @Override
    public List<String> getExtensions() {
        return extensions;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof FileType)) {
            return false;
        }
        FileType other = (FileType) o;
        Collections.sort(extensions);
        Collections.sort(other.getExtensions());
        return extensions.equals(other.getExtensions());
    }

    @Override
    public int hashCode() {
        return Objects.hash(extensions);
    }

    @Override
    public String getName() {
        return "Unknown File Type" + extensions.toString();
    }
}


text:
<?php

namespace Magento\CatalogInventory\Model;

use Magento\CatalogInventory\Model\Spi\StockRegistryProviderInterface;
use Magento\CatalogInventory\Api\StockRepositoryInterface;
use Magento\CatalogInventory\Api\StockItemRepositoryInterface;
use Magento\CatalogInventory\Api\StockStatusRepositoryInterface;
use Magento\CatalogInventory\Api\Data\StockInterfaceFactory;
use Magento\CatalogInventory\Api\Data\StockItemInterfaceFactory;
use Magento\CatalogInventory\Api\Data\StockStatusInterfaceFactory;
use Magento\CatalogInventory\Api\StockCriteriaInterfaceFactory;
use Magento\CatalogInventory\Api\StockItemCriteriaInterfaceFactory;
use Magento\CatalogInventory\Api\StockStatusCriteriaInterfaceFactory;
use Magento\Store\Model\StoreManagerInterface;

/**
 * Class StockRegistryProvider
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class StockRegistryProvider implements StockRegistryProviderInterface
{
    /**
     * @var StockRepositoryInterface
     */
    protected $stockRepository;

    /**
     * @var StockInterfaceFactory
     */
    protected $stockFactory;

    /**
     * @var StockItemRepositoryInterface
     */
    protected $stockItemRepository;

    /**
     * @var StockItemInterfaceFactory
     */
    protected $stockItemFactory;

    /**
     * @var StockStatusRepositoryInterface
     */
    protected $stockStatusRepository;

    /**
     * @var StockStatusInterfaceFactory
     */
    protected $stockStatusFactory;

    /**
     * @var StockCriteriaInterfaceFactory
     */
    protected $stockCriteriaFactory;

    /**
     * @var StockItemCriteriaInterfaceFactory
     */
    protected $stockItemCriteriaFactory;

    /**
     * @var StockStatusCriteriaInterfaceFactory
     */
    protected $stockStatusCriteriaFactory;

    /**
     * @var StockRegistryStorage
     */
    protected $stockRegistryStorage;

    /**
     * @param StockRepositoryInterface $stockRepository
     * @param StockInterfaceFactory $stockFactory
     * @param StockItemRepositoryInterface $stockItemRepository
     * @param StockItemInterfaceFactory $stockItemFactory
     * @param StockStatusRepositoryInterface $stockStatusRepository
     * @param StockStatusInterfaceFactory $stockStatusFactory
     * @param StockCriteriaInterfaceFactory $stockCriteriaFactory
     * @param StockItemCriteriaInterfaceFactory $stockItemCriteriaFactory
     * @param StockStatusCriteriaInterfaceFactory $stockStatusCriteriaFactory
     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
     */
    public function __construct(
        StockRepositoryInterface $stockRepository,
        StockInterfaceFactory $stockFactory,
        StockItemRepositoryInterface $stockItemRepository,
        StockItemInterfaceFactory $stockItemFactory,
        StockStatusRepositoryInterface $stockStatusRepository,
        StockStatusInterfaceFactory $stockStatusFactory,
        StockCriteriaInterfaceFactory $stockCriteriaFactory,
        StockItemCriteriaInterfaceFactory $stockItemCriteriaFactory,
        StockStatusCriteriaInterfaceFactory $stockStatusCriteriaFactory
    ) {
        $this->stockRepository = $stockRepository;
        $this->stockFactory = $stockFactory;
        $this->stockItemRepository = $stockItemRepository;
        $this->stockItemFactory = $stockItemFactory;
        $this->stockStatusRepository = $stockStatusRepository;
        $this->stockStatusFactory = $stockStatusFactory;
        $this->stockCriteriaFactory = $stockCriteriaFactory;
        $this->stockItemCriteriaFactory = $stockItemCriteriaFactory;
        $this->stockStatusCriteriaFactory = $stockStatusCriteriaFactory;
    }

    /**
     * @param int|null $scopeId
     * @return \Magento\CatalogInventory\Api\Data\StockInterface
     */
    public function getStock($scopeId)
    {
        $stock = $this->getStockRegistryStorage()->getStock($scopeId);
        if (null === $stock) {
            $criteria = $this->stockCriteriaFactory->create();
            $criteria->setScopeFilter($scopeId);
            $collection = $this->stockRepository->getList($criteria);
            $stock = current($collection->getItems());
            if ($stock && $stock->getStockId()) {
                $this->getStockRegistryStorage()->setStock($scopeId, $stock);
            } else {
                $stock = $this->stockFactory->create();
            }
        }
        return $stock;
    }

    /**
     * @param int $productId
     * @param int $scopeId
     * @return \Magento\CatalogInventory\Api\Data\StockItemInterface
     */
    public function getStockItem($productId, $scopeId)
    {
        $stockItem = $this->getStockRegistryStorage()->getStockItem($productId, $scopeId);
        if (null === $stockItem) {
            $criteria = $this->stockItemCriteriaFactory->create();
            $criteria->setProductsFilter($productId);
            $collection = $this->stockItemRepository->getList($criteria);
            $stockItem = current($collection->getItems());
            if ($stockItem && $stockItem->getItemId()) {
                $this->getStockRegistryStorage()->setStockItem($productId, $scopeId, $stockItem);
            } else {
                $stockItem = $this->stockItemFactory->create();
            }
        }
        return $stockItem;
    }

    /**
     * @param int $productId
     * @param int $scopeId
     * @return \Magento\CatalogInventory\Api\Data\StockStatusInterface
     */
    public function getStockStatus($productId, $scopeId)
    {
        $stockStatus = $this->getStockRegistryStorage()->getStockStatus($productId, $scopeId);
        if (null === $stockStatus) {
            $criteria = $this->stockStatusCriteriaFactory->create();
            $criteria->setProductsFilter($productId);
            $criteria->setScopeFilter($scopeId);
            $collection = $this->stockStatusRepository->getList($criteria);
            $stockStatus = current($collection->getItems());
            if ($stockStatus && $stockStatus->getProductId()) {
                $this->getStockRegistryStorage()->setStockStatus($productId, $scopeId, $stockStatus);
            } else {
                $stockStatus = $this->stockStatusFactory->create();
            }
        }
        return $stockStatus;
    }

    /**
     * @return StockRegistryStorage
     */
    private function getStockRegistryStorage()
    {
        if (null === $this->stockRegistryStorage) {
            $this->stockRegistryStorage = \Magento\Framework\App\ObjectManager::getInstance()
                ->get('Magento\CatalogInventory\Model\StockRegistryStorage');
        }
        return $this->stockRegistryStorage;
    }
}


text:
<!--
The MIT License (MIT)

Copyright (c) 2014, 2015 IBM Corporation
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.
-->

# Notice for use of battery powered beacons
In general, bluetooth beacons are powered by battery or USB.
The battery powered beacon is more popular as it is flexibility to be deployed.
However in long term (more than two month) beacon deployment, you need to keep maintaining batteries.
Please refer to the following information to minimize maintenance cost of battery.

## Battery capacities
Battery type and capacity for typical 3V beacons are as follows. Larger capacity battery has longer battery life.

| Type of battery | Capacity |
|---------------------|---------|
| 1 x CR2477 (Lithium)| 1000mAh |
| 2 x AA (Alkaline)   | 2000mAh - 2700mAh (Manufacturer dependent) |
| 2 x AA (Lithium)    | 3000mAh |

2 x AA (Lithium) powered beacon have 3 times battery life of CR2477 powered beacon.

In cold environment, Lithium battery is better than alkaline battery.

## Beacon settings and battery life
Battery life of beacon will strongly depend on advertising interval and transmission power settings.

Power consumption rate of 100ms advertising interval is 2 times of 200ms advertising interval.
Increasing transmission power also consumes battery power.

Advertising interval value is critical for beacon performance and it also affect user experience.
Please contact beacon vendor for optimum settings.

## How to check battery level
* LED indicator
 * Some beacon has LED indicator for battery level.
   LED color changes on dead battery level.
   Please contact beacon vendor for details.
* Beacon management tools
 * Some beacon vendor support battery level checker with special application program.
   Please contact beacon vendor for details.
* Voltage meter
 * If none of above indicator is available, you need to remove battery from beacon then use voltage meter to check battery level.
* RSSI level
 * If it is very hard to remove battery, you can check RSSI level using general-purpose beacon check tools such as Beacon Ranging (https://itunes.apple.com/jp/app/beacon-ranging/id734155067).
   You can find beacons which are already dead (Typically less than 0.7V on AA battery).
   Please note it is too late to replace battery at this timing. Please replace battery before it dies.

## When should you replace battery?
Please replace battery when battery level becomes less then the following voltage even if beacon is still working.

| Type of Battery | Dead battery voltage |
|--------|------|
| CR2477 | 2.0V |
| AA	 | 1.0V |

Leaving alkaline battery in dead voltage may cause electrolyte leakage.


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Shared.Extensions;

namespace Microsoft.CodeAnalysis.PullMemberUp
{
    internal static class MemberAndDestinationValidator
    {
        public static bool IsDestinationValid(Solution solution, INamedTypeSymbol destination, CancellationToken cancellationToken)
        {
            // Make sure destination is class or interface since it could be ErrorTypeSymbol
            if (destination.TypeKind != TypeKind.Interface && destination.TypeKind != TypeKind.Class)
            {
                return false;
            }

            // Don't provide any refactoring option if the destination is not in source.
            // If the destination is generated code, also don't provide refactoring since we can't make sure if we won't break it.
            var isDestinationInSourceAndNotGeneratedCode =
                destination.Locations.Any(location => location.IsInSource && !solution.GetDocument(location.SourceTree).IsGeneratedCode(cancellationToken));
            return isDestinationInSourceAndNotGeneratedCode;
        }

        public static bool IsMemberValid(ISymbol member)
        {
            // Static, abstract and accessiblity are not checked here but in PullMembersUpOptionsBuilder.cs since there are
            // two refactoring options provided for pull members up,
            // 1. Quick Action (Only allow members that don't cause error)
            // 2. Dialog box (Allow modifers may cause error and will provide fixing)
            return member switch
            {
                IMethodSymbol methodSymbol => methodSymbol.MethodKind == MethodKind.Ordinary,
                IFieldSymbol fieldSymbol => !fieldSymbol.IsImplicitlyDeclared,
                _ => member.IsKind(SymbolKind.Property) || member.IsKind(SymbolKind.Event),
            };
        }
    }
}


text:
Please Sign In

                    <form role="form">
                        <fieldset>

                                <input class="form-control" placeholder="User" name="email" ng-model="user" type="text" autofocus>

                                <input class="form-control" placeholder="Password" name="password" ng-model="password" type="password" value="">

                                    <input name="remember" type="checkbox" value="Remember Me">Remember Me

                            Login
                        </fieldset>
                    </form>


text:
package org.axonframework.serialization.upcasting.event;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.IntNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import org.axonframework.eventhandling.EventData;
import org.axonframework.eventhandling.GenericDomainEventEntry;
import org.axonframework.eventhandling.GenericDomainEventMessage;
import org.axonframework.eventhandling.GlobalSequenceTrackingToken;
import org.axonframework.eventhandling.TrackedDomainEventData;
import org.axonframework.messaging.MetaData;
import org.axonframework.serialization.SerializedObject;
import org.axonframework.serialization.SerializedType;
import org.axonframework.serialization.Serializer;
import org.axonframework.serialization.SimpleSerializedType;
import org.axonframework.serialization.json.JacksonSerializer;
import org.axonframework.serialization.upcasting.Upcaster;
import org.axonframework.utils.SecondStubEvent;
import org.axonframework.utils.StubDomainEvent;
import org.axonframework.utils.TestDomainEventEntry;
import org.axonframework.utils.ThirdStubEvent;
import org.junit.jupiter.api.*;

import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

/**
 * Test class validating the {@link EventMultiUpcaster}.
 *
 * @author Steven van Beelen
 */
class EventMultiUpcasterTest {

    private String expectedNewString;
    private Integer expectedNewInteger;
    private List<Boolean> expectedNewBooleans;

    private Serializer serializer;
    private Upcaster<IntermediateEventRepresentation> upcaster;

    @BeforeEach
    void setUp() {
        expectedNewString = "newNameValue";
        expectedNewInteger = 42;
        expectedNewBooleans = new ArrayList<>();
        expectedNewBooleans.add(true);
        expectedNewBooleans.add(false);

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new ParameterNamesModule(JsonCreator.Mode.PROPERTIES));
        serializer = JacksonSerializer.builder().objectMapper(objectMapper).build();
        upcaster = new StubEventMultiUpcaster(expectedNewString, expectedNewInteger, expectedNewBooleans);
    }

    @Test
    void upcasterIgnoresWrongEventType() {
        GenericDomainEventMessage<String> testEventMessage =
                new GenericDomainEventMessage<>("test", "aggregateId", 0, "someString");
        EventData<?> testEventData = new TestDomainEventEntry(testEventMessage, serializer);
        IntermediateEventRepresentation testRepresentation =
                spy(new InitialEventRepresentation(testEventData, serializer));

        List<IntermediateEventRepresentation> result = upcaster.upcast(Stream.of(testRepresentation))
                                                               .collect(toList());

        assertEquals(1, result.size());
        IntermediateEventRepresentation resultRepresentation = result.get(0);
        assertSame(testRepresentation, resultRepresentation);
        verify(testRepresentation, never()).getData();
    }

    @Test
    void upcasterIgnoresWrongEventRevision() {
        String expectedRevisionNumber = "1";

        GenericDomainEventMessage<StubDomainEvent> testEventMessage =
                new GenericDomainEventMessage<>("test", "aggregateId", 0, new StubDomainEvent("oldName"));
        EventData<?> testEventData = new TestDomainEventEntry(testEventMessage, serializer);
        IntermediateEventRepresentation testRepresentation = new InitialEventRepresentation(testEventData, serializer);

        List<IntermediateEventRepresentation> result = upcaster.upcast(Stream.of(testRepresentation))
                                                               .collect(toList());

        testRepresentation = spy(result.get(0));
        // Initial upcast was successful
        assertEquals(expectedRevisionNumber, testRepresentation.getType().getRevision());

        result = upcaster.upcast(Stream.of(testRepresentation))
                         .collect(toList());

        assertFalse(result.isEmpty());
        IntermediateEventRepresentation resultRepresentation = result.get(0);
        assertSame(testRepresentation, resultRepresentation);
        verify(testRepresentation, never()).getData();
    }

    @SuppressWarnings("OptionalGetWithoutIsPresent")
    @Test
    void upcastingDomainEventData() {
        String testAggregateType = "test";
        String testAggregateId = "aggregateId";
        GlobalSequenceTrackingToken testTrackingToken = new GlobalSequenceTrackingToken(10);
        long testSequenceNumber = 100;
        SerializedObject<String> testPayload = serializer.serialize(new StubDomainEvent("oldName"), String.class);
        EventData<?> testEventData = new TrackedDomainEventData<>(
                testTrackingToken, new GenericDomainEventEntry<>(
                testAggregateType, testAggregateId, testSequenceNumber, "eventId", Instant.now(),
                testPayload.getType().getName(), testPayload.getType().getRevision(), testPayload,
                serializer.serialize(MetaData.emptyInstance(), String.class)
        ));
        IntermediateEventRepresentation testRepresentation = new InitialEventRepresentation(testEventData, serializer);

        List<IntermediateEventRepresentation> result = upcaster.upcast(Stream.of(testRepresentation))
                                                               .collect(toList());

        assertFalse(result.isEmpty());

        IntermediateEventRepresentation firstEventResult = result.get(0);
        assertEquals(testAggregateType, firstEventResult.getAggregateType().get());
        assertEquals(testAggregateId, firstEventResult.getAggregateIdentifier().get());
        assertEquals(testTrackingToken, firstEventResult.getTrackingToken().get());
        assertEquals(Long.valueOf(testSequenceNumber), firstEventResult.getSequenceNumber().get());

        IntermediateEventRepresentation secondEventResult = result.get(1);
        assertEquals(testAggregateType, secondEventResult.getAggregateType().get());
        assertEquals(testAggregateId, secondEventResult.getAggregateIdentifier().get());
        assertEquals(testTrackingToken, secondEventResult.getTrackingToken().get());
        assertEquals(Long.valueOf(testSequenceNumber), secondEventResult.getSequenceNumber().get());

        IntermediateEventRepresentation thirdEventResult = result.get(2);
        assertEquals(testAggregateType, thirdEventResult.getAggregateType().get());
        assertEquals(testAggregateId, thirdEventResult.getAggregateIdentifier().get());
        assertEquals(testTrackingToken, thirdEventResult.getTrackingToken().get());
        assertEquals(Long.valueOf(testSequenceNumber), thirdEventResult.getSequenceNumber().get());
    }

    @SuppressWarnings("ConstantConditions")
    @Test
    void upcastsKnownType() {
        String expectedRevisionNumber = "1";
        String expectedSecondAndThirdRevisionNumber = null;

        MetaData testMetaData = MetaData.with("key", "value");
        GenericDomainEventMessage<StubDomainEvent> testEventMessage =
                new GenericDomainEventMessage<>("test", "aggregateId", 0, new StubDomainEvent("oldName"), testMetaData);
        EventData<?> testEventData = new TestDomainEventEntry(testEventMessage, serializer);
        InitialEventRepresentation testRepresentation = new InitialEventRepresentation(testEventData, serializer);

        List<IntermediateEventRepresentation> result = upcaster.upcast(Stream.of(testRepresentation))
                                                               .collect(toList());

        assertFalse(result.isEmpty());

        IntermediateEventRepresentation firstResultRepresentation = result.get(0);
        assertEquals(expectedRevisionNumber, firstResultRepresentation.getType().getRevision());
        assertEquals(testEventData.getEventIdentifier(), firstResultRepresentation.getMessageIdentifier());
        assertEquals(testEventData.getTimestamp(), firstResultRepresentation.getTimestamp());
        assertEquals(testMetaData, firstResultRepresentation.getMetaData().getObject());
        StubDomainEvent firstUpcastedEvent = serializer.deserialize(firstResultRepresentation.getData());
        assertEquals(expectedNewString, firstUpcastedEvent.getName());

        IntermediateEventRepresentation secondResultRepresentation = result.get(1);
        assertEquals(expectedSecondAndThirdRevisionNumber, secondResultRepresentation.getType().getRevision());
        assertEquals(testEventData.getEventIdentifier(), secondResultRepresentation.getMessageIdentifier());
        assertEquals(testEventData.getTimestamp(), secondResultRepresentation.getTimestamp());
        assertEquals(testMetaData, secondResultRepresentation.getMetaData().getObject());
        SecondStubEvent secondUpcastedEvent = serializer.deserialize(secondResultRepresentation.getData());
        assertEquals(expectedNewString, secondUpcastedEvent.getName());
        assertEquals(expectedNewInteger, secondUpcastedEvent.getNumber());

        IntermediateEventRepresentation thirdResultRepresentation = result.get(2);
        assertEquals(expectedSecondAndThirdRevisionNumber, thirdResultRepresentation.getType().getRevision());
        assertEquals(testEventData.getEventIdentifier(), thirdResultRepresentation.getMessageIdentifier());
        assertEquals(testEventData.getTimestamp(), thirdResultRepresentation.getTimestamp());
        assertEquals(testMetaData, thirdResultRepresentation.getMetaData().getObject());
        ThirdStubEvent thirdUpcastedEvent = serializer.deserialize(thirdResultRepresentation.getData());
        assertEquals(expectedNewString, thirdUpcastedEvent.getName());
        assertEquals(expectedNewInteger, thirdUpcastedEvent.getNumber());
        assertEquals(expectedNewBooleans, thirdUpcastedEvent.getTruths());
    }

    private static class StubEventMultiUpcaster extends EventMultiUpcaster {

        private final SerializedType targetType = new SimpleSerializedType(StubDomainEvent.class.getName(), null);

        private final String newStringValue;
        private final Integer newIntegerValue;
        private final List<Boolean> newBooleanValues;

        private StubEventMultiUpcaster(String newStringValue, Integer newIntegerValue, List<Boolean> newBooleanValues) {
            this.newStringValue = newStringValue;
            this.newIntegerValue = newIntegerValue;
            this.newBooleanValues = newBooleanValues;
        }

        @Override
        protected boolean canUpcast(IntermediateEventRepresentation intermediateRepresentation) {
            return intermediateRepresentation.getType().equals(targetType);
        }

        @Override
        protected Stream<IntermediateEventRepresentation> doUpcast(IntermediateEventRepresentation ir) {
            return Stream.of(
                    ir.upcastPayload(new SimpleSerializedType(targetType.getName(), "1"),
                                     JsonNode.class,
                                     this::doUpcast),
                    ir.upcastPayload(new SimpleSerializedType(SecondStubEvent.class.getName(), null),
                                     JsonNode.class,
                                     this::doUpcastTwo),
                    ir.upcastPayload(new SimpleSerializedType(ThirdStubEvent.class.getName(), null),
                                     JsonNode.class,
                                     this::doUpcastThree)
            );
        }

        private JsonNode doUpcast(JsonNode eventJsonNode) {
            if (!eventJsonNode.isObject()) {
                return eventJsonNode;
            }
            ObjectNode eventObjectNode = (ObjectNode) eventJsonNode;

            eventObjectNode.set("name", new TextNode(newStringValue));

            return eventObjectNode;
        }

        private JsonNode doUpcastTwo(JsonNode eventJsonNode) {
            if (!eventJsonNode.isObject()) {
                return eventJsonNode;
            }
            ObjectNode eventObjectNode = (ObjectNode) eventJsonNode;

            eventObjectNode.set("name", new TextNode(newStringValue));
            eventObjectNode.set("number", new IntNode(newIntegerValue));

            return eventJsonNode;
        }

        private JsonNode doUpcastThree(JsonNode eventJsonNode) {
            if (!eventJsonNode.isObject()) {
                return eventJsonNode;
            }
            ObjectNode eventObjectNode = (ObjectNode) eventJsonNode;

            eventObjectNode.set("name", new TextNode(newStringValue));
            eventObjectNode.set("number", new IntNode(newIntegerValue));
            ArrayNode truthsArrayNode = eventObjectNode.withArray("truths");
            newBooleanValues.forEach(truthsArrayNode::add);

            return eventJsonNode;
        }
    }
}


text:
module Wordpress
  class Revision < WpPost
    scope :exclude_autosaves, -> { where("post_name NOT LIKE '%autosave%'") }
  end
end


text:
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Autofac.Extras.FakeItEasy;
using Elasticsearch.Net.Connection;
using Elasticsearch.Net.Tests.Unit.Stubs;
using FakeItEasy;
using FluentAssertions;
using NUnit.Framework;

namespace Elasticsearch.Net.Tests.Unit.Exceptions
{
	[TestFixture]
	public class ThrownElasticsearchServerExceptions
	{
		private MemoryStream CreateServerExceptionResponse(int status, string exceptionType, string exceptionMessage)
		{
			var format = @"{{ ""status"": {0}, ""error"" : ""{1}[{2}]"" }}";
			var bytes = Encoding.UTF8.GetBytes(string.Format(format, status, exceptionType, exceptionMessage));
			var stream = new MemoryStream(bytes);
			return stream;
		}

		[Test]
		[TestCase(505, "SomeException", "Some Error Message")]
		[TestCase(505, "", "")]
		public void ServerExceptionIsCaught_DiscardResponse(int status, string exceptionType, string exceptionMessage)
		{
			var response = CreateServerExceptionResponse(status, exceptionType, exceptionMessage);
			using (var fake = new AutoFake(callsDoNothing: true))
			{
				this.Call(status, exceptionType, exceptionMessage, fake, response);
			}
		}

		[Test]
		[TestCase(505, "SomeException", "Some Error Message")]
		[TestCase(505, "", "")]
		public void ServerExceptionIsCaught_KeepResponse(int status, string exceptionType, string exceptionMessage)
		{
			var response = CreateServerExceptionResponse(status, exceptionType, exceptionMessage);
			using (var fake = new AutoFake(callsDoNothing: true))
			{
				this.Call(status, exceptionType, exceptionMessage, fake, response, exposeRawResponse: true);
			}
		}

		[Test]
		[TestCase(505, "SomeException", "Some Error Message")]
		[TestCase(505, "", "")]
		public void ServerExceptionIsCaught_DiscardResponse_Async(int status, string exceptionType, string exceptionMessage)
		{
			var response = CreateServerExceptionResponse(status, exceptionType, exceptionMessage);
			using (var fake = new AutoFake(callsDoNothing: true))
			{
				this.CallAsync(status, exceptionType, exceptionMessage, fake, response);
			}
		}

		[Test]
		[TestCase(505, "SomeException", "Some Error Message")]
		[TestCase(505, "", "")]
		public void ServerExceptionIsCaught_KeepResponse_Async(int status, string exceptionType, string exceptionMessage)
		{
			var response = CreateServerExceptionResponse(status, exceptionType, exceptionMessage);
			using (var fake = new AutoFake(callsDoNothing: true))
			{
				this.CallAsync(status, exceptionType, exceptionMessage, fake, response, exposeRawResponse: true);
			}
		}

		private void Call(int status, string exceptionType, string exceptionMessage, AutoFake fake, MemoryStream response, bool exposeRawResponse = false)
		{
			var connectionConfiguration = new ConnectionConfiguration()
				.ThrowOnElasticsearchServerExceptions()
				.ExposeRawResponse(exposeRawResponse);

			fake.Provide<IConnectionConfigurationValues>(connectionConfiguration);
			FakeCalls.ProvideDefaultTransport(fake);

			var getCall = FakeCalls.GetSyncCall(fake);
			getCall.Returns(FakeResponse.Bad(connectionConfiguration, response: response));

			var client = fake.Resolve<ElasticsearchClient>();

			var e = Assert.Throws<ElasticsearchServerException>(()=>client.Info());
			AssertServerErrorsException(e, status, exceptionType, exceptionMessage);
			getCall.MustHaveHappened(Repeated.Exactly.Once);
		}

		private void CallAsync(int status, string exceptionType, string exceptionMessage, AutoFake fake, MemoryStream response, bool exposeRawResponse = false)
		{
			var connectionConfiguration = new ConnectionConfiguration()
				.ThrowOnElasticsearchServerExceptions()
				.ExposeRawResponse(exposeRawResponse);

			fake.Provide<IConnectionConfigurationValues>(connectionConfiguration);
			FakeCalls.ProvideDefaultTransport(fake);

			var getCall = FakeCalls.GetCall(fake);
			getCall.Returns(FakeResponse.BadAsync(connectionConfiguration, response: response));

			var client = fake.Resolve<ElasticsearchClient>();

			var e = Assert.Throws<ElasticsearchServerException>(async ()=>await client.InfoAsync());
			AssertServerErrorsException(e, status, exceptionType, exceptionMessage);
			getCall.MustHaveHappened(Repeated.Exactly.Once);
		}

		private static void AssertServerErrorsException(ElasticsearchServerException serverException, int status, string exceptionType, string exceptionMessage)
		{
			serverException.Should().NotBeNull();
			serverException.ExceptionType.Should().Be(exceptionType);
			serverException.Message.Should().Be(exceptionMessage);
			serverException.Status.Should().Be(status);

		}
	}
}


text:
(function Cyclic() {
"use strict";

const Set = %Intrinsic("Set");
const {
  add: Set_prototype_add,
  delete: Set_prototype_delete,
  has: Set_prototype_has,
} = Set.prototype;

const set = new Set();

function checkCycle(fn, o, ...args) {
  if (%CallFunction(Set_prototype_has, set, o)) {
    if (typeof o == 'function' || typeof o == 'object' && o !== null) {
      return "";
    }
    return "" + o;
  }
  %CallFunction(Set_prototype_add, set, o);
  try {
    return %CallFunction(fn, o, ...args);
  } finally {
    %CallFunction(Set_prototype_delete, set, o);
  }
}

// Add cyclic check to: Array.prototype.join and Array.prototype.toLocaleString
const ArrayPrototype = %Intrinsic("ArrayPrototype");
const {
  join: Array_prototype_join,
  toLocaleString: Array_prototype_toLocaleString,
} = ArrayPrototype;

%CreateMethodProperties(ArrayPrototype, {
  join(separator) {
    return checkCycle(Array_prototype_join, this, separator);
  },
  toLocaleString() {
    return checkCycle(Array_prototype_toLocaleString, this);
  }
});

// Add cyclic check to: Error.prototype.toString
const ErrorPrototype = %Intrinsic("ErrorPrototype");
const Error_prototype_toString = ErrorPrototype.toString;

%CreateMethodProperties(ErrorPrototype, {
  toString() {
    return checkCycle(Error_prototype_toString, this);
  }
});

})();


text:
<?xml version="1.0" encoding="utf-8"?>
  <!-- $Id: en.xml 661 2012-08-27 11:26:39Z namiltd $ -->
  <!--
    phpSysInfo language file Language: English Created by: Erkan VALENTIN
  -->
<tns:translationPlugin language="english" charset="utf-8"
  xmlns:tns="http://phpsysinfo.sourceforge.net/translation-plugin" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://phpsysinfo.sourceforge.net/translation-plugin ../../../language/translation-plugin.xsd">
  <expression id="plugin_bat_001" name="bat_title">
    <exp>Battery Status</exp>
  </expression>
  <expression id="plugin_bat_002" name="bat_date">
    <exp>Last refresh</exp>
  </expression>
  <expression id="plugin_bat_003" name="bat_design_capacity">
    <exp>Design capacity</exp>
  </expression>
  <expression id="plugin_bat_004" name="bat_remaining_capacity">
    <exp>Remaining capacity</exp>
  </expression>
  <expression id="plugin_bat_005" name="bat_design_voltage">
    <exp>Design voltage</exp>
  </expression>
  <expression id="plugin_bat_006" name="bat_present_voltage">
    <exp>Present voltage</exp>
  </expression>
  <expression id="plugin_bat_007" name="bat_item">
    <exp>Items</exp>
  </expression>
  <expression id="plugin_bat_008" name="bat_value">
    <exp>Values</exp>
  </expression>
  <expression id="plugin_bat_009" name="bat_charging_state">
    <exp>Charging state</exp>
  </expression>
  <expression id="plugin_bat_010" name="bat_battery_type">
    <exp>Battery Type</exp>
  </expression>
  <expression id="plugin_bat_011" name="bat_battery_temperature">
    <exp>Battery Temperature</exp>
  </expression>
  <expression id="plugin_bat_012" name="bat_battery_condition">
    <exp>Battery Condition</exp>
  </expression>
  <expression id="plugin_bat_013" name="bat_cycle_count">
    <exp>Cycle Count</exp>
  </expression>
</tns:translationPlugin>


text:
<!DOCTYPE html>

    <title>Protocols  Reference</title>
    <link rel="stylesheet" type="text/css" href="css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="css/highlight.css" />
    <meta charset="utf-8">

           Docs

         (100% documented)

        <form role="search" action="search.json">
          <input type="text" placeholder="Search documentation" data-typeahead>
        </form>

       Reference

      Protocols  Reference

            Enums

                TaskError

                TaskEvent

            Extensions

                Observable

            Protocols

                TaskEventType

            Structs

                Task

Protocols

The following protocols are available globally.

                    TaskEventType

A protocol encapsulated TaskEvent. Necessary to create Observable operators and not intended for public use.

                        See more

Declaration

Swift

public protocol TaskEventType

© 2017 . All rights reserved. (Last updated: 2017-02-20)

Generated by jazzy ♪♫ v0.7.4, a Realm project.


text:
<?php

namespace Froiden\RestAPI\Tests\Models;

use Froiden\RestAPI\ApiModel;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class DummyComment extends ApiModel
{

    protected $table = 'dummy_comments';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'comments', 'user_id', 'post_id',
    ];

    protected $filterable = [
        'comments', 'user_id', 'post_id',
    ];

    protected $dates = [
        'created_at',
        'updated_at'
    ];

    /**
     * Get the post that owns the comment.
     */
    public function post()
    {
        return $this->belongsTo('Froiden\RestAPI\Tests\Models\DummyPost');
    }
}


text:
package insulin_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/ginkgo/extensions/table"
	. "github.com/onsi/gomega"

	dataNormalizer "github.com/tidepool-org/platform/data/normalizer"
	"github.com/tidepool-org/platform/data/types/insulin"
	dataTypesInsulinTest "github.com/tidepool-org/platform/data/types/insulin/test"
	dataTypesTest "github.com/tidepool-org/platform/data/types/test"
	errorsTest "github.com/tidepool-org/platform/errors/test"
	"github.com/tidepool-org/platform/pointer"
	"github.com/tidepool-org/platform/structure"
	structureValidator "github.com/tidepool-org/platform/structure/validator"
	"github.com/tidepool-org/platform/test"
)

var _ = Describe("Simple", func() {
	It("SimpleActingTypeIntermediate is expected", func() {
		Expect(insulin.SimpleActingTypeIntermediate).To(Equal("intermediate"))
	})

	It("SimpleActingTypeLong is expected", func() {
		Expect(insulin.SimpleActingTypeLong).To(Equal("long"))
	})

	It("SimpleActingTypeRapid is expected", func() {
		Expect(insulin.SimpleActingTypeRapid).To(Equal("rapid"))
	})

	It("SimpleActingTypeShort is expected", func() {
		Expect(insulin.SimpleActingTypeShort).To(Equal("short"))
	})

	It("SimpleBrandLengthMaximum is expected", func() {
		Expect(insulin.SimpleBrandLengthMaximum).To(Equal(100))
	})

	It("SimpleActingTypes returns expected", func() {
		Expect(insulin.SimpleActingTypes()).To(Equal([]string{"intermediate", "long", "rapid", "short"}))
	})

	Context("ParseSimple", func() {
		// TODO
	})

	Context("NewSimple", func() {
		It("is successful", func() {
			Expect(insulin.NewSimple()).To(Equal(&insulin.Simple{}))
		})
	})

	Context("Simple", func() {
		Context("Parse", func() {
			// TODO
		})

		Context("Validate", func() {
			DescribeTable("validates the datum",
				func(mutator func(datum *insulin.Simple), expectedErrors ...error) {
					datum := dataTypesInsulinTest.RandomSimple()
					mutator(datum)
					dataTypesTest.ValidateWithExpectedOrigins(datum, structure.Origins(), expectedErrors...)
				},
				Entry("succeeds",
					func(datum *insulin.Simple) {},
				),
				Entry("acting type missing",
					func(datum *insulin.Simple) { datum.ActingType = nil },
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/actingType"),
				),
				Entry("acting type invalid",
					func(datum *insulin.Simple) { datum.ActingType = pointer.FromString("invalid") },
					errorsTest.WithPointerSource(structureValidator.ErrorValueStringNotOneOf("invalid", []string{"intermediate", "long", "rapid", "short"}), "/actingType"),
				),
				Entry("acting type intermediate",
					func(datum *insulin.Simple) { datum.ActingType = pointer.FromString("intermediate") },
				),
				Entry("acting type long",
					func(datum *insulin.Simple) { datum.ActingType = pointer.FromString("long") },
				),
				Entry("acting type rapid",
					func(datum *insulin.Simple) { datum.ActingType = pointer.FromString("rapid") },
				),
				Entry("acting type short",
					func(datum *insulin.Simple) { datum.ActingType = pointer.FromString("short") },
				),
				Entry("brand missing",
					func(datum *insulin.Simple) { datum.Brand = nil },
				),
				Entry("brand empty",
					func(datum *insulin.Simple) { datum.Brand = pointer.FromString("") },
					errorsTest.WithPointerSource(structureValidator.ErrorValueEmpty(), "/brand"),
				),
				Entry("brand invalid",
					func(datum *insulin.Simple) { datum.Brand = pointer.FromString(test.RandomStringFromRange(101, 101)) },
					errorsTest.WithPointerSource(structureValidator.ErrorLengthNotLessThanOrEqualTo(101, 100), "/brand"),
				),
				Entry("brand valid",
					func(datum *insulin.Simple) { datum.Brand = pointer.FromString(test.RandomStringFromRange(1, 100)) },
				),
				Entry("concentration missing",
					func(datum *insulin.Simple) { datum.Concentration = nil },
				),
				Entry("concentration invalid",
					func(datum *insulin.Simple) { datum.Concentration.Units = nil },
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/concentration/units"),
				),
				Entry("concentration valid",
					func(datum *insulin.Simple) { datum.Concentration = dataTypesInsulinTest.RandomConcentration() },
				),
				Entry("multiple errors",
					func(datum *insulin.Simple) {
						datum.ActingType = nil
						datum.Brand = pointer.FromString("")
						datum.Concentration.Units = nil
					},
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/actingType"),
					errorsTest.WithPointerSource(structureValidator.ErrorValueEmpty(), "/brand"),
					errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/concentration/units"),
				),
			)
		})

		Context("Normalize", func() {
			DescribeTable("normalizes the datum",
				func(mutator func(datum *insulin.Simple)) {
					for _, origin := range structure.Origins() {
						datum := dataTypesInsulinTest.RandomSimple()
						mutator(datum)
						expectedDatum := dataTypesInsulinTest.CloneSimple(datum)
						normalizer := dataNormalizer.New()
						Expect(normalizer).ToNot(BeNil())
						datum.Normalize(normalizer.WithOrigin(origin))
						Expect(normalizer.Error()).To(BeNil())
						Expect(normalizer.Data()).To(BeEmpty())
						Expect(datum).To(Equal(expectedDatum))
					}
				},
				Entry("does not modify the datum",
					func(datum *insulin.Simple) {},
				),
				Entry("does not modify the datum; acting type nil",
					func(datum *insulin.Simple) { datum.ActingType = nil },
				),
				Entry("does not modify the datum; brand nil",
					func(datum *insulin.Simple) { datum.Brand = nil },
				),
				Entry("does not modify the datum; concentration nil",
					func(datum *insulin.Simple) { datum.Concentration = nil },
				),
			)
		})
	})
})


text:
**netem** provides Network Emulating functionality for testing protocols by emulating the properties of wide area networks. The current version emulates variable delay, loss, duplication and re-ordering.

Netem is controlled by the command line tool 'tc' which is part of the iproute2 package of tools. The ```tc``` command uses shared libraries and data files in the /usr/lib/tc directory.

## Emulating wide area network delays

This is the simplest example, it just add a fixed amount of delay to all packets going out of the local Ethernet.

   ```
   # tc qdisc add dev ens3 root netem delay 100ms
   ```

Now a simple ping test to host on the local network should show an increase of 100 milliseconds. The delay is limited by the clock resolution of the kernel (HZ). On most 2.4 systems, the system clock runs at 100hz which allows delays in increments of 10ms. On 2.6, the value is a configuration parameter from 1000 to 100 hz.

Later examples just change parameters without reloading the qdisc.

Real wide area networks show variability so it is possible to add random variation.

   ```
   # tc qdisc change dev ens3 root netem delay 100ms 10ms
   ```

This causes the added delay to be 100ms +/- 10ms. Network delay variation is not purely random, so to emulate that there is a correlation value as well.

   ```
   # tc qdisc change dev ens3 root netem delay 100ms 10ms 25%
   ```

This causes the added delay to be 100ms +/- 10ms with the next random elment depending 25% on the last on. This is not true statistical correlation, but an approximation.

## Delay distribution

Typically, the delay in a network is not uniform. It is more common to use a something like a normal distribution to describe the variation in delay. The netem discipline can take a table to specify a non-uniform distribution

   ```
   # tc qdisc change dev ens3 root netem delay 100ms 20ms distribution normal
   ```

The actual tables (normal, pareto, paretonormal) are generated as part of the iproute2 compilation and placed in /usr/lib/tc; so it is possible with some effort to make your own distribution on experimental data.

## Packet loss

Random packet loss is specified in the 'tc' command in percent. The smallest possible non-zero value is: 2^32 = 0.0000000232%

   ```
   # tc qdisc change dev ens3 root netem loss 0.1%
   ```

This causes 1/10th of a percent (i.e 1 out of 1000) packets to be randomly dropped.

An optional correlation may also be added. This causes the random number generator to be less random and can be used to emulate packet burst losses.

   ```
   # tc qdisc change dev ens3 root netem loss 0.3% 25%
   ```

This will cause 0.3% of packets to be lost, and each successive probability depends by a quarter on the last one.

Prob(n) = .25 * Prob(n-1) + .75 * Random

> Note: When loss is used locally (not on a bridge or router), the loss is reported to the upper level protocols. This may cause TCP to resend and behave as if there was no loss. When testing protocol reponse to loss it is best to use a netem on a bridge or router.


text:
require "test/unit"
require "bob/test"

class BobTestTest < Test::Unit::TestCase
  include Bob::Test

  def assert_scm_repo(repo)
    repo.destroy
    repo.create

    assert_equal 1, repo.commits.size
    assert_equal "First commit", repo.commits.first[:message]

    repo.add_failing_commit
    assert_equal 2, repo.commits.size
    assert_equal "This commit will fail", repo.commits.last[:message]
    assert_equal repo.commits.last[:identifier], repo.head
    assert repo.short_head

    repo.add_successful_commit
    assert_equal 3, repo.commits.size
    assert_equal "This commit will work", repo.commits.last[:message]
    assert_equal repo.commits.last[:identifier], repo.head
  end

  def test_buildable_stub
    b = BuildableStub.new(:git, "git://github.com/ry/node", "master", "make")

    assert_equal :git,                       b.kind
    assert_equal "git://github.com/ry/node", b.uri
    assert_equal "master",                   b.branch
    assert_equal "make",                     b.build_script
  end

  def test_scm_repo
    assert_scm_repo(GitRepo.new(:my_test_project))
    assert_scm_repo(SvnRepo.new(:my_test_project))
  end

  def test_buildable_git_repo
    Bob.directory = "/tmp/bob-git"

    repo = GitRepo.new(:test_repo)
    repo.destroy
    repo.create

    b = BuildableStub.from(repo)
    assert_equal :git,                     b.kind
    assert_equal "/tmp/bob-git/test_repo", b.uri
    assert_equal "master",                 b.branch
    assert_equal "./test",                 b.build_script
  end

  def test_buildable_svn_repo
    Bob.directory = "/tmp/bob-svn"

    repo = SvnRepo.new(:test_repo)
    repo.destroy
    repo.create

    b = BuildableStub.from(repo)
    assert_equal :svn,      b.kind
    assert_equal "",        b.branch
    assert_equal "./test",  b.build_script
    assert_equal "file:///tmp/bob-svn/svn/test_repo", b.uri
  end
end


text:
"""Tests for tf_agents.agents.ddpg.critic_rnn_network."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized

import tensorflow as tf  # pylint: disable=g-explicit-tensorflow-version-import

from tf_agents.agents.ddpg import critic_rnn_network
from tf_agents.specs import tensor_spec
from tf_agents.trajectories import time_step as ts

def lstm_keras_fn(lstm_size):
  return tf.keras.layers.LSTM(lstm_size, return_state=True,
                              return_sequences=True)

def rnn_keras_fn(lstm_size):
  cell = tf.keras.layers.SimpleRNNCell(lstm_size)
  return tf.keras.layers.RNN(cell, return_state=True,
                             return_sequences=True)

class CriticRnnNetworkTest(parameterized.TestCase, tf.test.TestCase):

  @parameterized.named_parameters(
      ('RNNKerasUnroll', None, rnn_keras_fn),
  )
  def testBuildsRnn(self, lstm_size, rnn_construction_fn):
    observation_spec = tensor_spec.BoundedTensorSpec((8, 8, 3), tf.float32, 0,
                                                     1)
    time_step_spec = ts.time_step_spec(observation_spec)
    time_step = tensor_spec.sample_spec_nest(time_step_spec, outer_dims=(1,))

    action_spec = tensor_spec.BoundedTensorSpec((2,), tf.float32, 2, 3)
    network_input_spec = (observation_spec, action_spec)
    action = tensor_spec.sample_spec_nest(action_spec, outer_dims=(1,))
    net = critic_rnn_network.CriticRnnNetwork(
        network_input_spec,
        observation_conv_layer_params=[(4, 2, 2)],
        observation_fc_layer_params=(4,),
        action_fc_layer_params=(5,),
        joint_fc_layer_params=(5,),
        lstm_size=lstm_size,
        output_fc_layer_params=(5,),
        rnn_construction_fn=rnn_construction_fn,
        rnn_construction_kwargs={'lstm_size': 3})

    network_input = (time_step.observation, action)
    q_values, network_state = net(network_input, time_step.step_type,
                                  net.get_initial_state(batch_size=1))

    self.evaluate(tf.compat.v1.global_variables_initializer())
    self.assertEqual([1], q_values.shape.as_list())

    self.assertLen(net.variables, 15)
    # Obs Conv Net Kernel
    self.assertEqual((2, 2, 3, 4), net.variables[0].shape)
    # Obs Conv Net bias
    self.assertEqual((4,), net.variables[1].shape)
    # Obs Fc Kernel
    self.assertEqual((64, 4), net.variables[2].shape)
    # Obs Fc Bias
    self.assertEqual((4,), net.variables[3].shape)
    # Action Fc Kernel
    self.assertEqual((2, 5), net.variables[4].shape)
    # Action Fc Bias
    self.assertEqual((5,), net.variables[5].shape)
    # Joint Fc Kernel
    self.assertEqual((9, 5), net.variables[6].shape)
    # Joint Fc Bias
    self.assertEqual((5,), net.variables[7].shape)
    # RNN Cell Kernel
    self.assertEqual((5, 3), net.variables[8].shape)
    # RNN Cell Recurrent Kernel
    self.assertEqual((3, 3), net.variables[9].shape)
    # RNN Cell Bias
    self.assertEqual((3,), net.variables[10].shape)
    # Output Fc Kernel
    self.assertEqual((3, 5), net.variables[11].shape)
    # Output Fc Bias
    self.assertEqual((5,), net.variables[12].shape)
    # Q Value Kernel
    self.assertEqual((5, 1), net.variables[13].shape)
    # Q Value Bias
    self.assertEqual((1,), net.variables[14].shape)

    # Assert LSTM cell is created.
    self.assertEqual((3,), network_state[0].shape)

  @parameterized.named_parameters(
      ('DynamicUnroll', (3,), None),
      ('LSTMKerasUnroll', None, lstm_keras_fn),
  )
  def testBuilds(self, lstm_size, rnn_construction_fn):
    observation_spec = tensor_spec.BoundedTensorSpec((8, 8, 3), tf.float32, 0,
                                                     1)
    time_step_spec = ts.time_step_spec(observation_spec)
    time_step = tensor_spec.sample_spec_nest(time_step_spec, outer_dims=(1,))

    action_spec = tensor_spec.BoundedTensorSpec((2,), tf.float32, 2, 3)
    network_input_spec = (observation_spec, action_spec)
    action = tensor_spec.sample_spec_nest(action_spec, outer_dims=(1,))
    net = critic_rnn_network.CriticRnnNetwork(
        network_input_spec,
        observation_conv_layer_params=[(4, 2, 2)],
        observation_fc_layer_params=(4,),
        action_fc_layer_params=(5,),
        joint_fc_layer_params=(5,),
        lstm_size=lstm_size,
        output_fc_layer_params=(5,),
        rnn_construction_fn=rnn_construction_fn,
        rnn_construction_kwargs={'lstm_size': 3})

    network_input = (time_step.observation, action)
    q_values, network_state = net(network_input, time_step.step_type,
                                  net.get_initial_state(batch_size=1))

    self.evaluate(tf.compat.v1.global_variables_initializer())
    self.assertEqual([1], q_values.shape.as_list())

    self.assertLen(net.variables, 15)
    print('variables %s', net.variables)
    # Obs Conv Net Kernel
    self.assertEqual((2, 2, 3, 4), net.variables[0].shape)
    # Obs Conv Net bias
    self.assertEqual((4,), net.variables[1].shape)
    # Obs Fc Kernel
    self.assertEqual((64, 4), net.variables[2].shape)
    # Obs Fc Bias
    self.assertEqual((4,), net.variables[3].shape)
    # Action Fc Kernel
    self.assertEqual((2, 5), net.variables[4].shape)
    # Action Fc Bias
    self.assertEqual((5,), net.variables[5].shape)
    # Joint Fc Kernel
    self.assertEqual((9, 5), net.variables[6].shape)
    # Joint Fc Bias
    self.assertEqual((5,), net.variables[7].shape)
    # LSTM Cell Kernel
    self.assertEqual((5, 12), net.variables[8].shape)
    # LSTM Cell Recurrent Kernel
    self.assertEqual((3, 12), net.variables[9].shape)
    # LSTM Cell Bias
    self.assertEqual((12,), net.variables[10].shape)
    # Output Fc Kernel
    self.assertEqual((3, 5), net.variables[11].shape)
    # Output Fc Bias
    self.assertEqual((5,), net.variables[12].shape)
    # Q Value Kernel
    self.assertEqual((5, 1), net.variables[13].shape)
    # Q Value Bias
    self.assertEqual((1,), net.variables[14].shape)

    # Assert LSTM cell is created.
    self.assertEqual((1, 3), network_state[0].shape)
    self.assertEqual((1, 3), network_state[1].shape)

  @parameterized.named_parameters(
      ('DynamicUnroll', (3,), None),
      ('LSTMKerasUnroll', None, lstm_keras_fn),
      ('RNNKerasUnroll', None, rnn_keras_fn),
  )
  def testInit(self, lstm_size, rnn_construction_fn):
    observation_spec = tensor_spec.BoundedTensorSpec((8, 8, 3), tf.float32, 0,
                                                     1)
    action_spec = tensor_spec.BoundedTensorSpec((2,), tf.float32, 2, 3)
    network_input_spec = (observation_spec, action_spec)
    critic_rnn_network.CriticRnnNetwork(
        network_input_spec,
        lstm_size=lstm_size,
        rnn_construction_fn=rnn_construction_fn,
        rnn_construction_kwargs={'lstm_size': 3})

if __name__ == '__main__':
  tf.test.main()


text:
module Hindsight
  module Associations
    module ClassMethods
      def self.extended(base)
        base.class_attribute :versioned_associations, :ignored_associations, :through_associations
        base.versioned_associations = []
        base.ignored_associations = []
        base.through_associations = []
      end

      # Modify versioned associations so they return only the latest version of the associated record
      def has_versioned_association(*associations)
        associations = associations.flatten.compact.collect(&:to_sym)
        associations.each do |association|
          next if versioned_association?(association)
          versioned_associations << association.to_sym

          # Duplicate reflection under as "#{association}_versions"
          all_versions_association = :"#{association}_versions"
          reflection = reflect_on_association(association)
          send(reflection.macro, all_versions_association, reflection.options.reverse_merge(:class_name => association.to_s.classify, :source => association.to_s.singularize))

          # Create an association that returns only the latest versions of associated records as appropriate
          send(reflection.macro, association, versioned_association_condition(all_versions_association), reflection.options)
        end
      end

      def association_versioning_status
        all = reflections.keys.select {|association| copyable_association?(association) }
        Hash.new.tap do |status|
          status[:versioned]              = versioned_associations
          status[:unversioned_history]    = all - status[:versioned]
          status[:unversioned_no_history] = reflections.select {|association, reflection| status[:unversioned_history].include?(association) && reflection.is_a?(ActiveRecord::Reflection::HasManyReflection) }.keys
          status[:unversioned_history]    = status[:unversioned_history] - status[:unversioned_no_history]
          status[:ignored]                = ignored_associations
          status[:through]                = through_associations
        end
      end

      private

      # Identify an association that should not be copied when making new_versions
      # e.g. it is a subset of another association, like :red_cars is to :all_cars
      def ignore_associations(*associations)
        ignored_associations.concat associations.flatten.compact.collect(&:to_sym)
        ignored_associations.uniq!
      end

      def detect_versioned_associations
        reflections.each do |association, reflection|
          has_versioned_association(association) if copyable_association?(association) && reflection.klass.acts_like?(:hindsight)
        end
      end

      # Detects associations that are the :through association for another association on the model
      def detect_through_associations
        reflections.each do |association, reflection|
          next if ignored_association?(association) || version_association?(association)
          self.through_associations << reflection.options.symbolize_keys[:through].try(:to_sym)
        end
        self.through_associations = through_associations.compact.uniq.reject {|association| ignored_association?(association) }
      end

      # Returns true if the association can be copied from one version to the next
      def copyable_association?(association)
        versionable_reflection?(association) &&
        !ignored_association?(association) &&
        !version_association?(association) &&
        !through_association?(association)
      end

      # Returns true if the association is versioned, and is therefore expected to return only the latest
      # versions of associated records
      def versioned_association?(association)
        versioned_associations.include?(association.to_sym)
      end

      # Returns true if the association is ignored and should not be copied to the new version
      def ignored_association?(association)
        ignored_associations.include? association.to_sym
      end

      def through_association?(association)
        through_associations.include? association.to_sym
      end

      # Returns true if the association exists only to keep track of previous versions of records
      def version_association?(association)
        association.to_s.end_with? 'versions'
      end

      def versionable_reflection?(association)
        reflect_on_association(association).is_a?(ActiveRecord::Reflection::HasManyReflection)
      end

      # Returns a condition for use in a versioned has_many association
      # If the record is the latest version, return only the latest versions of associated records
      # Else, return the latest version of each associated record that is associated with this version
      # (avoids old versions not returning an associated record if the latest version has been attached to a different record)
      def versioned_association_condition(all_versions_association)
        lambda do |record|
          if record.latest_version?
            latest_versions
          else
            latest_versions record.send(all_versions_association)
          end
        end
      end
    end

    module InstanceMethods
      private

      def copy_associations_to(new_version)
        self.class.reflections.each do |association, reflection|
          next if new_version.association(association.to_sym).loaded?
          next if self.class.send :version_association?, association
          next if !self.class.send :versionable_reflection?, association

          records = send(association).to_a

          if self.class.send :versioned_association?, association
            records.collect! {|r| r.send(:build_new_version) }
          elsif self.class.send :through_association?, association
            # duplicate the record so other metadata is retained
            records.collect! {|r| r.dup }
          end

          # assign the dups to the new_version's association
          new_version.send("#{association}=", records)
        end
      end
    end
  end
end


text:
try:
    from system.core.exceptions.exceptions import *
except ImportError:
    pass


text:
title: Coffee
main: 'true'
category: Coffee
date: 2016-07-24
---

Like a lot of things that I've started making and have fallen in love with, coffee started out as me trying to find a cost-effective way to have _okayish_ coffee all the time. My options were:

1. Infrequent __great__[^4] coffee
2. Consistent __okay__ [^5] coffee
3. Crap coffee
4. No Coffee

In this case, I prefer the __No Coffee__ to the __Crap Coffee__ (sour coffee) [^6] but didn't want to throw down the cash for the __Great Coffee__.

[^4]: 8-9/10 on my "goodness" scale
[^5]: 6.5-8/10 on my "goodness" scale
[^6]: ![Dry Heave](https://dl.dropboxusercontent.com/s/4bx36cw1hjhz3i3/dry-heave-o.gif)


text:
layout: CV
title: "CV"
description: "Curriculum Vitae"
header-img: "img/GNAM_1308.jpg"
---


text:
// Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file.
"use strict";

var hostweburl;
var appweburl;

// Load the required SharePoint libraries
$(document).ready(function () {
    //Get the URI decoded URLs.
    appweburl =
        decodeURIComponent(
            getQueryStringParameter("SPAppWebUrl")
    );
    hostweburl =
        decodeURIComponent(
            getQueryStringParameter("SPHostUrl")
    );

    // resources are in URLs in the form:
    // web_url/_layouts/15/resource
    var scriptbase = hostweburl + "/_layouts/15/";

    // Load the js file and continue to the
    //   success event handler
    // Load the js files and continue to the successHandler
    $.getScript(scriptbase + "SP.Runtime.js",
        function () {
            $.getScript(scriptbase + "SP.js",
                function () { $.getScript(scriptbase + "SP.RequestExecutor.js", getOrders); }
                );
        }
    );
});

// The list has already been localized,
// we can retrieve the localized displayname of the fields
function getOrders() {
    var executor = new SP.RequestExecutor(appweburl);

    // We can use the getbytitle by using the localized
    // string ordersListName in strings.js
    executor.executeAsync(
        {
            url:
                appweburl +
                "/_api/web/lists/getbytitle('" + ordersListName + "')/fields",
            method: "GET",
            headers: { "Accept": "application/json; odata=verbose" },
            success: successFieldsHandler,
            error: errorHandler
        }
    );

    //This is the custom property defined in the
    // app part.
    var orderStatus = getQueryStringParameter("OrderStatus");

    var context = new SP.ClientContext(appweburl);
    var factory =
        new SP.ProxyWebRequestExecutorFactory(
            appweburl
        );
    context.set_webRequestExecutorFactory(factory);
    //Get the web and list objects
    //  and prepare the query
    var web = context.get_web();
    var list = web.get_lists().getByTitle(ordersListName);
    var camlString =
        "<View><ViewFields>" +
            "<FieldRef Name='ID' />" +
            "<FieldRef Name='Bookname' />" +
            "<FieldRef Name='Price' />" +
            "<FieldRef Name='Created' />" +
        "</ViewFields></View>" +
        "<Query>" +
            "<Where>" +
                "<And>"
                "<Eq>" +
                    "<FieldRef Name='Author' />" +
                    "<Value Type='User'>" +
                        orderStatus
                    "</Value>" +
                "</Eq>" +
                "<Eq>" +
                    "<FieldRef Name='Orderstatus' LookupId='TRUE' />" +
                    "<Value Type='Lookup'>" +

                    "</Value>" +
                "</Eq>" +
                "</And>" +
            "</Where>" +
        "</Query>";

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml(camlString);
    var myorders = list.getItems(camlQuery);

    context.load(myorders);

    //Execute the query with all the previous
    //  options and parameters
    context.executeQueryAsync(
        function () { successItemsHandler(myorders); },
        errorHandler
    );
}

// Function to handle the success event.
// Builds the body for the table.
function successItemsHandler(myorders) {
    var bodyHTML;
    var enumerator = myorders.getEnumerator();

    bodyHTML + "";
    while (enumerator.moveNext()) {
        var order = enumerator.get_current();
        bodyHTML += "
" +
        "" + order.get_item("ID") + "	" +
        "" + order.get_item("Bookname") + "	" +
        "" + order.get_item("Price") + "	" +
        "" + order.get_item("Created") + "	" +
            "
";
    }

    $("tbody").append(bodyHTML);
}
// Function to handle the success event.
// Builds the header for the table.
function successFieldsHandler(data, req) {
    var headerHTML;
    var iddisplayname;
    var booknamedisplayname;
    var pricedisplayname;
    var createddisplayname;
    var jsonObject = JSON.parse(data.body);
    var fields = jsonObject.d.results;

    //Localized column names are already localized in the list
    // in the Title property.
    headerHTML = "";
    for (var i = 0; i < fields.length; i++) {
        headerHTML += "
";
        switch(fields[i].InternalName)
        {
            case "ID":
                iddisplayname = fields[i].Title;
                break;
            case "Bookname":
                booknamedisplayname = fields[i].Title;
                break;
            case "Price":
                pricedisplayname = fields[i].Title;
                break;
            case "Created":
                createddisplayname = fields[i].Title;
                break;
        }
        headerHTML += "
";
    }

    headerHTML = "
" +
            "" + iddisplayname + "	" +
            "" + booknamedisplayname + "	" +
            "" + pricedisplayname + "	" +
            "" + createddisplayname + "	" +
                "
";

    $("thead").append(headerHTML);
}

// Function to handle the error event.
// Prints the error message to the page.
function errorHandler() {
    document.getElementById("msg").innerText =
        "Could not complete cross-domain call: " +
        arguments[1];
}


text:
//
//  CTNumber.h
//  CTObject
//
//  Created by Carlo Tortorella on 24/10/13.
//  Copyright (c) 2013 Carlo Tortorella. All rights reserved.
//

#pragma once
#include "CTAllocator.h"
#include "CTObject.h"
#include <stdint.h>

typedef enum
{
    CTNUMBER_TYPE_ULONG,
    CTNUMBER_TYPE_LONG,
    CTNUMBER_TYPE_DOUBLE
} CTNUMBER_TYPE, * CTNUMBER_TYPERef;

union CTNumberValue
{
    uint64_t ULong;
    int64_t Long;
    long double Double;
};

typedef struct
{
    CTAllocatorRef alloc;
    union CTNumberValue value;
    CTNUMBER_TYPE type;
} CTNumber, * CTNumberRef;

typedef struct
{
    CTAllocatorRef alloc;
    CTNumberRef base;
    CTNumberRef exponent;
} CTLargeNumber, * CTLargeNumberRef;

CTNumberRef CTNumberCreateWithUnsignedInt(CTAllocatorRef restrict alloc, unsigned int integer);
CTNumberRef CTNumberCreateWithInt(CTAllocatorRef restrict alloc, int integer);
CTNumberRef CTNumberCreateWithUnsignedLong(CTAllocatorRef restrict alloc, uint64_t longInteger);
CTNumberRef CTNumberCreateWithLong(CTAllocatorRef restrict alloc, int64_t longInteger);
CTNumberRef CTNumberCreateWithDouble(CTAllocatorRef restrict alloc, long double floatingPoint);

CTNumberRef CTNumberCopy(CTAllocatorRef restrict alloc, CTNumberRef number);

/**
 * Compare two CTNumber objects
 * @param array	A properly initialised CTNumber that was created with CTNumberCreate*.
 * @return		A value indicating equality, 0 = false, 1 = true.
 **/
uint8_t CTNumberCompare(const CTNumber * restrict number1, const CTNumber * restrict number2);
uint8_t CTLargeNumberCompare(const CTLargeNumber * restrict number1, const CTLargeNumber * restrict number2);

void CTNumberRelease(CTNumberRef number);
void CTLargeNumberRelease(CTLargeNumberRef lnumber);

CTLargeNumberRef CTLargeNumberCreate(CTAllocatorRef restrict alloc, CTNumberRef base, CTNumberRef exponent);
CTLargeNumberRef CTLargeNumberCopy(CTAllocatorRef restrict alloc, CTLargeNumberRef number);
CTNumberRef CTLargeNumberBase(const CTLargeNumber * restrict number);
CTNumberRef CTLargeNumberExponent(const CTLargeNumber * restrict number);

void CTNumberSetUnsignedLongValue(CTNumberRef restrict number, uint64_t longInteger);
void CTNumberSetLongValue(CTNumberRef restrict number, int64_t longInteger);
void CTNumberSetDoubleValue(CTNumberRef restrict number, long double floatingPoint);

uint32_t CTNumberUnsignedIntValue(const CTNumber * restrict number);
int32_t CTNumberIntValue(const CTNumber * restrict number);
uint64_t CTNumberUnsignedLongValue(const CTNumber * restrict number);
int64_t CTNumberLongValue(const CTNumber * restrict number);
long double CTNumberDoubleValue(const CTNumber * restrict number);
CTNUMBER_TYPE CTNumberType(const CTNumber * restrict number);

/**
 * Return a CTObject encasing the CTNumber passed.
 * @param n	A properly initialised CTNumber that was created with CTNumberCreate*.
 * @return	The CTNumber wrapped in a CTObject. The result is identical to using CTObjectCreate.
 **/
CTObjectRef CTObjectWithNumber(CTAllocatorRef alloc, CTNumberRef restrict n);
CTObjectRef CTObjectWithLargeNumber(CTAllocatorRef alloc, CTLargeNumberRef restrict n);


text:
package dev.niekirk.com.instagram4android.requests.payload;

import java.util.List;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/**
 * Created by root on 20/09/17.
 */

@Getter
@Setter
@ToString(callSuper = true)
public class InstagramSuggestedUsers {
    public String id;
    public String view_all_text;
    public String title;
    public String auto_dvance;
    public String type;
    public String tracking_token;
    public String landing_site_type;
    public String landing_site_title;
    public String upsell_fb_pos;
    public List<InstagramSuggestion> suggestions;
    public String netego_type;
}


text:
namespace clay {

CodePtr clone(CodePtr x)
{
    CodePtr y = new Code();
    y->location = x->location;
    clone(x->patternVars, y->patternVars);
    y->predicate = cloneOpt(x->predicate);
    clone(x->formalArgs, y->formalArgs);
    y->formalVarArg = cloneOpt(x->formalVarArg);
    y->returnSpecsDeclared = x->returnSpecsDeclared;
    clone(x->returnSpecs, y->returnSpecs);
    y->varReturnSpec = cloneOpt(x->varReturnSpec);
    y->body = cloneOpt(x->body);
    y->llvmBody = x->llvmBody;
    return y;
}

void clone(const vector<PatternVar> &x, vector<PatternVar> &out)
{
    out = x;
}

void clone(const vector<IdentifierPtr> &x, vector<IdentifierPtr> &out)
{
    for (unsigned i = 0; i < x.size(); ++i)
        out.push_back(x[i]);
}

ExprPtr clone(ExprPtr x)
{
    ExprPtr out;

    switch (x->exprKind) {

    case BOOL_LITERAL : {
        BoolLiteral *y = (BoolLiteral *)x.ptr();
        out = new BoolLiteral(y->value);
        break;
    }

    case INT_LITERAL : {
        IntLiteral *y = (IntLiteral *)x.ptr();
        out = new IntLiteral(y->value, y->suffix);
        break;
    }

    case FLOAT_LITERAL : {
        FloatLiteral *y = (FloatLiteral *)x.ptr();
        out = new FloatLiteral(y->value, y->suffix);
        break;
    }

    case CHAR_LITERAL : {
        CharLiteral *y = (CharLiteral *)x.ptr();
        out = new CharLiteral(y->value);
        break;
    }

    case STRING_LITERAL : {
        StringLiteral *y = (StringLiteral *)x.ptr();
        out = new StringLiteral(y->value);
        break;
    }

    case FILE_EXPR : {
        out = new FILEExpr();
        break;
    }

    case LINE_EXPR : {
        out = new LINEExpr();
        break;
    }

    case COLUMN_EXPR : {
        out = new COLUMNExpr();
        break;
    }

    case ARG_EXPR : {
        ARGExpr *arg = (ARGExpr *)x.ptr();
        out = new ARGExpr(arg->name);
        break;
    }

    case NAME_REF : {
        NameRef *y = (NameRef *)x.ptr();
        out = new NameRef(y->name);
        break;
    }

    case TUPLE : {
        Tuple *y = (Tuple *)x.ptr();
        out = new Tuple(clone(y->args));
        break;
    }

    case PAREN : {
        Paren *y = (Paren *)x.ptr();
        out = new Paren(clone(y->args));
        break;
    }

    case INDEXING : {
        Indexing *y = (Indexing *)x.ptr();
        out = new Indexing(clone(y->expr), clone(y->args));
        break;
    }

    case CALL : {
        Call *y = (Call *)x.ptr();
        out = new Call(clone(y->expr), clone(y->parenArgs), clone(y->lambdaArgs));
        break;
    }

    case FIELD_REF : {
        FieldRef *y = (FieldRef *)x.ptr();
        out = new FieldRef(clone(y->expr), y->name);
        break;
    }

    case STATIC_INDEXING : {
        StaticIndexing *y = (StaticIndexing *)x.ptr();
        out = new StaticIndexing(clone(y->expr), y->index);
        break;
    }

    case VARIADIC_OP : {
        VariadicOp *y = (VariadicOp *)x.ptr();
        out = new VariadicOp(y->op,clone(y->exprs));
        break;
    }

    case AND : {
        And *y = (And *)x.ptr();
        out = new And(clone(y->expr1), clone(y->expr2));
        break;
    }

    case OR : {
        Or *y = (Or *)x.ptr();
        out = new Or(clone(y->expr1), clone(y->expr2));
        break;
    }

    case LAMBDA : {
        Lambda *y = (Lambda *)x.ptr();
        LambdaPtr z = new Lambda(y->captureByRef);
        clone(y->formalArgs, z->formalArgs);
        z->formalVarArg = y->formalVarArg;
        z->body = clone(y->body);
        out = z.ptr();
        break;
    }

    case UNPACK : {
        Unpack *y = (Unpack *)x.ptr();
        out = new Unpack(clone(y->expr));
        break;
    }

    case STATIC_EXPR : {
        StaticExpr *y = (StaticExpr *)x.ptr();
        out = new StaticExpr(clone(y->expr));
        break;
    }

    case DISPATCH_EXPR : {
        DispatchExpr *y = (DispatchExpr *)x.ptr();
        out = new DispatchExpr(clone(y->expr));
        break;
    }

    case FOREIGN_EXPR : {
        out = x;
        break;
    }

    case OBJECT_EXPR : {
        ObjectExpr *y = (ObjectExpr *)x.ptr();
        out = new ObjectExpr(y->obj);
        break;
    }

    case EVAL_EXPR : {
        EvalExpr *eval = (EvalExpr*)x.ptr();
        out = new EvalExpr(clone(eval->args));
        break;
    }

    default :
        assert(false);
        break;

    }

    out->location = x->location;
    out->startLocation = x->startLocation;
    out->endLocation = x->endLocation;
    return out;
}

ExprPtr cloneOpt(ExprPtr x)
{
    if (!x)
        return NULL;
    return clone(x);
}

ExprListPtr clone(ExprListPtr x)
{
    ExprListPtr out = new ExprList();
    for (unsigned i = 0; i < x->size(); ++i)
        out->add(clone(x->exprs[i]));
    return out;
}

void clone(const vector<FormalArgPtr> &x, vector<FormalArgPtr> &out)
{
    for (unsigned i = 0; i < x.size(); ++i)
        out.push_back(clone(x[i]));
}

FormalArgPtr clone(FormalArgPtr x)
{
    FormalArgPtr out = new FormalArg(x->name, cloneOpt(x->type), x->tempness);
    out->location = x->location;
    return out;
}

FormalArgPtr cloneOpt(FormalArgPtr x)
{
    if (!x)
        return NULL;
    return clone(x);
}

void clone(const vector<ReturnSpecPtr> &x, vector<ReturnSpecPtr> &out)
{
    for (unsigned i = 0; i < x.size(); ++i)
        out.push_back(clone(x[i]));
}

ReturnSpecPtr clone(ReturnSpecPtr x)
{
    return new ReturnSpec(clone(x->type), x->name);
}

ReturnSpecPtr cloneOpt(ReturnSpecPtr x)
{
    if (!x)
        return NULL;
    return clone(x);
}

StatementPtr clone(StatementPtr x)
{
    StatementPtr out;

    switch (x->stmtKind) {

    case BLOCK : {
        Block *y = (Block *)x.ptr();
        BlockPtr z = new Block();
        clone(y->statements, z->statements);
        out = z.ptr();
        break;
    }

    case LABEL : {
        Label *y = (Label *)x.ptr();
        out = new Label(y->name);
        break;
    }

    case BINDING : {
        Binding *y = (Binding *)x.ptr();
        vector<IdentifierPtr> names;
        clone(y->names, names);
        out = new Binding(y->bindingKind, names, clone(y->values));
        break;
    }

    case ASSIGNMENT : {
        Assignment *y = (Assignment *)x.ptr();
        out = new Assignment(clone(y->left), clone(y->right));
        break;
    }

    case INIT_ASSIGNMENT : {
        InitAssignment *y = (InitAssignment *)x.ptr();
        out = new InitAssignment(clone(y->left), clone(y->right));
        break;
    }

    case VARIADIC_ASSIGNMENT : {
        VariadicAssignment *y = (VariadicAssignment *)x.ptr();
        out = new VariadicAssignment(y->op, clone(y->exprs));
        break;
    }

    case GOTO : {
        Goto *y = (Goto *)x.ptr();
        out = new Goto(y->labelName);
        break;
    }

    case RETURN : {
        Return *y = (Return *)x.ptr();
        out = new Return(y->returnKind, clone(y->values));
        break;
    }

    case IF : {
        If *y = (If *)x.ptr();
        vector<StatementPtr> conditionStatements;
        clone(y->conditionStatements, conditionStatements);
        out = new If(conditionStatements, clone(y->condition), clone(y->thenPart),
                     cloneOpt(y->elsePart));
        break;
    }

    case SWITCH : {
        Switch *y = (Switch *)x.ptr();
        vector<StatementPtr> exprStatements;
        clone(y->exprStatements, exprStatements);
        vector<CaseBlockPtr> caseBlocks;
        clone(y->caseBlocks, caseBlocks);
        out = new Switch(exprStatements,
                         clone(y->expr),
                         caseBlocks,
                         cloneOpt(y->defaultCase));
        break;
    }

    case EXPR_STATEMENT : {
        ExprStatement *y = (ExprStatement *)x.ptr();
        out = new ExprStatement(clone(y->expr));
        break;
    }

    case WHILE : {
        While *y = (While *)x.ptr();
        vector<StatementPtr> conditionStatements;
        clone(y->conditionStatements, conditionStatements);
        out = new While(conditionStatements, clone(y->condition), clone(y->body));
        break;
    }

    case BREAK : {
        out = new Break();
        break;
    }

    case CONTINUE : {
        out = new Continue();
        break;
    }

    case FOR : {
        For *y = (For *)x.ptr();
        vector<IdentifierPtr> variables;
        clone(y->variables, variables);
        out = new For(variables, clone(y->expr), clone(y->body));
        break;
    }

    case FOREIGN_STATEMENT : {
        out = x;
        break;
    }

    case TRY : {
        Try *y = (Try *)x.ptr();
        vector<CatchPtr> catchBlocks;
        clone(y->catchBlocks, catchBlocks);
        out = new Try(clone(y->tryBlock), catchBlocks);
        break;
    }

    case THROW : {
        Throw *y = (Throw *)x.ptr();
        out = new Throw(cloneOpt(y->expr));
        break;
    }

    case STATIC_FOR : {
        StaticFor *y = (StaticFor *)x.ptr();
        out = new StaticFor(y->variable, clone(y->values), clone(y->body));
        break;
    }

    case FINALLY : {
        Finally *y = (Finally *)x.ptr();
        out = new Finally(clone(y->body));
        break;
    }

    case ONERROR : {
        OnError *y = (OnError *)x.ptr();
        out = new OnError(clone(y->body));
        break;
    }

    case UNREACHABLE : {
        out = new Unreachable();
        break;
    }

    case EVAL_STATEMENT : {
        EvalStatement *eval = (EvalStatement *)x.ptr();
        out = new EvalStatement(eval->args);
        break;
    }

    case WITH : {
        WithStatement *with= (WithStatement*)x.ptr();
        out = new WithStatement(with->lhs, with->rhs, with->withLocation);
        break;
    }

    default :
        assert(false);

    }

    out->location = x->location;
    return out;
}

StatementPtr cloneOpt(StatementPtr x)
{
    if (!x)
        return NULL;
    return clone(x);
}

void clone(const vector<StatementPtr> &x, vector<StatementPtr> &out)
{
    for (unsigned i = 0; i < x.size(); ++i)
        out.push_back(clone(x[i]));
}

CaseBlockPtr clone(CaseBlockPtr x)
{
    CaseBlockPtr y = new CaseBlock(clone(x->caseLabels), clone(x->body));
    y->location = x->location;
    return y;
}

void clone(const vector<CaseBlockPtr> &x, vector<CaseBlockPtr> &out)
{
    for (unsigned i = 0; i < x.size(); ++i)
        out.push_back(clone(x[i]));
}

CatchPtr clone(CatchPtr x)
{
    CatchPtr y = new Catch(x->exceptionVar,
                           cloneOpt(x->exceptionType),
                           clone(x->body));
    y->location = x->location;
    return y;
}

void clone(const vector<CatchPtr> &x, vector<CatchPtr> &out)
{
    for (unsigned i = 0; i < x.size(); ++i)
        out.push_back(clone(x[i]));
}

}


text:
<?php

namespace Ecommit\UtilBundle\DependencyInjection;

use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class EcommitUtilExtension extends Extension
{

    /**
     * Loads a specific configuration.
     *
     * @param array $config An array of configuration values
     * @param ContainerBuilder $container A ContainerBuilder instance
     *
     * @throws \InvalidArgumentException When provided tag is not defined in this extension
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.xml');
    }
}


text:
import time

from state_machine_crawler import State as BaseState, transition, StateMachineCrawler

EXEC_TIME = 0

class State(BaseState):

    def verify(self):
        time.sleep(EXEC_TIME)
        self._system.visited(self.__class__.__name__)
        self._system.ok()

class InitialState(State):

    @transition(source_state=StateMachineCrawler.EntryPoint)
    def init(self):
        time.sleep(EXEC_TIME)
        self._system.enter()

class UnknownState(State):
    pass

class StateOne(State):

    @transition(source_state=InitialState)
    def from_initial_state(self):
        time.sleep(EXEC_TIME)
        self._system.unique()

    @transition(target_state="self")
    def reset(self):
        time.sleep(EXEC_TIME)
        self._system.reset()

class StateTwo(State):

    @transition(source_state=StateOne)
    def from_state_one(self):
        time.sleep(EXEC_TIME)
        self._system.unique()

class StateThreeVariantOne(State):

    @transition(source_state=StateTwo, cost=2)
    def move(self):
        time.sleep(EXEC_TIME)
        self._system.non_unique()

class StateThreeVariantTwo(State):

    @transition(source_state=StateTwo)
    def from_state_two(self):
        time.sleep(EXEC_TIME)
        self._system.unique()

class StateFour(State):

    @transition(source_state=StateThreeVariantOne)
    def from_v1(self):
        time.sleep(EXEC_TIME)
        self._system.non_unique()

    @transition(source_state=StateThreeVariantTwo)
    def from_v2(self):
        time.sleep(EXEC_TIME)
        self._system.non_unique()

    def verify(self):
        super(StateFour, self).verify()
        self._system.last_verify()

ALL_STATES = [
    InitialState,
    StateOne,
    StateTwo,
    StateThreeVariantOne,
    StateThreeVariantTwo,
    StateFour
]


text:
package de.bps.onyx.plugin.wsclient;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;

import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceFeature;

import de.bps.onyx.plugin.OnyxModule;

/**
 * This class was generated by the JAX-WS RI. JAX-WS RI 2.1.6 in JDK 6 Generated source version: 2.1
 */
@WebServiceClient(name = "PluginService", targetNamespace = "http://server.webservice.plugin.bps.de/")
public class PluginService extends Service {

	private final static URL PLUGINSERVICE_WSDL_LOCATION;
	private final static Logger logger = Logger.getLogger(de.bps.onyx.plugin.wsclient.PluginService.class.getName());

	static {
		URL url = null;
		try {
			URL baseUrl;
			baseUrl = de.bps.onyx.plugin.wsclient.PluginService.class.getResource(".");
			url = new URL(baseUrl, OnyxModule.getPluginWSLocation() + "?wsdl");
		} catch (final MalformedURLException e) {
			logger.warning("Failed to create URL for the wsdl Location: '" + OnyxModule.getPluginWSLocation() + "?wsdl', retrying as a local file");
			logger.warning(e.getMessage());
		}
		PLUGINSERVICE_WSDL_LOCATION = url;
	}

	public PluginService(final URL wsdlLocation, final QName serviceName) {
		super(wsdlLocation, serviceName);
	}

	public PluginService() {
		super(PLUGINSERVICE_WSDL_LOCATION, new QName("http://server.webservice.plugin.bps.de/", "PluginService"));
	}

	/**
	 * @return returns OnyxPluginServices
	 */
	@WebEndpoint(name = "OnyxPluginServicesPort")
	public OnyxPluginServices getOnyxPluginServicesPort() {
		return super.getPort(new QName("http://server.webservice.plugin.bps.de/", "OnyxPluginServicesPort"), OnyxPluginServices.class);
	}

	/**
	 * @param features A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the features parameter will have
	 *            their default values.
	 * @return returns OnyxPluginServices
	 */
	@WebEndpoint(name = "OnyxPluginServicesPort")
	public OnyxPluginServices getOnyxPluginServicesPort(final WebServiceFeature... features) {
		return super.getPort(new QName("http://server.webservice.plugin.bps.de/", "OnyxPluginServicesPort"), OnyxPluginServices.class, features);
	}

}


text:
#include "ms_windows/win_console_out.ipp"

namespace pt { namespace pcaetano { namespace bluesy {
namespace ms_windows {

template std::string ConvertOutput(char const* s);
template std::string ConvertOutput(std::basic_string<char> const& s);
template std::string ConvertOutput(wchar_t const* s);
template std::string ConvertOutput(std::basic_string<wchar_t> const& s);

} // namespace ms_windows
}}}