text:
import { state } from './state.js';
import { store } from './store.js';
import { selectedTodo } from './selection.js';
import { Todo } from './Todo.js';

const selectNext = function () {
    const list = state.get('todos');
    const index = selectedTodo.get('index') + 1;
    if (index < list.get('length')) {
        selectedTodo.set('index', index);
    }
};

const selectPrevious = function () {
    const index = selectedTodo.get('index');
    if (index > 0) {
        selectedTodo.set('index', index - 1);
    }
};

const create = function () {
    // Create todo
    const todos = state.get('todos');
    const selectedIndex = selectedTodo.get('index');
    const newTodo = new Todo(store);

    // Assign to the currently selected list.
    newTodo.set('list', state.get('list').getDoppelganger(store));

    // Place just after selected todo, or at end of list if none selected
    this.reorderTodo(
        todos,
        newTodo,
        selectedIndex > -1 ? selectedIndex + 1 : todos.get('length'),
    );
    newTodo.saveToStore();

    // Select new todo
    selectedTodo.set('record', newTodo);
    state.set('editTodo', newTodo);
};

const reorderTodo = function (list, todo, toIndex) {
    const index = list.indexOf(todo);
    let prev;
    let next;
    let prevPrec;
    let nextPrec;
    let i;
    let p;
    let l;
    let otherTodo;

    if (index === toIndex) {
        return;
    }
    if (-1 < index && index < toIndex) {
        prev = list.getObjectAt(toIndex);
        next = list.getObjectAt(toIndex + 1) || null;
    } else {
        prev = toIndex ? list.getObjectAt(toIndex - 1) : null;
        next = list.getObjectAt(toIndex);
    }

    prevPrec = prev ? prev.get('precedence') : 0;
    nextPrec = next ? next.get('precedence') : (toIndex + 2) * 32;

    if (nextPrec - prevPrec < 2) {
        for (i = 0, p = 32, l = list.get('length'); i < l; i += 1, p += 32) {
            otherTodo = list.getObjectAt(i);
            if (otherTodo !== todo) {
                otherTodo.set('precedence', p);
                if (otherTodo === prev) {
                    p += 32;
                }
            }
        }
        if (prev) {
            prevPrec = prev.get('precedence');
        }
        if (next) {
            nextPrec = next.get('precedence');
        }
    }
    todo.set('precedence', (nextPrec + prevPrec) >> 1);
};

const toggleComplete = function () {
    const todo = selectedTodo.get('record');
    if (todo) {
        todo.toggle('isComplete');
    }
};

const edit = function () {
    const todo = selectedTodo.get('record');
    if (todo) {
        state.set('editTodo', todo);
    }
};

const destroy = function () {
    const todo = selectedTodo.get('record');
    if (todo) {
        todo.destroy();
    }
    store.commitChanges();
};

const actions = {
    selectNext,
    selectPrevious,
    create,
    reorderTodo,
    toggleComplete,
    edit,
    destroy,
};

export { actions };


text:
package net.meiolania.apps.habrahabr.fragments.companies;

import net.meiolania.apps.habrahabr.R;
import net.meiolania.apps.habrahabr.data.CompanyFullData;
import net.meiolania.apps.habrahabr.fragments.companies.loader.CompaniesShowLoader;
import net.meiolania.apps.habrahabr.utils.ConnectionUtils;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;

public class CompaniesShowFragment extends SherlockFragment implements LoaderCallbacks<CompanyFullData> {
    public final static String URL_ARGUMENT = "url";
    public final static int LOADER_COMPANY = 0;
    private String url;
    private ProgressDialog progressDialog;
    private String companyUrl;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setHasOptionsMenu(true);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
	super.onActivityCreated(savedInstanceState);

	url = getArguments().getString(URL_ARGUMENT);

	setRetainInstance(true);

	if (ConnectionUtils.isConnected(getSherlockActivity()))
	    getSherlockActivity().getSupportLoaderManager().initLoader(LOADER_COMPANY, null, this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
	return inflater.inflate(R.layout.companies_show_activity, container, false);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
	super.onCreateOptionsMenu(menu, inflater);

	inflater.inflate(R.menu.companies_show_fragment, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
	switch (item.getItemId()) {
	    case R.id.go_to_website:
		Uri uri = Uri.parse(companyUrl);
		Intent intent = new Intent(Intent.ACTION_VIEW, uri);
		startActivity(intent);
		return true;
	}
	return super.onOptionsItemSelected(item);
    }

    @Override
    public Loader<CompanyFullData> onCreateLoader(int id, Bundle args) {
	showProgressDialog();

	CompaniesShowLoader loader = new CompaniesShowLoader(getSherlockActivity(), url);
	loader.forceLoad();

	return loader;
    }

    @Override
    public void onLoadFinished(Loader<CompanyFullData> loader, CompanyFullData data) {
	SherlockFragmentActivity activity = getSherlockActivity();

	if (activity != null && data != null) {
	    ActionBar actionBar = activity.getSupportActionBar();
	    actionBar.setTitle(data.getCompanyName());
	    actionBar.setSubtitle(data.getDate());

	    /* Company website */
	    companyUrl = data.getCompanyUrl();

	    /* Industries */
	    TextView industriesDivider = (TextView) activity.findViewById(R.id.company_industries_divider);
	    TextView industries = (TextView) activity.findViewById(R.id.company_industries);

	    if (data.getIndustries().length() > 0)
		industries.setText(data.getIndustries());
	    else {
		industriesDivider.setVisibility(View.GONE);
		industries.setVisibility(View.GONE);
	    }

	    /* Location */
	    TextView locationDivider = (TextView) activity.findViewById(R.id.company_location_divider);
	    TextView location = (TextView) activity.findViewById(R.id.company_location);

	    if (data.getLocation().length() > 0)
		location.setText(data.getLocation());
	    else {
		locationDivider.setVisibility(View.GONE);
		location.setVisibility(View.GONE);
	    }

	    /* Quantity */
	    TextView quantityDivider = (TextView) activity.findViewById(R.id.company_quantity_divider);
	    TextView quantity = (TextView) activity.findViewById(R.id.company_quantity);

	    if (data.getQuantity().length() > 0)
		quantity.setText(data.getQuantity());
	    else {
		quantityDivider.setVisibility(View.GONE);
		quantity.setVisibility(View.GONE);
	    }

	    /* Summary */
	    TextView summaryDivider = (TextView) activity.findViewById(R.id.company_summary_divider);
	    WebView summary = (WebView) activity.findViewById(R.id.company_summary);

	    if (data.getSummary().length() > 0)
		summary.loadDataWithBaseURL("", data.getSummary(), "text/html", "UTF-8", null);
	    else {
		summaryDivider.setVisibility(View.GONE);
		summary.setVisibility(View.GONE);
	    }

	    /* Management */
	    TextView managementDivider = (TextView) activity.findViewById(R.id.company_management_divider);
	    WebView management = (WebView) activity.findViewById(R.id.company_management);

	    if (data.getManagement().length() > 0)
		management.loadDataWithBaseURL("", data.getManagement(), "text/html", "UTF-8", null);
	    else {
		managementDivider.setVisibility(View.GONE);
		management.setVisibility(View.GONE);
	    }

	    /* Development stages */
	    TextView developmentStagesDivider = (TextView) activity.findViewById(R.id.company_development_stages_divider);
	    WebView developmentStages = (WebView) activity.findViewById(R.id.company_development_stages);

	    if (data.getDevelopmentStages().length() > 0)
		developmentStages.loadDataWithBaseURL("", data.getDevelopmentStages(), "text/html", "UTF-8", null);
	    else {
		developmentStagesDivider.setVisibility(View.GONE);
		developmentStages.setVisibility(View.GONE);
	    }
	}

	hideProgressDialog();
    }

    @Override
    public void onLoaderReset(Loader<CompanyFullData> loader) {

    }

    private void showProgressDialog() {
	progressDialog = new ProgressDialog(getSherlockActivity());
	progressDialog.setMessage(getString(R.string.loading_company));
	progressDialog.setCancelable(true);
	progressDialog.show();
    }

    private void hideProgressDialog() {
	if (progressDialog != null)
	    progressDialog.dismiss();
    }

}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.provisionr.amazon.functions;

import com.amazonaws.services.ec2.model.IpPermission;
import com.google.common.base.Function;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.getOnlyElement;
import org.apache.provisionr.api.network.Protocol;
import org.apache.provisionr.api.network.Rule;
import org.apache.provisionr.api.network.RuleBuilder;

public enum ConvertIpPermissionToRule implements Function<IpPermission, Rule> {
    FUNCTION;

    @Override
    public Rule apply(IpPermission ipPermission) {
        checkNotNull(ipPermission, "ipPermission is null");

        final RuleBuilder builder = Rule.builder().cidr(getOnlyElement(ipPermission.getIpRanges()))
            .protocol(Protocol.valueOf(ipPermission.getIpProtocol().toUpperCase()));

        if (!ipPermission.getIpProtocol().equalsIgnoreCase("icmp")) {
            builder.ports(ipPermission.getFromPort(), ipPermission.getToPort());
        }

        return builder.createRule();
    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Alonsoa acutifolia Ruiz & Pav.

### Remarks
null


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>basic_stream::rate_policy</title>
<link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../index.html" title="Chapter 1. Boost.Beast">
<link rel="up" href="../boost__beast__basic_stream.html" title="basic_stream">
<link rel="prev" href="release_socket.html" title="basic_stream::release_socket">
<link rel="next" href="rate_policy/overload1.html" title="basic_stream::rate_policy (1 of 2 overloads)">

Home
Libraries
People
FAQ
More

basic_stream::rate_policy

          Returns the rate policy associated with the object.

RatePolicy&
rate_policy();
  » more...

RatePolicy const&
rate_policy() const;
  » more...

Copyright © 2016-2019 Vinnie
      Falco

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


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

// A simulated network for use within NaCl.
// The simulation is not particularly tied to NaCl,
// but other systems have real networks.

package syscall

import (
	"sync"
	"sync/atomic"
)

// Interface to timers implemented in package runtime.
// Must be in sync with ../runtime/runtime.h:/^struct.Timer$
// Really for use by package time, but we cannot import time here.

type runtimeTimer struct {
	i      int32
	when   int64
	period int64
	f      func(int64, interface{}) // NOTE: must not be closure
	arg    interface{}
}

func startTimer(*runtimeTimer)
func stopTimer(*runtimeTimer) bool

type timer struct {
	expired bool
	q       *queue
	r       runtimeTimer
}

func (t *timer) start(q *queue, deadline int64) {
	if deadline == 0 {
		return
	}
	t.q = q
	t.r.when = deadline
	t.r.f = timerExpired
	t.r.arg = t
	startTimer(&t.r)
}

func (t *timer) stop() {
	stopTimer(&t.r)
}

func timerExpired(now int64, i interface{}) {
	t := i.(*timer)
	go func() {
		t.q.Lock()
		defer t.q.Unlock()
		t.expired = true
		t.q.canRead.Broadcast()
		t.q.canWrite.Broadcast()
	}()
}

// Network constants and data structures. These match the traditional values.

const (
	AF_UNSPEC = iota
	AF_UNIX
	AF_INET
	AF_INET6
)

const (
	SHUT_RD = iota
	SHUT_WR
	SHUT_RDWR
)

const (
	SOCK_STREAM = 1 + iota
	SOCK_DGRAM
	SOCK_RAW
	SOCK_SEQPACKET
)

const (
	IPPROTO_IP   = 0
	IPPROTO_IPV4 = 4
	IPPROTO_IPV6 = 0x29
	IPPROTO_TCP  = 6
	IPPROTO_UDP  = 0x11
)

// Misc constants expected by package net but not supported.
const (
	_ = iota
	SOL_SOCKET
	SO_TYPE
	NET_RT_IFLIST
	IFNAMSIZ
	IFF_UP
	IFF_BROADCAST
	IFF_LOOPBACK
	IFF_POINTOPOINT
	IFF_MULTICAST
	IPV6_V6ONLY
	SOMAXCONN
	F_DUPFD_CLOEXEC
	SO_BROADCAST
	SO_REUSEADDR
	SO_REUSEPORT
	SO_RCVBUF
	SO_SNDBUF
	SO_KEEPALIVE
	SO_LINGER
	SO_ERROR
	IP_PORTRANGE
	IP_PORTRANGE_DEFAULT
	IP_PORTRANGE_LOW
	IP_PORTRANGE_HIGH
	IP_MULTICAST_IF
	IP_MULTICAST_LOOP
	IP_ADD_MEMBERSHIP
	IPV6_PORTRANGE
	IPV6_PORTRANGE_DEFAULT
	IPV6_PORTRANGE_LOW
	IPV6_PORTRANGE_HIGH
	IPV6_MULTICAST_IF
	IPV6_MULTICAST_LOOP
	IPV6_JOIN_GROUP
	TCP_NODELAY
	TCP_KEEPINTVL
	TCP_KEEPIDLE

	SYS_FCNTL = 500 // unsupported
)

var SocketDisableIPv6 bool

// A Sockaddr is one of the SockaddrXxx structs.
type Sockaddr interface {
	// copy returns a copy of the underlying data.
	copy() Sockaddr

	// key returns the value of the underlying data,
	// for comparison as a map key.
	key() interface{}
}

type SockaddrInet4 struct {
	Port int
	Addr [4]byte
}

func (sa *SockaddrInet4) copy() Sockaddr {
	sa1 := *sa
	return &sa1
}

func (sa *SockaddrInet4) key() interface{} { return *sa }

type SockaddrInet6 struct {
	Port   int
	ZoneId uint32
	Addr   [16]byte
}

func (sa *SockaddrInet6) copy() Sockaddr {
	sa1 := *sa
	return &sa1
}

func (sa *SockaddrInet6) key() interface{} { return *sa }

type SockaddrUnix struct {
	Name string
}

func (sa *SockaddrUnix) copy() Sockaddr {
	sa1 := *sa
	return &sa1
}

func (sa *SockaddrUnix) key() interface{} { return *sa }

type SockaddrDatalink struct {
	Len    uint8
	Family uint8
	Index  uint16
	Type   uint8
	Nlen   uint8
	Alen   uint8
	Slen   uint8
	Data   [12]int8
}

func (sa *SockaddrDatalink) copy() Sockaddr {
	sa1 := *sa
	return &sa1
}

func (sa *SockaddrDatalink) key() interface{} { return *sa }

// RoutingMessage represents a routing message.
type RoutingMessage interface {
	unimplemented()
}

type IPMreq struct {
	Multiaddr [4]byte /* in_addr */
	Interface [4]byte /* in_addr */
}

type IPv6Mreq struct {
	Multiaddr [16]byte /* in6_addr */
	Interface uint32
}

type Linger struct {
	Onoff  int32
	Linger int32
}

type ICMPv6Filter struct {
	Filt [8]uint32
}

// A queue is the bookkeeping for a synchronized buffered queue.
// We do not use channels because we need to be able to handle
// writes after and during close, and because a chan byte would
// require too many send and receive operations in real use.
type queue struct {
	sync.Mutex
	canRead  sync.Cond
	canWrite sync.Cond
	r        int // total read index
	w        int // total write index
	m        int // index mask
	closed   bool
}

func (q *queue) init(size int) {
	if size&(size-1) != 0 {
		panic("invalid queue size - must be power of two")
	}
	q.canRead.L = &q.Mutex
	q.canWrite.L = &q.Mutex
	q.m = size - 1
}

func past(deadline int64) bool {
	sec, nsec := now()
	return deadline > 0 && deadline < sec*1e9+int64(nsec)
}

func (q *queue) waitRead(n int, deadline int64) (int, error) {
	if past(deadline) {
		return 0, EAGAIN
	}
	var t timer
	t.start(q, deadline)
	for q.w-q.r == 0 && !q.closed && !t.expired {
		q.canRead.Wait()
	}
	t.stop()
	m := q.w - q.r
	if m == 0 && t.expired {
		return 0, EAGAIN
	}
	if m > n {
		m = n
		q.canRead.Signal() // wake up next reader too
	}
	q.canWrite.Signal()
	return m, nil
}

func (q *queue) waitWrite(n int, deadline int64) (int, error) {
	if past(deadline) {
		return 0, EAGAIN
	}
	var t timer
	t.start(q, deadline)
	for q.w-q.r > q.m && !q.closed && !t.expired {
		q.canWrite.Wait()
	}
	t.stop()
	m := q.m + 1 - (q.w - q.r)
	if m == 0 && t.expired {
		return 0, EAGAIN
	}
	if m == 0 {
		return 0, EAGAIN
	}
	if m > n {
		m = n
		q.canWrite.Signal() // wake up next writer too
	}
	q.canRead.Signal()
	return m, nil
}

func (q *queue) close() {
	q.Lock()
	defer q.Unlock()
	q.closed = true
	q.canRead.Broadcast()
	q.canWrite.Broadcast()
}

// A byteq is a byte queue.
type byteq struct {
	queue
	data []byte
}

func newByteq() *byteq {
	q := &byteq{
		data: make([]byte, 4096),
	}
	q.init(len(q.data))
	return q
}

func (q *byteq) read(b []byte, deadline int64) (int, error) {
	q.Lock()
	defer q.Unlock()
	n, err := q.waitRead(len(b), deadline)
	if err != nil {
		return 0, err
	}
	b = b[:n]
	for len(b) > 0 {
		m := copy(b, q.data[q.r&q.m:])
		q.r += m
		b = b[m:]
	}
	return n, nil
}

func (q *byteq) write(b []byte, deadline int64) (n int, err error) {
	q.Lock()
	defer q.Unlock()
	for n < len(b) {
		nn, err := q.waitWrite(len(b[n:]), deadline)
		if err != nil {
			return n, err
		}
		bb := b[n : n+nn]
		n += nn
		for len(bb) > 0 {
			m := copy(q.data[q.w&q.m:], bb)
			q.w += m
			bb = bb[m:]
		}
	}
	return n, nil
}

// A msgq is a queue of messages.
type msgq struct {
	queue
	data []interface{}
}

func newMsgq() *msgq {
	q := &msgq{
		data: make([]interface{}, 32),
	}
	q.init(len(q.data))
	return q
}

func (q *msgq) read(deadline int64) (interface{}, error) {
	q.Lock()
	defer q.Unlock()
	n, err := q.waitRead(1, deadline)
	if err != nil {
		return nil, err
	}
	if n == 0 {
		return nil, nil
	}
	m := q.data[q.r&q.m]
	q.r++
	return m, nil
}

func (q *msgq) write(m interface{}, deadline int64) error {
	q.Lock()
	defer q.Unlock()
	_, err := q.waitWrite(1, deadline)
	if err != nil {
		return err
	}
	q.data[q.w&q.m] = m
	q.w++
	return nil
}

// An addr is a sequence of bytes uniquely identifying a network address.
// It is not human-readable.
type addr string

// A conn is one side of a stream-based network connection.
// That is, a stream-based network connection is a pair of cross-connected conns.
type conn struct {
	rd     *byteq
	wr     *byteq
	local  addr
	remote addr
}

// A pktconn is one side of a packet-based network connection.
// That is, a packet-based network connection is a pair of cross-connected pktconns.
type pktconn struct {
	rd     *msgq
	wr     *msgq
	local  addr
	remote addr
}

// A listener accepts incoming stream-based network connections.
type listener struct {
	rd    *msgq
	local addr
}

// A netFile is an open network file.
type netFile struct {
	defaultFileImpl
	proto      *netproto
	sotype     int
	listener   *msgq
	packet     *msgq
	rd         *byteq
	wr         *byteq
	rddeadline int64
	wrdeadline int64
	addr       Sockaddr
	raddr      Sockaddr
}

// A netAddr is a network address in the global listener map.
// All the fields must have defined == operations.
type netAddr struct {
	proto  *netproto
	sotype int
	addr   interface{}
}

// net records the state of the network.
// It maps a network address to the listener on that address.
var net = struct {
	sync.Mutex
	listener map[netAddr]*netFile
}{
	listener: make(map[netAddr]*netFile),
}

// TODO(rsc): Some day, do a better job with port allocation.
// For playground programs, incrementing is fine.
var nextport = 2

// A netproto contains protocol-specific functionality
// (one for AF_INET, one for AF_INET6 and so on).
// It is a struct instead of an interface because the
// implementation needs no state, and I expect to
// add some data fields at some point.
type netproto struct {
	bind func(*netFile, Sockaddr) error
}

var netprotoAF_INET = &netproto{
	bind: func(f *netFile, sa Sockaddr) error {
		if sa == nil {
			f.addr = &SockaddrInet4{
				Port: nextport,
				Addr: [4]byte{127, 0, 0, 1},
			}
			nextport++
			return nil
		}
		addr, ok := sa.(*SockaddrInet4)
		if !ok {
			return EINVAL
		}
		addr = addr.copy().(*SockaddrInet4)
		if addr.Port == 0 {
			addr.Port = nextport
			nextport++
		}
		f.addr = addr
		return nil
	},
}

var netprotos = map[int]*netproto{
	AF_INET: netprotoAF_INET,
}

// These functions implement the usual BSD socket operations.

func (f *netFile) bind(sa Sockaddr) error {
	if f.addr != nil {
		return EISCONN
	}
	if err := f.proto.bind(f, sa); err != nil {
		return err
	}
	if f.sotype == SOCK_DGRAM {
		_, ok := net.listener[netAddr{f.proto, f.sotype, f.addr.key()}]
		if ok {
			f.addr = nil
			return EADDRINUSE
		}
		net.listener[netAddr{f.proto, f.sotype, f.addr.key()}] = f
		f.packet = newMsgq()
	}
	return nil
}

func (f *netFile) listen(backlog int) error {
	net.Lock()
	defer net.Unlock()
	if f.listener != nil {
		return EINVAL
	}
	_, ok := net.listener[netAddr{f.proto, f.sotype, f.addr.key()}]
	if ok {
		return EADDRINUSE
	}
	net.listener[netAddr{f.proto, f.sotype, f.addr.key()}] = f
	f.listener = newMsgq()
	return nil
}

func (f *netFile) accept() (fd int, sa Sockaddr, err error) {
	msg, err := f.listener.read(f.readDeadline())
	if err != nil {
		return -1, nil, err
	}
	newf, ok := msg.(*netFile)
	if !ok {
		// must be eof
		return -1, nil, EAGAIN
	}
	return newFD(newf), newf.raddr.copy(), nil
}

func (f *netFile) connect(sa Sockaddr) error {
	if past(f.writeDeadline()) {
		return EAGAIN
	}
	if f.addr == nil {
		if err := f.bind(nil); err != nil {
			return err
		}
	}
	net.Lock()
	if sa == nil {
		net.Unlock()
		return EINVAL
	}
	sa = sa.copy()
	if f.raddr != nil {
		net.Unlock()
		return EISCONN
	}
	if f.sotype == SOCK_DGRAM {
		net.Unlock()
		f.raddr = sa
		return nil
	}
	if f.listener != nil {
		net.Unlock()
		return EISCONN
	}
	l, ok := net.listener[netAddr{f.proto, f.sotype, sa.key()}]
	if !ok {
		net.Unlock()
		return ECONNREFUSED
	}
	f.raddr = sa
	f.rd = newByteq()
	f.wr = newByteq()
	newf := &netFile{
		proto:  f.proto,
		sotype: f.sotype,
		addr:   f.raddr,
		raddr:  f.addr,
		rd:     f.wr,
		wr:     f.rd,
	}
	net.Unlock()
	l.listener.write(newf, f.writeDeadline())
	return nil
}

func (f *netFile) read(b []byte) (int, error) {
	if f.rd == nil {
		if f.raddr != nil {
			n, _, err := f.recvfrom(b, 0)
			return n, err
		}
		return 0, ENOTCONN
	}
	return f.rd.read(b, f.readDeadline())
}

func (f *netFile) write(b []byte) (int, error) {
	if f.wr == nil {
		if f.raddr != nil {
			err := f.sendto(b, 0, f.raddr)
			var n int
			if err == nil {
				n = len(b)
			}
			return n, err
		}
		return 0, ENOTCONN
	}
	return f.wr.write(b, f.writeDeadline())
}

type pktmsg struct {
	buf  []byte
	addr Sockaddr
}

func (f *netFile) recvfrom(p []byte, flags int) (n int, from Sockaddr, err error) {
	if f.sotype != SOCK_DGRAM {
		return 0, nil, EINVAL
	}
	if f.packet == nil {
		return 0, nil, ENOTCONN
	}
	msg1, err := f.packet.read(f.readDeadline())
	if err != nil {
		return 0, nil, err
	}
	msg, ok := msg1.(*pktmsg)
	if !ok {
		return 0, nil, EAGAIN
	}
	return copy(p, msg.buf), msg.addr, nil
}

func (f *netFile) sendto(p []byte, flags int, to Sockaddr) error {
	if f.sotype != SOCK_DGRAM {
		return EINVAL
	}
	if f.packet == nil {
		if err := f.bind(nil); err != nil {
			return err
		}
	}
	net.Lock()
	if to == nil {
		net.Unlock()
		return EINVAL
	}
	to = to.copy()
	l, ok := net.listener[netAddr{f.proto, f.sotype, to.key()}]
	if !ok || l.packet == nil {
		net.Unlock()
		return ECONNREFUSED
	}
	net.Unlock()
	msg := &pktmsg{
		buf:  make([]byte, len(p)),
		addr: f.addr,
	}
	copy(msg.buf, p)
	l.packet.write(msg, f.writeDeadline())
	return nil
}

func (f *netFile) close() error {
	if f.listener != nil {
		f.listener.close()
	}
	if f.packet != nil {
		f.packet.close()
	}
	if f.rd != nil {
		f.rd.close()
	}
	if f.wr != nil {
		f.wr.close()
	}
	return nil
}

func fdToNetFile(fd int) (*netFile, error) {
	f, err := fdToFile(fd)
	if err != nil {
		return nil, err
	}
	impl := f.impl
	netf, ok := impl.(*netFile)
	if !ok {
		return nil, EINVAL
	}
	return netf, nil
}

func Socket(proto, sotype, unused int) (fd int, err error) {
	p := netprotos[proto]
	if p == nil {
		return -1, EPROTONOSUPPORT
	}
	if sotype != SOCK_STREAM && sotype != SOCK_DGRAM {
		return -1, ESOCKTNOSUPPORT
	}
	f := &netFile{
		proto:  p,
		sotype: sotype,
	}
	return newFD(f), nil
}

func Bind(fd int, sa Sockaddr) error {
	f, err := fdToNetFile(fd)
	if err != nil {
		return err
	}
	return f.bind(sa)
}

func StopIO(fd int) error {
	f, err := fdToNetFile(fd)
	if err != nil {
		return err
	}
	f.close()
	return nil
}

func Listen(fd int, backlog int) error {
	f, err := fdToNetFile(fd)
	if err != nil {
		return err
	}
	return f.listen(backlog)
}

func Accept(fd int) (newfd int, sa Sockaddr, err error) {
	f, err := fdToNetFile(fd)
	if err != nil {
		return 0, nil, err
	}
	return f.accept()
}

func Getsockname(fd int) (sa Sockaddr, err error) {
	f, err := fdToNetFile(fd)
	if err != nil {
		return nil, err
	}
	if f.addr == nil {
		return nil, ENOTCONN
	}
	return f.addr.copy(), nil
}

func Getpeername(fd int) (sa Sockaddr, err error) {
	f, err := fdToNetFile(fd)
	if err != nil {
		return nil, err
	}
	if f.raddr == nil {
		return nil, ENOTCONN
	}
	return f.raddr.copy(), nil
}

func Connect(fd int, sa Sockaddr) error {
	f, err := fdToNetFile(fd)
	if err != nil {
		return err
	}
	return f.connect(sa)
}

func Recvfrom(fd int, p []byte, flags int) (n int, from Sockaddr, err error) {
	f, err := fdToNetFile(fd)
	if err != nil {
		return 0, nil, err
	}
	return f.recvfrom(p, flags)
}

func Sendto(fd int, p []byte, flags int, to Sockaddr) error {
	f, err := fdToNetFile(fd)
	if err != nil {
		return err
	}
	return f.sendto(p, flags, to)
}

func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn, recvflags int, from Sockaddr, err error) {
	f, err := fdToNetFile(fd)
	if err != nil {
		return
	}
	n, from, err = f.recvfrom(p, flags)
	return
}

func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) error {
	_, err := SendmsgN(fd, p, oob, to, flags)
	return err
}

func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) {
	f, err := fdToNetFile(fd)
	if err != nil {
		return 0, err
	}
	switch f.sotype {
	case SOCK_STREAM:
		n, err = f.write(p)
	case SOCK_DGRAM:
		n = len(p)
		err = f.sendto(p, flags, to)
	}
	if err != nil {
		return 0, err
	}
	return n, nil
}

func GetsockoptInt(fd, level, opt int) (value int, err error) {
	f, err := fdToNetFile(fd)
	if err != nil {
		return 0, err
	}
	switch {
	case level == SOL_SOCKET && opt == SO_TYPE:
		return f.sotype, nil
	}
	return 0, ENOTSUP
}

func SetsockoptInt(fd, level, opt int, value int) error {
	return nil
}

func SetsockoptByte(fd, level, opt int, value byte) error {
	_, err := fdToNetFile(fd)
	if err != nil {
		return err
	}
	return ENOTSUP
}

func SetsockoptLinger(fd, level, opt int, l *Linger) error {
	return nil
}

func SetReadDeadline(fd int, t int64) error {
	f, err := fdToNetFile(fd)
	if err != nil {
		return err
	}
	atomic.StoreInt64(&f.rddeadline, t)
	return nil
}

func (f *netFile) readDeadline() int64 {
	return atomic.LoadInt64(&f.rddeadline)
}

func SetWriteDeadline(fd int, t int64) error {
	f, err := fdToNetFile(fd)
	if err != nil {
		return err
	}
	atomic.StoreInt64(&f.wrdeadline, t)
	return nil
}

func (f *netFile) writeDeadline() int64 {
	return atomic.LoadInt64(&f.wrdeadline)
}

func Shutdown(fd int, how int) error {
	f, err := fdToNetFile(fd)
	if err != nil {
		return err
	}
	switch how {
	case SHUT_RD:
		f.rd.close()
	case SHUT_WR:
		f.wr.close()
	case SHUT_RDWR:
		f.rd.close()
		f.wr.close()
	}
	return nil
}

func SetsockoptICMPv6Filter(fd, level, opt int, filter *ICMPv6Filter) error { panic("SetsockoptICMPv") }
func SetsockoptIPMreq(fd, level, opt int, mreq *IPMreq) error               { panic("SetsockoptIPMreq") }
func SetsockoptIPv6Mreq(fd, level, opt int, mreq *IPv6Mreq) error           { panic("SetsockoptIPv") }
func SetsockoptInet4Addr(fd, level, opt int, value [4]byte) error           { panic("SetsockoptInet") }
func SetsockoptString(fd, level, opt int, s string) error                   { panic("SetsockoptString") }
func SetsockoptTimeval(fd, level, opt int, tv *Timeval) error               { panic("SetsockoptTimeval") }
func Socketpair(domain, typ, proto int) (fd [2]int, err error)              { panic("Socketpair") }

func SetNonblock(fd int, nonblocking bool) error { return nil }


text:
function notify(level, msg) {
  $(".alert").remove();
  var div = $('
' + msg + '
');
  $("#page-wrapper").prepend(div);
  div.delay(6000).fadeOut();
}

// from dooley's implementation
if (document.querySelector("div.panel-primary")) {
  setTimeout(async() => {
    const res = await fetch("/api/stats", { method: "GET" });
    const stats = await res.json();
    const color = {
      messages: "primary",
      guilds: "green",
      users: "yellow",
      channels: "red"
    };
    for (const key in stats) {
      $(`div.panel-${color[key]} .huge`).text(stats[key]);
    }
  }, 1500);
}


text:
package loader

import (
	"fmt"

	"go/ast"
	"strconv"
	"sync"
)

// NB(directxman12): most of this is done by the typechecker,
// but it's a bit slow/heavyweight for what we want -- we want
// to resolve external imports *only* if we actually need them.

// Basically, what we do is:
// 1. Map imports to names
// 2. Find all explicit external references (`name.type`)
// 3. Find all referenced packages by merging explicit references and dot imports
// 4. Only type-check those packages
// 5. Ignore type-checking errors from the missing packages, because we won't ever
//    touch unloaded types (they're probably used in ignored fields/types, variables, or functions)
//    (done using PrintErrors with an ignore argument from the caller).
// 6. Notice any actual type-checking errors via invalid types

// importsMap saves import aliases, mapping them to underlying packages.
type importsMap struct {
	// dotImports maps package IDs to packages for any packages that have/ been imported as `.`
	dotImports map[string]*Package
	// byName maps package aliases or names to the underlying package.
	byName map[string]*Package
}

// mapImports maps imports from the names they use in the given file to the underlying package,
// using a map of package import paths to packages (generally from Package.Imports()).
func mapImports(file *ast.File, importedPkgs map[string]*Package) (*importsMap, error) {
	m := &importsMap{
		dotImports: make(map[string]*Package),
		byName:     make(map[string]*Package),
	}
	for _, importSpec := range file.Imports {
		path, err := strconv.Unquote(importSpec.Path.Value)
		if err != nil {
			return nil, ErrFromNode(err, importSpec.Path)
		}
		importedPkg := importedPkgs[path]
		if importedPkg == nil {
			return nil, ErrFromNode(fmt.Errorf("no such package located"), importSpec.Path)
		}
		if importSpec.Name == nil {
			m.byName[importedPkg.Name] = importedPkg
			continue
		}
		if importSpec.Name.Name == "." {
			m.dotImports[importedPkg.ID] = importedPkg
			continue
		}
		m.byName[importSpec.Name.Name] = importedPkg
	}

	return m, nil
}

// referenceSet finds references to external packages' types in the given file,
// without otherwise calling into the type-checker.  When checking structs,
// it only checks fields with JSON tags.
type referenceSet struct {
	file    *ast.File
	imports *importsMap
	pkg     *Package

	externalRefs map[*Package]struct{}
}

func (r *referenceSet) init() {
	if r.externalRefs == nil {
		r.externalRefs = make(map[*Package]struct{})
	}
}

// NodeFilter filters nodes, accepting them for reference collection
// when true is returned and rejecting them when false is returned.
type NodeFilter func(ast.Node) bool

// collectReferences saves all references to external types in the given info.
func (r *referenceSet) collectReferences(rawType ast.Expr, filterNode NodeFilter) {
	r.init()
	col := &referenceCollector{
		refs:       r,
		filterNode: filterNode,
	}
	ast.Walk(col, rawType)
}

// external saves an external reference to the given named package.
func (r *referenceSet) external(pkgName string) {
	pkg := r.imports.byName[pkgName]
	if pkg == nil {
		r.pkg.AddError(fmt.Errorf("use of unimported package %q", pkgName))
		return
	}
	r.externalRefs[pkg] = struct{}{}
}

// referenceCollector visits nodes in an AST, adding external references to a
// referenceSet.
type referenceCollector struct {
	refs       *referenceSet
	filterNode NodeFilter
}

func (c *referenceCollector) Visit(node ast.Node) ast.Visitor {
	if !c.filterNode(node) {
		return nil
	}
	switch typedNode := node.(type) {
	case *ast.Ident:
		// local reference or dot-import, ignore
		return nil
	case *ast.SelectorExpr:
		pkgName := typedNode.X.(*ast.Ident).Name
		c.refs.external(pkgName)
		return nil
	default:
		return c
	}
}

// allReferencedPackages finds all directly referenced packages in the given package.
func allReferencedPackages(pkg *Package, filterNodes NodeFilter) []*Package {
	pkg.NeedSyntax()
	refsByFile := make(map[*ast.File]*referenceSet)
	for _, file := range pkg.Syntax {
		imports, err := mapImports(file, pkg.Imports())
		if err != nil {
			pkg.AddError(err)
			return nil
		}
		refs := &referenceSet{
			file:    file,
			imports: imports,
			pkg:     pkg,
		}
		refsByFile[file] = refs
	}

	EachType(pkg, func(file *ast.File, decl *ast.GenDecl, spec *ast.TypeSpec) {
		refs := refsByFile[file]
		refs.collectReferences(spec.Type, filterNodes)
	})

	allPackages := make(map[*Package]struct{})
	for _, refs := range refsByFile {
		for _, pkg := range refs.imports.dotImports {
			allPackages[pkg] = struct{}{}
		}
		for ref := range refs.externalRefs {
			allPackages[ref] = struct{}{}
		}
	}

	res := make([]*Package, 0, len(allPackages))
	for pkg := range allPackages {
		res = append(res, pkg)
	}
	return res
}

// TypeChecker performs type-checking on a limitted subset of packages by
// checking each package's types' externally-referenced types, and only
// type-checking those packages.
type TypeChecker struct {
	// NodeFilters are used to filter the set of references that are followed
	// when typechecking.  If any of the filters returns true for a given node,
	// its package will be added to the set of packages to check.
	//
	// If no filters are specified, all references are followed (this may be slow).
	//
	// Modifying this after the first call to check may yield strange/invalid
	// results.
	NodeFilters []NodeFilter

	checkedPackages map[*Package]struct{}
	sync.Mutex
}

// Check type-checks the given package and all packages referenced by types
// that pass through (have true returned by) any of the NodeFilters.
func (c *TypeChecker) Check(root *Package) {
	c.init()

	// use a sub-checker with the appropriate settings
	(&TypeChecker{
		NodeFilters:     c.NodeFilters,
		checkedPackages: c.checkedPackages,
	}).check(root)
}

func (c *TypeChecker) isNodeInteresting(node ast.Node) bool {
	// no filters --> everything is important
	if len(c.NodeFilters) == 0 {
		return true
	}

	// otherwise, passing through any one filter means this node is important
	for _, filter := range c.NodeFilters {
		if filter(node) {
			return true
		}
	}
	return false
}

func (c *TypeChecker) init() {
	if c.checkedPackages == nil {
		c.checkedPackages = make(map[*Package]struct{})
	}
}

// check recursively type-checks the given package, only loading packages that
// are actually referenced by our types (it's the actual implementation of Check,
// without initialization).
func (c *TypeChecker) check(root *Package) {
	root.Lock()
	defer root.Unlock()

	c.Lock()
	_, ok := c.checkedPackages[root]
	c.Unlock()
	if ok {
		return
	}

	refedPackages := allReferencedPackages(root, c.isNodeInteresting)

	// first, resolve imports for all leaf packages...
	var wg sync.WaitGroup
	for _, pkg := range refedPackages {
		wg.Add(1)
		go func(pkg *Package) {
			defer wg.Done()
			c.check(pkg)
		}(pkg)
	}
	wg.Wait()

	// ...then, we can safely type-check ourself
	root.NeedTypesInfo()

	c.Lock()
	defer c.Unlock()
	c.checkedPackages[root] = struct{}{}
}


text:
class FeatureBuilder1;

namespace feature
{
struct GenerateInfo;
}  // namespace feature

namespace generator
{
class CityBoundaryProcessor;
class WorldMapper;
class LayerBase;

// This class is implementation of EmitterInterface for the world.
class EmitterWorld : public EmitterInterface
{
public:
  explicit EmitterWorld(feature::GenerateInfo const & info);

  // EmitterInterface overrides:
  void Process(FeatureBuilder1 & feature) override;
  bool Finish() override;
  void GetNames(std::vector<std::string> & names) const override;

private:
  std::shared_ptr<CityBoundaryProcessor> m_cityBoundaryProcessor;
  std::shared_ptr<WorldMapper> m_worldMapper;
  std::shared_ptr<LayerBase> m_processingChain;
};
}  // namespace generator


text:
'use strict';

// MODULES //

var logger = require( 'debug' );
var yRugTransform = require( './../utils/y_rug_transform.js' );

// VARIABLES //

var debug = logger( 'plot:render:svg:marks:y-rug' );

// MAIN //

/**
* Renders y-axis rug plots.
*
* @private
* @param {Object} state - state
* @returns {VTree} virtual tree
*/
function render( state ) {
	var rugTransform;
	var nOpacities;
	var nOrients;
	var opacity;
	var nColors;
	var nSizes;
	var orient;
	var nFlgs;
	var color;
	var marks;
	var size;
	var rug;
	var len;
	var tmp;
	var i;

	rug = state.$.svg.yRug;

	nOpacities = state.yRugOpacity.length;
	nOrients = state.yRugOrient.length;
	nColors = state.colors.length;
	nSizes = state.yRugSize.length;
	nFlgs = state.yRug.length;

	len = state.y.length;
	marks = [];

	debug( 'Rendering y-axis rug plots...' );
	for ( i = 0; i < len; i++ ) {
		if ( !state.yRug[ i%nFlgs ] ) {
			debug( 'Rug plot (%d) disabled. Skipping...', i );
			continue;
		}
		color = state.colors[ i%nColors ];
		debug( 'Rug color: %s (%d).', color, i );

		opacity = state.yRugOpacity[ i%nOpacities ];
		debug( 'Rug opacity: %d (%d).', opacity, i );

		orient = state.yRugOrient[ i%nOrients ];
		debug( 'Rug orientation: %s (%d).', orient, i );

		size = state.yRugSize[ i%nSizes ];
		debug( 'Rug tick size: %d (%d).', size, i );

		rug.data = state.y[ i ];
		rug.label = state.labels[ i ] || '';
		rug.color = color;
		rug.size = size;
		rug.opacity = opacity;
		rug.orientation = orient;

		debug( 'Rendering y-axis rug %d...', i );
		tmp = rug.render();

		// Update the class name to indicate this is a y-axis rug and add a transform to translate the rug into position based on the graph dimensions.
		tmp.properties.className += ' y';
		rugTransform = yRugTransform( orient, state.graphWidth );
		if ( !tmp.properties.attributes ) {
			tmp.properties.attributes = {};
		}
		tmp.properties.attributes.transform = rugTransform;

		marks.push( tmp );
	}
	debug( 'Finished rendering y-axis rug plots.' );
	return marks;
}

// EXPORTS //

module.exports = render;


text:
namespace WebKit { class WebGraphicsContext3D; }

namespace cc {
class ResourceUpdateQueue;
class TextureMailbox;

class TextureLayerClient {
 public:
  // Called to prepare this layer's texture for compositing. The client may
  // queue a texture upload or copy on the ResourceUpdateQueue.
  // Returns the texture ID to be used for compositing.
  virtual unsigned PrepareTexture(ResourceUpdateQueue* queue) = 0;

  // Returns the context that is providing the texture. Used for rate limiting
  // and detecting lost context.
  virtual WebKit::WebGraphicsContext3D* Context3d() = 0;

  // Returns true and provides a mailbox if a new frame is available.
  // Returns false if no new data is available
  // and the old mailbox is to be reused.
  virtual bool PrepareTextureMailbox(TextureMailbox* mailbox) = 0;

 protected:
  virtual ~TextureLayerClient() {}
};

}  // namespace cc

#endif  // CC_LAYERS_TEXTURE_LAYER_CLIENT_H_


text:
class PetSkill < ActiveRecord::Base
  belongs_to :battle_pet
  belongs_to :skill

  after_initialize :defaults

  def defaults
    self.level ||= 0
  end

end


text:
<?php

namespace Salim\PlateformeBundle\DoctrineListener;

use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use Salim\PlateformeBundle\Email\ApplicationMailer;
use Salim\PlateformeBundle\Entity\Application;

class ApplicationCreationListener
{

	/**
	 *  @var ApplicationMailer
	 */
	private $applicationMailer;

	public function __construct(ApplicationMailer $AM)
	{
		$this->applicationMailer=$AM;
	}

	public function postPersist (LifecycleEventArgs $args)
	{
		//$entity est l'objet sur lequel l'evenement se produit
		$entity = $args->getObject();

		// Filtre d'envoi de mail : Si $entity n'est pas
		// une application alors on sort de la méthode dans rien faire
		if (!$entity instanceof Application)
		{
			return;
		}

		// Si $entity est une application alors on envoie la notification
		$this->applicationMailer->sendNewNotification($entity);

	}
}


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
package cn.ucloud.sdk.vo.uhost.in;

import cn.ucloud.sdk.enums.ActionEnum;
import cn.ucloud.sdk.vo.PageVo;

/**
 *
 * @author Jack shen<37393993@qq.com>
 *
 */
public class DescribeImageInVo extends PageVo {
    private String imageType;
    private String osType;
    private String imageId;

    public DescribeImageInVo() {
        super(ActionEnum.DescribeImage.name());
    }

    public String getImageType() {
        return imageType;
    }

    public void setImageType(String imageType) {
        this.imageType = imageType;
    }

    public String getOsType() {
        return osType;
    }

    public void setOsType(String osType) {
        this.osType = osType;
    }

    public String getImageId() {
        return imageId;
    }

    public void setImageId(String imageId) {
        this.imageId = imageId;
    }

}


text:
from direct.directnotify import DirectNotifyGlobal
import DistributedLawOfficeAI
import DistributedStageAI
from toontown.coghq import StageLayout
from toontown.toonbase import ToontownGlobals
from direct.showbase import DirectObject
import random
StageId2Layouts = {ToontownGlobals.LawbotStageIntA: (0, 1, 2),
 ToontownGlobals.LawbotStageIntB: (3, 4, 5),
 ToontownGlobals.LawbotStageIntC: (6, 7, 8),
 ToontownGlobals.LawbotStageIntD: (9, 10, 11)}

class LawOfficeManagerAI(DirectObject.DirectObject):
    notify = DirectNotifyGlobal.directNotify.newCategory('LawOfficeManagerAI')
    lawOfficeId = None

    def __init__(self, air):
        DirectObject.DirectObject.__init__(self)
        self.air = air

    def getDoId(self):
        return 0

    def createLawOffice(self, StageId, entranceId, players):
        for avId in players:
            if bboard.has('StageId-%s' % avId):
                StageId = bboard.get('StageId-%s' % avId)
                break

        floor = 0
        layoutIndex = None
        for avId in players:
            if bboard.has('stageRoom-%s' % avId):
                roomId = bboard.get('stageRoom-%s' % avId)
                for lt in StageId2Layouts[StageId]:
                    for i in xrange(StageLayout.getNumFloors(lt)):
                        layout = StageLayout.StageLayout(StageId, i, stageLayout=lt)
                        if roomId in layout.getRoomIds():
                            layoutIndex = lt
                            floor = i

                else:
                    from toontown.coghq import StageRoomSpecs
                    roomName = StageRoomSpecs.CashbotStageRoomId2RoomName[roomId]
                    LawOfficeManagerAI.notify.warning('room %s (%s) not found in any floor of Stage %s' % (roomId, roomName, StageId))

        StageZone = self.air.allocateZone()
        if layoutIndex is None:
            layoutIndex = random.choice(StageId2Layouts[StageId])
        Stage = DistributedStageAI.DistributedStageAI(self.air, StageId, StageZone, floor, players, layoutIndex)
        Stage.generateWithRequired(StageZone)
        return StageZone


text:
"""
module which uses multiple flann indexes as a way of working around adding
points to a single flann structure which seems to cause crashes.
"""
from __future__ import absolute_import, division, print_function
import six
from six.moves import zip, map, range
import numpy as np
import utool as ut
import vtool as vt
from ibeis.algo.hots import neighbor_index_cache
from ibeis.algo.hots import hstypes
(print, print_, printDBG, rrr_, profile) = ut.inject(__name__, '[multi_index]', DEBUG=False)

USE_FORGROUND_REINDEX = ut.get_argflag(('--use-foreground-reindex', '--fg-reindex'))

def testdata_mindexer():
    import ibeis
    ibs = ibeis.opendb(db='PZ_MTEST')
    daid_list = ibs.get_valid_aids()[1:60]
    cfgdict = dict(fg_on=False)
    qreq_ = ibs.new_query_request(daid_list, daid_list, cfgdict=cfgdict)
    index_method = 'name'
    mxer = request_ibeis_mindexer(qreq_, index_method)
    return mxer, qreq_, ibs

@profile
def group_daids_for_indexing_by_name(ibs, daid_list, num_indexers=8,
                                     verbose=True):
    """
    returns groups with only one annotation per name in each group
    """
    tup = ibs.group_annots_by_known_names(daid_list)
    aidgroup_list, invalid_aids = tup
    largest_groupsize = max(map(len, aidgroup_list))
    num_bins = min(largest_groupsize, num_indexers)
    if verbose or ut.VERYVERBOSE:
        print('[mindex] num_indexers = %d ' % (num_indexers,))
        print('[mindex] largest_groupsize = %d ' % (largest_groupsize,))
        print('[mindex] num_bins = %d ' % (num_bins,))
    # Group annotations for indexing according to the split criteria
    aids_list, overflow_aids = ut.sample_zip(
        aidgroup_list, num_bins, allow_overflow=True, per_bin=1)
    if __debug__:
        # All groups have the same name
        nidgroup_list = ibs.unflat_map(ibs.get_annot_name_rowids, aidgroup_list)
        for nidgroup in nidgroup_list:
            assert ut.allsame(nidgroup), 'bad name grouping'
    if __debug__:
        # All subsiquent indexer are subsets (in name/identity space)
        # of the previous
        nids_list = ibs.unflat_map(ibs.get_annot_name_rowids, aids_list)
        prev_ = None
        for nids in nids_list:
            if prev_ is None:
                prev_ = set(nids)
            else:
                assert prev_.issuperset(nids), 'bad indexer grouping'
    return aids_list, overflow_aids, num_bins

@profile
def request_ibeis_mindexer(qreq_, index_method='multi', verbose=True):
    """

    CommandLine:
        python -m ibeis.algo.hots.multi_index --test-request_ibeis_mindexer:2

    Example0:
        >>> # SLOW_DOCTEST
        >>> from ibeis.algo.hots.multi_index import *  # NOQA
        >>> import ibeis
        >>> ibs = ibeis.opendb(db='PZ_MTEST')
        >>> valid_aids = ibs.get_valid_aids()
        >>> daid_list = valid_aids[1:60]
        >>> cfgdict = dict(fg_on=False)
        >>> qreq_ = ibs.new_query_request(daid_list, daid_list, cfgdict=cfgdict)
        >>> index_method = 'multi'
        >>> mxer = request_ibeis_mindexer(qreq_, index_method)

    Example1:
        >>> # DISABLE_DOCTEST
        >>> from ibeis.algo.hots.multi_index import *  # NOQA
        >>> import ibeis
        >>> ibs = ibeis.opendb(db='PZ_Master0')
        >>> valid_aids = ibs.get_valid_aids()
        >>> daid_list = valid_aids[1:60]
        >>> cfgdict = dict(fg_on=False)
        >>> qreq_ = ibs.new_query_request(daid_list, daid_list, cfgdict=cfgdict)
        >>> index_method = 'multi'
        >>> mxer = request_ibeis_mindexer(qreq_, index_method)

    Example2:
        >>> # DISABLE_DOCTEST
        >>> # Test background reindex
        >>> from ibeis.algo.hots.multi_index import *  # NOQA
        >>> import ibeis
        >>> import time
        >>> ibs = ibeis.opendb(db='PZ_MTEST')
        >>> valid_aids = ibs.get_valid_aids()
        >>> # Remove all cached nnindexers
        >>> ibs.delete_flann_cachedir()
        >>> # This request should build a new nnindexer
        >>> daid_list = valid_aids[1:30]
        >>> cfgdict = dict(fg_on=False)
        >>> qreq_ = ibs.new_query_request(daid_list, daid_list, cfgdict=cfgdict)
        >>> index_method = 'multi'
        >>> mxer = request_ibeis_mindexer(qreq_, index_method)
        >>> ut.assert_eq(len(mxer.nn_indexer_list), 1, 'one subindexer')
        >>> # The next request should trigger a background process
        >>> # and build two subindexer
        >>> daid_list = valid_aids[1:60]
        >>> qreq_ = ibs.new_query_request(daid_list, daid_list, cfgdict=cfgdict)
        >>> index_method = 'multi'
        >>> mxer = request_ibeis_mindexer(qreq_, index_method)
        >>> # Do some work in the foreground to ensure that it doesnt block
        >>> # the background job
        >>> print('[FG] sleeping or doing bit compute')
        >>> # Takes about 15 seconds
        >>> with ut.Timer():
        ...     ut.enumerate_primes(int(9E4))
        >>> #time.sleep(10)
        >>> print('[FG] done sleeping')
        >>> ut.assert_eq(len(mxer.nn_indexer_list), 2, 'two subindexer')
        >>> # And this shoud build just one subindexer
        >>> daid_list = valid_aids[1:60]
        >>> qreq_ = ibs.new_query_request(daid_list, daid_list, cfgdict=cfgdict)
        >>> index_method = 'multi'
        >>> mxer = request_ibeis_mindexer(qreq_, index_method)
        >>> ut.assert_eq(len(mxer.nn_indexer_list), 1, 'one big subindexer')

    """
    min_reindex_thresh = qreq_.qparams.min_reindex_thresh
    max_subindexers = qreq_.qparams.max_subindexers

    daid_list = qreq_.get_internal_daids()
    print('[mindex] make MultiNeighborIndex over %d annots' % (len(daid_list),))
    print('[mindex] index_method=%r' % index_method)

    # Split annotations into groups accorindg to index_method
    ibs = qreq_.ibs
    if index_method == 'name':
        # each group are annotations of the same name
        num_indexers = 8
        aids_list, overflow_aids, num_bins = group_daids_for_indexing_by_name(ibs, daid_list, num_indexers, verbose)
    elif index_method == 'multi':
        neighbor_index_cache.check_background_process()
        # Use greedy set cover to get a list of nnindxers that are already built
        tup = neighbor_index_cache.group_daids_by_cached_nnindexer(
            qreq_, daid_list, min_reindex_thresh)
        uncovered_aids, covered_aids_list = tup
        # If the number of bins gets too big do a reindex
        # in the background
        num_subindexers = len(covered_aids_list) + (len(uncovered_aids) > 1)
        if num_subindexers > max_subindexers:
            print('need to reindex something')
            if USE_FORGROUND_REINDEX:
                aids_list = [sorted(ut.flatten(covered_aids_list))]
                #ut.embed()
            else:
                neighbor_index_cache.request_background_nnindexer(qreq_, daid_list)
                aids_list = covered_aids_list
        else:
            aids_list = covered_aids_list
        if len(uncovered_aids) > 0:
            aids_list.append(uncovered_aids)
        num_bins = len(aids_list)
    else:
        raise AssertionError('unknown index_method=%r' % (index_method,))

    # Build a neighbor indexer for each
    nn_indexer_list = []
    #extra_indexes = []
    for tx, aids in enumerate(aids_list):
        print('[mindex] building forest %d/%d with %d aids' %
                (tx + 1, num_bins, len(aids)))
        if len(aids) > 0:
            # Dont bother shallow copying qreq_ here.
            # just passing aids is enough
            nnindexer = neighbor_index_cache.request_memcached_ibeis_nnindexer(qreq_, aids)
            nn_indexer_list.append(nnindexer)
    #if len(unknown_aids) > 0:
    #    print('[mindex] building unknown forest')
    #    unknown_vecs_list = ibs.get_annot_vecs(overflow_aids, config2_=qreq_.get_internal_data_config2())
    #    unknown_index = NeighborIndex(overflow_aids, unknown_vecs_list)
    #    extra_indexes.append(unknown_index)
    ##print('[mindex] building normalizer forest')  # TODO
    #mxer.nn_indexer_list = nn_indexer_list
    #mxer.extra_indexes = extra_indexes
    #mxer.overflow_index = overflow_index
    #mxer.unknown_index = unknown_index
    mxer = MultiNeighborIndex(nn_indexer_list, min_reindex_thresh, max_subindexers)
    return mxer

#@profile
def sort_along_rows(qfx2_xxx, qfx2_sortx):
    """
    sorts each row in qfx2_xxx with the corresponding row in qfx2_sortx
    """
    if qfx2_xxx.size == 0:
        return qfx2_xxx
    #return np.vstack([row[sortx] for sortx, row in zip(qfx2_sortx, qfx2_xxx)])
    return np.vstack([row.take(sortx) for sortx, row in zip(qfx2_sortx, qfx2_xxx)])

@six.add_metaclass(ut.ReloadingMetaclass)
class MultiNeighborIndex(object):
    """
    TODO: rename to DistributedNeighborIndex

    Generalization of a NeighborIndex
    More abstract wrapper around flann

    Example:
        >>> # SLOW_DOCTEST
        >>> from ibeis.algo.hots.multi_index import *  # NOQA
        >>> mxer, qreq_, ibs = testdata_mindexer()
    """

    def __init__(mxer, nn_indexer_list, min_reindex_thresh=10, max_subindexers=2):
        mxer.nn_indexer_list = nn_indexer_list  # List of single indexes
        # Parameters for adding support to multi_indexer
        mxer.min_reindex_thresh = min_reindex_thresh
        mxer.max_subindexers = max_subindexers

    def get_dtype(mxer):
        return mxer.nn_indexer_list[0].get_dtype()

    #@profile
    def multi_knn(mxer, qfx2_vec, K):
        """
        Does a query on each of the subindexer kdtrees
        returns list of the results

        Example:
            >>> # SLOW_DOCTEST
            >>> from ibeis.algo.hots.multi_index import *  # NOQA
            >>> import numpy as np
            >>> mxer, qreq_, ibs = testdata_mindexer()
            >>> K = 3
            >>> qfx2_vec = ibs.get_annot_vecs(1, config2_=qreq_.get_internal_query_config2())
            >>> (qfx2_idx_list, qfx2_dist_list) = mxer.multi_knn(qfx2_vec, K)
            >>> shape_list = list(map(np.shape, qfx2_idx_list))
            >>> d1_list = ut.get_list_column(shape_list, 0)
            >>> d2_list = ut.get_list_column(shape_list, 1)
            >>> ut.assert_eq(d2_list, [3] * 6)
            >>> ut.assert_eq(d1_list, [len(qfx2_vec)] * 6)
        """
        qfx2_idx_list  = []
        qfx2_dist_list = []
        for nnindexer in mxer.nn_indexer_list:
            # Returns distances in ascending order for each query descriptor
            (_qfx2_idx, _qfx2_dist) = nnindexer.knn(qfx2_vec, K=K)
            qfx2_idx_list.append(_qfx2_idx)
            qfx2_dist_list.append(_qfx2_dist)
        return qfx2_idx_list, qfx2_dist_list

    @profile
    def knn(mxer, qfx2_vec, K):
        """
        Polymorphic interface to knn, but uses the multindex backend

        CommandLine:
            python -m ibeis.algo.hots.multi_index --test-knn:0

        Example1:
            >>> # SLOW_DOCTEST
            >>> from ibeis.algo.hots.multi_index import *  # NOQA
            >>> import numpy as np
            >>> mxer, qreq_, ibs = testdata_mindexer()
            >>> K = 3
            >>> qfx2_vec = ibs.get_annot_vecs(1, config2_=qreq_.get_internal_query_config2())
            >>> (qfx2_imx, qfx2_dist) = mxer.knn(qfx2_vec, K)
            >>> print(qfx2_imx.shape)
            >>> assert qfx2_imx.shape[1] == 18
            >>> ut.assert_inbounds(qfx2_imx.shape[0], 1073, 1079)

        Example2:
            >>> # SLOW_DOCTEST
            >>> from ibeis.algo.hots.multi_index import *  # NOQA
            >>> mxer, qreq_, ibs = testdata_mindexer()
            >>> K = 3
            >>> qfx2_vec = np.empty((0, 128), dtype=mxer.get_dtype())
            >>> (qfx2_imx, qfx2_dist) = mxer.knn(qfx2_vec, K)
            >>> result = str(np.shape(qfx2_imx))
            >>> print(result)
            (0, 18)
        """
        (qfx2_idx_list, qfx2_dist_list) = mxer.multi_knn(qfx2_vec, K)
        qfx2_imx_list = []
        offset_list = mxer.get_offsets()
        prev = 0
        for _qfx2_idx, offset in zip(qfx2_idx_list, offset_list):
            # Returns distances in ascending order for each query descriptor
            qfx2_imx_list.append(_qfx2_idx + prev)
            prev = offset
        # Combine results from each tree
        qfx2_imx_   = np.hstack(qfx2_imx_list)
        qfx2_dist_  = np.hstack(qfx2_dist_list)
        # Sort over all tree result distances
        qfx2_sortx = qfx2_dist_.argsort(axis=1)
        # Apply sorting to concatenated results
        qfx2_dist  = sort_along_rows(qfx2_dist_, qfx2_sortx)
        qfx2_imx   = sort_along_rows(qfx2_imx_, qfx2_sortx)
        return (qfx2_imx, qfx2_dist)

    def get_offsets(mxer):
        r"""
        Returns:
            list:

        CommandLine:
            python -m ibeis.algo.hots.multi_index --test-get_offsets

        Example:
            >>> # SLOW_DOCTEST
            >>> from ibeis.algo.hots.multi_index import *  # NOQA
            >>> mxer, qreq_, ibs = testdata_mindexer()
            >>> offset_list = mxer.get_offsets()
            >>> #target = np.array([15257, 12769,  4819,  3542,  2694])
            >>> target = np.array([21384, 36627, 49435, 54244, 57786, 60482])
            >>> error = ut.assert_almost_eq(offset_list, target, 100)
            >>> print('error.max() = %r' % (error.max(),))
        """
        nIndexed_list = mxer.get_nIndexed_list()
        offset_list = np.cumsum(nIndexed_list)
        return offset_list

    def get_nIndexed_list(mxer):
        """
        returns a list of the number of indexed vectors in each subindexer

        Args:

        Returns:
            list : nIndexed_list

        CommandLine:
            python -m ibeis.algo.hots.multi_index --test-get_nIndexed_list

        Example:
            >>> # SLOW_DOCTEST
            >>> from ibeis.algo.hots.multi_index import *  # NOQA
            >>> mxer, qreq_, ibs = testdata_mindexer()
            >>> nIndexed_list = mxer.get_nIndexed_list()
            >>> target = np.array([21384, 15243, 12808, 4809, 3542, 2696])
            >>> error = ut.assert_almost_eq(nIndexed_list, target, 100)
            >>> print('error.max() = %r' % (error.max(),))
            >>> #np.all(ut.inbounds(nIndexed_list, low, high))
        """
        nIndexed_list = [nnindexer.num_indexed_vecs()
                         for nnindexer in mxer.nn_indexer_list]
        return nIndexed_list

    def get_multi_indexed_aids(mxer):
        index_aids_list = np.array([nnindexer.get_indexed_aids() for nnindexer in
                                     mxer.nn_indexer_list])
        return index_aids_list

    def get_indexed_aids(mxer):
        return ut.flatten(mxer.get_multi_indexed_aids())

    def get_multi_num_indexed_annots(mxer):
        num_indexed_list = np.array([nnindexer.num_indexed_annots() for nnindexer in
                                     mxer.nn_indexer_list])
        return num_indexed_list

    def assert_can_add_aids(mxer, new_aid_list):
        """
        Aids that are already indexed should never be added.

        Ignore:
            qreq_vsmany_ = ut.search_stack_for_localvar('qreq_vsmany_')
            qreq_vsmany_.daids
            qreq_vsmany_.qaids
            qreq_vsmany_.ibs.get_annot_exemplar_flags(new_aid_list)
        """
        indexed_aids_list = mxer.get_multi_indexed_aids()
        indexed_aids = np.hstack(indexed_aids_list)
        uncovered_mask = vt.get_uncovered_mask(indexed_aids, new_aid_list)
        if not np.all(uncovered_mask):
            msg_list = [
                'new aids must be disjoint from current aids',
                'new_aid_list = %r' % (new_aid_list,)
            ]
            msg = '\n'.join(msg_list)
            raise AssertionError(msg)

    def add_support(mxer, new_aid_list, new_vecs_list, new_fgws_list, verbose=True):
        """
        Chooses indexer with smallest number of annotations and reindexes it.
        """
        print('adding multi-indexer support')
        raise NotImplementedError()

    def add_ibeis_support(mxer, qreq_, new_aid_list):
        """
        Chooses indexer with smallest number of annotations and reindexes it.

        Args:
            qreq_ (QueryRequest):  query request object with hyper-parameters
            new_aid_list (list):

        CommandLine:
            python -m ibeis.algo.hots.multi_index --test-add_ibeis_support

        Example:
            >>> # DISABLE_DOCTEST
            >>> from ibeis.algo.hots.multi_index import *  # NOQA
            >>> mxer, qreq_, ibs = testdata_mindexer()
            >>> new_aid_list = ibs.get_valid_aids()[70:80]
            >>> # execute function
            >>> result = mxer.add_ibeis_support(qreq_, new_aid_list)
            >>> # verify results
            >>> print(result)
        """
        print('adding multi-indexer support')
        # Assert that the aids are indeed new
        mxer.assert_can_add_aids(new_aid_list)
        # Find the indexer to add to
        num_indexed_list = mxer.get_multi_num_indexed_annots()
        min_argx = num_indexed_list.argmin()
        nnindexer_old = mxer.nn_indexer_list[min_argx]
        # Combine old and new aids
        prev_aids = nnindexer_old.get_indexed_aids()
        new_aid_list_ = np.append(prev_aids, new_aid_list)
        # Reindexed combined aids
        nnindexer_new = neighbor_index_cache.request_memcached_ibeis_nnindexer(qreq_, new_aid_list_)
        # Replace the old nnindexer with the new nnindexer
        mxer.nn_indexer_list[min_argx] = nnindexer_new
        mxer.min_reindex_thresh = qreq_.qparams.min_reindex_thresh

        if neighbor_index_cache.can_request_background_nnindexer():
            # Check if background process needs to be spawned
            # FIXME: this does not belong in method code
            num_indexed_list_new = mxer.get_multi_num_indexed_annots()
            new_smalled_size = min(num_indexed_list_new)
            need_reindex = (new_smalled_size > mxer.min_reindex_thresh or
                            len(num_indexed_list_new) > mxer.max_subindexers)
            if need_reindex:
                if USE_FORGROUND_REINDEX:
                    raise NotImplementedError('no foreground reindex in stateful query')
                else:
                    # Reindex the multi-indexed trees in the background
                    aid_list = mxer.get_indexed_aids()
                    neighbor_index_cache.request_background_nnindexer(qreq_, aid_list)

    def num_indexed_vecs(mxer):
        """
        Example:
            >>> # SLOW_DOCTEST
            >>> from ibeis.algo.hots.multi_index import *  # NOQA
            >>> mxer, qreq_, ibs = testdata_mindexer()
            >>> num_indexed = mxer.num_indexed_vecs()
            >>> ut.assert_inbounds(num_indexed, 60300, 60500)
        """
        return np.sum([nnindexer.num_indexed_vecs()
                       for nnindexer in mxer.nn_indexer_list])

    def num_indexed_annots(mxer):
        """
        Example:
            >>> # SLOW_DOCTEST
            >>> from ibeis.algo.hots.multi_index import *  # NOQA
            >>> mxer, qreq_, ibs = testdata_mindexer()
            >>> result = mxer.num_indexed_annots()
            >>> print(result)
            59
        """
        return np.sum([nnindexer.num_indexed_annots()
                       for nnindexer in mxer.nn_indexer_list])

    def iter_subindexers(mxer, qfx2_imx):
        """
        generates subindexers, indices, and maskss within them
        that partially correspond to indices in qfx2_imx that belong
        to that subindexer

        Args:
            qfx2_imx (ndarray):

        CommandLine:
            python -m ibeis.algo.hots.multi_index --test-iter_subindexers

        Example:
            >>> # SLOW_DOCTEST
            >>> from ibeis.algo.hots.multi_index import *  # NOQA
            >>> mxer, qreq_, ibs = testdata_mindexer()
            >>> K = 3, 1028
            >>> qfx2_vec = ibs.get_annot_vecs(1, config2_=qreq_.get_internal_query_config2())
            >>> (qfx2_imx, qfx2_dist) = mxer.knn(qfx2_vec, K)
            >>> genlist_ = list(mxer.iter_subindexers(qfx2_imx))
            >>> covered = np.zeros(qfx2_imx.shape)
            >>> for nnindexer, idxs, mask in genlist_:
            ...     print(covered.sum())
            ...     assert idxs.size == mask.sum()
            ...     assert covered[mask].sum() == 0
            ...     covered[mask] = True
            >>> print(covered.sum())
            >>> assert covered.sum() == covered.size
        """
        nn_indexer_list = mxer.nn_indexer_list
        offset_list = mxer.get_offsets()
        prev = 0
        for nnindexer, offset in zip(nn_indexer_list, offset_list):
            mask = np.logical_and(qfx2_imx >= prev, qfx2_imx < offset)
            idxs = qfx2_imx[mask] - prev
            yield nnindexer, idxs, mask
            prev = offset

    #def get_nn_featxs(mxer, qfx2_imx):
    #    qfx2_fx = np.empty(qfx2_imx.shape, dtype=np.int32)
    #    nn_indexer_list = mxer.nn_indexer_list
    #    offset_list = mxer.get_offsets()
    #    prev = 0
    #    for nnindexer, offset in zip(nn_indexer_list, offset_list):
    #        mask = np.logical_and(qfx2_imx >= prev, qfx2_imx < offset)
    #        idxs = qfx2_imx[mask] - prev
    #        fxs = nnindexer.get_nn_featxs(idxs)
    #        qfx2_fx[mask] = fxs
    #        prev = offset
    #    return qfx2_fx

    def get_nn_aids(mxer, qfx2_imx):
        r"""
        Args:
            qfx2_imx (ndarray):

        Returns:
            ndarray: qfx2_aid

        CommandLine:
            python -m ibeis.algo.hots.multi_index --test-get_nn_aids

        Example:
            >>> # SLOW_DOCTEST
            >>> from ibeis.algo.hots.multi_index import *  # NOQA
            >>> import numpy as np
            >>> mxer, qreq_, ibs = testdata_mindexer()
            >>> K = 3
            >>> qaid = 1
            >>> qfx2_vec = ibs.get_annot_vecs(qaid, config2_=qreq_.get_internal_query_config2())
            >>> (qfx2_imx, qfx2_dist) = mxer.knn(qfx2_vec, K)
            >>> qfx2_aid = mxer.get_nn_aids(qfx2_imx)
            >>> gt_aids = ibs.get_annot_groundtruth(qaid)
            >>> result = np.array_str(qfx2_aid[0:2])
            >>> # Make sure there are lots (like 5%) of correct matches
            >>> mask_cover = vt.get_covered_mask(qfx2_aid, gt_aids)
            >>> num_correct   = mask_cover.sum()
            >>> num_incorrect = (~mask_cover).sum()
            >>> print('fraction correct = %r' % (num_correct / float(num_incorrect),))
            >>> ut.assert_inbounds(num_correct, 900, 1100,
            ...                    'not enough matches to groundtruth')
        """
        #qfx2_aid = -np.ones(qfx2_imx.shape, dtype=np.int32)
        qfx2_aid = np.empty(qfx2_imx.shape, dtype=np.int32)
        for nnindexer, idxs, mask in mxer.iter_subindexers(qfx2_imx):
            qfx2_aid[mask] = nnindexer.get_nn_aids(idxs)
        return qfx2_aid

    def get_nn_featxs(mxer, qfx2_imx):
        r"""
        Args:
            qfx2_imx (ndarray):

        Returns:
            ndarray: qfx2_fx

        CommandLine:
            python -m ibeis.algo.hots.multi_index --test-get_nn_featxs

        Example:
            >>> # SLOW_DOCTEST
            >>> from ibeis.algo.hots.multi_index import *  # NOQA
            >>> import numpy as np
            >>> mxer, qreq_, ibs = testdata_mindexer()
            >>> K = 3
            >>> qfx2_vec = ibs.get_annot_vecs(1, config2_=qreq_.get_internal_query_config2())
            >>> (qfx2_imx, qfx2_dist) = mxer.knn(qfx2_vec, K)
            >>> qfx2_fgw = mxer.get_nn_featxs(qfx2_imx)
            >>> result = np.array_str(qfx2_fgw)
            >>> print(result)
        """
        #qfx2_fx = -np.ones(qfx2_imx.shape, dtype=np.int32)
        qfx2_fx = np.empty(qfx2_imx.shape, dtype=np.int32)
        for nnindexer, idxs, mask in mxer.iter_subindexers(qfx2_imx):
            qfx2_fx[mask] = nnindexer.get_nn_featxs(idxs)
        return qfx2_fx

    def get_nn_fgws(mxer, qfx2_imx):
        r"""
        Args:
            qfx2_imx (ndarray):

        Returns:
            ndarray: qfx2_fgw

        CommandLine:
            python -m ibeis.algo.hots.multi_index --test-get_nn_fgws

        Example:
            >>> # SLOW_DOCTEST
            >>> from ibeis.algo.hots.multi_index import *  # NOQA
            >>> import numpy as np
            >>> mxer, qreq_, ibs = testdata_mindexer()
            >>> K = 3
            >>> qfx2_vec = ibs.get_annot_vecs(1, config2_=qreq_.get_internal_query_config2())
            >>> (qfx2_imx, qfx2_dist) = mxer.knn(qfx2_vec, K)
            >>> qfx2_fgw = mxer.get_nn_fgws(qfx2_imx)
            >>> result = np.array_str(qfx2_fgw)
            >>> print(result)
        """
        #qfx2_fgw = -np.ones(qfx2_imx.shape, dtype=np.float32)
        qfx2_fgw = np.empty(qfx2_imx.shape, dtype=hstypes.FS_DTYPE)
        for nnindexer, idxs, mask in mxer.iter_subindexers(qfx2_imx):
            qfx2_fgw[mask] = nnindexer.get_nn_fgws(idxs)
        return qfx2_fgw

    def knn2(mxer, qfx2_vec, K):
        """
        Example:
            >>> # SLOW_DOCTEST
            >>> from ibeis.algo.hots.multi_index import *  # NOQA
            >>> mxer, qreq_, ibs = testdata_mindexer()
            >>> K = 3
            >>> qfx2_vec = ibs.get_annot_vecs(1, config2_=qreq_.get_internal_query_config2())
            >>> (qfx2_dist_, qfx2_idx_,  qfx2_fx_, qfx2_ax_, qfx2_rankx_, qfx2_treex_,) = mxer.knn2(qfx2_vec, K)
        """
        qfx2_idx_list   = []
        qfx2_dist_list = []
        qfx2_ax_list  = []
        qfx2_fx_list   = []
        qfx2_rankx_list = []  # ranks index
        qfx2_treex_list = []  # tree index
        for tx, nnindexer in enumerate(mxer.nn_indexer_list):
            # Returns distances in ascending order for each query descriptor
            (qfx2_idx, qfx2_dist) = nnindexer.knn(qfx2_vec, K)
            qfx2_fx = nnindexer.get_nn_featxs(qfx2_idx)
            qfx2_ax = nnindexer.get_nn_axs(qfx2_idx)
            qfx2_idx_list.append(qfx2_idx)
            qfx2_dist_list.append(qfx2_dist)
            qfx2_fx_list.append(qfx2_fx)
            qfx2_ax_list.append(qfx2_ax)
            qfx2_rankx_list.append(np.array([[rankx for rankx in range(qfx2_idx.shape[1])]] * len(qfx2_idx)))
            qfx2_treex_list.append(np.array([[tx for rankx in range(qfx2_idx.shape[1])]] * len(qfx2_idx)))
        # Combine results from each tree
        qfx2_idx   = np.hstack(qfx2_idx_list)
        qfx2_dist  = np.hstack(qfx2_dist_list)
        qfx2_rankx = np.hstack(qfx2_rankx_list)
        qfx2_treex = np.hstack(qfx2_treex_list)
        qfx2_ax    = np.hstack(qfx2_ax_list)
        qfx2_fx    = np.hstack(qfx2_fx_list)

        # Sort over all tree result distances
        qfx2_sortx = qfx2_dist.argsort(axis=1)
        # Apply sorting to concatenated results
        def foreach_row_sort_cols(qfx2_xxx):
            return  np.vstack([row[sortx] for sortx, row in zip(qfx2_sortx, qfx2_xxx)])
        qfx2_dist_  = foreach_row_sort_cols(qfx2_dist)
        qfx2_idx_   = foreach_row_sort_cols(qfx2_idx)
        qfx2_ax_    = foreach_row_sort_cols(qfx2_ax)
        qfx2_fx_    = foreach_row_sort_cols(qfx2_fx)
        qfx2_rankx_ = foreach_row_sort_cols(qfx2_rankx)
        qfx2_treex_ = foreach_row_sort_cols(qfx2_treex)
        return (qfx2_dist_, qfx2_idx_,  qfx2_fx_, qfx2_ax_, qfx2_rankx_, qfx2_treex_,)

if __name__ == '__main__':
    """
    CommandLine:
        python -m ibeis.algo.hots.multi_index
        python -m ibeis.algo.hots.multi_index --allexamples
        python -m ibeis.algo.hots.multi_index --allexamples --noface --nosrc

        utprof.sh ibeis/algo/hots/multi_index.py --allexamples
    """
    import multiprocessing
    multiprocessing.freeze_support()  # for win32
    ut.doctest_funcs()


text:
///////////////////////////////////////////////////////////////////////////////
// FILE:          LoadSave.java
// PROJECT:       Micro-Manager
// SUBSYSTEM:     MightexPolygon plugin
//-----------------------------------------------------------------------------
// DESCRIPTION:   Mightex Polygon400 plugin.
//
// AUTHOR:        Wayne Liao, mightexsystem.com, 05/15/2015
//
// COPYRIGHT:     Mightex Systems, 2015
//
// LICENSE:       This file is distributed under the BSD license.
//                License text is included with the source distribution.
//
//                This file is distributed in the hope that it will be useful,
//                but WITHOUT ANY WARRANTY; without even the implied warranty
//                of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
//                IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//                CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//                INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//
package org.micromanager.polygon;

/**
 *
 * @author Wayne
 */
public interface LoadSave {
    public boolean Load( String fn );
    public boolean Save( String fn );
}


text:
title: Diceware
date: 2015-11-15
categories: portfolio
tags:
---

GitHub: [diceware](https://github.com/jwoos/python_diceware)
Demo: N/A

<!-- more -->

<asciinema-player src="/demo/python_diceware.json" cols="290" rows="32"></asciinema-player>

After reading an article about a little girl making diceware passwords and selling them, I became interested in automating that process. I got into learning about pseudorandom and random numbers, becoming aware that most number generation on a computer is pseudorandom. However, even if it is pseudorandom, there are ways to make them cryotographically secure - which is the method used in this project. Simply put, it will generate 6 random numbers ranging from one to six and look it up in a diceware words table and return that word. This process will repeat for however many words you want. In the end it was a simple but an educational project.


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.sql.planner.optimizations;

import com.facebook.presto.Session;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.planner.PlanNodeIdAllocator;
import com.facebook.presto.sql.planner.Symbol;
import com.facebook.presto.sql.planner.SymbolAllocator;
import com.facebook.presto.sql.planner.plan.JoinNode;
import com.facebook.presto.sql.planner.plan.LateralJoinNode;
import com.facebook.presto.sql.planner.plan.PlanNode;
import com.facebook.presto.sql.planner.plan.SimplePlanRewriter;
import com.google.common.collect.ImmutableList;

import java.util.Map;
import java.util.Optional;

import static java.util.Objects.requireNonNull;

public class TransformUncorrelatedLateralToJoin
        implements PlanOptimizer
{
    @Override
    public PlanNode optimize(PlanNode plan, Session session, Map<Symbol, Type> types, SymbolAllocator symbolAllocator, PlanNodeIdAllocator idAllocator)
    {
        return SimplePlanRewriter.rewriteWith(new Rewriter(idAllocator), plan, null);
    }

    private class Rewriter
            extends SimplePlanRewriter<PlanNode>
    {
        private final PlanNodeIdAllocator idAllocator;

        public Rewriter(PlanNodeIdAllocator idAllocator)
        {
            this.idAllocator = requireNonNull(idAllocator, "idAllocator is null");
        }

        @Override
        public PlanNode visitLateralJoin(LateralJoinNode node, RewriteContext<PlanNode> context)
        {
            LateralJoinNode rewrittenNode = (LateralJoinNode) context.defaultRewrite(node, context.get());
            if (rewrittenNode.getCorrelation().isEmpty()) {
                return new JoinNode(
                        idAllocator.getNextId(),
                        JoinNode.Type.INNER,
                        rewrittenNode.getInput(),
                        rewrittenNode.getSubquery(),
                        ImmutableList.of(),
                        ImmutableList.<Symbol>builder()
                                .addAll(rewrittenNode.getInput().getOutputSymbols())
                                .addAll(rewrittenNode.getSubquery().getOutputSymbols())
                                .build(),
                        Optional.empty(),
                        Optional.empty(),
                        Optional.empty(),
                        Optional.empty());
            }
            return rewrittenNode;
        }
    }
}


text:
#ifndef FACTORYBASE_H
#define FACTORYBASE_H

#include "pandabase.h"

#include "typedObject.h"
#include "typedReferenceCount.h"
#include "factoryParams.h"

#include "pvector.h"
#include "pmap.h"

/**
 * A Factory can be used to create an instance of a particular subclass of
 * some general base class.  Each subclass registers itself with the Factory,
 * supplying a function that will construct an instance of that subclass; the
 * Factory can later choose a suitable subclass and return a newly-constructed
 * pointer to an object of that type on the user's demand.  This is used, for
 * instance, to manage the set of GraphicsPipes available to the user.
 *
 * FactoryBase is the main definition of the thin template class Factory.
 */
class EXPCL_PANDA_PUTIL FactoryBase {
public:
  typedef TypedObject *BaseCreateFunc(const FactoryParams &params);

  // public interface
public:
  FactoryBase();
  ~FactoryBase();

  TypedObject *make_instance(TypeHandle handle,
                             const FactoryParams &params);

  INLINE TypedObject *make_instance(const string &type_name,
                                    const FactoryParams &params);

  TypedObject *make_instance_more_general(TypeHandle handle,
                                          const FactoryParams &params);

  INLINE TypedObject *make_instance_more_general(const string &type_name,
                                                 const FactoryParams &params);

  TypeHandle find_registered_type(TypeHandle handle);

  void register_factory(TypeHandle handle, BaseCreateFunc *func);

  int get_num_types() const;
  TypeHandle get_type(int n) const;

  void clear_preferred();
  void add_preferred(TypeHandle handle);
  int get_num_preferred() const;
  TypeHandle get_preferred(int n) const;

  void write_types(ostream &out, int indent_level = 0) const;

private:
  // These are private; we shouldn't be copy-constructing Factories.
  FactoryBase(const FactoryBase &copy);
  void operator = (const FactoryBase &copy);

  // internal utility functions
  TypedObject *make_instance_exact(TypeHandle handle,
                                   const FactoryParams &params);
  TypedObject *make_instance_more_specific(TypeHandle handle,
                                           const FactoryParams &params);

private:
  // internal mechanics and bookkeeping

#if (defined(WIN32_VC) || defined(WIN64_VC)) && !defined(__ICL)    //__ICL is Intel C++
  // Visual C++ seems to have a problem with building a map based on
  // BaseCreateFunc.  We'll have to typecast it on the way out.
  typedef pmap<TypeHandle, void *> Creators;
#else
  typedef pmap<TypeHandle, BaseCreateFunc *> Creators;
#endif

  Creators _creators;

  typedef pvector<TypeHandle> Preferred;
  Preferred _preferred;
};

#include "factoryBase.I"

#endif /* FACTORY_H */


text:
package com.smartsheet.api.internal.http;

import org.junit.Before;
import org.junit.Test;

import java.io.ByteArrayInputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;

import static org.junit.Assert.fail;

public class DefaultHttpClientTest {
    HttpClient client;

    @Before
    public void setUp() throws Exception {
        client = new DefaultHttpClient();
    }

    @Test
    public void testDefaultHttpClient() {}

    @Test
    public void testDefaultHttpClientCloseableHttpClient() { }

    @Test
    public void testRequest() throws HttpClientException, URISyntaxException {
        // Null Argument
        try {
            client.request(null);
            fail("Exception should have been thrown");
        } catch (IllegalArgumentException e) {
            // Expected
        }

        HttpRequest request = new HttpRequest();

        // No URL in request
        try {
            client.request(request);

            fail("Exception should have been thrown");
        } catch (IllegalArgumentException e) {
            // Expected
        }

////        // Test each http method
        request.setUri(new URI("http://google.com"));
        request.setMethod(HttpMethod.GET);
        client.request(request);
        client.releaseConnection();

        request.setMethod(HttpMethod.POST);
        client.request(request);
        client.releaseConnection();

        request.setMethod(HttpMethod.PUT);
        client.request(request);
        client.releaseConnection();

        request.setMethod(HttpMethod.DELETE);
        client.request(request);
        client.releaseConnection();

        // Test request with set headers and http entity but a null content
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("name","value");
        HttpEntity entity = new HttpEntity();
        entity.setContentType("text/html; charset=ISO-8859-4");
        request.setEntity(entity);
        request.setHeaders(headers);
        request.setMethod(HttpMethod.POST);
        client.request(request);
        client.releaseConnection();

        // Test request with set headers and http entity and some content
        entity.setContent(new ByteArrayInputStream("Hello World!".getBytes()));
        request.setEntity(entity);
        client.request(request);
        client.releaseConnection();

        // Test Client Protocol Exception by passing a second content-length
        try{
            headers.put("Content-Length","10");
            request.setHeaders(headers);
            client.request(request);
            client.releaseConnection();
            fail("Exception should have been thrown");
        }catch(HttpClientException ex){
            // Expected
        }finally{
            headers.remove("Content-Length");
            request.setHeaders(headers);
        }

        // Test IOException
        try{
            request.setUri(new URI("http://bad.domain"));
            client.request(request);
            client.releaseConnection();
            fail("Exception should have been thrown.");
        }catch(HttpClientException ex){
            // Expected
        }

    }

}


text:
/*
 * IOResult.java
 * Creation date: Jun 30, 2005.
 * By: Joseph Wong
 */

package org.openquark.cal.foreignsupport.module.File;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * The IOResult class encapsulates what a Java foreign support method in this
 * package returns to CAL, i.e. either a return value, or an uncaught
 * IOException. An instance of IOResult gets translated by helper functions in
 * the File module into a more native CAL representation, namely that of the type
 * (Either IOError a).
 *
 * @author Joseph Wong
 */
public final class IOResult {

    /**
     * The return value of the operation, or null if the operation terminated with an exception.
     */
    private final Object result;
    /**
     * The exception which terminated the operation, or null if the operation returned its result successfully.
     */
    private final IOException exception;
    /**
     * The file associated with the error, or null if not applicable.
     */
    private final File file;

    /**
     * Private constructor for IOResult.
     *
     * @param res
     *            the return value of the operation, or null if the operation
     *            terminated with an exception.
     * @param ex
     *            the exception which terminated the operation, or null if the
     *            operation returned its result successfully.
     * @param f
     *            the file associated with the error, or null if not applicable.
     */
    private IOResult(Object res, IOException ex, File f) {
        result = res;
        exception = ex;
        file = f;
    }

    /**
     * Construct an IOResult representing the successful execution of an
     * operation whose return type is void (or equivalently the CAL Unit type).
     *
     * @return the new IOResult instance.
     */
    public static IOResult makeVoidResult() {
        return new IOResult(org.openquark.cal.foreignsupport.module.Prelude.UnitValue.UNIT, null, null);
    }

    /**
     * Construct an IOResult representing the return value of a successful
     * operation.
     *
     * @param result
     *            the return value of the operation.
     * @return the new IOResult instance.
     */
    public static IOResult makeResult(Object result) {
        return new IOResult(result, null, null);
    }

    /**
     * Construct an IOResult representing an IOException which terminated the
     * operation.
     *
     * @param exception
     *            the IOException which terminated the operation.
     * @param fileName
     *            the name of the file involved in the error, or null if not
     *            applicable.
     * @return the new IOResult instance.
     */
    public static IOResult makeError(IOException exception, File fileName) {
        return new IOResult(null, exception, fileName);
    }

    /**
     * Returns whether this IOError instance represents an IOException which
     * terminated the operation.
     *
     * @return true iff this instance represents an IOException which terminated
     *         the operation.
     */
    public boolean isError() {
        return exception != null;
    }

    /**
     * Returns the return value represented by this instance, or null if the
     * operation was terminated with an exception.
     *
     * @return the return value of the operation, or null if it failed with an
     *         exception.
     */
    public Object getResult() {
        return result;
    }

    /**
     * Returns the exception which terminated the operation, or null if the
     * operation executed successfully.
     *
     * @return the exception which terminated the operation, or null if the
     *         operation succeeded.
     */
    public IOException getException() {
        return exception;
    }

    /**
     * Returns the File object associated with the exception that terminated the
     * operation, or null if the operation executed successfully or if the
     * exception is not associated with a particular File object.
     *
     * @return the associated File object, or null if not applicable.
     */
    public File getFile() {
        return file;
    }

    /**
     * Returns the stack trace associated with the given exception object.
     *
     * @param ex
     *            the exception whose stack trace is desired.
     * @return the stack trace as a string.
     */
    public static String getStackTrace(IOException ex) {
        StringWriter sw = new StringWriter();
        PrintWriter writer = new PrintWriter(sw);
        ex.printStackTrace(writer);
        return sw.toString();
    }

    /**
     * Returns true iff the given exception object represents an error that
     * arose because the user did not having sufficient privileges to perform
     * the operation.
     *
     * @param ex
     *            the exception to check
     */
    public static boolean isPermissionDenied_FileNotFoundException(IOException ex) {
        return ex instanceof FileNotFoundException &&
            (ex.getMessage().endsWith("(Access is denied)")
            || ex.getMessage().endsWith("(Permission denied)")
            || ex.getMessage().endsWith("(Read-only file system)"));
    }

    /**
     * Returns true iff the given exception object represents an error that
     * arose because a hardware device was not ready.
     *
     * @param ex
     *            the exception to check
     */
    public static boolean isDeviceNotReady_FileNotFoundException(IOException ex) {
        return ex instanceof FileNotFoundException && ex.getMessage().endsWith("(The device is not ready)");
    }

    /**
     * Returns true iff the given exception object represents an error that
     * arose because the specified file or directory was already in use.
     *
     * @param ex
     *            the exception to check
     */
    public static boolean isResourceBusyException(IOException ex) {
        return ex.getMessage().endsWith("The process cannot access the file because another process has locked a portion of the file");
    }

    /**
     * Returns true iff the given exception object represents an error that
     * arose because the hardware device (e.g. the disk) was full.
     *
     * @param ex
     *            the exception to check
     */
    public static boolean isResourceExhaustedException(IOException ex) {
        return ex.getMessage().endsWith("There is not enough space on the disk")
            || ex.getMessage().endsWith("No space left on device");
    }
}


text:
PG_MODULE_MAGIC;

PG_FUNCTION_INFO_V1(plruby_call_handler);
PG_FUNCTION_INFO_V1(plruby_inline_handler);
PG_FUNCTION_INFO_V1(plruby_call_validator);

Datum plruby_call_handler(PG_FUNCTION_ARGS);
Datum plruby_inline_handler(PG_FUNCTION_ARGS);
Datum plruby_call_validator(PG_FUNCTION_ARGS);

void _PG_init(void);

Datum plruby_call_handler(PG_FUNCTION_ARGS)
{
  printf("plruby_call_handler\n");

  Oid fn_oid = fcinfo->flinfo->fn_oid;

  HeapTuple procTup =
    SearchSysCache(PROCOID, ObjectIdGetDatum(fn_oid), 0, 0, 0);
  if (!HeapTupleIsValid(procTup))
    elog(ERROR, "cache lookup failed for function %u", fn_oid);

  bool isnull;
  Datum prosrc =
    SysCacheGetAttr(PROCOID, procTup, Anum_pg_proc_prosrc, &isnull);
  if (isnull)
    elog(ERROR, "null prosrc");

  //
  char *source_text = TextDatumGetCString(prosrc);
  ReleaseSysCache(procTup);
  //

  VALUE ret = rb_eval_string(source_text);
  StringValue(ret);
  return CStringGetTextDatum(RSTRING_PTR(ret));
}

Datum plruby_inline_handler(PG_FUNCTION_ARGS)
{
  printf("plruby_inline_handler\n");
  MemoryContext ctx = CurrentMemoryContext;

  InlineCodeBlock *codeblock =
    (InlineCodeBlock*) DatumGetPointer(PG_GETARG_DATUM(0));

  Assert(IsA(codeblock, InlineCodeBlock));

  //
  char *source_text = codeblock->source_text;
  PG_TRY();
  {
    elog(NOTICE, "%s", source_text);
  }
  PG_CATCH();
  {
    MemoryContextSwitchTo(ctx);
    ErrorData *edata = CopyErrorData();
    FlushErrorState();
    FreeErrorData(edata);
    return (Datum) NULL;
  }
  PG_END_TRY();
  //

  VALUE ret = rb_eval_string(source_text);
  StringValue(ret);
  return CStringGetTextDatum(RSTRING_PTR(ret));
}

Datum plruby_call_validator(PG_FUNCTION_ARGS)
{
  printf("plruby_call_validator\n");
  return (Datum) NULL;
}

void _PG_init(void)
{
  printf("_PG_init\n");
  ruby_init();
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp.Simplification
{
    internal partial class CSharpMiscellaneousReducer : AbstractCSharpReducer
    {
        private static readonly ObjectPool<IReductionRewriter> s_pool = new ObjectPool<IReductionRewriter>(
            () => new Rewriter(s_pool));

        public CSharpMiscellaneousReducer() : base(s_pool)
        {
        }

        private static bool CanRemoveTypeFromParameter(
            ParameterSyntax parameterSyntax,
            SemanticModel semanticModel,
            CancellationToken cancellationToken)
        {
            // We reduce any the parameters that are contained inside ParameterList
            if (parameterSyntax.IsParentKind(SyntaxKind.ParameterList) &&
                parameterSyntax.Parent.IsParentKind(SyntaxKind.ParenthesizedLambdaExpression))
            {
                if (parameterSyntax.Type != null)
                {
                    var annotation = new SyntaxAnnotation();
                    var newParameterSyntax = parameterSyntax.WithType(null).WithAdditionalAnnotations(annotation);

                    var oldLambda = parameterSyntax.FirstAncestorOrSelf<ParenthesizedLambdaExpressionSyntax>();
                    var newLambda = oldLambda.ReplaceNode(parameterSyntax, newParameterSyntax);
                    var speculationAnalyzer = new SpeculationAnalyzer(oldLambda, newLambda, semanticModel, cancellationToken);
                    newParameterSyntax = (ParameterSyntax)speculationAnalyzer.ReplacedExpression.GetAnnotatedNodesAndTokens(annotation).First();

                    var oldSymbol = semanticModel.GetDeclaredSymbol(parameterSyntax, cancellationToken);
                    var newSymbol = speculationAnalyzer.SpeculativeSemanticModel.GetDeclaredSymbol(newParameterSyntax, cancellationToken);
                    if (oldSymbol != null &&
                        newSymbol != null &&
                        oldSymbol.Type == newSymbol.Type)
                    {
                        return !speculationAnalyzer.ReplacementChangesSemantics();
                    }
                }
            }

            return false;
        }

        private static Func<ParameterSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode> s_simplifyParameter = SimplifyParameter;

        private static SyntaxNode SimplifyParameter(
            ParameterSyntax node,
            SemanticModel semanticModel,
            OptionSet optionSet,
            CancellationToken cancellationToken)
        {
            if (CanRemoveTypeFromParameter(node, semanticModel, cancellationToken))
            {
                var newParameterSyntax = node.WithType(null);
                newParameterSyntax = SimplificationHelpers.CopyAnnotations(node, newParameterSyntax).WithoutAnnotations(Simplifier.Annotation);
                return newParameterSyntax;
            }

            return node;
        }

        private static readonly Func<ParenthesizedLambdaExpressionSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode> s_simplifyParenthesizedLambdaExpression = SimplifyParenthesizedLambdaExpression;

        private static SyntaxNode SimplifyParenthesizedLambdaExpression(
            ParenthesizedLambdaExpressionSyntax parenthesizedLambda,
            SemanticModel semanticModel,
            OptionSet optionSet,
            CancellationToken cancellationToken)
        {
            if (parenthesizedLambda.ParameterList != null &&
                parenthesizedLambda.ParameterList.Parameters.Count == 1)
            {
                var parameter = parenthesizedLambda.ParameterList.Parameters.First();
                if (CanRemoveTypeFromParameter(parameter, semanticModel, cancellationToken))
                {
                    var newParameterSyntax = parameter.WithType(null);
                    var newSimpleLambda = SyntaxFactory.SimpleLambdaExpression(
                        parenthesizedLambda.AsyncKeyword,
                        newParameterSyntax.WithTrailingTrivia(parenthesizedLambda.ParameterList.GetTrailingTrivia()),
                        parenthesizedLambda.ArrowToken,
                        parenthesizedLambda.Body);

                    return SimplificationHelpers.CopyAnnotations(parenthesizedLambda, newSimpleLambda).WithoutAnnotations(Simplifier.Annotation);
                }
            }

            return parenthesizedLambda;
        }

        private static readonly Func<BlockSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode> s_simplifyBlock = SimplifyBlock;

        private static SyntaxNode SimplifyBlock(
            BlockSyntax node,
            SemanticModel semanticModel,
            OptionSet optionSet,
            CancellationToken cancellationToken)
        {
            if (node.Statements.Count == 1 &&
                CanHaveEmbeddedStatement(node.Parent) &&
                !optionSet.GetOption(CSharpCodeStyleOptions.PreferBraces).Value)
            {
                return node.Statements[0];
            }

            return node;
        }

        private static bool CanHaveEmbeddedStatement(SyntaxNode node)
        {
            if (node != null)
            {
                switch (node.Kind())
                {
                    case SyntaxKind.IfStatement:
                    case SyntaxKind.ElseClause:
                    case SyntaxKind.ForStatement:
                    case SyntaxKind.ForEachStatement:
                    case SyntaxKind.ForEachVariableStatement:
                    case SyntaxKind.WhileStatement:
                    case SyntaxKind.DoStatement:
                    case SyntaxKind.UsingStatement:
                    case SyntaxKind.LockStatement:
                        return true;
                }
            }

            return false;
        }
    }
}


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInitee2b00a97c0524654809d492995ee879::getLoader();