text:
<?php

namespace AppBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;

/**
 * Event
 *
 * @ORM\Table(name="event")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\EventRepository")
 */
class Event
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="title", type="string", length=500)
     */
    private $title;

    /**
     * @var string
     *
     * @ORM\Column(name="description", type="text", nullable=true)
     */
    private $description;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="dateAdd", type="datetime")
     */
    private $dateAdd;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="dateUpd", type="datetime")
     */
    private $dateUpd;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="dateStart", type="datetime")
     */
    private $dateStart;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="dateEnd", type="datetime")
     */
    private $dateEnd;

    /**
     * @var float
     *
     * @ORM\Column(name="longitude", type="float")
     */
    private $longitude;

    /**
     * @var float
     *
     * @ORM\Column(name="latitude", type="float")
     */
    private $latitude;

    /**
     * @var string
     *
     * @ORM\Column(name="address", type="string", length=2000)
     */
    private $address;

    /**
     * @var string
     *
     * @ORM\Column(name="town", type="string", length=500)
     */
    private $town;

    /**
     * @var string
     *
     * @ORM\Column(name="country", type="string", length=500)
     */
    private $country;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\EventCategory", inversedBy="event")
     * @ORM\JoinColumn(name="category", referencedColumnName="id")
     */
    private $category;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\User")
     * @ORM\JoinColumn(name="owner", referencedColumnName="id")
     */
    private $owner;

    /**
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\User", inversedBy="participant")
     * @ORM\JoinTable(name="Participant",
     *      joinColumns={@ORM\JoinColumn(name="event_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")}
     *      )
     */
    private $participant;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set title
     *
     * @param string $title
     *
     * @return Event
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set description
     *
     * @param string $description
     *
     * @return Event
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set dateAdd
     *
     * @param \DateTime $dateAdd
     *
     * @return Event
     */
    public function setDateAdd($dateAdd)
    {
        $this->dateAdd = $dateAdd;

        return $this;
    }

    /**
     * Get dateAdd
     *
     * @return \DateTime
     */
    public function getDateAdd()
    {
        return $this->dateAdd;
    }

    /**
     * Set dateUpd
     *
     * @param \DateTime $dateUpd
     *
     * @return Event
     */
    public function setDateUpd($dateUpd)
    {
        $this->dateUpd = $dateUpd;

        return $this;
    }

    /**
     * Get dateUpd
     *
     * @return \DateTime
     */
    public function getDateUpd()
    {
        return $this->dateUpd;
    }

    /**
     * Set dateStart
     *
     * @param \DateTime $dateStart
     *
     * @return Event
     */
    public function setDateStart($dateStart)
    {
        $this->dateStart = $dateStart;

        return $this;
    }

    /**
     * Get dateStart
     *
     * @return \DateTime
     */
    public function getDateStart()
    {
        return $this->dateStart;
    }

    /**
     * Set dateEnd
     *
     * @param \DateTime $dateEnd
     *
     * @return Event
     */
    public function setDateEnd($dateEnd)
    {
        $this->dateEnd = $dateEnd;

        return $this;
    }

    /**
     * Get dateEnd
     *
     * @return \DateTime
     */
    public function getDateEnd()
    {
        return $this->dateEnd;
    }

    /**
     * Set longitude
     *
     * @param float $longitude
     *
     * @return Event
     */
    public function setLongitude($longitude)
    {
        $this->longitude = $longitude;

        return $this;
    }

    /**
     * Get longitude
     *
     * @return float
     */
    public function getLongitude()
    {
        return $this->longitude;
    }

    /**
     * Set latitude
     *
     * @param float $latitude
     *
     * @return Event
     */
    public function setLatitude($latitude)
    {
        $this->latitude = $latitude;

        return $this;
    }

    /**
     * Get latitude
     *
     * @return float
     */
    public function getLatitude()
    {
        return $this->latitude;
    }

    /**
     * Set address
     *
     * @param string $address
     *
     * @return Event
     */
    public function setAddress($address)
    {
        $this->address = $address;

        return $this;
    }

    /**
     * Get address
     *
     * @return string
     */
    public function getAddress()
    {
        return $this->address;
    }

    /**
     * Set town
     *
     * @param string $town
     *
     * @return Event
     */
    public function setTown($town)
    {
        $this->town = $town;

        return $this;
    }

    /**
     * Get town
     *
     * @return string
     */
    public function getTown()
    {
        return $this->town;
    }

    /**
     * Set country
     *
     * @param string $country
     *
     * @return Event
     */
    public function setCountry($country)
    {
        $this->country = $country;

        return $this;
    }

    /**
     * Get country
     *
     * @return string
     */
    public function getCountry()
    {
        return $this->country;
    }

    /**
     * Set category
     *
     * @param EventCategory $category
     *
     * @return Event
     */
    public function setCategory(EventCategory $category = null)
    {
        $this->category = $category;

        return $this;
    }

    /**
     * Get category
     *
     * @return EventCategory
     */
    public function getCategory()
    {
        return $this->category;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->dateAdd = new \DateTime();
        $this->dateUpd = new \DateTime();
        $this->dateStart = new \DateTime();
        $this->dateEnd = new \DateTime();
    }

    /**
     * Add participant
     *
     * @param \AppBundle\Entity\User $participant
     *
     * @return Event
     */
    public function addParticipant(User $participant)
    {
        $this->participant[] = $participant;

        return $this;
    }

    /**
     * Remove participant
     *
     * @param \AppBundle\Entity\User $participant
     */
    public function removeParticipant(User $participant)
    {
        $this->participant->removeElement($participant);
    }

    /**
     * Get participant
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getParticipant()
    {
        return $this->participant;
    }

    /**
     * Set owner
     *
     * @param User $owner
     *
     * @return Event
     */
    public function setOwner(User $owner = null)
    {
        $this->owner = $owner;

        return $this;
    }

    /**
     * Get owner
     *
     * @return User
     */
    public function getOwner()
    {
        return $this->owner;
    }
}


text:
var mongoose = require('mongoose'),

    Schema = mongoose.Schema,

    GauntletStatus = new Schema({
            status: {
                type: String,
                enum: ['ACCEPTED', 'REJECTED', 'COMPLETED', 'FAILED', 'PENDING', 'REVIEW'],
                default: 'PENDING'
            },
            acc_rej_Date: { //date the challengee accepted or rejected the challenge
                type: Date
            },
            completed_Date: {
                type: Date
            }
        },
        {
            timestamps: true
        });

module.exports = mongoose.model('GauntletStatus', GauntletStatus);

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
using Digiseller.Client.Core.Interfaces;

namespace Digiseller.Client.Core.Helpers
{
    public class XmlSerializer<TRequest, TResponse> : ISerializer<TRequest, TResponse>
    {
        private readonly XmlWriterSettings _writerSettings =
            new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true };

        private readonly XmlSerializerNamespaces _namespaces =
            new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", "") });

        public Task<TResponse> Deserialize(string data)
        {
            return Task.Run(() =>
            {
                if (string.IsNullOrEmpty(data))
                    throw new NullReferenceException();

                using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(data)))
                {
                    var serializer = new XmlSerializer(typeof(TResponse));
                    return (TResponse)serializer.Deserialize(ms);
                }
            });
        }

        public Task<HttpContent> Serialize(TRequest obj)
        {
            return Task.Run(() => {
                if (obj == null)
                    throw new NullReferenceException();

                using (var ms = new MemoryStream())
                using (var writer = XmlWriter.Create(ms, _writerSettings))
                {
                    var serializer = new XmlSerializer(typeof(TRequest));
                    serializer.Serialize(writer, obj, _namespaces);
                    string serialized = Encoding.UTF8.GetString(ms.ToArray());
                    return new StringContent(serialized, Encoding.UTF8, "text/xml") as HttpContent;
                }
            });
        }
    }
}


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

<title>epsylon.environment</title>
<meta name="date" content="2014-09-14">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package epsylon.environment

Interface Summary

Interface
Description

Environment<T>

Defines an interface for all the objects that aims to represent an Environment.

Class Summary

Class
Description

DynamicEnvironment

Represents a Dynamic Environment of variables associated with their values.

GenericEnvironment<T>

Represents an abstract environment, implementing all the common methods from the Environment interface.

StaticEnvironment

Represents a Static Environment of variables associated with their type.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
#!/usr/bin/perl -w

# Based on create-mime.assign.pl in debian lighttpd (1.4.x) package
# Creates an example mime.conf from /etc/mime.types

use strict;

# text/* subtypes to serve as "text/...; charset=utf-8"
# text/html IS NOT INCLUDED: html has its own method for defining charset
#   (<meta>), but the standards specify that content-type in HTTP wins over
#   the setting in the html document.
my %text_utf8 = map { $_ => 1 } qw(
	css
	csv
	plain
	x-bibtex
	x-boo
	x-c++hdr
	x-c++src
	x-chdr
	x-csh
	x-csrc
	x-dsrc
	x-diff
	x-haskell
	x-java
	x-lilypond
	x-literate-haskell
	x-makefile
	x-moc
	x-pascal
	x-perl
	x-python
	x-scala
	x-sh
	x-tcl
	x-tex
);

# map extension to hash which maps types to the type they should be replaced with
my %manual_conflicts_resolve = (
	'.ra' => {
		'audio/x-pn-realaudio' => 'audio/x-realaudio',
	},
);

open MIMETYPES, "/etc/mime.types" or die "Can't open /etc/mime.types: $!";

my %extensions;
sub set {
	my ($extension, $mimetype) = @_;
	$extensions{$extension} = $mimetype;
}
sub add {
	my ($extension, $mimetype) = @_;
	my $have = $extensions{$extension};

	my $r = $manual_conflicts_resolve{$extension};
	# update @_ too for calls to set
	$_[1] = $mimetype = $r->{$mimetype} if $r && $r->{$mimetype};

	# mime.types can have same extension for different mime types
	if ($have) {
		# application/octet-stream means we couldn't resolve another conflict
		return if $have eq $mimetype || $have eq 'application/octet-stream';

		my ($have_type, $have_subtype) = split /\//, $have, 2;
		my ($type, $subtype) = split /\//, $mimetype, 2;

		my $have_x = ($have_type =~ /^x-/ || $have_subtype =~ /^x-/);
		my $x = ($type =~ /^x-/ || $subtype =~ /^x-/);

		# entries without x- prefix in type/subtype win:
		if ($have_x && !$x) {
			return set @_; # overwrite
		} elsif ($x && !$have_x) {
			return; # ignore
		}

		# text/ wins over application/ for same subtype
		if ($subtype eq $have_subtype) {
			if ($type eq "text" && $have_type eq "application") {
				return set @_; # overwrite
			} elsif ($have_type eq "text" && $type eq "application") {
				return; # ignore
			}
		}

		print STDERR "Duplicate mimetype: '${extension}' => '${mimetype}' (already have '${have}'), merging to 'application/octet-stream'\n";
		set ($extension, 'application/octet-stream');
	} else {
		set @_;
	}
}

sub print_type {
	my ($extension, $mimetype) = @_;
	if ($mimetype =~ /^text\/(.*)$/) {
		$mimetype .= "; charset=utf-8" if $text_utf8{$1};
	}

	print "\t\"${extension}\" => \"${mimetype}\",\n";
}

while (<MIMETYPES>) {
	chomp;
	s/\#.*//;
	next if /^\w*$/;
	if (/^([a-z0-9\/+-.]+)\s+((?:[a-z0-9.+-]+[ ]?)+)$/i) {
		my $mimetype = $1;
		my @extensions = split / /, $2;

		foreach my $ext (@extensions) {
			add(".${ext}", $mimetype);
		}
	}
}

# missing in /etc/mime.types;
# from http://www.iana.org/assignments/media-types/media-types.xhtml
add(".dtd", "application/xml-dtd");

# other useful mappings
my %useful = (
	".tar.gz"  => "application/x-gtar-compressed",
	".gz"      => "application/x-gzip",
	".tbz"     => "application/x-gtar-compressed",
	".tar.bz2" => "application/x-gtar-compressed",
	".bz2"     => "application/x-bzip",
	".log"     => "text/plain",
	".conf"    => "text/plain",
	".spec"    => "text/plain",
	"README"   => "text/plain",
	"Makefile" => "text/x-makefile",
);

while (my ($ext, $mimetype) = each %useful) {
	add($ext, $mimetype) unless $extensions{$ext};
}

print <<EOF;
# created by create-mime.conf.pl

#######################################################################
##
##  MimeType handling
## -------------------
##
## https://redmine.lighttpd.net/projects/lighttpd/wiki/Mimetype_assignDetails

##
## Use the "Content-Type" extended file attribute to obtain mime type if
## possible
##
## Disabled by default
##
#mimetype.use-xattr = "enable"

##
## mimetype ("Content-Type" HTTP header) mapping for static file handling
##
## The first matching suffix is used. If no mapping is found
## 'application/octet-stream' is used, and caching (etag/last-modified handling)
## is disabled to prevent clients from caching "unknown" mime types.
##
## Therefore the last mapping is:
##   "" => "application/octet-stream"
## This matches all extensions and acts as default mime type, and enables
## caching for those.
mimetype.assign = (
EOF

# sort "x-" and "vnd." prefixed names after everything else
sub mimecmpvalue {
	my ($mimetype) = @_;
	$mimetype =~ s/(^|\/)(x-|vnd\.)/~$1$2/g;
	return $mimetype;
}
sub countdots {
	my ($s) = @_;
	return scalar(() = $s =~ /\./g);
}
# the first matching suffix wins, so we have to sort by "length"
# as all extensions start with "." we use the number of "."s as length
# the exceptions are "README" and "Makefile" which are assumed not to conflict
#  (i.e. are not a suffix of any other extension)
for my $ext (sort { countdots($b) <=> countdots($a) || mimecmpvalue($extensions{$a}) cmp mimecmpvalue($extensions{$b}) || $a cmp $b } keys(%extensions)) {
	print_type($ext, $extensions{$ext});
}

print <<EOF;

	# enable caching for unknown mime types:
	"" => "application/octet-stream"
)
EOF


text:
package com.amazonaws.services.directconnect.model;

import java.io.Serializable;

/**
 *

 * A structure containing a list of virtual private gateways.
 *

 */
public class DescribeVirtualGatewaysResult implements Serializable, Cloneable {

    /**
     *

     * A list of virtual private gateways.
     *

     */
    private com.amazonaws.internal.SdkInternalList<VirtualGateway> virtualGateways;

    /**
     *

     * A list of virtual private gateways.
     *

     *
     * @return A list of virtual private gateways.
     */

    public java.util.List<VirtualGateway> getVirtualGateways() {
        if (virtualGateways == null) {
            virtualGateways = new com.amazonaws.internal.SdkInternalList<VirtualGateway>();
        }
        return virtualGateways;
    }

    /**
     *

     * A list of virtual private gateways.
     *

     *
     * @param virtualGateways
     *        A list of virtual private gateways.
     */

    public void setVirtualGateways(
            java.util.Collection<VirtualGateway> virtualGateways) {
        if (virtualGateways == null) {
            this.virtualGateways = null;
            return;
        }

        this.virtualGateways = new com.amazonaws.internal.SdkInternalList<VirtualGateway>(
                virtualGateways);
    }

    /**
     *

     * A list of virtual private gateways.
     *

     *

     * NOTE: This method appends the values to the existing list (if
     * any). Use {@link #setVirtualGateways(java.util.Collection)} or
     * {@link #withVirtualGateways(java.util.Collection)} if you want to
     * override the existing values.
     *

     *
     * @param virtualGateways
     *        A list of virtual private gateways.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public DescribeVirtualGatewaysResult withVirtualGateways(
            VirtualGateway... virtualGateways) {
        if (this.virtualGateways == null) {
            setVirtualGateways(new com.amazonaws.internal.SdkInternalList<VirtualGateway>(
                    virtualGateways.length));
        }
        for (VirtualGateway ele : virtualGateways) {
            this.virtualGateways.add(ele);
        }
        return this;
    }

    /**
     *

     * A list of virtual private gateways.
     *

     *
     * @param virtualGateways
     *        A list of virtual private gateways.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public DescribeVirtualGatewaysResult withVirtualGateways(
            java.util.Collection<VirtualGateway> virtualGateways) {
        setVirtualGateways(virtualGateways);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getVirtualGateways() != null)
            sb.append("VirtualGateways: " + getVirtualGateways());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DescribeVirtualGatewaysResult == false)
            return false;
        DescribeVirtualGatewaysResult other = (DescribeVirtualGatewaysResult) obj;
        if (other.getVirtualGateways() == null
                ^ this.getVirtualGateways() == null)
            return false;
        if (other.getVirtualGateways() != null
                && other.getVirtualGateways().equals(this.getVirtualGateways()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime
                * hashCode
                + ((getVirtualGateways() == null) ? 0 : getVirtualGateways()
                        .hashCode());
        return hashCode;
    }

    @Override
    public DescribeVirtualGatewaysResult clone() {
        try {
            return (DescribeVirtualGatewaysResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                            + "even though we're Cloneable!", e);
        }
    }
}


text:
layout: base
title:  'Statistics of PART in UD_Javanese-CSUI'
udver: '2'
---

## Treebank Statistics: UD_Javanese-CSUI: POS Tags: `PART`

There are 4 `PART` lemmas (0%), 5 `PART` types (0%) and 8 `PART` tokens (0%).
Out of 17 observed tags, the rank of `PART` is: 15 in number of lemmas, 15 in number of types and 15 in number of tokens.

The 10 most frequent `PART` lemmas: ora, boten, pun, ya

The 10 most frequent `PART` types:  ora, boten, mboten, pun, ya

The 10 most frequent ambiguous lemmas:

The 10 most frequent ambiguous types:

## Morphology

The form / lemma ratio of `PART` is 1.250000 (the average of all parts of speech is 1.014388).

The 1st highest number of forms (2) was observed with the lemma "boten": boten, mboten.

The 2nd highest number of forms (1) was observed with the lemma "ora": ora.

The 3rd highest number of forms (1) was observed with the lemma "pun": pun.

`PART` occurs with 2 features: <tt>Polarity</tt> (6; 75% instances), <tt>Polite</tt> (4; 50% instances)

`PART` occurs with 3 feature-value pairs: `Polarity=Neg`, `Polite=Form`, `Polite=Infm`

`PART` occurs with 4 feature combinations.
The most frequent feature combination is `Polarity=Neg|Polite=Infm` (3 tokens).
Examples: ora

## Relations

`PART` nodes are attached to their parents using 2 different relations: <tt>advmod</tt> (6; 75% instances), <tt>advmod:emph</tt> (2; 25% instances)

Parents of `PART` nodes belong to 4 different parts of speech: <tt>VERB</tt> (5; 63% instances), <tt>ADJ</tt> (1; 13% instances), <tt>NOUN</tt> (1; 13% instances), <tt>X</tt> (1; 13% instances)

8 (100%) `PART` nodes are leaves.

The highest child degree of a `PART` node is 0.


text:
<?php
namespace AssertionConstraint\Constraint;

use AssertionConstraint\AbstractAssertionConstraint;

/**
 * Assert that value is not in array of choices.
 *
 * @Annotation
 * @Target({"PROPERTY"})
 */
class AllNotInArray extends AbstractAssertionConstraint
{

    public $choices;
    public $message;

    /**
     * {@inheritdoc}
     */
    public function getAssertionParameterNames()
    {
        return array('choices', 'message');
    }

    /**
     * {@inheritdoc}
     */
    public function getAssertionMethodName()
    {
        return 'allNotInArray';
    }
}


text:
import os
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

SMALL_SIZE = 6
MEDIUM_SIZE = 8
BIGGER_SIZE = 10

plt.rc('font', size=SMALL_SIZE)          # controls default text sizes
plt.rc('axes', titlesize=SMALL_SIZE)     # fontsize of the axes title
plt.rc('axes', labelsize=MEDIUM_SIZE)    # fontsize of the x and y labels
plt.rc('xtick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE)    # legend fontsize
plt.rc('figure', titlesize=BIGGER_SIZE)  # fontsize of the figure title

def load_trial_csv(path, delimiter = ";"):
        """ load csv file for a configuration trial with the following format:
        (epoch, [train|valid|test] x [loss|error], xnorm, gnorm, seconds)+
        """
        name = os.path.basename(path).replace(".csv", "")
        data = mlab.csv2rec(path, delimiter=delimiter, names=None)
        return name, data

def load_config_csv(path, delimiter = ";"):
        """ load csv file for a configuration summary with the following format:
        (trial, optimum epoch, [train|valid|test] x [loss|error], xnorm, gnorm, seconds, speed)+
        """
        name = os.path.basename(path).replace(".csv", "")
        data = mlab.csv2rec(path, delimiter=delimiter, names=None)
        return name, data

def load_csvs(paths, loader, delimiter = ";"):
        names, datas = [], []
        for path in paths:
                name, data = loader(path, delimiter)
                names.append(name)
                datas.append(data)
        return names, datas

def plot_trial(spath, ppath):
        """ plot the training evolution of a model """
        title, data = load_trial_csv(spath)
        with PdfPages(ppath) as pdf:
                # (train, validation, test) loss value and error
                for ynames in (["train_loss", "valid_loss", "test_loss"], ["train_error", "valid_error", "test_error"]):
                        xname, yname0, yname1, yname2 = "epoch", ynames[0], ynames[1], ynames[2]
                        plt.plot(data[xname], data[yname0], "r-", label = yname0)
                        plt.plot(data[xname], data[yname1], "g-", label = yname1)
                        plt.plot(data[xname], data[yname2], "b-", label = yname2)
                        plt.title(title, weight = "bold")
                        plt.xlabel(xname, fontsize = "smaller")
                        plt.ylabel(yname0.replace("train_", ""), fontsize = "smaller")
                        plt.legend(fontsize = "smaller")
                        plt.grid(True, linestyle='--')
                        pdf.savefig()
                        plt.close()

                # xnorm and gnorm
                for yname in ("xnorm", "gnorm"):
                        xname = "epoch"
                        plt.plot(data[xname], data[yname], "k-", label = yname)
                        plt.title(title, weight = "bold")
                        plt.xlabel(xname, fontsize = "smaller")
                        plt.ylabel(yname, fontsize = "smaller")
                        plt.legend(fontsize = "smaller")
                        plt.grid(True, linestyle='--')
                        pdf.savefig()
                        plt.close()

def plot_trials(spaths, ppath):
        """ plot the training evolution of multiple models on the same plot """
        names, datas = load_csvs(spaths, load_trial_csv)
        with PdfPages(ppath) as pdf:
                for yname in ("train_loss", "train_error", "valid_loss", "valid_error", "test_loss", "test_error", "xnorm", "gnorm", "seconds"):
                        xname = "epoch"
                        for data, name in zip(datas, names):
                                plt.plot(data[xname], data[yname], label = name)
                        plt.xlabel(xname, fontsize = "smaller")
                        plt.ylabel(yname.replace("train_", "").replace("valid_", "").replace("test_", ""), fontsize = "smaller")
                        plt.title(yname, weight = "bold")
                        plt.legend(fontsize = "smaller")
                        plt.grid(True, linestyle='--')
                        pdf.savefig()
                        plt.close()

def plot_configs(spaths, ppath, names):
        """ plot the test results of multiple models on the sample plot """
        __, datas = load_csvs(spaths, load_config_csv)
        assert(len(names) == len(datas))
        title = os.path.basename(ppath).replace(".pdf", "").replace("result_", "")
        with PdfPages(ppath) as pdf:
                for yname in ("epoch", "train_loss", "train_error", "valid_loss", "valid_error", "test_loss", "test_error", "xnorm", "gnorm", "seconds", "speed"):
                        bdata = []
                        for data in datas:
                                bdata.append(data[yname])
                        plt.boxplot(bdata, labels = names)
                        plt.title(title, weight = "bold")
                        plt.ylabel(yname, fontsize = "smaller")
                        plt.grid(True, linestyle='--')
                        pdf.savefig()
                        plt.close()


text:
@interface MOBProjectionEPSG6607 : MOBProjection

@end


text:
#ifndef __EXTENSION_PERMISSIVE_STRATEGY_HPP__
#define __EXTENSION_PERMISSIVE_STRATEGY_HPP__

#include "gr1context.hpp"

#include <string>

/**
 * An extension to extract an explicit-state permissive strategy, which
 * is also maximal when no liveness assumptions and guarantees are given.
 */
template<class T> class XExtractPermissiveExplicitStrategy : public T {
protected:
    // New variables
    std::string outputFilename;

    // Inherited stuff used
    using T::mgr;
    using T::winningPositions;
    using T::initSys;
    using T::initEnv;
    using T::preVars;
    using T::livenessGuarantees;
    using T::strategyDumpingData;
    using T::variables;
    using T::safetyEnv;
    using T::variableTypes;
    using T::realizable;
    using T::postVars;
    using T::varCubePre;
    using T::variableNames;
    using T::varVectorPre;
    using T::varVectorPost;
    using T::varCubePostOutput;
    using T::varCubePostInput;
    using T::determinize;
    using T::doesVariableInheritType;
    using T::livenessAssumptions;
    using T::safetySys;

    XExtractPermissiveExplicitStrategy<T>(std::list<std::string> &filenames): T(filenames) {}

    void init(std::list<std::string> &filenames) {
        T::init(filenames);
        if (filenames.size()==0) {
            outputFilename = "";
        } else {
            outputFilename = filenames.front();
            filenames.pop_front();
        }
    }

public:

    void execute() {
        T::execute();
        if (realizable) {
            if (outputFilename=="") {
                computeAndPrintExplicitStateStrategy(std::cout);
            } else {
                std::ofstream of(outputFilename.c_str());
                if (of.fail()) {
                    SlugsException ex(false);
                    ex << "Error: Could not open output file'" << outputFilename << "\n";
                    throw ex;
                }
                computeAndPrintExplicitStateStrategy(of);
                if (of.fail()) {
                    SlugsException ex(false);
                    ex << "Error: Writing to output file'" << outputFilename << "failed. \n";
                    throw ex;
                }
                of.close();
            }
        }
    }

    /**
     * @brief Compute and print out (to stdout) an explicit-state strategy that is winning for
     *        the system.
     *        This function requires that the realizability of the specification has already been
     *        detected and that the variables "strategyDumpingData" and
     *        "winningPositions" have been filled by the synthesis algorithm with meaningful data.
     * @param outputStream - Where the strategy shall be printed to.
     */
    void computeAndPrintExplicitStateStrategy(std::ostream &outputStream) {

        // We don't want any reordering from this point onwards, as
        // the BDD manipulations from this point onwards are 'kind of simple'.
        mgr.setAutomaticOptimisation(false);

        // List of states in existance so far. The first map
        // maps from a BF node pointer (for the pre variable valuation) and a goal
        // to a state number. The vector then contains the concrete valuation.
        std::map<std::pair<size_t, unsigned int>, unsigned int > lookupTableForPastStates;
        std::vector<BF> bfsUsedInTheLookupTable;
        std::list<std::pair<size_t, unsigned int> > todoList;

        // Prepare initial to-do list from the allowed initial states
        BF todoInit = winningPositions;
        while (!(todoInit.isFalse())) {
            BF concreteState = determinize(todoInit,preVars);
            std::pair<size_t, unsigned int> lookup = std::pair<size_t, unsigned int>(concreteState.getHashCode(),0);
            lookupTableForPastStates[lookup] = bfsUsedInTheLookupTable.size();
            bfsUsedInTheLookupTable.push_back(concreteState);
            todoInit &= !concreteState;
            todoList.push_back(lookup);
        }

        // Prepare positional strategies for the individual goals
        std::vector<BF> positionalStrategiesForTheIndividualGoals(livenessGuarantees.size());
        for (unsigned int i=0;i<livenessGuarantees.size();i++) {
            BF statesCovered = mgr.constantFalse();
            BF stateInputsCovered = mgr.constantFalse();
            BF strategy = mgr.constantFalse();

            // Change: collect transitions as long as a state is not "fixed".
            for (auto it = strategyDumpingData.begin();it!=strategyDumpingData.end();it++) {
                if (it->first == i) {
                    BF newCases = it->second.ExistAbstract(varCubePostOutput) & (!statesCovered);
                    strategy |= (!statesCovered) & it->second;
                    stateInputsCovered |= newCases;
                    statesCovered = ((!safetyEnv) | stateInputsCovered).UnivAbstract(varCubePostInput);
                }
            }
            positionalStrategiesForTheIndividualGoals[i] = strategy;
            //BF_newDumpDot(*this,strategy,"PreInput PreOutput PostInput PostOutput","/tmp/generalStrategy.dot");
        }

        // Extract strategy
        while (todoList.size()>0) {
            std::pair<size_t, unsigned int> current = todoList.front();
            todoList.pop_front();
            unsigned int stateNum = lookupTableForPastStates[current];
            BF currentPossibilities = bfsUsedInTheLookupTable[stateNum];

            /*{
                std::ostringstream filename;
                filename << "/tmp/state" << stateNum << ".dot";
                BF_newDumpDot(*this,currentPossibilities,"PreInput PreOutput PostInput PostOutput",filename.str());
            }*/

            // Print state information
            outputStream << "State " << stateNum << " with rank " << current.second << "\n";
            bool first = true;
            for (unsigned int i=0;i<variables.size();i++) {
                if (doesVariableInheritType(i,Pre)) {
                    if (first) {
                        first = false;
                    } else {
                        outputStream << ", ";
                    }
                    outputStream << variableNames[i] << ":";
                    outputStream << (((currentPossibilities & variables[i]).isFalse())?"0":"1");
                }
            }

            outputStream << "\n";
            first = true;

            // Compute successors for all variables that allow these
            currentPossibilities &= positionalStrategiesForTheIndividualGoals[current.second];
            BF remainingTransitions = currentPossibilities;

            // Switching goals
            while (!(remainingTransitions.isFalse())) {
                BF newCombination = determinize(remainingTransitions,postVars);

                // Jump as much forward  in the liveness guarantee list as possible ("stuttering avoidance")
                unsigned int nextLivenessGuarantee = current.second;
                bool firstTry = true;
                while (((nextLivenessGuarantee != current.second) || firstTry) && !((livenessGuarantees[nextLivenessGuarantee] & newCombination).isFalse())) {
                    nextLivenessGuarantee = (nextLivenessGuarantee + 1) % livenessGuarantees.size();
                    firstTry = false;
                }

                // Mark which input has been captured by this case
                // ---- The following line is a modification for the maximally permissive strategy case.
                BF inputCaptured = newCombination;
                newCombination = newCombination.ExistAbstract(varCubePre).SwapVariables(varVectorPre,varVectorPost);
                remainingTransitions &= !inputCaptured;

                // Search for newCombination
                unsigned int tn;
                std::pair<size_t, unsigned int> target = std::pair<size_t, unsigned int>(newCombination.getHashCode(),nextLivenessGuarantee);
                if (lookupTableForPastStates.count(target)==0) {
                    tn = lookupTableForPastStates[target] = bfsUsedInTheLookupTable.size();
                    bfsUsedInTheLookupTable.push_back(newCombination);
                    todoList.push_back(target);
                } else {
                    tn = lookupTableForPastStates[target];
                }

                // Print
                outputStream << tn << std::endl;
            }
            outputStream << "\n";
        }
    }

    static GR1Context* makeInstance(std::list<std::string> &filenames) {
        return new XExtractPermissiveExplicitStrategy<T>(filenames);
    }
};

#endif


text:
function verifyModerationCheckedTopics()
{
	var f = document.formModeration.topic_id;

	if (f.length == undefined)	 {
		if (f.checked) {
			return true;
		}
	}

	for (var i = 0; i < f.length; i++) {
		if (f[i].checked) {
			return true;
		}
	}

	alert("${I18n.getMessage("Moderation.SelectTopics")}");
	return false;
}

function validateModerationDelete()
{
	var status = verifyModerationCheckedTopics()
		&& confirm("${I18n.getMessage("Moderation.ConfirmDelete")}")
		&& askModerationReason();

	if (status) {
		document.formModeration.log_type.value = "1";
	}

	return status;
}

function lockUnlock()
{
	var status = verifyModerationCheckedTopics() && askModerationReason();

	if (status) {
		document.formModeration.log_type.value = "3";
	}

	return status;
}

function askModerationReason()
{
	var message = prompt("${I18n.getMessage("ModerationLog.changeReason")}");

	if (message == null || message == "") {
		alert("${I18n.getMessage("ModerationLog.reasonIsEmpty")}");
		return false;
	}
	else {
		document.formModeration.log_description.value = message;
	}

	return true;
}

var oldClasses = {}

function changeTrClass(from, trIndex)
{
	var tr = from.parentNode.parentNode;
	trIndex = trIndex.toString();

	if (from.checked) {
		tr.className = "moderation_highlight";
		oldClasses[trIndex] = new Array();

		for (var i = 0; i < tr.childNodes.length; i++) {
			var node = tr.childNodes[i];

			if (node.nodeName.toUpperCase() == "TD") {
				oldClasses[trIndex].push(node.className);
				node.className = "";
			}
		}
	}
	else {
		tr.className = "";

		for (var i = tr.childNodes.length - 1; i >= 0; i--) {
			var node = tr.childNodes[i];

			if (node.nodeName.toUpperCase() == "TD") {
				node.className = oldClasses[trIndex].pop();
			}
		}
	}
}


text:
title: Work
permalink: /work
layout: content
---
{% include goback.html %}

# Past Work

View my Resume

## Experience

**Adventures Attendant , Associated Students, Inc.** 2018-Present

**Laser Software R&D Intern, Amada Miyachi America, Inc.** JUN 2018 - AUG 2018 (5 week internship)

**Web Development, taloranderson.com**

## Education

**Cal Poly Pomona Computer Science, B.S.** (Graduation May 2020)

Relevant Courses:

- CS 4650 **Big Data & Cloud Computing:**
  - Built multiple projects using AWS, including [ascii-maker](//ascii-maker.herokuapp.com).
- CS 4800 **Software Engineering:**
  - Used Agile methodology to create Talor's Dresses, an interactive virtual fitting room for wedding dresses. Built over the couse of 1 semester.
- CS 4990 **Machine Learning:**
  - I taught a computer to write convincing handwritten numbers. See my project presentation [here](https://drive.google.com/open?id=1gO9bVLDzAgpKk0cpLVPgiuHNhbdgR6po).
- CS 4200 **Artificial Intelligence:**
  - Project: N-Queens Solver


text:
package org.sprintapi.hyperdata.gwt.client.json.value;

import org.sprintapi.hyperdata.gwt.client.AdapterException;
import org.sprintapi.hyperdata.gwt.client.json.JsonValueAdapter;
import org.sprintapi.hyperdata.gwt.client.json.lang.JsonBoolean;
import org.sprintapi.hyperdata.gwt.client.json.lang.JsonValue;
import org.sprintapi.hyperdata.gwt.client.json.lang.impl.JsonBooleanImpl;

public class JsonBooleanAdapter implements JsonValueAdapter<Boolean> {

	@Override
	public Boolean read(JsonValue value) throws AdapterException {
		if (value == null) {
			throw new IllegalArgumentException("The value argument cannot be a null.");
		}
		JsonBoolean jsonBool = value.isBoolean();
		if (jsonBool == null) {
			throw new IllegalArgumentException("The value '" + value + "' argument is not " + JsonBoolean.class);
		}
		return jsonBool.booleanValue();
	}

	@Override
	public JsonValue write(Boolean value) {
		if (value == null) {
			throw new IllegalArgumentException("The value argument cannot be a null.");
		}
		return JsonBooleanImpl.getInstance(value);
	}

	@Override
	public Class<Boolean> getJavaClass() {
		return Boolean.class;
	}
}


text:
package mesosphere.marathon

import java.io.{ IOException, FileInputStream }

import com.google.protobuf.ByteString
import mesosphere.chaos.http.HttpConf
import org.apache.mesos.Protos.{ Credential, FrameworkInfo, FrameworkID }
import org.apache.mesos.{ MesosSchedulerDriver, SchedulerDriver }
import org.slf4j.LoggerFactory

object MarathonSchedulerDriver {
  private[this] val log = LoggerFactory.getLogger(getClass)

  def newDriver(config: MarathonConf,
                httpConfig: HttpConf,
                newScheduler: MarathonScheduler,
                frameworkId: Option[FrameworkID]): SchedulerDriver = {
    val frameworkInfoBuilder = FrameworkInfo.newBuilder()
      .setName(config.frameworkName())
      .setFailoverTimeout(config.mesosFailoverTimeout().toDouble)
      .setUser(config.mesosUser())
      .setCheckpoint(config.checkpoint())

    // Set the role, if provided.
    config.mesosRole.get.foreach(frameworkInfoBuilder.setRole)

    // Set the ID, if provided
    frameworkId.foreach(frameworkInfoBuilder.setId)

    if (config.webuiUrl.isSupplied) {
      frameworkInfoBuilder.setWebuiUrl(config.webuiUrl())
    }
    else if (httpConfig.sslKeystorePath.isDefined) {
      // ssl enabled, use https
      frameworkInfoBuilder.setWebuiUrl(s"https://${config.hostname()}:${httpConfig.httpsPort()}")
    }
    else {
      // ssl disabled, use http
      frameworkInfoBuilder.setWebuiUrl(s"http://${config.hostname()}:${httpConfig.httpPort()}")
    }

    // set the authentication principal, if provided
    config.mesosAuthenticationPrincipal.get.foreach(frameworkInfoBuilder.setPrincipal)

    val credential: Option[Credential] =
      config.mesosAuthenticationPrincipal.get.map { principal =>
        val credentialBuilder = Credential.newBuilder()
          .setPrincipal(principal)

        config.mesosAuthenticationSecretFile.get.foreach { secretFile =>
          try {
            val secretBytes = ByteString.readFrom(new FileInputStream(secretFile))
            credentialBuilder.setSecret(secretBytes)
          }
          catch {
            case cause: Throwable =>
              throw new IOException(s"Error reading authentication secret from file [$secretFile]", cause)
          }
        }

        credentialBuilder.build()
      }

    val frameworkInfo = frameworkInfoBuilder.build()

    log.debug("Start creating new driver")

    val newDriver: MesosSchedulerDriver = credential match {
      case Some(cred) =>
        new MesosSchedulerDriver(newScheduler, frameworkInfo, config.mesosMaster(), cred)

      case None =>
        new MesosSchedulerDriver(newScheduler, frameworkInfo, config.mesosMaster())
    }

    log.debug("Finished creating new driver")

    newDriver
  }
}


text:
class ComplexDrawing : public QWidget
{
    Q_OBJECT

    QHash<QString, QPoint> _points;

public:
    explicit ComplexDrawing(MainWindow*);
    void paintEvent(QPaintEvent*);
    void translateToNativeCoords(QPoint& p);
    void translateToNativeCoords(QLine& l);

signals:

public slots:
    void updateElems();
};

#endif // COMPLEX_H


text:
enum class FunCallType {
    SYNC,
    ASYNC,
};

class Funwrap3 {
private:
    class RetVoid {};
    class RetNonVoid{};
public:
    Funwrap3() : _fun(nullptr), _calltype(FunCallType::ASYNC) {}
    template< class F, class... Args >
    void set( FunCallType calltype, F f, Args... args ){
	using ResultType = typename std::result_of<F(Args...) >::type;
	using tag_dispatch_type = typename std::conditional<std::is_void<ResultType>::value, Funwrap3::RetVoid, Funwrap3::RetNonVoid>::type;
	tag_dispatch_type tag;
	set_aux( tag, calltype, f, args... );
    }
    template< class F, class... Args >
    void set_aux( Funwrap3::RetNonVoid tag, FunCallType calltype, F f, Args... args ){
	_calltype = calltype;
	using ResultType = typename std::result_of<F(Args...) >::type;
	ResultType _result;
	_fun = std::function<void()>([=]()->void {
		ResultType result = f( args... );
		return;
	    });
    }
    template< class F, class... Args >
    void set_aux( Funwrap3::RetVoid tag, FunCallType calltype, F f, Args... args ){
	_calltype = calltype;
	using ResultType = typename std::result_of<F(Args...) >::type;
	_fun = std::function<void()>([=]()->void {
		f( args... );
		return;
	    });
    }
    void apply(){
	if( nullptr != _fun ){
	    _fun();
	}
	_fun = nullptr;
    }
private:
    std::function<void()> _fun;
    FunCallType _calltype;
};

#endif


text:
LOGFILE=/var/log/postgresql/kill_idle.log

# REQUIRED: set timelimit for oldest idle transaction, in minutes
IDLETIME=15

# REQUIRED: set timelimit for oldest non-idle long-running transaction
# in minutes.  Set to 1000 if you don't really want these cancelled
XACTTIME=120

# REQUIRED: set users to be ignored and not kill idle transactions
# generally you want to omit the postgres superuser and the user
# pg_dump runs as from being killed
# if you have no users like this, just set both to XXXXX
SUPERUSER=postgres
BACKUPUSER=XXXXX

# REQUIRED: path to psql, since cron often lacks search paths
PSQL=/usr/lib/postgresql/9.1/bin/psql

# OPTIONAL: set these connection variables.  if you are running as the
# postgres user on the local machine with passwordless login, you will
# not needto set any of these
PGHOST=
PGUSER=
PGPORT=
PGPASSWORD=

# you should not need to change code below this line
####################################################

export PGHOST
export PGUSER
export PGPORT
export PGPASSWORD
exec >> $LOGFILE 2>&1
SAFELIST="ARRAY['${SUPERUSER}', '${BACKUPUSER}']"
IDLEPARAM="'${IDLETIME} minutes'"
XACTPARAM="'${XACTTIME} minutes'"

KILLQUERY="WITH idles AS (
    SELECT datname, procpid, usename, application_name,
        client_addr, backend_start, xact_start, query_start,
        waiting, pg_terminate_backend(procpid)
    FROM pg_stat_activity
    WHERE current_query = '<IDLE> in transaction'
        AND usename != '${SUPERUSER}'
        AND usename != '${BACKUPUSER}'
        AND ( ( now() - xact_start ) > '${XACTTIME} minutes'
            OR ( now() - query_start ) > '${IDLETIME} minutes' )
)
SELECT array_to_string(ARRAY[ now()::TEXT,
                idles.datname::TEXT, idles.procpid::TEXT, idles.usename::TEXT,
                idles.application_name, idles.client_addr::TEXT,
                idles.backend_start::TEXT, idles.xact_start::TEXT,
                idles.query_start::TEXT, idles.waiting::TEXT], '|')
FROM idles
ORDER BY xact_start;"

$PSQL -q -t -c "${KILLQUERY}"

exit 0


text:
(function(){

	if(steal.options.instrument){
		QUnit.done(function(){
			// send to console
			if(steal.options.browser){
				steal.client.trigger("coverage", steal.instrument.compileStats());
			}
		})
	}

	// if there's a failed assertion, don't run the rest of this test, just fail and move on
	QUnit.log(function(data){
		if(!window.FuncUnit) FuncUnit = {};
		if(data.result === false) {
			FuncUnit._queue = [];
			start();
		}
	})

	if(steal.options.browser === "phantomjs"){
		var ifrm = document.createElement("iframe");
		ifrm.id = 'funcunit_app';
		ifrm.setAttribute("width", "960");
		ifrm.setAttribute("height", "800");
		document.body.insertBefore(ifrm, document.body.firstChild);
	}

	if(steal.options.browser){
		var evts = ['begin', 'testStart', 'testDone', 'moduleStart', 'moduleDone', 'done', 'log'],
			type,
			orig = {};

		for (var i = 0; i < evts.length; i++) {
			type = evts[i];
			(function(type){
				QUnit[type] (function(data){
					if(orig[type]){
						orig[type].apply(this, arguments);
					}

					steal.client.trigger(type, data);
				});
			})(type);
		}
	}

})()


text:
package com.tickaroo.tikxml.annotationprocessing.namespace;

import com.tickaroo.tikxml.annotation.Element;
import com.tickaroo.tikxml.annotation.PropertyElement;
import com.tickaroo.tikxml.annotation.Xml;

/**
 * @author Hannes Dorfmann
 */
@Xml
public class Root {
  @PropertyElement(name = "x:name") String name;
  @Element(name = "m:child") Child child;
}


text:
"""Define AirVisual constants."""
import logging

DOMAIN = "airvisual"
LOGGER = logging.getLogger(__package__)

INTEGRATION_TYPE_GEOGRAPHY = "Geographical Location"
INTEGRATION_TYPE_NODE_PRO = "AirVisual Node/Pro"

CONF_CITY = "city"
CONF_COUNTRY = "country"
CONF_GEOGRAPHIES = "geographies"
CONF_INTEGRATION_TYPE = "integration_type"

DATA_COORDINATOR = "coordinator"


text:
if ENV['COVERAGE']
  require 'coveralls'
  Coveralls.wear!
end

require 'rspec'
require 'rspec-puppet-facts'
include RspecPuppetFacts


text:
import sys
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plot
import matplotlib.ticker as ticker
import numpy as np

LABELS = ['3-Gram', '4-Gram']
TYPES = ['Array', 'Trie']

COLORS = ['#fdcc8a', '#d7301f']
WIDTH = 0.2

Y_LABEL = "Encode Latency (ns per char)"
Y_LABEL_FONT_SIZE = 20

X_LABEL = "Encode Scheme"
X_LABEL_FONT_SIZE = 20

X_TICK_FONT_SIZE = 16
Y_TICK_FONT_SIZE = 16

X_START = 2**9
X_LIMIT = 2**18

LEGEND_FONT_SIZE = 16
LEGEND_POS = 'upper left'

GRAPH_HEIGHT = 4.5 #inches
GRAPH_WIDTH = 8 #inches

BORDER_SIZE = 0.5
BORDER_COLOR = 'black'

CSV_FILE_PATH = "results/microbench/array_trie/lat_email_array.csv"
GRAPH_OUTPUT_PATH = "figures/microbench/array_trie/lat_email_array_trie.pdf"
DICT_ID = 5

data = np.genfromtxt(CSV_FILE_PATH, delimiter=',')
print(data)
array = [data[DICT_ID,0], data[DICT_ID,2]]
trie = [data[DICT_ID,1], data[DICT_ID,3]]

#========================================================================================
mpl.rcParams['ps.useafm'] = True
mpl.rcParams['pdf.use14corefonts'] = True
mpl.rcParams['text.usetex'] = False

mpl.rcParams['text.latex.preamble'] = [
       r'\usepackage{siunitx}',   # i need upright \micro symbols, but you need...
       r'\sisetup{detect-all}',   # ...this to force siunitx to actually use your fonts
       r'\usepackage{helvet}',    # set the normal font here
       r'\usepackage{sansmath}',  # load up the sansmath so that math -> helvet
       r'\sansmath'               # <- tricky! -- gotta actually tell tex to use!
]
#========================================================================================

fig = plot.figure(figsize={GRAPH_HEIGHT, GRAPH_WIDTH})
ax = fig.add_subplot(111)

idx = np.arange(2) / 1.5
ax.bar(idx, array, WIDTH, linewidth = BORDER_SIZE, edgecolor = BORDER_COLOR, color=COLORS[0], label=TYPES[0])
ax.bar(idx + WIDTH, trie, WIDTH, linewidth = BORDER_SIZE, edgecolor = BORDER_COLOR, color=COLORS[1], label=TYPES[1])

ax.set_xticks(idx + WIDTH/ 2)
ax.set_xticklabels(LABELS)

for label in ax.get_xticklabels():
    label.set_fontsize(X_TICK_FONT_SIZE)

for label in ax.get_yticklabels():
    label.set_fontsize(Y_TICK_FONT_SIZE)

ax.set_xlabel(X_LABEL, fontsize=X_LABEL_FONT_SIZE)
ax.set_ylabel(Y_LABEL, fontsize=Y_LABEL_FONT_SIZE)

ax.legend(loc=LEGEND_POS, prop={'size':LEGEND_FONT_SIZE}, ncol=2)

plot.savefig(GRAPH_OUTPUT_PATH, bbox_inches='tight')


text:
function jackLabelEdited(options) {
  return {
    type: 'JACK_LABEL_EDITED',
    bay: options.bay,
    jackType: options.jackType,
    jackIndex: options.jackIndex,
    value: options.value,
  };
}

export default { jackLabelEdited };


text:
//
//  WZYUnlimitedScrollView.h
//  WZYUnlimitedScrollViewDemo
//
//  Created by CoderZYWang on 2017/2/8.
//  Copyright © 2017年 wzy. All rights reserved.
//

#import <UIKit/UIKit.h>

#define SCREENWIDTH [UIScreen mainScreen].bounds.size.width
#define SCREENHEIGHT [UIScreen mainScreen].bounds.size.height
#define HEXCOLOR(hex) [UIColor colorWithRed:((float)((hex & 0xFF0000) >> 16)) / 255.0 green:((float)((hex & 0xFF00) >> 8)) / 255.0 blue:((float)(hex & 0xFF)) / 255.0 alpha:1]

@protocol WZYUnlimitedScrollViewDelegate <NSObject>

/** 内层scroll滚动的过程中 影响外层scroll是否滚动 */
- (void)scrollDidScrollisOutsideScroll:(BOOL)isOutsideScroll;

@end

@interface WZYUnlimitedScrollView : UIView

@property (nonatomic, weak) id <WZYUnlimitedScrollViewDelegate> unlimitedScrollDelegate;

/** 本地图片数组*/
@property (nonatomic, strong) NSArray *imgArray;
/** 网络图片数组*/
@property (nonatomic, strong) NSArray *imgUrlArray;
/** 是否自动轮播滚动(默认为不自动轮播) */
@property (nonatomic, assign) BOOL isAutoScroll;
/** 图片点击调用*/
- (void)touchImageIndexBlock:(void (^)(NSInteger index, NSString *imgUrl))block;

- (instancetype)initWithFrame:(CGRect)frame placeholderImg:(UIImage *)img;

@end

/**
 使用说明:
 01 按照 FirExampleViewController.m 和 SecExampleViewController.m 的集成方法进行集成。集成步骤很简单,不做描述。
 02 集成依赖 UIView+Frame 和 SDWebImage
 03 传入isAutoScroll YES == 自动滚动, NO == 不自动滚动
 */


text:
layout: post
author: jamesma560
title: "Final Project Update"
---

My program is finished. I just need the extra day to do documentation stuff
which will involve putting in comments and writing the overall reflection. I don't have time
to do that in ten minutes (hence why this is so short).

Link to snapshot: https://github.com/jamesma560/INLS560FinalProject


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Hélène Pruvot</title>
    <meta name="description" content="" />

    <base href="http://localhost:3000/">

    <link rel="stylesheet" href="styles/main.css">


text:
require 'simplecov'
require 'simplecov-cobertura'

SimpleCov.formatters = [
    SimpleCov::Formatter::HTMLFormatter,
    SimpleCov::Formatter::CoberturaFormatter
]

SimpleCov.coverage_dir(ENV['COVERAGE_REPORTS'])
SimpleCov.start


text:
import {assert} from 'chai';
import * as path from 'path';
import {Analyzer} from 'polymer-analyzer';
import {ProjectConfig} from 'polymer-project-config';

import {Linter} from '../../linter';
import {registry} from '../../registry';
import {assertExpectedFixes, WarningPrettyPrinter} from '../util';

const fixtures_dir = path.join(__dirname, '..', '..', '..', 'test');
const ruleId = 'dom-module-invalid-attrs';

suite(ruleId, () => {
  let analyzer: Analyzer;
  let warningPrinter: WarningPrettyPrinter;
  let linter: Linter;

  setup(async () => {
    ({analyzer} =
         await ProjectConfig.initializeAnalyzerFromDirectory(fixtures_dir));
    warningPrinter = new WarningPrettyPrinter();
    linter = new Linter(registry.getRules([ruleId]), analyzer);
  });

  test('works in the trivial case', async () => {
    const {warnings} = await linter.lint([]);
    assert.deepEqual([...warnings], []);
  });

  test('gives no warnings for a perfectly fine file', async () => {
    const {warnings} =
        await linter.lint(['perfectly-fine/polymer-element.html']);
    assert.deepEqual([...warnings], []);
  });

  test('warns for a file "is" and "name" dom-modules', async () => {
    const {warnings} = await linter.lint([`${ruleId}/${ruleId}.html`]);
    assert.deepEqual(warningPrinter.prettyPrint(warnings), [
      `
<dom-module name="foo-elem">
            ~~~~`,
      `
<dom-module is="bar-elem">
            ~~`,
      `
<dom-module name="baz-elem" is="zod-elem">
                            ~~`,
      `
<dom-module name="baz-elem" is="zod-elem">
            ~~~~`,
    ]);
  });

  test('applies automatic-safe fixes', async () => {
    await assertExpectedFixes(
        linter,
        analyzer,
        `${ruleId}/before-fixes.html`,
        `${ruleId}/after-fixes.html`);
  });
});


text:
Upload

<?php
$form = new Form('/gallery/doUpload');
echo "

";
echo "<select name='galleryid'>";
foreach ($gallery as $cat) {
    echo "<option value='$cat->id'>$cat->title</option>";
}
echo "</select>

";
if(isset($_SESSION["errorTitle"])){
    echo $_SESSION["errorTitle"];
    unset($_SESSION['errorTitle']);
}
echo $form->text()->name('title')->placeholder('title')->type('text');
if(isset($_SESSION["errorImage"])){
    echo $_SESSION["errorImage"];
    unset($_SESSION['errorImage']);
}
if(isset($_SESSION["errorSize"])){
    echo $_SESSION["errorSize"];
    unset($_SESSION['errorSize']);
}

echo $form->text()->name('image')->placeholder('image')->type('file');
echo $form->submit()->label('Post')->name('post');
$form->end();
?>


text:
function [ res ] = surfdet( img, varargin )

res.detName = 'surfdet';
if isempty(img), res.frames = zeros(3, 0); return; end;

feats = features.utls.surf(img, [], varargin{:});
res = vl_override(res, feats);

end


text:
{% extends "layout.html" %}
{% load url from future %}
{% load i18n %}
{% load staticfiles %}
{% load thumbnail %}
{% load currency_filters %}

{% block extrahead %}

    <link rel="stylesheet" href="{{ STATIC_URL }}brand/css/brand.css" />
{% endblock %}

{% block title %}
{{ queryset_description }} | {{ block.super }}
{% endblock %}

{% block breadcrumbs %}

        {% trans "Home" %}
        /

        {% trans "Brands" %}
        /

{{ queryset_description }}

{% endblock %}

{% block headertext %}
{{ queryset_description }}
{% endblock %}

{% block content %}

        {% if brand_list %}

{%trans "All brands"%}

                    {% for brand in brand_list %}

                            {{ brand.name }}

                    {% endfor %}

        {% else %}

{% trans "No brand data available." %}

        {% endif %}

{% endblock %}


text:
package sos;

import java.util.*;

/**
 * This class simulates a simple, sharable write-only device.
 *
 * @see Sim
 * @see CPU
 * @see SOS
 * @see Device
 */
public class ConsoleDevice implements Device, Runnable
{
    private int m_maxLatency = 1000;   // maximum latency in ns
    private int m_minLatency = 100;    // minimum latnecy in ns
    private int m_Id = -999;           // the OS assigned device ID
    private boolean m_request = false; // is the device currently processing a request?
    private int m_addr = 0;            // address to write to
    private int m_data = 0;            // data associated with the current request
    private InterruptController m_IC;  // reference to the interrupt controller

    /**
     * This constructor uses the default values for latency)
     */
    public ConsoleDevice(InterruptController ic)
    {
        m_IC = ic;
    }

    /**
     * This constructor expects values for the minimum and maximum latency
     * of this device expressed as a number of nanoseconds
     */
    public ConsoleDevice(InterruptController ic, int min, int max)
    {
        //If latencies are out of order swap them
        if (min > max)
        {
            int tmp = max;
            max = min;
            min = tmp;
        }

        m_minLatency = min;
        m_maxLatency = max;
        m_IC = ic;
    }//ctor

    /**
     * getId
     *
     * @return the device id of this device
     */
    public int getId()
    {
        return m_Id;
    }

    /**
     * setId
     *
     * sets the device id of this device
     *
     * @param id the new id
     */
    public void setId(int id)
    {
        m_Id = id;
    }

    /**
     * isSharable
     *
     * This device can be used simultaneously by multiple processes
     *
     * @return true
     */
    public boolean isSharable()
    {
        return true;
    }

    /**
     * isAvailable
     *
     * this device is available if no requests are currently being processed
     */
    public boolean isAvailable()
    {
        return !m_request;
    }

    /**
     * isReadable
     *
     * @return whether this device can be read from (true/false)
     */
    public boolean isReadable()
    {
        return false;
    }

    /**
     * isWriteable
     *
     * @return whether this device can be written to (true/false)
     */
    public boolean isWriteable()
    {
        return true;
    }

    /**
     * read
     *
     * not implemented
     *
     */
    public int read(int addr /*not used*/)
    {
        //This method should never be called
        return -1;
    }//read

    /**
     * write
     *
     * method records a request for service from the device and as such is
     * analagous to setting a value in a register on the device's controller.
     * As a result, the function does not check to make sure that the
     * device is ready for this request (that's the OS's job).
     */
    public void write(int addr /*not used*/, int data)
    {
        m_addr = addr;
        m_data = data;
        m_request = true;
    }

    /**
     * run
     *
     * This method represents the device + controller.  It watches for reqeusts
     * (via m_request and m_data) and handles them.  It also inserts a random
     * latency to simulate the amount of time required.
     *
     * (I have no idea whether the default latency setting (500-1000 ns) is at
     * all realistic and, of course, the time spent calling System.out.println
     * and Math.random() probably overshadows it.  If someone has info on raw
     * video latencies I will change this code to reflect that data.)
     */
    public void run()
    {
        //Device runs until program ends
        while(true)
        {
            //While there is no request to process, yield the CPU to another thread
            while (!m_request)
            {
                Thread.yield();
            }

            //We've received a request.  Sleep to simulate the latency
            try
            {
                int rn = (int)(Math.random() * 2147483647); // random #
                int latency = (rn % (m_maxLatency - m_minLatency)) + m_minLatency;
                Thread.sleep(latency / 1000, latency % 1000);
            }
            catch(InterruptedException e) {} // should never happen

            //print the data
            System.out.println("\nCONSOLE: " + m_data);

            //Notify the CPU of completed operation
            m_IC.putData(InterruptController.INT_WRITE_DONE, m_Id, m_addr, -999);

            //Make the device available for another request
            m_request = false;
        }//while
    }//run

}//class ConsoleDevice


text:
// Copyright (c) 2011-2016 The Flericoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "TransfersContainer.h"
#include "IWalletLegacy.h"
#include "Common/StdInputStream.h"
#include "Common/StdOutputStream.h"
#include "CryptoNoteCore/CryptoNoteFormatUtils.h"
#include "Serialization/BinaryInputStreamSerializer.h"
#include "Serialization/BinaryOutputStreamSerializer.h"
#include "Serialization/SerializationOverloads.h"

using namespace Common;
using namespace Crypto;

namespace CryptoNote {

void serialize(TransactionInformation& ti, CryptoNote::ISerializer& s) {
  s(ti.transactionHash, "");
  s(ti.publicKey, "");
  serializeBlockHeight(s, ti.blockHeight, "");
  s(ti.timestamp, "");
  s(ti.unlockTime, "");
  s(ti.totalAmountIn, "");
  s(ti.totalAmountOut, "");
  s(ti.extra, "");
  s(ti.paymentId, "");
}

const uint32_t TRANSFERS_CONTAINER_STORAGE_VERSION = 0;

namespace {
  template<typename TIterator>
  class TransferIteratorList {
  public:
    TransferIteratorList(const TIterator& begin, const TIterator& end) : m_end(end) {
      for (auto it = begin; it != end; ++it) {
        m_list.emplace_back(it);
      }
    }

    TransferIteratorList(TransferIteratorList<TIterator>&& other) {
      m_list = std::move(other.m_list);
      m_end = std::move(other.m_end);
    }

    TransferIteratorList& operator=(TransferIteratorList<TIterator>&& other) {
      m_list = std::move(other.m_list);
      m_end = std::move(other.m_end);
      return *this;
    }

    void sort() {
      std::sort(m_list.begin(), m_list.end(), &TransferIteratorList::lessTIterator);
    }

    TIterator findFirstByAmount(uint64_t amount) const {
      auto listIt = std::find_if(m_list.begin(), m_list.end(), [amount](const TIterator& it) {
        return it->amount == amount;
      });
      return listIt == m_list.end() ? m_end : *listIt;
    }

    TIterator minElement() const {
      auto listIt = std::min_element(m_list.begin(), m_list.end(), &TransferIteratorList::lessTIterator);
      return listIt == m_list.end() ? m_end : *listIt;
    }

  private:
    static bool lessTIterator(const TIterator& it1, const TIterator& it2) {
      return
        (it1->blockHeight < it2->blockHeight) ||
        (it1->blockHeight == it2->blockHeight && it1->transactionIndex < it2->transactionIndex);
    }

  private:
    std::vector<TIterator> m_list;
    TIterator m_end;
  };

  template<typename TIterator>
  TransferIteratorList<TIterator> createTransferIteratorList(const std::pair<TIterator, TIterator>& itPair) {
    return TransferIteratorList<TIterator>(itPair.first, itPair.second);
  }
}

SpentOutputDescriptor::SpentOutputDescriptor() :
    m_type(TransactionTypes::OutputType::Invalid) {
}

SpentOutputDescriptor::SpentOutputDescriptor(const TransactionOutputInformationIn& transactionInfo) :
    m_type(transactionInfo.type),
    m_amount(0),
    m_globalOutputIndex(0) {
  if (m_type == TransactionTypes::OutputType::Key) {
    m_keyImage = &transactionInfo.keyImage;
  } else if (m_type == TransactionTypes::OutputType::Multisignature) {
    m_amount = transactionInfo.amount;
    m_globalOutputIndex = transactionInfo.globalOutputIndex;
  } else {
    assert(false);
  }
}

SpentOutputDescriptor::SpentOutputDescriptor(const KeyImage* keyImage) {
  assign(keyImage);
}

SpentOutputDescriptor::SpentOutputDescriptor(uint64_t amount, uint32_t globalOutputIndex) {
  assign(amount, globalOutputIndex);
}

void SpentOutputDescriptor::assign(const KeyImage* keyImage) {
  m_type = TransactionTypes::OutputType::Key;
  m_keyImage = keyImage;
}

void SpentOutputDescriptor::assign(uint64_t amount, uint32_t globalOutputIndex) {
  m_type = TransactionTypes::OutputType::Multisignature;
  m_amount = amount;
  m_globalOutputIndex = globalOutputIndex;
}

bool SpentOutputDescriptor::isValid() const {
  return m_type != TransactionTypes::OutputType::Invalid;
}

bool SpentOutputDescriptor::operator==(const SpentOutputDescriptor& other) const {
  if (m_type == TransactionTypes::OutputType::Key) {
    return other.m_type == m_type && *other.m_keyImage == *m_keyImage;
  } else if (m_type == TransactionTypes::OutputType::Multisignature) {
    return other.m_type == m_type && other.m_amount == m_amount && other.m_globalOutputIndex == m_globalOutputIndex;
  } else {
    assert(false);
    return false;
  }
}

size_t SpentOutputDescriptor::hash() const {
  if (m_type == TransactionTypes::OutputType::Key) {
    static_assert(sizeof(size_t) < sizeof(*m_keyImage), "sizeof(size_t) < sizeof(*m_keyImage)");
    return *reinterpret_cast<const size_t*>(m_keyImage->data);
  } else if (m_type == TransactionTypes::OutputType::Multisignature) {
    size_t hashValue = boost::hash_value(m_amount);
    boost::hash_combine(hashValue, m_globalOutputIndex);
    return hashValue;
  } else {
    assert(false);
    return 0;
  }
}

TransfersContainer::TransfersContainer(const Currency& currency, size_t transactionSpendableAge) :
  m_currentHeight(0),
  m_currency(currency),
  m_transactionSpendableAge(transactionSpendableAge) {
}

bool TransfersContainer::addTransaction(const TransactionBlockInfo& block, const ITransactionReader& tx,
  const std::vector<TransactionOutputInformationIn>& transfers) {
  std::unique_lock<std::mutex> lock(m_mutex);

  if (block.height < m_currentHeight) {
    throw std::invalid_argument("Cannot add transaction from block < m_currentHeight");
  }

  if (m_transactions.count(tx.getTransactionHash()) > 0) {
    throw std::invalid_argument("Transaction is already added");
  }

  bool added = addTransactionOutputs(block, tx, transfers);
  added |= addTransactionInputs(block, tx);

  if (added) {
    addTransaction(block, tx);
  }

  if (block.height != WALLET_LEGACY_UNCONFIRMED_TRANSACTION_HEIGHT) {
    m_currentHeight = block.height;
  }

  return added;
}

/**
 * \pre m_mutex is locked.
 */
void TransfersContainer::addTransaction(const TransactionBlockInfo& block, const ITransactionReader& tx) {
  auto txHash = tx.getTransactionHash();

  TransactionInformation txInfo;
  txInfo.blockHeight = block.height;
  txInfo.timestamp = block.timestamp;
  txInfo.transactionHash = txHash;
  txInfo.unlockTime = tx.getUnlockTime();
  txInfo.publicKey = tx.getTransactionPublicKey();
  txInfo.totalAmountIn = tx.getInputTotalAmount();
  txInfo.totalAmountOut = tx.getOutputTotalAmount();
  txInfo.extra = tx.getExtra();

  if (!tx.getPaymentId(txInfo.paymentId)) {
    txInfo.paymentId = NULL_HASH;
  }

  auto result = m_transactions.emplace(std::move(txInfo));
  (void)result; // Disable unused warning
  assert(result.second);
}

/**
 * \pre m_mutex is locked.
 */
bool TransfersContainer::addTransactionOutputs(const TransactionBlockInfo& block, const ITransactionReader& tx,
                                               const std::vector<TransactionOutputInformationIn>& transfers) {
  bool outputsAdded = false;

  auto txHash = tx.getTransactionHash();
  bool transactionIsUnconfimed = (block.height == WALLET_LEGACY_UNCONFIRMED_TRANSACTION_HEIGHT);
  for (const auto& transfer : transfers) {
    assert(transfer.outputInTransaction < tx.getOutputCount());
    assert(transfer.type == tx.getOutputType(transfer.outputInTransaction));
    assert(transfer.amount > 0);

    bool transferIsUnconfirmed = (transfer.globalOutputIndex == UNCONFIRMED_TRANSACTION_GLOBAL_OUTPUT_INDEX);
    if (transactionIsUnconfimed != transferIsUnconfirmed) {
      throw std::invalid_argument("Bad transfer's globalOutputIndex");
    }

    TransactionOutputInformationEx info;
    static_cast<TransactionOutputInformationIn&>(info) = transfer;
    info.blockHeight = block.height;
    info.transactionIndex = block.transactionIndex;
    info.unlockTime = tx.getUnlockTime();
    info.transactionHash = txHash;
    info.visible = true;

    if (transferIsUnconfirmed) {
      auto result = m_unconfirmedTransfers.emplace(std::move(info));
      (void)result; // Disable unused warning
      assert(result.second);
    } else {
      if (info.type == TransactionTypes::OutputType::Multisignature) {
        SpentOutputDescriptor descriptor(transfer);
        if (m_availableTransfers.get<SpentOutputDescriptorIndex>().count(descriptor) > 0 ||
            m_spentTransfers.get<SpentOutputDescriptorIndex>().count(descriptor) > 0) {
          throw std::runtime_error("Transfer already exists");
        }
      }

      auto result = m_availableTransfers.emplace(std::move(info));
      (void)result; // Disable unused warning
      assert(result.second);
    }

    if (info.type == TransactionTypes::OutputType::Key) {
      updateTransfersVisibility(info.keyImage);
    }

    outputsAdded = true;
  }

  return outputsAdded;
}

/**
 * \pre m_mutex is locked.
 */
bool TransfersContainer::addTransactionInputs(const TransactionBlockInfo& block, const ITransactionReader& tx) {
  bool inputsAdded = false;

  for (size_t i = 0; i < tx.getInputCount(); ++i) {
    auto inputType = tx.getInputType(i);

    if (inputType == TransactionTypes::InputType::Key) {
      KeyInput input;
      tx.getInput(i, input);

      SpentOutputDescriptor descriptor(&input.keyImage);
      auto spentRange = m_spentTransfers.get<SpentOutputDescriptorIndex>().equal_range(descriptor);
      if (std::distance(spentRange.first, spentRange.second) > 0) {
        throw std::runtime_error("Spending already spent transfer");
      }

      auto availableRange = m_availableTransfers.get<SpentOutputDescriptorIndex>().equal_range(descriptor);
      auto unconfirmedRange = m_unconfirmedTransfers.get<SpentOutputDescriptorIndex>().equal_range(descriptor);
      size_t availableCount = std::distance(availableRange.first, availableRange.second);
      size_t unconfirmedCount = std::distance(unconfirmedRange.first, unconfirmedRange.second);

      if (availableCount == 0) {
        if (unconfirmedCount > 0) {
          throw std::runtime_error("Spending unconfirmed transfer");
        } else {
          // This input doesn't spend any transfer from this container
          continue;
        }
      }

      auto& outputDescriptorIndex = m_availableTransfers.get<SpentOutputDescriptorIndex>();
      auto availableOutputsRange = outputDescriptorIndex.equal_range(SpentOutputDescriptor(&input.keyImage));

      auto iteratorList = createTransferIteratorList(availableOutputsRange);
      iteratorList.sort();
      auto spendingTransferIt = iteratorList.findFirstByAmount(input.amount);

      if (spendingTransferIt == availableOutputsRange.second) {
        throw std::runtime_error("Input has invalid amount, corresponding output isn't found");
      }

      assert(spendingTransferIt->keyImage == input.keyImage);
      copyToSpent(block, tx, i, *spendingTransferIt);
      // erase from available outputs
      outputDescriptorIndex.erase(spendingTransferIt);
      updateTransfersVisibility(input.keyImage);

      inputsAdded = true;
    } else if (inputType == TransactionTypes::InputType::Multisignature) {
      MultisignatureInput input;
      tx.getInput(i, input);

      auto& outputDescriptorIndex = m_availableTransfers.get<SpentOutputDescriptorIndex>();
      auto availableOutputIt = outputDescriptorIndex.find(SpentOutputDescriptor(input.amount, input.outputIndex));
      if (availableOutputIt != outputDescriptorIndex.end()) {
        copyToSpent(block, tx, i, *availableOutputIt);
        // erase from available outputs
        outputDescriptorIndex.erase(availableOutputIt);

        inputsAdded = true;
      }
    } else {
      assert(inputType == TransactionTypes::InputType::Generating);
    }
  }

  return inputsAdded;
}

bool TransfersContainer::deleteUnconfirmedTransaction(const Hash& transactionHash) {
  std::unique_lock<std::mutex> lock(m_mutex);

  auto it = m_transactions.find(transactionHash);
  if (it == m_transactions.end()) {
    return false;
  } else if (it->blockHeight != WALLET_LEGACY_UNCONFIRMED_TRANSACTION_HEIGHT) {
    return false;
  } else {
    deleteTransactionTransfers(it->transactionHash);
    m_transactions.erase(it);
    return true;
  }
}

bool TransfersContainer::markTransactionConfirmed(const TransactionBlockInfo& block, const Hash& transactionHash,
                                                  const std::vector<uint32_t>& globalIndices) {
  if (block.height == WALLET_LEGACY_UNCONFIRMED_TRANSACTION_HEIGHT) {
    throw std::invalid_argument("Block height equals WALLET_LEGACY_UNCONFIRMED_TRANSACTION_HEIGHT");
  }

  std::unique_lock<std::mutex> lock(m_mutex);

  auto transactionIt = m_transactions.find(transactionHash);
  if (transactionIt == m_transactions.end()) {
    return false;
  }

  if (transactionIt->blockHeight != WALLET_LEGACY_UNCONFIRMED_TRANSACTION_HEIGHT) {
    return false;
  }

  auto txInfo = *transactionIt;
  txInfo.blockHeight = block.height;
  txInfo.timestamp = block.timestamp;
  m_transactions.replace(transactionIt, txInfo);

  auto availableRange = m_unconfirmedTransfers.get<ContainingTransactionIndex>().equal_range(transactionHash);
  for (auto transferIt = availableRange.first; transferIt != availableRange.second; ) {
    auto transfer = *transferIt;
    assert(transfer.blockHeight == WALLET_LEGACY_UNCONFIRMED_TRANSACTION_HEIGHT);
    assert(transfer.globalOutputIndex == UNCONFIRMED_TRANSACTION_GLOBAL_OUTPUT_INDEX);
    if (transfer.outputInTransaction >= globalIndices.size()) {
      throw std::invalid_argument("Not enough elements in globalIndices");
    }

    transfer.blockHeight = block.height;
    transfer.transactionIndex = block.transactionIndex;
    transfer.globalOutputIndex = globalIndices[transfer.outputInTransaction];

    if (transfer.type == TransactionTypes::OutputType::Multisignature) {
      SpentOutputDescriptor descriptor(transfer);
      if (m_availableTransfers.get<SpentOutputDescriptorIndex>().count(descriptor) > 0 ||
          m_spentTransfers.get<SpentOutputDescriptorIndex>().count(descriptor) > 0) {
        // This exception breaks TransfersContainer consistency
        throw std::runtime_error("Transfer already exists");
      }
    }

    auto result = m_availableTransfers.emplace(std::move(transfer));
    (void)result; // Disable unused warning
    assert(result.second);

    transferIt = m_unconfirmedTransfers.get<ContainingTransactionIndex>().erase(transferIt);

    if (transfer.type == TransactionTypes::OutputType::Key) {
      updateTransfersVisibility(transfer.keyImage);
    }
  }

  auto& spendingTransactionIndex = m_spentTransfers.get<SpendingTransactionIndex>();
  auto spentRange = spendingTransactionIndex.equal_range(transactionHash);
  for (auto transferIt = spentRange.first; transferIt != spentRange.second; ++transferIt) {
    auto transfer = *transferIt;
    assert(transfer.spendingBlock.height == WALLET_LEGACY_UNCONFIRMED_TRANSACTION_HEIGHT);

    transfer.spendingBlock = block;
    spendingTransactionIndex.replace(transferIt, transfer);
  }

  return true;
}

/**
 * \pre m_mutex is locked.
 */
void TransfersContainer::deleteTransactionTransfers(const Hash& transactionHash) {
  auto& spendingTransactionIndex = m_spentTransfers.get<SpendingTransactionIndex>();
  auto spentTransfersRange = spendingTransactionIndex.equal_range(transactionHash);
  for (auto it = spentTransfersRange.first; it != spentTransfersRange.second;) {
    assert(it->blockHeight != WALLET_LEGACY_UNCONFIRMED_TRANSACTION_HEIGHT);
    assert(it->globalOutputIndex != UNCONFIRMED_TRANSACTION_GLOBAL_OUTPUT_INDEX);

    auto result = m_availableTransfers.emplace(static_cast<const TransactionOutputInformationEx&>(*it));
    assert(result.second);
    it = spendingTransactionIndex.erase(it);

    if (result.first->type == TransactionTypes::OutputType::Key) {
      updateTransfersVisibility(result.first->keyImage);
    }
  }

  auto unconfirmedTransfersRange = m_unconfirmedTransfers.get<ContainingTransactionIndex>().equal_range(transactionHash);
  for (auto it = unconfirmedTransfersRange.first; it != unconfirmedTransfersRange.second;) {
    if (it->type == TransactionTypes::OutputType::Key) {
      KeyImage keyImage = it->keyImage;
      it = m_unconfirmedTransfers.get<ContainingTransactionIndex>().erase(it);
      updateTransfersVisibility(keyImage);
    } else {
      it = m_unconfirmedTransfers.get<ContainingTransactionIndex>().erase(it);
    }
  }

  auto& transactionTransfersIndex = m_availableTransfers.get<ContainingTransactionIndex>();
  auto transactionTransfersRange = transactionTransfersIndex.equal_range(transactionHash);
  for (auto it = transactionTransfersRange.first; it != transactionTransfersRange.second;) {
    if (it->type == TransactionTypes::OutputType::Key) {
      KeyImage keyImage = it->keyImage;
    it = transactionTransfersIndex.erase(it);
      updateTransfersVisibility(keyImage);
    } else {
      it = transactionTransfersIndex.erase(it);
    }
  }
}

/**
 * \pre m_mutex is locked.
 */
void TransfersContainer::copyToSpent(const TransactionBlockInfo& block, const ITransactionReader& tx, size_t inputIndex,
                                     const TransactionOutputInformationEx& output) {
  assert(output.blockHeight != WALLET_LEGACY_UNCONFIRMED_TRANSACTION_HEIGHT);
  assert(output.globalOutputIndex != UNCONFIRMED_TRANSACTION_GLOBAL_OUTPUT_INDEX);

  SpentTransactionOutput spentOutput;
  static_cast<TransactionOutputInformationEx&>(spentOutput) = output;
  spentOutput.spendingBlock = block;
  spentOutput.spendingTransactionHash = tx.getTransactionHash();
  spentOutput.inputInTransaction = static_cast<uint32_t>(inputIndex);
  auto result = m_spentTransfers.emplace(std::move(spentOutput));
  (void)result; // Disable unused warning
  assert(result.second);
}

std::vector<Hash> TransfersContainer::detach(uint32_t height) {
  // This method expects that WALLET_LEGACY_UNCONFIRMED_TRANSACTION_HEIGHT is a big positive number
  assert(height < WALLET_LEGACY_UNCONFIRMED_TRANSACTION_HEIGHT);

  std::lock_guard<std::mutex> lk(m_mutex);

  std::vector<Hash> deletedTransactions;
  auto& spendingTransactionIndex = m_spentTransfers.get<SpendingTransactionIndex>();
  auto& blockHeightIndex = m_transactions.get<1>();
  auto it = blockHeightIndex.end();
  while (it != blockHeightIndex.begin()) {
    --it;

    bool doDelete = false;
    if (it->blockHeight == WALLET_LEGACY_UNCONFIRMED_TRANSACTION_HEIGHT) {
      auto range = spendingTransactionIndex.equal_range(it->transactionHash);
      for (auto spentTransferIt = range.first; spentTransferIt != range.second; ++spentTransferIt) {
        if (spentTransferIt->blockHeight >= height) {
          doDelete = true;
          break;
        }
      }
    } else if (it->blockHeight >= height) {
      doDelete = true;
    } else {
      break;
    }

    if (doDelete) {
      deleteTransactionTransfers(it->transactionHash);
      deletedTransactions.emplace_back(it->transactionHash);
      it = blockHeightIndex.erase(it);
    }
  }

  // TODO: notification on detach
  m_currentHeight = height == 0 ? 0 : height - 1;

  return deletedTransactions;
}

namespace {
  template<typename C, typename T>
  void updateVisibility(C& collection, const T& range, bool visible) {
    for (auto it = range.first; it != range.second; ++it) {
      auto updated = *it;
      updated.visible = visible;
      collection.replace(it, updated);
    }
  }
}

/**
 * \pre m_mutex is locked.
 */
void TransfersContainer::updateTransfersVisibility(const KeyImage& keyImage) {
  auto& unconfirmedIndex = m_unconfirmedTransfers.get<SpentOutputDescriptorIndex>();
  auto& availableIndex = m_availableTransfers.get<SpentOutputDescriptorIndex>();
  auto& spentIndex = m_spentTransfers.get<SpentOutputDescriptorIndex>();

  SpentOutputDescriptor descriptor(&keyImage);
  auto unconfirmedRange = unconfirmedIndex.equal_range(descriptor);
  auto availableRange = availableIndex.equal_range(descriptor);
  auto spentRange = spentIndex.equal_range(descriptor);

  size_t unconfirmedCount = std::distance(unconfirmedRange.first, unconfirmedRange.second);
  size_t availableCount = std::distance(availableRange.first, availableRange.second);
  size_t spentCount = std::distance(spentRange.first, spentRange.second);
  assert(spentCount == 0 || spentCount == 1);

  if (spentCount > 0) {
    updateVisibility(unconfirmedIndex, unconfirmedRange, false);
    updateVisibility(availableIndex, availableRange, false);
    updateVisibility(spentIndex, spentRange, true);
  } else if (availableCount > 0) {
    updateVisibility(unconfirmedIndex, unconfirmedRange, false);
    updateVisibility(availableIndex, availableRange, false);

    auto iteratorList = createTransferIteratorList(availableRange);
    auto earliestTransferIt = iteratorList.minElement();
    assert(earliestTransferIt != availableRange.second);

    auto earliestTransfer = *earliestTransferIt;
    earliestTransfer.visible = true;
    availableIndex.replace(earliestTransferIt, earliestTransfer);
  } else {
    updateVisibility(unconfirmedIndex, unconfirmedRange, unconfirmedCount == 1);
  }
}

bool TransfersContainer::advanceHeight(uint32_t height) {
  std::lock_guard<std::mutex> lk(m_mutex);

  if (m_currentHeight <= height) {
    m_currentHeight = height;
    return true;
  }

  return false;
}

size_t TransfersContainer::transfersCount() const {
  std::lock_guard<std::mutex> lk(m_mutex);
  return m_unconfirmedTransfers.size() + m_availableTransfers.size() + m_spentTransfers.size();
}

size_t TransfersContainer::transactionsCount() const {
  std::lock_guard<std::mutex> lk(m_mutex);
  return m_transactions.size();
}

uint64_t TransfersContainer::balance(uint32_t flags) const {
  std::lock_guard<std::mutex> lk(m_mutex);
  uint64_t amount = 0;

  for (const auto& t : m_availableTransfers) {
    if (t.visible && isIncluded(t, flags)) {
      amount += t.amount;
    }
  }

  if ((flags & IncludeStateLocked) != 0) {
    for (const auto& t : m_unconfirmedTransfers) {
      if (t.visible && isIncluded(t.type, IncludeStateLocked, flags)) {
        amount += t.amount;
      }
    }
  }

  return amount;
}

void TransfersContainer::getOutputs(std::vector<TransactionOutputInformation>& transfers, uint32_t flags) const {
  std::lock_guard<std::mutex> lk(m_mutex);
  for (const auto& t : m_availableTransfers) {
    if (t.visible && isIncluded(t, flags)) {
      transfers.push_back(t);
    }
  }

  if ((flags & IncludeStateLocked) != 0) {
    for (const auto& t : m_unconfirmedTransfers) {
      if (t.visible && isIncluded(t.type, IncludeStateLocked, flags)) {
        transfers.push_back(t);
      }
    }
  }
}

bool TransfersContainer::getTransactionInformation(const Hash& transactionHash, TransactionInformation& info, uint64_t* amountIn, uint64_t* amountOut) const {
  std::lock_guard<std::mutex> lk(m_mutex);
  auto it = m_transactions.find(transactionHash);
  if (it == m_transactions.end()) {
    return false;
  }

  info = *it;

  if (amountOut != nullptr) {
    *amountOut = 0;

    if (info.blockHeight == WALLET_LEGACY_UNCONFIRMED_TRANSACTION_HEIGHT) {
      auto unconfirmedOutputsRange = m_unconfirmedTransfers.get<ContainingTransactionIndex>().equal_range(transactionHash);
      for (auto it = unconfirmedOutputsRange.first; it != unconfirmedOutputsRange.second; ++it) {
        *amountOut += it->amount;
      }
    } else {
      auto availableOutputsRange = m_availableTransfers.get<ContainingTransactionIndex>().equal_range(transactionHash);
      for (auto it = availableOutputsRange.first; it != availableOutputsRange.second; ++it) {
        *amountOut += it->amount;
      }

      auto spentOutputsRange = m_spentTransfers.get<ContainingTransactionIndex>().equal_range(transactionHash);
      for (auto it = spentOutputsRange.first; it != spentOutputsRange.second; ++it) {
        *amountOut += it->amount;
      }
    }
  }

  if (amountIn != nullptr) {
    *amountIn = 0;
    auto rangeInputs = m_spentTransfers.get<SpendingTransactionIndex>().equal_range(transactionHash);
    for (auto it = rangeInputs.first; it != rangeInputs.second; ++it) {
      *amountIn += it->amount;
    }
  }

  return true;
}

std::vector<TransactionOutputInformation> TransfersContainer::getTransactionOutputs(const Hash& transactionHash,
                                                                                uint32_t flags) const {
  std::lock_guard<std::mutex> lk(m_mutex);

  std::vector<TransactionOutputInformation> result;

  auto availableRange = m_availableTransfers.get<ContainingTransactionIndex>().equal_range(transactionHash);
  for (auto i = availableRange.first; i != availableRange.second; ++i) {
    const auto& t = *i;
    if (isIncluded(t, flags)) {
      result.push_back(t);
    }
  }

  if ((flags & IncludeStateLocked) != 0) {
    auto unconfirmedRange = m_unconfirmedTransfers.get<ContainingTransactionIndex>().equal_range(transactionHash);
    for (auto i = unconfirmedRange.first; i != unconfirmedRange.second; ++i) {
      if (isIncluded(i->type, IncludeStateLocked, flags)) {
        result.push_back(*i);
      }
    }
  }

  if ((flags & IncludeStateSpent) != 0) {
    auto spentRange = m_spentTransfers.get<ContainingTransactionIndex>().equal_range(transactionHash);
    for (auto i = spentRange.first; i != spentRange.second; ++i) {
      if (isIncluded(i->type, IncludeStateAll, flags)) {
        result.push_back(*i);
      }
    }
  }

  return result;
}

std::vector<TransactionOutputInformation> TransfersContainer::getTransactionInputs(const Hash& transactionHash, uint32_t flags) const {
  //only type flags are feasible
  assert((flags & IncludeStateAll) == 0);
  flags |= IncludeStateUnlocked;

  std::lock_guard<std::mutex> lk(m_mutex);

  std::vector<TransactionOutputInformation> result;
  auto transactionInputsRange = m_spentTransfers.get<SpendingTransactionIndex>().equal_range(transactionHash);
  for (auto it = transactionInputsRange.first; it != transactionInputsRange.second; ++it) {
    if (isIncluded(it->type, IncludeStateUnlocked, flags)) {
      result.push_back(*it);
    }
  }

  return result;
}

void TransfersContainer::getUnconfirmedTransactions(std::vector<Crypto::Hash>& transactions) const {
  std::lock_guard<std::mutex> lk(m_mutex);
  transactions.clear();
  for (auto& element : m_transactions) {
    if (element.blockHeight == WALLET_LEGACY_UNCONFIRMED_TRANSACTION_HEIGHT) {
      transactions.push_back(*reinterpret_cast<const Crypto::Hash*>(&element.transactionHash));
    }
  }
}

std::vector<TransactionSpentOutputInformation> TransfersContainer::getSpentOutputs() const {
  std::lock_guard<std::mutex> lk(m_mutex);

  std::vector<TransactionSpentOutputInformation> spentOutputs;

  spentOutputs.reserve(m_spentTransfers.size());

  for (const auto& o : m_spentTransfers) {
    TransactionSpentOutputInformation spentOutput;
    static_cast<TransactionOutputInformation&>(spentOutput) = o;

    spentOutput.spendingBlockHeight = o.spendingBlock.height;
    spentOutput.timestamp = o.spendingBlock.timestamp;
    spentOutput.spendingTransactionHash = o.spendingTransactionHash;
    spentOutput.keyImage = o.keyImage;
    spentOutput.inputInTransaction = o.inputInTransaction;

    spentOutputs.push_back(spentOutput);
  }

  return spentOutputs;
}

void TransfersContainer::save(std::ostream& os) {
  std::lock_guard<std::mutex> lk(m_mutex);
  StdOutputStream stream(os);
  CryptoNote::BinaryOutputStreamSerializer s(stream);

  s(const_cast<uint32_t&>(TRANSFERS_CONTAINER_STORAGE_VERSION), "version");

  s(m_currentHeight, "height");
  writeSequence<TransactionInformation>(m_transactions.begin(), m_transactions.end(), "transactions", s);
  writeSequence<TransactionOutputInformationEx>(m_unconfirmedTransfers.begin(), m_unconfirmedTransfers.end(), "unconfirmedTransfers", s);
  writeSequence<TransactionOutputInformationEx>(m_availableTransfers.begin(), m_availableTransfers.end(), "availableTransfers", s);
  writeSequence<SpentTransactionOutput>(m_spentTransfers.begin(), m_spentTransfers.end(), "spentTransfers", s);
}

void TransfersContainer::load(std::istream& in) {
  std::lock_guard<std::mutex> lk(m_mutex);
  StdInputStream stream(in);
  CryptoNote::BinaryInputStreamSerializer s(stream);

  uint32_t version = 0;
  s(version, "version");

  if (version > TRANSFERS_CONTAINER_STORAGE_VERSION) {
    throw std::runtime_error("Unsupported transfers storage version");
  }

  uint32_t currentHeight = 0;
  TransactionMultiIndex transactions;
  UnconfirmedTransfersMultiIndex unconfirmedTransfers;
  AvailableTransfersMultiIndex availableTransfers;
  SpentTransfersMultiIndex spentTransfers;

  s(currentHeight, "height");
  readSequence<TransactionInformation>(std::inserter(transactions, transactions.end()), "transactions", s);
  readSequence<TransactionOutputInformationEx>(std::inserter(unconfirmedTransfers, unconfirmedTransfers.end()), "unconfirmedTransfers", s);
  readSequence<TransactionOutputInformationEx>(std::inserter(availableTransfers, availableTransfers.end()), "availableTransfers", s);
  readSequence<SpentTransactionOutput>(std::inserter(spentTransfers, spentTransfers.end()), "spentTransfers", s);

  m_currentHeight = currentHeight;
  m_transactions = std::move(transactions);
  m_unconfirmedTransfers = std::move(unconfirmedTransfers);
  m_availableTransfers = std::move(availableTransfers);
  m_spentTransfers = std::move(spentTransfers);
}

bool TransfersContainer::isSpendTimeUnlocked(uint64_t unlockTime) const {
  if (unlockTime < m_currency.maxBlockHeight()) {
    // interpret as block index
    return m_currentHeight + m_currency.lockedTxAllowedDeltaBlocks() >= unlockTime;
  } else {
    //interpret as time
    uint64_t current_time = static_cast<uint64_t>(time(NULL));
    return current_time + m_currency.lockedTxAllowedDeltaSeconds() >= unlockTime;
  }

  return false;
}

bool TransfersContainer::isIncluded(const TransactionOutputInformationEx& info, uint32_t flags) const {
  uint32_t state;
  if (info.blockHeight == WALLET_LEGACY_UNCONFIRMED_TRANSACTION_HEIGHT || !isSpendTimeUnlocked(info.unlockTime)) {
    state = IncludeStateLocked;
  } else if (m_currentHeight < info.blockHeight + m_transactionSpendableAge) {
    state = IncludeStateSoftLocked;
  } else {
    state = IncludeStateUnlocked;
  }

  return isIncluded(info.type, state, flags);
}

bool TransfersContainer::isIncluded(TransactionTypes::OutputType type, uint32_t state, uint32_t flags) {
  return
    // filter by type
    (
    ((flags & IncludeTypeKey) != 0            && type == TransactionTypes::OutputType::Key) ||
    ((flags & IncludeTypeMultisignature) != 0 && type == TransactionTypes::OutputType::Multisignature)
    )
    &&
    // filter by state
    ((flags & state) != 0);
}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Pertusaria superans var. superans Müll. Arg.

### Remarks
null


text:
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import log_loss
from sklearn.metrics import precision_score, recall_score, roc_auc_score
import numpy as np
import matplotlib.pyplot as plt

def zero_one_score(y, pred_y):
    total_errors =  np.sum( np.abs(y - pred_y) )
    return total_errors / len(y)

def run_predict_logistic_regression(X_train,Y_train,X_test,Y_test):
    clf = LogisticRegression()
    clf = clf.fit(X_train, Y_train)
    pred = clf.predict(X_test)
    print('Logistic 0-1 error. \n Training: ', zero_one_score(Y_train, clf.predict(X_train)),
          '\n Test:', zero_one_score(Y_test, pred))

    return clf

def show_im(im):
    plt.imshow(im, cmap='gray')
    plt.show()

def run_forests():
    print('random forest: \n')
    params = []
    scores = []

    for _ in range(5):
        max_features = np.random.randint(400,800)
        max_depth = np.random.choice([None, None, None, None, 30, 40, 60])
        forest = RandomForestClassifier(n_estimators=50,
                                        max_features=max_features,
                                        max_depth=max_depth)
        forest_fit = forest.fit(X_train, Y_train)
        pred = forest_fit.predict(X_test)
        print('\n params:', dict(max_features=max_features, max_depth=max_depth))
        print('forest train: ',zero_one_score(Y_train, forest_fit.predict(X_train)), ' test: ',
                  zero_one_score(Y_test, pred))

        params.append( (max_features, max_depth) )
        scores.append( zero_one_score(Y_test, pred))

    print('best:', params[np.argmin(scores)])

class SKClassifier(object):
    def __init__(self, clf):
        self.clf = clf
        self.threshold = 0.0
        #tf.add_to_collection("threshold", self.threshold)

    def fit(self,X_train,y_train):
        self.clf = self.clf.fit(X_train,y_train)
        return self.clf

    def predict_proba(self,X):
        return self.clf.predict_proba(X)

    def predict_proba_with_loss(self, X, y):
        y_pred = self.predict_proba(X)
        loss = log_loss(y,y_pred)
        return y_pred, loss

    # smallest prob given to an actual catastrophe
    def threshold_from_data(self, X, y):
        y_bool = y == 1.   ## true if x is a catast
        y_pred = self.predict_proba(X)
        if np.count_nonzero(y) == 0:
            return np.max(y_pred)
        return np.min(y_pred[y_bool][:,1])   # TODO CHANGED FROM WILL CODE

    def metrics(self, X, y):
        metrics = {}
        y_pred_pair, loss = self.predict_proba_with_loss(X, y)
        y_pred = y_pred_pair[:,1]  ## From softmax pair to prob of catastrophe

        metrics['loss'] = loss
        threshold = self.threshold_from_data(X, y)
        metrics['threshold'] = threshold
        metrics['np.std(y_pred)'] = np.std(y_pred)
        denom = np.count_nonzero(y == False)
        num = np.count_nonzero(np.logical_and(y == False, y_pred >= threshold))
        metrics['fpr'] = float(num) / float(denom)
        if any(y) and not all(y):
            metrics['auc'] = roc_auc_score(y, y_pred)
            y_pred_bool = y_pred >= threshold
            if (any(y_pred_bool) and not all(y_pred_bool)):
                metrics['precision'] = precision_score(np.array(y, dtype=np.float32), y_pred_bool)
                metrics['recall'] = recall_score(y, y_pred_bool)

        return metrics

    def get_gaps(self,X,y):
        return np.abs(y - self.predict_proba(X)[:,1])

    def show_mistakes(self,X,y,k):
        gaps = self.get_gaps(X,y)
        index_gap = np.array([[i,gap] for i,gap in enumerate(gaps)])
        sorted_index_gap = index_gap[index_gap[:,1].argsort()]
        tail_index_gap = sorted_index_gap[-k:,:]

        xs = []
        probs = []
        for row in range(k):
            index,gap = tail_index_gap[row,:]
            x = X[int(index),:]
            xs.append(x)
            show_im(x.reshape(40,40))
            print('Contains ball:', y[int(index)] == 1., '. Prob gap: ', gap, ' \n ')
        return xs

def run_predict_random_forest(X_train,Y_train,X_test,Y_test, n_estimators=30, max_features=500, show_mistakes=False):
    forest = RandomForestClassifier(n_estimators=10, max_features=20, max_depth=10)
    clf = SKClassifier(forest)
    forest_fit = clf.fit(X_train, Y_train)
    pred = forest_fit.predict(X_test)
    print('\n Random forest 0-1 error.  \n Train: ',zero_one_score(Y_train, forest_fit.predict(X_train)), '\n Test: ',
      zero_one_score(Y_test, pred))

    met = clf.metrics(X_test,Y_test)
    if show_mistakes:
        mis = clf.show_mistakes(X_test,Y_test,10)
    print('Metrics:', met)
    return clf