text:
package natlab;

import java.io.IOException;
import java.io.PrintWriter;

/** Generates natlab.NatlabParserPassTests from the provided list file. */
public class ParserPassTestGenerator extends AbstractTestGenerator {
	private ParserPassTestGenerator() {
		super("/natlab/NatlabParserPassTests.java");
	}

	public static void main(String[] args) throws IOException {
		new ParserPassTestGenerator().generate(args);
	}

	protected void printHeader(PrintWriter testFileWriter) {
		testFileWriter.println("package natlab;");
		testFileWriter.println();
		testFileWriter.println("import ast.Program;");
		testFileWriter.println();
		testFileWriter.println("public class NatlabParserPassTests extends ParserPassTestBase {");
	}

	protected void printMethod(PrintWriter testFileWriter, String testName) {
		String methodName = "test_" + testName;
		String inFileName = "test/" + testName + ".in";
		String outFileName = "test/" + testName + ".out";
		testFileWriter.println();
		testFileWriter.println("	public void " + methodName + "() throws Exception {");
		testFileWriter.println("		CommentBuffer commentBuffer = new CommentBuffer();");
		testFileWriter.println("		NatlabScanner scanner = getScanner(\"" + inFileName + "\");");
		testFileWriter.println("		scanner.setCommentBuffer(commentBuffer);");
		testFileWriter.println("		NatlabParser parser = new NatlabParser();");
		testFileWriter.println("		parser.setCommentBuffer(commentBuffer);");
		testFileWriter.println("		Program actual = (Program) parser.parse(scanner);");
		testFileWriter.println("		Structure expected = parseStructure(\"" + outFileName + "\");");
		testFileWriter.println("		assertEquiv(actual, expected);");
		testFileWriter.println("	}");
	}

	protected void printFooter(PrintWriter testFileWriter) {
		testFileWriter.println("}");
		testFileWriter.println();
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>

<tt xml:lang="" xmlns="http://www.w3.org/ns/ttml"
    xmlns:ttp="http://www.w3.org/ns/ttml#parameter" ttp:profile="ttml2-transformation"
    xmlns:tts="http://www.w3.org/ns/ttml#styling"
    xmlns:ttva="http://skynav.com/ns/ttv/annotations" ttva:warnOn="all" ttva:expectedErrors="2" ttva:expectedWarnings="0" ttva:model="ttml2">

        <image src="../resources/bad2.png" type="image/png"/>

</tt>

redpajama_set_name: RedPajamaGithub


text:
package com.dianaui.universal.core.client.ui;

import com.dianaui.universal.core.client.ui.constants.ButtonGroupSize;
import com.dianaui.universal.core.client.ui.constants.Styles;
import com.dianaui.universal.core.client.ui.constants.Toggle;
import com.google.gwt.dom.client.Document;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * @author Alexey Zhokhov
 */
public class ButtonGroupGwtTest extends TestCore {

    // TODO toggle attr helper
    String DATA_TOGGLE_BUTTONS = "data-toggle=\"" + Toggle.BUTTONS.getToggle() + "\"";

    static String getHtml(String content, String styles, String attributes) {
        return "
" + (content != null ? content : "") + "
";
    }

    public void testDefaults() {
        ButtonGroup group = new ButtonGroup();
        hasStyle(Styles.BTN_GROUP, group);
        assertFalse(group.isOpen());
        assertFalse(group.isJustified());
        assertEquals(getHtml(null, null, null), group.getElement().toString());

        group.setJustified(true);
        assertEquals(getHtml(null, Styles.BTN_GROUP_JUSTIFIED, null), group.getElement().toString());

        group.setJustified(false);
        group.setToggle(Toggle.BUTTONS);
        assertEquals(getHtml(null, null, DATA_TOGGLE_BUTTONS), group.getElement().toString());

        group.setToggle(null);
        group.setSize(ButtonGroupSize.EXTRA_SMALL);
        assertEquals(getHtml(null, ButtonGroupSize.EXTRA_SMALL.getCssName(), null), group.getElement().toString());

        group.setSize(ButtonGroupSize.DEFAULT);
        group.setDropUp(true);
        assertEquals(getHtml(null, Styles.DROP_UP, null), group.getElement().toString());

        group.setDropUp(false);
        group.show();
        assertEquals(getHtml(null, Styles.OPEN, null), group.getElement().toString());
        assertTrue(group.isOpen());

        group.hide();
        assertEquals(getHtml(null, null, null), group.getElement().toString());
    }

    public void testClickOnCheckBox() {
        ButtonGroup group = new ButtonGroup();
        CheckBoxButton button1 = new CheckBoxButton("left");
        CheckBoxButton button2 = new CheckBoxButton("right");

        group.add(button1);
        group.add(button2);

        RootPanel.get().add(group);

        try {
            assertFalse(button1.getValue());
            assertFalse(button2.getValue());
            doesNotHaveStyle(Styles.ACTIVE, button1);
            doesNotHaveStyle(Styles.ACTIVE, button2);

            click(button2);

            assertFalse(button1.getValue());
            assertTrue(button2.getValue());
            doesNotHaveStyle(Styles.ACTIVE, button1);
            hasStyle(Styles.ACTIVE, button2);

            click(button1);
            click(button2);

            assertTrue(button1.getValue());
            assertFalse(button2.getValue());
            hasStyle(Styles.ACTIVE, button1);
            doesNotHaveStyle(Styles.ACTIVE, button2);
        } finally {
            group.removeFromParent();
        }
    }

    public void testClickOnRadio() {
        ButtonGroup group = new ButtonGroup();
        RadioButton button1 = new RadioButton("test");
        RadioButton button2 = new RadioButton("test");

        group.add(button1);
        group.add(button2);

        RootPanel.get().add(group);

        try {
            assertFalse(button1.getValue());
            assertFalse(button2.getValue());
            doesNotHaveStyle(Styles.ACTIVE, button1);
            doesNotHaveStyle(Styles.ACTIVE, button2);

            click(button2);

            assertFalse(button1.getValue());
            assertTrue(button2.getValue());
            doesNotHaveStyle(Styles.ACTIVE, button1);
            hasStyle(Styles.ACTIVE, button2);

            // emulate click event on radio button2
            button1.onBrowserEvent((Event) Document.get().createClickEvent(0, 0, 0, 0, 0, false, false, false, false));
            button2.setValue(false, false);

            assertTrue(button1.getValue());
            assertFalse(button2.getValue());
            hasStyle(Styles.ACTIVE, button1);
            doesNotHaveStyle(Styles.ACTIVE, button2);
        } finally {
            group.removeFromParent();
        }
    }

}


text:
package tibamobile.com.golfscorecard;

public class Hole {
    private String mLabel;
    private int mStrokeCount;

    public Hole(String label, int strokeCount) {
        mLabel = label;
        mStrokeCount = strokeCount;
    }

    public String getLabel() {
        return mLabel;
    }

    public void setLabel(String label) {
        mLabel = label;
    }

    public int getStrokeCount() {
        return mStrokeCount;
    }

    public void setStrokeCount(int strokeCount) {
        mStrokeCount = strokeCount;
    }
}


text:
LLista d'usuaris

Permet gestionar les propietats dels usuaris inscrits amb l'excepció dels permisos, que es gestionen a través d'altres seccions.

Afegir un usuari

L'administrador pot afegir usuaris manualment.

Llista d'usuaris

La llista pot ser filtrada amb el nom d'usuari (* = comodí), amb el grup o l'estat. La llista pot ser ordenada per data d'inscripció o per nom d'usuari, de forma ascendent o descendent.

Aquesta pantalla permet la modificació de diversos usuaris simultàniament:

suprimir usuaris (es necessita confirmació)

canviar l'estat dels usuaris

associar o dissociar grups

modificar les propietats de visualització

modificar les propietats annexes

Els usuaris modificats són aquells usuaris seleccionats (per defecte) o la totalitat de la llista filtrada.


text:
var callbackApp = {
	init: function() {
		$('#callbackSubmit').on('click', this.callbackSubmit);
	},
	callbackSubmit: function( event ) {

		var data = $('#callback-form').serialize();
		$.ajax({
        	url: '/frontend/web/callback/callback/create-ajax',
        	type: "POST",
        	data: data,
        	success: function (result) {
	            if (result == 'true') {
	            	console.log('post callback');
					$('#modal-callback').modal('hide');
	            } else {
	            	$
	            	var res = $.parseJSON(result);
	            	$('#callback-errorSummary').empty();
	            	$.each(res, function(key, value) {
	            		$('#callback-errorSummary').append("<li>"+value+"</li>");
	            	});
	            }
        }
    });
	}
}

callbackApp.init();


text:
package com.msi.tough.model.elasticache.enums;

// in-sync is the AWS status, others unconfirmed
public enum CacheParameterGroupStatus {
	insync,
	modifying
}


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

<title>Scaling (libgdx API)</title>
<meta name="date" content="2016-02-02">
<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

				libgdx API

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method

com.badlogic.gdx.utils

Enum Scaling

java.lang.Object

java.lang.Enum<Scaling>

com.badlogic.gdx.utils.Scaling

All Implemented Interfaces:

java.io.Serializable, java.lang.Comparable<Scaling>

public enum Scaling
extends java.lang.Enum<Scaling>

Various scaling types for fitting one rectangle into another.

Author:

Nathan Sweet

Enum Constant Summary

Enum Constants

Enum Constant and Description

fill

Scales the source to fill the target while keeping the same aspect ratio.

fillX

Scales the source to fill the target in the x direction while keeping the same aspect ratio.

fillY

Scales the source to fill the target in the y direction while keeping the same aspect ratio.

fit

Scales the source to fit the target while keeping the same aspect ratio.

none

The source is not scaled.

stretch

Scales the source to fill the target.

stretchX

Scales the source to fill the target in the x direction, without changing the y direction.

stretchY

Scales the source to fill the target in the y direction, without changing the x direction.

Method Summary

All Methods Static Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

Vector2
apply(float sourceWidth,
     float sourceHeight,
     float targetWidth,
     float targetHeight)

Returns the size of the source scaled to the target.

static Scaling
valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.

static Scaling[]
values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Methods inherited from class java.lang.Enum

clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Enum Constant Detail

fit

public static final Scaling fit

Scales the source to fit the target while keeping the same aspect ratio. This may cause the source to be smaller than the
 target in one direction.

fill

public static final Scaling fill

Scales the source to fill the target while keeping the same aspect ratio. This may cause the source to be larger than the
 target in one direction.

fillX

public static final Scaling fillX

Scales the source to fill the target in the x direction while keeping the same aspect ratio. This may cause the source to be
 smaller or larger than the target in the y direction.

fillY

public static final Scaling fillY

Scales the source to fill the target in the y direction while keeping the same aspect ratio. This may cause the source to be
 smaller or larger than the target in the x direction.

stretch

public static final Scaling stretch

Scales the source to fill the target. This may cause the source to not keep the same aspect ratio.

stretchX

public static final Scaling stretchX

Scales the source to fill the target in the x direction, without changing the y direction. This may cause the source to not
 keep the same aspect ratio.

stretchY

public static final Scaling stretchY

Scales the source to fill the target in the y direction, without changing the x direction. This may cause the source to not
 keep the same aspect ratio.

none

public static final Scaling none

The source is not scaled.

Method Detail

values

public static Scaling[] values()

Returns an array containing the constants of this enum type, in
the order they are declared.  This method may be used to iterate
over the constants as follows:

for (Scaling c : Scaling.values())
    System.out.println(c);

Returns:

an array containing the constants of this enum type, in the order they are declared

valueOf

public static Scaling valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.
The string must match exactly an identifier used to declare an
enum constant in this type.  (Extraneous whitespace characters are
not permitted.)

Parameters:

name - the name of the enum constant to be returned.

Returns:

the enum constant with the specified name

Throws:

java.lang.IllegalArgumentException - if this enum type has no constant with the specified name

java.lang.NullPointerException - if the argument is null

apply

public Vector2 apply(float sourceWidth,
                     float sourceHeight,
                     float targetWidth,
                     float targetHeight)

Returns the size of the source scaled to the target. Note the same Vector2 instance is always returned and should never be
 cached.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

libgdx API

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method

				Copyright © 2010-2013 Mario Zechner (contact@badlogicgames.com), Nathan Sweet (admin@esotericsoftware.com)


text:
import type { Auth } from './auth';

export type Action = Auth; // union


text:
#include <Thor/Framework/Common.h>

#ifdef THOR_MS_WIN
	#ifdef THOR_GRAPHICS_SCENE_EXPORT
		#define THOR_GRAPHICS_SCENE_DLL __declspec(dllexport)
	#elif defined THOR_GRAPHICS_SCENE_IMPORT
		#define THOR_GRAPHICS_SCENE_DLL __declspec(dllimport)
	#else
		#define THOR_GRAPHICS_SCENE_DLL
	#endif
#else
	#define THOR_GRAPHICS_SCENE_DLL
#endif


text:
'use strict';

const strangeError = function () {

    throw 'This is a weird thing to throw';
};

module.exports = strangeError;


text:
layout: post
title: "Understanding empirical Bayes estimation (using baseball statistics)"
description: "An intuitive explanation of empirical Bayes estimation in terms of estimating baseball batting averages."
category: r
tags: [r, statistics, education]
comments: true
---

Which of these two proportions is higher: **4 out of 10**, or **300 out of 1000**? This sounds like a silly question. Obviously $$4/10=.4$$, which is greater than $$300/1000=.3$$.

But suppose you were a baseball recruiter, trying to decide which of two potential players is a better batter based on how many hits they get. One has achieved 4 hits in 10 chances, the other 300 hits in 1000 chances. While the first player has a higher proportion of hits, it's not a lot of evidence: a typical player tends to achieve a hit around 27% of the time, and this player's $$4/10$$ could be due to luck. The second player, on the other hand, has a lot of evidence that he's an above-average batter.

This post isn't really about baseball, I'm just using it as an illustrative example. (I actually know very little about [sabermetrics](https://en.wikipedia.org/wiki/Sabermetrics). If you want a more technical version of this post, check out [this great paper](https://projecteuclid.org/euclid.imsc/1288099025)). This post is, rather, about a very useful statistical method for estimating a large number of proportions, called **empirical Bayes estimation**. It's to help you with data that looks like this:

| Success| Total|
|-------:|-----:|
|      11|   104|
|      82|  1351|
|       2|    26|
|       0|    40|
|    1203|  7592|
|       5|   166|

A lot of data takes the form of these success/total counts, where you want to estimate a "proportion of success" for each instance. Each row might represent:

* **An ad you're running**: Which of your ads have higher clickthrough rates, and which have lower? (Note that I'm not talking about running an A/B test comparing two options, but rather about ranking and analyzing a large list of choices.)
* **A user on your site**: In my work at Stack Overflow, I might look at what fraction of a user's visits are to Javascript questions, to [guess whether they are a web developer](http://kevinmontrose.com/2015/01/27/providence-machine-learning-at-stack-exchange/). In another application, you might consider how often a user decides to read an article they browse over, or to purchase a product they've clicked on.

When you work with pairs of successes/totals like this, you tend to get tripped up by the uncertainty in low counts. $$1/2$$ does not mean the same thing as $$50/100$$; nor does $$0/1$$ mean the same thing as $$0/1000$$. One approach is to filter out all cases that don't meet some minimum, but this isn't always an option: you're throwing away useful information.

I previously wrote a post about one approach to this problem, using the same analogy: [Understanding the beta distribution (using baseball statistics)](http://varianceexplained.org/statistics/beta_distribution_and_baseball/). Using the beta distribution to represent your *prior expectations*, and *updating* based on the new evidence, can help make your estimate more accurate and practical. Now I'll demonstrate the related method of empirical Bayes estimation, where the beta distribution is used to improve a large set of estimates. What's great about this method is that as long as you have a lot of examples, *you don't need to  bring in prior expectations*.

Here I'll apply empirical Bayes estimation to a baseball dataset, with the goal of improving our estimate of each player's batting average. I'll focus on the intuition of this approach, but will also show the R code for running this analysis yourself. (So that the post doesn't get cluttered, I don't show the code for the graphs and tables, only the estimation itself. But you can find *all* this post's code [here](https://github.com/dgrtwo/dgrtwo.github.com/blob/master/_R/)).

### Working with batting averages

In my [original post about the beta distribution](http://varianceexplained.org/statistics/beta_distribution_and_baseball/), I made some vague guesses about the distribution of batting averages across history, but here we'll work with real data. We'll use the `Batting` dataset from the excellent [Lahman package](https://cran.r-project.org/web/packages/Lahman/index.html). We'll prepare and clean the data a little first, using dplyr and tidyr:

{% highlight r %}
library(dplyr)
library(tidyr)
library(Lahman)

career <- Batting %>%
  filter(AB > 0) %>%
  anti_join(Pitching, by = "playerID") %>%
  group_by(playerID) %>%
  summarize(H = sum(H), AB = sum(AB)) %>%
  mutate(average = H / AB)

# use names along with the player IDs
career <- Master %>%
  tbl_df() %>%
  select(playerID, nameFirst, nameLast) %>%
  unite(name, nameFirst, nameLast, sep = " ") %>%
  inner_join(career, by = "playerID") %>%
  select(-playerID)
{% endhighlight %}

Above, we filtered out pitchers (generally the weakest batters, who should be analyzed separately). We summarized each player across multiple years to get their *career* Hits (H) and At Bats (AB), and batting average. Finally, we added first and last names to the dataset, so we could work with them rather than an identifier:

{% highlight r %}
career
{% endhighlight %}

{% highlight text %}
## Source: local data frame [9,256 x 4]
##
##                 name     H    AB average
##                (chr) (int) (int)   (dbl)
## 1         Hank Aaron  3771 12364  0.3050
## 2       Tommie Aaron   216   944  0.2288
## 3          Andy Abad     2    21  0.0952
## 4        John Abadie    11    49  0.2245
## 5     Ed Abbaticchio   772  3044  0.2536
## 6        Fred Abbott   107   513  0.2086
## 7        Jeff Abbott   157   596  0.2634
## 8        Kurt Abbott   523  2044  0.2559
## 9         Ody Abbott    13    70  0.1857
## 10 Frank Abercrombie     0     4  0.0000
## ..               ...   ...   ...     ...
{% endhighlight %}

I wonder who the best batters in history were. Well, here are the ones with the highest batting average:

|name             |  H| AB| average|
|:----------------|--:|--:|-------:|
|Jeff Banister    |  1|  1|       1|
|Doc Bass         |  1|  1|       1|
|Steve Biras      |  2|  2|       1|
|C. B. Burns      |  1|  1|       1|
|Jackie Gallagher |  1|  1|       1|

Err, that's not really what I was looking for. These aren't the best batters, they're just the batters who went up once or twice and got lucky. How about the worst batters?

|name              |  H| AB| average|
|:-----------------|--:|--:|-------:|
|Frank Abercrombie |  0|  4|       0|
|Horace Allen      |  0|  7|       0|
|Pete Allen        |  0|  4|       0|
|Walter Alston     |  0|  1|       0|
|Bill Andrus       |  0|  9|       0|

Also not what I was looking for. That "average" is a really crummy estimate. **Let's make a better one.**

### Step 1: Estimate a prior from all your data

Let's look at the distribution of batting averages across players.

![center](/figs/2015-10-01-empirical_bayes_baseball/unnamed-chunk-7-1.png)

(For the sake of estimating the prior distribution, I've filtered out all players that have fewer than 500 at-bats, since we'll get a better estimate from the less noisy cases. I show a more principled approach in the Appendix).

The first step of empirical Bayes estimation is to estimate a beta prior using this data. Estimating priors from the data you're currently analyzing is not the typical Bayesian approach- usually you decide on your priors ahead of time. There's a lot of debate and discussion about when and where it's appropriate to use empirical Bayesian methods, but it basically comes down to how many observations we have: if we have a lot, we can get a good estimate that doesn't depend much on any one individual. Empirical Bayes is an **approximation** to more exact Bayesian methods- and with the amount of data we have, it's a very good approximation.

So far, a beta distribution looks like a pretty appropriate choice based on the above histogram. (What would make it a bad choice? Well, suppose the histogram had two peaks, or three, instead of one. Then we might need a [mixture of Betas](https://en.wikipedia.org/wiki/Mixture_model), or an even more complicated model). So we know we want to fit the following model:

$$X\sim\mbox{Beta}(\alpha_0,\beta_0)$$

We just need to pick $$\alpha_0$$ and $$\beta_0$$, which we call "hyper-parameters" of our model. There are many methods in R for fitting a probability distribution to data (`optim`, `mle`, `bbmle`, etc). You don't even have to use maximum likelihood: you could [use the mean and variance](http://stats.stackexchange.com/questions/12232), called the "method of moments". But we'll use the [fitdistr](http://www.inside-r.org/r-doc/MASS/fitdistr) function from MASS.

{% highlight r %}
# just like the graph, we have to filter for the players we actually
# have a decent estimate of
career_filtered <- career %>%
    filter(AB >= 500)

m <- MASS::fitdistr(career_filtered$average, dbeta,
                    start = list(shape1 = 1, shape2 = 10))

alpha0 <- m$estimate[1]
beta0 <- m$estimate[2]
{% endhighlight %}

This comes up with $$\alpha_0=78.661$$ and $$\beta_0=224.875$$. How well does this fit the data?

![center](/figs/2015-10-01-empirical_bayes_baseball/unnamed-chunk-8-1.png)

Not bad! Not perfect, but something we can work with.

### Step 2: Use that distribution as a prior for each individual estimate

Now when we look at any individual to estimate their batting average, we'll start with our overall prior, and [update](https://en.wikipedia.org/wiki/Bayesian_inference) based on the individual evidence. I went over this process in detail in the [original Beta distribution post](http://stats.stackexchange.com/questions/47771/what-is-the-intuition-behind-beta-distribution): it's as simple as adding $$\alpha_0$$ to the number of hits, and $$\alpha_0 + \beta_0$$ to the total number of at-bats.

For example, consider our hypothetical batter from the introduction that went up 1000 times, and got 300 hits. We would estimate his batting average as:

$$\frac{300+\alpha_0}{1000+\alpha_0+\beta_0}=\frac{300+78.7}{1000+78.7+224.9}=0.29$$

How about the batter who went up only 10 times, and got 4 hits. We would estimate his batting average as:

$$\frac{4+\alpha_0}{10+\alpha_0+\beta_0}=\frac{4+78.7}{10+78.7+224.9}=0.264$$

Thus, even though $$\frac{4}{10}>\frac{300}{1000}$$, we would guess that the $$\frac{300}{1000}$$ batter is better than the $$\frac{4}{10}$$ batter!

Performing this calculation for all the batters is simple enough:

{% highlight r %}
career_eb <- career %>%
    mutate(eb_estimate = (H + alpha0) / (AB + alpha0 + beta0))
{% endhighlight %}

### Results

Now we can ask: who are the best batters by this improved estimate?

|name                 |    H|   AB| average| eb_estimate|
|:--------------------|----:|----:|-------:|-----------:|
|Rogers Hornsby       | 2930| 8173|   0.358|       0.355|
|Shoeless Joe Jackson | 1772| 4981|   0.356|       0.350|
|Ed Delahanty         | 2596| 7505|   0.346|       0.343|
|Billy Hamilton       | 2158| 6268|   0.344|       0.340|
|Harry Heilmann       | 2660| 7787|   0.342|       0.339|

Who are the *worst* batters?

|name           |   H|   AB| average| eb_estimate|
|:--------------|---:|----:|-------:|-----------:|
|Bill Bergen    | 516| 3028|   0.170|       0.178|
|Ray Oyler      | 221| 1265|   0.175|       0.191|
|John Vukovich  |  90|  559|   0.161|       0.196|
|John Humphries |  52|  364|   0.143|       0.196|
|George Baker   |  74|  474|   0.156|       0.196|

Notice that in each of these cases, empirical Bayes didn't simply pick the players who had 1 or 2 at-bats. It found players who batted well, or poorly, across a long career. What a load off our minds: we can start using these empirical Bayes estimates in downstream analyses and algorithms, and not worry that we're accidentally letting $$0/1$$ or $$1/1$$ cases ruin everything.

Overall, let's see how empirical Bayes changed all of the batting average estimates:

![center](/figs/2015-10-01-empirical_bayes_baseball/unnamed-chunk-11-1.png)

The horizontal dashed red line marks $$y=\frac{\alpha_0}{\alpha_0 + \beta_0}=0.259$$- that's what we would guess someone's batting average was if we had *no* evidence at all. Notice that points above that line tend to move down towards it, while points below it move up.

The diagonal red line marks $$x=y$$. Points that lie close to it are the ones that didn't get shrunk at all by empirical Bayes. Notice that they're the ones with the highest number of at-bats (the brightest blue): they have enough evidence that we're willing to believe the naive batting average estimate.

This is why this process is sometimes called *shrinkage*: we've moved all our estimates towards the average. How much it moves these estimates depends on how much evidence we have: if we have very little evidence (4 hits out of 10) we move it a lot, if we have a lot of evidence (300 hits out of 1000) we move it only a little. That's shrinkage in a nutshell: *Extraordinary outliers require extraordinary evidence*.

### Conclusion: So easy it feels like cheating

Recall that there were two steps in empirical Bayes estimation:

1. Estimate the overall distribution of your data.
2. Use that distribution as your prior for estimating each average.

Step 1 can be done once, "offline"- analyze all your data and come up with some estimates of your overall distribution. Step 2 is done for each new observation you're considering. You might be estimating the success of a post or an ad, or classifying the behavior of a user in terms of how often they make a particular choice.

And because we're using the beta and the binomial, consider how *easy* that second step is. All we did was add one number to the successes, and add another number to the total. You can build that into your production system with a single line of code that takes nanoseconds to run.

    // We hired a Data Scientist to analyze our Big Data
    // and all we got was this lousy line of code.
    float estimate = (successes + 78.7) / (total + 303.5);

That really is so simple that it feels like cheating- like the kind of "fudge factor" you might throw into your code, with the intention of coming back to it later to do some real Machine Learning.

I bring this up to disprove the notion that statistical sophistication necessarily means dealing with complicated, burdensome algorithms. This Bayesian approach is based on sound principles, but it's still easy to implement. Conversely, next time you think "I only have time to implement a dumb hack," remember that you can use methods like these: it's a way to choose your fudge factor. Some dumb hacks are better than others!

But when anyone asks what you did, remember to call it "empirical Bayesian shrinkage towards a Beta prior." We statisticians have to keep up appearances.

### Appendix: How could we make this more complicated?

We've made some enormous simplifications in this post. For one thing, we assumed all batting averages are drawn from a single distribution. In reality, we'd expect that it depends on some known factors. For instance, the distribution of batting averages has changed over time:

![center](/figs/2015-10-01-empirical_bayes_baseball/unnamed-chunk-12-1.png)

Ideally, we'd want to estimate a different Beta prior for each decade. Similarly, we could estimate separate priors for each team, a separate prior for pitchers, and so on. One useful approach to this is [Bayesian hierarchical modeling](https://en.wikipedia.org/wiki/Bayesian_hierarchical_modeling) (as used in, for example, [this study of SAT scores across different schools](http://andrewgelman.com/2014/01/21/everything-need-know-bayesian-statistics-learned-eight-schools/)).

Also, as alluded to above, we shouldn't be estimating the distribution of batting averages using only the ones with more than 500 at-bats. Really, we should use all of our data to estimate the distribution, but give *more consideration* to the players with a higher number of at-bats. This can be done by fitting a beta-binomial distribution. For instance, we can use the [dbetabinom.ab](http://www.inside-r.org/packages/cran/VGAM/docs/Betabinom) function from VGAM, and the `mle` function:

{% highlight r %}
library(VGAM)

# negative log likelihood of data given alpha; beta
ll <- function(alpha, beta) {
  -sum(dbetabinom.ab(career$H, career$AB, alpha, beta, log = TRUE))
}

m <- mle(ll, start = list(alpha = 1, beta = 10), method = "L-BFGS-B")
coef(m)
{% endhighlight %}

{% highlight text %}
## alpha  beta
##    75   222
{% endhighlight %}

We end up getting almost the same prior, which is reassuring!


text:
package fr.xebia.android.freezer.migration;

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

/**
 * Created by florentchampigny on 28/01/2016.
 */
public class ColumnType {

    public static ModelType ofModel(String objectName) {
        return new ModelType(objectName,false);
    }

    public static ModelType collectionOfModel(String objectName) {
        return new ModelType(objectName,true);
    }

    public enum Collection {
        ListOfInts("MODEL_INT"),
        ListOfFloats("MODEL_FLOAT"),
        ListOfBooleans("MODEL_BOOLEAN"),
        ListOfStrings("MODEL_STRING");

        private String associationTable;

        Collection(String associationTable) {
            this.associationTable = associationTable;
        }

        public java.lang.String getAssociationTable() {
            return associationTable;
        }
    }

    public enum Array {
        ArrayOfInts("MODEL_INT"),
        ArrayOfFloats("MODEL_FLOAT"),
        ArrayOfBooleans("MODEL_BOOLEAN"),
        ArrayOfStrings("MODEL_STRING");

        private String associationTable;

        Array(String associationTable) {
            this.associationTable = associationTable;
        }

        public java.lang.String getAssociationTable() {
            return associationTable;
        }
    }

    public enum Primitive {
        Int("number"),
        Float("real"),
        Boolean("number"),
        String("text"),
        Date("text"),
        ;

        private String sqlName;

        Primitive(String sqlName) {
            this.sqlName = sqlName;
        }

        public java.lang.String getSqlName() {
            return sqlName;
        }
    }

    public static class ModelType {
        String objectName;
        boolean collection;

        protected ModelType(String objectName, boolean collection) {
            this.objectName = objectName;
            this.collection = collection;
        }

    }

    public static String getSqlName(Object type){
        if(type instanceof Primitive)
            return ((Primitive)type).getSqlName();
        return ""; //TODO
    }
}


text:
using ForumModels;
using System.Data.Entity;

namespace ForumDate
{
    public class ForumDbContext : DbContext
    {
        public ForumDbContext()
            :base("ForumDb")
        {
        }

        public DbSet<Post> Posts { get; set; }

        public DbSet<Category> Categories { get; set; }

        public DbSet<PostAnswer> PostAnswers { get; set; }

        public DbSet<Tag> Tags { get; set; }
    }
}


text:
var http = require('q-io/http');

var config = require('../../config/config');

var httpError = require('../error/error.http');

var persona = {};

persona.verify = function (assertion) {
    var options = {
        url: config.authUrl + '/login',
        method: 'POST',
        body: [
            JSON.stringify({
                assertion: assertion,
                audience: config.clientUrl
            })
        ],
        headers: {
            'Content-Type': 'application/json'
        }
    };
    return http.request(options)
        .then(function (verificationResult) {
            return verificationResult.body.read();
        })
        .then(function (authData) {
            return JSON.parse(authData);
        });
};

persona.decodeToken = function (token) {
    var options = {
        url: config.authUrl + '/me',
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + token
        }
    };
    return http.request(options)
        .then(function checkStatus(result) {
            if (result.status !== 200) httpError.throw(result.status, 'Error decoding token');
            return result;
        })
        .then(function (result) {
            return result.body.read();
        })
        .then(function (body) {
            return JSON.parse(body);
        });
};

module.exports = persona;


text:
package issst.evex.kb.util

import scala.collection.JavaConversions._
import java.nio.file.Paths

import org.apache.uima.util.CasCreationUtils
import org.uimafit.factory.{AnalysisEngineFactory, CollectionReaderFactory, TypeSystemDescriptionFactory}
import org.uimafit.factory.ExternalResourceFactory.createExternalResourceDescription
import org.uimafit.pipeline.SimplePipeline
import ru.kfu.itis.cll.uima.cpe.XmiCollectionReader
import ru.kfu.itis.issst.uima.brat.UIMA2BratAnnotator

import issst.evex.kb.JsonData
import issst.evex.kb.annotators.IndicatorAnnotator
import issst.evex.kb.annotators.ArgumentsAnnotator
import issst.evex.kb.B2UConfigImporter

object B2UCpeLauncher extends App {
  if (args.length != 2) {
    println("Please provide corpus directory path and output path.")
    System.exit(0)
  }

  launchCpe(args(0), args(1))

  def launchCpe(inputDir: String, outputDir: String) {
    val xmiColReaderDesc = CollectionReaderFactory.createDescription(classOf[XmiCollectionReader], CasCreationUtils.mergeTypeSystems(List(TypeSystemDescriptionFactory.createTypeSystemDescription(Paths.get(inputDir).resolve(LemmasDepsSerializer.typeSystemFilename).toUri.toString), TypeSystemDescriptionFactory.createTypeSystemDescription("ru.kfu.itis.cll.uima.commons.Commons-TypeSystem"))), XmiCollectionReader.PARAM_INPUTDIR, inputDir)

    val jsonDataDesc = createExternalResourceDescription(classOf[JsonData], "http://srl.meteor.com/data.json")
    val indicatorAnnotatorDesc = AnalysisEngineFactory.createPrimitiveDescription(classOf[IndicatorAnnotator], IndicatorAnnotator.JSON_DATA_KEY, jsonDataDesc)
    val argumentsAnnotatorDesc = AnalysisEngineFactory.createPrimitiveDescription(classOf[ArgumentsAnnotator], IndicatorAnnotator.JSON_DATA_KEY, jsonDataDesc)

    val annWriterDesc = AnalysisEngineFactory.createAnalysisEngineDescription("ru.kfu.itis.issst.uima.brat.UIMA2BratAnnotator", UIMA2BratAnnotator.BRAT_OUT, outputDir, UIMA2BratAnnotator.ENTITIES_TO_BRAT, B2UConfigImporter.entitiesToBrat.toArray, UIMA2BratAnnotator.EVENTS_TO_BRAT, B2UConfigImporter.eventsToBrat.toArray)

    val aggregateDesc = AnalysisEngineFactory.createAggregateDescription(indicatorAnnotatorDesc, argumentsAnnotatorDesc)
    //val aggregateDesc = AnalysisEngineFactory.createAggregateDescription(eventExtractorDesc)

    SimplePipeline.runPipeline(xmiColReaderDesc, aggregateDesc, annWriterDesc)
  }
}


text:
function Get-EXRGroupThreads {
    [CmdletBinding()]
    param (
        [Parameter(Position = 0, Mandatory = $false)]
        [string]
        $MailboxName,

        [Parameter(Position = 1, Mandatory = $false)]
        [psobject]
        $AccessToken,

        [Parameter(Position = 2, Mandatory = $false)]
        [psobject]
        $Group,

        [Parameter(Position = 3, Mandatory = $false)]
        [DateTime]
        $lastDeliveredDateTime,

        [Parameter(Position = 4, Mandatory = $false)]
        [Int]
        $Top = 1000,

        [Parameter(Position = 5, Mandatory = $false)]
        [string]
        $ThreadURI,

        [Parameter(Position = 6, Mandatory = $false)]
        [switch]
        $TopOnly
    )
    Process {
        if ($AccessToken -eq $null) {
            $AccessToken = Get-ProfiledToken -MailboxName $MailboxName
            if ($AccessToken -eq $null) {
                $AccessToken = Get-EXRAccessToken -MailboxName $MailboxName
            }
        }
        if ([String]::IsNullOrEmpty($MailboxName)) {
            $MailboxName = $AccessToken.mailbox
        }
        $HttpClient = Get-HTTPClient -MailboxName $MailboxName
        $EndPoint = Get-EndPoint -AccessToken $AccessToken -Segment "groups"
        $RequestURL = $EndPoint + "('" + $Group.Id + "')/Threads?`$Top=$Top"
        if(![String]::IsNullOrEmpty($ThreadURI)){
            $RequestURL = $ThreadURI
        }
        do {
            $JSONOutput = Invoke-RestGet -RequestURL $RequestURL -HttpClient $HttpClient -AccessToken $AccessToken -MailboxName $MailboxName
            foreach ($Message in $JSONOutput.Value) {
                $ItemURI = $EndPoint + "('" + $Group.Id + "')/Threads" + "('" + $Message.Id + "')"
                add-Member -InputObject $Message -NotePropertyName ItemURI -NotePropertyValue $ItemURI
                if ($lastDeliveredDateTime) {
                    if (([DateTime]$Message.lastDeliveredDateTime) -gt $lastDeliveredDateTime) {
                        Write-Output $Message
                    }
                }
                else {
                    Write-Output $Message
                }
            }
            $RequestURL = $JSONOutput.'@odata.nextLink'
        }
        while (![String]::IsNullOrEmpty($RequestURL) -band (!$TopOnly.IsPresent))
    }
}


text:
from __future__ import print_function, unicode_literals

"""
Evaluates lisp expressions. 'repl' reads from stdin. The other stuff probably
shouldn't be called unless you know what you're doing.
"""

__all__ = ['zeta', 'printError']

from src.parsers import parse, parse_file
from src.primitives import *
from src.operators import *

import functools

class Context(object):
    """Map symbol name to form implementation"""
    def __init__(self):
        self.forms = {}

    def register(self, function):
        """Register form by name"""
        name = function.__name__.split('_')[-1]
        self.forms[Symbol(name)] = function
        return function

    def get(self, name):
        """Get implementation by name"""
        return self.forms.get(name)

# Module level jump table for form implementations
context = Context()

@context.register
def eval_let(body, env):
    """Bind each name and evaluate the body"""
    local_env = Environment(scope=env)
    for name, expr in car(body):
        value = eval(expr, local_env)
        local_env[name] = value
    return eval(single(Symbol('BEGIN')) + cdr(body), local_env)

@context.register
def eval_lambda(function, env):
    """Build a closure"""
    formals = car(function)
    if isatom(car(cdr(function))):
        body = car(cdr(function))
    else:
        body = car(car(cdr(function)))
    if body == Symbol('DEF-BEGIN'):
        body = single(Symbol('BEGIN')) + cdr(car(cdr(function)))
    else:
        body = single(Symbol('BEGIN')) + cdr(function)
    return Closure(body, formals, env)

@context.register
def eval_quote(ls, env):
    """Return the quoted object unevaluated"""
    return car(ls)

@context.register
def eval_begin(exprs, env):
    """Evaluate a sequence of expressions and return the last one in
       a Thunk to keep simplifying"""
    for expr in exprs[:-1]:
        eval(expr, env)
    return Thunk(exprs[-1])

@context.register
def eval_if(exprs, env):
    """Evaluate the first expression and return the second or third
       in a Thunk to keep simplifying"""
    if len(exprs) != 3:
        raise Exception('Malformed if: "{}"'.format(exprs))
    test, consequent, alternative = exprs
    return Thunk(consequent if eval(test, env) else alternative)

@context.register
def eval_cond(exprs, env):
    """Evaluate conditions until one evaluates to True. Then
       return the body in a Thunk to keep simplifying"""
    for cond, expr in exprs:
        test = eval(cond, env)
        if test:
            return Thunk(expr)
    return NIL

@context.register
def eval_or(exprs, env):
    """Short circuit or"""
    for expr in exprs:
        if eval(expr, env):
            return True
    return False

@context.register
def eval_and(exprs, env):
    """Short circuit and"""
    for expr in exprs:
        if not eval(expr, env):
            return False
    return True

@context.register
def eval_define(expr, env):
    """Define a name or function in the current environment"""
    if isatom(car(expr)):
        name = car(expr)
        env[name] = eval(car(cdr(expr)), env)
        return NIL
    else:
        name = car(car(expr))
        formals = cdr(car(expr))
        body = single(Symbol('DEF-BEGIN')) + cdr(expr)
        function = (Symbol('LAMBDA'), formals, body)
        closure = eval(function, env)
        env[name] = closure
        return NIL

@context.register
def eval_delete(expr, env):
    """Remove a named object from the current environment"""
    if isatom(car(expr)):
        env.pop(car(expr))
    return NIL

@context.register
def eval_load(s, env):
    """Evaluate sequence of expressions in current environment"""
    with open(car(s)) as stream:
        value = NIL
        for expression in parse_file(stream):
            value = eval(expression, env)
        return value

def eval(expr, env):
    """Evaluate s-expression parsed into tuples"""
    while 1:
        if isinstance(expr, Symbol):
            return env[expr]
        elif isnil(expr) or not isinstance(expr, tuple):
            return expr

        first, rest = splits(expr)
        form = context.get(first)
        if form is not None:
            expr = form(rest, env)
            if isinstance(expr, Thunk):
                expr = expr.value
            else:
                return expr
        else:
            exprs = tuple(eval(expr, env) for expr in expr)
            function, actuals = splits(exprs)
            if isinstance(function, Closure):
                if len(function.formals) != len(actuals):
                    raise Exception("Wrong number of actual parameters")
                env = Environment(function.env, **dict(zip(function.formals, actuals)))
                expr = function.body
            elif hasattr(function, '__call__'):
                return function(actuals)
            else:
                raise Exception("Cannot apply '{}'".format(function))

def printError(e):
    """Print exception with name and reason"""
    print('{}: {}\n'.format(e.__class__.__name__, str_list(e)))

def repl(env):
    print("Type (help) for global definitions")
    while 1:
        value = NIL
        try:
            value = eval(parse('[]> '), env)
            print('Value: {}\n'.format(str_list(value)))
        except EOFError:
            break
        except KeyboardInterrupt:
            print('\nValue: nil\n')
        except Exception as e:
            printError(e)

def zeta(stream):
    eval_load(single('src/library.lisp'), global_env)
    if stream.isatty():
        repl(global_env)
    else:
        for expr in parse_file(stream):
            try:
                eval(expr, global_env)
            except (KeyboardInterrupt, EOFError):
                break
            except Exception as e:
                printError(e)
                break


text:
var searchData=
[
  ['elevator',['Elevator',['../class_elevator.html',1,'']]],
  ['event',['Event',['../class_event.html',1,'']]],
  ['eventcomparator',['EventComparator',['../class_event_comparator.html',1,'']]],
  ['eventdispatcher',['EventDispatcher',['../class_event_dispatcher.html',1,'']]],
  ['eventfactory',['EventFactory',['../class_event_factory.html',1,'']]],
  ['eventnotifier',['EventNotifier',['../class_event_notifier.html',1,'']]],
  ['eventobserver',['EventObserver',['../class_event_observer.html',1,'']]],
  ['eventqueue',['EventQueue',['../class_event_queue.html',1,'']]]
];


text:
/* $NetBSD: ieee80211_netbsd.c,v 1.20 2011/11/19 22:51:25 tls Exp $ */
/*-
 * Copyright (c) 2003-2005 Sam Leffler, Errno Consulting
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <special_includes/sys/cdefs.h>
#ifdef __FreeBSD__
__FBSDID("$FreeBSD: src/sys/net80211/ieee80211_freebsd.c,v 1.8 2005/08/08 18:46:35 sam Exp $");
#else
__KERNEL_RCSID(0, "$NetBSD: ieee80211_netbsd.c,v 1.20 2011/11/19 22:51:25 tls Exp $");
#endif

/*
 * IEEE 802.11 support (NetBSD-specific code)
 */
#include <special_includes/sys/param.h>
#include <special_includes/sys/kernel.h>
#include <special_includes/sys/systm.h>
#include <special_includes/sys/mbuf.h>
#include <special_includes/sys/proc.h>
#include <special_includes/sys/sysctl.h>
#include <special_includes/sys/once.h>

#include <special_includes/sys/socket.h>

#include <special_includes/sys/cprng.h>

#include <net/if.h>
#include <net/if_media.h>
#include <net/if_ether.h>
#include <net/route.h>

#include <net80211/ieee80211_netbsd.h>
#include <net80211/ieee80211_var.h>
#include <net80211/ieee80211_sysctl.h>

#define	LOGICALLY_EQUAL(x, y)	(!(x) == !(y))

static void ieee80211_sysctl_fill_node(struct ieee80211_node *,
    struct ieee80211_node_sysctl *, int, const struct ieee80211_channel *,
    uint32_t);
static struct ieee80211_node *ieee80211_node_walknext(
    struct ieee80211_node_walk *);
static struct ieee80211_node *ieee80211_node_walkfirst(
    struct ieee80211_node_walk *, u_short);
static int ieee80211_sysctl_node(SYSCTLFN_ARGS);

#ifdef IEEE80211_DEBUG
int	ieee80211_debug = 0;
#endif

typedef void (*ieee80211_setup_func)(void);

__link_set_decl(ieee80211_funcs, ieee80211_setup_func);

static int
ieee80211_init0(void)
{
	ieee80211_setup_func * const *ieee80211_setup, f;

        __link_set_foreach(ieee80211_setup, ieee80211_funcs) {
		f = (void*)*ieee80211_setup;
		(*f)();
	}

	return 0;
}

void
ieee80211_init(void)
{
	static ONCE_DECL(ieee80211_init_once);

	RUN_ONCE(&ieee80211_init_once, ieee80211_init0);
}

static int
ieee80211_sysctl_inact(SYSCTLFN_ARGS)
{
	int error, t;
	struct sysctlnode node;

	node = *rnode;
	/* sysctl_lookup copies the product from t.  Then, it
	 * copies the new value onto t.
	 */
	t = *(int*)rnode->sysctl_data * IEEE80211_INACT_WAIT;
	node.sysctl_data = &t;
	error = sysctl_lookup(SYSCTLFN_CALL(&node));
	if (error || newp == NULL)
		return (error);

	/* The new value was in seconds.  Convert to inactivity-wait
	 * intervals.  There are IEEE80211_INACT_WAIT seconds per
	 * interval.
	 */
	*(int*)rnode->sysctl_data = t / IEEE80211_INACT_WAIT;

	return (0);
}

static int
ieee80211_sysctl_parent(SYSCTLFN_ARGS)
{
	struct ieee80211com *ic;
	char pname[IFNAMSIZ];
	struct sysctlnode node;

	node = *rnode;
	ic = node.sysctl_data;
	strncpy(pname, ic->ic_ifp->if_xname, IFNAMSIZ);
	node.sysctl_data = pname;
	return sysctl_lookup(SYSCTLFN_CALL(&node));
}

/*
 * Create or get top of sysctl tree net.link.ieee80211.
 */
static const struct sysctlnode *
ieee80211_sysctl_treetop(struct sysctllog **log)
{
	int rc;
	const struct sysctlnode *rnode;

	if ((rc = sysctl_createv(log, 0, NULL, &rnode,
	    CTLFLAG_PERMANENT, CTLTYPE_NODE, "net", NULL,
	    NULL, 0, NULL, 0, CTL_NET, CTL_EOL)) != 0)
		goto err;

	if ((rc = sysctl_createv(log, 0, &rnode, &rnode,
	    CTLFLAG_PERMANENT, CTLTYPE_NODE, "link",
	    "link-layer statistics and controls",
	    NULL, 0, NULL, 0, PF_LINK, CTL_EOL)) != 0)
		goto err;

	if ((rc = sysctl_createv(log, 0, &rnode, &rnode,
	    CTLFLAG_PERMANENT, CTLTYPE_NODE, "ieee80211",
	    "IEEE 802.11 WLAN statistics and controls",
	    NULL, 0, NULL, 0, CTL_CREATE, CTL_EOL)) != 0)
		goto err;

	return rnode;
err:
	printf("%s: sysctl_createv failed, rc = %d\n", __func__, rc);
	return NULL;
}

void
ieee80211_sysctl_attach(struct ieee80211com *ic)
{
	int rc;
	const struct sysctlnode *cnode, *rnode;
	char num[sizeof("vap") + 14];		/* sufficient for 32 bits */

	if ((rnode = ieee80211_sysctl_treetop(NULL)) == NULL)
		return;

	snprintf(num, sizeof(num), "vap%u", ic->ic_vap);

	if ((rc = sysctl_createv(&ic->ic_sysctllog, 0, &rnode, &rnode,
	    CTLFLAG_PERMANENT, CTLTYPE_NODE, num, SYSCTL_DESCR("virtual AP"),
	    NULL, 0, NULL, 0, CTL_CREATE, CTL_EOL)) != 0)
		goto err;

	/* control debugging printfs */
	if ((rc = sysctl_createv(&ic->ic_sysctllog, 0, &rnode, &cnode,
	    CTLFLAG_PERMANENT|CTLFLAG_READONLY, CTLTYPE_STRING,
	    "parent", SYSCTL_DESCR("parent device"),
	    ieee80211_sysctl_parent, 0, ic, IFNAMSIZ, CTL_CREATE,
	    CTL_EOL)) != 0)
		goto err;

#ifdef IEEE80211_DEBUG
	/* control debugging printfs */
	if ((rc = sysctl_createv(&ic->ic_sysctllog, 0, &rnode, &cnode,
	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
	    "debug", SYSCTL_DESCR("control debugging printfs"),
	    NULL, ieee80211_debug, &ic->ic_debug, 0,
	    CTL_CREATE, CTL_EOL)) != 0)
		goto err;
#endif
	/* XXX inherit from tunables */
	if ((rc = sysctl_createv(&ic->ic_sysctllog, 0, &rnode, &cnode,
	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
	    "inact_run", SYSCTL_DESCR("station inactivity timeout (sec)"),
	    ieee80211_sysctl_inact, 0, &ic->ic_inact_run, 0,
	    CTL_CREATE, CTL_EOL)) != 0)
		goto err;
	if ((rc = sysctl_createv(&ic->ic_sysctllog, 0, &rnode, &cnode,
	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
	    "inact_probe",
	    SYSCTL_DESCR("station inactivity probe timeout (sec)"),
	    ieee80211_sysctl_inact, 0, &ic->ic_inact_probe, 0,
	    CTL_CREATE, CTL_EOL)) != 0)
		goto err;
	if ((rc = sysctl_createv(&ic->ic_sysctllog, 0, &rnode, &cnode,
	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
	    "inact_auth",
	    SYSCTL_DESCR("station authentication timeout (sec)"),
	    ieee80211_sysctl_inact, 0, &ic->ic_inact_auth, 0,
	    CTL_CREATE, CTL_EOL)) != 0)
		goto err;
	if ((rc = sysctl_createv(&ic->ic_sysctllog, 0, &rnode, &cnode,
	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
	    "inact_init",
	    SYSCTL_DESCR("station initial state timeout (sec)"),
	    ieee80211_sysctl_inact, 0, &ic->ic_inact_init, 0,
	    CTL_CREATE, CTL_EOL)) != 0)
		goto err;
	if ((rc = sysctl_createv(&ic->ic_sysctllog, 0, &rnode, &cnode,
	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
	    "driver_caps", SYSCTL_DESCR("driver capabilities"),
	    NULL, 0, &ic->ic_caps, 0, CTL_CREATE, CTL_EOL)) != 0)
		goto err;
	if ((rc = sysctl_createv(&ic->ic_sysctllog, 0, &rnode, &cnode,
	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
	    "bmiss_max", SYSCTL_DESCR("consecutive beacon misses before scanning"),
	    NULL, 0, &ic->ic_bmiss_max, 0, CTL_CREATE, CTL_EOL)) != 0)
		goto err;

	return;
err:
	printf("%s: sysctl_createv failed, rc = %d\n", __func__, rc);
}

void
ieee80211_sysctl_detach(struct ieee80211com *ic)
{
	sysctl_teardown(&ic->ic_sysctllog);
}

/*
 * Pointers for testing:
 *
 *	If there are no interfaces, or else no 802.11 interfaces,
 *	ieee80211_node_walkfirst must return NULL.
 *
 *	If there is any single 802.11 interface, ieee80211_node_walkfirst
 *	must not return NULL.
 */
static struct ieee80211_node *
ieee80211_node_walkfirst(struct ieee80211_node_walk *nw, u_short if_index)
{
	(void)memset(nw, 0, sizeof(*nw));

	nw->nw_ifindex = if_index;

	LIST_FOREACH(nw->nw_ic, &ieee80211com_head, ic_list) {
		if (if_index != 0 && nw->nw_ic->ic_ifp->if_index != if_index)
			continue;
		if (!TAILQ_EMPTY(&nw->nw_ic->ic_sta.nt_node))
			nw->nw_nt = &nw->nw_ic->ic_sta;
		else if (!TAILQ_EMPTY(&nw->nw_ic->ic_scan.nt_node))
			nw->nw_nt = &nw->nw_ic->ic_scan;
		else if (nw->nw_ic->ic_bss == NULL)
			continue;
		break;
	}

	if (nw->nw_ic == NULL)
		return NULL;

	if (nw->nw_nt == NULL)
		nw->nw_ni = nw->nw_ic->ic_bss;
	else
		nw->nw_ni = TAILQ_FIRST(&nw->nw_nt->nt_node);

	return nw->nw_ni;
}

static struct ieee80211_node *
ieee80211_node_walknext(struct ieee80211_node_walk *nw)
{
	if (nw->nw_nt != NULL)
		nw->nw_ni = TAILQ_NEXT(nw->nw_ni, ni_list);
	else
		nw->nw_ni = NULL;

	while (nw->nw_ni == NULL) {
		if (nw->nw_nt == &nw->nw_ic->ic_sta) {
			nw->nw_nt = &nw->nw_ic->ic_scan;
			nw->nw_ni = TAILQ_FIRST(&nw->nw_nt->nt_node);
			continue;
		} else if (nw->nw_nt == &nw->nw_ic->ic_scan) {
			nw->nw_nt = NULL;
			nw->nw_ni = nw->nw_ic->ic_bss;
			continue;
		}
		KASSERT(nw->nw_nt == NULL);
		if (nw->nw_ifindex != 0)
			return NULL;

		nw->nw_ic = LIST_NEXT(nw->nw_ic, ic_list);
		if (nw->nw_ic == NULL)
			return NULL;

		nw->nw_nt = &nw->nw_ic->ic_sta;
		nw->nw_ni = TAILQ_FIRST(&nw->nw_nt->nt_node);
	}

	return nw->nw_ni;
}

static void
ieee80211_sysctl_fill_node(struct ieee80211_node *ni,
    struct ieee80211_node_sysctl *ns, int ifindex,
    const struct ieee80211_channel *chan0, uint32_t flags)
{
	ns->ns_ifindex = ifindex;
	ns->ns_capinfo = ni->ni_capinfo;
	ns->ns_flags = flags;
	(void)memcpy(ns->ns_macaddr, ni->ni_macaddr, sizeof(ns->ns_macaddr));
	(void)memcpy(ns->ns_bssid, ni->ni_bssid, sizeof(ns->ns_bssid));
	if (ni->ni_chan != IEEE80211_CHAN_ANYC) {
		ns->ns_freq = ni->ni_chan->ic_freq;
		ns->ns_chanflags = ni->ni_chan->ic_flags;
		ns->ns_chanidx = ni->ni_chan - chan0;
	} else {
		ns->ns_freq = ns->ns_chanflags = 0;
		ns->ns_chanidx = 0;
	}
	ns->ns_rssi = ni->ni_rssi;
	ns->ns_esslen = ni->ni_esslen;
	(void)memcpy(ns->ns_essid, ni->ni_essid, sizeof(ns->ns_essid));
	ns->ns_erp = ni->ni_erp;
	ns->ns_associd = ni->ni_associd;
	ns->ns_inact = ni->ni_inact * IEEE80211_INACT_WAIT;
	ns->ns_rstamp = ni->ni_rstamp;
	ns->ns_rates = ni->ni_rates;
	ns->ns_txrate = ni->ni_txrate;
	ns->ns_intval = ni->ni_intval;
	(void)memcpy(ns->ns_tstamp, &ni->ni_tstamp, sizeof(ns->ns_tstamp));
	ns->ns_txseq = ni->ni_txseqs[0];
	ns->ns_rxseq = ni->ni_rxseqs[0];
	ns->ns_fhdwell = ni->ni_fhdwell;
	ns->ns_fhindex = ni->ni_fhindex;
	ns->ns_fails = ni->ni_fails;
}

/* Between two examinations of the sysctl tree, I expect each
 * interface to add no more than 5 nodes.
 */
#define IEEE80211_SYSCTL_NODE_GROWTH	5

static int
ieee80211_sysctl_node(SYSCTLFN_ARGS)
{
	struct ieee80211_node_walk nw;
	struct ieee80211_node *ni;
	struct ieee80211_node_sysctl ns;
	char *dp;
	u_int cur_ifindex, ifcount, ifindex, last_ifindex, op, arg, hdr_type;
	uint32_t flags;
	size_t len, needed, eltsize, out_size;
	int error, s, saw_bss = 0, nelt;

	if (namelen == 1 && name[0] == CTL_QUERY)
		return (sysctl_query(SYSCTLFN_CALL(rnode)));

	if (namelen != IEEE80211_SYSCTL_NODENAMELEN)
		return (EINVAL);

	/* ifindex.op.arg.header-type.eltsize.nelt */
	dp = oldp;
	len = (oldp != NULL) ? *oldlenp : 0;
	ifindex = name[IEEE80211_SYSCTL_NODENAME_IF];
	op = name[IEEE80211_SYSCTL_NODENAME_OP];
	arg = name[IEEE80211_SYSCTL_NODENAME_ARG];
	hdr_type = name[IEEE80211_SYSCTL_NODENAME_TYPE];
	eltsize = name[IEEE80211_SYSCTL_NODENAME_ELTSIZE];
	nelt = name[IEEE80211_SYSCTL_NODENAME_ELTCOUNT];
	out_size = MIN(sizeof(ns), eltsize);

	if (op != IEEE80211_SYSCTL_OP_ALL || arg != 0 ||
	    hdr_type != IEEE80211_SYSCTL_T_NODE || eltsize < 1 || nelt < 0)
		return (EINVAL);

	error = 0;
	needed = 0;
	ifcount = 0;
	last_ifindex = 0;

	s = splnet();

	for (ni = ieee80211_node_walkfirst(&nw, ifindex); ni != NULL;
	     ni = ieee80211_node_walknext(&nw)) {
		struct ieee80211com *ic;

		ic = nw.nw_ic;
		cur_ifindex = ic->ic_ifp->if_index;

		if (cur_ifindex != last_ifindex) {
			saw_bss = 0;
			ifcount++;
			last_ifindex = cur_ifindex;
		}

		if (nelt <= 0)
			continue;

		if (saw_bss && ni == ic->ic_bss)
			continue;
		else if (ni == ic->ic_bss) {
			saw_bss = 1;
			flags = IEEE80211_NODE_SYSCTL_F_BSS;
		} else
			flags = 0;
		if (ni->ni_table == &ic->ic_scan)
			flags |= IEEE80211_NODE_SYSCTL_F_SCAN;
		else if (ni->ni_table == &ic->ic_sta)
			flags |= IEEE80211_NODE_SYSCTL_F_STA;
		if (len >= eltsize) {
			ieee80211_sysctl_fill_node(ni, &ns, cur_ifindex,
			    &ic->ic_channels[0], flags);
			error = copyout(&ns, dp, out_size);
			if (error)
				goto cleanup;
			dp += eltsize;
			len -= eltsize;
		}
		needed += eltsize;
		if (nelt != INT_MAX)
			nelt--;
	}
cleanup:
	splx(s);

	*oldlenp = needed;
	if (oldp == NULL)
		*oldlenp += ifcount * IEEE80211_SYSCTL_NODE_GROWTH * eltsize;

	return (error);
}

/*
 * Setup sysctl(3) MIB, net.ieee80211.*
 *
 * TBD condition CTLFLAG_PERMANENT on being a module or not
 */
SYSCTL_SETUP(sysctl_ieee80211, "sysctl ieee80211 subtree setup")
{
	int rc;
	const struct sysctlnode *cnode, *rnode;

	if ((rnode = ieee80211_sysctl_treetop(clog)) == NULL)
		return;

	if ((rc = sysctl_createv(clog, 0, &rnode, NULL,
	    CTLFLAG_PERMANENT, CTLTYPE_NODE, "nodes", "client/peer stations",
	    ieee80211_sysctl_node, 0, NULL, 0, CTL_CREATE, CTL_EOL)) != 0)
		goto err;

#ifdef IEEE80211_DEBUG
	/* control debugging printfs */
	if ((rc = sysctl_createv(clog, 0, &rnode, &cnode,
	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
	    "debug", SYSCTL_DESCR("control debugging printfs"),
	    NULL, 0, &ieee80211_debug, 0, CTL_CREATE, CTL_EOL)) != 0)
		goto err;
#endif /* IEEE80211_DEBUG */

	return;
err:
	printf("%s: sysctl_createv failed (rc = %d)\n", __func__, rc);
}

int
ieee80211_node_dectestref(struct ieee80211_node *ni)
{
	if (atomic_dec_uint_nv(&ni->ni_refcnt) == 0) {
		atomic_inc_uint(&ni->ni_refcnt);
		return 1;
	} else
		return 0;
}

void
ieee80211_drain_ifq(struct ifqueue *ifq)
{
	struct ieee80211_node *ni;
	struct mbuf *m;

	for (;;) {
		IF_DEQUEUE(ifq, m);
		if (m == NULL)
			break;

		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
		KASSERT(ni != NULL);
		ieee80211_free_node(ni);
		m->m_pkthdr.rcvif = NULL;

		m_freem(m);
	}
}

void
if_printf(struct ifnet *ifp, const char *fmt, ...)
{
	va_list ap;
	va_start(ap, fmt);

	printf("%s: ", ifp->if_xname);
	vprintf(fmt, ap);

	va_end(ap);
	return;
}

/*
 * Set the m_data pointer of a newly-allocated mbuf
 * to place an object of the specified size at the
 * end of the mbuf, longword aligned.
 */
void
m_align(struct mbuf *m, int len)
{
       int adjust;

       if (m->m_flags & M_EXT)
	       adjust = m->m_ext.ext_size - len;
       else if (m->m_flags & M_PKTHDR)
	       adjust = MHLEN - len;
       else
	       adjust = MLEN - len;
       m->m_data += adjust &~ (sizeof(long)-1);
}

/*
 * Append the specified data to the indicated mbuf chain,
 * Extend the mbuf chain if the new data does not fit in
 * existing space.
 *
 * Return 1 if able to complete the job; otherwise 0.
 */
int
m_append(struct mbuf *m0, int len, const void *cpv)
{
	struct mbuf *m, *n;
	int remainder, space;
	const char *cp = cpv;

	for (m = m0; m->m_next != NULL; m = m->m_next)
		continue;
	remainder = len;
	space = M_TRAILINGSPACE(m);
	if (space > 0) {
		/*
		 * Copy into available space.
		 */
		if (space > remainder)
			space = remainder;
		memmove(mtod(m, char *) + m->m_len, cp, space);
		m->m_len += space;
		cp = cp + space, remainder -= space;
	}
	while (remainder > 0) {
		/*
		 * Allocate a new mbuf; could check space
		 * and allocate a cluster instead.
		 */
		n = m_get(M_DONTWAIT, m->m_type);
		if (n == NULL)
			break;
		n->m_len = min(MLEN, remainder);
		memmove(mtod(n, void *), cp, n->m_len);
		cp += n->m_len, remainder -= n->m_len;
		m->m_next = n;
		m = n;
	}
	if (m0->m_flags & M_PKTHDR)
		m0->m_pkthdr.len += len - remainder;
	return (remainder == 0);
}

/*
 * Allocate and setup a management frame of the specified
 * size.  We return the mbuf and a pointer to the start
 * of the contiguous data area that's been reserved based
 * on the packet length.  The data area is forced to 32-bit
 * alignment and the buffer length to a multiple of 4 bytes.
 * This is done mainly so beacon frames (that require this)
 * can use this interface too.
 */
struct mbuf *
ieee80211_getmgtframe(u_int8_t **frm, u_int pktlen)
{
	struct mbuf *m;
	u_int len;

	/*
	 * NB: we know the mbuf routines will align the data area
	 *     so we don't need to do anything special.
	 */
	/* XXX 4-address frame? */
	len = roundup(sizeof(struct ieee80211_frame) + pktlen, 4);
	IASSERT(len <= MCLBYTES, ("802.11 mgt frame too large: %u", len));
	if (len <= MHLEN) {
		m = m_gethdr(M_NOWAIT, MT_HEADER);
		/*
		 * Align the data in case additional headers are added.
		 * This should only happen when a WEP header is added
		 * which only happens for shared key authentication mgt
		 * frames which all fit in MHLEN.
		 */
		if (m != NULL)
			MH_ALIGN(m, len);
	} else
		m = m_getcl(M_NOWAIT, MT_HEADER, M_PKTHDR);
	if (m != NULL) {
		m->m_data += sizeof(struct ieee80211_frame);
		*frm = m->m_data;
		IASSERT((uintptr_t)*frm % 4 == 0, ("bad beacon boundary"));
	}
	return m;
}

void
get_random_bytes(void *p, size_t n)
{
	cprng_fast(p, n);
}

void
ieee80211_notify_node_join(struct ieee80211com *ic, struct ieee80211_node *ni, int newassoc)
{
	struct ifnet *ifp = ic->ic_ifp;
	struct ieee80211_join_event iev;

	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE, "%s: %snode %s join\n",
	    ifp->if_xname, (ni == ic->ic_bss) ? "bss " : "",
	    ether_sprintf(ni->ni_macaddr));

	memset(&iev, 0, sizeof(iev));
	if (ni == ic->ic_bss) {
		IEEE80211_ADDR_COPY(iev.iev_addr, ni->ni_bssid);
		rt_ieee80211msg(ifp, newassoc ?
			RTM_IEEE80211_ASSOC : RTM_IEEE80211_REASSOC,
			&iev, sizeof(iev));
		if_link_state_change(ifp, LINK_STATE_UP);
	} else {
		IEEE80211_ADDR_COPY(iev.iev_addr, ni->ni_macaddr);
		rt_ieee80211msg(ifp, newassoc ?
		    RTM_IEEE80211_JOIN : RTM_IEEE80211_REJOIN,
		    &iev, sizeof(iev));
	}
}

void
ieee80211_notify_node_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
{
	struct ifnet *ifp = ic->ic_ifp;
	struct ieee80211_leave_event iev;

	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE, "%s: %snode %s leave\n",
	    ifp->if_xname, (ni == ic->ic_bss) ? "bss " : "",
	    ether_sprintf(ni->ni_macaddr));

	if (ni == ic->ic_bss) {
		rt_ieee80211msg(ifp, RTM_IEEE80211_DISASSOC, NULL, 0);
		if_link_state_change(ifp, LINK_STATE_DOWN);
	} else {
		/* fire off wireless event station leaving */
		memset(&iev, 0, sizeof(iev));
		IEEE80211_ADDR_COPY(iev.iev_addr, ni->ni_macaddr);
		rt_ieee80211msg(ifp, RTM_IEEE80211_LEAVE, &iev, sizeof(iev));
	}
}

void
ieee80211_notify_scan_done(struct ieee80211com *ic)
{
	struct ifnet *ifp = ic->ic_ifp;

	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
		"%s: notify scan done\n", ic->ic_ifp->if_xname);

	/* dispatch wireless event indicating scan completed */
	rt_ieee80211msg(ifp, RTM_IEEE80211_SCAN, NULL, 0);
}

void
ieee80211_notify_replay_failure(struct ieee80211com *ic,
	const struct ieee80211_frame *wh, const struct ieee80211_key *k,
	u_int64_t rsc)
{
	struct ifnet *ifp = ic->ic_ifp;

	IEEE80211_DPRINTF(ic, IEEE80211_MSG_CRYPTO,
	    "[%s] %s replay detected <rsc %ju, csc %ju, keyix %u rxkeyix %u>\n",
	    ether_sprintf(wh->i_addr2), k->wk_cipher->ic_name,
	    (intmax_t) rsc, (intmax_t) k->wk_keyrsc,
	    k->wk_keyix, k->wk_rxkeyix);

	if (ifp != NULL) {		/* NB: for cipher test modules */
		struct ieee80211_replay_event iev;

		IEEE80211_ADDR_COPY(iev.iev_dst, wh->i_addr1);
		IEEE80211_ADDR_COPY(iev.iev_src, wh->i_addr2);
		iev.iev_cipher = k->wk_cipher->ic_cipher;
		if (k->wk_rxkeyix != IEEE80211_KEYIX_NONE)
			iev.iev_keyix = k->wk_rxkeyix;
		else
			iev.iev_keyix = k->wk_keyix;
		iev.iev_keyrsc = k->wk_keyrsc;
		iev.iev_rsc = rsc;
		rt_ieee80211msg(ifp, RTM_IEEE80211_REPLAY, &iev, sizeof(iev));
	}
}

void
ieee80211_notify_michael_failure(struct ieee80211com *ic,
	const struct ieee80211_frame *wh, u_int keyix)
{
	struct ifnet *ifp = ic->ic_ifp;

	IEEE80211_DPRINTF(ic, IEEE80211_MSG_CRYPTO,
		"[%s] michael MIC verification failed <keyix %u>\n",
	       ether_sprintf(wh->i_addr2), keyix);
	ic->ic_stats.is_rx_tkipmic++;

	if (ifp != NULL) {		/* NB: for cipher test modules */
		struct ieee80211_michael_event iev;

		IEEE80211_ADDR_COPY(iev.iev_dst, wh->i_addr1);
		IEEE80211_ADDR_COPY(iev.iev_src, wh->i_addr2);
		iev.iev_cipher = IEEE80211_CIPHER_TKIP;
		iev.iev_keyix = keyix;
		rt_ieee80211msg(ifp, RTM_IEEE80211_MICHAEL, &iev, sizeof(iev));
	}
}

void
ieee80211_load_module(const char *modname)
{
#ifdef notyet
	struct thread *td = curthread;

	if (suser(td) == 0 && securelevel_gt(td->td_ucred, 0) == 0) {
		mtx_lock(&Giant);
		(void) linker_load_module(modname, NULL, NULL, NULL, NULL);
		mtx_unlock(&Giant);
	}
#else
	printf("%s: load the %s module by hand for now.\n", __func__, modname);
#endif
}


text:
package com.squareup.picasso;

import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;

import java.lang.ref.WeakReference;

abstract class Action<T> {

  final Picasso picasso;
  final Request request;
  final WeakReference<T> target;
  final boolean skipCache;
  final int errorResId;
  final Drawable errorDrawable;
  final String key;
  final Object tag;
  long fadeTime;

  boolean willReplay;
  boolean cancelled;

  Action(Picasso picasso, T target, Request request, boolean skipCache, long fadeTime,
      int errorResId, Drawable errorDrawable, String key, Object tag) {
    this.picasso = picasso;
    this.request = request;
    this.target =
        target == null ? null : new RequestWeakReference<T>(this, target, picasso.referenceQueue);
    this.skipCache = skipCache;
    this.fadeTime = fadeTime;
    this.errorResId = errorResId;
    this.errorDrawable = errorDrawable;
    this.key = key;
    this.tag = (tag != null ? tag : this);
  }

  abstract void complete(Bitmap result, Picasso.LoadedFrom from);

  abstract void error();

  void cancel() {
    cancelled = true;
  }

  Request getRequest() {
    return request;
  }

  T getTarget() {
    return target.get();
  }

  String getKey() {
    return key;
  }

  boolean isCancelled() {
    return cancelled;
  }

  boolean willReplay() {
    return willReplay;
  }

  Picasso getPicasso() {
    return picasso;
  }

  Picasso.Priority getPriority() {
    return request.priority;
  }

  Object getTag() {
    return tag;
  }
}


text:
/*
  ## Fields (DEPRECATED)
*/
define([
  'angular',
  'app',
  'underscore'
],
function (angular, app, _) {
  'use strict';

  var module = angular.module('kibana.panels.fields', []);
  app.useModule(module);

  module.controller('fields', function($scope) {

    $scope.panelMeta = {
      status  : "Deprecated",
      description : "You should not use this table, it does not work anymore. The table panel now"+
        "integrates a field selector. This module will soon be removed."
    };

    // Set and populate defaults
    var _d = {
      style   : {},
      arrange : 'vertical',
      micropanel_position : 'right',
    };
    _.defaults($scope.panel,_d);

    $scope.init = function() {
      // Place holder until I remove this
    };

  });
});


text:
<?php

// Call Zend_Dojo_Form_Element_FilteringSelectTest::main() if this source file is executed directly.
if (!defined("PHPUnit_MAIN_METHOD")) {
    define("PHPUnit_MAIN_METHOD", "Zend_Dojo_Form_Element_FilteringSelectTest::main");
}

/** Zend_Dojo_Form_Element_FilteringSelect */
require_once 'Zend/Dojo/Form/Element/FilteringSelect.php';

/** Zend_View */
require_once 'Zend/View.php';

/** Zend_Registry */
require_once 'Zend/Registry.php';

/** Zend_Dojo_View_Helper_Dojo */
require_once 'Zend/Dojo/View/Helper/Dojo.php';

/**
 * Test class for Zend_Dojo_Form_Element_FilteringSelect.
 *
 * @category   Zend
 * @package    Zend_Dojo
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @group      Zend_Dojo
 * @group      Zend_Dojo_Form
 */
class Zend_Dojo_Form_Element_FilteringSelectTest extends PHPUnit_Framework_TestCase
{
    /**
     * Runs the test methods of this class.
     *
     * @return void
     */
    public static function main()
    {
        $suite  = new PHPUnit_Framework_TestSuite("Zend_Dojo_Form_Element_FilteringSelectTest");
        $result = PHPUnit_TextUI_TestRunner::run($suite);
    }

    /**
     * Sets up the fixture, for example, open a network connection.
     * This method is called before a test is executed.
     *
     * @return void
     */
    public function setUp()
    {
        Zend_Registry::_unsetInstance();
        Zend_Dojo_View_Helper_Dojo::setUseDeclarative();

        $this->view    = $this->getView();
        $this->element = $this->getElement();
        $this->element->setView($this->view);
    }

    /**
     * Tears down the fixture, for example, close a network connection.
     * This method is called after a test is executed.
     *
     * @return void
     */
    public function tearDown()
    {
    }

    public function getView()
    {
        require_once 'Zend/View.php';
        $view = new Zend_View();
        $view->addHelperPath('Zend/Dojo/View/Helper/', 'Zend_Dojo_View_Helper');
        return $view;
    }

    public function getElement()
    {
        $element = new Zend_Dojo_Form_Element_FilteringSelect(
            'foo',
            array(
                'value' => 'some text',
                'label' => 'FilteringSelect',
                'class' => 'someclass',
                'style' => 'width: 100px;',
            )
        );
        return $element;
    }

    public function testShouldRenderFilteringSelectDijit()
    {
        $html = $this->element->render();
        $this->assertContains('dojoType="dijit.form.FilteringSelect"', $html);
    }

    /**#@+
     * @group ZF-3286
     */
    public function testShouldRegisterInArrayValidatorWhenNoStoreProvided()
    {
        $options = array(
            'foo' => 'Foo Value',
            'bar' => 'Bar Value',
            'baz' => 'Baz Value',
        );
        $this->element->setMultiOptions($options);
        $this->assertFalse($this->element->getValidator('InArray'));
        $this->element->isValid('test');
        $validator = $this->element->getValidator('InArray');
        $this->assertTrue($validator instanceof Zend_Validate_InArray);
    }

    public function testShouldNotRegisterInArrayValidatorWhenStoreProvided()
    {
        $options = array(
            'foo' => 'Foo Value',
            'bar' => 'Bar Value',
            'baz' => 'Baz Value',
        );
        $this->element->setMultiOptions($options);
        $this->element->setStoreId('fooStore')
                      ->setStoreType('dojo.data.ItemFileReadStore')
                      ->setStoreParams(array('url' => '/foo'));
        $this->assertFalse($this->element->getValidator('InArray'));
        $this->element->isValid('test');
        $this->assertFalse($this->element->getValidator('InArray'));
    }
    /**#@-*/
}

// Call Zend_Dojo_Form_Element_FilteringSelectTest::main() if this source file is executed directly.
if (PHPUnit_MAIN_METHOD == "Zend_Dojo_Form_Element_FilteringSelectTest::main") {
    Zend_Dojo_Form_Element_FilteringSelectTest::main();
}


text:
// Jest configuration for api
const base = require('../../jest.config.base.js');

module.exports = {
  ...base,
  rootDir: '../..',
  testMatch: ['<rootDir>/packages/utils/**/*.test.ts', '<rootDir>/packages/utils/**/*.test.tsx'],
  name: '@sajari/react-sdk-utils',
  displayName: 'utils',
};


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>com.github.ferstl</groupId>
    <artifactId>parent</artifactId>
    <version>1.0.0-SNAPSHOT</version>
  </parent>

  <artifactId>submodule</artifactId>

  <dependencies>

    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
    </dependency>
  </dependencies>
</project>


text:
.class Landroid/widget/ScrollView$4;
.super Ljava/lang/Object;
.source "ScrollView.java"

# interfaces
.implements Ljava/lang/Runnable;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Landroid/widget/ScrollView;->dispatchTouchEvent(Landroid/view/MotionEvent;)Z
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Landroid/widget/ScrollView;

# direct methods
.method constructor <init>(Landroid/widget/ScrollView;)V
    .locals 0

    iput-object p1, p0, Landroid/widget/ScrollView$4;->this$0:Landroid/widget/ScrollView;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public run()V
    .locals 2

    const/4 v1, 0x0

    iget-object v0, p0, Landroid/widget/ScrollView$4;->this$0:Landroid/widget/ScrollView;

    invoke-virtual {v0, v1, v1}, Landroid/widget/ScrollView;->smoothScrollTo(II)V

    return-void
.end method


text:
*{margin:0px;padding:0px;}
.main{
width:100%;height:auto;background:#EEEEEE;margin:0px auto;

}
.main .head{
width:100%;height:100px;background:#800000;
}
.head .subhead{
width:1000px;height:100px;margin:0px auto;
}
.subhead .logo{
float:left;width:100px;height:50px;margin-top:20px;
}
.subhead .title{
float:left;color:#EEEEEE;margin-top:20px;font-size:30px;
}
.head .LogoutButton{
	float: right; margin-top: 20px;
}
.subhead .icon{
width:40px;height:40px;float:right;margin-top:20px;margin-left:5px;
}
.subhead .icon:hover{
border-radius:40px;
}
.main .menu{
width:100%;height:40px;background:#800000;
}
.menu .submenu{
width:1000px;height:40px;margin:0px auto;

}

.submenu .nav{
list-style:none;
}
.submenu .nav li{
float:left;width:250px;height:40px;background:#FFFFFF;text-align:center;line-height:40px;

}
.submenu .nav li a{
text-decoration:none;color:#800000;
}
.submenu .nav li:hover{
background:url(../img/btn2.png);background-size:100% 100%;
}
.submenu .nav li:hover a{
color:#800000;font-size:20px;
}
.nav .subnav{
list-style:none;visibility:hidden;
}
.nav li:hover .subnav{
visibility:visible;
}
.subnav li a{
color:blue !important;font-size:16px !important;
}
.subnav li:hover a{
color:white !important;
}
.subnav li{margin-left:0px !important;border-bottom:3px solid blue !important ;}

.subnav .subsubnav{
list-style:none;visibility:hidden;position:relative;left:195px;top:-40px;
}
.subnav li:hover .subsubnav{
visibility:visible;
}
.subnav .subsubnav li a{color:green !important;}
.subsubnav li:hover a{
color:white !important;
}
.subsubnav li{border-left:2px solid green;}

.tables{
	width:250px;border:2px solid grey;margin-left:180px;
}
.leftTable{
	margin-left:180px;width: 250px;margin-top:20px;
}
.rightTable{
	margin-left:30px;
margin-right:20px;
margin-top:10px;
/*background-color:powderblue;*/
width:80%;
padding:10px;
}

.leftTable td{
	 border: 1px solid black;padding:2px 5px;
}
#myDIV .div{
	list-style:none;
}
.div li:hover a{
	color:red;
}
#myDIV1 .div{
	list-style:none;
}

.col-md-6{
position:fixed;
bottom:0px;
margin-left:auto;
margin-right:auto;}
/* View Acc Details section.*/
element.style {
    border: 1px solid #828282;
    margin: 0 auto;
}
/* View Acc Details Main Header Table section.*/
element.style {
    margin-top: 15px;
}
.AdvDetailsTitle {
    color: #1c79c9;
    font-family: arial;
    font-size: 16px;
    font-weight: bold;
    margin-left: 10px;
    text-decoration: none;
}
/* View Acc Details section.*/
.topheaderBlock {
    -moz-border-bottom-colors: none;
    -moz-border-left-colors: none;
    -moz-border-right-colors: none;
    -moz-border-top-colors: none;
    background-color: #f1f1f1;
    border-color: #828282;
    border-image: none;
    border-style: solid none;
    border-width: 1px;
    height: 30px;
/* for heading */
.topHeadingRows {
    color: black;
    font-family: arial;
    font-size: 14px;
    font-weight: normal;
    margin-left: 30px;
}
/* Acc Details_Location Details */
element.style {
    background-color: #f0f8ff;
    margin-left: auto;
    margin-right: auto;
    margin-top: 10px;
}
.outermainborder {
    border: 1px solid #a6a6a6;
    margin-left: auto;
    margin-right: auto;
    position: relative;
}
/* Location*/

.column4Class {
    width: 200px;
}
element.style {
    margin-left: 40px;
    margin-top: 20px;
}
.fontBodyLabel {
    color: black;
    font-family: arial;
    font-size: 12px;
    font-weight: bold;

}
.column2Class {
    width: 5px;
}
element.style {
    margin-top: 20px;
}
.fontBodyLabel {
    color: black;
    font-family: arial;
    font-size: 12px;
    font-weight: bold;
}
/*address */

.column1Class {
    width: 190px;
}
element.style {
    margin-top: 20px;
}
.fontBody {
    color: black;
    font-family: arial;
    font-size: 12px !important;
    font-weight: normal;
}
/**/
.column3Class {
    width: 180px;
}

element.style {
    margin-left: 20px;
    margin-top: 20px;
}


text:
package com.dianping.cat.message.pipeline;

public interface MessagePipeline extends MessageHandler {
	void addLast(MessageHandler handler);

	MessageHandlerContext headContext(Object message);
}


text:
external help file: Microsoft.Azure.Commands.Network.dll-Help.xml
ms.assetid: CB7DED0C-52C6-45A0-955B-7B82738BE3FC
online version:
schema: 2.0.0
---

# Remove-AzureRmApplicationGatewayBackendHttpSettings

## SYNOPSIS
Removes back-end HTTP settings from an application gateway.

## SYNTAX

```
Remove-AzureRmApplicationGatewayBackendHttpSettings -Name <String> -ApplicationGateway <PSApplicationGateway>
 [-InformationAction <ActionPreference>] [-InformationVariable <String>] [<CommonParameters>]
```

## DESCRIPTION
The **Remove-AzureRmApplicationGatewayBackendHttpSettings** cmdlet removes back-end Hypertext Transfer Protocol (HTTP) settings from an Azure application gateway.

## EXAMPLES

### Example 1: Remove back-end HTTP settings from an application gateway
```
PS C:\>$AppGw = Get-AzureRmApplicationGateway -Name "ApplicationGateway01" -ResourceGroupName "ResourceGroup01"
PS C:\> Remove-AzureRmApplicationGatewayBackendHttpSettings -ApplicationGateway $AppGw -Name "BackEndSetting02"
```

The first command gets an application gateway named ApplicationGateway01 that belongs to the resource group named ResourceGroup01 and stores it in the $AppGw variable.

The second command removes the back-end HTTP setting named BackEndSetting02 from the application gateway stored in $AppGw.

## PARAMETERS

### -Name
Specifies the name of the back-end HTTP settings that this cmdlet removes.

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -ApplicationGateway
Specifies the application gateway from which this cmdlet removes back-end HTTP settings.

```yaml
Type: PSApplicationGateway
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: True (ByValue)
Accept wildcard characters: False
```

### -InformationAction
Specifies how this cmdlet responds to an information event.

The acceptable values for this parameter are:

- Continue
- Ignore
- Inquire
- SilentlyContinue
- Stop
- Suspend

```yaml
Type: ActionPreference
Parameter Sets: (All)
Aliases: infa

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -InformationVariable
Specifies an information variable.

```yaml
Type: String
Parameter Sets: (All)
Aliases: iv

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

### System.String

## OUTPUTS

## NOTES

## RELATED LINKS

[Add-AzureRmApplicationGatewayBackendHttpSettings](./Add-AzureRmApplicationGatewayBackendHttpSettings.md)

[New-AzureRmApplicationGatewayBackendHttpSettings](./New-AzureRmApplicationGatewayBackendHttpSettings.md)

[Get-AzureRmApplicationGatewayBackendHttpSettings](./Get-AzureRmApplicationGatewayBackendHttpSettings.md)

[Set-AzureRmApplicationGatewayBackendHttpSettings](./Set-AzureRmApplicationGatewayBackendHttpSettings.md)


text:
Package.describe({
  name: 'makerotc:dapple',
  version: '0.0.1',
  summary: 'Dapple related code for MakerOTC',
  git: '',
  documentation: 'README.md',
});

Package.onUse((api) => {
  api.versionsFrom('1.4.0.1');

  api.use('ecmascript', 'client');
  api.use('ethereum:web3', 'client');

  api.addFiles(['package-pre-init.js'], 'client');
  api.addFiles(['contracts-abi/maker-otc.js'], 'client');
  api.addFiles(['contracts-abi/ds-eth-token.js'], 'client');
  api.addFiles(['contracts-abi/token-wrapper.js'], 'client');
  api.addFiles(['package-post-init.js'], 'client');

  api.export('web3Obj', 'client');
  api.export('Dapple', 'client');
});


text:
<?php

namespace WebFW\Core\DBLayer\Tables;

use WebFW\Database\Table;
use WebFW\Database\TableColumns\IntegerColumn;
use WebFW\Database\TableColumns\VarcharColumn;
use WebFW\Database\TableColumns\BooleanColumn;
use WebFW\Database\TableConstraints\PrimaryKey;
use WebFW\Database\TableConstraints\Unique;

class RouteDefinition extends Table
{
    protected function init()
    {
        $this->setName('webfw_route_definition');

        $this->addColumn(IntegerColumn::spawn($this, 'route_definition_id', false)->setDefaultValue(null, true));
        $this->addColumn(VarcharColumn::spawn($this, 'pattern', true, 200)->setDefaultValue(null));
        $this->addColumn(VarcharColumn::spawn($this, 'controller', true, 50)->setDefaultValue(null));
        $this->addColumn(VarcharColumn::spawn($this, 'namespace', true, 50)->setDefaultValue(null));
        $this->addColumn(VarcharColumn::spawn($this, 'action', true, 50)->setDefaultValue(null));
        $this->addColumn(IntegerColumn::spawn($this, 'order_id', false)->setDefaultValue(null));
        $this->addColumn(BooleanColumn::spawn($this, 'active', false)->setDefaultValue(true));

        $this->addConstraint(PrimaryKey::spawn($this)->addColumn($this->getColumn('route_definition_id')));
        $this->addConstraint(Unique::spawn($this)->addColumn($this->getColumn('pattern')));
    }
}


text:
//
// Created by jrusnak on 7/22/16.
//

#ifndef __PYLLARS_INTERNAL__CLASSMETHODSEMANTICS_CPP__
#define __PYLLARS_INTERNAL__CLASSMETHODSEMANTICS_CPP__

#include "pyllars/internal/pyllars_function_wrapper.hpp"
#include "pyllars_staticfunctionsemantics.impl.hpp"
#include "pyllars_utils.impl.hpp"
#include "pyllars/internal/pyllars_conversions.impl.hpp"
#include <cstddef>

namespace __pyllars_internal{

    namespace {
        struct Arbitrary{
            float fdata;
            int idata;
        };

        template<typename func_type, typename... PyO>
        typename func_traits<func_type>::ReturnType
        __call_static_func(func_type func, PyObject *extra_args, PyO *...pyobjs);

        template<typename ReturnType, typename ...Args, typename... PyO>
        ReturnType
        __call_static_func(ReturnType (*func)(Args..., ...), PyObject *extra_args, PyO *...pyargs) {
            typedef ReturnType (func_type)(Args..., ...);

            if (!extra_args || PyTuple_Size(extra_args) == 0) {
                if constexpr (std::is_void<ReturnType>::value) {
                    func(toCArgument<Args>(*pyargs).value()...);
                } else {
                    return func(toCArgument<Args>(*pyargs).value()...);
                }
            } else {
                const ssize_t extra_args_size = PyTuple_Size(extra_args);

                ffi_cif cif;
                ffi_type *arg_types[func_traits<func_type>::argsize + extra_args_size] = {FFIType<Args>::type()...};
                bool is_reference[] = {std::is_reference<Args>::value...};
                void *arg_values_bare[func_traits<func_type>::argsize + extra_args_size] = {(void*)toCArgument<Args>(*pyargs).ptr()...};
                void *arg_values[func_traits<func_type>::argsize + extra_args_size] = {(void*)toCArgument<Args>(*pyargs).ptr()...};
                for (int i = 0; i < sizeof...(Args); ++i){
                    if (is_reference[i]){
                        arg_values[i] = &arg_values_bare[i];
                        arg_types[i] = &ffi_type_pointer;
                    }
                }
                ffi_status status;

                // Because the return _CObject from foo() is smaller than sizeof(long), it
                // must be passed as ffi_arg or ffi_sarg.
                ffi_arg result_small;
                void *result = &result_small;

                // Specify the data type of each argument. Available types are defined
                // in <ffi/ffi.h>.
                union ArgType {
                    char charvalue;
                    short shortvalue;
                    int intvalue;
                    long longvalue;
                    long long longlongvalue;
                    unsigned char ucharvalue;
                    unsigned short ushortvalue;
                    unsigned int uintvalue;
                    unsigned long ulongvalue;
                    unsigned long long ulonglongvalue;
                    float floatvalue;
                    double doublevalue;
                    bool boolvalue;
                    void *ptrvalue;
                };
                ArgType extra_arg_values[func_traits<func_type>::argsize + extra_args_size];
                for (size_t i = func_traits<func_type>::argsize;
                     i < func_traits<func_type>::argsize + extra_args_size; ++i) {
                    PyObject *const nextArg = PyTuple_GetItem(extra_args, i - func_traits<func_type>::argsize);
                    const int subtype = getType(nextArg, arg_types[i]);
                    switch (arg_types[i]->type) {
                        case FFI_TYPE_SINT8:
                            extra_arg_values[i].charvalue = static_cast<char>(PyInt_AsLong(nextArg));
                            arg_values[i] = &extra_arg_values[i].charvalue;
                            break;
                        case FFI_TYPE_SINT16:
                            extra_arg_values[i].shortvalue = static_cast<short>(PyInt_AsLong(nextArg));
                            arg_values[i] = &extra_arg_values[i].shortvalue;
                            break;
                        case FFI_TYPE_SINT32:
                            extra_arg_values[i].intvalue = static_cast<int>(PyInt_AsLong(nextArg));
                            arg_values[i] = &extra_arg_values[i].intvalue;
                            break;
                        case FFI_TYPE_SINT64:
                            extra_arg_values[i].longvalue = PyLong_AsLong(nextArg);
                            arg_values[i] = &extra_arg_values[i].longvalue;
                            break;
                        case FFI_TYPE_UINT8:
                            extra_arg_values[i].boolvalue = (nextArg == Py_True);
                            arg_values[i] = &extra_arg_values[i].boolvalue;
                            break;
                        case FFI_TYPE_UINT16:
                            extra_arg_values[i].ushortvalue = static_cast<unsigned short>(PyInt_AsLong(nextArg));
                            arg_values[i] = &extra_arg_values[i].ushortvalue;
                            break;
                        case FFI_TYPE_UINT32:
                            extra_arg_values[i].uintvalue = static_cast<unsigned int>(PyInt_AsLong(nextArg));
                            arg_values[i] = &extra_arg_values[i].uintvalue;
                            break;
                        case FFI_TYPE_UINT64:
                            extra_arg_values[i].ulongvalue = PyLong_AsUnsignedLongLong(nextArg);
                            arg_values[i] = &extra_arg_values[i].ulonglongvalue;
                            break;
                        case FFI_TYPE_FLOAT:
                            extra_arg_values[i].floatvalue = PyFloat_AsDouble(nextArg);
                            arg_values[i] = &extra_arg_values[i].floatvalue;
                            break;
                        case FFI_TYPE_DOUBLE:
                            extra_arg_values[i].doublevalue = PyFloat_AsDouble(nextArg);
                            arg_values[i] = &extra_arg_values[i].doublevalue;
                            break;
                        case FFI_TYPE_POINTER:
                            if (STRING_TYPE == subtype) {
                                extra_arg_values[i].ptrvalue = (void*) PyString_AsString(nextArg);
                                arg_values[i] = &extra_arg_values[i].ptrvalue;
                            } else if (COBJ_TYPE == subtype) {
                                static const size_t offset = offset_of<Arbitrary *, PythonClassWrapper<Arbitrary> >
                                        (&PythonClassWrapper<Arbitrary>::_CObject);
                                auto **ptrvalue = (Arbitrary **) (((char *) nextArg) + offset);
                                extra_arg_values[i].ptrvalue = ptrvalue;
                            } else if (FUNC_TYPE == subtype) {
                                static constexpr bool with_ellipsis = true;

                                typedef PythonFunctionWrapper<func_type> wtype;
                                static const size_t offset = offset_of(&wtype::_function);
                                void **ptrvalue = (void **) (((char *) nextArg) + offset);
                                extra_arg_values[i].ptrvalue = *ptrvalue;
                            } else {
                                throw PyllarsException(PyExc_TypeError, "Unable to convert Python object to C Object");
                            }
                            arg_values[i] = &extra_arg_values[i].ptrvalue;
                            break;
                        default:
                            throw PyllarsException(PyExc_TypeError, "Python object cannot be converted to C object");
                    }
                }
                ffi_type *return_type = nullptr;
                if constexpr(std::is_void<ReturnType>::value) {
                    return_type = &ffi_type_void;
                } else {
                    return_type = FFIType<ReturnType>::type();//&ffi_type_sint;
                }
                // Prepare the ffi_cif structure.
                if ((status = ffi_prep_cif_var(&cif,
                                               FFI_DEFAULT_ABI,
                                               func_traits<func_type>::argsize,
                                               func_traits<func_type>::argsize + extra_args_size,
                                               return_type, arg_types)) != FFI_OK) {
                    throw PyllarsException(PyExc_TypeError, "FFI error calling variadic function");
                }
                // Invoke the function.
                ffi_call(&cif, FFI_FN(func), result, arg_values);
                if constexpr(!std::is_void<ReturnType>::value){
                    return *reinterpret_cast<ReturnType*>(result);
                }
            }
        }

        template<typename ReturnType, typename ...Args, typename... PyO>
        ReturnType
        __call_static_func(ReturnType (*func)(Args...), PyObject *extra_args, PyO *...pyargs) {
            if (!extra_args || PyTuple_Size(extra_args) == 0) {
                if constexpr (std::is_void<ReturnType>::value) {
                    func(toCArgument<Args>(*pyargs).value()...);
                } else {
                    return func(toCArgument<Args>(*pyargs).value()...);
                }
            } else {
                throw PyllarsException(PyExc_TypeError, "Too many arguments provided to function call");
            }
        }
    }

    /**
    * Used for regular methods:
    */
    template< typename func_type>
    PyObject *StaticCallSemantics<func_type>::
    call(func_type function, const char* const kwlist[], PyObject *args, PyObject *kwds) {
        typedef typename argGenerator<func_traits<func_type>::argsize>::type arg_generator_t;
        try {
            if constexpr (std::is_void<ReturnType>::value){
                invoke(function, kwlist, args, kwds, arg_generator_t());
                return Py_None;
            } else {
                ReturnType &&result = invoke(function, kwlist, args, kwds, arg_generator_t());
                const ssize_t array_size = ArraySize<ReturnType>::size;//sizeof(result) / sizeof(T_base);
                return toPyObject<ReturnType>(result, array_size);
            }
        } catch (PyllarsException &e) {
            e.raise();
            return nullptr;
        } catch(std::exception const & e) {
            PyllarsException::raise_internal_cpp(e.what());
            return nullptr;
        } catch(...) {
            PyllarsException::raise_internal_cpp();
            return nullptr;
        }
    }

    /**
     * call that converts python given arguments to make C call:
     **/
    template<typename func_type>
    template<int ...S>
    typename func_traits<func_type>::ReturnType
    StaticCallSemantics<func_type>::
    template invoke(func_type method, const char* const kwlist[], PyObject *args, PyObject *kwds, container<S...> s) {
        static char format[func_traits<func_type>::argsize + 1] = {0};
        if (func_traits<func_type>::argsize > 0)
            memset(format, 'O', (size_t) func_traits<func_type>::argsize);
        const ssize_t arg_count = kwds ? PyDict_Size(kwds) : 0 + args ? PyTuple_Size(args) : 0;
        const ssize_t kwd_count = kwds ? PyDict_Size(kwds) : 0;
        PyObject *extra_args = nullptr;
        PyObject *tuple = nullptr;

        if ((arg_count > func_traits<func_type>::argsize) && func_traits<func_type>::has_ellipsis) {
            auto const size = func_traits<func_type>::argsize - kwd_count;
            if (size > PyTuple_Size(args)){
                throw PyllarsException(PyExc_TypeError, "Not enough arguments to call");
            }
            tuple = PyTuple_GetSlice(args, 0, size);
            auto low = func_traits<func_type>::argsize - kwd_count;
            extra_args = PyTuple_GetSlice(args, low, arg_count);
        } else {
            tuple = args;
        }
        (void) s;
        PyObject *pyobjs[func_traits<func_type>::argsize];
        memset(pyobjs, 0, func_traits<func_type>::argsize*sizeof(PyObject*));
        (void) pyobjs;
        if (func_traits<func_type>::argsize > 0 && !PyArg_ParseTupleAndKeywords(tuple, kwds, format, (char **) kwlist, &pyobjs[S]...)) {
            throw PyllarsException(PyExc_TypeError, "Invalid arguments to method call");
        }

        if constexpr (std::is_void<ReturnType>::value) {
            __call_static_func(method, extra_args, pyobjs[S]...);
        } else {
            return __call_static_func(method, extra_args, pyobjs[S]...);

        }
    }

    template<const char* const kwlist[], typename func_type, func_type function>
    PyObject *
    StaticFunctionContainer<kwlist, func_type, function>::call(PyObject *cls, PyObject *args, PyObject *kwds) {
        (void) cls;
        if (!kwlist){
            PyErr_SetString(PyExc_SystemError, "Internal error -- unset (null) function invoked");
            return nullptr;
        }
        try {
            return StaticCallSemantics<func_type>::call(function, kwlist, args, kwds);
        } catch (PyllarsException &e) {
            e.raise();
            return nullptr;
        } catch(std::exception const & e) {
            PyllarsException::raise_internal_cpp(e.what());
            return nullptr;
        } catch(...) {
            PyllarsException::raise_internal_cpp();
            return nullptr;
        }
    }

}

#endif