text:
/* @test
 * @summary Comprehensive test for FileChannel.transfer{From,To}
 * @bug 4708120
 * @author Mark Reinhold
 */

import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.*;

public class Transfers {

    static PrintStream out = System.out;

    private static class Failure
        extends RuntimeException
    {

        Failure(Exception x) {
            super(x);
        }

        Failure(String s) {
            super(s);
        }

    }

    // -- Writing and reading random bytes --

    private static void writeBytes(byte[] ba, FileChannel fc,
                                   int off, int len)
        throws IOException
    {
        fc.position(off);
        if (fc.write(ByteBuffer.wrap(ba, 0, len)) != len)
            throw new IOException("Incomplete write");
        fc.position(0);
    }

    private static void writeRandomBytes(long seed,
                                         FileChannel fc, int off, int len)
        throws IOException
    {
        Random r = new Random(seed);
        byte[] ba = new byte[len];
        r.nextBytes(ba);
        writeBytes(ba, fc, off, len);
    }

    private static void writeZeroBytes(FileChannel fc, int off, int len)
        throws IOException
    {
        byte[] ba = new byte[len];
        writeBytes(ba, fc, off, len);
    }

    private static void checkBytes(FileChannel fc, int off, int len,
                                   byte[] bytes)
        throws IOException
    {
        ByteBuffer bb = ByteBuffer.allocate(len);
        fc.position(off);
        if (fc.read(bb) != len)
            throw new IOException("Incomplete read");
        bb.flip();
        ByteBuffer bab = ByteBuffer.wrap(bytes, 0, len);
        if (!bb.equals(bab))
            throw new Failure("Wrong data written");
    }

    private static void checkRandomBytes(FileChannel fc, int off, int len,
                                         long seed)
        throws IOException
    {
        byte[] ba = new byte[len];
        Random r = new Random(seed);
        r.nextBytes(ba);
        checkBytes(fc, off, len, ba);
    }

    private static void checkZeroBytes(FileChannel fc, int off, int len)
        throws IOException
    {
        byte[] ba = new byte[len];
        checkBytes(fc, off, len, ba);
    }

    // For debugging
    //
    private static void dump(FileChannel fc)
        throws IOException
    {
        int sz = (int)fc.size();
        ByteBuffer bb = ByteBuffer.allocate(sz);
        fc.position(0);
        if (fc.read(bb) != sz)
            throw new IOException("Incomplete read");
        bb.flip();
        byte prev = -1;
        int r = 0;                      // Repeats
        int n = 0;
        while (bb.hasRemaining() && (n < 32)) {
            byte b = bb.get();
            if (b == prev) {
                r++;
                continue;
            }
            if (r > 0) {
                int c = prev & 0xff;
                if (c < 0x10)
                    out.print('0');
                out.print(Integer.toHexString(c));
                if (r > 1) {
                    out.print("[");
                    out.print(r);
                    out.print("]");
                }
                n++;
            }
            prev = b;
            r = 1;
        }
        if (r > 0) {
            int c = prev & 0xff;
            if (c < 0x10)
                out.print('0');
            out.print(Integer.toHexString(c));
            if (r > 1) {
                out.print("[");
                out.print(r);
                out.print("]");
            }
            n++;
        }
        if (bb.hasRemaining())
            out.print("...");
        out.println();
    }

    static File sourceFile;
    static File targetFile;

    // -- Self-verifying sources and targets --

    static abstract class Source {

        protected final int size;
        protected final long seed;
        private final String name;

        Source(int size, long seed, String name) {
            this.size = size;
            this.seed = seed;
            this.name = name;
        }

        String name() {
            return name;
        }

        abstract ReadableByteChannel channel();

        abstract void verify() throws IOException;

    }

    static class FileSource
        extends Source
    {
        private final File fn;
        private final RandomAccessFile raf;
        private final FileChannel fc;

        FileSource(int size, long seed) throws IOException {
            super(size, seed, "FileChannel");
            fn = sourceFile;
            raf = new RandomAccessFile(fn, "rw");
            fc = raf.getChannel();
            fc.position(0);
            writeRandomBytes(seed, fc, 0, size);
        }

        ReadableByteChannel channel() {
            return fc;
        }

        void verify() throws IOException {
            if (fc.position() != size)
                throw new Failure("Wrong position: "
                                  + fc.position() + " (expected " + size +
                                  ")");
            checkRandomBytes(fc, 0, size, seed);
            fc.close();
            raf.close();                // Bug in 1.4.0
        }

    }

    static class UserSource
        extends Source
    {
        private ReadableByteChannel ch;
        private final ByteBuffer src;

        UserSource(int size, long seed) {
            super(size, seed, "UserChannel");

            final byte[] bytes = new byte[size + 1];
            Random r = new Random(seed);
            r.nextBytes(bytes);
            src = ByteBuffer.wrap(bytes);

            ch = new ReadableByteChannel() {
                    public int read(ByteBuffer dst) {
                        if (!src.hasRemaining())
                            return -1;
                        int nr = Math.min(src.remaining(), dst.remaining());
                        ByteBuffer s = src.duplicate();
                        s.limit(s.position() + nr);
                        dst.put(s);
                        src.position(src.position() + nr);
                        return nr;
                    }
                    public boolean isOpen() {
                        return true;
                    }
                    public void close() { }
                };
        }

        ReadableByteChannel channel() {
            return ch;
        }

        void verify() {
            if (src.remaining() != 1)
                throw new Failure("Source has " + src.remaining()
                                  + " bytes remaining (expected 1)");
        }

    }

    static abstract class Target {

        protected final int size;
        protected final long seed;
        private final String name;

        Target(int size, long seed, String name) {
            this.size = size;
            this.seed = seed;
            this.name = name;
        }

        String name() {
            return name;
        }

        abstract WritableByteChannel channel();

        abstract void verify() throws IOException;

    }

    static class FileTarget
        extends Target
    {
        private final File fn;
        private final RandomAccessFile raf;
        private final FileChannel fc;

        FileTarget(int size, long seed) throws IOException {
            super(size, seed, "FileChannel");
            fn = targetFile;
            raf = new RandomAccessFile(fn, "rw");
            fc = raf.getChannel();
            fc.position(0);
        }

        WritableByteChannel channel() {
            return fc;
        }

        void verify() throws IOException {
            if (fc.position() != size)
                throw new Failure("Wrong position: "
                                  + fc.position() + " (expected " + size + ")");
            checkRandomBytes(fc, 0, size, seed);
            fc.close();
            raf.close();                // Bug in 1.4.0
        }

    }

    static class UserTarget
        extends Target
    {
        private WritableByteChannel ch;
        private final ByteBuffer dst;

        UserTarget(int size, long seed) {
            super(size, seed, "UserChannel");
            dst = ByteBuffer.wrap(new byte[size + 1]);

            ch = new WritableByteChannel() {
                    public int write(ByteBuffer src) {
                        int nr = Math.min(src.remaining(), dst.remaining());
                        ByteBuffer s = src.duplicate();
                        s.limit(s.position() + nr);
                        dst.put(s);
                        src.position(src.position() + nr);
                        return nr;
                    }
                    public boolean isOpen() {
                        return true;
                    }
                    public void close() { }
                };
        }

        WritableByteChannel channel() {
            return ch;
        }

        void verify() {
            if (dst.remaining() != 1)
                throw new Failure("Destination has " + dst.remaining()
                                  + " bytes remaining (expected 1)");
            byte[] ba = new byte[size];
            Random r = new Random(seed);
            r.nextBytes(ba);
            dst.flip();
            ByteBuffer rbb = ByteBuffer.wrap(ba, 0, size);
            if (!dst.equals(rbb))
                throw new Failure("Wrong data written");
        }

    }

    // Generates a sequence of ints of the form 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
    // 15, 16, 17, 31, 32, 33, ..., 2^i-1, 2^i, 2^i+1, ..., max.

    static class IntGenerator {

        private int max;
        private int cur = -1;
        private int p2 = 8;

        IntGenerator(int max) {
            this.max = max;
        }

        boolean hasNext() {
            return cur < max;
        }

        int next() {
            if (cur >= max)
                throw new IllegalStateException();
            if (cur < 6) {
                cur++;
                return cur;
            }
            if (cur == p2 + 1) {
                p2 <<= 1;
                cur = p2 - 1;
                return cur;
            }
            cur++;
            return cur;
        }

    }

    // -- Tests --

    private static final int MAX_XFER_SIZE = 1 << 14;
    private static final int MAX_FILE_SIZE = MAX_XFER_SIZE << 1;

    private static boolean debug = false;
    private static boolean verbose = false;

    static void show(String dir, String channelName, int off, int len) {
        if (!verbose)
            return;
        out.println(dir + " " + channelName +
                    ": offset " + off + ", length " + len);
    }

    static void testTo(long seed, FileChannel fc, int off, int len, Target tgt)
        throws IOException
    {
        show("To", tgt.name(), off, len);

        // Clear source, then randomize just the source region
        writeZeroBytes(fc, 0, MAX_FILE_SIZE);
        writeRandomBytes(seed, fc, off, len);

        // Randomize position
        int pos = (int)seed & 0xfff;
        fc.position(pos);

        int n = (int)fc.transferTo(off, len, tgt.channel());
        if (n != len)
            throw new Failure("Incorrect transfer length: " + n
                              + " (expected " + len + ")");

        // Check that source wasn't changed
        if (fc.position() != pos)
            throw new Failure("Position changed");
        if (debug)
            dump(fc);
        checkRandomBytes(fc, off, len, seed);
        writeZeroBytes(fc, off, len);
        checkZeroBytes(fc, 0, MAX_FILE_SIZE);

        // Check that target was updated correctly
        tgt.verify();
    }

    static void testFrom(long seed, Source src, FileChannel fc, int off, int len)
        throws IOException
    {
        show("From", src.name(), off, len);

        // Clear target
        writeZeroBytes(fc, 0, MAX_FILE_SIZE);

        // Randomize position
        int pos = (int)seed & 0xfff;
        fc.position(pos);

        int n = (int)fc.transferFrom(src.channel(), off, len);
        if (n != len)
            throw new Failure("Incorrect transfer length: " + n
                              + " (expected " + len + ")");

        // Check that source didn't change, and was read correctly
        src.verify();

        // Check that target was updated correctly
        if (fc.position() != pos)
            throw new Failure("Position changed");
        if (debug)
            dump(fc);
        checkRandomBytes(fc, off, len, seed);
        writeZeroBytes(fc, off, len);
        checkZeroBytes(fc, 0, MAX_FILE_SIZE);
    }

    public static void main(String[] args)
        throws Exception
    {
        if (args.length > 0) {
            if (args[0].indexOf('v') >= 0)
                verbose = true;
            if (args[0].indexOf('d') >= 0)
                debug = verbose = true;
        }

        sourceFile = File.createTempFile("xfer.src.", "");
        sourceFile.deleteOnExit();
        targetFile = File.createTempFile("xfer.tgt.", "");
        targetFile.deleteOnExit();

        File fn = File.createTempFile("xfer.fch.", "");
        fn.deleteOnExit();
        FileChannel fc = new RandomAccessFile(fn, "rw").getChannel();

        Random rnd = new Random();
        int failures = 0;

        for (boolean to = false;; to = true) {
            for (boolean user = false;; user = true) {
                if (!verbose)
                    out.print((to ? "To " : "From ") +
                              (user ? "user channel" : "file channel")
                              + ":");
                IntGenerator offGen = new IntGenerator(MAX_XFER_SIZE + 2);
                while (offGen.hasNext()) {
                    int off = offGen.next();
                    if (!verbose) out.print(" " + off);
                    IntGenerator lenGen = new IntGenerator(MAX_XFER_SIZE + 2);
                    while (lenGen.hasNext()) {
                        int len = lenGen.next();
                        long s = rnd.nextLong();
                        String chName = null;
                        try {
                            if (to) {
                                Target tgt;
                                if (user)
                                    tgt = new UserTarget(len, s);
                                else
                                    tgt = new FileTarget(len, s);
                                chName = tgt.name();
                                testTo(s, fc, off, len, tgt);
                            }
                            else {
                                Source src;
                                if (user)
                                    src = new UserSource(len, s);
                                else
                                    src = new FileSource(len, s);
                                chName = src.name();
                                testFrom(s, src, fc, off, len);
                            }
                        } catch (Failure x) {
                            out.println();
                            out.println("FAILURE: " + chName
                                        + ", offset " + off
                                        + ", length " + len);
                            x.printStackTrace(out);
                            failures++;
                        }
                    }
                }
                if (!verbose)
                    out.println();
                if (user)
                    break;
            }
            if (to)
                break;
        }

        sourceFile.delete();
        targetFile.delete();
        fn.delete();

        if (failures > 0) {
            out.println();
            throw new RuntimeException("Some tests failed");
        }

    }

}


text:
using System;

public class CircularQueue<T>
{
    private const int DefaultCapacity = 4;

    public T[] elements { get; set; }
    public int startIndex { get; private set; }
    public int endIndex { get; private set; }
    public int Count { get; private set; }

    public CircularQueue(int capacity = DefaultCapacity)
    {
        this.elements = new T[capacity];
        this.startIndex = 0;
        this.endIndex = 0;
    }

    public void Enqueue(T element)
    {
        if (this.Count >= this.elements.Length)
        {
            this.Grow();
        }

        this.elements[this.endIndex] = element;
        this.endIndex = (this.endIndex + 1) % this.elements.Length;
        this.Count++;
    }

    private void Grow()
    {
        var newElements = new T[2 * this.elements.Length];
        this.CopyAllElements(newElements);
        this.elements = newElements;
        this.startIndex = 0;
        this.endIndex = Count;
    }

    private void Resize()
    {
        // TODO
        throw new NotImplementedException();
    }

    private void CopyAllElements(T[] newArray)
    {
        int sourceIndex = this.startIndex;
        int destinationIndex = 0;
        for (int i = 0; i < this.Count; i++)
        {
            newArray[destinationIndex] = this.elements[sourceIndex];
            sourceIndex = (sourceIndex + 1) % this.elements.Length;
            destinationIndex++;
        }
    }

    public T Dequeue()
    {
        if (this.Count == 0)
        {
            throw new InvalidOperationException("The queue is empty!");
        }

        var result = this.elements[startIndex];
        this.startIndex = (this.startIndex + 1) % this.elements.Length;
        this.Count--;

        return result;
    }

    public T[] ToArray()
    {
        var result = new T[this.Count];
        CopyAllElements(result);

        return result;
    }
}

public class Example
{
    public static void Main()
    {

        CircularQueue<int> queue = new CircularQueue<int>();

        queue.Enqueue(1);
        queue.Enqueue(2);
        queue.Enqueue(3);
        queue.Enqueue(4);
        queue.Enqueue(5);
        queue.Enqueue(6);

        Console.WriteLine("Count = {0}", queue.Count);
        Console.WriteLine(string.Join(", ", queue.ToArray()));
        Console.WriteLine("---------------------------");

        int first = queue.Dequeue();
        Console.WriteLine("First = {0}", first);
        Console.WriteLine("Count = {0}", queue.Count);
        Console.WriteLine(string.Join(", ", queue.ToArray()));
        Console.WriteLine("---------------------------");

        queue.Enqueue(-7);
        queue.Enqueue(-8);
        queue.Enqueue(-9);
        Console.WriteLine("Count = {0}", queue.Count);
        Console.WriteLine(string.Join(", ", queue.ToArray()));
        Console.WriteLine("---------------------------");

        first = queue.Dequeue();
        Console.WriteLine("First = {0}", first);
        Console.WriteLine("Count = {0}", queue.Count);
        Console.WriteLine(string.Join(", ", queue.ToArray()));
        Console.WriteLine("---------------------------");

        queue.Enqueue(-10);
        Console.WriteLine("Count = {0}", queue.Count);
        Console.WriteLine(string.Join(", ", queue.ToArray()));
        Console.WriteLine("---------------------------");

        first = queue.Dequeue();
        Console.WriteLine("First = {0}", first);
        Console.WriteLine("Count = {0}", queue.Count);
        Console.WriteLine(string.Join(", ", queue.ToArray()));
        Console.WriteLine("---------------------------");
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Data.SqlClient;
using System.IO;
using MySql.Data.MySqlClient;

namespace Innvent.Models.Dao
{
    /// <summary>
    /// Responsável pelo acesso à base de dados de cache das cotações.
    /// Como a base só tem uma tabela, decidimos fazer apenas uma classe.
    /// </summary>
    public class CotacaoCacheDao
    {
        private static string SalvarCotacaoQuery = @"Insert into tbCacheCotacao
                                                        (DataCotacao, CodigoConversao, Valor)
                                                     Values
                                                        (@DataCotacao, @CodigoConversao, @Valor)";

        private static string ObterCotacaoEntreDatasQuery = @"Select * from tbCacheCotacao
                                                                where DataCotacao >= @DataCotacao1 and DataCotacao <= @DataCotacao2
                                                                    and CodigoConversao = @CodigoConversao";

        private static string ObterCotacaoPorCodigoQuery = @"Select * from tbCacheCotacao
                                                                where DataCotacao = @DataCotacao and CodigoConversao IN @CodigoConversao";

        /// <summary>
        /// Constroi e retorna a string de conexão com o banco de dados
        /// </summary>
        /// <returns></returns>
        private string ObterConnectionString()
        {
            MySqlConnectionStringBuilder conStr = new MySqlConnectionStringBuilder();
            conStr.Server   = ConfigurationManager.AppSettings["DB_Cache_CotacaoCS_Servidor"];
            conStr.Database = ConfigurationManager.AppSettings["DB_Cache_CotacaoCS_database"];
            conStr.UserID   = ConfigurationManager.AppSettings["DB_Cache_CotacaoCS_login"];

            conStr.ConnectionTimeout = uint.Parse(ConfigurationManager.AppSettings["DB_Cache_CotacaoCS_TimeoutConexao"]);

            conStr.Password = Apoio.GetVariavelAmbiente("Innvent_DB_Cache_Cotacao_Password");

            return conStr.ToString() ;

        }

        /// <summary>
        /// Salva uma cotação no cache
        /// </summary>
        /// <param name="cotacao"></param>
        public void SalvarCotacao(CotacaoCache cotacao)
        {
            // teste de sanidade
            if (cotacao == null)
                throw new ArgumentNullException();

            // Executando inserção no cache
            using (MySqlConnection connection = AbrirConexao())
            {
                // Inserindo parâmetros da query
                DynamicParameters dp = new DynamicParameters();
                dp.Add("@DataCotacao", cotacao.DataCotacao, System.Data.DbType.Date);
                dp.Add("@CodigoConversao", cotacao.CodigoConversao);
                dp.Add("@Valor", cotacao.Valor);

                connection.Execute(CotacaoCacheDao.SalvarCotacaoQuery, dp);
            }
        }

        /// <summary>
        /// Obtém uma cotação de um código de cotação em uma faixa de tempo
        /// </summary>
        /// <param name="dataOrigem"></param>
        /// <param name="dataFim"></param>
        /// <param name="CodigoConversao"></param>
        /// <returns></returns>
        public List<CotacaoCache> GetCotacao(DateTime dataOrigem, DateTime dataFim, string CodigoConversao)
        {
            // Executando query dos elementos
            using (MySqlConnection connection = AbrirConexao())
            {
                // Inserindo parâmetros da query
                DynamicParameters dp = new DynamicParameters();
                dp.Add("@DataCotacao1", dataOrigem.ToString("yyyy-MM-dd"), System.Data.DbType.Date);
                dp.Add("@DataCotacao2", dataFim.ToString("yyyy-MM-dd"), System.Data.DbType.Date);
                dp.Add("@CodigoConversao", CodigoConversao);

                return connection.Query< CotacaoCache>(CotacaoCacheDao.ObterCotacaoEntreDatasQuery, dp).ToList();
            }
        }

        /// <summary>
        /// Obtem as cotações de todas as moedas passadas com seus códigos
        /// em uma dada específica
        /// </summary>
        /// <param name="dataCotacao"></param>
        /// <param name="codigosMoedas"></param>
        /// <returns></returns>
        public List<CotacaoCache> GetCotacao(DateTime dataCotacao, List<string> codigosMoedas)
        {
            // Executando query dos elementos
            using (MySqlConnection connection = AbrirConexao())
            {
                // Inserindo parâmetros da query
                DynamicParameters dp = new DynamicParameters();
                dp.Add("@DataCotacao", dataCotacao.ToString("yyyy-MM-dd"), System.Data.DbType.Date);
                dp.Add("@CodigoConversao", codigosMoedas);

                // Executando query
                return connection.Query<CotacaoCache>(CotacaoCacheDao.ObterCotacaoEntreDatasQuery, dp).ToList();
            }
        }

        /// <summary>
        /// Abre uma conexão com o banco de dados se ela já não estiver
        /// sendo usada
        /// </summary>
        private MySqlConnection AbrirConexao()
        {
            string connectionString = ObterConnectionString();
            MySqlConnection connection = new MySqlConnection(connectionString);
            connection.Open();
            return connection;
        }

    }
}


text:
import static com.google.common.base.Charsets.UTF_8;

import com.google.template.soy.SoyFileSet;
import com.google.template.soy.data.SoyMapData;
import com.google.template.soy.data.SanitizedContent;
import com.google.template.soy.tofu.SoyTofu;

import java.io.File;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableList;
import com.google.common.io.Files;

public class WriteSvg {

  // Yay static
  private static SoyTofu tofu;

  public static void main (String[] args) throws Exception {

    // Bundle the Soy files for your project into a SoyFileSet.
    SoyFileSet.Builder sfs = SoyFileSet.builder();
    sfs.add(new File("src/windmill.soy"));
    sfs.setCompileTimeGlobals(new File("dist/soyglobals.txt"));

    // Compile the template into a SoyTofu object.
    // SoyTofu's newRenderer method returns an object that can render any template in the file set.
    tofu = sfs.build().compileToTofu();

    Files.write(
        tofu.newRenderer("windmill.templates.icons")
            .render(),
        new File("static/witness.svg"),
        UTF_8);
    Files.write(
        tofu.newRenderer("windmill.templates.logo")
            .render(),
        new File("static/logo.svg"),
        UTF_8);
  }
}


text:
Then(/^I should be on the advocate interim new claim page$/) do
  expect(@advocate_interim_claim_form_page).to be_displayed
end

And(/^I fill in '(.*)' as the warrant issued date$/) do |date|
  @advocate_interim_claim_form_page.warrant_issued_date.set_date date
end

And(/^I enter a Warrant net amount of '(.*?)'$/) do |amount|
  @advocate_interim_claim_form_page.warrant_net_amount.set amount
end


text:
namespace syncer {

struct SyncStatus;

// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class TrustedVaultHintDegradedRecoverabilityChangedReasonForUMA {
  kRecoveryMethodAdded = 0,
  kPersistentAuthErrorResolved = 1,
  kMaxValue = kPersistentAuthErrorResolved,
};

// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class TrustedVaultDeviceRegistrationStateForUMA {
  kAlreadyRegisteredV0 = 0,
  kLocalKeysAreStale = 1,
  kThrottledClientSide = 2,
  kAttemptingRegistrationWithNewKeyPair = 3,
  kAttemptingRegistrationWithExistingKeyPair = 4,
  kAttemptingRegistrationWithPersistentAuthError = 5,
  kAlreadyRegisteredV1 = 6,
  kMaxValue = kAlreadyRegisteredV1,
};

// Used to provide UMA metric breakdowns.
enum class TrustedVaultURLFetchReasonForUMA {
  kUnspecified,
  kRegisterDevice,
  kRegisterUnspecifiedAuthenticationFactor,
  kDownloadKeys,
  kDownloadIsRecoverabilityDegraded,
};

// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class TrustedVaultDownloadKeysStatusForUMA {
  kSuccess = 0,
  // Deprecated in favor of the more fine-grained buckets.
  kDeprecatedMembershipNotFoundOrCorrupted = 1,
  kNoNewKeys = 2,
  kKeyProofsVerificationFailed = 3,
  kAccessTokenFetchingFailure = 4,
  kOtherError = 5,
  kMemberNotFound = 6,
  kMembershipNotFound = 7,
  kMembershipCorrupted = 8,
  kMembershipEmpty = 9,
  kNoPrimaryAccount = 10,
  kDeviceNotRegistered = 11,
  kThrottledClientSide = 12,
  kCorruptedLocalDeviceRegistration = 13,
  kAborted = 14,
  kMaxValue = kAborted
};

// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class TrustedVaultFileReadStatusForUMA {
  kSuccess = 0,
  kNotFound = 1,
  kFileReadFailed = 2,
  kMD5DigestMismatch = 3,
  kFileProtoDeserializationFailed = 4,
  kDataProtoDeserializationFailed = 5,
  kMaxValue = kDataProtoDeserializationFailed
};

void RecordTrustedVaultHintDegradedRecoverabilityChangedReason(
    TrustedVaultHintDegradedRecoverabilityChangedReasonForUMA
        hint_degraded_recoverability_changed_reason);

void RecordTrustedVaultDeviceRegistrationState(
    TrustedVaultDeviceRegistrationStateForUMA registration_state);

// Records url fetch response status (combined http and net error code). If
// |http_response_code| is non-zero, it will be recorded, otherwise |net_error|
// will be recorded. Either |http_status| or |net_error| must be non zero.
void RecordTrustedVaultURLFetchResponse(
    int http_response_code,
    int net_error,
    TrustedVaultURLFetchReasonForUMA reason);

// Records the outcome of trying to download keys from the server.
// |also_log_with_v1_suffx| allows the caller to determine whether the local
// device's registration is a V1 registration (that is, more reliable), which
// causes a second histogram to be logged as well.
void RecordTrustedVaultDownloadKeysStatus(
    TrustedVaultDownloadKeysStatusForUMA status,
    bool also_log_with_v1_suffx = false);

void RecordTrustedVaultHistogramBooleanWithMigrationSuffix(
    const std::string& histogram_name,
    bool sample,
    const SyncStatus& sync_status);

void RecordTrustedVaultFileReadStatus(TrustedVaultFileReadStatusForUMA status);

}  // namespace syncer

#endif  // COMPONENTS_SYNC_DRIVER_TRUSTED_VAULT_HISTOGRAMS_H_


text:
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/login/users/default_user_image/default_user_images.h"

#include <algorithm>
#include <memory>
#include <string>
#include <vector>

#include "ash/constants/ash_features.h"
#include "ash/public/cpp/default_user_image.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/rand_util.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/system/sys_info.h"
#include "chrome/common/webui_url_constants.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/chromeos/resources/grit/ui_chromeos_resources.h"
#include "ui/chromeos/strings/grit/ui_chromeos_strings.h"
#include "ui/gfx/image/image_skia.h"
#include "url/gurl.h"

namespace ash {
namespace default_user_image {
namespace {

struct DefaultImageInfo {
  // Resource IDs of default user images.
  const int resource_id;

  // Message IDs of default user image descriptions.
  const int description_message_id;

  // Whether the user image is eligible in the current set. If so, user can
  // select the image as avatar through personalization settings.
  Eligibility eligibility;

  // A path of the default user image, will be used to generate gstatic URLs
  // and to cache the user image locally on disk.
  const char* path;
};

// Info of default user images. When adding new entries to this list,
// please also update the enum ChromeOSUserImageId2 in
// tools/metrics/histograms/enums.xml
// When deprecating images, please also update kCurrentImageIndexes accordingly.
// clang-format off
constexpr DefaultImageInfo kDefaultImageInfo[] = {
    // No description for deprecated user image 0-18.
    {IDR_LOGIN_DEFAULT_USER, 0, Eligibility::kDeprecated, "legacy/avatar_anonymous.png"},
    // Original set of images.
    {IDR_LOGIN_DEFAULT_USER_1, 0, Eligibility::kDeprecated, "legacy/avatar_bee.png"},
    {IDR_LOGIN_DEFAULT_USER_2, 0, Eligibility::kDeprecated, "legacy/avatar_briefcase.png"},
    {IDR_LOGIN_DEFAULT_USER_3, 0, Eligibility::kDeprecated, "legacy/avatar_circles.png"},
    {IDR_LOGIN_DEFAULT_USER_4, 0, Eligibility::kDeprecated, "legacy/avatar_cloud.png"},
    {IDR_LOGIN_DEFAULT_USER_5, 0, Eligibility::kDeprecated, "legacy/avatar_cupcake.png"},
    {IDR_LOGIN_DEFAULT_USER_6, 0, Eligibility::kDeprecated, "legacy/avatar_day.png"},
    {IDR_LOGIN_DEFAULT_USER_7, 0, Eligibility::kDeprecated, "legacy/avatar_flower.png"},
    {IDR_LOGIN_DEFAULT_USER_8, 0, Eligibility::kDeprecated, "legacy/avatar_globe.png"},
    {IDR_LOGIN_DEFAULT_USER_9, 0, Eligibility::kDeprecated, "legacy/avatar_hotair.png"},
    {IDR_LOGIN_DEFAULT_USER_10, 0, Eligibility::kDeprecated, "legacy/avatar_ladybug.png"},
    {IDR_LOGIN_DEFAULT_USER_11, 0, Eligibility::kDeprecated, "legacy/avatar_leaf.png"},
    {IDR_LOGIN_DEFAULT_USER_12, 0, Eligibility::kDeprecated, "legacy/avatar_night.png"},
    {IDR_LOGIN_DEFAULT_USER_13, 0, Eligibility::kDeprecated, "legacy/avatar_plane.png"},
    {IDR_LOGIN_DEFAULT_USER_14, 0, Eligibility::kDeprecated, "legacy/avatar_robot_body.png"},
    {IDR_LOGIN_DEFAULT_USER_15, 0, Eligibility::kDeprecated, "legacy/avatar_robot_head.png"},
    {IDR_LOGIN_DEFAULT_USER_16, 0, Eligibility::kDeprecated, "legacy/avatar_toolbox.png"},
    {IDR_LOGIN_DEFAULT_USER_17, 0, Eligibility::kDeprecated, "legacy/avatar_user_color.png"},
    {IDR_LOGIN_DEFAULT_USER_18, 0, Eligibility::kDeprecated, "legacy/avatar_user_enterprise.png"},
    // Second set of images.
    {IDR_LOGIN_DEFAULT_USER_19, IDS_LOGIN_DEFAULT_USER_DESC_19, Eligibility::kDeprecated, "legacy/avatar_bicycle.png"},
    {IDR_LOGIN_DEFAULT_USER_20, IDS_LOGIN_DEFAULT_USER_DESC_20, Eligibility::kDeprecated, "legacy/avatar_bokeh.png"},
    {IDR_LOGIN_DEFAULT_USER_21, IDS_LOGIN_DEFAULT_USER_DESC_21, Eligibility::kDeprecated, "legacy/avatar_chess.png"},
    {IDR_LOGIN_DEFAULT_USER_22, IDS_LOGIN_DEFAULT_USER_DESC_22, Eligibility::kDeprecated, "legacy/avatar_coffee.png"},
    {IDR_LOGIN_DEFAULT_USER_23, IDS_LOGIN_DEFAULT_USER_DESC_23, Eligibility::kDeprecated, "legacy/avatar_dragonfly.png"},
    {IDR_LOGIN_DEFAULT_USER_24, IDS_LOGIN_DEFAULT_USER_DESC_24, Eligibility::kDeprecated, "legacy/avatar_frog.png"},
    {IDR_LOGIN_DEFAULT_USER_25, IDS_LOGIN_DEFAULT_USER_DESC_25, Eligibility::kDeprecated, "legacy/avatar_ganzania.png"},
    {IDR_LOGIN_DEFAULT_USER_26, IDS_LOGIN_DEFAULT_USER_DESC_26, Eligibility::kDeprecated, "legacy/avatar_jackrussellterrier.png"},
    {IDR_LOGIN_DEFAULT_USER_27, IDS_LOGIN_DEFAULT_USER_DESC_27, Eligibility::kDeprecated, "legacy/avatar_jellyfish.png"},
    {IDR_LOGIN_DEFAULT_USER_28, IDS_LOGIN_DEFAULT_USER_DESC_28, Eligibility::kDeprecated, "legacy/avatar_kiwi.png"},
    {IDR_LOGIN_DEFAULT_USER_29, IDS_LOGIN_DEFAULT_USER_DESC_29, Eligibility::kDeprecated, "legacy/avatar_penguin.png"},
    {IDR_LOGIN_DEFAULT_USER_30, IDS_LOGIN_DEFAULT_USER_DESC_30, Eligibility::kDeprecated, "legacy/avatar_rainbowfish.png"},
    {IDR_LOGIN_DEFAULT_USER_31, IDS_LOGIN_DEFAULT_USER_DESC_31, Eligibility::kDeprecated, "legacy/avatar_recordplayer.png"},
    {IDR_LOGIN_DEFAULT_USER_32, IDS_LOGIN_DEFAULT_USER_DESC_32, Eligibility::kDeprecated, "legacy/avatar_upsidedown.png"},
    {IDR_LOGIN_DEFAULT_USER_33, IDS_LOGIN_DEFAULT_USER_DESC_33, Eligibility::kDeprecated, "legacy/avatar_cat.png"},
    // Third set of images.
    {IDR_LOGIN_DEFAULT_USER_34, IDS_LOGIN_DEFAULT_USER_DESC_34, Eligibility::kDeprecated, "origami/avatar_penguin.png"},
    {IDR_LOGIN_DEFAULT_USER_35, IDS_LOGIN_DEFAULT_USER_DESC_35, Eligibility::kDeprecated, "origami/avatar_fox.png"},
    {IDR_LOGIN_DEFAULT_USER_36, IDS_LOGIN_DEFAULT_USER_DESC_36, Eligibility::kDeprecated, "origami/avatar_snail.png"},
    {IDR_LOGIN_DEFAULT_USER_37, IDS_LOGIN_DEFAULT_USER_DESC_37, Eligibility::kDeprecated, "origami/avatar_redbutterfly.png"},
    {IDR_LOGIN_DEFAULT_USER_38, IDS_LOGIN_DEFAULT_USER_DESC_38, Eligibility::kDeprecated, "origami/avatar_cat.png"},
    {IDR_LOGIN_DEFAULT_USER_39, IDS_LOGIN_DEFAULT_USER_DESC_39, Eligibility::kDeprecated, "origami/avatar_corgi.png"},
    {IDR_LOGIN_DEFAULT_USER_40, IDS_LOGIN_DEFAULT_USER_DESC_40, Eligibility::kDeprecated, "origami/avatar_rabbit.png"},
    {IDR_LOGIN_DEFAULT_USER_41, IDS_LOGIN_DEFAULT_USER_DESC_41, Eligibility::kDeprecated, "origami/avatar_pinkbutterfly.png"},
    {IDR_LOGIN_DEFAULT_USER_42, IDS_LOGIN_DEFAULT_USER_DESC_42, Eligibility::kDeprecated, "origami/avatar_monkey.png"},
    {IDR_LOGIN_DEFAULT_USER_43, IDS_LOGIN_DEFAULT_USER_DESC_43, Eligibility::kDeprecated, "origami/avatar_dragon.png"},
    {IDR_LOGIN_DEFAULT_USER_44, IDS_LOGIN_DEFAULT_USER_DESC_44, Eligibility::kDeprecated, "origami/avatar_elephant.png"},
    {IDR_LOGIN_DEFAULT_USER_45, IDS_LOGIN_DEFAULT_USER_DESC_45, Eligibility::kDeprecated, "origami/avatar_panda.png"},
    {IDR_LOGIN_DEFAULT_USER_46, IDS_LOGIN_DEFAULT_USER_DESC_46, Eligibility::kDeprecated, "origami/avatar_unicorn.png"},
    {IDR_LOGIN_DEFAULT_USER_47, IDS_LOGIN_DEFAULT_USER_DESC_47, Eligibility::kDeprecated, "origami/avatar_butterflies.png"},
    {IDR_LOGIN_DEFAULT_USER_48, IDS_LOGIN_DEFAULT_USER_DESC_48, Eligibility::kEligible,   "illustration/avatar_bird.png"},
    {IDR_LOGIN_DEFAULT_USER_49, IDS_LOGIN_DEFAULT_USER_DESC_49, Eligibility::kEligible,   "illustration/avatar_ramen.png"},
    {IDR_LOGIN_DEFAULT_USER_50, IDS_LOGIN_DEFAULT_USER_DESC_50, Eligibility::kEligible,   "illustration/avatar_tamagotchi.png"},
    {IDR_LOGIN_DEFAULT_USER_51, IDS_LOGIN_DEFAULT_USER_DESC_51, Eligibility::kEligible,   "illustration/avatar_cheese.png"},
    {IDR_LOGIN_DEFAULT_USER_52, IDS_LOGIN_DEFAULT_USER_DESC_52, Eligibility::kEligible,   "illustration/avatar_football.png"},
    {IDR_LOGIN_DEFAULT_USER_53, IDS_LOGIN_DEFAULT_USER_DESC_53, Eligibility::kEligible,   "illustration/avatar_basketball.png"},
    {IDR_LOGIN_DEFAULT_USER_54, IDS_LOGIN_DEFAULT_USER_DESC_54, Eligibility::kEligible,   "illustration/avatar_vinyl.png"},
    {IDR_LOGIN_DEFAULT_USER_55, IDS_LOGIN_DEFAULT_USER_DESC_55, Eligibility::kEligible,   "illustration/avatar_sushi.png"},
    {IDR_LOGIN_DEFAULT_USER_56, IDS_LOGIN_DEFAULT_USER_DESC_56, Eligibility::kEligible,   "illustration/avatar_bike.png"},
    {IDR_LOGIN_DEFAULT_USER_57, IDS_LOGIN_DEFAULT_USER_DESC_57, Eligibility::kEligible,   "illustration/avatar_sunglasses.png"},
    {IDR_LOGIN_DEFAULT_USER_58, IDS_LOGIN_DEFAULT_USER_DESC_58, Eligibility::kEligible,   "abstract/avatar_pizza.png"},
    {IDR_LOGIN_DEFAULT_USER_59, IDS_LOGIN_DEFAULT_USER_DESC_59, Eligibility::kEligible,   "abstract/avatar_sandwich.png"},
    {IDR_LOGIN_DEFAULT_USER_60, IDS_LOGIN_DEFAULT_USER_DESC_60, Eligibility::kEligible,   "abstract/avatar_cappuccino.png"},
    {IDR_LOGIN_DEFAULT_USER_61, IDS_LOGIN_DEFAULT_USER_DESC_61, Eligibility::kEligible,   "abstract/avatar_icewater.png"},
    {IDR_LOGIN_DEFAULT_USER_62, IDS_LOGIN_DEFAULT_USER_DESC_62, Eligibility::kEligible,   "abstract/avatar_icecream.png"},
    {IDR_LOGIN_DEFAULT_USER_63, IDS_LOGIN_DEFAULT_USER_DESC_63, Eligibility::kEligible,   "abstract/avatar_onigiri.png"},
    {IDR_LOGIN_DEFAULT_USER_64, IDS_LOGIN_DEFAULT_USER_DESC_64, Eligibility::kEligible,   "abstract/avatar_melon.png"},
    {IDR_LOGIN_DEFAULT_USER_65, IDS_LOGIN_DEFAULT_USER_DESC_65, Eligibility::kEligible,   "abstract/avatar_avocado.png"},
    {IDR_LOGIN_DEFAULT_USER_66, IDS_LOGIN_DEFAULT_USER_DESC_66, Eligibility::kDeprecated, "geo/avatar_geo1.png"},
    {IDR_LOGIN_DEFAULT_USER_67, IDS_LOGIN_DEFAULT_USER_DESC_67, Eligibility::kDeprecated, "geo/avatar_geo2.png"},
    {IDR_LOGIN_DEFAULT_USER_68, IDS_LOGIN_DEFAULT_USER_DESC_68, Eligibility::kDeprecated, "geo/avatar_geo3.png"},
    {IDR_LOGIN_DEFAULT_USER_69, IDS_LOGIN_DEFAULT_USER_DESC_69, Eligibility::kDeprecated, "geo/avatar_geo4.png"},
    {IDR_LOGIN_DEFAULT_USER_70, IDS_LOGIN_DEFAULT_USER_DESC_70, Eligibility::kDeprecated, "geo/avatar_geo5.png"},
    {IDR_LOGIN_DEFAULT_USER_71, IDS_LOGIN_DEFAULT_USER_DESC_71, Eligibility::kEligible,   "imaginary/avatar_botanist.png"},
    {IDR_LOGIN_DEFAULT_USER_72, IDS_LOGIN_DEFAULT_USER_DESC_72, Eligibility::kEligible,   "imaginary/avatar_burger.png"},
    {IDR_LOGIN_DEFAULT_USER_73, IDS_LOGIN_DEFAULT_USER_DESC_73, Eligibility::kEligible,   "imaginary/avatar_graduate.png"},
    {IDR_LOGIN_DEFAULT_USER_74, IDS_LOGIN_DEFAULT_USER_DESC_74, Eligibility::kEligible,   "imaginary/avatar_guitar.png"},
    {IDR_LOGIN_DEFAULT_USER_75, IDS_LOGIN_DEFAULT_USER_DESC_75, Eligibility::kEligible,   "imaginary/avatar_waving.png"},
    {IDR_LOGIN_DEFAULT_USER_76, IDS_LOGIN_DEFAULT_USER_DESC_76, Eligibility::kEligible,   "imaginary/avatar_lion.png"},
    {IDR_LOGIN_DEFAULT_USER_77, IDS_LOGIN_DEFAULT_USER_DESC_77, Eligibility::kEligible,   "imaginary/avatar_planet.png"},
    {IDR_LOGIN_DEFAULT_USER_78, IDS_LOGIN_DEFAULT_USER_DESC_78, Eligibility::kEligible,   "imaginary/avatar_instant_camera.png"},
    {IDR_LOGIN_DEFAULT_USER_79, IDS_LOGIN_DEFAULT_USER_DESC_79, Eligibility::kEligible,   "imaginary/avatar_robot.png"},
    {IDR_LOGIN_DEFAULT_USER_80, IDS_LOGIN_DEFAULT_USER_DESC_80, Eligibility::kEligible,   "imaginary/avatar_sneaker.png"},
    {IDR_LOGIN_DEFAULT_USER_81, IDS_LOGIN_DEFAULT_USER_DESC_81, Eligibility::kEligible,   "imaginary/avatar_van.png"},
    {IDR_LOGIN_DEFAULT_USER_82, IDS_LOGIN_DEFAULT_USER_DESC_82, Eligibility::kEligible,   "imaginary/avatar_watermelon.png"},
    // Material design avatars.
    {IDR_LOGIN_DEFAULT_USER_83, IDS_LOGIN_DEFAULT_USER_DESC_83, Eligibility::kEligible, "material_design/avatar_person_watering_plants.png"},
    {IDR_LOGIN_DEFAULT_USER_84, IDS_LOGIN_DEFAULT_USER_DESC_84, Eligibility::kEligible, "material_design/avatar_person_daydreaming.png"},
    {IDR_LOGIN_DEFAULT_USER_85, IDS_LOGIN_DEFAULT_USER_DESC_85, Eligibility::kEligible, "material_design/avatar_person_with_flowers.png"},
    {IDR_LOGIN_DEFAULT_USER_86, IDS_LOGIN_DEFAULT_USER_DESC_86, Eligibility::kEligible, "material_design/avatar_person_with_cats.png"},
    {IDR_LOGIN_DEFAULT_USER_87, IDS_LOGIN_DEFAULT_USER_DESC_87, Eligibility::kEligible, "material_design/avatar_artist.png"},
    {IDR_LOGIN_DEFAULT_USER_88, IDS_LOGIN_DEFAULT_USER_DESC_88, Eligibility::kEligible, "material_design/avatar_person_doing_taichi.png"},
    {IDR_LOGIN_DEFAULT_USER_89, IDS_LOGIN_DEFAULT_USER_DESC_89, Eligibility::kEligible, "material_design/avatar_signing_thankyou.png"},
    {IDR_LOGIN_DEFAULT_USER_90, IDS_LOGIN_DEFAULT_USER_DESC_90, Eligibility::kEligible, "material_design/avatar_person_with_coffee.png"},
    {IDR_LOGIN_DEFAULT_USER_91, IDS_LOGIN_DEFAULT_USER_DESC_91, Eligibility::kEligible, "material_design/avatar_dog_wagging_tail.png"},
    {IDR_LOGIN_DEFAULT_USER_92, IDS_LOGIN_DEFAULT_USER_DESC_92, Eligibility::kEligible, "material_design/avatar_nurse.png"},
    {IDR_LOGIN_DEFAULT_USER_93, IDS_LOGIN_DEFAULT_USER_DESC_93, Eligibility::kEligible, "material_design/avatar_gamer.png"},
    {IDR_LOGIN_DEFAULT_USER_94, IDS_LOGIN_DEFAULT_USER_DESC_94, Eligibility::kEligible, "material_design/avatar_bookworm.png"},
    {IDR_LOGIN_DEFAULT_USER_95, IDS_LOGIN_DEFAULT_USER_DESC_95, Eligibility::kEligible, "material_design/avatar_biking.png"},
    {IDR_LOGIN_DEFAULT_USER_96, IDS_LOGIN_DEFAULT_USER_DESC_96, Eligibility::kEligible, "material_design/avatar_person_in_snow.png"},
    {IDR_LOGIN_DEFAULT_USER_97, IDS_LOGIN_DEFAULT_USER_DESC_97, Eligibility::kEligible, "material_design/avatar_person_with_megaphone.png"},
};
// clang-format on

// Indexes of the current set of default images in the order that will display
// in the personalization settings page. This list should contain all the
// indexes of egligible default images listed above.
// clang-format off
constexpr int kCurrentImageIndexes[] = {
    // Material design avatars.
    83,
    84,
    85,
    86,
    87,
    88,
    89,
    90,
    91,
    92,
    93,
    94,
    95,
    96,
    97,
    // Third set of images.
    48,
    49,
    50,
    51,
    52,
    53,
    54,
    55,
    56,
    57,
    58,
    59,
    60,
    61,
    62,
    63,
    64,
    65,
    71,
    72,
    73,
    74,
    75,
    76,
    77,
    78,
    79,
    80,
    81,
    82,
};
// clang-format on

// Compile time check that make sure the current default images are the set of
// all the eligible default images.
constexpr bool ValidateCurrentImageIndexes() {
  int num_eligible_images = 0;
  for (const auto info : kDefaultImageInfo) {
    if (info.eligibility == Eligibility::kEligible)
      num_eligible_images++;
  }
  if (num_eligible_images != std::size(kCurrentImageIndexes))
    return false;

  for (const int index : kCurrentImageIndexes) {
    if (kDefaultImageInfo[index].eligibility != Eligibility::kEligible)
      return false;
    if (kDefaultImageInfo[index].description_message_id == 0) {
      // All current and new images must have a description.
      return false;
    }
  }
  return true;
}

static_assert(ValidateCurrentImageIndexes(),
              "kCurrentImageIndexes should contain all the indexes of "
              "egligible default images listed in kDefaultImageInfo.");

// Source info ids of default user images.
struct DefaultImageSourceInfoIds {
  // Message IDs of author info.
  const int author_id;

  // Message IDs of website info.
  const int website_id;
};

// Source info of (deprecated) default user images.
const DefaultImageSourceInfoIds kDefaultImageSourceInfoIds[] = {
    {IDS_LOGIN_DEFAULT_USER_AUTHOR, IDS_LOGIN_DEFAULT_USER_WEBSITE},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_1, IDS_LOGIN_DEFAULT_USER_WEBSITE_1},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_2, IDS_LOGIN_DEFAULT_USER_WEBSITE_2},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_3, IDS_LOGIN_DEFAULT_USER_WEBSITE_3},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_4, IDS_LOGIN_DEFAULT_USER_WEBSITE_4},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_5, IDS_LOGIN_DEFAULT_USER_WEBSITE_5},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_6, IDS_LOGIN_DEFAULT_USER_WEBSITE_6},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_7, IDS_LOGIN_DEFAULT_USER_WEBSITE_7},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_8, IDS_LOGIN_DEFAULT_USER_WEBSITE_8},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_9, IDS_LOGIN_DEFAULT_USER_WEBSITE_9},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_10, IDS_LOGIN_DEFAULT_USER_WEBSITE_10},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_11, IDS_LOGIN_DEFAULT_USER_WEBSITE_11},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_12, IDS_LOGIN_DEFAULT_USER_WEBSITE_12},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_13, IDS_LOGIN_DEFAULT_USER_WEBSITE_13},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_14, IDS_LOGIN_DEFAULT_USER_WEBSITE_14},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_15, IDS_LOGIN_DEFAULT_USER_WEBSITE_15},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_16, IDS_LOGIN_DEFAULT_USER_WEBSITE_16},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_17, IDS_LOGIN_DEFAULT_USER_WEBSITE_17},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_18, IDS_LOGIN_DEFAULT_USER_WEBSITE_18},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_19, IDS_LOGIN_DEFAULT_USER_WEBSITE_19},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_20, IDS_LOGIN_DEFAULT_USER_WEBSITE_20},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_21, IDS_LOGIN_DEFAULT_USER_WEBSITE_21},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_22, IDS_LOGIN_DEFAULT_USER_WEBSITE_22},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_23, IDS_LOGIN_DEFAULT_USER_WEBSITE_23},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_24, IDS_LOGIN_DEFAULT_USER_WEBSITE_24},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_25, IDS_LOGIN_DEFAULT_USER_WEBSITE_25},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_26, IDS_LOGIN_DEFAULT_USER_WEBSITE_26},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_27, IDS_LOGIN_DEFAULT_USER_WEBSITE_27},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_28, IDS_LOGIN_DEFAULT_USER_WEBSITE_28},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_29, IDS_LOGIN_DEFAULT_USER_WEBSITE_29},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_30, IDS_LOGIN_DEFAULT_USER_WEBSITE_30},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_31, IDS_LOGIN_DEFAULT_USER_WEBSITE_31},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_32, IDS_LOGIN_DEFAULT_USER_WEBSITE_32},
    {IDS_LOGIN_DEFAULT_USER_AUTHOR_33, IDS_LOGIN_DEFAULT_USER_WEBSITE_33},
};

constexpr char kDefaultUrlPrefix[] = "chrome://theme/IDR_LOGIN_DEFAULT_USER_";
constexpr char kZeroDefaultUrl[] = "chrome://theme/IDR_LOGIN_DEFAULT_USER";
constexpr char kGstaticImagePrefix[] =
    "https://www.gstatic.com/chromecast/home/chromeos/avatars/";
constexpr char k100PercentPrefix[] = "default_100_percent/";
constexpr char k200PercentPrefix[] = "default_200_percent/";

const std::string GetUrlPrefixForScaleFactor(
    ui::ResourceScaleFactor scale_factor) {
  switch (scale_factor) {
    case ui::kScaleFactorNone:
    case ui::k100Percent:
      return k100PercentPrefix;
    case ui::k200Percent:
      return k200PercentPrefix;
    case ui::k300Percent:
    case ui::NUM_SCALE_FACTORS:
      NOTIMPLEMENTED();
      return k100PercentPrefix;
  }
}

ui::ResourceScaleFactor GetMaximumScaleFactorForDefaultImage(int index) {
  if (index <= kLastLegacyImageIndex)
    return ui::k100Percent;
  else
    return ui::k200Percent;
}

}  // namespace

const int kDefaultImagesCount = std::size(kDefaultImageInfo);

const int kFirstDefaultImageIndex = 48;

const int kLastLegacyImageIndex = 33;

// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
// The order and the values of these constants are important for histograms
// of different Chrome OS versions to be merged smoothly.
const int kHistogramImageFromCamera = 0;
const int kHistogramImageExternal = 1;
const int kHistogramImageFromProfile = 2;
// The special images max count is used to reserve a histogram range (0-9) for
// special images. Default images will have their histogram value starting
// at 10. Check ChromeOSUserImageId in tools/metrics/histograms/enums.xml to see
// how these values are mapped.
const int kHistogramSpecialImagesMaxCount = 10;
const int kHistogramImagesCount =
    kDefaultImagesCount + kHistogramSpecialImagesMaxCount;

ui::ResourceScaleFactor GetAdjustedScaleFactorForDefaultImage(
    int index,
    ui::ResourceScaleFactor scale_factor) {
  ui::ResourceScaleFactor max_scale_factor =
      GetMaximumScaleFactorForDefaultImage(index);
  if (max_scale_factor == ui::k100Percent)
    return max_scale_factor;

  return scale_factor;
}

GURL GetDefaultImageUrl(
    int index,
    ui::ResourceScaleFactor scale_factor /*= ui::k200Percent*/) {
  DCHECK(index >= 0 && index < kDefaultImagesCount);

  if (ash::features::IsAvatarsCloudMigrationEnabled()) {
    ui::ResourceScaleFactor adjusted_scale_factor =
        GetAdjustedScaleFactorForDefaultImage(index, scale_factor);
    auto scale_factor_prefix =
        GetUrlPrefixForScaleFactor(adjusted_scale_factor);

    return GURL(base::StrCat({kGstaticImagePrefix, scale_factor_prefix,
                              kDefaultImageInfo[index].path}));
  }

  if (index == 0)
    return GURL(kZeroDefaultUrl);
  return GURL(base::StringPrintf("%s%d", kDefaultUrlPrefix, index));
}

// DEPRECATED: after the full migration of the avatar images to cloud,
// this function should be removed since default images will no longer
// be available in device resources.
const gfx::ImageSkia& GetDefaultImageDeprecated(int index) {
  DCHECK(index >= 0 && index < kDefaultImagesCount);
  return *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
      kDefaultImageInfo[index].resource_id);
}

int GetDefaultImageResourceId(int index) {
  return kDefaultImageInfo[index].resource_id;
}

int GetRandomDefaultImageIndex() {
  return kCurrentImageIndexes[base::RandInt(
      0, std::size(kCurrentImageIndexes) - 1)];
}

bool IsValidIndex(int index) {
  return index >= 0 && index < kDefaultImagesCount;
}

bool IsInCurrentImageSet(int index) {
  return IsValidIndex(index) &&
         kDefaultImageInfo[index].eligibility == Eligibility::kEligible;
}

DefaultUserImage GetDefaultUserImage(
    int index,
    ui::ResourceScaleFactor scale_factor /*= ui::k200Percent*/) {
  DCHECK(IsValidIndex(index));
  int description_message_id = kDefaultImageInfo[index].description_message_id;
  std::u16string title = description_message_id
                             ? l10n_util::GetStringUTF16(description_message_id)
                             : std::u16string();

  return {index, std::move(title),
          default_user_image::GetDefaultImageUrl(index, scale_factor),
          GetDeprecatedDefaultImageSourceInfo(index)};
}

std::vector<DefaultUserImage> GetCurrentImageSet() {
  std::vector<DefaultUserImage> result;
  for (int index : kCurrentImageIndexes)
    result.push_back(GetDefaultUserImage(index));
  return result;
}

base::Value::List GetCurrentImageSetAsListValue() {
  base::Value::List image_urls;
  for (auto& user_image : GetCurrentImageSet()) {
    base::Value::Dict image_data;
    image_data.Set("index", user_image.index);
    image_data.Set("title", std::move(user_image.title));
    image_data.Set("url", user_image.url.spec());
    image_urls.Append(std::move(image_data));
  }
  return image_urls;
}

absl::optional<DeprecatedSourceInfo> GetDeprecatedDefaultImageSourceInfo(
    size_t index) {
  if (index >= std::size(kDefaultImageSourceInfoIds))
    return absl::nullopt;

  const auto& source_info_ids = kDefaultImageSourceInfoIds[index];
  return DeprecatedSourceInfo(
      l10n_util::GetStringUTF16(source_info_ids.author_id),
      GURL(l10n_util::GetStringUTF16(source_info_ids.website_id)));
}

}  // namespace default_user_image
}  // namespace ash


text:
package org.deeplearning4j.spark.ml.impl;

import org.apache.commons.io.FileUtils;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.ml.Pipeline;
import org.apache.spark.ml.PipelineStage;
import org.apache.spark.ml.feature.VectorAssembler;
import org.apache.spark.sql.SQLContext;
import org.deeplearning4j.nn.api.OptimizationAlgorithm;
import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.layers.OutputLayer;
import org.deeplearning4j.nn.conf.layers.RBM;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.spark.impl.paramavg.ParameterAveragingTrainingMaster;
import org.deeplearning4j.spark.ml.utils.DatasetFacade;
import org.deeplearning4j.spark.ml.utils.ParamSerializer;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.nd4j.linalg.lossfunctions.LossFunctions;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class AutoEncoderNetworkTest {

    private SparkConf sparkConf = new SparkConf().setAppName("testing").setMaster("local[4]");
    private JavaSparkContext sparkContext = new JavaSparkContext(sparkConf);
    private SQLContext sqlContext = new SQLContext(sparkContext);

    @Test
    public void testNetwork() {
        DatasetFacade df = DatasetFacade.dataRows(sqlContext.read().json("src/test/resources/autoencoders"));
        Pipeline p = new Pipeline().setStages(new PipelineStage[] {
                        getAssembler(new String[] {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"}, "features")});
        DatasetFacade part2 = DatasetFacade.dataRows(p.fit(df.get()).transform(df.get()).select("features"));

        AutoEncoder sparkDl4jNetwork = new AutoEncoder().setInputCol("features").setOutputCol("auto_encoded")
                        .setCompressedLayer(2).setTrainingMaster(new ParamHelper())
                        .setMultiLayerConfiguration(getNNConfiguration());

        AutoEncoderModel sm = sparkDl4jNetwork.fit(part2.get());
        MultiLayerNetwork mln = sm.getNetwork();
        Assert.assertNotNull(mln);
    }

    @Test
    public void testAutoencoderSave() throws IOException {
        DatasetFacade df = DatasetFacade.dataRows(sqlContext.read().json("src/test/resources/autoencoders"));
        Pipeline p = new Pipeline().setStages(new PipelineStage[] {
                        getAssembler(new String[] {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"}, "features")});
        DatasetFacade part2 = DatasetFacade.dataRows(p.fit(df.get()).transform(df.get()).select("features"));

        AutoEncoder sparkDl4jNetwork = new AutoEncoder().setInputCol("features").setOutputCol("auto_encoded")
                        .setCompressedLayer(2).setTrainingMaster(new ParamHelper())
                        .setMultiLayerConfiguration(getNNConfiguration());

        AutoEncoderModel sm = sparkDl4jNetwork.fit(part2.get());

        String fileName = UUID.randomUUID().toString();
        sm.write().save(fileName);
        AutoEncoderModel spdm = AutoEncoderModel.load(fileName);
        Assert.assertNotNull(spdm);
        Assert.assertNotNull(spdm.transform(part2.get()));

        File file = new File(fileName);
        File file2 = new File(fileName + "_metadata");
        FileUtils.deleteDirectory(file);
        FileUtils.deleteDirectory(file2);
    }

    @After
    public void closeIt() {
        sparkContext.close();
    }

    private MultiLayerConfiguration getNNConfiguration() {
        return new NeuralNetConfiguration.Builder().seed(12345).iterations(5).learningRate(.1)
                        .optimizationAlgo(OptimizationAlgorithm.LINE_GRADIENT_DESCENT).list()
                        .layer(0, new RBM.Builder().nIn(10).nOut(8)
                                        .lossFunction(LossFunctions.LossFunction.KL_DIVERGENCE).build())
                        .layer(1, new RBM.Builder().nIn(8).nOut(5)
                                        .lossFunction(LossFunctions.LossFunction.KL_DIVERGENCE).build())
                        .layer(2, new RBM.Builder().nIn(5).nOut(2)
                                        .lossFunction(LossFunctions.LossFunction.KL_DIVERGENCE).build())
                        .layer(3, new RBM.Builder().nIn(2).nOut(5)
                                        .lossFunction(LossFunctions.LossFunction.KL_DIVERGENCE).build())
                        .layer(4, new RBM.Builder().nIn(5).nOut(8)
                                        .lossFunction(LossFunctions.LossFunction.KL_DIVERGENCE).build()) //decoding starts
                        .layer(5, new OutputLayer.Builder(LossFunctions.LossFunction.MSE).activation("sigmoid").nIn(8)
                                        .nOut(10).build())
                        .pretrain(true).backprop(true).build();
    }

    private static VectorAssembler getAssembler(String[] input, String output) {
        return new VectorAssembler().setInputCols(input).setOutputCol(output);
    }

    static public class ParamHelper implements ParamSerializer {

        public ParameterAveragingTrainingMaster apply() {
            return new ParameterAveragingTrainingMaster.Builder(3).averagingFrequency(2).workerPrefetchNumBatches(2)
                            .batchSizePerWorker(2).build();
        }
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>

  			<canvas id="myCanvas" width="1000" height="500" style="padding:1px;border:1px solid black"></canvas>
  			Width: <input id="lineWidth" type="number" max="64" min="1" value="3" onchange="changeLineWidth()">
  			Red: <input id="lineRed" type="number" max="255" min="0" value="0" onchange="changeLineColor()">
  			Green: <input id="lineGreen" type="number" max="255" min="0" value="0" onchange="changeLineColor()">
  			Blue: <input id="lineBlue" type="number" max="255" min="0" value="0" onchange="changeLineColor()">


text:
void DifusionCotaSuperior(int *U, bool *nueva_U)
{
    difundir_cs_local = *nueva_U;
    if (difundir_cs_local && !pendiente_retorno_cs)
    {
        // Enviar valor local de cs al proceso (id+1)%P;
        MPI_Send(U, 1, MPI_INT, siguiente, id, COMM_DIFUSION_COTA);
        pendiente_retorno_cs = true;
        difundir_cs_local = false;
    }

    // Sondear si hay mensajes de cota superior pendientes
    MPI_Iprobe(anterior, MPI_ANY_TAG, COMM_DIFUSION_COTA, &hay_mensajes, &status);

    while (hay_mensajes)   // mientras tengamos mensajes
    {
        // Recibir mensaje con valor de cota superior desde el proceso (id-1+P)%P
        int cotaSup;
        MPI_Recv(&cotaSup, 1, MPI_INT, anterior, status.MPI_TAG, COMM_DIFUSION_COTA, &status);

        // Actualizar valor local de cota superior
        if (cotaSup < *U){
            *U = cotaSup;
            *nueva_U = true;
        }

        if (status.MPI_SOURCE == id && difundir_cs_local){
            // Enviar valor local de cs al proceso (id+1)%P;
            MPI_Send(U, 1, MPI_INT, siguiente, id, COMM_DIFUSION_COTA);
            pendiente_retorno_cs = true;
            difundir_cs_local = false;
        }
        else if (status.MPI_SOURCE == id && !difundir_cs_local)
            pendiente_retorno_cs = false;
        else    // origen mensaje = otro proceso
            // reenviar mensaje al proceso (id+1)%p;
            MPI_Send(U, 1, MPI_INT, siguiente, status.MPI_TAG, COMM_DIFUSION_COTA);

        // Sondear si hay mensajes de cota superior pendientes
        MPI_Iprobe(anterior, MPI_ANY_TAG, COMM_DIFUSION_COTA, &hay_mensajes, &status);
    }
}


text:
/* =Common Rules for all fields.
----------------------------------------------- */
.form-table td.at-field{ border: 1px solid #DDD; padding: 10px 10px 20px; margin: 0px; font-family: "HelveticaNeue-Light","Helvetica Neue Light","Helvetica Neue", Helvetica, Arial, sans-serif; }
.at-label { margin: 0 !important; padding: 5px 0 0 0;
            font: 20px/31px "HelveticaNeue-Light","Helvetica Neue Light","Helvetica Neue", Helvetica, Arial, sans-serif;
            text-shadow: rgba(255, 255, 255, 1) 0 1px 0; width: auto; }
.at-radio-label{ padding-right: 10px; }
.at-file-upload-label{ clear: both; margin: 5px 0px 5px 1px; }

/* =Form Fields
----------------------------------------------- */
.postbox .at-field input,
.postbox .at-field textarea { padding: 5px; line-height: 18px; }
.postbox .at-field input.at-radio{}
.postbox .at-field input.at-color{ border: 0px; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; margin-right: 10px; min-width: 100px; }
.at-field input:focus,
.at-field textarea:focus { background: #fffff8; }
#wpcontent select.at-select { min-height: 30px !important; padding: 5px; display: block; min-width: 200px; }
.at-field .desc-field { color: #AAA; font-style: italic; margin: 5px 0 0 3px !important; font-size: 13px; }
 .desc-field { background-color: #D9EDF7;  border: 1px solid #BCE8F1; color: #3A87AD; padding: 8px 35px 8px 14px;border-radius: 4px 4px 4px 4px;
    margin-bottom: 20px;
    padding: 8px 35px 8px 14px;
    text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);}
.at-field .wp_themeSkin table.mceLayout{ border: 1px solid #DFDFDF; }
#post-body .at-field .wp_themeSkin .mceStatusbar a.mceResize{ top: -25px; }

/* =Uploaded Images
----------------------------------------------- */
.at-images li { margin: 5px 10px 0px 0; float: left; width: 150px; height: 150px; text-align: center; border: 3px solid #ccc; cursor: move; position: relative; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; }
.at-images img { width: 150px; height: 150px; }
.at-images a { position: absolute; top: -12px; right: -12px; color: #fff;  font-weight: bold; padding: 5px; }
.at-images .at-delete-file img{ width: 16px; height: 16px; }

/* =Upload Button
----------------------------------------------- */
.at-upload-button { float: left; clear: both; margin-top: 10px; }
.at-add-file { float: left; clear: both; margin-top: 10px; }

/* =Time Picker
----------------------------------------------- */
.ui-timepicker-div { font-size: 0.9em; }
.ui-timepicker-div .ui-widget-header { margin-bottom: 8px; }
.ui-timepicker-div dl { text-align: left; }
.ui-timepicker-div dl dt { height: 25px; }
.ui-timepicker-div dl dd { margin: -25px 0 10px 65px; }
.ui-timepicker-div td { font-size: 90%; }
#ui-datepicker-div{display: none;}

/* =Repater Block
----------------------------------------------- */
/* inline */
.at-inline label{font-size: 12px !important;}
.at-inline textarea{height: 130px;width: 200px;}

/* =panel style
----------------------------------------------- */
.wrap{background: none repeat scroll 0 0 #EAEEF3; border: 1px solid #CCCCCC; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2); margin: 17px 0 40px 10px;width: 800px;border-radius: 6px 6px 6px 6px;}
.header_wrap{border-radius: 6px 6px 6px 6px;background: -moz-linear-gradient(center top , #FEFEFE, #E9EAEE) repeat scroll 0 0 transparent;  padding: 5px 20px 10px;}
.footer_wrap{border-radius: 6px 6px 6px 6px;background: -moz-linear-gradient(center top , #E9EAEE,#FEFEFE) repeat scroll 0 0 transparent;  padding: 5px 20px 10px;}
.panel_menu{float: left;width: 160px;}
.clearboth{clear: both;}
.f_row{border-bottom: 1px solid #F9F9F9;}
.sections{background: none repeat scroll 0 0 #FFFFFF;float: left;margin-top: 1px;min-height: 520px;padding-bottom: 10px;width: 639px;}
.field{padding: 10px;border-bottom: 1px solid #E9EAEE;}
.sections textarea{background: -moz-linear-gradient(center top , #F9F9F9, #FFFFFF) repeat scroll 0 0 transparent;color: #333333;font-size: 12px;height: 175px;line-height: 1.5em;padding: 4px;    width: 390px;}
.sections label{clear: both;display: block;font-size: 12px;font-weight: 700;margin: 0 0 10px;width: 100%;}
.setingstab{min-height: 500px;}
.sections input[type="text"], .sections input[type="password"], .sections input[type="file"], .sections select {background: -moz-linear-gradient(center top , #F9F9F9, #FFFFFF) repeat scroll 0 0 transparent;color: #333333;font-size: 12px;line-height: 1em;padding: 4px;}
.nav_tab_link{ border-color: #DFDFDF #DFDFDF #FFFFFF;border-radius: 3px 3px 0 0;border-style: solid;border-width: 1px 1px 0;color: #AAAAAA;display: inline-block;font-size: 12px;line-height: 16px; margin: 0 6px -1px 0; padding: 4px 14px 6px;text-decoration: none;text-shadow: 0 1px 0 #FFFFFF;}
.nav_tab_link{border: 0 none;border-radius: 0 0 0 0;clear: both;color: #444444;display: block;padding: 10px 20px;width: 100%;}
.nav_tab_link:hover{background: none repeat scroll 0 0 #FFFFFF; border-right: 1px solid #FFFFFF;box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);color: #666666;font-weight: bold;}
.description{color: #999999;display: block;float: right;font-size: 11px;margin-top: -2px;width: 200px;}
.active_tab{background: none repeat scroll 0 0 #FFFFFF; border-right: 1px solid #FFFFFF;box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);color: #666666;font-weight: bold;}
.editorcontainer { -webkit-border-radius:6px; border:1px solid #DEDEDE;}
.btn {
    -moz-border-bottom-colors: none;
    -moz-border-image: none;
    -moz-border-left-colors: none;
    -moz-border-right-colors: none;
    -moz-border-top-colors: none;
    background-color: #FAFAFA;
    background-image: -moz-linear-gradient(center top , #FFFFFF, #FFFFFF 25%, #E6E6E6);
    background-repeat: no-repeat;
    border-color: #CCCCCC #CCCCCC #BBBBBB;
    border-radius: 4px 4px 4px 4px;
    border-style: solid;
    border-width: 1px;
    box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2) inset, 0 1px 2px rgba(0, 0, 0, 0.05);
    color: #333333;
    cursor: pointer;
    display: inline-block;
    font-size: 13px;
    line-height: 18px;
    padding: 4px 10px;
    text-align: center;
    text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
}

.btn , .btn-info, .btn-info:hover , .btn-primary, .btn-primary:hover , .btn-warning, .btn-warning:hover{
    color: #FFFFFF !important;
    text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
}
.btn-info {
    background-color: #49AFCD !important;
    background-image: -moz-linear-gradient(center top , #5BC0DE, #2F96B4);
    background-repeat: repeat-x;
    border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
    color: #FFFFFF !important;
}
.btn-primary {
    background-color: #006DCC !important;
    background-image: -moz-linear-gradient(center top , #0088CC, #0044CC);
    background-repeat: repeat-x;
    border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
    color: #FFFFFF !important;
}
.btn-warning {
    background-color: #FAA732;
    background-image: -moz-linear-gradient(center top , #FBB450, #F89406);
    background-repeat: repeat-x;
    border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
    color: #FFFFFF !important;
}

/* alerts */
.alert {
    background-color: #FCF8E3;
    border: 1px solid #FBEED5;
    border-radius: 4px 4px 4px 4px;
    margin-bottom: 20px;
    padding: 8px 35px 8px 14px;
    text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
}

.alert, .alert-heading {
    color: #C09853;
}
.alert h4 {
    font-size: 17px;
    margin: 0;
}
.alert-success {
    background-color: #DFF0D8;
    border-color: #D6E9C6;
}

.alert-success, .alert-success .alert-heading {
    color: #468847;
}
.alert-danger, .alert-error {
    background-color: #F2DEDE;
    border-color: #EED3D7;
    color: #B94A48;
}
.alert .close {
    line-height: 20px;
    position: relative;
    right: -21px;
    top: -2px;
}
button.close {
    background: none repeat scroll 0 0 transparent;
    border: 0 none;
    cursor: pointer;
    padding: 0;
}
.close {
    color: #000000;
    float: right;
    font-size: 20px;
    font-weight: bold;
    line-height: 20px;
    opacity: 0.2;
    text-shadow: 0 1px 0 #FFFFFF;
}

/* Sort */
.widget-sort{
    background-color: #F5F5F5;
    background-image: -moz-linear-gradient(center top , #F9F9F9, #F5F5F5);
    border: 1px solid #DFDFDF;
    border-radius: 3px 3px 3px 3px;
    box-shadow: 0 1px 0 #FFFFFF inset;
    padding: 4px;
    text-align: center;
    width: 65%;
}
.ui-state-highlight{
    background-color: #FFFFE0;
    border-color: #E6DB55;
    border-radius: 3px 3px 3px 3px;
    box-shadow: 0 1px 0 #FFFFFF inset;
    padding: 14px;
    width: 60%;
}
.ui-sortable li{cursor: move;}
.ui-sortable .at-repater-block{cursor: move;}

/* Typo field iris color picker */
.wp-picker-container{height: 20px;}
/* issue #17 number 7 */
div.iris-picker{z-index: 100;}

/* Select 2 typo  field Fix*/
.at-typography-size{width: 11%;}
.at-typography-face{width: 30%;}
.hidden{display: none;}


text:
<p id="blischak.j" data-toggle="tooltip" title="">
    John Blischak is a graduate student at
    the University of Chicago. His research focuses on the
    transcriptional response of human macrophages to infection
    by Mycobacterium tuberculosis. He greatly benefited from
    attending a Software Carpentry bootcamp and enjoys passing along
    these useful skills to other scientists.

    Maintainer: Programming with R


text:
require 'singleton'

class Preferences
  include Singleton

  # Save any unsaved changes to disk.
  def save
    Preferences.user_defaults.synchronize
  end

  class << self
    # A shortcut method for access to <tt>OSX::NSUserDefaults.standardUserDefaults</tt>.
    def user_defaults
      OSX::NSUserDefaults.standardUserDefaults
    end

    # A hash of all default values for the user defaults
    def default_values
      @default_values ||= {}
    end

    # Registers the default values with NSUserDefaults.standardUserDefaults
    # Call this after all your Preferences code has been loaded, for instance
    # in <tt>awakeFromNib</tt> of your ApplicationController.
    def register_default_values!
      user_defaults.registerDefaults(default_values)
    end
  end

  class Namespace
    include Singleton

    class << self
      # Defines a reader method for the Namespace subclass on the Preferences instance.
      #
      # Defines a class <tt>Preferences::Keyword</tt> and <tt>preferences.keyword</tt>:
      #
      #   class Preferences
      #     class Keyword < Namespace
      #       defaults_accessor :an_option, true
      #     end
      #   end
      def inherited(klass)
        super
        method = klass.name.split('::').last.scan(/[A-Z][a-z]*/).map { |x| x.downcase }.join('_')
        Preferences.class_eval "def #{method}; #{klass.name}.instance end", __FILE__, __LINE__
      end

      # The key in the preferences that represents the section class.
      #
      #   Preferences::General.section_defaults_key # => "Preferences.General"
      def section_defaults_key
        @section_defaults_key ||= name.gsub('::', '.')
      end

      # Defines a reader and writer method for a user defaults key for this section.
      #
      # If the preference is a boolean value, inflected from the default value,
      # a query method is also defined.
      #
      #   # Defines #confirm_quit, #confirm_quit=, and #confirm_quit? It's default value is <tt>true</tt>.
      #   defaults_accessor :confirm_quit, true
      def defaults_accessor(name, default_value)
        key_path = "#{section_defaults_key}.#{name}"
        Preferences.default_values[key_path] = default_value

        class_eval do
          define_method(name) do
            Preferences.user_defaults[key_path].to_ruby
          end

          define_method("#{name}=") do |value|
            Preferences.user_defaults[key_path] = value
          end

          if default_value == true || default_value == false
            alias_method "#{name}?", name
          end
        end

        key_path
      end

      # Besides defining a reader and writer method via defaults_accessor,
      # it also defines a reader method which returns an array of strings
      # wrapped in KVO compatible string wrappers.
      #
      # The name of the wrapper class is defined by <tt>wrapper_class_name</tt>
      # and can be used as the `Class Name' of a NSArrayController.
      # The wrapper exposes `string' as a KVC accessor to which a NSTableColumn can be bound.
      #
      #   # Defines #highlight_words, #highlight_words=, and #highlight_words_wrapped
      #   string_array_defaults_accessor :highlight_words, [], 'HighlightWordWrapper'
      def string_array_defaults_accessor(name, default_value, wrapper_class_name)
        wrapper = eval("class ::#{wrapper_class_name} < StringArrayWrapper; self end")
        wrapper.key_path = defaults_accessor(name, default_value)

        class_eval do
          define_method("#{name}_wrapped") do
            ary = []
            send(name).each_with_index { |string, index| ary << wrapper.alloc.initWithString_index(string, index) }
            ary
          end
        end
      end
    end

    # Register an observer for a key.
    #
    # Include the <tt>Preferences::KVOCallbackHelper</tt> module in your class
    # to get rubyish callback handling, instead of handling it yourself by defining
    # the observeValueForKeyPath_ofObject_change_context method.
    #
    #   class PreferencesController < OSX::NSWindowController
    #     include Preferences::KVOCallbackHelper
    #
    #     def init
    #       if super_init
    #         preferences.keyword.observe(:highlight_words, self)
    #         self
    #       end
    #     end
    #
    #     def highlight_words_changed(new_value)
    #       # Do stuff because a new value has been set.
    #     end
    #   end
    def observe(name, observer)
      key_path = "values.#{self.class.section_defaults_key}.#{name}"
      OSX::NSUserDefaultsController.sharedUserDefaultsController.
        addObserver_forKeyPath_options_context(observer, key_path, OSX::NSKeyValueObservingOptionNew, nil)
    end
  end

  class StringArrayWrapper < OSX::NSObject
    class << self
      attr_accessor :key_path

      def array
        Preferences.user_defaults[key_path].to_ruby
      end

      def array=(array)
        Preferences.user_defaults[key_path] = array
      end

      def destroy(klass, new_wrappers)
        # Set the new correct indices on the remaining wrappers
        new_wrappers.each_with_index do |wrapper, new_index|
          wrapper.index = new_index
        end

        # Assign the new result array of strings
        klass.array = new_wrappers.map { |wrapper| wrapper.string }
      end
    end

    kvc_accessor :string
    attr_accessor :index

    def initWithString_index(string, index)
      if init
        @string, @index = string, index
        self
      end
    end

    def array
      self.class.array
    end

    def array=(array)
      self.class.array = array
    end

    def string=(string)
      @string = string
      set_string!
    end

    def set_string!
      if @index
        ary = array
        ary[@index] = string
        self.array = ary
      else
        ary = array
        ary << @string
        self.array = ary
        @index = ary.length - 1
      end
    end

    def inspect
      "#<#{self.class.name}:#{object_id} string=\"#{@string}\" key_path=\"#{self.class.key_path}\" index=\"#{@index}\">"
    end
  end

  # Extend your class with this module to get access to a few KVC accessor helper methods.
  module AccessorHelpers
    # Defines a kvc_accessor which reads and writes
    # to the specified preferences path (<tt>path_to_eval_to_object</tt>).
    #
    # This is useful for binding, for instance, UI elements
    # to an array in the NSUserDefaults which is normally immutable.
    #
    #   class PreferencesController < OSX::NSWindowController
    #     defaults_kvc_accessor :an_array_of_dictionaries, 'preferences.keyword.url_mappings'
    #   end
    #
    # Binding a NSArrayController to File's Owner with key path: <tt>an_array_of_dictionaries</tt>,
    # will perform the following read/write actions on the NSUserDefaults:
    #
    #   preferences_controller.valueForKey('an_array_of_dictionaries') # => [{'key' => 'value 1'}, {'key' => 'value 2'}]
    #   preferences_controller.setValueForKey([{'key' => 'value 1'}], 'an_array_of_dictionaries')
    #   preferences_controller.valueForKey('an_array_of_dictionaries') # => [{'key' => 'value 1'}]
    def defaults_kvc_accessor(name, path_to_eval_to_object)
      kvc_accessor(name)

      class_eval %{
        def #{name}
          @#{name} ||= #{path_to_eval_to_object}
        end

        def #{name}=(new_defaults)
          #{path_to_eval_to_object} = @#{name} = new_defaults
        end
      }, __FILE__, __LINE__
    end

    # Defines read and write KVC accessors like defaults_kvc_accessor does,
    # but is used specifically for defaults defined with Namespace#string_array_defaults_accessor.
    #
    #   class PreferencesController < OSX::NSWindowController
    #     defualts_string_array_kvc_accessor :an_array_of_strings, 'preferences.keyword.highlight_words'
    #   end
    #
    # See Namespace#string_array_defaults_accessor for more info.
    def defualts_string_array_kvc_accessor(name, path_to_eval_to_object)
      defaults_kvc_accessor(name, "#{path_to_eval_to_object}_wrapped")

      class_eval %{
        def #{name}=(new_wrappers)
          if new_wrappers.length < #{name}.length
            Preferences::StringArrayWrapper.destroy(#{name}.first.class, new_wrappers)
          end
          @#{name} = new_wrappers
        end
      }, __FILE__, __LINE__
    end
  end

  module KVOCallbackHelper
    # We need to actually define the method on the class because otherwise the method is not
    # resolved at runtime, probably a bug in RubyCocoa.
    def self.included(klass)
      klass.class_eval do
        def observeValueForKeyPath_ofObject_change_context(key_path, observed, change, context)
          value_key_path = key_path.sub(/^values\./, '')
          callback_method = "#{key_path.split('.').last}_changed"
          send(callback_method, Preferences.user_defaults[value_key_path].to_ruby)
        end
      end
    end
  end
end

module Kernel
  # A shortcut method for easy access anywhere to the shared user defaults.
  def preferences
    Preferences.instance
  end
end


text:
#ifndef _STENCIL_H_
#define _STENCIL_H_

#include "Parameters.h"

/** Stencil class
 *
 * Abstrat class for the definition of stencils and operations on the grids
 */
template<class FlowField>
class FieldStencil {

    protected:

        const Parameters & _parameters;  //! Reference to the parameters

    public:

        FieldStencil ( const Parameters & parameters ): _parameters(parameters){}
        virtual ~FieldStencil(){}

        /** Performs the operation in 2D in a given position
         * @param flowField Flow field data
         * @param parameters Parameters of the problem
         * @param i Position in the x direction
         * @param j Position in the y direction
         */
        virtual void apply ( FlowField & flowField, int i, int j) = 0;

        /** Performs the operation in 3D in a given position
         * @param flowField Flow field data
         * @param parameters Parameters of the problem
         * @param i Position in the x direction
         * @param j Position in the y direction
         * @param k Position in the z direction
         */
        virtual void apply ( FlowField & flowField, int i, int j, int k) = 0;

};

/** Interface for operations on the global (or parallel) boundary
 */
template<class FlowField>
class BoundaryStencil {

    protected:

        const Parameters & _parameters;  //! Reference to the parameters

    public:

        BoundaryStencil ( const Parameters & parameters ): _parameters(parameters){}
        virtual ~BoundaryStencil(){}

        /** Represents an operation in the left wall of a 2D domain.
         *
         * @param flowField State of the flow field
         * @param i Index in the x direction
         * @param j Index in the y direction
         */
        virtual void applyLeftWall   (FlowField & flowField, int i, int j) = 0;

        /** Represents an operation in the right wall of a 2D domain.
         *
         * @param flowField State of the flow field
         * @param i Index in the x direction
         * @param j Index in the y direction
         */
        virtual void applyRightWall  (FlowField & flowField, int i, int j) = 0;

        /** Represents an operation in the bottom wall of a 2D domain.
         *
         * @param flowField State of the flow field
         * @param i Index in the x direction
         * @param j Index in the y direction
         */
        virtual void applyBottomWall (FlowField & flowField, int i, int j) = 0;

        /** Represents an operation in the top wall of a 2D domain.
         *
         * @param flowField State of the flow field
         * @param i Index in the x direction
         * @param j Index in the y direction
         */
        virtual void applyTopWall    (FlowField & flowField, int i, int j) = 0;

        /** Represents an operation in the left wall of a 3D domain.
         *
         * @param flowField State of the flow field
         * @param i Index in the x direction
         * @param j Index in the y direction
         * @param k Index in the z direction
         */
        virtual void applyLeftWall   (FlowField & flowField, int i, int j, int k) = 0;

        /** Represents an operation in the right wall of a 3D domain.
         *
         * @param flowField State of the flow field
         * @param i Index in the x direction
         * @param j Index in the y direction
         * @param k Index in the z direction
         */
        virtual void applyRightWall  (FlowField & flowField, int i, int j, int k) = 0;

        /** Represents an operation in the bottom wall of a 3D domain.
         *
         * @param flowField State of the flow field
         * @param i Index in the x direction
         * @param j Index in the y direction
         * @param k Index in the z direction
         */
        virtual void applyBottomWall (FlowField & flowField, int i, int j, int k) = 0;

        /** Represents an operation in the top wall of a 3D domain.
         *
         * @param flowField State of the flow field
         * @param i Index in the x direction
         * @param j Index in the y direction
         * @param k Index in the z direction
         */
        virtual void applyTopWall    (FlowField & flowField, int i, int j, int k) = 0;

        /** Represents an operation in the front wall of a 3D domain.
         *
         * @param flowField State of the flow field
         * @param i Index in the x direction
         * @param j Index in the y direction
         * @param k Index in the z direction
         */
        virtual void applyFrontWall  (FlowField & flowField, int i, int j, int k) = 0;

        /** Represents an operation in the back wall of a 3D domain.
         *
         * @param flowField State of the flow field
         * @param i Index in the x direction
         * @param j Index in the y direction
         * @param k Index in the z direction
         */
        virtual void applyBackWall   (FlowField & flowField, int i, int j, int k) = 0;
};

#endif


text:
import Boom from 'boom';

/** ****************************************
 *
 * Define a basic skeleton for all custom controllers.
 *
 * Extend your controller with this class if want to have shared
 * methods across all your contollers or if you want to initialise
 * code across your controllers (via the `constructor()`)
 *
 ******************************************/
export class BaseController {

  /**
   * Constructor
   *
   * @param {stirng} notFoundMsg [optional]
   */
  constructor(notFoundMsg = '') {
    if (new.target === BaseController) {
      throw Error('BaseController is an abstract class and cannot be instantiated directly');
    }

    this.notFoundMsg = notFoundMsg;
    this.Boom = Boom;

    // Initialise more shared code here ...
  }

  /**
   * Run reply() if response is not undefined.
   * Otherwise reply 404
   *
   * @param  {Function call} Knex call
   * @param  {Function} hapi's reply
   *         Hapi default callback
   */
  async handleRequest(func, reply) {
    try {
      const response = await func;

      if ((Array.isArray(response) && response.length) || response > 0) {
        reply(response);
      }
      else {
        throw Error('Not Found');
      }
    }
    catch (err) {
      reply(this.Boom.notFound(this.notFoundMsg));
    }
  }

  // Extend with shared methods ...
}


text:
package org.apache.druid.segment.serde;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.druid.segment.IndexIO;
import org.apache.druid.segment.column.ValueType;
import org.apache.druid.segment.data.CompressedColumnarLongsSupplier;

import javax.annotation.Nullable;
import java.nio.ByteOrder;

/**
 */
public class LongNumericColumnPartSerde implements ColumnPartSerde
{
  @JsonCreator
  public static LongNumericColumnPartSerde createDeserializer(
      @JsonProperty("byteOrder") ByteOrder byteOrder
  )
  {
    return new LongNumericColumnPartSerde(byteOrder, null);
  }

  private final ByteOrder byteOrder;
  @Nullable
  private final Serializer serializer;

  private LongNumericColumnPartSerde(ByteOrder byteOrder, @Nullable Serializer serializer)
  {
    this.byteOrder = byteOrder;
    this.serializer = serializer;
  }

  @JsonProperty
  public ByteOrder getByteOrder()
  {
    return byteOrder;
  }

  public static SerializerBuilder serializerBuilder()
  {
    return new SerializerBuilder();
  }

  public static class SerializerBuilder
  {
    @Nullable
    private ByteOrder byteOrder = null;
    @Nullable
    private Serializer delegate = null;

    public SerializerBuilder withByteOrder(final ByteOrder byteOrder)
    {
      this.byteOrder = byteOrder;
      return this;
    }

    public SerializerBuilder withDelegate(final Serializer delegate)
    {
      this.delegate = delegate;
      return this;
    }

    public LongNumericColumnPartSerde build()
    {
      return new LongNumericColumnPartSerde(byteOrder, delegate);
    }
  }

  @Nullable
  @Override
  public Serializer getSerializer()
  {
    return serializer;
  }

  @Override
  public Deserializer getDeserializer()
  {
    return (buffer, builder, columnConfig) -> {
      final CompressedColumnarLongsSupplier column = CompressedColumnarLongsSupplier.fromByteBuffer(
          buffer,
          byteOrder
      );
      LongNumericColumnSupplier columnSupplier = new LongNumericColumnSupplier(
          column,
          IndexIO.LEGACY_FACTORY.getBitmapFactory().makeEmptyImmutableBitmap()
      );
      builder.setType(ValueType.LONG)
             .setHasMultipleValues(false)
             .setNumericColumnSupplier(columnSupplier);
    };
  }
}


text:
package edu.berkeley.compbio.ml;

import com.davidsoergel.dsutils.DSArrayUtils;
import com.google.common.base.Function;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.MapMaker;
import com.google.common.collect.Multiset;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 * @author David Soergel
 * @version $Id$
 */
public class MultiClassCrossValidationResults<L extends Comparable> extends CrossValidationResults
	{
	private static final Logger logger = Logger.getLogger(MultiClassCrossValidationResults.class);

	protected int numExamples;
	private final Map<L, Multiset<L>> confusionMatrix;

	// BAD test this class

	// BAD currently we don't include these in the computations...
	// samples that had no actual label, and so should be predicted "unknown"
	private final Multiset<L> confusionRowNull = HashMultiset.create();

	//private Map<L, String> friendlyLabelMap;

	public MultiClassCrossValidationResults()//Map<L, String> friendlyLabelMap)
	{
	confusionMatrix = new MapMaker().makeComputingMap(new Function<L, Multiset<L>>()
	{
	public Multiset<L> apply(final L key)
		{
		return HashMultiset.create();
		}
	});
	//this.friendlyLabelMap = friendlyLabelMap;
	}

	public SortedSet<L> getLabels()
		{
		return new TreeSet<L>(confusionMatrix.keySet());
		}

	public String[] getFriendlyLabels(final Map<L, String> friendlyLabelMap)
		{
		if (friendlyLabelMap == null)
			{
			return null;
			}
		final List<String> result = new ArrayList<String>(confusionMatrix.size());
		for (final L l : getLabels())
			{
			result.add(friendlyLabelMap.get(l));
			}
		return result.toArray(DSArrayUtils.EMPTY_STRING_ARRAY);
		}

	public void sanityCheck()
		{
		int predictionCount = 0;
		for (final Multiset<L> ls : confusionMatrix.values())
			{
			predictionCount += ls.size();
			}
		assert predictionCount == numExamples;  // every example got a prediction (perhaps null)
		}

	public void addSample(final L realValue, final L predictedValue)
		{
		final Multiset<L> confusionRow = realValue == null ? confusionRowNull : confusionMatrix.get(realValue);
		confusionRow.add(predictedValue);
		numExamples++;
		}

	public float accuracy()
		{
		int correct = 0;
		for (final Map.Entry<L, Multiset<L>> entry : confusionMatrix.entrySet())
			{
			correct += entry.getValue().count(entry.getKey());
			}
		return (float) correct / (float) numExamples;
		}

	public float unknown()
		{
		int unknown = 0;
		for (final Map.Entry<L, Multiset<L>> entry : confusionMatrix.entrySet())
			{
			unknown += entry.getValue().count(null);
			}
		return (float) unknown / (float) numExamples;
		}

	public float accuracyGivenClassified()
		{
		int correct = 0;
		int unknown = 0;
		for (final Map.Entry<L, Multiset<L>> entry : confusionMatrix.entrySet())
			{
			correct += entry.getValue().count(entry.getKey());
			unknown += entry.getValue().count(null);
			}
		return (float) correct / ((float) numExamples - (float) unknown);
		}

	public float sensitivity(final L label)
		{
		final Multiset<L> predictionsForLabel = confusionMatrix.get(label);
		final int totalWithRealLabel = predictionsForLabel.size();
		final int truePositives = predictionsForLabel.count(label);
		return (float) truePositives / (float) totalWithRealLabel;
		}

	public float precision(final L label)
		{
		final Multiset<L> predictionsForLabel = confusionMatrix.get(label);

		final int truePositives = predictionsForLabel.count(label);
		final float total = (float) getTotalPredicted(label);
		return total == 0 ? 1f : (float) truePositives / total;
		}

	public float[] getSpecificities()
		{
		final float[] result = new float[confusionMatrix.size()];
		int i = 0;
		for (final L label : getLabels())
			{
			result[i] = specificity(label);
			i++;
			}
		return result;
		}

	public float[] getSensitivities()
		{
		final float[] result = new float[confusionMatrix.size()];
		int i = 0;
		for (final L label : getLabels())
			{
			result[i] = sensitivity(label);
			i++;
			}
		return result;
		}

	public float[] getPrecisions()
		{
		final float[] result = new float[confusionMatrix.size()];
		int i = 0;
		for (final L label : getLabels())
			{
			result[i] = precision(label);
			i++;
			}
		return result;
		}

	public float[] getPredictedCounts()
		{
		final float[] result = new float[confusionMatrix.size()];
		int i = 0;
		for (final L label : getLabels())
			{
			result[i] = getTotalPredicted(label);
			i++;
			}
		return result;
		}

	public float[] getActualCounts()
		{
		final float[] result = new float[confusionMatrix.size()];
		int i = 0;
		for (final L label : getLabels())
			{
			result[i] = getTotalActual(label);
			i++;
			}
		return result;
		}

	public int getCount(L actual, L predicted)
		{
		return confusionMatrix.get(actual).count(predicted);
		}

	public float specificity(final L label)
		{
		// == sensitivity( not label )
		// note "unknown" counts as a negative

		final Multiset<L> predictionsForLabel = confusionMatrix.get(label);

		final int hasLabel = predictionsForLabel.size();
		final int hasLabelRight = predictionsForLabel.count(label);  // true positives

		final int notLabelWrong = getTotalPredicted(label) - hasLabelRight;  // false negatives
		final int notLabel = numExamples - hasLabel;
		final int notLabelRight = notLabel - notLabelWrong;   // true negatives

		if (notLabel == 0)
			{
			return 1.0f;
			}

		return (float) notLabelRight / (float) notLabel;
		}

	public int getTotalPredicted(final L label)

		{
		int totalWithPredictedLabel = 0;

		// PERF if we want precisions for all the labels, it's inefficient to iterate this n times; in practice it doesn't matter though since there are few enough labels
		for (final Map.Entry<L, Multiset<L>> entry : confusionMatrix.entrySet())
			{
			totalWithPredictedLabel += entry.getValue().count(label);
			}
		return totalWithPredictedLabel;
		}

	public int getTotalActual(final L label)
		{
		if (label == null)
			{
			return confusionRowNull.size();
			}
		else
			{
			return confusionMatrix.get(label).size();
			}
		}

	public float classNormalizedSpecificity()
		{
		float sum = 0;
		for (final L label : confusionMatrix.keySet())
			{
			sum += specificity(label);
			}
		return sum / (float) confusionMatrix.size();
		}

	public float classNormalizedSensitivity()
		{
		float sum = 0;
		for (final L label : confusionMatrix.keySet())
			{
			sum += sensitivity(label);
			}
		return sum / (float) confusionMatrix.size();
		}

	public float classNormalizedPrecision()
		{
		float sum = 0;
		for (final L label : confusionMatrix.keySet())
			{
			final float v = precision(label);
			if (!Double.isNaN(v))
				{
				sum += v;
				}
			else
				{
				logger.warn("Label " + label + " did not contribute to precision; " + getTotalPredicted(label)
				            + " predictions");
				}
			}
		return sum / (float) confusionMatrix.size();
		}

	public int numPopulatedRealLabels()
		{
		return confusionMatrix.size();
		}

	public int numPredictedLabels()
		{
		final Set<L> predictedLabels = new HashSet<L>();
		for (final Multiset<L> ls : confusionMatrix.values())
			{
			predictedLabels.addAll(ls.elementSet());
			}
		return predictedLabels.size();
		}
	}


text:
Created by Calisha D. Myers.

For Lashawn Melton, The Lab Salon, Washington, DC.