text:
package org.owasp.appsensor.kafka.event;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;

import kafka.consumer.Consumer;
import kafka.consumer.ConsumerConfig;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;
//import kafka.message.MessageAndMetadata;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.owasp.appsensor.core.Attack;
import org.owasp.appsensor.core.ClientApplication;
import org.owasp.appsensor.core.Event;
import org.owasp.appsensor.core.KeyValuePair;
import org.owasp.appsensor.core.RequestHandler;
import org.owasp.appsensor.core.Response;
import org.owasp.appsensor.core.event.EventManager;
import org.owasp.appsensor.core.util.DateUtils;
import org.owasp.appsensor.kafka.KafkaConfig;
import org.owasp.appsensor.kafka.KafkaConfig.KafkaConfigBuilder;
import org.owasp.appsensor.kafka.KafkaConstants;
import org.owasp.appsensor.kafka.util.KafkaSender;
import org.owasp.appsensor.kafka.util.KafkaUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;

import com.google.gson.Gson;

/**
 *
This is the kafka component that handles requests on the client-side.

 *
 *
This class has 2 primary responsibilities

 *

 *
Forward {@link Event}s and {@link Attack}s from {@link ClientApplication}s to
 * 	 the Kafka topic for the server-side {@link RequestHandler} to pick them up.

 *
Poll the Kafka topic specific to this {@link ClientApplication} and
 *   store the messages locally for access.

 *

 *
 *
The "add event" topic is called "appsensor-add-event-topic".

 *
The "add attack" topic is called "appsensor-add-attack-topic".

 *
The response topics are client application specific and follow the naming convention
 *    of "appsensor-" + "client application name" + "-response-topic". If a client application is
 *    named "myapp", then the queue name would be "appsensor-myapp-response-topic"

 *
 *
Note: This class requires a few settings to run properly. These can be set as either
 *    environment variables ('export my_var="some_value"') or environment
 *    properties ('-Dmy_var=some_value') set at the JVM

 *

 *
APPSENSOR_CLIENT_APPLICATION_NAME - the name used for this client application, e.g. "my-app"

 *
APPSENSOR_KAFKA_CONSUMER_GROUP_ID - A string that uniquely identifies the group of consumer processes
 *   												  to which this consumer belongs. By setting the same group id multiple processes
 *   											      indicate that they are all part of the same consumer group, e.g. "my-consumer-group

 *
APPSENSOR_KAFKA_CONSUMER_ZOOKEEPER_CONNECT - zookeeper connect string, e.g. "hostname1:port1,hostname2:port2,hostname3:port3"

 *
APPSENSOR_KAFKA_PRODUCER_BOOTSTRAP_SERVERS - A list of host/port pairs to use for establishing the initial connection to
 *   															the Kafka cluster, e.g. "host1:port1,host2:port2"

 *
APPSENSOR_KAFKA_PRODUCER_PARTITION - (OPTIONAL, MUST be integer if set) The partition to which the record should be sent, e.g. "2"

 *
APPSENSOR_KAFKA_PRODUCER_KEY - (OPTIONAL) The key that will be included in the record, e.g. "my-special-key"

 *

 *
 *
Note: This class assumes the 'auto.create.topics.enable' setting is set to 'true', which is the default.
 * If not set to true, the code will fail.

 *
 *
Note: The kafka implementation does NOT perform access control. Due to the asynchronous
 * nature of the communication, authentication and access control must be performed at one/both of
 * the network layer or the kafka layer (current version of kafka does not provide security)

 *
 * @author John Melton (jtmelton@gmail.com) http://www.jtmelton.com/
 */
@Named
public class KafkaEventManager implements EventManager, KafkaConstants {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Inject
	private Environment environment;

	private final Gson gson = new Gson();

	private boolean initializedProperly = true;

	/** maintain a collection of {@link Response}s as an in-memory list */
	private static Collection<Response> responses = new CopyOnWriteArrayList<>();

	private KafkaConfig config;

	private KafkaSender kafkaSender;

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void addEvent(Event event) {
		ensureInitialized();

		KeyValuePair keyValuePair = new KeyValuePair(KafkaConstants.EVENT_TYPE, gson.toJson(event));
		String message = gson.toJson(keyValuePair);

		try {
			kafkaSender.send(Arrays.asList(APPSENSOR_ADD_EVENT_TOPIC), message);
		} catch (InterruptedException | ExecutionException e) {
			logger.error("Failed to send add event message to output topic.", e);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void addAttack(Attack attack) {
		ensureInitialized();

		KeyValuePair keyValuePair = new KeyValuePair(KafkaConstants.ATTACK_TYPE, gson.toJson(attack));
		String message = gson.toJson(keyValuePair);

		try {
			kafkaSender.send(Arrays.asList(APPSENSOR_ADD_ATTACK_TOPIC), message);
		} catch (InterruptedException | ExecutionException e) {
			logger.error("Failed to send add attack message to output topic.", e);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Collection<Response> getResponses(String earliest) {
		ensureInitialized();

		Collection<Response> matchingResponses = new HashSet<>();

		for(Response response : responses) {
			DateTime earliestDateTime = DateUtils.fromString(earliest);
			DateTime responseDateTime = DateUtils.fromString(response.getTimestamp());

			if(earliestDateTime != null && responseDateTime != null) {
				if(earliestDateTime.isBefore(responseDateTime)) {
					matchingResponses.add(response);
				}
			}
		}

		return responses;
	}

	private void ensureInitialized() {
		if(! initializedProperly) {
			throw new IllegalStateException(getUninitializedMessage());
		}
	}

	@PostConstruct
	public void ensureEnvironmentVariablesSet() {
		initializedProperly = isInitializedProperly();

		if (! initializedProperly) {
			logger.error(getUninitializedMessage());
		} else {
			initializeConfig();
			startKafkaListeners();
			initializeSender();
		}
	}

	private void startKafkaListeners() {
		logger.info("Starting Kafka listeners for client application response queues");
		new ListenerThread(KafkaUtils.buildResponseTopicName(config.getClientApplicationName())).start();
		logger.info("Completed startup of Kafka listeners for client application response queues");
	}

	private void initializeConfig() {
		Integer partition = null;

		if (StringUtils.isNotBlank(environment.getProperty(KAFKA_PRODUCER_PARTITION))) {
			partition = Integer.parseInt(environment.getProperty(KAFKA_PRODUCER_PARTITION));
		}

		config =
				new KafkaConfigBuilder()
					.setClientApplicationName(environment.getProperty(APPSENSOR_CLIENT_APPLICATION_NAME))
					.setConsumerGroupId(environment.getProperty(KAFKA_CONSUMER_GROUP_ID))
					.setConsumerZookeeperConnect(environment.getProperty(KAFKA_CONSUMER_ZOOKEEPER_CONNECT))
					.setProducerBootstrapServers(environment.getProperty(KAFKA_PRODUCER_BOOTSTRAP_SERVERS))
					.setProducerPartition(partition)
					.setProducerKey(environment.getProperty(KAFKA_PRODUCER_KEY))
					.build();
	}

	private void initializeSender() {
		kafkaSender = new KafkaSender(config);
	}

	private boolean isInitializedProperly() {
		boolean initializedProperly = false;

		initializedProperly = StringUtils.isNotBlank(environment.getProperty(APPSENSOR_CLIENT_APPLICATION_NAME)) &&
				StringUtils.isNotBlank(environment.getProperty(KAFKA_CONSUMER_GROUP_ID)) &&
				StringUtils.isNotBlank(environment.getProperty(KAFKA_CONSUMER_ZOOKEEPER_CONNECT)) &&
				StringUtils.isNotBlank(environment.getProperty(KAFKA_PRODUCER_BOOTSTRAP_SERVERS));

		// fail early
		if (! initializedProperly) {
			return initializedProperly;
		}

		if (StringUtils.isNotBlank(environment.getProperty(KAFKA_PRODUCER_PARTITION))) {
			// optional field, but if set:
			//	- key field must also be set
			//	- this field must be int
			String partition = environment.getProperty(KAFKA_PRODUCER_PARTITION);

			try {
				Integer.parseInt(partition);
			} catch(NumberFormatException nfe) {
				// fail if this is not an integer
				initializedProperly = false;
			}

			if (! initializedProperly) {
				return initializedProperly;
			}

			// also ensure key is set
			initializedProperly = StringUtils.isNotBlank(environment.getProperty(KAFKA_PRODUCER_KEY));

			if (! initializedProperly) {
				return initializedProperly;
			}
		}

		return initializedProperly;
	}

	private String getUninitializedMessage() {
		StringBuilder sb = new StringBuilder();

		Collection<String> setVariables = new ArrayList<>();
		Collection<String> missingVariables = new ArrayList<>();

		if (StringUtils.isBlank(environment.getProperty(APPSENSOR_CLIENT_APPLICATION_NAME))) {
			missingVariables.add(APPSENSOR_CLIENT_APPLICATION_NAME);
		} else {
			setVariables.add(APPSENSOR_CLIENT_APPLICATION_NAME);
		}

		if (StringUtils.isBlank(environment.getProperty(KAFKA_CONSUMER_GROUP_ID))) {
			missingVariables.add(KAFKA_CONSUMER_GROUP_ID);
		} else {
			setVariables.add(KAFKA_CONSUMER_GROUP_ID);
		}

		if (StringUtils.isBlank(environment.getProperty(KAFKA_CONSUMER_ZOOKEEPER_CONNECT))) {
			missingVariables.add(KAFKA_CONSUMER_ZOOKEEPER_CONNECT);
		} else {
			setVariables.add(KAFKA_CONSUMER_ZOOKEEPER_CONNECT);
		}

		if (StringUtils.isBlank(environment.getProperty(KAFKA_PRODUCER_BOOTSTRAP_SERVERS))) {
			missingVariables.add(KAFKA_PRODUCER_BOOTSTRAP_SERVERS);
		} else {
			setVariables.add(KAFKA_PRODUCER_BOOTSTRAP_SERVERS);
		}

		if (missingVariables.size() > 0) {
			sb.append("The following Environment variables must be set: ").append(missingVariables);

			if (setVariables.size() > 0) {
				sb.append(" (already set variables - ").append(setVariables).append(")");
			}
		}

		if (StringUtils.isNotBlank(environment.getProperty(KAFKA_PRODUCER_PARTITION))) {
			// optional field, but if set:
			//	- key field must also be set
			//	- this field must be int
			String partition = environment.getProperty(KAFKA_PRODUCER_PARTITION);

			try {
				Integer.parseInt(partition);
			} catch(NumberFormatException nfe) {
				// fail if this is not an integer
				sb.append("\r\n");
				sb.append("If you use the " + KAFKA_PRODUCER_PARTITION + ", it must be set to an integer.");
			}

			// also ensure key is set
			if (StringUtils.isBlank(environment.getProperty(KAFKA_PRODUCER_KEY))) {
				sb.append("\r\n");
				sb.append("If you use the " + KAFKA_PRODUCER_PARTITION + ", you must also set the " + KAFKA_PRODUCER_KEY + ".");
			}
		}

		return sb.toString();
	}

	public class ListenerThread extends Thread {
	    final String topic;

	    ConsumerConnector consumerConnector;

	    public ListenerThread(String topicName){
	    	topic = topicName;

	    	logger.info("Starting EventManager kafka consumer .. ");

	    	logger.info("Connecting to zookepper: " + config.getConsumerZookeeperConnect());
	    	logger.info("Connecting with group id: " + config.getConsumerGroupId());
	    	logger.info("Connecting with client id: " + config.getClientApplicationName());
	    	logger.info("Connecting to topic: " + topic);

	        Properties properties = new Properties();
	        properties.put("zookeeper.connect", config.getConsumerZookeeperConnect());
	        properties.put("group.id", config.getConsumerGroupId());
	        properties.put("client.id", config.getClientApplicationName());
	        properties.put("zookeeper.session.timeout.ms", "400");
	        properties.put("zookeeper.sync.time.ms", "200");
	        properties.put("auto.commit.interval.ms", "1000");

	        ConsumerConfig consumerConfig = new ConsumerConfig(properties);
	        consumerConnector = Consumer.createJavaConsumerConnector(consumerConfig);

	        logger.info("Created event manager kafka consumer");
	    }

	    @Override
	    public void run() {
	        Map<String, Integer> topicCountMap = new HashMap<String, Integer>();
	        topicCountMap.put(topic, new Integer(1));

	        Map<String, List<KafkaStream<byte[], byte[]>>> consumerMap = consumerConnector.createMessageStreams(topicCountMap);
	        List<KafkaStream<byte[], byte[]>> streams = consumerMap.get(topic);
	        KafkaStream<byte[], byte[]> stream = streams.get(0);
	        ConsumerIterator<byte[], byte[]> it = stream.iterator();

            while (it.hasNext()) {
            	String message = new String(it.next().message());

                KeyValuePair keyValuePair = gson.fromJson(message, KeyValuePair.class);

                String type = keyValuePair.getKey();
                String content = keyValuePair.getValue();

                if(RESPONSE_TYPE.equals(type)) {
                	logger.trace("Received response on topic: " + topic);

					Response response = gson.fromJson(content, Response.class);

					responses.add(response);
    			} else {
    				logger.trace("Received message for UNKNOWN topic: " + topic);
    			}

            }

	    }
	}

}


text:
#ifndef _GDIPLUSINIT_H
#define _GDIPLUSINIT_H

enum DebugEventLevel
{
    DebugEventLevelFatal,
    DebugEventLevelWarning
};

typedef VOID (WINAPI *DebugEventProc)(enum DebugEventLevel, CHAR *);
typedef Status (WINAPI *NotificationHookProc)(ULONG_PTR *);
typedef void (WINAPI *NotificationUnhookProc)(ULONG_PTR);

struct GdiplusStartupInput
{
    UINT32 GdiplusVersion;
    DebugEventProc DebugEventCallback;
    BOOL SuppressBackgroundThread;
    BOOL SuppressExternalCodecs;

#ifdef __cplusplus
    GdiplusStartupInput(DebugEventProc debugEventCallback = NULL,
        BOOL suppressBackgroundThread = FALSE,
        BOOL suppressExternalCodecs = FALSE)
    {
        GdiplusVersion = 1;
        DebugEventCallback = debugEventCallback;
        SuppressBackgroundThread = suppressBackgroundThread;
        SuppressExternalCodecs = suppressExternalCodecs;
    }
#endif
};

struct GdiplusStartupOutput
{
    NotificationHookProc NotificationHook;
    NotificationUnhookProc NotificationUnhook;
};

#ifdef __cplusplus
extern "C" {
#endif

Status WINAPI GdiplusStartup(ULONG_PTR *, const struct GdiplusStartupInput *, struct GdiplusStartupOutput *);
void WINAPI GdiplusShutdown(ULONG_PTR);

#ifdef __cplusplus
}
#endif

#endif

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';
import classNames from 'classnames';
import { CardBodyProps } from './PropsType';

export default class CardBody extends React.Component<CardBodyProps, any> {
  static defaultProps = {
    prefixCls: 'am-card',
  };

  render() {
    const { prefixCls, className, ...restProps } = this.props;
    const wrapCls = classNames({
      [`${prefixCls}-body`]: true,
      [className as string]: className,
    });

    return (
      <div className={wrapCls} {...restProps} />
    );
  }
}


text:
import {CachablePainting} from "../draw/CachablePainting.js"
import {CircuitStats} from "../circuit/CircuitStats.js"
import {Config} from "../Config.js"
import {GateDrawParams} from "../draw/GateDrawParams.js"
import {GatePainting} from "../draw/GatePainting.js"
import {Hand} from "../ui/Hand.js"
import {MysteryGateSymbol, MysteryGateMaker} from "../gates/Joke_MysteryGate.js"
import {Rect} from "../math/Rect.js"
import {Painter} from "../draw/Painter.js"
import {Point} from "../math/Point.js"
import {seq} from "../base/Seq.js"
import {WidgetPainter} from "../draw/WidgetPainter.js"

class DisplayedToolbox {
    /**
     * That thing showing gates you can grab.
     * @param {!string} name
     * @param {!number} top
     * @param {!Array<!{hint: !string, gates: !Array<undefined|!Gate>}>} toolboxGroups
     * @param {!boolean} labelsOnTop
     * @param {undefined|!Array<!{hint: !string, gates: !Array<undefined|!Gate>}>=} originalGroups
     * @param {undefined|!CachablePainting=undefined} standardAppearance
     */
    constructor(
            name,
            top,
            toolboxGroups,
            labelsOnTop,
            originalGroups=undefined,
            standardAppearance=undefined) {
        /** @type {!String} */
        this.name = name;
        /** @type {!number} */
        this.top = top;
        /** @type {!Array<!{hint: !string, gates: !Array<undefined|!Gate>}>} */
        this.toolboxGroups = toolboxGroups;
        /** @type {!boolean} */
        this.labelsOnTop = labelsOnTop;
        /** @type {!Array<!{hint: !string, gates: !Array<undefined|!Gate>}>} */
        this._originalGroups = originalGroups || this.toolboxGroups;
        /**
         * @type {!CachablePainting}
         * @private
         */
        this._standardApperance = standardAppearance || new CachablePainting(
            () => ({width: this.desiredWidth(), height: this.desiredHeight()}),
            painter => {
                painter.ctx.save();
                painter.ctx.translate(0, -this.top);
                this._paintStandardContents(painter);
                painter.ctx.restore();
            });

        /** @type {!int} */
        this.groupHeight = 1;
        for (let group of toolboxGroups) {
            let h = Math.ceil(group.gates.length / 2);
            this.groupHeight = Math.max(this.groupHeight, h);
        }
    }

    /**
     * @param {!CustomGateSet} customGateSet
     */
    withCustomGatesInserted(customGateSet) {
        let groups = [...this._originalGroups];
        for (let i = 0; i < Math.max(1, customGateSet.gates.length); i += this.groupHeight*2) {
            let group = {
                hint: 'Custom Gates',
                gates: [undefined, undefined, undefined, undefined, undefined, undefined]
            };
            for (let j = 0; j < this.groupHeight*2 && i + j < customGateSet.gates.length; j++) {
                group.gates[j] = customGateSet.gates[i + j];
            }
            groups.push(group);
        }
        return new DisplayedToolbox(
            this.name,
            this.top,
            groups,
            this.labelsOnTop,
            this._originalGroups,
            this._standardApperance);
    }

    /**
     * @param {!int} groupIndex
     * @param {!int} gateIndex
     * @returns {!Rect}
     * @private
     */
    gateDrawRect(groupIndex, gateIndex) {
        let dx = gateIndex % 2;
        let dy = Math.floor(gateIndex / 2);

        let x = Config.TOOLBOX_MARGIN_X +
            dx * Config.TOOLBOX_GATE_SPAN +
            groupIndex * Config.TOOLBOX_GROUP_SPAN;
        let y = this.top +
            (this.labelsOnTop ? Config.TOOLBOX_MARGIN_Y : 3) +
            dy * Config.TOOLBOX_GATE_SPAN;

        return new Rect(
            Math.round(x - 0.5) + 0.5,
            Math.round(y - 0.5) + 0.5,
            Config.GATE_RADIUS * 2,
            Config.GATE_RADIUS * 2);
    }

    /**
     * @param {!int} groupIndex
     * @returns {!Rect}
     * @private
     */
    groupLabelRect(groupIndex) {
        if (this.labelsOnTop) {
            let r = this.gateDrawRect(groupIndex, 0);
            let c = new Point(r.x + Config.TOOLBOX_GATE_SPAN - Config.TOOLBOX_GATE_SPACING / 2, r.y - 18);
            return new Rect(c.x - Config.TOOLBOX_GATE_SPAN, c.y, Config.TOOLBOX_GATE_SPAN * 2, 20);
        }

        let r = this.gateDrawRect(groupIndex, this.groupHeight*2 - 2);
        let c = new Point(r.x + Config.TOOLBOX_GATE_SPAN - Config.TOOLBOX_GATE_SPACING / 2, r.bottom());
        return new Rect(c.x - Config.TOOLBOX_GATE_SPAN, c.y+2, Config.TOOLBOX_GATE_SPAN * 2, 20);
    }

    /**
     *
     * @param {undefined|!Point} pt
     *
     * @returns {undefined|!{groupIndex: !int, gateIndex: !int, gate: !Gate, rect: !Rect}}
     */
    findGateAt(pt) {
        if (pt === undefined) {
            return undefined;
        }
        for (let groupIndex = 0; groupIndex < this.toolboxGroups.length; groupIndex++) {
            let group = this.toolboxGroups[groupIndex];
            for (let gateIndex = 0; gateIndex < group.gates.length; gateIndex++) {
                let gate = group.gates[gateIndex];
                let rect = this.gateDrawRect(groupIndex, gateIndex);
                if (gate !== undefined && rect.containsPoint(pt)) {
                    return {groupIndex, gateIndex, gate, rect};
                }
            }
        }
        return undefined;
    }

    /**
     * @param {!DisplayedToolbox|*} other
     * @returns {!boolean}
     */
    isEqualTo(other) {
        return other instanceof DisplayedToolbox &&
            this.name === other.name &&
            this.top === other.top &&
            this.toolboxGroups === other.toolboxGroups &&
            this.labelsOnTop === other.labelsOnTop;
    }

    /**
     * @param {!number} newTop
     * @returns {!DisplayedToolbox}
     */
    withTop(newTop) {
        return new DisplayedToolbox(
            this.name,
            newTop,
            this.toolboxGroups,
            this.labelsOnTop,
            this._originalGroups,
            this._standardApperance);
    }

    /**
     * @param {!number} maxWidth
     * @returns {!Rect}
     */
    curArea(maxWidth) {
        return new Rect(0, this.top, maxWidth, this.desiredHeight());
    }

    /**
     * @param {!Painter} painter
     * @param {!CircuitStats} stats
     * @param {!Hand} hand
     */
    paint(painter, stats, hand) {
        painter.fillRect(this.curArea(painter.canvas.width), Config.BACKGROUND_COLOR_TOOLBOX);
        this._standardApperance.paint(0, this.top, painter);
        this._paintDeviations(painter, stats, hand);
    }

    /**
     * @param {!Painter} painter
     */
    _paintStandardContents(painter) {
        // Gates.
        for (let groupIndex = 0; groupIndex < this.toolboxGroups.length; groupIndex++) {
            this._paintGatesInGroup(painter, Hand.EMPTY, groupIndex);
        }

        // Title of toolbox.
        let r = this.curArea(Config.TOOLBOX_MARGIN_X);
        let {x, y} = r.center();
        painter.ctx.save();
        painter.ctx.translate(x, y);
        painter.ctx.rotate(-Math.PI/2);
        painter.printLine(this.name, new Rect(-r.h / 2, -r.w / 2, r.h, r.w), 0.5, 'black', 24);
        painter.ctx.restore();
    }

    /**
     * @param {!Painter} painter
     * @param {!CircuitStats} stats
     * @param {!Hand} hand
     */
    _paintDeviations(painter, stats, hand) {
        for (let groupIndex = 0; groupIndex < this.toolboxGroups.length; groupIndex++) {
            // Custom gates.
            if (groupIndex >= this._originalGroups.length) {
                this._paintGatesInGroup(painter, hand, groupIndex);
            }

            // Keep scroll blockers positioned over gates.
            let group = this.toolboxGroups[groupIndex];
            for (let gateIndex = 0; gateIndex < group.gates.length; gateIndex++) {
                if (group.gates[gateIndex] !== undefined) {
                    painter.noteTouchBlocker({
                        rect: this.gateDrawRect(groupIndex, gateIndex),
                        cursor: 'pointer'}
                    );
                }
            }
        }

        this._paintFocus(painter, stats, hand);
    }

    /**
     * @param {!Painter} painter
     * @param {!Hand} hand
     * @param {!int} groupIndex
     * @private
     */
    _paintGatesInGroup(painter, hand, groupIndex) {
        let group = this.toolboxGroups[groupIndex];
        let r = this.groupLabelRect(groupIndex);
        painter.print(
            group.hint,
            r.x + r.w/2,
            r.y + r.h/2,
            'center',
            'middle',
            'black',
            '16px sans-serif',
            r.w,
            r.h);

        for (let gateIndex = 0; gateIndex < group.gates.length; gateIndex++) {
            let gate = group.gates[gateIndex];
            if (gate === undefined) {
                continue;
            }
            let rect = this.gateDrawRect(groupIndex, gateIndex);
            DisplayedToolbox._paintGate(painter, hand, gate, rect, false, CircuitStats.EMPTY);
        }
    }

    /**
     * @param {!Painter} painter
     * @param {!Hand} hand
     * @param {!Gate} gate
     * @param {!Rect} rect
     * @param {!boolean} isHighlighted
     * @param {!CircuitStats} stats
     * @private
     */
    static _paintGate(painter, hand, gate, rect, isHighlighted, stats) {
        let drawer = gate.customDrawer || GatePainting.DEFAULT_DRAWER;
        painter.startIgnoringIncomingTouchBlockers();
        drawer(new GateDrawParams(
            painter,
            hand,
            true, // inToolbox
            isHighlighted,
            false, // isResizeShowing
            false, // isResizeHighlighted
            rect,
            gate,
            stats,
            undefined, // positionInCircuit
            [], // focusPoints
            undefined)); // customStatsForCircuitPos
        painter.stopIgnoringIncomingTouchBlockers();
    }

    /**
     * @param {!Painter} painter
     * @param {!CircuitStats} stats
     * @param {!Hand} hand
     * @private
     */
    _paintFocus(painter, stats, hand) {
        // Focus when hovering, but also when dragging a gate over its own toolbox spot.
        let f = this.findGateAt(hand.pos);
        if (f === undefined || (hand.heldGate !== undefined && f.gate.symbol !== hand.heldGate.symbol)) {
            return;
        }

        // Draw highlight.
        DisplayedToolbox._paintGate(painter, hand, f.gate, f.rect, true, stats);

        // Size tooltip.
        painter.ctx.save();
        painter.ctx.globalAlpha = 0;
        painter.ctx.translate(-10000, -10000);
        let {maxW, maxH} = WidgetPainter.paintGateTooltip(
            painter, new Rect(0, 0, 500, 300), f.gate, stats.time, true);
        let mayNeedToScale = maxW >= 500 || maxH >= 300;
        painter.ctx.restore();

        // Draw tooltip.
        let cx = f.rect.right() + 1;
        let hintRect = new Rect(cx, f.rect.center().y, maxW, maxH).
            snapInside(painter.paintableArea().skipRight(10).skipBottom(20));
        painter.defer(() => WidgetPainter.paintGateTooltip(painter, hintRect, f.gate, stats.time, mayNeedToScale));
    }

    /**
     * @returns {!number}
     */
    desiredWidth() {
        return this.gateDrawRect(this.toolboxGroups.length - 1, 5).right() + 5;
    }

    //noinspection JSMethodCanBeStatic
    /**
     * @returns {!number}
     */
    desiredHeight() {
        return (1 + this.groupHeight) * (Config.GATE_RADIUS * 2 + 2) - Config.GATE_RADIUS;
    }

    /**
     * @param {!Hand} hand
     * @returns {!Hand} newHand
     */
    tryGrab(hand) {
        if (hand.pos === undefined || hand.isBusy()) {
            return hand;
        }

        let f = this.findGateAt(hand.pos);
        if (f === undefined) {
            return hand;
        }

        if (f.gate.symbol === MysteryGateSymbol) {
            setTimeout(() => { this.toolboxGroups[f.groupIndex].gates[f.gateIndex] = MysteryGateMaker(); }, 0.1);
        }
        return hand.withHeldGate(f.gate, new Point(Config.GATE_RADIUS, Config.GATE_RADIUS));
    }

    /**
     * @param {!Hand} hand
     * @returns {Infinity|!number}
     */
    stableDuration(hand) {
        return seq(hand.hoverPoints()).
            map(p => this.findGateAt(p)).
            filter(e => e !== undefined).
            map(e => e.gate.stableDuration()).
            min(Infinity);
    }
}

export {DisplayedToolbox}


text:
layout: resume
title: management skills
---

## Technical Management Skills

- **Multiple Teams** - Sourced, hired and trained multiple teams. Organized multiple teams that consistently delivered high value features at all levels of the organization. Established a reputation for having the highest producing and happiest teams in the company.
- **Leadership Development** - Trained and prepared multiple candidates to take on additional leadership roles.
- **Hiring** - Developed strong relationships throughout the Salt Lake Valley in order to source appropriate candidates whenever a position opened up. Worked with various sourcing methods including referrals, cold calling, and recruiters to make sure we had the right candidate to accelerate a teams progress.


text:
from six.moves import http_client
from testtools import matchers

from keystone.tests import unit
from keystone.tests.unit import test_v3

class EndpointPolicyTestCase(test_v3.RestfulTestCase):
    """Test endpoint policy CRUD.

    In general, the controller layer of the endpoint policy extension is really
    just marshalling the data around the underlying manager calls. Given that
    the manager layer is tested in depth by the backend tests, the tests we
    execute here concentrate on ensuring we are correctly passing and
    presenting the data.

    """

    def setUp(self):
        super(EndpointPolicyTestCase, self).setUp()
        self.policy = unit.new_policy_ref()
        self.policy_api.create_policy(self.policy['id'], self.policy)
        self.service = unit.new_service_ref()
        self.catalog_api.create_service(self.service['id'], self.service)
        self.endpoint = unit.new_endpoint_ref(self.service['id'], enabled=True,
                                              interface='public',
                                              region_id=self.region_id)
        self.catalog_api.create_endpoint(self.endpoint['id'], self.endpoint)
        self.region = unit.new_region_ref()
        self.catalog_api.create_region(self.region)

    def assert_head_and_get_return_same_response(self, url, expected_status):
        self.get(url, expected_status=expected_status)
        self.head(url, expected_status=expected_status)

    # endpoint policy crud tests
    def _crud_test(self, url):
        # Test when the resource does not exist also ensures
        # that there is not a false negative after creation.

        self.assert_head_and_get_return_same_response(
            url,
            expected_status=http_client.NOT_FOUND)

        self.put(url)

        # test that the new resource is accessible.
        self.assert_head_and_get_return_same_response(
            url,
            expected_status=http_client.NO_CONTENT)

        self.delete(url)

        # test that the deleted resource is no longer accessible
        self.assert_head_and_get_return_same_response(
            url,
            expected_status=http_client.NOT_FOUND)

    def test_crud_for_policy_for_explicit_endpoint(self):
        """PUT, HEAD and DELETE for explicit endpoint policy."""
        url = ('/policies/%(policy_id)s/OS-ENDPOINT-POLICY'
               '/endpoints/%(endpoint_id)s') % {
                   'policy_id': self.policy['id'],
                   'endpoint_id': self.endpoint['id']}
        self._crud_test(url)

    def test_crud_for_policy_for_service(self):
        """PUT, HEAD and DELETE for service endpoint policy."""
        url = ('/policies/%(policy_id)s/OS-ENDPOINT-POLICY'
               '/services/%(service_id)s') % {
                   'policy_id': self.policy['id'],
                   'service_id': self.service['id']}
        self._crud_test(url)

    def test_crud_for_policy_for_region_and_service(self):
        """PUT, HEAD and DELETE for region and service endpoint policy."""
        url = ('/policies/%(policy_id)s/OS-ENDPOINT-POLICY'
               '/services/%(service_id)s/regions/%(region_id)s') % {
                   'policy_id': self.policy['id'],
                   'service_id': self.service['id'],
                   'region_id': self.region['id']}
        self._crud_test(url)

    def test_get_policy_for_endpoint(self):
        """GET /endpoints/{endpoint_id}/policy."""
        self.put('/policies/%(policy_id)s/OS-ENDPOINT-POLICY'
                 '/endpoints/%(endpoint_id)s' % {
                     'policy_id': self.policy['id'],
                     'endpoint_id': self.endpoint['id']})

        self.head('/endpoints/%(endpoint_id)s/OS-ENDPOINT-POLICY'
                  '/policy' % {
                      'endpoint_id': self.endpoint['id']},
                  expected_status=http_client.OK)

        r = self.get('/endpoints/%(endpoint_id)s/OS-ENDPOINT-POLICY'
                     '/policy' % {
                         'endpoint_id': self.endpoint['id']})
        self.assertValidPolicyResponse(r, ref=self.policy)

    def test_list_endpoints_for_policy(self):
        """GET /policies/%(policy_id}/endpoints."""
        self.put('/policies/%(policy_id)s/OS-ENDPOINT-POLICY'
                 '/endpoints/%(endpoint_id)s' % {
                     'policy_id': self.policy['id'],
                     'endpoint_id': self.endpoint['id']})

        r = self.get('/policies/%(policy_id)s/OS-ENDPOINT-POLICY'
                     '/endpoints' % {
                         'policy_id': self.policy['id']})
        self.assertValidEndpointListResponse(r, ref=self.endpoint)
        self.assertThat(r.result.get('endpoints'), matchers.HasLength(1))

    def test_endpoint_association_cleanup_when_endpoint_deleted(self):
        url = ('/policies/%(policy_id)s/OS-ENDPOINT-POLICY'
               '/endpoints/%(endpoint_id)s') % {
                   'policy_id': self.policy['id'],
                   'endpoint_id': self.endpoint['id']}

        self.put(url)
        self.head(url)

        self.delete('/endpoints/%(endpoint_id)s' % {
            'endpoint_id': self.endpoint['id']})

        self.head(url, expected_status=http_client.NOT_FOUND)

    def test_region_service_association_cleanup_when_region_deleted(self):
        url = ('/policies/%(policy_id)s/OS-ENDPOINT-POLICY'
               '/services/%(service_id)s/regions/%(region_id)s') % {
                   'policy_id': self.policy['id'],
                   'service_id': self.service['id'],
                   'region_id': self.region['id']}

        self.put(url)
        self.head(url)

        self.delete('/regions/%(region_id)s' % {
            'region_id': self.region['id']})

        self.head(url, expected_status=http_client.NOT_FOUND)

    def test_region_service_association_cleanup_when_service_deleted(self):
        url = ('/policies/%(policy_id)s/OS-ENDPOINT-POLICY'
               '/services/%(service_id)s/regions/%(region_id)s') % {
                   'policy_id': self.policy['id'],
                   'service_id': self.service['id'],
                   'region_id': self.region['id']}

        self.put(url)
        self.head(url)

        self.delete('/services/%(service_id)s' % {
            'service_id': self.service['id']})

        self.head(url, expected_status=http_client.NOT_FOUND)

    def test_service_association_cleanup_when_service_deleted(self):
        url = ('/policies/%(policy_id)s/OS-ENDPOINT-POLICY'
               '/services/%(service_id)s') % {
                   'policy_id': self.policy['id'],
                   'service_id': self.service['id']}

        self.put(url)
        self.get(url, expected_status=http_client.NO_CONTENT)

        self.delete('/policies/%(policy_id)s' % {
            'policy_id': self.policy['id']})

        self.head(url, expected_status=http_client.NOT_FOUND)

    def test_service_association_cleanup_when_policy_deleted(self):
        url = ('/policies/%(policy_id)s/OS-ENDPOINT-POLICY'
               '/services/%(service_id)s') % {
                   'policy_id': self.policy['id'],
                   'service_id': self.service['id']}

        self.put(url)
        self.get(url, expected_status=http_client.NO_CONTENT)

        self.delete('/services/%(service_id)s' % {
            'service_id': self.service['id']})

        self.head(url, expected_status=http_client.NOT_FOUND)

class JsonHomeTests(test_v3.JsonHomeTestMixin):
    EXTENSION_LOCATION = ('http://docs.openstack.org/api/openstack-identity/3/'
                          'ext/OS-ENDPOINT-POLICY/1.0/rel')
    PARAM_LOCATION = 'http://docs.openstack.org/api/openstack-identity/3/param'

    JSON_HOME_DATA = {
        EXTENSION_LOCATION + '/endpoint_policy': {
            'href-template': '/endpoints/{endpoint_id}/OS-ENDPOINT-POLICY/'
                             'policy',
            'href-vars': {
                'endpoint_id': PARAM_LOCATION + '/endpoint_id',
            },
        },
        EXTENSION_LOCATION + '/policy_endpoints': {
            'href-template': '/policies/{policy_id}/OS-ENDPOINT-POLICY/'
                             'endpoints',
            'href-vars': {
                'policy_id': PARAM_LOCATION + '/policy_id',
            },
        },
        EXTENSION_LOCATION + '/endpoint_policy_association': {
            'href-template': '/policies/{policy_id}/OS-ENDPOINT-POLICY/'
                             'endpoints/{endpoint_id}',
            'href-vars': {
                'policy_id': PARAM_LOCATION + '/policy_id',
                'endpoint_id': PARAM_LOCATION + '/endpoint_id',
            },
        },
        EXTENSION_LOCATION + '/service_policy_association': {
            'href-template': '/policies/{policy_id}/OS-ENDPOINT-POLICY/'
                             'services/{service_id}',
            'href-vars': {
                'policy_id': PARAM_LOCATION + '/policy_id',
                'service_id': PARAM_LOCATION + '/service_id',
            },
        },
        EXTENSION_LOCATION + '/region_and_service_policy_association': {
            'href-template': '/policies/{policy_id}/OS-ENDPOINT-POLICY/'
                             'services/{service_id}/regions/{region_id}',
            'href-vars': {
                'policy_id': PARAM_LOCATION + '/policy_id',
                'service_id': PARAM_LOCATION + '/service_id',
                'region_id': PARAM_LOCATION + '/region_id',
            },
        },
    }


text:
require File.dirname(__FILE__) + "/../spec_helper.rb"

describe Borneo::Client do

  let(:client_id) { "SOME_CLIENT_ID" }
  let(:client_secret) { "SOME_CLIENT_SECRET" }
  let(:redirect_url) { "http://localhost" }
  let(:app_name) { "SomeApplication" }
  let(:app_version) { "1.0.1" }

  describe "initialiser" do
    it "takes a client ID, client secret and redirect URL parameters" do
      client = Borneo::Client.new(client_id, client_secret, redirect_url)
      client.client_id.should == client_id
      client.client_secret.should == client_secret
      client.redirect_url.should == redirect_url
    end

    it "optionally takes an application name and version" do
      client = Borneo::Client.new(client_id, client_secret, redirect_url, app_name, app_version)
      client.application_name.should == app_name
      client.application_version.should == app_version
    end
  end

  it "should cache the Google client value" do
    client = Borneo::Client.new(client_id, client_secret, redirect_url)
    client.google_client.should == client.google_client
  end

  describe "for" do

    let(:client) { Borneo::Client.new(client_id, client_secret, redirect_url) }
    let(:access_token) { "ACCESS_TOKEN" }
    let(:refresh_token) { "REFRESH_TOKEN" }

    let(:proxy) { client.for(access_token, refresh_token) }

    it "should return an authorized proxy" do
      proxy.should be_a(Borneo::AuthorizedProxy)
    end

    describe "returned proxy" do
      it "should have the creating client as its client" do
        proxy.client.should == client
      end

      it "should contain the access token" do
        proxy.access_token.should == access_token
      end

      it "should contain the refresh token" do
        proxy.refresh_token.should == refresh_token
      end
    end

  end

  describe "mocking" do
    let(:client) { Borneo::Client.new(client_id, client_secret, redirect_url) }

    it "defaults to not mocking" do
      client.should_not be_mocking_requests
    end

    it "can be set globally to use a mock rather than calling external services" do
      Borneo::Client.enable_mocking!
      client.should be_mocking_requests
    end

    it "can be set globally to disable mocking" do
      Borneo::Client.enable_mocking!
      client.should be_mocking_requests
      Borneo::Client.disable_mocking!
      client.should_not be_mocking_requests
    end

    describe "stub_service" do
      it "should return a mock service" do
        Borneo::Client.stub_service('plus', 'v1').should be_a(Borneo::Mock::Service)
      end
    end

  end

end


text:
package org.apache.ignite.internal.util.lang;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.apache.ignite.internal.util.tostring.GridToStringInclude;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.jetbrains.annotations.Nullable;

/**
 * Convenience class representing mutable tuple of four values.
 *
Thread Safety

 * This class doesn't provide any synchronization for multi-threaded access
 * and it is responsibility of the user of this class to provide outside
 * synchronization, if needed.
 * @see GridFunc#t4()
 * @see GridFunc#t(Object, Object, Object, Object)
 */
public class GridTuple4<V1, V2, V3, V4> implements Iterable<Object>, Externalizable, Cloneable {
    /** */
    private static final long serialVersionUID = 0L;

    /** Value 1. */
    @GridToStringInclude
    private V1 val1;

    /** Value 2. */
    @GridToStringInclude
    private V2 val2;

    /** Value 3. */
    @GridToStringInclude
    private V3 val3;

    /** Value 4. */
    @GridToStringInclude
    private V4 val4;

    /**
     * Empty constructor required by {@link Externalizable}.
     */
    public GridTuple4() {
        // No-op.
    }

    /**
     * Fully initializes this tuple.
     *
     * @param val1 First value.
     * @param val2 Second value.
     * @param val3 Third value.
     * @param val4 Forth value.
     */
    public GridTuple4(@Nullable V1 val1, @Nullable V2 val2, @Nullable V3 val3, @Nullable V4 val4) {
        this.val1 = val1;
        this.val2 = val2;
        this.val3 = val3;
        this.val4 = val4;
    }

    /**
     * Gets first value.
     *
     * @return First value.
     */
    @Nullable public V1 get1() {
        return val1;
    }

    /**
     * Gets second value.
     *
     * @return Second value.
     */
    @Nullable public V2 get2() {
        return val2;
    }

    /**
     * Gets third value.
     *
     * @return Third value.
     */
    @Nullable public V3 get3() {
        return val3;
    }

    /**
     * Gets forth value.
     *
     * @return Forth value.
     */
    @Nullable public V4 get4() {
        return val4;
    }

    /**
     * Sets first value.
     *
     * @param val1 First value.
     */
    public void set1(@Nullable V1 val1) {
        this.val1 = val1;
    }

    /**
     * Sets second value.
     *
     * @param val2 Second value.
     */
    public void set2(@Nullable V2 val2) {
        this.val2 = val2;
    }

    /**
     * Sets third value.
     *
     * @param val3 Third value.
     */
    public void set3(@Nullable V3 val3) {
        this.val3 = val3;
    }

    /**
     * Sets fourth value.
     *
     * @param val4 Fourth value.
     */
    public void set4(@Nullable V4 val4) {
        this.val4 = val4;
    }

    /**
     * Sets all values.
     *
     * @param val1 First value.
     * @param val2 Second value.
     * @param val3 Third value.
     * @param val4 Fourth value.
     */
    public void set(@Nullable V1 val1, @Nullable V2 val2, @Nullable V3 val3, @Nullable V4 val4) {
        set1(val1);
        set2(val2);
        set3(val3);
        set4(val4);
    }

    /** {@inheritDoc} */
    @Override public Iterator<Object> iterator() {
        return new Iterator<Object>() {
            private int nextIdx = 1;

            @Override public boolean hasNext() {
                return nextIdx < 5;
            }

            @Nullable @Override public Object next() {
                if (!hasNext())
                    throw new NoSuchElementException();

                Object res = null;

                if (nextIdx == 1)
                    res = get1();
                else if (nextIdx == 2)
                    res = get2();
                else if (nextIdx == 3)
                    res = get3();
                else if (nextIdx == 4)
                    res = get4();

                nextIdx++;

                return res;
            }

            @Override public void remove() {
                throw new UnsupportedOperationException();
            }
        };
    }

    /** {@inheritDoc} */
    @SuppressWarnings({"CloneDoesntDeclareCloneNotSupportedException"})
    @Override public Object clone() {
        try {
            return super.clone();
        }
        catch (CloneNotSupportedException ignore) {
            throw new InternalError();
        }
    }

    /** {@inheritDoc} */
    @Override public void writeExternal(ObjectOutput out) throws IOException {
        out.writeObject(val1);
        out.writeObject(val2);
        out.writeObject(val3);
        out.writeObject(val4);
    }

    /** {@inheritDoc} */
    @SuppressWarnings({"unchecked"})
    @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        val1 = (V1)in.readObject();
        val2 = (V2)in.readObject();
        val3 = (V3)in.readObject();
        val4 = (V4)in.readObject();
    }

    /** {@inheritDoc} */
    @Override public boolean equals(Object o) {
        if (this == o)
            return true;

        if (!(o instanceof GridTuple4))
            return false;

        GridTuple4<?, ?, ?, ?> t = (GridTuple4<?, ?, ?, ?>)o;

        return F.eq(val1, t.val2) && F.eq(val2, t.val2) && F.eq(val3, t.val3) && F.eq(val4, t.val4);
    }

    /** {@inheritDoc} */
    @Override public int hashCode() {
        int res = val1 != null ? val1.hashCode() : 0;

        res = 13 * res + (val2 != null ? val2.hashCode() : 0);
        res = 17 * res + (val3 != null ? val3.hashCode() : 0);
        res = 19 * res + (val4 != null ? val4.hashCode() : 0);

        return res;
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return S.toString(GridTuple4.class, this);
    }
}


text:
namespace WpfControlsLib.Controls.Toolbar.StandardButtonsAndMenus
{
    using System.Collections.Generic;
    using Controller;
    using EditorPluginInterfaces;
    using EditorPluginInterfaces.Toolbar;

    public class SampleButtonsCollection
    {
        public SampleButtonsCollection(IConsole console, Controller controller)
        {
            var undoAction = new Command(() => { controller.Undo(); });
            var redoAction = new Command(() => { controller.Redo(); });
            var undoImage = "pack://application:,,,/" + "View/Pictures/Toolbar/undo.png";
            var redoImage = "pack://application:,,,/" + "View/Pictures/Toolbar/redo.png";
            var undoButton = new Button(undoAction, "Undo button", undoImage);
            var redoButton = new Button(redoAction, "Redo Button", redoImage);

            this.SampleButtons.Add(undoButton);
            this.SampleButtons.Add(redoButton);
        }

        public IList<IButton> SampleButtons { get; private set; } = new List<IButton>();
    }
}


text:
package common

import (
	"fmr/dal"
	"testing"
)

func TestFingerprintFilter(t *testing.T) {

	t.Run("EmptyFilter", testEmptyFilter)
	t.Run("FilenameFilter_Match_Extension", testFilenameFilterMatchExtension)
	t.Run("FilenameFilter_Match_Name", testFilenameFilterMatchName)
	t.Run("FilenameFilter_Match_NameNoAlgorithm", testFilenameFilterMatchNameNoAlgorithm)
	t.Run("FilenameFilter_NoMatch", testFilenameFilterNoMatch)
	t.Run("AlgorithmFilter_Match", testAlgorithmFilterMatch)
	t.Run("AlgorithmFilter_NoMatch_DifferentAlgorithm", testAlgorithmFilterNoMatchDifferentAlgorithm)
	t.Run("AlgorithmFilter_NoMatch_NotWellDefinedAlgorithm", testAlgorithmFilterNoMatchNotWellDefinedAlgorithm)
	t.Run("AllFilters", testAllFilters)
}

func testEmptyFilter(t *testing.T) {

	fp := createFingerprintWithNameAndAlg("sample-file-with_aWeird-name.txt", "crc32")
	filter := ""
	fpFilter := NewFingerprintFilter(filter)

	result := fpFilter.FilterFingerprint(fp)

	assertMatch(t, fp.Filename, filter, true, result)
}

func testFilenameFilterMatchExtension(t *testing.T) {

	fp := createFingerprintWithNameAndAlg("sample-file-with_aWeird-name.txt", "crc32")
	filter := ".txt"
	fpFilter := NewFingerprintFilter(filter)

	result := fpFilter.FilterFingerprint(fp)

	assertMatch(t, fp.Filename, filter, true, result)
}

func testFilenameFilterMatchName(t *testing.T) {

	fp := createFingerprintWithNameAndAlg("sample-file-with_aWeird-name.txt", "crc32")
	filter := "file-with"
	fpFilter := NewFingerprintFilter(filter)

	result := fpFilter.FilterFingerprint(fp)

	assertMatch(t, fp.Filename, filter, true, result)
}

func testFilenameFilterMatchNameNoAlgorithm(t *testing.T) {

	fp := createFingerprintWithNameAndAlg("sample-file-with_aWeird-name.txt", "crc32")
	filter := "file-with:"
	fpFilter := NewFingerprintFilter(filter)

	result := fpFilter.FilterFingerprint(fp)

	assertMatch(t, fp.Filename, filter, true, result)
}

func testFilenameFilterNoMatch(t *testing.T) {

	fp := createFingerprintWithNameAndAlg("sample-file-with_aWeird-name.txt", "crc32")
	filter := "f1le-with"
	fpFilter := NewFingerprintFilter(filter)

	result := fpFilter.FilterFingerprint(fp)

	assertMatch(t, fp.Filename, filter, false, result)
}

func testAlgorithmFilterMatch(t *testing.T) {

	fp := createFingerprintWithNameAndAlg("sample-file-with_aWeird-name.txt", "sha512")
	filter := ":sha512"
	fpFilter := NewFingerprintFilter(filter)

	result := fpFilter.FilterFingerprint(fp)

	assertMatch(t, fp.Algorithm, filter, true, result)
}

func testAlgorithmFilterNoMatchDifferentAlgorithm(t *testing.T) {

	fp := createFingerprintWithNameAndAlg("sample-file-with_aWeird-name.txt", "sha512")
	filter := ":crc32"
	fpFilter := NewFingerprintFilter(filter)

	result := fpFilter.FilterFingerprint(fp)

	assertMatch(t, fp.Algorithm, filter, false, result)
}

func testAlgorithmFilterNoMatchNotWellDefinedAlgorithm(t *testing.T) {

	fp := createFingerprintWithNameAndAlg("sample-file-with_aWeird-name.txt", "sha512")
	filter := ":sha"
	fpFilter := NewFingerprintFilter(filter)

	result := fpFilter.FilterFingerprint(fp)

	assertMatch(t, fp.Algorithm, filter, false, result)
}

func testAllFilters(t *testing.T) {

	fp := createFingerprintWithNameAndAlg("sample-file-with_aWeird-name.txt", "sha512")
	filter := "sample:sha512"
	fpFilter := NewFingerprintFilter(filter)

	result := fpFilter.FilterFingerprint(fp)

	assertMatch(t, fp.Filename+" | "+fp.Algorithm, filter, true, result)
}

func createFingerprintWithNameAndAlg(filename string, algorithm string) *dal.Fingerprint {

	return &dal.Fingerprint{filename, nil, algorithm, "", "", ""}
}

func assertMatch(t *testing.T, filteredText string, filter string, shouldMatch bool, match bool) {

	if shouldMatch && !match {
		t.Errorf("\"%s\" should match filter \"%s\".", filteredText, filter)
	} else if !shouldMatch && match {
		t.Errorf("\"%s\" should not match filter \"%s\".", filteredText, filter)
	}
}


text:
module Capistrano
  # Bundle
  module Bundle
    # Copy
    module Copy
      # Quick-Access to this gems root directory
      #
      # @return [String] Root directory of this gem
      def self.root_path
        File.expand_path('../../../..', __FILE__)
      end
    end
  end
end

require 'capistrano/bundle/copy/version'
require 'capistrano/bundle/copy/deploy'


text:
@interface OLALayout : OLAContainer

@end


text:
Contacto

<form method="POST" class="form-horizontal">
    <input type="hidden" name="_csrf"/>

        Nombre

            <input type="text" name="name" id="name" autofocus="autofocus" class="form-control"/>

        Email

            <input type="text" name="email" id="email" class="form-control"/>

        Cuentanos

            <textarea name="message" id="message" rows="7" class="form-control"></textarea>

            <button type="submit" class="btn btn-primary">Enviar</button>

</form>


text:
package org.stummi.factorio.gui;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import lombok.Getter;

import org.stummi.factorio.data.EntityLoader;
import org.stummi.factorio.data.Item;
import org.stummi.factorio.data.ItemThroughput;
import org.stummi.factorio.data.Throughput;

public class GoalTable extends TableView<GoalTable.Entry> implements Observable {
	@Getter
	class Entry {
		final ObjectProperty<Item> item = new SimpleObjectProperty<>();
		final ObjectProperty<Throughput> throughput = new SimpleObjectProperty<>(
				Throughput.NONE);

		public Entry() {
			InvalidationListener il = e -> fireInvalidate();
			item.addListener(il);
			throughput.addListener(il);
		}

		public ItemThroughput toItemThroughput() {
			return new ItemThroughput(item.get(), throughput.get());
		}
	}

	private final List<InvalidationListener> listeners = new ArrayList<>();

	public GoalTable(EntityLoader loader, JFXImageFactory imageFactory) {
		ObservableList<Item> items = FXCollections.observableArrayList(loader
				.getItems().values());
		Collections.sort(items, Comparator.comparing(Item::getName));

		TableColumn<GoalTable.Entry, Item> itemCol = new TableColumn<>("item");
		itemCol.setCellValueFactory(cda -> cda.getValue().getItem());
		itemCol.setCellFactory(tc -> new NameAndIconTableCell<>(imageFactory,
				items));

		TableColumn<GoalTable.Entry, Throughput> throughputCol = new TableColumn<>(
				"Prod / Min");
		throughputCol
				.setCellValueFactory(cda -> cda.getValue().getThroughput());
		throughputCol.setCellFactory(tc -> new AcceptOnExitTableCell<>(
				new ThroughputStringConverter()));

		getColumns().add(itemCol);
		getColumns().add(throughputCol);

		MenuItem addItem = new MenuItem("New");
		addItem.setOnAction(ae -> newItem());

		MenuItem delItem = new MenuItem("Remove Selected");
		delItem.setOnAction(ae -> deleteSelected());

		ContextMenu menu = new ContextMenu(addItem, delItem);
		setContextMenu(menu);

		getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
	}

	private void deleteSelected() {
		getItems().removeAll(getSelectionModel().getSelectedItems());
	}

	private void newItem() {
		getItems().add(new Entry());
	}

	public List<ItemThroughput> getGoals() {
		return getItems().stream().filter(
				e -> (e.item.get() != null && e.throughput.get()
						.amountPerMinute() > 0)).map(Entry::toItemThroughput)
						.collect(Collectors.toList());
	}

	@Override
	public void addListener(InvalidationListener listener) {
		listeners.add(listener);
	}

	@Override
	public void removeListener(InvalidationListener listener) {
		listeners.remove(listener);
	}

	public void fireInvalidate() {
		listeners.forEach(li -> li.invalidated(this));
	}
}


text:
package main

import (
	"context"
	"log"

	"github.com/google/go-containerregistry/pkg/authn/k8schain"
	"github.com/google/go-containerregistry/pkg/name"
	"github.com/google/go-containerregistry/pkg/v1/remote"
)

func main() {
	ref, err := name.NewTag("gcr.io/build-crd-testing/secret-sauce:latest")
	if err != nil {
		log.Fatalf("NewTag() = %v", err)
	}

	kc, err := k8schain.NewInCluster(context.Background(), k8schain.Options{
		Namespace: "explicit-namespace",
		ImagePullSecrets: []string{
			"explicit-secret",
		},
	})
	if err != nil {
		log.Fatalf("k8schain.New() = %v", err)
	}

	img, err := remote.Image(ref, remote.WithAuthFromKeychain(kc))
	if err != nil {
		log.Fatalf("remote.Image() = %v", err)
	}

	digest, err := img.Digest()
	if err != nil {
		log.Fatalf("Digest() = %v", err)
	}
	log.Printf("got digest: %v", digest)
}


text:
<?php

namespace Good\Memory\SQL;

use Good\Memory\Database as Database;

use Good\Memory\SQLStorage;
use Good\Manners\Condition;
use Good\Manners\Resolver;
use Good\Manners\ResolverVisitor;

class Selecter implements ResolverVisitor
{
    private $db;
    private $storage;

    private $subquery;

    private $currentTable;
    private $currentTableName;

    private $orderLayer;

    private $currentPropertyIsCollection;

    public function __construct(SQLStorage $storage, Database\Database $db, $currentTable)
    {
        $this->db = $db;
        $this->storage = $storage;
        $this->currentTable = $currentTable;
    }

    public function select($datatypeName, Condition $condition, Resolver $resolver)
    {
        $orderRootLayer = new OrderLayer(0);
        $this->orderLayer = $orderRootLayer;
        $this->currentPropertyIsCollection = false;

        $this->columns = [];
        $this->columns[] = new SelectColumn("t0", "id", "t0_id");

        $this->currentTableName = $this->storage->tableNamify($datatypeName);

        $resolver->acceptResolverVisitor($this);
        $order = $this->gatherOrderClauses($orderRootLayer);

        $sql = $this->writeQueryForColumns($datatypeName, $condition, $this->columns, $order);

        $this->db->query($sql);

        return $this->db->getResult();
    }

    private function columnToSelectClause($column)
    {
        $clause  = '`' . $column->table . '`';
        $clause .= '.`' . $column->column . '`';
        $clause .= ' AS `' . $column->as . '`';

        return $clause;
    }

    public function writeQueryForColumns($datatypeName, Condition $condition, $columns, $order)
    {
        $sql = "SELECT DISTINCT ";

        $columnsSQL = array_map([$this, 'columnToSelectClause'], $columns);
        $sql .= \implode(', ', $columnsSQL);

        $sql .= " FROM `" . $this->storage->tableNamify($datatypeName) . "` AS t0";

        $conditionWriter = new ConditionWriter($this->storage, 0, $datatypeName);
        $conditionWriter->writeCondition($condition);

        foreach ($this->storage->getJoins() as $somejoins)
        {
            foreach ($somejoins as $join)
            {
                $sql .= ' LEFT JOIN `' . $this->storage->tableNamify($join->tableNameDestination) .
                                                    '` AS `t' . $join->tableNumberDestination . '`';
                $sql .= ' ON `t' . $join->tableNumberOrigin . '`.`' .
                                            $this->storage->fieldNamify($join->fieldNameOrigin) . '`';
                $sql .= ' = `t' . $join->tableNumberDestination . '`.`' . $join->fieldNameDestination . '`';
            }
        }

        $sql .= ' WHERE ' . $conditionWriter->getCondition();

        if (count($conditionWriter->getHaving()) > 0)
        {
            $groupBySQL = array_map([$this, 'getEscapedAs'], $columns);

            $sql .= ' GROUP BY ' . \implode(', ', $groupBySQL);

            $sql .= ' HAVING ' . \implode(' AND ', $conditionWriter->getHaving());
        }

        if (\count($order) > 0)
        {
            $sql .= ' ORDER BY ';
            $sql .= \implode(', ', $order);
        }

        return $sql;
    }

    private function getEscapedAs($column)
    {
        return '`' . $column->as . '`';
    }

    private function gatherOrderClauses($orderLayer)
    {
        $orderClauses = $orderLayer->orderClauses;
        \ksort($orderClauses);

        if (count($orderLayer->childLayers) > 0)
        {
            $orderClauses[] = '`t' . $orderLayer->rootTableNumber . '`.`id` ASC';
        }

        foreach ($orderLayer->childLayers as $childLayer)
        {
            $childOrderClauses = $this->gatherOrderClauses($childLayer);

            $orderClauses = array_merge($orderClauses, $childOrderClauses);
        }

        return $orderClauses;
    }

    public function resolverVisitResolvedReferenceProperty($name, $datatypeName, Resolver $resolver)
    {
        $this->currentPropertyIsCollection = false;

        $this->writeSelectJoinedFields($this->currentTable, $datatypeName, $resolver, $name, 'id', null, true);
    }

    public function resolverVisitResolvedScalarCollectionProperty($name)
    {
        $this->currentPropertyIsCollection = true;

        $this->writeSelectJoinedFields($this->currentTable, $this->currentTableName . '_' . $name, null, 'id', 'owner', $name, false);
    }

    public function resolverVisitResolvedReferenceCollectionProperty($name, $typeName, Resolver $resolver)
    {
        $this->currentPropertyIsCollection = true;

        $table = $this->writeSelectJoinedFields($this->currentTable, $this->currentTableName . '_' . $name, null, 'id', 'owner', $name, false);
        $this->writeSelectJoinedFields($table, $typeName, $resolver, 'value', 'id', null, false);
    }

    public function writeSelectJoinedFields($leftTableNumber, $joinTable, ?Resolver $resolver,
        $currentTableJoinField, $otherTableJoinField, $collectionField, $selectJoinField)
    {
        if ($selectJoinField)
        {
            $table = 't' . $leftTableNumber;
            $column = $this->storage->fieldNamify($currentTableJoinField);
            $as = $table . '_' . $column;

            $this->columns[] = new SelectColumn($table, $column, $as);
        }

        $join = $this->storage->createJoin($leftTableNumber,
                                           $currentTableJoinField,
                                           $joinTable,
                                           $otherTableJoinField,
                                           $collectionField);

        if ($collectionField === null)
        {
            $this->columns[] = new SelectColumn('t' . $join, 'id', 't' . $join . '_id');
        }
        else
        {
            $table = 't' . $join;
            $column = 'value';
            $as = 't' . $leftTableNumber . '_' . $this->storage->fieldNamify($collectionField);

            $this->columns[] = new SelectColumn($table, $column, $as);
        }

        if ($resolver != null)
        {
            $currentTable = $this->currentTable;
            $currentTableName = $this->currentTableName;
            $this->currentTable = $join;
            $this->currentTableName = $joinTable;

            if ($collectionField !== null)
            {
                $orderLayer = $this->orderLayer;
                $this->orderLayer = new OrderLayer($join);
                $orderLayer->childLayers[] = $this->orderLayer;
            }

            $resolver->acceptResolverVisitor($this);

            if ($collectionField !== null)
            {
                $this->orderLayer = $orderLayer;
            }

            $this->currentTable = $currentTable;
            $this->currentTableName = $currentTableName;
        }

        return $join;
    }

    public function resolverVisitUnresolvedReferenceProperty($name)
    {
        $this->currentPropertyIsCollection = false;
    }

    public function resolverVisitUnresolvedCollectionProperty($name)
    {
        $this->currentPropertyIsCollection = true;
    }

    public function resolverVisitScalarProperty($name)
    {
        $this->currentPropertyIsCollection = false;

        $table = 't' . $this->currentTable;
        $column = $this->storage->fieldNamify($name);
        $as = $table . '_' . $column;

        $this->columns[] = new SelectColumn($table, $column, $as);
    }

    public function resolverVisitOrderAsc($number, $name)
    {
        $this->writeOrderTerm($number, $name, 'ASC');
    }

    public function resolverVisitOrderDesc($number, $name)
    {
        $this->writeOrderTerm($number, $name, 'DESC');
    }

    private function writeOrderTerm($number, $name, $direction)
    {
        $clause = '`t' . $this->currentTable . '_' .
            $this->storage->fieldnamify($name) . '` ' . $direction;

        if ($this->currentPropertyIsCollection)
        {
            // We don't know the table number here, but we do know it's not relevant...
            $childOrderLayer = new OrderLayer(null, [$number => $clause]);
            $this->orderLayer->childLayers[] = $childOrderLayer;
        }
        else
        {
            $this->orderLayer->orderClauses[$number] = $clause;
        }
    }
}

?>


text:
**To create an API in the specified region**

Command::

  aws apigateway create-rest-api --name 'My First API' --description 'This is my first API' --region us-west-2

**To create a duplicate API in the specified region from an existing API in the same region**

Command::

  aws apigateway create-rest-api --name 'Copy of My First API' --description 'This is a copy of my first API' --clone-from 1234123412 --region us-west-2


text:
namespace matCUDA
{
	// eig decomposition

	template <typename TElement>
	cublasStatus_t mixedOperations<TElement>::eig( Array<TElement> *A, Array<TElement> *eigvec )
	{
		cusolverDnHandle_t handleCusolver;
		CUSOLVER_CALL( cusolverDnCreate(&handleCusolver) );

		cublasHandle_t handleCublas;
		CUBLAS_CALL( cublasCreate( &handleCublas ) );

		cusolverOperations<TElement> opCusolver;
		cublasOperations<TElement> opCublas;
		mixedOperations<TElement> test;

		int M = A->getDim(0);
		int N = A->getDim(1);
		int minMN = std::min(M,N);
		TElement alpha = 1, beta = 0;

		TElement *d_A, *TAU, *Workspace, *d_Q, *d_R;
		CUDA_CALL( cudaMalloc(&d_A, M * N * sizeof(TElement)) );
		CUDA_CALL( cudaMalloc(&d_Q, M * N * sizeof(TElement)) );
		CUDA_CALL( cudaMalloc(&d_R, M * N * sizeof(TElement)) );
		CUDA_CALL( cudaMemcpy(d_A, A->data(), M * N * sizeof(TElement), cudaMemcpyHostToDevice) );

		int Lwork = 0;
		CUSOLVER_CALL( opCusolver.cusolverDnTgeqrf_bufferSize(&handleCusolver, M, N, d_A, M, &Lwork) );
		CUDA_CALL( cudaMalloc(&TAU, minMN * sizeof(TElement)) );
		CUDA_CALL(cudaMalloc(&Workspace, Lwork * sizeof(TElement)));

		int *devInfo;
		CUDA_CALL( cudaMalloc(&devInfo, sizeof(int)) );
		CUDA_CALL( cudaMemset( (void*)devInfo, 0, 1 ) );

		Array<TElement> aux( M, N );
		aux = 0;
		aux.print();
		CUDA_CALL( cudaMemcpy(d_Q, aux.data(), M * N * sizeof(TElement), cudaMemcpyHostToDevice) );

		int devInfo_h = 0;
		for( int i = 0; i < EIG_MAX_ITER; i++ ) {

			CUSOLVER_CALL( opCusolver.cusolverDnTgeqrf(&handleCusolver, M, N, d_A, M, TAU, Workspace, Lwork, devInfo) );

			CUDA_CALL( cudaMemcpy(&devInfo_h, devInfo, sizeof(int), cudaMemcpyDeviceToHost) );
			if (devInfo_h != 0)
				return CUBLAS_STATUS_INTERNAL_ERROR;

			// evaluate R
			CUDA_CALL( cudaMemcpy( d_R, d_A, M * N * sizeof(TElement), cudaMemcpyDeviceToDevice ) );
			zeros_under_diag( d_R, std::min( M, N ) );

			// evaluate Q
			cuda_eye<TElement>( d_Q, minMN );
			CUSOLVER_CALL( opCusolver.cusolverDnTormqr(&handleCusolver, CUBLAS_SIDE_LEFT, CUBLAS_OP_N, M, N, std::min(M, N), d_A, M, TAU, d_Q, M, Workspace, Lwork, devInfo) );

			// checkout
			CUDA_CALL( cudaMemcpy( aux.data(), d_Q, M * N * sizeof(TElement), cudaMemcpyDeviceToHost ) );
			aux.print();

			// evaluate new A = R*Q
			CUBLAS_CALL( opCublas.cublasTgemm(handleCublas, CUBLAS_OP_N, CUBLAS_OP_N, minMN, minMN, minMN, &alpha, d_R, minMN, d_Q, minMN, &beta, d_A, minMN) );

			//// checkout
			//CUDA_CALL( cudaMemcpy( aux.data(), d_R, M * N * sizeof(TElement), cudaMemcpyDeviceToHost ) );
			//aux.print();

		}
		CUDA_CALL( cudaDeviceSynchronize() );

		CUDA_CALL( cudaMemcpy( A->data(), d_A, M * N * sizeof(TElement), cudaMemcpyDeviceToHost ) );
		CUDA_CALL( cudaMemcpy( eigvec->data(), d_Q, M * N * sizeof(TElement), cudaMemcpyDeviceToHost ) );

		CUDA_CALL( cudaFree( d_A ) );
		CUDA_CALL( cudaFree( d_Q ) );
		CUDA_CALL( cudaFree( d_R ) );

		CUSOLVER_CALL( cusolverDnDestroy(handleCusolver) );
		CUBLAS_CALL( cublasDestroy(handleCublas) );

		return CUBLAS_STATUS_SUCCESS;
	}

	template cublasStatus_t mixedOperations<int>::eig( Array<int> *A, Array<int> *eigenvectors );
	template cublasStatus_t mixedOperations<float>::eig( Array<float> *A, Array<float> *eigenvectors );
	template cublasStatus_t mixedOperations<double>::eig( Array<double> *A, Array<double> *eigenvectors );
	template cublasStatus_t mixedOperations<ComplexFloat>::eig( Array<ComplexFloat> *A, Array<ComplexFloat> *eigenvectors );
	template cublasStatus_t mixedOperations<ComplexDouble>::eig( Array<ComplexDouble> *A, Array<ComplexDouble> *eigenvectors );
}


text:
import math
import platform
import numpy as np
from skimage import measure, transform
import logging
import nibabel

from spinalcordtoolbox.image import Image
from spinalcordtoolbox.aggregate_slicewise import Metric
from spinalcordtoolbox.centerline.core import ParamCenterline, get_centerline
from spinalcordtoolbox.resampling import resample_nib
from spinalcordtoolbox.utils import sct_progress_bar

# NB: We use a threshold to check if an array is empty, instead of checking if it's exactly 0. This is because
# resampling can change 0 -> ~0 (e.g. 1e-16). See: https://github.com/spinalcordtoolbox/spinalcordtoolbox/issues/3402
NEAR_ZERO_THRESHOLD = 1e-6

def compute_shape(segmentation, angle_correction=True, param_centerline=None, verbose=1):
    """
    Compute morphometric measures of the spinal cord in the transverse (axial) plane from the segmentation.
    The segmentation could be binary or weighted for partial volume [0,1].

    :param segmentation: input segmentation. Could be either an Image or a file name.
    :param angle_correction:
    :param param_centerline: see centerline.core.ParamCenterline()
    :param verbose:
    :return metrics: Dict of class Metric(). If a metric cannot be calculated, its value will be nan.
    :return fit_results: class centerline.core.FitResults()
    """
    # List of properties to output (in the right order)
    property_list = ['area',
                     'angle_AP',
                     'angle_RL',
                     'diameter_AP',
                     'diameter_RL',
                     'eccentricity',
                     'orientation',
                     'solidity',
                     'length'
                     ]

    im_seg = Image(segmentation).change_orientation('RPI')
    # Getting image dimensions. x, y and z respectively correspond to RL, PA and IS.
    nx, ny, nz, nt, px, py, pz, pt = im_seg.dim
    pr = min([px, py])
    # Resample to isotropic resolution in the axial plane. Use the minimum pixel dimension as target dimension.
    im_segr = resample_nib(im_seg, new_size=[pr, pr, pz], new_size_type='mm', interpolation='linear')

    # Update dimensions from resampled image.
    nx, ny, nz, nt, px, py, pz, pt = im_segr.dim

    # Extract min and max index in Z direction
    data_seg = im_segr.data
    X, Y, Z = (data_seg > NEAR_ZERO_THRESHOLD).nonzero()
    min_z_index, max_z_index = min(Z), max(Z)

    # Initialize dictionary of property_list, with 1d array of nan (default value if no property for a given slice).
    shape_properties = {key: np.full_like(np.empty(nz), np.nan, dtype=np.double) for key in property_list}

    fit_results = None

    if angle_correction:
        # compute the spinal cord centerline based on the spinal cord segmentation
        # here, param_centerline.minmax needs to be False because we need to retrieve the total number of input slices
        _, arr_ctl, arr_ctl_der, fit_results = get_centerline(im_segr, param=param_centerline, verbose=verbose)

    # Loop across z and compute shape analysis
    for iz in sct_progress_bar(range(min_z_index, max_z_index + 1), unit='iter', unit_scale=False, desc="Compute shape analysis",
                               ascii=True, ncols=80):
        # Extract 2D patch
        current_patch = im_segr.data[:, :, iz]
        if angle_correction:
            # Extract tangent vector to the centerline (i.e. its derivative)
            tangent_vect = np.array([arr_ctl_der[0][iz - min_z_index] * px,
                                     arr_ctl_der[1][iz - min_z_index] * py,
                                     pz])
            # Normalize vector by its L2 norm
            tangent_vect = tangent_vect / np.linalg.norm(tangent_vect)
            # Compute the angle about AP axis between the centerline and the normal vector to the slice
            v0 = [tangent_vect[0], tangent_vect[2]]
            v1 = [0, 1]
            angle_AP_rad = np.math.atan2(np.linalg.det([v0, v1]), np.dot(v0, v1))
            # Compute the angle about RL axis between the centerline and the normal vector to the slice
            v0 = [tangent_vect[1], tangent_vect[2]]
            v1 = [0, 1]
            angle_RL_rad = np.math.atan2(np.linalg.det([v0, v1]), np.dot(v0, v1))
            # Apply affine transformation to account for the angle between the centerline and the normal to the patch
            tform = transform.AffineTransform(scale=(np.cos(angle_RL_rad), np.cos(angle_AP_rad)))
            # Convert to float64, to avoid problems in image indexation causing issues when applying transform.warp
            current_patch = current_patch.astype(np.float64)
            # TODO: make sure pattern does not go extend outside of image border
            current_patch_scaled = transform.warp(current_patch,
                                                  tform.inverse,
                                                  output_shape=current_patch.shape,
                                                  order=1,
                                                  )
        else:
            current_patch_scaled = current_patch
            angle_AP_rad, angle_RL_rad = 0.0, 0.0
        # compute shape properties on 2D patch
        shape_property = _properties2d(current_patch_scaled, [px, py])
        if shape_property is not None:
            # Add custom fields
            shape_property['angle_AP'] = angle_AP_rad * 180.0 / math.pi
            shape_property['angle_RL'] = angle_RL_rad * 180.0 / math.pi
            shape_property['length'] = pz / (np.cos(angle_AP_rad) * np.cos(angle_RL_rad))
            # Loop across properties and assign values for function output
            for property_name in property_list:
                shape_properties[property_name][iz] = shape_property[property_name]
        else:
            logging.warning('\nNo properties for slice: {}'.format(iz))

        """ DEBUG
        from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
        from matplotlib.figure import Figure
        fig = Figure()
        FigureCanvas(fig)
        ax = fig.add_subplot(111)
        ax.imshow(current_patch_scaled)
        ax.grid()
        ax.set_xlabel('y')
        ax.set_ylabel('x')
        fig.savefig('tmp_fig.png')
        """
    metrics = {}
    for key, value in shape_properties.items():
        # Making sure all entries added to metrics have results
        if not value == []:
            metrics[key] = Metric(data=np.array(value), label=key)

    return metrics, fit_results

def _properties2d(image, dim):
    """
    Compute shape property of the input 2D image. Accounts for partial volume information.
    :param image: 2D input image in uint8 or float (weighted for partial volume) that has a single object.
    :param dim: [px, py]: Physical dimension of the image (in mm). X,Y respectively correspond to AP,RL.
    :return:
    """
    upscale = 5  # upscale factor for resampling the input image (for better precision)
    pad = 3  # padding used for cropping
    # Check if slice is empty
    if np.all(image < NEAR_ZERO_THRESHOLD):
        logging.debug('The slice is empty.')
        return None
    # Normalize between 0 and 1 (also check if slice is empty)
    image_norm = (image - image.min()) / (image.max() - image.min())
    # Convert to float64
    image_norm = image_norm.astype(np.float64)
    # Binarize image using threshold at 0. Necessary input for measure.regionprops
    image_bin = np.array(image_norm > 0.5, dtype='uint8')
    # Get all closed binary regions from the image (normally there is only one)
    regions = measure.regionprops(image_bin, intensity_image=image_norm)
    # Check number of regions
    if len(regions) > 1:
        logging.debug('There is more than one object on this slice.')
        return None
    region = regions[0]
    # Get bounding box of the object
    minx, miny, maxx, maxy = region.bbox
    # Use those bounding box coordinates to crop the image (for faster processing)
    image_crop = image_norm[np.clip(minx-pad, 0, image_bin.shape[0]): np.clip(maxx+pad, 0, image_bin.shape[0]),
                 np.clip(miny-pad, 0, image_bin.shape[1]): np.clip(maxy+pad, 0, image_bin.shape[1])]
    # Oversample image to reach sufficient precision when computing shape metrics on the binary mask
    image_crop_r = transform.pyramid_expand(image_crop, upscale=upscale, sigma=None, order=1)
    # Binarize image using threshold at 0. Necessary input for measure.regionprops
    image_crop_r_bin = np.array(image_crop_r > 0.5, dtype='uint8')
    # Get all closed binary regions from the image (normally there is only one)
    regions = measure.regionprops(image_crop_r_bin, intensity_image=image_crop_r)
    region = regions[0]
    # Compute area with weighted segmentation and adjust area with physical pixel size
    area = np.sum(image_crop_r) * dim[0] * dim[1] / upscale ** 2
    # Compute ellipse orientation, modulo pi, in deg, and between [0, 90]
    orientation = fix_orientation(region.orientation)
    # Find RL and AP diameter based on major/minor axes and cord orientation=
    [diameter_AP, diameter_RL] = \
        _find_AP_and_RL_diameter(region.major_axis_length, region.minor_axis_length, orientation,
                                 [i / upscale for i in dim])
    # TODO: compute major_axis_length/minor_axis_length by summing weighted voxels along axis
    # Deal with https://github.com/spinalcordtoolbox/spinalcordtoolbox/issues/2307
    if any(x in platform.platform() for x in ['Darwin-15', 'Darwin-16']):
        solidity = np.nan
    else:
        solidity = region.solidity
    # Fill up dictionary
    properties = {'area': area,
                  'diameter_AP': diameter_AP,
                  'diameter_RL': diameter_RL,
                  'centroid': region.centroid,
                  'eccentricity': region.eccentricity,
                  'orientation': orientation,
                  'solidity': solidity  # convexity measure
    }

    return properties

def fix_orientation(orientation):
    """Re-map orientation from skimage.regionprops from [-pi/2,pi/2] to [0,90] and rotate by 90deg because image axis
    are inverted"""
    orientation_new = orientation * 180.0 / math.pi
    if 360 <= abs(orientation_new) <= 540:
        orientation_new = 540 - abs(orientation_new)
    if 180 <= abs(orientation_new) <= 360:
        orientation_new = 360 - abs(orientation_new)
    if 90 <= abs(orientation_new) <= 180:
        orientation_new = 180 - abs(orientation_new)
    return abs(orientation_new)

def _find_AP_and_RL_diameter(major_axis, minor_axis, orientation, dim):
    """
    This script checks the orientation of the and assigns the major/minor axis to the appropriate dimension, right-
    left (RL) or antero-posterior (AP). It also multiplies by the pixel size in mm.
    :param major_axis: major ellipse axis length calculated by regionprops
    :param minor_axis: minor ellipse axis length calculated by regionprops
    :param orientation: orientation in degree. Ranges between [0, 90]
    :param dim: pixel size in mm.
    :return: diameter_AP, diameter_RL
    """
    if 0 <= orientation < 45.0:
        diameter_AP = minor_axis
        diameter_RL = major_axis
    else:
        diameter_AP = major_axis
        diameter_RL = minor_axis
    # Adjust with pixel size
    diameter_AP *= dim[0]
    diameter_RL *= dim[1]
    return diameter_AP, diameter_RL


text:
package org.kie.services.client.serialization.jaxb.impl.query;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;

@XmlRootElement(name="query-process-instance-result")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlSeeAlso({JaxbQueryProcessInstanceInfo.class})
public class JaxbQueryProcessInstanceResult {

    @XmlElement
    private List<JaxbQueryProcessInstanceInfo> processInstanceInfoList = new ArrayList<JaxbQueryProcessInstanceInfo>();

    public JaxbQueryProcessInstanceResult() {
        // default for JAXB
    }

    public List<JaxbQueryProcessInstanceInfo> getProcessInstanceInfoList() {
        return processInstanceInfoList;
    }

    public void setProcessInstanceInfoList( List<JaxbQueryProcessInstanceInfo> processInstanceInfoList ) {
        this.processInstanceInfoList = processInstanceInfoList;
    }
}