text:
'use strict';

import { Event, filterEvent, mapEvent, anyEvent } from 'vs/base/common/event';
import { TPromise } from 'vs/base/common/winjs.base';
import { IWindowService, IWindowsService, INativeOpenDialogOptions, IEnterWorkspaceResult, IMessageBoxResult, IWindowConfiguration, IDevToolsOptions } from 'vs/platform/windows/common/windows';
import { IRecentlyOpened } from 'vs/platform/history/common/history';
import { ISerializableCommandAction } from 'vs/platform/actions/common/actions';
import { IWorkspaceFolderCreationData } from 'vs/platform/workspaces/common/workspaces';
import { ParsedArgs } from 'vs/platform/environment/common/environment';

export class WindowService implements IWindowService {

	readonly onDidChangeFocus: Event<boolean>;
	readonly onDidChangeMaximize: Event<boolean>;

	_serviceBrand: any;

	constructor(
		private windowId: number,
		private configuration: IWindowConfiguration,
		@IWindowsService private windowsService: IWindowsService
	) {
		const onThisWindowFocus = mapEvent(filterEvent(windowsService.onWindowFocus, id => id === windowId), _ => true);
		const onThisWindowBlur = mapEvent(filterEvent(windowsService.onWindowBlur, id => id === windowId), _ => false);
		const onThisWindowMaximize = mapEvent(filterEvent(windowsService.onWindowMaximize, id => id === windowId), _ => true);
		const onThisWindowUnmaximize = mapEvent(filterEvent(windowsService.onWindowUnmaximize, id => id === windowId), _ => false);
		this.onDidChangeFocus = anyEvent(onThisWindowFocus, onThisWindowBlur);
		this.onDidChangeMaximize = anyEvent(onThisWindowMaximize, onThisWindowUnmaximize);
	}

	getCurrentWindowId(): number {
		return this.windowId;
	}

	getConfiguration(): IWindowConfiguration {
		return this.configuration;
	}

	pickFileFolderAndOpen(options: INativeOpenDialogOptions): TPromise<void> {
		options.windowId = this.windowId;

		return this.windowsService.pickFileFolderAndOpen(options);
	}

	pickFileAndOpen(options: INativeOpenDialogOptions): TPromise<void> {
		options.windowId = this.windowId;

		return this.windowsService.pickFileAndOpen(options);
	}

	pickFolderAndOpen(options: INativeOpenDialogOptions): TPromise<void> {
		options.windowId = this.windowId;

		return this.windowsService.pickFolderAndOpen(options);
	}

	pickWorkspaceAndOpen(options: INativeOpenDialogOptions): TPromise<void> {
		options.windowId = this.windowId;

		return this.windowsService.pickWorkspaceAndOpen(options);
	}

	reloadWindow(args?: ParsedArgs): TPromise<void> {
		return this.windowsService.reloadWindow(this.windowId, args);
	}

	openDevTools(options?: IDevToolsOptions): TPromise<void> {
		return this.windowsService.openDevTools(this.windowId, options);
	}

	toggleDevTools(): TPromise<void> {
		return this.windowsService.toggleDevTools(this.windowId);
	}

	closeWorkspace(): TPromise<void> {
		return this.windowsService.closeWorkspace(this.windowId);
	}

	createAndEnterWorkspace(folders?: IWorkspaceFolderCreationData[], path?: string): TPromise<IEnterWorkspaceResult> {
		return this.windowsService.createAndEnterWorkspace(this.windowId, folders, path);
	}

	saveAndEnterWorkspace(path: string): TPromise<IEnterWorkspaceResult> {
		return this.windowsService.saveAndEnterWorkspace(this.windowId, path);
	}

	openWindow(paths: string[], options?: { forceNewWindow?: boolean, forceReuseWindow?: boolean, forceOpenWorkspaceAsFile?: boolean; }): TPromise<void> {
		return this.windowsService.openWindow(this.windowId, paths, options);
	}

	closeWindow(): TPromise<void> {
		return this.windowsService.closeWindow(this.windowId);
	}

	toggleFullScreen(): TPromise<void> {
		return this.windowsService.toggleFullScreen(this.windowId);
	}

	setRepresentedFilename(fileName: string): TPromise<void> {
		return this.windowsService.setRepresentedFilename(this.windowId, fileName);
	}

	getRecentlyOpened(): TPromise<IRecentlyOpened> {
		return this.windowsService.getRecentlyOpened(this.windowId);
	}

	focusWindow(): TPromise<void> {
		return this.windowsService.focusWindow(this.windowId);
	}

	isFocused(): TPromise<boolean> {
		return this.windowsService.isFocused(this.windowId);
	}

	isMaximized(): TPromise<boolean> {
		return this.windowsService.isMaximized(this.windowId);
	}

	maximizeWindow(): TPromise<void> {
		return this.windowsService.maximizeWindow(this.windowId);
	}

	unmaximizeWindow(): TPromise<void> {
		return this.windowsService.unmaximizeWindow(this.windowId);
	}

	minimizeWindow(): TPromise<void> {
		return this.windowsService.minimizeWindow(this.windowId);
	}

	onWindowTitleDoubleClick(): TPromise<void> {
		return this.windowsService.onWindowTitleDoubleClick(this.windowId);
	}

	setDocumentEdited(flag: boolean): TPromise<void> {
		return this.windowsService.setDocumentEdited(this.windowId, flag);
	}

	show(): TPromise<void> {
		return this.windowsService.showWindow(this.windowId);
	}

	showMessageBox(options: Electron.MessageBoxOptions): TPromise<IMessageBoxResult> {
		return this.windowsService.showMessageBox(this.windowId, options);
	}

	showSaveDialog(options: Electron.SaveDialogOptions): TPromise<string> {
		return this.windowsService.showSaveDialog(this.windowId, options);
	}

	showOpenDialog(options: Electron.OpenDialogOptions): TPromise<string[]> {
		return this.windowsService.showOpenDialog(this.windowId, options);
	}

	updateTouchBar(items: ISerializableCommandAction[][]): TPromise<void> {
		return this.windowsService.updateTouchBar(this.windowId, items);
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using MicroStuff.Models;
using Newtonsoft.Json;

namespace MicroStuff.Data
{
    public interface ISessions
    {
        Task<IList<Session>> Get();
    }

    public class Sessions : ISessions
    {
        private readonly HttpClient _client;
        private readonly string _sessionsUri;

        public Sessions()
        {
            _client = new HttpClient();

            _sessionsUri = "http://sessions:5000/sessions/";
        }

        public async Task<IList<Session>> Get()
        {
            var json = await _client.GetStringAsync(_sessionsUri);
            return JsonConvert.DeserializeObject<List<Session>>(json);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * HOOKS.PHP
 *
 * Hooks provide the ability, as the name implies, to hook into various parts of
 * the view rendering process and insert customizations. The contents of these
 * functions are run at the appropriate time *EVERY* time a view is rendered, i.e.
 * the content of the hooks is not by default view-specific but rather will be
 * applied to all views. (However, there is nothing that prevents developers from
 * inserting conditional logic inside a hook that then causes view-specific
 * them to exhibit view-specific behavior).
 *
 * As an example, consider a hook that adds the amount of time Balance took to render
 * the page as an inline HTML comment at the bottom of each page after it has been sent:
 *
 * function hook_after_send() {
 *     $timeStart = $GLOBALS['balance_request_start'];
 *     $timeNow   = microtime(true);
 *     $elapsed   = $timeNow - $timeStart;
 *     echo "<!-- page rendered in {$elapsed} seconds -->";
 * }
 *
 *
 * Take a look at the docblock descriptions of each hook to get a sense of where
 * in the view rendering process the hook is invoked.
 *
 * @author ahart
 */

/**
 * hook_before_header
 *
 * This hook is executed before the contents of the header file are processed.
 */
function hook_before_header() {}

/**
 * hook_before_view
 *
 * This hook is executed before the contents of the main view are processed.
 */
function hook_before_view() {
	App::Get()->response->addStylesheet(MODULE_STATIC.'/css/profile.css');
}

/**
 * hook_before_footer
 *
 * This hook is executed before the contents of the footer are processed
 */
function hook_before_footer() {}

/**
 * hook_before_send
 *
 * This hook is after all of the view components (header, view, footer) have been
 * processed but before the processed results are sent out across the wire to the
 * browser. HTTP headers have not yet been sent to the browser.
 */
function hook_before_send() {}

/**
 * hook_after_send
 *
 * This hook is after all of the view components (header, view, footer) have been
 * processed and sent out across the wire to the browser. It can be used for logging
 * or analytics purposes, or to append a common trailer to all content.
 */
function hook_after_send() {
	$timeStart = $GLOBALS['balance_request_start'];
	$timeEnd   = microtime(true);
	$elapsed   = $timeEnd - $timeStart;

	echo "\r\n<!-- page rendered in {$elapsed} seconds -->";
}


text:
package api

import (
	"bytes"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"github.com/chromium/hstspreload"
	"github.com/chromium/hstspreload.org/database"
	"github.com/chromium/hstspreload/chromium/preloadlist"
)

var emptyIssues = hstspreload.Issues{}

var issuesWithWarnings = hstspreload.Issues{
	Warnings: []hstspreload.Issue{{Code: "code", Summary: "warning", Message: "message"}},
}

var issuesWithErrors = hstspreload.Issues{
	Errors: []hstspreload.Issue{
		{Code: "code1", Summary: "warning1", Message: "message1"},
		{Code: "code2", Summary: "warning2", Message: "message2"},
	},
	Warnings: []hstspreload.Issue{{Code: "code", Summary: "warning", Message: "message"}},
}

var issuesRemovableProtected = hstspreload.Issues{
	Errors: []hstspreload.Issue{
		{Code: "server.removable.protected"},
	},
}

var issuesRemovableSubdomain = hstspreload.Issues{
	Errors: []hstspreload.Issue{
		{Code: "server.removable.subdomain"},
	},
}

var issuesRemovablePreloadedTld = hstspreload.Issues{
	Errors: []hstspreload.Issue{
		{Code: "server.removable.preloaded_tld"},
	},
}

var issuesRemoveProtected = hstspreload.Issues{
	Errors: []hstspreload.Issue{
		{Code: "server.remove.protected"},
	},
}

func mockAPI(cacheDuration time.Duration) (api API, mc *database.MockController, h *mockHstspreload, c *mockPreloadlist) {
	db, mc := database.NewMock()
	h = &mockHstspreload{}
	c = &mockPreloadlist{}
	api = API{
		database:      db,
		hstspreload:   h,
		preloadlist:   c,
		bulkPreloaded: make(DomainSet),
		cache:         cacheWithDuration(cacheDuration),
	}
	return api, mc, h, c
}

func TestCheckConnection(t *testing.T) {
	api, mc, _, _ := mockAPI(0 * time.Second)

	if err := api.CheckConnection(); err != nil {
		t.Errorf("%s", err)
	}

	mc.FailCalls = true
	if err := api.CheckConnection(); err == nil {
		t.Error("connection should fail")
	}
}

// Any non-zero values are considered wanted.
type wantBody struct {
	text      string
	state     *database.DomainState
	bulkState *DomainStateWithBulk
	issues    *hstspreload.Issues
}

type MockData struct {
	preloadableResponses map[string]hstspreload.Issues
	removableResponses   map[string]hstspreload.Issues
	preloadlist          preloadlist.PreloadList
}

const (
	failDatabase = 1 << iota
	failChromiumpreload
	failNone = 0
)

type apiTestCase struct {
	description     string
	mockData        MockData
	failState       int
	handlerFunc     http.HandlerFunc
	method          string
	url             string
	wantCode        int
	wantContentType string
	wantBody        wantBody
}

func TestAPI(t *testing.T) {
	api, mc, h, c := mockAPI(0 * time.Second)

	api.bulkPreloaded["removal-preloaded-bulk-eligible.test"] = true
	api.bulkPreloaded["removal-not-preloaded-bulk-eligible.test"] = true
	api.bulkPreloaded["removal-preloaded-bulk-ineligible.test"] = true

	pr1 := map[string]hstspreload.Issues{
		"garron.net":                      emptyIssues,
		"badssl.com":                      issuesWithWarnings,
		"example.com":                     issuesWithErrors,
		"removal-pending-eligible.test":   emptyIssues,
		"removal-pending-ineligible.test": emptyIssues,
	}
	rr1 := map[string]hstspreload.Issues{
		"removal-preloaded-bulk-eligible.test":     emptyIssues,
		"removal-preloaded-not-bulk-eligible.test": emptyIssues,
		"removal-preloaded-bulk-ineligible.test":   issuesWithErrors,
		"removal-pending-eligible.test":            emptyIssues,
		"removal-pending-ineligible.test":          issuesWithErrors,
	}

	pl1 := preloadlist.PreloadList{Entries: []preloadlist.Entry{
		{Name: "garron.net", Mode: preloadlist.ForceHTTPS, IncludeSubDomains: true},
		{Name: "chromium.org", Mode: preloadlist.ForceHTTPS, IncludeSubDomains: false},
		{Name: "removal-preloaded-bulk-eligible.test", Mode: preloadlist.ForceHTTPS, IncludeSubDomains: true},
		{Name: "removal-preloaded-not-bulk-eligible.test", Mode: preloadlist.ForceHTTPS, IncludeSubDomains: true},
		{Name: "removal-preloaded-bulk-ineligible.test", Mode: preloadlist.ForceHTTPS, IncludeSubDomains: true},
		{Name: "godoc.og", Mode: "", IncludeSubDomains: true},
		{Name: "dev", Mode: preloadlist.ForceHTTPS, IncludeSubDomains: true},
	}}

	pl2 := preloadlist.PreloadList{Entries: []preloadlist.Entry{
		{Name: "chromium.org", Mode: preloadlist.ForceHTTPS, IncludeSubDomains: false},
		{Name: "godoc.og", Mode: "", IncludeSubDomains: true},
	}}

	data1 := MockData{pr1, rr1, pl1}
	data2 := MockData{pr1, rr1, pl2}

	jsonContentType := "application/json; charset=utf-8"
	textContentType := "text/plain; charset=utf-8" // Errors

	apiTestSequence := []apiTestCase{
		// wrong HTTP method
		{"submit wrong method", data1, failNone, api.Preloadable, "POST", "?domain=garron.net",
			405, textContentType, wantBody{text: "Wrong method. Requires GET.\n"}},
		{"submit wrong method", data1, failNone, api.Removable, "POST", "?domain=garron.net",
			405, textContentType, wantBody{text: "Wrong method. Requires GET.\n"}},
		{"status wrong method", data1, failNone, api.Status, "POST", "?domain=garron.net",
			405, textContentType, wantBody{text: "Wrong method. Requires GET.\n"}},
		{"pending wrong method", data1, failNone, api.Pending, "POST", "",
			405, textContentType, wantBody{text: "Wrong method. Requires GET.\n"}},
		{"submit wrong method", data1, failNone, api.Submit, "GET", "?domain=garron.net",
			405, textContentType, wantBody{text: "Wrong method. Requires POST.\n"}},

		// misc. issues
		{"status wrong method", data1, failNone, api.Status, "GET", "",
			400, textContentType, wantBody{text: ""}},
		{"status wrong method", data1, failNone, api.Status, "GET", "?domain=",
			400, textContentType, wantBody{text: ""}},

		// preloadable and removable
		{"preloadable good", data1, failNone, api.Preloadable, "GET", "?domain=garron.net",
			200, jsonContentType, wantBody{issues: &emptyIssues}},
		{"preloadable warning", data1, failNone, api.Preloadable, "GET", "?domain=badssl.com",
			200, jsonContentType, wantBody{issues: &issuesWithWarnings}},
		{"preloadable error", data1, failNone, api.Preloadable, "GET", "?domain=example.com",
			200, jsonContentType, wantBody{issues: &issuesWithErrors}},
		// initial
		{"garron.net initial", data1, failNone, api.Status, "GET", "?domain=garron.net",
			200, jsonContentType, wantBody{state: &database.DomainState{
				Name: "garron.net", Status: database.StatusUnknown}}},
		{"example.com initial", data1, failNone, api.Status, "GET", "?domain=example.com",
			200, jsonContentType, wantBody{state: &database.DomainState{
				Name: "example.com", Status: database.StatusUnknown}}},
		{"pending 1", data1, failNone, api.Pending, "GET", "",
			200, jsonContentType, wantBody{text: "[\n]\n"}},
		{"bulk status", data1, failNone, api.Status, "GET", "?domain=removal-not-preloaded-bulk-eligible.test",
			200, jsonContentType, wantBody{bulkState: &DomainStateWithBulk{
				DomainState: &database.DomainState{Name: "removal-not-preloaded-bulk-eligible.test", Status: database.StatusUnknown},
				Bulk:        true,
			}}},

		// initial with database failure
		{"pending failure", data1, failDatabase, api.Pending, "GET", "",
			500, textContentType, wantBody{text: "Internal error: could not retrieve list for status \"pending\". (forced failure)\n\n"}},
		{"status failure", data1, failDatabase, api.Status, "GET", "?domain=garron.net",
			500, textContentType, wantBody{text: "Internal error: could not retrieve status. (forced failure)\n\n"}},

		// submit
		{"bad submit", data1, failNone, api.Submit, "POST", "?domain=example.com",
			200, jsonContentType, wantBody{issues: &issuesWithErrors}},
		{"submit database failure", data1, failDatabase, api.Submit, "POST", "?domain=garron.net",
			500, textContentType, wantBody{text: "Internal error: could not get current domain status. (forced failure)\n\n"}},
		{"good submit", data1, failNone, api.Submit, "POST", "?domain=garron.net",
			200, jsonContentType, wantBody{issues: &emptyIssues}},

		// pending
		{"pending 2", data1, failNone, api.Pending, "GET", "",
			200, jsonContentType, wantBody{text: "[\n    { \"name\": \"garron.net\", \"policy\": \"bulk-1-year\", \"mode\": \"force-https\", \"include_subdomains\": true }\n]\n"}},
		{"submit while pending", data1, failNone, api.Submit, "POST", "?domain=garron.net",
			200, jsonContentType, wantBody{issues: &hstspreload.Issues{
				Warnings: []hstspreload.Issue{{Code: "server.preload.already_pending"}},
			}}},

		// update
		{"garron.net pending", data1, failNone, api.Status, "GET", "?domain=garron.net",
			200, jsonContentType, wantBody{state: &database.DomainState{
				Name: "garron.net", Status: database.StatusPending}}},
		{"update chromiumpreload failure", data1, failChromiumpreload, api.Update, "GET", "",
			500, textContentType, wantBody{text: "Internal error: could not retrieve latest preload list. (forced failure)\n\n"}},
		{"update database failure", data1, failDatabase, api.Update, "GET", "",
			500, textContentType, wantBody{text: "Internal error: could not retrieve domain names previously marked as preloaded. (forced failure)\n\n"}},
		{"update success", data1, failNone, api.Update, "GET", "",
			200, textContentType, wantBody{text: "The preload list has 7 entries.\n- # of preloaded HSTS entries: 6\n- # to be added in this update: 6\n- # to be removed this update: 0\n- # to be self-rejected this update: 0\nSuccess. 6 domain states updated.\n"}},
		{"pending 3", data1, failNone, api.Pending, "GET", "",
			200, jsonContentType, wantBody{text: "[\n]\n"}},

		// create removable pending
		{"create removable pending eligible", data1, failNone, api.Submit, "POST", "?domain=removal-pending-eligible.test",
			200, jsonContentType, wantBody{issues: &emptyIssues}},
		{"create removable pending ineligible", data1, failNone, api.Submit, "POST", "?domain=removal-pending-ineligible.test",
			200, jsonContentType, wantBody{issues: &emptyIssues}},

		// removable
		{"removable preloaded-bulk-eligible", data1, failNone, api.Removable, "GET", "?domain=removal-preloaded-bulk-eligible.test",
			200, jsonContentType, wantBody{issues: &emptyIssues}},
		{"removable subdomain", data1, failNone, api.Removable, "GET", "?domain=subdomain.removal-preloaded-bulk-eligible.test", 200, jsonContentType, wantBody{issues: &issuesRemovableSubdomain}},
		{"removable subsubdomain", data1, failNone, api.Removable, "GET", "?domain=sub.subdomain.removal-preloaded-bulk-eligible.test", 200, jsonContentType, wantBody{issues: &issuesRemovableSubdomain}},
		{"removable subdomain-of-preloaded-tld", data1, failNone, api.Removable, "GET", "?domain=subdomain.dev", 200, jsonContentType, wantBody{issues: &issuesRemovablePreloadedTld}},
		{"removable preloaded-not-bulk-eligible", data1, failNone, api.Removable, "GET", "?domain=removal-preloaded-not-bulk-eligible.test",
			200, jsonContentType, wantBody{issues: &issuesRemovableProtected}},
		{"removable preloaded-bulk-ineligible", data1, failNone, api.Removable, "GET", "?domain=removal-preloaded-bulk-ineligible.test",
			200, jsonContentType, wantBody{issues: &issuesWithErrors}},
		{"removable pending-eligible", data1, failNone, api.Removable, "GET", "?domain=removal-pending-eligible.test",
			200, jsonContentType, wantBody{issues: &emptyIssues}},
		{"removable pending-ineligible", data1, failNone, api.Removable, "GET", "?domain=removal-pending-ineligible.test",
			200, jsonContentType, wantBody{issues: &issuesWithErrors}},

		// remove
		{"remove preloaded-bulk-eligible", data1, failNone, api.Remove, "POST", "?domain=removal-preloaded-bulk-eligible.test",
			200, jsonContentType, wantBody{issues: &emptyIssues}},
		{"remove preloaded-not-bulk-eligible", data1, failNone, api.Remove, "POST", "?domain=removal-preloaded-not-bulk-eligible.test",
			200, jsonContentType, wantBody{issues: &issuesRemoveProtected}},
		{"remove preloaded-bulk-ineligible", data1, failNone, api.Remove, "POST", "?domain=removal-preloaded-bulk-ineligible.test",
			200, jsonContentType, wantBody{issues: &issuesWithErrors}},
		{"remove pending-eligible", data1, failNone, api.Remove, "POST", "?domain=removal-pending-eligible.test",
			200, jsonContentType, wantBody{issues: &emptyIssues}},
		{"remove pending-ineligible", data1, failNone, api.Remove, "POST", "?domain=removal-pending-ineligible.test",
			200, jsonContentType, wantBody{issues: &issuesWithErrors}},

		// Check removals
		{"remove preloaded-bulk-eligible", data1, failNone, api.Status, "GET", "?domain=removal-preloaded-bulk-eligible.test",
			200, jsonContentType, wantBody{state: &database.DomainState{
				Name: "removal-preloaded-bulk-eligible.test", Status: database.StatusPendingRemoval}}},
		{"remove preloaded-not-bulk-eligible", data1, failNone, api.Status, "GET", "?domain=removal-preloaded-not-bulk-eligible.test",
			200, jsonContentType, wantBody{state: &database.DomainState{
				Name: "removal-preloaded-not-bulk-eligible.test", Status: database.StatusPreloaded}}},
		{"remove preloaded-bulk-ineligible", data1, failNone, api.Status, "GET", "?domain=removal-preloaded-bulk-ineligible.test",
			200, jsonContentType, wantBody{state: &database.DomainState{
				Name: "removal-preloaded-bulk-ineligible.test", Status: database.StatusPreloaded}}},
		{"remove pending-eligible", data1, failNone, api.Status, "GET", "?domain=removal-pending-eligible.test",
			200, jsonContentType, wantBody{state: &database.DomainState{
				Name: "removal-pending-eligible.test", Status: database.StatusPendingRemoval}}},
		{"remove pending-ineligible", data1, failNone, api.Status, "GET", "?domain=removal-pending-ineligible.test",
			200, jsonContentType, wantBody{state: &database.DomainState{
				Name: "removal-pending-ineligible.test", Status: database.StatusPending}}},

		// after update
		{"submit after preloaded", data1, failNone, api.Submit, "POST", "?domain=garron.net",
			200, jsonContentType, wantBody{issues: &hstspreload.Issues{
				Errors: []hstspreload.Issue{{Code: "server.preload.already_preloaded"}},
			}}},
		{"example.com after update", data1, failNone, api.Status, "GET", "?domain=example.com",
			200, jsonContentType, wantBody{state: &database.DomainState{
				Name: "example.com", Status: database.StatusUnknown}}},
		{"garron.net after update", data1, failNone, api.Status, "GET", "?domain=garron.net",
			200, jsonContentType, wantBody{state: &database.DomainState{
				Name: "garron.net", Status: database.StatusPreloaded}}},
		{"subdomains of garron.net after update", data1, failNone, api.Status, "GET", "?domain=www.sub.garron.net",
			200, jsonContentType, wantBody{state: &database.DomainState{
				Name: "www.sub.garron.net", Status: database.StatusPreloaded}}},
		{"chromium.org after update", data1, failNone, api.Status, "GET", "?domain=chromium.org",
			200, jsonContentType, wantBody{state: &database.DomainState{
				Name: "chromium.org", Status: database.StatusPreloaded}}},
		{"godoc.org after update", data1, failNone, api.Status, "GET", "?domain=godoc.org",
			200, jsonContentType, wantBody{state: &database.DomainState{
				Name: "godoc.org", Status: database.StatusUnknown}}},

		// subdomain status checks
		{"subdomain status parent", data1, failNone, api.Status, "GET", "?domain=garron.net", 200, jsonContentType,
			wantBody{
				bulkState: &DomainStateWithBulk{
					DomainState: &database.DomainState{
						Name:   "garron.net",
						Status: database.StatusPreloaded,
					},
					PreloadedDomain: "garron.net",
				},
			}},
		{"subdomain status child", data1, failNone, api.Status, "GET", "?domain=sub.garron.net", 200, jsonContentType,
			wantBody{
				bulkState: &DomainStateWithBulk{
					DomainState: &database.DomainState{
						Name:   "sub.garron.net",
						Status: database.StatusPreloaded,
					},
					PreloadedDomain: "garron.net",
				},
			}},

		// update with removal
		{"update with removal", data2, failNone, api.Update, "GET", "",
			200, textContentType, wantBody{text: "The preload list has 2 entries.\n- # of preloaded HSTS entries: 1\n- # to be added in this update: 0\n- # to be removed this update: 4\n- # to be self-rejected this update: 2\nSuccess. 6 domain states updated.\n"}},
		{"garron.net after update with removal", data2, failNone, api.Status, "GET", "?domain=garron.net",
			200, jsonContentType, wantBody{state: &database.DomainState{
				Name: "garron.net", Status: database.StatusRemoved}}},
		{"chromium.org after update with removal", data2, failNone, api.Status, "GET", "?domain=chromium.org",
			200, jsonContentType, wantBody{state: &database.DomainState{
				Name: "chromium.org", Status: database.StatusPreloaded}}},
	}

	for _, tt := range apiTestSequence {
		h.preloadableResponses = tt.mockData.preloadableResponses
		h.removableResponses = tt.mockData.removableResponses
		c.list = tt.mockData.preloadlist

		mc.FailCalls = (tt.failState & failDatabase) != 0
		c.failCalls = (tt.failState & failChromiumpreload) != 0

		w := httptest.NewRecorder()
		w.Body = &bytes.Buffer{}

		r, err := http.NewRequest(tt.method, tt.url, nil)
		if err != nil {
			t.Fatalf("[%s] %s", tt.description, err)
		}

		tt.handlerFunc(w, r)

		contentType := w.HeaderMap.Get(http.CanonicalHeaderKey("Content-Type"))
		if contentType != tt.wantContentType {
			t.Errorf("[%s] Wrong content type: %s", tt.description, contentType)
		}

		if w.Code != tt.wantCode {
			t.Errorf("[%s] Status code does not match wanted: %d", tt.description, w.Code)
		}

		if tt.wantBody.text != "" {
			text := w.Body.String()
			if text != tt.wantBody.text {
				t.Errorf("[%s] Body text does not match wanted: %#v", tt.description, text)
			}
		}

		if tt.wantBody.state != nil {
			var s database.DomainState
			if err := json.Unmarshal(w.Body.Bytes(), &s); err != nil {
				t.Fatalf("[%s] %s", tt.description, err)
			}
			if !s.MatchesWanted(*tt.wantBody.state) {
				t.Errorf("[%s] Domain state does not match wanted: %#v", tt.description, s)
			}
		}

		if tt.wantBody.bulkState != nil {
			var s DomainStateWithBulk
			if err := json.Unmarshal(w.Body.Bytes(), &s); err != nil {
				t.Fatalf("[%s] %s", tt.description, err)
			}
			if !s.MatchesWanted(*tt.wantBody.bulkState.DomainState) {
				t.Errorf("[%s] Domain state does not match wanted: %#v", tt.description, s.DomainState)
			}
			if s.Bulk != tt.wantBody.bulkState.Bulk {
				t.Errorf("[%s] Domain state bulk does not match wanted: %#v", tt.description, s.Bulk)
			}
			if tt.wantBody.bulkState.PreloadedDomain != "" && s.PreloadedDomain != tt.wantBody.bulkState.PreloadedDomain {
				t.Errorf("[%s] Domain state preloaded domain does not match wanted: %#v", tt.description, s.PreloadedDomain)
			}
		}

		if tt.wantBody.issues != nil {
			var iss hstspreload.Issues
			if err := json.Unmarshal(w.Body.Bytes(), &iss); err != nil {
				t.Fatalf("[%s] %s", tt.description, err)
			}
			if !iss.Match(*tt.wantBody.issues) {
				t.Errorf("[%s] Issues do not match wanted: %#v", tt.description, iss)
			}
		}
	}
}

func TestCORS(t *testing.T) {
	api, _, _, _ := mockAPI(0 * time.Second)

	cases := []struct {
		handlerName  string
		handlerFunc  http.HandlerFunc
		method       string
		clientOrigin string
		wantCORS     string
	}{
		// Handlers that should allow CORS.
		{"Preloadable", api.Preloadable, http.MethodGet, "", ""},
		{"Preloadable", api.Preloadable, http.MethodGet, "http://example.com", "null"},
		{"Preloadable", api.Preloadable, http.MethodGet, "http://example.com:80", "null"},
		{"Preloadable", api.Preloadable, http.MethodGet, "http://example.com:443", "null"},
		{"Preloadable", api.Preloadable, http.MethodGet, "https://example.com", "null"},
		{"Preloadable", api.Preloadable, http.MethodGet, "https://example.com:80", "null"},
		{"Preloadable", api.Preloadable, http.MethodGet, "https://example.com:443", "null"},
		{"Preloadable", api.Preloadable, http.MethodGet, "http://localhost", "*"},
		{"Preloadable", api.Preloadable, http.MethodGet, "http://localhost:8080", "*"},
		{"Preloadable", api.Preloadable, http.MethodGet, "http://mozilla.github.io", "null"},
		{"Preloadable", api.Preloadable, http.MethodGet, "http://mozilla.github.io:80", "null"},
		{"Preloadable", api.Preloadable, http.MethodGet, "http://mozilla.github.io:443", "null"},
		{"Preloadable", api.Preloadable, http.MethodGet, "https://mozilla.github.io", "*"},
		{"Preloadable", api.Preloadable, http.MethodGet, "https://mozilla.github.io:80", "*"},
		{"Preloadable", api.Preloadable, http.MethodGet, "https://mozilla.github.io:443", "*"},
		{"Preloadable", api.Preloadable, http.MethodOptions, "http://localhost", "*"},
		{"Preloadable", api.Preloadable, http.MethodOptions, "http://example.com", "null"},
		{"Preloadable", api.Preloadable, http.MethodOptions, "https://example.com", "null"},
		{"Preloadable", api.Preloadable, http.MethodOptions, "http://mozilla.github.io", "null"},
		{"Preloadable", api.Preloadable, http.MethodOptions, "https://mozilla.github.io", "*"},
		{"Preloadable", api.Preloadable, http.MethodPost, "https://mozilla.github.io", "*"},
		{"Status", api.Status, http.MethodGet, "http://localhost:8080", "*"},
		{"Status", api.Status, http.MethodGet, "http://example.com", "null"},
		{"Status", api.Status, http.MethodGet, "https://example.com", "null"},
		{"Status", api.Status, http.MethodGet, "http://mozilla.github.io", "null"},
		{"Status", api.Status, http.MethodGet, "https://mozilla.github.io", "*"},
		{"Status", api.Status, http.MethodOptions, "http://localhost:8080", "*"},
		{"Status", api.Status, http.MethodOptions, "http://example.com", "null"},
		{"Status", api.Status, http.MethodOptions, "https://example.com", "null"},
		{"Status", api.Status, http.MethodOptions, "http://mozilla.github.io", "null"},
		{"Status", api.Status, http.MethodOptions, "https://mozilla.github.io", "*"},
		// Handlers that should not allow CORS.
		{"Removable", api.Removable, http.MethodGet, "http://localhost:8080", ""},
		{"Removable", api.Removable, http.MethodGet, "http://example.com", ""},
		{"Removable", api.Removable, http.MethodGet, "https://example.com", ""},
		{"Removable", api.Removable, http.MethodGet, "http://mozilla.github.io", ""},
		{"Removable", api.Removable, http.MethodGet, "https://mozilla.github.io", ""},
		{"Removable", api.Removable, http.MethodOptions, "https://mozilla.github.io", ""},
		{"Submit", api.Submit, http.MethodGet, "https://mozilla.github.io", ""},
		{"Submit", api.Submit, http.MethodOptions, "https://mozilla.github.io", ""},
		{"Pending", api.Pending, http.MethodGet, "https://mozilla.github.io", ""},
		{"Pending", api.Pending, http.MethodOptions, "https://mozilla.github.io", ""},
		{"Update", api.Update, http.MethodGet, "https://mozilla.github.io", ""},
		{"Update", api.Update, http.MethodOptions, "https://mozilla.github.io", ""},
	}

	for _, tt := range cases {
		r, err := http.NewRequest(tt.method, "", nil)
		if err != nil {
			t.Fatalf("%s", err)
		}
		r.Header.Set("Origin", tt.clientOrigin)

		w := httptest.NewRecorder()
		w.Body = &bytes.Buffer{}

		tt.handlerFunc(w, r)

		key := http.CanonicalHeaderKey(corsOriginHeader)
		actual := w.Header().Get(key)
		if tt.wantCORS != actual {
			t.Errorf(
				"[%s][%s][%s] CORS header `%s` does not match expected value `%s`.",
				tt.handlerName,
				tt.method,
				tt.clientOrigin,
				actual,
				tt.wantCORS,
			)
		}
	}
}


text:
namespace System.Net.Test.Common
{
    internal class HttpTestServers
    {
        public readonly static string Host = TestSettings.Http.Host;
        public readonly static string SecureHost = TestSettings.Http.SecureHost;
        public readonly static string Http2Host = TestSettings.Http.Http2Host;

        public const string SSLv2RemoteServer = "https://www.ssllabs.com:10200/";
        public const string SSLv3RemoteServer = "https://www.ssllabs.com:10300/";
        public const string TLSv10RemoteServer = "https://www.ssllabs.com:10301/";
        public const string TLSv11RemoteServer = "https://www.ssllabs.com:10302/";
        public const string TLSv12RemoteServer = "https://www.ssllabs.com:10303/";

        public const string ExpiredCertRemoteServer = "https://expired.badssl.com/";
        public const string WrongHostNameCertRemoteServer = "https://wrong.host.badssl.com/";
        public const string SelfSignedCertRemoteServer = "https://self-signed.badssl.com/";
        public const string RevokedCertRemoteServer = "https://revoked.grc.com/";

        private const string HttpScheme = "http";
        private const string HttpsScheme = "https";

        private const string EchoHandler = "Echo.ashx";
        private const string EmptyContentHandler = "EmptyContent.ashx";
        private const string StatusCodeHandler = "StatusCode.ashx";
        private const string RedirectHandler = "Redirect.ashx";
        private const string VerifyUploadHandler = "VerifyUpload.ashx";
        private const string DeflateHandler = "Deflate.ashx";
        private const string GZipHandler = "GZip.ashx";

        public readonly static Uri RemoteEchoServer = new Uri("http://" + Host + "/" + EchoHandler);
        public readonly static Uri SecureRemoteEchoServer = new Uri("https://" + SecureHost + "/" + EchoHandler);

        public readonly static Uri RemoteVerifyUploadServer = new Uri("http://" + Host + "/" + VerifyUploadHandler);
        public readonly static Uri SecureRemoteVerifyUploadServer = new Uri("https://" + SecureHost + "/" + VerifyUploadHandler);

        public readonly static Uri RemoteEmptyContentServer = new Uri("http://" + Host + "/" + EmptyContentHandler);
        public readonly static Uri RemoteDeflateServer = new Uri("http://" + Host + "/" + DeflateHandler);
        public readonly static Uri RemoteGZipServer = new Uri("http://" + Host + "/" + GZipHandler);

        public readonly static object[][] EchoServers = { new object[] { RemoteEchoServer }, new object[] { SecureRemoteEchoServer } };
        public readonly static object[][] VerifyUploadServers = { new object[] { RemoteVerifyUploadServer }, new object[] { SecureRemoteVerifyUploadServer } };
        public readonly static object[][] CompressedServers = { new object[] { RemoteDeflateServer }, new object[] { RemoteGZipServer } };
        public readonly static object[][] Http2Servers = { new object[] { new Uri("https://" + Http2Host) } };

        public static Uri NegotiateAuthUriForDefaultCreds(bool secure)
        {
            return new Uri(
                string.Format(
                    "{0}://{1}/{2}?auth=negotiate",
                    secure ? HttpsScheme : HttpScheme,
                    Host,
                    EchoHandler));
        }

        public static Uri BasicAuthUriForCreds(bool secure, string userName, string password)
        {
            return new Uri(
                string.Format(
                    "{0}://{1}/{2}?auth=basic&user={3}&password={4}",
                    secure ? HttpsScheme : HttpScheme,
                    Host,
                    EchoHandler,
                    userName,
                    password));
        }

        public static Uri StatusCodeUri(bool secure, int statusCode)
        {
            return new Uri(
                string.Format(
                    "{0}://{1}/{2}?statuscode={3}",
                    secure ? HttpsScheme : HttpScheme,
                    Host,
                    StatusCodeHandler,
                    statusCode));
        }

        public static Uri StatusCodeUri(bool secure, int statusCode, string statusDescription)
        {
            return new Uri(
                string.Format(
                    "{0}://{1}/{2}?statuscode={3}&statusDescription={4}",
                    secure ? HttpsScheme : HttpScheme,
                    Host,
                    StatusCodeHandler,
                    statusCode,
                    statusDescription));
        }

        public static Uri RedirectUriForDestinationUri(bool secure, int statusCode, Uri destinationUri, int hops, bool relative = false)
        {
            string uriString;
            string destination = Uri.EscapeDataString(relative ? destinationUri.PathAndQuery : destinationUri.AbsoluteUri);

            if (hops > 1)
            {
                uriString = string.Format("{0}://{1}/{2}?statuscode={3}&uri={4}&hops={5}",
                    secure ? HttpsScheme : HttpScheme,
                    Host,
                    RedirectHandler,
                    statusCode,
                    destination,
                    hops);
            }
            else
            {
                uriString = string.Format("{0}://{1}/{2}?statuscode={3}&uri={4}",
                    secure ? HttpsScheme : HttpScheme,
                    Host,
                    RedirectHandler,
                    statusCode,
                    destination);
            }

            return new Uri(uriString);
        }

        public static Uri RedirectUriForCreds(bool secure, int statusCode, string userName, string password)
        {
            Uri destinationUri = BasicAuthUriForCreds(secure, userName, password);
            string destination = Uri.EscapeDataString(destinationUri.AbsoluteUri);

            return new Uri(string.Format("{0}://{1}/{2}?statuscode={3}&uri={4}",
                secure ? HttpsScheme : HttpScheme,
                Host,
                RedirectHandler,
                statusCode,
                destination));
        }
    }
}


text:
This module has integration tests for the OpenTracing fraction. It serves
also as an example of how a project can be bootstrapped with the OpenTracing
fraction and how to create "business spans", which are children of the span
started via the Servlet framework integration.

The image below is a visual representation of the spans, as if they were reported
to Jaeger. It contains a parent span that is automatically created by the Servlet
framework integration, plus the business span under that.

![WildFly Swarm: Rightsize your JavaEE Applications](example.png)


text:
"""
Tests for series expansions and limits.
"""


text:
from __future__ import unicode_literals

try:
    from pkg_resources import resource_string
except ImportError:
    resource_string = None

from django.conf import settings
from django.template.base import TemplateDoesNotExist
from django.template.loader import BaseLoader
from django.utils import six

class Loader(BaseLoader):
    is_usable = resource_string is not None

    def load_template_source(self, template_name, template_dirs=None):
        """
        Loads templates from Python eggs via pkg_resource.resource_string.

        For every installed app, it tries to get the resource (app, template_name).
        """
        if resource_string is not None:
            pkg_name = 'templates/' + template_name
            for app in settings.INSTALLED_APPS:
                try:
                    resource = resource_string(app, pkg_name)
                except Exception:
                    continue
                if not six.PY3:
                    resource = resource.decode(settings.FILE_CHARSET)
                return (resource, 'egg:%s:%s' % (app, pkg_name))
        raise TemplateDoesNotExist(template_name)

_loader = Loader()


text:
        <link rel="Stylesheet" media="screen" href="data/testsuite.css" />

Unit tests: passedfailed

jQuery version


text:
package org.topclouders.chessprofile.domain;

import com.mysema.query.annotations.QueryEmbeddable;
import org.springframework.data.mongodb.core.mapping.Field;

/**
 * Created by kokeny on 29/03/16.
 */
@QueryEmbeddable
public class Rating extends Document {

    @Field
    private Integer value;

    public Rating() {
        super();
    }
}


text:
package gw.internal.gosu.parser;

import gw.lang.reflect.IType;

/**
 * @deprecated
 */
public class QueryPathRootSymbol extends Symbol
{
  public QueryPathRootSymbol( String strName, IType type, Object value )
  {
    super( strName, type, null, value );
  }

}


text:
package com.redli.tmvpsimple.base;

import com.redli.tmvpsimple.mvp.IPresenter;
import com.redli.tmvpsimple.mvp.IView;

/**
 * MVPPlugin
 *  邮箱 784787081@qq.com
 */

public class BasePresenter<V extends IView> implements IPresenter<V> {
    protected V mView;
    @Override
    public void attachView(V view) {
        mView=view;
    }

    @Override
    public void detachView() {
        mView=null;
    }
}


text:
[![Version](https://img.shields.io/cocoapods/v/PhoneVerificationController.svg?style=flat)](https://cocoapods.org/pods/PhoneVerificationController)
[![License](https://img.shields.io/cocoapods/l/PhoneVerificationController.svg?style=flat)](https://cocoapods.org/pods/PhoneVerificationController)
[![Platform](https://img.shields.io/cocoapods/p/PhoneVerificationController.svg?style=flat)](https://cocoapods.org/pods/PhoneVerificationController)
[![Swift version](https://img.shields.io/badge/Swift-4-orange.svg)](https://cocoapods.org/pods/CountryPickerSwift)

## Example

To run the example project, clone the repo, and run `pod install` from the Example directory first.

## Requirements

## Installation

### CocoaPods

[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command:

```bash
$ gem install cocoapods
```

To integrate PhoneVerificationController into your Xcode project using CocoaPods, specify it in your `Podfile`:

```ruby
use_frameworks!

pod 'FireBase/Auth'
pod 'PhoneVerificationController'
```

Note that you'll need to add `FireBase/Auth` as well (we can't depend on it as it's a static framework). Then, run the following command:

```bash
$ pod install
```

## Usage

Follow the first 2 steps for Firebase authentication on iOS as documenteded [here](https://firebase.google.com/docs/auth/ios/phone-auth). PhoneVerificationController will handle the rest, as long as you invoke it using:

```swift
import FirebaseAuth
import PhoneVerificationController

let configuration = Configuration(requestCode: { phone, completion in
	PhoneAuthProvider.provider().verifyPhoneNumber(phone, completion: completion)
}, signIn: { verificationID, verificationCode, completion in
	let credential = PhoneAuthProvider.provider().credential(withVerificationID: verificationID, verificationCode: verificationCode)
	Auth.auth().signIn(with: credential) { _, error in completion(error) }
})
let vc = PhoneVerificationController(configuration: configuration)
vc.delegate = self
present(vc, animated: true)
```

You'll receive a callback if the verification succeeds, or is cancelled.

## Authors

- [David Jennes](https://github.com/djbe)
- [Tom Knapen](https://github.com/wassup-)
- [Yannick Winters](https://github.com/YWinters)

## License

PhoneVerificationController is available under the MIT license. See the LICENSE file for more info.


text:
from flask import render_template
import lib.es as es
import web.util.tools as tools

def get(p):
    host = p['c']['host']; index = p['c']['index'];

    # load history
    history_id = p['nav'][-1]
    p['history'] = es.get(host, index, 'log', history_id)
    if not p['history']:
        return tools.alert('not valid id - {}'.format(history_id))

    return render_template("post/history/view.html", p=p)


text:
layout: nav_menu_item
title: GetTaxHistory
date: 2014-07-11 03:56
author: anya.stettler
comments: true
categories: [API Reference Menu]
---


text:
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Hgamelaunch.DbTools
       ( makeDb,
         insertUser,
         updateUser,
         updateMaybeUser,
         fetchUserFromDb,
         UserField(UserField),
         userIdNum,
         userUsername,
         userPassword,
         userEmail,
         userAdmin,
         userDebugger
         ) where

import Data.Text
import Control.Applicative
import Database.SQLite.Simple
import Control.Lens

data UserField = UserField { _userIdNum    :: Int
                           , _userUsername :: Text
                           , _userPassword :: Text
                           , _userEmail    :: Text
                           , _userAdmin    :: Bool
                           , _userDebugger :: Bool
                           } deriving (Show)

makeLenses ''UserField

instance FromRow UserField where
  fromRow = UserField <$> field <*> field <*> field <*> field <*> field <*> field

makeDb :: Connection -> Bool -> IO ()
makeDb conn False = do
  execute conn "CREATE TABLE users(id INTEGER PRIMARY KEY,username VARCHAR NOT NULL,password VARCHAR NOT NULL,email VARCHAR NOT NULL,admin BOOLEAN NOT NULL,debugger BOOLEAN NOT NULL,CONSTRAINT username_key UNIQUE (username))" ()
  insertUser conn (UserField 0 "admin" "admin" "admin@server.org" True False)
makeDb _ True = return ()

insertUser :: Connection -> UserField -> IO ()
insertUser conn (UserField _ username password email admin debugger) = do
  execute conn "INSERT INTO users (username, password, email, admin, debugger) VALUES (?, ?, ?, ?, ?)" (username, password, email, admin :: Bool, debugger :: Bool)

updateUser :: Connection -> UserField -> IO ()
updateUser conn (UserField idNum username password email admin debugger) = do
  execute conn "UPDATE users SET username=?, password=?, email=?, admin=?, debugger=? WHERE id=?" (username, password, email, admin :: Bool, debugger :: Bool, idNum :: Int)

updateMaybeUser :: Connection -> Maybe UserField -> IO ()
updateMaybeUser conn (Just user) = do
  updateUser conn user
updateMaybeUser _ Nothing = do
  return ()

fetchUserFromDb :: Connection -> Text -> IO (Maybe UserField)
fetchUserFromDb conn username = do
  xs <- query conn "SELECT * FROM users WHERE username like ? LIMIT 1" (Only username)
--  return $ head xs
  case xs of [] -> return Nothing
             x:[] -> return (Just x)
             _ -> return Nothing


text:
package org.kuali.rice.kew.plugin;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.kuali.rice.core.api.config.property.Config;
import org.kuali.rice.kew.api.WorkflowRuntimeException;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * Loads a plugin from a zip file on the file system.
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public class ZipFilePluginLoader extends BasePluginLoader {
	private static final Logger LOG = Logger.getLogger(ZipFilePluginLoader.class);

	private final File pluginZipFile;
    private final File extractionDirectory;
    private long zipFileLastModified = -1;
    private boolean loadFailed = false;

    private static String validatePluginZipFile(File pluginZipFile) {
        PluginUtils.validatePluginZipFile(pluginZipFile);
        String fileName = pluginZipFile.getName();
        int indexOf = fileName.lastIndexOf(".zip");
        return fileName.substring(0, indexOf);
    }

    public ZipFilePluginLoader(File pluginZipFile, File sharedPluginDirectory, ClassLoader parentClassLoader, Config parentConfig) {
    	super(validatePluginZipFile(pluginZipFile), sharedPluginDirectory, parentClassLoader, parentConfig);
    	this.pluginZipFile = pluginZipFile;
    	this.extractionDirectory = determineExtractionDirectory(getSimplePluginName(), pluginZipFile);
    }

	public boolean isModified() {
		long currentZipFileLastModified = pluginZipFile.lastModified();
		if (zipFileLastModified == -1) {
			zipFileLastModified = currentZipFileLastModified;
			return false;
		} else if (currentZipFileLastModified > zipFileLastModified) {
			return !isZipFileStillBeingModified();
		}
		return false;
	}

	protected boolean isZipFileStillBeingModified() {
		long lastModified = pluginZipFile.lastModified();
		long size = pluginZipFile.length();
		// sleep for a fraction of a second and then check again if the values have changed
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {}
		if (lastModified != pluginZipFile.lastModified()) {
			return true;
		}
		if (size != pluginZipFile.length()) {
			return true;
		}
		return false;
	}

	public boolean isRemoved() {
		return pluginZipFile != null && !pluginZipFile.exists();
	}

    @Override
	public Plugin load() throws Exception {
        try {
            updateLastModified();
            extractPluginFiles();
            Plugin plugin = super.load();
            loadFailed = false;
            return plugin;
        } catch (Exception e) {
            loadFailed = true;
            throw e;
        }
	}

    protected File determineExtractionDirectory(String pluginName, File pluginZipFile) {
		return new File(pluginZipFile.getParentFile(), pluginName);
	}

    /**
     * Extracts the plugin files if necessary.
     */
    protected void extractPluginFiles() throws Exception {
    	if (isExtractNeeded()) {
    		// first, delete the current copy of the extracted plugin
    		if (extractionDirectory.exists()) {
    			// TODO how to handle locked files under windows?!?  This will throw an IOException in this case.
    			FileUtils.deleteDirectory(extractionDirectory);
    		}
    		if (!extractionDirectory.mkdir()) {
    			throw new WorkflowRuntimeException("Could not create the extraction directory for the plugin: " + extractionDirectory.getAbsolutePath());
    		}
    		ZipFile zipFile = new ZipFile(pluginZipFile, ZipFile.OPEN_READ);
    		for (Enumeration entries = zipFile.entries(); entries.hasMoreElements();) {
    			ZipEntry entry = (ZipEntry)entries.nextElement();
				File entryFile = new File(extractionDirectory + java.io.File.separator + entry.getName());
    			if (entry.isDirectory()) { // if its a directory, create it
    				if (!entryFile.mkdir()) {
    					throw new WorkflowRuntimeException("Failed to create directory: " + entryFile.getAbsolutePath());
    				}
    				continue;
    			}
    			InputStream is = null;
    			OutputStream os = null;
    			try {
    				is = new BufferedInputStream(zipFile.getInputStream(entry)); // get the input stream
    				os = new BufferedOutputStream(new FileOutputStream(entryFile));
    				while (is.available() > 0) {  // write contents of 'is' to 'fos'
    					os.write(is.read());
    				}
    			} finally {
    				if (os != null) {
    					os.close();
    				}
    				if (is != null) {
    					is.close();
    				}
    			}
    		}
    	}
    }

    /**
     * @return the loadFailed
     */
    public boolean isLoadFailed() {
        return this.loadFailed;
    }

    /**
     * An extract is required if the plugin has been modified or the last modified date of the zip file
     * is later than the last modified date of the extraction directory.
     */
    protected boolean isExtractNeeded() {
    	return isModified() || pluginZipFile.lastModified() > extractionDirectory.lastModified();
    }

    protected void updateLastModified() {
    	zipFileLastModified = pluginZipFile.lastModified();
    }

	protected PluginClassLoader createPluginClassLoader() throws MalformedURLException {
        LOG.info(getLogPrefix() + " Initiating loading of plugin from file system: " + extractionDirectory.getPath());
        LOG.info(getLogPrefix() + " Absolute path on file system is: " + extractionDirectory.getAbsolutePath());
        /* MalformedURLException should technically never be thrown as the URLs are coming from (presumably)
         * valid File objects
         */
        return new PluginClassLoader(parentClassLoader, sharedPluginDirectory, extractionDirectory);
    }

    protected URL getPluginConfigURL() throws PluginException, MalformedURLException {
        File pluginConfigFile = new File(extractionDirectory, pluginConfigPath);
        if (!pluginConfigFile.exists() || !pluginConfigFile.isFile()) {
            throw new PluginException(getLogPrefix() + " Could not locate the plugin config file at path " + pluginConfigFile.getAbsolutePath());
        }
        return pluginConfigFile.toURI().toURL();
    }
}


text:
import logging
from time import time
from collections import deque

from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import numpy as np
from scipy import stats

import progressbar

from pybar.daq.readout_utils import get_col_row_array_from_data_record_array, convert_data_array, is_data_record
# from pybar.daq.readout_utils import data_array_from_data_iterable
# from pybar_fei4_interpreter.data_interpreter import PyDataInterpreter
# from pybar_fei4_interpreter.data_histograming import PyDataHistograming
from pybar.analysis.analyze_raw_data import AnalyzeRawData
from pybar.fei4.register_utils import make_box_pixel_mask_from_col_row, invert_pixel_mask
from pybar.fei4_run_base import Fei4RunBase
from pybar.run_manager import RunManager
from pybar.analysis.plotting.plotting import plot_occupancy, plot_fancy_occupancy, plot_three_way, hist_quantiles

class ThresholdBaselineTuning(Fei4RunBase):
    '''Threshold Baseline Tuning aka Noise Tuning

    Tuning the FEI4 to the lowest possible threshold (GDAC and TDAC). Feedback current will not be tuned.
    NOTE: In case of RX errors decrease the trigger frequency (= increase trigger_rate_limit), or reduce the number of triggers
    NOTE: To increase the TDAC range, decrease TdacVbp.
    '''
    _default_run_conf = {
        "broadcast_commands": False,
        "threaded_scan": True,
        "occupancy_limit": 1 * 10 ** (-5),  # occupancy limit, when reached, the TDAC will be decreased (threshold increased). 0 will mask any pixel with occupancy greater than zero. Occupancy limit 10^-5 is default for IBL (see ATLAS IBL TDR)
        "start_gdac": 120,  # start value of GDAC tuning
        "gdac_lower_limit": 0,  # set GDAC lower limit to prevent FEI4 from becoming noisy, set to 0 or None to disable
        "scan_parameters": [('Vthin_AltFine', None), ('TDAC_step', None)],  # the Vthin_AltFine range, number of steps (repetition at constant Vthin_AltFine)
        "refine_tuning": True,  # undertake additional TDAC tuning steps, might increase threshold but will reduce noise occupancy to a minimum
        "plot_n_steps": 5,  # store and plot n last steps
        "disabled_pixels_limit": 0.01,  # limit of disabled pixels, fraction of all pixels
        "use_enable_mask": False,  # if True, enable mask from config file anded with mask (from col_span and row_span), if False use mask only for enable mask
        "n_triggers": 10000,  # total number of trigger sent to FE
        "trigger_rate_limit": 500,  # artificially limiting the trigger rate, in BCs (25ns)
        "trig_count": 1,  # FE-I4 trigger count, number of consecutive BCs, 0 means 16, from 0 to 15
        "col_span": [1, 80],  # column range (from minimum to maximum value). From 1 to 80.
        "row_span": [1, 336],  # row range (from minimum to maximum value). From 1 to 336.
    }

    def configure(self):
        commands = []
        commands.extend(self.register.get_commands("ConfMode"))
        # GDAC
        self.gdac_range = [self.register.get_global_register_value("Vthin_AltFine"), 0]  # default GDAC range
        if self.start_gdac is not None:
            self.gdac_range[0] = min(self.start_gdac, 2 ** self.register.global_registers['Vthin_AltFine']['bitlength'])
        if self.gdac_lower_limit is not None:
            self.gdac_range[1] = max(self.gdac_lower_limit, 0)
        self.register.set_global_register_value("Vthin_AltFine", self.gdac_range[0])  # set to start threshold value
        commands.extend(self.register.get_commands("WrRegister", name=["Vthin_AltFine"]))
        # TDAC
        tdac_max = 2 ** self.register.pixel_registers['TDAC']['bitlength'] - 1
        self.register.set_pixel_register_value("TDAC", tdac_max)
        commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=False, name="TDAC"))
        mask = make_box_pixel_mask_from_col_row(column=self.col_span, row=self.row_span)
        # Enable
        if self.use_enable_mask:
            self.register.set_pixel_register_value("Enable", np.logical_and(mask, self.register.get_pixel_register_value("Enable")))
        else:
            self.register.set_pixel_register_value("Enable", mask)
        commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=False, name="Enable"))
        # Imon
        self.register.set_pixel_register_value('Imon', 1)
        commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=True, name='Imon'))
        # C_High
        self.register.set_pixel_register_value('C_High', 0)
        commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=True, name='C_High'))
        # C_Low
        self.register.set_pixel_register_value('C_Low', 0)
        commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=True, name='C_Low'))
        # Registers
#         self.register.set_global_register_value("Trig_Lat", self.trigger_latency)  # set trigger latency
        self.register.set_global_register_value("Trig_Count", self.trig_count)  # set number of consecutive triggers
        commands.extend(self.register.get_commands("WrRegister", name=["Trig_Count"]))
        commands.extend(self.register.get_commands("RunMode"))
        self.register_utils.send_commands(commands)

    def scan(self):
        if self.trig_count == 0:
            self.consecutive_lvl1 = 2 ** self.register.global_registers['Trig_Count']['bitlength']
        else:
            self.consecutive_lvl1 = self.trig_count
        enabled_pixels = self.register.get_pixel_register_value('Enable').sum()
        preselected_pixels = invert_pixel_mask(self.register.get_pixel_register_value('Enable')).sum()
        disabled_pixels_limit_cnt = int(self.disabled_pixels_limit * self.register.get_pixel_register_value('Enable').sum())
        abs_occ_limit = stats.poisson.ppf(0.5, mu=self.occupancy_limit * self.n_triggers * self.consecutive_lvl1)
        logging.info('The pixel threshold will be increased when occpancy >%d' % abs_occ_limit)
        total_occ_limit = int(self.occupancy_limit * self.n_triggers * self.consecutive_lvl1 * enabled_pixels)
        # Sum of PMF of Poisson distribution (k>0)
        n_expected_pixel_hits = int((1.0 - stats.poisson.pmf(k=0, mu=self.occupancy_limit * self.n_triggers * self.consecutive_lvl1)) * enabled_pixels)
        logging.info('The global threshold will be decreased when total occupancy is <=%d and pixel with hits <=%d' % (total_occ_limit, n_expected_pixel_hits))
        max_tdac_steps = max(1, int(np.ceil((1 / self.occupancy_limit) / (self.n_triggers * self.consecutive_lvl1) * (1 / (1 - 0.5)))))
        tdac_center = 2 ** self.register.pixel_registers['TDAC']['bitlength'] / 2
        lvl1_command = self.register.get_commands("LV1")[0] + self.register.get_commands("zeros", length=self.trigger_rate_limit)[0]
        total_scan_time = int(lvl1_command.length() * 25 * (10 ** -9) * self.n_triggers)

        self.threshold = deque([None] * (self.plot_n_steps + 2), maxlen=self.plot_n_steps + 2)
        self.tdac_step = deque([None] * (self.plot_n_steps + 2), maxlen=self.plot_n_steps + 2)
        self.tdac = deque([None] * (self.plot_n_steps + 2), maxlen=self.plot_n_steps + 2)
        self.new_tdac = deque([None] * (self.plot_n_steps + 2), maxlen=self.plot_n_steps + 2)
        self.enable_mask = deque([None] * (self.plot_n_steps + 2), maxlen=self.plot_n_steps + 2)
        self.new_enable_mask = deque([None] * (self.plot_n_steps + 2), maxlen=self.plot_n_steps + 2)
        self.occupancy_hist = deque([None] * (self.plot_n_steps + 2), maxlen=self.plot_n_steps + 2)
        self.occupancy_mask = deque([None] * (self.plot_n_steps + 2), maxlen=self.plot_n_steps + 2)

#         interpreter = PyDataInterpreter()
#         histogram = PyDataHistograming()
#         interpreter.set_trig_count(self.trig_count)
#         interpreter.set_warning_output(False)
#         histogram.set_no_scan_parameter()
#         histogram.create_occupancy_hist(True)
        coarse_threshold = [self.gdac_range[0]]
        reached_pixels_limit_cnt = False
        reached_tdac_center = False
        reached_gdac_lower_limit = False
        do_refine_tuning = False
        for reg_val in coarse_threshold:  # outer loop, coarse tuning threshold
            if self.stop_run.is_set():
                break
            logging.info('Scanning Vthin_AltFine %d', reg_val)
            commands = []
            commands.extend(self.register.get_commands("ConfMode"))
            self.register.set_global_register_value("Vthin_AltFine", reg_val)
            commands.extend(self.register.get_commands("WrRegister", name=["Vthin_AltFine"]))
            # setting FE into RunMode
            commands.extend(self.register.get_commands("RunMode"))
            self.register_utils.send_commands(commands)
            tdac_step = 1
            while True:  # inner loop
                if self.stop_run.is_set():
                    break
#                 histogram.reset()

                logging.info('TDAC step %d at Vthin_AltFine %d', tdac_step, reg_val)
#                 logging.info('Estimated scan time: %ds', total_scan_time)

                with self.readout(Vthin_AltFine=reg_val, TDAC_step=tdac_step, fill_buffer=True):
                    got_data = False
                    start = time()
                    self.register_utils.send_command(lvl1_command, repeat=self.n_triggers, wait_for_finish=False, set_length=True, clear_memory=False)
                    while not self.stop_run.wait(0.1):
                        if self.register_utils.is_ready:
                            if got_data:
                                self.progressbar.finish()
                            logging.info('Finished sending %d triggers', self.n_triggers)
                            break
                        if not got_data:
                            if self.data_words_per_second() > 0:
                                got_data = True
                                logging.info('Taking data...')
                                self.progressbar = progressbar.ProgressBar(widgets=['', progressbar.Percentage(), ' ', progressbar.Bar(marker='*', left='|', right='|'), ' ', progressbar.Timer()], maxval=total_scan_time, poll=10, term_width=80).start()
                        else:
                            try:
                                self.progressbar.update(time() - start)
                            except ValueError:
                                pass
                # use Numpy for analysis and histogramming
                col_arr, row_arr = convert_data_array(array=self.read_data(), filter_func=is_data_record, converter_func=get_col_row_array_from_data_record_array)
                occ_hist, _, _ = np.histogram2d(col_arr, row_arr, bins=(80, 336), range=[[1, 80], [1, 336]])
                occ_mask = np.zeros(shape=occ_hist.shape, dtype=np.dtype('>u1'))

                # use FEI4 interpreter for analysis and histogramming
#                 from pybar.daq.readout_utils import data_array_from_data_iterable
#                 raw_data = np.ascontiguousarray(data_array_from_data_iterable(self.read_data()), dtype=np.uint32)
#                 interpreter.interpret_raw_data(raw_data)
#                 interpreter.store_event()  # force to create latest event
#                 histogram.add_hits(interpreter.get_hits())
#                 occ_hist = histogram.get_occupancy()[:, :, 0]
#                 # noisy pixels are set to 1
#                 occ_mask = np.zeros(shape=occ_hist.shape, dtype=np.dtype('>u1'))

                occ_mask[occ_hist > abs_occ_limit] = 1

                tdac_reg = self.register.get_pixel_register_value('TDAC')
                decrease_pixel_mask = np.logical_and(occ_mask > 0, tdac_reg > 0)
                disable_pixel_mask = np.logical_and(occ_mask > 0, tdac_reg == 0)
                enable_mask = self.register.get_pixel_register_value('Enable')
                new_enable_mask = np.logical_and(enable_mask, invert_pixel_mask(disable_pixel_mask))
                if np.logical_and(occ_mask > 0, enable_mask == 0).sum():
                    logging.warning('Received data from disabled pixels')
#                     disabled_pixels += disable_pixel_mask.sum()  # can lead to wrong values if the enable reg is corrupted
                disabled_pixels = invert_pixel_mask(new_enable_mask).sum() - preselected_pixels
                logging.info('Found %d noisy pixels', occ_mask.sum())
                logging.info('Increasing threshold of %d pixel(s)', decrease_pixel_mask.sum())
                logging.info('Disabling %d pixel(s), total number of disabled pixel(s): %d', disable_pixel_mask.sum(), disabled_pixels)

                # increasing threshold before writing TDACs to avoid FE becoming noisy
                self.register.set_global_register_value("Vthin_AltFine", self.gdac_range[0])
                commands = []
                commands.extend(self.register.get_commands("ConfMode"))
                commands.extend(self.register.get_commands("WrRegister", name=["Vthin_AltFine"]))
                self.register_utils.send_commands(commands)
                # writing TDAC
                new_tdac_reg = tdac_reg.copy()
                new_tdac_reg[decrease_pixel_mask] -= 1  # smaller TDAC translates to higher threshold
                self.register.set_pixel_register_value('TDAC', new_tdac_reg)
                self.register.set_pixel_register_value('Enable', new_enable_mask)
                commands = []
                commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=False, name='TDAC'))
                commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=False, name='Enable'))
                self.register_utils.send_commands(commands)
                # writing threshold value after writing TDACs
                self.register.set_global_register_value("Vthin_AltFine", reg_val)
                commands = []
                commands.extend(self.register.get_commands("WrRegister", name=["Vthin_AltFine"]))
                commands.extend(self.register.get_commands("RunMode"))
                self.register_utils.send_commands(commands)

                if (not do_refine_tuning and occ_hist.sum() <= total_occ_limit and occ_mask.sum() <= n_expected_pixel_hits) or (tdac_step >= max_tdac_steps):
                    logging.info('Stop tuning TDACs at Vthin_AltFine %d', reg_val)
                    self.threshold.appendleft(self.register.get_global_register_value("Vthin_AltFine"))
                    self.tdac_step.appendleft(tdac_step)
                    self.tdac.appendleft(tdac_reg)
                    self.new_tdac.appendleft(new_tdac_reg)
                    self.enable_mask.appendleft(enable_mask)
                    self.new_enable_mask.appendleft(new_enable_mask)
                    self.occupancy_hist.appendleft(occ_hist.copy())
                    self.occupancy_mask.appendleft(occ_mask.copy())
                    if not do_refine_tuning and np.mean(new_tdac_reg[new_enable_mask]) <= tdac_center + (1 if self.refine_tuning else 0):
                        reached_tdac_center = True
                    if not do_refine_tuning and disabled_pixels > disabled_pixels_limit_cnt:
                        reached_pixels_limit_cnt = True
                        logging.info('Limit of disabled pixels reached: %d (limit %d).' % (disabled_pixels, disabled_pixels_limit_cnt))
                    if not do_refine_tuning and reg_val <= self.gdac_range[1]:
                        reached_gdac_lower_limit = True
                    break
                else:
                    logging.info('Continue tuning TDACs at Vthin_AltFine %d', reg_val)
                # increase scan parameter counter
                tdac_step += 1

            if not self.refine_tuning and (reached_pixels_limit_cnt or reached_tdac_center or reached_gdac_lower_limit):
                pass  # will exit loop
            elif do_refine_tuning:
                logging.info("Finished TDAC refine tuning.")
            elif reached_pixels_limit_cnt or reached_tdac_center or reached_gdac_lower_limit:
                do_refine_tuning = True
                logging.info("Starting TDAC refine tuning...")
                coarse_threshold.append(reg_val - 1)
                abs_occ_limit = stats.poisson.ppf(0.99, mu=self.occupancy_limit * self.n_triggers * self.consecutive_lvl1)
                logging.info('The pixel threshold will be increased when occpancy >%d' % abs_occ_limit)
                max_tdac_steps = max(1, int(np.ceil((1 / self.occupancy_limit) / (self.n_triggers * self.consecutive_lvl1) * (1 / (1 - 0.99)))))
            else:
                coarse_threshold.append(reg_val - 1)

    def analyze(self):
        self.register.set_global_register_value("Vthin_AltFine", self.threshold[0])
        self.register.set_pixel_register_value('TDAC', self.new_tdac[0])
        self.register.set_pixel_register_value('Enable', self.new_enable_mask[0])  # use enable mask from the lowest point to mask bad pixels
        # write configuration to avoid high current states
        commands = []
        commands.extend(self.register.get_commands("ConfMode"))
        commands.extend(self.register.get_commands("WrRegister", name=["Vthin_AltFine"]))
        commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=False, name="TDAC"))
        commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=False, name="Enable"))
        self.register_utils.send_commands(commands)

        with AnalyzeRawData(raw_data_file=self.output_filename, create_pdf=True) as analyze_raw_data:
            analyze_raw_data.create_source_scan_hist = True
            analyze_raw_data.interpreter.set_warning_output(False)
            analyze_raw_data.interpret_word_table()
            analyze_raw_data.interpreter.print_summary()
            analyze_raw_data.plot_histograms()
            last_step = None
            for step in range(self.plot_n_steps, -1, -1):
                if self.threshold[step] is not None:
                    plot_occupancy(self.occupancy_hist[step].T, title='Occupancy at Vthin_AltFine %d Step %d' % (self.threshold[step], self.tdac_step[step]), filename=analyze_raw_data.output_pdf)
                    plot_fancy_occupancy(self.occupancy_hist[step].T, filename=analyze_raw_data.output_pdf)
                    plot_occupancy(self.occupancy_mask[step].T, title='Noisy pixels at Vthin_AltFine %d Step %d' % (self.threshold[step], self.tdac_step[step]), z_max=1, filename=analyze_raw_data.output_pdf)
                    plot_fancy_occupancy(self.occupancy_mask[step].T, filename=analyze_raw_data.output_pdf)
                    plot_three_way(self.tdac[step].T, title='TDAC at Vthin_AltFine %d Step %d' % (self.threshold[step], self.tdac_step[step]), x_axis_title="TDAC", filename=analyze_raw_data.output_pdf, maximum=31, bins=32)
                    plot_occupancy(self.tdac[step].T, title='TDAC at Vthin_AltFine %d Step %d' % (self.threshold[step], self.tdac_step[step]), z_max=31, filename=analyze_raw_data.output_pdf)
                    plot_occupancy(self.enable_mask[step].T, title='Enable mask at Vthin_AltFine %d Step %d' % (self.threshold[step], self.tdac_step[step]), z_max=1, filename=analyze_raw_data.output_pdf)
                    # adding Poisson statistics plots
                    fig = Figure()
                    FigureCanvas(fig)
                    ax = fig.add_subplot(111)
                    ax.set_title("Hit statistics")
                    hist, bin_edges = np.histogram(self.occupancy_hist[step], bins=np.arange(0.0, np.max(self.occupancy_hist[step]) + 2, 1.0))
                    try:
                        _, idx = hist_quantiles(hist, [0.0, 0.9], return_indices=True)
                    except IndexError:
                        idx = [0, 1]
                    bins = np.arange(0, np.maximum(bin_edges[idx[1]], stats.poisson.ppf(0.9999, mu=self.occupancy_limit * self.n_triggers * self.consecutive_lvl1)) + 2, 1)
                    _, bin_edges, _ = ax.hist(self.occupancy_hist[step].flatten(), bins=350 if len(bins) > 351 else bins, range=(0.0, bins[-1]), align='left', alpha=0.5, label="Measured occupancy")
                    # re-binning
                    statistic, _, _ = stats.binned_statistic(bins[:-1], stats.poisson.pmf(k=bins[:-1], mu=self.occupancy_limit * self.n_triggers * self.consecutive_lvl1) * self.register.get_pixel_register_value("Enable").sum(), statistic='sum', bins=bin_edges)
                    ax.bar(bin_edges[:-1], statistic, alpha=0.5, width=bin_edges[1] - bin_edges[0], color="r", label="Expected occupancy (Poisson statistics)")
                    # ax.hist(stats.poisson.rvs(mu=self.occupancy_limit * self.n_triggers * self.consecutive_lvl1, size=self.enable_mask[step].sum()), bins=bins, align='left', alpha=0.5, label="Expected occupancy (Poisson statistics)")
                    ax.set_xlabel('#Hits')
                    ax.set_ylabel('#Pixels')
                    ax.legend()
                    analyze_raw_data.output_pdf.savefig(fig)
                    last_step = step
            if last_step is not None:
                plot_three_way(self.new_tdac[last_step].T, title='Final TDAC after Vthin_AltFine %d Step %d' % (self.threshold[last_step], self.tdac_step[last_step]), x_axis_title="TDAC", filename=analyze_raw_data.output_pdf, maximum=31, bins=32)
                plot_occupancy(self.new_tdac[last_step].T, title='Final TDAC after Vthin_AltFine %d Step %d' % (self.threshold[last_step], self.tdac_step[last_step]), z_max=31, filename=analyze_raw_data.output_pdf)
                plot_occupancy(self.new_enable_mask[last_step].T, title='Final Enable mask after Vthin_AltFine %d Step %d' % (self.threshold[last_step], self.tdac_step[last_step]), z_max=1, filename=analyze_raw_data.output_pdf)

if __name__ == "__main__":
    with RunManager('configuration.yaml') as runmngr:
        runmngr.run_run(ThresholdBaselineTuning)


text:
import defend.game.GameEngine.Protocol.RocketFired
import defend.model._

package object defend {

  val collisionDistance: Double = 8

  def move(position: Position, moveVector: MoveVector, millis: Long): Position = {
    Position(
      position.x + (moveVector.speed * Math.cos(moveVector.direction) * millis) / 1000,
      position.y + (moveVector.speed * Math.sin(moveVector.direction) * millis) / 1000)
  }

  def move(position: Position, moveVector: MoveVector, millis: Double): Position = {
    Position(
      position.x + (moveVector.speed * Math.cos(moveVector.direction) * millis) / 1000,
      position.y + (moveVector.speed * Math.sin(moveVector.direction) * millis) / 1000)
  }

  def findMissileToIntercept(list: List[WeaponInAction[AlienWeapon]], landScape: LandScape, tower: Position, speed: Double, range: Double): Option[WeaponInAction[AlienWeapon]] = {
    list.flatMap { w =>
      val height = w.position.y - landScape.groundLevel
      val dropSpeed = w.moveVector.speed * Math.sin(w.moveVector.direction)
      val hitTime = if (dropSpeed == 0) {
        Integer.MAX_VALUE
      } else {
        -(height / dropSpeed)
      }
      val weaponTypeFactor = w.weapon match {
        case _: AlienEmp  => 1
        case _: AlienNuke => 2
        case _: Any       => 3
      }
      val interceptionData: Option[InterceptionData] = calculateInterception(tower, speed, w.position, w.moveVector)
      interceptionData.toList.filter { i =>
        i.distance < range
      }.map(i => (i.duration * hitTime * weaponTypeFactor, i, w))
    }.sortBy(t => t._1).map(t => t._3).headOption
  }

  def findFirstToIntercept(list: List[WeaponInAction[AlienWeapon]], landScape: LandScape): Option[WeaponInAction[AlienWeapon]] = {
    list.sortBy { w =>
      val height = w.position.y - landScape.groundLevel
      val dropSpeed = w.moveVector.speed * Math.sin(w.moveVector.direction)
      if (dropSpeed == 0) {
        Integer.MAX_VALUE
      } else {
        -(height / dropSpeed)
      }
    }.headOption
  }

  def closeEnough(position1: Position, position2: Position, maxDistance: Double): Boolean = {
    val a: Double = position1.x - position2.x
    val b: Double = position1.y - position2.y
    a * a + b * b < maxDistance * maxDistance
    //    (Math.abs(a) < maxDistance) && (Math.abs(b) < maxDistance)
  }

  def findCollisions(human: List[WeaponInAction[HumanWeapon]], aliens: List[WeaponInAction[AlienWeapon]]): List[(WeaponInAction[HumanWeapon], List[WeaponInAction[AlienWeapon]])] = {
    human.foldLeft(List.empty[(WeaponInAction[HumanWeapon], List[WeaponInAction[AlienWeapon]])]) {
      (acc, item) =>
        val filter: List[WeaponInAction[AlienWeapon]] = aliens.filter(p => {
          closeEnough(item.position, p.position, collisionDistance)
        })
        if (filter.nonEmpty) {
          (item, filter) :: acc
        } else {
          acc
        }
    }
  }

  def damageCities(cities: List[City], explosions: List[Explosion]): List[City] = {
    cities.map {
      city =>
        val affectedBy: List[Explosion] = explosions.filter(e => closeEnough(city.position, e.position, e.weapon.explosionRadius))
        val sumDamage: Int = affectedBy.map(_.weapon.damage).sum

        city.copy(condition = Math.max(city.condition - sumDamage, 0))
    }
  }

  def experienceToLevel(exp: Int): Int = {
    Integer.toBinaryString(exp).length
  }

  def calculateDirection(start: Position, end: Position): MoveVector = {
    val x = end.x - start.x
    val y = end.y - start.y
    val z = Math.sqrt(x * x + y * y)

    val α = if (y > 0 && x > 0) {
      Math.atan(y / x)
    } else if (y > 0 && x < 0) {
      Math.PI + Math.atan(y / x)
    } else if (y < 0 && x < 0) {
      Math.PI + Math.atan(y / x)
    } else if (y < 0 && x > 0) {
      2 * Math.PI + Math.atan(y / x)
    } else if (x == 0) {
      if (y > 0) Math.PI / 2 else Math.PI * 1.5
    } else if (y == 0) {
      if (x > 0) 0 else Math.PI
    } else {
      0
    }

    MoveVector(α, z)
  }

  def distance(p1: Position, p2: Position): Double = {
    Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y))
  }

  def calculateInterception(start: Position, chaserSpeed: Double, target: Position, targetVector: MoveVector): Option[InterceptionData] = {
    def dot(p1: Position, p2: Position): Double = {
      p1.x * p2.x + p1.y * p2.y
    }

    def quadraticSolver(a: Double, b: Double, c: Double): List[Double] = {
      val delta = b * b - 4 * a * c
      if (a == 0) {
        List(-c / b)
      } else if (delta < 0) {
        Nil
      } else {
        val deltaSqrt: Double = Math.sqrt(delta)
        val x1 = (-b + deltaSqrt) / (2 * a)
        val x2 = (-b - deltaSqrt) / (2 * a)
        List(x1, x2)
      }
    }

    val distanceToRunner = distance(start, target)
    val vectorFromRunner = Position(start.x - target.x, start.y - target.y)
    val vectorRunner = Position(targetVector.speed * Math.cos(targetVector.direction), targetVector.speed * Math.sin(targetVector.direction))
    //    val cosTheta = dot(vectorFromRunner, vectorRunner) / (distanceToRunner * targetVector.speed)
    val a = targetVector.speed * targetVector.speed - chaserSpeed * chaserSpeed
    val b = -2 * dot(vectorFromRunner, vectorRunner)
    val c = distanceToRunner * distanceToRunner

    val solutions: List[Double] = quadraticSolver(a, b, c)
    val interceptTimeMs = solutions.filter(_ >= 0).sorted.headOption
    interceptTimeMs.map {
      t =>
        val interceptionDuration: Double = t * 1000
        val hitPosition: Position = move(target, targetVector, interceptionDuration)
        val angle = calculateDirection(start, hitPosition).direction
        val moveVector = MoveVector(angle, chaserSpeed)
        InterceptionData(moveVector, hitPosition, interceptionDuration, distance(hitPosition, start))

    }.filter(r => r.moveVector.direction > 5d.toRadians && r.moveVector.direction < Math.PI - 5d.toRadians)

  }

  def reduceByLevel(value: Double, level: Int, reduction: Double): Double = {
    value * Math.pow(1 - reduction, level)
  }

  def angleErrorForLevel(level: Int): Double = {
    val nextLevelReduction = 0.20
    reduceByLevel(40d.toRadians, level - 1, nextLevelReduction)
  }

  def rangeForLevel(level: Int): Double = {
    (100 + level * (20 + level * 2)).toDouble
  }

  def fireMissile(me: DefenceTower, target: WeaponInAction[AlienWeapon], speed: Double, range: Double, explosionRadius: Double): Option[RocketFired] = {
    val vector: Option[InterceptionData] = defend.calculateInterception(me.position, speed, target.position, target.moveVector)
    vector.map {
      v =>
        RocketFired(
          HumanMissile(me.name, 1, explosionRadius),
          v.moveVector,
          me,
          Some(range * Math.sin(v.moveVector.direction) + me.position.y))
    }
  }
}


text:
<!DOCTYPE html>

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

    <title>Measure DD in Oakland 2014</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/agency.css" rel="stylesheet">

    <link href="font-awesome-4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href='http://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Measure DD is good for Oakland

                        What is DD 2014?

                        Why it matters

                        How it works

                        Supporters

                        Endorse DD

Vote for Measure DD in 2014

Oakland Deserves an Independent Redistricting Commission

                Tell Me More

What is Measure DD?

A new ballot measure that will create an Independent Redistricting Commission for Oakland.

E-Commerce

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.

Responsive Design

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.

Web Security

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.

Why DD Matters

Power to make new districts should reside in the hands of the people.

Round Icons

Graphic Design

Startup Framework

Website Design

Treehouse

Website Design

Golden

Website Design

Escape

Website Design

Dreams

Website Design

How the Commission will work

This plan is modeled after California's Commission and adapted from the new ICRC in Austin, TX

Census year (2020)

Nominations

Oakland residents may nominate themselves to serve on the commission- you must live here..xx

Sometime (2021)

The Commission is Launched

After process, review, diversity, qualifications, new commission of xx Oaklanders is formed.

Engagement (Mid 2021)

Redrawing the lines begins!

The new commission, with the help of a consultant and city staff, starts a comprehensive engagement process to hear from residents about what communities need protecting, lines that should be changed.

Late 2021

The Redesign

The commissioners, using mapping tools and community input, draw up the new Council and School Board district lines to reflect the community concerns as well as Census data.

You can

be part

of this!

Organizations Supporting Measure DD

Urban Strategies Council

League of Women Voters Oakland

Oakland Rising

Want to add your support to this initiative?

                                    Endorse DD Now!

Endorse DD: Let's make Oakland's Independent Redistricting Commission happen!

Your email will remain confidential and will not be given/sold to anyone. Your name will be published on this site unless you request otherwise.

                    <form name="sentMessage" id="contactForm" novalidate>

                                    <input type="text" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name.">

                                    <input type="email" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address.">

                                    <input type="tel" class="form-control" placeholder="Your Organization *" id="org" required data-validation-required-message="Please enter your organization name if this is not an individual endorsement.">

                                    <textarea class="form-control" placeholder="Why are you supporting DD? *" id="message" required data-validation-required-message="Please enter a message."></textarea>

                                <button type="submit" class="btn btn-xl">Send Your Support</button>

                    </form>

                    MIT Licensed as Open Source - copy this code

Privacy Policy

Project Name

Lorem ipsum dolor sit amet consectetur.

Use this area to describe your project. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est blanditiis dolorem culpa incidunt minus dignissimos deserunt repellat aperiam quasi sunt officia expedita beatae cupiditate, maiores repudiandae, nostrum, reiciendis facere nemo!

                                Want these icons in this portfolio item sample?You can download 60 of them for free, courtesy of RoundIcons.com, or you can purchase the 1500 icon set here.

Date: July 2014

Client: Round Icons

Category: Graphic Design

                            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Project Heading

Lorem ipsum dolor sit amet consectetur.

Startup Framework is a website builder for professionals. Startup Framework contains components and complex blocks (PSD+HTML Bootstrap themes and templates) which can easily be integrated into almost any design. All of these components are made in the same style, and can easily be integrated into projects, allowing you to create hundreds of solutions for your future projects.

You can preview Startup Framework here.

                            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Project Name

Lorem ipsum dolor sit amet consectetur.

Treehouse is a free PSD web template built by Mathavan Jaya. This is bright and spacious design perfect for people or startup companies looking to showcase their apps or other projects.

You can download the PSD template in this portfolio sample item at FreebiesXpress.com.

                            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Project Name

Lorem ipsum dolor sit amet consectetur.

Start Bootstrap's Agency theme is based on Golden, a free PSD website template built by Mathavan Jaya. Golden is a modern and clean one page web template that was made exclusively for Best PSD Freebies. This template has a great portfolio, timeline, and meet your team sections that can be easily modified to fit your needs.

You can download the PSD template in this portfolio sample item at FreebiesXpress.com.

                            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Project Name

Lorem ipsum dolor sit amet consectetur.

Escape is a free PSD web template built by Mathavan Jaya. Escape is a one page web template that was designed with agencies in mind. This template is ideal for those looking for a simple one page solution to describe your business and offer your services.

You can download the PSD template in this portfolio sample item at FreebiesXpress.com.

                            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Project Name

Lorem ipsum dolor sit amet consectetur.

Dreams is a free PSD web template built by Mathavan Jaya. Dreams is a modern one page web template designed for almost any purpose. It's a beautiful template that's designed with the Bootstrap framework in mind.

You can download the PSD template in this portfolio sample item at FreebiesXpress.com.

                            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>


text:
window.CountryModel = Backbone.Model.extend({
    defaults: {
        "id": "",
        "name": "",
    },
    parse: function(response) {
        return response;
    }
});

window.CountryCollection = Backbone.Collection.extend({
    model: CountryModel,
    url: 'api/countries/1',
    parse: function(response) {
        var resp = Array();
        for (var i = 0; i < response.countries.length; i++) {
            var model = {id: response.countries[i][0], name: response.countries[i][1]};
            resp[i] = model;
        }
        return resp;
    }
});


text:
layout: post
title: An Experiential Degree
date: 2016-04-18 23:26
# Should be longer than 150 words, so it will appear as post summary
description: What if you decided to make your own grad school by reproducing the best results in the field?
# tags will also be used as html meta keywords.
categories: ["science", "learning", "metalearning"]

show_meta: true
comments: true
mathjax: true
gistembed: true
published: true
noindex: false
nofollow: false
---

Table of Contents

1. The Value of a Ph.D.

2. Unbundling the doctorate?

3. A recent innovation

### The Value of a Ph.D.

A university provides lab space, access to high-powered machines, advanced
researchers in disparate fields (essential for interdisciplinary work), and funding
and training through and beyond graduate school.

That is, a Ph.D. bundles together training, resources, and credibility. The credibility is necessary
for convincing investors or academics to give you a job.

If you are able to provide yourself sufficient resources and training, and don't need
the credibility, then a Ph.D. may possibly be an inefficient way to get the training and
begin research. While the program involves a lot of cutting-edge classes, it also involves
working on other people's research, doing lab scut work, and teaching classes.

### Unbundling the doctorate?

How much money would it take to replicate graduate school in molecular biology?
Let's say you had 45000 USD to live on for three years. Access to research is free.
You need equipment, most of which you can create for about \$1000.
You need further materials, such as reagents, so budget a few thousand for that.
You need a lab space, though perhaps you could get lucky and use a friend's garage.

You then set yourself the task of replicating the most useful and accessible current
results: an experiential, experiment-based science education.

Collect a list of the most essential results to understand, and the most educational results
to replicate. Group these into prerequisite groups: this requires more statistics knowledge,
this more chemistry knowledge. Begin reading papers and performing experiments at a regular
pace. Each paper should have the time required for reading or replication attached.
By grouping the papers, you can prepare ahead of time for the groups in which you are weakest.

This course of action would probably result in a better quality education than found
in many university laboratories. The sticking point is cost. A university provides the
\$45000, equipment, materials, and lab space.

### A recent innovation

Freeman Dyson is rather proud that he never got a Ph.D., and that his children did not
either. The German innovation which has become the standard still has a lot going for it,
but as Peter Medawar wrote, "science is as science does." Real work could occur outside the halls of academe.


text:
<?php

namespace Symfony\Component\HttpKernel\Tests\EventListener;

use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\EventListener\ServiceResetListener;
use Symfony\Component\HttpKernel\Tests\Fixtures\ClearableService;
use Symfony\Component\HttpKernel\Tests\Fixtures\ResettableService;

class ServiceResetListenerTest extends TestCase
{
    protected function setUp()
    {
        ResettableService::$counter = 0;
        ClearableService::$counter = 0;
    }

    public function testResetServicesNoOp()
    {
        $container = $this->buildContainer();
        $container->get('reset_subscriber')->onKernelTerminate();

        $this->assertEquals(0, ResettableService::$counter);
        $this->assertEquals(0, ClearableService::$counter);
    }

    public function testResetServicesPartially()
    {
        $container = $this->buildContainer();
        $container->get('one');
        $container->get('reset_subscriber')->onKernelTerminate();

        $this->assertEquals(1, ResettableService::$counter);
        $this->assertEquals(0, ClearableService::$counter);
    }

    public function testResetServicesTwice()
    {
        $container = $this->buildContainer();
        $container->get('one');
        $container->get('reset_subscriber')->onKernelTerminate();
        $container->get('two');
        $container->get('reset_subscriber')->onKernelTerminate();

        $this->assertEquals(2, ResettableService::$counter);
        $this->assertEquals(1, ClearableService::$counter);
    }

    /**
     * @return ContainerBuilder
     */
    private function buildContainer()
    {
        $container = new ContainerBuilder();
        $container->register('one', ResettableService::class)->setPublic(true);
        $container->register('two', ClearableService::class)->setPublic(true);

        $container->register('reset_subscriber', ServiceResetListener::class)
            ->setPublic(true)
            ->addArgument(new IteratorArgument(array(
                'one' => new Reference('one', ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE),
                'two' => new Reference('two', ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE),
            )))
            ->addArgument(array(
                'one' => 'reset',
                'two' => 'clear',
            ));

        $container->compile();

        return $container;
    }
}