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

namespace GenericList
{
    /// <summary>
    /// Doubly generic linked list implementation
    /// </summary>
    /// <typeparam name="T">Type of elements</typeparam>
    public class GenericList<T> : IList<T>
    {
        private class Node
        {
            public T value;
            public Node next;
            public Node prev;

            public Node(T value, Node prev, Node next)
            {
                this.value = value;
                this.prev = prev;
                this.next = next;
            }
        }

        private Node head;
        private Node tail;
        private int size;

        /// <summary>
        /// Number of items in the list
        /// </summary>
        public int Count => size;

        public bool IsReadOnly => false;

        /// <summary>
        /// List indexer
        /// </summary>
        /// <param name="index">Element index</param>
        public T this[int index]
        {
            get
            {
                if (index > size || index < 0)
                {
                    throw new IndexOutOfRangeException("Incorrect index is entered.");
                }

                return GetValueByIndex(index);
            }
            set
            {
                if (index > size || index < 0)
                {
                    throw new IndexOutOfRangeException("Incorrect index is entered.");
                }

                SearchNodeByIndex(index).value = value;
            }
        }

        /// <summary>
        /// Search for the index of a given element
        /// </summary>
        /// <param name="item">Given element</param>
        /// <returns>index element</returns>
        public int IndexOf(T item)
        {
            Node current = head;
            int index = 0;
            while (current != null && !current.value.Equals(item))
            {
                current = current.next;
                ++index;
            }

            return index < size ? index: -1;
        }

        /// <summary>
        /// Adding a value at a specified index
        /// </summary>
        /// <param name="index">Item index</param>
        /// <param name="item">Added value</param>
        public void Insert(int index, T item)
        {
            if (index > size || index < 0)
            {
                throw new IndexOutOfRangeException("Incorrect index is entered.");
            }

            if (index == 0)
            {
                Node oldHead = head;
                head = new Node(item, null, oldHead);
            }
            else if (index == size)
            {
                tail.next = new Node(item, tail, null);
                tail = tail.next;
            }
            else
            {
                Node prevNewNode = SearchNodeByIndex(index - 1);
                prevNewNode.next = new Node(item, prevNewNode, prevNewNode.next);
            }

            ++size;
        }

        /// <summary>
        /// Deleting a value at a specified index
        /// </summary>
        /// <param name="index">Preset index</param>
        public void RemoveAt(int index)
        {
            if (index > size || index < 0)
            {
                throw new IndexOutOfRangeException("Incorrect index is entered.");
            }

            if (index == 0)
            {
                head = head.next;
            }
            else if (index == size - 1)
            {
                tail = tail.prev;
                tail.next = null;
            }
            else
            {
                Node prevDeletion = SearchNodeByIndex(index - 1);
                prevDeletion.next = prevDeletion.next.next;
            }

            --size;
        }

        /// <summary>
        /// Adding an item to the list
        /// </summary>
        public void Add(T item)
        {
            if (head == null)
            {
                head = new Node(item, null, null);
            }
            else if (tail == null)
            {
                tail = new Node(item, head, null);
                head.next = tail;
            }
            else
            {
                tail.next = new Node(item, tail, null);
                tail = tail.next;
            }

            ++size;
        }

        /// <summary>
        /// Clearing the list
        /// </summary>
        public void Clear()
        {
            head = null;
            tail = null;
            size = 0;
        }

        /// <summary>
        /// Checking the item's membership
        /// </summary>
        /// <param name="item">The item to be checked for membership in the list</param>
        /// <returns>Returns a boolean value depending on the value of the list</returns>
        public bool Contains(T item)
        {
            Node findElement = head;
            for (var i = 0; i < size; ++i)
            {
                if (findElement.value.Equals(item))
                {
                    return true;
                }

                findElement = findElement.next;
            }

            return false;
        }

        /// <summary>
        /// Copy list items to a specified array
        /// </summary>
        /// <param name="array">Specified array</param>
        /// <param name="arrayIndex">Array size</param>
        public void CopyTo(T[] array, int arrayIndex)
        {
            Node current = head;
            for (var i = arrayIndex; i < size; ++i)
            {
                array[i] = current.value;
                current = current.next;
            }
        }

        /// <summary>
        /// Removing an item from the list
        /// </summary>
        /// <param name="item"The item removing from the list></param>
        /// <returns>Returns true if the item was deleted otherwise false</returns>
        public bool Remove(T item)
        {
            var index = IndexOf(item);
            if (index == -1)
            {
                return false;
            }
            else
            {
                RemoveAt(index);
                return true;
            }
        }

        /// <summary>
        /// Getting the value at a given index
        /// </summary>
        /// <param name="index">The index of the search value in the list</param>
        /// <returns>Returns the value of the list at the specified index</returns>
        public T GetValueByIndex(int index)
        {
            if (index >= size || index < 0)
            {
                throw new IndexOutOfRangeException("Incorrect index is entered.");
            }

            Node iFindU = SearchNodeByIndex(index);
            return iFindU.value;
        }

        /// <summary>
        /// Returns the node at the specified index
        /// </summary>
        /// <param name="index">The index of the desired node</param>
        /// <returns>Returns the searched node</returns>
        private Node SearchNodeByIndex(int index)
        {
            Node iFindU = head;
            for (var i = 0; i < index; ++i)
            {
                iFindU = iFindU.next;
            }

            return iFindU;
        }

        public IEnumerator<T> GetEnumerator() => new ListEnumerator(this);

        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();

        private class ListEnumerator : IEnumerator<T>
        {
            private GenericList<T> list;
            private Node currentNode;

            public ListEnumerator(GenericList<T> list)
            {
                this.list = list;
            }

            public T Current
            {
                get => currentNode.value;
                set => currentNode.value = value;
            }

            public bool MoveNext()
            {
                if (currentNode == null)
                {
                    currentNode = list.head;
                }
                else
                {
                    currentNode = currentNode.next;
                }

                return currentNode != null;
            }

            public void Reset() => currentNode = null;

            object IEnumerator.Current => currentNode;

            public void Dispose()
            {
            }
        }
    }
}


text:
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using uBlog.Data;
using uBlog.Data.Entities;

namespace uBlog.Core.Services
{
    public class TagService : ITagService
    {
        IBlogContext context;

        public TagService(IBlogContext context)
        {
            this.context = context;
        }

        public Tag GetBySlug(string slug)
        {
            slug = slug.ToLower();
            var tag = context.Tags.SingleOrDefault(t => t.Slug == slug);
            return tag;
        }

        public List<Tag> GetAll()
        {
            var tags = context.Tags.OrderBy(t => t.Name).ToList();
            for (int i = 0; i < tags.Count; i++)
            {
                tags[i].PostTags = context.PostTags.Include(p => p.Post).Where(p => p.TagId == tags[i].Id).ToList();
            }
            return tags;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
include_recipe 'osl-mysql'

if node['osl-mysql']['enable_percona_client']
  include_recipe 'percona::client'
else
  mysql_client 'default' do
    package_name %w(mariadb mariadb-devel)
  end
end


text:
#ifndef ScriptCallStack_h
#define ScriptCallStack_h

#include "core/InspectorTypeBuilder.h"
#include "core/inspector/ScriptCallFrame.h"
#include "platform/heap/Handle.h"
#include "wtf/Forward.h"
#include "wtf/RefCounted.h"
#include "wtf/Vector.h"

namespace blink {

class ScriptAsyncCallStack;

class ScriptCallStack FINAL : public RefCountedWillBeGarbageCollectedFinalized<ScriptCallStack> {
    DECLARE_EMPTY_DESTRUCTOR_WILL_BE_REMOVED(ScriptCallStack);
public:
    static const size_t maxCallStackSizeToCapture = 200;

    static PassRefPtrWillBeRawPtr<ScriptCallStack> create(Vector<ScriptCallFrame>&);

    const ScriptCallFrame &at(size_t) const;
    size_t size() const;

    PassRefPtrWillBeRawPtr<ScriptAsyncCallStack> asyncCallStack() const;
    void setAsyncCallStack(PassRefPtrWillBeRawPtr<ScriptAsyncCallStack>);

    PassRefPtr<TypeBuilder::Array<TypeBuilder::Console::CallFrame> > buildInspectorArray() const;

    void trace(Visitor*);

private:
    explicit ScriptCallStack(Vector<ScriptCallFrame>&);

    Vector<ScriptCallFrame> m_frames;
    RefPtrWillBeMember<ScriptAsyncCallStack> m_asyncCallStack;
};

} // namespace blink

#endif // ScriptCallStack_h


text: i clone myself, so futuristic wow


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;

namespace Vendord.Desktop.WPF.App.ViewModel
{
    /// <summary>
    /// Represents an actionable item displayed by a View.
    /// </summary>
    public class CommandViewModel : ViewModelBase
    {
        public CommandViewModel(string displayName, ICommand command)
        {
            if (command == null)
                throw new ArgumentNullException("command");

            base.DisplayName = displayName;
            this.Command = command;
        }

        public ICommand Command { get; private set; }
    }
}


text:
#ifndef QATOMIC_POWER_H
#define QATOMIC_POWER_H

#include <QtCore/qoldbasicatomic.h>

QT_BEGIN_NAMESPACE

#if 0
// silence syncqt warnings
QT_END_NAMESPACE
QT_END_HEADER

#pragma qt_sync_skip_header_check
#pragma qt_sync_stop_processing
#endif

#define Q_ATOMIC_INT_REFERENCE_COUNTING_IS_ALWAYS_NATIVE

inline bool QBasicAtomicInt::isReferenceCountingNative()
{ return true; }
inline bool QBasicAtomicInt::isReferenceCountingWaitFree()
{ return false; }

#define Q_ATOMIC_INT_TEST_AND_SET_IS_ALWAYS_NATIVE

inline bool QBasicAtomicInt::isTestAndSetNative()
{ return true; }
inline bool QBasicAtomicInt::isTestAndSetWaitFree()
{ return false; }

#define Q_ATOMIC_INT_FETCH_AND_STORE_IS_ALWAYS_NATIVE

inline bool QBasicAtomicInt::isFetchAndStoreNative()
{ return true; }
inline bool QBasicAtomicInt::isFetchAndStoreWaitFree()
{ return false; }

#define Q_ATOMIC_INT_FETCH_AND_ADD_IS_ALWAYS_NATIVE

inline bool QBasicAtomicInt::isFetchAndAddNative()
{ return true; }
inline bool QBasicAtomicInt::isFetchAndAddWaitFree()
{ return false; }

#define Q_ATOMIC_POINTER_TEST_AND_SET_IS_ALWAYS_NATIVE

template <typename T>
Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::isTestAndSetNative()
{ return true; }
template <typename T>
Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::isTestAndSetWaitFree()
{ return false; }

#define Q_ATOMIC_POINTER_FETCH_AND_STORE_IS_ALWAYS_NATIVE

template <typename T>
Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::isFetchAndStoreNative()
{ return true; }
template <typename T>
Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::isFetchAndStoreWaitFree()
{ return false; }

#define Q_ATOMIC_POINTER_FETCH_AND_ADD_IS_ALWAYS_NATIVE

template <typename T>
Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::isFetchAndAddNative()
{ return true; }
template <typename T>
Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::isFetchAndAddWaitFree()
{ return false; }

#if defined(Q_CC_GNU)

#ifdef Q_PROCESSOR_POWER_32
#  define _Q_VALUE "0, %[_q_value]"
#  define _Q_VALUE_MEMORY_OPERAND "+m" (_q_value)
#  define _Q_VALUE_REGISTER_OPERAND [_q_value] "r" (&_q_value),
#else // Q_PROCESSOR_POWER_64
#  define _Q_VALUE "%y[_q_value]"
#  define _Q_VALUE_MEMORY_OPERAND [_q_value] "+Z" (_q_value)
#  define _Q_VALUE_REGISTER_OPERAND
#endif

inline bool QBasicAtomicInt::ref()
{
    int originalValue;
    int newValue;
    asm volatile("lwarx  %[originalValue]," _Q_VALUE "\n"
                 "addi   %[newValue], %[originalValue], %[one]\n"
                 "stwcx. %[newValue]," _Q_VALUE "\n"
                 "bne-   $-12\n"
                 : [originalValue] "=&b" (originalValue),
                   [newValue] "=&r" (newValue),
                   _Q_VALUE_MEMORY_OPERAND
                 : _Q_VALUE_REGISTER_OPERAND
                   [one] "i" (1)
                 : "cc", "memory");
    return newValue != 0;
}

inline bool QBasicAtomicInt::deref()
{
    int originalValue;
    int newValue;
    asm volatile("lwarx  %[originalValue]," _Q_VALUE "\n"
                 "addi   %[newValue], %[originalValue], %[minusOne]\n"
                 "stwcx. %[newValue]," _Q_VALUE "\n"
                 "bne-   $-12\n"
                 : [originalValue] "=&b" (originalValue),
                   [newValue] "=&r" (newValue),
                   _Q_VALUE_MEMORY_OPERAND
                 : _Q_VALUE_REGISTER_OPERAND
                   [minusOne] "i" (-1)
                 : "cc", "memory");
    return newValue != 0;
}

inline bool QBasicAtomicInt::testAndSetRelaxed(int expectedValue, int newValue)
{
    int result;
    asm volatile("lwarx  %[result]," _Q_VALUE "\n"
                 "xor.   %[result], %[result], %[expectedValue]\n"
                 "bne    $+12\n"
                 "stwcx. %[newValue]," _Q_VALUE "\n"
                 "bne-   $-16\n"
                 : [result] "=&r" (result),
                   _Q_VALUE_MEMORY_OPERAND
                 : _Q_VALUE_REGISTER_OPERAND
                   [expectedValue] "r" (expectedValue),
                   [newValue] "r" (newValue)
                 : "cc", "memory");
    return result == 0;
}

inline bool QBasicAtomicInt::testAndSetAcquire(int expectedValue, int newValue)
{
    int result;
    asm volatile("lwarx  %[result]," _Q_VALUE "\n"
                 "xor.   %[result], %[result], %[expectedValue]\n"
                 "bne    $+16\n"
                 "stwcx. %[newValue]," _Q_VALUE "\n"
                 "bne-   $-16\n"
                 "isync\n"
                 : [result] "=&r" (result),
                   _Q_VALUE_MEMORY_OPERAND
                 : _Q_VALUE_REGISTER_OPERAND
                   [expectedValue] "r" (expectedValue),
                   [newValue] "r" (newValue)
                 : "cc", "memory");
    return result == 0;
}

inline bool QBasicAtomicInt::testAndSetRelease(int expectedValue, int newValue)
{
    int result;
    asm volatile("eieio\n"
                 "lwarx  %[result]," _Q_VALUE "\n"
                 "xor.   %[result], %[result], %[expectedValue]\n"
                 "bne    $+12\n"
                 "stwcx. %[newValue]," _Q_VALUE "\n"
                 "bne-   $-16\n"
                 : [result] "=&r" (result),
                   _Q_VALUE_MEMORY_OPERAND
                 : _Q_VALUE_REGISTER_OPERAND
                   [expectedValue] "r" (expectedValue),
                   [newValue] "r" (newValue)
                 : "cc", "memory");
    return result == 0;
}

inline int QBasicAtomicInt::fetchAndStoreRelaxed(int newValue)
{
    int originalValue;
    asm volatile("lwarx  %[originalValue]," _Q_VALUE "\n"
                 "stwcx. %[newValue]," _Q_VALUE "\n"
                 "bne-   $-8\n"
                 : [originalValue] "=&r" (originalValue),
                   _Q_VALUE_MEMORY_OPERAND
                 : _Q_VALUE_REGISTER_OPERAND
                   [newValue] "r" (newValue)
                 : "cc", "memory");
    return originalValue;
}

inline int QBasicAtomicInt::fetchAndStoreAcquire(int newValue)
{
    int originalValue;
    asm volatile("lwarx  %[originalValue]," _Q_VALUE "\n"
                 "stwcx. %[newValue]," _Q_VALUE "\n"
                 "bne-   $-8\n"
                 "isync\n"
                 : [originalValue] "=&r" (originalValue),
                   _Q_VALUE_MEMORY_OPERAND
                 : _Q_VALUE_REGISTER_OPERAND
                   [newValue] "r" (newValue)
                 : "cc", "memory");
    return originalValue;
}

inline int QBasicAtomicInt::fetchAndStoreRelease(int newValue)
{
    int originalValue;
    asm volatile("eieio\n"
                 "lwarx  %[originalValue]," _Q_VALUE "\n"
                 "stwcx. %[newValue]," _Q_VALUE "\n"
                 "bne-   $-8\n"
                 : [originalValue] "=&r" (originalValue),
                   _Q_VALUE_MEMORY_OPERAND
                 : _Q_VALUE_REGISTER_OPERAND
                   [newValue] "r" (newValue)
                 : "cc", "memory");
    return originalValue;
}

inline int QBasicAtomicInt::fetchAndAddRelaxed(int valueToAdd)
{
    int originalValue;
    int newValue;
    asm volatile("lwarx  %[originalValue]," _Q_VALUE "\n"
                 "add    %[newValue], %[originalValue], %[valueToAdd]\n"
                 "stwcx. %[newValue]," _Q_VALUE "\n"
                 "bne-   $-12\n"
                 : [originalValue] "=&r" (originalValue),
                   [newValue] "=&r" (newValue),
                   _Q_VALUE_MEMORY_OPERAND
                 : _Q_VALUE_REGISTER_OPERAND
                   [valueToAdd] "r" (valueToAdd)
                 : "cc", "memory");
    return originalValue;
}

inline int QBasicAtomicInt::fetchAndAddAcquire(int valueToAdd)
{
    int originalValue;
    int newValue;
    asm volatile("lwarx  %[originalValue]," _Q_VALUE "\n"
                 "add    %[newValue], %[originalValue], %[valueToAdd]\n"
                 "stwcx. %[newValue]," _Q_VALUE "\n"
                 "bne-   $-12\n"
                 "isync\n"
                 : [originalValue] "=&r" (originalValue),
                   [newValue] "=&r" (newValue),
                   _Q_VALUE_MEMORY_OPERAND
                 : _Q_VALUE_REGISTER_OPERAND
                   [valueToAdd] "r" (valueToAdd)
                 : "cc", "memory");
    return originalValue;
}

inline int QBasicAtomicInt::fetchAndAddRelease(int valueToAdd)
{
    int originalValue;
    int newValue;
    asm volatile("eieio\n"
                 "lwarx  %[originalValue]," _Q_VALUE "\n"
                 "add    %[newValue], %[originalValue], %[valueToAdd]\n"
                 "stwcx. %[newValue]," _Q_VALUE "\n"
                 "bne-   $-12\n"
                 : [originalValue] "=&r" (originalValue),
                   [newValue] "=&r" (newValue),
                   _Q_VALUE_MEMORY_OPERAND
                 : _Q_VALUE_REGISTER_OPERAND
                   [valueToAdd] "r" (valueToAdd)
                 : "cc", "memory");
    return originalValue;
}

#ifdef Q_PROCESSOR_POWER_64
#  define LPARX "ldarx"
#  define STPCX "stdcx."
#else
#  define LPARX "lwarx"
#  define STPCX "stwcx."
#endif

template <typename T>
Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::testAndSetRelaxed(T *expectedValue, T *newValue)
{
    void *result;
    asm volatile(LPARX"  %[result]," _Q_VALUE "\n"
                 "xor.   %[result], %[result], %[expectedValue]\n"
                 "bne    $+12\n"
                 STPCX"  %[newValue]," _Q_VALUE "\n"
                 "bne-   $-16\n"
                 : [result] "=&r" (result),
                   _Q_VALUE_MEMORY_OPERAND
                 : _Q_VALUE_REGISTER_OPERAND
                   [expectedValue] "r" (expectedValue),
                   [newValue] "r" (newValue)
                 : "cc", "memory");
    return result == 0;
}

template <typename T>
Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::testAndSetAcquire(T *expectedValue, T *newValue)
{
    void *result;
    asm volatile(LPARX"  %[result]," _Q_VALUE "\n"
                 "xor.   %[result], %[result], %[expectedValue]\n"
                 "bne    $+16\n"
                 STPCX"  %[newValue]," _Q_VALUE "\n"
                 "bne-   $-16\n"
                 "isync\n"
                 : [result] "=&r" (result),
                   _Q_VALUE_MEMORY_OPERAND
                 : _Q_VALUE_REGISTER_OPERAND
                   [expectedValue] "r" (expectedValue),
                   [newValue] "r" (newValue)
                 : "cc", "memory");
    return result == 0;
}

template <typename T>
Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::testAndSetRelease(T *expectedValue, T *newValue)
{
    void *result;
    asm volatile("eieio\n"
                 LPARX"  %[result]," _Q_VALUE "\n"
                 "xor.   %[result], %[result], %[expectedValue]\n"
                 "bne    $+12\n"
                 STPCX"  %[newValue]," _Q_VALUE "\n"
                 "bne-   $-16\n"
                 : [result] "=&r" (result),
                   _Q_VALUE_MEMORY_OPERAND
                 : _Q_VALUE_REGISTER_OPERAND
                   [expectedValue] "r" (expectedValue),
                   [newValue] "r" (newValue)
                 : "cc", "memory");
    return result == 0;
}

template <typename T>
Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndStoreRelaxed(T *newValue)
{
    T *originalValue;
    asm volatile(LPARX"  %[originalValue]," _Q_VALUE "\n"
                 STPCX"  %[newValue]," _Q_VALUE "\n"
                 "bne-   $-8\n"
                 : [originalValue] "=&r" (originalValue),
                   _Q_VALUE_MEMORY_OPERAND
                 : _Q_VALUE_REGISTER_OPERAND
                   [newValue] "r" (newValue)
                 : "cc", "memory");
    return originalValue;
}

template <typename T>
Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndStoreAcquire(T *newValue)
{
    T *originalValue;
    asm volatile(LPARX"  %[originalValue]," _Q_VALUE "\n"
                 STPCX"  %[newValue]," _Q_VALUE "\n"
                 "bne-   $-8\n"
                 "isync\n"
                 : [originalValue] "=&r" (originalValue),
                   _Q_VALUE_MEMORY_OPERAND
                 : _Q_VALUE_REGISTER_OPERAND
                   [newValue] "r" (newValue)
                 : "cc", "memory");
    return originalValue;
}

template <typename T>
Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndStoreRelease(T *newValue)
{
    T *originalValue;
    asm volatile("eieio\n"
                 LPARX"  %[originalValue]," _Q_VALUE "\n"
                 STPCX"  %[newValue]," _Q_VALUE "\n"
                 "bne-   $-8\n"
                 : [originalValue] "=&r" (originalValue),
                   _Q_VALUE_MEMORY_OPERAND
                 : _Q_VALUE_REGISTER_OPERAND
                   [newValue] "r" (newValue)
                 : "cc", "memory");
    return originalValue;
}

template <typename T>
Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndAddRelaxed(qptrdiff valueToAdd)
{
    T *originalValue;
    T *newValue;
    asm volatile(LPARX"  %[originalValue]," _Q_VALUE "\n"
                 "add    %[newValue], %[originalValue], %[valueToAdd]\n"
                 STPCX"  %[newValue]," _Q_VALUE "\n"
                 "bne-   $-12\n"
                 : [originalValue] "=&r" (originalValue),
                   [newValue] "=&r" (newValue),
                   _Q_VALUE_MEMORY_OPERAND
                 : _Q_VALUE_REGISTER_OPERAND
                   [valueToAdd] "r" (valueToAdd * sizeof(T))
                 : "cc", "memory");
    return originalValue;
}

template <typename T>
Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndAddAcquire(qptrdiff valueToAdd)
{
    T *originalValue;
    T *newValue;
    asm volatile(LPARX"  %[originalValue]," _Q_VALUE "\n"
                 "add    %[newValue], %[originalValue], %[valueToAdd]\n"
                 STPCX"  %[newValue]," _Q_VALUE "\n"
                 "bne-   $-12\n"
                 "isync\n"
                 : [originalValue] "=&r" (originalValue),
                   [newValue] "=&r" (newValue),
                   _Q_VALUE_MEMORY_OPERAND
                 : _Q_VALUE_REGISTER_OPERAND
                   [valueToAdd] "r" (valueToAdd * sizeof(T))
                 : "cc", "memory");
    return originalValue;
}

template <typename T>
Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndAddRelease(qptrdiff valueToAdd)
{
    T *originalValue;
    T *newValue;
    asm volatile("eieio\n"
                 LPARX"  %[originalValue]," _Q_VALUE "\n"
                 "add    %[newValue], %[originalValue], %[valueToAdd]\n"
                 STPCX"  %[newValue]," _Q_VALUE "\n"
                 "bne-   $-12\n"
                 : [originalValue] "=&r" (originalValue),
                   [newValue] "=&r" (newValue),
                   _Q_VALUE_MEMORY_OPERAND
                 : _Q_VALUE_REGISTER_OPERAND
                   [valueToAdd] "r" (valueToAdd * sizeof(T))
                 : "cc", "memory");
    return originalValue;
}

#undef LPARX
#undef STPCX
#undef _Q_VALUE
#undef _Q_VALUE_MEMORY_OPERAND
#undef _Q_VALUE_REGISTER_OPERAND

#else
#  error "This compiler for Power/PowerPC is not supported"
#endif

inline bool QBasicAtomicInt::testAndSetOrdered(int expectedValue, int newValue)
{
    return testAndSetAcquire(expectedValue, newValue);
}

inline int QBasicAtomicInt::fetchAndStoreOrdered(int newValue)
{
    return fetchAndStoreAcquire(newValue);
}

inline int QBasicAtomicInt::fetchAndAddOrdered(int valueToAdd)
{
    return fetchAndAddAcquire(valueToAdd);
}

template <typename T>
Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::testAndSetOrdered(T *expectedValue, T *newValue)
{
    return testAndSetAcquire(expectedValue, newValue);
}

template <typename T>
Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndStoreOrdered(T *newValue)
{
    return fetchAndStoreAcquire(newValue);
}

template <typename T>
Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndAddOrdered(qptrdiff valueToAdd)
{
    return fetchAndAddAcquire(valueToAdd);
}

QT_END_NAMESPACE

#endif // QATOMIC_POWER_H


text:
std::tuple<ID3D11Device&, ID3D11DeviceContext&> GetDevice()
{
    static dx::DeviceContext3DPair device = dx::MakeDevice3D();
    return {dx::Ref(device.first), dx::Ref(device.second)};
}


text:
package eu.atos.sla.datamodel;

import java.util.List;

public interface IProvider {

	/*
	 * Internal generated id
	 */
	Long getId();

	/**
	 * The provider is recognized by external parties by this UUID
	 */
	String getUuid();

	/**
	 * Provider's name
	 */
	String getName();

	void setId(Long id);

	/**
	 * The provider is recognized by external parties by this UUID
	 */
	void setUuid(String uuid);

	/**
	 * Provider's name
	 */
	void setName(String name);

	/**
	 * Template list
	 */
	public List<ITemplate> getTemplates();
	public void setTemplates(List<ITemplate> templates);
	public void addTemplate(ITemplate template);
}


text:
const gridNumberOfColumns = 30;
const usefulWidth = 1400;
const gridColumnWidth = usefulWidth / gridNumberOfColumns;

/*--------------*/

module.exports = {
  _namespace: 'layout',
  gridNumberOfColumns: gridNumberOfColumns,
  usefulWidth: usefulWidth,
  gridColumnWidth: gridColumnWidth,
  gutter: 20,
  gridSectionNumberOfColumns: 28,
  gridContainerNumberOfColumns: 30,
  gridCompactContainerNumberOfColumns: 12,
  sectionMargin: 100,
  sectionMarginBig: 100,
  screenHeightIdeal: 800,
  headerBlockHeight: 500,

};


text:
"""
Core Haystack Session client object interface.  This file defines an abstract
interface for Project Haystack clients and is responsible for opening and
maintaining a session with the server.
"""

import logging
import hszinc
import weakref
from threading import Lock
from six import string_types

from .http import sync
from .ops import grid as grid_ops
from .ops import entity as entity_ops
from .ops import his as his_ops
from .ops import feature as feature_ops
from .entity.models.haystack import HaystackTaggingModel

class HaystackSession(object):
    """
    The Haystack Session handler is responsible for presenting an API for
    querying and controlling a Project Haystack server.

    HaystackSession itself is the base class, which is then implemented by way
    of HaystackOperation subclasses which are instantiated by the session
    object before being started and returned.

    These operations by default are specified by class member references
    to the classes concerned.

    Methods for Haystack operations return an 'Operation' object, which
    may be used in any of two ways:

    - as a synchronous result placeholder by calling its `wait` method
    followed by inspection of its `result` attribute.
    - as an asynchronous call manager by connecting a "slot" (`callable`
    that takes keyword arguments) to the `done_sig` signal.

    The base class takes some arguments that control the default behaviour of
    the object.
    """

    # Operation references
    _GET_GRID_OPERATION = grid_ops.GetGridOperation
    _POST_GRID_OPERATION = grid_ops.PostGridOperation
    _GET_ENTITY_OPERATION = entity_ops.GetEntityOperation
    _FIND_ENTITY_OPERATION = entity_ops.FindEntityOperation

    _HIS_READ_SERIES_OPERATION = his_ops.HisReadSeriesOperation
    _HIS_READ_FRAME_OPERATION = his_ops.HisReadFrameOperation
    _HIS_WRITE_SERIES_OPERATION = his_ops.HisWriteSeriesOperation
    _HIS_WRITE_FRAME_OPERATION = his_ops.HisWriteFrameOperation

    _HAS_FEATURES_OPERATION = feature_ops.HasFeaturesOperation

    def __init__(
        self,
        uri,
        api_dir,
        grid_format=hszinc.MODE_ZINC,
        http_client=sync.SyncHttpClient,
        http_args=None,
        tagging_model=HaystackTaggingModel,
        log=None,
        pint=False,
        cache_expiry=3600.0,
    ):
        """
        Initialise a base Project Haystack session handler.

        :param uri: Base URI for the Haystack installation.
        :param api_dir: Subdirectory relative to URI where API calls are made.
        :param grid_format: What format to use for grids in GET/POST requests?
        :param http_client: HTTP client class to use.
        :param http_args: Optional HTTP client arguments to configure.
        :param tagging_model: Entity Tagging model in use.
        :param log: Logging object for reporting messages.
        :param pint: Configure hszinc to use basic quantity or Pint Quanity
        :param cache_expiry: Number of seconds before cached data expires.

        See : https://pint.readthedocs.io/ for details about pint
        """
        if log is None:
            log = logging.getLogger("pyhaystack.client.%s" % self.__class__.__name__)
        self._log = log

        if http_args is None:
            http_args = {}

        # Configure hszinc to use pint or not for Quantity definition
        self.config_pint(pint)

        if grid_format not in (hszinc.MODE_ZINC, hszinc.MODE_JSON):
            raise ValueError("Unrecognised grid format %s" % grid_format)
        self._grid_format = grid_format

        # Create the HTTP client object
        if bool(http_args.pop("debug", None)) and ("log" not in http_args):
            http_args["log"] = log.getChild("http_client")
        self._client = http_client(uri=uri, **http_args)
        self._api_dir = api_dir

        # Current in-progress authentication operation, if any.
        self._auth_op = None

        # Entity references, stored as weakrefs
        self._entities = weakref.WeakValueDictionary()

        # Tagging model in use
        self._tagging_model = tagging_model(self)

        # Grid cache
        self._grid_lk = Lock()
        self._grid_expiry = cache_expiry
        self._grid_cache = {}  # 'op' -> (op, expiry, grid)

    # Public methods/properties

    def authenticate(self, callback=None):
        """
        Authenticate with the Project Haystack server.  If an authentication
        attempt is in progress, we return it, otherwise we instantiate a new
        one.
        """
        if self._auth_op is not None:
            auth_op = self._auth_op()
        else:
            auth_op = None

        new = auth_op is None
        if new:
            auth_op = self._AUTH_OPERATION(self)
            auth_op.done_sig.connect(self._on_authenticate_done)

        if callback is not None:
            if auth_op.is_done:
                # Already done
                return callback(auth_op)
            else:
                auth_op.done_sig.connect(callback)

        if new:
            auth_op.go()
            self._auth_op = weakref.ref(auth_op)

        return auth_op

    def about(self, cache=True, callback=None):
        """
        Retrieve the version information of this Project Haystack server.
        """
        return self._on_about(cache=cache, callback=callback)

    def ops(self, cache=True, callback=None):
        """
        Retrieve the operations supported by this Project Haystack server.
        """
        return self._on_ops(cache=cache, callback=callback)

    def formats(self, cache=True, callback=None):
        """
        Retrieve the grid formats supported by this Project Haystack server.
        """
        return self._on_formats(cache=cache, callback=callback)

    def read(self, ids=None, filter_expr=None, limit=None, callback=None):
        """
        Retrieve information on entities matching the given criteria.
        Either ids or filter_expr may be given.  ids may be given as a
        list or as a single ID string/reference.

        filter_expr is given as a string.  pyhaystack.util.filterbuilder
        may be useful for generating these programatically.

        :param id: ID of a single entity to retrieve
        :param ids: IDs of many entities to retrieve as a list
        :param filter_expr: A filter expression that describes the entities
                            of interest.
        :param limit: A limit on the number of entities to return.
        """
        return self._on_read(
            ids=ids, filter_expr=filter_expr, limit=limit, callback=callback
        )

    def nav(self, nav_id=None, callback=None):
        """
        The nav op is used navigate a project for learning and discovery. This
        operation allows servers to expose the database in a human-friendly
        tree (or graph) that can be explored.
        """
        return self._on_nav(nav_id=nav_id, callback=callback)

    def watch_sub(
        self, points, watch_id=None, watch_dis=None, lease=None, callback=None
    ):
        """
        This creates a new watch with debug string watch_dis, identifier
        watch_id (string) and a lease time of lease (integer) seconds.  points
        is a list of strings, Entity objects or hszinc.Ref objects.
        """
        return self._on_watch_sub(
            points=points,
            watch_id=watch_id,
            watch_dis=watch_dis,
            lease=lease,
            callback=callback,
        )

    def watch_unsub(self, watch, points=None, callback=None):
        """
        watch is either the value of watch_id given when creating a watch, or
        an instance of a Watch object.

        If points is not None, it is a list of strings, Entity objects or
        hszinc.Ref objects which will be removed from the Watch object.
        Otherwise, it closes the Watch object.
        """
        return self._on_watch_unsub(watch=watch, points=points, callback=callback)

    def watch_poll(self, watch, refresh=False, callback=None):
        """
        watch is either the value of watch_id given when creating a watch, or
        an instance of a Watch object.

        If refresh is True, then all points on the watch will be updated, not
        just those that have changed since the last poll.
        """
        return self._on_watch_poll(watch=watch, refresh=refresh, callback=callback)

    def point_write(
        self, point, level=None, val=None, who=None, duration=None, callback=None
    ):
        """
        point is either the ID of the writeable point entity, or an instance of
        the writeable point entity to retrieve the write status of or write a
        value to.

        If level is None, the other parameters are required to be None too, the
        write status of the point is retrieved.  Otherwise, a write is
        performed to the nominated point.
        """
        who = who or self._username
        return self._on_point_write(
            point=point,
            level=level,
            val=val,
            who=who,
            duration=duration,
            callback=callback,
        )

    def his_read(self, point, rng, callback=None):
        """
        point is either the ID of the historical point entity, or an instance
        of the historical point entity to read historical from.  rng is
        either a string describing a time range (e.g. "today", "yesterday"), a
        datetime.date object (providing all samples on the nominated day), a
        datetime.datetime (providing all samples since the nominated time) or a
        slice of datetime.dates or datetime.datetimes.
        """
        return self._on_his_read(point=point, rng=rng, callback=callback)

    def his_write(self, point, timestamp_records, callback=None):
        """
        point is either the ID of the writeable historical point entity, or an
        instance of the writeable historical point entity to write historical
        data to.  timestamp_records should be a dict mapping timestamps
        (datetime.datetime) to the values to be written at those times, or a
        Pandas Series object.
        """
        return self._on_his_write(
            point=point, timestamp_records=timestamp_records, callback=callback
        )

    def invoke_action(self, entity, action, callback=None, **kwargs):
        """
        entity is either the ID of the entity, or an instance of the entity to
        invoke the named action on.  Keyword arguments give any additional
        parameters required for the user action.
        """
        return self._on_invoke_action(
            entity=entity, action=action, callback=callback, action_args=kwargs
        )

    def get_entity(self, ids, refresh=False, single=None, callback=None):
        """
        Retrieve instances of entities, possibly refreshing them.

        :param ids: A single entity ID, or a list of entity IDs.
        :param refresh: Do we refresh the tags on those entities?
        :param single: Are we expecting a single entity?  Defaults to
                       True if `ids` is not a list.
        :param callback: Asynchronous result callback.
        """
        if isinstance(ids, string_types) or isinstance(ids, hszinc.Ref):
            # Make sure we always pass a list.
            ids = [ids]
            if single is None:
                single = True
        elif single is None:
            single = False

        op = self._GET_ENTITY_OPERATION(self, ids, refresh, single)
        if callback is not None:
            op.done_sig.connect(callback)
        op.go()
        return op

    def find_entity(self, filter_expr, limit=None, single=False, callback=None):
        """
        Retrieve instances of entities that match a filter expression.

        :param filter_expr: The filter expression to search for.
        :param limit: Optional limit to number of entities retrieved.
        :param single: Are we expecting a single entity?  Defaults to
                       True if `ids` is not a list.
        :param callback: Asynchronous result callback.
        """
        op = self._FIND_ENTITY_OPERATION(self, filter_expr, limit, single)
        if callback is not None:
            op.done_sig.connect(callback)
        op.go()
        return op

    def his_read_series(self, point, rng, tz=None, series_format=None, callback=None):
        """
        Read the historical data of the given point and return it as a series.

        :param point: Haystack 'point' entity to read the data from
        :param rng: Historical read range for the 'point'
        :param tz: Optional timezone to translate timestamps to
        :param series_format: Optional desired format for the series
        """
        if series_format is None:
            if his_ops.HAVE_PANDAS:
                series_format = self._HIS_READ_SERIES_OPERATION.FORMAT_SERIES
            else:
                series_format = self._HIS_READ_SERIES_OPERATION.FORMAT_LIST

        op = self._HIS_READ_SERIES_OPERATION(self, point, rng, tz, series_format)
        if callback is not None:
            op.done_sig.connect(callback)
        op.go()
        return op

    def his_write_series(self, point, series, tz=None, callback=None):
        """
        Write the historical data of the given point.

        :param point: Haystack 'point' entity to read the data from
        :param series: Historical series data to write
        :param tz: Optional timezone to translate timestamps to
        """
        op = self._HIS_WRITE_SERIES_OPERATION(self, point, series, tz)
        if callback is not None:
            op.done_sig.connect(callback)
        op.go()
        return op

    def his_read_frame(self, columns, rng, tz=None, frame_format=None, callback=None):
        """
        Read the historical data of multiple given points and return
        them as a data frame.

        :param columns: A list of Haystack 'point' instances or a dict mapping
                        the column label to the Haystack 'point' instance.
        :param rng: Historical read range for the 'point'
        :param tz: Optional timezone to translate timestamps to
        :param frame_format: Optional desired format for the data frame
        """
        if frame_format is None:
            if his_ops.HAVE_PANDAS:
                frame_format = self._HIS_READ_FRAME_OPERATION.FORMAT_FRAME
            else:
                frame_format = self._HIS_READ_FRAME_OPERATION.FORMAT_LIST

        op = self._HIS_READ_FRAME_OPERATION(self, columns, rng, tz, frame_format)
        if callback is not None:
            op.done_sig.connect(callback)
        op.go()
        return op

    def his_write_frame(self, frame, columns=None, tz=None, callback=None):
        """
        Write the historical data of multiple given points.

        :param frame: Data frame to write to.  Columns either list explicit
                        entity IDs or column aliases which are mapped in the
                        columns parameter.
        :param columns: If frame does not list explicit IDs, this should be a
                        dict mapping the column names to either entity IDs or
                        entity instances.
        :param tz: Reference timestamp to use for writing, default is UTC.
        """
        op = self._HIS_WRITE_FRAME_OPERATION(self, columns, frame, tz)
        if callback is not None:
            op.done_sig.connect(callback)
        op.go()
        return op

    @property
    def site(self):
        """
        This helper will return the first site found on the server.
        This case is typical : having one site per server.
        """
        sites = self.find_entity("site").result
        return sites[list(sites.keys())[0]]

    @property
    def sites(self):
        """
        This helper will return all sites found on the server.
        """
        sites = self.find_entity("site").result
        return sites

    # Extension feature support.
    FEATURE_HISREAD_MULTI = "hisRead/multi"  # Multi-point hisRead
    FEATURE_HISWRITE_MULTI = "hisWrite/multi"  # Multi-point hisWrite
    FEATURE_ID_UUID = "id_uuid"

    def has_features(self, features, cache=True, callback=None):
        """
        Determine if a given feature is supported.  This is a helper function
        for determining if the server implements a given feature.  The feature
        is given as a string in the form of "base_feature/extension".

        Result is a dict of features and the states (boolean).

        :param features: Features to check for.
        """
        op = self._HAS_FEATURES_OPERATION(self, features, cache=cache)
        if callback is not None:
            op.done_sig.connect(callback)
        op.go()
        return op

    # Protected methods/properties

    def _on_about(self, cache, callback, **kwargs):
        return self._get_grid("about", callback, cache=cache, **kwargs)

    def _on_ops(self, cache, callback, **kwargs):
        return self._get_grid("ops", callback, cache=cache, **kwargs)

    def _on_formats(self, cache, callback, **kwargs):
        return self._get_grid("formats", callback, cache=cache, **kwargs)

    def _on_read(self, ids, filter_expr, limit, callback, **kwargs):
        if isinstance(ids, string_types) or isinstance(ids, hszinc.Ref):
            # Make sure we always pass a list.
            ids = [ids]

        if bool(ids):
            if filter_expr is not None:
                raise ValueError("Either specify ids or filter_expr, not both")

            ids = [self._obj_to_ref(r) for r in ids]

            if len(ids) == 1:
                # Reading a single entity
                return self._get_grid("read", callback, args={"id": ids[0]}, **kwargs)
            else:
                # Reading several entities
                grid = hszinc.Grid()
                grid.column["id"] = {}
                grid.extend([{"id": r} for r in ids])
                return self._post_grid("read", grid, callback, **kwargs)
        else:
            args = {"filter": filter_expr}
            if limit is not None:
                args["limit"] = int(limit)

            return self._get_grid("read", callback, args=args, **kwargs)

    def _on_nav(self, nav_id, callback, **kwargs):
        return self._get_grid("nav", callback, args={"nav_id": nav_id}, **kwargs)

    def _on_watch_sub(self, points, watch_id, watch_dis, lease, callback, **kwargs):
        grid = hszinc.Grid()
        grid.column["id"] = {}
        grid.extend([{"id": self._obj_to_ref(p)} for p in points])
        if watch_id is not None:
            grid.metadata["watchId"] = watch_id
        if watch_dis is not None:
            grid.metadata["watchDis"] = watch_dis
        if lease is not None:
            grid.metadata["lease"] = lease
        return self._post_grid("watchSub", grid, callback, **kwargs)

    def _on_watch_unsub(self, watch, points, callback, **kwargs):
        grid = hszinc.Grid()
        grid.column["id"] = {}

        if not isinstance(watch, string_types):
            watch = watch.id
        grid.metadata["watchId"] = watch

        if points is not None:
            grid.extend([{"id": self._obj_to_ref(p)} for p in points])
        else:
            grid.metadata["close"] = hszinc.MARKER
        return self._post_grid("watchSub", grid, callback, **kwargs)

    def _on_watch_poll(self, watch, refresh, callback, **kwargs):
        grid = hszinc.Grid()
        grid.column["empty"] = {}

        if not isinstance(watch, string_types):
            watch = watch.id
        grid.metadata["watchId"] = watch
        return self._post_grid("watchPoll", grid, callback, **kwargs)

    def _on_point_write(self, point, level, val, who, duration, callback, **kwargs):
        args = {"id": self._obj_to_ref(point)}
        if level is None:
            if (val is not None) or (who is not None) or (duration is not None):
                raise ValueError(
                    "If level is None, val, who and duration must " "be None too."
                )
        else:
            args.update({"level": level, "val": val})
            if who is not None:
                args["who"] = who
            if duration is not None:
                args["duration"] = duration
        return self._get_grid("pointWrite", callback, args=args, **kwargs)
        # Won't work in for nhaystack... putting that on old
        # return self._post_grid("pointWrite", grid_ops.dict_to_grid(args), callback, expect_format=hszinc.MODE_ZINC, args=args, **kwargs)

    def _on_his_read(self, point, rng, callback, **kwargs):
        if isinstance(rng, slice):
            str_rng = ",".join([hszinc.dump_scalar(p) for p in (rng.start, rng.stop)])
        elif not isinstance(rng, string_types):
            str_rng = hszinc.dump_scalar(rng)
        else:
            # Better be valid!
            # str_rng = rng
            str_rng = hszinc.dump_scalar(rng, mode=hszinc.MODE_ZINC)

        return self._get_grid(
            "hisRead",
            callback,
            args={"id": self._obj_to_ref(point), "range": str_rng},
            **kwargs
        )

    def _on_his_write(
        self, point, timestamp_records, callback, post_format=hszinc.MODE_ZINC, **kwargs
    ):
        grid = hszinc.Grid()
        grid.metadata["id"] = self._obj_to_ref(point)
        grid.column["ts"] = {}
        grid.column["val"] = {}

        if hasattr(timestamp_records, "to_dict"):
            timestamp_records = timestamp_records.to_dict()

        timestamp_records = list(timestamp_records.items())
        timestamp_records.sort(key=lambda rec: rec[0])
        for (ts, val) in timestamp_records:
            grid.append({"ts": ts, "val": val})

        return self._post_grid(
            "hisWrite", grid, callback, post_format=post_format, **kwargs
        )

    def _on_invoke_action(
        self,
        entity,
        action,
        callback,
        action_args,
        post_format=hszinc.MODE_ZINC,
        **kwargs
    ):
        grid = hszinc.Grid()
        grid.metadata["id"] = self._obj_to_ref(entity)
        grid.metadata["action"] = action
        for arg in action_args.keys():
            grid.column[arg] = {}
        grid.append(action_args)

        return self._post_grid(
            "invokeAction", grid, callback, post_format=post_format, **kwargs
        )

    def _get(self, uri, callback, api=True, **kwargs):
        """
        Perform a raw HTTP GET operation.  This is a convenience wrapper around
        the HTTP client class that allows pre/post processing of the request by
        the session instance.
        """
        if api:
            uri = "%s/%s" % (self._api_dir, uri)
        return self._client.get(uri, callback, **kwargs)

    def _get_grid(self, uri, callback, expect_format=None, cache=False, **kwargs):
        """
        Perform a HTTP GET of a grid.
        """
        if expect_format is None:
            expect_format = self._grid_format
        op = self._GET_GRID_OPERATION(
            self, uri, expect_format=expect_format, cache=cache, **kwargs
        )
        if callback is not None:
            op.done_sig.connect(callback)
        op.go()
        return op

    def _post(
        self,
        uri,
        callback,
        body=None,
        body_type=None,
        body_size=None,
        headers=None,
        api=True,
        **kwargs
    ):
        """
        Perform a raw HTTP POST operation.  This is a convenience wrapper around
        the HTTP client class that allows pre/post processing of the request by
        the session instance.
        """
        if api:
            uri = "%s/%s" % (self._api_dir, uri)
        return self._client.post(
            uri=uri,
            callback=callback,
            body=body,
            body_type=body_type,
            body_size=body_size,
            headers=headers,
            **kwargs
        )

    def _post_grid(
        self, uri, grid, callback, post_format=None, expect_format=None, **kwargs
    ):
        """
        Perform a HTTP POST of a grid.
        """
        if expect_format is None:
            expect_format = self._grid_format
        if post_format is None:
            post_format = self._grid_format
        op = self._POST_GRID_OPERATION(
            self,
            uri,
            grid,
            expect_format=expect_format,
            post_format=post_format,
            **kwargs
        )
        if callback is not None:
            op.done_sig.connect(callback)
        op.go()
        return op

    def _obj_to_ref(self, obj):
        """
        Convert an arbitrary object referring to an entity to an entity
        reference.
        """
        if isinstance(obj, hszinc.Ref):
            return obj
        if isinstance(obj, string_types):
            return hszinc.Ref(obj)
        if hasattr(obj, "id"):
            return obj.id
        raise NotImplementedError(
            "Don't know how to get the ID from a %s" % obj.__class__.__name__
        )

    # Private methods/properties

    def _on_authenticate_done(self, operation, **kwargs):
        """
        Process the result of an authentication operation.  This needs to be
        implemented in the subclass and should, at minimum, set a flag in the
        subclass to indicate the authentication state and clear the _auth_op
        attribute on the base class.
        """
        raise NotImplementedError("To be implemented in %s" % self.__class__.__name__)

    def config_pint(self, value=False):
        if value:
            self._use_pint = True
        else:
            self._use_pint = False
        hszinc.use_pint(self._use_pint)

    def logout(self):
        raise NotImplementedError("Must be defined depending on each implementation")

    def __enter__(self):
        """Entering context manager

        usage:
        with WhateverSession(uri, username, password, **kwargs) as session:
            # do whatever with session

        """

        return self

    def __exit__(self, _type, value, traceback):
        """On exit, call the logout procedure defined in the class"""
        self.logout()


text:
import { getElements, scrollTo, isTruthy } from '../util';

/**
 * When editing an object, it is sometimes desirable to customize the form action *without*
 * overriding the form's `submit` event. For example, the 'Save & Continue' button. We don't want
 * to use the `formaction` attribute on that element because it will be included on the form even
 * if the button isn't clicked.
 *
 * @example
 * ```html
 * <button type="button" return-url="/special-url/">
 *   Save & Continue
 * </button>
 * ```
 *
 * @param event Click event.
 */
function handleSubmitWithReturnUrl(event: MouseEvent): void {
  const element = event.target as HTMLElement;
  if (element.tagName === 'BUTTON') {
    const button = element as HTMLButtonElement;
    const action = button.getAttribute('return-url');
    const form = button.form;
    if (form !== null && isTruthy(action)) {
      form.action = action;
      form.submit();
    }
  }
}

function handleFormSubmit(event: Event, form: HTMLFormElement): void {
  // Track the names of each invalid field.
  const invalids = new Set<string>();

  for (const element of form.querySelectorAll<FormControls>('*[name]')) {
    if (!element.validity.valid) {
      invalids.add(element.name);
      // If the field is invalid, but doesn't contain the .is-invalid class, add it.
      if (!element.classList.contains('is-invalid')) {
        element.classList.add('is-invalid');
      }
    } else {
      // If the field is valid, but contains the .is-invalid class, remove it.
      if (element.classList.contains('is-invalid')) {
        element.classList.remove('is-invalid');
      }
    }
  }

  if (invalids.size !== 0) {
    // If there are invalid fields, pick the first field and scroll to it.
    const firstInvalid = form.elements.namedItem(Array.from(invalids)[0]) as Element;
    scrollTo(firstInvalid);

    // If the form has invalid fields, don't submit it.
    event.preventDefault();
  }
}

/**
 * Attach event listeners to form buttons with the `return-url` attribute present.
 */
function initReturnUrlSubmitButtons(): void {
  for (const button of getElements<HTMLButtonElement>('button[return-url]')) {
    button.addEventListener('click', handleSubmitWithReturnUrl);
  }
}

/**
 * Attach an event listener to each form's submitter (button[type=submit]). When called, the
 * callback checks the validity of each form field and adds the appropriate Bootstrap CSS class
 * based on the field's validity.
 */
export function initFormElements(): void {
  for (const form of getElements('form')) {
    // Find each of the form's submitters. Most object edit forms have a "Create" and
    // a "Create & Add", so we need to add a listener to both.
    const submitters = form.querySelectorAll<HTMLButtonElement>('button[type=submit]');

    for (const submitter of submitters) {
      // Add the event listener to each submitter.
      submitter.addEventListener('click', (event: Event) => handleFormSubmit(event, form));
    }
  }
  initReturnUrlSubmitButtons();
}


text:
<?xml version="1.0" encoding="utf-8"?>
<XnaContent>
  <Asset Type="RolePlayingGameData.Chest">
    <Name>MO Elixer</Name>
    <Gold>0</Gold>
    <Entries>
      <Item>
        <ContentName>Items\MOElixir</ContentName>
        <Count>1</Count>
      </Item>
    </Entries>
    <TextureName>Chest1d</TextureName>
  </Asset>
</XnaContent>


text:
layout: post
date: 2017-01-22
title: "J. Mendel bridal-2015-collection Style 11 Short Sleeves Sweep/Brush Train Sheath/Column"
category: J. Mendel
tags: [J. Mendel,Sheath/Column,Bateau,Sweep/Brush Train,Short Sleeves]
---
### J. Mendel bridal-2015-collection Style 11
Just **$369.99**
###   Short Sleeves Sweep/Brush Train Sheath/Column

BRANDS	J. Mendel

Silhouette	Sheath/Column

Neckline	Bateau

Hemline/Train	Sweep/Brush Train

Sleeve	Short Sleeves

Buy it: [https://www.readybrides.com/en/j-mendel/44375-j-mendel-bridal-2015-collection-style-11.html](https://www.readybrides.com/en/j-mendel/44375-j-mendel-bridal-2015-collection-style-11.html)


text:
require 'rspec'
require 'webmock/rspec'
require 'uri'

def require_job path
  require File.expand_path '../../jobs/' + path, __FILE__
end

class SCHEDULER
  def self.every(ignoreme)
  end
end

module Builds
  BUILD_CONFIG = {
    "goBaseUrl" => 'http://go-place',
    "bambooBaseUrl" => 'http://bamboo-place',
    "jenkinsBaseUrl" => 'http://jenkins-url'
  }
end

RSpec.configure do |config|
  config.color = true
  config.order = 'random'
end


text:
package backend

import (
	"bytes"
	"context"
	"crypto/rand"
	"crypto/tls"
	"crypto/x509"
	"encoding/binary"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"time"

	"github.com/go-redis/redis/v8"
	"github.com/pkg/errors"
	log "github.com/sirupsen/logrus"
)

// Errors.
var (
	ErrAsyncTimeout = errors.New("async timeout")
)

// Client defines the backend client interface.
type Client interface {
	// GetSenderID returns the SenderID.
	GetSenderID() string
	// GetReceiverID returns the ReceiverID.
	GetReceiverID() string
	// IsAsync returns a bool indicating if the client is async.
	IsAsync() bool
	// GetRandomTransactionID returns a random transaction id.
	GetRandomTransactionID() uint32
	// JoinReq method.
	JoinReq(context.Context, JoinReqPayload) (JoinAnsPayload, error)
	// RejoinReq method.
	RejoinReq(context.Context, RejoinReqPayload) (RejoinAnsPayload, error)
	// PRStartReq method.
	PRStartReq(context.Context, PRStartReqPayload) (PRStartAnsPayload, error)
	// PRStopReq method.
	PRStopReq(context.Context, PRStopReqPayload) (PRStopAnsPayload, error)
	// XmitDataReq method.
	XmitDataReq(context.Context, XmitDataReqPayload) (XmitDataAnsPayload, error)
	// ProfileReq method.
	ProfileReq(context.Context, ProfileReqPayload) (ProfileAnsPayload, error)
	// HomeNSReq method.
	HomeNSReq(context.Context, HomeNSReqPayload) (HomeNSAnsPayload, error)
	// SendAnswer sends the async answer.
	SendAnswer(context.Context, Answer) error
	// HandleAnswer handles an async answer.
	HandleAnswer(context.Context, Answer) error
}

// ClientConfig holds the backend client configuration.
type ClientConfig struct {
	SenderID   string
	ReceiverID string
	Server     string
	CACert     string
	TLSCert    string
	TLSKey     string
	// Authorization contains the value for the Authorization header. This may
	// include a prefix, like Bearer, Key or Basic.
	Authorization string

	// RedisClient holds the optional Redis database client. When set the client
	// will use the aysnc protocol scheme. In this case the client will wait
	// AsyncTimeout before returning a timeout error.
	RedisClient redis.UniversalClient

	// AsyncTimeout defines the async timeout. This must be set when RedisClient
	// is set.
	AsyncTimeout time.Duration

	// Logger holds a Logger instance.
	Logger *log.Logger
}

// NewClient creates a new Client.
func NewClient(config ClientConfig) (Client, error) {
	httpClient := http.DefaultClient

	if config.CACert != "" || config.TLSCert != "" || config.TLSKey != "" {
		tlsConfig := &tls.Config{}

		if config.CACert != "" {
			rawCACert, err := ioutil.ReadFile(config.CACert)
			if err != nil {
				return nil, errors.Wrap(err, "read ca cert error")
			}

			caCertPool := x509.NewCertPool()
			if !caCertPool.AppendCertsFromPEM(rawCACert) {
				return nil, errors.New("append ca cert to pool error")
			}

			tlsConfig.RootCAs = caCertPool
		}

		if config.TLSCert != "" || config.TLSKey != "" {
			cert, err := tls.LoadX509KeyPair(config.TLSCert, config.TLSKey)
			if err != nil {
				return nil, errors.Wrap(err, "load x509 keypair error")
			}
			tlsConfig.Certificates = []tls.Certificate{cert}
		}

		httpClient = &http.Client{
			Transport: &http.Transport{
				TLSClientConfig: tlsConfig,
			},
		}
	}

	if config.Logger == nil {
		config.Logger = &log.Logger{
			Out: ioutil.Discard,
		}
	}

	config.Logger.WithFields(log.Fields{
		"server":        config.Server,
		"ca_cert":       config.CACert,
		"tls_cert":      config.TLSCert,
		"tls_key":       config.TLSKey,
		"authorization": config.Authorization,
		"sender_id":     config.SenderID,
		"receiver_id":   config.ReceiverID,
	}).Debug("lorawan/backend: new backend client")

	return &client{
		log:             config.Logger,
		server:          config.Server,
		httpClient:      httpClient,
		authorization:   config.Authorization,
		senderID:        config.SenderID,
		receiverID:      config.ReceiverID,
		protocolVersion: ProtocolVersion1_0,
		redisClient:     config.RedisClient,
		asyncTimeout:    config.AsyncTimeout,
	}, nil

}

type client struct {
	log             *log.Logger
	server          string
	httpClient      *http.Client
	authorization   string
	protocolVersion string
	senderID        string
	receiverID      string
	redisClient     redis.UniversalClient
	asyncTimeout    time.Duration
}

func (c *client) GetSenderID() string {
	return c.senderID
}

func (c *client) GetReceiverID() string {
	return c.receiverID
}

func (c *client) IsAsync() bool {
	return c.redisClient != nil
}

func (c *client) JoinReq(ctx context.Context, pl JoinReqPayload) (JoinAnsPayload, error) {
	pl.BasePayload.ProtocolVersion = c.protocolVersion
	pl.BasePayload.SenderID = c.senderID
	pl.BasePayload.ReceiverID = c.receiverID
	pl.BasePayload.MessageType = JoinReq
	if pl.BasePayload.TransactionID == 0 {
		pl.BasePayload.TransactionID = c.GetRandomTransactionID()
	}

	var ans JoinAnsPayload

	if err := c.request(ctx, pl, &ans); err != nil {
		return ans, err
	}

	if ans.Result.ResultCode != Success {
		return ans, fmt.Errorf("response error, code: %s, description: %s", ans.Result.ResultCode, ans.Result.Description)
	}

	return ans, nil
}

func (c *client) RejoinReq(ctx context.Context, pl RejoinReqPayload) (RejoinAnsPayload, error) {
	pl.BasePayload.ProtocolVersion = c.protocolVersion
	pl.BasePayload.SenderID = c.senderID
	pl.BasePayload.ReceiverID = c.receiverID
	pl.BasePayload.MessageType = RejoinReq
	if pl.BasePayload.TransactionID == 0 {
		pl.BasePayload.TransactionID = c.GetRandomTransactionID()
	}

	var ans RejoinAnsPayload

	if err := c.request(ctx, pl, &ans); err != nil {
		return ans, err
	}

	if ans.Result.ResultCode != Success {
		return ans, fmt.Errorf("response error, code: %s, description: %s", ans.Result.ResultCode, ans.Result.Description)
	}

	return ans, nil
}

func (c *client) PRStartReq(ctx context.Context, pl PRStartReqPayload) (PRStartAnsPayload, error) {
	pl.BasePayload.ProtocolVersion = c.protocolVersion
	pl.BasePayload.SenderID = c.senderID
	pl.BasePayload.ReceiverID = c.receiverID
	pl.BasePayload.MessageType = PRStartReq
	if pl.BasePayload.TransactionID == 0 {
		pl.BasePayload.TransactionID = c.GetRandomTransactionID()
	}

	var ans PRStartAnsPayload

	if err := c.request(ctx, pl, &ans); err != nil {
		return ans, err
	}

	if ans.Result.ResultCode != Success {
		return ans, fmt.Errorf("response error, code: %s, description: %s", ans.Result.ResultCode, ans.Result.Description)
	}

	return ans, nil
}

func (c *client) PRStopReq(ctx context.Context, pl PRStopReqPayload) (PRStopAnsPayload, error) {
	pl.BasePayload.ProtocolVersion = c.protocolVersion
	pl.BasePayload.SenderID = c.senderID
	pl.BasePayload.ReceiverID = c.receiverID
	pl.BasePayload.MessageType = PRStopReq
	if pl.BasePayload.TransactionID == 0 {
		pl.BasePayload.TransactionID = c.GetRandomTransactionID()
	}

	var ans PRStopAnsPayload

	if err := c.request(ctx, pl, &ans); err != nil {
		return ans, err
	}

	if ans.Result.ResultCode != Success {
		return ans, fmt.Errorf("response error, code: %s, description: %s", ans.Result.ResultCode, ans.Result.Description)
	}

	return ans, nil
}

func (c *client) XmitDataReq(ctx context.Context, pl XmitDataReqPayload) (XmitDataAnsPayload, error) {
	pl.BasePayload.ProtocolVersion = c.protocolVersion
	pl.BasePayload.SenderID = c.senderID
	pl.BasePayload.ReceiverID = c.receiverID
	pl.BasePayload.MessageType = XmitDataReq
	if pl.BasePayload.TransactionID == 0 {
		pl.BasePayload.TransactionID = c.GetRandomTransactionID()
	}

	var ans XmitDataAnsPayload

	if err := c.request(ctx, pl, &ans); err != nil {
		return ans, err
	}

	if ans.Result.ResultCode != Success {
		return ans, fmt.Errorf("response error, code: %s, description: %s", ans.Result.ResultCode, ans.Result.Description)
	}

	return ans, nil
}

func (c *client) ProfileReq(ctx context.Context, pl ProfileReqPayload) (ProfileAnsPayload, error) {
	pl.BasePayload.ProtocolVersion = c.protocolVersion
	pl.BasePayload.SenderID = c.senderID
	pl.BasePayload.ReceiverID = c.receiverID
	pl.BasePayload.MessageType = ProfileReq
	if pl.BasePayload.TransactionID == 0 {
		pl.BasePayload.TransactionID = c.GetRandomTransactionID()
	}

	var ans ProfileAnsPayload

	if err := c.request(ctx, pl, &ans); err != nil {
		return ans, err
	}

	if ans.Result.ResultCode != Success {
		return ans, fmt.Errorf("response error, code: %s, description: %s", ans.Result.ResultCode, ans.Result.Description)
	}

	return ans, nil
}

func (c *client) HomeNSReq(ctx context.Context, pl HomeNSReqPayload) (HomeNSAnsPayload, error) {
	pl.BasePayload.ProtocolVersion = c.protocolVersion
	pl.BasePayload.SenderID = c.senderID
	pl.BasePayload.ReceiverID = c.receiverID
	pl.BasePayload.MessageType = HomeNSReq
	if pl.BasePayload.TransactionID == 0 {
		pl.BasePayload.TransactionID = c.GetRandomTransactionID()
	}

	var ans HomeNSAnsPayload

	if err := c.request(ctx, pl, &ans); err != nil {
		return ans, err
	}

	if ans.Result.ResultCode != Success {
		return ans, fmt.Errorf("response error, code: %s, description: %s", ans.Result.ResultCode, ans.Result.Description)
	}

	return ans, nil
}

func (c *client) request(ctx context.Context, pl Request, ans Answer) error {
	b, err := json.Marshal(pl)
	if err != nil {
		return errors.Wrap(err, "json marshal error")
	}

	responseChan := make(chan []byte, 1)
	errorChan := make(chan error, 1)

	// Setup async subscriber to receive response. Please note that we have to do
	// this before making the request, as the response might come in, before the
	// request has returned.
	if c.IsAsync() {
		key := c.getAsyncKey(pl.GetBasePayload().TransactionID)
		sub := c.redisClient.Subscribe(ctx, key)
		if _, err := sub.Receive(ctx); err != nil {
			return errors.Wrap(err, "async response subscription error")
		}
		ch := sub.Channel()

		go func() {
			defer sub.Close()

			select {
			case msg := <-ch:
				responseChan <- []byte(msg.Payload)
			case <-time.After(c.asyncTimeout):
				errorChan <- ErrAsyncTimeout
			}
		}()
	}

	req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.server, bytes.NewReader(b))
	if err != nil {
		return errors.Wrap(err, "new request error")
	}
	req.Header.Add("Content-Type", "application/json")
	if c.authorization != "" {
		req.Header.Add("Authorization", c.authorization)
	}

	resp, err := c.httpClient.Do(req)
	if err != nil {
		return errors.Wrap(err, "http post error")
	}
	defer resp.Body.Close()

	// If async is not used, the http response contains the API response payload.
	if !c.IsAsync() {
		bb, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			errorChan <- err
		} else {
			responseChan <- bb
		}
	} else {
		// By reading the complete body, Go will re-use the connection.
		io.Copy(ioutil.Discard, resp.Body)
	}

	select {
	case err := <-errorChan:
		return err
	case bb := <-responseChan:
		if err := json.Unmarshal(bb, ans); err != nil {
			return errors.Wrap(err, "unmarshal response error")
		}
	}

	c.log.WithFields(log.Fields{
		"protocol_version": pl.GetBasePayload().ProtocolVersion,
		"sender_id":        pl.GetBasePayload().SenderID,
		"receiver_id":      pl.GetBasePayload().ReceiverID,
		"transaction_id":   pl.GetBasePayload().TransactionID,
		"message_type":     pl.GetBasePayload().MessageType,
		"result_code":      ans.GetBasePayload().Result.ResultCode,
	}).Info("lorawan/backend: finished backend api call")

	return nil
}

func (c *client) HandleAnswer(ctx context.Context, pl Answer) error {
	if !c.IsAsync() {
		return errors.New("async is not configured")
	}

	b, err := json.Marshal(pl)
	if err != nil {
		return errors.Wrap(err, "marshal answer error")
	}

	err = c.redisClient.Publish(ctx, c.getAsyncKey(pl.GetBasePayload().TransactionID), b).Err()
	if err != nil {
		return errors.Wrap(err, "publish answer error")
	}

	return nil
}

func (c *client) SendAnswer(ctx context.Context, pl Answer) error {
	b, err := json.Marshal(pl)
	if err != nil {
		return errors.Wrap(err, "json marshal error")
	}

	req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.server, bytes.NewReader(b))
	if err != nil {
		return errors.Wrap(err, "new request error")
	}
	req.Header.Add("Content-Type", "application/json")
	if c.authorization != "" {
		req.Header.Add("Authorization", c.authorization)
	}

	resp, err := c.httpClient.Do(req)
	if err != nil {
		return errors.Wrap(err, "http post error")
	}
	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		bb, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return errors.Wrap(err, "read body error")
		}
		return fmt.Errorf("expected: 200, got: %d (%s)", resp.StatusCode, string(bb))
	}

	return nil
}

func (c *client) GetRandomTransactionID() uint32 {
	b := make([]byte, 4)
	rand.Read(b)
	return binary.LittleEndian.Uint32(b)
}

func (c *client) getAsyncKey(id uint32) string {
	return fmt.Sprintf("lora:backend:async:%d", id)
}


text:
package org.springframework.boot.actuate.redis;

import java.util.Arrays;
import java.util.List;
import java.util.Properties;

import org.junit.Test;

import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.Status;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.data.redis.connection.ClusterInfo;
import org.springframework.data.redis.connection.RedisClusterConnection;
import org.springframework.data.redis.connection.RedisClusterNode;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

/**
 * Tests for {@link RedisHealthIndicator}.
 *
 * @author Christian Dupuis
 * @author Richard Santana
 * @author Stephane Nicoll
 */
public class RedisHealthIndicatorTests {

	@Test
	public void redisIsUp() {
		Properties info = new Properties();
		info.put("redis_version", "2.8.9");
		RedisConnection redisConnection = mock(RedisConnection.class);
		given(redisConnection.info()).willReturn(info);
		RedisHealthIndicator healthIndicator = createHealthIndicator(redisConnection);
		Health health = healthIndicator.health();
		assertThat(health.getStatus()).isEqualTo(Status.UP);
		assertThat(health.getDetails().get("version")).isEqualTo("2.8.9");
	}

	@Test
	public void redisIsDown() {
		RedisConnection redisConnection = mock(RedisConnection.class);
		given(redisConnection.info())
				.willThrow(new RedisConnectionFailureException("Connection failed"));
		RedisHealthIndicator healthIndicator = createHealthIndicator(redisConnection);
		Health health = healthIndicator.health();
		assertThat(health.getStatus()).isEqualTo(Status.DOWN);
		assertThat((String) health.getDetails().get("error"))
				.contains("Connection failed");
	}

	private RedisHealthIndicator createHealthIndicator(RedisConnection redisConnection) {
		RedisConnectionFactory redisConnectionFactory = mock(
				RedisConnectionFactory.class);
		given(redisConnectionFactory.getConnection()).willReturn(redisConnection);
		return new RedisHealthIndicator(redisConnectionFactory);
	}

	@Test
	public void redisClusterIsUp() {
		Properties clusterProperties = new Properties();
		clusterProperties.setProperty("cluster_size", "4");
		clusterProperties.setProperty("cluster_slots_ok", "4");
		clusterProperties.setProperty("cluster_slots_fail", "0");
		List<RedisClusterNode> redisMasterNodes = Arrays.asList(
				new RedisClusterNode("127.0.0.1", 7001),
				new RedisClusterNode("127.0.0.2", 7001));
		RedisClusterConnection redisConnection = mock(RedisClusterConnection.class);
		given(redisConnection.clusterGetNodes()).willReturn(redisMasterNodes);
		given(redisConnection.clusterGetClusterInfo())
				.willReturn(new ClusterInfo(clusterProperties));
		RedisConnectionFactory redisConnectionFactory = mock(
				RedisConnectionFactory.class);
		given(redisConnectionFactory.getConnection()).willReturn(redisConnection);
		RedisHealthIndicator healthIndicator = new RedisHealthIndicator(
				redisConnectionFactory);
		Health health = healthIndicator.health();
		assertThat(health.getStatus()).isEqualTo(Status.UP);
		assertThat(health.getDetails().get("cluster_size")).isEqualTo(4L);
		assertThat(health.getDetails().get("slots_up")).isEqualTo(4L);
		assertThat(health.getDetails().get("slots_fail")).isEqualTo(0L);
		verify(redisConnectionFactory, atLeastOnce()).getConnection();
	}

}


text:
import {TemplateBuilder as T} from '../src'

const icon = () => null

describe('T.template()', () => {
  test('builds template through constructor', () => {
    expect(
      T.template({
        id: 'foo',
        title: 'some title',
        schemaType: 'author',
        value: {name: 'Default name!'},
        icon,
      }).serialize()
    ).toMatchSnapshot()
  })

  test('throws on missing id', () => {
    expect(() => T.template().serialize()).toThrowError(/required "id"/)
  })

  test('throws on missing title', () => {
    expect(() => T.template().id('id').serialize()).toThrowError(/required "title"/)
  })

  test('throws on missing schemaType', () => {
    expect(() => T.template().id('id').title('Blah').serialize()).toThrowError(
      /required "schemaType"/
    )
  })

  test('throws on missing value', () => {
    expect(() => T.template().id('id').title('Blah').schemaType('author').serialize()).toThrowError(
      /required "value"/
    )
  })

  test('can construct using builder', () => {
    expect(
      T.template()
        .id('yeah')
        .title('Yeah')
        .schemaType('author')
        .icon(icon)
        .value({name: 'bar'})
        .serialize()
    ).toMatchSnapshot()
  })

  test('builder is immutable', () => {
    const original = T.template()
    expect(original.id('foo')).not.toEqual(original)
    expect(original.title('foo')).not.toEqual(original)
    expect(original.schemaType('author')).not.toEqual(original)
    expect(original.icon(icon)).not.toEqual(original)
    expect(original.value({name: 'foo'})).not.toEqual(original)
  })

  test('getters work', () => {
    const original = T.template()
    expect(original.id('foo').getId()).toEqual('foo')
    expect(original.title('bar').getTitle()).toEqual('bar')
    expect(original.schemaType('author').getSchemaType()).toEqual('author')
    expect(original.icon(icon).getIcon()).toEqual(icon)
    expect(original.value({name: 'bar'}).getValue()).toEqual({name: 'bar'})
  })
})

describe('T.defaultTemplateForType()', () => {
  test('generates correct representation of type without initial value', () => {
    expect(T.defaultTemplateForType('author').serialize()).toMatchSnapshot()
  })

  test('generates correct representation of type with initial value', () => {
    expect(T.defaultTemplateForType('post').serialize()).toMatchSnapshot()
  })
})

describe('T.defaults()', () => {
  test('generates array of all schema type templates', () => {
    expect(T.defaults()).toMatchSnapshot()
    expect(T.defaults().map((tpl) => tpl.serialize())).toMatchSnapshot()
  })
})


text:
<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\DatabaseMigrations;

class TidingsTest extends TestCase
{
    use DatabaseMigrations;

    /** @test */
    public function a_user_can_view_all_tidings()
    {
        $tiding = factory('App\Models\Tiding')->create();

        $company = factory('App\Models\Company')->create();

        $response = $this->get('/tidings');

        $response->assertSee($tiding->title);
    }

    /** @test */
    public function a_user_can_read_a_single_tiding()
    {
        $tiding = factory('App\Models\Tiding')->create();

        $company = factory('App\Models\Company')->create();

        $response = $this->get('/tidings/' . $tiding->id);

        $response->assertSee($tiding->title);
    }
}


text:
class Import::CreateRefereeContext < BaseContext
  include Scrap::AnalysisRefereeContentConcern

  before_perform :parse_json_data
  before_perform :find_court
  before_perform :find_or_create_story
  before_perform :create_referee
  before_perform :create_main_judge_by_highest, if: :is_highest_court?
  before_perform :assign_names
  before_perform :build_content_json
  before_perform :build_file
  before_perform :assign_attributes
  after_perform  :update_data_to_story
  after_perform  :update_date_to_story, if: :is_verdict?
  after_perform  :create_relation_for_role
  after_perform  :remove_tempfile

  def initialize(hash_data)
    @data = hash_data
    @crawler_history = CrawlerHistory.find_or_create_by(crawler_on: Time.zone.today)
    @content_file_data = {}
  end

  def perform
    run_callbacks :perform do
      return false unless @referee.save
      @referee
    end
  end

  private

  def parse_json_data
    @court_code = @data['JID'].split(',').first[0..2]
    @story_type = convert_type(@data['JID'].split(',').first[3])
    @year = @data['JYEAR']
    @word = @data['JCASE']
    @number = @data['JNO']
    @adjudged_on = @data['JDATE'].to_date
    @reason = @data['JTITLE']
    @content = @data['JFULL']
  end

  def find_court
    return false unless @court = Court.find_by(code: @court_code)
  end

  def find_or_create_story
    @story = Story.find_or_create_by(story_type: @story_type, year: @year, word_type: @word, number: @number, court: @court)
  end

  def create_referee
    is_verdict? ? find_or_create_verdict : find_or_create_rule
  end

  def find_or_create_rule
    @referee = Rule.find_or_create_by(
      story: @story,
      adjudged_on: @adjudged_on
    )
  end

  def find_or_create_verdict
    @referee = Verdict.find_or_create_by(story: @story)
    @referee.assign_attributes(adjudged_on: @adjudged_on)
    @referee
  end

  def create_main_judge_by_highest
    parse_judges_names(@referee, @content, @crawler_history).each do |judge|
      Scrap::CreateJudgeByHighestCourtContext.new(@court, judge).perform
    end
  end

  def is_highest_court?
    @court.code == 'TPS'
  end

  def build_content_json
    start_point = get_content_start_point(@content)
    @content_file_data['related_roles'] = parse_roles_hash(@referee, @content, @crawler_history)
    @content_file_data['main_content'] = @content[start_point..-1]
  end

  def build_file
    @content_file = generate_tempfile(@content_file_data.to_json, @referee.story.identity, 'json')
  end

  def assign_attributes
    @referee.assign_attributes(
      content_file: File.open(@content_file.path),
      reason: @reason,
      roles_data: @content_file_data['related_roles']
    )
  end

  def assign_names
    @referee.assign_attributes(
      judges_names: parse_judges_names(@referee, @content, @crawler_history),
      prosecutor_names: parse_prosecutor_names(@referee, @content, @crawler_history),
      lawyer_names: parse_lawyer_names(@referee, @content, @crawler_history),
      party_names: parse_party_names(@referee, @content, @crawler_history)
    )
  end

  def update_data_to_story
    @story.assign_attributes(reason: @referee.reason) if @referee.reason
    @story.assign_attributes(judges_names: (@story.judges_names + @referee.judges_names).uniq)
    @story.assign_attributes(prosecutor_names: (@story.prosecutor_names + @referee.prosecutor_names).uniq)
    @story.assign_attributes(lawyer_names: (@story.lawyer_names + @referee.lawyer_names).uniq)
    @story.assign_attributes(party_names: (@story.party_names + @referee.party_names).uniq)
    @story.save
  end

  def update_date_to_story
    @story.update_attributes(adjudged_on: @adjudged_on, is_adjudged: true) unless @story.adjudged_on == @adjudged_on
    @story.update_attributes(pronounced_on: Time.zone.today, is_pronounced: true) unless @story.pronounced_on
  end

  def create_relation_for_role
    referee_role_name = @referee.lawyer_names + @referee.judges_names + @referee.party_names + @referee.prosecutor_names
    referee_role_name.each do |name|
      RefereeRelationCreateContext.new(@referee).perform(name)
      Story::RelationCreateContext.new(@story).perform(name)
    end
  end

  def remove_tempfile
    @content_file.unlink
  end

  def convert_type(type)
    case type
    when 'A'
      '行政'
    when 'M'
      '刑事'
    when 'V'
      '民事'
    when 'P'
      '公懲'
    end
  end

  def is_verdict?
    @content.split.first.match(/判決/).present?
  end

  def generate_tempfile(data, file_name, file_type)
    file = Tempfile.new([file_name, ".#{file_type}"], "#{Rails.root}/tmp/")
    file.write(data)
    file.rewind
    file.close
    file
  end
end


text:
B: Proprietorship Register

Title absolute

        1
        (14.02.2015) PROPRIETOR:

        <input type="text" disabled="true" style="background-color:#AAAAFF; width:100%" value="BARRY EDGAR CHEESE and EMILY LILY CAKE ">

        of

        <input type="text" disabled="true" style="background-color:#AAAAFF; width:100%" value="23 Sandwich Road, Plymouth PL1 234">

        2
        (14.02.2015) The price, other than rents, stated to have been paid on the grant of the lease was

        <input type="text" disabled="true" style="background-color:#AAAAFF; width:100%" value="£234,850">

        3
        (14.02.2015) RESTRICTION: This property may not be transferred to any third party or have any charge applied to
        it without the express permission of

        <input type="text" disabled="true" style="background-color:#AAAAFF; width:100%" value="BARRY EDGAR CHEESE or EMILY LILY CAKE">

        Unless they've died, in which case,
        you know, it's probably too late to ask them so just go ahead I guess.


text:
from django.conf import settings
from django.conf.urls.defaults import patterns, include, url, handler404, handler500
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns("",
    url(r"", include("translator.urls")),
    url(r"^admin/", include(admin.site.urls)),
)

if settings.DEBUG:
    urlpatterns += patterns("",
        url("^static/(?P<path>.*)$", "django.views.static.serve",
            {"document_root": settings.MEDIA_ROOT}),
    )


text: docker build --force-rm=true --no-cache -t italiangrid/storm-frontend .


text:
namespace ospray {
  namespace cpp    {

    class Renderer : public ManagedObject_T<OSPRenderer>
    {
    public:

      Renderer(const std::string &type);
      Renderer(const Renderer &copy);
      Renderer(OSPRenderer existing = nullptr);

      Material newMaterial(const std::string &type) const;
      Light    newLight(const std::string &type) const;

      float renderFrame(const FrameBuffer &fb, uint32_t channels) const;

      OSPPickResult pick(const ospcommon::vec2f &screenPos) const;
    };

    // Inlined function definitions ///////////////////////////////////////////////

    inline Renderer::Renderer(const std::string &type)
    {
      OSPRenderer c = ospNewRenderer(type.c_str());
      if (c) {
        ospObject = c;
      } else {
        throw std::runtime_error("Failed to create OSPRenderer!");
      }
    }

    inline Renderer::Renderer(const Renderer &copy) :
      ManagedObject_T<OSPRenderer>(copy.handle())
    {
    }

    inline Renderer::Renderer(OSPRenderer existing) :
      ManagedObject_T<OSPRenderer>(existing)
    {
    }

    inline Material Renderer::newMaterial(const std::string &type) const
    {
      auto mat = Material(ospNewMaterial(handle(), type.c_str()));

      if (!mat.handle()) {
        throw std::runtime_error("Failed to create OSPMaterial!");
      }

      return mat;
    }

    inline Light Renderer::newLight(const std::string &type) const
    {
      return Light(ospNewLight(handle(), type.c_str()));
    }

    inline float Renderer::renderFrame(const FrameBuffer &fb, uint32_t channels) const
    {
      return ospRenderFrame(fb.handle(), handle(), channels);
    }

    inline OSPPickResult Renderer::pick(const ospcommon::vec2f &screenPos) const
    {
      OSPPickResult result;
      ospPick(&result, handle(), (const osp::vec2f&)screenPos);
      return result;
    }

  }// namespace cpp
}// namespace ospray


text:
<!DOCTYPE html>
<title>CSS Overflow and Transforms: css-overflow-3</title>
<link rel="author" title="mailto:atotic@google.com">

<link rel="help" href="https://www.w3.org/TR/css-overflow-3/#scrollable">
<meta name="assert" content="css transform is used to compute scroll overflow of inline-block children">

    scroll

    down


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

namespace Nortal.Utilities.TaskSchedulerEngine
{
	/// <summary>
	/// Task scheduler engine which automatically discovers and executes tasks from entrypoint assembly.
	/// </summary>
	public class AllHostTasksSchedulerEngine : SchedulerEngineBase
	{
		protected override IEnumerable<ISchedulerTask> InitializeTasks()
		{
			var assemblyTasks = LoadInterfaceImplementations<ISchedulerTask>(Assembly.GetEntryAssembly());
			foreach (var assemblyTask in assemblyTasks)
			{
				yield return assemblyTask;
			}
		}

		/// <summary>
		/// Loads classes that implement given interface
		/// </summary>
		internal static IEnumerable<T> LoadInterfaceImplementations<T>(Assembly assembly)
		{
			if (assembly == null) { throw new ArgumentNullException("assembly"); }

			Type interfaceType = typeof(T);
			foreach (var type in assembly.GetTypes())
			{
				if (type.IsInterface || !interfaceType.IsAssignableFrom(type)) { continue; }
				var matchingTask = (T)Activator.CreateInstance(type);
				yield return matchingTask;
			}
		}

	}
}


text:
//Problem 2. Print Company Information

//A company has name, address, phone number, fax number, web site and manager. The manager has first name,
//last name, age and a phone number.
//Write a program that reads the information about a company and its manager and prints it back on the console.

using System;

class PrintCompanyInfo
{
    static void Main()
    {
        Console.WriteLine("Please enter company information...");

        Console.Write("Name: ");
        string companyName = Console.ReadLine();

        Console.Write("Address: ");
        string address = Console.ReadLine();

        Console.Write("Phone number: ");
        string phoneCompany = Console.ReadLine();

        Console.Write("Fax number: ");
        string faxCompany = Console.ReadLine();

        Console.Write("Web site: ");
        string webSite = Console.ReadLine();

        Console.WriteLine("Please enter manager information.");
        Console.Write("First name: ");
        string managerFName = Console.ReadLine();

        Console.Write("Last name: ");
        string managerLName = Console.ReadLine();

        Console.Write("Age: ");
        string managerAge = Console.ReadLine();

        Console.Write("Phone number: ");
        string managerPhone = Console.ReadLine();
        Console.WriteLine();

        Console.WriteLine(companyName + "\nAddress: " + address);
        Console.WriteLine("Tel: " + managerPhone);
        if (faxCompany.Length < 8)
        {
            Console.WriteLine("Fax: (no fax)");
        }
        else
        {
            Console.WriteLine("Fax: " + faxCompany);
        }
        Console.WriteLine("Web site: " + webSite);
        Console.WriteLine();
        Console.WriteLine("Manager: " + managerFName + " " + managerLName);
        Console.WriteLine("(age: {0}, tel. {1} )", managerAge, managerPhone);
    }
}


text:
namespace Kirby
{
	public class ScenarioRunner
	{
		public GivenSatisfier GivenSatisfier { get; private set; }

		public ScenarioRunner(GivenSatisfier givenSatisfier)
		{
			GivenSatisfier = givenSatisfier;
		}

		public void Given(params IGiven[] givens)
		{
			foreach (var given in givens)
			{
				GivenSatisfier.Satisfy(given);
			}
		}

		public void When(params IWhen[] whens)
		{

		}

		public void Then(params IThen[] thens)
		{

		}
	}
}


text:
'use strict'
const resolveFromTarball = require('@pnpm/tarball-resolver').default

resolveFromTarball({pref: 'http://registry.npmjs.org/is-array/-/is-array-1.0.1.tgz'})
  .then(resolveResult => console.log(JSON.stringify(resolveResult, null, 2)))


text:
class BooksController < ApplicationController
end


text:
var crypto = require("crypto");
var Promise = require("bluebird");
var csprng = require("csprng");
var sha = require("sha.js");
var fs = require("fs");
var pfs = Promise.promisifyAll(require("fs"));

exports.hash = {

  /**
	 * return a hash of the provided data
	 *
	 * @param {String} data
	 * @return {String} hash
	 * @api private
	 */
  hashData: function(data) {
    return crypto
      .createHash("sha1")
      .update(data)
      .digest("hex");
  },

  /**
	 * return a hash of the file at filePath
	 *
	 * @param {String} filePath
	 * @return {String} hash
	 * @api public
	 */
  fileSha1: function(filePath) {
    return this.hashData(fs.readFileSync(filePath));
  },

  /**
	 * return a promise to create a hash of the file at filePath
	 *
	 * @param {String} filePath
	 * @return {Promise} with hash entity
	 * @api public
	 */
  fileSha1Async: function (filePath) {
    //if no file path given, return a promise that resolves to null
    if (!filePath) {
      return new Promise(function(resolve) {
          resolve(null);
      });
    }
    var self = this;
    //else return a promise that resolves to a hash of the file
    return pfs.readFileAsync(filePath)
    .then(function (data) {
      return self.hashData(data);
    });
  },

  /**
   * return a CSPRNG random 'hash' string
   *
   * @param {Integer} bits
   * @return {String} hash
   * @api private
   */
  randomHash: function(bits) {
    return csprng(bits,36);
  },

  /**
   * return a CSPRNG random 'token' string
   *
   * @param {String} length
   * @return {String} token
   * @api private
   */
  randomString: function(length) {
    return this.randomHash(320).substr(0,length);
  },

  /**
   * return a SHA256 hash of salted password/token
   *
   * @param {String} salt
   * @param {String} secret
   * @return {String} hash
   * @api private
   */
  hashedCredentials: function(salt,secret) {
    var sha256 = sha("sha256");
    return sha256.update(salt+secret,"utf8").digest("hex");
  },

};


text:
package com.eagleoj.web.service.impl;

import com.eagleoj.web.controller.exception.WebErrorException;
import com.eagleoj.web.dao.TagProblemMapper;
import com.eagleoj.web.entity.TagProblemEntity;
import com.eagleoj.web.service.TagProblemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Smith
 **/
@Service
public class TagProblemServiceImpl implements TagProblemService {

    @Autowired
    private TagProblemMapper tagProblemMapper;

    @Override
    public void saveProblemTag(int tid, int pid) {
        TagProblemEntity entity = new TagProblemEntity();
        entity.setTid(tid);
        entity.setPid(pid);
        boolean flag = tagProblemMapper.save(entity) == 1;
        if (! flag) {
            throw new WebErrorException("题目标签添加失败");
        }
    }

    @Override
    public void deleteProblemTags(int pid) {
        boolean flag = tagProblemMapper.deleteByPid(pid) > 0;
        if (! flag) {
            throw new WebErrorException("题目标签删除失败");
        }
    }

    @Override
    public int countTagProblems(int tid) {
        return tagProblemMapper.countByTid(tid);
    }

    @Override
    public List<TagProblemEntity> getProblemTags(int pid) {
        return tagProblemMapper.listByPid(pid);
    }
}


text:
<?php

use Main\Classes\ThemeManager;

/**
 * Theme helper functions
 */

// ------------------------------------------------------------------------

if (!function_exists('active_theme')) {
    /**
     * Get the active theme code of the specified domain
     *
     * @return null
     */
    function active_theme()
    {
        return ThemeManager::instance()->getActiveThemeCode();
    }
}

// ------------------------------------------------------------------------

if (!function_exists('parent_theme')) {
    /**
     * Get the parent theme code of the specified domain
     *
     * @param string $theme
     *
     * @return null
     */
    function parent_theme($theme)
    {
        return ThemeManager::instance()->findParentCode($theme);
    }
}

// ------------------------------------------------------------------------


text:
<?php

namespace App;

use DCAS\Observers\ConsumerModelObserver;

/**
 * App\Consumer
 *
 * @property string $id
 * @property string|null $api_token
 * @property string $name
 * @property string $url
 * @property string $ip
 * @property int $active
 * @property \Carbon\Carbon|null $created_at
 * @property \Carbon\Carbon|null $updated_at
 * @property-read string $is_active
 * @property-read string $is_archived
 * @property-read string $is_deleted
 * @property-read string $is_removed
 * @property-read string $state_name
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model mode($mode = '0')
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model onlyActive($type = true)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model onlyArchived($type = true)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model onlyDeleted($type = true)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model order($field = '', $direction = '')
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model search($search, $threshold = null, $entireText = false, $entireTextOnly = false)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model searchRestricted($search, $restriction, $threshold = null, $entireText = false, $entireTextOnly = false)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model sortable($defaultSortColumn = null, $direction = 'asc')
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Consumer whereActive($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Consumer whereApiToken($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Consumer whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Consumer whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Consumer whereIp($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Consumer whereName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Consumer whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Consumer whereUrl($value)
 * @mixin \Eloquent
 */
class Consumer extends UUIDModel
{
    /**
     * @var array
     */
    protected $fillable = [
        'active',
        'api_token',
        'ip',
        'name',
        'url',
    ];

    /**
     * The API token field.
     *
     * @var string
     */
    private $apiTokenKey = 'api_token';

    /**
     * Add the ConsumerModelObserver to the boot method of the current model.
     */
    public static function boot()
    {
        parent::boot();

        self::observe(ConsumerModelObserver::class);
    }

    /**
     * Return the API token field.
     *
     * @return string
     */
    public function getApiTokenKey(): string
    {
        return $this->apiTokenKey;
    }

    /**
     * Get the index name for the model.
     *
     * @return string
     */
    public function searchableAs(): string
    {
        return 'consumers_index';
    }
}


text:
module ScheduleEVR (dayItem, dayItemFile) where

import Output
import Parser
import FromID
import Data.Time
import Control.Applicative

dayItemFile :: Day -> [FilePath] -> IO [(Day, String)]
dayItemFile b = (dayItem b <$>) . mapM readFile

dayItem :: Day -> [String] -> [(Day, String)]
dayItem b = ((b, "start") :) . map (\((_, e), i) -> (e, i)) . fromItemN b . map parse