text:
/* $Id$ */

package org.apache.fop.layoutmgr;

import java.util.Collections;
import java.util.List;

import org.apache.fop.fo.Constants;
import org.apache.fop.layoutmgr.inline.AlignmentContext;
import org.apache.fop.layoutmgr.inline.HyphContext;
import org.apache.fop.traits.MinOptMax;
import org.apache.fop.traits.WritingMode;

/**
 * This class is used to pass information to the getNextKnuthElements()
 * method. It is set up by higher level LM and used by lower level LM.
 */
public class LayoutContext {

    /**  linebreak at line feed only flag */
    public static final int LINEBREAK_AT_LF_ONLY = 0x01;
    /** Generated break possibility is first in a new area */
    public static final int NEW_AREA = 0x02;
    /**  ipd unknown flag */
    public static final int IPD_UNKNOWN = 0x04;
    /** Signal to a Line LM that a higher level LM may provoke a change
     *  in the reference area, thus ref area IPD. The LineLM should return
     *  without looking for a line break.
     */
    public static final int CHECK_REF_AREA = 0x08;

    /**
     * If this flag is set, it indicates that any break-before values other than "auto" should
     * not cause a mandatory break as this break was already handled by a parent layout manager.
     */
    public static final int SUPPRESS_BREAK_BEFORE = 0x10;
    /** first area flag */
    public static final int FIRST_AREA = 0x20;
    /** try hypenate flag */
    public static final int TRY_HYPHENATE = 0x40;
    /** last area flag */
    public static final int LAST_AREA = 0x80;
    /**  resolve leading space flag */
    public static final int RESOLVE_LEADING_SPACE = 0x100;

    /**
     * This flag indicates that there's a keep-with-next that hasn't
     * been processed, yet.
     */
    //public static final int KEEP_WITH_NEXT_PENDING = 0x200;
    /**
     * This flag indicates that there's a keep-with-previous that hasn't
     * been processed, yet.
     */
    //public static final int KEEP_WITH_PREVIOUS_PENDING = 0x400;

    private int flags; // Contains some set of flags defined above
    /**
     * Total available stacking dimension for a "galley-level" layout
     * manager in block-progression-direction. It is passed by the
     * parent LM.
     * These LM <b>may</b> wish to pass this information down to lower
     * level LM to allow them to optimize returned break possibilities.
     */
    private MinOptMax stackLimitBP;

    /** to keep track of spanning in multi-column layout */
    private int currentSpan = Constants.NOT_SET;
    private int nextSpan = Constants.NOT_SET;

    /** inline-progression-dimension of nearest ancestor reference area */
    private int refIPD;
    //TODO After the split of stackLimit into stackLimitBP and stackLimitIP there's now some
    //overlap with refIPD. Need to investigate how best to refactor that.

    /** the writing mode established by the nearest ancestor reference area */
    private WritingMode writingMode = WritingMode.LR_TB;

    /** Current pending space-after or space-end from preceding area */
    private SpaceSpecifier trailingSpace;

    /** Current pending space-before or space-start from ancestor areas */
    private SpaceSpecifier leadingSpace;

    /**
     * A list of pending marks (border and padding) on the after edge when a page break occurs.
     * May be null.
     */
    private List pendingAfterMarks;

    /**
     * A list of pending marks (border and padding) on the before edge when a page break occurs.
     * May be null.
     */
    private List pendingBeforeMarks;

    /** Current hyphenation context. May be null. */
    private HyphContext hyphContext = null;

    /** Alignment in BP direction */
    private int bpAlignment = Constants.EN_START;

    /** Stretch or shrink value when making areas. */
    private double ipdAdjust = 0.0;

    /** Stretch or shrink value when adding spaces. */
    private double dSpaceAdjust = 0.0;

    private AlignmentContext alignmentContext = null;

    /** Amount of space before / start */
    private int spaceBefore = 0;
    /** Amount of space after / end */
    private int spaceAfter = 0;

    /** Amount of space to reserve at the beginning of each line */
    private int lineStartBorderAndPaddingWidth = 0;
    /** Amount of space to reserve at the end of each line */
    private int lineEndBorderAndPaddingWidth = 0;

    private int breakBefore;
    private int breakAfter;

    private Keep pendingKeepWithNext = Keep.KEEP_AUTO;
    private Keep pendingKeepWithPrevious = Keep.KEEP_AUTO;

    private int disableColumnBalancing;

    /**
     * Copy constructor for creating child layout contexts.
     * @param parentLC the parent layout context to copy from
     */
    public LayoutContext(LayoutContext parentLC) {
        this.flags = parentLC.flags;
        this.refIPD = parentLC.refIPD;
        this.writingMode = parentLC.writingMode;
        setStackLimitBP(parentLC.getStackLimitBP());
        this.leadingSpace = parentLC.leadingSpace; //???
        this.trailingSpace = parentLC.trailingSpace; //???
        this.hyphContext = parentLC.hyphContext;
        this.bpAlignment = parentLC.bpAlignment;
        this.dSpaceAdjust = parentLC.dSpaceAdjust;
        this.ipdAdjust = parentLC.ipdAdjust;
        this.alignmentContext = parentLC.alignmentContext;
        this.lineStartBorderAndPaddingWidth = parentLC.lineStartBorderAndPaddingWidth;
        this.lineEndBorderAndPaddingWidth = parentLC.lineEndBorderAndPaddingWidth;
        copyPendingMarksFrom(parentLC);
        this.pendingKeepWithNext = parentLC.pendingKeepWithNext;
        this.pendingKeepWithPrevious = parentLC.pendingKeepWithPrevious;
        // Copy other fields as necessary.
        this.disableColumnBalancing = parentLC.disableColumnBalancing;
    }

    /**
     * Main constructor.
     * @param flags the initial flags
     */
    public LayoutContext(int flags) {
        this.flags = flags;
        this.refIPD = 0;
        stackLimitBP = MinOptMax.ZERO;
        leadingSpace = null;
        trailingSpace = null;
    }

    /** @param source from which pending marks are copied */
    public void copyPendingMarksFrom(LayoutContext source) {
        if (source.pendingAfterMarks != null) {
            this.pendingAfterMarks = new java.util.ArrayList(source.pendingAfterMarks);
        }
        if (source.pendingBeforeMarks != null) {
            this.pendingBeforeMarks = new java.util.ArrayList(source.pendingBeforeMarks);
        }
    }

    /** @param flags to set */
    public void setFlags(int flags) {
        setFlags(flags, true);
    }

    /**
     * @param flags to set or clear
     * @param bSet true to set, false to clear
     */
    public void setFlags(int flags, boolean bSet) {
        if (bSet) {
            this.flags |= flags;
        } else {
            this.flags &= ~flags;
        }
    }

    /** @param flags to clear */
    public void unsetFlags(int flags) {
        setFlags(flags, false);
    }

    /** @return true if new area is set */
    public boolean isStart() {
        return ((this.flags & NEW_AREA) != 0);
    }

    /** @return true if new area is set and leading space is non-null */
    public boolean startsNewArea() {
        return ((this.flags & NEW_AREA) != 0 && leadingSpace != null);
    }

    /** @return true if first area is set */
    public boolean isFirstArea() {
        return ((this.flags & FIRST_AREA) != 0);
    }

    /** @return true if last area is set */
    public boolean isLastArea() {
        return ((this.flags & LAST_AREA) != 0);
    }

    /** @return true if suppress break before is set */
    public boolean suppressBreakBefore() {
        return ((this.flags & SUPPRESS_BREAK_BEFORE) != 0);
    }

    /**
     * Returns the strength of a keep-with-next currently pending.
     * @return the keep-with-next strength
     */
    public Keep getKeepWithNextPending() {
        return this.pendingKeepWithNext;
    }

    /**
     * Returns the strength of a keep-with-previous currently pending.
     * @return the keep-with-previous strength
     */
    public Keep getKeepWithPreviousPending() {
        return this.pendingKeepWithPrevious;
    }

    /**
     * Clears any pending keep-with-next strength.
     */
    public void clearKeepWithNextPending() {
        this.pendingKeepWithNext = Keep.KEEP_AUTO;
    }

    /**
     * Clears any pending keep-with-previous strength.
     */
    public void clearKeepWithPreviousPending() {
        this.pendingKeepWithPrevious = Keep.KEEP_AUTO;
    }

    /**
     * Clears both keep-with-previous and keep-with-next strengths.
     */
    public void clearKeepsPending() {
        clearKeepWithPreviousPending();
        clearKeepWithNextPending();
    }

    /**
     * Updates the currently pending keep-with-next strength.
     * @param keep the new strength to consider
     */
    public void updateKeepWithNextPending(Keep keep) {
        this.pendingKeepWithNext = this.pendingKeepWithNext.compare(keep);
    }

    /**
     * Updates the currently pending keep-with-previous strength.
     * @param keep the new strength to consider
     */
    public void updateKeepWithPreviousPending(Keep keep) {
        this.pendingKeepWithPrevious = this.pendingKeepWithPrevious.compare(keep);
    }

    /**
     * Indicates whether a keep-with-next constraint is pending.
     * @return true if a keep-with-next constraint is pending
     */
    public boolean isKeepWithNextPending() {
        return !getKeepWithNextPending().isAuto();
    }

    /**
     * Indicates whether a keep-with-previous constraint is pending.
     * @return true if a keep-with-previous constraint is pending
     */
    public boolean isKeepWithPreviousPending() {
        return !getKeepWithPreviousPending().isAuto();
    }

    /** @param space leading space */
    public void setLeadingSpace(SpaceSpecifier space) {
        leadingSpace = space;
    }

    /** @return leading space */
    public SpaceSpecifier getLeadingSpace() {
        return leadingSpace;
    }

    /** @return true if resolve leading space is set */
    public boolean resolveLeadingSpace() {
        return ((this.flags & RESOLVE_LEADING_SPACE) != 0);
    }

    /** @param space trailing space */
    public void setTrailingSpace(SpaceSpecifier space) {
        trailingSpace = space;
    }

    /** @return trailing space */
    public SpaceSpecifier getTrailingSpace() {
        return trailingSpace;
    }

    /**
     * Adds a border or padding element to the pending list which will be used to generate
     * the right element list for break possibilities. Conditionality resolution will be done
     * elsewhere.
     * @param element the border, padding or space element
     */
    public void addPendingAfterMark(UnresolvedListElementWithLength element) {
        if (this.pendingAfterMarks == null) {
            this.pendingAfterMarks = new java.util.ArrayList();
        }
        this.pendingAfterMarks.add(element);
    }

    /**
     * @return the pending border and padding elements at the after edge
     * @see #addPendingAfterMark(UnresolvedListElementWithLength)
     */
    public List getPendingAfterMarks() {
        if (this.pendingAfterMarks != null) {
            return Collections.unmodifiableList(this.pendingAfterMarks);
        } else {
            return null;
        }
    }

    /**
     * Clears all pending marks on the LayoutContext.
     */
    public void clearPendingMarks() {
        this.pendingBeforeMarks = null;
        this.pendingAfterMarks = null;
    }

    /**
     * Adds a border or padding element to the pending list which will be used to generate
     * the right element list for break possibilities. Conditionality resolution will be done
     * elsewhere.
     * @param element the border, padding or space element
     */
    public void addPendingBeforeMark(UnresolvedListElementWithLength element) {
        if (this.pendingBeforeMarks == null) {
            this.pendingBeforeMarks = new java.util.ArrayList();
        }
        this.pendingBeforeMarks.add(element);
    }

    /**
     * @return the pending border and padding elements at the before edge
     * @see #addPendingBeforeMark(UnresolvedListElementWithLength)
     */
    public List getPendingBeforeMarks() {
        if (this.pendingBeforeMarks != null) {
            return Collections.unmodifiableList(this.pendingBeforeMarks);
        } else {
            return null;
        }
    }

    /**
     * Sets the stack limit in block-progression-dimension.
     * @param limit the stack limit
     */
    public void setStackLimitBP(MinOptMax limit) {
        stackLimitBP = limit;
    }

    /**
     * Returns the stack limit in block-progression-dimension.
     * @return the stack limit
     */
    public MinOptMax getStackLimitBP() {
        return stackLimitBP;
    }

    /**
     * Sets the inline-progression-dimension of the nearest ancestor reference area.
     * @param ipd of nearest ancestor reference area
     */
    public void setRefIPD(int ipd) {
        refIPD = ipd;
    }

    /**
     * Returns the inline-progression-dimension of the nearest ancestor reference area.
     *
     * @return the inline-progression-dimension of the nearest ancestor reference area
     */
    public int getRefIPD() {
        return refIPD;
    }

    /** @param hyph a hyphenation context */
    public void setHyphContext(HyphContext hyph) {
        hyphContext = hyph;
    }

    /** @return hyphenation context */
    public HyphContext getHyphContext() {
        return hyphContext;
    }

    /** @return true if try hyphenate is set */
    public boolean tryHyphenate() {
        return ((this.flags & TRY_HYPHENATE) != 0);
    }

    /**
     * Sets the currently applicable alignment in BP direction.
     * @param alignment one of EN_START, EN_JUSTIFY etc.
     */
    public void setBPAlignment(int alignment) {
        this.bpAlignment = alignment;
    }

    /** @return the currently applicable alignment in BP direction (EN_START, EN_JUSTIFY...) */
    public int getBPAlignment() {
        return this.bpAlignment;
    }

    /** @param adjust space adjustment */
    public void setSpaceAdjust(double adjust) {
        dSpaceAdjust = adjust;
    }

    /** @return space adjustment */
    public double getSpaceAdjust() {
        return dSpaceAdjust;
    }

    /** @param ipdA ipd adjustment */
    public void setIPDAdjust(double ipdA) {
        ipdAdjust = ipdA;
    }

    /** @return ipd adjustment */
    public double getIPDAdjust() {
        return ipdAdjust;
    }

    /** @param alignmentContext alignment context */
    public void setAlignmentContext(AlignmentContext alignmentContext) {
        this.alignmentContext = alignmentContext;
    }

    /** @return alignment context */
    public AlignmentContext getAlignmentContext() {
        return this.alignmentContext;
    }

    /**
     * Reset alignment context.
     */
    public void resetAlignmentContext() {
        if (this.alignmentContext != null) {
            this.alignmentContext = this.alignmentContext.getParentAlignmentContext();
        }
    }

    /**
     * Get the width to be reserved for border and padding at the start of the line.
     * @return the width to be reserved
     */
    public int getLineStartBorderAndPaddingWidth() {
        return lineStartBorderAndPaddingWidth;
    }

    /**
     * Set the width to be reserved for border and padding at the start of the line.
     * @param lineStartBorderAndPaddingWidth the width to be reserved
     */
    public void setLineStartBorderAndPaddingWidth(int lineStartBorderAndPaddingWidth) {
        this.lineStartBorderAndPaddingWidth = lineStartBorderAndPaddingWidth;
    }

    /**
     * Get the width to be reserved for border and padding at the end of the line.
     * @return the width to be reserved
     */
    public int getLineEndBorderAndPaddingWidth() {
        return lineEndBorderAndPaddingWidth;
    }

    /**
     * Set the width to be reserved for border and padding at the end of the line.
     * @param lineEndBorderAndPaddingWidth the width to be reserved
     */
    public void setLineEndBorderAndPaddingWidth(int lineEndBorderAndPaddingWidth) {
        this.lineEndBorderAndPaddingWidth = lineEndBorderAndPaddingWidth;
    }

    /**
     * @return one of: {@link Constants#NOT_SET}, {@link Constants#EN_NONE}
     *                  {@link Constants#EN_ALL}
     */
    public int getNextSpan() {
        return nextSpan;
    }

    /**
     * @return one of: {@link Constants#NOT_SET}, {@link Constants#EN_NONE}
     *                  {@link Constants#EN_ALL}
     */
    public int getCurrentSpan() {
        return (currentSpan == Constants.NOT_SET)
                ? Constants.EN_NONE : currentSpan;
    }

    /**
     * Used to signal the PSLM that the element list ends early because of a span change in
     * multi-column layout.
     * @param span the new span value (legal values: NOT_SET, EN_NONE, EN_ALL)
     */
    public void signalSpanChange(int span) {
        switch (span) {
        case Constants.NOT_SET:
        case Constants.EN_NONE:
        case Constants.EN_ALL:
            this.currentSpan = this.nextSpan;
            this.nextSpan = span;
            break;
        default:
            assert false;
            throw new IllegalArgumentException("Illegal value on signalSpanChange() for span: "
                    + span);
        }
    }

    /**
     * Get the writing mode of the relevant reference area.
     * @return the applicable writing mode
     */
    public WritingMode getWritingMode() {
        return writingMode;
    }

    /**
     * Set the writing mode.
     * @param writingMode the writing mode
     */
    public void setWritingMode(WritingMode writingMode) {
        this.writingMode = writingMode;
    }

    /**
     * Get the current amount of space before / start
     * @return the space before / start amount
     */
    public int getSpaceBefore() {
        return spaceBefore;
    }

    /**
     * Set the amount of space before / start
     * @param spaceBefore the amount of space before / start
     */
    public void setSpaceBefore(int spaceBefore) {
        this.spaceBefore = spaceBefore;
    }

    /**
     * Get the current amount of space after / end
     * @return the space after / end amount
     */
    public int getSpaceAfter() {
        return spaceAfter;
    }

    /**
     * Set the amount of space after / end
     * @param spaceAfter the amount of space after / end
     */
    public void setSpaceAfter(int spaceAfter) {
        this.spaceAfter = spaceAfter;
    }

    /**
     * Returns the value of the break before the element whose
     * {@link LayoutManager#getNextKnuthElements(LayoutContext, int)} method has just been
     * called.
     *
     * @return one of {@link Constants#EN_AUTO}, {@link Constants#EN_COLUMN},
     * {@link Constants#EN_PAGE}, {@link Constants#EN_EVEN_PAGE}, or
     * {@link Constants#EN_ODD_PAGE}
     */
    public int getBreakBefore() {
        return breakBefore;
    }

    /**
     * Sets the value of the break before the current element.
     *
     * @param breakBefore the value of the break-before
     * @see #getBreakBefore()
     */
    public void setBreakBefore(int breakBefore) {
        this.breakBefore = breakBefore;
    }

    /**
     * Returns the value of the break after the element whose
     * {@link LayoutManager#getNextKnuthElements(LayoutContext, int)} method has just been
     * called.
     *
     * @return one of {@link Constants#EN_AUTO}, {@link Constants#EN_COLUMN},
     * {@link Constants#EN_PAGE}, {@link Constants#EN_EVEN_PAGE}, or
     * {@link Constants#EN_ODD_PAGE}
     */
    public int getBreakAfter() {
        return breakAfter;
    }

    /**
     * Sets the value of the break after the current element.
     *
     * @param breakAfter the value of the break-after
     * @see #getBreakAfter()
     */
    public void setBreakAfter(int breakAfter) {
        this.breakAfter = breakAfter;
    }

    /** {@inheritDoc} */
    public String toString() {
        return "Layout Context:"
        + "\nStack Limit BPD: \t"
            + (getStackLimitBP() == null ? "null" : getStackLimitBP().toString())
        + "\nTrailing Space: \t"
            + (getTrailingSpace() == null ? "null" : getTrailingSpace().toString())
        + "\nLeading Space: \t"
            + (getLeadingSpace() == null ? "null" : getLeadingSpace().toString())
        + "\nReference IPD: \t" + getRefIPD()
        + "\nSpace Adjust: \t" + getSpaceAdjust()
        + "\nIPD Adjust: \t" + getIPDAdjust()
        + "\nResolve Leading Space: \t" + resolveLeadingSpace()
        + "\nSuppress Break Before: \t" + suppressBreakBefore()
        + "\nIs First Area: \t" + isFirstArea()
        + "\nStarts New Area: \t" + startsNewArea()
        + "\nIs Last Area: \t" + isLastArea()
        + "\nTry Hyphenate: \t" + tryHyphenate()
        + "\nKeeps: \t[keep-with-next=" + getKeepWithNextPending()
                + "][keep-with-previous=" + getKeepWithPreviousPending() + "] pending"
        + "\nBreaks: \tforced [" + (breakBefore != Constants.EN_AUTO ? "break-before" : "") + "]["
        + (breakAfter != Constants.EN_AUTO ? "break-after" : "") + "]";
    }

    /**
     * Returns whether the column balancer should be disabled before a spanning block
     *
     * @return one of {@link Constants#EN_TRUE}, {@link Constants#EN_FALSE}
     */
    public int getDisableColumnBalancing() {
        return disableColumnBalancing;
    }

    /**
     * Sets whether the column balancer should be disabled before a spanning block
     *
     * @param disableColumnBalancing the value of the fox:disable-column-balancing property
     * @see #getDisableColumnBalancing()
     */
    public void setDisableColumnBalancing(int disableColumnBalancing) {
        this.disableColumnBalancing = disableColumnBalancing;
    }
}


text:
namespace SNES {

PPU ppu;

#include "mmio/mmio.cpp"
#include "window/window.cpp"
#include "cache/cache.cpp"
#include "background/background.cpp"
#include "sprite/sprite.cpp"
#include "screen/screen.cpp"
#include "serialization.cpp"

void PPU::step(unsigned clocks) {
  clock += clocks;
}

void PPU::synchronize_cpu() {
  if(CPU::Threaded == true) {
    if(clock >= 0 && scheduler.sync != Scheduler::SynchronizeMode::All) co_switch(cpu.thread);
  } else {
    while(clock >= 0) cpu.enter();
  }
}

void PPU::Enter() { ppu.enter(); }

void PPU::enter() {
  while(true) {
    if(scheduler.sync == Scheduler::SynchronizeMode::All) {
      scheduler.exit(Scheduler::ExitReason::SynchronizeEvent);
    }

    scanline();
    if(vcounter() < display.height && vcounter()) {
      add_clocks(512);
      render_scanline();
      add_clocks(lineclocks() - 512);
    } else {
      add_clocks(lineclocks());
    }
  }
}

void PPU::add_clocks(unsigned clocks) {
  tick(clocks);
  step(clocks);
  synchronize_cpu();
}

void PPU::render_scanline() {
  if(display.framecounter) return;  //skip this frame?
  bg1.scanline();
  bg2.scanline();
  bg3.scanline();
  bg4.scanline();
  if(regs.display_disable) return screen.render_black();
  screen.scanline();
  bg1.render();
  bg2.render();
  bg3.render();
  bg4.render();
  sprite.render();
  screen.render();
}

void PPU::scanline() {
  display.width = !hires() ? 256 : 512;
  display.height = !overscan() ? 225 : 240;
  if(vcounter() == 0) frame();
  if(vcounter() == display.height && regs.display_disable == false) sprite.address_reset();
}

void PPU::frame() {
  sprite.frame();
  system.frame();
  display.interlace = regs.interlace;
  display.overscan = regs.overscan;
  display.framecounter = display.frameskip == 0 ? 0 : (display.framecounter + 1) % display.frameskip;
}

void PPU::enable() {
  function<uint8 (unsigned)> read = { &PPU::mmio_read, (PPU*)&ppu };
  function<void (unsigned, uint8)> write = { &PPU::mmio_write, (PPU*)&ppu };

  bus.map(Bus::MapMode::Direct, 0x00, 0x3f, 0x2100, 0x213f, read, write);
  bus.map(Bus::MapMode::Direct, 0x80, 0xbf, 0x2100, 0x213f, read, write);
}

void PPU::power() {
	for(int i=0;i<128*1024;i++) vram[i] = 0;
	for(int i=0;i<544;i++) oam[i] = 0;
	for(int i=0;i<512;i++) cgram[i] = 0;
  reset();
}

void PPU::reset() {
  create(Enter, system.cpu_frequency());
  PPUcounter::reset();
  memset(surface, 0, 512 * 512 * sizeof(uint32));
  mmio_reset();
  display.interlace = false;
  display.overscan = false;
}

void PPU::layer_enable(unsigned layer, unsigned priority, bool enable) {
  switch(layer * 4 + priority) {
    case  0: bg1.priority0_enable = enable; break;
    case  1: bg1.priority1_enable = enable; break;
    case  4: bg2.priority0_enable = enable; break;
    case  5: bg2.priority1_enable = enable; break;
    case  8: bg3.priority0_enable = enable; break;
    case  9: bg3.priority1_enable = enable; break;
    case 12: bg4.priority0_enable = enable; break;
    case 13: bg4.priority1_enable = enable; break;
    case 16: sprite.priority0_enable = enable; break;
    case 17: sprite.priority1_enable = enable; break;
    case 18: sprite.priority2_enable = enable; break;
    case 19: sprite.priority3_enable = enable; break;
  }
}

void PPU::set_frameskip(unsigned frameskip) {
  display.frameskip = frameskip;
  display.framecounter = 0;
}

PPU::PPU() :
cache(*this),
bg1(*this, Background::ID::BG1),
bg2(*this, Background::ID::BG2),
bg3(*this, Background::ID::BG3),
bg4(*this, Background::ID::BG4),
sprite(*this),
screen(*this),
vram(nullptr),
oam(nullptr),
cgram(nullptr)
{
  surface = new uint32[512 * 512];
  output = surface + 16 * 512;
  display.width = 256;
  display.height = 224;
  display.frameskip = 0;
  display.framecounter = 0;
}

PPU::~PPU() {
  delete[] surface;
	interface()->freeSharedMemory(vram);
	interface()->freeSharedMemory(oam);
	interface()->freeSharedMemory(cgram);
}

void PPU::initialize()
{
	vram = (uint8*)interface()->allocSharedMemory("VRAM",128 * 1024);
  oam = (uint8*)interface()->allocSharedMemory("OAM",544);
  cgram = (uint8*)interface()->allocSharedMemory("CGRAM",512);
}

}

redpajama_set_name: RedPajamaGithub


text:
class InterestArea < ActiveRecord::Base
  # The line below was inserted by uix.
  resourcify

  validates :name, presence: true, uniqueness: true
end


text:
package com.lensflare.svh.minecraft;

import java.io.IOException;
import java.net.Socket;

import com.lensflare.svh.Server;
import com.lensflare.svh.impl.Connection;

public class ConnectionPost17 extends Connection {
	public ConnectionPost17(Server server, Socket socket) {
		super(server, socket);
	}

	@Override
	public void end() throws IOException {
		if (!isActive())
			return;

		String reason = "";
		int rLength = reason.length();
		int packetID = 0x40;
		int pLength = rLength + 3;

		byte[] data = new byte[pLength];
		data[0] = (byte)pLength;
		data[1] = (byte)packetID;
		data[2] = (byte)rLength;
		System.arraycopy(reason.getBytes(), 0, data, 3, rLength);

		getSocket().getOutputStream().write(data);

		super.end();
	}
}


text:
set -e
set -x
echo -e "Starting to update gh-pages\n"

#using token to clone gh-pages branch
git clone --quiet --branch=gh-pages https://${GITHUB_ACTOR}:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git gh-pages

git config --global user.email "alexander.schwartz@gmx.net"
git config --global user.name "GitHub Action"

#go into directory and copy data we're interested in to that directory
set -e
cd gh-pages
cp index.html ../tutorial/output
rm -rf ./*
cp -Rf ../tutorial/output/* .

#add, commit and push files
git add -f .

if [ ! -z "$(git status --porcelain)" ]; then
  git commit -m "GitHub build $GITHUB_RUN_ID pushed to gh-pages"
else
  echo no changes
fi

git push -fq origin gh-pages

echo -e "Done publishing to gh-pages.\n"


text:
import React from 'react';
import { Form } from 'react-bootstrap';

import { makeClasses } from '../helpers/object';
import { RowsPerPageOnChange } from '../helpers/types';
import { useDatatableWrapper } from './DatatableWrapper';

/** This is an interface to customize the pagination options labels. */
export interface PaginationOptionsLabels {
  /**
   * Change the label that is shown before the select input.
   * Defaults to "Rows per page".
   */
  beforeSelect?: string;
  /**
   * Change the label that is shown after the select input.
   * Defaults to `undefined`. This probably should be used if the form group
   * is a horizontal form instead of vertical (e.g. using `flex-direction: row`).
   */
  afterSelect?: string;
}

/**
 * This is an interface for customizing the classes for
 * the `PaginationOptions` component.
 */
export interface PaginationOptionsClasses {
  /**
   * The class for the pagination options group, which covers
   * the `beforeSelect` label, the select input, and the `afterSelect` text.
   */
  formGroup?: string;
  /** The class for the `beforeSelect` and `afterSelect` labels. */
  formText?: string;
  /** The class for the select input. */
  formControl?: string;
}

/**
 * This is an interface for `PaginationOptions` component props.
 */
export interface PaginationOptionsProps {
  /** Customize the labels of the `PaginationOptions` component. */
  labels?: PaginationOptionsLabels;
  /** Customize the classes of the `PaginationOptions` component. */
  classes?: PaginationOptionsClasses;
  /**
   * Determine whether the pagination button group should be always visible or not.
   * When set to `false`, the pagination will be hidden when there is only 1 page.
   * To prevent layout shifts, `visibility: hidden` will be applied instead of
   * `display: none` style. Defaults to `true`.
   */
  alwaysShowPagination?: boolean;
  /** Props to make the component controlled. */
  controlledProps?: {
    /** Number of rows shown per page. */
    rowsPerPage?: number;
    /** Number of rows shown per page options. */
    rowsPerPageOptions?: number[];
    /**
     * The filtered data length. When not using filter control,
     * then this should equal to the table body's length.
     */
    filteredDataLength?: number;
    /** The function fired when any of the pagination option is changed. */
    onRowsPerPageChange?: RowsPerPageOnChange;
  };
}

/**
 * Renders a control for the pagination options. It will show a form group, consisting of
 * a select input, as well as a label/text before and after the input. By default,
 * it renders "Rows per page" as a label, which refers to the select input. There is no
 * text after the select input, unless specified in the `labels.afterSelect` prop.
 *
 * The options available in the select input are the ones specified from the `DatatableWrapper`,
 * or the ones passed in this component's prop `controlledProps.rowsPerPageOptions`.
 *
 * When `alwaysShowPagination` is set to `false`, then this component will be visually hidden.
 */
export function PaginationOptions({
  labels,
  classes,
  alwaysShowPagination = true,
  controlledProps
}: PaginationOptionsProps) {
  const {
    onRowsPerPageChange: onRowsPerPageChangeContext,
    rowsPerPageOptions: rowsPerPageOptionsContext,
    rowsPerPageState: rowsPerPageStateContext,
    filteredDataLength: filteredDataLengthContext
  } = useDatatableWrapper();

  // Controlled has the bigger priority.
  const rowsPerPageOptions =
    controlledProps?.rowsPerPageOptions || rowsPerPageOptionsContext;
  const rowsPerPageState =
    controlledProps?.rowsPerPage || rowsPerPageStateContext;
  const filteredDataLength =
    controlledProps?.filteredDataLength || filteredDataLengthContext;
  const onRowsPerPageChange =
    controlledProps?.onRowsPerPageChange || onRowsPerPageChangeContext;

  // Hide pagination if pagination is meant to not always be shown or
  // if the filtered data length is less than the minimum rows per page option.
  const hidePaginationOptions =
    !alwaysShowPagination &&
    filteredDataLength <= Math.min(...rowsPerPageOptions);

  return (
    <Form.Group
      controlId="formGroupPagination"
      className={makeClasses('paginationOpts__root', classes?.formGroup, {
        invisible: hidePaginationOptions
      })}
    >
      <Form.Label className={classes?.formText}>
        {labels?.beforeSelect || 'Rows per page'}
      </Form.Label>
      <Form.Select
        name="table-pagination-options"
        value={rowsPerPageState}
        as="select"
        placeholder="select"
        onChange={(e) => onRowsPerPageChange(Number(e.target.value))}
        className={classes?.formControl}
      >
        {rowsPerPageOptions.map((option: number) => {
          const optionProps = {
            key: `page-opt-${option}`,
            value: option
          };

          return <option {...optionProps}>{option}</option>;
        })}
      </Form.Select>
      {labels?.afterSelect && (
        <Form.Text className={classes?.formText}>
          {labels?.afterSelect}
        </Form.Text>
      )}
    </Form.Group>
  );
}


text:
package pod

import (
	"context"
	"fmt"

	v1 "k8s.io/api/core/v1"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/types"
	clientset "k8s.io/client-go/kubernetes"
	"k8s.io/klog/v2"
	kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
	kubetypes "k8s.io/kubernetes/pkg/kubelet/types"
)

// MirrorClient knows how to create/delete a mirror pod in the API server.
type MirrorClient interface {
	// CreateMirrorPod creates a mirror pod in the API server for the given
	// pod or returns an error.  The mirror pod will have the same annotations
	// as the given pod as well as an extra annotation containing the hash of
	// the static pod.
	CreateMirrorPod(pod *v1.Pod) error
	// DeleteMirrorPod deletes the mirror pod with the given full name from
	// the API server or returns an error.
	DeleteMirrorPod(podFullName string, uid *types.UID) (bool, error)
}

// nodeGetter is a subset a NodeLister, simplified for testing.
type nodeGetter interface {
	// Get retrieves the Node for a given name.
	Get(name string) (*v1.Node, error)
}

// basicMirrorClient is a functional MirrorClient.  Mirror pods are stored in
// the kubelet directly because they need to be in sync with the internal
// pods.
type basicMirrorClient struct {
	apiserverClient clientset.Interface
	nodeGetter      nodeGetter
	nodeName        string
}

// NewBasicMirrorClient returns a new MirrorClient.
func NewBasicMirrorClient(apiserverClient clientset.Interface, nodeName string, nodeGetter nodeGetter) MirrorClient {
	return &basicMirrorClient{
		apiserverClient: apiserverClient,
		nodeName:        nodeName,
		nodeGetter:      nodeGetter,
	}
}

func (mc *basicMirrorClient) CreateMirrorPod(pod *v1.Pod) error {
	if mc.apiserverClient == nil {
		return nil
	}
	// Make a copy of the pod.
	copyPod := *pod
	copyPod.Annotations = make(map[string]string)

	for k, v := range pod.Annotations {
		copyPod.Annotations[k] = v
	}
	hash := getPodHash(pod)
	copyPod.Annotations[kubetypes.ConfigMirrorAnnotationKey] = hash

	// With the MirrorPodNodeRestriction feature, mirror pods are required to have an owner reference
	// to the owning node.
	// See https://git.k8s.io/enhancements/keps/sig-auth/1314-node-restriction-pods/README.md
	nodeUID, err := mc.getNodeUID()
	if err != nil {
		return fmt.Errorf("failed to get node UID: %v", err)
	}
	controller := true
	copyPod.OwnerReferences = []metav1.OwnerReference{{
		APIVersion: v1.SchemeGroupVersion.String(),
		Kind:       "Node",
		Name:       mc.nodeName,
		UID:        nodeUID,
		Controller: &controller,
	}}

	apiPod, err := mc.apiserverClient.CoreV1().Pods(copyPod.Namespace).Create(context.TODO(), &copyPod, metav1.CreateOptions{})
	if err != nil && apierrors.IsAlreadyExists(err) {
		// Check if the existing pod is the same as the pod we want to create.
		if h, ok := apiPod.Annotations[kubetypes.ConfigMirrorAnnotationKey]; ok && h == hash {
			return nil
		}
	}
	return err
}

// DeleteMirrorPod deletes a mirror pod.
// It takes the full name of the pod and optionally a UID.  If the UID
// is non-nil, the pod is deleted only if its UID matches the supplied UID.
// It returns whether the pod was actually deleted, and any error returned
// while parsing the name of the pod.
// Non-existence of the pod or UID mismatch is not treated as an error; the
// routine simply returns false in that case.
func (mc *basicMirrorClient) DeleteMirrorPod(podFullName string, uid *types.UID) (bool, error) {
	if mc.apiserverClient == nil {
		return false, nil
	}
	name, namespace, err := kubecontainer.ParsePodFullName(podFullName)
	if err != nil {
		klog.ErrorS(err, "Failed to parse a pod full name", "podFullName", podFullName)
		return false, err
	}
	klog.V(2).InfoS("Deleting a mirror pod", "pod", klog.KRef(namespace, name), "podUID", uid)
	var GracePeriodSeconds int64
	if err := mc.apiserverClient.CoreV1().Pods(namespace).Delete(context.TODO(), name, metav1.DeleteOptions{GracePeriodSeconds: &GracePeriodSeconds, Preconditions: &metav1.Preconditions{UID: uid}}); err != nil {
		// Unfortunately, there's no generic error for failing a precondition
		if !(apierrors.IsNotFound(err) || apierrors.IsConflict(err)) {
			// We should return the error here, but historically this routine does
			// not return an error unless it can't parse the pod name
			klog.ErrorS(err, "Failed deleting a mirror pod", "pod", klog.KRef(namespace, name))
		}
		return false, nil
	}
	return true, nil
}

func (mc *basicMirrorClient) getNodeUID() (types.UID, error) {
	node, err := mc.nodeGetter.Get(mc.nodeName)
	if err != nil {
		return "", err
	}
	if node.UID == "" {
		return "", fmt.Errorf("UID unset for node %s", mc.nodeName)
	}
	return node.UID, nil
}

// IsStaticPod returns true if the passed Pod is static.
func IsStaticPod(pod *v1.Pod) bool {
	source, err := kubetypes.GetPodSource(pod)
	return err == nil && source != kubetypes.ApiserverSource
}

func getHashFromMirrorPod(pod *v1.Pod) (string, bool) {
	hash, ok := pod.Annotations[kubetypes.ConfigMirrorAnnotationKey]
	return hash, ok
}

func getPodHash(pod *v1.Pod) string {
	// The annotation exists for all static pods.
	return pod.Annotations[kubetypes.ConfigHashAnnotationKey]
}


text:
@implementation QButtonElement
@synthesize enabled = _enabled;

- (QButtonElement *)init {
    self = [super init];
    if (self) {
        self.enabled = YES;
    }
    return self;
}

- (QButtonElement *)initWithTitle:(NSString *)title {
    self = [super initWithTitle:title Value:nil];
    self.enabled = YES;
    return self;
}

- (UITableViewCell *)getCellForTableView:(QuickDialogTableView *)tableView controller:(QuickDialogController *)controller {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QuickformButtonElement"];
    if (cell == nil){
        cell= [[QTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"QuickformButtonElement"];
    }
    if (self.enabled) {
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
        cell.textLabel.textColor = [UIColor colorWithRed:50.0f/255.0f green:79.0f/255.0f blue:133.0f/255.0f alpha:1];
    } else {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.textColor = [UIColor lightGrayColor];
    }

    cell.textLabel.text = _title;
    cell.textLabel.textAlignment = UITextAlignmentCenter;
    return cell;
}

- (void)selected:(QuickDialogTableView *)tableView controller:(QuickDialogController *)controller indexPath:(NSIndexPath *)indexPath {
    if (self.enabled) {
        [super selected:tableView controller:controller indexPath:indexPath];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end


text:
class RackApp
  attr_reader :last_value

  def call(env)
    RequestStore.store[:foo] ||= 0
    RequestStore.store[:foo] += 1
    @last_value = RequestStore.store[:foo]
    raise 'FAIL' if env[:error]
  end
end


text:
import factory
from faker import Factory
fake = Factory.create()

from django.contrib.auth.hashers import make_password

from .models import User

class UserFactory(factory.DjangoModelFactory):

    class Meta:
        model = User

    @factory.lazy_attribute
    def password(self):
        return make_password('qwerty')

    @factory.lazy_attribute
    def email(self):
        return fake.safe_email()

    @factory.lazy_attribute
    def name(self):
        return fake.name()

class AdminFactory(UserFactory):
    email = 'admin@example.com'
    password = make_password('admin')
    is_staff = True
    is_active = True
    is_superuser = True

def generate_users():
    AdminFactory()
    UserFactory.create_batch(10)


text:
/**
 * Created by Papa on 10/28/2016.
 */
//# sourceMappingURL=HierarchicalEntitySQLQuery.js.map


text:
// .NAME vtkMatrixToLinearTransform - convert a matrix to a transform
// .SECTION Description
// This is a very simple class which allows a vtkMatrix4x4 to be used in
// place of a vtkLinearTransform or vtkAbstractTransform.  For example,
// if you use it as a proxy between a matrix and vtkTransformPolyDataFilter
// then any modifications to the matrix will automatically be reflected in
// the output of the filter.
// .SECTION See Also
// vtkTransform vtkMatrix4x4 vtkMatrixToHomogeneousTransform

#ifndef vtkMatrixToLinearTransform_h
#define vtkMatrixToLinearTransform_h

#include "vtkCommonTransformsModule.h" // For export macro
#include "vtkLinearTransform.h"

class vtkMatrix4x4;

class VTKCOMMONTRANSFORMS_EXPORT vtkMatrixToLinearTransform : public vtkLinearTransform
{
 public:
  static vtkMatrixToLinearTransform *New();
  vtkTypeMacro(vtkMatrixToLinearTransform,vtkLinearTransform);
  void PrintSelf (ostream& os, vtkIndent indent) VTK_OVERRIDE;

  // Description:
  // Set the input matrix.  Any modifications to the matrix will be
  // reflected in the transformation.
  virtual void SetInput(vtkMatrix4x4*);
  vtkGetObjectMacro(Input,vtkMatrix4x4);

  // Description:
  // The input matrix is left as-is, but the transformation matrix
  // is inverted.
  void Inverse() VTK_OVERRIDE;

  // Description:
  // Get the MTime: this is the bit of magic that makes everything work.
  vtkMTimeType GetMTime() VTK_OVERRIDE;

  // Description:
  // Make a new transform of the same type.
  vtkAbstractTransform *MakeTransform() VTK_OVERRIDE;

protected:
  vtkMatrixToLinearTransform();
  ~vtkMatrixToLinearTransform();

  void InternalUpdate() VTK_OVERRIDE;
  void InternalDeepCopy(vtkAbstractTransform *transform) VTK_OVERRIDE;

  int InverseFlag;
  vtkMatrix4x4 *Input;
private:
  vtkMatrixToLinearTransform(const vtkMatrixToLinearTransform&) VTK_DELETE_FUNCTION;
  void operator=(const vtkMatrixToLinearTransform&) VTK_DELETE_FUNCTION;
};

#endif


text:
import Utils = require('../utils/utils');
class Match {
	public categorie: string;
	public equipe1: string;
	public equipe2: string;
	public equipe1Complet: string;
	public equipe2Complet: string;
	public score1: number;
	public score2: number;
	public date: string; // TODO: Voir pour changer en Date
	public infos: string;

	fromObject(object): void {
		this.date = object.date;
		this.equipe1 = object.equipe1;
		this.equipe2 = object.equipe2;
		this.infos = object.infos;
		this.score1 = object.score1;
		this.score2 = object.score2;
		this.categorie = object.categorie;
	}

	formatDate(): string {
		return Utils.formatDate(new Date(this.date));
	}

	toString(): string {
		return '{"equipe1":"'+this.equipe1+'","equipe2":"'+this.equipe2+'","score1":'+this.score1+',"score2":'+this.score2+',"date":"'+this.formatDate()+'"}'
	}
}

export = Match;


text:
package com.hundsun.jresplus.web.nosession.cookie;

import org.apache.commons.lang.SerializationException;

public interface Encode {

	public String encode(Object object) throws SerializationException;

	public Object decode(String str) throws SerializationException;
}


text:
<?php

/**
 * @file
 * Contains \Drupal\Core\Config\UnsupportedDataTypeConfigException.
 */

namespace Drupal\Core\Config;

/**
 * Exception thrown when a config data type is invalid.
 */
class UnsupportedDataTypeConfigException extends ConfigException {
}


text:
package cz.atlascon.travny.parser;

import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import cz.atlascon.travny.TravnyParser;
import cz.atlascon.travny.data.JsonReader;
import cz.atlascon.travny.schemas.*;
import cz.atlascon.travny.types.Type;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Function;

/**
 * Created by trehak on 23.5.17.
 */
class RecordSchemaParser {

    private final TravnyParser.RecordContext ctx;
    private BiConsumer<String, Schema> parsedConsumer;
    private Function<String, Schema> schemaSupplier;
    private HashMap<String, JsonNode> annotations = Maps.newHashMap();
    private String name;

    public RecordSchemaParser(TravnyParser.RecordContext child, BiConsumer<String, Schema> parsedConsumer, Function<String, Schema> schemaSupplier) {
        this.ctx = child;
        this.parsedConsumer = parsedConsumer;
        this.schemaSupplier = schemaSupplier;
    }

    public void parse() throws IOException {
        this.annotations.putAll(new AnnotationParser(ctx.annotation()).parse());
        parseIdSchema();
        parseRecordSchema();
    }

    private void parseRecordSchema() throws IOException {
        this.name = ParserUtils.qualifiedIdentifierToString(ctx.qualifiedIdentifier());
        List<Field> fieldList = Lists.newArrayList();
        int ord = 0;
        for (TravnyParser.FieldContext fieldContext : ctx.field()) {
            ord++;
            Field parsedField = parseField(fieldContext, ord);
            fieldList.add(parsedField);
        }
        checkFields(fieldList);
        RecordSchema idSchema = (RecordSchema) schemaSupplier.apply(SchemaNameUtils.getIdForRecord(this.name));
        RecordSchema recordSchema = new RecordSchema(fieldList, name, idSchema, annotations);
        parsedConsumer.accept(recordSchema.getName(), recordSchema);
    }

    private void checkFields(List<Field> fieldList) {
        Preconditions.checkArgument(fieldList.stream().filter(f -> !f.isRemoved()).count() > 0, "No fields present!");
        Set<String> names = Sets.newHashSet();
        for (Field f : fieldList) {
            if (f.isRemoved()) {
                continue;
            }
            if (names.contains(f.getName())) {
                throw new IllegalArgumentException("Duplicate field " + f.getName());
            } else {
                names.add(f.getName());
            }
        }

    }

    private Field parseField(TravnyParser.FieldContext fieldContext, int ord) throws IOException {
        Map<String, JsonNode> fieldAnnotations = new AnnotationParser(fieldContext.annotation()).parse();
        String fieldName = fieldContext.Identifier().getSymbol().getText();
        Schema schema = typeToSchema(fieldContext.type());
        Object defaultValue = parseDefaultValue(schema, fieldAnnotations);
        Field field = new Field(schema, fieldName, ord, defaultValue, fieldAnnotations);
        return field;
    }

    private void parseIdSchema() throws IOException {
        String recordName = ParserUtils.qualifiedIdentifierToString(ctx.qualifiedIdentifier());
        String name = SchemaNameUtils.getIdForRecord(recordName);
        List<Field> fieldList = Lists.newArrayList();
        int ord = 0;
        for (TravnyParser.FieldContext fieldContext : ctx.field()) {
            Map<String, JsonNode> fieldAnnotations = new AnnotationParser(fieldContext.annotation()).parse();
            // skip non-ID fields
            if (!fieldAnnotations.containsKey(Field.ID_ANNOTATION)) {
                continue;
            }
            ord++;
            Field field = parseField(fieldContext, ord);
            fieldList.add(field);
        }
        if (fieldList.isEmpty()) {
            return;
        }
        Map<String, JsonNode> annotationsCopy = Maps.newHashMap(annotations);
        JsonNode shortId = annotationsCopy.remove(RecordSchema.SHORT_ID);
        Preconditions.checkNotNull(shortId);
        annotationsCopy.put(RecordSchema.PARENT_SHORT_ID, shortId);
        RecordSchema idSchema = new RecordSchema(fieldList, name, null, annotationsCopy);
        parsedConsumer.accept(idSchema.getName(), idSchema);
    }

    private Object parseDefaultValue(Schema schema, Map<String, JsonNode> fieldAnnotations) {
        JsonNode def = fieldAnnotations.get("Default");
        if (def == null || def.isNull()) {
            return null;
        }
        return new JsonReader().getNodeData(schema, def);
    }

    private Schema typeToSchema(TravnyParser.TypeContext type) throws IOException {
        if (type.simpleType() != null) {
            String name = type.simpleType().Identifier().getSymbol().getText();
            return resolveSimple(name);
        } else if (type.qualifiedIdentifier() != null) {
            String name = ParserUtils.qualifiedIdentifierToString(type.qualifiedIdentifier());
            return resolveSimple(name);
        } else if (type.listType() != null) {
            Schema items = typeToSchema(type.listType().type());
            return ListSchema.of(items);
        } else if (type.mapType() != null) {
            return MapSchema.of(typeToSchema(type.mapType().type(0)), typeToSchema(type.mapType().type(1)));
        } else if (type.idRef() != null) {
            // type is ID
            String refName = ParserUtils.qualifiedIdentifierToString(type.idRef().qualifiedIdentifier());
            return resolveSimple(SchemaNameUtils.getIdForRecord(refName));
        } else {
            throw new IllegalArgumentException("Unknown type " + type);
        }

    }

    private Schema resolveSimple(String name) {
        Type simple = Type.NAMES.get(name);
        if (simple != null) {
            return new Schema(simple);
        }
        Schema got = schemaSupplier.apply(name);
        if (got == null) {
            throw new IllegalArgumentException("Unable to resolve schema " + name + " in " + this.name);
        }
        return got;
    }
}


text:
const mws = require('..');
const keys = require('../test/keys.json');

mws.init(keys);

async function main() {
    try {
        const startDate = new Date();
        startDate.setDate(startDate.getDate() - 1);
        const results = await mws.listFinancialEvents({ PostedAfter: startDate });
        console.log(JSON.stringify(results, null, 4));
    } catch (err) {
        console.warn('* error', err);
    }
}

main();


text:
package com.bt.pi.core.util;

public abstract class SerialExecutorRunnable implements Runnable {
    private String queueUrl;
    private String entityUrl;

    public SerialExecutorRunnable(String aQueueUrl, String anEntityUrl) {
        queueUrl = aQueueUrl;
        entityUrl = anEntityUrl;
    }

    public String getQueueUrl() {
        return queueUrl;
    }

    public String getEntityUrl() {
        return entityUrl;
    }
}


text:
package org.wso2.developerstudio.eclipse.artifact.gadget.ui.wizard;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.ResourceBundle;

import org.apache.maven.model.Plugin;
import org.apache.maven.project.MavenProject;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import org.wso2.developerstudio.eclipse.artifact.gadget.model.GadgetModel;
import org.wso2.developerstudio.eclipse.artifact.gadget.template.GadgetTemplate;
import org.wso2.developerstudio.eclipse.artifact.gadget.utils.GadgetImageUtils;
import org.wso2.developerstudio.eclipse.capp.maven.utils.MavenConstants;
import org.wso2.developerstudio.eclipse.libraries.utils.LibraryUtils;
import org.wso2.developerstudio.eclipse.maven.util.MavenUtils;
import org.wso2.developerstudio.eclipse.platform.ui.wizard.AbstractWSO2ProjectCreationWizard;
import org.wso2.developerstudio.eclipse.utils.archive.ArchiveManipulator;
import org.wso2.developerstudio.eclipse.utils.file.FileUtils;
import org.wso2.developerstudio.eclipse.utils.jdt.JavaUtils;
import org.wso2.developerstudio.eclipse.utils.project.ProjectUtils;

public class GadgetCreationWizard extends AbstractWSO2ProjectCreationWizard {
	private static final String GADGET_PROJECT_NATURE = "org.wso2.developerstudio.eclipse.artifact.gadget.project.nature";
	private GadgetModel gadgetModel;
    private  IProject project;
    private static final String GADGET_CONF_FILE = "gadget-conf.xml";

	public GadgetCreationWizard() {
		setGadgetModel(new GadgetModel());
		setModel(getGadgetModel());
		setWindowTitle("Create New Gadget ");
		setDefaultPageImageDescriptor(GadgetImageUtils.getInstance().getImageDescriptor("Gadget-wizard.png"));
	}

	public boolean performFinish(){
		try{
		File gadgetFile =null;
		if(gadgetModel.getSelectedOption().equals("new.gadget")){
		project = createNewProject();
		IFolder gadgetResource =createWorkspaceFolder("gadget-resources");
//		JavaUtils.addJavaSupportAndSourceFolder(project,null);
		String fileName = gadgetModel.getGadgetXml().replaceAll(".xml$","")+".xml";
		createWorkspaceFolder("gadget-resources/thumb");
		gadgetFile = createProjectFile(gadgetResource, fileName,
							GadgetTemplate.createGadgetXmlTemp(project.getName()));
		createProjectFile(gadgetResource, GADGET_CONF_FILE,
				GadgetTemplate.createGadgetConf(gadgetModel));
		project.refreshLocal(IResource.DEPTH_INFINITE,new NullProgressMonitor());
		}
		if(gadgetModel.getSelectedOption().equals("import.gadget.fs")){
		   project = createNewProject();
//		   JavaUtils.addJavaSupportAndSourceFolder(project,null);
		   IFolder gadgetResource =createWorkspaceFolder("gadget-resources");
		   File sourceFile = new File(gadgetModel.getResourceDir());
		   FileUtils.copyDirectoryContents(sourceFile, gadgetResource.getLocation().toFile());
		   project.refreshLocal(IResource.DEPTH_INFINITE,new NullProgressMonitor());
		}
		if(gadgetModel.getSelectedOption().equals("import.dar")){
			project = createNewProject();
//		    JavaUtils.addJavaSupportAndSourceFolder(project,null);
		    IFolder gadgetResource =createWorkspaceFolder("gadget-resources");
		    File importFile = getModel().getImportFile();
		    ArchiveManipulator archiveManipulator = new ArchiveManipulator();
			archiveManipulator.extract(importFile, gadgetResource.getLocation().toFile());
			gadgetResource.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
		}
		File pomfile = project.getFile("pom.xml").getLocation().toFile();
		getModel().getMavenInfo().setPackageName("wso2/gadget");
		if(!pomfile.exists()){
			createPOM(pomfile);
			addDependancies(project);
		}
		MavenProject mavenProject = MavenUtils.getMavenProject(pomfile);

		boolean pluginExists = MavenUtils.checkOldPluginEntry(mavenProject,
				"org.wso2.maven", "maven-gadget-plugin",
				MavenConstants.MAVEN_GADGET_PLUGIN_VERSION);
		if(pluginExists){
			project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
			return true;
		}
		project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
		ProjectUtils.addNatureToProject(project,false,
		                       GADGET_PROJECT_NATURE);
		MavenUtils
		.updateWithMavenEclipsePlugin(
				pomfile,
				new String[] { },
				new String[] { GADGET_PROJECT_NATURE });
		getModel().addToWorkingSet(project);
		project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());

		if(gadgetModel.getSelectedOption().equals("new.gadget")){
			openEditor(gadgetFile);
		}
	}catch(Exception e){
		 return false;
		}
	 return true;
	}

	public void setGadgetModel(GadgetModel gadgetModel) {
		this.gadgetModel = gadgetModel;
	}

	public GadgetModel getGadgetModel() {
		return gadgetModel;
	}

	public String getProjectRelativePath() {
		String path =getModel().getLocation().getPath().substring(ResourcesPlugin.getWorkspace()
		                                                             .getRoot().getLocation()
		                                                             .toOSString().length());
		return path;
	}

	public IResource getCreatedResource() {
		// TODO Auto-generated method stub
		return null;
	}

	private File createProjectFile(IFolder folder,String fileName,String fileSource) throws IOException{
		File  file = new File(folder.getLocation().toFile(),fileName);
		FileUtils.createFile(file, fileSource);
		return file;
	}

	private IFolder createWorkspaceFolder(String folderName) throws CoreException {
		IFolder folder = ProjectUtils.getWorkspaceFolder(project,folderName);
		if (!folder.exists()) {
			folder.create(false, true, null);
		}
		return folder;
	}

	private void addDependancies(IProject project) {
		try {
			String[] depedencyList1 = getDepandanceyList();
			if(depedencyList1!=null){
				for (String libName : depedencyList1) {
					if(libName!=""){
						File dependencyPath = LibraryUtils.getDependencyPath(libName);
						JavaUtils.addJarLibraryToProject(project, dependencyPath);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private String[] getDepandanceyList() throws Exception {
		String[] depedencyList =null;
		ResourceBundle mediatorPropetiesBundle = ResourceBundle.getBundle("gadget");
		String jarList = mediatorPropetiesBundle.getString("Plugin_dependencies");
		if(!"".equals(jarList)){
			String delimiter = ",";
		    depedencyList = jarList.split(delimiter);
		}
		return depedencyList;
	}

	public void openEditor(File file){
		try {
			refreshDistProjects();
			IFile resFile  = ResourcesPlugin
			.getWorkspace()
			.getRoot()
			.getFileForLocation(
					Path.fromOSString(file.getAbsolutePath()));
			IDE.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(),resFile);
		} catch (Exception e) { /* ignore */}
	}
}


text:
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Transducers.Net;
using static Transducers.Net.Transducers;

namespace Tests
{
    [TestFixture]
    class EnumerableTests
    {
        [Test]
        public void TakeTest()
        {
            var transducer = Take<int>(3);
            var input = TestUtils.UpTo(5);
            var output = input.Transduce(transducer);
            var expected = TestUtils.UpTo(2);
            Assert.That(expected, Is.EqualTo(output));
        }

        [Test]
        public void LazyTakeTest()
        {
            var transducer = Take<int>(20);
            var input = AllInts();
            var output = input.Transduce(transducer);
            var expected = TestUtils.UpTo(19);
            Assert.That(expected, Is.EqualTo(output));
        }

        [Test]
        public void LazyComposeTest()
        {
            var transducer = Select<int, int>(x => x * 2).Then(Take<int>(10));
            var input = AllInts();
            var output = input.Transduce(transducer);
            var expected = TestUtils.UpTo(9).Select(x => x * 2);
            Assert.That(expected, Is.EqualTo(output));
        }

        private static IEnumerable<int> AllInts()
        {
            int counter = 0;
            while (true) {
                yield return counter++;
            }
            // ReSharper disable once FunctionNeverReturns
        }
    }
}


text:
<?php

final class ManiphestTaskEditController extends ManiphestController {

  public function handleRequest(AphrontRequest $request) {
    $viewer = $this->getViewer();
    $id = $request->getURIData('id');

    $response_type = $request->getStr('responseType', 'task');
    $order = $request->getStr('order', PhabricatorProjectColumn::DEFAULT_ORDER);

    $can_edit_assign = $this->hasApplicationCapability(
      ManiphestEditAssignCapability::CAPABILITY);
    $can_edit_policies = $this->hasApplicationCapability(
      ManiphestEditPoliciesCapability::CAPABILITY);
    $can_edit_priority = $this->hasApplicationCapability(
      ManiphestEditPriorityCapability::CAPABILITY);
    $can_edit_projects = $this->hasApplicationCapability(
      ManiphestEditProjectsCapability::CAPABILITY);
    $can_edit_status = $this->hasApplicationCapability(
      ManiphestEditStatusCapability::CAPABILITY);
    $can_create_projects = PhabricatorPolicyFilter::hasCapability(
      $viewer,
      PhabricatorApplication::getByClass('PhabricatorProjectApplication'),
      ProjectCreateProjectsCapability::CAPABILITY);

    $parent_task = null;
    $template_id = null;

    if ($id) {
      $task = id(new ManiphestTaskQuery())
        ->setViewer($viewer)
        ->requireCapabilities(
          array(
            PhabricatorPolicyCapability::CAN_VIEW,
            PhabricatorPolicyCapability::CAN_EDIT,
          ))
        ->withIDs(array($id))
        ->needSubscriberPHIDs(true)
        ->needProjectPHIDs(true)
        ->executeOne();
      if (!$task) {
        return new Aphront404Response();
      }
    } else {
      $task = ManiphestTask::initializeNewTask($viewer);

      // We currently do not allow you to set the task status when creating
      // a new task, although now that statuses are custom it might make
      // sense.
      $can_edit_status = false;

      // These allow task creation with defaults.
      if (!$request->isFormPost()) {

        $task->setTitle($request->getStr('title'));

        if ($can_edit_projects) {
          $projects = $request->getStr('projects');
          if ($projects) {
            $tokens = $request->getStrList('projects');

            $type_project = PhabricatorProjectProjectPHIDType::TYPECONST;
            foreach ($tokens as $key => $token) {
              if (phid_get_type($token) == $type_project) {
                // If this is formatted like a PHID, leave it as-is.
                continue;
              }

              if (preg_match('/^#/', $token)) {
                // If this already has a "#", leave it as-is.
                continue;
              }

              // Add a "#" prefix.
              $tokens[$key] = '#'.$token;
            }

            $default_projects = id(new PhabricatorObjectQuery())
              ->setViewer($viewer)
              ->withNames($tokens)
              ->execute();
            $default_projects = mpull($default_projects, 'getPHID');

            if ($default_projects) {
              $task->attachProjectPHIDs($default_projects);
              $projectObjs = id(new PhabricatorProjectQuery())
                ->setViewer($this->getViewer())
                ->withPHIDs($default_projects)
                ->execute();
              foreach ($projectObjs as $key => $value) {
                $task->setViewPolicy($value->getViewPolicy());
                $task->setEditPolicy($value->getViewPolicy());
                break;
              }
            }
          }
        }

        if ($can_edit_priority) {
          $priority = $request->getInt('priority');
          if ($priority !== null) {
            $priority_map = ManiphestTaskPriority::getTaskPriorityMap();
            if (isset($priority_map[$priority])) {
                $task->setPriority($priority);
            }
          }
        }

        $task->setDescription($request->getStr('description'));

        if ($can_edit_assign) {
          $assign = $request->getStr('assign');
          if (strlen($assign)) {
            $assign_user = id(new PhabricatorPeopleQuery())
              ->setViewer($viewer)
              ->withUsernames(array($assign))
              ->executeOne();
            if (!$assign_user) {
              $assign_user = id(new PhabricatorPeopleQuery())
                ->setViewer($viewer)
                ->withPHIDs(array($assign))
                ->executeOne();
            }

            if ($assign_user) {
              $task->setOwnerPHID($assign_user->getPHID());
            }
          }
        }
      }

      $template_id = $request->getInt('template');

      // You can only have a parent task if you're creating a new task.
      $parent_id = $request->getInt('parent');
      if (strlen($parent_id)) {
        $parent_task = id(new ManiphestTaskQuery())
          ->setViewer($viewer)
          ->withIDs(array($parent_id))
          ->executeOne();
        if (!$parent_task) {
          return new Aphront404Response();
        }
        if (!$template_id) {
          $template_id = $parent_id;
        }
      }
    }

    $errors = array();
    $e_title = true;

    $field_list = PhabricatorCustomField::getObjectFields(
      $task,
      PhabricatorCustomField::ROLE_EDIT);
    $field_list->setViewer($viewer);
    $field_list->readFieldsFromStorage($task);

    $aux_fields = $field_list->getFields();

    $v_space = $task->getSpacePHID();

    if ($request->isFormPost()) {
      $changes = array();

      $new_title = $request->getStr('title');
      $new_desc = $request->getStr('description');
      $new_status = $request->getStr('status');
      $v_space = $request->getStr('spacePHID');

      if (!$task->getID()) {
        $workflow = 'create';
      } else {
        $workflow = '';
      }

      $changes[ManiphestTransaction::TYPE_TITLE] = $new_title;
      $changes[ManiphestTransaction::TYPE_DESCRIPTION] = $new_desc;

      if ($can_edit_status) {
        $changes[ManiphestTransaction::TYPE_STATUS] = $new_status;
      } else if (!$task->getID()) {
        // Create an initial status transaction for the burndown chart.
        // TODO: We can probably remove this once Facts comes online.
        $changes[ManiphestTransaction::TYPE_STATUS] = $task->getStatus();
      }

      $owner_tokenizer = $request->getArr('assigned_to');
      $owner_phid = reset($owner_tokenizer);

      if (!strlen($new_title)) {
        $e_title = pht('Required');
        $errors[] = pht('Title is required.');
      }

      $old_values = array();
      foreach ($aux_fields as $aux_arr_key => $aux_field) {
        // TODO: This should be buildFieldTransactionsFromRequest() once we
        // switch to ApplicationTransactions properly.

        $aux_old_value = $aux_field->getOldValueForApplicationTransactions();
        $aux_field->readValueFromRequest($request);
        $aux_new_value = $aux_field->getNewValueForApplicationTransactions();

        // TODO: We're faking a call to the ApplicaitonTransaction validation
        // logic here. We need valid objects to pass, but they aren't used
        // in a meaningful way. For now, build User objects. Once the Maniphest
        // objects exist, this will switch over automatically. This is a big
        // hack but shouldn't be long for this world.
        $placeholder_editor = id(new PhabricatorUserProfileEditor())
          ->setActor($viewer);

        $field_errors = $aux_field->validateApplicationTransactions(
          $placeholder_editor,
          PhabricatorTransactions::TYPE_CUSTOMFIELD,
          array(
            id(new ManiphestTransaction())
              ->setOldValue($aux_old_value)
              ->setNewValue($aux_new_value),
          ));

        foreach ($field_errors as $error) {
          $errors[] = $error->getMessage();
        }

        $old_values[$aux_field->getFieldKey()] = $aux_old_value;
      }

      if ($errors) {
        $task->setTitle($new_title);
        $task->setDescription($new_desc);
        $task->setPriority($request->getInt('priority'));
        $task->setOwnerPHID($owner_phid);
        $task->attachSubscriberPHIDs($request->getArr('cc'));
        $task->attachProjectPHIDs($request->getArr('projects'));
      } else {

        if ($can_edit_priority) {
          $changes[ManiphestTransaction::TYPE_PRIORITY] =
            $request->getInt('priority');
        }
        if ($can_edit_assign) {
          $changes[ManiphestTransaction::TYPE_OWNER] = $owner_phid;
        }

        $changes[PhabricatorTransactions::TYPE_SUBSCRIBERS] =
          array('=' => $request->getArr('cc'));

        if ($can_edit_projects) {
          $projects = $request->getArr('projects');
          $changes[PhabricatorTransactions::TYPE_EDGE] =
            $projects;
          $column_phid = $request->getStr('columnPHID');
          // allow for putting a task in a project column at creation -only-
          if (!$task->getID() && $column_phid && $projects) {
            $column = id(new PhabricatorProjectColumnQuery())
              ->setViewer($viewer)
              ->withProjectPHIDs($projects)
              ->withPHIDs(array($column_phid))
              ->executeOne();
            if ($column) {
              $changes[ManiphestTransaction::TYPE_PROJECT_COLUMN] =
                array(
                  'new' => array(
                    'projectPHID' => $column->getProjectPHID(),
                    'columnPHIDs' => array($column_phid),
                  ),
                  'old' => array(
                    'projectPHID' => $column->getProjectPHID(),
                    'columnPHIDs' => array(),
                  ),
                );
            }
          }
        }

        if ($can_edit_policies) {
          $changes[PhabricatorTransactions::TYPE_SPACE] = $v_space;
          $changes[PhabricatorTransactions::TYPE_VIEW_POLICY] =
            $request->getStr('viewPolicy');
          $changes[PhabricatorTransactions::TYPE_EDIT_POLICY] =
            $request->getStr('editPolicy');
        }

        $template = new ManiphestTransaction();
        $transactions = array();

        foreach ($changes as $type => $value) {
          $transaction = clone $template;
          $transaction->setTransactionType($type);
          if ($type == ManiphestTransaction::TYPE_PROJECT_COLUMN) {
            $transaction->setNewValue($value['new']);
            $transaction->setOldValue($value['old']);
          } else if ($type == PhabricatorTransactions::TYPE_EDGE) {
            $project_type =
              PhabricatorProjectObjectHasProjectEdgeType::EDGECONST;
            $transaction
              ->setMetadataValue('edge:type', $project_type)
              ->setNewValue(
                array(
                  '=' => array_fuse($value),
                ));
          } else {
            $transaction->setNewValue($value);
          }
          $transactions[] = $transaction;
        }

        if ($aux_fields) {
          foreach ($aux_fields as $aux_field) {
            $transaction = clone $template;
            $transaction->setTransactionType(
              PhabricatorTransactions::TYPE_CUSTOMFIELD);
            $aux_key = $aux_field->getFieldKey();
            $transaction->setMetadataValue('customfield:key', $aux_key);
            $old = idx($old_values, $aux_key);
            $new = $aux_field->getNewValueForApplicationTransactions();

            $transaction->setOldValue($old);
            $transaction->setNewValue($new);

            $transactions[] = $transaction;
          }
        }

        if ($transactions) {
          $is_new = !$task->getID();

          $event = new PhabricatorEvent(
            PhabricatorEventType::TYPE_MANIPHEST_WILLEDITTASK,
            array(
              'task'          => $task,
              'new'           => $is_new,
              'transactions'  => $transactions,
            ));
          $event->setUser($viewer);
          $event->setAphrontRequest($request);
          PhutilEventEngine::dispatchEvent($event);

          $task = $event->getValue('task');
          $transactions = $event->getValue('transactions');

          $editor = id(new ManiphestTransactionEditor())
            ->setActor($viewer)
            ->setContentSourceFromRequest($request)
            ->setContinueOnNoEffect(true)
            ->applyTransactions($task, $transactions);

          $event = new PhabricatorEvent(
            PhabricatorEventType::TYPE_MANIPHEST_DIDEDITTASK,
            array(
              'task'          => $task,
              'new'           => $is_new,
              'transactions'  => $transactions,
            ));
          $event->setUser($viewer);
          $event->setAphrontRequest($request);
          PhutilEventEngine::dispatchEvent($event);
        }

        if ($parent_task) {
          // TODO: This should be transactional now.
          id(new PhabricatorEdgeEditor())
            ->addEdge(
              $parent_task->getPHID(),
              ManiphestTaskDependsOnTaskEdgeType::EDGECONST,
              $task->getPHID())
            ->save();
          $workflow = $parent_task->getID();
        }

        if ($request->isAjax()) {
          switch ($response_type) {
            case 'card':
              $owner = null;
              if ($task->getOwnerPHID()) {
                $owner = id(new PhabricatorHandleQuery())
                  ->setViewer($viewer)
                  ->withPHIDs(array($task->getOwnerPHID()))
                  ->executeOne();
              }
              $tasks = id(new ProjectBoardTaskCard())
                ->setViewer($viewer)
                ->setTask($task)
                ->setOwner($owner)
                ->setCanEdit(true)
                ->getItem();

              $column = id(new PhabricatorProjectColumnQuery())
                ->setViewer($viewer)
                ->withPHIDs(array($request->getStr('columnPHID')))
                ->executeOne();
              if (!$column) {
                return new Aphront404Response();
              }

              // re-load projects for accuracy as they are not re-loaded via
              // the editor
              $project_phids = PhabricatorEdgeQuery::loadDestinationPHIDs(
                $task->getPHID(),
                PhabricatorProjectObjectHasProjectEdgeType::EDGECONST);
              $task->attachProjectPHIDs($project_phids);
              $remove_from_board = false;
              if (!in_array($column->getProjectPHID(), $project_phids)) {
                $remove_from_board = true;
              }

              $positions = id(new PhabricatorProjectColumnPositionQuery())
                ->setViewer($viewer)
                ->withColumns(array($column))
                ->execute();
              $task_phids = mpull($positions, 'getObjectPHID');

              $column_tasks = id(new ManiphestTaskQuery())
                ->setViewer($viewer)
                ->withPHIDs($task_phids)
                ->execute();

              if ($order == PhabricatorProjectColumn::ORDER_NATURAL) {
                // TODO: This is a little bit awkward, because PHP and JS use
                // slightly different sort order parameters to achieve the same
                // effect. It would be good to unify this a bit at some point.
                $sort_map = array();
                foreach ($positions as $position) {
                  $sort_map[$position->getObjectPHID()] = array(
                    -$position->getSequence(),
                    $position->getID(),
                  );
                }
              } else {
                $sort_map = mpull(
                  $column_tasks,
                  'getPrioritySortVector',
                  'getPHID');
              }

              $data = array(
                'sortMap' => $sort_map,
                'removeFromBoard' => $remove_from_board,
              );
              break;
            case 'task':
            default:
              $tasks = $this->renderSingleTask($task);
              $data = array();
              break;
          }
          return id(new AphrontAjaxResponse())->setContent(
            array(
              'tasks' => $tasks,
              'data' => $data,
            ));
        }

        $redirect_uri = '/T'.$task->getID();

        if ($workflow) {
          $redirect_uri .= '?workflow='.$workflow;
        }

        return id(new AphrontRedirectResponse())
          ->setURI($redirect_uri);
      }
    } else {
      if (!$task->getID()) {
        $task->attachSubscriberPHIDs(array(
          $viewer->getPHID(),
        ));
        if ($template_id) {
          $template_task = id(new ManiphestTaskQuery())
            ->setViewer($viewer)
            ->withIDs(array($template_id))
            ->needSubscriberPHIDs(true)
            ->needProjectPHIDs(true)
            ->executeOne();
          if ($template_task) {
            $cc_phids = array_unique(array_merge(
              $template_task->getSubscriberPHIDs(),
              array($viewer->getPHID())));
            $task->attachSubscriberPHIDs($cc_phids);
            $task->attachProjectPHIDs($template_task->getProjectPHIDs());
            $task->setOwnerPHID($template_task->getOwnerPHID());
            $task->setPriority($template_task->getPriority());
            $task->setViewPolicy($template_task->getViewPolicy());
            $task->setEditPolicy($template_task->getEditPolicy());

            $v_space = $template_task->getSpacePHID();

            $template_fields = PhabricatorCustomField::getObjectFields(
              $template_task,
              PhabricatorCustomField::ROLE_EDIT);

            $fields = $template_fields->getFields();
            foreach ($fields as $key => $field) {
              if (!$field->shouldCopyWhenCreatingSimilarTask()) {
                unset($fields[$key]);
              }
              if (empty($aux_fields[$key])) {
                unset($fields[$key]);
              }
            }

            if ($fields) {
              id(new PhabricatorCustomFieldList($fields))
                ->setViewer($viewer)
                ->readFieldsFromStorage($template_task);

              foreach ($fields as $key => $field) {
                $aux_fields[$key]->setValueFromStorage(
                  $field->getValueForStorage());
              }
            }
          }
        }
      }
    }

    $error_view = null;
    if ($errors) {
      $error_view = new PHUIInfoView();
      $error_view->setErrors($errors);
    }

    $priority_map = ManiphestTaskPriority::getTaskPriorityMap();

    if ($task->getOwnerPHID()) {
      $assigned_value = array($task->getOwnerPHID());
    } else {
      $assigned_value = array();
    }

    if ($task->getSubscriberPHIDs()) {
      $cc_value = $task->getSubscriberPHIDs();
    } else {
      $cc_value = array();
    }

    if ($task->getProjectPHIDs()) {
      $projects_value = $task->getProjectPHIDs();
    } else {
      $projects_value = array();
    }

    $cancel_id = nonempty($task->getID(), $template_id);
    if ($cancel_id) {
      $cancel_uri = '/T'.$cancel_id;
    } else {
      $cancel_uri = '/maniphest/';
    }

    if ($task->getID()) {
      $button_name = pht('Save Task');
      $header_name = pht('Edit Task');
    } else if ($parent_task) {
      $cancel_uri = '/T'.$parent_task->getID();
      $button_name = pht('Create Task');
      $header_name = pht('Create New Subtask');
    } else {
      $button_name = pht('Create Task');
      $header_name = pht('Create New Task');
    }

    require_celerity_resource('maniphest-task-edit-css');

    $project_tokenizer_id = celerity_generate_unique_node_id();

    $form = new AphrontFormView();
    $form
      ->setUser($viewer)
      ->addHiddenInput('template', $template_id)
      ->addHiddenInput('responseType', $response_type)
      ->addHiddenInput('order', $order)
      ->addHiddenInput('ungrippable', $request->getStr('ungrippable'))
      ->addHiddenInput('columnPHID', $request->getStr('columnPHID'));

    if ($parent_task) {
      $form
        ->appendChild(
          id(new AphrontFormStaticControl())
            ->setLabel(pht('Parent Task'))
            ->setValue($viewer->renderHandle($parent_task->getPHID())))
        ->addHiddenInput('parent', $parent_task->getID());
    }

    $form
      ->appendChild(
        id(new AphrontFormTextAreaControl())
          ->setLabel(pht('Title'))
          ->setName('title')
          ->setError($e_title)
          ->setHeight(AphrontFormTextAreaControl::HEIGHT_VERY_SHORT)
          ->setValue($task->getTitle()));

    if ($can_edit_status) {
      // See T4819.
      $status_map = ManiphestTaskStatus::getTaskStatusMap();
      $dup_status = ManiphestTaskStatus::getDuplicateStatus();

      if ($task->getStatus() != $dup_status) {
        unset($status_map[$dup_status]);
      }

      $form
        ->appendChild(
          id(new AphrontFormSelectControl())
            ->setLabel(pht('Status'))
            ->setName('status')
            ->setValue($task->getStatus())
            ->setOptions($status_map));
    }

    $policies = id(new PhabricatorPolicyQuery())
      ->setViewer($viewer)
      ->setObject($task)
      ->execute();

    if ($can_edit_assign) {
      $form->appendControl(
        id(new AphrontFormTokenizerControl())
          ->setLabel(pht('Assigned To'))
          ->setName('assigned_to')
          ->setValue($assigned_value)
          ->setUser($viewer)
          ->setDatasource(new PhabricatorPeopleDatasource())
          ->setLimit(1));
    }

    $form
      ->appendControl(
        id(new AphrontFormTokenizerControl())
          ->setLabel(pht('CC'))
          ->setName('cc')
          ->setValue($cc_value)
          ->setUser($viewer)
          ->setDatasource(new PhabricatorMetaMTAMailableDatasource()));

    if ($can_edit_priority) {
      $form
        ->appendChild(
          id(new AphrontFormSelectControl())
            ->setLabel(pht('Priority'))
            ->setName('priority')
            ->setOptions($priority_map)
            ->setValue($task->getPriority()));
    }

    if ($can_edit_policies) {
      $form
        ->appendChild(
          id(new AphrontFormPolicyControl())
            ->setUser($viewer)
            ->setCapability(PhabricatorPolicyCapability::CAN_VIEW)
            ->setPolicyObject($task)
            ->setPolicies($policies)
            ->setSpacePHID($v_space)
            ->setName('viewPolicy'))
        ->appendChild(
          id(new AphrontFormPolicyControl())
            ->setUser($viewer)
            ->setCapability(PhabricatorPolicyCapability::CAN_EDIT)
            ->setPolicyObject($task)
            ->setPolicies($policies)
            ->setName('editPolicy'));
    }

    if ($can_edit_projects) {
      $caption = null;
      if ($can_create_projects) {
        $caption = javelin_tag(
          'a',
          array(
            'href'        => '/project/create/',
            'mustcapture' => true,
            'sigil'       => 'project-create',
          ),
          pht('Create New Project'));
      }
      $form
        ->appendControl(
          id(new AphrontFormTokenizerControl())
            ->setLabel(pht('Projects'))
            ->setName('projects')
            ->setValue($projects_value)
            ->setID($project_tokenizer_id)
            ->setCaption($caption)
            ->setDatasource(new PhabricatorProjectDatasource()));
    }

    $field_list->appendFieldsToForm($form);

    require_celerity_resource('phui-info-view-css');

    Javelin::initBehavior('project-create', array(
      'tokenizerID' => $project_tokenizer_id,
    ));

    $description_control = id(new PhabricatorRemarkupControl())
      ->setLabel(pht('Description'))
      ->setName('description')
      ->setID('description-textarea')
      ->setValue($task->getDescription())
      ->setUser($viewer);

    $form
      ->appendChild($description_control);

    if ($request->isAjax()) {
      $dialog = id(new AphrontDialogView())
        ->setUser($viewer)
        ->setWidth(AphrontDialogView::WIDTH_FULL)
        ->setTitle($header_name)
        ->appendChild(
          array(
            $error_view,
            $form->buildLayoutView(),
          ))
        ->addCancelButton($cancel_uri)
        ->addSubmitButton($button_name);
      return id(new AphrontDialogResponse())->setDialog($dialog);
    }

    $form
      ->appendChild(
        id(new AphrontFormSubmitControl())
          ->addCancelButton($cancel_uri)
          ->setValue($button_name));

    $form_box = id(new PHUIObjectBoxView())
      ->setHeaderText($header_name)
      ->setFormErrors($errors)
      ->setForm($form);

    $preview = id(new PHUIRemarkupPreviewPanel())
      ->setHeader(pht('Description Preview'))
      ->setControlID('description-textarea')
      ->setPreviewURI($this->getApplicationURI('task/descriptionpreview/'));

    if ($task->getID()) {
      $page_objects = array($task->getPHID());
    } else {
      $page_objects = array();
    }

    $crumbs = $this->buildApplicationCrumbs();

    if ($task->getID()) {
      $crumbs->addTextCrumb('T'.$task->getID(), '/T'.$task->getID());
    }

    $crumbs->addTextCrumb($header_name);

    return $this->buildApplicationPage(
      array(
        $crumbs,
        $form_box,
        $preview,
      ),
      array(
        'title' => $header_name,
        'pageObjects' => $page_objects,
      ));
  }

}


text:
typedef struct char_device char_device_t;
typedef struct char_device_ops char_device_ops_t;

#include "common/types.h"
#include "sync/spinlock.h"
#include "fs/vfs.h"

struct char_device_ops {
    ssize_t (*read)(char_device_t *device, char *buff, size_t len);
    ssize_t (*write)(char_device_t *device, const char *buff, size_t len);
    ssize_t (*poll)(char_device_t *device, fpoll_data_t *fp);
};

struct char_device {
    void *private;

    char_device_ops_t *ops;

    spinlock_t lock;
};

char_device_t * char_device_alloc();
void register_char_device(char_device_t *device, char *name);

#endif


text:
/* @version $Id: debug.c 1198399 2011-11-06 16:20:44Z mturk $ */
#include "jsvc.h"
#include <sys/types.h>
#include <unistd.h>
#include <time.h>

/* Wether debug is enabled or not */
bool log_debug_flag = false;

/* Wether SYSLOG logging (for stderr) is enable or not. */
bool log_stderr_syslog_flag = false;

/* Wether SYSLOG logging (for stdout) is enable or not. */
bool log_stdout_syslog_flag = false;

/* The name of the jsvc binary. */
char *log_prog = "jsvc";

/* Dump a debug trace message to stderr */
void log_debug(const char *fmt, ...)
{
    va_list ap;
    time_t now;
    struct tm *nowtm;
    char buff[80];

    if (log_debug_flag == false)
        return;
    if (fmt == NULL)
        return;

    now   = time(NULL);
    nowtm = localtime(&now);
    strftime(buff, sizeof(buff), "%Y-%m-%d %T", nowtm);
    va_start(ap, fmt);
    if (log_stderr_syslog_flag)
        fprintf(stderr, "%s %d %s debug: ", buff, getpid(), log_prog);
#if defined(DEBUG) || defined(_DEBUG)
    else
        fprintf(stderr, "[debug] %s %d ", buff, getpid());
#endif
    vfprintf(stderr, fmt, ap);
    fprintf(stderr, "\n");
    fflush(stderr);
    va_end(ap);
}

/* Dump an error message to stderr */
void log_error(const char *fmt, ...)
{
    va_list ap;
    time_t now;
    struct tm *nowtm;
    char buff[80];

    if (fmt == NULL)
        return;

    va_start(ap, fmt);
    if (log_stderr_syslog_flag) {
        now   = time(NULL);
        nowtm = localtime(&now);
        strftime(buff, sizeof(buff), "%Y-%m-%d %T", nowtm);
        fprintf(stderr, "%s %d %s error: ", buff, getpid(), log_prog);
    }
    vfprintf(stderr, fmt, ap);
    fprintf(stderr, "\n");
    fflush(stderr);
    va_end(ap);
}


text:
"""
###############################################################################
Classes that encapsulate top-level interfaces.
Allows same GUI to be main, pop-up, or attached; content classes may inherit
from these directly, or be mixed together with them per usage mode; may also
be called directly without a subclass; designed to be mixed in after (further
to the right than) app-specific classes: else, subclass gets methods here
(destroy, okayToQuit), instead of from app-specific classes--can't redefine.
###############################################################################
"""

import os, glob
from Tkinter import Tk, Toplevel, Frame, YES, BOTH, RIDGE
from Tkinter.messagebox import showinfo, askyesno

class _window:
    """
    mixin shared by main and pop-up windows
    """
    foundicon = None                                       # shared by all inst
    iconpatt  = '*.ico'                                    # may be reset
    iconmine  = 'py.ico'

    def configBorders(self, app, kind, iconfile):
        if not iconfile:                                   # no icon passed?
            iconfile = self.findIcon()                     # try curr,tool dirs
        title = app
        if kind: title += ' - ' + kind
        self.title(title)                                  # on window border
        self.iconname(app)                                 # when minimized
        if iconfile:
            try:
                self.iconbitmap(iconfile)                  # window icon image
            except:                                        # bad py or platform
                pass
        self.protocol('WM_DELETE_WINDOW', self.quit)       # don't close silent

    def findIcon(self):
        if _window.foundicon:                              # already found one?
            return _window.foundicon
        iconfile  = None                                   # try curr dir first
        iconshere = glob.glob(self.iconpatt)               # assume just one
        if iconshere:                                      # del icon for red Tk
            iconfile = iconshere[0]
        else:                                              # try tools dir icon
            mymod  = __import__(__name__)                  # import self for dir
            path   = __name__.split('.')                   # poss a package path
            for mod in path[1:]:                           # follow path to end
                mymod = getattr(mymod, mod)                # only have leftmost
            mydir  = os.path.dirname(mymod.__file__)
            myicon = os.path.join(mydir, self.iconmine)    # use myicon, not tk
            if os.path.exists(myicon): iconfile = myicon
        _window.foundicon = iconfile                       # don't search again
        return iconfile

class MainWindow(Tk, _window):
    """
    when run in main top-level window
    """
    def __init__(self, app, kind='', iconfile=None):
        self.findIcon()
        Tk.__init__(self)
        self.__app = app
        self.configBorders(app, kind, iconfile)

    def quit(self):
        if self.okayToQuit():                                # threads running?
            if askyesno(self.__app, 'Verify Quit Program?'):
                self.destroy()                               # quit whole app
        else:
            showinfo(self.__app, 'Quit not allowed')         # or in okayToQuit?

    def destroy(self):                                       # exit app silently
        Tk.quit(self)                                        # redef if exit ops

    def okayToQuit(self):                                    # redef me if used
        return True                                          # e.g., thread busy

class PopupWindow(Toplevel, _window):
    """
    when run in secondary pop-up window
    """
    def __init__(self, app, kind='', iconfile=None):
        Toplevel.__init__(self)
        self.__app = app
        self.configBorders(app, kind, iconfile)

    def quit(self):                                        # redef me to change
        if askyesno(self.__app, 'Verify Quit Window?'):    # or call destroy
            self.destroy()                                 # quit this window

    def destroy(self):                                     # close win silently
        Toplevel.destroy(self)                             # redef for close ops

class QuietPopupWindow(PopupWindow):
    def quit(self):
        self.destroy()                                     # don't verify close

class ComponentWindow(Frame):
    """
    when attached to another display
    """
    def __init__(self, parent):                            # if not a frame
        Frame.__init__(self, parent)                       # provide container
        self.pack(expand=YES, fill=BOTH)
        self.config(relief=RIDGE, border=2)                # reconfig to change

    def quit(self):
        showinfo('Quit', 'Not supported in attachment mode')

    # destroy from Frame: erase frame silent               # redef for close ops


text:
package uk.ac.ebi.arrayexpress.utils.efo;

import java.io.Serializable;
import java.util.*;

/**
 * Internal EFO class representation structure.
 */
public class EFONode implements Serializable
{
    private String id;
    private String efoUri;
    private String term;
    private Set<String> alternativeTerms;
    private Boolean isOrganizationalClass;

    /**
     * Comparator comparing 2 nodes by comparing their terms lexicographically.
     */

    protected static final Comparator<EFONode> TERM_COMPARATOR = new Comparator<EFONode>()
    {
        private String safeGetTerm( EFONode node )
        {
            return null != node && null != node.getTerm() ? node.getTerm() : "";
        }

        public int compare( EFONode o1, EFONode o2 )
        {
            return safeGetTerm(o1).compareTo(safeGetTerm(o2));
        }
    };

    private SortedSet<EFONode> children = new TreeSet<EFONode>(TERM_COMPARATOR);
    private SortedSet<EFONode> parents = new TreeSet<EFONode>(TERM_COMPARATOR);

    protected EFONode( String id )
    {
        this.setId(id);
        this.setAlternativeTerms(new HashSet<String>());
    }

    @Override
    public boolean equals( Object o )
    {
        if (this == o) return true;
        if (null == o || getClass() != o.getClass()) return false;
        EFONode node = (EFONode) o;
        return (getId() != null ? getId().equals(node.getId()) : node.getId() == null);
    }

    @Override
    public int hashCode()
    {
        int result = getId() != null ? getId().hashCode() : 0;
        result = 31 * result + (getTerm() != null ? getTerm().hashCode() : 0);
        result = 31 * result + (getChildren() != null ? getChildren().hashCode() : 0);
        return result;
    }

    @Override
    public String toString()
    {
        return getId() + "(" + getTerm() + ")" + (getChildren().isEmpty() ? "" : "+");
    }

    public String getId()
    {
        return this.id;
    }

    public void setId( String id )
    {
        this.id = id;
    }

    public String getEfoUri()
    {
        return this.efoUri;
    }

    public void setEfoUri( String efoUri )
    {
        this.efoUri = efoUri;
    }

    public String getTerm()
    {
        return this.term;
    }

    public void setTerm( String term )
    {
        this.term = term;
    }

    public Set<String> getAlternativeTerms()
    {
        return this.alternativeTerms;
    }

    public void setAlternativeTerms( Set<String> terms )
    {
        this.alternativeTerms = terms;
    }

    public boolean isOrganizationalClass()
    {
        return null != this.isOrganizationalClass && this.isOrganizationalClass;
    }

    public void setOrganizationalClass( Boolean isOrganizationalClass )
    {
        this.isOrganizationalClass = isOrganizationalClass;
    }

    public boolean hasChildren()
    {
        return children.size() > 0;
    }

    public SortedSet<EFONode> getChildren()
    {
        return children;
    }

    public SortedSet<EFONode> getParents()
    {
        return parents;
    }
}


text:
@implementation YMABalanceDetailsModel

#pragma mark - Object Lifecycle

- (instancetype)initWithTotal:(NSString *)total
                    available:(NSString *)available
            depositionPending:(NSString *)depositionPending
                      blocked:(NSString *)blocked
                         debt:(NSString *)debt
                         hold:(NSString *)hold
{
    self = [super init];

    if (self != nil) {
        _total = [total copy];
        _available = [available copy];
        _depositionPending = [depositionPending copy];
        _blocked = [blocked copy];
        _debt = [debt copy];
        _hold = [hold copy];
    }

    return self;
}

+ (instancetype)balanceDetailsWithTotal:(NSString *)total
                              available:(NSString *)available
                      depositionPending:(NSString *)depositionPending
                                blocked:(NSString *)blocked
                                   debt:(NSString *)debt
                                   hold:(NSString *)hold
{
    return [[YMABalanceDetailsModel alloc] initWithTotal:total
                                               available:available
                                       depositionPending:depositionPending
                                                 blocked:blocked
                                                    debt:debt
                                                    hold:hold];
}

@end