text:
package ariba.util.core;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.List;

import ariba.util.log.Log;

/**
    Math Utilities. These are helper functions for dealing with
    math.

    @aribaapi documented
*/
public final class MathUtil
{
	private static final long Offset = power2(32);

    /* prevent people from creating instances of this class */
    private MathUtil ()
    {
    }

    /**
        Calculate the log (base 2) of a specified long. This can be
        useful for calculating a bit index from a bit mask.

        @param x a long to calculate the log of

        @return floor(lg(x)), that is, the greatest integer
        less than or equal to log base 2 of x.
        @aribaapi documented
    */
    public static int log2 (long x)
    {
        Assert.that(x > 0, "long x must be greater than 0");
        int lg = -1;
        for (int i = 1; i <= x; i += i) {
            lg++;
        }
        return lg;
    }

    /**
        Calculate 2 raised to a specified power.

        @param x the power to raise 2 to, must be greater or equal to 0

        @return 2 raised to the power of x.
        @aribaapi documented
    */
    public static long power2 (int x)
    {
        Assert.that(x >= 0,
                      "power2 currently requires integers greater or equal to 0");
        long p = 1;
        for (int i = 1; i <= x; i++)
            p += p;
        return p;
    }

    /**
        Returns the specified number with its least significant bit
        zeroed.

        @param n an integer to make even

        @return the specified number with its least significant bit
        zeroed
        @aribaapi documented
    */
    public static int forceEven (int n)
    {
        return (n & 0xfffffffe);
    }

    /**
        Calculate 10 raised to a specified power.

        @param power the power to raise 10 to

        @return 10 raised to the power of power.
        @aribaapi documented
    */
    public static double powerOfTen (int power)
    {
        Assert.that(power >= 0,
                      "power2 currently requires integers greater or equal to 0");
        double value = 10.0;
        if (power == 0) {
            return 1.0;
        }
        for (int i = 1; i < power; i++) {
            value *= 10.0;
        }
        return value;
    }

    /**
        Returns the integer result of (d mod 10).  If round is true, then
        result will be rounded, otherwise, the resulted will be the greatest
        integer at or below the result.

        @param d a double to mod against 10
        @param round if true the double will be rounded to the
        nearest long, if false floor() will be called.

        @return an integer between 0 and 9 of the mod result
        @aribaapi documented
    */
    public static int modulo10 (double d, boolean round)
    {
        long l = round ? Math.round(d) : (long)Math.floor(d);
        int i = (int)(l % 10);
        return i;
    }

    /**
        Returns the specified number with its least significant bit
        set.

        @param n an integer to make odd

        @return the specified number with its least significant bit
        set
        @aribaapi documented
    */
    public static int forceOdd (int n)
    {
        return (n | 0x1);
    }

    /**
        Calculate the greatest common denominator for two longs.

        @param a the first number in long
        @param b the sencond number in long

        @return long value that is the greatest common denominator of the two.
           0 if either of the two numbers is 0 or negative.
        @aribaapi documented
    */
    public static long getGCD (long a,  long b)
    {
        long small = Math.min(a, b);
        long large = Math.max(a, b);
        long temp;

        if (small <= 0) {
            return 1;
        }

        temp = large % small;
        while (temp > 0) {
            large = small;
            small = temp;
            temp = large % small;
        }
        return small;
    }

    /**
        Calculate the least common multiple for two longs.

        @param a the first number in long
        @param b the sencond number in long

        @return long value that is the least common multiple of the two.
           0 if either of the two numbers is 0 or negative.
        @aribaapi documented
    */
    public static long getLCM (long a,  long b)
    {
        long lcd = getGCD(a, b);
        return (a * b / lcd);
    }

    /**
        Adjust the scale of the given BigDecimal to the specified scale.
        @param value the BigDecimal
        @param scale the scale, which can't be negative.
    */
    public static BigDecimal setScale (BigDecimal value, int scale)
    {
        Assert.that(scale >= 0, "Got a negative scale %s",
            String.valueOf(scale));

        try {
           value = value.setScale(scale, BigDecimal.ROUND_HALF_UP);
        }
        catch (ArithmeticException e) {
            Log.util.debug("Should never happen %s", e);
        }
        catch (IllegalArgumentException e) {
            Log.util.debug("Should never happen %s", e);
        }
        return value;
    }

    public static Double setScale (Double value, int scale)
    {
        Assert.that(scale >= 0, "Got a negative scale %s",
            String.valueOf(scale));

        BigDecimal temp = new BigDecimal(value.doubleValue());
        temp = setScale(temp, scale);

        return new Double(temp.doubleValue());
    }

    /*-- Base 64 Conversion -------------------------------------------------*/

    private static final int AlphabetSize = 26;
    private static final int AlphabetSizeTimesTwo = 52;
    private static final int Base64 = 64;

    private static final char base64ConvertTable[] =
    {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
     'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
     'U', 'V', 'W', 'X', 'Y', 'Z',
     'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
     'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
     'u', 'v', 'w', 'x', 'y', 'z',
     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
     '+', '!'
    };

    /**
        Converts the given long into a base 64 string.

        @param num the number to convert into base 64

        @return a String representation of num in base 64
        @aribaapi documented
    */
    public static String toBase64 (long num)
    {
        Assert.that(num >= 0,
                    "the long passed into MathUtil.toBase64 must be positive.");

            // Long.MAX_VALUE can more than fit in array of size 16.
        char [] buffer = new char[16];
        int offset = toBase64(num, buffer, 15);
        return new String(buffer, offset+1, 15-offset);
    }

    /**
        Converts the given long into a base 64 string. The result is
        stored in the character array chr, starting with the
        character at off, counted from the end of the array.

        @param num the number to convert into base 64
        @param chr the character array to insert the base 64
        representation of the number into
        @param off the offset into the character array to start writing

        @return the index of the character preceding the last
        character written into the buffer.
        @aribaapi documented
    */
    public static int toBase64 (long num, char[] chr, int off)
    {
        if (num == 0) {
            chr[off] = 'A';
            off--;
        }
        else {
            for (; num > 0; off--) {
                chr[off] = base64ConvertTable[(int)(num % 64)];
                num = num / Base64;
            }
        }
        return off;
    }

    /**
        Convert a string representation of a base64 number into a
        long.

        @param s a String representation of a base 64 number

        @return long the number as a long; -1 in case the string s contains
        a character not present in the base64 character set

        @aribaapi documented
    */
    public static long fromBase64 (String s)
    {
        return fromBase64(s, 0, s.length() - 1);
    }

    /**
        Convert a string representation of a base64 number into a
        long.

        @param s a String containing a representation of a base 64
        number
        @param offset the offset of the first character in the string
        to start begin parsing at.

        @return long the number as a long; -1 in case the string s contains
        a character not present in the base64 character set

        @aribaapi documented
    */
    public static long fromBase64 (String s, int offset)
    {
        return fromBase64(s, offset, s.length() - 1);
    }

    /**
        Convert a string representation of a base64 number into a
        long.

        @param s a String containing a representation of a base 64
        number
        @param beginIndex the offset of the first character in the string
        to parse (inclusive).
        @param endIndex the offset of the last character in the string
        to parse (inclusive).

        @return long the number as a long; -1 in case the string s contains
        a character not present in the base64 character set

        @aribaapi documented
    */
    public static long fromBase64 (String s, int beginIndex, int endIndex)
    {
        long sum = 0;
        for (int i = beginIndex; i <= endIndex; i++) {
            char c = s.charAt(i);
            int digit;
            if (c >= 'A' && c <= 'Z') {
                digit = c - 'A';
            }
            else if (c >= 'a' && c <= 'z') {
                digit = c - 'a' + AlphabetSize;
            }
            else if (c >= '0' && c <= '9') {
                digit = c - '0' + AlphabetSizeTimesTwo;
            }
            else if (c == '+') {
                digit = 62;
            }
            else if (c == '!') {
                digit = 63;
            }
            else {
                return -1;
            }
            sum = (sum * Base64) + digit;
        }

        return sum;
    }

    /*-- Base36 Conversion -------------------------------------------------*/

    /**
        Converts the given long into a base 36 string.

        @param num the number to convert into base 36

        @return a String representation of num in base 36
        @aribaapi documented
    */
    public static String toBase36 (long num)
    {
        Assert.that(num >= 0,
                    "the long passed MathUtil.toBase36 must be positive.");
        char [] buffer = new char[32];
        int offset = toBase36(num, buffer, 31);
        return new String(buffer, offset+1, 31-offset);
    }

    /**
        Converts the given long into a base 36 string. The result is
        stored in the character array chr, starting with the
        character at off, counted from the end of the array.

        @param num the number to convert into base 36
        @param chr the character array to insert the base 36
        representation of the number into
        @param off the offset into the character array to start writing

        @return the index of the character preceding the last
        character written into the buffer.
        @aribaapi documented
    */
    public static int toBase36 (long num, char[] chr, int off)
    {
        if (num == 0) {
            chr[off] = '0';
            off--;
        }
        else {
            for (; num > 0; off--) {
                chr[off] = base36ConvertTable[(int)(num % 36)];
                num = num / 36;
            }
        }
        return off;
    }

    private static final char base36ConvertTable[] =
    {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
     'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
     'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
     'u', 'v', 'w', 'x', 'y', 'z'};

    /**
        Parse starting with the offset-th character, until reaching an
        invalid character.
    */
    private static final int AlphaDigitOffset = 'a' - 10;
    private static final int Base36 = 36;

    /**
        Convert a string representation of a base36 number into a
        long.

        @param s a String representation of a base 36 number

        @return long the number as a long

        @exception ParseException if the String s could not be
        parsed
        @aribaapi documented
    */
    public static long fromBase36 (String s) throws ParseException
    {
        for (int i = 0, l = s.length(); i < l ; i++) {
            char c = s.charAt(i);
            if (!((c >= '0' && c <= '9') ||
                  (c >= 'a' && c <= 'z')))
            {
                throw new ParseException(
                    Fmt.S("%s is not a valid Base 36 digit in %s",
                          new Character(c), s),
                    i);
            }
        }
        return fromBase36(s, 0);
    }

    /**
        Convert a string representation of a base36 number into a
        long. Parsing stops at the first character that can not be
        part of a base 36 number.

        @param s a String containing a representation of a base 36
        number
        @param offset the offset of the first character in the string
        to start begin parsing at.

        @return long the number as a long
        @aribaapi documented
    */
    public static long fromBase36 (String s, int offset)
    {
        int len = s.length();
        long sum = 0;
        for (int i = offset; i < len; i++) {
            char c = s.charAt(i);
            int digit;
            if (c >= '0' && c <= '9') {
                digit = c - '0';
            }
            else if (c >= 'a' && c <= 'z') {
                digit = c - AlphaDigitOffset;
            }
            else {
                break;
            }
            sum = (sum * Base36) + digit;
        }

        return sum;
    }

        // 2-D hashtable cache of permutation sets
    private static final Gridtable PermsCache = new Gridtable();

    /**
        Returns a List of Lists, where each sub-List is a list of
        Integers representing one permutation of r numbers between 0
        and n.

        @param n upper limit of the range within which the members of the
        permutation fall
        @param r count of integers in the permutation
        @return List of Lists, where each sub-List is a list of
        Integers representing one permutation
        @aribaapi documented
    */
    public static List permutations (int n, int r)
    {
            // check cache first
        List perms =
            (List)PermsCache.get(Constants.getInteger(n), Constants.getInteger(r));
        if (perms == null) {
            Object[] alphabet = new Object[n+1];
            for (int i = 0; i < n; i++) {
                alphabet[i] = Constants.getInteger(i);
            }
            perms = permutations(n, r, alphabet, 0, r);
            PermsCache.put(Constants.getInteger(n), Constants.getInteger(r), perms);
        }

        return perms;
    }

    /*
        Implements a P(n,r) permutations algorithm.  The alphabet a can
        be an array of arbitrary objects, e.g. Integers, Strings, Characters,
        etc.
    */
    private static List permutations (int n, int r, Object[] a, int s, int max)
    {
        Assert.that((r <= n), "MathUtil.permutations: r must be <= n");

        List perms = ListUtil.list();

        if (r == 1) {
            for (int i = 0; i < n; i++) {
                Object[] perm = new Object[max];
                perm[0] = a[i+s];
                perms.add(perm);
            }
        }

        // iterate over all n items in the alphabet
        // append each to the permutations of the rest
        else {

            for (int i = 0; i < n; i++) {

                // take the first element as our prefix
                Object prefix = a[s];

                // calculate all the perms of the rest of the alphabet
                List subs = permutations(n-1, r-1, a, s+1, max);

                // for each sub-perm, tack on the suffix element
                for (int j = 0; j < subs.size(); j++) {
                    Object[] sub = (Object[])subs.get(j);
                    sub[r-1] = prefix;
                }

                // save this set of permutations
                perms.addAll(subs);

                // swap the first element with the next prefix
                a[s] = a[s+i+1];
                a[s+i+1] = prefix;
            }

            // alphabet is shifted right one now, shift it back
            System.arraycopy(a, s+1, a, s, n);
            a[a.length-1] = null;
        }

        return perms;
    }

    /**
        Returns the value of the sgn mathematical function (the
        signum function) on the operands a and b.

        The signum function returns -1 if a < b,
        0 if a == b and +1 if a > b.
        It serves as a safe way to determine how two integers compare.
        Simply subtracting the integers and comparing the result with
        zero can fail for numbers close to Integer.MAX_VALUE
        and Integer.MIN_VALUE.

        @return the value of the sgn function on the supplied
                operands
        @aribaapi ariba
    */
    public static int sgn (int a, int b)
    {
        return a < b ? -1 : (a == b ? 0 : +1);
    }

    /**
        Returns the value of the sgn mathematical function (the
        signum function) on the operands a and b.

        The signum function returns -1 if a < b,
        0 if a == b and +1 if a > b.
        It serves as a safe way to determine how two longs compare.
        Simply subtracting the numbers and comparing the result with
        zero can fail for numbers close to Long.MAX_VALUE
        and Long.MIN_VALUE.

        @return the value of the sgn function on the supplied
                operands
        @aribaapi ariba
    */
    public static int sgn (long a, long b)
    {
        return a < b ? -1 : (a == b ? 0 : +1);
    }

    /**
        Bounds value to be within lower and
        upper, inclusively.

        That is if value < lower then
        lower is returned and if value > upper
        then upper is returned, else value itself
        is returned.

        Note that if upper is less than lower, this
        function returns as if upper is positive infinity.

        @param value the value to be bounded
        @param lower the lower bound
        @param upper the upper bound
        @return the bounded value

        @aribaapi documented
    */
    public static int bound (int value, int lower, int upper)
    {
        return value < lower ? lower : (value > upper ? upper : value);
    }

    /**
	    Private method that calculates the hash code for the char[]
	    val according to the sun's unique implementation which
	    they say will be standard in 1.2 (love those standards)
    */
	public static final int sunHashCode (char[] val)
	{
	    int i1 = 0;
	    int j = 0;
	    char ach[] = val;
	    int k = val.length;
	    for (int i2 = 0; i2 < k; i2++)
	        i1 = 31 * i1 + ach[j++];
	    return i1;
	}

    /**
        Private method that calculates the hash code for the char[]
        val according to the java spec.
    */
	public static final int normalHashCode (char[] val)
	{
	    int h = 0;
	    int off = 0;
	    int len = val.length;

	    if (len < 16) {
	        for (int i = len ; i > 0; i--) {
	            h = (h * 37) + val[off++];
	        }
	    }
	    else {
	            // only sample some characters
	        int skip = len / 8;
	        for (int i = len ; i > 0; i -= skip, off += skip) {
	            h = (h * 39) + val[off];
	        }
	    }
	    return h;
	}

	/**
     * @param s
     * @return int
     *
 A convenience method to return an unsigned hash for a given
     * String. If a hash code generated is negative, it is offset by
     * adding 2 ^ 32
     */
    public static final long unsignedUniqueId (String s)
    {
    	int jdkHash = sunHashCode(s.toCharArray());
    	long unsignedId = jdkHash < 0 ? jdkHash + Offset :
    		jdkHash;
    	return unsignedId;
    }

}


text:
"""Futures for dealing with asynchronous operations."""

from google.api_core.future.base import Future

__all__ = [
    'Future',
]

redpajama_set_name: RedPajamaGithub


text:
package com.gdn.venice.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.gdn.venice.persistence.VenOrderStatusHistory;

public interface VenOrderStatusHistoryDAO extends JpaRepository<VenOrderStatusHistory, Long> {

}


text:
Solves for the new path of `srcFilePath` given the changes to the directory structure described by `directoryChanges`. `directoryChanges` is either a hash that maps the absolute paths of old directories to those of new directories or a function that does the same. `srcFilePath` is an absolute path.

If no changes are described in `directoryChanges` that affect the path of `srcFilePath`, then `srcFilePath` is returned.

```javascript
pathMapper = require( 'path-mapper' );

dstFilePath = pathMapper( srcFilePath, directoryChanges );

// or

var url = pathMapper( srcFilePath, function( srcDir ) {
	return '/' + packagePathsToIds[ srcDir ];
} );
```

## License

MIT


text:
from nipype.testing import assert_equal
from nipype.interfaces.semtools.utilities.brains import ImageRegionPlotter

def test_ImageRegionPlotter_inputs():
    input_map = dict(args=dict(argstr='%s',
    ),
    environ=dict(nohash=True,
    usedefault=True,
    ),
    ignore_exception=dict(nohash=True,
    usedefault=True,
    ),
    inputBinaryROIVolume=dict(argstr='--inputBinaryROIVolume %s',
    ),
    inputLabelVolume=dict(argstr='--inputLabelVolume %s',
    ),
    inputVolume1=dict(argstr='--inputVolume1 %s',
    ),
    inputVolume2=dict(argstr='--inputVolume2 %s',
    ),
    numberOfHistogramBins=dict(argstr='--numberOfHistogramBins %d',
    ),
    outputJointHistogramData=dict(argstr='--outputJointHistogramData %s',
    ),
    terminal_output=dict(nohash=True,
    ),
    useIntensityForHistogram=dict(argstr='--useIntensityForHistogram ',
    ),
    useROIAUTO=dict(argstr='--useROIAUTO ',
    ),
    verbose=dict(argstr='--verbose ',
    ),
    )
    inputs = ImageRegionPlotter.input_spec()

    for key, metadata in input_map.items():
        for metakey, value in metadata.items():
            yield assert_equal, getattr(inputs.traits()[key], metakey), value

def test_ImageRegionPlotter_outputs():
    output_map = dict()
    outputs = ImageRegionPlotter.output_spec()

    for key, metadata in output_map.items():
        for metakey, value in metadata.items():
            yield assert_equal, getattr(outputs.traits()[key], metakey), value


text:
package com.guonl.builder;

public class Coke extends ColdDrink {

	@Override
	public float price() {
		return 30.0f;
	}

	@Override
	public String name() {
		return "Coke";
	}
}


text:
// ZAP: 2011/08/30 Support for scanner levels
// ZAP: 2012/01/02 Separate param and attack
// ZAP: 2012/03/03 Added getLevel(boolean incDefault)
// ZAP: 2102/03/15 Changed the type of the parameter "sb" of the method matchBodyPattern to
// StringBuilder.
// ZAP: 2012/04/25 Added @Override annotation to all appropriate methods.
// ZAP: 2012/08/07 Renamed Level to AlertThreshold and added support for AttackStrength
// ZAP: 2012/08/31 Enabled control of AttackStrength
// ZAP: 2012/10/03 Issue 388 Added enabling support for technologies
// ZAP: 2013/01/19 Issue 460 Add support for a scan progress dialog
// ZAP: 2013/01/25 Removed the "(non-Javadoc)" comments.
// ZAP: 2013/02/19 Issue 528 Scan progress dialog can show negative progress times
// ZAP: 2013/04/14 Issue 611: Log the exceptions thrown by active scanners as error
// ZAP: 2013/05/02 Re-arranged all modifiers into Java coding standard order
// ZAP: 2013/07/12 Issue 713: Add CWE and WASC numbers to issues
// ZAP: 2013/09/08 Issue 691: Handle old plugins
// ZAP: 2013/11/16 Issue 842: NullPointerException while active scanning with ExtensionAntiCSRF disabled
// ZAP: 2014/01/16 Add support to plugin skipping
// ZAP: 2014/02/12 Issue 1030: Load and save scan policies
// ZAP: 2014/02/21 Issue 1043: Custom active scan dialog
// ZAP: 2014/05/15 Issue 1196: AbstractPlugin.bingo incorrectly sets evidence to attack
// ZAP: 2014/05/23 Issue 1209: Reliability becomes Confidence and add levels
// ZAP: 2014/07/07 Issue 389: Enable technology scope for scanners
// ZAP: 2014/10/25 Issue 1062: Made plugins that calls sendandrecieve also invoke scanner
// hook before and after message update
// ZAP: 2014/11/19 Issue 1412: Init scan rule status (quality) from add-on
// ZAP: 2015/03/26 Issue 1573: Add option to inject plugin ID in header for all ascan requests
// ZAP: 2015/07/26 Issue 1618: Target Technology Not Honored
// ZAP: 2015/08/19 Issue 1785: Plugin enabled even if dependencies are not, "hangs" active scan

package org.parosproxy.paros.core.scanner;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.InvalidParameterException;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.httpclient.HttpException;
import org.apache.log4j.Logger;
import org.parosproxy.paros.control.Control;
import org.parosproxy.paros.extension.encoder.Encoder;
import org.parosproxy.paros.network.HttpHeader;
import org.parosproxy.paros.network.HttpMessage;
import org.zaproxy.zap.control.AddOn;
import org.zaproxy.zap.extension.anticsrf.AntiCsrfToken;
import org.zaproxy.zap.extension.anticsrf.ExtensionAntiCSRF;
import org.zaproxy.zap.model.Tech;
import org.zaproxy.zap.model.TechSet;

public abstract class AbstractPlugin implements Plugin, Comparable<Object> {

    /**
     * Default pattern used in pattern check for most plugins.
     */
    protected static final int PATTERN_PARAM = Pattern.CASE_INSENSITIVE | Pattern.MULTILINE;
    /**
     * CRLF string.
     */
    protected static final String CRLF = "\r\n";
    private HostProcess parent = null;
    private HttpMessage msg = null;
    private boolean enabled = true;
    private Logger log = Logger.getLogger(this.getClass());
    private Configuration config = null;
    // ZAP Added delayInMs
    private int delayInMs;
    private ExtensionAntiCSRF extAntiCSRF = null;
    private Encoder encoder = new Encoder();
    private AlertThreshold defaultAttackThreshold = AlertThreshold.MEDIUM;
    private static final AlertThreshold[] alertThresholdsSupported = new AlertThreshold[]{AlertThreshold.MEDIUM};
    private AttackStrength defaultAttackStrength = AttackStrength.MEDIUM;
    private static final AttackStrength[] attackStrengthsSupported = new AttackStrength[]{AttackStrength.MEDIUM};
    private TechSet techSet = null;
    private Date started = null;
    private Date finished = null;
    private AddOn.Status status = AddOn.Status.unknown;

    /**
     * Default Constructor
     */
    public AbstractPlugin() {
    }

    @Override
    public abstract int getId();

    @Override
    public abstract String getName();

    @Override
    public String getCodeName() {
        String result = getClass().getName();
        int pos = getClass().getName().lastIndexOf(".");
        if (pos > -1) {
            result = result.substring(pos + 1);
        }
        return result;
    }

    @Override
    public abstract String[] getDependency();

    @Override
    public abstract String getDescription();

    @Override
    public abstract int getCategory();

    @Override
    public abstract String getSolution();

    @Override
    public abstract String getReference();

    @Override
    public void init(HttpMessage msg, HostProcess parent) {
        this.msg = msg.cloneAll();
        this.parent = parent;
        if (this.parent.getScannerParam().isInjectPluginIdInHeader()) {
    		this.msg.getRequestHeader().setHeader(HttpHeader.X_ZAP_SCAN_ID, Integer.toString(getId()));
    	}
        init();
    }

    public abstract void init();

    /**
     * Obtain a new HttpMessage with the same request as the base. The response
     * is empty. This is used by plugin to build/craft a new message to
     * send/receive. It does not affect the base message.
     *
     * @return A new HttpMessage with cloned request. Response is empty.
     */
    protected HttpMessage getNewMsg() {
        return msg.cloneRequest();
    }

    /**
     * Get the base reference HttpMessage for this check. Both request and
     * response is present. It should not be modified during when the plugin
     * runs.
     *
     * @return The base HttpMessage with request/response.
     */
    protected HttpMessage getBaseMsg() {
        return msg;
    }

    /**
     * Send and receive a HttpMessage. msg should have the request header/body
     * set. Fresh copy will always be retrieved via this method. The request
     * header content length will be modified by this method.
     *
     * @param msg
     * @throws HttpException
     * @throws IOException
     */
    protected void sendAndReceive(HttpMessage msg) throws HttpException, IOException {
        sendAndReceive(msg, true);
    }

    protected void sendAndReceive(HttpMessage msg, boolean isFollowRedirect) throws HttpException, IOException {
        sendAndReceive(msg, isFollowRedirect, true);
    }

    /**
     * Send and receive a HttpMessage. msg should have the request header/body
     * set. Fresh copy will always be retrieved via this method. The request
     * header content length will be modified by this method.
     *
     * @param msg
     * @param isFollowRedirect follow redirect response
     * @throws HttpException
     * @throws IOException
     */
    protected void sendAndReceive(HttpMessage msg, boolean isFollowRedirect, boolean handleAntiCSRF) throws HttpException, IOException {

        if (parent.handleAntiCsrfTokens() && handleAntiCSRF) {
            if (extAntiCSRF == null) {
                extAntiCSRF = (ExtensionAntiCSRF) Control.getSingleton().getExtensionLoader().getExtension(ExtensionAntiCSRF.NAME);
            }
            if (extAntiCSRF != null) {
                List<AntiCsrfToken> tokens = extAntiCSRF.getTokens(msg);
                AntiCsrfToken antiCsrfToken = null;
                if (tokens.size() > 0) {
                    antiCsrfToken = tokens.get(0);
                }

                if (antiCsrfToken != null) {
                    regenerateAntiCsrfToken(msg, antiCsrfToken);
                }
            }
        }

        // always get the fresh copy
        msg.getRequestHeader().setHeader(HttpHeader.IF_MODIFIED_SINCE, null);
        msg.getRequestHeader().setHeader(HttpHeader.IF_NONE_MATCH, null);
        msg.getRequestHeader().setContentLength(msg.getRequestBody().length());

        if (this.getDelayInMs() > 0) {
            try {
                Thread.sleep(this.getDelayInMs());
            } catch (InterruptedException e) {
                // Ignore
            }
        }

        //ZAP: Runs the "beforeScan" methods of any ScannerHooks
        parent.performScannerHookBeforeScan(msg, this);

        parent.getHttpSender().sendAndReceive(msg, isFollowRedirect);

        // ZAP: Notify parent
        parent.notifyNewMessage(msg);

        //ZAP: Set the history reference back and run the "afterScan" methods of any ScannerHooks
        parent.performScannerHookAfterScan(msg, this);
    }

    private void regenerateAntiCsrfToken(HttpMessage msg, AntiCsrfToken antiCsrfToken) {
        if (antiCsrfToken == null) {
            return;
        }

        String tokenValue = null;
        try {
            HttpMessage tokenMsg = antiCsrfToken.getMsg().cloneAll();

            // Ensure we dont loop
            sendAndReceive(tokenMsg, true, false);

            tokenValue = extAntiCSRF.getTokenValue(tokenMsg, antiCsrfToken.getName());

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        if (tokenValue != null) {
            // Replace token value - only supported in the body right now
            log.debug("regenerateAntiCsrfToken replacing " + antiCsrfToken.getValue() + " with " + encoder.getURLEncode(tokenValue));
            String replaced = msg.getRequestBody().toString();
            replaced = replaced.replace(encoder.getURLEncode(antiCsrfToken.getValue()), encoder.getURLEncode(tokenValue));
            msg.setRequestBody(replaced);
            extAntiCSRF.registerAntiCsrfToken(new AntiCsrfToken(msg, antiCsrfToken.getName(), tokenValue, antiCsrfToken.getFormIndex()));
        }
    }

    @Override
    public void run() {
        // ZAP : set skipped to false otherwise the plugin shoud stop continously
        //this.skipped = false;

        try {
            if (!isStop()) {
                this.started = new Date();
                scan();
            }

        } catch (Exception e) {
            getLog().error(e.getMessage(), e);
        }

        notifyPluginCompleted(getParent());
        this.finished = new Date();
    }

    /**
     * The core scan method to be implmented by subclass.
     */
    @Override
    public abstract void scan();

    /**
     * Generate an alert when a security issue (risk/info) is found. Default
     * name, description, solution of this Plugin will be used.
     *
     * @param risk
     * @param confidence
     * @param uri
     * @param param
     * @param attack
     * @param otherInfo
     * @param msg
     */
    protected void bingo(int risk, int confidence, String uri, String param, String attack, String otherInfo,
            HttpMessage msg) {

        bingo(risk, confidence, this.getName(), this.getDescription(), uri, param, attack, otherInfo, this.getSolution(),
                msg);
    }

    /**
     * Generate an alert when a security issue (risk/info) is found. Custome
     * alert name, description and solution will be used.
     *
     * @param risk
     * @param confidence
     * @param name
     * @param description
     * @param uri
     * @param param
     * @param attack
     * @param otherInfo
     * @param solution
     * @param msg
     */
    protected void bingo(int risk, int confidence, String name, String description, String uri,
            String param, String attack, String otherInfo, String solution,
            HttpMessage msg) {

        log.debug("New alert pluginid=" + +this.getId() + " " + name + " uri=" + uri);

        Alert alert = new Alert(this.getId(), risk, confidence, name);
        if (uri == null || uri.equals("")) {
            uri = msg.getRequestHeader().getURI().toString();
        }

        if (param == null) {
            param = "";
        }

        alert.setDetail(description, uri, param, attack, otherInfo, solution, this.getReference(),
                "", this.getCweId(), this.getWascId(), msg);

        parent.alertFound(alert);
    }

    /**
     * Generate an alert when a security issue (risk/info) is found. Default
     * name, description, solution of this Plugin will be used.
     *
     * @param risk
     * @param confidence
     * @param uri
     * @param param
     * @param attack
     * @param otherInfo
     * @param evidence
     * @param msg
     */
    protected void bingo(int risk, int confidence, String uri, String param, String attack, String otherInfo,
            String evidence, HttpMessage msg) {

        bingo(risk, confidence, this.getName(), this.getDescription(), uri, param, attack, otherInfo, this.getSolution(),
                evidence, msg);
    }

    /**
     * Generate an alert when a security issue (risk/info) is found. Custome
     * alert name, description and solution will be used.
     *
     * @param risk
     * @param confidence
     * @param name
     * @param description
     * @param uri
     * @param param
     * @param attack
     * @param otherInfo
     * @param solution
     * @param evidence
     * @param msg
     */
    protected void bingo(int risk, int confidence, String name, String description, String uri,
            String param, String attack, String otherInfo, String solution,
            String evidence, HttpMessage msg) {

        log.debug("New alert pluginid=" + +this.getId() + " " + name + " uri=" + uri);
        Alert alert = new Alert(this.getId(), risk, confidence, name);
        if (uri == null || uri.equals("")) {
            uri = msg.getRequestHeader().getURI().toString();
        }

        if (param == null) {
            param = "";
        }

        alert.setDetail(description, uri, param, attack, otherInfo, solution, this.getReference(),
                evidence, this.getCweId(), this.getWascId(), msg);

        parent.alertFound(alert);
    }

    protected void bingo(int risk, int confidence, String name, String description, String uri,
            String param, String attack, String otherInfo, String solution,
            String evidence, int cweId, int wascId, HttpMessage msg) {

        log.debug("New alert pluginid=" + +this.getId() + " " + name + " uri=" + uri);
        Alert alert = new Alert(this.getId(), risk, confidence, name);

        if (uri == null || uri.equals("")) {
            uri = msg.getRequestHeader().getURI().toString();
        }

        if (param == null) {
            param = "";
        }

        alert.setDetail(description, uri, param, attack, otherInfo, solution, this.getReference(),
                evidence, cweId, wascId, msg);

        parent.alertFound(alert);
    }

    /**
     * Check i
     *
     * @param msg
     * @return
     */
    protected boolean isFileExist(HttpMessage msg) {
        return parent.getAnalyser().isFileExist(msg);
    }

    /**
     * Check if this test should be stopped. It should be checked periodically
     * in Plugin (eg when in loops) so the HostProcess can stop this Plugin
     * cleanly.
     *
     * @return
     */
    protected boolean isStop() {
        // ZAP: added skipping controls
        return parent.isStop() || parent.isSkipped(this);
    }

    /**
     * @return Returns if this test is enabled.
     */
    @Override
    public boolean isEnabled() {
        return enabled;

    }

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

    /**
     * Enable this test
     */
    @Override
    public void setEnabled(boolean enabled) {
        if (this.enabled != enabled) {
            this.enabled = enabled;
            setProperty("enabled", Boolean.toString(enabled));
            if (enabled && getAlertThreshold() == AlertThreshold.OFF) {
                setAlertThreshold(AlertThreshold.DEFAULT);
            }
        }
    }

    @Override
    public AlertThreshold getAlertThreshold() {
        return this.getAlertThreshold(false);
    }

    @Override
    public AlertThreshold getAlertThreshold(boolean incDefault) {
        AlertThreshold level = null;
        try {
            level = AlertThreshold.valueOf(getProperty("level"));
            //log.debug("getAlertThreshold from configs: " + level.name());

        } catch (Exception e) {
            // Ignore
        }

        if (level == null) {
            if (this.isEnabled()) {
                if (incDefault) {
                    level = AlertThreshold.DEFAULT;

                } else {
                    level = defaultAttackThreshold;
                }

                //log.debug("getAlertThreshold default: " + level.name());

            } else {
                level = AlertThreshold.OFF;
                //log.debug("getAlertThreshold not enabled: " + level.name());
            }

        } else if (level.equals(AlertThreshold.DEFAULT)) {
            if (incDefault) {
                level = AlertThreshold.DEFAULT;

            } else {
                level = defaultAttackThreshold;
            }

            //log.debug("getAlertThreshold default: " + level.name());
        }

        return level;
    }

    @Override
    public void setAlertThreshold(AlertThreshold level) {
        setProperty("level", level.name());
        setEnabled(level != AlertThreshold.OFF);
    }

    @Override
    public void setDefaultAlertThreshold(AlertThreshold level) {
        this.defaultAttackThreshold = level;
    }

    /**
     * Override this if you plugin supports other levels.
     */
    @Override
    public AlertThreshold[] getAlertThresholdsSupported() {
        return alertThresholdsSupported;
    }

    @Override
    public AttackStrength getAttackStrength(boolean incDefault) {
        AttackStrength level = null;
        try {
            level = AttackStrength.valueOf(getProperty("strength"));
            //log.debug("getAttackStrength from configs: " + level.name());

        } catch (Exception e) {
            // Ignore
        }

        if (level == null) {
            if (incDefault) {
                level = AttackStrength.DEFAULT;

            } else {
                level = this.defaultAttackStrength;
            }

            //log.debug("getAttackStrength default: " + level.name());

        } else if (level.equals(AttackStrength.DEFAULT)) {
            if (incDefault) {
                level = AttackStrength.DEFAULT;

            } else {
                level = this.defaultAttackStrength;
            }

            //log.debug("getAttackStrength default: " + level.name());
        }

        return level;
    }

    @Override
    public AttackStrength getAttackStrength() {
        return this.getAttackStrength(false);
    }

    @Override
    public void setAttackStrength(AttackStrength level) {
        setProperty("strength", level.name());
    }

    @Override
    public void setDefaultAttackStrength(AttackStrength strength) {
        this.defaultAttackStrength = strength;
    }

    /**
     * Override this if you plugin supports other levels.
     */
    @Override
    public AttackStrength[] getAttackStrengthsSupported() {
        return attackStrengthsSupported;
    }

    /**
     * Compare if 2 plugin is the same.
     */
    @Override
    public int compareTo(Object obj) {
        int result = -1;
        if (obj instanceof AbstractPlugin) {
            AbstractPlugin test = (AbstractPlugin) obj;
            if (getId() < test.getId()) {
                result = -1;

            } else if (getId() > test.getId()) {
                result = 1;

            } else {
                result = 0;
            }
        }

        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (compareTo(obj) == 0) {
            return true;
        }

        return false;
    }

    /**
     * Check if the given pattern can be found in the header.
     *
     * @param msg
     * @param header name.
     * @param pattern
     * @return true if the pattern can be found.
     */
    protected boolean matchHeaderPattern(HttpMessage msg, String header, Pattern pattern) {
        if (msg.getResponseHeader().isEmpty()) {
            return false;
        }

        String val = msg.getResponseHeader().getHeader(header);
        if (val == null) {
            return false;
        }

        Matcher matcher = pattern.matcher(val);
        return matcher.find();
    }

    /**
     * Check if the given pattern can be found in the msg body. If the supplied
     * StringBuilder is not null, append the result to the StringBuilder.
     *
     * @param msg
     * @param pattern
     * @param sb
     * @return true if the pattern can be found.
     */
    protected boolean matchBodyPattern(HttpMessage msg, Pattern pattern, StringBuilder sb) { // ZAP: Changed the type of the parameter "sb" to StringBuilder.
        Matcher matcher = pattern.matcher(msg.getResponseBody().toString());
        boolean result = matcher.find();
        if (result) {
            if (sb != null) {
                sb.append(matcher.group());
            }
        }
        return result;
    }

    /**
     * Write a progress update message. Currently this just display in
     * System.out
     *
     * @param msg
     */
    protected void writeProgress(String msg) {
        //System.out.println(msg);
    }

    /**
     * Get the parent HostProcess.
     *
     * @return
     */
    //ZAP: Changed from protected to public access modifier.
    public HostProcess getParent() {
        return parent;
    }

    @Override
    public abstract void notifyPluginCompleted(HostProcess parent);

    /**
     * Replace body by stripping of pattern string. The URLencoded and
     * URLdecoded pattern will also be stripped off. This is mainly used for
     * stripping off a testing string in HTTP response for comparison against
     * the original response. Reference: TestInjectionSQL
     *
     * @param body
     * @param pattern
     * @return
     */
    protected String stripOff(String body, String pattern) {
        String urlEncodePattern = getURLEncode(pattern);
        String urlDecodePattern = getURLDecode(pattern);
        String htmlEncodePattern1 = getHTMLEncode(pattern);
        String htmlEncodePattern2 = getHTMLEncode(urlEncodePattern);
        String htmlEncodePattern3 = getHTMLEncode(urlDecodePattern);
        String result = body.replaceAll("\\Q" + pattern + "\\E", "").replaceAll("\\Q" + urlEncodePattern + "\\E", "").replaceAll("\\Q" + urlDecodePattern + "\\E", "");
        result = result.replaceAll("\\Q" + htmlEncodePattern1 + "\\E", "").replaceAll("\\Q" + htmlEncodePattern2 + "\\E", "").replaceAll("\\Q" + htmlEncodePattern3 + "\\E", "");
        return result;
    }

    public static String getURLEncode(String msg) {
        String result = "";
        try {
            result = URLEncoder.encode(msg, "UTF8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return result;
    }

    public static String getURLDecode(String msg) {
        String result = "";
        try {
            result = URLDecoder.decode(msg, "UTF8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return result;
    }

    public static String getHTMLEncode(String msg) {
        String result = msg.replaceAll("<", "<");
        result = result.replaceAll(">", ">");
        return result;
    }

    protected Kb getKb() {
        return getParent().getKb();
    }

    protected Logger getLog() {
        return log;
    }

    public String getProperty(String key) {
    	return this.getProperty(config, key);
    }

    private String getProperty(Configuration conf, String key) {
        return conf.getString("plugins." + "p" + getId() + "." + key);
    }

    public void setProperty(String key, String value) {
        this.setProperty(config, key, value);
    }

    private void setProperty(Configuration conf, String key, String value) {
        conf.setProperty("plugins." + "p" + getId() + "." + key, value);
    }

    @Override
    public void setConfig(Configuration config) {
        this.config = config;
    }

    @Override
    public Configuration getConfig() {
        return config;
    }

    @Override
    public void saveTo(Configuration conf) {
        setProperty(conf, "enabled", getProperty("enabled"));
        setProperty(conf, "level", getProperty("level"));
        setProperty(conf, "strength", getProperty("strength"));
    }

    @Override
    public void loadFrom(Configuration conf) {
        setProperty("enabled", getProperty(conf, "enabled"));
        setProperty("level", getProperty(conf, "level"));
        setProperty("strength", getProperty(conf, "strength"));
    }

    @Override
    public void cloneInto(Plugin plugin) {
    	if (plugin instanceof AbstractPlugin) {
    		AbstractPlugin ap = (AbstractPlugin) plugin;
    		ap.setEnabled(this.isEnabled());
    		ap.setAlertThreshold(this.getAlertThreshold(true));
    		ap.setAttackStrength(this.getAttackStrength(true));
    		ap.setDefaultAlertThreshold(this.defaultAttackThreshold);
    		ap.setDefaultAttackStrength(this.defaultAttackStrength);
    		ap.setTechSet(this.getTechSet());
    		ap.setStatus(this.getStatus());
    		ap.saveTo(plugin.getConfig());
    	} else {
    		throw new InvalidParameterException("Not an AbstractPlugin");
    	}
    }

    /**
     * Check and create necessary parameter in config file if not already
     * present.
     *
     */
    @Override
    public void createParamIfNotExist() {
        if (getProperty("enabled") == null) {
            setEnabled(getAlertThreshold() != AlertThreshold.OFF);
        }
    }

    // ZAP Added isDepreciated
    @Override
    public boolean isDepreciated() {
        return false;
    }

    /**
     * @since 2.2.0
     */
    @Override
    public int getRisk() {
        return Alert.RISK_MEDIUM;
    }

    @Override
    public int getDelayInMs() {
        return delayInMs;
    }

    @Override
    public void setDelayInMs(int delayInMs) {
        this.delayInMs = delayInMs;
    }

    @Override
    public boolean inScope(Tech tech) {
        return this.techSet == null || this.techSet.includes(tech);
    }

    @Override
    public void setTechSet(TechSet ts) {
        this.techSet = ts;
    }

    /**
     * Returns the technologies enabled for the scan.
     *
     * @return a {@code TechSet} with the technologies enabled for the scan.
     * @see #inScope(Tech)
     * @see #targets(TechSet)
     */
    public TechSet getTechSet() {
    	return this.techSet;
    }

    /**
     * Returns {@code true} by default.
     *
     * @see #getTechSet()
     */
    @Override
    public boolean targets(TechSet technologies) {
        return true;
    }

    @Override
    public Date getTimeStarted() {
        return this.started;
    }

    @Override
    public Date getTimeFinished() {
        return this.finished;
    }

    @Override
    public void setTimeStarted() {
        this.started = new Date();
        this.finished = null;
    }

    @Override
    public void setTimeFinished() {
        this.finished = new Date();
    }

    @Override
    public int getCweId() {
        // Default 'unknown' value
        return 0;
    }

    @Override
    public int getWascId() {
        // Default 'unknown' value
        return 0;
    }

	@Override
	public AddOn.Status getStatus() {
		return status;
	}

	public void setStatus(AddOn.Status status) {
		this.status = status;
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:theme="@style/MTThemeOverlay">

    <ImageView
        android:layout_width="@dimen/action_bar_size_static"
        android:layout_height="@dimen/action_bar_size_static"
        android:padding="8dp"
        android:scaleType="centerInside"
        android:src="@drawable/product_logo" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif"
        android:gravity="center_vertical"
        android:minHeight="@dimen/action_bar_size_static"
        android:paddingStart="8dp"
        android:paddingEnd="16dp"
        android:text="@string/app_name"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textStyle="normal" />

</LinearLayout>


text:
package com.proofpoint.node;

import com.google.inject.Binder;
import com.google.inject.Module;

import static com.google.common.base.MoreObjects.firstNonNull;
import static java.util.Objects.requireNonNull;

public class ApplicationNameModule implements Module
{
    private final String applicationName;

    public ApplicationNameModule(String applicationName)
    {
        this.applicationName = requireNonNull(applicationName, "applicationName is null");
    }

    @Override
    public void configure(Binder binder)
    {
        binder.bindConstant().annotatedWith(ApplicationName.class).to(applicationName);
        binder.bindConstant().annotatedWith(ApplicationVersion.class).to(
                firstNonNull(System.getProperty("launcher.main.version"), "")
        );
        binder.bindConstant().annotatedWith(PlatformVersion.class).to(
                firstNonNull(getClass().getPackage().getImplementationVersion(), "")
        );
    }
}


text:
from config import *
import cv2 as cv
import numpy
from operator import itemgetter
import os
import traceback
import math

HC_EYEPAIRPATH = os.path.join(HCDIR, HC_EYEPAIR_NAME)
HC_LEFTEYEPATH = os.path.join(HCDIR, HC_LEFTEYE_NAME)
HC_RIGHTEYEPATH = os.path.join(HCDIR, HC_RIGHTEYE_NAME)
HC_FACEPATH = os.path.join(HCDIR, HC_FACE_NAME)

class Point:
    def __init__(self, *args):
        if len(args) == 1:
            self.x = args[0][0]
            self.y = args[0][1]
        elif len(args) == 2:
            self.x = args[0]
            self.y = args[1]

    def dist(self, p1):
        """ Returns the pythagorean distance from this point to p1 """
        return pow(pow(self.x - p1.x, 2) + pow(self.y - p1.y, 2), .5)

    def toTuple(self):
        return (self.x, self.y)

    def __str__(self):
        return '({0}, {1})'.format(self.x, self.y)

    def __repr(self):
        return self.__str__()

class Size:
    def __init__(self, *args):
        if len(args) == 1:
            self.w = len(args[0][0])
            self.h = len(args[0])
        elif len(args) == 2:
            self.w = args[0]
            self.h = args[1]

    def toTuple(self):
        return (self.w, self.h)

    def __str__(self):
        return '({0}, {1})'.format(self.w, self.h)

    def __repr(self):
        return self.__str__()

class Rect:
    def __init__(self, array):
        self.x = array[0]
        self.y = array[1]
        self.w = array[2]
        self.h = array[3]
        self.a = self.w * self.h
        self.center = Point(self.x + self.w/2.0, self.y + self.h/2.0)

    def contains(self, p):
        return self.x <= p.x <= self.x + self.w and \
               self.y <= p.y <= self.y + self.h

    def vsplit(self):
        lRect = Rect((self.x, self.y, self.w/2.0, self.h))
        rRect = Rect((self.center.x, self.y, self.w/2.0, self.h))
        return lRect, rRect

    def __str__(self):
        return '({0}, {1}), ({2}, {3}), w = {4}, h = {5}, a = {6}'.format(
            self.x, self.y, self.x + self.w, self.y + self.h, self.w, self.h, self.a
        )

    def __repr(self):
        return self.__str__()

class FaceImage:
    """ Represents an image with a face in it, and all the scaling/cropping that goes along with it. """

    def __init__(self, imagepath):
        self.filename = os.path.basename(imagepath)
        self.image = cv.imread(imagepath)
        self.origSize = Size(self.image)
        self.imagepath = imagepath
        self._finalImg = None
        self.log = ''

    def cropToFace(self):
        """ Finds the face position of the OpenCV image, scales so that the face is the 'ideal'
        size, then crops so that the face is in the center """
        self._log('Starting ' + self.imagepath)
        eyepair = None
        lEye = rEye = None

        if not FORCE_FULL_FACE:
            eyepair = self._getEyePair()
            lEye, rEye = self._getEyes(eyepair)

        # Find the middle of the eyes
        if lEye is not None and rEye is not None:
            mid = Point(rEye.center.x/2.0 + lEye.center.x/2.0,
                        rEye.center.y/2.0 + lEye.center.y/2.0)
            eyewidth = rEye.center.dist(lEye.center)
            eyeAngle = math.degrees(
                math.atan((rEye.center.y - lEye.center.y)/(rEye.center.x - lEye.center.x)))
        else:
            eyeAngle = 0
            if eyepair is not None:
                self._log('No individual eyes found, falling back on eyepair')
                mid = eyepair.center
                eyewidth = eyepair.w*EYEPAIR_WIDTH_TO_EYE_WIDTH
            else:
                self._log('No eyes found, falling back on face')
                face = self._getFace()
                mid = Point(face.center.x, face.h*FACE_HEIGHT_TO_EYE_MID + face.y)
                eyewidth = face.w*FACE_WIDTH_TO_EYE_WIDTH
                if MARKUSED or MARKALL:
                    self._markPoint(mid, MIDPOINT_COLOR)

        self._log('', 1)
        self._log('Eye mid at: ' + str(mid) + ', should be: ' + str(Point(MID_X_TARGET, MID_Y_TARGET)), 1)

        if NOTRANSFORM:
            self._finalImg = self.image
            return

        # Calculate scaling params
        scaleF = EYEW_TARGET/eyewidth
        scSize = Size(int(self.origSize.w*scaleF), int(self.origSize.h*scaleF))
        scMid = Point(mid.x*scaleF, mid.y*scaleF)
        self._log('Eye width: ' + str(eyewidth) + ', should be: ' + str(EYEW_TARGET), 1)
        self._log('Scale factor: ' + str(scaleF), 1)
        self._log('Pre-crop scaled size: ' + str(scSize), 1)

        # Scale image
        scImg = cv.resize(self.image, (scSize.w, scSize.h), interpolation=cv.INTER_LANCZOS4)

        # Determine translation. offset: (positive leaves a top/left border, negative doesn't)
        self._log('Scaled midpoint: ' + str(scMid), 1)
        self._log('Target midpoint: ' + str(Point(MID_X_TARGET, MID_Y_TARGET)), 1)
        offset = Point(int(MID_X_TARGET - scMid.x), int(MID_Y_TARGET - scMid.y))
        self._log("offset: " + str(offset), 1)
        translatedScaledImage = crop(scImg, offset, Size(WIDTH_TARGET, HEIGHT_TARGET))

        # Rotate
        if eyeAngle == 0:
            self._finalImg = translatedScaledImage
        else:
            self._log('Rotating to: ' + str(eyeAngle))
            rotMatrix = cv.getRotationMatrix2D((MID_X_TARGET, MID_Y_TARGET), eyeAngle, 1)
            self._finalImg = cv.warpAffine(translatedScaledImage, rotMatrix, (WIDTH_TARGET, HEIGHT_TARGET))

    def save(self, outputpath):
        """ Saves the final image to the specified output path. Creates the path if necessary """
        self._log('Saving as ' + outputpath)
        if self._finalImg == None:
            raise Exception('Final image is uninitialized- run cropToFace first')

        outdir = os.path.dirname(outputpath)
        try:
            if not os.path.exists(outdir):
                self._log('Creating directory ' + outdir)
                os.makedirs(outdir)
        except:
            print(outdir)

        cv.imwrite(outputpath, self._finalImg)

    def _getEyePair(self):
        cascade = cv.CascadeClassifier(HC_EYEPAIRPATH)
        minSize = (int(EYEPAIR_MIN_SIZE[0]*self.origSize.w),
                   int(EYEPAIR_MIN_SIZE[1]*self.origSize.h))
        maxSize = (int(EYEPAIR_MAX_SIZE[0]*self.origSize.w),
                   int(EYEPAIR_MAX_SIZE[1]*self.origSize.h))
        eyepairs = toRects(cascade.detectMultiScale(self.image, minSize=minSize, maxSize=maxSize))

        if not eyepairs:
            return None

        for eyepair in eyepairs:
            self._log('Eyepair found: ' + str(eyepair), 1)
            if MARKALL:
                self._markRect(eyepair, EYEPAIR_COLOR)

        # Find the largest eyepair
        largest = max(eyepairs, key=lambda e: e.a)

        if largest.w / largest.h < EYEPAIR_RATIO:
            return None
        else:
            if MARKUSED:
                self._markRect(largest, EYEPAIR_COLOR)
            return largest

    def _getEyes(self, eyepair):
        lEyeCascade = cv.CascadeClassifier(HC_LEFTEYEPATH)
        rEyeCascade = cv.CascadeClassifier(HC_RIGHTEYEPATH)

        lEyes = toRects(lEyeCascade.detectMultiScale(self.image))
        rEyes = toRects(rEyeCascade.detectMultiScale(self.image))

        # mark eyes if needed
        for eye in lEyes:
            self._log('Left eye found: ' + str(eye), 1)
            if MARKALL:
                self._markRect(eye, LEFT_EYE_COLOR)

        for eye in rEyes:
            self._log('Right eye found: ' + str(eye), 1)
            if MARKALL:
                self._markRect(eye, RIGHT_EYE_COLOR)

        if len(lEyes) == 0 or len(rEyes) == 0:
            self._log("Didn't find both left and right eyes")
            return (None, None)

        # Filter eye results by having centers in the correct half of the eyepair
        if eyepair:
            rightEyepair, leftEyepair = eyepair.vsplit()
            self._log(str(leftEyepair))
            self._log(str(rightEyepair))
            lEyes = filter(lambda e: leftEyepair.contains(e.center), lEyes)
            rEyes = filter(lambda e: rightEyepair.contains(e.center), rEyes)

            if (len(lEyes) == 0 or len(rEyes) == 0):
                self._log("Didn't find eyes in the correct half of the eyepair")
                return (None, None)

        lEye = max(lEyes, key=lambda e: e.a)
        rEye = max(rEyes, key=lambda e: e.a)

        # Throw out the eyes if they are too close
        eyeDist = lEye.center.dist(rEye.center)
        minEyeDist = EYE_MIN_DISTANCE*self.origSize.w
        if eyeDist < minEyeDist:
            self._log('Eyes too close, rejected - %d, should be %d' % (eyeDist, minEyeDist))
            return (None, None)

        # Throw out the eyes if they differ in size too much
        eyeSizeDiff = max(lEye.a, rEye.a)/min(lEye.a, rEye.a)
        if eyeSizeDiff >= EYE_MAX_SIZE_DIFFERENCE:
            self._log('Eyes too different in size, rejected - %d vs %d' % (lEye.a, rEye.a))
            return (None, None)

        if MARKUSED:
            self._markRect(lEye, LEFT_EYE_COLOR)
            self._markRect(rEye, RIGHT_EYE_COLOR)

        return (lEye, rEye)

    def _getFace(self):
        """ Returns coordinates of the face in this image """
        cascade = cv.CascadeClassifier(HC_FACEPATH)
        faces = toRects(cascade.detectMultiScale(self.image))

        for face in faces:
            self._log('Face found: ' + str(face), 1)
            if MARKALL:
                self._markRect(face, FACE_COLOR)

        if len(faces) > 0:
            bestFace = faces[0]
            for face in faces:
                bestFace = self._bestFace(bestFace, face)

            if MARKUSED:
                self._markRect(bestFace, FACE_COLOR)

            return bestFace
        else:
            return None

    def _bestFace(self, f1, f2):
        # if the sizes of these faces are within .5% of each other, take the
        # one nearest midpoint
        p = .005
        deltaP = float(abs(f1.a - f2.a))/max(f1.a, f2.a)
        imageMidpoint = Point(self.origSize.w*MID_X_TARGET_RATIO, self.origSize.h*MID_Y_TARGET_RATIO)
        if deltaP < p:
            return f1 if f1.center.dist(imageMidpoint) < f2.center.dist(imageMidpoint) else f2
        else:
            return max(f1, f2, key=lambda f: f.a)

    def _markRect(self, rect, color):
        """ Marks the location of the given rect onto the image """
        cv.rectangle(self.image, (rect.x, rect.y), (rect.x + rect.w, rect.y + rect.h), color)
        self._markPoint(rect.center, MIDPOINT_COLOR)

    def _markPoint(self, p, color):
        pointSize = 10
        cv.rectangle(
            self.image,
            (int(p.x) - pointSize/2, int(p.y) - pointSize/2),
            (int(p.x) + pointSize/2, int(p.y) + pointSize/2),
            color,
            cv.cv.CV_FILLED)

    def _log(self, msg, level=0):
        if DEBUG:
            self.log += '  '*level + str(msg) + '\n'

def toRects(cvResults):
    return [Rect(result) for result in cvResults]

def crop(image, offset, size):
    imageSize = Size(image)

    # If there will be a border, use CopyMakeBorder.
    # Setting ROI, no border is created and resulting image is smaller
    if offset.x > 0 or \
       offset.y > 0 or \
       offset.x + imageSize.w < size.w or \
       offset.y + imageSize.h < size.h:

        # offset may have negative values, if there will be a right/bottom border
        offsTop = offset.y
        offsBottom = -(offset.y + imageSize.h - size.h)
        offsLeft = offset.x
        offsRight = -(offset.x + imageSize.w - size.w)

        image = image[max(0, -offset.y):min(-offset.y + size.h, imageSize.h), max(0, -offset.x):min(-offset.x + size.w, imageSize.w)]
        offsTop = max(0, offsTop)
        offsBottom = max(0, offsBottom)
        offsLeft = max(0, offsLeft)
        offsRight = max(0, offsRight)

        finalImg = cv.copyMakeBorder(image, offsTop, offsBottom, offsLeft, offsRight, GAP_BORDER)

        return finalImg

    else:
        return image[-offset.y:-offset.y + size.h, -offset.x:-offset.x + size.w]

def runFaceImage(imagepath, outpath):
    # exceptions just disappear from multiprocessing.Pool, for some reason
    try:
        print('beginning FaceImage run for image path: ' + imagepath)
        fi = FaceImage(imagepath)
        fi.cropToFace()
        fi.save(outpath)
        print(fi.log)

    except Exception as e:
        # print all at once to keep imagepath and stack trace from getting separated by multithreading
        msg = '*** Incomplete: ' + imagepath + ' ***\n'
        msg += traceback.format_exc()
        if fi != None:
            print(fi.log)
        print(msg)


text:
module GooglePlaces
    require 'rest_client'

    def google_places(query, lat, lng)
        articles = ['the', 'a', 'and', 'an', 'at', 'of', 'or', 'are', 'in', 'by', 'restaurant', 'cafe']
        query = query.gsub(/[']/i, '')
        query = query.gsub(/[^0-9a-z ]/i, ' ')
        query = (query.downcase.split - articles).join(' ')
        api_key = YAML.load_file('config/config.yml')['google_places_api_key']
        raw_url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?name=%s&location=%s,%s&radius=20000&types=restaurant|bakery|bar|cafe|food|meal_takeaway|meal_delivery|night_club&sensor=false&key=%s" % [CGI::escape(query), lat, lng, api_key]
        encoded_url = URI.encode(raw_url)  # raw_url is invalid due to pipes
        data = JSON.parse(RestClient.get encoded_url, :accept => :json).with_indifferent_access
        results = []
        data[:results].each do |place|
            result = {}
            result[:formatted_address] = place[:vicinity] if place[:vicinity]
            result[:lng] = place[:geometry][:location][:lng] if place[:geometry][:location][:lng]
            result[:lat] = place[:geometry][:location][:lat] if place[:geometry][:location][:lat]
            result[:name] = place[:name] if place[:name]
            result[:price] = place[:price_level] if place[:price_level]
            result[:reference] = place[:reference] if place[:reference]
            result[:google_id] = place[:id] if place[:id]
            results.push result.with_indifferent_access
        end
        results
    end

    def google_places_details(reference)
        api_key = YAML.load_file('config/config.yml')['google_places_api_key']
        url = "https://maps.googleapis.com/maps/api/place/details/json?reference=%s&sensor=false&key=%s" % [reference, api_key]
        data = JSON.parse(RestClient.get url, :accept => :json).with_indifferent_access
        location = data[:result]
        result = {}
        result[:formatted_address] = location[:formatted_address] if location[:formatted_address]
        result[:phone] = location[:formatted_phone_number] if location[:formatted_phone_number]
        result[:website] = location[:website] if location[:website]
        location[:address_components].each do |component|
            types = component[:types]
            key = case
            when types.include?('street_number')
                :street_number
            when types.include?('route')
                :street
            when types.include?('sublocality')
                :neighborhood
            when types.include?('locality')
                :city
            when types.include?('administrative_area_level_1')
                :state
            when types.include?('country')
                :country
            when types.include?('postal_code')
                :zip_code
            end
            result[key] = component[:short_name] if key
        end

        result[:hours] = []
        unless location[:opening_hours].nil?
            if location[:opening_hours][:periods]
                location[:opening_hours][:periods].each do |period|
                    hours = {}

                    unless period[:open].nil?
                        open_day = period[:open][:day]
                        open_time = period[:open][:time]
                        @open_in_minutes = to_minutes(open_day, open_time)
                        hours[:open_in_minutes] = @open_in_minutes

                        hours[:open_day] = open_day
                        hours[:open_time] = open_time
                    end

                    unless period[:close].nil?
                        close_day = period[:close][:day]
                        close_time = period[:close][:time]
                        close_in_minutes = to_minutes(close_day, close_time)
                        close_in_minutes += 60 * 24 * 7 if @open_in_minutes && close_in_minutes < @open_in_minutes
                        hours[:close_in_minutes] = close_in_minutes

                        hours[:close_day] = close_day
                        hours[:close_time] = close_time
                    end
                    result[:hours].push(hours)
                end
            end
        end
        result
    end

    def to_minutes(day, time)
        day = day.to_i
        time = time.to_i
        day_in_minutes = day * 60 * 24
        time_in_minutes = time / 100 * 60 + time % 100
        day_in_minutes + time_in_minutes
    end
end


text:
module Minitest
  module Parallel #:nodoc:

    ##
    # The engine used to run multiple tests in parallel.

    class Executor

      ##
      # The size of the pool of workers.

      attr_reader :size

      ##
      # Create a parallel test executor of with +size+ workers.

      def initialize size
        @size  = size
        @queue = Queue.new
        @pool  = nil
      end

      ##
      # Start the executor

      def start
        @pool  = size.times.map {
          Thread.new(@queue) do |queue|
            Thread.current.abort_on_exception = true
            while (job = queue.pop)
              klass, method, reporter = job
              reporter.synchronize { reporter.prerecord klass, method }
              result = Minitest.run_one_method klass, method
              reporter.synchronize { reporter.record result }
            end
          end
        }
      end

      ##
      # Add a job to the queue

      def << work; @queue << work; end

      ##
      # Shuts down the pool of workers by signalling them to quit and
      # waiting for them all to finish what they're currently working
      # on.

      def shutdown
        size.times { @queue << nil }
        @pool.each(&:join)
      end
    end

    module Test
      def _synchronize; Minitest::Test.io_lock.synchronize { yield }; end # :nodoc:

      module ClassMethods # :nodoc:
        def run_one_method klass, method_name, reporter
          Minitest.parallel_executor << [klass, method_name, reporter]
        end

        def test_order
          :parallel
        end
      end
    end
  end
end


text:
function(bitbucket_default_branch user repo)
  set(api_uri "https://bitbucket.org/api/1.0")
  set(query_uri "${api_uri}/repositories/${user}/${repo}/main-branch" )

  http_get("${query_uri}" --json --silent-fail)
  ans(response)

  if(NOT response)
    return()
  endif()

  map_tryget(${response} name)
  ans(res)
  return_ref(res)

endfunction()


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Collections.Specialized;
using System.IO;

namespace Ivony.Web
{

  /// <summary>
  /// 定义响应内容,用于缓存
  /// </summary>
  [Serializable]
  public class RawResponse : IClientCacheableResponse, ICachedResponse
  {

    /// <summary>
    /// 创建 RawResponse 对象
    /// </summary>
    public RawResponse()
    {
      Headers = new NameValueCollection();

      StatusCode = 200;
      Status = "OK";

      HeaderEncoding = Encoding.UTF8;
      ContentEncoding = Encoding.UTF8;
    }

    /// <summary>
    /// HTTP 响应状态码,如 200
    /// </summary>
    public int StatusCode
    {
      get;
      set;
    }

    /// <summary>
    /// HTTP 响应状态说明,如 OK
    /// </summary>
    public string Status
    {
      get;
      set;
    }

    /// <summary>
    /// HTTP 响应头集合
    /// </summary>
    public NameValueCollection Headers
    {
      get;
      set;
    }

    /// <summary>
    /// HTTP 响应内容
    /// </summary>
    public string Content
    {
      get;
      set;
    }

    /// <summary>
    /// 响应头的编码
    /// </summary>
    public Encoding HeaderEncoding
    {
      get;
      set;
    }

    /// <summary>
    /// 响应内容的编码
    /// </summary>
    public Encoding ContentEncoding
    {
      get;
      set;
    }

    /// <summary>
    /// 将响应直接输出
    /// </summary>
    /// <param name="response">HttpResponse 对象,用于输出响应</param>
    public virtual void Apply( HttpResponseBase response )
    {
      response.Clear();

      response.HeaderEncoding = HeaderEncoding;

      foreach ( var key in Headers.AllKeys )
      {
        foreach ( var value in Headers.GetValues( key ) )
        {
          response.AppendHeader( key, value );
        }
      }

      response.ContentEncoding = ContentEncoding;
      response.Write( Content );

    }

    /// <summary>
    /// 将响应写入响应输出流
    /// </summary>
    /// <param name="stream">输出流</param>
    public void WriteTo( Stream stream )
    {
      var headerWriter = new StreamWriter( stream, HeaderEncoding );

      headerWriter.NewLine = "\r\n";

      foreach ( var key in Headers.AllKeys )
        headerWriter.WriteLine( "{0}: {1}", key, Headers.Get( key ) );

      headerWriter.WriteLine();

      var contentWriter = new StreamWriter( stream, ContentEncoding );
      contentWriter.Write( Content );
    }

    /// <summary>
    /// 创建响应的 ETag 标识
    /// </summary>
    /// <returns>ETag 标识</returns>
    public string CreateETag()
    {

      if ( string.IsNullOrEmpty( Content ) || StatusCode != 200 )
        return null;

      return HttpServerUtility.UrlTokenEncode( CacheHelper.ComputeHash( ContentEncoding.ToString() + "\n" + Content ) );
    }
  }
}


text:
import { Class, Field } from 'meteor/jagi:astronomy';

Tinytest.add('Core - Extend', function(test) {
  reset();

  const Extended = Class.create({
    name: 'Extended',
    fields: {
      originalField: {
        type: String
      }
    },
    helpers: {
      originalHelper() {}
    },
    events: {
      afterInit() {}
    }
  });

  Extended.extend({
    fields: {
      extendField: {
        type: String
      }
    },
    helpers: {
      extendHelper() {}
    },
    events: {
      afterInit() {}
    }
  });

  // Fields.
  test.instanceOf(Extended.getField('originalField'), Field,
    'Class should contain original fields'
  );
  test.instanceOf(Extended.getField('extendField'), Field,
    'Class should contain extended fields'
  );

  // Helpers.
  test.instanceOf(Extended.getHelper('originalHelper'), Function,
    'Class should contain original methods'
  );
  test.instanceOf(Extended.getHelper('extendHelper'), Function,
    'Class should contain extended methods'
  );

  // Events.
  test.equal(Extended.getEvents('afterInit').length, 2,
    'Class should contain two "afterInit" event handlers'
  );
});


text:
package com.lookfirst.wepay.api;

import lombok.Data;

import java.io.Serializable;

/**
 * https://stage.wepay.com/developer/reference/account
 *
 * @author Jon Scott Stevens
 * @author Jeff Schnitzer
 */
@Data
public class AccountStatus implements Serializable {
	private static final long serialVersionUID = 1L;

	/** The currency of the above amounts. For now this will always be USD. */
	private String currency;
	private String incomingPaymentsStatus;
	private String outgoingPaymentsStatus;
}


text:
<!DOCTYPE html>

    <title>Matt's Dev Bootcamp Blog</title>
    <meta charset="UTF-8">
    <link href="../stylesheets/default.css" rel="stylesheet" type="text/css">
    <link href="../stylesheets/blog-stylesheet.css" rel="stylesheet" type="text/css">
    <link href="../stylesheets/prism.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Roboto:300,500,700" rel="stylesheet" type="text/css">

Matt's Dev Bootcamp Blog

      Back to Homepage / Projects / Email Me

        < previous
        /
        next >

        Analyzing Conflict

        Uploaded June 22, 2015

          Conflict is a challenging but inevitable part of life. It's something that has to be managed and responded to appropriately, and the ability to do so for most of us has to be acquired. The only way to achieve that is to experience conflict and analyze it. Being in a relationship has given me many opportunities to do that, and I've learned much about myself and the nature of conflict in the process. I'm glad to say that not a whole lot came to mind when I tried to remember past conflicts. At least in recent years, I think I've eventually resolved most of them and let them be forgotten.

          Eventually I did recall a conflict, one that occurred last week. My girlfriend, Ivy, and I were at the wedding reception of a friend of mine from high school. Unfortunately, the wedding was on a Sunday and Ivy has to get up fairly early for work during the week. After a few hours of eating and dancing, we were both tired, but I couldn't decide if I wanted to stay or leave. I could tell that Ivy wanted to go home, but she insisted that the choice was mine, and I remained indecisive. This was incredibly frustrating for her and turned what could have been an innocuous situation into a tense one.

          This conflict was fueled by fatigue on both our parts, but the main problem, which is now obvious to me, is that I wasn't communicating. I recognize that this is a pattern of behavior on my part that I would like to change. Sometimes, I respond to conflict by shutting down rather than communicating my side of the story and trying to bridge the gap. Eventually, I said we could leave soon, apologized, and the conflict was mostly resolved. It also helped that tacos were served as a late-night snack. This confirms what I suspected about our relationship: to mitigate conflict, I need to make sure we're communicating and eating enough.

        Hi, I'm Matt. I'm studying full-stack web development at Dev Bootcamp in Chicago. I'll be blogging about my DBC experience here.

      Previous Posts

Week 8 Technical Blog

Week 7 Cultural Blog

Week 7 Technical Blog

Week 6 Cultural Blog

Week 6 Technical Blog

Week 5 Technical Blog

Week 4 Technical Blog

Week 4 Cultural Blog

Week 3 Cultural Blog

Week 3 Technical Blog

Week 2 Technical Blog

Week 1 Cultural Blog

Week 1 Technical Blog

        Tweets by @zebogen


text:
<!DOCTYPE html>

<meta http-equiv="Content-type" content="text/html; charset=utf-8">

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas volutpat. Duis purus lectus, hendrerit vitae, blandit ac, tristique quis, neque. Cras a nisl. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In consectetuer lorem sit amet quam facilisis mollis. Etiam dolor. Donec elementum leo in ligula. Duis lacus diam, sodales vitae, rutrum a, feugiat non, tortor. Maecenas cursus lobortis diam. Mauris in pede eu purus ultricies vehicula. עברית


text:
package net.dv8tion.jda.core.handle;

import net.dv8tion.jda.core.entities.EntityBuilder;
import net.dv8tion.jda.core.entities.impl.GuildImpl;
import net.dv8tion.jda.core.entities.impl.JDAImpl;
import org.json.JSONArray;
import org.json.JSONObject;

public class GuildSyncHandler extends SocketHandler
{
    public GuildSyncHandler(JDAImpl api)
    {
        super(api);
    }

    @Override
    protected Long handleInternally(JSONObject content)
    {
        final long guildId = content.getLong("id");
        if (!api.getGuildMap().containsKey(guildId))
        {
            JDAImpl.LOG.fatal("Received a GUILD_SYNC for a Guild that does not yet exist in JDA's guild cache. This is a BAD ERROR FOR CLIENTS!");
            return null;
        }

        GuildImpl guild = (GuildImpl) api.getGuildMap().get(guildId);
        JSONArray members = content.getJSONArray("members");
        JSONArray presences = content.getJSONArray("presences");
        api.getEntityBuilder().handleGuildSync(guild, members, presences);

        return null;
    }
}


text:
<?php
/**
 * This file is part of the Ghostscript package
 *
 * @author Daniel Schröder <daniel.schroeder@gravitymedia.de>
 */

namespace GravityMedia\Ghostscript\Device\DistillerParameters;

use GravityMedia\Ghostscript\Enum\ImageDownsampleType;
use GravityMedia\Ghostscript\Enum\MonoImageFilter;
use GravityMedia\Ghostscript\Enum\PdfSettings;

/**
 * The monochrome image compression distiller parameters trait.
 *
 * @package GravityMedia\Ghostscript\Device\DistillerParameters
 *
 * @link    http://ghostscript.com/doc/current/Ps2pdf.htm
 */
trait MonoImageCompressionTrait
{
    /**
     * Get argument value
     *
     * @param string $name
     *
     * @return null|string
     */
    abstract protected function getArgumentValue($name);

    /**
     * Set argument
     *
     * @param string $argument
     *
     * @return $this
     */
    abstract protected function setArgument($argument);

    /**
     * Get PDF settings
     *
     * @return string
     */
    abstract public function getPdfSettings();

    /**
     * Whether to anti alias monochrome images
     *
     * @return bool
     */
    public function isAntiAliasMonoImages()
    {
        $value = $this->getArgumentValue('-dAntiAliasMonoImages');
        if (null === $value) {
            return false;
        }

        return filter_var($value, FILTER_VALIDATE_BOOLEAN);
    }

    /**
     * Set anti alias monochrome images flag
     *
     * @param bool $antiAliasMonoImages
     *
     * @return $this
     */
    public function setAntiAliasMonoImages($antiAliasMonoImages)
    {
        $this->setArgument(sprintf('-dAntiAliasMonoImages=%s', $antiAliasMonoImages ? 'true' : 'false'));

        return $this;
    }

    /**
     * Whether to downsample monochrome images
     *
     * @return bool
     */
    public function isDownsampleMonoImages()
    {
        $value = $this->getArgumentValue('-dDownsampleMonoImages');
        if (null === $value) {
            switch ($this->getPdfSettings()) {
                case PdfSettings::SCREEN:
                case PdfSettings::EBOOK:
                    return true;
                default:
                    return false;
            }
        }

        return filter_var($value, FILTER_VALIDATE_BOOLEAN);
    }

    /**
     * Set downsample monochrome images flag
     *
     * @param bool $downsampleMonoImages
     *
     * @return $this
     */
    public function setDownsampleMonoImages($downsampleMonoImages)
    {
        $this->setArgument(sprintf('-dDownsampleMonoImages=%s', $downsampleMonoImages ? 'true' : 'false'));

        return $this;
    }

    /**
     * Whether to encode monochrome images
     *
     * @return bool
     */
    public function isEncodeMonoImages()
    {
        $value = $this->getArgumentValue('-dEncodeMonoImages');
        if (null === $value) {
            return true;
        }

        return filter_var($value, FILTER_VALIDATE_BOOLEAN);
    }

    /**
     * Set encode monochrome images flag
     *
     * @param bool $encodeMonoImages
     *
     * @return $this
     */
    public function setEncodeMonoImages($encodeMonoImages)
    {
        $this->setArgument(sprintf('-dEncodeMonoImages=%s', $encodeMonoImages ? 'true' : 'false'));

        return $this;
    }

    /**
     * Get monochrome image depth
     *
     * @return int
     */
    public function getMonoImageDepth()
    {
        $value = $this->getArgumentValue('-dMonoImageDepth');
        if (null === $value) {
            return -1;
        }

        return intval($value);
    }

    /**
     * Set monochrome image depth
     *
     * @param int $monoImageDepth
     *
     * @return $this
     */
    public function setMonoImageDepth($monoImageDepth)
    {
        $this->setArgument(sprintf('-dMonoImageDepth=%s', $monoImageDepth));

        return $this;
    }

    /**
     * Get monochrome image downsample threshold
     *
     * @return float
     */
    public function getMonoImageDownsampleThreshold()
    {
        $value = $this->getArgumentValue('-dMonoImageDownsampleThreshold');
        if (null === $value) {
            return 1.5;
        }

        return floatval($value);
    }

    /**
     * Set monochrome image downsample threshold
     *
     * @param float $monoImageDownsampleThreshold
     *
     * @return $this
     */
    public function setMonoImageDownsampleThreshold($monoImageDownsampleThreshold)
    {
        $this->setArgument(sprintf('-dMonoImageDownsampleThreshold=%s', $monoImageDownsampleThreshold));

        return $this;
    }

    /**
     * Get monochrome image downsample type
     *
     * @return string
     */
    public function getMonoImageDownsampleType()
    {
        $value = $this->getArgumentValue('-dMonoImageDownsampleType');
        if (null === $value) {
            switch ($this->getPdfSettings()) {
                case PdfSettings::PREPRESS:
                    return ImageDownsampleType::BICUBIC;
                default:
                    return ImageDownsampleType::SUBSAMPLE;
            }
        }

        return ltrim($value, '/');
    }

    /**
     * Set monochrome image downsample type
     *
     * @param string $monoImageDownsampleType
     *
     * @throws \InvalidArgumentException
     *
     * @return $this
     */
    public function setMonoImageDownsampleType($monoImageDownsampleType)
    {
        $monoImageDownsampleType = ltrim($monoImageDownsampleType, '/');
        if (!in_array($monoImageDownsampleType, ImageDownsampleType::values())) {
            throw new \InvalidArgumentException('Invalid monochrome image downsample type argument');
        }

        $this->setArgument(sprintf('-dMonoImageDownsampleType=/%s', $monoImageDownsampleType));

        return $this;
    }

    /**
     * Get monochrome image filter
     *
     * @return string
     */
    public function getMonoImageFilter()
    {
        $value = $this->getArgumentValue('-dMonoImageFilter');
        if (null === $value) {
            return MonoImageFilter::CCITT_FAX_ENCODE;
        }

        return ltrim($value, '/');
    }

    /**
     * Set monochrome image filter
     *
     * @param string $monoImageFilter
     *
     * @throws \InvalidArgumentException
     *
     * @return $this
     */
    public function setMonoImageFilter($monoImageFilter)
    {
        $monoImageFilter = ltrim($monoImageFilter, '/');
        if (!in_array($monoImageFilter, MonoImageFilter::values())) {
            throw new \InvalidArgumentException('Invalid monochrome image filter argument');
        }

        $this->setArgument(sprintf('-dMonoImageFilter=/%s', $monoImageFilter));

        return $this;
    }

    /**
     * Get monochrome image resolution
     *
     * @return int
     */
    public function getMonoImageResolution()
    {
        $value = $this->getArgumentValue('-dMonoImageResolution');
        if (null === $value) {
            switch ($this->getPdfSettings()) {
                case PdfSettings::PRINTER:
                case PdfSettings::PREPRESS:
                    return 1200;
                default:
                    return 300;
            }
        }

        return intval($value);
    }

    /**
     * Set monochrome image resolution
     *
     * @param int $monoImageResolution
     *
     * @return $this
     */
    public function setMonoImageResolution($monoImageResolution)
    {
        $this->setArgument(sprintf('-dMonoImageResolution=%s', $monoImageResolution));

        return $this;
    }
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<example>
    <description>
        <![CDATA[This example shows master-details concept.]]>
    </description>
    <zip-folders>
        <folder url="../../../../Code/Northwind/"></folder>
    </zip-folders>
</example>


text:
using System;

namespace MeepMeep.Extensions
{
    public static class StringExtensions
    {
        public static string RemoveNewLines(this string value)
        {
            return value == null ? null : value.Replace(Environment.NewLine, string.Empty);
        }
    }
}


text:
<!DOCTYPE html>
<html>
<head>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">

	<title>angular2-notifier (Demo)</title>

	<!-- Polyfills and libraries -->
	<script src="/node_modules/core-js/client/shim.min.js" defer></script>
	<script src="/node_modules/zone.js/dist/zone.js" defer></script>
	<script src="/node_modules/reflect-metadata/Reflect.js" defer></script>
	<script src="/node_modules/systemjs/dist/system.src.js" defer></script>

	<!-- SystemJS module loader -->
	<script src="/demo/systemjs.config.js" defer></script>

	<!-- Get all styles -->
	<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:400,700">
	<link rel="stylesheet" href="./style.css">
	<link rel="stylesheet" href="./../styles/style.css">

</head>
<body>

	<x-app>
		Loading demo (this might take some seconds) ...
	</x-app>

</body>
</html>


text:
@interface SBLockScreenNotificationSystemBannerItem : SBLockScreenNotificationBannerItem
{
}

- (id)_systemListItem;
- (id)lockScreenActionContext;
- (id)iconImage;
- (id)message;
- (id)title;

@end


text:
import LoadingBarContainer, { LoadingBar } from './loading_bar'
import loadingBarMiddleware from './loading_bar_middleware'
import {
  hideLoading,
  loadingBarReducer,
  resetLoading,
  showLoading,
} from './loading_bar_ducks'
import ImmutableLoadingBar from './immutable'

export {
  hideLoading,
  ImmutableLoadingBar,
  LoadingBar,
  loadingBarMiddleware,
  loadingBarReducer,
  resetLoading,
  showLoading,
}
export default LoadingBarContainer


text:
package org.wangzw.plugin.cppstyle;

import java.io.IOException;
import java.io.OutputStream;

import org.eclipse.cdt.core.IConsoleParser;

/**
 * Intercepts an output to console and forwards it to console parsers for
 * processing
 */
public class ConsoleOutputSniffer {

	/**
	 * Private class to sniff the output stream for this sniffer.
	 */
	private class ConsoleOutputStream extends OutputStream {
		// Stream's private buffer for the stream's read contents.
		private StringBuffer currentLine = new StringBuffer();
		private OutputStream outputStream = null;

		public ConsoleOutputStream(OutputStream outputStream) {
			this.outputStream = outputStream;
		}

		@Override
		public void write(int b) throws IOException {
			currentLine.append((char) b);
			checkLine(false);

			// Continue writing the bytes to the console's output.
			if (outputStream != null) {
				outputStream.write(b);
			}
		}

		@Override
		public void write(byte[] b, int off, int len) throws IOException {
			if (b == null) {
				throw new NullPointerException();
			} else if (off != 0 || (len < 0) || (len > b.length)) {
				throw new IndexOutOfBoundsException();
			} else if (len == 0) {
				return;
			}
			currentLine.append(new String(b, 0, len));
			checkLine(false);

			// Continue writing the bytes to the console's output.
			if (outputStream != null)
				outputStream.write(b, off, len);
		}

		@Override
		public void close() throws IOException {
			checkLine(true);
			closeConsoleOutputStream();
		}

		@Override
		public void flush() throws IOException {
			if (outputStream != null) {
				outputStream.flush();
			}
		}

		/**
		 * Checks to see if the already read input constitutes a complete line
		 * (e.g. does the sniffing). If so, then send it to processLine.
		 *
		 * @param flush
		 */
		private void checkLine(boolean flush) {
			if (currentLine.length() == 0) {
				return;
			}

			String buffer = currentLine.toString();
			int i = 0;
			while ((i = buffer.indexOf('\n')) != -1) {
				int eol = i;
				if (i > 0 && buffer.charAt(i - 1) == '\r') {
					// also get rid of trailing \r in case of Windows line
					// delimiter "\r\n"
					eol = i - 1;
				}
				String line = buffer.substring(0, eol);
				processLine(line);

				buffer = buffer.substring(i + 1); // skip the \n and advance
			}
			currentLine.setLength(0);
			if (flush) {
				if (buffer.length() > 0) {
					processLine(buffer);
				}
			} else {
				currentLine.append(buffer);
			}
		}

	} // end ConsoleOutputStream class

	private int nOpens = 0;
	private OutputStream consoleOutputStream;
	private OutputStream consoleErrorStream;
	private IConsoleParser[] parsers;

	public ConsoleOutputSniffer(IConsoleParser[] parsers) {
		this.parsers = parsers;
	}

	public ConsoleOutputSniffer(OutputStream outputStream, OutputStream errorStream, IConsoleParser[] parsers) {
		this(parsers);
		this.consoleOutputStream = outputStream;
		this.consoleErrorStream = errorStream;
	}

	/**
	 * Returns an output stream that will be sniffed. This stream should be
	 * hooked up so the command output stream goes into here.
	 */
	public OutputStream getOutputStream() {
		incNOpens();
		return new ConsoleOutputStream(consoleOutputStream);
	}

	/**
	 * Returns an error stream that will be sniffed. This stream should be
	 * hooked up so the command error stream goes into here.
	 */
	public OutputStream getErrorStream() {
		incNOpens();
		return new ConsoleOutputStream(consoleErrorStream);
	}

	private synchronized void incNOpens() {
		nOpens++;
	}

	/*
	 */
	public synchronized void closeConsoleOutputStream() throws IOException {
		if (nOpens > 0 && --nOpens == 0) {
			for (int i = 0; i < parsers.length; ++i) {
				try {
					parsers[i].shutdown();
				} catch (Throwable e) {
					// Report exception if any but let all the parsers a chance
					// to shutdown.
					CppStyle.log(e);
				}
			}
		}
	}

	/*
	 * Processes the line by passing the line to the parsers.
	 *
	 * @param line
	 */
	private synchronized void processLine(String line) {
		for (IConsoleParser parser : parsers) {
			try {
				// Report exception if any but let all the parsers a chance to
				// process the line.
				parser.processLine(line);
			} catch (Throwable e) {
				CppStyle.log(e);
			}
		}
	}

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>[Polymer] WebAudio Slider(Fader) Examples</title>

    <link rel="import" href="webcomponents/slider.html">

Polymer Web Audio Slider(Fader) Elements

These sliders are made using Polymer and WebComponents. Checkout source code.

Also visit here to get webaudio-knob source code vreated by agektmr.

Sample: Size Variation

<webaudio-slider id="hoge01" class="hoge01" basesrc="images/fader-base01.jpg" knobsrc="images/fader-knob01.jpg" value="20" min="0" max="100" step="1" basewidth="104" baseheight="404" knobwidth="45" knobheight="86" ditchLength="290"></webaudio-slider>

<webaudio-slider id="hoge02" class="hoge02" basesrc="images/fader-base03.jpg" knobsrc="images/fader-knob03.jpg" value="40" min="0" max="100" step="1" basewidth="76" baseheight="300" knobwidth="35" knobheight="50" ditchLength="230"></webaudio-slider>

<webaudio-slider id="hoge03" class="hoge03" basesrc="images/fader-base02.jpg" knobsrc="images/fader-knob02.jpg" value="0" min="0" max="100" step="1" basewidth="43" baseheight="124" knobwidth="20" knobheight="30" ditchLength="80"></webaudio-slider>

<webaudio-slider id="hoge04" class="hoge04" basesrc="images/fader-base03.jpg" knobsrc="images/fader-knob03.jpg" value="40" min="0" max="100" step="1" basewidth="76" baseheight="300" knobwidth="35" knobheight="50" ditchLength="230"></webaudio-slider>

<webaudio-slider id="hoge05" class="hoge05" basesrc="images/fader-base01.jpg" knobsrc="images/fader-knob01.jpg" value="20" min="0" max="100" step="1" basewidth="104" baseheight="404" knobwidth="45" knobheight="86" ditchLength="290"></webaudio-slider>

Sample: Console Style

<webaudio-slider id="hoge101" class="hoge101" basesrc="images/fader-base03.jpg" knobsrc="images/fader-knob03.jpg" value="90" min="0" max="100" step="1" basewidth="76" baseheight="300" knobwidth="35" knobheight="50" ditchLength="230"></webaudio-slider>

<webaudio-slider id="hoge102" class="hoge102" basesrc="images/fader-base03.jpg" knobsrc="images/fader-knob03.jpg" value="60" min="0" max="100" step="1" basewidth="76" baseheight="300" knobwidth="35" knobheight="50" ditchLength="230"></webaudio-slider>

<webaudio-slider id="hoge103" class="hoge103" basesrc="images/fader-base03.jpg" knobsrc="images/fader-knob03.jpg" value="30" min="0" max="100" step="1" basewidth="76" baseheight="300" knobwidth="35" knobheight="50" ditchLength="230"></webaudio-slider>

<webaudio-slider id="hoge104" class="hoge104" basesrc="images/fader-base03.jpg" knobsrc="images/fader-knob03.jpg" value="00" min="0" max="100" step="1" basewidth="76" baseheight="300" knobwidth="35" knobheight="50" ditchLength="230"></webaudio-slider>

<webaudio-slider id="hoge105" class="hoge105" basesrc="images/fader-base03.jpg" knobsrc="images/fader-knob03.jpg" value="30" min="0" max="100" step="1" basewidth="76" baseheight="300" knobwidth="35" knobheight="50" ditchLength="230"></webaudio-slider>

<webaudio-slider id="hoge106" class="hoge106" basesrc="images/fader-base03.jpg" knobsrc="images/fader-knob03.jpg" value="60" min="0" max="100" step="1" basewidth="76" baseheight="300" knobwidth="35" knobheight="50" ditchLength="230"></webaudio-slider>

<webaudio-slider id="hoge107" class="hoge107" basesrc="images/fader-base03.jpg" knobsrc="images/fader-knob03.jpg" value="90" min="0" max="100" step="1" basewidth="76" baseheight="300" knobwidth="35" knobheight="50" ditchLength="230"></webaudio-slider>

Developed by Ryoya KAWAI.