text:
package views.html.helper

import org.specs2.mutable.Specification
import play.api.data.Forms._
import play.api.data._
import play.api.i18n.Lang
import play.api.templates.Html
import scala.beans.BeanProperty

object HelpersSpec extends Specification {
  import FieldConstructor.defaultField
  import Lang.defaultLang

  "@inputText" should {

    "allow setting a custom id" in {

      val body = inputText.apply(Form(single("foo" -> Forms.text))("foo"), 'id -> "someid").body

      val idAttr = "id=\"someid\""
      body must contain(idAttr)

      // Make sure it doesn't have it twice, issue #478
      body.substring(body.indexOf(idAttr) + idAttr.length) must not contain(idAttr)
    }

    "default to a type of text" in {
      inputText.apply(Form(single("foo" -> Forms.text))("foo")).body must contain("type=\"text\"")
    }

    "allow setting a custom type" in {
      val body = inputText.apply(Form(single("foo" -> Forms.text))("foo"), 'type -> "email").body

      val typeAttr = "type=\"email\""
      body must contain(typeAttr)

      // Make sure it doesn't contain it twice
      body.substring(body.indexOf(typeAttr) + typeAttr.length) must not contain(typeAttr)
    }
  }

  "@select" should {

    "allow setting a custom id" in {

      val body = select.apply(Form(single("foo" -> Forms.text))("foo"),Seq(("0", "test")), 'id -> "someid").body

      val idAttr = "id=\"someid\""
      body must contain(idAttr)

      // Make sure it doesn't have it twice, issue #478
      body.substring(body.indexOf(idAttr) + idAttr.length) must not contain(idAttr)
    }

    "Work as a simple select" in {
      val form = Form(single("foo" -> Forms.text)).fill("0")
      val body = select.apply(form("foo"), Seq(("0", "test"), ("1", "test"))).body

      body must contain( "name=\"foo\"" )

      body must contain( """<option value="0" selected>""" )
      body must contain( """<option value="1" >""" )
    }

    "Work as a multiple select" in {
      val form = Form(single("foo" -> Forms.list(Forms.text))).fill(List("0", "1"))
      val body = select.apply(form("foo"), Seq(("0", "test"), ("1", "test")), 'multiple -> None).body

      // Append [] to the name for the form binding
      body must contain( "name=\"foo[]\"" )
      body must contain( "multiple" )

      body must contain( """<option value="0" selected>""" )
      body must contain( """<option value="1" selected>""" )
    }

  }

  "@repeat" should {
    val form = Form(single("foo" -> Forms.seq(Forms.text)))
    def renderFoo(form: Form[_], min: Int = 1) = repeat.apply(form("foo"), min) { f =>
      Html(f.name + ":" + f.value.getOrElse(""))
    }.map(_.toString)

    val complexForm = Form(single("foo" ->
      Forms.seq(tuple(
        "a" -> Forms.text,
        "b" -> Forms.text
      ))
    ))
    def renderComplex(form: Form[_], min: Int = 1) = repeat.apply(form("foo"), min) { f =>
      val a = f("a")
      val b = f("b")
      Html(s"${a.name}=${a.value.getOrElse("")},${b.name}=${b.value.getOrElse("")}")
    }.map(_.toString)

    "render a sequence of fields" in {
      renderFoo(form.fill(Seq("a", "b", "c"))) must exactly("foo[0]:a", "foo[1]:b", "foo[2]:c").inOrder
    }

    "render a sequence of fields in an unfilled form" in {
      renderFoo(form, 4) must exactly("foo[0]:", "foo[1]:", "foo[2]:", "foo[3]:").inOrder
    }

    "fill the fields out if less than the min" in {
      renderFoo(form.fill(Seq("a", "b")), 4) must exactly("foo[0]:a", "foo[1]:b", "foo[2]:", "foo[3]:").inOrder
    }

    "fill the fields out if less than the min but the maximum is high" in {
      renderFoo(form.bind(Map("foo[0]" -> "a", "foo[123]" -> "b")), 4) must exactly("foo[0]:a", "foo[123]:b", "foo[124]:", "foo[125]:").inOrder
    }

    "render the right number of fields if there's multiple sub fields at a given index when filled" in {
      renderComplex(
        complexForm.fill(Seq("somea" -> "someb"))
      ) must exactly("foo[0].a=somea,foo[0].b=someb")
    }

    "render fill the right number of fields out if there's multiple sub fields at a given index when bound" in {
      renderComplex(
        // Don't bind, we don't want it to use the successfully bound value
        form.copy(data = Map("foo[0].a" -> "somea", "foo[0].b" -> "someb"))
      ) must exactly("foo[0].a=somea,foo[0].b=someb")
    }
  }
}


text:
namespace Dot
{
	using CollidersVector = std::vector<BoundingBox *>;

	class BoundingBox : AObjectPlugin
	{
	public:
		static CollidersVector		all;
		sf::Vector2f				size;
		sf::Vector2f				min;
		sf::Vector2f				max;
		std::vector<std::string>	layers;

				BoundingBox(float = 0, float = 0);
				BoundingBox(BasicObject *, float = 0, float = 0);
		bool	collideWith(const BoundingBox &) const;
		bool	isOnSameLayer(const BoundingBox &) const;

		virtual void	update();
		virtual void	draw();
		virtual void	setParent(BasicObject *);

	private:
		void			_resetBoxPosition(void);
	};
}

#endif

redpajama_set_name: RedPajamaGithub


text:
package com.tcmonitor.server.service;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.tcmonitor.model.Health;
import com.tcmonitor.model.Logs;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.List;

@Service
public class LogProcessor {
    private static final String FULL_SCOPE = "full";
    private static final String PART_SCOPE = "part";

    @Value("${tcmonitor.log.storage}")
    private String logPathStorage;

    public void processLogs(Logs log){
        checkOrCreateVmFolder(log.getVmTag());
        if(FULL_SCOPE.equals(log.getScope())){
            File file = new File(logPathStorage + "/" + log.getVmTag() + "/" + log.getFileName());
            if(file.exists()){
                checkAndAppend(log);
            } else {
                writeFullFile(log);
            }
        }
        if(PART_SCOPE.equals(log.getScope())){
            append(log);
        }
    }

    private void checkAndAppend(Logs log) {
        String lastLine = check(log);
        if(lastLine != null){
            append(findDif(log, lastLine));
        }

    }

    private String check(Logs log){
        String lastLine = null;
        String currentLIne = "";
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(logPathStorage + "/" + log.getVmTag() + "/" + log.getFileName()), "UTF-8"));
            while ((currentLIne = br.readLine()) != null){
                if(!currentLIne.isEmpty() && !"null".equals(currentLIne)){
                    lastLine = currentLIne;
                }
            }
            br.close();
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Iterable<String> messageIterable = Splitter.on("\n").trimResults().omitEmptyStrings().split(log.getLogMessage());
        List<String> messageList = Lists.newArrayList(messageIterable);
        String lastMessage = null;
        if(!messageList.isEmpty()){
            lastMessage = messageList.get(messageList.size()-1);
        }
        if(lastLine != null && lastLine.equals(lastMessage)){
            return null;
        }
        return lastLine;
    }

    private Logs findDif(Logs log, String lastLine){
        Logs newLog = new Logs();
        newLog.setVmTag(log.getVmTag());
        newLog.setFileName(log.getFileName());
        Iterable<String> messageIterable = Splitter.on("\n").trimResults().omitEmptyStrings().split(log.getLogMessage());
        List<String> messageList = Lists.newArrayList(messageIterable);
        StringBuilder sb = new StringBuilder();
        boolean needAdd = false;
        String prefix = "\n";
        for(String message : messageList){
            if(needAdd){
                sb.append(prefix);
                sb.append(message);
            }
            if(message.equals(lastLine)){
                needAdd = true;
            }
        }

        newLog.setLogMessage(sb.toString());
        return newLog;
    }

    private void append(Logs log){
        Writer writer;
        try {
            writer = new BufferedWriter(new FileWriter(logPathStorage + "/" + log.getVmTag() + "/" + log.getFileName(), true));
            writer.append(log.getLogMessage());
            writer.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void processHealth(Health health){
        System.out.println("START-----------------------");
        System.out.println(health.getVmTag());
        System.out.println("END-----------------------");
    }

    private boolean checkOrCreateVmFolder(String vmTag){
        File vmFolder = new File(logPathStorage + "/" + vmTag);
        if(!vmFolder.exists()){
            return vmFolder.mkdir();
        }
        return false;
    }

    private void writeFullFile(Logs log){
        PrintWriter writer;
        try {
            writer = new PrintWriter(logPathStorage + "/" + log.getVmTag() + "/" + log.getFileName(), "UTF-8");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        writer.println(log.getLogMessage());
        writer.close();
    }

}


text:
package uk.ac.lkl.client.event;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.xml.client.Element;

import uk.ac.lkl.client.Utils;
import uk.ac.lkl.client.Modeller;

import uk.ac.lkl.client.composer.MacroBehaviourView;
import uk.ac.lkl.shared.CommonUtils;

@SuppressWarnings("serial")
public class RenameMacroBehaviourEvent extends ModellerEvent {

    protected String newName = null;
    protected String oldName = null;

    public RenameMacroBehaviourEvent(MacroBehaviourView object, String oldName) {
	super(object);
	this.oldName = oldName;
	this.newName = getMacroBehaviour().getNameHTML();
    }

    @Override
    public String toHTMLString(boolean brief) {
	return Modeller.constants.renamed() + Modeller.NON_BREAKING_SPACE + oldName + Modeller.NON_BREAKING_SPACE +
	       Modeller.constants.to() + Modeller.NON_BREAKING_SPACE + newName;
    }

    public String getXML() {
	return "<RenameMacroBehaviourEvent version='2' newName='" + CommonUtils.encode(newName) +
	       "' name='" + CommonUtils.encode(oldName) + "'" +
	       getDateAttribute() + "/>";
    }

    public void recordInDatabase(AsyncCallback<String[]> recordSubsequentEventCallback, boolean notifyOthers) {
	Modeller.getHistoryService().renameMacroBehaviourEvent(Modeller.userGuid, Modeller.sessionGuid,
		                                               oldName,
		                                               newName,
		                                               notifyOthers,
		                                               recordSubsequentEventCallback);
    }

    public static void reconstruct(
	    String macroBehaviourName, Element eventElement,
	    boolean restoringHistory,
	    boolean justRecord,
	    int version,
	    ReconstructEventsContinutation continuation) {
	MacroBehaviourView macroBehaviour = Modeller.instance().getMacroBehaviourWithHTMLName(macroBehaviourName);
	String newName;
	if (version == 1) {
	    newName = Utils.decode(eventElement.getAttribute("newName"));
	} else if (version == 2) {
	    newName = CommonUtils.decode(eventElement.getAttribute("newName"));
	} else {
	    newName = Utils.getElementString("newName", eventElement);
	}
	ModellerEvent event = null;
	if (macroBehaviour != null) {
	    if (!justRecord) {
		macroBehaviour.setHTML(newName);
	    }
	    if (restoringHistory) {
		event = new RenameMacroBehaviourEvent(macroBehaviour, macroBehaviourName);
	    }
	} else {
	    Modeller.addToErrorLog("Could not find a macro behaviour " + macroBehaviourName +
		                   " in RenameMacroBehaviourEvent to " + newName + ". " +
		                   "Known macro-behaviours are: " +
		                   Modeller.instance().getMacroBehaviourNames());;
	}
	continuation.reconstructSubsequentEvents(event);
    }

    @Override
    public void undo(boolean record, boolean justRecord, ReconstructEventsContinutation continuation) {
	super.undo(record, justRecord, continuation);
	if (!justRecord) {
	    getMacroBehaviour().setHTML(oldName);
	}
	if (continuation != null) {
	    continuation.reconstructSubsequentEvents(null);
	}
    }

    @Override
    public void redo(boolean record, boolean justRecord, ReconstructEventsContinutation continuation) {
	super.redo(record, justRecord, continuation);
	if (!justRecord) {
	    getMacroBehaviour().setHTML(newName);
	}
	if (continuation != null) {
	    continuation.reconstructSubsequentEvents(null);
	}
    }

    public MacroBehaviourView getMacroBehaviour() {
	return (MacroBehaviourView) getSource();
    }

}


text:
/*
 *= require delayed/web/bootstrap
 */

/* Remove bootstrap form margins on rails button_to.
 *
 * Example:
 *   <%= button_to ... form_class: 'btn-rails' %>
 */
.btn-rails {
  margin: 0;
}

.page-header {
  position: relative;
}

/* Positions a button group to the right of the header.
 */
.page-header .btn-group {
  position: absolute;
  right: 0;
  top: 0;
}

.page-header .btn-group .btn {
  margin-left: 10px;
}

/* Whitespace between the alert and top of the page.
 */
.alert {
  margin-top: 20px;
  margin-bottom: 20px;
}


text:
package com.facebook.buck.features.dotnet;

import com.google.common.collect.ImmutableList;

public enum FrameworkVersion {
  NET35(
      ImmutableList.of(
          "C:/Program Files (x86)/Reference Assemblies/Microsoft/Framework/v3.5",
          "C:/Program Files (x86)/Reference Assemblies/Microsoft/Framework/.NETFramework/v3.5/Profile/Client")),
  NET40(
      ImmutableList.of(
          "C:/Program Files (x86)/Reference Assemblies/Microsoft/Framework/.NETFramework/v4.0")),
  NET45(
      ImmutableList.of(
          "C:/Program Files (x86)/Reference Assemblies/Microsoft/Framework/.NETFramework/v4.5")),
  NET46(
      ImmutableList.of(
          "C:/Program Files (x86)/Reference Assemblies/Microsoft/Framework/.NETFramework/v4.6")),
  ;

  private final ImmutableList<String> directories;

  FrameworkVersion(ImmutableList<String> directories) {
    this.directories = directories;
  }

  public ImmutableList<String> getDirectories() {
    return directories;
  }
}


text:
package LinkFuture.EnvInjection.Model;

/**
 * Created by Cyokin on 10/24/2014.
 */
public enum  InjectionFileType {
    Property,
    Xml,
    Replace
}


text:
package mcjty.rftools.blocks.builder;

import mcjty.lib.thirteen.ConfigSpec;
import mcjty.lib.varia.Logging;
import net.minecraft.block.state.IBlockState;
import net.minecraft.command.CommandBase;
import net.minecraft.command.InvalidBlockStateException;
import net.minecraft.command.NumberInvalidException;
import net.minecraft.init.Blocks;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.registry.ForgeRegistries;

public class BuilderConfiguration {
    public static final String CATEGORY_BUILDER = "builder";

    public static ConfigSpec.IntValue BUILDER_MAXENERGY;// = 1000000;
    public static ConfigSpec.IntValue BUILDER_RECEIVEPERTICK;// = 20000;

    public static ConfigSpec.IntValue builderRfPerOperation;// = 500;
    public static ConfigSpec.IntValue builderRfPerLiquid;// = 300;
    public static ConfigSpec.IntValue builderRfPerQuarry;// = 300;
    public static ConfigSpec.IntValue builderRfPerSkipped;// = 50;
    public static ConfigSpec.IntValue builderRfPerEntity;// = 5000;
    public static ConfigSpec.IntValue builderRfPerPlayer;// = 40000;
    public static ConfigSpec.DoubleValue dimensionCostFactor;

    public static ConfigSpec.ConfigValue<BuilderTileEntityMode> teMode;

    public static ConfigSpec.BooleanValue showProgressHud;

    public static ConfigSpec.IntValue maxSpaceChamberDimension;

    public static ConfigSpec.DoubleValue voidShapeCardFactor;
    public static ConfigSpec.DoubleValue silkquarryShapeCardFactor;
    public static ConfigSpec.DoubleValue fortunequarryShapeCardFactor;

    public static ConfigSpec.ConfigValue<String> quarryReplace;
    private static IBlockState quarryReplaceBlock = null;

    public static ConfigSpec.BooleanValue quarryChunkloads;
    public static ConfigSpec.BooleanValue shapeCardAllowed;
    public static ConfigSpec.BooleanValue quarryAllowed;
    public static ConfigSpec.BooleanValue clearingQuarryAllowed;

    public static ConfigSpec.IntValue quarryBaseSpeed;
    public static ConfigSpec.IntValue quarryInfusionSpeedFactor;
    public static ConfigSpec.BooleanValue quarryTileEntities;

    public static ConfigSpec.IntValue maxBuilderOffset;
    public static ConfigSpec.IntValue maxBuilderDimension;

    public static ConfigSpec.BooleanValue oldSphereCylinderShape;

    public static ConfigSpec.IntValue collectTimer;
    public static ConfigSpec.IntValue collectRFPerItem;
    public static ConfigSpec.DoubleValue collectRFPerXP;
    public static ConfigSpec.DoubleValue collectRFPerTickPerArea;

    public static void init(ConfigSpec.Builder SERVER_BUILDER, ConfigSpec.Builder CLIENT_BUILDER) {
        SERVER_BUILDER.comment("Settings for the builder").push(CATEGORY_BUILDER);
        CLIENT_BUILDER.comment("Settings for the builder").push(CATEGORY_BUILDER);

        BUILDER_MAXENERGY = SERVER_BUILDER
                .comment("Maximum RF storage that the builder can hold")
                .defineInRange("builderMaxRF", 1000000, 0, Integer.MAX_VALUE);
        BUILDER_RECEIVEPERTICK = SERVER_BUILDER
                .comment("RF per tick that the builder can receive")
                .defineInRange("builderRFPerTick", 20000, 0, Integer.MAX_VALUE);
        builderRfPerOperation = SERVER_BUILDER
                .comment("RF per block operation for the builder when used to build")
                .defineInRange("builderRfPerOperation", 500, 0, Integer.MAX_VALUE);
        builderRfPerLiquid = SERVER_BUILDER
                .comment("Base RF per block operation for the builder when used as a pump")
                .defineInRange("builderRfPerLiquid", 300, 0, Integer.MAX_VALUE);
        builderRfPerQuarry = SERVER_BUILDER
                .comment("Base RF per block operation for the builder when used as a quarry or voider (actual cost depends on hardness of block)")
                .defineInRange("builderRfPerQuarry", 300, 0, Integer.MAX_VALUE);
        builderRfPerSkipped = SERVER_BUILDER
                .comment("RF per block that is skipped (used when a filter is added to the builder)")
                .defineInRange("builderRfPerSkipped", 50, 0, Integer.MAX_VALUE);
        builderRfPerEntity = SERVER_BUILDER
                .comment("RF per entity move operation for the builder")
                .defineInRange("builderRfPerEntity", 5000, 0, Integer.MAX_VALUE);
        builderRfPerPlayer = SERVER_BUILDER
                .comment("RF per player move operation for the builder")
                .defineInRange("builderRfPerPlayer", 40000, 0, Integer.MAX_VALUE);
        teMode = SERVER_BUILDER
                .comment("Can Tile Entities be moved? 'forbidden' means never, 'whitelist' means only whitelisted, 'blacklist' means all except blacklisted, 'allowed' means all")
                .defineEnum("tileEntityMode", BuilderTileEntityMode.MOVE_WHITELIST, BuilderTileEntityMode.values());
        maxSpaceChamberDimension = SERVER_BUILDER
                .comment("Maximum dimension for the space chamber")
                .defineInRange("maxSpaceChamberDimension", 128, 0, 100000);

        collectTimer = SERVER_BUILDER
                .comment("How many ticks we wait before collecting again (with the builder 'collect items' mode)")
                .defineInRange("collectTimer", 10, 0, Integer.MAX_VALUE);
        collectRFPerItem = SERVER_BUILDER
                .comment("The cost of collecting an item (builder 'collect items' mode))")
                .defineInRange("collectRFPerItem", 20, 0, Integer.MAX_VALUE);

        dimensionCostFactor = SERVER_BUILDER
                .comment("How much more expensive a move accross dimensions is")
                .defineInRange("dimensionCostFactor", 5.0, 0, 1000000.0);

        collectRFPerXP = SERVER_BUILDER
                .comment("The cost of collecting 1 XP level (builder 'collect items' mode))")
                .defineInRange("collectRFPerXP", 2.0, 0, 1000000.0);
        collectRFPerTickPerArea = SERVER_BUILDER
                .comment("The RF/t per area to keep checking for items in a given area (builder 'collect items' mode))")
                .defineInRange("collectRFPerTickPerArea", 0.5, 0, 1000000.0);

        voidShapeCardFactor = SERVER_BUILDER
                .comment("The RF per operation of the builder is multiplied with this factor when using the void shape card")
                .defineInRange("voidShapeCardFactor", 0.5, 0, 1000000.0);
        silkquarryShapeCardFactor = SERVER_BUILDER
                .comment("The RF per operation of the builder is multiplied with this factor when using the silk quarry shape card")
                .defineInRange("silkquarryShapeCardFactor", 3.0, 0, 1000000.0);
        fortunequarryShapeCardFactor = SERVER_BUILDER
                .comment("The RF per operation of the builder is multiplied with this factor when using the fortune quarry shape card")
                .defineInRange("fortunequarryShapeCardFactor", 2, 0, 1000000.0);

        quarryReplace = SERVER_BUILDER
                .comment("Use this block for the builder to replace with")
                .define("quarryReplacE", "minecraft:dirt");
        quarryTileEntities = SERVER_BUILDER
                .comment("If true the quarry will also quarry tile entities. Otherwise it just ignores them")
                .define("quarryTileEntities", true);
        quarryChunkloads = SERVER_BUILDER
                .comment("If true the quarry will chunkload a chunk at a time. If false the quarry will stop if a chunk is not loaded")
                .define("quarryChunkloads", true);
        shapeCardAllowed = SERVER_BUILDER
                .comment("If true we allow shape cards to be crafted. Note that in order to use the quarry system you must also enable this")
                .define("shapeCardAllowed", true);
        quarryAllowed = SERVER_BUILDER
                .comment("If true we allow quarry cards to be crafted")
                .define("quarryAllowed", true);
        clearingQuarryAllowed = SERVER_BUILDER
                .comment("If true we allow the clearing quarry cards to be crafted (these can be heavier on the server)")
                .define("clearingQuarryAllowed", true);

        quarryBaseSpeed = SERVER_BUILDER
                .comment("The base speed (number of blocks per tick) of the quarry")
                .defineInRange("quarryBaseSpeed", 8, 0, Integer.MAX_VALUE);
        quarryInfusionSpeedFactor = SERVER_BUILDER
                .comment("Multiply the infusion factor with this value and add that to the quarry base speed")
                .defineInRange("quarryInfusionSpeedFactor", 20, 0, Integer.MAX_VALUE);

        maxBuilderOffset = SERVER_BUILDER
                .comment("Maximum offset of the shape when a shape card is used in the builder")
                .defineInRange("maxBuilderOffset", 260, 0, Integer.MAX_VALUE);
        maxBuilderDimension = SERVER_BUILDER
                .comment("Maximum dimension of the shape when a shape card is used in the builder")
                .defineInRange("maxBuilderDimension", 512, 0, Integer.MAX_VALUE);

        oldSphereCylinderShape = SERVER_BUILDER
                .comment("If true we go back to the old (wrong) sphere/cylinder calculation for the builder/shield")
                .define("oldSphereCylinderShape", false);
        showProgressHud = CLIENT_BUILDER
                .comment("If true a holo hud with current progress is shown above the builder")
                .define("showProgressHud", true);

        SERVER_BUILDER.pop();
        CLIENT_BUILDER.pop();
    }

    public static IBlockState getQuarryReplace() {
        if (quarryReplaceBlock == null) {
            int index = quarryReplace.get().indexOf(' ');
            if(index == -1) {
                quarryReplaceBlock = ForgeRegistries.BLOCKS.getValue(new ResourceLocation(quarryReplace.get())).getDefaultState();
            } else {
                try {
                    quarryReplaceBlock = CommandBase.convertArgToBlockState(ForgeRegistries.BLOCKS.getValue(new ResourceLocation(quarryReplace.get().substring(0, index))), quarryReplace.get().substring(index + 1));
                } catch (NumberInvalidException | InvalidBlockStateException e) {
                    Logging.logError("Invalid builder quarry replace block: " + quarryReplace, e);
                }
            }
            if (quarryReplaceBlock == null) {
                quarryReplaceBlock = Blocks.DIRT.getDefaultState();
            }
        }
        return quarryReplaceBlock;
    }
}


text:
Ripple

Ripple directive adds ripple effect to the host element.

    <app-demoActions github="ripple" stackblitz="ripple-demo"></app-demoActions>

Default

Green

Orange

Purple

Import

<app-code lang="typescript" ngNonBindable ngPreserveWhitespaces>
import {RippleModule} from 'primeng/ripple';
</app-code>

Getting Started

Ripple is an optional animation for the supported components such as buttons. It is disabled by default and needs to be enabled globally at your main component e.g. app.component.ts by injecting
                PrimeNGConfig.

<app-code lang="typescript" ngNonBindable ngPreserveWhitespaces>
import { PrimeNGConfig } from 'primeng/api';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {

    constructor(private primengConfig: PrimeNGConfig) {}

    ngOnInit() {
        this.primengConfig.ripple = true;
    }

}
</app-code>

Directive

Ripple is applied by adding the pRipple directive to the host.

<app-code lang="markup" ngNonBindable ngPreserveWhitespaces>
<div pRipple></div>
</app-code>

<app-code lang="typescript" ngNonBindable ngPreserveWhitespaces>
export class ModelComponent {

    val: number;

}
</app-code>

Styling

Default styling of the animation adds a shade of white. This can easily be customized using css that changes the color of .p-ink element.

<app-code lang="markup" ngNonBindable ngPreserveWhitespaces>
<div pRipple class="purple" ></div>
</app-code>

<app-code lang="css" ngNonBindable ngPreserveWhitespaces>
.p-ripple.purple .p-ink {
    background: rgba(256,39,176,.3);
}
</app-code>

Styling

                                    Name
                                    Element

                                    p-ripple
                                    Host element.

                                    p-ink
                                    Ripple element.

                                    p-ink-active
                                    Ripple element during animating.

Dependencies

None.

                        View on GitHub

                        Edit in StackBlitz

<app-code lang="markup" ngNonBindable ngPreserveWhitespaces>
<div class="card-container p-d-flex">
    <div class="card primary-box" pRipple>Default</div>
    <div class="card styled-box-green" pRipple>Green</div>
    <div class="card styled-box-orange" pRipple>Orange</div>
    <div class="card styled-box-purple" pRipple>Purple</div>
</div>
</app-code>

<app-code lang="css" ngNonBindable ngPreserveWhitespaces>
:host ::ng-deep .card-container {
    .card {
        width: 75px;
        height: 75px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 1rem;
        user-select: none;
        padding: 0;

        &.primary-box {
            background-color: var(--primary-color);
            padding: 0;
            color: var(--primary-color-text);
        }

        &.styled-box-green {
            .p-ink {
                background: rgba(#4baf50, 0.3);
            }
        }

        &.styled-box-orange {
            .p-ink {
                background: rgba(#ffc106, 0.3);
            }
        }

        &.styled-box-purple {
            .p-ink {
                background: rgba(#9c27b0, 0.3);
            }
        }

        &:last-child {
            margin-right: 0;
        }
    }
}
</app-code>

<app-code lang="typescript" ngNonBindable ngPreserveWhitespaces>
export class Ripple {

}
</app-code>

                    <ng-template pTemplate="content">

                    </ng-template>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/item_userassets_title" />

    <com.xinyu.mwp.view.CellView
        android:id="@+id/buy_type"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cell_icon="@mipmap/icon_buyup"
        app:cell_content="00000"
        app:cell_name="xxx" />

    <include layout="@layout/ly_space" />
</LinearLayout>


text:
package com.intellij.execution.junit2.ui.model;

import com.intellij.execution.junit2.events.NewChildEvent;
import com.intellij.execution.junit2.events.TestEvent;
import com.intellij.execution.junit2.TestProxy;

public class TreeCollapser extends JUnitAdapter {
  private JUnitRunningModel myModel;
  private TestProxy myLastDynamicSuite = null;

  public void setModel(final JUnitRunningModel model) {
    myModel = model;
    model.addListener(this);
  }

  public void onTestChanged(final TestEvent event) {
    if (!(event instanceof NewChildEvent))
      return;
    final TestProxy parent = event.getSource();
    if (parent == myLastDynamicSuite)
      return;
    if (parent.getParent() != myModel.getRoot())
      return;
    if (myLastDynamicSuite != null && myLastDynamicSuite.getState().isPassed())
      myModel.collapse(myLastDynamicSuite);
    myLastDynamicSuite = parent;
  }

  public void doDispose() {
    myModel = null;
    myLastDynamicSuite = null;
  }
}


text:
using System;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Configuration;
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
using PCSComUtils.Common;

namespace PCSComProduct.Items.DS
{

	public class ITM_DeleteReasonDS
	{
		public ITM_DeleteReasonDS()
		{
		}
		private const string THIS = "PCSComProduct.Items.DS.DS.ITM_DeleteReasonDS";

		//**************************************************************************
		///    <Description>
		///       This method uses to add data to ITM_DeleteReason
		///    </Description>
		///    <Inputs>
		///        ITM_DeleteReasonVO
		///    </Inputs>
		///    <Outputs>
		///       newly inserted primarkey value
		///    </Outputs>
		///    <Returns>
		///       void
		///    </Returns>
		///    <Authors>
		///       HungLa
		///    </Authors>
		///    <History>
		///       Wednesday, January 19, 2005
		///    </History>
		///    <Notes>
		///    </Notes>
		//**************************************************************************

		public void Add(object pobjObjectVO)
		{
			const string METHOD_NAME = THIS + ".Add()";

			OleDbConnection oconPCS =null;
			OleDbCommand ocmdPCS =null;
			try
			{
				ITM_DeleteReasonVO objObject = (ITM_DeleteReasonVO) pobjObjectVO;
				string strSql = String.Empty;
				Utils utils = new Utils();
				oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
				ocmdPCS = new OleDbCommand("", oconPCS);

				strSql=	"INSERT INTO ITM_DeleteReason("
				+ ITM_DeleteReasonTable.CODE_FLD + ","
				+ ITM_DeleteReasonTable.DESCRIPTION_FLD + ")"
				+ "VALUES(?,?)";

				ocmdPCS.Parameters.Add(new OleDbParameter(ITM_DeleteReasonTable.CODE_FLD, OleDbType.VarWChar));
				ocmdPCS.Parameters[ITM_DeleteReasonTable.CODE_FLD].Value = objObject.Code;

				ocmdPCS.Parameters.Add(new OleDbParameter(ITM_DeleteReasonTable.DESCRIPTION_FLD, OleDbType.VarWChar));
				ocmdPCS.Parameters[ITM_DeleteReasonTable.DESCRIPTION_FLD].Value = objObject.Description;

				ocmdPCS.CommandText = strSql;
				ocmdPCS.Connection.Open();
				ocmdPCS.ExecuteNonQuery();

			}
			catch(OleDbException ex)
			{
				if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
				{

					throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
				}
				else
				{
					throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
				}
			}

			catch(InvalidOperationException ex)
			{
				throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
			}
			catch (Exception ex)
			{
				throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
			}

			finally
			{
				if (oconPCS!=null)
				{
					if (oconPCS.State != ConnectionState.Closed)
					{
						oconPCS.Close();
					}
				}
			}
		}

		//**************************************************************************
		///    <Description>
		///       This method uses to delete data from ITM_DeleteReason
		///    </Description>
		///    <Inputs>
		///        ID
		///    </Inputs>
		///    <Outputs>
		///       void
		///    </Outputs>
		///    <Returns>
		///
		///    </Returns>
		///    <Authors>
		///       HungLa
		///    </Authors>
		///    <History>
		///       09-Dec-2004
		///    </History>
		///    <Notes>
		///    </Notes>
		//**************************************************************************

		public void Delete(int pintID)
		{
			const string METHOD_NAME = THIS + ".Delete()";
			string strSql = String.Empty;
			strSql=	"DELETE " + ITM_DeleteReasonTable.TABLE_NAME + " WHERE  " + "DeleteReasonID" + "=" + pintID.ToString();
			OleDbConnection oconPCS=null;
			OleDbCommand ocmdPCS =null;
			try
			{
				Utils utils = new Utils();
				oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
				ocmdPCS = new OleDbCommand(strSql, oconPCS);

				ocmdPCS.Connection.Open();
				ocmdPCS.ExecuteNonQuery();
				ocmdPCS = null;

			}
			catch(OleDbException ex)
			{
				if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
				{

					throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
				}
				else
				{
					throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
				}
			}

			catch (Exception ex)
			{
				throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
			}

			finally
			{
				if (oconPCS!=null)
				{
					if (oconPCS.State != ConnectionState.Closed)
					{
						oconPCS.Close();
					}
				}
			}
		}

		//**************************************************************************
		///    <Description>
		///       This method uses to get data from ITM_DeleteReason
		///    </Description>
		///    <Inputs>
		///        ID
		///    </Inputs>
		///    <Outputs>
		///       ITM_DeleteReasonVO
		///    </Outputs>
		///    <Returns>
		///       ITM_DeleteReasonVO
		///    </Returns>
		///    <Authors>
		///       HungLa
		///    </Authors>
		///    <History>
		///       Wednesday, January 19, 2005
		///    </History>
		///    <Notes>
		///    </Notes>
		//**************************************************************************

		public object GetObjectVO(int pintID)
		{
			const string METHOD_NAME = THIS + ".GetObjectVO()";
			DataSet dstPCS = new DataSet();

			OleDbDataReader odrPCS = null;
			OleDbConnection oconPCS = null;
			OleDbCommand ocmdPCS = null;
			try
			{
				string strSql = String.Empty;
				strSql=	"SELECT "
				+ ITM_DeleteReasonTable.DELETEREASONID_FLD + ","
				+ ITM_DeleteReasonTable.CODE_FLD + ","
				+ ITM_DeleteReasonTable.DESCRIPTION_FLD
				+ " FROM " + ITM_DeleteReasonTable.TABLE_NAME
				+" WHERE " + ITM_DeleteReasonTable.DELETEREASONID_FLD + "=" + pintID;

				Utils utils = new Utils();
				oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
				ocmdPCS = new OleDbCommand(strSql, oconPCS);

				ocmdPCS.Connection.Open();
				odrPCS = ocmdPCS.ExecuteReader();

				ITM_DeleteReasonVO objObject = new ITM_DeleteReasonVO();

				while (odrPCS.Read())
				{
				objObject.DeleteReasonID = int.Parse(odrPCS[ITM_DeleteReasonTable.DELETEREASONID_FLD].ToString().Trim());
				objObject.Code = odrPCS[ITM_DeleteReasonTable.CODE_FLD].ToString().Trim();
				objObject.Description = odrPCS[ITM_DeleteReasonTable.DESCRIPTION_FLD].ToString().Trim();

				}
				return objObject;
			}
			catch(OleDbException ex)
			{
				throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
			}

			catch (Exception ex)
			{
				throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
			}

			finally
			{
				if (oconPCS!=null)
				{
					if (oconPCS.State != ConnectionState.Closed)
					{
						oconPCS.Close();
					}
				}
			}
		}

		//**************************************************************************
		///    <Description>
		///       This method uses to update data to ITM_DeleteReason
		///    </Description>
		///    <Inputs>
		///       ITM_DeleteReasonVO
		///    </Inputs>
		///    <Outputs>
		///
		///    </Outputs>
		///    <Returns>
		///
		///    </Returns>
		///    <Authors>
		///       HungLa
		///    </Authors>
		///    <History>
		///       09-Dec-2004
		///    </History>
		///    <Notes>
		///    </Notes>
		//**************************************************************************

		public void Update(object pobjObjecVO)
		{
			const string METHOD_NAME = THIS + ".Update()";

			ITM_DeleteReasonVO objObject = (ITM_DeleteReasonVO) pobjObjecVO;

			//prepare value for parameters
			OleDbConnection oconPCS =null;
			OleDbCommand ocmdPCS = null;
			try
			{
				string strSql = String.Empty;
				Utils utils = new Utils();
				oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
				ocmdPCS = new OleDbCommand(strSql, oconPCS);
				strSql=	"UPDATE ITM_DeleteReason SET "
				+ ITM_DeleteReasonTable.CODE_FLD + "=   ?" + ","
				+ ITM_DeleteReasonTable.DESCRIPTION_FLD + "=  ?"
				+" WHERE " + ITM_DeleteReasonTable.DELETEREASONID_FLD + "= ?";

				ocmdPCS.Parameters.Add(new OleDbParameter(ITM_DeleteReasonTable.CODE_FLD, OleDbType.VarWChar));
				ocmdPCS.Parameters[ITM_DeleteReasonTable.CODE_FLD].Value = objObject.Code;

				ocmdPCS.Parameters.Add(new OleDbParameter(ITM_DeleteReasonTable.DESCRIPTION_FLD, OleDbType.VarWChar));
				ocmdPCS.Parameters[ITM_DeleteReasonTable.DESCRIPTION_FLD].Value = objObject.Description;

				ocmdPCS.Parameters.Add(new OleDbParameter(ITM_DeleteReasonTable.DELETEREASONID_FLD, OleDbType.Integer));
				ocmdPCS.Parameters[ITM_DeleteReasonTable.DELETEREASONID_FLD].Value = objObject.DeleteReasonID;

				ocmdPCS.CommandText = strSql;
				ocmdPCS.Connection.Open();
				ocmdPCS.ExecuteNonQuery();
			}
			catch(OleDbException ex)
			{
				if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
				{

					throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
				}
				else
				{
					throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
				}
			}

			catch(InvalidOperationException ex)
			{
				throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
			}
			catch (Exception ex)
			{
				throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
			}

			finally
			{
				if (oconPCS!=null)
				{
					if (oconPCS.State != ConnectionState.Closed)
					{
						oconPCS.Close();
					}
				}
			}

		}

		//**************************************************************************
		///    <Description>
		///       This method uses to get all data from ITM_DeleteReason
		///    </Description>
		///    <Inputs>
		///
		///    </Inputs>
		///    <Outputs>
		///       DataSet
		///    </Outputs>
		///    <Returns>
		///       DataSet
		///    </Returns>
		///    <Authors>
		///       HungLa
		///    </Authors>
		///    <History>
		///       Wednesday, January 19, 2005
		///    </History>
		///    <Notes>
		///    </Notes>
		//**************************************************************************

		public DataSet List()
		{
			const string METHOD_NAME = THIS + ".List()";
			DataSet dstPCS = new DataSet();

			OleDbConnection oconPCS =null;
			OleDbCommand ocmdPCS = null;
			try
			{
				string strSql = String.Empty;

				strSql=	"SELECT "
				+ ITM_DeleteReasonTable.DELETEREASONID_FLD + ","
				+ ITM_DeleteReasonTable.CODE_FLD + ","
				+ ITM_DeleteReasonTable.DESCRIPTION_FLD
					+ " FROM " + ITM_DeleteReasonTable.TABLE_NAME;
				Utils utils = new Utils();
				oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
				ocmdPCS = new OleDbCommand(strSql, oconPCS);
				ocmdPCS.Connection.Open();

				OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
				odadPCS.Fill(dstPCS,ITM_DeleteReasonTable.TABLE_NAME);

				return dstPCS;
			}
			catch(OleDbException ex)
			{
   				throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
			}
			catch (Exception ex)
			{
				throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
			}

			finally
			{
				if (oconPCS!=null)
				{
					if (oconPCS.State != ConnectionState.Closed)
					{
						oconPCS.Close();
					}
				}
			}

		}

		//**************************************************************************
		///    <Description>
		///       This method uses to update a DataSet
		///    </Description>
		///    <Inputs>
		///        DataSet
		///    </Inputs>
		///    <Outputs>
		///
		///    </Outputs>
		///    <Returns>
		///
		///    </Returns>
		///    <Authors>
		///       HungLa
		///    </Authors>
		///    <History>
		///       Wednesday, January 19, 2005
		///    </History>
		///    <Notes>
		///    </Notes>
		//**************************************************************************

		public void UpdateDataSet(DataSet pData)
		{
			const string METHOD_NAME = THIS + ".UpdateDataSet()";
			string strSql;
			OleDbConnection oconPCS =null;
			OleDbCommandBuilder odcbPCS ;
			OleDbDataAdapter odadPCS = new OleDbDataAdapter();

			try
			{
				strSql=	"SELECT "
				+ ITM_DeleteReasonTable.DELETEREASONID_FLD + ","
				+ ITM_DeleteReasonTable.CODE_FLD + ","
				+ ITM_DeleteReasonTable.DESCRIPTION_FLD
		+ "  FROM " + ITM_DeleteReasonTable.TABLE_NAME;

				Utils utils = new Utils();
				oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
				odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
				odcbPCS = new OleDbCommandBuilder(odadPCS);
				pData.EnforceConstraints = false;
				odadPCS.Update(pData,ITM_DeleteReasonTable.TABLE_NAME);

			}
			catch(OleDbException ex)
			{
				if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
				{

					throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
				}
				else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
				{

					throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
				}

				else
				{
					throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
				}
			}

			catch(InvalidOperationException ex)
			{
				throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
			}
			catch (Exception ex)
			{
				throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
			}

			finally
			{
				if (oconPCS!=null)
				{
					if (oconPCS.State != ConnectionState.Closed)
					{
						oconPCS.Close();
					}
				}
			}

		}
	}
}


text:
#import "KGPaint_ramp.h"
#import "KGShading.h"
#import "O2ColorSpace.h"
#import "KGFunction.h"

@implementation KGPaint_ramp

static inline void GrayAToRGBA(float *input,float *output){
   output[0]=input[0];
   output[1]=input[0];
   output[2]=input[0];
   output[3]=input[1];
}

static inline void RGBAToRGBA(float *input,float *output){
   output[0]=input[0];
   output[1]=input[1];
   output[2]=input[2];
   output[3]=input[3];
}

static inline void CMYKAToRGBA(float *input,float *output){
   float white=1-input[3];

   output[0]=(input[0]>white)?0:white-input[0];
   output[1]=(input[1]>white)?0:white-input[1];
   output[2]=(input[2]>white)?0:white-input[2];
   output[3]=input[4];
}

-initWithShading:(KGShading *)shading deviceTransform:(CGAffineTransform)deviceTransform numberOfSamples:(int)numberOfSamples {
   [super init];

   m_surfaceToPaintMatrix=CGAffineTransformInvert(deviceTransform);

   _startPoint=[shading startPoint];
   _endPoint=[shading endPoint];
   _extendStart=[shading extendStart];
   _extendEnd=[shading extendEnd];

   KGFunction      *function=[shading function];
   O2ColorSpace    *colorSpace=[shading colorSpace];
   O2ColorSpaceType colorSpaceType=[colorSpace type];
   float            output[[colorSpace numberOfComponents]+1];
   void           (*outputToRGBA)(float *,float *);
   float            rgba[4];

   switch(colorSpaceType){

    case O2ColorSpaceDeviceGray:
     outputToRGBA=GrayAToRGBA;
     break;

    case O2ColorSpaceDeviceRGB:
    case O2ColorSpacePlatformRGB:
     outputToRGBA=RGBAToRGBA;
     break;

    case O2ColorSpaceDeviceCMYK:
     outputToRGBA=CMYKAToRGBA;
     break;

    default:
     NSLog(@"shading can't deal with colorspace %@",colorSpace);
     return nil;
   }

   _numberOfColorStops=numberOfSamples;
   _colorStops=NSZoneMalloc(NULL,_numberOfColorStops*sizeof(GradientStop));
   int i;
   for(i=0;i<_numberOfColorStops;i++){
    _colorStops[i].offset=(CGFloat)i/(CGFloat)(_numberOfColorStops-1);

// FIXME: This assumes range=0..1, we need to map this to the functions range

    [function evaluateInput:_colorStops[i].offset output:output];
    outputToRGBA(output,rgba);
    _colorStops[i].color=KGRGBAffffPremultiply(KGRGBAffffInit(rgba[0],rgba[1],rgba[2],rgba[3]));
   }

   return self;
}

-(void)dealloc {
   if(_colorStops!=NULL)
    NSZoneFree(NULL,_colorStops);

   [super dealloc];
}

/*-------------------------------------------------------------------*//*!
* \brief	Returns the average color within an offset range in the color ramp.
* \param
* \return
* \note
*//*-------------------------------------------------------------------*/

static KGRGBAffff readStopColor(GradientStop *colorRampStops,int colorRampStopsCount, int i)
{
	RI_ASSERT(i >= 0 && i < colorRampStopsCount);
	return  colorRampStops[i].color;
}

KGRGBAffff KGPaintIntegrateColorRamp(KGPaint_ramp *self,CGFloat gmin, CGFloat gmax) {
	RI_ASSERT(gmin <= gmax);
	RI_ASSERT(gmin >= 0.0f && gmin <= 1.0f);
	RI_ASSERT(gmax >= 0.0f && gmax <= 1.0f);
	RI_ASSERT(self->_numberOfColorStops >= 2);	//there are at least two stops

	KGRGBAffff c=KGRGBAffffInit(0,0,0,0);
	if(gmin == 1.0f || gmax == 0.0f)
		return c;

	int i=floor(gmin*(self->_numberOfColorStops-1));
	for(;i<self->_numberOfColorStops-1;i++)
	{
		if(gmin >= self->_colorStops[i].offset && gmin < self->_colorStops[i+1].offset)
		{
			CGFloat s = self->_colorStops[i].offset;
			CGFloat e = self->_colorStops[i+1].offset;
			RI_ASSERT(s < e);
			CGFloat g = (gmin - s) / (e - s);

			KGRGBAffff sc = readStopColor(self->_colorStops,self->_numberOfColorStops, i);
			KGRGBAffff ec = readStopColor(self->_colorStops,self->_numberOfColorStops, i+1);
			KGRGBAffff rc = KGRGBAffffAdd(KGRGBAffffMultiplyByFloat(sc, (1.0f-g)),KGRGBAffffMultiplyByFloat(ec , g));

			//subtract the average color from the start of the stop to gmin
			c=KGRGBAffffSubtract(c,KGRGBAffffMultiplyByFloat(KGRGBAffffAdd(sc,rc) , 0.5f*(gmin - s)));
			break;
		}
	}

	for(;i<self->_numberOfColorStops-1;i++)
	{
		CGFloat s = self->_colorStops[i].offset;
		CGFloat e = self->_colorStops[i+1].offset;
		RI_ASSERT(s <= e);

		KGRGBAffff sc = readStopColor(self->_colorStops,self->_numberOfColorStops, i);
		KGRGBAffff ec = readStopColor(self->_colorStops,self->_numberOfColorStops, i+1);

		//average of the stop
		c=KGRGBAffffAdd(c , KGRGBAffffMultiplyByFloat(KGRGBAffffAdd(sc , ec), 0.5f*(e-s)));

		if(gmax >= self->_colorStops[i].offset && gmax < self->_colorStops[i+1].offset)
		{
			CGFloat g = (gmax - s) / (e - s);
			KGRGBAffff rc = KGRGBAffffAdd(KGRGBAffffMultiplyByFloat(sc , (1.0f-g)),KGRGBAffffMultiplyByFloat( ec , g));

			//subtract the average color from gmax to the end of the stop
			c=KGRGBAffffSubtract(c,KGRGBAffffMultiplyByFloat(KGRGBAffffAdd(rc , ec) , 0.5f*(e - gmax)));
			break;
		}
	}
	return c;
}

/*-------------------------------------------------------------------*//*!
* \brief	Maps a gradient function value to a color.
* \param
* \return
* \note
*//*-------------------------------------------------------------------*/

KGRGBAffff KGPaintColorRamp(KGPaint_ramp *self,CGFloat gradient, CGFloat rho)  {
	RI_ASSERT(self);
	RI_ASSERT(rho >= 0.0f);

	KGRGBAffff c=KGRGBAffffInit(0,0,0,0);

	if(rho == 0.0f)
	{	//filter size is zero or gradient is degenerate

			gradient = RI_CLAMP(gradient, 0.0f, 1.0f);

        int i;
		for(i=0;i<self->_numberOfColorStops-1;i++)
		{
			if(gradient >= self->_colorStops[i].offset && gradient < self->_colorStops[i+1].offset)
			{
				CGFloat s = self->_colorStops[i].offset;
				CGFloat e = self->_colorStops[i+1].offset;
				RI_ASSERT(s < e);
				CGFloat g = RI_CLAMP((gradient - s) / (e - s), 0.0f, 1.0f);	//clamp needed due to numerical inaccuracies

				KGRGBAffff sc = readStopColor(self->_colorStops,self->_numberOfColorStops, i);
				KGRGBAffff ec = readStopColor(self->_colorStops,self->_numberOfColorStops, i+1);
				return KGRGBAffffAdd(KGRGBAffffMultiplyByFloat(sc , (1.0f-g)) , KGRGBAffffMultiplyByFloat(ec , g));	//return interpolated value
			}
		}
		return readStopColor(self->_colorStops,self->_numberOfColorStops, self->_numberOfColorStops-1);
	}

	CGFloat gmin = gradient - rho*0.5f;			//filter starting from the gradient point (if starts earlier, radial gradient center will be an average of the first and the last stop, which doesn't look good)
	CGFloat gmax = gradient + rho*0.5f;

		if(gmin < 0.0f)
			c=KGRGBAffffAdd(c,KGRGBAffffMultiplyByFloat(readStopColor(self->_colorStops,self->_numberOfColorStops, 0), (RI_MIN(gmax, 0.0f) - gmin)));
		if(gmax > 1.0f)
			c=KGRGBAffffAdd(c,KGRGBAffffMultiplyByFloat(readStopColor(self->_colorStops,self->_numberOfColorStops, self->_numberOfColorStops-1) , (gmax - RI_MAX(gmin, 1.0f))));
		gmin = RI_CLAMP(gmin, 0.0f, 1.0f);
		gmax = RI_CLAMP(gmax, 0.0f, 1.0f);
		c=KGRGBAffffAdd(c, KGPaintIntegrateColorRamp(self,gmin, gmax));
		c=KGRGBAffffMultiplyByFloat(c , 1.0f/rho);
		c=KGRGBAffffClamp(c);	//clamp needed due to numerical inaccuracies
		return c;

}

@end


text:
NAMESPACE_UPP

#define LLOG(x)  // LOG(x)

TopWindowFrame::TopWindowFrame()
{
	close.SetImage(CoreGlImg::close());
	close.EdgeStyle();
	Add(close);
	maximize.SetImage(CoreGlImg::maximize());
	maximize.EdgeStyle();
	Add(maximize);
	maximize <<= THISBACK(ToggleMaximize);
	maximized = false;
	sizeable = false;
	holding = false;
}

void TopWindowFrame::SyncRect()
{
	if(maximized) {
		Size sz = screenRect.GetSize();
		if(GetRect().GetSize() != sz)
			SetRect(sz);
	}
}

void TopWindowFrame::Maximize()
{
	if(!maximized && maximize.IsShown()) {
		maximized = true;
		overlapped = GetRect();
		SetRect(screenRect);
		maximize.SetImage(CoreGlImg::overlap());
	}
}

void TopWindowFrame::Overlap()
{
	if(maximized && maximize.IsShown()) {
		maximized = false;
		SetRect(overlapped);
		maximize.SetImage(CoreGlImg::maximize());
	}
}

void TopWindowFrame::ToggleMaximize()
{
	if(maximized)
		Overlap();
	else
		Maximize();
}

Rect TopWindowFrame::Margins() const
{
	return maximized ? Rect(0, 0, 0, 0) : ChMargins(CoreGlImg::border());
}

void TopWindowFrame::Paint(Draw& w)
{
	Size sz = GetSize();
	Rect m = Margins();
	int c = GetStdFontCy() + 4;
	ChPaintEdge(w, sz, CoreGlImg::border());
	Image img = window->IsForeground() ? CoreGlImg::title() : CoreGlImg::bgtitle();
	resources.Bind(img, Resources::FORCE_FILTERING | Resources::LINEAR_FILTERING);
	ChPaint(w, m.left, m.top, sz.cx - m.left - m.right, GetStdFontCy() + 4, img);
	int tx = m.left + 2;
	int tcx = sz.cx - m.left - m.right - 4 - c * (close.IsShown() + maximize.IsShown());
	if(!IsNull(icon)) {
		Image h = icon;
		if(h.GetWidth() > c || h.GetHeight() > c)
			h = Rescale(h, GetFitSize(h.GetSize(), Size(c)));
		w.DrawImage(tx, m.top + 2, h);
		tx += c;
		tcx -= c;
	}
	DrawTextEllipsis(w, tx, m.top + 2, tcx, title, "..", StdFont(), SColorHighlightText());
}

void TopWindowFrame::Layout()
{
	Size sz = GetSize();
	Rect m = Margins();
	int c = GetStdFontCy() + 4;
	int x = sz.cx - m.right;
	if(close.IsShown())
		close.SetRect(x -= c, m.top, c, c);
	if(maximize.IsShown())
		maximize.SetRect(x -= c, m.top, c, c);
}

Rect TopWindowFrame::GetClient() const
{
	Rect r = GetRect();
	Rect m = Margins();
	r.left += m.left;
	r.right -= m.right;
	r.top += m.top;
	r.bottom -= m.bottom;
	r.top += GetStdFontCy() + 4;
	return r;
}

Rect TopWindowFrame::ComputeClient(Rect r)
{
	Rect m = Margins();
	r.left -= m.left;
	r.right += m.right;
	r.top -= m.top;
	r.bottom += m.bottom;
	r.top -= GetStdFontCy() + 4;
	return r;
}

void TopWindowFrame::SetClient(Rect r)
{
	SetRect(ComputeClient(r));
}

Point TopWindowFrame::GetDragMode(Point p)
{
	Size sz = GetSize();
	Rect m = ChMargins(CoreGlImg::border());
	Point dir;
	dir.y = p.y < m.top ? -1 : p.y > sz.cy - m.top ? 1 : 0;
	dir.x = p.x < m.left ? -1 : p.x > sz.cx - m.right ? 1 : 0;
	return dir;
}

void TopWindowFrame::StartDrag()
{
	if(maximized)
		return;
	if(!sizeable && (dir.x || dir.y))
		return;
	SetCapture();
	startrect = GetRect();
	startpos = GetMousePos();
}

void TopWindowFrame::GripResize()
{
	dir = Point(1, 1);
	StartDrag();
}

void TopWindowFrame::LeftDown(Point p, dword keyflags)
{
	dir = GetDragMode(p);
	StartDrag();
}

void TopWindowFrame::LeftDouble(Point p, dword keyflags)
{
	ToggleMaximize();
	IgnoreMouseUp();
}

void TopWindowFrame::LeftUp(Point p, dword keyflags)
{
	ReleaseCapture();
}

void TopWindowFrame::MouseMove(Point, dword)
{
	if(!HasCapture())
		return;
	Size msz = ComputeClient(minsize).GetSize();
	Point p = GetMousePos() - startpos;
	Rect r = startrect;
	if(dir.x == -1)
		r.left = min(r.left + p.x, startrect.right - msz.cx);
	if(dir.x == 1)
		r.right = max(r.right + p.x, startrect.left + msz.cx);
	if(dir.y == -1)
		r.top = min(r.top + p.y, startrect.bottom - msz.cy);
	if(dir.y == 1)
		r.bottom = max(r.bottom + p.y, startrect.top + msz.cy);
	if(dir.y == 0 && dir.x == 0)
		r.Offset(p);
	SetRect(r);
}

Image TopWindowFrame::GetDragImage(Point dir)
{
	static Image (*im[9])() = {
		Image::SizeTopLeft, Image::SizeLeft, Image::SizeBottomLeft,
		Image::SizeTop, Image::Arrow, Image::SizeBottom,
		Image::SizeTopRight, Image::SizeRight, Image::SizeBottomRight,
	};
	return (*im[(dir.x + 1) * 3 + (dir.y + 1)])();
}

Image TopWindowFrame::CursorImage(Point p, dword)
{
	if(!sizeable)
		return Image::Arrow();
	return GetDragImage(HasCapture() ? dir : GetDragMode(p));
}

END_UPP_NAMESPACE

#endif


text:
WebGL
=====

Some WebGL tests with the Three.js framework


text:
package router

import (
	"errors"
	"sync"
)

var routes map[string]Route
var routesLock sync.RWMutex

func init() {
	routesLock.Lock()
	defer routesLock.Unlock()
	routes = make(map[string]Route)
}

func RegisterRoute(key string, val Route) {
	routesLock.Lock()
	defer routesLock.Unlock()
	routes[key] = val
}

func CallRoute(key string, p *Payload) error {
	routesLock.RLock()
	defer routesLock.RUnlock()
	r, ok := routes[key]

	if !ok {
		return errors.New("Can't find route")
	}

	return r(p)
}


text:
require 'serverspec'
require 'tempfile'

set :backend, :exec
set :path, '~/.homebrew/bin:/usr/local/go/bin/:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:$PATH'
set :request_pty, true


text:
- just two contrasting shapes
colors contrast

- same shape overwriting self
thick then thin


text:
package com.tcl.idm.model;

/**
 * API´íÎóÂ붨Òå
 * @author TCL
 *
 */
public enum CustomErrorCode
{
	@Error(msg = "The request has been successfully processed.")
	Success,

	@Error(msg = "A required parameter for the specified action is not supplied.")
	MissingParameter,

	@Error(msg = "An invalid or out-of-range value was supplied for the input parameter.")
	InvalidParameter,

	@Error(msg = "The request signature we calculated does not match the signature you provided.")
	SignatureDoesNotMatch,

	@Error(msg = "The request was rejected because it attempted to create a resource that already exists.")
	EntityAlreadyExists,

	@Error(msg = "The request was rejected because it referenced an entity that does not exist.")
	NoSuchEntity,

	@Error(msg = "The request was rejected because it attempted to create resources beyond the current account limits.")
	LimitExceeded,

	@Error(msg = "The request was rejected because the policy document was malformed.")
	MalformedPolicyDocument,

	@Error(msg = "The request access is not authorized.")
	Unauthorized,

	@Error(msg = "The provided password does not match the real password.")
	PasswordNotMatch,

	@Error(msg = "The request access key is not active.")
	AccessKeyInactive,

	@Error(msg = "Access key was already active.")
	AccessKeyAlreadyActive,

	@Error(msg = "Access key was already inactive.")
	AccessKeyAlreadyInactive,

	@Error(msg = "The provided credentials could not be validated.")
	AuthFailure,

	@Error(msg = "The request processing has failed because of an unknown error, exception or failure.")
	InternalError,

	@Error(msg = "The request is expired.")
	RequestExpired,

	@Error(msg = "Unknown error.")
	UnknownError;

	/**
	 * ·µ»Ø´íÎóÂë
	 */
	public String getCode()
	{
		return name();
	}

	/**
	 * ·µ»Ø´íÎóÐÅÏ¢
	 */
	public String getMessage()
	{
		Error error = null;
		try
		{
			error = this.getClass().getField(getCode()).getAnnotation(Error.class);
		}
		catch (Exception e)
		{
			return null;
		}
		return error.msg();
	}
}


text:
using System;
using System.Linq;
using Common.Logging;
using Hepsi.CommandProcessor.Extensions;
using Hepsi.CommandProcessor.Handlers;
using Hepsi.CommandProcessor.Messaging;
using Polly;

namespace Hepsi.CommandProcessor
{
    ///
    /// Class CommandProcessor.
    /// Implements both the Command Dispatcher
    /// and Command Processor Design Patterns
    ///
    public class CommandProcessor : IAmACommandProcessor
    {
        readonly IAmAMessageMapperRegistry mapperRegistry;
        readonly IAmASubscriberRegistry subscriberRegistry;
        readonly IAmAHandlerFactory handlerFactory;
        readonly IAmARequestContextFactory requestContextFactory;
        readonly IAmAPolicyRegistry policyRegistry;
        readonly ILog logger;
        readonly IAmAMessageStore<Message> messageStore;
        readonly IAmAClientRequestHandler messagingGateway;
        ///
        /// Use this as an identifier for your <see cref="Policy"/> that determines for how long to break the circuit when communication with the Work Queue fails.
        /// Register that policy with your <see cref="IAmAPolicyRegistry"/> such as <see cref="PolicyRegistry"/>
        /// You can use this an identifier for you own policies, if your generic policy is the same as your Work Queue policy.
        ///
        public const string CIRCUITBREAKER = "Hepsi.CommandProcessor.CircuitBreaker";
        ///
        /// Use this as an identifier for your <see cref="Policy"/> that determines the retry strategy when communication with the Work Queue fails.
        /// Register that policy with your <see cref="IAmAPolicyRegistry"/> such as <see cref="PolicyRegistry"/>
        /// You can use this an identifier for you own policies, if your generic policy is the same as your Work Queue policy.
        ///
        public const string RETRYPOLICY = "Hepsi.CommandProcessor.RetryPolicy";

        ///
        /// Initializes a new instance of the <see cref="CommandProcessor"/> class.
        /// Use this constructor when no task queue support is required
        ///
        /// <param name="subscriberRegistry">The subscriber registry.</param>
        /// <param name="handlerFactory">The handler factory.</param>
        /// <param name="requestContextFactory">The request context factory.</param>
        /// <param name="policyRegistry">The policy registry.</param>
        /// <param name="logger">The logger.</param>
        public CommandProcessor(
            IAmASubscriberRegistry subscriberRegistry,
            IAmAHandlerFactory handlerFactory,
            IAmARequestContextFactory requestContextFactory,
            IAmAPolicyRegistry policyRegistry,
            ILog logger)
        {
            this.subscriberRegistry = subscriberRegistry;
            this.handlerFactory = handlerFactory;
            this.requestContextFactory = requestContextFactory;
            this.policyRegistry = policyRegistry;
            this.logger = logger;
        }

        ///
        /// Initializes a new instance of the <see cref="CommandProcessor"/> class.
        /// Use this constructor when only task queue support is required
        ///
        /// <param name="requestContextFactory">The request context factory.</param>
        /// <param name="policyRegistry">The policy registry.</param>
        /// <param name="mapperRegistry">The mapper registry.</param>
        /// <param name="messageStore">The message store.</param>
        /// <param name="messagingGateway">The messaging gateway.</param>
        /// <param name="logger">The logger.</param>
        public CommandProcessor(
            IAmARequestContextFactory requestContextFactory,
            IAmAPolicyRegistry policyRegistry,
            IAmAMessageMapperRegistry mapperRegistry,
            IAmAMessageStore<Message> messageStore,
            IAmAClientRequestHandler messagingGateway,
            ILog logger)
        {
            this.requestContextFactory = requestContextFactory;
            this.policyRegistry = policyRegistry;
            this.logger = logger;
            this.mapperRegistry = mapperRegistry;
            this.messageStore = messageStore;
            this.messagingGateway = messagingGateway;
        }

        ///
        /// Initializes a new instance of the <see cref="CommandProcessor"/> class.
        /// Use this constructor when both task queue and command processor support is required
        ///
        /// <param name="subscriberRegistry">The subscriber registry.</param>
        /// <param name="handlerFactory">The handler factory.</param>
        /// <param name="requestContextFactory">The request context factory.</param>
        /// <param name="policyRegistry">The policy registry.</param>
        /// <param name="mapperRegistry">The mapper registry.</param>
        /// <param name="messageStore">The message store.</param>
        /// <param name="messagingGateway">The messaging gateway.</param>
        /// <param name="logger">The logger.</param>
        public CommandProcessor(
            IAmASubscriberRegistry subscriberRegistry,
            IAmAHandlerFactory handlerFactory,
            IAmARequestContextFactory requestContextFactory,
            IAmAPolicyRegistry policyRegistry,
            IAmAMessageMapperRegistry mapperRegistry,
            IAmAMessageStore<Message> messageStore,
            IAmAClientRequestHandler messagingGateway,
            ILog logger)
            : this(subscriberRegistry, handlerFactory, requestContextFactory, policyRegistry, logger)
        {
            this.mapperRegistry = mapperRegistry;
            this.messageStore = messageStore;
            this.messagingGateway = messagingGateway;
        }

        ///
        /// Sends the specified command. We expect only one handler. The command is handled synchronously.
        ///
        /// <typeparam name="T"></typeparam>
        /// <param name="command">The command.</param>
        /// <exception cref="System.ArgumentException">
        /// </exception>
        public void Send<T>(T command) where T : class, IRequest
        {
            using (var builder = new PipelineBuilder<T>(subscriberRegistry, handlerFactory, logger))
            {
                var requestContext = requestContextFactory.Create();
                requestContext.Policies = policyRegistry;

                logger.Info(m => m("Building send pipeline for command: {0}", command.Id));

                var handlerChain = builder.Build(requestContext);

                var handlerCount = handlerChain.Count();

                logger.Info(m => m("Found {0} pipelines for command: {1} {2}", handlerCount, typeof(T), command.Id));

                if (handlerCount > 1)
                {
                    throw new ArgumentException(string.Format("More than one handler was found for the typeof command {0} - a command should only have one handler.", typeof(T)));
                }

                if (handlerCount == 0)
                {
                    throw new ArgumentException(string.Format("No command handler was found for the typeof command {0} - a command should have only one handler.", typeof(T)));
                }

                handlerChain.First().Handle(command);
            }
        }

        ///
        /// Publishes the specified event. We expect zero or more handlers. The events are handled synchronously, in turn
        ///
        /// <typeparam name="T"></typeparam>
        /// <param name="event">The event.</param>
        public void Publish<T>(T @event) where T : class, IRequest
        {
            using (var builder = new PipelineBuilder<T>(subscriberRegistry, handlerFactory, logger))
            {
                var requestContext = requestContextFactory.Create();
                requestContext.Policies = policyRegistry;

                logger.Info(m => m("Building send pipeline for command: {0}", @event.Id));
                var handlerChain = builder.Build(requestContext);

                var handlerCount = handlerChain.Count();

                logger.Info(m => m("Found {0} pipelines for command: {0}", handlerCount, @event.Id));

                handlerChain.Each(chain => chain.Handle(@event));
            }
        }

        ///
        /// Posts the specified request. The message is placed on a task queue and into a message store for reposting in the event of failure.
        /// You will need to configure a service that reads from the task queue to process the message
        /// Paramore.Brighter.ServiceActivator provides an endpoint for use in a windows service that reads from a queue
        /// and then Sends or Publishes the message to a <see cref="CommandProcessor"/> within that service. The decision to <see cref="Send{T}"/> or <see cref="Publish{T}"/> is based on the
        /// mapper. Your mapper can map to a <see cref="Message"/> with either a <see cref="T:MessageType.MT_COMMAND"/> , which results in a <see cref="Send{T}(T)"/> or a
        /// <see cref="T:MessageType.MT_EVENT"/> which results in a <see cref="Publish{T}(T)"/>
        ///
        /// <typeparam name="T"></typeparam>
        /// <param name="request">The request.</param>
        /// <exception cref="System.ArgumentOutOfRangeException"></exception>
        public void Post<T>(T request) where T : class, IRequest
        {
            logger.Info(m => m("Decoupled invocation of request: {0}", request.Id));

            var messageMapper = mapperRegistry.Get<T>();

            if (messageMapper == null)
            {
                throw new ArgumentOutOfRangeException(string.Format("No message mapper registered for messages of type: {0}", typeof(T)));
            }

            var message = messageMapper.MapToMessage(request);
            /*
             * NOTE: Don't rewrite with await, compiles but Policy does not call await on the lambda so becomes fire and forget,
             * see http://blogs.msdn.com/b/pfxteam/archive/2012/02/08/10265476.aspx
            */
            RetryAndBreakCircuit(() =>
            {
                messageStore.Add(message).Wait();
                messagingGateway.Send(message).Wait();
            });
        }

        ///
        /// Reposts the specified message identifier. It retrieves a message previously posted via Post, from the Message Store, and publishes it
        /// onto the Work Queue again.
        ///
        /// <param name="messageId">The message identifier.</param>
        public void Repost(Guid messageId)
        {
            var requestedMessageid = messageId; //avoid closure on this
            logger.Info(m => m("Resend of request: {0}", requestedMessageid));

            /*
             * NOTE: Don't rewrite with await, compiles but Policy does not call await on the lambda so becomes fire and forget,
             * see http://blogs.msdn.com/b/pfxteam/archive/2012/02/08/10265476.aspx
            */
            RetryAndBreakCircuit(() =>
            {
                var task = messageStore.Get(messageId);
                task.Wait();
                var message = task.Result;
                messagingGateway.Send(message);
            });
        }

        void RetryAndBreakCircuit(Action send)
        {
            CheckCircuit(() => Retry(send));
        }

        void CheckCircuit(Action send)
        {
            policyRegistry.Get(CIRCUITBREAKER).Execute(send);
        }

        void Retry(Action send)
        {
            policyRegistry.Get(RETRYPOLICY).Execute(send);
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace Baethon\Phln;

const last = 'Baethon\\Phln\\last';

/**
 * @param mixed $collection
 *
 * @return mixed
 *
 * @throws \InvalidArgumentException
 */
function last($collection)
{
    if (is_array($collection)) {
        /* @var array<mixed> $collection */
        return ([] === $collection)
            ? null
            : array_slice($collection, -1, 1)[0];
    }

    if (is_stringable($collection)) {
        /* @var string $collection */
        return substr($collection, -1, 1);
    }

    throw new \InvalidArgumentException('Unsupported collection type');
}


text:
import * as $ from 'jquery';
import { clearStyles } from '../util';
import { Article } from '..';

export function parse(): Article {
    const title = $('#vmNewsTitle').text();

    const article = $('#container > div.w_inner > div.w_article > div.w_article_cont > div.w_article_left > div.article_cont_area')[0].cloneNode(true);
    $('.lazy', article).each(function (_, anchor) {
        anchor.classList.remove("lazy");
        anchor.setAttribute('src', anchor.getAttribute('data-original')!);
    });
    const content = clearStyles(article).innerHTML;

    const [
        ,
        created = null,
        lastModified = null,
    ] = [...$('#container > div.w_inner > div.w_article > div.w_article_title > div.info_area > .date > meta')]
        .map(element => (element instanceof HTMLElement) ? element.getAttribute('content') : null)
        .map(dateString => dateString ? new Date(dateString) : null);
    const timestamp = {
        created,
        lastModified,
    };

    const name = $('#container > div.w_inner > div.w_article > div.w_article_title > div.info_area > p > span:nth-child(1)').text();
    const mail = $('#container > div.w_inner > div.w_article > div.w_article_title > div.info_area > p > a:nth-child(5)').text();
    const reporters = (name || mail) ? [{ name, mail }] : [];

    return {
        title,
        content,
        timestamp,
        reporters,
    };
}


text:
package catsbroker

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"testing"
)

type ResponseTest func(t *testing.T, r *httptest.ResponseRecorder)

func All(tests ...ResponseTest) ResponseTest {
	return func(t *testing.T, r *httptest.ResponseRecorder) {
		t.Helper()

		for _, test := range tests {
			test(t, r)
		}
	}
}

func Status(statusCode int) ResponseTest {
	return func(t *testing.T, r *httptest.ResponseRecorder) {
		t.Helper()

		if r.Code != statusCode {
			t.Error("wanted status code:", statusCode, "got:", r.Code)
		}
	}
}

var StatusOK = Status(http.StatusOK)
var StatusNotFound = Status(http.StatusNotFound)

func JSONBody() ResponseTest {
	return func(t *testing.T, r *httptest.ResponseRecorder) {
		t.Helper()

		if !json.Valid(r.Body.Bytes()) {
			t.Error("body wasn't valid JSON")
		}
	}
}

func BodyContains(needle string) ResponseTest {
	return func(t *testing.T, r *httptest.ResponseRecorder) {
		t.Helper()

		haystack := r.Body.Bytes()
		if !bytes.Contains(haystack, []byte(needle)) {
			t.Errorf("body didn't contain %q", needle)
		}
	}
}

type HTTPTest struct {
	// Input
	Method string
	Target string
	Body   []byte

	Want ResponseTest
}

type HTTPTestSuite []HTTPTest

func (ht HTTPTestSuite) Test(t *testing.T) {
	t.Helper()
	// Don't introduce Parallel() at this level because cases should be run in
	// order.

	broker := NewBroker()

	for i, tc := range ht {
		name := fmt.Sprintf("%d %s %s", i, tc.Method, tc.Target)
		t.Run(name, func(t *testing.T) {
			var bodyReader io.Reader
			if tc.Body != nil {
				bodyReader = bytes.NewBuffer(tc.Body)
			}

			req := httptest.NewRequest(tc.Method, tc.Target, bodyReader)
			w := httptest.NewRecorder()
			broker.ServeHTTP(w, req)

			t.Logf("Response code: %d", w.Code)
			t.Logf("Body: %q", w.Body.String())

			tc.Want(t, w)
		})
	}
}

func Test_health(t *testing.T) {
	t.Parallel()

	cases := map[string]HTTPTestSuite{
		"get health": {
			{
				Method: http.MethodGet,
				Target: "/",
				Want:   All(StatusOK),
			},
		},
	}

	for tn, tc := range cases {
		t.Run(tn, tc.Test)
	}
}

func Test_catalog(t *testing.T) {
	t.Parallel()

	cases := map[string]HTTPTestSuite{
		"get catalog": {
			{
				Method: http.MethodGet,
				Target: "/v2/catalog",
				Want:   All(JSONBody(), StatusOK),
			},
		},
	}

	for tn, tc := range cases {
		t.Run(tn, tc.Test)
	}
}

func Test_serviceInstances(t *testing.T) {
	t.Parallel()

	cases := map[string]HTTPTestSuite{
		"creating normal plan": {
			{
				Method: http.MethodPut,
				Target: "/v2/service_instances/test-id",
				Body:   []byte(`{}`),
				Want:   All(JSONBody(), StatusOK),
			},
		},
		"creating normal plan with accepts_incomplete": {
			{
				Method: http.MethodPut,
				Target: "/v2/service_instances/test-id?accepts_incomplete=true",
				Body:   []byte(`{}`),
				Want:   All(JSONBody(), StatusOK),
			},
		},
		"creating async only plan without accepts_incomplete": {
			{
				Method: http.MethodPut,
				Target: "/v2/service_instances/test-id",
				Body:   []byte(`{"plan_id":"fake-async-only-plan-guid"}`),
				Want:   All(Status(http.StatusUnprocessableEntity)),
			},
		},
		"creating async only plan with accepts_incomplete": {
			{
				Method: http.MethodPut,
				Target: "/v2/service_instances/test-id?accepts_incomplete=true",
				Body:   []byte(`{"plan_id":"fake-async-only-plan-guid"}`),
				Want:   All(Status(http.StatusAccepted)),
			},
		},
		"updating async only plan starts operation": {
			{
				Method: http.MethodPut,
				Target: "/v2/service_instances/test-id?accepts_incomplete=true",
				Body:   []byte(`{"plan_id":"fake-async-only-plan-guid"}`),
				Want:   All(),
			},
			{
				Method: http.MethodPatch,
				Target: "/v2/service_instances/test-id?accepts_incomplete=true",
				Body:   []byte(`{"plan_id":"fake-async-only-plan-guid"}`),
				Want:   All(Status(http.StatusAccepted)),
			},
		},
		"updating async only plan fails without accepts_incomplete": {
			{
				Method: http.MethodPut,
				Target: "/v2/service_instances/test-id?accepts_incomplete=true",
				Body:   []byte(`{"plan_id":"fake-async-only-plan-guid"}`),
				Want:   All(),
			},
			{
				Method: http.MethodPatch,
				Target: "/v2/service_instances/test-id",
				Body:   []byte(`{"plan_id":"fake-async-only-plan-guid"}`),
				Want:   All(Status(http.StatusUnprocessableEntity)),
			},
		},
		"updating async to synchronous plan returns operation": {
			{
				Method: http.MethodPut,
				Target: "/v2/service_instances/test-id?accepts_incomplete=true",
				Body:   []byte(`{"plan_id":"fake-async-only-plan-guid"}`),
				Want:   All(),
			},
			{
				Method: http.MethodPatch,
				Target: "/v2/service_instances/test-id?accepts_incomplete=true",
				Body:   []byte(`{"plan_id":"fake-plan-guid"}`),
				Want:   Status(http.StatusAccepted),
			},
		},
		"updating missing instance 404s": {
			{
				Method: http.MethodPatch,
				Target: "/v2/service_instances/missing?accepts_incomplete=true",
				Body:   []byte(`{"plan_id":"fake-plan-guid"}`),
				Want:   All(StatusNotFound),
			},
		},
		"deleting async plan starts operation": {
			{
				Method: http.MethodPut,
				Target: "/v2/service_instances/test-id",
				Body:   []byte(`{"plan_id":"fake-async-plan-guid"}`),
				Want:   All(),
			},
			{
				Method: http.MethodDelete,
				Target: "/v2/service_instances/test-id",
				Want:   All(Status(http.StatusAccepted)),
			},
		},
		"deleting async only plan requires accepts_incomplete": {
			{
				Method: http.MethodPut,
				Target: "/v2/service_instances/test-id?accepts_incomplete=true",
				Body:   []byte(`{"plan_id":"fake-async-only-plan-guid"}`),
				Want:   All(),
			},
			{
				Method: http.MethodDelete,
				Target: "/v2/service_instances/test-id",
				Want:   All(Status(http.StatusUnprocessableEntity)),
			},
			{
				Method: http.MethodDelete,
				Target: "/v2/service_instances/test-id?accepts_incomplete=true",
				Want:   All(Status(http.StatusAccepted)),
			},
		},
		"deleting missing instance 404s": {
			{
				Method: http.MethodDelete,
				Target: "/v2/service_instances/missing?accepts_incomplete=true",
				Want:   All(StatusNotFound),
			},
		},
	}

	for tn, tc := range cases {
		t.Run(tn, tc.Test)
	}
}

func Test_lastOperation(t *testing.T) {
	t.Parallel()

	cases := map[string]HTTPTestSuite{
		"404s for missing instance": {
			{
				Method: http.MethodGet,
				Target: "/v2/service_instances/test-id/last_operation",
				Want:   All(StatusNotFound),
			},
		},
		"last operation keeps track of calls": {
			{
				Method: http.MethodPut,
				Target: "/v2/service_instances/test-id?accepts_incomplete=true",
				Body:   []byte(`{"plan_id":"fake-async-only-plan-guid"}`),
				Want:   All(Status(http.StatusAccepted)),
			},
			{
				Method: http.MethodGet,
				Target: "/v2/service_instances/test-id/last_operation",
				Want:   All(Status(http.StatusOK), BodyContains("in progress")),
			},
			{
				Method: http.MethodGet,
				Target: "/v2/service_instances/test-id/last_operation",
				Want:   All(Status(http.StatusOK), BodyContains("succeeded")),
			},
			{ // repeated calls should succeed
				Method: http.MethodGet,
				Target: "/v2/service_instances/test-id/last_operation",
				Want:   All(Status(http.StatusOK), BodyContains("succeeded")),
			},
		},
		"number of calls can be customized via config": {
			{
				Method: http.MethodPatch,
				Target: "/config",
				Body:   []byte(`{"max_fetch_service_instance_requests": 2}`),
				Want:   All(Status(http.StatusOK)),
			},
			{
				Method: http.MethodPut,
				Target: "/v2/service_instances/test-id?accepts_incomplete=true",
				Body:   []byte(`{"plan_id":"fake-async-only-plan-guid"}`),
				Want:   All(Status(http.StatusAccepted)),
			},
			{
				Method: http.MethodGet,
				Target: "/v2/service_instances/test-id/last_operation",
				Want:   All(Status(http.StatusOK), BodyContains("in progress")),
			},
			{
				Method: http.MethodGet,
				Target: "/v2/service_instances/test-id/last_operation",
				Want:   All(Status(http.StatusOK), BodyContains("in progress")),
			},
			{
				Method: http.MethodGet,
				Target: "/v2/service_instances/test-id/last_operation",
				Want:   All(Status(http.StatusOK), BodyContains("succeeded")),
			},
			{ // repeated calls should succeed
				Method: http.MethodGet,
				Target: "/v2/service_instances/test-id/last_operation",
				Want:   All(Status(http.StatusOK), BodyContains("succeeded")),
			},
		},
	}

	for tn, tc := range cases {
		t.Run(tn, tc.Test)
	}
}

func Test_config(t *testing.T) {
	t.Parallel()

	cases := map[string]HTTPTestSuite{
		"serves current configuration": {
			{
				Method: http.MethodGet,
				Target: "/config",
				Want:   All(StatusOK, JSONBody()),
			},
		},
		"allows updating configuration": {
			{
				Method: http.MethodPost,
				Target: "/config",
				Body:   []byte("{}"),
				Want:   StatusOK,
			},
			{
				Method: http.MethodGet,
				Target: "/config",
				Want:   All(BodyContains(`{"behaviors":{"catalog":{}}}`), StatusOK),
			},
		},
		"allows resetting configuration": {
			{
				Method: http.MethodPost,
				Target: "/config",
				Body:   []byte("{}"),
				Want:   StatusOK,
			},
			{
				Method: http.MethodGet,
				Target: "/v2/catalog",
				Want:   Status(0), // Invalid due to invalid config.
			},
			{
				Method: http.MethodPost,
				Target: "/config/reset",
				Want:   StatusOK,
			},
			{
				Method: http.MethodGet,
				Target: "/v2/catalog",
				Want:   StatusOK,
			},
		},
	}

	for tn, tc := range cases {
		t.Run(tn, tc.Test)
	}
}

func Test_bind(t *testing.T) {
	t.Parallel()

	cases := map[string]HTTPTestSuite{
		"404s for missing instance": {
			{
				Method: http.MethodPut,
				Target: "/v2/service_instances/test-id/service_bindings/some-binding",
				Body:   []byte(`{}`),
				Want:   StatusNotFound,
			},
		},
		"valid binding": {
			{
				Method: http.MethodPut,
				Target: "/v2/service_instances/test-id",
				Body:   []byte(`{}`),
				Want:   All(JSONBody(), StatusOK),
			},
			{
				Method: http.MethodPut,
				Target: "/v2/service_instances/test-id/service_bindings/some-binding",
				Body:   []byte(`{}`),
				Want:   All(JSONBody(), Status(http.StatusCreated)),
			},
		},
	}

	for tn, tc := range cases {
		t.Run(tn, tc.Test)
	}
}

func Test_unbind(t *testing.T) {
	t.Parallel()

	cases := map[string]HTTPTestSuite{
		"404s for missing instance": {
			{
				Method: http.MethodDelete,
				Target: "/v2/service_instances/test-id/service_bindings/some-binding",
				Body:   []byte(`{}`),
				Want:   StatusNotFound,
			},
		},
		"valid binding": {
			{
				Method: http.MethodPut,
				Target: "/v2/service_instances/test-id",
				Body:   []byte(`{}`),
				Want:   All(JSONBody(), StatusOK),
			},
			{
				Method: http.MethodPut,
				Target: "/v2/service_instances/test-id/service_bindings/some-binding",
				Body:   []byte(`{}`),
				Want:   All(JSONBody(), Status(http.StatusCreated)),
			},
			{
				Method: http.MethodDelete,
				Target: "/v2/service_instances/test-id/service_bindings/some-binding",
				Want:   All(JSONBody(), Status(http.StatusOK)),
			},
		},
	}

	for tn, tc := range cases {
		t.Run(tn, tc.Test)
	}
}


text:
<?php

namespace Erfans\MaintenanceBundle\DependencyInjection;

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

class ErfansMaintenanceExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');

        $definition = $container->getDefinition("Erfans\MaintenanceBundle\EventListener\MaintenanceListener");
        $definition->addArgument($config);

        $container->setParameter("erfans.maintenance.parameters.view.title", $config["view"]["title"]);
        $container->setParameter("erfans.maintenance.parameters.view.description", $config["view"]["description"]);
    }
}


text:
namespace ash {

// ArcAppfuseProviderClient is used to communicate with the ArcAppfuseProvider
// service which provides ProxyFileDescriptor (aka appfuse) feature for ARC. All
// methods should be called from the origin thread (UI thread) which initializes
// the DBusThreadManager instance.
class COMPONENT_EXPORT(ASH_DBUS_ARC) ArcAppfuseProviderClient
    : public chromeos::DBusClient {
 public:
  // Returns the global instance if initialized. May return null.
  static ArcAppfuseProviderClient* Get();

  // Creates and initializes the global instance. |bus| must not be null.
  static void Initialize(dbus::Bus* bus);

  // Creates and initializes a fake global instance.
  static void InitializeFake();

  // Destroys the global instance if it has been initialized.
  static void Shutdown();

  // Mounts a new appfuse file system and returns a filtered /dev/fuse FD
  // associated with the mounted file system.
  virtual void Mount(uint32_t uid,
                     int32_t mount_id,
                     chromeos::DBusMethodCallback<base::ScopedFD> callback) = 0;

  // Unmounts the specified appfuse file system.
  virtual void Unmount(uint32_t uid,
                       int32_t mount_id,
                       chromeos::VoidDBusMethodCallback callback) = 0;

  // Opens a file under the specified appfuse file system.
  virtual void OpenFile(
      uint32_t uid,
      int32_t mount_id,
      int32_t file_id,
      int32_t flags,
      chromeos::DBusMethodCallback<base::ScopedFD> callback) = 0;

 protected:
  ArcAppfuseProviderClient();
  ~ArcAppfuseProviderClient() override;
};

}  // namespace ash

#endif  // CHROMEOS_ASH_COMPONENTS_DBUS_ARC_ARC_APPFUSE_PROVIDER_CLIENT_H_


text:
Pipeline Workflow
=================

.. contents:: :local:

km3pipe is a lightweight framework which tries to give you a lose structure and
workflow for data analysis. It uses the simple, yet powerful module system
of the `thepipe <https://github.com/tamasgal/thepipe>`_ Python module,
which allows you to organise and reuse code.

In this section, a few examples are shown how to work the with
pipeline, but it is recommended to check the `documentation of thepipe
<https://thepipe.readthedocs.io/en/latest/?badge=latest>`_ since the features
will change in future.

The main structure is a ``Pipeline`` which is meant to hold everything
together. The building blocks are simply called Modules and are either
basic Python functions or instances of the class ``Module``. These classes
are simply imported from ``thepipe`` package and can also be used directly
from that.

To setup a workflow, you first create a pipeline, attach the modules to it
and to fire up the analysis chain, you call ``.drain()`` on your pipeline
and let the flow go.

Draining Procedure
------------------

Everything is standing still up until the ``pipe.drain()`` method is called.
This method can be called without arguments, which will cycle through the iterations
until the attached pump stops it. One can however also pass a number, which stands
for the maximum number of iterations, like ``pipe.drain(23)``.
Another possibility to stop the pipeline before the pump finishes is pressing ``CTRL+C``,
which will execute the current cycle, gracefully finish up every module and close
all the file handlers properly.

The stages a pipeline launches when ``pipe.drain()`` is executed are the following:

- Call ``.configure()`` on every attached module one-by-one
- Call ``.prepare()`` on every attached module one-by-one
- Start with the actual iteration and call ``.process(blob)`` on the first module
- Take it's output (a ``Blob()``) and call the next attached module with that Blob instance
- When the cycle reached the last module, start from the beginning
- Stop whenever (one of) the pump raises a ``StopIteration``
- Call ``.finish()`` on every module one-by-one

Pipeline Example
----------------

The following script shows the module system of KM3Pipe. There is a
``DummyPump`` which is in this case a dummy data generator. The other Modules
do some modifications on the data and pass them through to the next module in
the pipeline.

.. literalinclude:: ../examples/nogallery/module_workflow.py
   :language: python
   :linenos:

Which will print the following:::

    Pipeline and module initialisation took 0.000s (CPU 0.000s).
    This is the current blob: {'nr': 1}
    {'nr': 1, 'foo_entry': 'default_foo', 'moo_entry': 42}
    This is the current blob: {'nr': 2}
    {'nr': 2, 'foo_entry': 'default_foo', 'moo_entry': 42}
    My process() method was called 2 times.
    ============================================================
    2 cycles drained in 0.000553s (CPU 0.000525s). Memory peak: 154.08 MB
      wall  mean: 0.000058s  medi: 0.000058s  min: 0.000055s  max: 0.000062s  std: 0.000004s
      CPU   mean: 0.000059s  medi: 0.000059s  min: 0.000056s  max: 0.000062s  std: 0.000003s

Modules
-------

A module is a configurable building block which can be attached to a pipeline.
It has a ``process()`` method, which is called every time with the current
data ("blob") in the pipeline cycle. This piece of data can be analysed,
manipulated and finally returned to allow the handover to the next module
in the pipeline system.

Instance variables can be initialised within the ``configure()`` method.
User defined parameters are accessible via ``self.get()`` or ``self.required()``
calls inside the ``configure()`` method.
Both of them return the passed value or in case of ``self.get()``, the ``default=None``
value.
This allows an easy way to define default values as seen in the example below.

.. literalinclude:: ../examples/nogallery/module_workflow.py
   :pyobject: Foo
   :emphasize-lines: 4-6
   :linenos:

To override the default parameters, the desired values can be set when
attaching the module to the pipeline. Always use the class itself, since
the ``attach()`` method of the pipeline will care about the initialisation::

    pipe.attach(Foo, bar='dummybar', baz=69)

Module can optionally implement the following methods::

    configure()
    prepare()
    process()
    finish()

Pumps / Sinks
-------------

The pump and sink are special kinds of ``Module`` and are usually the
first and last ones to be attached to a pipeline. They are responsible
for reading and writing data to/from files, or streams from socket
connections in each iteration, continuously.
Note that they still simply derive from ``Module``.

``configure()`` method should be used to set up the file or socket
handler and the ``finish()`` has to close them. The actual data is
passed via the ``process()`` method. A data chunk is internally called
``Blob`` (a fancier ``dict``) and contains whatever the pump extracts
in each iteration. It can be a single event or the contents of a whole
file.

To end the data pumping, the pump has to raise a ``StopIteration``
exception. One elegant way to implement this in Python is using a
generator.

The following example shows a very basic pump, which simply initialises
a list of dictionaries and "io" one blob after another on each
``process()`` call to the next module in the pipeline.

.. literalinclude:: ../examples/nogallery/module_workflow.py
   :pyobject: DummyPump
   :linenos:

Logging and Printing
--------------------

Every module inheriting from the ``Module`` class has a fancy logger and a
printer available to produce output which is unique (an actual colour code
is generated using a hash of the module name).

Inside any method of the module, use ``self.log`` to access the logger, which
comes with the usual functions like ``self.log.debug()``, ``self.log.info()``,
``self.log.warning()``, ``self.log.error()`` or ``self.log.critical()``.

The ``self.cprint`` function can be used to print messages which are colour
coded with the same colours used for the logger.

Configuring the Pipeline using Configuration Files
--------------------------------------------------

The pipeline and all the attached modules can be configured by a TOML formatted
file, sitting at the current working directory (where the initial script is
invoked to launch the pipeline). The default filename is ``pipeline.toml``
but a different filename can be chosen when creating the ``Pipeline`` instance
using ``Pipeline(configfile='your_desired_filename.toml')``.

TOML does not support variables, but a section called ``[VARIABLES]`` can be
defined and those will be substituted when used in other (module) sections.

Here is an example of the file:

.. literalinclude:: ../examples/nogallery/pipeline.toml
   :linenos:


text:
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;

internal static partial class Interop
{
    internal static partial class Kernel32
    {
        [DllImport(Interop.Libraries.Kernel32, SetLastError = true)]
        internal static extern bool DuplicateHandle(
            IntPtr hSourceProcessHandle,
            IntPtr hSourceHandle,
            IntPtr hTargetProcessHandle,
            ref SafeAccessTokenHandle lpTargetHandle,
            uint dwDesiredAccess,
            bool bInheritHandle,
            uint dwOptions);
    }
}