text:
import React, { PropTypes } from 'react'
import { lengthWithoutCRLF, formatTime } from '../utils/stringUtils'

const styles = {
  list: {
    width: '100%',
    margin: 0,
    padding: '8px 0',
    fontFamily: 'Roboto, sans-serif',
    listStyle: 'none',
  },
  listItem: {
    display: 'block',
    position: 'relative',
    padding: '16px 16px 12px 16px',
  },
  index: {
    position: 'absolute',
    left: 16,
    top: 16,
    color: 'rgba(0, 0, 0, 0.54)',
    fontSize: 24,
    lineHeight: 1,
  },
  primaryText: {
    paddingLeft: 56,
    color: 'rgba(0, 0, 0, 0.87)',
    fontSize: 16,
    lineHeight: 20/16,
    whiteSpace: 'pre',
  },
  secondaryText: {
    paddingLeft: 56,
    color: 'rgba(0, 0, 0, 0.54)',
    fontSize: 14,
    lineHeight: 20/14,
  },
}

const getCps = (startTimeMs, endTimeMs, text) => {
  const cps = lengthWithoutCRLF(text) / (endTimeMs - startTimeMs) * 1000
  return cps.toFixed(2)
}

export default class TablesNarrow extends React.Component {

  static propTypes = {
    translations: PropTypes.shape({
      translate: PropTypes.func.isRequired,
    }).isRequired,
    tables: PropTypes.arrayOf(
      PropTypes.shape({
        id: PropTypes.number.isRequired,
        startTimeMs: PropTypes.number.isRequired,
        endTimeMs: PropTypes.number.isRequired,
        text: PropTypes.string.isRequired,
      })
    ).isRequired,
  }

  render() {
    const t = this.props.translations

    return (

      {
        this.props.tables.map((table) => (

{table.id}

{table.text}

{t.translate('app.tablesNarrow.stats1', { startTimeMs: formatTime(table.startTimeMs), endTimeMs: formatTime(table.endTimeMs) })}

{t.translate('app.tablesNarrow.stats2', { durationMs: table.endTimeMs - table.startTimeMs, charCount: lengthWithoutCRLF(table.text), cps: getCps(table.startTimeMs, table.endTimeMs, table.text) })}

        ))
      }

    )
  }
}


text:
#ifndef _UAPILINUX_NFSD_DEBUG_H
#define _UAPILINUX_NFSD_DEBUG_H
#include <linux/sunrpc/debug.h>
#define NFSDDBG_SOCK 0x0001
#define NFSDDBG_FH 0x0002
#define NFSDDBG_EXPORT 0x0004
#define NFSDDBG_SVC 0x0008
#define NFSDDBG_PROC 0x0010
#define NFSDDBG_FILEOP 0x0020
#define NFSDDBG_AUTH 0x0040
#define NFSDDBG_REPCACHE 0x0080
#define NFSDDBG_XDR 0x0100
#define NFSDDBG_LOCKD 0x0200
#define NFSDDBG_PNFS 0x0400
#define NFSDDBG_ALL 0x7FFF
#define NFSDDBG_NOCHANGE 0xFFFF
#endif

redpajama_set_name: RedPajamaGithub


text:
package moulder.moulds;

import moulder.Moulder;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;

import java.util.Arrays;
import java.util.List;

/**
 * A moulder that does nothing, no really ! Can be useful in conjunction with
 * the {@link IfMoulder} for example.
 *
 * @author jawher
 *
 */
public class NopMoulder implements Moulder {

    public List<Node> process(Element element) {
		return Arrays.<Node>asList(element);
	}

}


text:
const enum Constants {
	MINIMUM_HEIGHT = 4
}

export class ColorZone {
	_colorZoneBrand: void = undefined;

	public readonly from: number;
	public readonly to: number;
	public readonly colorId: number;

	constructor(from: number, to: number, colorId: number) {
		this.from = from | 0;
		this.to = to | 0;
		this.colorId = colorId | 0;
	}

	public static compare(a: ColorZone, b: ColorZone): number {
		if (a.colorId === b.colorId) {
			if (a.from === b.from) {
				return a.to - b.to;
			}
			return a.from - b.from;
		}
		return a.colorId - b.colorId;
	}
}

/**
 * A zone in the overview ruler
 */
export class OverviewRulerZone {
	_overviewRulerZoneBrand: void = undefined;

	public readonly startLineNumber: number;
	public readonly endLineNumber: number;
	public readonly color: string;

	private _colorZone: ColorZone | null;

	constructor(
		startLineNumber: number,
		endLineNumber: number,
		color: string
	) {
		this.startLineNumber = startLineNumber;
		this.endLineNumber = endLineNumber;
		this.color = color;
		this._colorZone = null;
	}

	public static compare(a: OverviewRulerZone, b: OverviewRulerZone): number {
		if (a.color === b.color) {
			if (a.startLineNumber === b.startLineNumber) {
				return a.endLineNumber - b.endLineNumber;
			}
			return a.startLineNumber - b.startLineNumber;
		}
		return a.color < b.color ? -1 : 1;
	}

	public setColorZone(colorZone: ColorZone): void {
		this._colorZone = colorZone;
	}

	public getColorZones(): ColorZone | null {
		return this._colorZone;
	}
}

export class OverviewZoneManager {

	private readonly _getVerticalOffsetForLine: (lineNumber: number) => number;
	private _zones: OverviewRulerZone[];
	private _colorZonesInvalid: boolean;
	private _lineHeight: number;
	private _domWidth: number;
	private _domHeight: number;
	private _outerHeight: number;
	private _pixelRatio: number;

	private _lastAssignedId: number;
	private readonly _color2Id: { [color: string]: number; };
	private readonly _id2Color: string[];

	constructor(getVerticalOffsetForLine: (lineNumber: number) => number) {
		this._getVerticalOffsetForLine = getVerticalOffsetForLine;
		this._zones = [];
		this._colorZonesInvalid = false;
		this._lineHeight = 0;
		this._domWidth = 0;
		this._domHeight = 0;
		this._outerHeight = 0;
		this._pixelRatio = 1;

		this._lastAssignedId = 0;
		this._color2Id = Object.create(null);
		this._id2Color = [];
	}

	public getId2Color(): string[] {
		return this._id2Color;
	}

	public setZones(newZones: OverviewRulerZone[]): void {
		this._zones = newZones;
		this._zones.sort(OverviewRulerZone.compare);
	}

	public setLineHeight(lineHeight: number): boolean {
		if (this._lineHeight === lineHeight) {
			return false;
		}
		this._lineHeight = lineHeight;
		this._colorZonesInvalid = true;
		return true;
	}

	public setPixelRatio(pixelRatio: number): void {
		this._pixelRatio = pixelRatio;
		this._colorZonesInvalid = true;
	}

	public getDOMWidth(): number {
		return this._domWidth;
	}

	public getCanvasWidth(): number {
		return this._domWidth * this._pixelRatio;
	}

	public setDOMWidth(width: number): boolean {
		if (this._domWidth === width) {
			return false;
		}
		this._domWidth = width;
		this._colorZonesInvalid = true;
		return true;
	}

	public getDOMHeight(): number {
		return this._domHeight;
	}

	public getCanvasHeight(): number {
		return this._domHeight * this._pixelRatio;
	}

	public setDOMHeight(height: number): boolean {
		if (this._domHeight === height) {
			return false;
		}
		this._domHeight = height;
		this._colorZonesInvalid = true;
		return true;
	}

	public getOuterHeight(): number {
		return this._outerHeight;
	}

	public setOuterHeight(outerHeight: number): boolean {
		if (this._outerHeight === outerHeight) {
			return false;
		}
		this._outerHeight = outerHeight;
		this._colorZonesInvalid = true;
		return true;
	}

	public resolveColorZones(): ColorZone[] {
		const colorZonesInvalid = this._colorZonesInvalid;
		const lineHeight = Math.floor(this._lineHeight); // @perf
		const totalHeight = Math.floor(this.getCanvasHeight()); // @perf
		const outerHeight = Math.floor(this._outerHeight); // @perf
		const heightRatio = totalHeight / outerHeight;
		const halfMinimumHeight = Math.floor(Constants.MINIMUM_HEIGHT * this._pixelRatio / 2);

		let allColorZones: ColorZone[] = [];
		for (let i = 0, len = this._zones.length; i < len; i++) {
			const zone = this._zones[i];

			if (!colorZonesInvalid) {
				const colorZone = zone.getColorZones();
				if (colorZone) {
					allColorZones.push(colorZone);
					continue;
				}
			}

			const y1 = Math.floor(heightRatio * (this._getVerticalOffsetForLine(zone.startLineNumber)));
			const y2 = Math.floor(heightRatio * (this._getVerticalOffsetForLine(zone.endLineNumber) + lineHeight));

			let ycenter = Math.floor((y1 + y2) / 2);
			let halfHeight = (y2 - ycenter);

			if (halfHeight < halfMinimumHeight) {
				halfHeight = halfMinimumHeight;
			}

			if (ycenter - halfHeight < 0) {
				ycenter = halfHeight;
			}
			if (ycenter + halfHeight > totalHeight) {
				ycenter = totalHeight - halfHeight;
			}

			const color = zone.color;
			let colorId = this._color2Id[color];
			if (!colorId) {
				colorId = (++this._lastAssignedId);
				this._color2Id[color] = colorId;
				this._id2Color[colorId] = color;
			}
			const colorZone = new ColorZone(ycenter - halfHeight, ycenter + halfHeight, colorId);

			zone.setColorZone(colorZone);
			allColorZones.push(colorZone);
		}

		this._colorZonesInvalid = false;

		allColorZones.sort(ColorZone.compare);
		return allColorZones;
	}
}


text:
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"><title>EventData</title>

EventData()

语法

Data = EventData()

概要

Get the data associated with the current event. The event needs to be a custom event sent
with PostEvent().

参数

无.

返回值

Returns the value associated with the current event. If the current event isn't a custom
event sent with PostEvent(), this value is undefined.

参阅

PostEvent(), WindowEvent()

已支持操作系统
所有

<- DisableWindow() - Window Index - EventGadget() ->


text:
import * as ResourceTiming from '../resource-timing';
import * as lolex from 'lolex';
import {ExpansionOptions, installVariableService} from '../variables';
import {RequestHandler, expandPostMessage} from '../requests';
import {dict} from '../../../../src/utils/object';
import {macroTask} from '../../../../testing/yield';

describes.realWin('Requests', {amp: 1}, env => {
  let ampdoc;
  let clock;
  let preconnect;
  let preconnectSpy;

  beforeEach(() => {
    installVariableService(env.win);
    ampdoc = env.ampdoc;
    ampdoc.defaultView = env.win;
    clock = lolex.install({target: ampdoc.win});
    preconnectSpy = sandbox.spy();
    preconnect = {
      url: preconnectSpy,
    };
  });

  afterEach(() => {
    clock.uninstall();
  });

  describe('RequestHandler', () => {
    describe('batch', () => {
      it('should batch multiple send', function* () {
        const spy = sandbox.spy();
        const r = {'baseUrl': 'r2', 'batchInterval': 1};
        const handler = new RequestHandler(
            ampdoc, r, preconnect, {sendRequest: spy}, false);
        const expansionOptions = new ExpansionOptions({});
        handler.send({}, {}, expansionOptions, {});
        handler.send({}, {}, expansionOptions, {});
        clock.tick(500);
        handler.send({}, {}, expansionOptions, {});
        clock.tick(500);
        yield macroTask();
        expect(spy).to.be.calledOnce;
      });

      it('should work properly with no batch', function* () {
        const spy = sandbox.spy();
        const r = {'baseUrl': 'r1'};
        const handler = new RequestHandler(
            ampdoc, r, preconnect, {sendRequest: spy}, false);
        const expansionOptions = new ExpansionOptions({});
        handler.send({}, {}, expansionOptions, {});
        handler.send({}, {}, expansionOptions, {});
        yield macroTask();
        expect(spy).to.be.calledTwice;
      });

      it('should preconnect', function* () {
        const r = {'baseUrl': 'r2?cid=CLIENT_ID(scope)&var=${test}'};
        const handler = new RequestHandler(
            ampdoc, r, preconnect, {sendRequest: sandbox.spy()}, false);
        const expansionOptions = new ExpansionOptions({'test': 'expanded'});
        handler.send({}, {}, expansionOptions, {});
        yield macroTask();
        expect(preconnectSpy).to.be.calledWith(
            'r2?cid=CLIENT_ID(scope)&var=expanded');
      });
    });

    describe('batch with batchInterval', () => {
      let spy;
      let transport;
      beforeEach(() => {
        spy = sandbox.spy();
        transport = {sendRequest: spy};
      });

      it('should support number', () => {
        const r = {'baseUrl': 'r1', 'batchInterval': 5};
        const handler = new RequestHandler(
            ampdoc, r, preconnect, transport, false);
        expect(handler.batchIntervalPointer_).to.not.be.null;
        expect(handler.batchInterval_).to.deep.equal([5000]);
      });

      it('should support array', () => {
        const r = {'baseUrl': 'r1', 'batchInterval': [1, 2, 3]};
        const handler = new RequestHandler(
            ampdoc, r, preconnect, transport, false);
        expect(handler.batchIntervalPointer_).to.not.be.null;
        expect(handler.batchInterval_).to.deep.equal([1000, 2000, 3000]);
      });

      it('should check batchInterval is valid', () => {
        //Should be number
        const r1 = {'baseUrl': 'r', 'batchInterval': 'invalid'};
        const r2 = {'baseUrl': 'r', 'batchInterval': ['invalid']};
        try {
          new RequestHandler(ampdoc, r1, preconnect, transport, false);
          throw new Error('should never happen');
        } catch (e) {
          expect(e).to.match(/Invalid batchInterval value/);
        }
        try {
          new RequestHandler(ampdoc, r2, preconnect, transport, false);
          throw new Error('should never happen');
        } catch (e) {
          expect(e).to.match(/Invalid batchInterval value/);
        }

        //Should be greater than BATCH_INTERVAL_MIN
        const r3 = {'baseUrl': 'r', 'batchInterval': 0.01};
        const r4 = {'baseUrl': 'r', 'batchInterval': [-1, 5]};
        const r5 = {'baseUrl': 'r', 'batchInterval': [1, 0.01]};
        try {
          new RequestHandler(ampdoc, r3, preconnect, transport, false);
          throw new Error('should never happen');
        } catch (e) {
          expect(e).to.match(/Invalid batchInterval value/);
        }
        try {
          new RequestHandler(ampdoc, r4, preconnect, transport, false);
          throw new Error('should never happen');
        } catch (e) {
          expect(e).to.match(/Invalid batchInterval value/);
        }
        try {
          new RequestHandler(ampdoc, r5, preconnect, transport, false);
          throw new Error('should never happen');
        } catch (e) {
          expect(e).to.match(/Invalid batchInterval value/);
        }
      });

      it('should schedule send request with interval array', function* () {
        const r = {'baseUrl': 'r', 'batchInterval': [1, 2]};
        const handler = new RequestHandler(
            ampdoc, r, preconnect, transport, false);
        const expansionOptions = new ExpansionOptions({});
        clock.tick(998);
        handler.send({}, {}, expansionOptions, {});
        clock.tick(2);
        yield macroTask();
        expect(spy).to.be.calledOnce;
        spy.resetHistory();
        handler.send({}, {}, expansionOptions, {});
        clock.tick(1000);
        yield macroTask();
        expect(spy).to.not.be.called;
        handler.send({}, {}, expansionOptions, {});
        clock.tick(1000);
        yield macroTask();
        expect(spy).to.be.calledOnce;
        spy.resetHistory();
        handler.send({}, {}, expansionOptions, {});
        clock.tick(1000);
        yield macroTask();
        expect(spy).to.not.be.called;
        clock.tick(1000);
        yield macroTask();
        expect(spy).to.be.calledOnce;
      });

      it('should not schedule send request w/o trigger', function* () {
        const r = {'baseUrl': 'r', 'batchInterval': [1]};
        new RequestHandler(ampdoc, r, preconnect, transport, false);
        clock.tick(1000);
        yield macroTask();
        expect(spy).to.not.be.called;
      });

      it('should schedule send independent of trigger immediate', function* () {
        const r = {'baseUrl': 'r', 'batchInterval': [1, 2]};
        const handler = new RequestHandler(
            ampdoc, r, preconnect, transport, false);
        const expansionOptions = new ExpansionOptions({});
        handler.send({}, {}, expansionOptions, {});
        clock.tick(999);
        handler.send({}, {'important': true}, expansionOptions, {});
        yield macroTask();
        expect(spy).to.be.calledOnce;
        spy.resetHistory();
        handler.send({}, {}, expansionOptions, {});
        clock.tick(1);
        yield macroTask();
        expect(spy).to.be.calledOnce;
      });
    });

    describe('reportWindow', () => {
      let spy;
      let transport;
      beforeEach(() => {
        spy = sandbox.spy();
        transport = {sendRequest: spy};
      });

      it('should accept reportWindow with number', () => {
        const r = {'baseUrl': 'r', 'reportWindow': 1};
        const handler = new RequestHandler(
            ampdoc, r, preconnect, transport, false);
        const r2 = {'baseUrl': 'r', 'reportWindow': '2'};
        const handler2 = new RequestHandler(
            ampdoc, r2, preconnect, transport, false);
        const r3 = {'baseUrl': 'r', 'reportWindow': 'invalid'};
        const handler3 = new RequestHandler(
            ampdoc, r3, preconnect, transport, false);
        expect(handler.reportWindow_).to.equal(1);
        expect(handler2.reportWindow_).to.equal(2);
        expect(handler3.reportWindow_).to.be.null;
      });

      it('should stop bathInterval outside batch report window', function* () {
        const r = {'baseUrl': 'r', 'batchInterval': 0.5, 'reportWindow': 1};
        const handler = new RequestHandler(
            ampdoc, r, preconnect, transport, false);
        const expansionOptions = new ExpansionOptions({});
        handler.send({}, {}, expansionOptions, {});
        clock.tick(500);
        yield macroTask();
        expect(spy).to.be.calledOnce;
        spy.resetHistory();
        clock.tick(500);
        expect(handler.batchIntervalTimeoutId_).to.be.null;
        handler.send({}, {}, expansionOptions, {});
        clock.tick(500);
        yield macroTask();
        expect(spy).to.not.be.called;
      });

      it('should stop send request outside batch report window', function* () {
        const r = {'baseUrl': 'r', 'reportWindow': 1};
        const handler = new RequestHandler(
            ampdoc, r, preconnect, transport, false);
        const expansionOptions = new ExpansionOptions({});
        handler.send({}, {}, expansionOptions, {});
        yield macroTask();
        expect(spy).to.be.calledOnce;
        spy.resetHistory();
        clock.tick(1000);
        handler.send({}, {}, expansionOptions, {});
        yield macroTask();
        expect(spy).to.not.be.called;
      });

      it('should flush batch queue after batch report window', function* () {
        const r = {'baseUrl': 'r', 'batchInterval': 5, 'reportWindow': 1};
        const handler = new RequestHandler(
            ampdoc, r, preconnect, transport, false);
        const expansionOptions = new ExpansionOptions({});
        handler.send({}, {}, expansionOptions, {});
        clock.tick(1000);
        yield macroTask();
        expect(spy).to.be.calledOnce;
      });

      it('should respect immediate trigger', function* () {
        const r = {'baseUrl': 'r', 'batchInterval': 0.2, 'reportWindow': 0.5};
        const handler = new RequestHandler(
            ampdoc, r, preconnect, transport, false);
        const expansionOptions = new ExpansionOptions({});
        clock.tick(500);
        yield macroTask();
        handler.send({}, {}, expansionOptions, {});
        clock.tick(200);
        expect(spy).to.not.be.called;
        handler.send({}, {'important': true}, expansionOptions, {});
      });
    });

    describe('batch segments', () => {
      it('should respect config extraUrlParam', function* () {
        const spy = sandbox.spy();
        const r = {'baseUrl': 'r1', 'batchInterval': 1};
        const handler = new RequestHandler(
            ampdoc, r, preconnect, {sendRequest: spy}, false);
        const expansionOptions = new ExpansionOptions({});
        handler.send({'e1': 'e1'}, {}, expansionOptions);
        handler.send({'e1': 'e1'}, {}, expansionOptions);
        clock.tick(1000);
        yield macroTask();
        expect(spy).to.be.calledWith('r1?e1=e1&e1=e1');
      });

      it('should respect trigger extraUrlParam', function* () {
        const spy = sandbox.spy();
        const r = {'baseUrl': 'r1', 'batchInterval': 1};
        const handler = new RequestHandler(
            ampdoc, r, preconnect, {sendRequest: spy}, false);
        const expansionOptions = new ExpansionOptions({'v2': '中'});
        handler.send({}, {
          'extraUrlParams': {
            'e1': 'e1',
            'e2': '${v2}', // check vars are used and not double encoded
          },
        }, expansionOptions, {});
        handler.send(
            {}, {'extraUrlParams': {'e1': 'e1'}}, expansionOptions, {});
        clock.tick(1000);
        yield macroTask();
        expect(spy).to.be.calledWith('r1?e1=e1&e2=%E4%B8%AD&e1=e1');
      });

      it('should replace extraUrlParam', function* () {
        const spy = sandbox.spy();
        const r = {'baseUrl': 'r1&${extraUrlParams}&r2', 'batchInterval': 1};
        const handler = new RequestHandler(
            ampdoc, r, preconnect, {sendRequest: spy}, false);
        const expansionOptions = new ExpansionOptions({});
        handler.send(
            {}, {'extraUrlParams': {'e1': 'e1'}}, expansionOptions, {});
        handler.send(
            {}, {'extraUrlParams': {'e2': 'e2'}}, expansionOptions, {});
        clock.tick(1000);
        yield macroTask();
        expect(spy).to.be.calledWith('r1&e1=e1&e2=e2&r2');
      });
    });

    describe('batch plugin', () => {
      it('should throw error when defined on non batched request', () => {
        const spy = sandbox.spy();
        const r = {'baseUrl': 'r', 'batchPlugin': '_ping_'};
        try {
          new RequestHandler(
              ampdoc, r, preconnect, {sendRequest: spy}, false);
        } catch (e) {
          expect(e).to.match(
              /batchPlugin cannot be set on non-batched request/);
        }
      });

      it('should throw error with unsupported batchPlugin', () => {
        const spy = sandbox.spy();
        const r =
            {'baseUrl': 'r', 'batchInterval': 1, 'batchPlugin': 'invalid'};
        try {
          new RequestHandler(
              ampdoc, r, preconnect, {sendRequest: spy}, false);
        } catch (e) {
          expect(e).to.match(/unsupported batch plugin/);
        }
      });

      it('should pass in correct batchSegments', function* () {
        const spy = sandbox.spy();
        const r = {'baseUrl': 'r', 'batchInterval': 1, 'batchPlugin': '_ping_'};
        const handler = new RequestHandler(
            ampdoc, r, preconnect, {sendRequest: spy}, false);
        // Overwrite batchPlugin function
        const batchPluginSpy = sandbox.spy(handler, 'batchingPlugin_');
        const expansionOptions = new ExpansionOptions({});
        handler.send({}, {'on': 'timer', 'extraUrlParams': {'e1': 'e1'}},
            expansionOptions);
        clock.tick(5);
        // Test that we decode when pass to batchPlugin function
        handler.send({}, {'on': 'click', 'extraUrlParams': {'e2': '&e2'}},
            expansionOptions);
        clock.tick(5);
        handler.send({}, {'on': 'visible', 'extraUrlParams': {'e3': ''}},
            expansionOptions);
        clock.tick(1000);
        yield macroTask();
        expect(batchPluginSpy).to.be.calledOnce;
        expect(batchPluginSpy).to.be.calledWith('r', [dict({
          'trigger': 'timer',
          'timestamp': 0,
          'extraUrlParams': {
            'e1': 'e1',
          },
        }), dict({
          'trigger': 'click',
          'timestamp': 5,
          'extraUrlParams': {
            'e2': '&e2',
          },
        }), dict({
          'trigger': 'visible',
          'timestamp': 10,
          'extraUrlParams': {
            'e3': '',
          },
        })]);
        expect(spy).to.be.calledOnce;
        expect(spy).to.be.calledWith('testFinalUrl');
      });
    });
  });

  it('should replace dynamic bindings', function* () {
    const spy = sandbox.spy();
    const r = {'baseUrl': 'r1&${resourceTiming}'};
    const handler = new RequestHandler(
        ampdoc, r, preconnect, {sendRequest: spy}, false);
    const expansionOptions = new ExpansionOptions({
      'resourceTiming': 'RESOURCE_TIMING',
    });
    sandbox.stub(ResourceTiming, 'getResourceTiming')
        .returns(Promise.resolve('resource-timing'));
    handler.send({}, {}, expansionOptions);
    yield macroTask();
    expect(spy).to.be.calledWith('r1&resource-timing');
  });

  describe('expandPostMessage', () => {
    let expansionOptions;
    let params;
    beforeEach(() => {
      expansionOptions = new ExpansionOptions({
        'teste1': 'TESTE1',
      });
      params = {
        'e1': '${teste1}',
        'e2': 'teste2',
      };
    });

    it('should expand', () => {
      return expandPostMessage(
          ampdoc,
          'test foo 123 ... ${teste1}',
          undefined,
          {},
          expansionOptions).then(msg => {
        expect(msg).to.equal('test foo 123 ... TESTE1');
      });
    });

    it('should replace not append ${extraUrlParams}', () => {
      const replacePromise = expandPostMessage(
          ampdoc,
          'test ${extraUrlParams} foo',
          params, /* configParams */
          {}, /* trigger */
          expansionOptions);
      const appendPromise = expandPostMessage(
          ampdoc,
          'test foo',
          params, /* configParams */
          {}, /* trigger */
          expansionOptions);
      return replacePromise.then(replace => {
        expect(replace).to.equal('test e1=TESTE1&e2=teste2 foo');
        expect(appendPromise).to.eventually.equal('test foo');
      });
    });
  });
});


text:
[See html formatted version](https://huasofoundries.github.io/google-maps-documentation/ScaleControlStyle.html)

ScaleControlStyle constants
---------------------------

google.maps.ScaleControlStyle constants

Identifiers for scale control ids.

Constants

[DEFAULT](#ScaleControlStyle.DEFAULT)

The standard scale control.


text:
using System;

namespace VersionOne.ServiceHost.ConfigurationTool.DL.Exceptions {
    public class FieldNameException : VersionOneException {
        public FieldNameException(string message) : base(message) {
        }

        public FieldNameException(string message, Exception exception) : base(message, exception) {
        }
    }
}


text:
> ICBD is a defunct project, but I'm releasing the source code in case any one is interested.

ICBD is a static type analyzer and static compiler for Python.  It originated
from the desire at Dropbox to have additional type information for our growing
codebases, without requiring programmers to add type annotations.  There are
other static type analyzers for Python out there; the goal of ICBD was to
produce one that would work well on the Dropbox codebase, which meant
concretely:

- Handling untypable code as gracefully as possible
- "Acceptable" running times for multi-100k LOC codebases
- A plugin system for handling code that is inherently not statically analyzable

These goals were somewhat met, perhaps to the limits of using whole-program type
inference; the running time for the Dropbox codebase was about 15 minutes, which
I believe is better than alternatives but is not good enough for easy use.

The plugin system was able to get anecdotally get ICBD to successfully analyze a
sufficient fraction of the Dropbox codebase, though when typing failed, it was
difficult to tell why.

### Testing it out

You need to install pygments and simplejson to run ICBD; once you do, run

```
bash icbd/type_analyzer/run.sh icbd
```

to have ICBD analyze its own codebase (it doesn't do particularly well since
there are no plugins for its getattr usage).  You can see the output at
file:///tmp/icbd_icbd/icbd/type_analyzer/type_checker.html

### Technical approach

ICBD treats every Python expression as a constraint on the allowable types of
the program: `a = o.x` encodes the constraint that "a will have the type of o's
x attribute", `f(x)` encodes the constaint that "f accepts a type argument of
type type(x)", etc.  At a high level, ICBD then does a graph fixed-point
analysis to determine a set of types that satisfy the constraints, and emits
errors when types could not be found (ex: `a, b, c = 1, 2`).

The guessed types start at the BOTTOM type, and ICBD iteratively finds
unsatisfied constraints and raises the involved types to attempt to satisfy the
constraints.  In theory, if ICBD always raises types monotonically and to the
minimum satisfying type, this process will converge on a deterministic set of
lowest (or in some sense, most descriptive) types.

In practice, this is somewhat harder because the type constraints are dependent
on other types -- for example, attribute lookup dependencies can change based on
learning that an attribute may actually be a instance attribute.  This doesn't
seem to be that big a deal, though.

### Comparison to Python type analyzers

ICBD only analyzes a single version of each function, and assumes that any
combination of seen argument types could occur together.  For example, in this
snippet:

```python
def add_int_or_str(a, b):
    return a + b

add_int_or_str(1, 2)
add_int_or_str("hello ", "world")
```

ICBD will report an error, saying that an int cannot be added to a string.
Other analyzers will notice that add_int_or_str does not actually receive an
(int, str) combination of arguments and handle this correctly, but at an
exponentially-large cost.

This means that ICBD does not handle polymorphic functions very gracefully,
but in practice this seems to net be a common thing for applications code, and
the plugin system makes it possible to handle on a one-off basis.

#### Quick note about HM

People often ask "why don't you just apply HM (Hindley-Milner) which computes
the types ideally".  Yes, it's true that HM has some nice ideality properties,
but it only applies to a fairly-restrictive type system.  I'm not a type
theorist, but my understanding is that to properly represent the Python type
system you need

- Dependent types to represent attributes, and
- Rank-n polymorphism to represent global variables

both of which I believe make the inference problem undecidable.  (Is there
really any Haskell program that uses 0 type annotations?)

Of course in theory it's possible to translate Python code into, for example,
Haskell, but I don't see any reason to believe this can be done in an automated
way such that the generated Haskell has any meaningful relation to the original
Python.  For example, one could build an X86 emulator in Haskell, and use that
to run the Python interpreter, but the types on the Haskell program have no
usefulness to the original Python programmer.

# Compiler

ICBD also includes a static compiler, in icbd/compiler.  Assuming that the type
analyzer can come up with a complete set of types for your program (a big
assumption), in theory it should be possible to compile the Python as if it were
a more traditionally-typed static language.

In practice I doubt that real code can really be 100% typed; the ICBD compiler
served as the starting point for the [Pyston](https://github.com/dropbox/pyston)
project, which replaces it.


text:
const cache = require('../state/cache');

module.exports = function(name) {
  return function *() {
    this.body = cache.get(name).list();
  }
}


text:
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>

#include "py/mpstate.h"
#include "py/emit.h"
#include "py/bc0.h"

#define BYTES_FOR_INT ((BYTES_PER_WORD * 8 + 6) / 7)
#define DUMMY_DATA_SIZE (BYTES_FOR_INT)

struct _emit_t {
    pass_kind_t pass : 8;
    mp_uint_t last_emit_was_return_value : 8;

    int stack_size;

    scope_t *scope;

    mp_uint_t last_source_line_offset;
    mp_uint_t last_source_line;

    mp_uint_t max_num_labels;
    mp_uint_t *label_offsets;

    mp_uint_t code_info_offset;
    mp_uint_t code_info_size;
    mp_uint_t bytecode_offset;
    mp_uint_t bytecode_size;
    byte *code_base; // stores both byte code and code info
    // Accessed as mp_uint_t, so must be aligned as such
    byte dummy_data[DUMMY_DATA_SIZE];
};

emit_t *emit_bc_new(void) {
    emit_t *emit = m_new0(emit_t, 1);
    return emit;
}

void emit_bc_set_max_num_labels(emit_t *emit, mp_uint_t max_num_labels) {
    emit->max_num_labels = max_num_labels;
    emit->label_offsets = m_new(mp_uint_t, emit->max_num_labels);
}

void emit_bc_free(emit_t *emit) {
    m_del(mp_uint_t, emit->label_offsets, emit->max_num_labels);
    m_del_obj(emit_t, emit);
}

typedef byte *(*emit_allocator_t)(emit_t *emit, int nbytes);

STATIC void emit_write_uint(emit_t *emit, emit_allocator_t allocator, mp_uint_t val) {
    // We store each 7 bits in a separate byte, and that's how many bytes needed
    byte buf[BYTES_FOR_INT];
    byte *p = buf + sizeof(buf);
    // We encode in little-ending order, but store in big-endian, to help decoding
    do {
        *--p = val & 0x7f;
        val >>= 7;
    } while (val != 0);
    byte *c = allocator(emit, buf + sizeof(buf) - p);
    while (p != buf + sizeof(buf) - 1) {
        *c++ = *p++ | 0x80;
    }
    *c = *p;
}

// all functions must go through this one to emit code info
STATIC byte *emit_get_cur_to_write_code_info(emit_t *emit, int num_bytes_to_write) {
    //printf("emit %d\n", num_bytes_to_write);
    if (emit->pass < MP_PASS_EMIT) {
        emit->code_info_offset += num_bytes_to_write;
        return emit->dummy_data;
    } else {
        assert(emit->code_info_offset + num_bytes_to_write <= emit->code_info_size);
        byte *c = emit->code_base + emit->code_info_offset;
        emit->code_info_offset += num_bytes_to_write;
        return c;
    }
}

STATIC void emit_align_code_info_to_machine_word(emit_t *emit) {
    emit->code_info_offset = (emit->code_info_offset + sizeof(mp_uint_t) - 1) & (~(sizeof(mp_uint_t) - 1));
}

STATIC void emit_write_code_info_uint(emit_t *emit, mp_uint_t val) {
    emit_write_uint(emit, emit_get_cur_to_write_code_info, val);
}

STATIC void emit_write_code_info_qstr(emit_t *emit, qstr qst) {
    emit_write_uint(emit, emit_get_cur_to_write_code_info, qst);
}

#if MICROPY_ENABLE_SOURCE_LINE
STATIC void emit_write_code_info_bytes_lines(emit_t *emit, mp_uint_t bytes_to_skip, mp_uint_t lines_to_skip) {
    assert(bytes_to_skip > 0 || lines_to_skip > 0);
    //printf("  %d %d\n", bytes_to_skip, lines_to_skip);
    while (bytes_to_skip > 0 || lines_to_skip > 0) {
        mp_uint_t b, l;
        if (lines_to_skip <= 6) {
            // use 0b0LLBBBBB encoding
            b = MIN(bytes_to_skip, 0x1f);
            l = MIN(lines_to_skip, 0x3);
            *emit_get_cur_to_write_code_info(emit, 1) = b | (l << 5);
        } else {
            // use 0b1LLLBBBB 0bLLLLLLLL encoding (l's LSB in second byte)
            b = MIN(bytes_to_skip, 0xf);
            l = MIN(lines_to_skip, 0x7ff);
            byte *ci = emit_get_cur_to_write_code_info(emit, 2);
            ci[0] = 0x80 | b | ((l >> 4) & 0x70);
            ci[1] = l;
        }
        bytes_to_skip -= b;
        lines_to_skip -= l;
    }
}
#endif

// all functions must go through this one to emit byte code
STATIC byte *emit_get_cur_to_write_bytecode(emit_t *emit, int num_bytes_to_write) {
    //printf("emit %d\n", num_bytes_to_write);
    if (emit->pass < MP_PASS_EMIT) {
        emit->bytecode_offset += num_bytes_to_write;
        return emit->dummy_data;
    } else {
        assert(emit->bytecode_offset + num_bytes_to_write <= emit->bytecode_size);
        byte *c = emit->code_base + emit->code_info_size + emit->bytecode_offset;
        emit->bytecode_offset += num_bytes_to_write;
        return c;
    }
}

STATIC void emit_align_bytecode_to_machine_word(emit_t *emit) {
    emit->bytecode_offset = (emit->bytecode_offset + sizeof(mp_uint_t) - 1) & (~(sizeof(mp_uint_t) - 1));
}

STATIC void emit_write_bytecode_byte(emit_t *emit, byte b1) {
    byte *c = emit_get_cur_to_write_bytecode(emit, 1);
    c[0] = b1;
}

STATIC void emit_write_bytecode_uint(emit_t *emit, mp_uint_t val) {
    emit_write_uint(emit, emit_get_cur_to_write_bytecode, val);
}

STATIC void emit_write_bytecode_byte_byte(emit_t *emit, byte b1, byte b2) {
    assert((b2 & (~0xff)) == 0);
    byte *c = emit_get_cur_to_write_bytecode(emit, 2);
    c[0] = b1;
    c[1] = b2;
}

// Similar to emit_write_bytecode_uint(), just some extra handling to encode sign
STATIC void emit_write_bytecode_byte_int(emit_t *emit, byte b1, mp_int_t num) {
    emit_write_bytecode_byte(emit, b1);

    // We store each 7 bits in a separate byte, and that's how many bytes needed
    byte buf[BYTES_FOR_INT];
    byte *p = buf + sizeof(buf);
    // We encode in little-ending order, but store in big-endian, to help decoding
    do {
        *--p = num & 0x7f;
        num >>= 7;
    } while (num != 0 && num != -1);
    // Make sure that highest bit we stored (mask 0x40) matches sign
    // of the number. If not, store extra byte just to encode sign
    if (num == -1 && (*p & 0x40) == 0) {
        *--p = 0x7f;
    } else if (num == 0 && (*p & 0x40) != 0) {
        *--p = 0;
    }

    byte *c = emit_get_cur_to_write_bytecode(emit, buf + sizeof(buf) - p);
    while (p != buf + sizeof(buf) - 1) {
        *c++ = *p++ | 0x80;
    }
    *c = *p;
}

STATIC void emit_write_bytecode_byte_uint(emit_t *emit, byte b, mp_uint_t val) {
    emit_write_bytecode_byte(emit, b);
    emit_write_uint(emit, emit_get_cur_to_write_bytecode, val);
}

STATIC void emit_write_bytecode_prealigned_ptr(emit_t *emit, void *ptr) {
    mp_uint_t *c = (mp_uint_t*)emit_get_cur_to_write_bytecode(emit, sizeof(mp_uint_t));
    // Verify thar c is already uint-aligned
    assert(c == MP_ALIGN(c, sizeof(mp_uint_t)));
    *c = (mp_uint_t)ptr;
}

// aligns the pointer so it is friendly to GC
STATIC void emit_write_bytecode_byte_ptr(emit_t *emit, byte b, void *ptr) {
    emit_write_bytecode_byte(emit, b);
    emit_align_bytecode_to_machine_word(emit);
    mp_uint_t *c = (mp_uint_t*)emit_get_cur_to_write_bytecode(emit, sizeof(mp_uint_t));
    // Verify thar c is already uint-aligned
    assert(c == MP_ALIGN(c, sizeof(mp_uint_t)));
    *c = (mp_uint_t)ptr;
}

/* currently unused
STATIC void emit_write_bytecode_byte_uint_uint(emit_t *emit, byte b, mp_uint_t num1, mp_uint_t num2) {
    emit_write_bytecode_byte(emit, b);
    emit_write_bytecode_byte_uint(emit, num1);
    emit_write_bytecode_byte_uint(emit, num2);
}
*/

STATIC void emit_write_bytecode_byte_qstr(emit_t *emit, byte b, qstr qst) {
    emit_write_bytecode_byte_uint(emit, b, qst);
}

// unsigned labels are relative to ip following this instruction, stored as 16 bits
STATIC void emit_write_bytecode_byte_unsigned_label(emit_t *emit, byte b1, mp_uint_t label) {
    mp_uint_t bytecode_offset;
    if (emit->pass < MP_PASS_EMIT) {
        bytecode_offset = 0;
    } else {
        bytecode_offset = emit->label_offsets[label] - emit->bytecode_offset - 3;
    }
    byte *c = emit_get_cur_to_write_bytecode(emit, 3);
    c[0] = b1;
    c[1] = bytecode_offset;
    c[2] = bytecode_offset >> 8;
}

// signed labels are relative to ip following this instruction, stored as 16 bits, in excess
STATIC void emit_write_bytecode_byte_signed_label(emit_t *emit, byte b1, mp_uint_t label) {
    int bytecode_offset;
    if (emit->pass < MP_PASS_EMIT) {
        bytecode_offset = 0;
    } else {
        bytecode_offset = emit->label_offsets[label] - emit->bytecode_offset - 3 + 0x8000;
    }
    byte *c = emit_get_cur_to_write_bytecode(emit, 3);
    c[0] = b1;
    c[1] = bytecode_offset;
    c[2] = bytecode_offset >> 8;
}

#if MICROPY_EMIT_NATIVE
STATIC void mp_emit_bc_set_native_type(emit_t *emit, mp_uint_t op, mp_uint_t arg1, qstr arg2) {
    (void)emit;
    (void)op;
    (void)arg1;
    (void)arg2;
}
#endif

void mp_emit_bc_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scope) {
    emit->pass = pass;
    emit->stack_size = 0;
    emit->last_emit_was_return_value = false;
    emit->scope = scope;
    emit->last_source_line_offset = 0;
    emit->last_source_line = 1;
    if (pass < MP_PASS_EMIT) {
        memset(emit->label_offsets, -1, emit->max_num_labels * sizeof(mp_uint_t));
    }
    emit->bytecode_offset = 0;
    emit->code_info_offset = 0;

    // Write code info size as compressed uint.  If we are not in the final pass
    // then space for this uint is reserved in emit_bc_end_pass.
    if (pass == MP_PASS_EMIT) {
        emit_write_code_info_uint(emit, emit->code_info_size);
    }

    // write the name and source file of this function
    emit_write_code_info_qstr(emit, scope->simple_name);
    emit_write_code_info_qstr(emit, scope->source_file);

    // bytecode prelude: argument names (needed to resolve positional args passed as keywords)
    // we store them as full word-sized objects for efficient access in mp_setup_code_state
    // this is the start of the prelude and is guaranteed to be aligned on a word boundary
    {
        // For a given argument position (indexed by i) we need to find the
        // corresponding id_info which is a parameter, as it has the correct
        // qstr name to use as the argument name.  Note that it's not a simple
        // 1-1 mapping (ie i!=j in general) because of possible closed-over
        // variables.  In the case that the argument i has no corresponding
        // parameter we use "*" as its name (since no argument can ever be named
        // "*").  We could use a blank qstr but "*" is better for debugging.
        // Note: there is some wasted RAM here for the case of storing a qstr
        // for each closed-over variable, and maybe there is a better way to do
        // it, but that would require changes to mp_setup_code_state.
        for (int i = 0; i < scope->num_pos_args + scope->num_kwonly_args; i++) {
            qstr qst = MP_QSTR__star_;
            for (int j = 0; j < scope->id_info_len; ++j) {
                id_info_t *id = &scope->id_info[j];
                if ((id->flags & ID_FLAG_IS_PARAM) && id->local_num == i) {
                    qst = id->qst;
                    break;
                }
            }
            emit_write_bytecode_prealigned_ptr(emit, MP_OBJ_NEW_QSTR(qst));
        }
    }

    // bytecode prelude: local state size and exception stack size
    {
        mp_uint_t n_state = scope->num_locals + scope->stack_size;
        if (n_state == 0) {
            // Need at least 1 entry in the state, in the case an exception is
            // propagated through this function, the exception is returned in
            // the highest slot in the state (fastn[0], see vm.c).
            n_state = 1;
        }
        emit_write_bytecode_uint(emit, n_state);
        emit_write_bytecode_uint(emit, scope->exc_stack_size);
    }

    // bytecode prelude: initialise closed over variables
    for (int i = 0; i < scope->id_info_len; i++) {
        id_info_t *id = &scope->id_info[i];
        if (id->kind == ID_INFO_KIND_CELL) {
            assert(id->local_num < 255);
            emit_write_bytecode_byte(emit, id->local_num); // write the local which should be converted to a cell
        }
    }
    emit_write_bytecode_byte(emit, 255); // end of list sentinel
}

void mp_emit_bc_end_pass(emit_t *emit) {
    if (emit->pass == MP_PASS_SCOPE) {
        return;
    }

    // check stack is back to zero size
    if (emit->stack_size != 0) {
        mp_printf(&mp_plat_print, "ERROR: stack size not back to zero; got %d\n", emit->stack_size);
    }

    *emit_get_cur_to_write_code_info(emit, 1) = 0; // end of line number info

    if (emit->pass == MP_PASS_CODE_SIZE) {
        // Need to make sure we have enough room in the code-info block to write
        // the size of the code-info block.  Since the size is written as a
        // compressed uint, we don't know its size until we write it!  Thus, we
        // take the biggest possible value it could be and write that here.
        // Then there will be enough room to write the value, and any leftover
        // space will be absorbed in the alignment at the end of the code-info
        // block.
        mp_uint_t max_code_info_size =
            emit->code_info_offset  // current code-info size
            + BYTES_FOR_INT         // maximum space for compressed uint
            + BYTES_PER_WORD - 1;   // maximum space for alignment padding
        emit_write_code_info_uint(emit, max_code_info_size);

        // Align code-info so that following bytecode is aligned on a machine word.
        // We don't need to write anything here, it's just dead space between the
        // code-info block and the bytecode block that follows it.
        emit_align_code_info_to_machine_word(emit);

        // calculate size of total code-info + bytecode, in bytes
        emit->code_info_size = emit->code_info_offset;
        emit->bytecode_size = emit->bytecode_offset;
        emit->code_base = m_new0(byte, emit->code_info_size + emit->bytecode_size);

    } else if (emit->pass == MP_PASS_EMIT) {
        mp_emit_glue_assign_bytecode(emit->scope->raw_code, emit->code_base,
            emit->code_info_size + emit->bytecode_size,
            emit->scope->num_pos_args, emit->scope->num_kwonly_args,
            emit->scope->scope_flags);
    }
}

bool mp_emit_bc_last_emit_was_return_value(emit_t *emit) {
    return emit->last_emit_was_return_value;
}

void mp_emit_bc_adjust_stack_size(emit_t *emit, mp_int_t delta) {
    emit->stack_size += delta;
}

void mp_emit_bc_set_source_line(emit_t *emit, mp_uint_t source_line) {
    //printf("source: line %d -> %d  offset %d -> %d\n", emit->last_source_line, source_line, emit->last_source_line_offset, emit->bytecode_offset);
#if MICROPY_ENABLE_SOURCE_LINE
    if (MP_STATE_VM(mp_optimise_value) >= 3) {
        // If we compile with -O3, don't store line numbers.
        return;
    }
    if (source_line > emit->last_source_line) {
        mp_uint_t bytes_to_skip = emit->bytecode_offset - emit->last_source_line_offset;
        mp_uint_t lines_to_skip = source_line - emit->last_source_line;
        emit_write_code_info_bytes_lines(emit, bytes_to_skip, lines_to_skip);
        emit->last_source_line_offset = emit->bytecode_offset;
        emit->last_source_line = source_line;
    }
#endif
}

STATIC void emit_bc_pre(emit_t *emit, mp_int_t stack_size_delta) {
    if (emit->pass == MP_PASS_SCOPE) {
        return;
    }
    assert((mp_int_t)emit->stack_size + stack_size_delta >= 0);
    emit->stack_size += stack_size_delta;
    if (emit->stack_size > emit->scope->stack_size) {
        emit->scope->stack_size = emit->stack_size;
    }
    emit->last_emit_was_return_value = false;
}

void mp_emit_bc_label_assign(emit_t *emit, mp_uint_t l) {
    emit_bc_pre(emit, 0);
    if (emit->pass == MP_PASS_SCOPE) {
        return;
    }
    assert(l < emit->max_num_labels);
    if (emit->pass < MP_PASS_EMIT) {
        // assign label offset
        assert(emit->label_offsets[l] == (mp_uint_t)-1);
        emit->label_offsets[l] = emit->bytecode_offset;
    } else {
        // ensure label offset has not changed from MP_PASS_CODE_SIZE to MP_PASS_EMIT
        //printf("l%d: (at %d vs %d)\n", l, emit->bytecode_offset, emit->label_offsets[l]);
        assert(emit->label_offsets[l] == emit->bytecode_offset);
    }
}

void mp_emit_bc_import_name(emit_t *emit, qstr qst) {
    emit_bc_pre(emit, -1);
    emit_write_bytecode_byte_qstr(emit, MP_BC_IMPORT_NAME, qst);
}

void mp_emit_bc_import_from(emit_t *emit, qstr qst) {
    emit_bc_pre(emit, 1);
    emit_write_bytecode_byte_qstr(emit, MP_BC_IMPORT_FROM, qst);
}

void mp_emit_bc_import_star(emit_t *emit) {
    emit_bc_pre(emit, -1);
    emit_write_bytecode_byte(emit, MP_BC_IMPORT_STAR);
}

void mp_emit_bc_load_const_tok(emit_t *emit, mp_token_kind_t tok) {
    emit_bc_pre(emit, 1);
    switch (tok) {
        case MP_TOKEN_KW_FALSE: emit_write_bytecode_byte(emit, MP_BC_LOAD_CONST_FALSE); break;
        case MP_TOKEN_KW_NONE: emit_write_bytecode_byte(emit, MP_BC_LOAD_CONST_NONE); break;
        case MP_TOKEN_KW_TRUE: emit_write_bytecode_byte(emit, MP_BC_LOAD_CONST_TRUE); break;
        no_other_choice:
        case MP_TOKEN_ELLIPSIS: emit_write_bytecode_byte_ptr(emit, MP_BC_LOAD_CONST_OBJ, (void*)&mp_const_ellipsis_obj); break;
        default: assert(0); goto no_other_choice; // to help flow control analysis
    }
}

void mp_emit_bc_load_const_small_int(emit_t *emit, mp_int_t arg) {
    emit_bc_pre(emit, 1);
    if (-16 <= arg && arg <= 47) {
        emit_write_bytecode_byte(emit, MP_BC_LOAD_CONST_SMALL_INT_MULTI + 16 + arg);
    } else {
        emit_write_bytecode_byte_int(emit, MP_BC_LOAD_CONST_SMALL_INT, arg);
    }
}

void mp_emit_bc_load_const_str(emit_t *emit, qstr qst) {
    emit_bc_pre(emit, 1);
    emit_write_bytecode_byte_qstr(emit, MP_BC_LOAD_CONST_STRING, qst);
}

void mp_emit_bc_load_const_obj(emit_t *emit, void *obj) {
    emit_bc_pre(emit, 1);
    emit_write_bytecode_byte_ptr(emit, MP_BC_LOAD_CONST_OBJ, obj);
}

void mp_emit_bc_load_null(emit_t *emit) {
    emit_bc_pre(emit, 1);
    emit_write_bytecode_byte(emit, MP_BC_LOAD_NULL);
};

void mp_emit_bc_load_fast(emit_t *emit, qstr qst, mp_uint_t local_num) {
    (void)qst;
    assert(local_num >= 0);
    emit_bc_pre(emit, 1);
    if (local_num <= 15) {
        emit_write_bytecode_byte(emit, MP_BC_LOAD_FAST_MULTI + local_num);
    } else {
        emit_write_bytecode_byte_uint(emit, MP_BC_LOAD_FAST_N, local_num);
    }
}

void mp_emit_bc_load_deref(emit_t *emit, qstr qst, mp_uint_t local_num) {
    (void)qst;
    emit_bc_pre(emit, 1);
    emit_write_bytecode_byte_uint(emit, MP_BC_LOAD_DEREF, local_num);
}

void mp_emit_bc_load_name(emit_t *emit, qstr qst) {
    (void)qst;
    emit_bc_pre(emit, 1);
    emit_write_bytecode_byte_qstr(emit, MP_BC_LOAD_NAME, qst);
    if (MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE) {
        emit_write_bytecode_byte(emit, 0);
    }
}

void mp_emit_bc_load_global(emit_t *emit, qstr qst) {
    (void)qst;
    emit_bc_pre(emit, 1);
    emit_write_bytecode_byte_qstr(emit, MP_BC_LOAD_GLOBAL, qst);
    if (MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE) {
        emit_write_bytecode_byte(emit, 0);
    }
}

void mp_emit_bc_load_attr(emit_t *emit, qstr qst) {
    emit_bc_pre(emit, 0);
    emit_write_bytecode_byte_qstr(emit, MP_BC_LOAD_ATTR, qst);
    if (MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE) {
        emit_write_bytecode_byte(emit, 0);
    }
}

void mp_emit_bc_load_method(emit_t *emit, qstr qst) {
    emit_bc_pre(emit, 1);
    emit_write_bytecode_byte_qstr(emit, MP_BC_LOAD_METHOD, qst);
}

void mp_emit_bc_load_build_class(emit_t *emit) {
    emit_bc_pre(emit, 1);
    emit_write_bytecode_byte(emit, MP_BC_LOAD_BUILD_CLASS);
}

void mp_emit_bc_load_subscr(emit_t *emit) {
    emit_bc_pre(emit, -1);
    emit_write_bytecode_byte(emit, MP_BC_LOAD_SUBSCR);
}

void mp_emit_bc_store_fast(emit_t *emit, qstr qst, mp_uint_t local_num) {
    (void)qst;
    assert(local_num >= 0);
    emit_bc_pre(emit, -1);
    if (local_num <= 15) {
        emit_write_bytecode_byte(emit, MP_BC_STORE_FAST_MULTI + local_num);
    } else {
        emit_write_bytecode_byte_uint(emit, MP_BC_STORE_FAST_N, local_num);
    }
}

void mp_emit_bc_store_deref(emit_t *emit, qstr qst, mp_uint_t local_num) {
    (void)qst;
    emit_bc_pre(emit, -1);
    emit_write_bytecode_byte_uint(emit, MP_BC_STORE_DEREF, local_num);
}

void mp_emit_bc_store_name(emit_t *emit, qstr qst) {
    emit_bc_pre(emit, -1);
    emit_write_bytecode_byte_qstr(emit, MP_BC_STORE_NAME, qst);
}

void mp_emit_bc_store_global(emit_t *emit, qstr qst) {
    emit_bc_pre(emit, -1);
    emit_write_bytecode_byte_qstr(emit, MP_BC_STORE_GLOBAL, qst);
}

void mp_emit_bc_store_attr(emit_t *emit, qstr qst) {
    emit_bc_pre(emit, -2);
    emit_write_bytecode_byte_qstr(emit, MP_BC_STORE_ATTR, qst);
    if (MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE) {
        emit_write_bytecode_byte(emit, 0);
    }
}

void mp_emit_bc_store_subscr(emit_t *emit) {
    emit_bc_pre(emit, -3);
    emit_write_bytecode_byte(emit, MP_BC_STORE_SUBSCR);
}

void mp_emit_bc_delete_fast(emit_t *emit, qstr qst, mp_uint_t local_num) {
    (void)qst;
    emit_write_bytecode_byte_uint(emit, MP_BC_DELETE_FAST, local_num);
}

void mp_emit_bc_delete_deref(emit_t *emit, qstr qst, mp_uint_t local_num) {
    (void)qst;
    emit_write_bytecode_byte_uint(emit, MP_BC_DELETE_DEREF, local_num);
}

void mp_emit_bc_delete_name(emit_t *emit, qstr qst) {
    emit_bc_pre(emit, 0);
    emit_write_bytecode_byte_qstr(emit, MP_BC_DELETE_NAME, qst);
}

void mp_emit_bc_delete_global(emit_t *emit, qstr qst) {
    emit_bc_pre(emit, 0);
    emit_write_bytecode_byte_qstr(emit, MP_BC_DELETE_GLOBAL, qst);
}

void mp_emit_bc_delete_attr(emit_t *emit, qstr qst) {
    mp_emit_bc_load_null(emit);
    mp_emit_bc_rot_two(emit);
    mp_emit_bc_store_attr(emit, qst);
}

void mp_emit_bc_delete_subscr(emit_t *emit) {
    mp_emit_bc_load_null(emit);
    mp_emit_bc_rot_three(emit);
    mp_emit_bc_store_subscr(emit);
}

void mp_emit_bc_dup_top(emit_t *emit) {
    emit_bc_pre(emit, 1);
    emit_write_bytecode_byte(emit, MP_BC_DUP_TOP);
}

void mp_emit_bc_dup_top_two(emit_t *emit) {
    emit_bc_pre(emit, 2);
    emit_write_bytecode_byte(emit, MP_BC_DUP_TOP_TWO);
}

void mp_emit_bc_pop_top(emit_t *emit) {
    emit_bc_pre(emit, -1);
    emit_write_bytecode_byte(emit, MP_BC_POP_TOP);
}

void mp_emit_bc_rot_two(emit_t *emit) {
    emit_bc_pre(emit, 0);
    emit_write_bytecode_byte(emit, MP_BC_ROT_TWO);
}

void mp_emit_bc_rot_three(emit_t *emit) {
    emit_bc_pre(emit, 0);
    emit_write_bytecode_byte(emit, MP_BC_ROT_THREE);
}

void mp_emit_bc_jump(emit_t *emit, mp_uint_t label) {
    emit_bc_pre(emit, 0);
    emit_write_bytecode_byte_signed_label(emit, MP_BC_JUMP, label);
}

void mp_emit_bc_pop_jump_if(emit_t *emit, bool cond, mp_uint_t label) {
    emit_bc_pre(emit, -1);
    if (cond) {
        emit_write_bytecode_byte_signed_label(emit, MP_BC_POP_JUMP_IF_TRUE, label);
    } else {
        emit_write_bytecode_byte_signed_label(emit, MP_BC_POP_JUMP_IF_FALSE, label);
    }
}

void mp_emit_bc_jump_if_or_pop(emit_t *emit, bool cond, mp_uint_t label) {
    emit_bc_pre(emit, -1);
    if (cond) {
        emit_write_bytecode_byte_signed_label(emit, MP_BC_JUMP_IF_TRUE_OR_POP, label);
    } else {
        emit_write_bytecode_byte_signed_label(emit, MP_BC_JUMP_IF_FALSE_OR_POP, label);
    }
}

void mp_emit_bc_unwind_jump(emit_t *emit, mp_uint_t label, mp_uint_t except_depth) {
    if (except_depth == 0) {
        emit_bc_pre(emit, 0);
        if (label & MP_EMIT_BREAK_FROM_FOR) {
            // need to pop the iterator if we are breaking out of a for loop
            emit_write_bytecode_byte(emit, MP_BC_POP_TOP);
        }
        emit_write_bytecode_byte_signed_label(emit, MP_BC_JUMP, label & ~MP_EMIT_BREAK_FROM_FOR);
    } else {
        emit_write_bytecode_byte_signed_label(emit, MP_BC_UNWIND_JUMP, label & ~MP_EMIT_BREAK_FROM_FOR);
        emit_write_bytecode_byte(emit, ((label & MP_EMIT_BREAK_FROM_FOR) ? 0x80 : 0) | except_depth);
    }
}

void mp_emit_bc_setup_with(emit_t *emit, mp_uint_t label) {
    // TODO We can probably optimise the amount of needed stack space, since
    // we don't actually need 4 slots during the entire with block, only in
    // the cleanup handler in certain cases.  It needs some thinking.
    emit_bc_pre(emit, 4);
    emit_write_bytecode_byte_unsigned_label(emit, MP_BC_SETUP_WITH, label);
}

void mp_emit_bc_with_cleanup(emit_t *emit) {
    emit_bc_pre(emit, -4);
    emit_write_bytecode_byte(emit, MP_BC_WITH_CLEANUP);
}

void mp_emit_bc_setup_except(emit_t *emit, mp_uint_t label) {
    emit_bc_pre(emit, 0);
    emit_write_bytecode_byte_unsigned_label(emit, MP_BC_SETUP_EXCEPT, label);
}

void mp_emit_bc_setup_finally(emit_t *emit, mp_uint_t label) {
    emit_bc_pre(emit, 0);
    emit_write_bytecode_byte_unsigned_label(emit, MP_BC_SETUP_FINALLY, label);
}

void mp_emit_bc_end_finally(emit_t *emit) {
    emit_bc_pre(emit, -1);
    emit_write_bytecode_byte(emit, MP_BC_END_FINALLY);
}

void mp_emit_bc_get_iter(emit_t *emit) {
    emit_bc_pre(emit, 0);
    emit_write_bytecode_byte(emit, MP_BC_GET_ITER);
}

void mp_emit_bc_for_iter(emit_t *emit, mp_uint_t label) {
    emit_bc_pre(emit, 1);
    emit_write_bytecode_byte_unsigned_label(emit, MP_BC_FOR_ITER, label);
}

void mp_emit_bc_for_iter_end(emit_t *emit) {
    emit_bc_pre(emit, -1);
}

void mp_emit_bc_pop_block(emit_t *emit) {
    emit_bc_pre(emit, 0);
    emit_write_bytecode_byte(emit, MP_BC_POP_BLOCK);
}

void mp_emit_bc_pop_except(emit_t *emit) {
    emit_bc_pre(emit, 0);
    emit_write_bytecode_byte(emit, MP_BC_POP_EXCEPT);
}

void mp_emit_bc_unary_op(emit_t *emit, mp_unary_op_t op) {
    if (op == MP_UNARY_OP_NOT) {
        emit_bc_pre(emit, 0);
        emit_write_bytecode_byte(emit, MP_BC_UNARY_OP_MULTI + MP_UNARY_OP_BOOL);
        emit_bc_pre(emit, 0);
        emit_write_bytecode_byte(emit, MP_BC_NOT);
    } else {
        emit_bc_pre(emit, 0);
        emit_write_bytecode_byte(emit, MP_BC_UNARY_OP_MULTI + op);
    }
}

void mp_emit_bc_binary_op(emit_t *emit, mp_binary_op_t op) {
    bool invert = false;
    if (op == MP_BINARY_OP_NOT_IN) {
        invert = true;
        op = MP_BINARY_OP_IN;
    } else if (op == MP_BINARY_OP_IS_NOT) {
        invert = true;
        op = MP_BINARY_OP_IS;
    }
    emit_bc_pre(emit, -1);
    emit_write_bytecode_byte(emit, MP_BC_BINARY_OP_MULTI + op);
    if (invert) {
        emit_bc_pre(emit, 0);
        emit_write_bytecode_byte(emit, MP_BC_NOT);
    }
}

void mp_emit_bc_build_tuple(emit_t *emit, mp_uint_t n_args) {
    emit_bc_pre(emit, 1 - n_args);
    emit_write_bytecode_byte_uint(emit, MP_BC_BUILD_TUPLE, n_args);
}

void mp_emit_bc_build_list(emit_t *emit, mp_uint_t n_args) {
    emit_bc_pre(emit, 1 - n_args);
    emit_write_bytecode_byte_uint(emit, MP_BC_BUILD_LIST, n_args);
}

void mp_emit_bc_list_append(emit_t *emit, mp_uint_t list_stack_index) {
    emit_bc_pre(emit, -1);
    emit_write_bytecode_byte_uint(emit, MP_BC_LIST_APPEND, list_stack_index);
}

void mp_emit_bc_build_map(emit_t *emit, mp_uint_t n_args) {
    emit_bc_pre(emit, 1);
    emit_write_bytecode_byte_uint(emit, MP_BC_BUILD_MAP, n_args);
}

void mp_emit_bc_store_map(emit_t *emit) {
    emit_bc_pre(emit, -2);
    emit_write_bytecode_byte(emit, MP_BC_STORE_MAP);
}

void mp_emit_bc_map_add(emit_t *emit, mp_uint_t map_stack_index) {
    emit_bc_pre(emit, -2);
    emit_write_bytecode_byte_uint(emit, MP_BC_MAP_ADD, map_stack_index);
}

#if MICROPY_PY_BUILTINS_SET
void mp_emit_bc_build_set(emit_t *emit, mp_uint_t n_args) {
    emit_bc_pre(emit, 1 - n_args);
    emit_write_bytecode_byte_uint(emit, MP_BC_BUILD_SET, n_args);
}

void mp_emit_bc_set_add(emit_t *emit, mp_uint_t set_stack_index) {
    emit_bc_pre(emit, -1);
    emit_write_bytecode_byte_uint(emit, MP_BC_SET_ADD, set_stack_index);
}
#endif

#if MICROPY_PY_BUILTINS_SLICE
void mp_emit_bc_build_slice(emit_t *emit, mp_uint_t n_args) {
    emit_bc_pre(emit, 1 - n_args);
    emit_write_bytecode_byte_uint(emit, MP_BC_BUILD_SLICE, n_args);
}
#endif

void mp_emit_bc_unpack_sequence(emit_t *emit, mp_uint_t n_args) {
    emit_bc_pre(emit, -1 + n_args);
    emit_write_bytecode_byte_uint(emit, MP_BC_UNPACK_SEQUENCE, n_args);
}

void mp_emit_bc_unpack_ex(emit_t *emit, mp_uint_t n_left, mp_uint_t n_right) {
    emit_bc_pre(emit, -1 + n_left + n_right + 1);
    emit_write_bytecode_byte_uint(emit, MP_BC_UNPACK_EX, n_left | (n_right << 8));
}

void mp_emit_bc_make_function(emit_t *emit, scope_t *scope, mp_uint_t n_pos_defaults, mp_uint_t n_kw_defaults) {
    if (n_pos_defaults == 0 && n_kw_defaults == 0) {
        emit_bc_pre(emit, 1);
        emit_write_bytecode_byte_ptr(emit, MP_BC_MAKE_FUNCTION, scope->raw_code);
    } else {
        emit_bc_pre(emit, -1);
        emit_write_bytecode_byte_ptr(emit, MP_BC_MAKE_FUNCTION_DEFARGS, scope->raw_code);
    }
}

void mp_emit_bc_make_closure(emit_t *emit, scope_t *scope, mp_uint_t n_closed_over, mp_uint_t n_pos_defaults, mp_uint_t n_kw_defaults) {
    if (n_pos_defaults == 0 && n_kw_defaults == 0) {
        emit_bc_pre(emit, -n_closed_over + 1);
        emit_write_bytecode_byte_ptr(emit, MP_BC_MAKE_CLOSURE, scope->raw_code);
        emit_write_bytecode_byte(emit, n_closed_over);
    } else {
        assert(n_closed_over <= 255);
        emit_bc_pre(emit, -2 - n_closed_over + 1);
        emit_write_bytecode_byte_ptr(emit, MP_BC_MAKE_CLOSURE_DEFARGS, scope->raw_code);
        emit_write_bytecode_byte(emit, n_closed_over);
    }
}

STATIC void emit_bc_call_function_method_helper(emit_t *emit, mp_int_t stack_adj, mp_uint_t bytecode_base, mp_uint_t n_positional, mp_uint_t n_keyword, mp_uint_t star_flags) {
    if (star_flags) {
        if (!(star_flags & MP_EMIT_STAR_FLAG_SINGLE)) {
            // load dummy entry for non-existent pos_seq
            mp_emit_bc_load_null(emit);
            mp_emit_bc_rot_two(emit);
        } else if (!(star_flags & MP_EMIT_STAR_FLAG_DOUBLE)) {
            // load dummy entry for non-existent kw_dict
            mp_emit_bc_load_null(emit);
        }
        emit_bc_pre(emit, stack_adj - (mp_int_t)n_positional - 2 * (mp_int_t)n_keyword - 2);
        emit_write_bytecode_byte_uint(emit, bytecode_base + 1, (n_keyword << 8) | n_positional); // TODO make it 2 separate uints?
    } else {
        emit_bc_pre(emit, stack_adj - (mp_int_t)n_positional - 2 * (mp_int_t)n_keyword);
        emit_write_bytecode_byte_uint(emit, bytecode_base, (n_keyword << 8) | n_positional); // TODO make it 2 separate uints?
    }
}

void mp_emit_bc_call_function(emit_t *emit, mp_uint_t n_positional, mp_uint_t n_keyword, mp_uint_t star_flags) {
    emit_bc_call_function_method_helper(emit, 0, MP_BC_CALL_FUNCTION, n_positional, n_keyword, star_flags);
}

void mp_emit_bc_call_method(emit_t *emit, mp_uint_t n_positional, mp_uint_t n_keyword, mp_uint_t star_flags) {
    emit_bc_call_function_method_helper(emit, -1, MP_BC_CALL_METHOD, n_positional, n_keyword, star_flags);
}

void mp_emit_bc_return_value(emit_t *emit) {
    emit_bc_pre(emit, -1);
    emit->last_emit_was_return_value = true;
    emit_write_bytecode_byte(emit, MP_BC_RETURN_VALUE);
}

void mp_emit_bc_raise_varargs(emit_t *emit, mp_uint_t n_args) {
    assert(0 <= n_args && n_args <= 2);
    emit_bc_pre(emit, -n_args);
    emit_write_bytecode_byte_byte(emit, MP_BC_RAISE_VARARGS, n_args);
}

void mp_emit_bc_yield_value(emit_t *emit) {
    emit_bc_pre(emit, 0);
    emit->scope->scope_flags |= MP_SCOPE_FLAG_GENERATOR;
    emit_write_bytecode_byte(emit, MP_BC_YIELD_VALUE);
}

void mp_emit_bc_yield_from(emit_t *emit) {
    emit_bc_pre(emit, -1);
    emit->scope->scope_flags |= MP_SCOPE_FLAG_GENERATOR;
    emit_write_bytecode_byte(emit, MP_BC_YIELD_FROM);
}

void mp_emit_bc_start_except_handler(emit_t *emit) {
    mp_emit_bc_adjust_stack_size(emit, 6); // stack adjust for the 3 exception items, +3 for possible UNWIND_JUMP state
}

void mp_emit_bc_end_except_handler(emit_t *emit) {
    mp_emit_bc_adjust_stack_size(emit, -5); // stack adjust
}

#if MICROPY_EMIT_NATIVE
const emit_method_table_t emit_bc_method_table = {
    mp_emit_bc_set_native_type,
    mp_emit_bc_start_pass,
    mp_emit_bc_end_pass,
    mp_emit_bc_last_emit_was_return_value,
    mp_emit_bc_adjust_stack_size,
    mp_emit_bc_set_source_line,

    {
        mp_emit_bc_load_fast,
        mp_emit_bc_load_deref,
        mp_emit_bc_load_name,
        mp_emit_bc_load_global,
    },
    {
        mp_emit_bc_store_fast,
        mp_emit_bc_store_deref,
        mp_emit_bc_store_name,
        mp_emit_bc_store_global,
    },
    {
        mp_emit_bc_delete_fast,
        mp_emit_bc_delete_deref,
        mp_emit_bc_delete_name,
        mp_emit_bc_delete_global,
    },

    mp_emit_bc_label_assign,
    mp_emit_bc_import_name,
    mp_emit_bc_import_from,
    mp_emit_bc_import_star,
    mp_emit_bc_load_const_tok,
    mp_emit_bc_load_const_small_int,
    mp_emit_bc_load_const_str,
    mp_emit_bc_load_const_obj,
    mp_emit_bc_load_null,
    mp_emit_bc_load_attr,
    mp_emit_bc_load_method,
    mp_emit_bc_load_build_class,
    mp_emit_bc_load_subscr,
    mp_emit_bc_store_attr,
    mp_emit_bc_store_subscr,
    mp_emit_bc_delete_attr,
    mp_emit_bc_delete_subscr,
    mp_emit_bc_dup_top,
    mp_emit_bc_dup_top_two,
    mp_emit_bc_pop_top,
    mp_emit_bc_rot_two,
    mp_emit_bc_rot_three,
    mp_emit_bc_jump,
    mp_emit_bc_pop_jump_if,
    mp_emit_bc_jump_if_or_pop,
    mp_emit_bc_unwind_jump,
    mp_emit_bc_unwind_jump,
    mp_emit_bc_setup_with,
    mp_emit_bc_with_cleanup,
    mp_emit_bc_setup_except,
    mp_emit_bc_setup_finally,
    mp_emit_bc_end_finally,
    mp_emit_bc_get_iter,
    mp_emit_bc_for_iter,
    mp_emit_bc_for_iter_end,
    mp_emit_bc_pop_block,
    mp_emit_bc_pop_except,
    mp_emit_bc_unary_op,
    mp_emit_bc_binary_op,
    mp_emit_bc_build_tuple,
    mp_emit_bc_build_list,
    mp_emit_bc_list_append,
    mp_emit_bc_build_map,
    mp_emit_bc_store_map,
    mp_emit_bc_map_add,
    #if MICROPY_PY_BUILTINS_SET
    mp_emit_bc_build_set,
    mp_emit_bc_set_add,
    #endif
    #if MICROPY_PY_BUILTINS_SLICE
    mp_emit_bc_build_slice,
    #endif
    mp_emit_bc_unpack_sequence,
    mp_emit_bc_unpack_ex,
    mp_emit_bc_make_function,
    mp_emit_bc_make_closure,
    mp_emit_bc_call_function,
    mp_emit_bc_call_method,
    mp_emit_bc_return_value,
    mp_emit_bc_raise_varargs,
    mp_emit_bc_yield_value,
    mp_emit_bc_yield_from,

    mp_emit_bc_start_except_handler,
    mp_emit_bc_end_except_handler,
};
#else
const mp_emit_method_table_id_ops_t mp_emit_bc_method_table_load_id_ops = {
    mp_emit_bc_load_fast,
    mp_emit_bc_load_deref,
    mp_emit_bc_load_name,
    mp_emit_bc_load_global,
};

const mp_emit_method_table_id_ops_t mp_emit_bc_method_table_store_id_ops = {
    mp_emit_bc_store_fast,
    mp_emit_bc_store_deref,
    mp_emit_bc_store_name,
    mp_emit_bc_store_global,
};

const mp_emit_method_table_id_ops_t mp_emit_bc_method_table_delete_id_ops = {
    mp_emit_bc_delete_fast,
    mp_emit_bc_delete_deref,
    mp_emit_bc_delete_name,
    mp_emit_bc_delete_global,
};
#endif


text:
@interface SRFieldDetailViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, retain) IBOutlet UITableView *tableView;

@property (nonatomic, retain) SRField *field;
@property (nonatomic, retain) NSArray *methodNames;

@end


text:
SELECT
Id,
date

FROM study.necropsies
WHERE cast(date as date) = cast((SELECT MAX(date) FROM study.necropsies WHERE QCState.Label = 'Completed') as date)


text:
.. _internals:

.. currentmodule:: pandas

.. ipython:: python
   :suppress:

   import numpy as np
   np.random.seed(123456)
   np.set_printoptions(precision=4, suppress=True)
   import pandas as pd
   pd.options.display.max_rows = 15

*********
Internals
*********

This section will provide a look into some of pandas internals.

Indexing
--------

In pandas there are a few objects implemented which can serve as valid
containers for the axis labels:

- ``Index``: the generic "ordered set" object, an ndarray of object dtype
  assuming nothing about its contents. The labels must be hashable (and
  likely immutable) and unique. Populates a dict of label to location in
  Cython to do ``O(1)`` lookups.
- ``Int64Index``: a version of ``Index`` highly optimized for 64-bit integer
  data, such as time stamps
- ``Float64Index``: a version of ``Index`` highly optimized for 64-bit float data
- ``MultiIndex``: the standard hierarchical index object
- ``DatetimeIndex``: An Index object with ``Timestamp`` boxed elements (impl are the int64 values)
- ``TimedeltaIndex``: An Index object with ``Timedelta`` boxed elements (impl are the in64 values)
- ``PeriodIndex``: An Index object with Period elements

There are functions that make the creation of a regular index easy:

- ``date_range``: fixed frequency date range generated from a time rule or
  DateOffset. An ndarray of Python datetime objects
- ``period_range``: fixed frequency date range generated from a time rule or
  DateOffset. An ndarray of ``Period`` objects, representing Timespans

The motivation for having an ``Index`` class in the first place was to enable
different implementations of indexing. This means that it's possible for you,
the user, to implement a custom ``Index`` subclass that may be better suited to
a particular application than the ones provided in pandas.

From an internal implementation point of view, the relevant methods that an
``Index`` must define are one or more of the following (depending on how
incompatible the new object internals are with the ``Index`` functions):

- ``get_loc``: returns an "indexer" (an integer, or in some cases a
  slice object) for a label
- ``slice_locs``: returns the "range" to slice between two labels
- ``get_indexer``: Computes the indexing vector for reindexing / data
  alignment purposes. See the source / docstrings for more on this
- ``get_indexer_non_unique``: Computes the indexing vector for reindexing / data
  alignment purposes when the index is non-unique. See the source / docstrings
  for more on this
- ``reindex``: Does any pre-conversion of the input index then calls
  ``get_indexer``
- ``union``, ``intersection``: computes the union or intersection of two
  Index objects
- ``insert``: Inserts a new label into an Index, yielding a new object
- ``delete``: Delete a label, yielding a new object
- ``drop``: Deletes a set of labels
- ``take``: Analogous to ndarray.take

MultiIndex
~~~~~~~~~~

Internally, the ``MultiIndex`` consists of a few things: the **levels**, the
integer **labels**, and the level **names**:

.. ipython:: python

   index = pd.MultiIndex.from_product([range(3), ['one', 'two']], names=['first', 'second'])
   index
   index.levels
   index.labels
   index.names

You can probably guess that the labels determine which unique element is
identified with that location at each layer of the index. It's important to
note that sortedness is determined **solely** from the integer labels and does
not check (or care) whether the levels themselves are sorted. Fortunately, the
constructors ``from_tuples`` and ``from_arrays`` ensure that this is true, but
if you compute the levels and labels yourself, please be careful.

.. _ref-subclassing-pandas:

Subclassing pandas Data Structures
----------------------------------

.. warning:: There are some easier alternatives before considering subclassing ``pandas`` data structures.

  1. Extensible method chains with :ref:`pipe <basics.pipe>`

  2. Use *composition*. See `here <http://en.wikipedia.org/wiki/Composition_over_inheritance>`_.

This section describes how to subclass ``pandas`` data structures to meet more specific needs. There are 2 points which need attention:

1. Override constructor properties.
2. Define original properties

.. note:: You can find a nice example in `geopandas <https://github.com/geopandas/geopandas>`_ project.

Override Constructor Properties
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Each data structure has constructor properties to specifying data constructors. By overriding these properties, you can retain defined-classes through ``pandas`` data manipulations.

There are 3 constructors to be defined:

- ``_constructor``: Used when a manipulation result has the same dimesions as the original.
- ``_constructor_sliced``: Used when a manipulation result has one lower dimension(s) as the original, such as ``DataFrame`` single columns slicing.
- ``_constructor_expanddim``: Used when a manipulation result has one higher dimension as the original, such as ``Series.to_frame()`` and ``DataFrame.to_panel()``.

Following table shows how ``pandas`` data structures define constructor properties by default.

===========================  ======================= =================== =======================
Property Attributes          ``Series``              ``DataFrame``       ``Panel``
===========================  ======================= =================== =======================
``_constructor``             ``Series``              ``DataFrame``       ``Panel``
``_constructor_sliced``      ``NotImplementedError`` ``Series``          ``DataFrame``
``_constructor_expanddim``   ``DataFrame``           ``Panel``           ``NotImplementedError``
===========================  ======================= =================== =======================

Below example shows how to define ``SubclassedSeries`` and ``SubclassedDataFrame`` overriding constructor properties.

.. code-block:: python

   class SubclassedSeries(Series):

       @property
       def _constructor(self):
           return SubclassedSeries

       @property
       def _constructor_expanddim(self):
           return SubclassedDataFrame

   class SubclassedDataFrame(DataFrame):

       @property
       def _constructor(self):
           return SubclassedDataFrame

       @property
       def _constructor_sliced(self):
           return SubclassedSeries

.. code-block:: python

   >>> s = SubclassedSeries([1, 2, 3])
   >>> type(s)
   <class '__main__.SubclassedSeries'>

   >>> to_framed = s.to_frame()
   >>> type(to_framed)
   <class '__main__.SubclassedDataFrame'>

   >>> df = SubclassedDataFrame({'A', [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
   >>> df
      A  B  C
   0  1  4  7
   1  2  5  8
   2  3  6  9

   >>> type(df)
   <class '__main__.SubclassedDataFrame'>

   >>> sliced1 = df[['A', 'B']]
   >>> sliced1
      A  B
   0  1  4
   1  2  5
   2  3  6
   >>> type(sliced1)
   <class '__main__.SubclassedDataFrame'>

   >>> sliced2 = df['A']
   >>> sliced2
   0    1
   1    2
   2    3
   Name: A, dtype: int64
   >>> type(sliced2)
   <class '__main__.SubclassedSeries'>

Define Original Properties
~~~~~~~~~~~~~~~~~~~~~~~~~~

To let original data structures have additional properties, you should let ``pandas`` know what properties are added. ``pandas`` maps unknown properties to data names overriding ``__getattribute__``. Defining original properties can be done in one of 2 ways:

1. Define ``_internal_names`` and ``_internal_names_set`` for temporary properties which WILL NOT be passed to manipulation results.
2. Define ``_metadata`` for normal properties which will be passed to manipulation results.

Below is an example to define 2 original properties, "internal_cache" as a temporary property and "added_property" as a normal property

.. code-block:: python

   class SubclassedDataFrame2(DataFrame):

       # temporary properties
       _internal_names = pd.DataFrame._internal_names + ['internal_cache']
       _internal_names_set = set(_internal_names)

       # normal properties
       _metadata = ['added_property']

       @property
       def _constructor(self):
           return SubclassedDataFrame2

.. code-block:: python

   >>> df = SubclassedDataFrame2({'A', [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
   >>> df
      A  B  C
   0  1  4  7
   1  2  5  8
   2  3  6  9

   >>> df.internal_cache = 'cached'
   >>> df.added_property = 'property'

   >>> df.internal_cache
   cached
   >>> df.added_property
   property

   # properties defined in _internal_names is reset after manipulation
   >>> df[['A', 'B']].internal_cache
   AttributeError: 'SubclassedDataFrame2' object has no attribute 'internal_cache'

   # properties defined in _metadata are retained
   >>> df[['A', 'B']].added_property
   property


text:
var path = require('path');
var _ = require('lodash');
var Promise = require('bluebird');

module.exports = (function(){
  return new InitCommand();
})();

module.exports.InitCommand = InitCommand;

function InitCommand() {
  this.usage = 'Usage: $0 init';
  this.options = {
    'yes': {
      description: 'Accept default values',
      alias: 'y'
    }
  };
}

InitCommand.prototype.validate = function(args, rapido) {
  if(args._.length > 0){
    throw 'Unexpected command line arguement';
  }

  return {
    yes: args.yes
  };
};

InitCommand.prototype.run = function(args, config, rapido) {
  var self = this;
  return new Promise(function(resolve, reject){
    self._getRepos(args, rapido).then(function(repos){
      resolve(self._writeConfig(repos, config, rapido));
    })
    .catch(function(err){
      rapido.log.error(err);
      reject(err);
    });
  });
};

InitCommand.prototype._writeConfig = function(repos, config, rapido){
  return new Promise(function(resolve, reject){
    rapido.writeConfig(path.join(process.cwd(), rapido.configFilename), {
      dependencies: repos
    });

    if (repos.length > 0) {
      rapido.log.success('Successfully loaded ' + _.map(repos, 'name').join(', '));
    } else {
      rapido.log.info('No repositories found');
    }
    resolve(undefined);
  });
};

InitCommand.prototype._getRepos = function(args, rapido) {
  var self = this;
  var promptProps = {
    properties: {
      name: {
        descritpion: 'Git repository name',
        require: true
      },
      url: {
        description: 'Git repository URL',
        required: true
      },
      more: {
        description: 'Add another repository?',
        default: 'y',
        required: false,
        pattern: /^y|n|yes|no$/i,
        message: 'Must enter yes or no',
        before: function(value){return value.match(/^y|yes$/i);}
      }
    }
  };
  return new Promise(function(resolve, reject){
    if(args.yes){
      return resolve([]);
    }

    rapido.prompt.start();
    var promptGet = Promise.promisify(rapido.prompt.get);
    promptGet(promptProps).then(function(result){
      if(!args.result) args.result = [];

      args.result.push({
        name: result.name,
        url: result.url
      });

      if(result.more){
        resolve(self._getRepos(args, rapido));
      } else {
        resolve(args.result);
      }
    })
    .catch(function(err){
      reject(err);
    });
  });
};


text:
package com.spectralogic.dsbrowser.gui.util;

public final class ByteFormat {

    public static String humanReadableByteCount(final long bytes, final boolean si) {
        final int unit = si ? 1000 : 1024;
        if (bytes < unit) {
            return bytes + " B";
        }

        final int exp = (int) (Math.log(bytes) / Math.log(unit));
        final String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");

        return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
    }
}


text:
<!DOCTYPE html>

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

    <link href="{{ config.STATIC_URL }}/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="{{ config.STATIC_URL }}/fontawesome/css/font-awesome.min.css?v=4.7.0" rel="stylesheet">
    <link href="{{ config.STATIC_URL }}/snappass/css/custom.css" rel="stylesheet">

          Heroku Snappass

    {% block content %}{% endblock %}

    {% block js %}{% endblock %}

Heroku fork of the original from the great folks at Pinterest.


text:
export default function useSocialShare({ text, url }) {
  function share(service) {
    const encodedText = encodeURIComponent(text);
    const encodedUrl = encodeURIComponent(url);

    if (navigator.share) {
      return navigator.share({
        url,
        text,
        title: '',
      });
    }

    if (service === 'twitter') {
      return window.open(`https://twitter.com/intent/tweet?text=${encodedText}&url=${encodedUrl}`, '_newtab');
    }

    if (service === 'facebook') {
      return window.open(`https://www.facebook.com/sharer/sharer.php?quote=${encodedText}&u=${encodedUrl}`, '_newtab');
    }

    if (service === 'messenger') {
      return window.open(
        `https://www.facebook.com/dialog/send?app_id=${
          process.env.GATSBY_FB_APP_ID
        }&link=${encodedUrl}&redirect_uri=${encodedUrl}`,
        '_newtab',
      );
    }

    return null;
  }

  return share;
}


text:
import taskController from '../../database/controllers/task-controller'
import taskConstants from '../../database/constants/task'
import { validateRequiredArgument } from '../argument-validation'

export function updateTaskModel(taskModel, options) {
	var { lastExecutedOn, status } = options

	taskModel.lastExecutedOn = lastExecutedOn
	taskModel.status = status
}

export default function finishTask(taskModel, error){
	validateRequiredArgument({ taskModel })

	return new Promise((resolve, reject) => {
		try {

			updateTaskModel(taskModel, {
				lastExecutedOn: Date.now(),
				status : error ? taskConstants.statusses.error : taskConstants.statusses.success
			})

			taskModel.save().then(() => {
				resolve(taskModel)
			}).catch(reject)
		}
		catch(error) {
			reject(error)
		}
	})
}


text:
package com.parse.buzzbox;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;

public class GalleryImageAdapter extends BaseAdapter {

	private Context mContext;

	private Integer[] mImageIds = {
            R.drawable.avatar1,
            R.drawable.avatar2,
            R.drawable.avatar3,
            R.drawable.avatar4,
            R.drawable.avatar5,
            R.drawable.avatar6,
            R.drawable.avatar7,
            R.drawable.avatar8,
            R.drawable.avatar9
    };

    public GalleryImageAdapter(Context context)
    {
        mContext = context;
    }

    public int getCount() {
        return mImageIds.length;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    // Override this method according to your need
    @SuppressWarnings("deprecation")
	public View getView(int index, View view, ViewGroup viewGroup)
    {
        // TODO Auto-generated method stub
        ImageView i = new ImageView(mContext);

        i.setImageResource(mImageIds[index]);
        i.setLayoutParams(new Gallery.LayoutParams(200, 200));

        i.setScaleType(ImageView.ScaleType.FIT_XY);

        return i;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<agency.tango.materialintroscreen.parallax.ParallaxLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:paddingTop="100dp"
    android:paddingBottom="90dp"
    android:paddingLeft="15dp"
    android:paddingRight="15dp"
    android:background="#154360"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textview"
        android:layout_width="fill_parent"
        android:text="Device Setup"
        android:layout_height="wrap_content"
        android:textAlignment="center"
        android:paddingBottom="10dp"
        android:textSize="10pt"
        android:textStyle="bold"
        android:textColor="#DC7633"

        />
    <TextView
        android:id="@+id/textview_app_no"
        android:layout_width="fill_parent"
        android:text="2/3"
        android:layout_height="wrap_content"
        android:textAlignment="center"
        android:paddingBottom="90dp"
        android:textSize="7pt"
        android:textColor="#DC7633"

        />

    <ListView
        android:id="@+id/listview"
        android:background="#283747"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />

</agency.tango.materialintroscreen.parallax.ParallaxLinearLayout>


text:
ActiveRecord::Schema.define(version: 20140929090407) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "movies", force: true do |t|
    t.string   "title"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.text     "description"
    t.string   "category"
  end

  create_table "ratings", force: true do |t|
    t.integer  "value"
    t.integer  "user_id"
    t.integer  "movie_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "users", force: true do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.inet     "current_sign_in_ip"
    t.inet     "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree

end


text: export declare const safeEval: <T>(expression: string, context?: any) => T;


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("Umbraco.Core")]
[assembly: AssemblyDescription("Umbraco Core")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Umbraco CMS")]

[assembly: ComVisible(false)]
[assembly: Guid("130a6b5c-50e7-4df3-a0dd-e9e7eb0b7c5c")]

// Umbraco Cms
[assembly: InternalsVisibleTo("Umbraco.Web")]
[assembly: InternalsVisibleTo("Umbraco.Web.UI")]
[assembly: InternalsVisibleTo("Umbraco.Examine")]

[assembly: InternalsVisibleTo("Umbraco.Tests")]
[assembly: InternalsVisibleTo("Umbraco.Tests.Benchmarks")]

// Allow this to be mocked in our unit tests
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]

// Umbraco Deploy
[assembly: InternalsVisibleTo("Umbraco.Deploy")]
[assembly: InternalsVisibleTo("Umbraco.Deploy.UI")]
[assembly: InternalsVisibleTo("Umbraco.Deploy.Cloud")]

// Umbraco Forms
[assembly: InternalsVisibleTo("Umbraco.Forms.Core")]
[assembly: InternalsVisibleTo("Umbraco.Forms.Core.Providers")]
[assembly: InternalsVisibleTo("Umbraco.Forms.Web")]

// Umbraco Headless
[assembly: InternalsVisibleTo("Umbraco.Headless")]

// code analysis
// IDE1006 is broken, wants _value syntax for consts, etc - and it's even confusing ppl at MS, kill it
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "~_~")]