text:
package pixlepix.auracascade.block;

import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Items;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import pixlepix.auracascade.block.tile.AuraTilePumpBase;
import pixlepix.auracascade.block.tile.ConsumerTile;
import pixlepix.auracascade.registry.CraftingBenchRecipe;
import pixlepix.auracascade.registry.ITTinkererBlock;
import pixlepix.auracascade.registry.ThaumicTinkererRecipe;

import java.util.ArrayList;

/**
 * Created by localmacaccount on 5/27/15.
 */
public class BlockMonitor extends Block implements ITTinkererBlock {
    public BlockMonitor() {
        super(Material.REDSTONE_LIGHT);
        setHardness(3);
        setHarvestLevel("pickaxe", 2);
    }

    @Override
    public boolean canConnectRedstone(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing side) {
        return true;
    }

    @Override
    public int getWeakPower(IBlockState blockState, IBlockAccess world, BlockPos pos, EnumFacing side) {
        EnumFacing powerDirection = side.getOpposite();
        for (EnumFacing direction : EnumFacing.VALUES) {
            if (direction != powerDirection) {
                TileEntity auraTile = world.getTileEntity(pos.offset(direction));

                if (auraTile instanceof AuraTilePumpBase) {
                    return ((AuraTilePumpBase) auraTile).pumpPower > 0 ? 0 : 15;
                }
                if (auraTile instanceof ConsumerTile) {
                    return ((ConsumerTile) auraTile).validItemsNearby() ? 0 : 15;
                }
            }
        }
        return 0;
    }

    /**
     * Can this block provide power. Only wire currently seems to have this change based on its state.
     */

    @Override
    public boolean canProvidePower(IBlockState state) {
        return true;
    }

    @Override
    public ArrayList<Object> getSpecialParameters() {
        return null;
    }

    @Override
    public String getBlockName() {
        return "monitor";
    }

    @Override
    public boolean shouldRegister() {
        return true;
    }

    @Override
    public boolean shouldDisplayInTab() {
        return true;
    }

    @Override
    public Class<? extends ItemBlock> getItemBlock() {
        return null;
    }

    @Override
    public Class<? extends TileEntity> getTileEntity() {
        return null;
    }

    @Override
    public ThaumicTinkererRecipe getRecipeItem() {
        return new CraftingBenchRecipe(new ItemStack(this), "RRR", "RAR", "RRR", 'R', new ItemStack(Items.REDSTONE), 'A', AuraBlock.getAuraNodeItemstack());
    }

    @Override
    public int getCreativeTabPriority() {
        return 3;
    }
}


text:
package com.inversoft.passport.domain.oauth2;

/**
 * Authorization Grant types as defined by the The OAuth 2.0 Authorization
 * Framework - RFC 6749.
 *
 * @author Daniel DeGroff
 */
public enum GrantType {
  Authorization,
  Implicit,
  Resource_Owner_Credentials,
  Client_Credentials,
  Refresh_Token
}

redpajama_set_name: RedPajamaGithub


text:
package narc

type TaskLimits struct {
	MemoryLimitInBytes uint64
	DiskLimitInBytes   uint64
}

func (limits *TaskLimits) IsValid() bool {
	return limits.MemoryLimitInBytes > 0 && limits.DiskLimitInBytes > 0
}


text:
/**
 * Extends the target object with properties from another object.
 */
module.exports.extend = function(target, object) {
    var property, src, copy;
    for (property in object) {
        if (target[property] === undefined) {
            copy = object[property];
            if (typeof copy === object) {
                target[property] = extend(target[property] || {}, copy)
            } else if (copy !== undefined) {
                target[property] = copy;
            }
        }
    }
    return target;
}


text:
package com.google.inject.binder;

import java.lang.annotation.Annotation;

/**
 * See the EDSL examples at {@link com.google.inject.Binder}.
 *
 * @author crazybob@google.com (Bob Lee)
 */
public interface AnnotatedConstantBindingBuilder {

  /** See the EDSL examples at {@link com.google.inject.Binder}. */
  ConstantBindingBuilder annotatedWith(Class<? extends Annotation> annotationType);

  /** See the EDSL examples at {@link com.google.inject.Binder}. */
  ConstantBindingBuilder annotatedWith(Annotation annotation);
}


text:
package yaes.ui.simulationcontrol;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Dictionary;
import java.util.Hashtable;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

/**
 * This is the whole thing.
 *
 * Todo: split it into components, such that we can make a single tabbed GUI.
 *
 * yaes.ui.simulationcontrol.SimulationControlPanel
 *
 * @todo describe
 *
 * @author Ladislau Boloni (lboloni@eecs.ucf.edu)
 */
public class SimulationControlPanel implements ActionListener, ChangeListener {
    public enum State {
        FINISHED, INITIAL, POSTPROCESSED, READY_TO_RUN, RUNNING
    };

    private final JButton              btnPostProcess;
    private final JButton              btnRun;
    private final JButton              btnRunTo;
    // buttons
    private final JButton              btnSetup;
    private final JButton              btnStep;
    private final JButton              btnStop;
    private JLabel                     lblOneStepIs;
    private final JPanel               pnlButtons;
    private PnlSimulationOutput        pnlOutput;
    private JSlider                    sldDelay;
    private State                      state            = State.INITIAL;
    private JTabbedPane                tbPanelComponents;
    private final JFormattedTextField  tfRunTo;
    //
    private final JTextField           tfStatus;
    private final SimulationControlGui theGui;
    private final JPanel               thePanel;

    public SimulationControlPanel(SimulationControlGui theGui) {
        this.theGui = theGui;
        thePanel = new JPanel();
        thePanel.setLayout(new BoxLayout(thePanel, BoxLayout.Y_AXIS));
        // button panel
        pnlButtons = new JPanel();
        pnlButtons.setLayout(new BoxLayout(pnlButtons, BoxLayout.X_AXIS));
        thePanel.add(pnlButtons);
        btnSetup = addButton("Setup");
        btnStep = addButton("Step");
        btnRun = addButton("Run");
        btnRunTo = addButton("Run to:");
        tfRunTo = new JFormattedTextField(new Integer(0));
        Dimension prefSize = tfRunTo.getPreferredSize();
        tfRunTo.setMinimumSize(new Dimension(100, 0));
        tfRunTo.setPreferredSize(new Dimension(100, prefSize.height));
        tfRunTo.setMaximumSize(new Dimension(100, prefSize.height));
        pnlButtons.add(tfRunTo);
        pnlButtons
                .add(Box.createHorizontalStrut(UiHelper.INTERBUTTON_DISTANCE));
        btnStop = addButton("Stop");
        btnPostProcess = addButton("Postprocess");
        tfStatus = UiHelper.createDisplayField(15);
        pnlButtons.add(tfStatus);
        pnlButtons.add(createSimulationSpeedPanel());
        state = State.INITIAL;
        setButtonBasedOnState();
        // tabs
        tbPanelComponents = new JTabbedPane();
        thePanel.add(tbPanelComponents);
        pnlOutput = new PnlSimulationOutput();
        addTab("Output", pnlOutput);
    }

    /**
     * Handles the buttons
     *
     * @param event
     */
    @Override
    public void actionPerformed(ActionEvent event) {
        if (event.getSource() == btnSetup) {
            theGui.setNextCommand(SimulationControlGui.Command.Setup);
            state = State.READY_TO_RUN;
            setButtonBasedOnState();
            return;
        }
        if (event.getSource() == btnStep) {
            theGui.setNextCommand(SimulationControlGui.Command.Step);
            state = State.READY_TO_RUN;
            setButtonBasedOnState();
            return;
        }
        if (event.getSource() == btnRun) {
            theGui.setNextCommand(SimulationControlGui.Command.Run);
            state = State.RUNNING;
            setButtonBasedOnState();
            return;
        }
        if (event.getSource() == btnRunTo) {
            theGui.setNextCommand(SimulationControlGui.Command.RunTo);
            theGui.setRunTo((Integer) tfRunTo.getValue());
            state = State.RUNNING;
            setButtonBasedOnState();
            return;
        }
        if (event.getSource() == btnStop) {
            theGui.setNextCommand(SimulationControlGui.Command.Stop);
            state = State.READY_TO_RUN;
            setButtonBasedOnState();
            return;
        }
        if (event.getSource() == btnPostProcess) {
            theGui.setNextCommand(SimulationControlGui.Command.PostProcess);
            state = State.POSTPROCESSED;
            setButtonBasedOnState();
            return;
        }
    }

    /**
     * Adds a button to the button panel
     *
     * @param text
     * @return
     */
    private JButton addButton(String text) {
        final JButton button = new JButton(text);
        pnlButtons.add(button);
        // pnlButtons
        // .add(Box.createHorizontalStrut(UiHelper.INTERBUTTON_DISTANCE));
        button.addActionListener(this);
        button.setEnabled(false);
        return button;
    }

    public void addTab(String tabName, ISimulationControlPanel iscp) {
        tbPanelComponents.add(tabName, iscp.getPanel());
        tbPanelComponents.setSelectedComponent(iscp.getPanel());
    }

    /**
     * Simulation speed panel
     *
     * @return
     */
    private JPanel createSimulationSpeedPanel() {
        JPanel pnlSlider = new JPanel();
        pnlSlider.setLayout(new BoxLayout(pnlSlider, BoxLayout.X_AXIS));
        lblOneStepIs = new JLabel("Sec/step:");
        pnlSlider.add(lblOneStepIs);
        sldDelay = new JSlider(SwingConstants.HORIZONTAL, 0, 5, (int) theGui
                .getRunningDelay());
        sldDelay.addChangeListener(this);
        Dictionary<Integer, JComponent> labelTable = new Hashtable<>();
        labelTable.put(0, new JLabel("Max"));
        labelTable.put(1, new JLabel("0.01"));
        labelTable.put(2, new JLabel("0.03"));
        labelTable.put(3, new JLabel("0.1"));
        labelTable.put(4, new JLabel("0.3"));
        labelTable.put(5, new JLabel("1"));
        sldDelay.setLabelTable(labelTable);
        sldDelay.setPaintLabels(true);
        pnlSlider.add(sldDelay);
        return pnlSlider;
    }

    /**
     * @return the thePanel
     */
    public JPanel getThePanel() {
        return thePanel;
    }

    /**
     * Turns the buttons on and off.
     *
     */
    private void setButtonBasedOnState() {
        tfStatus.setText(theGui.getStatusString());
        if (theGui.getSimulationOutput() != null) {
            pnlOutput.setSimulationOutput(theGui.getSimulationOutput());
        }
        switch (state) {
        case INITIAL:
            btnSetup.setEnabled(true);
            btnStep.setEnabled(false);
            btnRun.setEnabled(false);
            btnRunTo.setEnabled(false);
            btnStop.setEnabled(false);
            btnPostProcess.setEnabled(false);
            break;
        case READY_TO_RUN:
            btnSetup.setEnabled(false);
            btnStep.setEnabled(true);
            btnRun.setEnabled(true);
            btnRunTo.setEnabled(true);
            btnStop.setEnabled(false);
            btnPostProcess.setEnabled(false);
            break;
        case RUNNING:
            btnSetup.setEnabled(false);
            btnStep.setEnabled(false);
            btnRun.setEnabled(false);
            btnRunTo.setEnabled(false);
            btnStop.setEnabled(true);
            btnPostProcess.setEnabled(false);
            break;
        case FINISHED:
            btnSetup.setEnabled(false);
            btnStep.setEnabled(false);
            btnRun.setEnabled(false);
            btnRunTo.setEnabled(false);
            btnStop.setEnabled(false);
            btnPostProcess.setEnabled(true);
            break;
        case POSTPROCESSED:
            btnSetup.setEnabled(false);
            btnStep.setEnabled(false);
            btnRun.setEnabled(false);
            btnRunTo.setEnabled(false);
            btnStop.setEnabled(false);
            btnPostProcess.setEnabled(false);
            break;
		default:
			break;
        }
    }

    /**
     * If the simulation speed is too high... turns the one step is to red!
     *
     * @param isOk
     */
    public void setSimulationSpeedOK(boolean isOk) {
        if (isOk) {
            lblOneStepIs.setForeground(Color.black);
        } else {
            lblOneStepIs.setForeground(Color.red);
        }
    }

    /**
     * Sets the button based on the state
     *
     * @param state
     */
    public void setState(State state) {
        this.state = state;
        setButtonBasedOnState();
    }

    /**
     * Handles events - for the time being, it is the slider for the simulation
     * speed
     *
     * @param arg0
     */
    @Override
    public void stateChanged(ChangeEvent arg0) {
        if (arg0.getSource() == sldDelay) {
            if (!sldDelay.getValueIsAdjusting()) {
                int val = sldDelay.getValue();
                switch (val) {
                case 0:
                    theGui.setRunningDelay(0);
                    break;
                case 1:
                    theGui.setRunningDelay(10);
                    break;
                case 2:
                    theGui.setRunningDelay(33);
                    break;
                case 3:
                    theGui.setRunningDelay(100);
                    break;
                case 4:
                    theGui.setRunningDelay(333);
                    break;
                case 5:
                    theGui.setRunningDelay(1000);
                    break;
				default:
					break;
                }
            }
        }
    }

    /**
     * Updates the status button
     */
    public void update() {
        tfStatus.setText(theGui.getStatusString());
    }
}


text:
<?php
/**
 * @link https://github.com/old-town/old-town-workflow
 * @author  Malofeykin Andrey  <and-rey2@yandex.ru>
 */
namespace OldTown\Workflow;

use OldTown\PropertySet\PropertySetInterface;
use OldTown\Workflow\Exception\InvalidInputException;
use OldTown\Workflow\Exception\RemoteException;
use OldTown\Workflow\TransientVars\TransientVarsInterface;

/**
 * Interface ValidatorRemoteInterface
 *
 * @package OldTown\Workflow
 */
interface ValidatorInterface
{
    /**
     * @param TransientVarsInterface            $transientVars
     * @param             $args
     * @param PropertySetInterface $ps
     *
     * @throws InvalidInputException
     * @throws RemoteException
     * @return void
     */
    public function validate(TransientVarsInterface $transientVars, array $args = [], PropertySetInterface $ps);
}


text:
/**
 * @author mrdoob / http://mrdoob.com/
 * @author Mugen87 / https://github.com/Mugen87
 */

import { Geometry } from '../core/Geometry.js';
import { BufferGeometry } from '../core/BufferGeometry.js';
import { Float32BufferAttribute } from '../core/BufferAttribute.js';
import { Vector3 } from '../math/Vector3.js';
import { Vector2 } from '../math/Vector2.js';

// CylinderGeometry

function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {

	Geometry.call( this );

	this.type = 'CylinderGeometry';

	this.parameters = {
		radiusTop: radiusTop,
		radiusBottom: radiusBottom,
		height: height,
		radialSegments: radialSegments,
		heightSegments: heightSegments,
		openEnded: openEnded,
		thetaStart: thetaStart,
		thetaLength: thetaLength
	};

	this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
	this.mergeVertices();

}

CylinderGeometry.prototype = Object.create( Geometry.prototype );
CylinderGeometry.prototype.constructor = CylinderGeometry;

// CylinderBufferGeometry

function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {

	BufferGeometry.call( this );

	this.type = 'CylinderBufferGeometry';

	this.parameters = {
		radiusTop: radiusTop,
		radiusBottom: radiusBottom,
		height: height,
		radialSegments: radialSegments,
		heightSegments: heightSegments,
		openEnded: openEnded,
		thetaStart: thetaStart,
		thetaLength: thetaLength
	};

	var scope = this;

	radiusTop = radiusTop !== undefined ? radiusTop : 1;
	radiusBottom = radiusBottom !== undefined ? radiusBottom : 1;
	height = height || 1;

	radialSegments = Math.floor( radialSegments ) || 8;
	heightSegments = Math.floor( heightSegments ) || 1;

	openEnded = openEnded !== undefined ? openEnded : false;
	thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
	thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;

	// buffers

	var indices = [];
	var vertices = [];
	var normals = [];
	var uvs = [];

	// helper variables

	var index = 0;
	var indexArray = [];
	var halfHeight = height / 2;
	var groupStart = 0;

	// generate geometry

	generateTorso();

	if ( openEnded === false ) {

		if ( radiusTop > 0 ) generateCap( true );
		if ( radiusBottom > 0 ) generateCap( false );

	}

	// build geometry

	this.setIndex( indices );
	this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
	this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
	this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

	function generateTorso() {

		var x, y;
		var normal = new Vector3();
		var vertex = new Vector3();

		var groupCount = 0;

		// this will be used to calculate the normal
		var slope = ( radiusBottom - radiusTop ) / height;

		// generate vertices, normals and uvs

		for ( y = 0; y <= heightSegments; y ++ ) {

			var indexRow = [];

			var v = y / heightSegments;

			// calculate the radius of the current row

			var radius = v * ( radiusBottom - radiusTop ) + radiusTop;

			for ( x = 0; x <= radialSegments; x ++ ) {

				var u = x / radialSegments;

				var theta = u * thetaLength + thetaStart;

				var sinTheta = Math.sin( theta );
				var cosTheta = Math.cos( theta );

				// vertex

				vertex.x = radius * sinTheta;
				vertex.y = - v * height + halfHeight;
				vertex.z = radius * cosTheta;
				vertices.push( vertex.x, vertex.y, vertex.z );

				// normal

				normal.set( sinTheta, slope, cosTheta ).normalize();
				normals.push( normal.x, normal.y, normal.z );

				// uv

				uvs.push( u, 1 - v );

				// save index of vertex in respective row

				indexRow.push( index ++ );

			}

			// now save vertices of the row in our index array

			indexArray.push( indexRow );

		}

		// generate indices

		for ( x = 0; x < radialSegments; x ++ ) {

			for ( y = 0; y < heightSegments; y ++ ) {

				// we use the index array to access the correct indices

				var a = indexArray[ y ][ x ];
				var b = indexArray[ y + 1 ][ x ];
				var c = indexArray[ y + 1 ][ x + 1 ];
				var d = indexArray[ y ][ x + 1 ];

				// faces

				indices.push( a, b, d );
				indices.push( b, c, d );

				// update group counter

				groupCount += 6;

			}

		}

		// add a group to the geometry. this will ensure multi material support

		scope.addGroup( groupStart, groupCount, 0 );

		// calculate new start value for groups

		groupStart += groupCount;

	}

	function generateCap( top ) {

		var x, centerIndexStart, centerIndexEnd;

		var uv = new Vector2();
		var vertex = new Vector3();

		var groupCount = 0;

		var radius = ( top === true ) ? radiusTop : radiusBottom;
		var sign = ( top === true ) ? 1 : - 1;

		// save the index of the first center vertex
		centerIndexStart = index;

		// first we generate the center vertex data of the cap.
		// because the geometry needs one set of uvs per face,
		// we must generate a center vertex per face/segment

		for ( x = 1; x <= radialSegments; x ++ ) {

			// vertex

			vertices.push( 0, halfHeight * sign, 0 );

			// normal

			normals.push( 0, sign, 0 );

			// uv

			uvs.push( 0.5, 0.5 );

			// increase index

			index ++;

		}

		// save the index of the last center vertex

		centerIndexEnd = index;

		// now we generate the surrounding vertices, normals and uvs

		for ( x = 0; x <= radialSegments; x ++ ) {

			var u = x / radialSegments;
			var theta = u * thetaLength + thetaStart;

			var cosTheta = Math.cos( theta );
			var sinTheta = Math.sin( theta );

			// vertex

			vertex.x = radius * sinTheta;
			vertex.y = halfHeight * sign;
			vertex.z = radius * cosTheta;
			vertices.push( vertex.x, vertex.y, vertex.z );

			// normal

			normals.push( 0, sign, 0 );

			// uv

			uv.x = ( cosTheta * 0.5 ) + 0.5;
			uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
			uvs.push( uv.x, uv.y );

			// increase index

			index ++;

		}

		// generate indices

		for ( x = 0; x < radialSegments; x ++ ) {

			var c = centerIndexStart + x;
			var i = centerIndexEnd + x;

			if ( top === true ) {

				// face top

				indices.push( i, i + 1, c );

			} else {

				// face bottom

				indices.push( i + 1, i, c );

			}

			groupCount += 3;

		}

		// add a group to the geometry. this will ensure multi material support

		scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );

		// calculate new start value for groups

		groupStart += groupCount;

	}

}

CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;

export { CylinderGeometry, CylinderBufferGeometry };


text:
from django.core.urlresolvers import reverse

from lib.paypal.client import get_client
from lib.paypal.signals import create
from solitude.base import Cached, Resource as BaseResource

class Resource(BaseResource):

    class Meta(BaseResource.Meta):
        object_class = Cached

    def get_resource_uri(self, bundle):
        return reverse('api_dispatch_detail',
                        kwargs={'api_name': 'paypal',
                                'resource_name': self._meta.resource_name,
                                'pk': bundle.obj.pk})

    def obj(self, pk=None):
        return self._meta.object_class(prefix=self._meta.resource_name, pk=pk)

    def obj_create(self, bundle, request, **kwargs):
        form = self._meta.form(bundle.data)
        if not form.is_valid():
            raise self.form_errors(form)

        paypal = get_client()
        bundle.data = getattr(paypal, self._meta.method)(*form.args())
        create.send(sender=self, bundle=bundle)
        return bundle


text:
package org.spongepowered.common.data.processor.data.block;

import net.minecraft.block.BlockStoneSlab;
import net.minecraft.item.ItemStack;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.manipulator.immutable.block.ImmutableSlabData;
import org.spongepowered.api.data.manipulator.mutable.block.SlabData;
import org.spongepowered.api.data.type.SlabType;
import org.spongepowered.api.data.type.SlabTypes;
import org.spongepowered.api.data.value.mutable.Value;
import org.spongepowered.api.item.ItemTypes;
import org.spongepowered.common.data.manipulator.mutable.block.SpongeSlabData;
import org.spongepowered.common.data.processor.common.AbstractCatalogDataProcessor;
import org.spongepowered.common.data.value.mutable.SpongeValue;

public class SlabDataProcessor extends AbstractCatalogDataProcessor<SlabType, Value<SlabType>, SlabData, ImmutableSlabData> {

    public SlabDataProcessor() {
        super(Keys.SLAB_TYPE, input -> input.getItem() == ItemTypes.STONE_SLAB || input.getItem() == ItemTypes.STONE_SLAB2);
    }

    @Override
    protected int setToMeta(SlabType value) {
        return -1; // not used
    }

    @Override
    protected SlabType getFromMeta(int meta) {
        return (SlabType) (Object) BlockStoneSlab.EnumType.byMetadata(meta);
    }

    @Override
    public SlabData createManipulator() {
        return new SpongeSlabData();
    }

    @Override
    protected boolean set(ItemStack stack, SlabType value) {
        // TODO - the API needs to be refactored, as it's no longer possible to change the type of an ItemStack
        return false;
        /*
        if (stack.getType() == ItemTypes.STONE_SLAB) {
            if (!value.equals(SlabTypes.RED_SAND)) {
                stack.setItemDamage(((BlockStoneSlab.EnumType) (Object) value).getMetadata());
            } else {
                stack.setItem(Item.getItemFromBlock(Blocks.STONE_SLAB2));
                stack.setItemDamage(((BlockStoneSlabNew.EnumType) (Object) value).getMetadata());
            }
        } else if (stack.getType() == ItemTypes.STONE_SLAB2) {
            if (stack.getType() == ItemTypes.STONE_SLAB2) {
                if (value.equals(SlabTypes.RED_SAND)) {
                    stack.setItemDamage(((BlockStoneSlabNew.EnumType) (Object) value).getMetadata());
                } else {
                    stack.setItem(Item.getItemFromBlock(Blocks.STONE_SLAB));
                    stack.setItemDamage(((BlockStoneSlab.EnumType) (Object) value).getMetadata());
                }
            }
        }
        return true;*/
    }

    @Override
    protected SlabType getDefaultValue() {
        return SlabTypes.COBBLESTONE;
    }

    @Override
    protected Value<SlabType> constructValue(SlabType actualValue) {
        return new SpongeValue<>(this.key, getDefaultValue(), actualValue);
    }

}


text:
/* jshint globalstrict:false, strict:false, unused : false */
/* global assertFalse */

// //////////////////////////////////////////////////////////////////////////////
// / @brief tests for dump/reload
// /
// / @file
// /
// / DISCLAIMER
// /
// / Copyright 2010-2012 triagens GmbH, Cologne, Germany
// /
// / Licensed under the Apache License, Version 2.0 (the "License")
// / you may not use this file except in compliance with the License.
// / You may obtain a copy of the License at
// /
// /     http://www.apache.org/licenses/LICENSE-2.0
// /
// / Unless required by applicable law or agreed to in writing, software
// / distributed under the License is distributed on an "AS IS" BASIS,
// / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// / See the License for the specific language governing permissions and
// / limitations under the License.
// /
// / Copyright holder is triAGENS GmbH, Cologne, Germany
// /
// / @author Jan Steemann
// / @author Copyright 2012, triAGENS GmbH, Cologne, Germany
// //////////////////////////////////////////////////////////////////////////////

var db = require('@arangodb').db;
var internal = require('internal');
var jsunity = require('jsunity');
var fs = require('fs');

function runSetup () {
  'use strict';

  var path = fs.join(db._path(), 'collection-999999999999-123456');
  fs.makeDirectory(path);
  fs.write(fs.join(path, '.tmp'), ''); // create .tmp file

  path = fs.join(db._path(), 'collection-999999999998-123456.tmp');
  fs.makeDirectory(path);

  internal.debugSegfault('crashing server');
}

// //////////////////////////////////////////////////////////////////////////////
// / @brief test suite
// //////////////////////////////////////////////////////////////////////////////

function recoverySuite () {
  'use strict';
  jsunity.jsUnity.attachAssertions();

  return {
    setUp: function () {},
    tearDown: function () {},

    // //////////////////////////////////////////////////////////////////////////////
    // / @brief test whether failures when creating collections causes issues
    // //////////////////////////////////////////////////////////////////////////////

    testCreateWithTemp: function () {
      var ids = { };
      db._collections().forEach(function (c) {
        ids[c._id] = 1;
      });

      assertFalse(ids.hasOwnProperty('999999999999'));
      assertFalse(ids.hasOwnProperty('999999999998'));
    }

  };
}

// //////////////////////////////////////////////////////////////////////////////
// / @brief executes the test suite
// //////////////////////////////////////////////////////////////////////////////

function main (argv) {
  'use strict';
  if (argv[1] === 'setup') {
    runSetup();
    return 0;
  } else {
    jsunity.run(recoverySuite);
    return jsunity.done().status ? 0 : 1;
  }
}


text:
const path = require('path');
const getOptions = require('./getOptions');

module.exports = (options, jestRootDir)  => {
  // Override outputName and outputDirectory with outputFile if outputFile is defined
  let output = options.outputFile;
  if (!output) {
    // Set output to use new outputDirectory and fallback on original output
    const outputName = (options.uniqueOutputName === 'true') ? getOptions.getUniqueOutputName(options.outputName) : options.outputName
    output = getOptions.replaceRootDirInOutput(jestRootDir, options.outputDirectory);
    const finalOutput = path.join(output, outputName);
    return finalOutput;
  }

  const finalOutput = getOptions.replaceRootDirInOutput(jestRootDir, output);
  return finalOutput;
};


text:
set -eo pipefail

function help() {
  local -r NAME=$(basename "$0")
  local -r BOLD="\e[1m"
  local -r RESET="\e[0m"
  local -r help=$(cat << EOF
${BOLD}NAME${RESET}
\t$NAME - Build delivery using the ${BOLD}local host system${RESET}.
${BOLD}SYNOPSIS${RESET}
\t$NAME [-h|--help|help] [examples|dotnet|java|python|all|reset]
${BOLD}DESCRIPTION${RESET}
\tBuild Google OR-Tools deliveries.
\tYou ${BOLD}MUST${RESET} define the following variables before running this script:
\t* ORTOOLS_TOKEN: secret use to decrypt keys to sign .Net and Java packages.

${BOLD}OPTIONS${RESET}
\t-h --help: display this help text
\tdotnet: build all .Net packages
\tjava: build all Java packages
\tpython: build all Pyhon packages
\texamples: build examples archives
\tall: build everything (default)

${BOLD}EXAMPLES${RESET}
Using export to define the ${BOLD}ORTOOLS_TOKEN${RESET} env and only building the Java packages:
export ORTOOLS_TOKEN=SECRET
$0 java

note: the 'export ...' should be placed in your bashrc to avoid any leak
of the secret in your bash history
EOF
)
  echo -e "$help"
}

function assert_defined(){
  if [[ -z "${!1}" ]]; then
    >&2 echo "Variable '${1}' must be defined"
    exit 1
  fi
}

# .Net build
function build_dotnet() {
  if echo "${ORTOOLS_BRANCH} ${ORTOOLS_SHA1}" | cmp --silent "${ROOT_DIR}/export/dotnet_build" -; then
    echo "build .Net up to date!" | tee -a build.log
    return 0
  fi

  cd "${ROOT_DIR}" || exit 2
  command -v swig
  command -v swig | xargs echo "swig: " | tee -a build.log
  command -v dotnet
  command -v dotnet | xargs echo "dotnet: " | tee -a build.log

  # Install .Net SNK
  echo -n "Install .Net SNK..." | tee -a build.log
  local OPENSSL_PRG=openssl
  if [[ -x $(command -v openssl11) ]]; then
    OPENSSL_PRG=openssl11
  fi

  $OPENSSL_PRG aes-256-cbc -iter 42 -pass pass:"$ORTOOLS_TOKEN" \
    -in "${RELEASE_DIR}"/or-tools.snk.enc \
    -out "${ROOT_DIR}"/export/or-tools.snk -d
  DOTNET_SNK=export/or-tools.snk
  echo "DONE" | tee -a build.log

  # Clean dotnet
  echo -n "Clean .Net..." | tee -a build.log
  cd "${ROOT_DIR}" || exit 2
  rm -rf "${ROOT_DIR}/temp_dotnet"
  echo "DONE" | tee -a build.log

  echo -n "Build .Net..." | tee -a build.log
  cmake -S. -Btemp_dotnet -DBUILD_SAMPLES=OFF -DBUILD_EXAMPLES=OFF -DBUILD_DOTNET=ON
  cmake --build temp_dotnet -j8 -v
  echo "DONE" | tee -a build.log
  #cmake --build temp_dotnet --target test
  #echo "cmake test: DONE" | tee -a build.log

  # copy nupkg to export
  cp temp_dotnet/dotnet/packages/*nupkg export/
  echo "${ORTOOLS_BRANCH} ${ORTOOLS_SHA1}" > "${ROOT_DIR}/export/dotnet_build"
}

# Java build
function build_java() {
  if echo "${ORTOOLS_BRANCH} ${ORTOOLS_SHA1}" | cmp --silent "${ROOT_DIR}/export/java_build" -; then
    echo "build Java up to date!" | tee -a build.log
    return 0
  fi

  cd "${ROOT_DIR}" || exit 2
  command -v swig
  command -v swig | xargs echo "swig: " | tee -a build.log
  # maven require JAVA_HOME
  if [[ -z "${JAVA_HOME}" ]]; then
    echo "JAVA_HOME: not found !" | tee -a build.log
    exit 1
  else
    echo "JAVA_HOME: ${JAVA_HOME}" | tee -a build.log
    command -v java | xargs echo "java: " | tee -a build.log
    command -v javac | xargs echo "javac: " | tee -a build.log
    command -v jar | xargs echo "jar: " | tee -a build.log
    command -v mvn | xargs echo "mvn: " | tee -a build.log
  fi
  # Maven central need gpg sign and we store the release key encoded using openssl
  local OPENSSL_PRG=openssl
  if [[ -x $(command -v openssl11) ]]; then
    OPENSSL_PRG=openssl11
  fi
  command -v $OPENSSL_PRG | xargs echo "openssl: " | tee -a build.log
  command -v gpg
  command -v gpg | xargs echo "gpg: " | tee -a build.log

  # Install Java GPG
  echo -n "Install Java GPG..." | tee -a build.log
  $OPENSSL_PRG aes-256-cbc -iter 42 -pass pass:"$ORTOOLS_TOKEN" \
  -in tools/release/private-key.gpg.enc \
  -out private-key.gpg -d
  gpg --batch --import private-key.gpg
  # Don't need to trust the key
  #expect -c "spawn gpg --edit-key "corentinl@google.com" trust quit; send \"5\ry\r\"; expect eof"

  # Install the maven settings.xml having the GPG passphrase
  mkdir -p ~/.m2
  $OPENSSL_PRG aes-256-cbc -iter 42 -pass pass:"$ORTOOLS_TOKEN" \
  -in tools/release/settings.xml.enc \
  -out ~/.m2/settings.xml -d
  echo "DONE" | tee -a build.log

  # Clean java
  echo -n "Clean Java..." | tee -a build.log
  cd "${ROOT_DIR}" || exit 2
  rm -rf "${ROOT_DIR}/temp_java"
  echo "DONE" | tee -a build.log

  echo -n "Build Java..." | tee -a build.log

  if [[ ! -v GPG_ARGS ]]; then
    GPG_EXTRA=""
  else
    GPG_EXTRA="-DGPG_ARGS=${GPG_ARGS}"
  fi

  # shellcheck disable=SC2086: cmake fail to parse empty string ""
  cmake -S. -Btemp_java -DBUILD_SAMPLES=OFF -DBUILD_EXAMPLES=OFF \
 -DBUILD_JAVA=ON -DSKIP_GPG=OFF ${GPG_EXTRA}
  cmake --build temp_java -j8 -v
  echo "DONE" | tee -a build.log
  #cmake --build temp_java --target test
  #echo "cmake test: DONE" | tee -a build.log

  # copy jar to export
  if [ ${PLATFORM} == "aarch64" ]; then
    cp temp_java/java/ortools-linux-aarch64/target/*.jar* export/
  else
    cp temp_java/java/ortools-linux-x86-64/target/*.jar* export/
  fi
  cp temp_java/java/ortools-java/target/*.jar* export/
  echo "${ORTOOLS_BRANCH} ${ORTOOLS_SHA1}" > "${ROOT_DIR}/export/java_build"
}

# Python 3
# TODO(user) Use `make --directory tools/docker python` instead
function build_python() {
  if echo "${ORTOOLS_BRANCH} ${ORTOOLS_SHA1}" | cmp --silent "${ROOT_DIR}/export/python_build" -; then
    echo "build python up to date!" | tee -a build.log
    return 0
  fi

  cd "${ROOT_DIR}" || exit 2
  command -v swig
  command -v swig | xargs echo "swig: " | tee -a build.log
  command -v python3 | xargs echo "python3: " | tee -a build.log
  command -v protoc-gen-mypy | xargs echo "protoc-gen-mypy: " | tee -a build.log
  protoc-gen-mypy --version | xargs echo "protoc-gen-mypy version: " | tee -a build.log
  protoc-gen-mypy --version | grep "3\.2\.0"

  echo -n "Cleaning Python 3..." | tee -a build.log
  rm -rf temp_python
  echo "DONE" | tee -a build.log

  echo -n "Build Python 3..." | tee -a build.log
  cmake -S . -B temp_python -DBUILD_SAMPLES=OFF -DBUILD_EXAMPLES=OFF -DBUILD_PYTHON=ON
  cmake --build temp_python -j8 -v
  echo "DONE" | tee -a build.log
  #cmake --build test_python --target test
  #echo "cmake test_python: DONE" | tee -a build.log

  cp temp_python/python/dist/*.whl export/
  echo "${ORTOOLS_BRANCH} ${ORTOOLS_SHA1}" > "${ROOT_DIR}/export/python_build"
}

# Create Archive
function build_archive() {
  if echo "${ORTOOLS_BRANCH} ${ORTOOLS_SHA1}" | cmp --silent "${ROOT_DIR}/export/archive_build" -; then
    echo "build archive up to date!" | tee -a build.log
    return 0
  fi

  # Clean archive
  cd "${ROOT_DIR}" || exit 2
  make clean_archive

  echo -n "Make cpp archive..." | tee -a build.log
  make archive_cpp
  echo "DONE" | tee -a build.log

  echo -n "Make dotnet archive..." | tee -a build.log
  make archive_dotnet
  echo "DONE" | tee -a build.log

  echo -n "Make java archive..." | tee -a build.log
  make archive_java
  echo "DONE" | tee -a build.log

  # move archive to export
  mv or-tools_*.tar.gz export/
  echo "${ORTOOLS_BRANCH} ${ORTOOLS_SHA1}" > "${ROOT_DIR}/export/archive_build"
}

# Build Examples
function build_examples() {
  if echo "${ORTOOLS_BRANCH} ${ORTOOLS_SHA1}" | cmp --silent "${ROOT_DIR}/export/examples_build" -; then
    echo "build examples up to date!" | tee -a build.log
    return 0
  fi

  cd "${ROOT_DIR}" || exit 2

  rm -rf temp ./*.tar.gz
  echo -n "Build examples archives..." | tee -a build.log
  echo -n "  Python examples archive..." | tee -a build.log
  make python_examples_archive UNIX_PYTHON_VER=3
  echo -n "  Java examples archive..." | tee -a build.log
  make java_examples_archive UNIX_PYTHON_VER=3
  echo -n "  .Net examples archive..." | tee -a build.log
  make dotnet_examples_archive UNIX_PYTHON_VER=3
  echo "DONE" | tee -a build.log

  # move example to export/
  mv or-tools_*_examples_*.tar.gz export/
  echo "${ORTOOLS_BRANCH} ${ORTOOLS_SHA1}" > "${ROOT_DIR}/export/examples_build"
}

# Cleaning everything
function reset() {
  echo "Cleaning everything..."

  cd "${ROOT_DIR}" || exit 2

  make clean
  rm -rf temp_dotnet
  rm -rf temp_java
  rm -rf temp_python*
  rm -rf export/
  rm -f ./*.log
  rm -f ./*.whl
  rm -f ./*.tar.gz
  rm ortools.snk
  echo "DONE"
}

# Main
function main() {
  case ${1} in
    -h | --help | help)
      help; exit ;;
  esac

  assert_defined ORTOOLS_TOKEN
  echo "ORTOOLS_TOKEN: FOUND" | tee -a build.log

  local -r ROOT_DIR="$(cd -P -- "$(dirname -- "$0")/../.." && pwd -P)"
  echo "ROOT_DIR: '${ROOT_DIR}'" | tee -a build.log

  local -r RELEASE_DIR="$(cd -P -- "$(dirname -- "$0")" && pwd -P)"
  echo "RELEASE_DIR: '${RELEASE_DIR}'" | tee -a build.log

  (cd "${ROOT_DIR}" && make print-OR_TOOLS_VERSION | tee -a build.log)

  local -r ORTOOLS_BRANCH=$(git rev-parse --abbrev-ref HEAD)
  local -r ORTOOLS_SHA1=$(git rev-parse --verify HEAD)
  local -r PLATFORM=$(uname -m)

  mkdir -p "${ROOT_DIR}/export"

  case ${1} in
    dotnet|java|python|archive|examples)
      "build_$1"
      exit ;;
    reset)
      reset
      exit ;;
    all)
      build_dotnet
      build_java
      #build_python
      build_archive
      #build_examples
      exit ;;
    *)
      >&2 echo "Target '${1}' unknown"
      exit 1
  esac
  exit 0
}

main "${1:-all}"


text:
WPI_CS542_rms
=============
OK, I've created the rms repo for sharing code in github.

This is the CS542 project, which is building a website to manage room usage of WPI.

It will be fun!

Hopefully, we can finish it by the end of this month! Cheers!!!

Congyuan Tang @ Nov.13th 2014


text:
<?php
/**
 * Base class for filtering the subtree for certain node statuses.
 *
 * The simplest way of building a CMSSiteTreeFilter is to create a pagesToBeShown() method that
 * returns an Iterator of maps, each entry containing the 'ID' and 'ParentID' of the pages to be
 * included in the tree.  The reuslt of a DB::query() can be returned directly.
 *
 * If you wish to make a more complex tree, you can overload includeInTree($page) to return true/
 * false depending on whether the given page should be included.  Note that you will need to include
 * parent helper pages yourself.
 *
 * @package cms
 * @subpackage content
 */
abstract class CMSSiteTreeFilter extends Object {

	/**
	 * @var Array Search parameters, mostly properties on {@link SiteTree}.
	 * Caution: Unescaped data.
	 */
	protected $params = array();

	/**
	 * @var Array
	 */
	protected $_cache_ids = null;

	/**
	 * @var Array
	 */
	protected $_cache_expanded = array();

	/**
	 * @var String
	 */
	protected $childrenMethod = null;

	/**
	 * Returns a sorted array of all implementators of CMSSiteTreeFilter, suitable for use in a dropdown.
	 *
	 * @return array
	 */
	public static function get_all_filters() {
		// get all filter instances
		$filters = ClassInfo::subclassesFor('CMSSiteTreeFilter');
		// remove abstract CMSSiteTreeFilter class
		array_shift($filters);
		// add filters to map
		$filterMap = array();

		foreach($filters as $filter) {
			$filterMap[$filter] = call_user_func(array($filter, 'title'));
		}
		// ensure that 'all pages' filter is on top position
		uasort($filterMap,
			create_function('$a,$b', 'return ($a == "CMSSiteTreeFilter_Search") ? 1 : -1;')
		);

		return $filterMap;
	}

	public function __construct($params = null) {
		if($params) $this->params = $params;

		parent::__construct();
	}

	/**
	 * @return String Method on {@link Hierarchy} objects
	 * which is used to traverse into children relationships.
	 */
	public function getChildrenMethod() {
		return $this->childrenMethod;
	}

	/**
	 * @return Array Map of Page IDs to their respective ParentID values.
	 */
	public function pagesIncluded() {}

	/**
	 * Populate the IDs of the pages returned by pagesIncluded(), also including
	 * the necessary parent helper pages.
	 */
	protected function populateIDs() {
		$parents = array();
		$this->_cache_ids = array();

		if($pages = $this->pagesIncluded()) {

			// And keep a record of parents we don't need to get
			// parents of themselves, as well as IDs to mark
			foreach($pages as $pageArr) {
				$parents[$pageArr['ParentID']] = true;
				$this->_cache_ids[$pageArr['ID']] = true;
			}

			while(!empty($parents)) {
				$q = new SQLQuery();
				$q->setSelect(array('"ID"','"ParentID"'))
					->setFrom('"SiteTree"')
					->setWhere('"ID" in ('.implode(',',array_keys($parents)).')');

				$parents = array();

				foreach($q->execute() as $row) {
					if ($row['ParentID']) $parents[$row['ParentID']] = true;
					$this->_cache_ids[$row['ID']] = true;
					$this->_cache_expanded[$row['ID']] = true;
				}
			}
		}
	}

	/**
	 * Returns TRUE if the given page should be included in the tree.
	 * Caution: Does NOT check view permissions on the page.
	 *
	 * @param SiteTree $page
	 * @return Boolean
	 */
	public function isPageIncluded($page) {
		if($this->_cache_ids === NULL) $this->populateIDs();

		return (isset($this->_cache_ids[$page->ID]) && $this->_cache_ids[$page->ID]);
	}

}

/**
 * Works a bit different than the other filters:
 * Shows all pages *including* those deleted from stage and live.
 * It does not filter out pages still existing in the different stages.
 *
 * @package cms
 * @subpackage content
 */
class CMSSiteTreeFilter_DeletedPages extends CMSSiteTreeFilter {

	protected $childrenMethod = "AllHistoricalChildren";

	static public function title() {
		return _t('CMSSiteTreeFilter_DeletedPages.Title', "All pages, including deleted");
	}

	public function pagesIncluded() {
		$ids = array();
		// TODO Not very memory efficient, but usually not very many deleted pages exist
		$pages = Versioned::get_including_deleted('SiteTree');
		if($pages) foreach($pages as $page) {
			$ids[] = array('ID' => $page->ID, 'ParentID' => $page->ParentID);
		}
		return $ids;
	}
}

/**
 * Gets all pages which have changed on stage.
 *
 * @package cms
 * @subpackage content
 */
class CMSSiteTreeFilter_ChangedPages extends CMSSiteTreeFilter {

	static public function title() {
		return _t('CMSSiteTreeFilter_ChangedPages.Title', "Changed pages");
	}

	public function pagesIncluded() {
		$ids = array();
		$q = new SQLQuery();
		$q->setSelect(array('"SiteTree"."ID"','"SiteTree"."ParentID"'))
			->setFrom('"SiteTree"')
			->addLeftJoin('SiteTree_Live', '"SiteTree_Live"."ID" = "SiteTree"."ID"')
			->setWhere('"SiteTree"."Version" > "SiteTree_Live"."Version"');

		foreach($q->execute() as $row) {
			$ids[] = array('ID'=>$row['ID'],'ParentID'=>$row['ParentID']);
		}

		return $ids;
	}
}

/**
 * @package cms
 * @subpackage content
 */
class CMSSiteTreeFilter_Search extends CMSSiteTreeFilter {

	static public function title() {
		return _t('CMSSiteTreeFilter_Search.Title', "All pages");
	}

	/**
	 * Retun an array of maps containing the keys, 'ID' and 'ParentID' for each page to be displayed
	 * in the search.
	 *
	 * @return Array
	 */
	public function pagesIncluded() {
		$sng = singleton('SiteTree');
		$ids = array();

		$query = new DataQuery('SiteTree');
		$query->setQueriedColumns(array('ID', 'ParentID'));

		foreach($this->params as $name => $val) {
			$SQL_val = Convert::raw2sql($val);

			switch($name) {
				case 'Term':
					$query->whereAny(array(
						"\"URLSegment\" LIKE '%$SQL_val%'",
						"\"Title\" LIKE '%$SQL_val%'",
						"\"MenuTitle\" LIKE '%$SQL_val%'",
						"\"Content\" LIKE '%$SQL_val%'"
					));
					break;

				case 'LastEditedFrom':
					$fromDate = new DateField(null, null, $SQL_val);
					$query->where("\"LastEdited\" >= '{$fromDate->dataValue()}'");
					break;

				case 'LastEditedTo':
					$toDate = new DateField(null, null, $SQL_val);
					$query->where("\"LastEdited\" <= '{$toDate->dataValue()}'");
					break;

				case 'ClassName':
					if($val && $val != 'All') {
						$query->where("\"ClassName\" = '$SQL_val'");
					}
					break;

				default:
					if(!empty($val) && $sng->hasDatabaseField($name)) {
						$filter = $sng->dbObject($name)->defaultSearchFilter();
						$filter->setValue($val);
						$filter->apply($query);
					}
			}
		}

		foreach($query->execute() as $row) {
			$ids[] = array('ID' => $row['ID'], 'ParentID' => $row['ParentID']);
		}

		return $ids;
	}
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Media;

namespace Anne.Foundation.Controls
{
    // 参考: http://www.wpftutorial.net/DrawOnPhysicalDevicePixels.html

    public class GuidelineSetBlock : IDisposable
    {
        private readonly DrawingContext _target;

        public GuidelineSetBlock(
            DrawingContext target,
            IEnumerable<double> xGuides = null,
            IEnumerable<double> yGuides = null)
        {
            Debug.Assert(target != null);

            _target = target;

            var guidelines = new GuidelineSet();
            {
                xGuides?.ForEach(g => guidelines.GuidelinesX.Add(g));
                yGuides?.ForEach(g => guidelines.GuidelinesY.Add(g));
            }

            target.PushGuidelineSet(guidelines);
        }

        public GuidelineSetBlock(
            DrawingContext target,
            Rect rect,
            double rectPenWidth = 0,
            IEnumerable<double> xGuides = null,
            IEnumerable<double> yGuides = null)
        {
            Debug.Assert(target != null);

            _target = target;

            var guidelines = new GuidelineSet();
            {
                guidelines.GuidelinesX.Add(rect.Left + rectPenWidth*0.5);
                guidelines.GuidelinesX.Add(rect.Right + rectPenWidth*0.5);
                guidelines.GuidelinesY.Add(rect.Top + rectPenWidth*0.5);
                guidelines.GuidelinesY.Add(rect.Bottom + rectPenWidth*0.5);

                xGuides?.ForEach(g => guidelines.GuidelinesX.Add(g));
                yGuides?.ForEach(g => guidelines.GuidelinesY.Add(g));
            }

            target.PushGuidelineSet(guidelines);
        }

        public void Dispose()
        {
            _target.Pop();
        }
    }
}


text:
module Util.Text where

import Prelude
import qualified Data.Text as T

-- | Joins a list of texts with the given text separating them.
joinWith :: T.Text -> [T.Text] -> T.Text
joinWith sep = T.concat . map (`T.append` sep)

-- | Similar to joinWith, but doesn't add the separator at the end.
joinWith' :: T.Text -> [T.Text] -> T.Text
joinWith' sep = T.dropEnd (T.length sep) . T.concat . map (`T.append` sep)


text:
import { Room } from "matrix-js-sdk/src/models/room";
import { MatrixEventEvent, MatrixEvent, MatrixClient } from "matrix-js-sdk/src/matrix";

import { stubClient } from "../../test-utils";
import { MatrixClientPeg } from "../../../src/MatrixClientPeg";
import { RoomNotificationState } from "../../../src/stores/notifications/RoomNotificationState";
import * as testUtils from "../../test-utils";
import { NotificationStateEvents } from "../../../src/stores/notifications/NotificationState";

describe("RoomNotificationState", () => {
    let testRoom: Room;
    let client: MatrixClient;

    beforeEach(() => {
        stubClient();
        client = MatrixClientPeg.get();
        testRoom = testUtils.mkStubRoom("$aroomid", "Test room", client);
    });

    it("Updates on event decryption", () => {
        const roomNotifState = new RoomNotificationState(testRoom as any as Room);
        const listener = jest.fn();
        roomNotifState.addListener(NotificationStateEvents.Update, listener);
        const testEvent = {
            getRoomId: () => testRoom.roomId,
        } as unknown as MatrixEvent;
        testRoom.getUnreadNotificationCount = jest.fn().mockReturnValue(1);
        client.emit(MatrixEventEvent.Decrypted, testEvent);
        expect(listener).toHaveBeenCalled();
    });

    it("removes listeners", () => {
        const roomNotifState = new RoomNotificationState(testRoom as any as Room);
        expect(() => roomNotifState.destroy()).not.toThrow();
    });
});


text:
package memento;

import java.awt.event.ActionListener;

public class BtnPrevious {
	Mediator med;

	BtnPrevious(ActionListener al, Mediator m) {
		super("Previous");
		addActionListener(al);
		med = m;
		med.registerPrevious(this);
	}

	public void execute() {
		med.previous();
	}
}


text:
"""HTTP authentication module.

"""

import logging
import re
import base64
import binascii

from io import StringIO
from hashlib import md5

from ganeti import compat
from ganeti import http
from ganeti import utils

# Digest types from RFC2617
HTTP_BASIC_AUTH = "Basic"
HTTP_DIGEST_AUTH = "Digest"

# Not exactly as described in RFC2616, section 2.2, but good enough
_NOQUOTE = re.compile(r"^[-_a-z0-9]+$", re.I)

def _FormatAuthHeader(scheme, params):
  """Formats WWW-Authentication header value as per RFC2617, section 1.2

  @type scheme: str
  @param scheme: Authentication scheme
  @type params: dict
  @param params: Additional parameters
  @rtype: str
  @return: Formatted header value

  """
  buf = StringIO()

  buf.write(scheme)

  for name, value in params.items():
    buf.write(" ")
    buf.write(name)
    buf.write("=")
    if _NOQUOTE.match(value):
      buf.write(value)
    else:
      buf.write("\"")
      # TODO: Better quoting
      buf.write(value.replace("\"", "\\\""))
      buf.write("\"")

  return buf.getvalue()

class HttpServerRequestAuthentication(object):
  # Default authentication realm
  AUTH_REALM = "Unspecified"

  # Schemes for passwords
  _CLEARTEXT_SCHEME = "{CLEARTEXT}"
  _HA1_SCHEME = "{HA1}"

  def GetAuthRealm(self, req):
    """Returns the authentication realm for a request.

    May be overridden by a subclass, which then can return different realms for
    different paths.

    @type req: L{http.server._HttpServerRequest}
    @param req: HTTP request context
    @rtype: string
    @return: Authentication realm

    """
    # today we don't have per-request filtering, but we might want to
    # add it in the future
    # pylint: disable=W0613
    return self.AUTH_REALM

  def AuthenticationRequired(self, req):
    """Determines whether authentication is required for a request.

    To enable authentication, override this function in a subclass and return
    C{True}. L{AUTH_REALM} must be set.

    @type req: L{http.server._HttpServerRequest}
    @param req: HTTP request context

    """
    # Unused argument, method could be a function
    # pylint: disable=W0613,R0201
    return False

  def PreHandleRequest(self, req):
    """Called before a request is handled.

    @type req: L{http.server._HttpServerRequest}
    @param req: HTTP request context

    """
    # Authentication not required, and no credentials given?
    if not (self.AuthenticationRequired(req) or
            (req.request_headers and
             http.HTTP_AUTHORIZATION in req.request_headers)):
      return

    realm = self.GetAuthRealm(req)

    if not realm:
      raise AssertionError("No authentication realm")

    # Check "Authorization" header
    if self._CheckAuthorization(req):
      # User successfully authenticated
      return

    # Send 401 Unauthorized response
    params = {
      "realm": realm,
      }

    # TODO: Support for Digest authentication (RFC2617, section 3).
    # TODO: Support for more than one WWW-Authenticate header with the same
    # response (RFC2617, section 4.6).
    headers = {
      http.HTTP_WWW_AUTHENTICATE: _FormatAuthHeader(HTTP_BASIC_AUTH, params),
      }

    raise http.HttpUnauthorized(headers=headers)

  def _CheckAuthorization(self, req):
    """Checks 'Authorization' header sent by client.

    @type req: L{http.server._HttpServerRequest}
    @param req: HTTP request context
    @rtype: bool
    @return: Whether user is allowed to execute request

    """
    credentials = req.request_headers.get(http.HTTP_AUTHORIZATION, None)
    if not credentials:
      return False

    # Extract scheme
    parts = credentials.strip().split(None, 2)
    if len(parts) < 1:
      # Missing scheme
      return False

    # RFC2617, section 1.2: "[...] It uses an extensible, case-insensitive
    # token to identify the authentication scheme [...]"
    scheme = parts[0].lower()

    if scheme == HTTP_BASIC_AUTH.lower():
      # Do basic authentication
      if len(parts) < 2:
        raise http.HttpBadRequest(message=("Basic authentication requires"
                                           " credentials"))
      return self._CheckBasicAuthorization(req, parts[1])

    elif scheme == HTTP_DIGEST_AUTH.lower():
      # TODO: Implement digest authentication
      # RFC2617, section 3.3: "Note that the HTTP server does not actually need
      # to know the user's cleartext password. As long as H(A1) is available to
      # the server, the validity of an Authorization header may be verified."
      pass

    # Unsupported authentication scheme
    return False

  def _CheckBasicAuthorization(self, req, in_data):
    """Checks credentials sent for basic authentication.

    @type req: L{http.server._HttpServerRequest}
    @param req: HTTP request context
    @type in_data: str
    @param in_data: Username and password encoded as Base64
    @rtype: bool
    @return: Whether user is allowed to execute request

    """
    try:
      creds = base64.b64decode(in_data.encode("ascii")).decode("ascii")
    except (TypeError, binascii.Error, UnicodeError):
      logging.exception("Error when decoding Basic authentication credentials")
      return False

    if ":" not in creds:
      return False

    (user, password) = creds.split(":", 1)

    return self.Authenticate(req, user, password)

  def Authenticate(self, req, user, password):
    """Checks the password for a user.

    This function MUST be overridden by a subclass.

    """
    raise NotImplementedError()

  def VerifyBasicAuthPassword(self, req, username, password, expected):
    """Checks the password for basic authentication.

    As long as they don't start with an opening brace ("E{lb}"), old passwords
    are supported. A new scheme uses H(A1) from RFC2617, where H is MD5 and A1
    consists of the username, the authentication realm and the actual password.

    @type req: L{http.server._HttpServerRequest}
    @param req: HTTP request context
    @type username: string
    @param username: Username from HTTP headers
    @type password: string
    @param password: Password from HTTP headers
    @type expected: string
    @param expected: Expected password with optional scheme prefix (e.g. from
                     users file)

    """
    # Backwards compatibility for old-style passwords without a scheme
    if not expected.startswith("{"):
      expected = self._CLEARTEXT_SCHEME + expected

    # Check again, just to be sure
    if not expected.startswith("{"):
      raise AssertionError("Invalid scheme")

    scheme_end_idx = expected.find("}", 1)

    # Ensure scheme has a length of at least one character
    if scheme_end_idx <= 1:
      logging.warning("Invalid scheme in password for user '%s'", username)
      return False

    scheme = expected[:scheme_end_idx + 1].upper()
    expected_password = expected[scheme_end_idx + 1:]

    # Good old plain text password
    if scheme == self._CLEARTEXT_SCHEME:
      return password == expected_password

    # H(A1) as described in RFC2617
    if scheme == self._HA1_SCHEME:
      realm = self.GetAuthRealm(req)
      if not realm:
        # There can not be a valid password for this case
        raise AssertionError("No authentication realm")

      digest = "%s:%s:%s" % (username, realm, password)
      expha1 = md5(digest.encode("ascii"))

      return (expected_password.lower() == expha1.hexdigest().lower())

    logging.warning("Unknown scheme '%s' in password for user '%s'",
                    scheme, username)

    return False

class PasswordFileUser(object):
  """Data structure for users from password file.

  """
  def __init__(self, name, password, options):
    self.name = name
    self.password = password
    self.options = options

def ParsePasswordFile(contents):
  """Parses the contents of a password file.

  Lines in the password file are of the following format::

      <username> <password> [options]

  Fields are separated by whitespace. Username and password are mandatory,
  options are optional and separated by comma (','). Empty lines and comments
  ('#') are ignored.

  @type contents: str
  @param contents: Contents of password file
  @rtype: dict
  @return: Dictionary containing L{PasswordFileUser} instances

  """
  users = {}

  for line in utils.FilterEmptyLinesAndComments(contents):
    parts = line.split(None, 2)
    if len(parts) < 2:
      # Invalid line
      # TODO: Return line number from FilterEmptyLinesAndComments
      logging.warning("Ignoring non-comment line with less than two fields")
      continue

    name = parts[0]
    password = parts[1]

    # Extract options
    options = []
    if len(parts) >= 3:
      for part in parts[2].split(","):
        options.append(part.strip())
    else:
      logging.warning("Ignoring values for user '%s': %s", name, parts[3:])

    users[name] = PasswordFileUser(name, password, options)

  return users


text:
package mem

import (
	"testing"
	"time"
)

func TestFileDataNameRace(t *testing.T) {
	t.Parallel()
	const someName = "someName"
	const someOtherName = "someOtherName"
	d := FileData{
		name: someName,
	}

	if d.Name() != someName {
		t.Errorf("Failed to read correct Name, was %v", d.Name())
	}

	ChangeFileName(&d, someOtherName)
	if d.Name() != someOtherName {
		t.Errorf("Failed to set Name, was %v", d.Name())
	}

	go func() {
		ChangeFileName(&d, someName)
	}()

	if d.Name() != someName && d.Name() != someOtherName {
		t.Errorf("Failed to read either Name, was %v", d.Name())
	}
}

func TestFileDataModTimeRace(t *testing.T) {
	t.Parallel()
	someTime := time.Now()
	someOtherTime := someTime.Add(1 * time.Minute)

	d := FileData{
		modtime: someTime,
	}

	s := FileInfo{
		FileData: &d,
	}

	if s.ModTime() != someTime {
		t.Errorf("Failed to read correct value, was %v", s.ModTime())
	}

	SetModTime(&d, someOtherTime)
	if s.ModTime() != someOtherTime {
		t.Errorf("Failed to set ModTime, was %v", s.ModTime())
	}

	go func() {
		SetModTime(&d, someTime)
	}()

	if s.ModTime() != someTime && s.ModTime() != someOtherTime {
		t.Errorf("Failed to read either modtime, was %v", s.ModTime())
	}
}

func TestFileDataModeRace(t *testing.T) {
	t.Parallel()
	const someMode = 0777
	const someOtherMode = 0660

	d := FileData{
		mode: someMode,
	}

	s := FileInfo{
		FileData: &d,
	}

	if s.Mode() != someMode {
		t.Errorf("Failed to read correct value, was %v", s.Mode())
	}

	SetMode(&d, someOtherMode)
	if s.Mode() != someOtherMode {
		t.Errorf("Failed to set Mode, was %v", s.Mode())
	}

	go func() {
		SetMode(&d, someMode)
	}()

	if s.Mode() != someMode && s.Mode() != someOtherMode {
		t.Errorf("Failed to read either mode, was %v", s.Mode())
	}
}

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

	d := FileData{
		dir: true,
	}

	s := FileInfo{
		FileData: &d,
	}

	if s.IsDir() != true {
		t.Errorf("Failed to read correct value, was %v", s.IsDir())
	}

	go func() {
		s.Lock()
		d.dir = false
		s.Unlock()
	}()

	//just logging the value to trigger a read:
	t.Logf("Value is %v", s.IsDir())
}

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

	const someData = "Hello"
	const someOtherDataSize = "Hello World"

	d := FileData{
		data: []byte(someData),
		dir:  false,
	}

	s := FileInfo{
		FileData: &d,
	}

	if s.Size() != int64(len(someData)) {
		t.Errorf("Failed to read correct value, was %v", s.Size())
	}

	go func() {
		s.Lock()
		d.data = []byte(someOtherDataSize)
		s.Unlock()
	}()

	//just logging the value to trigger a read:
	t.Logf("Value is %v", s.Size())

	//Testing the Dir size case
	d.dir = true
	if s.Size() != int64(42) {
		t.Errorf("Failed to read correct value for dir, was %v", s.Size())
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Using as: D10V-Size</title>

<meta name="description" content="Using as: D10V-Size">
<meta name="keywords" content="Using as: D10V-Size">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="AS-Index.html#AS-Index" rel="index" title="AS Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="D10V_002dSyntax.html#D10V_002dSyntax" rel="up" title="D10V-Syntax">
<link href="D10V_002dSubs.html#D10V_002dSubs" rel="next" title="D10V-Subs">
<link href="D10V_002dSyntax.html#D10V_002dSyntax" rel="prev" title="D10V-Syntax">

Next: D10V-Subs, Up: D10V-Syntax   [Contents][Index]

9.9.2.1 Size Modifiers

The D10V version of as uses the instruction names in the D10V
Architecture Manual.  However, the names in the manual are sometimes ambiguous.
There are instruction names that can assemble to a short or long form opcode.
How does the assembler pick the correct form?  as will always pick the
smallest form if it can.  When dealing with a symbol that is not defined yet when a
line is being assembled, it will always use the long form.  If you need to force the
assembler to use either the short or long form of the instruction, you can append
either ‘<samp>.s</samp>’ (short) or ‘<samp>.l</samp>’ (long) to it.  For example, if you are writing
an assembly program and you want to do a branch to a symbol that is defined later
in your program, you can write ‘<samp>bra.s   foo</samp>’.
Objdump and GDB will always append ‘<samp>.s</samp>’ or ‘<samp>.l</samp>’ to instructions which
have both short and long forms.


text:
import { Component, Input, Output, EventEmitter, Inject, forwardRef, OnChanges, ChangeDetectionStrategy } from '@angular/core';
import { SearchComponent } from '../../../+search/search.component';
import { DateRange } from '../../utilities/dateRange';

@Component({
  moduleId: module.id,
  selector: 'breadcrumb-component',
  templateUrl: 'wz.breadcrumb.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})

export class WzBreadcrumbComponent implements OnChanges {
  @Input() filters: any;
  @Input() loading: boolean;
  @Output() apply = new EventEmitter();
  @Output() clear = new EventEmitter();
  public searchComponent: SearchComponent;
  public activeFilters: any;

  constructor( @Inject(forwardRef(() => SearchComponent)) searchComponent: SearchComponent) {
    this.searchComponent = searchComponent;
    this.activeFilters = [];
  }

  public clearFilter(filter: any) {
    this.searchComponent.applyFilter(filter.filterId);
  }

  ngOnChanges(changes: any) {
    if (changes.filters && changes.filters.currentValue) {
      this.activeFilters = [];
      this.getFilters(this.filters);
    }
  }

  public clearFilters() {
    this.searchComponent.clearFilters();
  }

  public formattedValueFor(filter: any): string {
    if (filter.type === 'DateRange') {
      const dateRange: DateRange = new DateRange();
      dateRange.set('start', filter.filterValue);
      dateRange.set('end', filter.filterValue);
      return dateRange.toHumanString();
    }

    return filter.filterValue;
  }

  private getFilters(filter: any) {
    if (filter.subFilters) {
      for (var l of filter.subFilters) this.getFilters(l);
      return filter;
    } else {
      if (filter.active) this.activeFilters.push(filter);
      return filter;
    }
  }
}


text:
var path=require('path');
var cat=require(path.resolve(__dirname,'./libs/cat.js'));
module.exports=cat;


text:
using System;

namespace xcite.logging {
    /// <summary> Describes the data to log. </summary>
    public struct LogData {

        /// <summary> Logger name </summary>
        public string name;

        /// <summary> Log level </summary>
        public ELogLevel level;

        /// <summary> Log value </summary>
        public string value;

        /// <summary> Log excecption </summary>
        public Exception exception;

    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Verh. zool. -bot. Ges. Wein (1861)

#### Original name
Agaricus sainsonii Lév., 1842

### Remarks
null


text: var app = angular.module("calendarModule", []);


text:
package br.unb.dali.models.agg.exceptions;

public class ModelSemanticsVerificationException extends AggModelConstructionException {
	private static final long serialVersionUID = 4016888976223953531L;

	public ModelSemanticsVerificationException(String description) {
		super(description);
	}
}


text:
class RenameContestSourceColumnToProblems < ActiveRecord::Migration[5.0]
  def change
    rename_column :problems, :contest_source, :problem_source
  end
end


text:
from fabric.api import task

import six
if six.PY3:
    from . import system, db
else:
    import system, db

@task
def deploy():
    pass

@task
def build_docs():
    pass


text:
class Alfi::Providers::Offline < Alfi::Providers::Base
  def initialize(query, search_type)
    @query = query
  end

  def call
    google_libs = [
      'com.android.support:appcompat-v7',
      'com.android.support:cardview-v7',
      'com.android.support:gridlayout-v7',
      'com.android.support:leanback-v17',
      'com.android.support:mediarouter-v7',
      'com.android.support:palette-v7',
      'com.android.support:support-annotations',
      'com.android.support:support-v4',
      'com.android.support:support-v13',
      'com.google.android.gms:play-services-wearable',
      'com.google.android.gms:play-services',
      'com.android.support:recyclerview-v7'
    ]
    results = google_libs.map { |lib| "#{lib}:+" if lib.include?(@query) }.compact
    return unless results.size > 0
    add_to_list '  # Google'
    results.each { |library| add_repo_to_list(library) }
  end
end


text:
package org.wso2.carbon.event.flow.internal;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.event.processor.core.EventProcessorService;
import org.wso2.carbon.event.publisher.core.EventPublisherService;
import org.wso2.carbon.event.receiver.core.EventReceiverService;
import org.wso2.carbon.event.stream.core.EventStreamService;

/**
 * @scr.component name="eventFlowService.component" immediate="true"
 * @scr.reference name="eventStreamManager.service"
 * interface="org.wso2.carbon.event.stream.core.EventStreamService" cardinality="1..1"
 * policy="dynamic" bind="setEventStreamService" unbind="unsetEventStreamService"
 * @scr.reference name="eventProcessor.service"
 * interface="org.wso2.carbon.event.processor.core.EventProcessorService" cardinality="1..1"
 * policy="dynamic" bind="setEventProcessorService" unbind="unsetEventProcessorService"
 * @scr.reference name="eventReceiver.service"
 * interface="org.wso2.carbon.event.receiver.core.EventReceiverService" cardinality="1..1"
 * policy="dynamic" bind="setEventReceiverService" unbind="unsetEventReceiverService"
 * @scr.reference name="eventPublisher.service"
 * interface="org.wso2.carbon.event.publisher.core.EventPublisherService" cardinality="1..1"
 * policy="dynamic" bind="setEventPublisherService" unbind="unsetEventPublisherService"
 */
public class EventFlowServiceDS {
    private static final Log log = LogFactory.getLog(EventFlowServiceDS.class);

    protected void activate(ComponentContext context) {

        if (log.isDebugEnabled()) {
            log.debug("Successfully deployed Event Flow Service.");
        }
    }

    protected void setEventStreamService(EventStreamService eventStreamService) {
        EventFlowServiceValueHolder.registerEventStreamService(eventStreamService);
    }

    protected void unsetEventStreamService(EventStreamService eventStreamService) {
        EventFlowServiceValueHolder.registerEventStreamService(null);
    }
    protected void setEventProcessorService(EventProcessorService eventProcessorService) {
        EventFlowServiceValueHolder.registerEventProcessorService(eventProcessorService);
    }

    protected void unsetEventProcessorService(EventProcessorService eventProcessorService) {
        EventFlowServiceValueHolder.registerEventProcessorService(null);
    }

    protected void setEventReceiverService(EventReceiverService eventReceiverService) {
        EventFlowServiceValueHolder.registerEventReceiverService(eventReceiverService);
    }

    protected void unsetEventReceiverService(EventReceiverService eventReceiverService) {
        EventFlowServiceValueHolder.registerEventReceiverService(null);
    }

    protected void setEventPublisherService(EventPublisherService eventPublisherService) {
        EventFlowServiceValueHolder.registerEventPublisherService(eventPublisherService);
    }

    protected void unsetEventPublisherService(EventPublisherService eventPublisherService) {
        EventFlowServiceValueHolder.registerEventPublisherService(null);
    }
}


text:
from __future__ import division

import json
import os
import re
from collections import OrderedDict, defaultdict

from six import iteritems

from ..constants import ServiceCheck
from ..utils.common import ensure_unicode, to_native_string
from .common import HistogramBucketStub, MetricStub, ServiceCheckStub
from .similar import build_similar_elements_msg

METRIC_REPLACEMENT = re.compile(r"([^a-zA-Z0-9_.]+)|(^[^a-zA-Z]+)")
METRIC_DOTUNDERSCORE_CLEANUP = re.compile(r"_*\._*")

def normalize_tags(tags, sort=False):
    # The base class ensures the Agent receives bytes in PY2 and unicode in PY3.
    # This function makes sure strings are compared with the same type.
    if tags:
        if sort:
            return sorted(to_native_string(tag) for tag in tags)
        else:
            return [to_native_string(tag) for tag in tags]
    return tags

def backend_normalize_metric_name(metric_name):
    """
    Normalize a metric name for the backend to understand it.
    This is the same metric that is used to validate the metadata.csv file
    """
    metric_name = METRIC_REPLACEMENT.sub("_", metric_name)
    return METRIC_DOTUNDERSCORE_CLEANUP.sub(".", metric_name).strip("_")

def check_tag_names(metric, tags):
    if tags and not os.environ.get('DDEV_SKIP_GENERIC_TAGS_CHECK'):
        try:
            from datadog_checks.base.utils.tagging import GENERIC_TAGS
        except ImportError:
            GENERIC_TAGS = []

        for tag in tags:
            tag_name = tag.split(':')[0]
            if tag_name in GENERIC_TAGS:
                raise Exception(
                    "Metric {} was submitted with a forbidden tag: {}. Please rename this tag, or skip "
                    "the tag validation with DDEV_SKIP_GENERIC_TAGS_CHECK environment variable.".format(
                        metric, tag_name
                    )
                )

class AggregatorStub(object):
    """
    This implements the methods defined by the Agent's
    [C bindings](https://github.com/DataDog/datadog-agent/blob/master/rtloader/common/builtins/aggregator.c)
    which in turn call the
    [Go backend](https://github.com/DataDog/datadog-agent/blob/master/pkg/collector/python/aggregator.go).

    It also provides utility methods for test assertions.
    """

    # Replicate the Enum we have on the Agent
    METRIC_ENUM_MAP = OrderedDict(
        (
            ('gauge', 0),
            ('rate', 1),
            ('count', 2),
            ('monotonic_count', 3),
            ('counter', 4),
            ('histogram', 5),
            ('historate', 6),
        )
    )
    METRIC_ENUM_MAP_REV = {v: k for k, v in iteritems(METRIC_ENUM_MAP)}
    GAUGE, RATE, COUNT, MONOTONIC_COUNT, COUNTER, HISTOGRAM, HISTORATE = list(METRIC_ENUM_MAP.values())
    AGGREGATE_TYPES = {COUNT, COUNTER}
    IGNORED_METRICS = {'datadog.agent.profile.memory.check_run_alloc'}
    METRIC_TYPE_SUBMISSION_TO_BACKEND_MAP = {
        'gauge': 'gauge',
        'rate': 'gauge',
        'count': 'count',
        'monotonic_count': 'count',
        'counter': 'rate',
        'histogram': 'rate',  # Checking .count only, the other are gauges
        'historate': 'rate',  # Checking .count only, the other are gauges
    }

    def __init__(self):
        self.reset()

    @classmethod
    def is_aggregate(cls, mtype):
        return mtype in cls.AGGREGATE_TYPES

    @classmethod
    def ignore_metric(cls, name):
        return name in cls.IGNORED_METRICS

    def submit_metric(self, check, check_id, mtype, name, value, tags, hostname, flush_first_value):
        check_tag_names(name, tags)
        if not self.ignore_metric(name):
            self._metrics[name].append(MetricStub(name, mtype, value, tags, hostname, None, flush_first_value))

    def submit_metric_e2e(
        self, check, check_id, mtype, name, value, tags, hostname, device=None, flush_first_value=False
    ):
        check_tag_names(name, tags)
        # Device is only present in metrics read from the real agent in e2e tests. Normally it is submitted as a tag
        if not self.ignore_metric(name):
            self._metrics[name].append(MetricStub(name, mtype, value, tags, hostname, device, flush_first_value))

    def submit_service_check(self, check, check_id, name, status, tags, hostname, message):
        if status == ServiceCheck.OK and message:
            raise Exception("Expected empty message on OK service check")

        check_tag_names(name, tags)
        self._service_checks[name].append(ServiceCheckStub(check_id, name, status, tags, hostname, message))

    def submit_event(self, check, check_id, event):
        self._events.append(event)

    def submit_event_platform_event(self, check, check_id, raw_event, event_type):
        self._event_platform_events[event_type].append(raw_event)

    def submit_histogram_bucket(
        self,
        check,
        check_id,
        name,
        value,
        lower_bound,
        upper_bound,
        monotonic,
        hostname,
        tags,
        flush_first_value=False,
    ):
        check_tag_names(name, tags)
        self._histogram_buckets[name].append(
            HistogramBucketStub(name, value, lower_bound, upper_bound, monotonic, hostname, tags, flush_first_value)
        )

    def metrics(self, name):
        """
        Return the metrics received under the given name
        """
        return [
            MetricStub(
                ensure_unicode(stub.name),
                stub.type,
                stub.value,
                normalize_tags(stub.tags),
                ensure_unicode(stub.hostname),
                stub.device,
                stub.flush_first_value,
            )
            for stub in self._metrics.get(to_native_string(name), [])
        ]

    def service_checks(self, name):
        """
        Return the service checks received under the given name
        """
        return [
            ServiceCheckStub(
                ensure_unicode(stub.check_id),
                ensure_unicode(stub.name),
                stub.status,
                normalize_tags(stub.tags),
                ensure_unicode(stub.hostname),
                ensure_unicode(stub.message),
            )
            for stub in self._service_checks.get(to_native_string(name), [])
        ]

    @property
    def events(self):
        """
        Return all events
        """
        return self._events

    def get_event_platform_events(self, event_type, parse_json=True):
        """
        Return all event platform events for the event_type
        """
        return [json.loads(e) if parse_json else e for e in self._event_platform_events[event_type]]

    def histogram_bucket(self, name):
        """
        Return the histogram buckets received under the given name
        """
        return [
            HistogramBucketStub(
                ensure_unicode(stub.name),
                stub.value,
                stub.lower_bound,
                stub.upper_bound,
                stub.monotonic,
                ensure_unicode(stub.hostname),
                normalize_tags(stub.tags),
                stub.flush_first_value,
            )
            for stub in self._histogram_buckets.get(to_native_string(name), [])
        ]

    def assert_metric_has_tag(self, metric_name, tag, count=None, at_least=1):
        """
        Assert a metric is tagged with tag
        """
        self._asserted.add(metric_name)

        candidates = []
        candidates_with_tag = []
        for metric in self.metrics(metric_name):
            candidates.append(metric)
            if tag in metric.tags:
                candidates_with_tag.append(metric)

        if candidates_with_tag:  # The metric was found with the tag but not enough times
            msg = "The metric '{}' with tag '{}' was only found {}/{} times".format(metric_name, tag, count, at_least)
        elif candidates:
            msg = (
                "The metric '{}' was found but not with the tag '{}'.\n".format(metric_name, tag)
                + "Similar submitted:\n"
                + "\n".join(["     {}".format(m) for m in candidates])
            )
        else:
            expected_stub = MetricStub(metric_name, type=None, value=None, tags=[tag], hostname=None, device=None)
            msg = "Metric '{}' not found".format(metric_name)
            msg = "{}\n{}".format(msg, build_similar_elements_msg(expected_stub, self._metrics))

        if count is not None:
            assert len(candidates_with_tag) == count, msg
        else:
            assert len(candidates_with_tag) >= at_least, msg

    # Potential kwargs: aggregation_key, alert_type, event_type,
    # msg_title, source_type_name
    def assert_event(self, msg_text, count=None, at_least=1, exact_match=True, tags=None, **kwargs):
        candidates = []
        for e in self.events:
            if exact_match and msg_text != e['msg_text'] or msg_text not in e['msg_text']:
                continue
            if tags and set(tags) != set(e['tags']):
                continue
            for name, value in iteritems(kwargs):
                if e[name] != value:
                    break
            else:
                candidates.append(e)

        msg = "Candidates size assertion for `{}`, count: {}, at_least: {}) failed".format(msg_text, count, at_least)
        if count is not None:
            assert len(candidates) == count, msg
        else:
            assert len(candidates) >= at_least, msg

    def assert_histogram_bucket(
        self,
        name,
        value,
        lower_bound,
        upper_bound,
        monotonic,
        hostname,
        tags,
        count=None,
        at_least=1,
        flush_first_value=None,
    ):
        expected_tags = normalize_tags(tags, sort=True)

        candidates = []
        for bucket in self.histogram_bucket(name):
            if value is not None and value != bucket.value:
                continue

            if expected_tags and expected_tags != sorted(bucket.tags):
                continue

            if hostname and hostname != bucket.hostname:
                continue

            if monotonic != bucket.monotonic:
                continue

            if flush_first_value is not None and flush_first_value != bucket.flush_first_value:
                continue

            candidates.append(bucket)

        expected_bucket = HistogramBucketStub(
            name, value, lower_bound, upper_bound, monotonic, hostname, tags, flush_first_value
        )

        if count is not None:
            msg = "Needed exactly {} candidates for '{}', got {}".format(count, name, len(candidates))
            condition = len(candidates) == count
        else:
            msg = "Needed at least {} candidates for '{}', got {}".format(at_least, name, len(candidates))
            condition = len(candidates) >= at_least
        self._assert(
            condition=condition, msg=msg, expected_stub=expected_bucket, submitted_elements=self._histogram_buckets
        )

    def assert_metric(
        self,
        name,
        value=None,
        tags=None,
        count=None,
        at_least=1,
        hostname=None,
        metric_type=None,
        device=None,
        flush_first_value=None,
    ):
        """
        Assert a metric was processed by this stub
        """

        self._asserted.add(name)
        expected_tags = normalize_tags(tags, sort=True)

        candidates = []
        for metric in self.metrics(name):
            if value is not None and not self.is_aggregate(metric.type) and value != metric.value:
                continue

            if expected_tags and expected_tags != sorted(metric.tags):
                continue

            if hostname is not None and hostname != metric.hostname:
                continue

            if metric_type is not None and metric_type != metric.type:
                continue

            if device is not None and device != metric.device:
                continue

            if flush_first_value is not None and flush_first_value != metric.flush_first_value:
                continue

            candidates.append(metric)

        expected_metric = MetricStub(name, metric_type, value, expected_tags, hostname, device, flush_first_value)

        if value is not None and candidates and all(self.is_aggregate(m.type) for m in candidates):
            got = sum(m.value for m in candidates)
            msg = "Expected count value for '{}': {}, got {}".format(name, value, got)
            condition = value == got
        elif count is not None:
            msg = "Needed exactly {} candidates for '{}', got {}".format(count, name, len(candidates))
            condition = len(candidates) == count
        else:
            msg = "Needed at least {} candidates for '{}', got {}".format(at_least, name, len(candidates))
            condition = len(candidates) >= at_least
        self._assert(condition, msg=msg, expected_stub=expected_metric, submitted_elements=self._metrics)

    def assert_service_check(self, name, status=None, tags=None, count=None, at_least=1, hostname=None, message=None):
        """
        Assert a service check was processed by this stub
        """
        tags = normalize_tags(tags, sort=True)
        candidates = []
        for sc in self.service_checks(name):
            if status is not None and status != sc.status:
                continue

            if tags and tags != sorted(sc.tags):
                continue

            if hostname is not None and hostname != sc.hostname:
                continue

            if message is not None and message != sc.message:
                continue

            candidates.append(sc)

        expected_service_check = ServiceCheckStub(
            None, name=name, status=status, tags=tags, hostname=hostname, message=message
        )

        if count is not None:
            msg = "Needed exactly {} candidates for '{}', got {}".format(count, name, len(candidates))
            condition = len(candidates) == count
        else:
            msg = "Needed at least {} candidates for '{}', got {}".format(at_least, name, len(candidates))
            condition = len(candidates) >= at_least
        self._assert(
            condition=condition, msg=msg, expected_stub=expected_service_check, submitted_elements=self._service_checks
        )

    @staticmethod
    def _assert(condition, msg, expected_stub, submitted_elements):
        new_msg = msg
        if not condition:  # It's costly to build the message with similar metrics, so it's built only on failure.
            new_msg = "{}\n{}".format(msg, build_similar_elements_msg(expected_stub, submitted_elements))
        assert condition, new_msg

    def assert_all_metrics_covered(self):
        # use `condition` to avoid building the `msg` if not needed
        condition = self.metrics_asserted_pct >= 100.0
        msg = ''
        if not condition:
            prefix = '\n\t- '
            msg = 'Some metrics are collected but not asserted:'
            msg += '\nAsserted Metrics:{}{}'.format(prefix, prefix.join(sorted(self._asserted)))
            msg += '\nFound metrics that are not asserted:{}{}'.format(prefix, prefix.join(sorted(self.not_asserted())))
        assert condition, msg

    def assert_metrics_using_metadata(
        self, metadata_metrics, check_metric_type=True, check_submission_type=False, exclude=None
    ):
        """
        Assert metrics using metadata.csv

        Checking type: By default we are asserting the in-app metric type (`check_submission_type=False`),
        asserting this type make sense for e2e (metrics collected from agent).
        For integrations tests, we can check the submission type with `check_submission_type=True`, or
        use `check_metric_type=False` not to check types.

        Usage:

            from datadog_checks.dev.utils import get_metadata_metrics
            aggregator.assert_metrics_using_metadata(get_metadata_metrics())

        """

        exclude = exclude or []
        errors = set()
        for metric_name, metric_stubs in iteritems(self._metrics):
            if metric_name in exclude:
                continue
            for metric_stub in metric_stubs:
                metric_stub_name = backend_normalize_metric_name(metric_stub.name)
                actual_metric_type = AggregatorStub.METRIC_ENUM_MAP_REV[metric_stub.type]

                # We only check `*.count` metrics for histogram and historate submissions
                # Note: all Openmetrics histogram and summary metrics are actually separately submitted
                if check_submission_type and actual_metric_type in ['histogram', 'historate']:
                    metric_stub_name += '.count'

                # Checking the metric is in `metadata.csv`
                if metric_stub_name not in metadata_metrics:
                    errors.add("Expect `{}` to be in metadata.csv.".format(metric_stub_name))
                    continue

                expected_metric_type = metadata_metrics[metric_stub_name]['metric_type']
                if check_submission_type:
                    # Integration tests type mapping
                    actual_metric_type = AggregatorStub.METRIC_TYPE_SUBMISSION_TO_BACKEND_MAP[actual_metric_type]
                else:
                    # E2E tests
                    if actual_metric_type == 'monotonic_count' and expected_metric_type == 'count':
                        actual_metric_type = 'count'

                if check_metric_type:
                    if expected_metric_type != actual_metric_type:
                        errors.add(
                            "Expect `{}` to have type `{}` but got `{}`.".format(
                                metric_stub_name, expected_metric_type, actual_metric_type
                            )
                        )

        assert not errors, "Metadata assertion errors using metadata.csv:" + "\n\t- ".join([''] + sorted(errors))

    def assert_no_duplicate_all(self):
        """
        Assert no duplicate metrics and service checks have been submitted.
        """
        self.assert_no_duplicate_metrics()
        self.assert_no_duplicate_service_checks()

    def assert_no_duplicate_metrics(self):
        """
        Assert no duplicate metrics have been submitted.

        Metrics are considered duplicate when all following fields match:

        - metric name
        - type (gauge, rate, etc)
        - tags
        - hostname
        """
        # metric types that intended to be called multiple times are ignored
        ignored_types = [self.COUNT, self.COUNTER]
        metric_stubs = [m for metrics in self._metrics.values() for m in metrics if m.type not in ignored_types]

        def stub_to_key_fn(stub):
            return stub.name, stub.type, str(sorted(stub.tags)), stub.hostname

        self._assert_no_duplicate_stub('metric', metric_stubs, stub_to_key_fn)

    def assert_no_duplicate_service_checks(self):
        """
        Assert no duplicate service checks have been submitted.

        Service checks are considered duplicate when all following fields match:
            - metric name
            - status
            - tags
            - hostname
        """
        service_check_stubs = [m for metrics in self._service_checks.values() for m in metrics]

        def stub_to_key_fn(stub):
            return stub.name, stub.status, str(sorted(stub.tags)), stub.hostname

        self._assert_no_duplicate_stub('service_check', service_check_stubs, stub_to_key_fn)

    @staticmethod
    def _assert_no_duplicate_stub(stub_type, all_metrics, stub_to_key_fn):
        all_contexts = defaultdict(list)
        for metric in all_metrics:
            context = stub_to_key_fn(metric)
            all_contexts[context].append(metric)

        dup_contexts = defaultdict(list)
        for context, metrics in iteritems(all_contexts):
            if len(metrics) > 1:
                dup_contexts[context] = metrics

        err_msg_lines = ["Duplicate {}s found:".format(stub_type)]
        for key in sorted(dup_contexts):
            contexts = dup_contexts[key]
            err_msg_lines.append('- {}'.format(contexts[0].name))
            for metric in contexts:
                err_msg_lines.append('    ' + str(metric))

        assert len(dup_contexts) == 0, "\n".join(err_msg_lines)

    def reset(self):
        """
        Set the stub to its initial state
        """
        self._metrics = defaultdict(list)
        self._asserted = set()
        self._service_checks = defaultdict(list)
        self._events = []
        # dict[event_type, [events]]
        self._event_platform_events = defaultdict(list)
        self._histogram_buckets = defaultdict(list)

    def all_metrics_asserted(self):
        assert self.metrics_asserted_pct >= 100.0

    def not_asserted(self):
        present_metrics = {ensure_unicode(m) for m in self._metrics}
        return present_metrics - set(self._asserted)

    def assert_metric_has_tag_prefix(self, metric_name, tag_prefix, count=None, at_least=1):
        candidates = []
        self._asserted.add(metric_name)

        for metric in self.metrics(metric_name):
            tags = metric.tags
            gtags = [t for t in tags if t.startswith(tag_prefix)]
            if len(gtags) > 0:
                candidates.append(metric)

        msg = "Candidates size assertion for `{}`, count: {}, at_least: {}) failed".format(metric_name, count, at_least)
        if count is not None:
            assert len(candidates) == count, msg
        else:
            assert len(candidates) >= at_least, msg

    @property
    def metrics_asserted_pct(self):
        """
        Return the metrics assertion coverage
        """
        num_metrics = len(self._metrics)
        num_asserted = len(self._asserted)

        if num_metrics == 0:
            if num_asserted == 0:
                return 100
            else:
                return 0

        # If it there have been assertions with at_least=0 the length of the num_metrics and num_asserted can match
        # even if there are different metrics in each set
        not_asserted = self.not_asserted()
        return (num_metrics - len(not_asserted)) / num_metrics * 100

    @property
    def metric_names(self):
        """
        Return all the metric names we've seen so far
        """
        return [ensure_unicode(name) for name in self._metrics.keys()]

    @property
    def service_check_names(self):
        """
        Return all the service checks names seen so far
        """
        return [ensure_unicode(name) for name in self._service_checks.keys()]

# Use the stub as a singleton
aggregator = AggregatorStub()