text:
This example shows the automatically created async commons chunks.

The example entry references two chunks:

- entry chunk
  - async require -> chunk X
  - async require -> chunk Y
- chunk X
  - module `a`
  - module `b`
  - module `c`
- chunk Y
  - module `a`
  - module `b`
  - module `d`

These chunks share modules `a` and `b`. The optimization extract these into chunk Z:

Note: The optimization compares the size of chunk Z to some minimum value, but this is disabled from this example. In practice, there is no configuration needed for this.

- entry chunk
  - async require -> chunk X & Z
  - async require -> chunk Y & Z
- chunk X
  - module `c`
- chunk Y
  - module `d`
- chunk Z
  - module `a`
  - module `b`

Pretty useful for a router in a SPA.

# example.js

```javascript
// a chunks with a, b, c
require(["./a", "./b", "./c"]);

// a chunk with a, b, d
require.ensure(["./a"], function(require) {
	require("./b");
	require("./d");
});
```

# dist/output.js

```javascript
/******/ (() => { // webpackBootstrap
/******/ 	var __webpack_modules__ = ({});
```

/* webpack runtime code */

``` js
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = __webpack_modules__;
/******/
/************************************************************************/
/******/ 	/* webpack/runtime/ensure chunk */
/******/ 	(() => {
/******/ 		__webpack_require__.f = {};
/******/ 		// This file contains only the entry chunk.
/******/ 		// The chunk loading function for additional chunks
/******/ 		__webpack_require__.e = (chunkId) => {
/******/ 			return Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {
/******/ 				__webpack_require__.f[key](chunkId, promises);
/******/ 				return promises;
/******/ 			}, []));
/******/ 		};
/******/ 	})();
/******/
/******/ 	/* webpack/runtime/get javascript chunk filename */
/******/ 	(() => {
/******/ 		// This function allow to reference async chunks
/******/ 		__webpack_require__.u = (chunkId) => {
/******/ 			// return url for filenames based on template
/******/ 			return "" + chunkId + ".output.js";
/******/ 		};
/******/ 	})();
/******/
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/
/******/ 	/* webpack/runtime/load script */
/******/ 	(() => {
/******/ 		var inProgress = {};
/******/ 		// data-webpack is not used as build has no uniqueName
/******/ 		// loadScript function to load a script via script tag
/******/ 		__webpack_require__.l = (url, done, key, chunkId) => {
/******/ 			if(inProgress[url]) { inProgress[url].push(done); return; }
/******/ 			var script, needAttach;
/******/ 			if(key !== undefined) {
/******/ 				var scripts = document.getElementsByTagName("script");
/******/ 				for(var i = 0; i < scripts.length; i++) {
/******/ 					var s = scripts[i];
/******/ 					if(s.getAttribute("src") == url) { script = s; break; }
/******/ 				}
/******/ 			}
/******/ 			if(!script) {
/******/ 				needAttach = true;
/******/ 				script = document.createElement('script');
/******/
/******/ 				script.charset = 'utf-8';
/******/ 				script.timeout = 120;
/******/ 				if (__webpack_require__.nc) {
/******/ 					script.setAttribute("nonce", __webpack_require__.nc);
/******/ 				}
/******/
/******/ 				script.src = url;
/******/ 			}
/******/ 			inProgress[url] = [done];
/******/ 			var onScriptComplete = (prev, event) => {
/******/ 				// avoid mem leaks in IE.
/******/ 				script.onerror = script.onload = null;
/******/ 				clearTimeout(timeout);
/******/ 				var doneFns = inProgress[url];
/******/ 				delete inProgress[url];
/******/ 				script.parentNode && script.parentNode.removeChild(script);
/******/ 				doneFns && doneFns.forEach((fn) => (fn(event)));
/******/ 				if(prev) return prev(event);
/******/ 			}
/******/ 			;
/******/ 			var timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);
/******/ 			script.onerror = onScriptComplete.bind(null, script.onerror);
/******/ 			script.onload = onScriptComplete.bind(null, script.onload);
/******/ 			needAttach && document.head.appendChild(script);
/******/ 		};
/******/ 	})();
/******/
/******/ 	/* webpack/runtime/publicPath */
/******/ 	(() => {
/******/ 		__webpack_require__.p = "dist/";
/******/ 	})();
/******/
/******/ 	/* webpack/runtime/jsonp chunk loading */
/******/ 	(() => {
/******/ 		// no baseURI
/******/
/******/ 		// object to store loaded and loading chunks
/******/ 		// undefined = chunk not loaded, null = chunk preloaded/prefetched
/******/ 		// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded
/******/ 		var installedChunks = {
/******/ 			179: 0
/******/ 		};
/******/
/******/ 		__webpack_require__.f.j = (chunkId, promises) => {
/******/ 				// JSONP chunk loading for javascript
/******/ 				var installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;
/******/ 				if(installedChunkData !== 0) { // 0 means "already installed".
/******/
/******/ 					// a Promise means "currently loading".
/******/ 					if(installedChunkData) {
/******/ 						promises.push(installedChunkData[2]);
/******/ 					} else {
/******/ 						if(true) { // all chunks have JS
/******/ 							// setup Promise in chunk cache
/******/ 							var promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));
/******/ 							promises.push(installedChunkData[2] = promise);
/******/
/******/ 							// start chunk loading
/******/ 							var url = __webpack_require__.p + __webpack_require__.u(chunkId);
/******/ 							// create error before stack unwound to get useful stacktrace later
/******/ 							var error = new Error();
/******/ 							var loadingEnded = (event) => {
/******/ 								if(__webpack_require__.o(installedChunks, chunkId)) {
/******/ 									installedChunkData = installedChunks[chunkId];
/******/ 									if(installedChunkData !== 0) installedChunks[chunkId] = undefined;
/******/ 									if(installedChunkData) {
/******/ 										var errorType = event && (event.type === 'load' ? 'missing' : event.type);
/******/ 										var realSrc = event && event.target && event.target.src;
/******/ 										error.message = 'Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')';
/******/ 										error.name = 'ChunkLoadError';
/******/ 										error.type = errorType;
/******/ 										error.request = realSrc;
/******/ 										installedChunkData[1](error);
/******/ 									}
/******/ 								}
/******/ 							};
/******/ 							__webpack_require__.l(url, loadingEnded, "chunk-" + chunkId, chunkId);
/******/ 						} else installedChunks[chunkId] = 0;
/******/ 					}
/******/ 				}
/******/ 		};
/******/
/******/ 		// no prefetching
/******/
/******/ 		// no preloaded
/******/
/******/ 		// no HMR
/******/
/******/ 		// no HMR manifest
/******/
/******/ 		// no on chunks loaded
/******/
/******/ 		// install a JSONP callback for chunk loading
/******/ 		var webpackJsonpCallback = (parentChunkLoadingFunction, data) => {
/******/ 			var [chunkIds, moreModules, runtime] = data;
/******/ 			// add "moreModules" to the modules object,
/******/ 			// then flag all "chunkIds" as loaded and fire callback
/******/ 			var moduleId, chunkId, i = 0;
/******/ 			if(chunkIds.some((id) => (installedChunks[id] !== 0))) {
/******/ 				for(moduleId in moreModules) {
/******/ 					if(__webpack_require__.o(moreModules, moduleId)) {
/******/ 						__webpack_require__.m[moduleId] = moreModules[moduleId];
/******/ 					}
/******/ 				}
/******/ 				if(runtime) var result = runtime(__webpack_require__);
/******/ 			}
/******/ 			if(parentChunkLoadingFunction) parentChunkLoadingFunction(data);
/******/ 			for(;i < chunkIds.length; i++) {
/******/ 				chunkId = chunkIds[i];
/******/ 				if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {
/******/ 					installedChunks[chunkId][0]();
/******/ 				}
/******/ 				installedChunks[chunkIds[i]] = 0;
/******/ 			}
/******/
/******/ 		}
/******/
/******/ 		var chunkLoadingGlobal = self["webpackChunk"] = self["webpackChunk"] || [];
/******/ 		chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));
/******/ 		chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));
/******/ 	})();
/******/
/************************************************************************/
```

``` js
var __webpack_exports__ = {};
/*!********************!*\
  !*** ./example.js ***!
  \********************/
/*! unknown exports (runtime-defined) */
/*! runtime requirements: __webpack_require__, __webpack_require__.e, __webpack_require__.oe, __webpack_require__.* */
// a chunks with a, b, c
Promise.all(/*! AMD require */[__webpack_require__.e(394), __webpack_require__.e(460)]).then(function() {[__webpack_require__(/*! ./a */ 1), __webpack_require__(/*! ./b */ 2), __webpack_require__(/*! ./c */ 3)];}).catch(__webpack_require__.oe);

// a chunk with a, b, d
Promise.all(/*! require.ensure */[__webpack_require__.e(394), __webpack_require__.e(767)]).then((function(require) {
	__webpack_require__(/*! ./b */ 2);
	__webpack_require__(/*! ./d */ 4);
}).bind(null, __webpack_require__)).catch(__webpack_require__.oe);

/******/ })()
;
```

# dist/394.output.js

```javascript
(self["webpackChunk"] = self["webpackChunk"] || []).push([[394],[
/* 0 */,
/* 1 */
/*!**************!*\
  !*** ./a.js ***!
  \**************/
/*! unknown exports (runtime-defined) */
/*! runtime requirements: module */
/*! CommonJS bailout: module.exports is used directly at 1:0-14 */
/***/ ((module) => {

module.exports = "a";

/***/ }),
/* 2 */
/*!**************!*\
  !*** ./b.js ***!
  \**************/
/*! unknown exports (runtime-defined) */
/*! runtime requirements: module */
/*! CommonJS bailout: module.exports is used directly at 1:0-14 */
/***/ ((module) => {

module.exports = "b";

/***/ })
]]);
```

# dist/460.output.js

```javascript
(self["webpackChunk"] = self["webpackChunk"] || []).push([[460],{

/***/ 3:
/*!**************!*\
  !*** ./c.js ***!
  \**************/
/*! unknown exports (runtime-defined) */
/*! runtime requirements: module */
/*! CommonJS bailout: module.exports is used directly at 1:0-14 */
/***/ ((module) => {

module.exports = "c";

/***/ })

}]);
```

# dist/767.output.js

```javascript
(self["webpackChunk"] = self["webpackChunk"] || []).push([[767],{

/***/ 4:
/*!**************!*\
  !*** ./d.js ***!
  \**************/
/*! unknown exports (runtime-defined) */
/*! runtime requirements: module */
/*! CommonJS bailout: module.exports is used directly at 1:0-14 */
/***/ ((module) => {

module.exports = "d";

/***/ })

}]);
```

# Info

## Unoptimized

```
asset output.js 9.18 KiB [emitted] (name: main)
asset 394.output.js 610 bytes [emitted]
asset 460.output.js 338 bytes [emitted]
asset 767.output.js 338 bytes [emitted]
chunk (runtime: main) output.js (main) 164 bytes (javascript) 4.98 KiB (runtime) [entry] [rendered]
  > ./example.js main
  runtime modules 4.98 KiB 6 modules
  ./example.js 164 bytes [built] [code generated]
    [used exports unknown]
    entry ./example.js main
chunk (runtime: main) 394.output.js 42 bytes [rendered] split chunk (cache group: default)
  > ./a ./b ./c ./example.js 2:0-30
  > ./example.js 5:0-8:2
  ./a.js 21 bytes [built] [code generated]
    [used exports unknown]
    cjs self exports reference ./a.js 1:0-14
    amd require ./a ./example.js 2:0-30
    require.ensure item ./a ./example.js 5:0-8:2
  ./b.js 21 bytes [built] [code generated]
    [used exports unknown]
    cjs self exports reference ./b.js 1:0-14
    amd require ./b ./example.js 2:0-30
    cjs require ./b ./example.js 6:1-15
chunk (runtime: main) 460.output.js 21 bytes [rendered]
  > ./a ./b ./c ./example.js 2:0-30
  ./c.js 21 bytes [built] [code generated]
    [used exports unknown]
    cjs self exports reference ./c.js 1:0-14
    amd require ./c ./example.js 2:0-30
chunk (runtime: main) 767.output.js 21 bytes [rendered]
  > ./example.js 5:0-8:2
  ./d.js 21 bytes [built] [code generated]
    [used exports unknown]
    cjs self exports reference ./d.js 1:0-14
    cjs require ./d ./example.js 7:1-15
webpack 5.51.1 compiled successfully
```

## Production mode

```
asset output.js 1.81 KiB [emitted] [minimized] (name: main)
asset 394.output.js 104 bytes [emitted] [minimized]
asset 460.output.js 81 bytes [emitted] [minimized]
asset 767.output.js 81 bytes [emitted] [minimized]
chunk (runtime: main) output.js (main) 164 bytes (javascript) 4.98 KiB (runtime) [entry] [rendered]
  > ./example.js main
  runtime modules 4.98 KiB 6 modules
  ./example.js 164 bytes [built] [code generated]
    [no exports used]
    entry ./example.js main
chunk (runtime: main) 394.output.js 42 bytes [rendered] split chunk (cache group: default)
  > ./a ./b ./c ./example.js 2:0-30
  > ./example.js 5:0-8:2
  ./a.js 21 bytes [built] [code generated]
    [used exports unknown]
    cjs self exports reference ./a.js 1:0-14
    amd require ./a ./example.js 2:0-30
    require.ensure item ./a ./example.js 5:0-8:2
  ./b.js 21 bytes [built] [code generated]
    [used exports unknown]
    cjs self exports reference ./b.js 1:0-14
    amd require ./b ./example.js 2:0-30
    cjs require ./b ./example.js 6:1-15
chunk (runtime: main) 460.output.js 21 bytes [rendered]
  > ./a ./b ./c ./example.js 2:0-30
  ./c.js 21 bytes [built] [code generated]
    [used exports unknown]
    cjs self exports reference ./c.js 1:0-14
    amd require ./c ./example.js 2:0-30
chunk (runtime: main) 767.output.js 21 bytes [rendered]
  > ./example.js 5:0-8:2
  ./d.js 21 bytes [built] [code generated]
    [used exports unknown]
    cjs self exports reference ./d.js 1:0-14
    cjs require ./d ./example.js 7:1-15
webpack 5.51.1 compiled successfully
```


text:
<resources>
    <string name="app_name">Rehtaew</string>

    <!-- menu_appbar_main -->
    <string name="text_dummy">\?</string>

    <!-- menu_appbar_main -->
    <string name="item_location">City</string>
    <string name="item_refresh">Update</string>
    <string name="item_share">Share</string>
    <string name="item_settings">Settings</string>

    <!-- content desc -->
    <string name="main_desc_weather">weather</string>
    <string name="main_desc_wind">Wind</string>
    <string name="main_desc_humid">Humid</string>
    <string name="main_desc_pm25">PM 2.5</string>

    <!-- content string -->
    <string name="main_pm25">PM 2.5</string>
    <string name="main_humid">湿度</string>

    <!-- location string -->
    <string name="selectcity_title">选择城市</string>
    <string name="item_searchcity">城市名</string>

    <string name="searchcity_empty">没有找到匹配的城市</string>

    <!-- guide string -->
    <string name="button_guide">开始</string>

    <!-- widget -->
    <string name="add_widget">Add widget</string>

</resources>

redpajama_set_name: RedPajamaGithub


text: #include "../../../tlm_utils/instance_specific_extensions_int.h"


text:
layout: post

#event information
title:  "Lego Family Day"
cover: "/images/1024px-HKPIEG_City_Gallery_exhibit.jpg"
attribution:
  name: "Hong Kong City Gallery Exhibit"
  author: "Hopfare368"
  license: "CC BY-SA 3.0"
  name_url: "https://commons.wikimedia.org/wiki/File:HKPIEG_City_Gallery_exhibit_-_%E5%B0%96%E6%B2%99%E5%92%80_TST_%E7%8F%BE%E4%BB%8A_%E5%BB%BA%E7%AF%89%E7%89%A9_Lego_model_now_May-2013_K11_Ocean_Terminal_Star_Ferry_Piers_Harbour_City_One_Peking.JPG"
  license_url: "https://creativecommons.org/licenses/by-sa/3.0/"
date:   "2016-09-17 11:30"
endDate: "2016-09-17 15:00"
creation: "2016-08-28"
start_time: "11:30 AM"
end_time: "3:00 PM"
location:
  name: "Smithsonian American Art Museum"
  address:
    - "800 G Street NW"
  city: Washington
  state: DC
  zip: 20001
tags: [ 'American Art Museum', 'Family Events' ]
excerpt: >
  Bring your budding architects to our LEGO Family Day at the Smithsonian
  American Art Museum on September 17 where they can use problem-solving skills
  and imagination to make works of art and architecture at our LEGO building
  stations.

---

Bring your budding architects to our [LEGO Family Day](http://americanart.si.edu/calendar/event.cfm?trumbaEmbed=view%3Devent%26eventid%3D119936457)
where they can use problem-solving skills and imagination to make works of art
and architecture at our LEGO building stations. Recreate some of our famous
sculptures on display in the galleries, or invent your own new creations! Get
inspired by the USPTO's LEGO model of our historic building, which was home to
the U.S. Patent Office in the nineteenth century. The model will remain on
public view in our Luce Foundation Center through October 5.


text:
/// <reference path="SpriteRenderer.ts"/>
/// <reference path="../PropertySnip.ts"/>
module WOZLLA.component {

    var QuadCommand = WOZLLA.renderer.QuadCommand;

    /**
     * @class WOZLLA.component.TilingSpriteRenderer
     */
    export class TilingSpriteRenderer extends SpriteRenderer {

        get renderRegion():WOZLLA.math.Rectangle {
            return this._renderRegion;
        }
        set renderRegion(value:WOZLLA.math.Rectangle) {
            this._renderRegion = value;
            this._quadVertexDirty = true;
        }

        get tileMargin():WOZLLA.layout.Margin {
            return this._tileMargin;
        }

        set tileMargin(value:WOZLLA.layout.Margin) {
            this._tileMargin = value;
        }

        _renderRegion:WOZLLA.math.Rectangle;
        _tileMargin:WOZLLA.layout.Margin = new WOZLLA.layout.Margin(0, 0, 0, 0);

        _initQuad() {
            if(this._renderRegion && this._sprite) {
                var frame = this._sprite.frame;
                var count = Math.ceil(this._renderRegion.width/frame.width) *
                    Math.ceil(this._renderRegion.height/frame.height);
                this._quad = new WOZLLA.renderer.Quad(count);
            }
        }

        _updateTilingQuads() {
            this._updateTilingQuadVertices();
            this._updateTilingQuadAlpha();
            this._updateTilingQuadColor();
            this._textureUpdated = false;
        }

        _updateTilingQuadVertices() {
            var frame = this._getTextureFrame();
            var textureOffset = this._getTextureOffset();
            var normalUVS = this._getTextureUVS();
            var colNum = Math.ceil(this._renderRegion.width/frame.width);
            var rowNum = Math.ceil(this._renderRegion.height/frame.height);
            var thisTrans = this.gameObject.transform;
            var margin = this._tileMargin;
            var posX, posY;
            for(var i=0; i<rowNum; i++) {
                for(var j=0; j<colNum; j++) {
                    sharedHelpTransform.reset();
                    posX = (margin.left + margin.right + frame.width) * j + margin.left + this._renderRegion.x;
                    posY = (margin.top + margin.bottom + frame.height) * i + margin.top + this._renderRegion.y;
                    sharedHelpTransform.x = posX;
                    sharedHelpTransform.y = posY;
                    sharedHelpTransform.transform(thisTrans);
                    this._updateQuadVerticesByArgs(normalUVS, frame, textureOffset, sharedHelpTransform.worldMatrix, i*colNum+j);
                }
            }
            this._quadVertexDirty = false;
        }

        _updateTilingQuadAlpha() {
            for(var i=0; i<this._quad.count; i++) {
                this._updateQuadAlpha(i);
            }
            this._quadAlphaDirty = false;
        }

        _updateTilingQuadColor() {
            for(var i=0; i<this._quad.count; i++) {
                this._updateQuadColor(i);
            }
            this._quadColorDirty = false;
        }

        render(renderer:WOZLLA.renderer.IRenderer, flags:number):void {
            if (!this._texture || !this._quad) {
                return;
            }
            if((flags & GameObject.MASK_TRANSFORM_DIRTY) === GameObject.MASK_TRANSFORM_DIRTY) {
                this._quadVertexDirty = true;
            }
            if (this._textureUpdated) {
                this._updateTilingQuads();
            }
            if (this._quadVertexDirty) {
                this._updateTilingQuadVertices();
            }
            if (this._quadAlphaDirty) {
                this._updateTilingQuadAlpha();
            }
            if (this._quadColorDirty) {
                this._updateTilingQuadColor();
            }
            renderer.addCommand(QuadCommand.init(
                this._quadGlobalZ,
                this._quadLayer,
                this._texture,
                this._quadMaterialId,
                this._quad,
                this._gameObject.name + '[tiling]'));
        }

    }

    Component.register(TilingSpriteRenderer, {
        name: "TilingSpriteRenderer",
        properties: [
            Component.extendConfig(SpriteRenderer),
            PropertySnip.createRect('renderRegion'),
            PropertySnip.createMargin('tileMargin')
        ]
    });

}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Reflection;
using System.Runtime.InteropServices;

using XenAdmin.Core;

namespace XenAdmin.Controls
{
    public class FlickerFreeListBox : ListBox
    {
        /// <summary>
        /// These flicker free list boxes must be owner drawn.
        /// </summary>
        public FlickerFreeListBox()
        {
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            this.SetStyle(ControlStyles.ResizeRedraw, true);
            this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            this.SetStyle(ControlStyles.UserPaint, true);
            this.DoubleBuffered = true;
            this.IntegralHeight = false;
            this.DrawMode = DrawMode.OwnerDrawFixed;
        }

        /// <summary>
        /// The last seen value of the horizontal scrollbar position (offset in pixels from the lhs).
        /// </summary>
        private int _scrollLeft = 0;
        /// <summary>
        /// The handle of the horizontal scrollbar of this ListBox
        /// </summary>
        private IntPtr _hScrollbarHandle = IntPtr.Zero;
        public WndProcCancelDelegate CancelWndProc = new WndProcCancelDelegate(delegate(Message msg) { return false; });

        protected override void WndProc(ref Message msg)
        {
            if (msg.Msg == Win32.WM_HSCROLL)
            {
                // Store the handle for use in Invalidate()
                _hScrollbarHandle = msg.HWnd;
                // Collect info about the position of the horizontal scrollbar
                Win32.ScrollInfo si = new Win32.ScrollInfo();
                si.fMask = (int)Win32.ScrollInfoMask.SIF_ALL;
                si.cbSize = (uint)Marshal.SizeOf(si);
                Win32.GetScrollInfo(msg.HWnd, 0, ref si);

                if ((msg.WParam.ToInt32() & 0xFF) == Win32.SB_THUMBTRACK)
                {
                    // If the user is in the middle of dragging the scrollbar, we're interested in
                    // the 'track' position
                    _scrollLeft = si.nTrackPos;
                }
                else
                {
                    // Otherwise just the regular scrollbar position
                    _scrollLeft = si.nPos;
                }
                // Force repaint
                base.Invalidate();
            }

            if(!CancelWndProc(msg))
                base.WndProc(ref msg);
        }

        public new void Invalidate()
        {
            if (_hScrollbarHandle != IntPtr.Zero)
            {
                // If we've been invalidated, update our drawing code to the new horizontal scrollbar
                // position (which is sometimes spontaneously reset to zero and can't be programmatically
                // set to its former value) - see CA-11405.
                Win32.ScrollInfo si = new Win32.ScrollInfo();
                si.fMask = (int)Win32.ScrollInfoMask.SIF_ALL;
                si.cbSize = (uint)Marshal.SizeOf(si);
                Win32.GetScrollInfo(_hScrollbarHandle, 0, ref si);
                _scrollLeft = si.nTrackPos; // often zero
            }
            base.Invalidate();
        }

        protected override void OnMouseWheel(MouseEventArgs e)
        {
            Invalidate();
            base.OnMouseWheel(e);
        }

        private ContextMenuStrip _contextMenuStrip = null;

        public override ContextMenuStrip ContextMenuStrip
        {
            get
            {
                return _contextMenuStrip;
            }
            set
            {
                _contextMenuStrip = value;
            }
        }

        protected override void OnKeyUp(KeyEventArgs e)
        {
            base.OnKeyUp(e);

            if (e.KeyCode == Keys.Apps && _contextMenuStrip != null)
            {
                if (SelectedIndex < 0 || SelectedIndex >= Items.Count)
                    return;

                Rectangle r = GetItemRectangle(SelectedIndex);
                Point p = new Point(r.X + 1, r.Bottom + 1);
                ContextMenuStrip.Show(this, p);
            }
        }

        protected override void OnMouseUp(MouseEventArgs e)
        {
            base.OnMouseUp(e);

            if (e.Button == MouseButtons.Right && _contextMenuStrip != null)
            {
                int i = IndexFromPoint(e.Location);
                if (i == ListBox.NoMatches)
                    return;

                SelectedIndex = i;

                ContextMenuStrip.Show(this, e.Location);
            }
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            Graphics g = e.Graphics;

            if(Enabled)
            {
                using (SolidBrush backBrush = new SolidBrush(BackColor))
                {
                    g.FillRectangle(backBrush, g.ClipBounds);
                }
            }
            else
            {
                g.FillRectangle(SystemBrushes.Control, g.ClipBounds);
            }

            int top = 0;

            for (int i = 0; i < TopIndex; i++)
            {
                if (i < Items.Count)
                    top += base.GetItemHeight(i);
            }

            Rectangle t = new Rectangle(-_scrollLeft, -top, ClientSize.Width, ItemHeight);

            for (int i = 0; i < this.Items.Count; i++)
            {
                int itemHeight = GetItemHeight(i);
                Rectangle bounds = new Rectangle(t.Left, t.Top, t.Width, itemHeight);

                // if selected
                if (SelectedIndices.Contains(i))
                {
                    // Enabled & Focused = blue
                    // Enabled & !Focused = control
                    // !Enabled = dark grey

                    if(!Enabled)
                        OnDrawItem(new DrawItemEventArgs(g, Font, bounds, i,
                            DrawItemState.Disabled, SystemColors.HighlightText,
                            SystemColors.ControlDark));
                    else if (!Focused)
                        OnDrawItem(new DrawItemEventArgs(g, Font, bounds, i,
                            DrawItemState.Inactive, SystemColors.ControlText,
                            SystemColors.Control));
                    else
                        OnDrawItem(new DrawItemEventArgs(g, Font, bounds, i,
                            DrawItemState.Selected, SystemColors.HighlightText,
                            SystemColors.Highlight));
                }
                else
                {
                    // If not selected, then we just care if the control is enabled

                    OnDrawItem(new DrawItemEventArgs(g, Font, bounds, i,
                        DrawItemState.Default, SystemColors.ControlText,
                        Enabled ? BackColor : SystemColors.Control));
                }

                t.Offset(0, itemHeight);
            }
        }

        protected override void OnSelectedIndexChanged(EventArgs e)
        {
            base.OnSelectedIndexChanged(e);
            Refresh();
        }

        public const int RIGHT_PADDING = 5;

        public void WilkieSpecial(Image icon, string text, string extraText, Color extraTextColor, Font extraTextFont, DrawItemEventArgs e)
        {
            Graphics g = e.Graphics;

            WSPaintBG(e, this);

            // This is the rect where we want to put the text pair
            Rectangle bounds = new Rectangle(e.Bounds.Height, e.Bounds.Y, e.Bounds.Width - e.Bounds.Height - RIGHT_PADDING, e.Bounds.Height);

            String display;
            Size s = WSDrawTextPair(this, text, extraText, extraTextColor, extraTextFont, e,  bounds, true, out display);

            WSDrawSelectRect(e, bounds.Height + s.Width);

            WSDrawLeftImage(icon, e);

            // And the text
            Drawing.DrawText(g, display, e.Font,
                bounds, e.ForeColor, e.BackColor, TextFormatFlags.Left | TextFormatFlags.VerticalCenter);
        }

        private static void WSDrawSelectRect(DrawItemEventArgs e, int width)
        {
            Graphics g = e.Graphics;

            Rectangle selectionRectangle = new Rectangle(e.Bounds.Location, e.Bounds.Size);
            selectionRectangle.Width = width;

            using (SolidBrush backBrush = new SolidBrush(e.BackColor))
            {
                g.FillRectangle(backBrush, selectionRectangle);
            }
        }

        private static Color GetBackColorFor(Control control)
        {
            return !control.Enabled ? SystemColors.Control : control.BackColor;
        }

        private static void WSDrawLeftImage(Image icon, DrawItemEventArgs e)
        {
            Graphics g = e.Graphics;

            g.DrawImage(icon, e.Bounds.Left + 1, e.Bounds.Top + 1, e.Bounds.Height - 2, e.Bounds.Height - 2);
        }

        private static Size WSDrawTextPair(Control control, String text, String extraText, Color extraTextColor, Font extraTextFont, DrawItemEventArgs e, Rectangle bounds, bool ShowSelectOnExtraText, out String display)
        {
            Graphics g = e.Graphics;
            g.TextRenderingHint = Drawing.TextRenderingHint;

            display = text;
            Size s = Drawing.MeasureText(g, display, e.Font,
                        bounds.Size, TextFormatFlags.Right | TextFormatFlags.VerticalCenter);

            if (extraText == null)
                return s;

            // We're going to have the extra text take precedent over the text,
            // so shrink the text and put ellipses on until it measures up

            Size t = Drawing.MeasureText(g, extraText, extraTextFont,
                bounds.Size, TextFormatFlags.Right | TextFormatFlags.VerticalCenter);

            int trim = text.Length;

            while (s.Width + t.Width + 10 > bounds.Width && trim > 0)
            {
                trim--;

                display = text.Ellipsise(trim);

                s = Drawing.MeasureText(g, display, e.Font,
                    bounds.Size, TextFormatFlags.Right | TextFormatFlags.VerticalCenter);
            }

            Color backColor = ShowSelectOnExtraText && control.Focused && e.State == DrawItemState.Selected
                                  ? Color.LightGray
                                  : GetBackColorFor(control);

            if (ShowSelectOnExtraText)
            {
                Rectangle greySelectionRectangle = new Rectangle(bounds.Width - t.Width + bounds.X, bounds.Y + 2, t.Width, t.Height);

                using (SolidBrush brush = new SolidBrush(backColor))
                {
                    g.FillRectangle(brush, greySelectionRectangle);
                }
            }

            Drawing.DrawText(g, extraText, extraTextFont,
                bounds, extraTextColor, backColor, TextFormatFlags.Right | TextFormatFlags.VerticalCenter);

            return s;
        }

        private static void WSPaintBG(DrawItemEventArgs e, Control control)
        {
            Graphics g = e.Graphics;
            Color color = GetBackColorFor(control);

            using (SolidBrush backBrush = new SolidBrush(color))
            {
                g.FillRectangle(backBrush, e.Bounds);
            }
        }

        protected override void OnGotFocus(EventArgs e)
        {
            base.OnGotFocus(e);
            this.Refresh();
        }

        protected override void OnLostFocus(EventArgs e)
        {
            base.OnLostFocus(e);
            this.Refresh();
        }
    }

    public delegate bool WndProcCancelDelegate(Message msg);
}


text:
package org.kaazing.nuklei.tcp.internal.router;

import org.agrona.concurrent.status.AtomicCounter;

public enum RouteKind
{
    SERVER_INITIAL
    {
        @Override
        public int kind()
        {
            return 0x21;
        }

        @Override
        public final long nextRef(
            AtomicCounter counter)
        {
            // positive, even, non-zero
            counter.increment();
            return counter.get() << 1L;
        }
    },

    SERVER_REPLY
    {
        @Override
        public int kind()
        {
            return 0x22;
        }

        @Override
        public final long nextRef(
            AtomicCounter counter)
        {
            // negative, even, non-zero
            counter.increment();
            return counter.get() << 1L | 0x8000000000000000L;
        }
    },

    CLIENT_INITIAL
    {
        @Override
        public int kind()
        {
            return 0x11;
        }

        @Override
        public final long nextRef(
            AtomicCounter counter)
        {
            // positive, odd
            return (counter.increment() << 1L) | 1L;
        }
    },

    CLIENT_REPLY
    {
        @Override
        public int kind()
        {
            return 0x12;
        }

        @Override
        public final long nextRef(
            AtomicCounter counter)
        {
            // negative, odd
            return (counter.increment() << 1L) | 0x8000000000000001L;
        }
    };

    public abstract long nextRef(
        AtomicCounter counter);

    public abstract int kind();

    public static RouteKind of(
        int kind)
    {
        switch (kind)
        {
        case 0x11:
            return CLIENT_INITIAL;
        case 0x12:
            return CLIENT_REPLY;
        case 0x21:
            return SERVER_INITIAL;
        case 0x22:
            return SERVER_REPLY;
        default:
            throw new IllegalArgumentException("Unexpected kind: " + kind);
        }
    }

    public static RouteKind match(
        long referenceId)
    {
        switch ((int)referenceId & 0x01 | (int)(referenceId >> 32) & 0x80000000)
        {
        case 0x00000001:
            return CLIENT_INITIAL;
        case 0x80000001:
            return CLIENT_REPLY;
        case 0x00000000:
            return SERVER_INITIAL;
        case 0x80000000:
            return SERVER_REPLY;
        default:
            throw new IllegalArgumentException();
        }
    }
}


text:
/* eslint-disable no-new, comma-dangle, class-methods-use-this, no-param-reassign */

((global) => {
  class IssuableTemplateSelectors {
    constructor({ $dropdowns, editor } = {}) {
      this.$dropdowns = $dropdowns || $('.js-issuable-selector');
      this.editor = editor || this.initEditor();

      this.$dropdowns.each((i, dropdown) => {
        const $dropdown = $(dropdown);
        new gl.IssuableTemplateSelector({
          pattern: /(\.md)/,
          data: $dropdown.data('data'),
          wrapper: $dropdown.closest('.js-issuable-selector-wrap'),
          dropdown: $dropdown,
          editor: this.editor
        });
      });
    }

    initEditor() {
      const editor = $('.markdown-area');
      // Proxy ace-editor's .setValue to jQuery's .val
      editor.setValue = editor.val;
      editor.getValue = editor.val;
      return editor;
    }
  }

  global.IssuableTemplateSelectors = IssuableTemplateSelectors;
})(window.gl || (window.gl = {}));


text:
'use strict';

const _ = require('lodash');
const imageStream = require('etcher-image-stream');
const electron = require('electron');

module.exports = function($q, SupportedFormatsModel) {

  /**
   * @summary Open an image selection dialog
   * @function
   * @public
   *
   * @description
   * Notice that by image, we mean *.img/*.iso/*.zip/etc files.
   *
   * @fulfil {Object} - selected image
   * @returns {Promise};
   *
   * @example
   * OSDialogService.selectImage().then((image) => {
   *   console.log('The selected image is', image.path);
   * });
   */
  this.selectImage = () => {
    return $q((resolve, reject) => {
      electron.remote.dialog.showOpenDialog({

        // This variable is set when running in GNU/Linux from
        // inside an AppImage, and represents the working directory
        // from where the AppImage was run (which might not be the
        // place where the AppImage is located). `OWD` stands for
        // "Original Working Directory".
        //
        // See: https://github.com/probonopd/AppImageKit/commit/1569d6f8540aa6c2c618dbdb5d6fcbf0003952b7
        defaultPath: process.env.OWD,

        properties: [
          'openFile'
        ],
        filters: [
          {
            name: 'OS Images',
            extensions: SupportedFormatsModel.getAllExtensions()
          }
        ]
      }, (files) => {

        // `_.first` is smart enough to not throw and return `undefined`
        // if we pass it an `undefined` value (e.g: when the selection
        // dialog was cancelled).
        const imagePath = _.first(files);

        if (!imagePath) {
          return resolve();
        }

        imageStream.getEstimatedFinalSize(imagePath).then((estimatedSize) => {
          return resolve({
            path: imagePath,
            size: estimatedSize
          });
        }).catch(reject);
      });
    });
  };

  /**
   * @summary Show error dialog for an Error instance
   * @function
   * @public
   *
   * @param {(Error|String)} error - error
   * @param {String} [description] - error description
   *
   * @example
   * OSDialogService.showError(new Error('Foo Bar'));
   *
   * @example
   * OSDialogService.showError(new Error('Foo Bar'), 'A custom description');
   *
   * @example
   * OSDialogService.showError('Foo Bar', 'An error happened!');
   */
  this.showError = (error, description) => {
    error = error || {};

    // Try to get as most information as possible about the error
    // rather than falling back to generic messages right away.
    const title = _.attempt(() => {
      if (_.isString(error)) {
        return error;
      }

      return error.message || error.code || 'An error ocurred';
    });

    const message = description || error.stack || JSON.stringify(error) || '';

    // Ensure the parameters are strings to prevent the following
    // types of obscure errors:
    //
    //   Error: Could not call remote function ''.
    //   Check that the function signature is correct.
    //   Underlying error:
    //     Error processing argument at index 0, conversion failure
    //
    // This can be thrown if for some reason, either `title` or `message`
    // are not strings.
    electron.remote.dialog.showErrorBox(title.toString(), message.toString());
  };

};


text: Responsible for testing ALGCategory and ALGCategorizer


text:
$:.unshift File.join(File.dirname(__FILE__), "..", "lib")
require 'test/unit'
require 'tzinfo/linked_timezone_info'

include TZInfo

class TCLinkedTimezoneInfo < Test::Unit::TestCase

  def test_identifier
    lti = LinkedTimezoneInfo.new('Test/Zone', 'Test/Linked')
    assert_equal('Test/Zone', lti.identifier)
  end

  def test_link_to_identifier
    lti = LinkedTimezoneInfo.new('Test/Zone', 'Test/Linked')
    assert_equal('Test/Linked', lti.link_to_identifier)
  end
end


text:
"""remove redundant user subscription fields

Revision ID: 3fc4c97dc6bd
Revises: 3d723944025f
Create Date: 2015-01-27 18:11:15.822193

"""

# revision identifiers, used by Alembic.
revision = '3fc4c97dc6bd'
down_revision = '3d723944025f'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('user', u'subscribe_bill')
    op.drop_column('user', u'subscribe_call_for_comment')
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.add_column('user', sa.Column(u'subscribe_call_for_comment', sa.BOOLEAN(), autoincrement=False, nullable=True))
    op.add_column('user', sa.Column(u'subscribe_bill', sa.BOOLEAN(), autoincrement=False, nullable=True))
    ### end Alembic commands ###


text:
/*
 * Copyright (c) 1982, 1986, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)if_loop.c	8.1 (Berkeley) 6/10/93
 * $Id: if_loop.c,v 1.22.2.1 1998/05/13 11:19:05 danny Exp $
 */

/*
 * Loopback interface driver for protocol testing and timing.
 */
#include "loop.h"
#if NLOOP > 0

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/mbuf.h>
#include <sys/socket.h>
#include <sys/errno.h>
#include <sys/ioctl.h>
#include <sys/time.h>

#include <net/if.h>
#include <net/if_types.h>
#include <net/netisr.h>
#include <net/route.h>
#include <net/bpf.h>

#ifdef	INET
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/in_var.h>
#include <netinet/ip.h>
#endif

#ifdef IPX
#include <netipx/ipx.h>
#include <netipx/ipx_if.h>
#endif

#ifdef INET6
#ifndef INET
#include <netinet/in.h>
#endif
#include <netinet6/in6_var.h>
#include <netinet/ip6.h>
#endif

#ifdef NS
#include <netns/ns.h>
#include <netns/ns_if.h>
#endif

#ifdef ISO
#include <netiso/iso.h>
#include <netiso/iso_var.h>
#endif

#ifdef NETATALK
#include <netinet/if_ether.h>
#include <netatalk/at.h>
#include <netatalk/at_var.h>
#endif NETATALK

#include "bpfilter.h"

static int loioctl __P((struct ifnet *, int, caddr_t));
static void lortrequest __P((int, struct rtentry *, struct sockaddr *));

static void loopattach __P((void *));
#ifdef ALTQ
static void lo_altqstart __P((struct ifnet *));
#endif
PSEUDO_SET(loopattach, if_loop);

#ifdef TINY_LOMTU
#define	LOMTU	(1024+512)
#elif defined(LARGE_LOMTU)
#define LOMTU	131072
#else
#define LOMTU	16384
#endif

struct	ifnet loif[NLOOP];

/* ARGSUSED */
static void
loopattach(dummy)
	void *dummy;
{
	register struct ifnet *ifp;
	register int i = 0;

	for (ifp = loif; i < NLOOP; ifp++) {
	    ifp->if_name = "lo";
	    ifp->if_next = NULL;
	    ifp->if_unit = i++;
	    ifp->if_mtu = LOMTU;
	    ifp->if_flags = IFF_LOOPBACK | IFF_MULTICAST;
	    ifp->if_ioctl = loioctl;
	    ifp->if_output = looutput;
	    ifp->if_type = IFT_LOOP;
	    ifp->if_hdrlen = 0;
	    ifp->if_addrlen = 0;
	    IFQ_SET_READY(&ifp->if_snd);
#ifdef ALTQ
	    ifp->if_start = lo_altqstart;
#endif
	    if_attach(ifp);
#if NBPFILTER > 0
	    bpfattach(ifp, DLT_NULL, sizeof(u_int));
#endif
	}
}

int
looutput(ifp, m, dst, rt)
	struct ifnet *ifp;
	register struct mbuf *m;
	struct sockaddr *dst;
	register struct rtentry *rt;
{
	int s, isr;
	register struct ifqueue *ifq = 0;

	if ((m->m_flags & M_PKTHDR) == 0)
		panic("looutput no HDR");

#if NBPFILTER > 0
	/* BPF write needs to be handled specially */
	if (dst->sa_family == AF_UNSPEC) {
		dst->sa_family = *(mtod(m, int *));
		m->m_len -= sizeof(int);
		m->m_pkthdr.len -= sizeof(int);
		m->m_data += sizeof(int);
	}

	if (loif[0].if_bpf) {
		/*
		 * We need to prepend the address family as
		 * a four byte field.  Cons up a dummy header
		 * to pacify bpf.  This is safe because bpf
		 * will only read from the mbuf (i.e., it won't
		 * try to free it or keep a pointer a to it).
		 */
		struct mbuf m0;
		u_int af = dst->sa_family;

		m0.m_next = m;
		m0.m_len = 4;
		m0.m_data = (char *)

		bpf_mtap(&loif[0], &m0);
	}
#endif
	m->m_pkthdr.rcvif = ifp;

	if (rt && rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
		m_freem(m);
		return (rt->rt_flags & RTF_BLACKHOLE ? 0 :
		        rt->rt_flags & RTF_HOST ? EHOSTUNREACH : ENETUNREACH);
	}

	/*
	 * KAME requires that the packet to be contiguous on the
	 * mbuf.  We need to make that sure.
	 * this kind of code should be avoided.
	 * XXX: fails to join if interface MTU > MCLBYTES.  jumbogram?
	 */
	if (m && m->m_next != NULL && m->m_pkthdr.len < MCLBYTES) {
		struct mbuf *n;

		MGETHDR(n, M_DONTWAIT, MT_HEADER);
		if (!n)
			goto contiguousfail;
		MCLGET(n, M_DONTWAIT);
		if (! (n->m_flags & M_EXT)) {
			m_freem(n);
			goto contiguousfail;
		}

		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
		n->m_pkthdr.rcvif = m->m_pkthdr.rcvif;
		n->m_pkthdr.len = m->m_pkthdr.len;
		n->m_len = m->m_pkthdr.len;
		n->m_pkthdr.aux = m->m_pkthdr.aux;
		m->m_pkthdr.aux = (struct mbuf *)NULL;
		m_freem(m);
		m = n;
	}
	if (0) {
contiguousfail:
		printf("looutput: mbuf allocation failed\n");
	}
#if 0
	if (m && m->m_next != NULL)
		printf("loop: not contiguous...\n");
#endif

	ifp->if_opackets++;
	ifp->if_obytes += m->m_pkthdr.len;
#ifdef ALTQ
	/*
	 * altq for loop is just for debugging.
	 * only used when called for loop interface (not for
	 * a simplex interface).
	 */
	if ((ALTQ_IS_ENABLED(&ifp->if_snd) || TBR_IS_ENABLED(&ifp->if_snd))
	    && ifp->if_start == lo_altqstart) {
		struct altq_pktattr pktattr;
		int32_t *afp;
	        int error;

		/*
		 * if the queueing discipline needs packet classification,
		 * do it before prepending link headers.
		 */
		IFQ_CLASSIFY(&ifp->if_snd, m, dst->sa_family, &pktattr);

		M_PREPEND(m, sizeof(int32_t), M_DONTWAIT);
		if (m == 0)
			return(ENOBUFS);
		afp = mtod(m, int32_t *);
		*afp = (int32_t)dst->sa_family;

	        s = splimp();
		IFQ_ENQUEUE(&ifp->if_snd, m, &pktattr, error);
		(*ifp->if_start)(ifp);
		splx(s);
		return (error);
	}
#endif /* ALTQ */

	switch (dst->sa_family) {

#ifdef INET
	case AF_INET:
		ifq = &ipintrq;
		isr = NETISR_IP;
		break;
#endif
#ifdef IPX
	case AF_IPX:
		ifq = &ipxintrq;
		isr = NETISR_IPX;
		break;
#endif
#ifdef INET6
	case AF_INET6:
		m->m_flags |= M_LOOP;
		ifq = &ip6intrq;
		isr = NETISR_IPV6;
		break;
#endif
#ifdef NS
	case AF_NS:
		ifq = &nsintrq;
		isr = NETISR_NS;
		break;
#endif
#ifdef ISO
	case AF_ISO:
		ifq = &clnlintrq;
		isr = NETISR_ISO;
		break;
#endif
#ifdef NETATALK
	case AF_APPLETALK:
	        ifq = &atintrq2;
		isr = NETISR_ATALK;
		break;
#endif NETATALK
	default:
		printf("lo%d: can't handle af%d\n", ifp->if_unit,
			dst->sa_family);
		m_freem(m);
		return (EAFNOSUPPORT);
	}
	s = splimp();
	if (IF_QFULL(ifq)) {
		IF_DROP(ifq);
		m_freem(m);
		splx(s);
		return (ENOBUFS);
	}
	IF_ENQUEUE(ifq, m);
	schednetisr(isr);
	ifp->if_ipackets++;
	ifp->if_ibytes += m->m_pkthdr.len;
	splx(s);
	return (0);
}

#ifdef ALTQ
static void
lo_altqstart(ifp)
	struct ifnet *ifp;
{
	struct ifqueue *ifq;
	struct mbuf *m;
	int32_t af, *afp;
	int s, isr;

	while (1) {
		s = splimp();
		IFQ_DEQUEUE(&ifp->if_snd, m);
		splx(s);
		if (m == NULL)
			return;

		afp = mtod(m, int32_t *);
		af = *afp;
		m_adj(m, sizeof(int32_t));

		switch (af) {
#ifdef INET
		case AF_INET:
			ifq = &ipintrq;
			isr = NETISR_IP;
			break;
#endif
#ifdef INET6
		case AF_INET6:
			m->m_flags |= M_LOOP;
			ifq = &ip6intrq;
			isr = NETISR_IPV6;
			break;
#endif
#ifdef IPX
		case AF_IPX:
			ifq = &ipxintrq;
			isr = NETISR_IPX;
			break;
#endif
#ifdef NS
		case AF_NS:
			ifq = &nsintrq;
			isr = NETISR_NS;
			break;
#endif
#ifdef ISO
		case AF_ISO:
			ifq = &clnlintrq;
			isr = NETISR_ISO;
			break;
#endif
#ifdef NETATALK
		case AF_APPLETALK:
			ifq = &atintrq2;
			isr = NETISR_ATALK;
			break;
#endif NETATALK
		default:
			printf("lo_altqstart: can't handle af%d\n", af);
			m_freem(m);
			return;
		}

		s = splimp();
		if (IF_QFULL(ifq)) {
			IF_DROP(ifq);
			m_freem(m);
			splx(s);
			return;
		}
		IF_ENQUEUE(ifq, m);
		schednetisr(isr);
		ifp->if_ipackets++;
		ifp->if_ibytes += m->m_pkthdr.len;
		splx(s);
	}
}
#endif /* ALTQ */

/* ARGSUSED */
static void
lortrequest(cmd, rt, sa)
	int cmd;
	struct rtentry *rt;
	struct sockaddr *sa;
{
	if (rt) {
		rt->rt_rmx.rmx_mtu = rt->rt_ifp->if_mtu; /* for ISO */
		/*
		 * For optimal performance, the send and receive buffers
		 * should be at least twice the MTU plus a little more for
		 * overhead.
		 */
		rt->rt_rmx.rmx_recvpipe =
			rt->rt_rmx.rmx_sendpipe = 3 * LOMTU;
	}
}

/*
 * Process an ioctl request.
 */
/* ARGSUSED */
static int
loioctl(ifp, cmd, data)
	register struct ifnet *ifp;
	int cmd;
	caddr_t data;
{
	register struct ifaddr *ifa;
	register struct ifreq *ifr = (struct ifreq *)data;
	register int error = 0;

	switch (cmd) {

	case SIOCSIFADDR:
		ifp->if_flags |= IFF_UP | IFF_RUNNING;
		ifa = (struct ifaddr *)data;
		ifa->ifa_rtrequest = lortrequest;
		/*
		 * Everything else is done at a higher level.
		 */
		break;

	case SIOCADDMULTI:
	case SIOCDELMULTI:
		if (ifr == 0) {
			error = EAFNOSUPPORT;		/* XXX */
			break;
		}
		switch (ifr->ifr_addr.sa_family) {

#ifdef INET
		case AF_INET:
			break;
#endif
#ifdef INET6
		case AF_INET6:
			break;
#endif

		default:
			error = EAFNOSUPPORT;
			break;
		}
		break;

	case SIOCSIFMTU:
		ifp->if_mtu = ifr->ifr_mtu;
		break;

	case SIOCSIFFLAGS:
		break;

	default:
		error = EINVAL;
	}
	return (error);
}
#endif /* NLOOP > 0 */


text:
local theme = require 'theme'
local o = vim.opt
local g = vim.g

-- Leader key configuation
-- https://learnvimscriptthehardway.stevelosh.com/chapters/06.html
g.mapleader = '\\' -- Define leader key.
g.localmapleader = ',' -- Define local leader.

vim.cmd [[set fcs=eob:\ ]]
vim.cmd [[filetype plugin indent on]]

local options = {
  autoread = true,
  background = 'dark',
  backup = false,
  clipboard = 'unnamedplus', -- Allows neovim to access the system clipboard.
  cmdheight = 1,
  colorcolumn = '80',
  cursorline = true, -- Highlight the screen line of the cursor.
  expandtab = true,
  exrc = true,
  fileencoding = 'utf-8', -- The encoding written to a file.
  foldcolumn = '1',
  foldlevel = 99,
  foldlevelstart = 99,
  foldenable = true,
  guifont = 'MesloLGM Nerd Font Mono',
  hidden = true,
  hlsearch = true,
  ignorecase = true,
  incsearch = true,
  laststatus = 3, -- Display the status line always.
  linespace = 0, -- Set line-spacing to minimum.
  mouse = 'a', -- Enable mouse.
  number = true, -- Line numbers.
  pumheight = 10,
  relativenumber = true, -- Line relative numbers.
  scrolloff = 5,
  secure = true, -- Prevent run autocmd not owned by you.
  shiftround = true,
  shiftwidth = 2,
  showcmd = true, -- Show (partial) command in status line.
  showmode = true, -- Show current mode.
  sidescrolloff = 5,
  signcolumn = 'yes',
  smartcase = true,
  smartindent = true,
  splitbelow = true,
  splitright = true, -- Split configurations.
  swapfile = false,
  synmaxcol = 2048, -- Set a limit for syntax highlights
  tabstop = 2,
  termguicolors = true, -- Enable true colors
  timeoutlen = 1000,
  undodir = vim.fn.stdpath 'cache' .. '/undo', -- set an undo directory.
  undofile = true,
  updatetime = 250,
  wildmenu = true,
  listchars = {
    eol = '↵',
    space = ' ',
    trail = '✚',
    extends = '◀',
    precedes = '▶',
  },
  fillchars = {
    eob = ' ',
    fold = ' ',
    foldopen = '',
    foldsep = ' ',
    foldclose = '',
  },
}

o.shortmess:append 'c'

for key, value in pairs(options) do
  o[key] = value
end

theme.init()


text:
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>

#include <libchdr/huffman.h>
#include <libchdr/minmax.h>

/***************************************************************************
 *  MACROS
 ***************************************************************************
 */

#define MAKE_LOOKUP(code,bits)  (((code) << 5) | ((bits) & 0x1f))

/***************************************************************************
 *  IMPLEMENTATION
 ***************************************************************************
 */

/*-------------------------------------------------
 *  huffman_context_base - create an encoding/
 *  decoding context
 *-------------------------------------------------
 */

struct huffman_decoder* create_huffman_decoder(int numcodes, int maxbits)
{
   struct huffman_decoder* decoder;
	/* limit to 24 bits */
	if (maxbits > 24)
		return NULL;

	decoder = (struct huffman_decoder*)malloc(sizeof(struct huffman_decoder));
	decoder->numcodes = numcodes;
	decoder->maxbits = maxbits;
	decoder->lookup = (lookup_value*)malloc(sizeof(lookup_value) * (1 << maxbits));
	decoder->huffnode = (struct node_t*)malloc(sizeof(struct node_t) * numcodes);
	decoder->datahisto = NULL;
	decoder->prevdata = 0;
	decoder->rleremaining = 0;
	return decoder;
}

void delete_huffman_decoder(struct huffman_decoder* decoder)
{
	if (decoder != NULL)
	{
		if (decoder->lookup != NULL)
			free(decoder->lookup);
		if (decoder->huffnode != NULL)
			free(decoder->huffnode);
		free(decoder);
	}
}

/*-------------------------------------------------
 *  decode_one - decode a single code from the
 *  huffman stream
 *-------------------------------------------------
 */

uint32_t huffman_decode_one(struct huffman_decoder* decoder, struct bitstream* bitbuf)
{
	/* peek ahead to get maxbits worth of data */
	uint32_t bits = bitstream_peek(bitbuf, decoder->maxbits);

	/* look it up, then remove the actual number of bits for this code */
	lookup_value lookup = decoder->lookup[bits];
	bitstream_remove(bitbuf, lookup & 0x1f);

	/* return the value */
	return lookup >> 5;
}

/*-------------------------------------------------
 *  import_tree_rle - import an RLE-encoded
 *  huffman tree from a source data stream
 *-------------------------------------------------
 */

enum huffman_error huffman_import_tree_rle(struct huffman_decoder* decoder, struct bitstream* bitbuf)
{
   enum huffman_error error;
	/* bits per entry depends on the maxbits */
	int numbits;
	int curnode;
	if (decoder->maxbits >= 16)
		numbits = 5;
	else if (decoder->maxbits >= 8)
		numbits = 4;
	else
		numbits = 3;

	/* loop until we read all the nodes */
	for (curnode = 0; curnode < decoder->numcodes; )
	{
		/* a non-one value is just raw */
		int nodebits = bitstream_read(bitbuf, numbits);
		if (nodebits != 1)
			decoder->huffnode[curnode++].numbits = nodebits;

		/* a one value is an escape code */
		else
		{
			/* a double 1 is just a single 1 */
			nodebits = bitstream_read(bitbuf, numbits);
			if (nodebits == 1)
				decoder->huffnode[curnode++].numbits = nodebits;

			/* otherwise, we need one for value for the repeat count */
			else
			{
				int repcount = bitstream_read(bitbuf, numbits) + 3;
				while (repcount--)
					decoder->huffnode[curnode++].numbits = nodebits;
			}
		}
	}

	/* make sure we ended up with the right number */
	if (curnode != decoder->numcodes)
		return HUFFERR_INVALID_DATA;

	/* assign canonical codes for all nodes based on their code lengths */
	error = huffman_assign_canonical_codes(decoder);
	if (error != HUFFERR_NONE)
		return error;

	/* build the lookup table */
	huffman_build_lookup_table(decoder);

	/* determine final input length and report errors */
	return bitstream_overflow(bitbuf) ? HUFFERR_INPUT_BUFFER_TOO_SMALL : HUFFERR_NONE;
}

/*-------------------------------------------------
 *  import_tree_huffman - import a huffman-encoded
 *  huffman tree from a source data stream
 *-------------------------------------------------
 */

enum huffman_error huffman_import_tree_huffman(struct huffman_decoder* decoder, struct bitstream* bitbuf)
{
	int last = 0;
	int curcode;
   uint32_t temp;
   enum huffman_error error;
	uint8_t rlefullbits = 0;
	int index, count = 0;
   int start;
	/* start by parsing the lengths for the small tree */
	struct huffman_decoder* smallhuff = create_huffman_decoder(24, 6);

	smallhuff->huffnode[0].numbits = bitstream_read(bitbuf, 3);
	start = bitstream_read(bitbuf, 3) + 1;

	for (index = 1; index < 24; index++)
	{
		if (index < start || count == 7)
			smallhuff->huffnode[index].numbits = 0;
		else
		{
			count = bitstream_read(bitbuf, 3);
			smallhuff->huffnode[index].numbits = (count == 7) ? 0 : count;
		}
	}

	/* then regenerate the tree */
	error = huffman_assign_canonical_codes(smallhuff);
	if (error != HUFFERR_NONE)
		return error;
	huffman_build_lookup_table(smallhuff);

	/* determine the maximum length of an RLE count */
	temp = decoder->numcodes - 9;
	while (temp != 0)
    {
        temp >>= 1;
        rlefullbits++;
    }

	/* now process the rest of the data */
	for (curcode = 0; curcode < decoder->numcodes; )
	{
		int value = huffman_decode_one(smallhuff, bitbuf);
		if (value != 0)
			decoder->huffnode[curcode++].numbits = last = value - 1;
		else
		{
			int count = bitstream_read(bitbuf, 3) + 2;
			if (count == 7+2)
				count += bitstream_read(bitbuf, rlefullbits);
			for ( ; count != 0 && curcode < decoder->numcodes; count--)
				decoder->huffnode[curcode++].numbits = last;
		}
	}

	/* make sure we ended up with the right number */
	if (curcode != decoder->numcodes)
   {
      delete_huffman_decoder(smallhuff);
		return HUFFERR_INVALID_DATA;
   }

	/* assign canonical codes for all nodes based on their code lengths */
	error = huffman_assign_canonical_codes(decoder);
	if (error != HUFFERR_NONE)
   {
      delete_huffman_decoder(smallhuff);
		return error;
   }

	/* build the lookup table */
	huffman_build_lookup_table(decoder);
	delete_huffman_decoder(smallhuff);

	/* determine final input length and report errors */
	return bitstream_overflow(bitbuf) ? HUFFERR_INPUT_BUFFER_TOO_SMALL : HUFFERR_NONE;
}

/*-------------------------------------------------
 *  compute_tree_from_histo - common backend for
 *  computing a tree based on the data histogram
 *-------------------------------------------------
 */

enum huffman_error huffman_compute_tree_from_histo(struct huffman_decoder* decoder)
{
	/* compute the number of data items in the histogram */
	int i;
   uint32_t upperweight;
	uint32_t lowerweight = 0;
	uint32_t sdatacount = 0;
	for (i = 0; i < decoder->numcodes; i++)
		sdatacount += decoder->datahisto[i];

	/* binary search to achieve the optimum encoding */
	upperweight = sdatacount * 2;
	while (1)
	{
		/* build a tree using the current weight */
		uint32_t curweight = (upperweight + lowerweight) / 2;
		int curmaxbits = huffman_build_tree(decoder, sdatacount, curweight);

		/* apply binary search here */
		if (curmaxbits <= decoder->maxbits)
		{
			lowerweight = curweight;

			/* early out if it worked with the raw weights, or if we're done searching */
			if (curweight == sdatacount || (upperweight - lowerweight) <= 1)
				break;
		}
		else
			upperweight = curweight;
	}

	/* assign canonical codes for all nodes based on their code lengths */
	return huffman_assign_canonical_codes(decoder);
}

/***************************************************************************
 *  INTERNAL FUNCTIONS
 ***************************************************************************
 */

/*-------------------------------------------------
 *  tree_node_compare - compare two tree nodes
 *  by weight
 *-------------------------------------------------
 */

static int huffman_tree_node_compare(const void *item1, const void *item2)
{
	const struct node_t *node1 = *(const struct node_t **)item1;
	const struct node_t *node2 = *(const struct node_t **)item2;
	if (node2->weight != node1->weight)
		return node2->weight - node1->weight;
	if (node2->bits - node1->bits == 0)
		fprintf(stderr, "identical node sort keys, should not happen!\n");
	return (int)node1->bits - (int)node2->bits;
}

/*-------------------------------------------------
 *  build_tree - build a huffman tree based on the
 *  data distribution
 *-------------------------------------------------
 */

int huffman_build_tree(struct huffman_decoder* decoder, uint32_t totaldata, uint32_t totalweight)
{
   int nextalloc;
	int maxbits = 0;
	/* make a list of all non-zero nodes */
	struct node_t** list   = (struct node_t**)
      malloc(sizeof(struct node_t*) * decoder->numcodes * 2);
	int curcode, listitems = 0;

	memset(decoder->huffnode, 0,
         decoder->numcodes * sizeof(decoder->huffnode[0]));

	for (curcode = 0; curcode < decoder->numcodes; curcode++)
		if (decoder->datahisto[curcode] != 0)
		{
			list[listitems++] = &decoder->huffnode[curcode];
			decoder->huffnode[curcode].count = decoder->datahisto[curcode];
			decoder->huffnode[curcode].bits = curcode;

			/* scale the weight by the current effective length, ensuring we don't go to 0 */
			decoder->huffnode[curcode].weight = ((uint64_t)decoder->datahisto[curcode]) * ((uint64_t)totalweight) / ((uint64_t)totaldata);
			if (decoder->huffnode[curcode].weight == 0)
				decoder->huffnode[curcode].weight = 1;
		}

#if 0
   {
      unsigned i;
      fprintf(stderr, "Pre-sort:\n");
      for (i = 0; i < listitems; i++)
         fprintf(stderr, "weight: %d code: %d\n",
               list[i]->m_weight, list[i]->m_bits);
   }
#endif

	/* sort the list by weight, largest weight first */
	qsort(&list[0], listitems, sizeof(list[0]), huffman_tree_node_compare);

#if 0
   fprintf(stderr, "Post-sort:\n");
   for (int i = 0; i < listitems; i++) {
      fprintf(stderr, "weight: %d code: %d\n", list[i]->m_weight, list[i]->m_bits);
   }
   fprintf(stderr, "===================\n");
#endif

	/* now build the tree */
	nextalloc = decoder->numcodes;

	while (listitems > 1)
	{
		int curitem;
		/* remove lowest two items */
		struct node_t* node1   = &(*list[--listitems]);
		struct node_t* node0   = &(*list[--listitems]);

		/* create new node */
		struct node_t* newnode = &decoder->huffnode[nextalloc++];
		newnode->parent        = NULL;
		node0->parent          =
         node1->parent       = newnode;
		newnode->weight        =
         node0->weight + node1->weight;

		/* insert into list at appropriate location */
		for (curitem = 0; curitem < listitems; curitem++)
			if (newnode->weight > list[curitem]->weight)
			{
				memmove(&list[curitem+1],
                  &list[curitem],
                  (listitems - curitem) * sizeof(list[0]));
				break;
			}
		list[curitem] = newnode;
		listitems++;
	}

	/* compute the number of bits in each code,
    * and fill in another histogram */
	for (curcode = 0; curcode < decoder->numcodes; curcode++)
	{
		struct node_t *curnode;
		struct node_t* node = &decoder->huffnode[curcode];
		node->numbits = 0;
		node->bits = 0;

		/* if we have a non-zero weight, compute the number of bits */
		if (node->weight > 0)
		{
			/* determine the number of bits for this node */
			for (curnode = node;
               curnode->parent != NULL; curnode = curnode->parent)
				node->numbits++;
			if (node->numbits == 0)
				node->numbits = 1;

			/* keep track of the max */
			maxbits = MAX(maxbits, ((int)node->numbits));
		}
	}
   free(list);
	return maxbits;
}

/*-------------------------------------------------
 *  assign_canonical_codes - assign canonical codes
 *  to all the nodes based on the number of bits
 *  in each
 *-------------------------------------------------
 */

enum huffman_error huffman_assign_canonical_codes(struct huffman_decoder* decoder)
{
	uint32_t curstart = 0;
	/* build up a histogram of bit lengths */
	int curcode, codelen;
	uint32_t bithisto[33] = { 0 };
	for (curcode = 0; curcode < decoder->numcodes; curcode++)
	{
		struct node_t* node = &decoder->huffnode[curcode];
		if (node->numbits > decoder->maxbits)
			return HUFFERR_INTERNAL_INCONSISTENCY;
		if (node->numbits <= 32)
			bithisto[node->numbits]++;
	}

	/* for each code length, determine the starting code number */
	for (codelen = 32; codelen > 0; codelen--)
	{
		uint32_t nextstart = (curstart + bithisto[codelen]) >> 1;
		if (codelen != 1 && nextstart * 2 != (curstart + bithisto[codelen]))
			return HUFFERR_INTERNAL_INCONSISTENCY;
		bithisto[codelen] = curstart;
		curstart = nextstart;
	}

	/* now assign canonical codes */
	for (curcode = 0; curcode < decoder->numcodes; curcode++)
	{
		struct node_t* node = &decoder->huffnode[curcode];
		if (node->numbits > 0)
			node->bits = bithisto[node->numbits]++;
	}
	return HUFFERR_NONE;
}

/*-------------------------------------------------
 *  build_lookup_table - build a lookup table for
 *  fast decoding
 *-------------------------------------------------
 */

void huffman_build_lookup_table(struct huffman_decoder* decoder)
{
	/* iterate over all codes */
	int curcode;
	for (curcode = 0; curcode < decoder->numcodes; curcode++)
	{
		/* process all nodes which have non-zero bits */
		struct node_t* node = &decoder->huffnode[curcode];
		if (node->numbits > 0)
		{
         int shift;
         lookup_value *dest;
         lookup_value *destend;
			/* set up the entry */
			lookup_value value = MAKE_LOOKUP(curcode, node->numbits);

			/* fill all matching entries */
			shift = decoder->maxbits - node->numbits;
			dest = &decoder->lookup[node->bits << shift];
			destend = &decoder->lookup[((node->bits + 1) << shift) - 1];
			while (dest <= destend)
				*dest++ = value;
		}
	}
}


text:
<!DOCTYPE HTML>

<title>co.aikar.commands.sponge.contexts Class Hierarchy (ACF (Sponge) 0.5.1-SNAPSHOT API)</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="description" content="tree: package: co.aikar.commands.sponge.contexts">
<meta name="generator" content="javadoc/PackageTreeWriter">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../script-dir/jquery-ui.min.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../jquery-ui.overrides.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

SEARCH:
<input type="text" id="search-input" value="search" disabled="disabled">
<input type="reset" id="reset-button" value="reset" disabled="disabled">

Hierarchy For Package co.aikar.commands.sponge.contexts

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

co.aikar.commands.sponge.contexts.OnlinePlayer

Copyright © 2021. All rights reserved.


text:
/**
 * @class Admin_Form_Song
 * @extends CM_Form_Abstract
 */
var Admin_Form_Song = CM_Form_Abstract.extend({
  _class: 'Admin_Form_Song',

  childrenEvents: {
    'Denkmal_FormField_FileSong uploadComplete': function(field, files) {
      this._setLabelFromFilename(files[0].name);
    }
  },

  /**
   * @param {String} filename
   */
  _setLabelFromFilename: function(filename) {
    filename = filename.replace(/\.[^\.]+$/, '');
    this.getField('label').setValue(filename);
  }
});


text:
/*
 * Copyright 2001-2004 The Apache Software Foundation.
 *
 * 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.
 */
/*
 * $Id: RealType.java,v 1.2.4.1 2005/09/05 11:28:45 pvedula Exp $
 */

package com.sun.org.apache.xalan.internal.xsltc.compiler.util;

import com.sun.org.apache.bcel.internal.generic.BranchHandle;
import com.sun.org.apache.bcel.internal.generic.CHECKCAST;
import com.sun.org.apache.bcel.internal.generic.ConstantPoolGen;
import com.sun.org.apache.bcel.internal.generic.DLOAD;
import com.sun.org.apache.bcel.internal.generic.DSTORE;
import com.sun.org.apache.bcel.internal.generic.GOTO;
import com.sun.org.apache.bcel.internal.generic.IFEQ;
import com.sun.org.apache.bcel.internal.generic.IFNE;
import com.sun.org.apache.bcel.internal.generic.INVOKESPECIAL;
import com.sun.org.apache.bcel.internal.generic.INVOKESTATIC;
import com.sun.org.apache.bcel.internal.generic.INVOKEVIRTUAL;
import com.sun.org.apache.bcel.internal.generic.Instruction;
import com.sun.org.apache.bcel.internal.generic.InstructionConstants;
import com.sun.org.apache.bcel.internal.generic.InstructionList;
import com.sun.org.apache.bcel.internal.generic.LocalVariableGen;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.sun.org.apache.xalan.internal.xsltc.compiler.Constants;
import com.sun.org.apache.xalan.internal.xsltc.compiler.FlowList;

/**
 * @author Jacek Ambroziak
 * @author Santiago Pericas-Geertsen
 */
public final class RealType extends NumberType {
    protected RealType() {}

    public String toString() {
        return "real";
    }

    public boolean identicalTo(Type other) {
        return this == other;
    }

    public String toSignature() {
        return "D";
    }

    public com.sun.org.apache.bcel.internal.generic.Type toJCType() {
        return com.sun.org.apache.bcel.internal.generic.Type.DOUBLE;
    }

    /**
     * @see     com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type#distanceTo
     */
    public int distanceTo(Type type) {
        if (type == this) {
            return 0;
        }
        else if (type == Type.Int) {
            return 1;
        }
        else {
            return Integer.MAX_VALUE;
        }
    }

    /**
     * Translates a real into an object of internal type type. The
     * translation to int is undefined since reals are never converted to ints.
     *
     * @see     com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type#translateTo
     */
    public void translateTo(ClassGenerator classGen, MethodGenerator methodGen,
                            Type type) {
        if (type == Type.String) {
            translateTo(classGen, methodGen, (StringType) type);
        }
        else if (type == Type.Boolean) {
            translateTo(classGen, methodGen, (BooleanType) type);
        }
        else if (type == Type.Reference) {
            translateTo(classGen, methodGen, (ReferenceType) type);
        }
        else if (type == Type.Int) {
            translateTo(classGen, methodGen, (IntType) type);
        }
        else {
            ErrorMsg err = new ErrorMsg(ErrorMsg.DATA_CONVERSION_ERR,
                                        toString(), type.toString());
            classGen.getParser().reportError(Constants.FATAL, err);
        }
    }

    /**
     * Expects a real on the stack and pushes its string value by calling
     * Double.toString(double d).
     *
     * @see     com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type#translateTo
     */
    public void translateTo(ClassGenerator classGen, MethodGenerator methodGen,
                            StringType type) {
        final ConstantPoolGen cpg = classGen.getConstantPool();
        final InstructionList il = methodGen.getInstructionList();
        il.append(new INVOKESTATIC(cpg.addMethodref(BASIS_LIBRARY_CLASS,
                                                    "realToString",
                                                    "(D)" + STRING_SIG)));
    }

    /**
     * Expects a real on the stack and pushes a 0 if that number is 0.0 and
     * a 1 otherwise.
     *
     * @see     com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type#translateTo
     */
    public void translateTo(ClassGenerator classGen, MethodGenerator methodGen,
                            BooleanType type) {
        final InstructionList il = methodGen.getInstructionList();
        FlowList falsel = translateToDesynthesized(classGen, methodGen, type);
        il.append(ICONST_1);
        final BranchHandle truec = il.append(new GOTO(null));
        falsel.backPatch(il.append(ICONST_0));
        truec.setTarget(il.append(NOP));
    }

    /**
     * Expects a real on the stack and pushes a truncated integer value
     *
     * @see     com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type#translateTo
     */
    public void translateTo(ClassGenerator classGen, MethodGenerator methodGen,
                            IntType type) {
        final ConstantPoolGen cpg = classGen.getConstantPool();
        final InstructionList il = methodGen.getInstructionList();
        il.append(new INVOKESTATIC(cpg.addMethodref(BASIS_LIBRARY_CLASS,
                                                    "realToInt","(D)I")));
    }

    /**
     * Translates a real into a non-synthesized boolean. It does not push a
     * 0 or a 1 but instead returns branchhandle list to be appended to the
     * false list. A NaN must be converted to "false".
     *
     * @see     com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type#translateToDesynthesized
     */
    public FlowList translateToDesynthesized(ClassGenerator classGen,
                                             MethodGenerator methodGen,
                                             BooleanType type) {
        LocalVariableGen local;
        final FlowList flowlist = new FlowList();
        final ConstantPoolGen cpg = classGen.getConstantPool();
        final InstructionList il = methodGen.getInstructionList();

        // Store real into a local variable
        il.append(DUP2);
        local = methodGen.addLocalVariable("real_to_boolean_tmp",
                                           com.sun.org.apache.bcel.internal.generic.Type.DOUBLE,
                                           null, null);
        local.setStart(il.append(new DSTORE(local.getIndex())));

        // Compare it to 0.0
        il.append(DCONST_0);
        il.append(DCMPG);
        flowlist.add(il.append(new IFEQ(null)));

        //!!! call isNaN
        // Compare it to itself to see if NaN
        il.append(new DLOAD(local.getIndex()));
        local.setEnd(il.append(new DLOAD(local.getIndex())));
        il.append(DCMPG);
        flowlist.add(il.append(new IFNE(null)));        // NaN != NaN
        return flowlist;
    }

    /**
     * Expects a double on the stack and pushes a boxed double. Boxed
     * double are represented by an instance of java.lang.Double.
     *
     * @see     com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type#translateTo
     */
    public void translateTo(ClassGenerator classGen, MethodGenerator methodGen,
                            ReferenceType type) {
        final ConstantPoolGen cpg = classGen.getConstantPool();
        final InstructionList il = methodGen.getInstructionList();
        il.append(new NEW(cpg.addClass(DOUBLE_CLASS)));
        il.append(DUP_X2);
        il.append(DUP_X2);
        il.append(POP);
        il.append(new INVOKESPECIAL(cpg.addMethodref(DOUBLE_CLASS,
                                                     "<init>", "(D)V")));
    }

    /**
     * Translates a real into the Java type denoted by clazz.
     * Expects a real on the stack and pushes a number of the appropriate
     * type after coercion.
     */
    public void translateTo(ClassGenerator classGen, MethodGenerator methodGen,
                            final Class clazz) {
        final InstructionList il = methodGen.getInstructionList();
        if (clazz == Character.TYPE) {
            il.append(D2I);
            il.append(I2C);
        }
        else if (clazz == Byte.TYPE) {
            il.append(D2I);
            il.append(I2B);
        }
        else if (clazz == Short.TYPE) {
            il.append(D2I);
            il.append(I2S);
        }
        else if (clazz == Integer.TYPE) {
            il.append(D2I);
        }
        else if (clazz == Long.TYPE) {
            il.append(D2L);
        }
        else if (clazz == Float.TYPE) {
            il.append(D2F);
        }
        else if (clazz == Double.TYPE) {
            il.append(NOP);
        }
        // Is Double <: clazz? I.e. clazz in { Double, Number, Object }
        else if (clazz.isAssignableFrom(java.lang.Double.class)) {
            translateTo(classGen, methodGen, Type.Reference);
        }
        else {
            ErrorMsg err = new ErrorMsg(ErrorMsg.DATA_CONVERSION_ERR,
                                        toString(), clazz.getName());
            classGen.getParser().reportError(Constants.FATAL, err);
        }
    }

    /**
     * Translates an external (primitive) Java type into a real. Expects a java
     * object on the stack and pushes a real (i.e., a double).
     */
    public void translateFrom(ClassGenerator classGen, MethodGenerator methodGen,
                              Class clazz) {
        InstructionList il = methodGen.getInstructionList();

        if (clazz == Character.TYPE || clazz == Byte.TYPE ||
            clazz == Short.TYPE || clazz == Integer.TYPE) {
            il.append(I2D);
        }
        else if (clazz == Long.TYPE) {
            il.append(L2D);
        }
        else if (clazz == Float.TYPE) {
            il.append(F2D);
        }
        else if (clazz == Double.TYPE) {
            il.append(NOP);
        }
        else {
            ErrorMsg err = new ErrorMsg(ErrorMsg.DATA_CONVERSION_ERR,
                                        toString(), clazz.getName());
            classGen.getParser().reportError(Constants.FATAL, err);
        }
    }

    /**
     * Translates an object of this type to its boxed representation.
     */
    public void translateBox(ClassGenerator classGen,
                             MethodGenerator methodGen) {
        translateTo(classGen, methodGen, Type.Reference);
    }

    /**
     * Translates an object of this type to its unboxed representation.
     */
    public void translateUnBox(ClassGenerator classGen,
                               MethodGenerator methodGen) {
        final ConstantPoolGen cpg = classGen.getConstantPool();
        final InstructionList il = methodGen.getInstructionList();
        il.append(new CHECKCAST(cpg.addClass(DOUBLE_CLASS)));
        il.append(new INVOKEVIRTUAL(cpg.addMethodref(DOUBLE_CLASS,
                                                     DOUBLE_VALUE,
                                                     DOUBLE_VALUE_SIG)));
    }

    public Instruction ADD() {
        return InstructionConstants.DADD;
    }

    public Instruction SUB() {
        return InstructionConstants.DSUB;
    }

    public Instruction MUL() {
        return InstructionConstants.DMUL;
    }

    public Instruction DIV() {
        return InstructionConstants.DDIV;
    }

    public Instruction REM() {
        return InstructionConstants.DREM;
    }

    public Instruction NEG() {
        return InstructionConstants.DNEG;
    }

    public Instruction LOAD(int slot) {
        return new DLOAD(slot);
    }

    public Instruction STORE(int slot) {
        return new DSTORE(slot);
    }

    public Instruction POP() {
        return POP2;
    }

    public Instruction CMP(boolean less) {
        return less ? InstructionConstants.DCMPG : InstructionConstants.DCMPL;
    }

    public Instruction DUP() {
        return DUP2;
    }
}


text:
<?php
/**
 * Contains MKosolofski\HouseSeats\MonitorBundle\DependencyInjection\MKosolofskiHouseSeatsMonitorExtension
 *
 * @package MKosolofski
 * @subpackage HouseSeats\MonitorBundle
 */

namespace MKosolofski\HouseSeats\MonitorBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder,
    Symfony\Component\Config\FileLocator,
    Symfony\Component\HttpKernel\DependencyInjection\Extension,
    Symfony\Component\DependencyInjection\Loader;

/**
 * @package MKosolofski
 * @subpackage HouseSeats\MonitorBundle
 * @author Matthew Kosolofski <matthew.kosolofski@gmail.com>
 */
class MKosolofskiHouseSeatsMonitorExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $container->setParameter('mkosolofski.house_seats.monitor.config', $config);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');
    }
}


text:
package org.overlord.dtgov.ui.client.shared.beans;

import java.io.Serializable;
import java.util.List;

import org.jboss.errai.common.client.api.annotations.Portable;

/**
 * Models the set of Processes Bean summary objects.
 *
 * @author dvirgiln@redhat.com
 */
@Portable
public class ProcessesResultSetBean implements Serializable{

    /**
     *
     */
    private static final long serialVersionUID = 1469275782682092743L;

    /** The _queries. */
    private List<ProcessBean> _processes;

    /** The _total results. */
    protected long _totalResults;

    /** The _items per page. */
    private int _itemsPerPage;

    /** The _start index. */
    private int _startIndex;

    /**
     * Instantiates a new workflow query result set bean.
     */
    public ProcessesResultSetBean(){

    }

    public List<ProcessBean> getProcesses() {
        return _processes;
    }

    public void setProcesses(List<ProcessBean> processes) {
        this._processes = processes;
    }

    public long get_totalResults() {
        return _totalResults;
    }

    public void set_totalResults(long _totalResults) {
        this._totalResults = _totalResults;
    }

    /**
     * Gets the items per page.
     *
     * @return the items per page
     */
    public int getItemsPerPage() {
        return _itemsPerPage;
    }

    /**
     * Sets the items per page.
     *
     * @param itemsPerPage
     *            the new items per page
     */
    public void setItemsPerPage(int itemsPerPage) {
        this._itemsPerPage = itemsPerPage;
    }

    /**
     * Gets the start index.
     *
     * @return the start index
     */
    public int getStartIndex() {
        return _startIndex;
    }

    /**
     * Sets the start index.
     *
     * @param startIndex
     *            the new start index
     */
    public void setStartIndex(int startIndex) {
        this._startIndex = startIndex;
    }

}


text:
#ifndef otbImageFileReaderException_h
#define otbImageFileReaderException_h

#include "itkMacro.h"
#include "OTBImageIOExport.h"

namespace otb
{

/** \class ImageFileReaderException
 *
 * \brief Base exception class for IO conflicts.
 *
 * \ingroup OTBImageIO
 */
class OTBImageIO_EXPORT ImageFileReaderException : public itk::ExceptionObject
{
public:
  /** Run-time information. */
  itkTypeMacro(ImageFileReaderException, ExceptionObject);

  /** Constructor. */
  ImageFileReaderException(const char* file, unsigned int line, const std::string& desc = "", const std::string& filename = "");

  /** Destructor. */
  ~ImageFileReaderException();

  std::string m_Filename;
};
}

#endif


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Elasticsearch.Net;
using Newtonsoft.Json;

namespace Nest
{
	[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
	public interface IOptimizeRequest : IIndicesOptionalPath<OptimizeRequestParameters> { }

	internal static class OptimizePathInfo
	{
		public static void Update(ElasticsearchPathInfo<OptimizeRequestParameters> pathInfo, IOptimizeRequest request)
		{
			pathInfo.HttpMethod = PathInfoHttpMethod.POST;
		}
	}

	public partial class OptimizeRequest : IndicesOptionalPathBase<OptimizeRequestParameters>, IOptimizeRequest
	{

		/// <summary>
		/// Does an _optimize on all indices (unless bounded by setting the Indices property).
		/// </summary>
		public OptimizeRequest() {}

		/// <summary>
		/// Does an _optimize on /{index}/_optimize
		/// </summary>
		public OptimizeRequest(IndexNameMarker index)
		{
			this.Indices = new[] { index };
		}
		/// <summary>
		/// Does an _optimize on /{indices}/_optimize
		/// </summary>
		public OptimizeRequest(IEnumerable<IndexNameMarker> indices)
		{
			this.Indices = indices;
		}

		protected override void UpdatePathInfo(IConnectionSettingsValues settings, ElasticsearchPathInfo<OptimizeRequestParameters> pathInfo)
		{
			OptimizePathInfo.Update(pathInfo, this);
		}
	}
	[DescriptorFor("IndicesOptimize")]
	public partial class OptimizeDescriptor : IndicesOptionalPathDescriptor<OptimizeDescriptor, OptimizeRequestParameters>, IOptimizeRequest
	{
		protected override void UpdatePathInfo(IConnectionSettingsValues settings, ElasticsearchPathInfo<OptimizeRequestParameters> pathInfo)
		{
			OptimizePathInfo.Update(pathInfo, this);
		}
	}
}


text:
"""
Utilities for use by latchpony classes
"""

import uuid
import functools
import operator
#from pprint import pprint
from copy import copy

UUID_LENGTH = 8  # TO-DO Import this rather than redefine it.
__all__ = ['sanitise_name', 'random_uuid', 'unique_key_dict_update', 'borg',
           'init_caps', 'lru_cache', 'Abacus',
           'sets_to_sorted_lists']

"""
TO-DO
[ ] Validation:
    1. Check that competitors have consistent members/groups

[ ] Naming conventions:
    1. Require that all names are unique, not just within riders or ponies.
       If we do that, then referring to the object by lookup becomes easier,
       and it reduces potential confusion.

[ ] Use of ZCA for documentation or testing
"""

# Utilities
def borg(cls):
    """Class decorator for Borg pattern, used to ensure that to start with
    there is only one competition in the system at one time.
    """
    cls._state = {}
    orig_init = cls.__init__

    def new_init(self, *args, **kwargs):
        self.__dict__ = cls._state
        orig_init(self, *args, **kwargs)

    cls.__init__ = new_init
    return cls

def init_caps(text):
    """Upper case each word in the text.
    """
    return " ".join(word.capitalize() for word in str(text).split())

def sets_to_sorted_lists(dict_with_sets):
    """Recursively replace sets with sorted lists, in a dictionary copy.
    """
    result = {}
    for key in dict_with_sets:
        value = dict_with_sets[key]
        try:
            # Check that the input is a set by or-ing with empty set
            result[key] = sorted(value | set([]))  # TypeError if not a set
        except TypeError:
            try:
                value['$$no-such-key$$']
            except KeyError:
                # Ha! But the KeyError shows you are a dictionary!
                result[key] = sets_to_sorted_lists(dict_with_sets[key])
            except TypeError:
                result[key] = value  # OK if it's a string, number or list
    return result

def random_uuid(uuid_length=UUID_LENGTH, uuid_dict={}):
    """Generate a random UUID. Since the length may be shorter than the
    32 significant chars of a proper UUID, check for uniqueness by
    comparing against the keys of the dictionary within which they are used.

    TO-DO: Prevent infinite recursion on very small uuid_length.
    """
    long_uuid = str(uuid.uuid4())
    if uuid_length < 36:
        result = long_uuid[:uuid_length]
        if result in uuid_dict:
            # Keep going recursively until we have found a unique uuid
            result = random_uuid(uuid_length, uuid_dict)
        return result
    else:
        # Statistically unique: no need to check
        return long_uuid

def sanitise_name(raw_name):
    """Strip leading/trailing white space, and replace internal (multiple)
    spaces with an underscore.
    """
    return '_'.join(str(raw_name).lower().strip().split())

def unique_key_dict_update(adict, key, node):
    """Add key+value to dictionary, ensuring keys remain unique by adding
    UUIDs where necessary. This is so that we can use names as keys, without
    having to worry about duplicates in mass imports.
    The node parameter should have a 'name' attribute.
    We have to leave the old key there to ensure further duplicates are
    correctly handled.
    """
    # TO-DO Handle None for dup competitor
    # TO-DO Fix duplicates in two dictionaries at once
    # TO-DO Examples in docstring
    try:
        existing_node = adict[key]
        # Need to avoid overwriting existing_node. If existing_value is
        # None then this is another duplicate, with first duplicate key
        # needing to be kept as a marker.
        if not existing_node.name.startswith('duplicate$'):
            existing_key_with_uuid = '{}${}'.format(key, random_uuid())
            adict[existing_key_with_uuid] = existing_node
            # We have to update the competitor's name that we've changed
            existing_node.name = existing_key_with_uuid

            adict[key] = copy(existing_node)
            adict[key].name = 'duplicate${}'.format(key)
        new_key_with_uuid = '{}${}'.format(key, random_uuid(8))
        adict[new_key_with_uuid] = node
        node.name = new_key_with_uuid
        return new_key_with_uuid
    except KeyError:
        # This is a new key
        adict[key] = node
        return key

class Abacus(object):
    """Example class to help Rob understand what is happening in creating
    a REST web service.

    Called from url
        http://localhost:16804/abacus/product?data=[5,2,3]
    using route from
    ../pp-latchpony-restservice/Service/pp/latchpony/service/__init__.py
        config.add_route('get_greeting', '/greeting')
    and function from
    ../pp-latchpony-restservice/Service/pp/latchpony/service/views.py
        def greeting_handler(request):
    This creates a Competition object, from which say_hello() is called.
    """

    def __init__(self, name, operation='sum'):
        self.name = name
        self.operation = operation

    def calculate(self, *args):
        if self.operation in ['sum', 'add']:
            result = sum(args)
        elif self.operation == 'product':
            result = self.product(args)
        else:
            raise NotImplementedError('Unknown operation "{}"'.format(
                self.operation))
        return dict(operation=self.operation, data=args, result=result)

    def product(self, data_list):
        """Product of a sequence. Third argument is the initial value."""
        return functools.reduce(operator.mul, data_list, 1)

#  http://code.activestate.com/recipes/578078/ (r5)
from collections import namedtuple
from functools import update_wrapper
from threading import Lock

_CacheInfo = namedtuple("CacheInfo", ["hits", "misses", "maxsize", "currsize"])

def lru_cache(maxsize=1000, typed=False):
    """Least-recently-used cache decorator.

    If *maxsize* is set to None, the LRU features are disabled and the cache
    can grow without bound.

    If *typed* is True, arguments of different types will be cached separately.
    For example, f(3.0) and f(3) will be treated as distinct calls with
    distinct results.

    Arguments to the cached function must be hashable.

    View the cache statistics named tuple (hits, misses, maxsize, currsize)
    with f.cache_info().  Clear the cache and statistics with f.cache_clear().
    Access the underlying function with f.__wrapped__.

    See:  http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used

    """

    # Users should only access the lru_cache through its public API:
    #       cache_info, cache_clear, and f.__wrapped__
    # The internals of the lru_cache are encapsulated for thread safety and
    # to allow the implementation to change (including a possible C version).

    def decorating_function(user_function):
        cache = dict()
        stats = [0, 0]                # make statistics updateable non-locally
        HITS, MISSES = 0, 1             # names for the stats fields
        kwd_mark = (object(),)          # separate positional and keyword args
        cache_get = cache.get      # bound method to lookup key or return None
        _len = len                      # localize the global len() function
        lock = Lock()          # because linkedlist updates aren't threadsafe
        root = []                    # root of the circular doubly linked list
        nonlocal_root = [root]                  # make updateable non-locally
        root[:] = [root, root, None, None]     # initialize by pointing to self
        PREV, NEXT, KEY, RESULT = 0, 1, 2, 3    # names for the link fields

        def make_key(args, kwds, typed, tuple=tuple, sorted=sorted, type=type):
            # helper function to build a cache key from positional and keyword
            # args
            key = args
            if kwds:
                sorted_items = tuple(sorted(kwds.items()))
                key += kwd_mark + sorted_items
            if typed:
                key += tuple(type(v) for v in args)
                if kwds:
                    key += tuple(type(v) for k, v in sorted_items)
            return key

        if maxsize == 0:

            def wrapper(*args, **kwds):
                # no caching, just do a statistics update after a
                # successful call
                result = user_function(*args, **kwds)
                stats[MISSES] += 1
                return result

        elif maxsize is None:

            def wrapper(*args, **kwds):
                # simple caching without ordering or size limit
                key = make_key(args, kwds, typed) if kwds or typed else args
                # root used here as a unique not-found sentinel
                result = cache_get(key, root)
                if result is not root:
                    stats[HITS] += 1
                    return result
                result = user_function(*args, **kwds)
                cache[key] = result
                stats[MISSES] += 1
                return result

        else:

            def wrapper(*args, **kwds):
                # size limited caching that tracks accesses by recency
                key = make_key(args, kwds, typed) if kwds or typed else args
                with lock:
                    link = cache_get(key)
                    if link is not None:
                        # record recent use of the key by moving it to the
                        # front of the list
                        root, = nonlocal_root
                        link_prev, link_next, key, result = link
                        link_prev[NEXT] = link_next
                        link_next[PREV] = link_prev
                        last = root[PREV]
                        last[NEXT] = root[PREV] = link
                        link[PREV] = last
                        link[NEXT] = root
                        stats[HITS] += 1
                        return result
                result = user_function(*args, **kwds)
                with lock:
                    root = nonlocal_root[0]
                    if _len(cache) < maxsize:
                        # put result in a new link at the front of the list
                        last = root[PREV]
                        link = [last, root, key, result]
                        cache[key] = last[NEXT] = root[PREV] = link
                    else:
                        # use root to store the new key and result
                        root[KEY] = key
                        root[RESULT] = result
                        cache[key] = root
                        # empty the oldest link and make it the new root
                        root = nonlocal_root[0] = root[NEXT]
                        del cache[root[KEY]]
                        root[KEY] = None
                        root[RESULT] = None
                    stats[MISSES] += 1
                return result

        def cache_info():
            """Report cache statistics"""
            with lock:
                return _CacheInfo(
                    stats[HITS], stats[MISSES], maxsize, len(cache))

        def cache_clear():
            """Clear the cache and cache statistics"""
            with lock:
                cache.clear()
                root = nonlocal_root[0]
                root[:] = [root, root, None, None]
                stats[:] = [0, 0]

        wrapper.__wrapped__ = user_function
        wrapper.cache_info = cache_info
        wrapper.cache_clear = cache_clear
        return update_wrapper(wrapper, user_function)

    return decorating_function
# end of http://code.activestate.com/recipes/578078/


text:
package org.elasticsearch.common.io.stream;

import java.io.IOException;

/**
 * Implementers can be read from {@linkplain StreamInput} by calling their {@link #readFrom(StreamInput)} method.
 *
 * Implementers of this interface that also implement {@link Writeable} should see advice there on how to do so.
 */
public interface StreamableReader<T> {
    /**
     * Reads an object of this type from the provided {@linkplain StreamInput}. The receiving instance remains unchanged.
     */
    T readFrom(StreamInput in) throws IOException;
}