text:
/**
 * 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.
 *
 * @author Andreas Joelsson (andreas.joelsson@gmail.com)
 */
package io.github.scrier.opus.duke.commander;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

import io.github.scrier.opus.common.data.BaseDataC;
import io.github.scrier.opus.common.duke.DukeCommandReqMsgC;
import io.github.scrier.opus.common.duke.DukeCommandEnum;
import io.github.scrier.opus.common.duke.DukeCommandRspMsgC;
import io.github.scrier.opus.common.duke.DukeInfo;
import io.github.scrier.opus.common.duke.DukeMsgFactory;
import io.github.scrier.opus.common.message.BaseMsgC;

/**
 * Method to handle termination of another duke if duplicates are found.
 * @author andreas.joelsson
 */
public class TerminateDukeProcedure extends BaseDukeProcedure implements ITimeOutCallback {

	private static Logger log = LogManager.getLogger(TerminateDukeProcedure.class);

	private long id;
	private IProcedureWait callback;
	private DukeInfo duke;

	private final int statusTimeout = 5;		// Time in seconds that duke is allowed to respond in for a status message.
	private final int stopTimeout = 5;			// Time in seconds that duke is allowed to respond in for a stop message.
	private final int terminateTimeout = 5;	// Time in seconds that duke is allowed to respond in for a terminate message.
	private final int removeTimeout = 5;		// Time in seconds that duke is allowed to respond in for a remove of the other duke.

	protected final long STATUS_TIMEOUT_ID    = 456L;
	protected final long STOP_TIMEOUT_ID      = 457L;
	protected final long TERMINATE_TIMEOUT_ID = 458L;
	protected final long REMOVE_TIMEOUT_ID    = 459L;

	public final int WAITING_FOR_STATUS    = CREATED + 1;
	public final int WAITING_FOR_STOP      = CREATED + 2;
	public final int WAITING_FOR_TERMINATE = CREATED + 3;
	public final int WAITING_FOR_REMOVE    = CREATED + 4;

	private State[] states;

	/**
	 * Constructor
	 * @param identity the identity of the conflicting duke.
	 * @param callback interface to do callback to when done.
	 * @param otherDuke DukeInfo with the information about the other duke.
	 */
	public TerminateDukeProcedure(long identity, IProcedureWait callback, DukeInfo otherDuke) {
		log.trace("TerminateDukeProcedure(" + identity + ", " + callback + ", " +  otherDuke + ")");
		this.id = identity;
		this.callback = callback;
		this.duke = otherDuke;
		this.states = new State[WAITING_FOR_REMOVE + 1];
		this.states[ABORTED] = new Aborted();
		this.states[CREATED] = new Created();
		this.states[WAITING_FOR_STATUS] = new WaitingForStatus();
		this.states[WAITING_FOR_STOP] = new WaitingForStop();
		this.states[WAITING_FOR_TERMINATE] = new WaitingForTerminate();
		this.states[WAITING_FOR_REMOVE] = new WaitingForRemove();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void init() throws Exception {
		DukeCommandReqMsgC command = new DukeCommandReqMsgC(getSendIF());
		command.setDukeCommand(DukeCommandEnum.STATUS);
		command.setSource(getIdentity());
		command.setDestination(duke.getKey());
		command.setTxID(getTxID());
		command.send();
		startTimeout(statusTimeout, STATUS_TIMEOUT_ID, this);
		setState(WAITING_FOR_STATUS);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void shutDown() throws Exception {
		callback.procedureFinished(id, getState());
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int handleOnUpdated(BaseDataC value) {
		// do nothing
		return getState();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int handleOnEvicted(BaseDataC value) {
		// do nothing
		return getState();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int handleOnRemoved(Long key) {
		log.trace("handleOnRemoved(" + key + ")");
		log.debug("handleOnRemoved(" + key + ")");
		if( duke.getKey() == key ) {
			log.info("Duke is removed, we are done.");
			setState(COMPLETED);
		}
		return getState();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int handleInMessage(BaseMsgC message) {
		log.trace("handleInMessage(" + message + ")");
		switch( message.getId() ) {
			case DukeMsgFactory.DUKE_COMMAND_RSP: {
				DukeCommandRspMsgC command = new DukeCommandRspMsgC(message);
				handleMessage(command);
				break;
			}
		}
		return getState();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onStateChanged(int newState, int previousState) {
		log.trace("onStateChanged(" + newState + ", " + previousState + ")");
		try {
			if( COMPLETED != previousState ) {
				log.debug("states[" + states[previousState].getClass().getSimpleName() + "].cleanup();");
				states[previousState].cleanup();
			}
			if( COMPLETED != newState ) {
				log.debug("states[" + states[newState].getClass().getSimpleName() + "].init();");
				states[newState].init();
			}
		} catch ( ArrayIndexOutOfBoundsException e ) {
			log.fatal("Received ArrayIndexOutOfBoundsException in onStateChanged(" + newState + ", " + previousState + ") method.", e);
			theContext.getBaseAoC().shutDown();
		}
	}

	/**
	 * Method to handle the DukeCommand message
	 * @param message DukeCommandMsgC message.
	 */
	protected void handleMessage(DukeCommandRspMsgC message) {
		log.trace("handleMessage(" + message + ")");
		try {
			log.debug("states[" + states[getState()].getClass().getSimpleName() + "].handleMessage(" + message + ");");
			states[getState()].handleMessage(message);
		} catch ( ArrayIndexOutOfBoundsException e ) {
			if( COMPLETED == getState() ) {
				new Completed().handleMessage(message);
			} else {
				log.error("Received out of bound exception in state: " + getState() + ".", e);
				setState(ABORTED);
			}
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void timeOutTriggered(long id) {
		log.trace("timeOutTriggered(" + id + ")");
		try {
			log.debug("states[" + states[getState()].getClass().getSimpleName() + "].handleTimeOut(" + id + ");");
			states[getState()].handleTimeOut(id);
		} catch ( ArrayIndexOutOfBoundsException e ) {
			if( COMPLETED == getState() ) {
				new Completed().handleTimeOut(id);
			} else {
				log.error("Received out of bound exception in state: " + getState() + ".", e);
				setState(ABORTED);
			}
		}
	}

	/**
	 * Exposed method to subclasses to start timeouts.
	 * @param time int with the time in seconds.
	 * @param id that the timeout should have.
	 */
	public void startTimeout(int time, long id) {
		log.trace("startTimeout(" + time + ", " + id + ")");
		startTimeout(time,  id, this);
	}

	/**
	 * Method to initialize the terminate command.
	 */
	private void sendTerminateCommand() {
		log.trace("sendTerminateCommand()");
		DukeCommandReqMsgC pDukeCommandReq = new DukeCommandReqMsgC(getSendIF());
		pDukeCommandReq.setSource(getIdentity());
		pDukeCommandReq.setDestination(duke.getKey());
		pDukeCommandReq.setTxID(getTxID());
		pDukeCommandReq.setDukeCommand(DukeCommandEnum.TERMINATE);
		pDukeCommandReq.send();
		setState(WAITING_FOR_TERMINATE);
		startTimeout(terminateTimeout, TERMINATE_TIMEOUT_ID, this);
	}

	/**
	 * Base state for the FSM logic.
	 */
	public abstract class State {

		protected Logger logLocal;

		public State() {
			logLocal = LogManager.getLogger("io.github.scrier.opus.duke.commander.TerminateDukeProcedure.State");
		}

		/**
		 * Method to handle the DukeCommandMsgC in a specified state.
		 * @param message DukeCommandMsgC message to handle
		 */
		public void handleMessage(DukeCommandRspMsgC message) {
			logLocal.trace("handleMessage(" + message + ")");
			logLocal.error("Called default state when in state " + getState() + ", cannot continue.");
			setState(ABORTED);
		}

		/**
		 * Method to handle a timeout in a given state.
		 * @param id long identifying the unique id for the timeout.
		 */
		public void handleTimeOut(long id) {
			logLocal.trace("handleTimeOut(" + id + ")");
			logLocal.error("Called default state when in state " + getState() + ", cannot continue.");
			setState(ABORTED);
		}

		/**
		 * Method called before each state starts working.
		 * {@code
		 * setState(newState);
		 * oldState.cleanup();
		 * ...
		 * newState.init();
		 * ...
		 * }
		 */
		public abstract void init();

		/**
		 * Method called at the end of each state change.
		 * {@code
		 * setState(newState);
		 * oldState.cleanup();
		 * ...
		 * newState.init();
		 * ...
		 * }
		 */
		public abstract void cleanup();

	}

	/**
	 * Empty state for not handled information.
	 */
	public class Aborted extends State {

		public Aborted() {
			logLocal = LogManager.getLogger("io.github.scrier.opus.duke.commander.TerminateDukeProcedure.Aborted");
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void init() {
			logLocal.trace("init()");
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void cleanup() {
			logLocal.trace("cleanup()");
		}

	}

	/**
	 * Empty state for not handled information.
	 */
	public class Created extends State {

		public Created() {
			logLocal = LogManager.getLogger("io.github.scrier.opus.duke.commander.TerminateDukeProcedure.Created");
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void init() {
			logLocal.trace("init()");
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void cleanup() {
			logLocal.trace("cleanup()");
		}

	}

	/**
	 * State handling the Waiting For Status message.
	 */
	public class WaitingForStatus extends State {

		public WaitingForStatus() {
			logLocal = LogManager.getLogger("io.github.scrier.opus.duke.commander.TerminateDukeProcedure.WaitingForStatus");
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void handleMessage(DukeCommandRspMsgC message) {
			logLocal.trace("handleMessage(" + message + ")");
			if( getTxID() == message.getTxID() ) {
				log.info("Old duke is reporting the following information: \"" + message.getResponse() + "\", sending stop command.");
				terminateTimeout(STATUS_TIMEOUT_ID);
				DukeCommandReqMsgC pDukeCommand = new DukeCommandReqMsgC(getSendIF());
				pDukeCommand.setSource(getIdentity());
				pDukeCommand.setDestination(duke.getKey());
				pDukeCommand.setTxID(getTxID());
				pDukeCommand.setDukeCommand(DukeCommandEnum.STOP);
				pDukeCommand.send();
				startTimeout(stopTimeout, STOP_TIMEOUT_ID);
				setState(WAITING_FOR_STOP);
			}
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void handleTimeOut(long id) {
			logLocal.trace("handleTimeOut(" + id + ")");
			if( STATUS_TIMEOUT_ID == id ) {
				log.info("Timed out while waiting for the status feedback from duke with id: " + duke.getKey() + ", sending terminate command.");
				sendTerminateCommand();
			}
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void init() {
			logLocal.trace("init()");
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void cleanup() {
			logLocal.trace("cleanup()");
			if( isTimeoutActive(STATUS_TIMEOUT_ID) ) {
				terminateTimeout(STATUS_TIMEOUT_ID);
			}
		}

	}

	/**
	 * State handling the Waiting For Stop message.
	 */
	public class WaitingForStop extends State {

		public WaitingForStop() {
			logLocal = LogManager.getLogger("io.github.scrier.opus.duke.commander.TerminateDukeProcedure.WaitingForStop");
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void handleMessage(DukeCommandRspMsgC message) {
			logLocal.trace("handleMessage(" + message + ")");
			if( getTxID() == message.getTxID() ) {
				log.info("Old duke is reporting the following information from stop command: \"" + message.getResponse() + "\", waiting for removal from map.");
				terminateTimeout(STOP_TIMEOUT_ID);
				setState(WAITING_FOR_REMOVE);
				startTimeout(removeTimeout, REMOVE_TIMEOUT_ID);
			}
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void handleTimeOut(long id) {
			logLocal.trace("handleTimeOut(" + id + ")");
			if( STOP_TIMEOUT_ID == id ) {
				log.info("Timed out while waiting for the stop feedback from duke with id: " + duke.getKey() + ", sending terminate command.");
				sendTerminateCommand();
			}
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void init() {
			logLocal.trace("init()");
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void cleanup() {
			logLocal.trace("cleanup()");
			if( isTimeoutActive(STOP_TIMEOUT_ID) ) {
				terminateTimeout(STOP_TIMEOUT_ID);
			}
		}

	}

	/**
	 * State handling the Waiting For Terminate message.
	 */
	public class WaitingForTerminate extends State {

		public WaitingForTerminate() {
			logLocal = LogManager.getLogger("io.github.scrier.opus.duke.commander.TerminateDukeProcedure.WaitingForTerminate");
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void handleMessage(DukeCommandRspMsgC message) {
			logLocal.trace("handleMessage(" + message + ")");
			if( getTxID() == message.getTxID() ) {
				log.info("Old duke is reporting the following information from terminate command: \"" + message.getResponse() + "\", waiting for removal from map.");
				terminateTimeout(TERMINATE_TIMEOUT_ID);
				setState(WAITING_FOR_REMOVE);
				startTimeout(removeTimeout, REMOVE_TIMEOUT_ID);
			}
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void handleTimeOut(long id) {
			logLocal.trace("handleTimeOut(" + id + ")");
			if( TERMINATE_TIMEOUT_ID == id ) {
				log.info("Timed out while waiting for the terminutae feedback from duke with id: " + duke.getKey() + ", cannot continue.");
				setState(ABORTED);
			}
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void init() {
			logLocal.trace("init()");
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void cleanup() {
			logLocal.trace("cleanup()");
			if( isTimeoutActive(TERMINATE_TIMEOUT_ID) ) {
				terminateTimeout(TERMINATE_TIMEOUT_ID);
			}
		}

	}

	/**
	 * State handling the Waiting For Remove message.
	 */
	public class WaitingForRemove extends State {

		public WaitingForRemove() {
			logLocal = LogManager.getLogger("io.github.scrier.opus.duke.commander.TerminateDukeProcedure.WaitingForRemove");
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void handleMessage(DukeCommandRspMsgC message) {
			logLocal.trace("handleMessage(" + message + ")");
			// do nothing
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void handleTimeOut(long id) {
			logLocal.trace("handleTimeOut(" + id + ")");
			logLocal.info("Received timeout, should have terminated it with id: " + id + ".");
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void init() {
			logLocal.trace("init()");
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void cleanup() {
			logLocal.trace("cleanup()");
		}

	}

	/**
	 * Empty state for not handled information.
	 */
	public class Completed extends State {

		public Completed() {
			logLocal = LogManager.getLogger("io.github.scrier.opus.duke.commander.TerminateDukeProcedure.Completed");
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void init() {
			logLocal.trace("init()");
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void cleanup() {
			logLocal.trace("cleanup()");
		}

	}

}


text:
import React, { Component } from 'react';
import {
  Dimensions,
  Platform,
  StyleSheet,
  Text,
  TouchableOpacity,
} from 'react-native';

import * as Animatable from 'react-native-animatable';
import * as StoreReview from 'react-native-store-review';
import Icon from 'react-native-vector-icons/MaterialIcons';
import StarRating from 'react-native-star-rating';
import store from 'react-native-simple-store';

import I18n from '../utils/i18n';
import tracker from '../utils/tracker';
import { openURL } from '../utils/helpers';

import { config } from '../config';

const { height } = Dimensions.get('window');

const RATING_VERSION = 1;
const STARS_TO_APP_STORE = 4;
const SHOW_RATING_AFTER = 30 * 60 * 1000;

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    top: height / 3,
    margin: 15,
    padding: 15,
    alignItems: 'center',
    backgroundColor: 'rgba(255,255,255,0.96)',
    borderRadius: 8,
  },
  button: {
    marginTop: 6,
    padding: 10,
    backgroundColor: '#3B5998',
    borderRadius: 2,
  },
  ratingTitleText: {
    fontSize: 14,
    marginTop: 20,
  },
  ratingDescriptionText: {
    fontSize: 12,
    marginVertical: 15,
    textAlign: 'center',
  },
  feedbackDescriptionText: {
    color: 'white',
    fontSize: 14,
    textAlign: 'center',
  },
  close: {
    position: 'absolute',
    padding: 5,
    top: 6,
    right: 10,
  },
});

export default class Rating extends Component {
  static openFeedbackUrl() {
    const url = I18n.isZh ? config.feedbackUrl.zh : config.feedbackUrl.en;
    openURL(url);
  }

  state = {
    starCount: 0,
    isRatingClose: true,
  };

  componentDidMount() {
    const that = this;
    store.get(`isRatingGiven.${RATING_VERSION}`).then((isRatingGiven) => {
      if (isRatingGiven) {
        that.setState({ isRatingClose: true });
      } else {
        this.showRatingBlockTimeout = setTimeout(() => {
          that.setState({ isRatingClose: false });
        }, SHOW_RATING_AFTER);
      }
    });
  }

  componentWillUnmount() {
    if (this.showRatingBlockTimeout) clearTimeout(this.showRatingBlockTimeout);
  }

  onStarRatingPress(rating) {
    this.setState({
      starCount: rating,
    });

    let type;
    if (rating >= STARS_TO_APP_STORE) {
      if (StoreReview.isAvailable) {
        StoreReview.requestReview();
        type = 'inapp-store-review';
      } else if (Platform.OS === 'ios') {
        openURL(config.appStore);
        type = 'apple-store';
      } else if (Platform.OS === 'android') {
        openURL(config.googlePlay);
        type = 'google-play';
      }
    }

    store.save(`isRatingGiven.${RATING_VERSION}`, true);
    tracker.logEvent('give-rating', { type, rating: String(rating) });
  }

  render() {
    if (this.state.isRatingClose) {
      return null;
    }

    return (
      <Animatable.View style={styles.container} animation="fadeIn">
        <TouchableOpacity
          style={styles.close}
          onPress={() => this.setState({ isRatingClose: true })}
        >
          <Icon name="clear" size={24} color="#616161" />
        </TouchableOpacity>

        <Animatable.View animation="tada" iterationCount="infinite">
          <Icon name="thumb-up" size={32} color="#616161" />
        </Animatable.View>
        <Text style={styles.ratingTitleText}>{I18n.t('rating_title')}</Text>
        <Text style={styles.ratingDescriptionText}>
          {I18n.t('rating_description')}
        </Text>
        <StarRating
          starSize={36}
          rating={this.state.starCount}
          selectedStar={(rating) => this.onStarRatingPress(rating)}
        />
        {this.state.starCount > 0 && this.state.starCount < STARS_TO_APP_STORE && (
          <TouchableOpacity onPress={() => Rating.openFeedbackUrl()}>
            <Animatable.View style={styles.button} animation="fadeIn">
              <Text style={styles.feedbackDescriptionText}>
                {I18n.t('feedback_description')}
              </Text>
            </Animatable.View>
          </TouchableOpacity>
        )}
      </Animatable.View>
    );
  }
}

redpajama_set_name: RedPajamaGithub


text:
package de.fhg.igd.iva.colormaps.impl;

import static java.lang.Math.hypot;

import java.awt.Color;
import java.util.AbstractMap;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Function;

import de.fhg.igd.iva.colormaps.AbstractKnownColormap;
import de.fhg.igd.iva.colorspaces.CIELAB;

/**
 * Guo-style Lab 2D color spaces, based on functions that reflect the choices in the paper.
 * @author simon
 */
public abstract class GuoLabStyle extends AbstractKnownColormap
{
	private static final Logger logger = LoggerFactory.getLogger(GuoLabStyle.class);

	private Function<Double, Double> lightnessFunc;

	private Function<Map.Entry<Double, Double>, Map.Entry<Double, Double>> chromaFunc;

	/**
	 * @param lightnessFunc the lightness function, defined based on distance from the mid point 0..sqrt 2
	 * @param chromaFunc The chroma function, defined based on x and y as in {@link de.fhg.igd.iva.colormaps.KnownColormap#getColor(float, float)}
	 */
	public GuoLabStyle(Function<Double, Double> lightnessFunc, Function<Entry<Double, Double>, Entry<Double, Double>> chromaFunc)
	{
		this.lightnessFunc = lightnessFunc;
		this.chromaFunc = chromaFunc;
	}

	public static Function<Double, Double> cone(final float factor)
	{
		return (input) -> 100.0f - (input * factor);
	}

	public static Function<Double, Double> pseudoGaussian(float sigma)
	{
		final float sigmasquare = sigma * sigma;
		return input -> 100 * Math.exp(-((input * input) / 2 * sigmasquare));
	}

	public static Function<Map.Entry<Double, Double>, Map.Entry<Double, Double>> linearAB(final float xOffset,
			final float xFactor, final float yOffset, final float yFactor)
	{
		return input -> new AbstractMap.SimpleEntry<>(
						xOffset + input.getKey() * xFactor,
						yOffset + input.getValue() * yFactor);
	}

	public static Function<Map.Entry<Double, Double>, Map.Entry<Double, Double>> linearBa(
			final float xOffset,
			final float xFactor,
			final float yOffset,
			final float yFactor) {
		return input -> new AbstractMap.SimpleEntry<>(
						yOffset + input.getValue() * yFactor,
						xOffset + input.getKey() * xFactor);
	}

	@Override
	public Color getColor(double x, double y)
	{
		// normalize to -1..1
		double nx = x * 2 - 1;
		double ny = y * 2 - 1;
		double dist = (float) hypot(nx, ny);
		double light = lightnessFunc.apply(dist);
		Map.Entry<Double, Double> ab = chromaFunc.apply(new AbstractMap.SimpleEntry<>(nx, ny));
		double[] lab = new double[] { light, ab.getKey(), ab.getValue() };

		double[] rgb = CIELAB.lab2rgb(lab);

		for (int i = 0; i < rgb.length; i++)
		{
			// TODO clamp is not the best idea but it's unclear what Guo did
			// also ATM we do not have a way of evaluating the delta E in the UI
			// meaning we should have a color class supporting further analysis.
			if (rgb[i] < 0)
			{
				rgb[i] = 0;
				if (rgb[i] < -0.01)
				{
					logger.warn("Color channel {} was clamped from {} to 0", i, rgb[i]);
				}
			}

			if (rgb[i] > 1)
			{
				rgb[i] = 1;
				if (rgb[i] > 1.01)
				{
					logger.warn("Color channel {} was clamped from {} to 1", i, rgb[i]);
				}
			}

		}

		return new Color((float)rgb[0], (float)rgb[1], (float)rgb[2]);
	}

	@Override
	public de.fhg.igd.iva.colormaps.ColorSpace getColorSpace() {
		return de.fhg.igd.iva.colormaps.ColorSpace.CIE_Lab;
	}

}


text:
package com.oberasoftware.home.zwave.api.events.controller;

/**
 * @author renarj
 */
public class SendDataEvent extends SendDataStateEvent {
    private int nodeId;
    private int callbackId;

    public SendDataEvent(int nodeId, int callbackId, SEND_STATE sendState) {
        super(sendState);
        this.nodeId = nodeId;
        this.callbackId = callbackId;
    }

    public int getNodeId() {
        return nodeId;
    }

    public int getCallbackId() {
        return callbackId;
    }

    @Override
    public boolean isTransactionCompleted() {
        return getState() == SEND_STATE.SUCCESS;
    }

    @Override
    public String toString() {
        return "SendDataEvent{" +
                "nodeId=" + nodeId +
                ", callbackId=" + callbackId +
                ", sendState=" + getState() +
                '}';
    }
}


text:
// Copyright © 2017 - 2021 Chocolatey Software, Inc
// Copyright © 2011 - 2017 RealDimensions Software, LLC
//
// 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.

namespace chocolatey.infrastructure.app.utility
{
    //todo: #2560 maybe find a better name/location for this

    public static class ArgumentsUtility
    {
        public static bool arguments_contain_sensitive_information(string commandArguments)
        {
            //todo: #2561 this check is naive, we should switch to regex
            //this picks up cases where arguments are passed with '-' and '--'
            return commandArguments.contains("-install-arguments-sensitive")
             || commandArguments.contains("-package-parameters-sensitive")
             || commandArguments.contains("apikey ")
             || commandArguments.contains("config ")
             || commandArguments.contains("push ") // push can be passed w/out parameters, it's fine to log it then
             || commandArguments.contains("-p ")
             || commandArguments.contains("-p=")
             || commandArguments.contains("-password")
             || commandArguments.contains("-cp ")
             || commandArguments.contains("-cp=")
             || commandArguments.contains("-certpassword")
             || commandArguments.contains("-k ")
             || commandArguments.contains("-k=")
             || commandArguments.contains("-key ")
             || commandArguments.contains("-key=")
             || commandArguments.contains("-apikey")
             || commandArguments.contains("-api-key")
            ;
        }
    }
}


text:
layout: post
title: Building an invert index with Python sets.
---

Almost everybody has written about the Python [sets](https://docs.python.org/2/library/stdtypes.html#set) and a few
ones about the frozensets. Even thought the literature is still too much pragmatic and it lacks of real examples to
figure out daily problems, something that a Python coder practices almost unwittingly. Yesterday I had an Eureka
moment trying to find the right problem to show how *frozensets* can be used. This post shows how to build a full text
search engine through an [invert index](https://en.wikipedia.org/wiki/Inverted_index) using a few lines of Python and plenty
of memory RAM.

# The theory

An inverted index is fully used to implement full text search engines, at least the first document retrieval systems appeard many
years ago. The idea of the inverted index is process the words belonging to each document and create an entry, indexed in a sort way,
that looks to the proper document, meaning that index colision reprsents two or more documents sharing the words used by the index.

Once the index is created we can use the same index function to process the words given as a query params to retrieve those
documents that are related with the index entry. For instance, the following sentences are used as tweet entries of our
implementation:

{% highlight console %}
$ cat tweets.txt
This is a tweet about python and linux
This is a tweet about python and windows
This is a tweet about python and linux and windows
This is a tweet about rust
This is a tweet about the languages such as python running in linux
{% endhighlight console %}

A query composed by *Python* and *Windows* words would return just the second sentence.

In the implementation presented we are relaxing the use of boolean operands where we are going to use always *ANDs* between words.

# Frozensets as index function for the inverted index

The [Frozensets](https://docs.python.org/2/library/stdtypes.html#frozenset) are immutable sets and due its immutability are hasheable, this
characteristics fits very well to be used as a dictionary keys.

In the inverted index case, as we mentioned before, each document is going to be processed with a index function that takes the words belonging
to the document to create the proper index entry. We are going to **use the hash function of a frozenset as the inverted index function**.

The following snippet shows a few examples of the value got by the hash function:

{% highlight python %}

>>> hash(frozenset(['foo']))
4047620867903992349
>>> hash(frozenset(['bar']))
-9113672416919086926
>>> hash(frozenset(['foo', 'bar']))
4955649761666739161
>>> hash(frozenset(['bar', 'foo']))
4955649761666739161

{% endhighlight python %}

As you can notice the last two entries generate the same hash value, worth mentioning that **sets/frozensets have no sense of the order**. In the case of the
implementation shown is also a requirement, look up for documents with the *foo* and *bar* words irrespective of the order.

# Creating the index ready to be used by any search

Time and space are intimately coupled in terms of complexity, they usually are inversely proportional. This implementation chooses save in
in terms of cost of search - not in the processing step - to then use more memory. This election was based on the preference to make an extensive use of the frozensets.

As we saw before the frozenset can be used to get an unique hash value for a bunch of words, we can take profit of that characteristic
**creating as many entries to the inverted index as many unique combinations of words the document has**. For example, the following snippet shows
how with a bit of *itertools* sauce we are able to generate all of these needed hash values.

{% highlight python %}

>>> from itertools import combinations
>>> words = "my name is Foo and surname Bar".split(" ")
>>> for c in map(lambda i: combinations(words, i), xrange(1, len(words) + 1)):
...     print list(c)
...
[('my',), ('name',), ('is',), ('Foo',), ('and',), ('surname',), ('Bar',)]
[('my', 'name'), ('my', 'is'), ('my', 'Foo'), ('my', 'and'), ('my', 'surname'), ....

{% endhighlight python %}

The itertools [combinations](https://docs.python.org/2/library/itertools.html#itertools.combinations) helps us to create all of
these needed values that will be used as input of the inverted index function.

# Resolving positive words and negative words in a query

In the previous section we have seen how the inverted index key space is populated each time that a new document is inserted, but what value
will be used for each key?.

The documents by them self are stored as elements in a list and the positions are used as pointers, hereby the implementation uses the
positions as a way to identify and look up a document. Each value, regarding a key of the inverted index, **stores a set with all of the
document pointers**. For example the following snippet shows an example of how documents are index and stored to at last be linked between
both data structures:

{% highlight python %}

>>> l = ['Hi my name is Foo and my surname is Bar']
>>> d = { frozenset(['Foo', 'Bar']): set([0]), frozenset(['Foo', 'Bar', 'surname']): set([0]) }
>>> d[frozenset(['Foo', 'Bar'])]
set([0])
{% endhighlight python %}

As we can see each entry of the inverted index is in fact a *set*, it means that **we are able to do bitwise operations between
the different entries**. To get all of these documents that contain a certain words and not other ones it is a cinch.

# The implementation

The following snippet shows the final implementation putting all together. The *TextSearchIndex* publishes a interface
to add new documents and then find them by one or many words. The *find* method is used to retrieve those documents
that contain the desired words regarding either the positive or negative ones.

{% highlight python %}

import sys

from itertools import combinations
from collections import defaultdict

class TextSearchIndex(object):

    def __init__(self):
        self._texts = []
        self._index = defaultdict(set)

    def add(self, text):
        """Index a new `text` to become searchable by all of its words permutations.

        :param text: str.
        """
        self._texts.append(text)

        words = [reduce(lambda word, s: word.strip(s), [word] + [' ', '\n', ',', '.', ':', ';']) for word in text.split(' ')]
        for c in map(lambda i: combinations(words, i), xrange(1, len(words) + 1)):
            for words in c:
                self._index[frozenset(words)].add(len(self._texts) - 1)

    def find(self, words):
        """ Return a iteartor with all index entries that have this words, otherwise
        return a None.

        :param words: list of strings
        """
        return self._index.get(frozenset(words), set())

    def entry(self, index):
        """ Return a text regarding a index given.

        :param index: int.
        """
        return self._texts[index]

def main():
    t = TextSearchIndex()
    map(lambda line: t.add(line), sys.stdin.readlines())

    try:
        all_words = set(sys.argv[1:])
    except IndexError:
        print "Give some word!"
        sys.exit(1)

    negative_words = set(filter(lambda word: word[0] == '-', all_words))
    positive_words = all_words - negative_words

    if not positive_words:
        print "Give some none negative word!"
        sys.exit(1)

    indexes_with_chances = t.find(positive_words)
    for word in negative_words:
        indexes_with_chances -= t.find([word[1:]])  # remove the first `-` character

    for index in indexes_with_chances:
        print "Entry found: {}".format(t.entry(index))

if __name__ == '__main__':
    main()

{% endhighlight python %}

As an example we used a tweets corpus to search the tweets that have the have the words *python* and *linux* but not those tweets that have the word
*windows*,

{% highlight console %}
$ cat tweets.txt | ./text_search_index.py python linux -windows
Entry found: This is a tweet about python and linux

Entry found: This is a tweet about the languages such as python running in linux
{% endhighlight console %}


text:
//
// Created by Subhabrata Ghosh on 28/10/16.
//

#ifndef REACTFS_COMMON_STRUCTS_H
#define REACTFS_COMMON_STRUCTS_H

#include <atomic>

#include "common/includes/common.h"
#include "common/includes/base_error.h"
#include "block_common_structs_v0.h"

#define BLOCK_USAGE_FLUSH_INTERVAL 15 * 1000

using namespace com::wookler::reactfs::common;

namespace com {
    namespace wookler {
        namespace reactfs {
            namespace core {
                typedef __compression_v0 __compression;
                typedef __encryption_v0 __encryption;
                typedef __record_header_v0 __record_header;
                typedef __record_v0 __record;
                typedef __record_index_header_v0 __record_index_header;
                typedef __record_index_ptr_v0 __record_index_ptr;
                typedef __rollback_info_v0 __rollback_info;
                typedef __block_header_v0 __block_header;

                typedef struct __block_usage_stat__ {
                    atomic<uint64_t> bytes_used;
                    atomic<uint64_t> elapsed_time;
                    uint64_t last_synced = 0;
                } __block_usage_stat;

                class __mapped_ptr {
                private:
                    uint32_t size = 0;
                    void *data_ptr = nullptr;
                public:
                    void set_data_ptr(void *data_ptr, uint32_t size) {
                        PRECONDITION(NOT_NULL(data_ptr));

                        this->data_ptr = data_ptr;
                        this->size = size;
                    }

                    void *get_data_ptr() {
                        CHECK_NOT_NULL(this->data_ptr);
                        return this->data_ptr;
                    }

                    uint32_t get_size() {
                        return this->size;
                    }
                };

                class __read_ptr {
                private:
                    bool allocated = false;
                    uint32_t size = 0;
                    void *data_ptr = nullptr;
                    const void *const_ptr = nullptr;
                public:
                    __read_ptr(uint32_t size) {
                        this->size = size;
                    }

                    ~__read_ptr() {
                        if (allocated) {
                            FREE_PTR(data_ptr);
                        }
                        data_ptr = nullptr;
                    }

                    void set_data_ptr(const void *data_ptr, uint32_t size) {
                        PRECONDITION(NOT_NULL(data_ptr));

                        this->const_ptr = data_ptr;
                        this->size = size;
                    }

                    void copy(const void *data_ptr, uint32_t size = 0) {
                        PRECONDITION(NOT_NULL(data_ptr));
                        if (allocated) {
                            FREE_PTR(this->data_ptr);
                        }
                        if (size == 0) {
                            size = this->size;
                        }
                        PRECONDITION(size > 0);

                        this->data_ptr = (BYTE_PTR) malloc(size * sizeof(BYTE_PTR));
                        CHECK_ALLOC(this->data_ptr, TYPE_NAME(BYTE * ));

                        allocated = true;
                        memcpy(this->data_ptr, data_ptr, size);
                    }

                    const void *get_data_ptr() {
                        if (allocated)
                            return this->data_ptr;
                        else
                            return this->const_ptr;
                    }

                    uint32_t get_size() {
                        return this->size;
                    }
                };

                typedef shared_ptr<__read_ptr> shared_read_ptr;
                typedef shared_ptr<__mapped_ptr> shared_mapped_ptr;
            }
        }
    }
}
#endif //REACTFS_COMMON_STRUCTS_H


text:
package org.apache.flex.compiler.internal.definitions.references;

import org.apache.flex.compiler.definitions.references.IReference;
import org.apache.flex.compiler.definitions.references.ReferenceFactory;
import com.google.common.collect.MapMaker;

import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * A cache to manage instances of {@link IReference}.
 *

 * Clients should use {@link ReferenceFactory} to get {@link IReference}s; this
 * class is just an implementation detail.
 */
public class ReferenceCache
{
    public ReferenceCache()
    {
        threadLocalLexicalCache = new ThreadLocal<Map<String, WeakReference<LexicalReference>>>()
        {
            @Override
            protected Map<String, WeakReference<LexicalReference>> initialValue()
            {
                // Use a WeakHashMap with WeakRefs as values - the Strings and LexicalRefs
                // will be kept alive or not by the shared cache
                return new WeakHashMap<String, WeakReference<LexicalReference>>();
            }
        };
    }

    /**
     * Map of name to LexicalReference.
     */
    private final ConcurrentMap<String, LexicalReference> lexicalCache =
            new MapMaker().weakValues().makeMap();

    /**
     * Thread local cache for lexical references - improves performance, as we
     * can look here without worrying about locking or contention, and only look
     * at the shared cache if we have a miss here.
     */
    private final ThreadLocal<Map<String, WeakReference<LexicalReference>>> threadLocalLexicalCache;

    /**
     * Gets a {@link LexicalReference} representing name. If one
     * already exists, it is returned. If one does not exist a new one is
     * created, cached, and returned.
     *
     * @param name the name you want a lexical ref for
     * @return the LexicalReference representing name
     */
    public LexicalReference getLexicalReference(String name)
    {
        Map<String, WeakReference<LexicalReference>> cache = threadLocalLexicalCache.get();
        WeakReference<LexicalReference> weakRef = cache.get(name);
        LexicalReference ref = weakRef != null ? weakRef.get() : null;
        if (ref != null)
            return ref;

        LexicalReference newref = new LexicalReference(name);
        ref = lexicalCache.putIfAbsent(name, newref);
        if (ref == null)
            ref = newref;

        cache.put(name, new WeakReference<LexicalReference>(ref));
        return ref;
    }
}


text:
#pragma checksum "C:\Users\Informatica\Documents\Visual Studio 2010\Projects\SubastAutos\SubastAutos\paginas\modificarAuto.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "3FD53F3326403ECC420B5A1735BA291D"
//------------------------------------------------------------------------------
// <auto-generated>
//     Este código fue generado por una herramienta.
//     Versión de runtime:4.0.30319.225
//
//     Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si
//     se vuelve a generar el código.
// </auto-generated>
//------------------------------------------------------------------------------

using System;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Resources;
using System.Windows.Shapes;
using System.Windows.Threading;
using VIBlend.Silverlight.Controls;

namespace SubastAutos.paginas {

    public partial class modificarAuto : System.Windows.Controls.Page {

        internal System.Windows.Controls.Canvas LayoutRoot;

        internal VIBlend.Silverlight.Controls.TabControl tabControl1;

        internal VIBlend.Silverlight.Controls.TextBox txtPlaca;

        internal VIBlend.Silverlight.Controls.ComboBox cbxCombustible;

        internal VIBlend.Silverlight.Controls.TextBox txtMarca;

        internal VIBlend.Silverlight.Controls.MaskEditor txtAño;

        internal VIBlend.Silverlight.Controls.TextBox txtModelo;

        internal VIBlend.Silverlight.Controls.NumberEditor txtKilometraje;

        internal VIBlend.Silverlight.Controls.TextBox txtColor;

        internal VIBlend.Silverlight.Controls.ComboBox cbxTipoVehiculo;

        internal VIBlend.Silverlight.Controls.CurrencyEditor txtPrecio;

        internal VIBlend.Silverlight.Controls.Button btnAceptar;

        internal VIBlend.Silverlight.Controls.Button btnCancelar;

        private bool _contentLoaded;

        /// <summary>
        /// InitializeComponent
        /// </summary>
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public void InitializeComponent() {
            if (_contentLoaded) {
                return;
            }
            _contentLoaded = true;
            System.Windows.Application.LoadComponent(this, new System.Uri("/SubastAutos;component/paginas/modificarAuto.xaml", System.UriKind.Relative));
            this.LayoutRoot = ((System.Windows.Controls.Canvas)(this.FindName("LayoutRoot")));
            this.tabControl1 = ((VIBlend.Silverlight.Controls.TabControl)(this.FindName("tabControl1")));
            this.txtPlaca = ((VIBlend.Silverlight.Controls.TextBox)(this.FindName("txtPlaca")));
            this.cbxCombustible = ((VIBlend.Silverlight.Controls.ComboBox)(this.FindName("cbxCombustible")));
            this.txtMarca = ((VIBlend.Silverlight.Controls.TextBox)(this.FindName("txtMarca")));
            this.txtAño = ((VIBlend.Silverlight.Controls.MaskEditor)(this.FindName("txtAño")));
            this.txtModelo = ((VIBlend.Silverlight.Controls.TextBox)(this.FindName("txtModelo")));
            this.txtKilometraje = ((VIBlend.Silverlight.Controls.NumberEditor)(this.FindName("txtKilometraje")));
            this.txtColor = ((VIBlend.Silverlight.Controls.TextBox)(this.FindName("txtColor")));
            this.cbxTipoVehiculo = ((VIBlend.Silverlight.Controls.ComboBox)(this.FindName("cbxTipoVehiculo")));
            this.txtPrecio = ((VIBlend.Silverlight.Controls.CurrencyEditor)(this.FindName("txtPrecio")));
            this.btnAceptar = ((VIBlend.Silverlight.Controls.Button)(this.FindName("btnAceptar")));
            this.btnCancelar = ((VIBlend.Silverlight.Controls.Button)(this.FindName("btnCancelar")));
        }
    }
}


text:
package com.evolveum.midpoint.repo.api.query;

import org.apache.commons.lang.Validate;
import org.w3c.dom.Element;

/**
 * @author lazyman
 */
public class NotLogicalFilter extends LogicalFilter {

    private QueryFilter filter;

    public NotLogicalFilter(QueryFilter filter) {
        setFilter(filter);
    }

    public QueryFilter getFilter() {
        return filter;
    }

    public void setFilter(QueryFilter filter) {
        Validate.notNull(filter, "Filter must not be null.");
        this.filter = filter;
    }

    @Override
    public void toDOM(Element parent) {
        //todo implement
    }
}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/action_menu_admin_view"
        android:showAsAction="withText"
        android:title="Admin View"/>

</menu>


text:
package org.jadira.usertype.spi.shared;

import static org.jadira.usertype.spi.utils.reflection.ArrayUtils.copyOf;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.type.AbstractSingleColumnStandardBasicType;
import org.hibernate.type.TypeResolver;
import org.hibernate.type.descriptor.java.JavaTypeDescriptor;
import org.hibernate.usertype.EnhancedUserType;

public abstract class AbstractHeuristicUserType extends AbstractUserType implements EnhancedUserType, Serializable {

	private static final long serialVersionUID = 7099384329368123541L;

	private Class<?> identifierType;

	private AbstractSingleColumnStandardBasicType<?> type;

	private int[] sqlTypes;

    protected void setIdentifierType(Class<?> identifierType) {
    	this.identifierType = identifierType;
    }

    protected Class<?> getIdentifierType() {
    	return identifierType;
    }

    protected AbstractSingleColumnStandardBasicType<?> getType() {
    	return type;
    }

	public void setParameterValues(Properties parameters) {

		@SuppressWarnings("unchecked")
		final AbstractSingleColumnStandardBasicType<? extends Object> heuristicType = (AbstractSingleColumnStandardBasicType<? extends Object>) new TypeResolver().heuristicType(identifierType.getName(), parameters);
		if (heuristicType == null) {
			throw new HibernateException("Unsupported identifier type " + identifierType.getName());
		}

		type = heuristicType;
		sqlTypes = new int[]{ type.sqlType() };
	}

	public int[] sqlTypes() {
        return copyOf(sqlTypes);
    }

    @Override
    public abstract Class<?> returnedClass();

	@Override
	public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {

		beforeNullSafeOperation(session);

		try {

			try {
				return doNullSafeGet(rs, names, session, owner);
			} catch (IllegalArgumentException e) {
				throw new HibernateException(
						"Exception during nullSafeGet of type '"
							+ identifierType.getName() + "'", e);
			} catch (IllegalAccessException e) {
				throw new HibernateException(
						"Exception during nullSafeGet of type '"
								+ identifierType.getName() + "'", e);
			} catch (InvocationTargetException e) {
				throw new HibernateException(
						"Exception during nullSafeGet of type '"
								+ identifierType.getName() + "'", e);
			}
    	} finally {
    		afterNullSafeOperation(session);
    	}
	}

    public abstract Object doNullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException, IllegalArgumentException, IllegalAccessException, InvocationTargetException;

    @Override
    public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index, SharedSessionContractImplementor session) throws SQLException {

    	beforeNullSafeOperation(session);

    	try {
    		doNullSafeSet(preparedStatement, value, index, session);
		} catch (IllegalArgumentException e) {
			throw new HibernateException(
					"Exception during nullSafeSet of type '"
							+ identifierType.getName() + "'", e);
		} catch (IllegalAccessException e) {
			throw new HibernateException(
					"Exception during nullSafeSet of type '"
							+ identifierType.getName() + "'", e);
			} catch (InvocationTargetException e) {
		} finally {
			afterNullSafeOperation(session);
		}
    }

    public abstract void doNullSafeSet(PreparedStatement preparedStatement, Object value, int index, SharedSessionContractImplementor session) throws SQLException, IllegalArgumentException, IllegalAccessException, InvocationTargetException;

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Override
    public String objectToSQLString(Object object) {
    	final JavaTypeDescriptor desc = type.getJavaTypeDescriptor();
    	return desc.toString(object);
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	@Deprecated
    public String toXMLString(Object object) {
    	final JavaTypeDescriptor desc = type.getJavaTypeDescriptor();
    	return desc.toString(object);
    }

    @Override
    @Deprecated
    public Object fromXMLString(String string) {
		return type.fromString(string);
    }
}


text:
var mongoose = require('mongoose');
var dbConf = require('../../config/dbConf');
var Session = require('../models/Session');
var CanvasShapesManager = require('../DbManagers/CanvasShapesManager');
// open connection with uri
mongoose.connect(dbConf.getUri());

var Connection = mongoose.connection;

Connection.on('open', function() {
    mongoose.connection.db.dropDatabase();

    mongoose.connection.close();
})


text:
@interface CCBDictionaryMigrationStepVersion4_Tests : XCTestCase

@property (nonatomic, strong) CCBDictionaryMigrationStepVersion4 *migrationStep;

@end

@implementation CCBDictionaryMigrationStepVersion4_Tests

- (void)setUp
{
    [super setUp];
    self.migrationStep = [[CCBDictionaryMigrationStepVersion4 alloc] init];
}

- (void)testMigrate
{
    NSDictionary *ccb = @{
        CCB_DICTIONARY_KEY_FILEVERSION : @4,
        CCB_DICTIONARY_KEY_NODEGRAPH : @{
            CCB_DICTIONARY_KEY_PROPERTIES : @[
                @{
                    CCB_DICTIONARY_KEY_PROPERTY_NAME : @"blendFunc",
                    CCB_DICTIONARY_KEY_PROPERTY_TYPE : @"Blendmode",
                    CCB_DICTIONARY_KEY_PROPERTY_VALUE : @[ @774, @772 ]
                }
            ],
            CCB_DICTIONARY_KEY_CHILDREN : @[
                @{
                    CCB_DICTIONARY_KEY_PROPERTIES : @[
                        // Should be ignored
                        @{
                            CCB_DICTIONARY_KEY_PROPERTY_NAME : @"Homer",
                            CCB_DICTIONARY_KEY_PROPERTY_TYPE : @"quote",
                            CCB_DICTIONARY_KEY_PROPERTY_VALUE : @"Duh!"
                        },
                        // Should not get migrated due to wrong value
                        @{
                            CCB_DICTIONARY_KEY_PROPERTY_NAME : @"blendFunc",
                            CCB_DICTIONARY_KEY_PROPERTY_TYPE : @"Blendmode",
                            CCB_DICTIONARY_KEY_PROPERTY_VALUE : @"Not an array!"
                        }
                    ]
                },
                @{
                    CCB_DICTIONARY_KEY_PROPERTIES : @[
                        @{
                            CCB_DICTIONARY_KEY_PROPERTY_NAME : @"blendFunc",
                            CCB_DICTIONARY_KEY_PROPERTY_TYPE : @"Blendmode",
                            CCB_DICTIONARY_KEY_PROPERTY_VALUE : @[ @769, @771 ]
                        }
                    ],
                }
            ]
        }
    };

    NSError *error;
    NSDictionary *migratedCCB = [_migrationStep migrate:ccb error:&error];

    XCTAssertNotNil(migratedCCB);
    XCTAssertNil(error);

    NSDictionary *expectedBlendModeProperty = @{
        CCB_DICTIONARY_KEY_PROPERTY_NAME : @"blendMode",
        CCB_DICTIONARY_KEY_PROPERTY_TYPE : @"Blendmode",
        CCB_DICTIONARY_KEY_PROPERTY_VALUE : @{
            @"CCBlendFuncSrcColor" : @774,
            @"CCBlendFuncSrcAlpha" : @774,
            @"CCBlendFuncDstAlpha" : @772,
            @"CCBlendFuncDstColor" : @772,
            @"CCBlendEquationColor" : @32774,
            @"CCBlendEquationAlpha" : @32774
        }
    };

    NSDictionary *expectedBlendModePropertyOfSecondChild = @{
        CCB_DICTIONARY_KEY_PROPERTY_NAME : @"blendMode",
        CCB_DICTIONARY_KEY_PROPERTY_TYPE : @"Blendmode",
        CCB_DICTIONARY_KEY_PROPERTY_VALUE : @{
            @"CCBlendFuncSrcColor" : @769,
            @"CCBlendFuncSrcAlpha" : @769,
            @"CCBlendFuncDstAlpha" : @771,
            @"CCBlendFuncDstColor" : @771,
            @"CCBlendEquationColor" : @32774,
            @"CCBlendEquationAlpha" : @32774
        }
    };

    NSDictionary *rootNodeBlendModeProperty = migratedCCB[CCB_DICTIONARY_KEY_NODEGRAPH][CCB_DICTIONARY_KEY_PROPERTIES][0];
    NSDictionary *firstChildsBlendModeProperty = migratedCCB[CCB_DICTIONARY_KEY_NODEGRAPH][CCB_DICTIONARY_KEY_CHILDREN][0][CCB_DICTIONARY_KEY_PROPERTIES][1];
    NSDictionary *secondChildsBlendModeProperty = migratedCCB[CCB_DICTIONARY_KEY_NODEGRAPH][CCB_DICTIONARY_KEY_CHILDREN][1][CCB_DICTIONARY_KEY_PROPERTIES][0];

    XCTAssertEqualObjects(rootNodeBlendModeProperty, expectedBlendModeProperty);
    XCTAssertEqualObjects(firstChildsBlendModeProperty[CCB_DICTIONARY_KEY_PROPERTY_NAME], @"blendFunc");
    XCTAssertEqualObjects(firstChildsBlendModeProperty[CCB_DICTIONARY_KEY_PROPERTY_VALUE], @"Not an array!");
    XCTAssertEqualObjects(secondChildsBlendModeProperty, expectedBlendModePropertyOfSecondChild);
};

- (void)testMigrateWithoutNodeGraph
{
    NSError *error;
    NSDictionary *migratedCCB = [_migrationStep migrate:@{@"foo" : @"baa"} error:&error];

    XCTAssertNotNil(error);
    XCTAssertEqual(error.code, SBCCBMigrationError);
    XCTAssertNil(migratedCCB);
};

- (void)testMigrateWithNilParam
{
    NSError *error;
    NSDictionary *migratedCCB = [_migrationStep migrate:nil error:&error];

    XCTAssertNotNil(error);
    XCTAssertEqual(error.code, SBCCBMigrationError);
    XCTAssertNil(migratedCCB);
};

@end


text:
Testable and PSR-compliant mail mime parser alternative to PHP's imap* functions and Pear libraries for reading messages in _Internet Message Format_ [RFC 822](http://tools.ietf.org/html/rfc822) (and later revisions [RFC 2822](http://tools.ietf.org/html/rfc2822), [RFC 5322](http://tools.ietf.org/html/rfc5322)).

[![Build Status](https://travis-ci.com/zbateson/mail-mime-parser.svg?branch=master)](https://travis-ci.com/zbateson/mail-mime-parser)
[![Code Coverage](https://scrutinizer-ci.com/g/zbateson/mail-mime-parser/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/zbateson/mail-mime-parser/?branch=master)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/zbateson/mail-mime-parser/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/zbateson/mail-mime-parser/?branch=master)
[![Total Downloads](https://poser.pugx.org/zbateson/mail-mime-parser/downloads)](//packagist.org/packages/zbateson/mail-mime-parser)
[![Latest Stable Version](https://poser.pugx.org/zbateson/mail-mime-parser/v)](//packagist.org/packages/zbateson/mail-mime-parser)

The goals of this project are to be:

* Well written
* Standards-compliant but forgiving
* Tested where possible

To include it for use in your project, please install via composer:

```
composer require zbateson/mail-mime-parser
```

## Sponsors

A huge thank you to my first sponsor. <3

[![SecuMailer](https://mail-mime-parser.org/sponsors/logo-secumailer.png)](https://secumailer.com)

## Deprecation Notice (since 1.2.1)

getContentResourceHandle, getTextResourceHandle, and getHtmlResourceHandle have all been deprecated due to #106. fread() will only return a single byte of a multibyte char, and so will cause potentially unexpected results/warnings in some cases, and psr7 streams should be used instead. Note that this deprecation doesn't apply to getBinaryContentResourceHandle or getResourceHandle.

## Requirements

MailMimeParser requires PHP 5.4 or newer.  Tested on PHP 5.4, 5.5, 5.6, 7, 7.1, 7.2, 7.3, 7.4 and 8.0 on travis.

## Usage

```php
use ZBateson\MailMimeParser\MailMimeParser;
use ZBateson\MailMimeParser\Message;
use ZBateson\MailMimeParser\Header\HeaderConsts;

// use an instance of MailMimeParser as a class dependency
$mailParser = new MailMimeParser();

$handle = fopen('file.mime', 'r');
// parse() accepts a string, resource or Psr7 StreamInterface
$message = $mailParser->parse($handle);         // returns `Message`
fclose($handle);

// OR: use this procedurally (Message::from also accepts a string,
// resource or Psr7 StreamInterface
$message = Message::from($string);

echo $message->getHeaderValue(HeaderConsts::FROM);     // user@example.com
echo $message
    ->getHeader(HeaderConsts::FROM)                    // AddressHeader
    ->getPersonName();                                 // Person Name
echo $message->getHeaderValue(HeaderConsts::SUBJECT);  // The email's subject
echo $message
    ->getHeader(HeaderConsts::TO)                      // also AddressHeader
    ->getAddresses()[0]                                // AddressPart
    ->getName();                                       // Person Name
echo $message
    ->getHeader(HeaderConsts::CC)                      // also AddressHeader
    ->getAddresses()[0]                                // AddressPart
    ->getEmail();                                      // user@example.com

echo $message->getTextContent();                       // or getHtmlContent()

echo $message->getHeader('X-Foo');                     // for custom or undocumented headers

$att = $message->getAttachmentPart(0);                 // first attachment
echo $att->getHeaderValue(HeaderConsts::CONTENT_TYPE); // e.g. "text/plain"
echo $att->getHeaderParameter(                         // value of "charset" part
    'content-type',
    'charset'
);
echo $att->getContent();                               // get the attached file's contents
$stream = $att->getContentStream();                    // the file is decoded automatically
$dest = \GuzzleHttp\Psr7\stream_for(
    fopen('my-file.ext')
);
\GuzzleHttp\Psr7\copy_to_stream(
    $stream, $dest
);
// OR: more simply if saving or copying to another stream
$att->saveContent('my-file.ext');               // writes to my-file.ext
$att->saveContent($stream);                     // copies to the stream
```

## Documentation

* [Usage Guide](https://mail-mime-parser.org/)
* [API Reference](https://mail-mime-parser.org/api/1.3)

## Upgrading to 1.x

* [Upgrade Guide](https://mail-mime-parser.org/upgrade-1.0)

## License

BSD licensed - please see [license agreement](https://github.com/zbateson/mail-mime-parser/blob/master/LICENSE).


text:
package com.wavesplatform.http

import akka.http.scaladsl.model.StatusCodes
import com.wavesplatform.TestWallet
import com.wavesplatform.api.BlockMeta
import com.wavesplatform.api.common.CommonBlocksApi
import com.wavesplatform.api.http.{BlocksApiRoute, RouteTimeout}
import com.wavesplatform.api.http.ApiError.TooBigArrayAllocation
import com.wavesplatform.block.serialization.BlockHeaderSerializer
import com.wavesplatform.block.{Block, BlockHeader}
import com.wavesplatform.common.state.ByteStr
import com.wavesplatform.db.WithDomain
import com.wavesplatform.lagonaki.mocks.TestBlock
import com.wavesplatform.state.Blockchain
import com.wavesplatform.transaction.TxHelpers
import com.wavesplatform.utils.{Schedulers, SystemTime}
import monix.reactive.Observable
import org.scalamock.scalatest.PathMockFactory
import play.api.libs.json.*

import scala.concurrent.duration.*
import scala.util.Random

class BlocksApiRouteSpec extends RouteSpec("/blocks") with PathMockFactory with RestAPISettingsHelper with TestWallet with WithDomain {
  private val blocksApi = mock[CommonBlocksApi]
  private val blocksApiRoute: BlocksApiRoute =
    BlocksApiRoute(restAPISettings, blocksApi, SystemTime, new RouteTimeout(60.seconds)(Schedulers.fixedPool(1, "heavy-request-scheduler")))
  private val route = blocksApiRoute.route

  private val testBlock1 = TestBlock.create(Nil)
  private val testBlock2 = TestBlock.create(Nil, Block.ProtoBlockVersion)

  private val testBlock1Json = testBlock1.json() ++ Json.obj("height" -> 1, "totalFee" -> 0L)
  private val testBlock2Json = testBlock2.json() ++ Json.obj("height" -> 2, "totalFee" -> 0L, "reward" -> 5, "VRF" -> testBlock2.id().toString)

  private val testBlock1HeaderJson = BlockHeaderSerializer.toJson(testBlock1.header, testBlock1.bytes().length, 0, testBlock1.signature) ++ Json.obj(
    "height"   -> 1,
    "totalFee" -> 0L
  )

  private val testBlock2HeaderJson = BlockHeaderSerializer.toJson(testBlock2.header, testBlock2.bytes().length, 0, testBlock2.signature) ++ Json.obj(
    "height"   -> 2,
    "totalFee" -> 0L,
    "reward"   -> 5,
    "VRF"      -> testBlock2.id().toString
  )

  private val testBlock1Meta = BlockMeta.fromBlock(testBlock1, 1, 0L, None, None)
  private val testBlock2Meta = BlockMeta.fromBlock(testBlock2, 2, 0L, Some(5), Some(testBlock2.id()))

  private val invalidBlockId = ByteStr(new Array[Byte](32))
  (blocksApi.block _).expects(invalidBlockId).returning(None).anyNumberOfTimes()
  (blocksApi.meta _).expects(invalidBlockId).returning(None).anyNumberOfTimes()

  routePath("/first") in {
    (blocksApi.blockAtHeight _).expects(1).returning(Some(testBlock1Meta -> Seq.empty)).once()
    Get(routePath("/first")) ~> route ~> check {
      val response = responseAs[JsObject]
      response shouldBe testBlock1Json
    }
  }

  routePath("/last") in {
    (() => blocksApi.currentHeight).expects().returning(2).once()
    (blocksApi.blockAtHeight _).expects(2).returning(Some(testBlock2Meta -> Seq.empty)).once()
    Get(routePath("/last")) ~> route ~> check {
      val response = responseAs[JsObject]
      response shouldBe testBlock2Json
    }
  }

  routePath("/at/{height}") in {
    (blocksApi.blockAtHeight _).expects(1).returning(Some(testBlock1Meta -> Seq.empty)).once()
    Get(routePath("/at/1")) ~> route ~> check {
      val response = responseAs[JsObject]
      response shouldBe testBlock1Json
    }

    (blocksApi.blockAtHeight _).expects(2).returning(Some(testBlock2Meta -> Seq.empty)).once()
    Get(routePath("/at/2")) ~> route ~> check {
      val response = responseAs[JsObject]
      response shouldBe testBlock2Json
    }

    (blocksApi.blockAtHeight _).expects(3).returning(None).once()
    Get(routePath("/at/3")) ~> route ~> check {
      response.status shouldBe StatusCodes.NotFound
      responseAs[String] should include("block does not exist")
    }
  }

  routePath("/signature/{signature}") in {
    (blocksApi.block _).expects(testBlock1.id()).returning(Some(testBlock1Meta -> Seq.empty)).once()
    (blocksApi.block _).expects(testBlock2.id()).returning(Some(testBlock2Meta -> Seq.empty)).once()
    Get(routePath(s"/signature/${testBlock1.id()}")) ~> route ~> check {
      val response = responseAs[JsObject]
      response shouldBe testBlock1Json
    }

    Get(routePath(s"/signature/${testBlock2.id()}")) ~> route ~> check {
      val response = responseAs[JsObject]
      response shouldBe testBlock2Json
    }

    Get(routePath(s"/signature/$invalidBlockId")) ~> route ~> check {
      response.status.isFailure() shouldBe true
      responseAs[String] should include("block does not exist")
    }
  }

  routePath("/{id}") in {
    (blocksApi.block _).expects(testBlock1.id()).returning(Some(testBlock1Meta -> Seq.empty)).once()
    (blocksApi.block _).expects(testBlock2.id()).returning(Some(testBlock2Meta -> Seq.empty)).once()

    Get(routePath(s"/${testBlock1.id()}")) ~> route ~> check {
      val response = responseAs[JsObject]
      response shouldBe testBlock1Json
    }

    Get(routePath(s"/${testBlock2.id()}")) ~> route ~> check {
      val response = responseAs[JsObject]
      response shouldBe testBlock2Json
    }

    Get(routePath(s"/$invalidBlockId")) ~> route ~> check {
      response.status.isFailure() shouldBe true
      responseAs[String] should include("block does not exist")
    }
  }

  routePath("/seq/{from}/{to}") in {
    (blocksApi
      .blocksRange(_: Int, _: Int))
      .expects(1, 2)
      .returning(
        Observable.fromIterable(
          Seq(
            testBlock1Meta -> Seq.empty,
            testBlock2Meta -> Seq.empty
          )
        )
      )
    Get(routePath("/seq/1/2")) ~> route ~> check {
      val response = responseAs[Seq[JsObject]]
      response shouldBe Seq(testBlock1Json, testBlock2Json)
    }
  }

  routePath("/headers/last") in {
    (() => blocksApi.currentHeight).expects().returning(2).once()
    (blocksApi.metaAtHeight _).expects(2).returning(Some(testBlock2Meta)).once()
    Get(routePath("/headers/last")) ~> route ~> check {
      val response = responseAs[JsObject]
      response shouldBe testBlock2HeaderJson
    }
  }

  routePath("/headers/{id}") in {
    (blocksApi.meta _).expects(testBlock1.id()).returning(Some(testBlock1Meta)).once()
    (blocksApi.meta _).expects(testBlock2.id()).returning(Some(testBlock2Meta)).once()

    Get(routePath(s"/headers/${testBlock1.id()}")) ~> route ~> check {
      val response = responseAs[JsObject]
      response shouldBe testBlock1HeaderJson
      response
    }

    Get(routePath(s"/headers/${testBlock2.id()}")) ~> route ~> check {
      val response = responseAs[JsObject]
      response shouldBe testBlock2HeaderJson
    }

    Get(routePath(s"/headers/$invalidBlockId")) ~> route ~> check {
      response.status.isFailure() shouldBe true
      responseAs[String] should include("block does not exist")
    }
  }

  routePath("/headers/at/{height}") in {
    (blocksApi.metaAtHeight _).expects(1).returning(Some(testBlock1Meta)).once()
    (blocksApi.metaAtHeight _).expects(2).returning(Some(testBlock2Meta)).once()
    (blocksApi.metaAtHeight _).expects(3).returning(None).once()

    Get(routePath("/headers/at/1")) ~> route ~> check {
      val response = responseAs[JsObject]
      response shouldBe testBlock1HeaderJson
    }

    Get(routePath("/headers/at/2")) ~> route ~> check {
      val response = responseAs[JsObject]
      response shouldBe testBlock2HeaderJson
    }

    Get(routePath("/headers/at/3")) ~> route ~> check {
      response.status shouldBe StatusCodes.NotFound
      responseAs[String] should include("block does not exist")
    }
  }

  routePath("/headers/seq/{from}/{to}") in {
    (blocksApi.metaRange _)
      .expects(1, 2)
      .returning(
        Observable.fromIterable(
          Seq(
            testBlock1Meta,
            testBlock2Meta
          )
        )
      )
    Get(routePath("/headers/seq/1/2")) ~> route ~> check {
      val response = responseAs[Seq[JsObject]]
      response shouldBe Seq(testBlock1HeaderJson, testBlock2HeaderJson)
    }
  }

  routePath("/delay/{blockId}/{number}") in {
    val blocks = Vector(
      Block(
        BlockHeader(1, 0, ByteStr.empty, 0, ByteStr.empty, TxHelpers.defaultSigner.publicKey, Nil, 0, ByteStr.empty),
        ByteStr(Random.nextBytes(64)),
        Nil
      ),
      Block(
        BlockHeader(1, 1000, ByteStr.empty, 0, ByteStr.empty, TxHelpers.defaultSigner.publicKey, Nil, 0, ByteStr.empty),
        ByteStr(Random.nextBytes(64)),
        Nil
      ),
      Block(
        BlockHeader(1, 2000, ByteStr.empty, 0, ByteStr.empty, TxHelpers.defaultSigner.publicKey, Nil, 0, ByteStr.empty),
        ByteStr(Random.nextBytes(64)),
        Nil
      )
    )

    val blockchain = stub[Blockchain]
    (blockchain.heightOf _).when(blocks.last.id()).returning(Some(3))

    def metaAt(height: Int): Option[BlockMeta] =
      if (height >= 1 && height <= 3)
        Some(BlockMeta(blocks(height - 1).header, ByteStr.empty, None, 1, 0, 0, 0, None, None))
      else None

    val blocksApi = CommonBlocksApi(blockchain, metaAt, _ => None)
    val route     = blocksApiRoute.copy(commonApi = blocksApi).route
    Get(routePath(s"/delay/${blocks.last.id()}/3")) ~> route ~> check {
      val delay = (responseAs[JsObject] \ "delay").as[Int]
      delay shouldBe 1000
    }

    Get(routePath(s"/delay/${blocks.last.id()}/1")) ~> route ~> check {
      val delay = (responseAs[JsObject] \ "delay").as[Int]
      delay shouldBe 1000
    }

    Get(routePath(s"/delay/${blocks.last.id()}/${BlocksApiRoute.MaxBlocksForDelay}")) ~> route ~> check {
      response.status shouldBe StatusCodes.OK
      val delay = (responseAs[JsObject] \ "delay").as[Int]
      delay shouldBe 1000
    }

    Get(routePath(s"/delay/${blocks.last.id()}/${BlocksApiRoute.MaxBlocksForDelay + 1}")) ~> route ~> check {
      response.status shouldBe StatusCodes.BadRequest
      (responseAs[JsObject] \ "message").as[String] shouldBe TooBigArrayAllocation(BlocksApiRoute.MaxBlocksForDelay).message
    }
  }

  routePath("/heightByTimestamp") - {
    def emulateBlocks(blocks: IndexedSeq[Block]): CommonBlocksApi = {
      require(blocks.nonEmpty)
      val blocksApi = stub[CommonBlocksApi]
      (() => blocksApi.currentHeight).when().returning(blocks.length)
      (blocksApi.metaAtHeight _)
        .when(*)
        .onCall { (height: Int) =>
          if (height < 1 || height > blocks.size) None
          else {
            val block = blocks(height - 1)
            Some(BlockMeta(block.header, block.signature, None, height, 1, 0, 0L, None, None))
          }
        }
      blocksApi
    }

    "missing blocks" in {
      (blocksApi.metaAtHeight _).expects(1).returning(None).repeat(2)
      (() => blocksApi.currentHeight).expects().returning(5).repeat(2)
      Get(routePath(s"/heightByTimestamp/1")) ~> route ~> check {
        responseAs[JsObject] shouldBe Json.parse("{\"error\":199,\"message\":\"State was altered\"}")
      }
    }

    "ideal blocks" in {
      val blocks = (1 to 10).map(i => TestBlock.create(i * 10, Nil))
      val route  = blocksApiRoute.copy(commonApi = emulateBlocks(blocks)).route

      Get(routePath(s"/heightByTimestamp/10")) ~> route ~> check {
        val result = (responseAs[JsObject] \ "height").as[Int]
        result shouldBe 1
      }

      Get(routePath(s"/heightByTimestamp/100")) ~> route ~> check {
        val result = (responseAs[JsObject] \ "height").as[Int]
        result shouldBe 10
      }

      Get(routePath(s"/heightByTimestamp/55")) ~> route ~> check {
        val result = (responseAs[JsObject] \ "height").as[Int]
        result shouldBe 5
      }

      Get(routePath(s"/heightByTimestamp/99")) ~> route ~> check {
        val result = (responseAs[JsObject] \ "height").as[Int]
        result shouldBe 9
      }

      Get(routePath(s"/heightByTimestamp/110")) ~> route ~> check {
        val result = (responseAs[JsObject] \ "height").as[Int]
        result shouldBe 10
      }

      Get(routePath(s"/heightByTimestamp/9")) ~> route ~> check {
        responseAs[JsObject] shouldBe Json.parse("{\"error\":199,\"message\":\"Indicated timestamp is before the start of the blockchain\"}")
      }

      Get(routePath(s"/heightByTimestamp/${System.currentTimeMillis() + 10000}")) ~> route ~> check {
        responseAs[JsObject] shouldBe Json.parse("{\"error\":199,\"message\":\"Indicated timestamp belongs to the future\"}")
      }
    }

    "random blocks" in {
      val (_, blocks) = (1 to 10).foldLeft((0L, Vector.empty[Block])) { case ((ts, blocks), _) =>
        val newBlock = TestBlock.create(ts + 100 + Random.nextInt(10000), Nil)
        (newBlock.header.timestamp, blocks :+ newBlock)
      }

      val route = blocksApiRoute.copy(commonApi = emulateBlocks(blocks)).route

      blocks.zipWithIndex.foreach { case (block, index) =>
        Get(routePath(s"/heightByTimestamp/${block.header.timestamp}")) ~> route ~> check {
          val result = (responseAs[JsObject] \ "height").as[Int]
          result shouldBe (index + 1)
        }
      }
    }
  }
}


text:
.. EN-Revision: none
.. _user-guide.routing-and-controllers:

#######################
Routing et contrôleurs
#######################

Nous allons mettre en place un système d'inventaire très simple pour afficher
notre collection d'albums. La page d'accueil listera notre collection et nous
permettra d'ajouter, modifier et effacer des albums. Pour cela, il nous faut
les pages suivantes :

+---------------+------------------------------------------------------------+
| Page          | Description                                                |
+===============+============================================================+
| Accueil       | Cette page affichera la liste d'albums et contiendra des   |
|               | liens pour les modifier et les effacer. Elle contiendra    |
|               | aussi un bouton qui nous permettra d'ajouter de nouveaux   |
|               | albums.                                                    |
|               |                                                            |
+---------------+------------------------------------------------------------+
| Ajouter album | Cette page contiendra un formulaire pour ajouter un album. |
+---------------+------------------------------------------------------------+
| Modifier album| Cette page contiendra un formulaire pour modifier un album.|
+---------------+------------------------------------------------------------+
| Effacer album | Cette page nous permettra d'effacer un album avec demande  |
|               | de confirmation.                                           |
+---------------+------------------------------------------------------------+

Avant tout chose, il est important de comprendre comment les pages doivent être
organisées pour le framework. Chaque page de l'application est une *action* et
les actions sont regroupées au sein de *contrôleurs* dans les *modules*. Ainsi,
vous regrouperez généralement les actions au sein d'un contrôleur; par exemple,
un contrôleur qui gèrerait des actualités auraient des actions  comme ``nouvelles``,
``archivées`` etc.

Comme nous avons quatre pages pour nos albums, nous les regrouperons dans un seul
contrôleur ``AlbumController`` dans notre module ``Album`` sous forme de 4 actions.
Ces 4 actions seront :

+---------------+---------------------+------------+
| Page          | Contrôleur          | Action     |
+===============+=====================+============+
| Accueil       | ``AlbumController`` | ``index``  |
+---------------+---------------------+------------+
| Ajouter album | ``AlbumController`` | ``add``    |
+---------------+---------------------+------------+
| Modifier album| ``AlbumController`` | ``edit``   |
+---------------+---------------------+------------+
| Effacer album | ``AlbumController`` | ``delete`` |
+---------------+---------------------+------------+

La correspondance entre une URL et une action particulière se fait à l'aide des
routes qui sont décrites dans le fichier ``module.config.php`` du module. Nous
ajouterons une route pour nos 4 actions. Voici le fichier de configuration
mis à jour avec le code qui est commenté.

.. code-block:: php

    // module/Album/config/module.config.php:
    return array(
        'controllers' => array(
            'invokables' => array(
                'Album\Controller\Album' => 'Album\Controller\AlbumController',
            ),
        ),

        // Code à ajouter à votre fichier.
        'router' => array(
            'routes' => array(
                'album' => array(
                    'type'    => 'segment',
                    'options' => array(
                        'route'    => '/album[/:action][/:id]',
                        'constraints' => array(
                            'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                            'id'     => '[0-9]+',
                        ),
                        'defaults' => array(
                            'controller' => 'Album\Controller\Album',
                            'action'     => 'index',
                        ),
                    ),
                ),
            ),
        ),

        'view_manager' => array(
            'template_path_stack' => array(
                'album' => __DIR__ . '/../view',
            ),
        ),
    );

Le nom de la route est 'album' et possède un type de 'segment'. Les segments
nous permettent de spécifier des espaces réservés dans l'URL qui seront mappés
aux paramètres nommés dans la route correspondante. Dans notre cas, la route est
**``/album[/:action][/:id]``**, qui vérifiera chaque url qui commence par ``/album``.
Le segment suivant correspond au nom d'une action optionnelle, et le dernier segment
correspond à un id, optionnel lui aussi. Les crochets indiquent qu'un segment est
optionnel. La section constraints permet de nous assurer que les caractères relevés
dans un segment correspondent bien à ceux attendus, nous avons donc restreint les actions
pour qu'elles commencent par une lettre, les caractères suivants étant alphanumériques,
le signe souligné '_', et le tiret. Les id sont ainsi limités aux seuls chiffres.

Cette route nous permet d'avoir les URL suivantes :

+---------------------+------------------------------+------------+
| URL                 | Page                         | Action     |
+=====================+==============================+============+
| ``/album``          | Accueil (listes des albums)  | ``index``  |
+---------------------+------------------------------+------------+
| ``/album/add``      | Ajouter un album             | ``add``    |
+---------------------+------------------------------+------------+
| ``/album/edit/2``   | Modifier l'album avec l'id 2 | ``edit``   |
+---------------------+------------------------------+------------+
| ``/album/delete/4`` | Effacer l'album avec l'id 4  | ``delete`` |
+---------------------+------------------------------+------------+

Créer le contrôleur
===================

Nous sommes maintenant prêts à mettre en place notre contrôleur. Dans zend framework 2,
le contrôleur est une classe que l'on nomme généralement ``{Nom du contrôleur}Controller``.
Notez que ``{Nom du contrôleur}`` doit commencer par une majuscule. Cette classe réside dans
un fichier nommé ``{Nom du contrôleur}Controller.php``, sous le dossier ``Controller`` du
module. Dans notre cas, ce sera ``module/Album/src/Album/Controller``. Chaque action est une méthode
publique de la classe contrôleur nommée ``{nom de l'action}Action``. Dans notre cas, ``{nom de l'action}``
devrait commencer par une lettre minuscule.

Ceci n'est qu'une convention. Zend Framework 2 n'impose pas beaucoup de
restrictions sur les contrôleurs, outre le fait qu'ils doivent implémenter
l'interface ``Zend\Stdlib\Dispatchable``. Le framework propose deux classes
abstraites qui font le travail pour nous : ``Zend\Mvc\Controller\AbstractActionController``
et ``Zend\Mvc\Controller\AbstractRestfulController``. Nous utiliserons
``AbstractActionController``, mais si vous avez l'intention d'écrire un service RESTful,
``AbstractRestfulController`` vous sera plus utile.

Allons-y et créons notre classe contrôleur :

.. code-block:: php

    // module/Album/src/Album/Controller/AlbumController.php:
    namespace Album\Controller;

    use Zend\Mvc\Controller\AbstractActionController;
    use Zend\View\Model\ViewModel;

    class AlbumController extends AbstractActionController
    {
        public function indexAction()
        {
        }

        public function addAction()
        {
        }

        public function editAction()
        {
        }

        public function deleteAction()
        {
        }
    }

Notez que nous avons déjà informé le module de l'existence de notre contrôleur
dans la section 'controllers' de ``config/module.config.php``.

Nous avons désormais nos 4 actions que nous souhaitons utiliser. Elles ne
fonctionneront que lorsque nous aurons mis en place les vues. Les URL de chaque
action sont :

+--------------------------------------------+----------------------------------------------------+
| URL                                        | Methode appelée                                    |
+============================================+====================================================+
| http://zf2-tutorial.localhost/album        | ``Album\Controller\AlbumController::indexAction``  |
+--------------------------------------------+----------------------------------------------------+
| http://zf2-tutorial.localhost/album/add    | ``Album\Controller\AlbumController::addAction``    |
+--------------------------------------------+----------------------------------------------------+
| http://zf2-tutorial.localhost/album/edit   | ``Album\Controller\AlbumController::editAction``   |
+--------------------------------------------+----------------------------------------------------+
| http://zf2-tutorial.localhost/album/delete | ``Album\Controller\AlbumController::deleteAction`` |
+--------------------------------------------+----------------------------------------------------+

Nous avons désormais un routeur fonctionnel et les actions sont renseignées
pour chaque page de notre application.

Il est temps de construire la vue et la couche modèle.

Initialiser les scripts de vue
------------------------------

Pour intégrer la vue dans notre application, tout ce que nous avons à faire est de
créer les fichiers de la vue. Ces fichiers seront exécutés par le ``DefaultViewStrategy``
et recevront n'importe quelle variable ou modèles de vue retournées par les méthodes d'action
du contrôleur. Créez maintenant ces 4 fichiers vides :

* ``module/Album/view/album/album/index.phtml``
* ``module/Album/view/album/album/add.phtml``
* ``module/Album/view/album/album/edit.phtml``
* ``module/Album/view/album/album/delete.phtml``

Nous pouvons désormais commencer à tout renseigner, à commencer par notre base de données
et les modèles.


text:
/*
* Generated by SGWrapperGen - DO NOT EDIT!
*
* SwinGame wrapper for C - Sprites
*
* Wrapping sgSprites.pas
*/

#ifndef sgSprites
#define sgSprites

#include <stdint.h>

#ifndef __cplusplus
  #include <stdbool.h>
#endif

#include "Types.h"

void call_for_all_sprites(sprite_function fn);
void call_on_sprite_event(sprite_event_handler handler);
point2d center_point(sprite s);
sprite create_basic_sprite(bitmap layer);
sprite create_basic_sprite_named(const char *name, bitmap layer);
sprite create_sprite_with_bitmap_and_animation_name(const char *bitmapName, const char *animationName);
sprite create_sprite_with_animation(bitmap layer, animation_script ani);
sprite create_sprite_with_animation_named(const char *name, bitmap layer, animation_script ani);
void create_sprite_pack(const char *name);
void current_sprite_pack(char *result);
void draw_all_sprites();
void draw_sprite(sprite s);
void draw_sprite_offset_point(sprite s, const point2d *position);
void draw_sprite_offset_point_byval(sprite s, const point2d position);
void draw_sprite_offset_xy(sprite s, int32_t xOffset, int32_t yOffset);
void free_sprite(sprite *s);
bool has_sprite(const char *name);
bool has_sprite_pack(const char *name);
void move_sprite(sprite s);
void move_sprite_vec(sprite s, const vector *distance);
void move_sprite_vec_byval(sprite s, const vector distance);
void move_sprite_pct(sprite s, float pct);
void move_sprite_vec_pct(sprite s, const vector *distance, float pct);
void move_sprite_vec_pct_byval(sprite s, const vector distance, float pct);
void move_sprite_to(sprite s, int32_t x, int32_t y);
void release_all_sprites();
void release_sprite(const char *name);
void select_sprite_pack(const char *name);
int32_t sprite_add_layer(sprite s, bitmap newLayer, const char *layerName);
void sprite_add_to_velocity(sprite s, const vector *value);
void sprite_add_to_velocity_byval(sprite s, const vector value);
void sprite_add_value(sprite s, const char *name);
void sprite_add_value_with_initial_value(sprite s, const char *name, float initVal);
point2d sprite_anchor_point(sprite s);
bool sprite_animation_has_ended(sprite s);
void sprite_animation_name(sprite s, char *result);
void sprite_bring_layer_forward(sprite s, int32_t visibleLayer);
void sprite_bring_layer_to_front(sprite s, int32_t visibleLayer);
void sprite_call_on_event(sprite s, sprite_event_handler handler);
circle sprite_circle(sprite s);
bitmap sprite_collision_bitmap(sprite s);
circle sprite_collision_circle(sprite s);
collision_test_kind sprite_collision_kind(sprite s);
rectangle sprite_collision_rectangle(sprite s);
int32_t sprite_current_cell(sprite s);
rectangle sprite_current_cell_rectangle(sprite s);
float sprite_dx(sprite s);
float sprite_dy(sprite s);
float sprite_heading(sprite s);
int32_t sprite_height(sprite s);
void sprite_hide_layer_named(sprite s, const char *name);
void sprite_hide_layer(sprite s, int32_t id);
bitmap sprite_layer_named(sprite s, const char *name);
bitmap sprite_layer_at_idx(sprite s, int32_t idx);
circle sprite_layer_circle(sprite s, int32_t idx);
circle sprite_layer_named_circle(sprite s, const char *name);
int32_t sprite_layer_count(sprite s);
int32_t sprite_layer_named_height(sprite s, const char *name);
int32_t sprite_layer_height(sprite s, int32_t idx);
int32_t sprite_layer_index(sprite s, const char *name);
void sprite_layer_name(sprite s, int32_t idx, char *result);
point2d sprite_layer_offset_named(sprite s, const char *name);
point2d sprite_layer_offset(sprite s, int32_t idx);
rectangle sprite_layer_rectangle(sprite s, int32_t idx);
rectangle sprite_layer_named_rectangle(sprite s, const char *name);
int32_t sprite_layer_width(sprite s, int32_t idx);
int32_t sprite_layer_named_width(sprite s, const char *name);
matrix2d  sprite_location_matrix(sprite s);
float sprite_mass(sprite s);
bool sprite_move_from_anchor_point(sprite s);
void sprite_move_to(sprite s, const point2d *pt, int32_t takingSeconds);
void sprite_move_to_byval(sprite s, const point2d pt, int32_t takingSeconds);
void sprite_name(sprite sprt, char *result);
sprite sprite_named(const char *name);
bool sprite_offscreen(sprite s);
bool sprite_on_screen_at_point(sprite s, const point2d *pt);
bool sprite_on_screen_at_point_byval(sprite s, const point2d pt);
bool sprite_on_screen_at(sprite s, int32_t x, int32_t y);
point2d sprite_position(sprite s);
void sprite_replay_animation(sprite s);
void replay_animation_with_sound(sprite s, bool withSound);
float sprite_rotation(sprite s);
float sprite_scale(sprite s);
rectangle sprite_screen_rectangle(sprite s);
void sprite_send_layer_backward(sprite s, int32_t visibleLayer);
void sprite_send_layer_to_back(sprite s, int32_t visibleLayer);
void sprite_set_anchor_point(sprite s, point2d pt);
void sprite_set_collision_bitmap(sprite s, bitmap bmp);
void sprite_set_collision_kind(sprite s, collision_test_kind value);
void sprite_set_dx(sprite s, float value);
void sprite_set_dy(sprite s, float value);
void sprite_set_heading(sprite s, float value);
void sprite_set_layer_offset(sprite s, int32_t idx, const point2d *value);
void sprite_set_layer_offset_byval(sprite s, int32_t idx, const point2d value);
void sprite_set_layer_offset_named(sprite s, const char *name, const point2d *value);
void sprite_set_layer_offset_named_byval(sprite s, const char *name, const point2d value);
void sprite_set_mass(sprite s, float value);
void sprite_set_move_from_anchor_point(sprite s, bool value);
void sprite_set_position(sprite s, const point2d *value);
void sprite_set_position_byval(sprite s, const point2d value);
void sprite_set_rotation(sprite s, float value);
void sprite_set_scale(sprite s, float value);
void sprite_set_speed(sprite s, float value);
void sprite_set_value_named(sprite s, const char *name, float val);
void sprite_set_value(sprite s, int32_t idx, float val);
void sprite_set_velocity(sprite s, const vector *value);
void sprite_set_velocity_byval(sprite s, const vector value);
void sprite_set_x(sprite s, float value);
void sprite_set_y(sprite s, float value);
int32_t sprite_show_layer(sprite s, int32_t id);
int32_t sprite_show_layer_named(sprite s, const char *name);
float sprite_speed(sprite s);
void sprite_start_animation(sprite s, int32_t idx);
void sprite_start_animation_named(sprite s, const char *named);
void sprite_start_animation_named_with_sound(sprite s, const char *named, bool withSound);
void sprite_start_animation_with_sound(sprite s, int32_t idx, bool withSound);
void sprite_stop_calling_on_event(sprite s, sprite_event_handler handler);
void sprite_toggle_layer_visible(sprite s, int32_t id);
void sprite_toggle_layer_named_visible(sprite s, const char *name);
float sprite_value(sprite s, int32_t index);
float sprite_value_named(sprite s, const char *name);
int32_t sprite_value_count(sprite s);
void sprite_value_name(sprite s, int32_t idx, char *result);
vector sprite_velocity(sprite s);
int32_t sprite_visible_index_of_layer(sprite s, int32_t id);
int32_t sprite_visible_index_of_layer_named(sprite s, const char *name);
int32_t sprite_visible_layer(sprite s, int32_t idx);
int32_t sprite_visible_layer_count(sprite s);
int32_t sprite_visible_layer_id(sprite s, int32_t idx);
int32_t sprite_width(sprite s);
float sprite_x(sprite s);
float sprite_y(sprite s);
void stop_calling_on_sprite_event(sprite_event_handler handler);
void update_all_sprites();
void update_all_sprites_pct(float pct);
void update_sprite(sprite s);
void update_sprite_with_sound(sprite s, bool withSound);
void update_sprite_percent(sprite s, float pct);
void update_sprite_pct_with_sound(sprite s, float pct, bool withSound);
void update_sprite_animation(sprite s);
void update_sprite_animation_with_sound(sprite s, bool withSound);
void update_sprite_animation_percent(sprite s, float pct);
void update_sprite_animation_pct_with_sound(sprite s, float pct, bool withSound);
vector vector_from_center_sprite_to_point(sprite s, const point2d *pt);
vector vector_from_center_sprite_to_point_byval(sprite s, const point2d pt);
vector vector_from_to(sprite s1, sprite s2);

#ifdef __cplusplus
// C++ overloaded functions
sprite create_sprite(bitmap layer);
sprite create_sprite(const char *name, bitmap layer);
sprite create_sprite(const char *bitmapName, const char *animationName);
sprite create_sprite(bitmap layer, animation_script ani);
sprite create_sprite(const char *name, bitmap layer, animation_script ani);
void draw_sprite(sprite s, const point2d &position);
void draw_sprite(sprite s, int32_t xOffset, int32_t yOffset);
void free_sprite(sprite &s);
void move_sprite(sprite s, const vector &distance);
void move_sprite(sprite s, float pct);
void move_sprite(sprite s, const vector &distance, float pct);
void sprite_add_to_velocity(sprite s, const vector &value);
void sprite_add_value(sprite s, const char *name, float initVal);
void sprite_hide_layer(sprite s, const char *name);
bitmap sprite_layer(sprite s, const char *name);
bitmap sprite_layer(sprite s, int32_t idx);
circle sprite_layer_circle(sprite s, const char *name);
int32_t sprite_layer_height(sprite s, const char *name);
point2d sprite_layer_offset(sprite s, const char *name);
rectangle sprite_layer_rectangle(sprite s, const char *name);
int32_t sprite_layer_width(sprite s, const char *name);
void sprite_move_to(sprite s, const point2d &pt, int32_t takingSeconds);
bool sprite_on_screen_at(sprite s, const point2d &pt);
void sprite_replay_animation(sprite s, bool withSound);
void sprite_set_layer_offset(sprite s, int32_t idx, const point2d &value);
void sprite_set_layer_offset(sprite s, const char *name, const point2d &value);
void sprite_set_position(sprite s, const point2d &value);
void sprite_set_value(sprite s, const char *name, float val);
void sprite_set_velocity(sprite s, const vector &value);
int32_t sprite_show_layer(sprite s, const char *name);
void sprite_start_animation(sprite s, const char *named);
void sprite_start_animation(sprite s, const char *named, bool withSound);
void sprite_start_animation(sprite s, int32_t idx, bool withSound);
void sprite_toggle_layer_visible(sprite s, const char *name);
float sprite_value(sprite s, const char *name);
int32_t sprite_visible_index_of_layer(sprite s, const char *name);
void update_all_sprites(float pct);
void update_sprite(sprite s, bool withSound);
void update_sprite(sprite s, float pct);
void update_sprite(sprite s, float pct, bool withSound);
void update_sprite_animation(sprite s, bool withSound);
void update_sprite_animation(sprite s, float pct);
void update_sprite_animation(sprite s, float pct, bool withSound);
vector vector_from_center_sprite_to_point(sprite s, const point2d &pt);

#endif

#endif


text:
ACCEPTED

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

#### Published in
Dansk bot. Ark. 4(no. 6): 51 (1938)

#### Original name
Crepidotus autochthonus J.E. Lange, 1938

### Remarks
null


text:
class Less_than {
    double v;
public:
    Less_than(double vv) : v{vv} { }

    bool operator()(const double val) { return val < v; }
};

template<typename C> void print(const C& c, char sep = '\n')
{
    std::cout << "CONTAINER ELEMENTS:\n"
              << "===================\n";

    for (const auto ele : c)
        std::cout << ele << sep;

    std::cout << '\n';
}

int main()
try {
    // 1. Read floating-point values from a file into a vector<double>
    const std::string iname {"input_floats.txt"};
    std::ifstream ifs {iname};
    if (!ifs) throw std::runtime_error("Could not read from file: " + iname);

    std::vector<double> vd;
    for (double d; ifs >> d; )
        vd.push_back(d);

    // 2. Output vd to std::cout
    print(vd);

    // 3. Make a vector of ints and copy the elements from vd to vi
    std::vector<int> vi (vd.size());
    std::copy(vd.begin(), vd.end(), vi.begin());

    // 4. Output the pairs of vd[i], vi[i] to cout, one pair per line
    for (int i = 0; i < vd.size(); ++i)
        std::cout << vd[i] << '\t' << vi[i] << '\n';

    // 5. Output the sum of the elements of vd
    double double_sum = std::accumulate(vd.begin(), vd.end(), 0.0);

    std::cout << "Sum of vector<double>: " << double_sum << '\n';

    // 6. Output the difference between the sum of vd and sum of vi
    double diff_sum =
        std::inner_product(vd.begin(), vd.end(),
                vi.begin(),
                0.0,
                std::plus<double>(),
                std::minus<double>());

    std::cout << "The cumulative difference of int(double) truncs is: "
              << diff_sum << '\n';

    // 7. Reverse vd and output vd to std::cout
    std::reverse(vd.begin(), vd.end());

    print(vd);

    // 8. Compute the mean value of vd and output it
    double vd_mean = double_sum / vd.size();

    std::cout << "The mean of vd is: " << vd_mean << '\n';

    // 9. Make a new vector<double> and copy all elements from vd that are less
    // than vd's mean.
    std::vector<double> vd2 (vd.size());    // too big?

    auto it = std::copy_if(vd.begin(), vd.end(), vd2.begin(),
            Less_than(vd_mean));
    vd2.resize(std::distance(vd2.begin(), it));

    print(vd2);

    // 10. Sort vd, output it again
    std::sort(vd.begin(), vd.end());

    print(vd);
}
catch(std::exception& e) {
    std::cerr << "Exception: " << e.what() << '\n';
    return 1;
}
catch(...) {
    std::cerr << "Unknown exception\n";
    return 2;
}