text:
package org.lwjgl.vulkan;

import javax.annotation.*;

import java.nio.*;

import org.lwjgl.*;
import org.lwjgl.system.*;

import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;

/**
 * Structure specifying parameters controlling shading rate image usage.
 *
 *
Description

 *
 *
The {@link VkCoarseSampleOrderCustomNV} structure is used with a coverage sample ordering type of {@link NVShadingRateImage#VK_COARSE_SAMPLE_ORDER_TYPE_CUSTOM_NV COARSE_SAMPLE_ORDER_TYPE_CUSTOM_NV} to specify the order of coverage samples for one combination of fragment width, fragment height, and coverage sample count.

 *
 *
When using a custom sample ordering, element j in {@code pSampleLocations} specifies a specific pixel location and sample index that corresponds to coverage index j in the multi-pixel fragment.

 *
 *
Valid Usage

 *
 *

 *
{@code shadingRate} must be a shading rate that generates fragments with more than one pixel

 *
{@code sampleCount} must correspond to a sample count enumerated in {@code VkSampleCountFlags} whose corresponding bit is set in {@link VkPhysicalDeviceLimits}{@code ::framebufferNoAttachmentsSampleCounts}

 *
{@code sampleLocationCount} must be equal to the product of {@code sampleCount}, the fragment width for {@code shadingRate}, and the fragment height for {@code shadingRate}

 *
{@code sampleLocationCount} must be less than or equal to the value of {@link VkPhysicalDeviceShadingRateImagePropertiesNV}{@code ::shadingRateMaxCoarseSamples}

 *
The array {@code pSampleLocations} must contain exactly one entry for every combination of valid values for {@code pixelX}, {@code pixelY}, and {@code sample} in the structure {@link VkCoarseSampleOrderCustomNV}

 *

 *
 *
Valid Usage (Implicit)

 *
 *

 *
{@code shadingRate} must be a valid {@code VkShadingRatePaletteEntryNV} value

 *
{@code pSampleLocations} must be a valid pointer to an array of {@code sampleLocationCount} {@link VkCoarseSampleLocationNV} structures

 *
{@code sampleLocationCount} must be greater than 0

 *

 *
 *
See Also

 *
 *
{@link VkCoarseSampleLocationNV}, {@link VkPipelineViewportCoarseSampleOrderStateCreateInfoNV}, {@link NVShadingRateImage#vkCmdSetCoarseSampleOrderNV CmdSetCoarseSampleOrderNV}

 *
 *
Layout

 *
 *

 * struct VkCoarseSampleOrderCustomNV {
 *     VkShadingRatePaletteEntryNV {@link #shadingRate};
 *     uint32_t {@link #sampleCount};
 *     uint32_t {@link #sampleLocationCount};
 *     {@link VkCoarseSampleLocationNV VkCoarseSampleLocationNV} const * {@link #pSampleLocations};
 * }

 */
public class VkCoarseSampleOrderCustomNV extends Struct implements NativeResource {

    /** The struct size in bytes. */
    public static final int SIZEOF;

    /** The struct alignment in bytes. */
    public static final int ALIGNOF;

    /** The struct member offsets. */
    public static final int
        SHADINGRATE,
        SAMPLECOUNT,
        SAMPLELOCATIONCOUNT,
        PSAMPLELOCATIONS;

    static {
        Layout layout = __struct(
            __member(4),
            __member(4),
            __member(4),
            __member(POINTER_SIZE)
        );

        SIZEOF = layout.getSize();
        ALIGNOF = layout.getAlignment();

        SHADINGRATE = layout.offsetof(0);
        SAMPLECOUNT = layout.offsetof(1);
        SAMPLELOCATIONCOUNT = layout.offsetof(2);
        PSAMPLELOCATIONS = layout.offsetof(3);
    }

    /**
     * Creates a {@code VkCoarseSampleOrderCustomNV} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
     * visible to the struct instance and vice versa.
     *
     *
The created instance holds a strong reference to the container object.

     */
    public VkCoarseSampleOrderCustomNV(ByteBuffer container) {
        super(memAddress(container), __checkContainer(container, SIZEOF));
    }

    @Override
    public int sizeof() { return SIZEOF; }

    /** a shading rate palette entry that identifies the fragment width and height for the combination of fragment area and per-pixel coverage sample count to control. */
    @NativeType("VkShadingRatePaletteEntryNV")
    public int shadingRate() { return nshadingRate(address()); }
    /** identifies the per-pixel coverage sample count for the combination of fragment area and coverage sample count to control. */
    @NativeType("uint32_t")
    public int sampleCount() { return nsampleCount(address()); }
    /** specifies the number of sample locations in the custom ordering. */
    @NativeType("uint32_t")
    public int sampleLocationCount() { return nsampleLocationCount(address()); }
    /** a pointer to an array of {@link VkCoarseSampleLocationNV} structures specifying the location of each sample in the custom ordering. */
    @NativeType("VkCoarseSampleLocationNV const *")
    public VkCoarseSampleLocationNV.Buffer pSampleLocations() { return npSampleLocations(address()); }

    /** Sets the specified value to the {@link #shadingRate} field. */
    public VkCoarseSampleOrderCustomNV shadingRate(@NativeType("VkShadingRatePaletteEntryNV") int value) { nshadingRate(address(), value); return this; }
    /** Sets the specified value to the {@link #sampleCount} field. */
    public VkCoarseSampleOrderCustomNV sampleCount(@NativeType("uint32_t") int value) { nsampleCount(address(), value); return this; }
    /** Sets the address of the specified {@link VkCoarseSampleLocationNV.Buffer} to the {@link #pSampleLocations} field. */
    public VkCoarseSampleOrderCustomNV pSampleLocations(@NativeType("VkCoarseSampleLocationNV const *") VkCoarseSampleLocationNV.Buffer value) { npSampleLocations(address(), value); return this; }

    /** Initializes this struct with the specified values. */
    public VkCoarseSampleOrderCustomNV set(
        int shadingRate,
        int sampleCount,
        VkCoarseSampleLocationNV.Buffer pSampleLocations
    ) {
        shadingRate(shadingRate);
        sampleCount(sampleCount);
        pSampleLocations(pSampleLocations);

        return this;
    }

    /**
     * Copies the specified struct data to this struct.
     *
     * @param src the source struct
     *
     * @return this struct
     */
    public VkCoarseSampleOrderCustomNV set(VkCoarseSampleOrderCustomNV src) {
        memCopy(src.address(), address(), SIZEOF);
        return this;
    }

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

    /** Returns a new {@code VkCoarseSampleOrderCustomNV} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
    public static VkCoarseSampleOrderCustomNV malloc() {
        return wrap(VkCoarseSampleOrderCustomNV.class, nmemAllocChecked(SIZEOF));
    }

    /** Returns a new {@code VkCoarseSampleOrderCustomNV} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
    public static VkCoarseSampleOrderCustomNV calloc() {
        return wrap(VkCoarseSampleOrderCustomNV.class, nmemCallocChecked(1, SIZEOF));
    }

    /** Returns a new {@code VkCoarseSampleOrderCustomNV} instance allocated with {@link BufferUtils}. */
    public static VkCoarseSampleOrderCustomNV create() {
        ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF);
        return wrap(VkCoarseSampleOrderCustomNV.class, memAddress(container), container);
    }

    /** Returns a new {@code VkCoarseSampleOrderCustomNV} instance for the specified memory address. */
    public static VkCoarseSampleOrderCustomNV create(long address) {
        return wrap(VkCoarseSampleOrderCustomNV.class, address);
    }

    /** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */
    @Nullable
    public static VkCoarseSampleOrderCustomNV createSafe(long address) {
        return address == NULL ? null : wrap(VkCoarseSampleOrderCustomNV.class, address);
    }

    /**
     * Returns a new {@link VkCoarseSampleOrderCustomNV.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
     *
     * @param capacity the buffer capacity
     */
    public static VkCoarseSampleOrderCustomNV.Buffer malloc(int capacity) {
        return wrap(Buffer.class, nmemAllocChecked(__checkMalloc(capacity, SIZEOF)), capacity);
    }

    /**
     * Returns a new {@link VkCoarseSampleOrderCustomNV.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
     *
     * @param capacity the buffer capacity
     */
    public static VkCoarseSampleOrderCustomNV.Buffer calloc(int capacity) {
        return wrap(Buffer.class, nmemCallocChecked(capacity, SIZEOF), capacity);
    }

    /**
     * Returns a new {@link VkCoarseSampleOrderCustomNV.Buffer} instance allocated with {@link BufferUtils}.
     *
     * @param capacity the buffer capacity
     */
    public static VkCoarseSampleOrderCustomNV.Buffer create(int capacity) {
        ByteBuffer container = __create(capacity, SIZEOF);
        return wrap(Buffer.class, memAddress(container), capacity, container);
    }

    /**
     * Create a {@link VkCoarseSampleOrderCustomNV.Buffer} instance at the specified memory.
     *
     * @param address  the memory address
     * @param capacity the buffer capacity
     */
    public static VkCoarseSampleOrderCustomNV.Buffer create(long address, int capacity) {
        return wrap(Buffer.class, address, capacity);
    }

    /** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */
    @Nullable
    public static VkCoarseSampleOrderCustomNV.Buffer createSafe(long address, int capacity) {
        return address == NULL ? null : wrap(Buffer.class, address, capacity);
    }

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

    /** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */
    @Deprecated public static VkCoarseSampleOrderCustomNV mallocStack() { return malloc(stackGet()); }
    /** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */
    @Deprecated public static VkCoarseSampleOrderCustomNV callocStack() { return calloc(stackGet()); }
    /** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */
    @Deprecated public static VkCoarseSampleOrderCustomNV mallocStack(MemoryStack stack) { return malloc(stack); }
    /** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */
    @Deprecated public static VkCoarseSampleOrderCustomNV callocStack(MemoryStack stack) { return calloc(stack); }
    /** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */
    @Deprecated public static VkCoarseSampleOrderCustomNV.Buffer mallocStack(int capacity) { return malloc(capacity, stackGet()); }
    /** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */
    @Deprecated public static VkCoarseSampleOrderCustomNV.Buffer callocStack(int capacity) { return calloc(capacity, stackGet()); }
    /** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */
    @Deprecated public static VkCoarseSampleOrderCustomNV.Buffer mallocStack(int capacity, MemoryStack stack) { return malloc(capacity, stack); }
    /** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */
    @Deprecated public static VkCoarseSampleOrderCustomNV.Buffer callocStack(int capacity, MemoryStack stack) { return calloc(capacity, stack); }

    /**
     * Returns a new {@code VkCoarseSampleOrderCustomNV} instance allocated on the specified {@link MemoryStack}.
     *
     * @param stack the stack from which to allocate
     */
    public static VkCoarseSampleOrderCustomNV malloc(MemoryStack stack) {
        return wrap(VkCoarseSampleOrderCustomNV.class, stack.nmalloc(ALIGNOF, SIZEOF));
    }

    /**
     * Returns a new {@code VkCoarseSampleOrderCustomNV} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
     *
     * @param stack the stack from which to allocate
     */
    public static VkCoarseSampleOrderCustomNV calloc(MemoryStack stack) {
        return wrap(VkCoarseSampleOrderCustomNV.class, stack.ncalloc(ALIGNOF, 1, SIZEOF));
    }

    /**
     * Returns a new {@link VkCoarseSampleOrderCustomNV.Buffer} instance allocated on the specified {@link MemoryStack}.
     *
     * @param stack    the stack from which to allocate
     * @param capacity the buffer capacity
     */
    public static VkCoarseSampleOrderCustomNV.Buffer malloc(int capacity, MemoryStack stack) {
        return wrap(Buffer.class, stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity);
    }

    /**
     * Returns a new {@link VkCoarseSampleOrderCustomNV.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
     *
     * @param stack    the stack from which to allocate
     * @param capacity the buffer capacity
     */
    public static VkCoarseSampleOrderCustomNV.Buffer calloc(int capacity, MemoryStack stack) {
        return wrap(Buffer.class, stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity);
    }

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

    /** Unsafe version of {@link #shadingRate}. */
    public static int nshadingRate(long struct) { return UNSAFE.getInt(null, struct + VkCoarseSampleOrderCustomNV.SHADINGRATE); }
    /** Unsafe version of {@link #sampleCount}. */
    public static int nsampleCount(long struct) { return UNSAFE.getInt(null, struct + VkCoarseSampleOrderCustomNV.SAMPLECOUNT); }
    /** Unsafe version of {@link #sampleLocationCount}. */
    public static int nsampleLocationCount(long struct) { return UNSAFE.getInt(null, struct + VkCoarseSampleOrderCustomNV.SAMPLELOCATIONCOUNT); }
    /** Unsafe version of {@link #pSampleLocations}. */
    public static VkCoarseSampleLocationNV.Buffer npSampleLocations(long struct) { return VkCoarseSampleLocationNV.create(memGetAddress(struct + VkCoarseSampleOrderCustomNV.PSAMPLELOCATIONS), nsampleLocationCount(struct)); }

    /** Unsafe version of {@link #shadingRate(int) shadingRate}. */
    public static void nshadingRate(long struct, int value) { UNSAFE.putInt(null, struct + VkCoarseSampleOrderCustomNV.SHADINGRATE, value); }
    /** Unsafe version of {@link #sampleCount(int) sampleCount}. */
    public static void nsampleCount(long struct, int value) { UNSAFE.putInt(null, struct + VkCoarseSampleOrderCustomNV.SAMPLECOUNT, value); }
    /** Sets the specified value to the {@code sampleLocationCount} field of the specified {@code struct}. */
    public static void nsampleLocationCount(long struct, int value) { UNSAFE.putInt(null, struct + VkCoarseSampleOrderCustomNV.SAMPLELOCATIONCOUNT, value); }
    /** Unsafe version of {@link #pSampleLocations(VkCoarseSampleLocationNV.Buffer) pSampleLocations}. */
    public static void npSampleLocations(long struct, VkCoarseSampleLocationNV.Buffer value) { memPutAddress(struct + VkCoarseSampleOrderCustomNV.PSAMPLELOCATIONS, value.address()); nsampleLocationCount(struct, value.remaining()); }

    /**
     * Validates pointer members that should not be {@code NULL}.
     *
     * @param struct the struct to validate
     */
    public static void validate(long struct) {
        check(memGetAddress(struct + VkCoarseSampleOrderCustomNV.PSAMPLELOCATIONS));
    }

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

    /** An array of {@link VkCoarseSampleOrderCustomNV} structs. */
    public static class Buffer extends StructBuffer<VkCoarseSampleOrderCustomNV, Buffer> implements NativeResource {

        private static final VkCoarseSampleOrderCustomNV ELEMENT_FACTORY = VkCoarseSampleOrderCustomNV.create(-1L);

        /**
         * Creates a new {@code VkCoarseSampleOrderCustomNV.Buffer} instance backed by the specified container.
         *
         * Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
         * will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
         * by {@link VkCoarseSampleOrderCustomNV#SIZEOF}, and its mark will be undefined.
         *
         *
The created buffer instance holds a strong reference to the container object.

         */
        public Buffer(ByteBuffer container) {
            super(container, container.remaining() / SIZEOF);
        }

        public Buffer(long address, int cap) {
            super(address, null, -1, 0, cap, cap);
        }

        Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) {
            super(address, container, mark, pos, lim, cap);
        }

        @Override
        protected Buffer self() {
            return this;
        }

        @Override
        protected VkCoarseSampleOrderCustomNV getElementFactory() {
            return ELEMENT_FACTORY;
        }

        /** @return the value of the {@link VkCoarseSampleOrderCustomNV#shadingRate} field. */
        @NativeType("VkShadingRatePaletteEntryNV")
        public int shadingRate() { return VkCoarseSampleOrderCustomNV.nshadingRate(address()); }
        /** @return the value of the {@link VkCoarseSampleOrderCustomNV#sampleCount} field. */
        @NativeType("uint32_t")
        public int sampleCount() { return VkCoarseSampleOrderCustomNV.nsampleCount(address()); }
        /** @return the value of the {@link VkCoarseSampleOrderCustomNV#sampleLocationCount} field. */
        @NativeType("uint32_t")
        public int sampleLocationCount() { return VkCoarseSampleOrderCustomNV.nsampleLocationCount(address()); }
        /** @return a {@link VkCoarseSampleLocationNV.Buffer} view of the struct array pointed to by the {@link VkCoarseSampleOrderCustomNV#pSampleLocations} field. */
        @NativeType("VkCoarseSampleLocationNV const *")
        public VkCoarseSampleLocationNV.Buffer pSampleLocations() { return VkCoarseSampleOrderCustomNV.npSampleLocations(address()); }

        /** Sets the specified value to the {@link VkCoarseSampleOrderCustomNV#shadingRate} field. */
        public VkCoarseSampleOrderCustomNV.Buffer shadingRate(@NativeType("VkShadingRatePaletteEntryNV") int value) { VkCoarseSampleOrderCustomNV.nshadingRate(address(), value); return this; }
        /** Sets the specified value to the {@link VkCoarseSampleOrderCustomNV#sampleCount} field. */
        public VkCoarseSampleOrderCustomNV.Buffer sampleCount(@NativeType("uint32_t") int value) { VkCoarseSampleOrderCustomNV.nsampleCount(address(), value); return this; }
        /** Sets the address of the specified {@link VkCoarseSampleLocationNV.Buffer} to the {@link VkCoarseSampleOrderCustomNV#pSampleLocations} field. */
        public VkCoarseSampleOrderCustomNV.Buffer pSampleLocations(@NativeType("VkCoarseSampleLocationNV const *") VkCoarseSampleLocationNV.Buffer value) { VkCoarseSampleOrderCustomNV.npSampleLocations(address(), value); return this; }

    }

}


text:
package newspoints.sfsu.com.newsp.ui.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import newspoints.sfsu.com.newsp.R;

public class AudioVideoLibraryFragment extends Fragment {

    public AudioVideoLibraryFragment() {
        // Required empty public constructor
    }

    public static AudioVideoLibraryFragment newInstance(String param1, String param2) {
        AudioVideoLibraryFragment fragment = new AudioVideoLibraryFragment();
        Bundle args = new Bundle();

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_video_library, container, false);
    }

}

redpajama_set_name: RedPajamaGithub


text:
package Interpreter;

/**
 *
 */

public class Test {
  public static void main(String[] args) {
    // Test :
    //         (true and x) and (y and (not x))
    Context context = new Context();

    Variableexp x = new Variableexp("X");
    Variableexp y = new Variableexp("Y");
    Variableexp bTure = new Variableexp("true");
    Variableexp bFalse = new Variableexp("false");

    context.Assign("true", true);
    context.Assign("false", false);
    context.Assign("X", false);
    context.Assign("Y", true);

    Booleanexp expression = new Andexp(
            new Andexp(bTure, x),
            new Andexp(y, new Notexp(x))
    );
    boolean result = expression.Evaluate(context);
    System.out.println("The result is:" + result);
  }
}


text:
using namespace IECore;
using namespace Gaffer;
using namespace GafferDispatch;

//////////////////////////////////////////////////////////////////////////
// Task implementation
//////////////////////////////////////////////////////////////////////////

TaskNode::Task::Task( ConstTaskPlugPtr plug, const Gaffer::Context *context )
	:	m_plug( plug ), m_context( new Context( *context ) )
{
	Context::Scope scopedContext( m_context.get() );
	m_hash = m_plug->hash();
}

TaskNode::Task::Task( const Task &t ) : m_plug( t.m_plug ), m_context( t.m_context ), m_hash( t.m_hash )
{
}

TaskNode::Task::Task( TaskNodePtr n, const Context *c ) : m_plug( n->taskPlug() ), m_context( new Context( *c ) )
{
	Context::Scope scopedContext( m_context.get() );
	m_hash = m_plug->hash();
}

const TaskNode::TaskPlug *TaskNode::Task::plug() const
{
	return m_plug.get();
}

const TaskNode *TaskNode::Task::node() const
{
	return runTimeCast<const TaskNode>( m_plug->node() );
}

const Context *TaskNode::Task::context() const
{
	return m_context.get();
}

const MurmurHash TaskNode::Task::hash() const
{
	return m_hash;
}

bool TaskNode::Task::operator == ( const Task &rhs ) const
{
	return ( m_hash == rhs.m_hash );
}

bool TaskNode::Task::operator < ( const Task &rhs ) const
{
	return ( m_hash < rhs.m_hash );
}

//////////////////////////////////////////////////////////////////////////
// TaskPlug implementation.
//////////////////////////////////////////////////////////////////////////

namespace
{

class TaskNodeProcess : public Gaffer::Process
{

	public :

		TaskNodeProcess( const IECore::InternedString &type, const TaskNode::TaskPlug *plug )
			:	Process( type, plug->source<Plug>(), plug )
		{
		}

		const TaskNode *taskNode() const
		{
			const TaskNode *n = runTimeCast<const TaskNode>( plug()->node() );
			if( !n )
			{
				throw IECore::Exception( boost::str( boost::format( "TaskPlug \"%s\" has no TaskNode." ) % plug()->fullName() ) );
			}
			return n;
		}

		static InternedString hashProcessType;
		static InternedString executeProcessType;
		static InternedString executeSequenceProcessType;
		static InternedString requiresSequenceExecutionProcessType;
		static InternedString preTasksProcessType;
		static InternedString postTasksProcessType;

};

InternedString TaskNodeProcess::hashProcessType( "taskNode:hash" );
InternedString TaskNodeProcess::executeProcessType( "taskNode:execute" );
InternedString TaskNodeProcess::executeSequenceProcessType( "taskNode:executeSequence" );
InternedString TaskNodeProcess::requiresSequenceExecutionProcessType( "taskNode:requiresSequenceExecution" );
InternedString TaskNodeProcess::preTasksProcessType( "taskNode:preTasks" );
InternedString TaskNodeProcess::postTasksProcessType( "taskNode:postTasks" );

} // namespace

IE_CORE_DEFINERUNTIMETYPED( TaskNode::TaskPlug );

TaskNode::TaskPlug::TaskPlug( const std::string &name, Direction direction, unsigned flags )
	:	Plug( name, direction, flags )
{
}

bool TaskNode::TaskPlug::acceptsChild( const Gaffer::GraphComponent *potentialChild ) const
{
	return false;
}

bool TaskNode::TaskPlug::acceptsInput( const Plug *input ) const
{
	if( !Plug::acceptsInput( input ) )
	{
		return false;
	}

	if( !input )
	{
		return true;
	}

	if( input->isInstanceOf( staticTypeId() ) )
	{
		return true;
	}

	// Ideally we'd return false right now, but we must
	// provide backwards compatibility with old scripts
	// where the task plugs were just represented
	// as standard Plugs, and may have been promoted to
	// Boxes and Dots in that form.
	if( input->typeId() == Plug::staticTypeId() )
	{
		const Plug *sourcePlug = input->source<Plug>();
		if( sourcePlug->isInstanceOf( staticTypeId() ) )
		{
			return true;
		}
		const Node *sourceNode = sourcePlug->node();
		return runTimeCast<const SubGraph>( sourceNode ) || runTimeCast<const Dot>( sourceNode );
	}

	return false;

}

PlugPtr TaskNode::TaskPlug::createCounterpart( const std::string &name, Direction direction ) const
{
	return new TaskPlug( name, direction, getFlags() );
}

IECore::MurmurHash TaskNode::TaskPlug::hash() const
{
	TaskNodeProcess p( TaskNodeProcess::hashProcessType, this );
	return p.taskNode()->hash( Context::current() );
}

void TaskNode::TaskPlug::execute() const
{
	TaskNodeProcess p( TaskNodeProcess::executeProcessType, this );
	return p.taskNode()->execute();
}

void TaskNode::TaskPlug::executeSequence( const std::vector<float> &frames ) const
{
	TaskNodeProcess p( TaskNodeProcess::executeSequenceProcessType, this );
	return p.taskNode()->executeSequence( frames );
}

bool TaskNode::TaskPlug::requiresSequenceExecution() const
{
	TaskNodeProcess p( TaskNodeProcess::requiresSequenceExecutionProcessType, this );
	return p.taskNode()->requiresSequenceExecution();
}

void TaskNode::TaskPlug::preTasks( Tasks &tasks ) const
{
	TaskNodeProcess p( TaskNodeProcess::preTasksProcessType, this );
	return p.taskNode()->preTasks( Context::current(), tasks );
}

void TaskNode::TaskPlug::postTasks( Tasks &tasks ) const
{
	TaskNodeProcess p( TaskNodeProcess::postTasksProcessType, this );
	return p.taskNode()->postTasks( Context::current(), tasks );
}

//////////////////////////////////////////////////////////////////////////
// TaskNode implementation
//////////////////////////////////////////////////////////////////////////

IE_CORE_DEFINERUNTIMETYPED( TaskNode )

size_t TaskNode::g_firstPlugIndex;

TaskNode::TaskNode( const std::string &name )
	:	Node( name )
{
	storeIndexOfNextChild( g_firstPlugIndex );
	addChild( new ArrayPlug( "preTasks", Plug::In, new TaskPlug( "preTask0" ) ) );
	addChild( new ArrayPlug( "postTasks", Plug::In, new TaskPlug( "postTask0" ) ) );
	addChild( new TaskPlug( "task", Plug::Out ) );

	PlugPtr dispatcherPlug = new Plug( "dispatcher", Plug::In );
	addChild( dispatcherPlug );

	Dispatcher::setupPlugs( dispatcherPlug.get() );
}

TaskNode::~TaskNode()
{
}

ArrayPlug *TaskNode::preTasksPlug()
{
	return getChild<ArrayPlug>( g_firstPlugIndex );
}

const ArrayPlug *TaskNode::preTasksPlug() const
{
	return getChild<ArrayPlug>( g_firstPlugIndex );
}

ArrayPlug *TaskNode::postTasksPlug()
{
	return getChild<ArrayPlug>( g_firstPlugIndex + 1 );
}

const ArrayPlug *TaskNode::postTasksPlug() const
{
	return getChild<ArrayPlug>( g_firstPlugIndex + 1 );
}

TaskNode::TaskPlug *TaskNode::taskPlug()
{
	return getChild<TaskPlug>( g_firstPlugIndex + 2 );
}

const TaskNode::TaskPlug *TaskNode::taskPlug() const
{
	return getChild<TaskPlug>( g_firstPlugIndex + 2 );
}

Plug *TaskNode::dispatcherPlug()
{
	return getChild<Plug>( g_firstPlugIndex + 3 );
}

const Plug *TaskNode::dispatcherPlug() const
{
	return getChild<Plug>( g_firstPlugIndex + 3 );
}

void TaskNode::preTasks( const Context *context, Tasks &tasks ) const
{
	for( PlugIterator cIt( preTasksPlug() ); !cIt.done(); ++cIt )
	{
		Plug *source = (*cIt)->source<Plug>();
		if( source != *cIt )
		{
			if( TaskNodePtr n = runTimeCast<TaskNode>( source->node() ) )
			{
				tasks.push_back( Task( n, context ) );
			}
		}
	}
}

void TaskNode::postTasks( const Context *context, Tasks &tasks ) const
{
	for( PlugIterator cIt( postTasksPlug() ); !cIt.done(); ++cIt )
	{
		Plug *source = (*cIt)->source<Plug>();
		if( source != *cIt )
		{
			if( TaskNodePtr n = runTimeCast<TaskNode>( source->node() ) )
			{
				tasks.push_back( Task( n, context ) );
			}
		}
	}
}

IECore::MurmurHash TaskNode::hash( const Context *context ) const
{
	IECore::MurmurHash h;
	h.append( typeId() );
	return h;
}

void TaskNode::execute() const
{
}

void TaskNode::executeSequence( const std::vector<float> &frames ) const
{
	ContextPtr context = new Context( *Context::current(), Context::Borrowed );
	Context::Scope scopedContext( context.get() );

	for ( std::vector<float>::const_iterator it = frames.begin(); it != frames.end(); ++it )
	{
		context->setFrame( *it );
		execute();
	}
}

bool TaskNode::requiresSequenceExecution() const
{
	return false;
}


text:
import React from 'react'
import hogan from 'hogan.js'
import shallowCompare from 'react-addons-shallow-compare'

export default class ReactHogan extends React.Component {

  shouldComponentUpdate(nextProps, nextState) {
    return shallowCompare(this, nextProps, nextState)
  }

  compileTemplate(template){
    // lazy template compiling
    if (this.compiledTemplate == template){
      return this.compilationResult
    }
    this.compilationResult = hogan.compile(template)
    this.compiledTemplate = template
    return this.compilationResult
  }

  render() {
    const { template, data, Component, ...props } = this.props
    if (!template) return false

    const compiledTemplate = this.compileTemplate(template)
    const __html = compiledTemplate.render(data)
    return (
      <Component dangerouslySetInnerHTML={{__html}} {...props}/>
    )
  }
}

ReactHogan.defaultProps = {
  data: {},
  Component: 'div'
}


text:
<?php

require 'Include/Config.php';
require 'Include/Functions.php';

use ChurchCRM\Utils\InputUtils;
use ChurchCRM\dto\SystemURLs;
use ChurchCRM\Utils\RedirectUtils;
use ChurchCRM\Authentication\AuthenticationManager;

// Security: user must be administrator to use this page
if (!AuthenticationManager::GetCurrentUser()->isAdmin()) {
    RedirectUtils::Redirect('Menu.php');
    exit;
}

$sPageTitle = gettext('Custom Family Fields Editor');

require 'Include/Header.php'; ?>

<?php

$bNewNameError = false;
$bDuplicateNameError = false;
$bErrorFlag = false;
$aNameErrors = [];

// Does the user want to save changes to text fields?
if (isset($_POST['SaveChanges'])) {
    // Fill in the other needed custom field data arrays not gathered from the form submit
    $sSQL = 'SELECT * FROM family_custom_master ORDER BY fam_custom_Order';
    $rsCustomFields = RunQuery($sSQL);
    $numRows = mysqli_num_rows($rsCustomFields);

    for ($row = 1; $row <= $numRows; $row++) {
        $aRow = mysqli_fetch_array($rsCustomFields, MYSQLI_BOTH);
        extract($aRow);

        $aFieldFields[$row] = $fam_custom_Field;
        $aTypeFields[$row] = $type_ID;
        if (isset($fam_custom_Special)) {
            $aSpecialFields[$row] = $fam_custom_Special;
        } else {
            $aSpecialFields[$row] = 'NULL';
        }
    }

    for ($iFieldID = 1; $iFieldID <= $numRows; $iFieldID++) {
        $aNameFields[$iFieldID] = InputUtils::LegacyFilterInput($_POST[$iFieldID.'name']);

        if (strlen($aNameFields[$iFieldID]) == 0) {
            $aNameErrors[$iFieldID] = true;
            $bErrorFlag = true;
        } else {
            $aNameErrors[$iFieldID] = false;
        }

        $aFieldSecurity[$iFieldID] = $_POST[$iFieldID.'FieldSec'];

        if (isset($_POST[$iFieldID.'special'])) {
            $aSpecialFields[$iFieldID] = InputUtils::LegacyFilterInput($_POST[$iFieldID.'special'], 'int');

            if ($aSpecialFields[$iFieldID] == 0) {
                $aSpecialErrors[$iFieldID] = true;
                $bErrorFlag = true;
            } else {
                $aSpecialErrors[$iFieldID] = false;
            }
        }
    }

    // If no errors, then update.
    if (!$bErrorFlag) {
        for ($iFieldID = 1; $iFieldID <= $numRows; $iFieldID++) {
            $sSQL = "UPDATE family_custom_master
                    SET `fam_custom_Name` = '".$aNameFields[$iFieldID]."',
                        `fam_custom_Special` = ".$aSpecialFields[$iFieldID].",
                        `fam_custom_FieldSec` = ".$aFieldSecurity[$iFieldID]."
                    WHERE `fam_custom_Field` = '".$aFieldFields[$iFieldID]."';";

            RunQuery($sSQL);
        }
    }
} else {
    // Check if we're adding a field
    if (isset($_POST['AddField'])) {
        $newFieldType = InputUtils::LegacyFilterInput($_POST['newFieldType'], 'int');
        $newFieldName = InputUtils::LegacyFilterInput($_POST['newFieldName']);
        $newFieldSec = $_POST['newFieldSec'];

        if (strlen($newFieldName) == 0) {
            $bNewNameError = true;
        } elseif (strlen($newFieldType) == 0 || $newFieldType < 1) {
            // This should never happen, but check anyhow.
            // $bNewTypeError = true;
        } else {
            $sSQL = 'SELECT fam_custom_Name FROM family_custom_master';
            $rsCustomNames = RunQuery($sSQL);
            while ($aRow = mysqli_fetch_array($rsCustomNames)) {
                if ($aRow[0] == $newFieldName) {
                    $bDuplicateNameError = true;
                    break;
                }
            }

            if (!$bDuplicateNameError) {
                global $cnInfoCentral;
                // Find the highest existing field number in the table to
                // determine the next free one.
                // This is essentially an auto-incrementing system where
                // deleted numbers are not re-used.
                $fields = mysqli_query($cnInfoCentral, 'SHOW COLUMNS FROM family_custom');
                $last = mysqli_num_rows($fields) - 1;
                // Set the new field number based on the highest existing.
                // Chop off the "c" at the beginning of the old one's name.
                // The "c#" naming scheme is necessary because MySQL 3.23
                // doesn't allow numeric-only field (table column) names.
                $fields = mysqli_query($cnInfoCentral, 'SELECT * FROM family_custom');
                $fieldInfo = mysqli_fetch_field_direct($fields, $last);
                $newFieldNum = mb_substr($fieldInfo->name, 1) + 1;

                // If we're inserting a new custom-list type field,
                // create a new list and get its ID
                if ($newFieldType == 12) {
                    // Get the first available lst_ID for insertion.
                    // lst_ID 0-9 are reserved for permanent lists.
                    $sSQL = 'SELECT MAX(lst_ID) FROM list_lst';
                    $aTemp = mysqli_fetch_array(RunQuery($sSQL));
                    if ($aTemp[0] > 9) {
                        $newListID = $aTemp[0] + 1;
                    } else {
                        $newListID = 10;
                    }

                    // Insert into the lists table with an example option.
                    $sSQL = "INSERT INTO list_lst VALUES ($newListID, 1, 1,'".gettext('Default Option')."')";
                    RunQuery($sSQL);

                    $newSpecial = "'$newListID'";
                } else {
                    $newSpecial = 'NULL';
                }

                // Insert into the master table
                $newOrderID = $last + 1;
                $sSQL = "INSERT INTO `family_custom_master`
                        (`fam_custom_Order` , `fam_custom_Field` , `fam_custom_Name` ,  `fam_custom_Special` , `fam_custom_FieldSec` , `type_ID`)
                        VALUES ('".$newOrderID."', 'c".$newFieldNum."', '".$newFieldName."', ".$newSpecial.", '".$newFieldSec."', '".$newFieldType."');";
                RunQuery($sSQL);

                // Insert into the custom fields table
                $sSQL = 'ALTER TABLE `family_custom` ADD `c'.$newFieldNum.'` ';

                switch ($newFieldType) {
                case 1:
                    $sSQL .= "ENUM('false', 'true')";
                    break;
                case 2:
                    $sSQL .= 'DATE';
                    break;
                case 3:
                    $sSQL .= 'VARCHAR(50)';
                    break;
                case 4:
                    $sSQL .= 'VARCHAR(100)';
                    break;
                case 5:
                    $sSQL .= 'TEXT';
                    break;
                case 6:
                    $sSQL .= 'YEAR';
                    break;
                case 7:
                    $sSQL .= "ENUM('winter', 'spring', 'summer', 'fall')";
                    break;
                case 8:
                    $sSQL .= 'INT';
                    break;
                case 9:
                    $sSQL .= 'MEDIUMINT(9)';
                    break;
                case 10:
                    $sSQL .= 'DECIMAL(10,2)';
                    break;
                case 11:
                    $sSQL .= 'VARCHAR(30)';
                    break;
                case 12:
                    $sSQL .= 'TINYINT(4)';
                }

                $sSQL .= ' DEFAULT NULL ;';
                RunQuery($sSQL);

                $bNewNameError = false;
            }
        }
    }

    // Get data for the form as it now exists..
    $sSQL = 'SELECT * FROM family_custom_master ORDER BY fam_custom_Order';

    $rsCustomFields = RunQuery($sSQL);
    $numRows = mysqli_num_rows($rsCustomFields);

    // Create arrays of the fields.
    for ($row = 1; $row <= $numRows; $row++) {
        $aRow = mysqli_fetch_array($rsCustomFields, MYSQLI_BOTH);
        extract($aRow);

        $aNameFields[$row] = $fam_custom_Name;
        $aSpecialFields[$row] = $fam_custom_Special;
        $aFieldFields[$row] = $fam_custom_Field;
        $aTypeFields[$row] = $type_ID;
        $aFieldSecurity[$row] = $fam_custom_FieldSec;
        $aNameErrors[$row] = false;
    }
}

// Prepare Security Group list
    $sSQL = 'SELECT * FROM list_lst WHERE lst_ID = 5 ORDER BY lst_OptionSequence';
    $rsSecurityGrp = RunQuery($sSQL);

    $aSecurityGrp = [];
    while ($aRow = mysqli_fetch_array($rsSecurityGrp)) {
        $aSecurityGrp[] = $aRow;
        extract($aRow);
        $aSecurityType[$lst_OptionID] = $lst_OptionName;
    }

function GetSecurityList($aSecGrp, $fld_name, $currOpt = 'bAll')
{
    $sOptList = '<select name="'.$fld_name.'">';
    $grp_Count = count($aSecGrp);

    for ($i = 0; $i < $grp_Count; $i++) {
        $aAryRow = $aSecGrp[$i];
        $sOptList .= '<option value="'.$aAryRow['lst_OptionID'].'"';
        if ($aAryRow['lst_OptionName'] == $currOpt) {
            $sOptList .= ' selected';
        }
        $sOptList .= '>'.$aAryRow['lst_OptionName']."</option>\n";
    }
    $sOptList .= '</select>';

    return $sOptList;
}

// Construct the form
?>

		<?= gettext("Warning: Arrow and delete buttons take effect immediately.  Field name changes will be lost if you do not 'Save Changes' before using an up, down, delete or 'add new' button!") ?>

<form method="post" action="FamilyCustomFieldsEditor.php" name="FamilyCustomFieldsEditor">

<?php
if ($numRows == 0) {
    ?>

<?= gettext('No custom Family fields have been added yet') ?>

<?php
} else {
        ?>

    <?php
    if ($bErrorFlag) {
        echo '
'.gettext('Invalid fields or selections. Changes not saved! Please correct and try again!').'';
    } ?>

            <?= gettext('Type') ?>
            <?= gettext('Name') ?>
            <?= gettext('Special option') ?>
            <?= gettext('Security Option') ?>
            <?= gettext('Delete') ?>

    <?php

    for ($row = 1; $row <= $numRows; $row++) {
        ?>

                <?= $aPropTypes[$aTypeFields[$row]] ?>

                <input type="text" name="<?= $row.'name' ?>" value="<?= htmlentities(stripslashes($aNameFields[$row]), ENT_NOQUOTES, 'UTF-8') ?>" size="35" maxlength="40">
                <?php
                if ($aNameErrors[$row]) {
                    echo '
'.gettext('You must enter a name').' ';
                } ?>

            <?php
            if ($aTypeFields[$row] == 9) {
                echo '<select name="'.$row.'special">';
                echo '<option value="0" selected>Select a group</option>';

                $sSQL = 'SELECT grp_ID,grp_Name FROM group_grp ORDER BY grp_Name';
                $rsGroupList = RunQuery($sSQL);

                while ($aRow = mysqli_fetch_array($rsGroupList)) {
                    extract($aRow);

                    echo '<option value="'.$grp_ID.'"';
                    if ($aSpecialFields[$row] == $grp_ID) {
                        echo ' selected';
                    }
                    echo '>'.$grp_Name;
                }

                echo '</select>';
                if ($aSpecialErrors[$row]) {
                    echo '
'.gettext('You must select a group.').'';
                }
            } elseif ($aTypeFields[$row] == 12) {

                // TLH 6-23-07 Added scrollbars to the popup so long lists can be edited.
                echo "".gettext('Edit List Options').'';
            } else {
                echo ' ';
            } ?>

                <?= GetSecurityList($aSecurityGrp, $row.'FieldSec', $aSecurityType[$aFieldSecurity[$row]]) ?>

                <input type="button" class="btn btn-danger" value="<?= gettext('Delete') ?>"   name="delete" onclick="return confirmDeleteField('<?= $aFieldFields[$row] ?>');">

                <?php
                if ($row > 1) {
                    echo "';
                }
        if ($row < $numRows) {
            echo "';
        } ?>

    <?php
    } ?>

                        <input type="submit" class="btn btn-primary" value="<?= gettext('Save Changes') ?>" Name="SaveChanges">

<?php
    } ?>

<?= gettext('Type') ?>:

                    <?php
                        echo '<select name="newFieldType">';

                        for ($iOptionID = 1; $iOptionID <= count($aPropTypes); $iOptionID++) {
                            echo '<option value="'.$iOptionID.'"';
                            echo '>'.$aPropTypes[$iOptionID];
                        }
                        echo '</select>';
                    ?>

                    <a href="<?= SystemURLs::getSupportURL() ?>"><?= gettext('Help on types..') ?>

<?= gettext('Name') ?>:

                        <input type="text" name="newFieldName" size="30" maxlength="40">
                        <?php
                            if ($bNewNameError) {
                                echo '

'.gettext('You must enter a name').'
';
                            }
                            if ($bDuplicateNameError) {
                                echo '

'.gettext('That field name already exists.').'
';
                            }
                        ?>

<?= gettext('Security Option') ?>

                        <?= GetSecurityList($aSecurityGrp, 'newFieldSec') ?>

                        <input type="submit" class="btn btn-primary" <?= 'value="'.gettext('Add New Field').'"' ?> Name="AddField">

    </form>

<?php require 'Include/Footer.php' ?>


text:
\begin{figure}[H]
\centering
\includegraphics[width=6in]{figs/run_56/run_56_T_vs_r_mesh_ctkescatter}
\caption{Scatter plot of azimuthal velocity vs radius, turbulent kinetic energy, at $z/c$=9.50, $V_{free}$=24.97, station 6.}
\label{fig:run_56_T_vs_r_mesh_ctkescatter}
\end{figure}


text:
<?php

namespace Symfony\Component\HttpKernel\Config;

use Symfony\Component\Config\Resource\SelfCheckingResourceInterface;

/**
 * EnvParametersResource represents resources stored in prefixed environment variables.
 *
 * @author Chris Wilkinson <chriswilkinson84@gmail.com>
 *
 * @deprecated since version 3.4, to be removed in 4.0
 */
class EnvParametersResource implements SelfCheckingResourceInterface, \Serializable
{
    /**
     * @var string
     */
    private $prefix;

    /**
     * @var string
     */
    private $variables;

    /**
     * @param string $prefix
     */
    public function __construct($prefix)
    {
        $this->prefix = $prefix;
        $this->variables = $this->findVariables();
    }

    /**
     * {@inheritdoc}
     */
    public function __toString()
    {
        return serialize($this->getResource());
    }

    /**
     * @return array An array with two keys: 'prefix' for the prefix used and 'variables' containing all the variables watched by this resource
     */
    public function getResource()
    {
        return array('prefix' => $this->prefix, 'variables' => $this->variables);
    }

    /**
     * {@inheritdoc}
     */
    public function isFresh($timestamp)
    {
        return $this->findVariables() === $this->variables;
    }

    public function serialize()
    {
        return serialize(array('prefix' => $this->prefix, 'variables' => $this->variables));
    }

    public function unserialize($serialized)
    {
        if (\PHP_VERSION_ID >= 70000) {
            $unserialized = unserialize($serialized, array('allowed_classes' => false));
        } else {
            $unserialized = unserialize($serialized);
        }

        $this->prefix = $unserialized['prefix'];
        $this->variables = $unserialized['variables'];
    }

    private function findVariables()
    {
        $variables = array();

        foreach ($_SERVER as $key => $value) {
            if (0 === strpos($key, $this->prefix)) {
                $variables[$key] = $value;
            }
        }

        ksort($variables);

        return $variables;
    }
}


text:
namespace Stripe
{
    public class PaymentMethodAlipay : StripeEntity<PaymentMethodAlipay>
    {
    }
}


text:
struct PUElem
{
    PUElem() : base('A'), lp(0) {}
    PUElem(char b, double l) : base(b), lp(l) {}

    char base;

    // log probability this base is correct
    double lp;
};

typedef std::vector<PUElem> PUElemVector;

class Pileup
{
    public:
        Pileup() {}
        Pileup(size_t n) { m_data.reserve(n); }

        char calculateSimpleConsensus() const;
        AlphaCount64 getAlphaCount() const;
        DNADouble calculateSimpleAlphaProb() const;
        DNADouble calculateLikelihoodNoQuality(double p_error) const;

        inline void add(char b) { m_data.push_back(PUElem(b, DEFAULT_LOG_PROB)); }
        inline void add(char b, double lp) { m_data.push_back(PUElem(b, lp)); }

        char getBase(size_t idx) const;
        char getCount(char base) const;
        size_t getDepth() const;

        std::string toStr() const;

    private:
        PUElemVector m_data;
};

typedef std::vector<Pileup> PileupVector;

#endif


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

  angular
  .module('hr2AngularUi')
  .config(routerConfig)
  .controller('ParentController', parentController);

  /** @ngInject */
  function routerConfig($stateProvider) {
    $stateProvider
    .state('app', {
      abstract: true,
      template: '<ui-view/>',
      controller: 'ParentController',
      controllerAs: 'vm',
      resolve: {
          userInfo: ['$rootScope', 'userinfoService', '$log', function($rootScope, userinfoService, $log) {
            if ($rootScope.preloadFinished) {
              return;
            }
            $log.debug('Preload userInfo');
            return userinfoService.getUserInfo();
          }],
          localeResource: ['$rootScope', 'userInfo', 'localeService', '$log', function($rootScope, userInfo, localeService, $log) {
            if ($rootScope.preloadFinished) {
              return;
            }
            var userLocale = userInfo.locale;
            $log.debug('Preload language resources: ' + userLocale);
            return localeService.use(userLocale);
          }],
          grantedAuthorities: ['$rootScope', 'userInfoCache', 'userInfo', function($rootScope, userInfoCache, userInfo) {
            if ($rootScope.preloadFinished) {
              return;
            }
            userInfoCache.put('grantedAuthorities', userInfo.grantedAuthorities);
          }]
        }
    });
  }

  /** @ngInject */
  function parentController($rootScope) {
    $rootScope.preloadFinished = true;
  }

})();


text:
All notable changes to this project will be documented in this file, in reverse chronological order by release.

## 1.2.1 - 2016-07-12

### Added

- Nothing.

### Deprecated

- Nothing.

### Removed

- Nothing.

### Fixed

- [#97](https://github.com/zfcampus/zf-rest/pull/97) fixes `Location` header
  generation in the `RestController::create()` method to only use the `href`
  property of the relational link; previously, if you'd defined additional
  properties, these were also incorrectly serialized in the generated link.


text:
const arrayOfArrays = [[1, 2, 3], [4, 5], [6]];

const singleArray = arrayOfArrays.reduce((prev, cur) => {
    return prev.concat(cur);
});

console.log(singleArray);


text:
require 'fileutils'
require 'set'

module CartonDb
  class ListMapDb

    class Segment

      def self.in_db_for_hashcode(db_name, hashcode)
        seg_hash_part = hashcode[-1]
        seg_num = seg_hash_part.bytes[0] & 127

        group_hashcode = hashcode[0..-2]
        seg_group = ListMapDb::SegmentGroup.
          in_db_for_hashcode(db_name, group_hashcode)

        new(seg_group, "#{seg_num}.txt")
      end

      def self.each_in_db(db_name)
        ListMapDb::SegmentGroup.each_in_db db_name do |seg_group|
          Dir.entries(seg_group.directory_path).each do |de|
            next unless de =~ /^\d{1,3}[.]txt$/
            yield new(seg_group, de)
          end
        end
      end

      def self.clear_all_in_db(db_name)
        ListMapDb::SegmentGroup.each_in_db db_name do |seg_group|
          filenames = []
          Dir.entries(seg_group.directory_path).each do |de|
            next unless de =~ /^\d{1,3}[.]txt$/
            filename = File.join(seg_group.directory_path, de)
            filenames << filename
          end
          FileUtils.rm *filenames
        end
      end

      attr_accessor :segment_group,  :segment_filename
      private       :segment_group=, :segment_filename=

      def initialize(segment_group, segment_filename)
        self.segment_group = segment_group
        self.segment_filename = segment_filename
      end

      def filename
        File.join(segment_group.directory_path, segment_filename)
      end

      def content?
        stat && ! stat.zero?
      end

      def empty?
        ! content?
      end

      def key_count
        return 0 if empty?
        key_d_set.length
      end

      def touch_d(key_d, optimization)
        return if optimization == :small && key_d?(key_d)

        # Add a placeholder: An escaped key not followed by a tab
        # character.
        open_append do |io|
          io << key_d.escaped << "\n"
        end
      end

      def key_d_set
        result = Set.new
        each_entry_element_line do |kd, _ed, _line|
          result << kd
        end
        result
      end

      def key_d?(key_d)
        each_entry_element_line do |kd, _ed, _line|
          return true if kd = key_d
        end
        false
      end

      def element_d?(key_d, element_d)
        each_entry_element_line do |kd, ed, _line|
          return true if kd == key_d && ed == element_d
        end
        false
      end

      def collect_content(key_d, collection_class)
        result = nil
        each_element_for_d key_d do |ed|
          result ||= collection_class.new
          result << ed.plain unless ed.placeholder?
        end
        result
      end

      def each_entry
        entries = key_d_contents_map
        return unless entries
        entries.each do |key_d, content|
          yield key_d.plain, content
        end
      end

      def each_element_for_d(key_d)
        each_entry_element_line do |kd, ed, _line|
          next unless kd == key_d
          yield ed
        end
      end

      def each_first_element
        first_element_map = key_d_first_element_map
        return unless first_element_map

        first_element_map.each do |key_d, element|
          yield key_d.plain, element
        end
      end

      def each_entry_element_line
        return if empty?
        each_line do |line|
          # For a placeholder line, there is no tab character, so
          # esc_element is nil.
          esc_key, esc_element = line.strip.split("\t", 2)
          key_d = CartonDb::Datum.for_escaped(esc_key)
          element_d = CartonDb::Datum.for_escaped(
            esc_element, auto_placeholder: true)
          yield key_d, element_d, line
        end
      end

      def replace
        repl_name = "#{segment_filename}.temp"
        replacement = self.class.new(segment_group, repl_name)
        begin
          replacement.open_overwrite do |io|
            yield io
          end
        rescue StandardError
          File.unlink replacement.filename
          raise
        end
        File.unlink filename
        File.rename replacement.filename, filename
      end

      def write_key_element_d(key_d, element_d)
        open_append do |io|
          io << "#{key_d.escaped}\t#{element_d.escaped}\n"
        end
      end

      def write_key_d_elements(key_d, elements)
        open_append do |io|
          elements.each do |element|
            element_d = CartonDb::Datum.for_plain(element)
            io<< "#{key_d.escaped}\t#{element_d.escaped}\n"
          end
        end
      end

      def copy_entries_except(key_d, to_io)
        each_entry_element_line do |kd, _ed, line|
          to_io << line unless kd == key_d
        end
      end

      protected

      def open_overwrite
        touch_dir
        File.open filename, 'w', **FILE_ENCODING_OPTS do |io|
          yield io
        end
      end

      private

      def stat
        return @stat if defined? @stat
        return @stat = nil unless File.file?(filename)
        return @stat = File.stat(filename)
      end

      def open_read
        File.open filename, 'r', **FILE_ENCODING_OPTS do |io|
          yield io
        end
      end

      def open_append
        touch_dir
        File.open filename, 'a', **FILE_ENCODING_OPTS do |io|
          yield io
        end
      end

      def touch_dir
        dir = File.dirname(filename)
        return if File.directory?(dir)
        FileUtils.mkdir dir
      end

      def each_line
        open_read do |io|
          io.each_line do |line|
            yield line
          end
        end
      end

      def key_d_contents_map
        entries = nil
        each_entry_element_line do |key_d, elem_d, _line|
          entries ||= {}
          content = entries[key_d] ||= []
          content << elem_d.plain unless elem_d.placeholder?
        end
        entries
      end

      def key_d_first_element_map
        result = nil
        each_entry_element_line do |key_d, elem_d, _line|
          result ||= {}
          result[key_d] ||= elem_d.plain
        end
        return result
      end

    end

  end
end


text:
<?php

/**
 * @task discover   Discovering Repositories
 * @task svn        Discovering Subversion Repositories
 * @task git        Discovering Git Repositories
 * @task hg         Discovering Mercurial Repositories
 * @task internal   Internals
 */
final class PhabricatorRepositoryDiscoveryEngine
  extends PhabricatorRepositoryEngine {

  private $repairMode;
  private $commitCache = array();
  private $workingSet = array();

  const MAX_COMMIT_CACHE_SIZE = 65535;

/* -(  Discovering Repositories  )------------------------------------------- */

  public function setRepairMode($repair_mode) {
    $this->repairMode = $repair_mode;
    return $this;
  }

  public function getRepairMode() {
    return $this->repairMode;
  }

  /**
   * @task discovery
   */
  public function discoverCommits() {
    $repository = $this->getRepository();

    $lock = $this->newRepositoryLock($repository, 'repo.look', false);

    try {
      $lock->lock();
    } catch (PhutilLockException $ex) {
      throw new DiffusionDaemonLockException(
        pht(
          'Another process is currently discovering repository "%s", '.
          'skipping discovery.',
          $repository->getDisplayName()));
    }

    try {
      $result = $this->discoverCommitsWithLock();
    } catch (Exception $ex) {
      $lock->unlock();
      throw $ex;
    }

    $lock->unlock();

    return $result;
  }

  private function discoverCommitsWithLock() {
    $repository = $this->getRepository();
    $viewer = $this->getViewer();

    $vcs = $repository->getVersionControlSystem();
    switch ($vcs) {
      case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN:
        $refs = $this->discoverSubversionCommits();
        break;
      case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL:
        $refs = $this->discoverMercurialCommits();
        break;
      case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT:
        $refs = $this->discoverGitCommits();
        break;
      default:
        throw new Exception(pht("Unknown VCS '%s'!", $vcs));
    }

    if ($this->isInitialImport($refs)) {
      $this->log(
        pht(
          'Discovered more than %s commit(s) in an empty repository, '.
          'marking repository as importing.',
          new PhutilNumber(PhabricatorRepository::IMPORT_THRESHOLD)));

      $repository->markImporting();
    }

    // Clear the working set cache.
    $this->workingSet = array();

    $task_priority = $this->getImportTaskPriority($repository, $refs);

    // Record discovered commits and mark them in the cache.
    foreach ($refs as $ref) {
      $this->recordCommit(
        $repository,
        $ref->getIdentifier(),
        $ref->getEpoch(),
        $ref->getCanCloseImmediately(),
        $ref->getParents(),
        $task_priority);

      $this->commitCache[$ref->getIdentifier()] = true;
    }

    $this->markUnreachableCommits($repository);

    $version = $this->getObservedVersion($repository);
    if ($version !== null) {
      id(new DiffusionRepositoryClusterEngine())
        ->setViewer($viewer)
        ->setRepository($repository)
        ->synchronizeWorkingCopyAfterDiscovery($version);
    }

    return $refs;
  }

/* -(  Discovering Git Repositories  )--------------------------------------- */

  /**
   * @task git
   */
  private function discoverGitCommits() {
    $repository = $this->getRepository();
    $publisher = $repository->newPublisher();

    $heads = id(new DiffusionLowLevelGitRefQuery())
      ->setRepository($repository)
      ->execute();

    if (!$heads) {
      // This repository has no heads at all, so we don't need to do
      // anything. Generally, this means the repository is empty.
      return array();
    }

    $heads = $this->sortRefs($heads);
    $head_commits = mpull($heads, 'getCommitIdentifier');

    $this->log(
      pht(
        'Discovering commits in repository "%s".',
        $repository->getDisplayName()));

    $this->fillCommitCache($head_commits);

    $refs = array();
    foreach ($heads as $ref) {
      $name = $ref->getShortName();
      $commit = $ref->getCommitIdentifier();

      $this->log(
        pht(
          'Examining "%s" (%s) at "%s".',
          $name,
          $ref->getRefType(),
          $commit));

      if (!$repository->shouldTrackRef($ref)) {
        $this->log(pht('Skipping, ref is untracked.'));
        continue;
      }

      if ($this->isKnownCommit($commit)) {
        $this->log(pht('Skipping, HEAD is known.'));
        continue;
      }

      // In Git, it's possible to tag anything. We just skip tags that don't
      // point to a commit. See T11301.
      $fields = $ref->getRawFields();
      $ref_type = idx($fields, 'objecttype');
      $tag_type = idx($fields, '*objecttype');
      if ($ref_type != 'commit' && $tag_type != 'commit') {
        $this->log(pht('Skipping, this is not a commit.'));
        continue;
      }

      $this->log(pht('Looking for new commits.'));

      $head_refs = $this->discoverStreamAncestry(
        new PhabricatorGitGraphStream($repository, $commit),
        $commit,
        $publisher->shouldPublishRef($ref));

      $this->didDiscoverRefs($head_refs);

      $refs[] = $head_refs;
    }

    return array_mergev($refs);
  }

/* -(  Discovering Subversion Repositories  )-------------------------------- */

  /**
   * @task svn
   */
  private function discoverSubversionCommits() {
    $repository = $this->getRepository();

    if (!$repository->isHosted()) {
      $this->verifySubversionRoot($repository);
    }

    $upper_bound = null;
    $limit = 1;
    $refs = array();
    do {
      // Find all the unknown commits on this path. Note that we permit
      // importing an SVN subdirectory rather than the entire repository, so
      // commits may be nonsequential.

      if ($upper_bound === null) {
        $at_rev = 'HEAD';
      } else {
        $at_rev = ($upper_bound - 1);
      }

      try {
        list($xml, $stderr) = $repository->execxRemoteCommand(
          'log --xml --quiet --limit %d %s',
          $limit,
          $repository->getSubversionBaseURI($at_rev));
      } catch (CommandException $ex) {
        $stderr = $ex->getStderr();
        if (preg_match('/(path|File) not found/', $stderr)) {
          // We've gone all the way back through history and this path was not
          // affected by earlier commits.
          break;
        }
        throw $ex;
      }

      $xml = phutil_utf8ize($xml);
      $log = new SimpleXMLElement($xml);
      foreach ($log->logentry as $entry) {
        $identifier = (int)$entry['revision'];
        $epoch = (int)strtotime((string)$entry->date[0]);
        $refs[$identifier] = id(new PhabricatorRepositoryCommitRef())
          ->setIdentifier($identifier)
          ->setEpoch($epoch)
          ->setCanCloseImmediately(true);

        if ($upper_bound === null) {
          $upper_bound = $identifier;
        } else {
          $upper_bound = min($upper_bound, $identifier);
        }
      }

      // Discover 2, 4, 8, ... 256 logs at a time. This allows us to initially
      // import large repositories fairly quickly, while pulling only as much
      // data as we need in the common case (when we've already imported the
      // repository and are just grabbing one commit at a time).
      $limit = min($limit * 2, 256);

    } while ($upper_bound > 1 && !$this->isKnownCommit($upper_bound));

    krsort($refs);
    while ($refs && $this->isKnownCommit(last($refs)->getIdentifier())) {
      array_pop($refs);
    }
    $refs = array_reverse($refs);

    $this->didDiscoverRefs($refs);

    return $refs;
  }

  private function verifySubversionRoot(PhabricatorRepository $repository) {
    list($xml) = $repository->execxRemoteCommand(
      'info --xml %s',
      $repository->getSubversionPathURI());

    $xml = phutil_utf8ize($xml);
    $xml = new SimpleXMLElement($xml);

    $remote_root = (string)($xml->entry[0]->repository[0]->root[0]);
    $expect_root = $repository->getSubversionPathURI();

    $normal_type_svn = PhabricatorRepositoryURINormalizer::TYPE_SVN;

    $remote_normal = id(new PhabricatorRepositoryURINormalizer(
      $normal_type_svn,
      $remote_root))->getNormalizedPath();

    $expect_normal = id(new PhabricatorRepositoryURINormalizer(
      $normal_type_svn,
      $expect_root))->getNormalizedPath();

    if ($remote_normal != $expect_normal) {
      throw new Exception(
        pht(
          'Repository "%s" does not have a correctly configured remote URI. '.
          'The remote URI for a Subversion repository MUST point at the '.
          'repository root. The root for this repository is "%s", but the '.
          'configured URI is "%s". To resolve this error, set the remote URI '.
          'to point at the repository root. If you want to import only part '.
          'of a Subversion repository, use the "Import Only" option.',
          $repository->getDisplayName(),
          $remote_root,
          $expect_root));
    }
  }

/* -(  Discovering Mercurial Repositories  )--------------------------------- */

  /**
   * @task hg
   */
  private function discoverMercurialCommits() {
    $repository = $this->getRepository();

    $branches = id(new DiffusionLowLevelMercurialBranchesQuery())
      ->setRepository($repository)
      ->execute();

    $this->fillCommitCache(mpull($branches, 'getCommitIdentifier'));

    $refs = array();
    foreach ($branches as $branch) {
      // NOTE: Mercurial branches may have multiple heads, so the names may
      // not be unique.
      $name = $branch->getShortName();
      $commit = $branch->getCommitIdentifier();

      $this->log(pht('Examining branch "%s" head "%s".', $name, $commit));
      if (!$repository->shouldTrackBranch($name)) {
        $this->log(pht('Skipping, branch is untracked.'));
        continue;
      }

      if ($this->isKnownCommit($commit)) {
        $this->log(pht('Skipping, this head is a known commit.'));
        continue;
      }

      $this->log(pht('Looking for new commits.'));

      $branch_refs = $this->discoverStreamAncestry(
        new PhabricatorMercurialGraphStream($repository, $commit),
        $commit,
        $close_immediately = true);

      $this->didDiscoverRefs($branch_refs);

      $refs[] = $branch_refs;
    }

    return array_mergev($refs);
  }

/* -(  Internals  )---------------------------------------------------------- */

  private function discoverStreamAncestry(
    PhabricatorRepositoryGraphStream $stream,
    $commit,
    $close_immediately) {

    $discover = array($commit);
    $graph = array();
    $seen = array();

    // Find all the reachable, undiscovered commits. Build a graph of the
    // edges.
    while ($discover) {
      $target = array_pop($discover);

      if (empty($graph[$target])) {
        $graph[$target] = array();
      }

      $parents = $stream->getParents($target);
      foreach ($parents as $parent) {
        if ($this->isKnownCommit($parent)) {
          continue;
        }

        $graph[$target][$parent] = true;

        if (empty($seen[$parent])) {
          $seen[$parent] = true;
          $discover[] = $parent;
        }
      }
    }

    // Now, sort them topologically.
    $commits = $this->reduceGraph($graph);

    $refs = array();
    foreach ($commits as $commit) {
      $epoch = $stream->getCommitDate($commit);

      // If the epoch doesn't fit into a uint32, treat it as though it stores
      // the current time. For discussion, see T11537.
      if ($epoch > 0xFFFFFFFF) {
        $epoch = PhabricatorTime::getNow();
      }

      // If the epoch is not present at all, treat it as though it stores the
      // value "0". For discussion, see T12062. This behavior is consistent
      // with the behavior of "git show".
      if (!strlen($epoch)) {
        $epoch = 0;
      }

      $refs[] = id(new PhabricatorRepositoryCommitRef())
        ->setIdentifier($commit)
        ->setEpoch($epoch)
        ->setCanCloseImmediately($close_immediately)
        ->setParents($stream->getParents($commit));
    }

    return $refs;
  }

  private function reduceGraph(array $edges) {
    foreach ($edges as $commit => $parents) {
      $edges[$commit] = array_keys($parents);
    }

    $graph = new PhutilDirectedScalarGraph();
    $graph->addNodes($edges);

    $commits = $graph->getNodesInTopologicalOrder();

    // NOTE: We want the most ancestral nodes first, so we need to reverse the
    // list we get out of AbstractDirectedGraph.
    $commits = array_reverse($commits);

    return $commits;
  }

  private function isKnownCommit($identifier) {
    if (isset($this->commitCache[$identifier])) {
      return true;
    }

    if (isset($this->workingSet[$identifier])) {
      return true;
    }

    if ($this->repairMode) {
      // In repair mode, rediscover the entire repository, ignoring the
      // database state. We can hit the local cache above, but if we miss it
      // stop the script from going to the database cache.
      return false;
    }

    $this->fillCommitCache(array($identifier));

    return isset($this->commitCache[$identifier]);
  }

  private function fillCommitCache(array $identifiers) {
    if (!$identifiers) {
      return;
    }

    $max_size = self::MAX_COMMIT_CACHE_SIZE;

    // If we're filling more identifiers than would fit in the cache, ignore
    // the ones that don't fit. Because the cache is FIFO, overfilling it can
    // cause the entire cache to miss. See T12296.
    if (count($identifiers) > $max_size) {
      $identifiers = array_slice($identifiers, 0, $max_size);
    }

    // When filling the cache we ignore commits which have been marked as
    // unreachable, treating them as though they do not exist. When recording
    // commits later we'll revive commits that exist but are unreachable.

    $commits = id(new PhabricatorRepositoryCommit())->loadAllWhere(
      'repositoryID = %d AND commitIdentifier IN (%Ls)
        AND (importStatus & %d) != %d',
      $this->getRepository()->getID(),
      $identifiers,
      PhabricatorRepositoryCommit::IMPORTED_UNREACHABLE,
      PhabricatorRepositoryCommit::IMPORTED_UNREACHABLE);

    foreach ($commits as $commit) {
      $this->commitCache[$commit->getCommitIdentifier()] = true;
    }

    while (count($this->commitCache) > $max_size) {
      array_shift($this->commitCache);
    }
  }

  /**
   * Sort branches so we process closeable branches first. This makes the
   * whole import process a little cheaper, since we can close these commits
   * the first time through rather than catching them in the refs step.
   *
   * @task internal
   *
   * @param   list<DiffusionRepositoryRef> List of refs.
   * @return  list<DiffusionRepositoryRef> Sorted list of refs.
   */
  private function sortRefs(array $refs) {
    $repository = $this->getRepository();
    $publisher = $repository->newPublisher();

    $head_refs = array();
    $tail_refs = array();
    foreach ($refs as $ref) {
      if ($publisher->shouldPublishRef($ref)) {
        $head_refs[] = $ref;
      } else {
        $tail_refs[] = $ref;
      }
    }

    return array_merge($head_refs, $tail_refs);
  }

  private function recordCommit(
    PhabricatorRepository $repository,
    $commit_identifier,
    $epoch,
    $close_immediately,
    array $parents,
    $task_priority) {

    $commit = new PhabricatorRepositoryCommit();
    $conn_w = $repository->establishConnection('w');

    // First, try to revive an existing unreachable commit (if one exists) by
    // removing the "unreachable" flag. If we succeed, we don't need to do
    // anything else: we already discovered this commit some time ago.
    queryfx(
      $conn_w,
      'UPDATE %T SET importStatus = (importStatus & ~%d)
        WHERE repositoryID = %d AND commitIdentifier = %s',
      $commit->getTableName(),
      PhabricatorRepositoryCommit::IMPORTED_UNREACHABLE,
      $repository->getID(),
      $commit_identifier);
    if ($conn_w->getAffectedRows()) {
      $commit = $commit->loadOneWhere(
        'repositoryID = %d AND commitIdentifier = %s',
        $repository->getID(),
        $commit_identifier);

      // After reviving a commit, schedule new daemons for it.
      $this->didDiscoverCommit($repository, $commit, $epoch, $task_priority);
      return;
    }

    $commit->setRepositoryID($repository->getID());
    $commit->setCommitIdentifier($commit_identifier);
    $commit->setEpoch($epoch);
    if ($close_immediately) {
      $commit->setImportStatus(PhabricatorRepositoryCommit::IMPORTED_CLOSEABLE);
    }

    $data = new PhabricatorRepositoryCommitData();

    try {
      // If this commit has parents, look up their IDs. The parent commits
      // should always exist already.

      $parent_ids = array();
      if ($parents) {
        $parent_rows = queryfx_all(
          $conn_w,
          'SELECT id, commitIdentifier FROM %T
            WHERE commitIdentifier IN (%Ls) AND repositoryID = %d',
          $commit->getTableName(),
          $parents,
          $repository->getID());

        $parent_map = ipull($parent_rows, 'id', 'commitIdentifier');

        foreach ($parents as $parent) {
          if (empty($parent_map[$parent])) {
            throw new Exception(
              pht('Unable to identify parent "%s"!', $parent));
          }
          $parent_ids[] = $parent_map[$parent];
        }
      } else {
        // Write an explicit 0 so we can distinguish between "really no
        // parents" and "data not available".
        if (!$repository->isSVN()) {
          $parent_ids = array(0);
        }
      }

      $commit->openTransaction();
        $commit->save();

        $data->setCommitID($commit->getID());
        $data->save();

        foreach ($parent_ids as $parent_id) {
          queryfx(
            $conn_w,
            'INSERT IGNORE INTO %T (childCommitID, parentCommitID)
              VALUES (%d, %d)',
            PhabricatorRepository::TABLE_PARENTS,
            $commit->getID(),
            $parent_id);
        }
      $commit->saveTransaction();

      $this->didDiscoverCommit($repository, $commit, $epoch, $task_priority);

      if ($this->repairMode) {
        // Normally, the query should throw a duplicate key exception. If we
        // reach this in repair mode, we've actually performed a repair.
        $this->log(pht('Repaired commit "%s".', $commit_identifier));
      }

      PhutilEventEngine::dispatchEvent(
        new PhabricatorEvent(
          PhabricatorEventType::TYPE_DIFFUSION_DIDDISCOVERCOMMIT,
          array(
            'repository'  => $repository,
            'commit'      => $commit,
          )));

    } catch (AphrontDuplicateKeyQueryException $ex) {
      $commit->killTransaction();
      // Ignore. This can happen because we discover the same new commit
      // more than once when looking at history, or because of races or
      // data inconsistency or cosmic radiation; in any case, we're still
      // in a good state if we ignore the failure.
    }
  }

  private function didDiscoverCommit(
    PhabricatorRepository $repository,
    PhabricatorRepositoryCommit $commit,
    $epoch,
    $task_priority) {

    $this->insertTask($repository, $commit, $task_priority);

    // Update the repository summary table.
    queryfx(
      $commit->establishConnection('w'),
      'INSERT INTO %T (repositoryID, size, lastCommitID, epoch)
        VALUES (%d, 1, %d, %d)
        ON DUPLICATE KEY UPDATE
          size = size + 1,
          lastCommitID =
            IF(VALUES(epoch) > epoch, VALUES(lastCommitID), lastCommitID),
          epoch = IF(VALUES(epoch) > epoch, VALUES(epoch), epoch)',
      PhabricatorRepository::TABLE_SUMMARY,
      $repository->getID(),
      $commit->getID(),
      $epoch);
  }

  private function didDiscoverRefs(array $refs) {
    foreach ($refs as $ref) {
      $this->workingSet[$ref->getIdentifier()] = true;
    }
  }

  private function insertTask(
    PhabricatorRepository $repository,
    PhabricatorRepositoryCommit $commit,
    $task_priority,
    $data = array()) {

    $vcs = $repository->getVersionControlSystem();
    switch ($vcs) {
      case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT:
        $class = 'PhabricatorRepositoryGitCommitMessageParserWorker';
        break;
      case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN:
        $class = 'PhabricatorRepositorySvnCommitMessageParserWorker';
        break;
      case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL:
        $class = 'PhabricatorRepositoryMercurialCommitMessageParserWorker';
        break;
      default:
        throw new Exception(pht("Unknown repository type '%s'!", $vcs));
    }

    $data['commitID'] = $commit->getID();

    $options = array(
      'priority' => $task_priority,
    );

    PhabricatorWorker::scheduleTask($class, $data, $options);
  }

  private function isInitialImport(array $refs) {
    $commit_count = count($refs);

    if ($commit_count <= PhabricatorRepository::IMPORT_THRESHOLD) {
      // If we fetched a small number of commits, assume it's an initial
      // commit or a stack of a few initial commits.
      return false;
    }

    $viewer = $this->getViewer();
    $repository = $this->getRepository();

    $any_commits = id(new DiffusionCommitQuery())
      ->setViewer($viewer)
      ->withRepository($repository)
      ->setLimit(1)
      ->execute();

    if ($any_commits) {
      // If the repository already has commits, this isn't an import.
      return false;
    }

    return true;
  }

  private function getObservedVersion(PhabricatorRepository $repository) {
    if ($repository->isHosted()) {
      return null;
    }

    if ($repository->isGit()) {
      return $this->getGitObservedVersion($repository);
    }

    return null;
  }

  private function getGitObservedVersion(PhabricatorRepository $repository) {
    $refs = id(new DiffusionLowLevelGitRefQuery())
     ->setRepository($repository)
     ->execute();
    if (!$refs) {
      return null;
    }

    // In Git, the observed version is the most recently discovered commit
    // at any repository HEAD. It's possible for this to regress temporarily
    // if a branch is pushed and then deleted. This is acceptable because it
    // doesn't do anything meaningfully bad and will fix itself on the next
    // push.

    $ref_identifiers = mpull($refs, 'getCommitIdentifier');
    $ref_identifiers = array_fuse($ref_identifiers);

    $version = queryfx_one(
      $repository->establishConnection('w'),
      'SELECT MAX(id) version FROM %T WHERE repositoryID = %d
        AND commitIdentifier IN (%Ls)',
      id(new PhabricatorRepositoryCommit())->getTableName(),
      $repository->getID(),
      $ref_identifiers);

    if (!$version) {
      return null;
    }

    return (int)$version['version'];
  }

  private function markUnreachableCommits(PhabricatorRepository $repository) {
    // For now, this is only supported for Git.
    if (!$repository->isGit()) {
      return;
    }

    // Find older versions of refs which we haven't processed yet. We're going
    // to make sure their commits are still reachable.
    $old_refs = id(new PhabricatorRepositoryOldRef())->loadAllWhere(
      'repositoryPHID = %s',
      $repository->getPHID());

    // If we don't have any refs to update, bail out before building a graph
    // stream. In particular, this improves behavior in empty repositories,
    // where `git log` exits with an error.
    if (!$old_refs) {
      return;
    }

    // We can share a single graph stream across all the checks we need to do.
    $stream = new PhabricatorGitGraphStream($repository);

    foreach ($old_refs as $old_ref) {
      $identifier = $old_ref->getCommitIdentifier();
      $this->markUnreachableFrom($repository, $stream, $identifier);

      // If nothing threw an exception, we're all done with this ref.
      $old_ref->delete();
    }
  }

  private function markUnreachableFrom(
    PhabricatorRepository $repository,
    PhabricatorGitGraphStream $stream,
    $identifier) {

    $unreachable = array();

    $commit = id(new PhabricatorRepositoryCommit())->loadOneWhere(
      'repositoryID = %s AND commitIdentifier = %s',
      $repository->getID(),
      $identifier);
    if (!$commit) {
      return;
    }

    $look = array($commit);
    $seen = array();
    while ($look) {
      $target = array_pop($look);

      // If we've already checked this commit (for example, because history
      // branches and then merges) we don't need to check it again.
      $target_identifier = $target->getCommitIdentifier();
      if (isset($seen[$target_identifier])) {
        continue;
      }

      $seen[$target_identifier] = true;

      try {
        $stream->getCommitDate($target_identifier);
        $reachable = true;
      } catch (Exception $ex) {
        $reachable = false;
      }

      if ($reachable) {
        // This commit is reachable, so we don't need to go any further
        // down this road.
        continue;
      }

      $unreachable[] = $target;

      // Find the commit's parents and check them for reachability, too. We
      // have to look in the database since we no may longer have the commit
      // in the repository.
      $rows = queryfx_all(
        $commit->establishConnection('w'),
        'SELECT commit.* FROM %T commit
          JOIN %T parents ON commit.id = parents.parentCommitID
          WHERE parents.childCommitID = %d',
        $commit->getTableName(),
        PhabricatorRepository::TABLE_PARENTS,
        $target->getID());
      if (!$rows) {
        continue;
      }

      $parents = id(new PhabricatorRepositoryCommit())
        ->loadAllFromArray($rows);
      foreach ($parents as $parent) {
        $look[] = $parent;
      }
    }

    $unreachable = array_reverse($unreachable);

    $flag = PhabricatorRepositoryCommit::IMPORTED_UNREACHABLE;
    foreach ($unreachable as $unreachable_commit) {
      $unreachable_commit->writeImportStatusFlag($flag);
    }

    // If anything was unreachable, just rebuild the whole summary table.
    // We can't really update it incrementally when a commit becomes
    // unreachable.
    if ($unreachable) {
      $this->rebuildSummaryTable($repository);
    }
  }

  private function rebuildSummaryTable(PhabricatorRepository $repository) {
    $conn_w = $repository->establishConnection('w');

    $data = queryfx_one(
      $conn_w,
      'SELECT COUNT(*) N, MAX(id) id, MAX(epoch) epoch
        FROM %T WHERE repositoryID = %d AND (importStatus & %d) != %d',
      id(new PhabricatorRepositoryCommit())->getTableName(),
      $repository->getID(),
      PhabricatorRepositoryCommit::IMPORTED_UNREACHABLE,
      PhabricatorRepositoryCommit::IMPORTED_UNREACHABLE);

    queryfx(
      $conn_w,
      'INSERT INTO %T (repositoryID, size, lastCommitID, epoch)
        VALUES (%d, %d, %d, %d)
        ON DUPLICATE KEY UPDATE
          size = VALUES(size),
          lastCommitID = VALUES(lastCommitID),
          epoch = VALUES(epoch)',
      PhabricatorRepository::TABLE_SUMMARY,
      $repository->getID(),
      $data['N'],
      $data['id'],
      $data['epoch']);
  }

  private function getImportTaskPriority(
    PhabricatorRepository $repository,
    array $refs) {

    // If the repository is importing for the first time, we schedule tasks
    // at IMPORT priority, which is very low. Making progress on importing a
    // new repository for the first time is less important than any other
    // daemon task.

    // If the repository has finished importing and we're just catching up
    // on recent commits, we usually schedule discovery at COMMIT priority,
    // which is slightly below the default priority.

    // Note that followup tasks and triggered tasks (like those generated by
    // Herald or Harbormaster) will queue at DEFAULT priority, so that each
    // commit tends to fully import before we start the next one. This tends
    // to give imports fairly predictable progress. See T11677 for some
    // discussion.

    if ($repository->isImporting()) {
      $this->log(
        pht(
          'Importing %s commit(s) at low priority ("PRIORITY_IMPORT") '.
          'because this repository is still importing.',
          phutil_count($refs)));

      return PhabricatorWorker::PRIORITY_IMPORT;
    }

    // See T13369. If we've discovered a lot of commits at once, import them
    // at lower priority.

    // This is mostly aimed at reducing the impact that synchronizing thousands
    // of commits from a remote upstream has on other repositories. The queue
    // is "mostly FIFO", so queueing a thousand commit imports can stall other
    // repositories.

    // In a perfect world we'd probably give repositories round-robin queue
    // priority, but we don't currently have the primitives for this and there
    // isn't a strong case for building them.

    // Use "a whole lot of commits showed up at once" as a heuristic for
    // detecting "someone synchronized an upstream", and import them at a lower
    // priority to more closely approximate fair scheduling.

    if (count($refs) >= PhabricatorRepository::LOWPRI_THRESHOLD) {
      $this->log(
        pht(
          'Importing %s commit(s) at low priority ("PRIORITY_IMPORT") '.
          'because many commits were discovered at once.',
          phutil_count($refs)));

      return PhabricatorWorker::PRIORITY_IMPORT;
    }

    // Otherwise, import at normal priority.

    if ($refs) {
      $this->log(
        pht(
          'Importing %s commit(s) at normal priority ("PRIORITY_COMMIT").',
          phutil_count($refs)));
    }

    return PhabricatorWorker::PRIORITY_COMMIT;
  }

}


text:
"""
Copyright 2015 SmartBear Software

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

    Ref: https://github.com/swagger-api/swagger-codegen
"""

from pprint import pformat
from six import iteritems

class V1Capabilities(object):
    """
    NOTE: This class is auto generated by the swagger code generator program.
    Do not edit the class manually.
    """
    def __init__(self):
        """
        V1Capabilities - a model defined in Swagger

        :param dict swaggerTypes: The key is attribute name
                                  and the value is attribute type.
        :param dict attributeMap: The key is attribute name
                                  and the value is json key in definition.
        """
        self.swagger_types = {
            'add': 'list[V1Capability]',
            'drop': 'list[V1Capability]'
        }

        self.attribute_map = {
            'add': 'add',
            'drop': 'drop'
        }

        self._add = None
        self._drop = None

    @property
    def add(self):
        """
        Gets the add of this V1Capabilities.
        Added capabilities

        :return: The add of this V1Capabilities.
        :rtype: list[V1Capability]
        """
        return self._add

    @add.setter
    def add(self, add):
        """
        Sets the add of this V1Capabilities.
        Added capabilities

        :param add: The add of this V1Capabilities.
        :type: list[V1Capability]
        """
        self._add = add

    @property
    def drop(self):
        """
        Gets the drop of this V1Capabilities.
        Removed capabilities

        :return: The drop of this V1Capabilities.
        :rtype: list[V1Capability]
        """
        return self._drop

    @drop.setter
    def drop(self, drop):
        """
        Sets the drop of this V1Capabilities.
        Removed capabilities

        :param drop: The drop of this V1Capabilities.
        :type: list[V1Capability]
        """
        self._drop = drop

    def to_dict(self):
        """
        Returns the model properties as a dict
        """
        result = {}

        for attr, _ in iteritems(self.swagger_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            else:
                result[attr] = value

        return result

    def to_str(self):
        """
        Returns the string representation of the model
        """
        return pformat(self.to_dict())

    def __repr__(self):
        """
        For `print` and `pprint`
        """
        return self.to_str()

    def __eq__(self, other):
        """
        Returns true if both objects are equal
        """
        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        """
        Returns true if both objects are not equal
        """
        return not self == other


text:
import mongoose         from 'mongoose-fill';
import { modelCleaner } from '../../db/utils';

const ObjectId = mongoose.Schema.Types.ObjectId;

const AttachmentSchema = new mongoose.Schema({
  url: {
    type:     String
  },
  contentType: {
    type:     String
  },
  filename: {
    type:     String
  },
  size: {
    type:     Number
  }
}, {
  timestamps: {
    createdAt: 'createdAt',
    updatedAt: 'updatedAt'
  }
});

modelCleaner(AttachmentSchema);
export default mongoose.model('Attachment', AttachmentSchema);


text:
  #include "Arduino.h"
#else
  #include "WProgram.h"
#endif

class GrafComms
{
 public:
  GrafComms () ;

  virtual void  resetChip () = 0 ;

  virtual void  wr_comm (byte comm) = 0 ;
  virtual void  wr_data (byte data) = 0 ;
  virtual void  wr_data_16 (unsigned int data) = 0 ;
  virtual void  wr_data_16xN (unsigned int data, byte count) = 0 ;
  virtual unsigned int  rd_data_16 () = 0 ;

  virtual unsigned int  read_reg (byte reg) = 0 ;
  virtual void  write_reg (byte reg, unsigned int val) = 0 ;

  virtual void  gen_start_ram (byte ram_comm) = 0 ;
  virtual void  write_ram (unsigned int val) = 0 ;
  virtual void  start_ram () = 0 ;
  virtual void  stop_ram () = 0 ;
};

#endif


text:
author: chipoglesby
comments: true
date: 2007-02-14 04:37:00+00:00
layout: post
slug: crooners-and-swooners
title: Crooners and Swooners
wordpress_id: 127
categories:
- Photojournalism
---

This was taken down at Art Bar in Columbia for their Crooners and Swooner's Valentines Day event.[![](http://bp0.blogger.com/_GlcbreYSTwI/RdKShIo4ZbI/AAAAAAAAAAo/7CaCGfhPEak/s400/IMG_9193.jpg)](http://bp0.blogger.com/_GlcbreYSTwI/RdKShIo4ZbI/AAAAAAAAAAo/7CaCGfhPEak/s1600-h/IMG_9193.jpg)


text:
package io.github.qwefgh90.handyfinder.memory.monitor;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

import com.beust.jcommander.ParameterException;
/**
 * FunctionalLatch class provides functional tools for awaiting and release.
 * Default value which is for release is 1. You can set this value at any time.
 *

Every second, a internal timer executes functions and release threads which return true.
 *
 * @author qwefgh90
 *
 */
public class FunctionalLatch {
	private final List<Locker> lockerList = Collections.synchronizedList(new ArrayList<Locker>());
	private final Timer timer = new Timer(true); //make a daemon thread
	private volatile boolean terminated = false;
	private volatile int numberAtOnceForRelease;

	/**
	 * Initialize a functional latch.
	 * At once, one thread is released.
	 */
	public FunctionalLatch(){
		this(1);
	}

	/**
	 * Initialize a functional latch.
	 * @param numberAtOnceForRelease a number greater than zero
	 */
	public FunctionalLatch(int numberAtOnceForRelease){
		if(numberAtOnceForRelease <= 0)
			throw new ParameterException("numberAtOnceForRelease is less than one. " + numberAtOnceForRelease);
		this.numberAtOnceForRelease = numberAtOnceForRelease;
		timer.schedule(new ConditionChecker(), 0, ConditionChecker.CHECK_INTERVAL); // Start checking lockers
	}

	/**
	 * Setter for the number of thread which will be released at once.
	 * @param numberAtOnceForRelease number
	 */
	public void setNumberAtOnceRelease(int numberAtOnceForRelease){
		if(numberAtOnceForRelease <= 0)
			return;
		this.numberAtOnceForRelease = numberAtOnceForRelease;
	}

	/**
	 * Causes the current thread to wait until receiving a signal.
	 * @return
	 * @throws InterruptedException
	 * @throws IllegalStateException
	 */
	public void await() throws InterruptedException{
		if(terminated)
			throw new IllegalStateException("A latch is already terminated.");
		final CountDownLatch latch = new CountDownLatch(1);
		final Locker loc = new Locker(Optional.empty(), Optional.empty(), Optional.of(latch));
		lockerList.add(loc);
		latch.await();

	}

	/**
	 * Causes the current thread to wait until receiving a signal or conditions are met.
	 * @param f it's for release. if returning true, releases a thread
	 * @param interval second between 1 and 3600. it's related to how often a timer executes a function
	 * @return
	 * @throws InterruptedException
	 * @throws IllegalStateException
	 * @throws NullPointerException
	 */
	public void await(Supplier<Boolean> f, long interval) throws InterruptedException{
		if(terminated)
			throw new IllegalStateException("A latch is already terminated.");
		if(f == null)
			throw new NullPointerException("Function parameter is null.");
		if(interval < 1 || interval > ConditionChecker.END_OF_SECONDS)
			throw new IllegalStateException("Invalid interval is found. " + interval);

		final CountDownLatch latch = new CountDownLatch(1);
		final Locker loc = new Locker(Optional.of(f), Optional.of(interval), Optional.of(latch));
		lockerList.add(loc);
		latch.await();
	}

	/**
	 * Causes the current thread to wait until receiving a signal or timeout or conditions are met.
	 * @param f it's for release. if returning true, releases a thread
	 * @param interval second between 1 and 3600. it's related to how often a timer executes a function
	 * @param timeout maximum waiting time
	 * @param unit it's for timeout
	 * @return
	 * @throws InterruptedException
	 * @throws IllegalStateException
	 * @throws NullPointerException
	 */
	public void await(Supplier<Boolean> f, long interval, long timeout, TimeUnit unit) throws InterruptedException{
		if(terminated)
			throw new IllegalStateException("A latch is already terminated.");
		if(f == null || unit == null)
			throw new NullPointerException("Function parameter or time unit is null.");
		if(interval < 1 || interval > ConditionChecker.END_OF_SECONDS)
			throw new IllegalStateException("Invalid interval is found. " + interval);

		final CountDownLatch latch = new CountDownLatch(1);
		final Locker loc = new Locker(Optional.of(f), Optional.of(interval), Optional.of(latch));
		lockerList.add(loc);
		latch.await(timeout, unit);
	}

	/**
	 * Releases all threads.
	 * @return a number of threads which receive signal.
	 */
	public int signalAll(){
		int countOfActiveThreads = 0;
		//https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#synchronizedList(java.util.List)
		//It's imperative.
		synchronized(lockerList){
			final Iterator<Locker> iter = lockerList.iterator();
			while(iter.hasNext()){
				final Locker cond = iter.next();
				final boolean success =
						cond.latch.map(latch -> {
							iter.remove();
							latch.countDown();
							return true;
						}).orElse(false);
				if(success)
					countOfActiveThreads++;

			}
		}
		return countOfActiveThreads;
	}

	/**
	 * Signal the latch and terminate the latch.
	 * This latch can't used after it's called.
	 */
	public void terminate(){
		//1) set a flag
		terminated = true;
		//2) cancel a timer (release all waiting threads.)
		timer.cancel();
		//3) signal all latch for release
		signalAll();
	}

	/**
	 * Locker is private class and contains function which return boolean value, latch, interval for checking.
	 * @author qwefgh90
	 *
	 */
	private class Locker{
		private final Optional<Supplier<Boolean>> f;
		private final Optional<Long> interval;
		private final Optional<CountDownLatch> latch;
		private Locker(Optional<Supplier<Boolean>> f, Optional<Long> interval, Optional<CountDownLatch> latch){
			this.f = f;
			this.interval = interval;
			this.latch = latch;
		}
	}

	/**
	 * This which is used by a timer iterates all elements and decides whether to release threads in elements by itself.
	 *

This class is a implementation of TimerTask.
	 * @author qwefgh90
	 *
	 */
	private class ConditionChecker extends TimerTask{
		private static final long END_OF_SECONDS = 3600L;
		private static final long CHECK_INTERVAL = 1000; // Check it every 1000 millisecond
		private volatile long count = 1;
		@Override
		public void run() {
			int numberAtOnceForRelease = FunctionalLatch.this.numberAtOnceForRelease;
			// Check for all lockers
			synchronized(lockerList){
				final Iterator<Locker> iter = lockerList.iterator();
				while(iter.hasNext()){
					if(numberAtOnceForRelease == 0){
						break;
					}
					final Locker loc = iter.next();
					if((count % loc.interval.orElse(1L) == 0) && loc.f.orElse(() -> false).get() == true){
						boolean success = loc.latch.map(latch -> {
							iter.remove();
							latch.countDown();// If the condition is true, release thread.
							return true;
						}).orElse(false);
						if(success)
							numberAtOnceForRelease--;
					}
				}

				count++;
				if(count > ConditionChecker.END_OF_SECONDS)
					count = 1;
			}
		}
	}
}