text:
import { Seconds, Ticks } from "../type/Units";
import { noOp } from "../util/Interface";

type Transport = import("../clock/Transport").Transport;

export interface TransportEventOptions {
	callback: (time: number) => void;
	once: boolean;
	time: Ticks;
}

/**
 * TransportEvent is an internal class used by [[Transport]]
 * to schedule events. Do no invoke this class directly, it is
 * handled from within Tone.Transport.
 */
export class TransportEvent {

	/**
	 * Reference to the Transport that created it
	 */
	protected transport: Transport;

	/**
	 * The unique id of the event
	 */
	id: number = TransportEvent._eventId++;

	/**
	 * The time the event starts
	 */
	time: Ticks;

	/**
	 * The callback to invoke
	 */
	private callback?: (time: Seconds) => void;

	/**
	 * If the event should be removed after being invoked.
	 */
	private _once: boolean;

	/**
	 * The remaining value between the passed in time, and Math.floor(time).
	 * This value is later added back when scheduling to get sub-tick precision.
	 */
	protected _remainderTime = 0;

	/**
	 * @param transport The transport object which the event belongs to
	 */
	constructor(transport: Transport, opts: Partial<TransportEventOptions>) {

		const options: TransportEventOptions = Object.assign(TransportEvent.getDefaults(), opts);

		this.transport = transport;
		this.callback = options.callback;
		this._once = options.once;
		this.time = Math.floor(options.time);
		this._remainderTime = options.time - this.time;
	}

	static getDefaults(): TransportEventOptions {
		return {
			callback: noOp,
			once: false,
			time: 0,
		};
	}

	/**
	 * Current ID counter
	 */
	private static _eventId = 0;

	/**
	 * Get the time and remainder time.
	 */
	protected get floatTime(): number {
		return this.time + this._remainderTime;
	}

	/**
	 * Invoke the event callback.
	 * @param  time  The AudioContext time in seconds of the event
	 */
	invoke(time: Seconds): void {
		if (this.callback) {
			const tickDuration = this.transport.bpm.getDurationOfTicks(1, time);
			this.callback(time + this._remainderTime * tickDuration);
			if (this._once) {
				this.transport.clear(this.id);
			}
		}
	}

	/**
	 * Clean up
	 */
	dispose(): this {
		this.callback = undefined;
		return this;
	}
}


text:
package com.deffence.mm.dropwizard.thymeleaf;

import java.nio.charset.Charset;

import io.dropwizard.views.View;

/**
 *
 * @author mmatsushita
 *
 */
public abstract class ThymeleafView extends View {

	private String simpleTemplateName;

	protected ThymeleafView(String templateName) {
		super(templateName);
	}

	public ThymeleafView(String templateName, Charset charset) {
		super(templateName, charset);
	}

	@Override
	public String getTemplateName() {

		if(null == simpleTemplateName){
			simpleTemplateName = convertToSimpleTemplateName(super.getTemplateName());
		}
		return simpleTemplateName;

	}

	private String convertToSimpleTemplateName(String templateName) {
		String[] names = templateName.split("/");

		return names[names.length-1];
	}

}

redpajama_set_name: RedPajamaGithub


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TelescopeMove : MonoBehaviour
{

    public bool canMove = false;
    public float moveSpeed = 0.5f;
    public float maxX = 6.5f;
    public float maxY = 3.5f;
    public float edgeX = 6.0f;
    public float edgeSkyX = 16.0f;

    [Header("new system - bounds")]
    public float boundsTop = 13.0f;
    public float boundsBottom = -1.0f;
    public float boundsLeft = -20.0f;
    public float boundsRight = 20.0f;
    public Transform sky;
    public Transform starParent;
    public List<Transform> stars;
    public StarGazingScene sceneManager;

    public SpriteRenderer fadeOverlay;
    public List<GameObject> hiddenInTelescope = new List<GameObject>();

    [Header("Constellations")]
    public List<GameObject> constallations = new List<GameObject>();
    public List<Vector2> constellationPositions = new List<Vector2>();
    public List<sceneState> sceneStates = new List<sceneState>();
    public List<int> constellationCounter = new List<int>();
    public List<int> constellationMaxCount = new List<int>();
    public List<GameObject> pulsingStars = new List<GameObject>();
    public bool pulseGo = false;

    [HideInInspector]
    public float x;
    [HideInInspector]
    public float y;

    private List<Transform> starArray;
    public Transform currentConstellationPos;

    [Header ("Audio")]
    public float distanceToCurrentConstellation;
    private float timeSinceDistanceUpdate;
    [SerializeField]
    private float pulseRate;
    [Range (0, 100)]
    public float pulseMultiplier;

    private void Start()
    {

        starArray = new List<Transform>();
        if (stars.Count > 0)
            starArray.AddRange(stars);
        for (int i = 0; i < constallations.Count; i++)
        {
            constellationCounter.Add(0);
            constellationMaxCount.Add(constallations[i].GetComponentsInChildren<CircleCollider2D>().Length);
        }
        GameObject starPulse = constallations[0].GetComponentInChildren<StarPulse>().gameObject;
        currentConstellationPos = starPulse.transform;
        UpdateDistance();
    }

    public void AttachSoundToCurrentStar()
    {
        AudioManager.instance.Attach(AudioManager.instance.Searching, currentConstellationPos);
    }

    void UpdateDistance()
    {
        var currentDistance = ((Vector2)(currentConstellationPos.position - transform.position)).magnitude;
        if (distanceToCurrentConstellation != currentDistance)
        {
            distanceToCurrentConstellation = currentDistance;
            pulseRate = 1 / distanceToCurrentConstellation * pulseMultiplier;
            timeSinceDistanceUpdate = 0f;
        }
    }

    void Update()
    {
        timeSinceDistanceUpdate += Time.deltaTime;
        AudioManager.instance.SetParameterValue(AudioManager.instance.Searching, "SearchPulse", (Mathf.Sin(Time.time * pulseRate) + 1) / 2);
        if (timeSinceDistanceUpdate > 2f) UpdateDistance();

        if (canMove)
        {
            float s = Screen.width / 100;

            float moveX = (Input.GetAxis("StarsHoriz") * moveSpeed) / (s * s);
            float moveY = (Input.GetAxis("StarsVert") * moveSpeed) / (s * s);

            if (y + moveY > boundsBottom &&
                y + moveY < boundsTop &&
                x + moveX > boundsLeft &&
                x + moveX < boundsRight)
            {
                x += moveX;
                y += moveY;
                sky.position = new Vector3(sky.position.x - moveX, sky.position.y - moveY, 0);
            }

            float keysX = (Input.GetAxis("StarsHorizKeys") * moveSpeed * 20) / (s * s);
            float keysY = (Input.GetAxis("StarsVertKeys") * moveSpeed * 20) / (s * s);

            if (y + keysY > boundsBottom &&
                y + keysY < boundsTop &&
                x + keysX > boundsLeft &&
                x + keysX < boundsRight)
            {
                x += keysX;
                y += keysY;
                sky.position = new Vector3(sky.position.x - keysX, sky.position.y - keysY, 0);
            }
        }

        for (int i = 0; i < sceneStates.Count; i++)
        {
            if (sceneManager.SceneState == sceneStates[i])
            {
                if (!pulsingStars[i].GetComponent<StarPulse>().pulseStart && pulseGo)
                {
                    pulsingStars[i].GetComponent<StarPulse>().t = 0;
                    pulsingStars[i].GetComponent<StarPulse>().pulseStart = true;
                    pulsingStars[i].GetComponent<StarPulse>().pulse = true;
                }
            }
        }
    }

    public void OnTriggerEnter2D(Collider2D c)
    {
        for (int i = 0; i < constallations.Count; i++)
        {
            if (sceneManager.SceneState == sceneStates[i])
            {
                if (c.gameObject.tag == constallations[i].tag)
                {
                    constellationCounter[i] += 1;
                    FoundStar(c.gameObject, constellationCounter[i], constellationMaxCount[i], i + 1);

                }
            }
        }
    }

    private void FoundStar(GameObject star, int currentCount, int maxCount, int constNo)
    {
        star.transform.GetChild(0).gameObject.SetActive(true);
        star.GetComponent<Collider2D>().enabled = false;
        if (sceneManager.overlay)
            star.GetComponent<SpriteRenderer>().material.SetColor("_Color", Color.yellow);

        sceneManager.displayMemories.ForceQuit();

        //Play StarFound sound
        var tempSound = AudioManager.instance.CreateEventInstance(AudioManager.Events.StarFound);

        if (maxCount == 1) tempSound.setParameterValue("StarCount", AudioManager.instance.GetParameterMaxValue(tempSound, "StarCount"));
        else tempSound.setParameterValue("StarCount", maxCount - (maxCount - currentCount) - 1);
        tempSound.start();
        if (AudioManager.instance.IsMatchingEvent(AudioManager.instance.StarGazingAmbience, AudioManager.Events.IndiaAmbience)){
            AudioManager.instance.PlayOneShot(AudioManager.Events.StarFoundIndiaLayer);
        }

        if (currentCount == maxCount)
        {
            AudioManager.instance.StopEventInstance(AudioManager.instance.Searching, FMOD.Studio.STOP_MODE.ALLOWFADEOUT, false);
            // if this is not the last constellation in scene, update audio position to next constellation
            if (constNo < constallations.Count)
            {
                // Zero based - so constNo is actually setting the next constellation here
                currentConstellationPos = constallations[constNo].GetComponentInChildren<StarPulse>().transform;
                AttachSoundToCurrentStar();
            }

            StartCoroutine(Delay(constNo));
            for (int i = 0; i < sceneStates.Count; i++)
            {
                if (sceneManager.SceneState == sceneStates[i])
                {
                    if (!pulsingStars[i].GetComponent<StarPulse>().pulseStop)
                    {
                        pulsingStars[i].GetComponent<StarPulse>().pulseStop = true;
                        pulsingStars[i].GetComponent<StarPulse>().pulse = false;
                    }
                }
            }
        }
    }

    private IEnumerator Delay(int constNo)
    {
        bool done = false;
        while (!done)
        {
            yield return new WaitForSeconds(0.5f);

            // Debug.Log("I found a constellation!" + constNo);

            AudioManager.instance.PlayEvent(AudioManager.instance.ConstellationFound);

            if (constNo == 1)
            {
                StartCoroutine(lerpToConstellationPos(sky.position, constellationPositions[0], false));
                sceneManager.SceneState = sceneState.CONSTONEDURING;
                sceneManager.updateSceneState(sceneManager.SceneState);
            }
            else if (constNo == 2)
            {

                if (sceneManager.overlayMagGlass)
                {
                    sceneManager.SceneState = sceneState.CONSTONEDURING2;
                    StartCoroutine(lerpToConstellationPos(sky.position, constellationPositions[1], true));
                }
                else
                {
                    sceneManager.SceneState = sceneState.CONSTONEDONE;
                    StartCoroutine(lerpToConstellationPos(sky.position, constellationPositions[1], false));
                }

                sceneManager.updateSceneState(sceneManager.SceneState);
            }
            else if (constNo == 3)
            {
                StartCoroutine(lerpToConstellationPos(sky.position, constellationPositions[2], false));
                if (sceneManager.overlayMagGlass)
                {
                    sceneManager.SceneState = sceneState.CONSTONEDONE;
                }
                else
                    sceneManager.SceneState = sceneState.CONSTTWODURING;
                sceneManager.updateSceneState(sceneManager.SceneState);
            }
            else if (constNo == 4)
            {
                StartCoroutine(lerpToConstellationPos(sky.position, constellationPositions[3], false));
                sceneManager.SceneState = sceneState.CONSTTWODONE;
                sceneManager.updateSceneState(sceneManager.SceneState);
            }
            else if (constNo == 5)
            {
                StartCoroutine(lerpToConstellationPos(sky.position, constellationPositions[4], false));
                sceneManager.SceneState = sceneState.CONSTTHREEDURING;
                sceneManager.updateSceneState(sceneManager.SceneState);
            }
            else if (constNo == 6)
            {
                StartCoroutine(lerpToConstellationPos(sky.position, constellationPositions[5], false));
                sceneManager.SceneState = sceneState.CONSTTHREEDONE;
                sceneManager.updateSceneState(sceneManager.SceneState);
            }
            done = true;
        }
    }
    public IEnumerator returnTelescopeToOrigin(Vector3 endPoint, Vector3 endScale, bool zoom)
    {
        float i = 0;
        Vector3 startPos = transform.localPosition;
        Vector3 startScale = transform.localScale;

        while (i < 1)
        {
            i += Time.deltaTime * 0.5f;
            transform.localPosition = Vector3.Lerp(new Vector3(startPos.x, startPos.y, 1), endPoint, i);
            transform.localScale = Vector3.Lerp(new Vector3(startScale.x, startScale.y, 1), endScale, i);
            yield return new WaitForEndOfFrame();
        }
        if (zoom)
            sceneManager.StartCoroutine(sceneManager.zoomScope(transform.localScale.x, 3.5f, false));
    }

    public IEnumerator returnSky(sceneState scene)
    {
        float i = 0;
        while (i < 1)
        {
            i += Time.deltaTime;
            fadeOverlay.color = new Color(0, 0, 0, i);
            yield return new WaitForEndOfFrame();
        }

        bool done = false;
        while (!done)
        {
            if (stars.Count > 0)
            {
                stars.Clear();
                stars.AddRange(starArray);

                foreach (var item in stars)
                {
                    item.localPosition = Vector3.zero;
                }
            }

            starParent.localPosition = Vector3.zero;
            sky.localPosition = Vector3.zero;
            StartCoroutine(hideObjects(false));
            yield return new WaitForSeconds(0.5f);
            //StartCoroutine(returnTelescopeToOrigin(new Vector3(0, 0, 1), new Vector3(1, 1, 1),true));
            sceneManager.StartCoroutine(sceneManager.zoomScope(1.6f, 3.5f, false));
            done = true;
        }

        float j = 1;
        while (j > 0)
        {
            j -= Time.deltaTime;
            fadeOverlay.color = new Color(0, 0, 0, j);
            sceneManager.lensOverlay.intensity = 0;
            yield return new WaitForEndOfFrame();
        }
        sceneManager.SceneState = scene;
        sceneManager.updateSceneState(scene);
    }

    public IEnumerator hideObjects(bool hide)
    {
        float i = 0;
        if (hide)
        {
            Color c = new Color(1, 1, 1, 1);
            while (i < 1)
            {
                i += Time.deltaTime * 0.5f;
                c.a = Mathf.Lerp(1, 0, i);

                if (hiddenInTelescope.Count > 0)
                {
                    foreach (var item in hiddenInTelescope)
                    {
                        item.GetComponent<SpriteRenderer>().color = c;
                    }
                }

                yield return new WaitForEndOfFrame();
            }
        }
        else if (!hide)
        {
            Color c = new Color(1, 1, 1, 0);
            while (i < 1)
            {
                i += Time.deltaTime;
                c.a = Mathf.Lerp(0, 1, i);

                if (hiddenInTelescope.Count > 0)
                {
                    foreach (var item in hiddenInTelescope)
                    {
                        item.GetComponent<SpriteRenderer>().color = c;
                    }
                }

                yield return new WaitForEndOfFrame();
            }
        }
    }

    public IEnumerator lerpToConstellationPos(Vector2 start, Vector2 end, bool lerpCameraAtEnd)
    {
        float i = 0;
        while (i<1)
        {
            i += Time.deltaTime;
            Vector2 pos = Vector2.Lerp(start, end, i);
            sky.position = pos;
            yield return new WaitForEndOfFrame();
        }

        if (lerpCameraAtEnd)
            sceneManager.StartCoroutine(sceneManager.lerpCamera(5, 17, new Vector3(-6, -6, -10), new Vector3(0, -8, -10), 0.25f));
    }
}


text:
if (typeof console === 'undefined') {
  console = {
    log: function() {},
    warn: function() {},
    error: function() {},
    debug: function() {}
  };
}

var perfRunner;
if (typeof exports === 'object') {
  perfRunner = exports;
} else {
  perfRunner = {};
}

perfRunner.assert = function(test, message) {
  if (typeof test === 'function') {
    test = test();
  }
  if (test) {
    return;
  }
  throw Error(message);
};

perfRunner.WriteScript = function(props) {
  var type = '';
  if (props.jsx) {
    type = ' type=\'text/jsx\'';
  }
  var src = props.src;
  if (!props.cache) {
    src += src.indexOf('?') === -1 ? '?_' : '&_';
    src += perfRunner.WriteScript.cacheBust;
  }
  document.write('<script' + type + ' src=\'' + src + '\'><\/script>');
};
perfRunner.WriteScript.cacheBust = (+new Date()).toString(36);

perfRunner.WriteReactLibScript = function(params) {
  var src;
  var minSuffix;
  if (params.debug) {
    minSuffix = '';
  } else {
    minSuffix = '.min';
  }

  if (params.version && typeof params.version !== 'string') {
    throw TypeError('Expected \'version\' to be a string');
  }

  if (params.version === 'edge' || !params.version) {
    console.log('React edge (local)');
    perfRunner.WriteScript({src:'../build/react' + minSuffix + '.js'});
    perfRunner.WriteScript({src:'../build/JSXTransformer.js'});
  } else if (params.version === 'previous') {
    console.log('React previous (local)');
    perfRunner.WriteScript({cache:true, src:'../build/react-previous' + minSuffix + '.js'});
    perfRunner.WriteScript({cache:true, src:'../build/JSXTransformer-previous.js'});
  } else if (params.version.indexOf('builds/') === 0) {
    perfRunner.WriteScript({cache:true, src:'http://react.zpao.com/' + params.version + '/react' + minSuffix + '.js'});
    perfRunner.WriteScript({cache:true, src:'http://react.zpao.com/' + params.version + '/JSXTransformer.js'});
  } else {
    console.log('React ' + params.version);
    perfRunner.WriteScript({cache:true, src:'http://fb.me/react-' + params.version + minSuffix + '.js'});
    perfRunner.WriteScript({cache:true, src:'http://fb.me/JSXTransformer-' + params.version + '.js'});
  }
  if (params.debug) {
    console.warn('Loading the unminified build of React, performance may suffer.');
    console.warn('Load \'' + location.href.replace(/\bdebug=\w+&?|&\bdebug=\w+/ig, '') + '\' for better perf.');
  } else {
    console.warn('Loading the minified build of React, debugging may be harder.');
    console.warn('Load \'' + location.href.replace(/\bdebug=\w+&?|&\bdebug=\w+/ig, '') + '&debug=1' + '\' for easier debugging.');
  }
};

perfRunner.WriteTestScript = function(params) {
  if (Array.isArray(params.test)) {
    return params.test
      .map(function(test) {
        return {
          test:test
        };
      })
      .map(perfRunner.WriteTestScript);
  }
  perfRunner.assert(params.test.indexOf('..') === -1, 'no relative paths allowed');
  return perfRunner.WriteScript({jsx:true, src: './tests/' + params.test});
};

perfRunner.getQueryParamArray = function(key) {
  var values;
  var queryString = location.search.substr(1);
  var _key = encodeURIComponent(key) + '=';

  if (queryString.indexOf(_key) > -1) {
    values = queryString
      .split(_key)
      .slice(1)
      .map(function(part) {
        return part.split('&')[0];
      })
      .map(decodeURIComponent)
      .map(function(string) {
        try {
          return JSON.parse(string);
        } catch(e) {}
        return string;
      });
  }

  perfRunner.assert(values && values.length && values[0], 'expected ' + key + ' query param');
  return values;
};

perfRunner.getQueryParamArrayOrDefault = function(key, defaultValue) {
  try {
    return perfRunner.getQueryParamArray(key);
  } catch (e) {}
  return defaultValue;
};

perfRunner.Polyfill = function() {
  if (typeof Function.prototype.bind !== 'undefined') {
    return;
  }
  perfRunner.WriteScript({src:'/node_modules/es5-shim/es5-shim.js', cache:true});
  perfRunner.WriteScript({src:'/node_modules/es5-shim/es5-sham.js', cache:true});
};

perfRunner.BenchmarkResults = function(props) {
  return perfRunner.roundNumberWithPrecision(props.stats.mean * 1000) + 'ms/op';
};

perfRunner.roundNumberWithPrecision = function(number, precision) {
  if (!precision) {
    precision = 1000;
  }
  return Math.round(number * precision) / precision;
};

perfRunner.quickBench = function(benchmarkOptions, onComplete, onBeforeStart) {
  var bench = new Benchmark(benchmarkOptions);
  if (onBeforeStart) {
    onBeforeStart(null, bench);
  }

  bench.on('error', function(event) {
    console.error(event.message);
    console.log(event.target.compiled.toString());
    onComplete(Error(event.error));
  });

  bench.on('start', function() {
    console.log('starting', bench.name);
  });

  bench.on('cycle', function() {
    var benchmark = this,
        size = benchmark.stats.size;

    if (!benchmark.aborted) {
      console.warn(benchmark.name + ' × ' + benchmark.count +
        ' (' + benchmark.stats.sample.length + ' samples)' +
        ' (' + Math.round(1 / benchmark.stats.mean) + ' ops/sec' + ')' +
        ' (' + (benchmark.stats.mean * 1000) + ' ms/op' + ')' +
        ' (±' + benchmark.stats.rme.toFixed(2) + '%)' +
          ' with ' + React.version
      );
    }
  });

  bench.on('complete', function() {
    var results = {
      platform: Benchmark.platform.description,
      react: React.version,
      name: bench.name
      // times: bench.times,
      // stats: bench.stats
    };

    results['s/op'] = bench.stats.mean;
    results['ms/op'] = results['s/op'] * 1000;
    results['op/s'] = 1 / results['s/op'];
    results['% frame 60'] = results['ms/op'] / (1000 / 60) * 100;

    console.log(results);
    onComplete(null, results);
  });

  bench.run();
};

perfRunner.singleTest = function(benchmarkOptions, onComplete) {
  var bench = Benchmark(exports);
  bench.on('complete', function() {
    var results = {
      platform: Benchmark.platform.description,
      react: React.version,
      name: bench.name,
      stats: bench.stats
    };
    onComplete(results);
  });
  bench.run();
};

perfRunner.ViewObject = function(props) {
  var value = props.value;
  delete props.value;

  if (typeof value !== 'object') {
    return React.DOM.span(props, [JSON.stringify(value), ' ', typeof value]);
  }

  return React.DOM.table(props, Object.keys(value).map(function(key) {
    return React.DOM.tr(null,
      React.DOM.th(null, key),
      React.DOM.td(null, perfRunner.ViewObject({key:key, value:value[key]}))
    );
  }));
};


text:
flask-minitwit-mongodb
====

What is flask-minitwit-mongodb?

A MongoDB powered fork of Flask's Minitwit. (https://github.com/mitsuhiko/flask/tree/master/examples/minitwit)

Prerequisites
====

MongoDB installed on your machine, running and listening on port 27017.

Installation
====

1. Download flask-minitwit-mongodb, then:

        cd flask-minitwit-mongodb/

2. Create a virtualenv and activate it:

        virtualenv env
        source env/bin/activate

3. Install the required packages:

        pip install -r requirements.txt

4. Run the application:

        python minitwit.py

5. Open your favorite browser and go to http://127.0.0.1:5000/


text:
QuickSpecBegin(SDLSetDisplayLayoutSpec)

describe(@"Getter/Setter Tests", ^ {
    it(@"Should set and get correctly", ^ {
        SDLSetDisplayLayout* testRequest = [[SDLSetDisplayLayout alloc] init];

        testRequest.displayLayout = @"wat";

        expect(testRequest.displayLayout).to(equal(@"wat"));
    });

    it(@"Should get correctly when initialized", ^ {
        NSMutableDictionary* dict = [@{NAMES_request:
                                           @{NAMES_parameters:
                                                 @{NAMES_displayLayout:@"wat"},
                                             NAMES_operation_name:NAMES_SetDisplayLayout}} mutableCopy];
        SDLSetDisplayLayout* testRequest = [[SDLSetDisplayLayout alloc] initWithDictionary:dict];

        expect(testRequest.displayLayout).to(equal(@"wat"));
    });

    it(@"Should return nil if not set", ^ {
        SDLSetDisplayLayout* testRequest = [[SDLSetDisplayLayout alloc] init];

        expect(testRequest.displayLayout).to(beNil());
    });
});

QuickSpecEnd


text:
package com.logginghub.logging.utils;

import java.util.Collection;

import com.logginghub.logging.LogEvent;
import com.logginghub.logging.listeners.LogEventListener;
import com.logginghub.utils.Bucket;

/**
 * A convenient helper that listens to new events and drops them into a bucket.
 * It helps bridging between asynchronous and synchronous models.
 *
 * @author admin
 *
 */
public class LogEventBucket extends Bucket<LogEvent> implements LogEventListener {
    public LogEventBucket() {
        super();
    }

    public LogEventBucket(String name) {
        super(name);
    }

    public void onNewLogEvent(LogEvent event) {
        add(event);
    }

    public void addAll(Collection<LogEvent> logEvents) {
        addAll(logEvents);
    }
}


text:
> `docker-compose` interface for Grunt

## Getting Started
This plugin requires:

	- grunt: "^1.0.1"
	- grunt-shell

**Important**: `grunt-shell` is a `peerDependency`. as NPM v3+ deprecates `peerDependencies`, you need to explicitly specify `grunt-shell` in your project's `devDependencies`:

`npm install grunt-shell --save-dev`

If you haven't used [Grunt](http://gruntjs.com/) before, be sure to check out the [Getting Started](http://gruntjs.com/getting-started) guide, as it explains how to create a [Gruntfile](http://gruntjs.com/sample-gruntfile) as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin and its dependencies with this command:

```bash
npm install grunt grunt-docker-compose grunt-shell grunt-concurrent --save-dev
```

Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:

```js
grunt.loadNpmTasks('grunt-docker-compose');
```

### Prerequisite: Docker
It is assumed you already have your Docker toolchain installed and working:

 - `docker-compose: >1.7.1`,
 - `docker: >1.11.1`

You should have at least a `docker-compose.yml` file in the working directory.

If you are not familiar with Docker, please see `http://docker.io` to get started.

### Tasks setup
Add this to your Gruntfile.js to register all of the tasks as aliases to your `grunt` command:

```js
// register all dockerCompose targets
['up','down','stop','restart','logs','build','pull','exec','config'].forEach(function (target) {
	grunt.registerTask(target, function () {
		var args = '';
		if (this.args.length > 0) {
			args += ':' + this.args.join(':')
		}
		grunt.task.run('dockerCompose:' + target + args);
	});
})
```

Now you can:

- `grunt up` will execute `docker-compose up`
- `grunt down` will execute `docker-compose down`
- etc...

## The "dockerCompose" task

### Overview
In your project's Gruntfile, add a section named `dockerCompose` to the data object passed into `grunt.initConfig()`.

##### Example

```js
grunt.initConfig({
	// ....... stuff .......
	dockerCompose: {
   		options: {
   			mappedComposeFile: 'docker-compose-mapped.yml',
   			dockerRegistryNamespace: 'my-web-app'
   		}
	}
});
```

### Options

To use the `tag`, `dockerRegistry`, and `dockerRegistryNamespace` options, you must utilize environment variable interpolation in your `docker-compose.yml`:

```yaml
version: '2'
services:
  redis:
    image: redis

  my-web-app:
    build: .
    image: ${DOCKER_REGISTRY}/${DOCKER_REGISTRY_NAMESPACE}/my-web-app:${TAG}
    ports:
      - 80:80
.....
```

##### Order of precedence (higher options override lower ones)

0. sane defaults set by the plugin
0. Gruntfile
0. environment variables
0. command line arguments

E.g.:

- `grunt up:foo` will set the `foo` tag instead of default `latest`,
- `TAG=foobar grunt up` will set the `foobar` tag instead of default `latest`,
- `TAG=baz grunt up:foo` will set the `foo` tag instead of default `latest`. Note that `TAG` is overridden, being lower precedence.

#### options.dockerRegistry

Docker Registry. Defaults to an empty string, which corresponds to DockerHub. If set, this option will set a `DOCKER_REGISTRY` environment variable before running each command. Use it by interpolation in your `docker-compose.yml` file, e.g.:

```yaml
myapp:
	image: ${DOCKER_REGISTRY}/myNamespace/myapp:some-tag
```

If you aren't using it this way in your `docker-compose` files, setting this option has no effect.

#### options.dockerRegistryNamespace

Docker Registry Namespace. If using this option, you should specify your DockerHub username or organization here. Defaults to an empty string.

Used in the same way as `dockerRegistry`:

```yaml
myapp:
	image: ${DOCKER_REGISTRY}/${DOCKER_REGISTRY_NAMESPACE}/myapp:some-tag
```

#### options.tag

Image tag. Defaults to 'latest'. Use by interpolation in your `docker-compose` files.

```yaml
myapp:
	image: ${DOCKER_REGISTRY}/${DOCKER_REGISTRY_NAMESPACE}/myapp:${TAG}
```

#### options.mainService

The name of your "main" service in the docker-compose file. This is the service whose logs will be tailed by default (and piped through `bunyan`) when doing `grunt logs`

#### options.logTail

How many lines of log to tail initially when starting to tail the logs. Defaults to 10.

#### options.mappedComposeFile

An optional `docker-compose` YAML file that extends the default, and allows for mounting host directories into the container for development. Defaults to `docker-compose.yml` (functionally identical to not using any extra `docker-compose` files).

You would use this option if your `docker-compose.yml` doesn't mount any volumes into your container by default, and you had another file like `docker-compose-volumes.yml` extending it and specifying mounted volumes, e.g.:

`docker-compose.yml:`
```yaml
myapp:
	build: .
	ports: 80:80
	...
```

`docker-compose-mapped-volumes.yml`:
```yaml
myapp:
	extends:
		file: docker-compose.yml
		service: myapp
	volumes:
		- ./src:/usr/local/src/myapp
```

#### options.debugComposeFile

Another optional `docker-compose` YAML file that extends the default and uses a different Dockerfile or other options for debug use (or whatever other purpose you may have). Same idea as above.

#### options.composeFile (NOT YET IMPLEMENTED)

Name of the `docker-compose` file to use. Defaults to `docker-compose.yml`.

### Usage Examples

```
grunt dockerCompose:up
grunt dockerCompose:up:v1.0-tag
grunt dockerCompose:up:v1.0-tag --baked
grunt dockerCompose:up --debug

grunt dockerCompose:down

grunt dockerCompose:restart
grunt dockerCompose:restart:my-app

grunt dockerCompose:logs
grunt dockerCompose:logs:my-app
grunt dockerCompose:logs --raw

grunt dockerCompose:build
grunt dockerCompose:build:my-app
grunt dockerCompose:build:my-app:v1.0-tag
grunt dockerCompose:build:my-app:v1.0-tag --no-cache
grunt dockerCompose:build:my-app:v1.0-tag --debug

grunt dockerCompose:pull
grunt dockerCompose:pull:my-app
grunt dockerCompose:pull:my-app:v1.0-tag

grunt dockerCompose:exec
grunt dockerCompose:exec:some-service
grunt dockerCompose:exec:some-service:some-executable
grunt dockerCompose:exec:redis:redis-cli

grunt dockerCompose:config
```

## Contributing
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com/).

## Release History
06/15/2016 0.1.0 Initial release


text:
#include "mcl.h"

#define MCL_MAX_STRING_LENGTH 1024
#define MCL_MAX_SOURCE_SIZE (0x100000)

#include "mcl_device_info.h"

#include <stdarg.h>
#include <sys/time.h>
#include <time.h>

static unsigned int mclLogLevel = 0;

void logStream(FILE* os, const char* fmt, ...)
{
  char buffer[30];
  struct timeval tv;
  time_t curtime;
  gettimeofday(&tv, NULL);
  curtime=tv.tv_sec;
  strftime(buffer,30,"%Y-%m-%d %T.",localtime(&curtime));
  fprintf(os, "MCL %s%d - ", buffer, (int)tv.tv_usec);
  va_list args;
  va_start(args,fmt);
  vfprintf(os,fmt,args);
  va_end(args);
  fprintf(os, "\n");
}

void logOclCall(const char* fmt, ...)
{
  if (mclLogLevel > 0) {
    va_list args;
    va_start(args,fmt);
    logStream(stdout,fmt,args);
    va_end(args);
  }
}

cl_platform_id mclGetPlatformID()
{
  /* Get the platform information */
  cl_uint num_platforms;
  clGetPlatformIDs(0, NULL, &num_platforms);             // get number of platforms
  cl_platform_id* platforms = calloc(sizeof(cl_platform_id), num_platforms);
  clGetPlatformIDs(num_platforms, platforms, NULL);     // populate platform table
  if (mclLogLevel > 1) {
    logStream(stdout,"System has %d platform(s):", num_platforms);
    for(cl_uint i = 0; i < num_platforms;i++) {
      char buf[MCL_MAX_STRING_LENGTH];
      clGetPlatformInfo(platforms[i], CL_PLATFORM_NAME, MCL_MAX_STRING_LENGTH, buf, NULL);
      logStream(stdout,"  Platform: %s", buf);
    }
  }
  if (num_platforms == 0) {
    fprintf(stderr, "MCL - Exiting: No OpenCL Platform available\n");
    exit(1);
  }
  return platforms[0];
}

cl_device_id mclGetGpuDeviceID()
{
  cl_platform_id platform_id = mclGetPlatformID();

  // Info about devices
  cl_uint num_devices;
  clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, 0, NULL, &num_devices);
  cl_device_id* devices = calloc(sizeof(cl_device_id), num_devices);
  clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, num_devices, devices, NULL);

  if (mclLogLevel > 1) {
    logStream(stdout, "System has %d GPU device(s):", num_devices);
    char buf1[MCL_MAX_STRING_LENGTH];
    char buf2[MCL_MAX_STRING_LENGTH];
    for(cl_uint i = 0; i < num_devices;i++) {
      clGetDeviceInfo(devices[i], CL_DEVICE_NAME, MCL_MAX_STRING_LENGTH, buf1, NULL);
      clGetDeviceInfo(devices[i], CL_DEVICE_VERSION, MCL_MAX_STRING_LENGTH, buf2, NULL);
      logStream(stdout, "   Device %d: %s, which supports %s", i, buf1, buf2);
    }
  }

  if (num_devices < 1) {
    fprintf(stderr, "MCL - Exiting: No GPU devices available\n");
    exit(1);
  }

  // Selecting the device
  cl_uint num_device = num_devices - 1;
  cl_device_id device_id = devices[num_device];
  if (mclLogLevel > 0) {
    char buf[MCL_MAX_STRING_LENGTH];
    clGetDeviceInfo(device_id, CL_DEVICE_NAME, MCL_MAX_STRING_LENGTH, buf, NULL);
    logStream(stdout,"Selected device %d: %s", num_device, buf);
    if (mclLogLevel > 2) {
      mclPrintDeviceInfo(device_id);
    }
  }
  return device_id;
}

cl_context mclCreateContext(cl_device_id* device_id)
{
  cl_int ret;
  logOclCall("clCreateContext");
  cl_context context = clCreateContext( NULL, 1, device_id, NULL, NULL, &ret);
  if (ret != CL_SUCCESS) {
    fprintf(stderr, "MCL - Exiting: Failed to create context\n");
    exit(1);
  }
  return context;
}

cl_command_queue mclCreateCommandQueue(cl_context context, cl_device_id device_id)
{
  cl_int ret;
  logOclCall("clCreateCommmandQueue");
  cl_command_queue command_queue = clCreateCommandQueue(context, device_id, 0, &ret);
  if (ret != CL_SUCCESS) {
    fprintf(stderr, "MCL - Exiting: Failed to create command queue\n");
    exit(1);
  }
  return command_queue;
}

mclContext mclInitialize(unsigned int log_level) {
  mclLogLevel = log_level;
  mclContext context;
  context.device_id = mclGetGpuDeviceID();
  context.context = mclCreateContext(&context.device_id);
  context.command_queue = mclCreateCommandQueue(context.context,context.device_id);
  return context;
}

cl_program mclBuildProgram(mclContext ctx, const char* filename)
{
  cl_device_id device_id = ctx.device_id;
  cl_context context = ctx.context;
  // Read file
  FILE *fp = fopen(filename, "r");
  if (!fp) {
    fprintf(stderr, "MCL - Exiting: Failed to load kernel.\n");
    exit(1);
  }
  char *source_str = (char *)malloc(MCL_MAX_STRING_LENGTH);
  size_t source_size = fread( source_str, 1, MCL_MAX_STRING_LENGTH, fp );
  fclose( fp );

  cl_int ret;
  logOclCall("clCreateProgramWithSource");
  cl_program program = clCreateProgramWithSource(context, 1, (const char **)&source_str, (const size_t *)&source_size, &ret);
  if (ret != CL_SUCCESS) {
    fprintf(stderr, "MCL - Exiting: Failed to create program.\n");
    exit(1);
  }
  logOclCall("clBuildProgram");
  ret = clBuildProgram(program, 1, &device_id, NULL, NULL, NULL);
  if (ret != CL_SUCCESS) {
    fprintf(stderr, "MCL - Exiting: Failed to build program.\n");
    char *build_log;
    size_t ret_val_size;
    clGetProgramBuildInfo(program, device_id, CL_PROGRAM_BUILD_LOG, 0, NULL, &ret_val_size);
    build_log = (char*) malloc(sizeof(char)*(ret_val_size+1));
    clGetProgramBuildInfo(program, device_id, CL_PROGRAM_BUILD_LOG, ret_val_size, build_log, NULL);
    // terminate with \0; the reference says nothing about whether the string is 0 terminated
    build_log[ret_val_size] = '\0';
    fprintf(stderr, "MCL - Error in clBuildProgram, Line %u in file %s\n", __LINE__, __FILE__);
    fprintf(stderr, "MCL - Error in kernel file %s:\n%s\n", filename, build_log);
    free (build_log);
    exit(1);
  }
  free(source_str);
  return program;
}

inline size_t mclSizeOfType(mclType t) {
  size_t sz;
  if (t == MCL_FLOAT) {
    sz = sizeof(float);
  } else if (t == MCL_INT) {
    sz = sizeof(int);
  } else if (t == MCL_DOUBLE) {
    sz = sizeof(double);
  } else {
    fprintf(stderr, "MCL - Exiting: Unknown type of data.\n");
    exit(1);
  }
  return sz;
}

mclDeviceData mclDataToDevice(mclContext ctx, mclBufType buftype, mclType type, void* data, cl_int n)
{
  // Copy argument to GPU
  cl_int ret;
  size_t sz = n * mclSizeOfType(type);
  logOclCall("clCreateBuffer");
  cl_mem data_gpu = clCreateBuffer(ctx.context, buftype, sz, NULL, &ret);
  if (ret != CL_SUCCESS) {
    fprintf(stderr, "MCL - Error creating buffer on device.\n");
    exit(1);
  }
  logOclCall("clEnqueueWriteBuffer");
  ret = clEnqueueWriteBuffer(ctx.command_queue, data_gpu, CL_TRUE, 0, sz, data, 0, NULL, NULL);
  if (ret != CL_SUCCESS) {
    fprintf(stderr, "MCL - Error copying data to device.\n");
    exit(1);
  }
  mclDeviceData res;
  res.buftype = buftype;
  res.type = type;
  res.data = data_gpu;
  res.n = n;
  return res;
}

void mclReleaseDeviceData(mclDeviceData* devData)
{
  cl_int ret;
  logOclCall("clReleaseMemObject");
  ret = clReleaseMemObject(devData->data);
  devData->data = NULL;
  if (ret != CL_SUCCESS) {
    fprintf(stderr, "MCL - Failed to release device data.\n");
    exit(1);
  }
}

//void mclDataFromDevice(mclContext ctx, mclDeviceData devdata, void* data);

void mclCallKernel(mclContext ctx, cl_program program, char* kernelName, cl_int workSz, mclDeviceData* args, ...)
{
  // Create the kernel
  cl_int ret;
  logOclCall("clCreateKernel");
  cl_kernel kernel = clCreateKernel(program, kernelName, &ret);
  if (ret != CL_SUCCESS) {
    fprintf(stderr, "MCL - Error creating kernel '%s' from program.\n", kernelName);
    exit(1);
  }
  // Attach arguments
  va_list ap;
  va_start(ap, args);
  mclDeviceData* devData = args;
  for (int i = 0; devData != NULL; i++)
    {
      logOclCall("clSetKernelArg");
      ret = clSetKernelArg(kernel, i, sizeof(cl_mem), (void*)&((*devData).data));
      if (ret != CL_SUCCESS) {
	fprintf(stderr, "MCL - Error setting argument %d to kernel %s.\n", i, kernelName);
	exit(1);
      }
      devData = va_arg(ap,mclDeviceData*);
    }
  va_end(ap);
  // Do the call
  size_t global_work_size[3] = {workSz};
  logOclCall("clEnqueueNDRangeKernel");
  ret = clEnqueueNDRangeKernel(ctx.command_queue, kernel, 1, NULL, global_work_size, NULL, 0, NULL, NULL);
  if (ret != CL_SUCCESS) {
    fprintf(stderr, "MCL - Error calling kernel %s.\n", kernelName);
    exit(1);
  }
  ret = clReleaseKernel(kernel);
  if (ret != CL_SUCCESS) {
    fprintf(stderr, "MCL - Error releasing kernel %s.\n", kernelName);
    exit(1);
  }
}

void mclReleaseContext(mclContext* ctx)
{
  cl_int ret;
  ret = clFlush(ctx->command_queue);
  if (ret != CL_SUCCESS) {
    fprintf(stderr, "MCL - Failing to flush command queue.\n");
    exit(1);
  }
  ret = clFinish(ctx->command_queue);
  if (ret != CL_SUCCESS) {
    fprintf(stderr, "MCL - Failing to finish command queue.\n");
    exit(1);
  }
  ret = clReleaseCommandQueue(ctx->command_queue);
  if (ret != CL_SUCCESS) {
    fprintf(stderr, "MCL - Failing releasing command queue.\n");
    exit(1);
  }
  ctx->command_queue = NULL;

  ret = clReleaseContext(ctx->context);
  if (ret != CL_SUCCESS) {
    fprintf(stderr, "MCL - Failing releasing context.\n");
    exit(1);
  }
  ctx->context = NULL;
  ctx->device_id = NULL;
}


text:
import fnmatch
import optparse
import os
import sys

import scons_to_gn

TOOLS_DIR = os.path.dirname(__file__)

"""Convert from Scons to GN.

Takes a set of SCONS input files and generates a output file per input, as
well as a global alias file.
"""

def RunTests():
  test_path = os.path.abspath(os.path.join(TOOLS_DIR, 'scons_to_gn'))
  fail_count = 0
  for filename in os.listdir(test_path):
    if fnmatch.fnmatch(filename, '*_test.py'):
      print 'Testing: ' + filename
      filepath = os.path.join(test_path, filename)
      val = os.system(sys.executable + ' ' + filepath)
      if val:
        print 'FAILED: ' + filename
        fail_count += 1
      print '\n'

def main(argv):
  usage = 'usage: %prog [options] <scons files> ...'
  parser = optparse.OptionParser(usage)
  parser.add_option('-v', '--verbose', dest='verbose',
      action='store_true', default=False)
  parser.add_option('-t', '--test', dest='test',
      action='store_true', default=False)
  parser.add_option('-w', '--write', dest='write',
      action='store_true', default=False)

  options, args = parser.parse_args(argv)
  if options.test:
    RunTests()
    return 0

  if len(args) == 0:
    parser.error('Expecting list of sources.')

  trusted = scons_to_gn.TrustedConditions()
  untrusted = scons_to_gn.UntrustedConditions()

  for name in args:
    if name.endswith('nacl.scons'):
      tracker = scons_to_gn.ObjectTracker(name, untrusted)
    elif name.endswith('build.scons'):
      tracker = scons_to_gn.ObjectTracker(name, trusted)
    else:
      parser.error('Expecting build.scons and nacl.scons sources.')
    if options.write:
      outname = os.path.join(os.path.dirname(name), 'BUILD.gn')
      with open(outname, 'wt') as outfile:
        tracker.Dump(outfile)
    else:
      tracker.Dump(sys.stdout)
  return 0

if __name__ == '__main__':
  retval = main(sys.argv[1:])
  sys.exit(retval)


text:
/* Generated from SymbolMapServiceNative
 * Do not edit, as this WILL be overwritten
 */
@protocol SymbolMapServiceNative <NSObject>

- (void) setSymbolMapDetails: (NSString*) moduleName : (NSString*) strongName;

@end


text:
ALTER TABLE sepal_user.sepal_user
  ADD CONSTRAINT username UNIQUE(username);


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

    <string name="app_name">TimoPlayer</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="title_file">本地视频</string>
    <string name="title_online">网络视频</string>

</resources>


text:
package org.experiment.query;

import org.apache.lucene.benchmark.quality.QualityQuery;
import org.apache.lucene.benchmark.quality.QualityQueryParser;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.queryparser.classic.QueryParserBase;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
import org.experiment.analyzer.TRECAnalyzer;

/**
 * Created by sonic on 19/10/16.
 *
 * @Author Fanghong
 */
public class TRECQQParser implements QualityQueryParser {

    private String qqNames[];
    private String indexField;
    ThreadLocal<QueryParser> queryParser = new ThreadLocal<QueryParser>();

    /**
     * Constructor of a simple qq HTMLParser.
     *
     * @param qqNames    name-value pairs of quality query to use for creating the query
     * @param indexField corresponding index field
     */
    public TRECQQParser(String qqNames[], String indexField) {
        this.qqNames = qqNames;
        this.indexField = indexField;
    }

    /**
     * Constructor of a simple qq HTMLParser.
     *
     * @param qqName     name-value pair of quality query to use for creating the query
     * @param indexField corresponding index field
     */
    public TRECQQParser(String qqName, String indexField) {
        this(new String[]{qqName}, indexField);
    }

    /* (non-Javadoc)
     * @see org.apache.lucene.benchmark.quality.QualityQueryParser#parse(org.apache.lucene.benchmark.quality.QualityQuery)
     */
    @Override
    public Query parse(QualityQuery qq) throws ParseException {
        QueryParser qp = queryParser.get();
        if (qp==null) {
            qp = new QueryParser(indexField, new TRECAnalyzer());
            queryParser.set(qp);
        }

        BooleanQuery.Builder bq = new BooleanQuery.Builder();

        for (String qqName : qqNames)
            bq.add(qp.parse(QueryParserBase.escape(qq.getValue(qqName))), BooleanClause.Occur.SHOULD);

        return bq.build();
    }
}


text:
//  Copyright Paul A. Bristow 2007.
//  Use, modification and distribution are subject to the
//  Boost Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_STATS_rayleigh_HPP
#define BOOST_STATS_rayleigh_HPP

#include <boost/math/distributions/fwd.hpp>
#include <boost/math/constants/constants.hpp>
#include <boost/math/special_functions/log1p.hpp>
#include <boost/math/special_functions/expm1.hpp>
#include <boost/math/distributions/complement.hpp>
#include <boost/math/distributions/detail/common_error_handling.hpp>
#include <boost/config/no_tr1/cmath.hpp>

#ifdef BOOST_MSVC
# pragma warning(push)
# pragma warning(disable: 4702) // unreachable code (return after domain_error throw).
#endif

#include <utility>

namespace boost{ namespace math{

namespace detail
{ // Error checks:
  template <class RealType, class Policy>
  inline bool verify_sigma(const char* function, RealType sigma, RealType* presult, const Policy& pol)
  {
     if((sigma <= 0) || (!(boost::math::isfinite)(sigma)))
     {
        *presult = policies::raise_domain_error<RealType>(
           function,
           "The scale parameter \"sigma\" must be > 0 and finite, but was: %1%.", sigma, pol);
        return false;
     }
     return true;
  } // bool verify_sigma

  template <class RealType, class Policy>
  inline bool verify_rayleigh_x(const char* function, RealType x, RealType* presult, const Policy& pol)
  {
     if((x < 0) || (boost::math::isnan)(x))
     {
        *presult = policies::raise_domain_error<RealType>(
           function,
           "The random variable must be >= 0, but was: %1%.", x, pol);
        return false;
     }
     return true;
  } // bool verify_rayleigh_x
} // namespace detail

template <class RealType = double, class Policy = policies::policy<> >
class rayleigh_distribution
{
public:
   typedef RealType value_type;
   typedef Policy policy_type;

   rayleigh_distribution(RealType l_sigma = 1)
      : m_sigma(l_sigma)
   {
      RealType err;
      detail::verify_sigma("boost::math::rayleigh_distribution<%1%>::rayleigh_distribution", l_sigma, &err, Policy());
   } // rayleigh_distribution

   RealType sigma()const
   { // Accessor.
     return m_sigma;
   }

private:
   RealType m_sigma;
}; // class rayleigh_distribution

typedef rayleigh_distribution<double> rayleigh;

template <class RealType, class Policy>
inline const std::pair<RealType, RealType> range(const rayleigh_distribution<RealType, Policy>& /*dist*/)
{ // Range of permissible values for random variable x.
   using boost::math::tools::max_value;
   return std::pair<RealType, RealType>(static_cast<RealType>(0), std::numeric_limits<RealType>::has_infinity ? std::numeric_limits<RealType>::infinity() : max_value<RealType>());
}

template <class RealType, class Policy>
inline const std::pair<RealType, RealType> support(const rayleigh_distribution<RealType, Policy>& /*dist*/)
{ // Range of supported values for random variable x.
   // This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.
   using boost::math::tools::max_value;
   return std::pair<RealType, RealType>(static_cast<RealType>(0),  max_value<RealType>());
}

template <class RealType, class Policy>
inline RealType pdf(const rayleigh_distribution<RealType, Policy>& dist, const RealType& x)
{
   BOOST_MATH_STD_USING // for ADL of std function exp.

   RealType sigma = dist.sigma();
   RealType result = 0;
   static const char* function = "boost::math::pdf(const rayleigh_distribution<%1%>&, %1%)";
   if(false == detail::verify_sigma(function, sigma, &result, Policy()))
   {
      return result;
   }
   if(false == detail::verify_rayleigh_x(function, x, &result, Policy()))
   {
      return result;
   }
   if((boost::math::isinf)(x))
   {
      return 0;
   }
   RealType sigmasqr = sigma * sigma;
   result = x * (exp(-(x * x) / ( 2 * sigmasqr))) / sigmasqr;
   return result;
} // pdf

template <class RealType, class Policy>
inline RealType cdf(const rayleigh_distribution<RealType, Policy>& dist, const RealType& x)
{
   BOOST_MATH_STD_USING // for ADL of std functions

   RealType result = 0;
   RealType sigma = dist.sigma();
   static const char* function = "boost::math::cdf(const rayleigh_distribution<%1%>&, %1%)";
   if(false == detail::verify_sigma(function, sigma, &result, Policy()))
   {
      return result;
   }
   if(false == detail::verify_rayleigh_x(function, x, &result, Policy()))
   {
      return result;
   }
   result = -boost::math::expm1(-x * x / ( 2 * sigma * sigma), Policy());
   return result;
} // cdf

template <class RealType, class Policy>
inline RealType quantile(const rayleigh_distribution<RealType, Policy>& dist, const RealType& p)
{
   BOOST_MATH_STD_USING // for ADL of std functions

   RealType result = 0;
   RealType sigma = dist.sigma();
   static const char* function = "boost::math::quantile(const rayleigh_distribution<%1%>&, %1%)";
   if(false == detail::verify_sigma(function, sigma, &result, Policy()))
      return result;
   if(false == detail::check_probability(function, p, &result, Policy()))
      return result;

   if(p == 0)
   {
      return 0;
   }
   if(p == 1)
   {
     return policies::raise_overflow_error<RealType>(function, 0, Policy());
   }
   result = sqrt(-2 * sigma * sigma * boost::math::log1p(-p, Policy()));
   return result;
} // quantile

template <class RealType, class Policy>
inline RealType cdf(const complemented2_type<rayleigh_distribution<RealType, Policy>, RealType>& c)
{
   BOOST_MATH_STD_USING // for ADL of std functions

   RealType result = 0;
   RealType sigma = c.dist.sigma();
   static const char* function = "boost::math::cdf(const rayleigh_distribution<%1%>&, %1%)";
   if(false == detail::verify_sigma(function, sigma, &result, Policy()))
   {
      return result;
   }
   RealType x = c.param;
   if(false == detail::verify_rayleigh_x(function, x, &result, Policy()))
   {
      return result;
   }
   RealType ea = x * x / (2 * sigma * sigma);
   // Fix for VC11/12 x64 bug in exp(float):
   if (ea >= tools::max_value<RealType>())
      return 0;
   result =  exp(-ea);
   return result;
} // cdf complement

template <class RealType, class Policy>
inline RealType quantile(const complemented2_type<rayleigh_distribution<RealType, Policy>, RealType>& c)
{
   BOOST_MATH_STD_USING // for ADL of std functions, log & sqrt.

   RealType result = 0;
   RealType sigma = c.dist.sigma();
   static const char* function = "boost::math::quantile(const rayleigh_distribution<%1%>&, %1%)";
   if(false == detail::verify_sigma(function, sigma, &result, Policy()))
   {
      return result;
   }
   RealType q = c.param;
   if(false == detail::check_probability(function, q, &result, Policy()))
   {
      return result;
   }
   if(q == 1)
   {
      return 0;
   }
   if(q == 0)
   {
     return policies::raise_overflow_error<RealType>(function, 0, Policy());
   }
   result = sqrt(-2 * sigma * sigma * log(q));
   return result;
} // quantile complement

template <class RealType, class Policy>
inline RealType mean(const rayleigh_distribution<RealType, Policy>& dist)
{
   RealType result = 0;
   RealType sigma = dist.sigma();
   static const char* function = "boost::math::mean(const rayleigh_distribution<%1%>&, %1%)";
   if(false == detail::verify_sigma(function, sigma, &result, Policy()))
   {
      return result;
   }
   using boost::math::constants::root_half_pi;
   return sigma * root_half_pi<RealType>();
} // mean

template <class RealType, class Policy>
inline RealType variance(const rayleigh_distribution<RealType, Policy>& dist)
{
   RealType result = 0;
   RealType sigma = dist.sigma();
   static const char* function = "boost::math::variance(const rayleigh_distribution<%1%>&, %1%)";
   if(false == detail::verify_sigma(function, sigma, &result, Policy()))
   {
      return result;
   }
   using boost::math::constants::four_minus_pi;
   return four_minus_pi<RealType>() * sigma * sigma / 2;
} // variance

template <class RealType, class Policy>
inline RealType mode(const rayleigh_distribution<RealType, Policy>& dist)
{
   return dist.sigma();
}

template <class RealType, class Policy>
inline RealType median(const rayleigh_distribution<RealType, Policy>& dist)
{
   using boost::math::constants::root_ln_four;
   return root_ln_four<RealType>() * dist.sigma();
}

template <class RealType, class Policy>
inline RealType skewness(const rayleigh_distribution<RealType, Policy>& /*dist*/)
{
  // using namespace boost::math::constants;
  return static_cast<RealType>(0.63111065781893713819189935154422777984404221106391L);
  // Computed using NTL at 150 bit, about 50 decimal digits.
  // return 2 * root_pi<RealType>() * pi_minus_three<RealType>() / pow23_four_minus_pi<RealType>();
}

template <class RealType, class Policy>
inline RealType kurtosis(const rayleigh_distribution<RealType, Policy>& /*dist*/)
{
  // using namespace boost::math::constants;
  return static_cast<RealType>(3.2450893006876380628486604106197544154170667057995L);
  // Computed using NTL at 150 bit, about 50 decimal digits.
  // return 3 - (6 * pi<RealType>() * pi<RealType>() - 24 * pi<RealType>() + 16) /
  // (four_minus_pi<RealType>() * four_minus_pi<RealType>());
}

template <class RealType, class Policy>
inline RealType kurtosis_excess(const rayleigh_distribution<RealType, Policy>& /*dist*/)
{
  //using namespace boost::math::constants;
  // Computed using NTL at 150 bit, about 50 decimal digits.
  return static_cast<RealType>(0.2450893006876380628486604106197544154170667057995L);
  // return -(6 * pi<RealType>() * pi<RealType>() - 24 * pi<RealType>() + 16) /
  //   (four_minus_pi<RealType>() * four_minus_pi<RealType>());
} // kurtosis

} // namespace math
} // namespace boost

#ifdef BOOST_MSVC
# pragma warning(pop)
#endif

// This include must be at the end, *after* the accessors
// for this distribution have been defined, in order to
// keep compilers that support two-phase lookup happy.
#include <boost/math/distributions/detail/derived_accessors.hpp>

#endif // BOOST_STATS_rayleigh_HPP


text:
require 'spec_helper'
require 'garner/mixins/mongoid'

describe Garner::Mixins::Mongoid::Identity do
  before(:each) do
    @mock_strategy = double('strategy')
    allow(@mock_strategy).to receive(:apply)
    @mock_mongoid_strategy = double('mongoid_strategy')
    allow(@mock_mongoid_strategy).to receive(:apply)
  end

  describe 'from_class_and_handle' do
    before(:each) do
      Garner.configure do |config|
        config.mongoid_identity_fields = [:_id, :_slugs]
      end
    end

    subject { Garner::Mixins::Mongoid::Identity }

    it 'raises an exception if called on a non-Mongoid class' do
      expect do
        subject.from_class_and_handle(Class.new, 'id')
      end.to raise_error

      expect do
        subject.from_class_and_handle(Monger.new, 'id')
      end.to raise_error
    end

    it 'raises an exception if called on an embedded document' do
      expect do
        subject.from_class_and_handle(Fish, 'id')
      end.to raise_error
    end

    it 'sets klass, handle and a conditions hash' do
      identity = subject.from_class_and_handle(Monger, 'id')
      expect(identity.klass).to eq Monger
      expect(identity.handle).to eq 'id'
      expect(identity.conditions['$or']).to eq [
        { _id: 'id' },
        { _slugs: 'id' }
      ]
    end

    context 'on a Mongoid subclass' do
      it 'sets klass to parent and includes the _type field' do
        identity = subject.from_class_and_handle(Cheese, 'id')
        expect(identity.klass).to eq Cheese
        expect(identity.conditions[:_type]).to eq('$in' => ['Cheese'])
        expect(identity.conditions['$or']).to eq [
          { _id: 'id' },
          { _slugs: 'id' }
        ]
      end
    end
  end

  describe 'to_s' do
    subject { Monger.identify('m1').to_s }

    it 'stringizes the binding and includes klass and handle' do
      expect(subject).to be_a(String)
      expect(subject).to match(/Monger/)
      expect(subject).to match(/m1/)
    end

    it 'should not change across identical instances' do
      expect(subject).to eq Monger.identify('m1').to_s
    end

    it 'should be different across different instances' do
      expect(subject).not_to eq(Monger.identify('m2').to_s)
    end
  end

  context 'with default configuration and real documents' do
    before(:each) do
      Garner.configure do |config|
        config.mongoid_identity_fields = [:_id, :_slugs]
      end

      @monger = Monger.create(name: 'M1')
      @cheese = Cheese.create(name: 'Havarti')
      @cheese.reload
    end

    describe 'proxy_binding' do
      it 'returns nil for nonexistent bindings' do
        expect(Monger.identify('m2').proxy_binding).to be_nil
      end

      it 'returns nil for nil bindings' do
        @monger.unset(:_slugs)
        expect(Monger.identify(nil).proxy_binding).to be_nil
      end

      it 'limits the query' do
        expect_any_instance_of(Mongoid::Slug::Criteria).to receive(:limit).with(1).and_return([@monger])
        Monger.identify('m1').proxy_binding
      end

      describe 'cache_key' do
        it "generates a cache key equal to Mongoid::Document's" do
          expect(Monger.identify('m1').proxy_binding.cache_key).to eq @monger.cache_key

          # Also test for Mongoid subclasses
          expect(Cheese.identify('havarti').proxy_binding.cache_key).to eq @cheese.cache_key
          expect(Food.identify(@cheese.id).proxy_binding.cache_key).to eq @cheese.cache_key
        end

        context 'without Mongoid::Timestamps' do
          before(:each) do
            @monger.unset(:updated_at)
            @cheese.unset(:updated_at)
          end

          it "generates a cache key equal to Mongoid::Document's" do
            expect(Monger.identify('m1').proxy_binding.cache_key).to eq @monger.cache_key

            # Also test for Mongoid subclasses
            expect(Cheese.identify('havarti').proxy_binding.cache_key).to eq @cheese.cache_key
            expect(Food.identify(@cheese.id).proxy_binding.cache_key).to eq @cheese.cache_key
          end
        end
      end

      describe 'updated_at' do
        it "returns :updated_at equal to Mongoid::Document's" do
          expect(Monger.identify('m1').proxy_binding.updated_at).to eq Monger.find('m1').updated_at

          # Also test for Mongoid subclasses
          expect(Cheese.identify('havarti').proxy_binding.updated_at).to eq @cheese.updated_at
          expect(Food.identify(@cheese.id).proxy_binding.updated_at).to eq @cheese.updated_at
        end
      end
    end
  end
end


text:
package org.intellij.lang.xpath.completion;

import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.Iconable;

import org.intellij.lang.xpath.context.functions.Function;

import javax.swing.*;

public class FunctionLookup extends AbstractLookup implements Iconable {
    private final String type;
    private final boolean hasParameters;

    FunctionLookup(String name, String _presentation, String type) {
        this(name, _presentation, type, false);
    }

    FunctionLookup(String name, String _presentation, String type, boolean hasParams) {
        super(name, _presentation);
        this.type = type;
        this.hasParameters = hasParams;
    }

    public String getTypeHint() {
        return type == null ? "" : type;
    }

    public boolean isFunction() {
        return true;
    }

    public boolean hasParameters() {
        return hasParameters;
    }

    public boolean isKeyword() {
        return type == null;
    }

    public Icon getIcon(int flags) {
        return IconLoader.getIcon("/icons/function.png");
    }

    public static Lookup newFunctionLookup(String name, Function functionDecl) {
        final CodeInsightSettings codeinsightsettings = CodeInsightSettings.getInstance();
        final String presentation = functionDecl.buildSignature(name);
        final String returnType = functionDecl.returnType.getName();
        final boolean hasParams = functionDecl.parameters.length > 0;
        return new FunctionLookup(name, presentation, returnType, hasParams);
    }
}


text:
package huton

import (
	"errors"
	"net"
	"strconv"

	"github.com/golang/protobuf/proto"
	"github.com/huton-io/huton/pkg/proto"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
)

// ErrUnsupportedMessageType is an error for when an RPC is of an unexpected type.
var ErrUnsupportedMessageType = errors.New("unsupported message type")

type rpcServer struct {
	delegate *grpc.Server
	instance *Instance
}

func (s *rpcServer) Set(ctx context.Context, r *huton_proto.CacheSet) (*huton_proto.CacheSetResp, error) {
	resp := &huton_proto.CacheSetResp{}
	b, err := proto.Marshal(r)
	if err != nil {
		return resp, err
	}
	err = s.instance.apply(cacheOpSet, b)
	return resp, err
}

func (s *rpcServer) Del(ctx context.Context, r *huton_proto.CacheDel) (*huton_proto.CacheDelResp, error) {
	resp := &huton_proto.CacheDelResp{}
	b, err := proto.Marshal(r)
	if err != nil {
		return resp, err
	}
	err = s.instance.apply(cacheOpDel, b)
	return resp, err
}

func (s *rpcServer) setup() error {
	bindHost := s.instance.config.BindHost
	if bindHost == "" {
		bindHost = "127.0.0.1"
	}
	addr := net.JoinHostPort(bindHost, strconv.Itoa(s.instance.config.BindPort+2))
	listener, err := net.Listen("tcp", addr)
	if err != nil {
		return err
	}
	s.delegate = grpc.NewServer()
	huton_proto.RegisterCacheServer(s.delegate, s)
	reflection.Register(s.delegate)
	go s.delegate.Serve(listener)
	return nil
}

func (s *rpcServer) Stop() {
	s.delegate.Stop()
}

func (i *Instance) sendRPC(ctx context.Context, peer *Peer, msg proto.Message) error {
	conn, err := grpc.Dial(peer.RPCAddr.String(), grpc.WithInsecure())
	if err != nil {
		return err
	}
	defer conn.Close()
	client := huton_proto.NewCacheClient(conn)
	switch v := msg.(type) {
	case *huton_proto.CacheSet:
		_, err = client.Set(ctx, v)
	case *huton_proto.CacheDel:
		_, err = client.Del(ctx, v)
	default:
		return ErrUnsupportedMessageType
	}
	return err
}

func (i *Instance) sendRPCToLeader(ctx context.Context, msg proto.Message) error {
	leader := i.raft.Leader()
	i.peersMu.Lock()
	defer i.peersMu.Unlock()
	return i.sendRPC(ctx, i.peers[string(leader)], msg)
}

func newRPCServer(instance *Instance) (*rpcServer, error) {
	server := &rpcServer{
		instance: instance,
	}
	err := server.setup()
	return server, err
}


text:
One page website template with parallax and animations
- First download a sample project from html5 boilerplate
- Download and install bootstrap
- Add the Navigation
-- Replace content with a header>div.container>ul.nav nav-justified>n*li
- Add about section


text:
package main

import (
	"encoding/gob"
	"fmt"
	"log"
	"net/http"
	"os"
	"runtime/debug"
	"strings"
	"time"

	"github.com/1lann/airlift/airlift"
	"github.com/1lann/airlift/fs"

	"github.com/gin-gonic/contrib/renders/multitemplate"
	"github.com/gin-gonic/contrib/secure"
	"github.com/gin-gonic/contrib/sessions"
	"github.com/gin-gonic/gin"
)

var packagePath = os.Getenv("GOPATH") + "/src/github.com/1lann/airlift"
var viewsPath = packagePath + "/views"

var registers []func(r *gin.RouterGroup, t multitemplate.Render)

func main() {
	err := airlift.Connect(dbConnectOpts)
	if err != nil {
		log.Fatal("failed to connect to database: ", err)
	}
	err = fs.Connect(minioAddr, minioAccessKey, minioSecretKey)
	if err != nil {
		log.Fatal("failed to connect to object store: ", err)
	}

	r := gin.Default()
	t := multitemplate.New()

	registerBaseHandlers(r, t)

	store := sessions.NewCookieStore([]byte(sessionSecret))
	store.Options(sessionOpts)
	r.Use(sessions.Sessions("airlift", store))

	rg := r.Group("/")
	rg.Use(authMiddleware)

	t.AddFromFiles("not-found", viewsPath+"/not-found.tmpl",
		viewsPath+"/components/base.tmpl")

	r.NoRoute(func(c *gin.Context) {
		c.HTML(http.StatusNotFound, "not-found", nil)
	})

	for _, registerFunc := range registers {
		registerFunc(rg, t)
	}
	r.HTMLRender = t
	r.Run()
}

func authMiddleware(c *gin.Context) {
	if strings.HasPrefix(c.Request.URL.Path, "/static") ||
		c.Request.URL.Path == "/favicon.ico" {
		return
	}

	session := sessions.Default(c)
	username, ok := session.Get("username").(string)
	if !ok && c.Request.URL.Path == "/" {
		c.Next()
		return
	}

	if !ok {
		session.AddFlash(showMessage{
			Title:   "You aren't logged in",
			Message: "You need to log in first before you can see this content.",
			Type:    "error",
		}, "login")
		session.Save()
		c.Redirect(http.StatusSeeOther, "/")
		c.Abort()
		return
	}

	if c.Request.URL.Path == "/" {
		c.Redirect(http.StatusSeeOther, "/schedule")
		c.Abort()
		return
	}

	user, err := airlift.GetUser(username)
	if err == airlift.ErrNotFound {
		session.AddFlash(showMessage{
			Title:   "Your account has gone missing",
			Message: "Was it deleted? Contact Chuie for help.",
			Type:    "error",
		}, "login")
		session.Delete("username")
		session.Save()
		c.Redirect(http.StatusSeeOther, "/")
		c.Abort()
		return
	} else if err != nil {
		panic(err)
	}

	c.Set("user", user)
}

func registerBaseHandlers(r *gin.Engine, t multitemplate.Render) {
	r.Use(secure.Secure(secureOpts))

	r.Use(func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				if strings.Contains(fmt.Sprintf("%v", err), "write: broken pipe") {
					return
				}

				// Recover from panic
				stackTrace := strings.Replace(string(debug.Stack()),
					os.Getenv("GOPATH")+"/src/", "", -1)
				log.Println("Recovered from panic:", fmt.Sprintf("%v\n", err)+stackTrace)
				c.HTML(http.StatusInternalServerError, "error", gin.H{
					"StackTrace": fmt.Sprintf("%v\n", err) + stackTrace,
				})
			}
		}()

		c.Next()
	})
}

func getGreeting() string {
	hour := time.Now().Hour()
	if hour < 5 {
		return "evening"
	} else if hour < 12 {
		return "morning"
	} else if hour < 18 {
		return "afternoon"
	}

	return "evening"
}

func htmlOK(c *gin.Context, template string, h map[string]interface{}) {
	h["User"] = c.MustGet("user")
	h["Greeting"] = getGreeting()
	c.HTML(http.StatusOK, template, h)
}

func init() {
	gob.Register(showMessage{})

	registers = append(registers, func(r *gin.RouterGroup, t multitemplate.Render) {
		rg := r.Group("/static")
		rg.Use(func(c *gin.Context) {
			c.Header("Cache-Control", "max-age=10000000")
		})
		rg.Static("/", packagePath+"/static")
	})

	registers = append(registers, func(r *gin.RouterGroup, t multitemplate.Render) {
		t.AddFromFiles("error", viewsPath+"/error.tmpl",
			viewsPath+"/components/base.tmpl")
	})
}


text:
define(['../dist/localForage'], function(lf) {
    var key = 'STORE_KEY';
    var value = 'What we save offline';
    var UNKNOWN_KEY = 'unknown_key';

    lf.setItem(key, value, function() {
      console.log('SAVING', value);

      lf.getItem(key, function(readValue) {
        console.log('READING', readValue);
      });
    });

    // Promises code.
    lf.setItem('promise', 'ring', function() {
      lf.getItem('promise').then(function(readValue) {
        console.log('YOU PROMISED!', readValue);
      });
    });

    // Since this key hasn't been set yet, we'll get a null value
    lf.getItem(UNKNOWN_KEY, function(readValue) {
      console.log('FAILED READING', UNKNOWN_KEY, readValue);
    });
});


text:
title: Graphics
blog_url: blog
banner: parakeet1600.jpg
body_classes: header-image fullwidth

sitemap:
    changefreq: monthly
    priority: 1.03

content:
    items: @self.children
    order:
        by: date
        dir: desc
    limit: 5
    pagination: true

feed:
    description: Sample Blog Description
    limit: 10

pagination: true
---

### Notes on Web Graphic Techniques


text:
package com.fuhj.itower.model;

import java.util.Date;

public class GElecInfo extends BaseModel {
    private int gelecInfoId;

    public static final String GELEC_INFO_ID = "gelec_info_id";

    private String gCode;

    public static final String G_CODE = "g_code";

    private String province;

    public static final String PROVINCE = "province";

    private String city;

    public static final String CITY = "city";

    private String district;

    public static final String DISTRICT = "district";

    private String itProvinceId;

    public static final String IT_PROVINCE_ID = "it_province_id";

    private String itCityId;

    public static final String IT_CITY_ID = "it_city_id";

    private String itDistrictId;

    public static final String IT_DISTRICT_ID = "it_district_id";

    private int itBillId;

    public static final String IT_BILL_ID = "it_bill_id";

    private String billCode;

    public static final String BILL_CODE = "bill_code";

    private String faultSource;

    public static final String FAULT_SOURCE = "fault_source";

    private String alarmDetail;

    public static final String ALARM_DETAIL = "alarm_detail";

    private String stationName;

    public static final String STATION_NAME = "station_name";

    private String stationCode;

    public static final String STATION_CODE = "station_code";

    private String stationSysCode;

    public static final String STATION_SYS_CODE = "station_SYS_Code";

    private String operator;

    public static final String OPERATOR = "operator";

    private String operCode;

    public static final String OPER_CODE = "oper_code";

    private Date startTime;

    public static final String START_TIME = "start_time";

    private Date endTime;

    public static final String END_TIME = "end_time";

    private String duration;

    public static final String DURATION = "duration";

    private String odometer;

    public static final String ODOMETER = "odometer";

    private String petrolPrice;

    public static final String PETROL_PRICE = "petrol_price";

    private int machineCount;

    public static final String MACHINE_COUNT = "machine_count";

    private String areaType;

    public static final String AREA_TYPE = "area_type";

    private String dataOrigin;

    public static final String DATA_ORIGIN = "data_origin";

    private String reason;

    public static final String REASON = "reason";

    private String machinePower;

    public static final String MACHINE_POWER = "machine_power";

    private String machineType;

    public static final String MACHINE_TYPE = "machine_type";

    private String machineNo;

    public static final String MACHINE_NO = "machine_NO";

    private String person;

    public static final String PERSON = "person";

    private String contact;

    public static final String CONTACT = "contact";

    private String startVoltage;

    public static final String START_VOLTAGE = "start_voltage";

    private double startLng;

    public static final String START_LNG = "start_lng";

    private double startLat;

    public static final String START_LAT = "start_lat";

    private String startAddr;

    public static final String START_ADDR = "start_addr";

    private String endVoltage;

    public static final String END_VOLTAGE = "end_voltage";

    private double endLng;

    public static final String END_LNG = "end_lng";

    private double endLat;

    public static final String END_LAT = "end_lat";

    private String endAddr;

    public static final String END_ADDR = "end_addr";

    private String pic1;

    public static final String PIC1 = "pic1";

    private String pic2;

    public static final String PIC2 = "pic2";

    private Date createTime;

    public static final String CREATE_TIME = "create_time";

    private Date updateTime;

    public static final String UPDATE_TIME = "update_time";

    private int creatorId;

    public static final String CREATOR_ID = "creator_id";

    private int creatorAgentId;

    public static final String CREATOR_AGENT_ID = "creator_agent_id";

    private int status;

    public static final String STATUS = "status";

    private String remark;

    public static final String REMARK = "remark";

    public int getGelecInfoId() {
        return gelecInfoId;
    }

    public void setGelecInfoId(int gelecInfoId) {
        this.gelecInfoId = gelecInfoId;
    }

    public String getgCode() {
        return gCode;
    }

    public void setgCode(String gCode) {
        this.gCode = gCode == null ? null : gCode.trim();
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province == null ? null : province.trim();
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city == null ? null : city.trim();
    }

    public String getDistrict() {
        return district;
    }

    public void setDistrict(String district) {
        this.district = district == null ? null : district.trim();
    }

    public String getItProvinceId() {
        return itProvinceId;
    }

    public void setItProvinceId(String itProvinceId) {
        this.itProvinceId = itProvinceId == null ? null : itProvinceId.trim();
    }

    public String getItCityId() {
        return itCityId;
    }

    public void setItCityId(String itCityId) {
        this.itCityId = itCityId == null ? null : itCityId.trim();
    }

    public String getItDistrictId() {
        return itDistrictId;
    }

    public void setItDistrictId(String itDistrictId) {
        this.itDistrictId = itDistrictId == null ? null : itDistrictId.trim();
    }

    public int getItBillId() {
        return itBillId;
    }

    public void setItBillId(int itBillId) {
        this.itBillId = itBillId;
    }

    public String getBillCode() {
        return billCode;
    }

    public void setBillCode(String billCode) {
        this.billCode = billCode == null ? null : billCode.trim();
    }

    public String getFaultSource() {
        return faultSource;
    }

    public void setFaultSource(String faultSource) {
        this.faultSource = faultSource == null ? null : faultSource.trim();
    }

    public String getAlarmDetail() {
        return alarmDetail;
    }

    public void setAlarmDetail(String alarmDetail) {
        this.alarmDetail = alarmDetail == null ? null : alarmDetail.trim();
    }

    public String getStationName() {
        return stationName;
    }

    public void setStationName(String stationName) {
        this.stationName = stationName == null ? null : stationName.trim();
    }

    public String getStationCode() {
        return stationCode;
    }

    public void setStationCode(String stationCode) {
        this.stationCode = stationCode == null ? null : stationCode.trim();
    }

    public String getStationSysCode() {
        return stationSysCode;
    }

    public void setStationSysCode(String stationSysCode) {
        this.stationSysCode = stationSysCode == null ? null : stationSysCode.trim();
    }

    public String getOperator() {
        return operator;
    }

    public void setOperator(String operator) {
        this.operator = operator == null ? null : operator.trim();
    }

    public String getOperCode() {
        return operCode;
    }

    public void setOperCode(String operCode) {
        this.operCode = operCode == null ? null : operCode.trim();
    }

    public Date getStartTime() {
        return startTime;
    }

    public void setStartTime(Date startTime) {
        this.startTime = startTime;
    }

    public Date getEndTime() {
        return endTime;
    }

    public void setEndTime(Date endTime) {
        this.endTime = endTime;
    }

    public String getDuration() {
        return duration;
    }

    public void setDuration(String duration) {
        this.duration = duration == null ? null : duration.trim();
    }

    public String getOdometer() {
        return odometer;
    }

    public void setOdometer(String odometer) {
        this.odometer = odometer == null ? null : odometer.trim();
    }

    public String getPetrolPrice() {
        return petrolPrice;
    }

    public void setPetrolPrice(String petrolPrice) {
        this.petrolPrice = petrolPrice == null ? null : petrolPrice.trim();
    }

    public int getMachineCount() {
        return machineCount;
    }

    public void setMachineCount(int machineCount) {
        this.machineCount = machineCount;
    }

    public String getAreaType() {
        return areaType;
    }

    public void setAreaType(String areaType) {
        this.areaType = areaType == null ? null : areaType.trim();
    }

    public String getDataOrigin() {
        return dataOrigin;
    }

    public void setDataOrigin(String dataOrigin) {
        this.dataOrigin = dataOrigin == null ? null : dataOrigin.trim();
    }

    public String getReason() {
        return reason;
    }

    public void setReason(String reason) {
        this.reason = reason == null ? null : reason.trim();
    }

    public String getMachinePower() {
        return machinePower;
    }

    public void setMachinePower(String machinePower) {
        this.machinePower = machinePower == null ? null : machinePower.trim();
    }

    public String getMachineType() {
        return machineType;
    }

    public void setMachineType(String machineType) {
        this.machineType = machineType == null ? null : machineType.trim();
    }

    public String getMachineNo() {
        return machineNo;
    }

    public void setMachineNo(String machineNo) {
        this.machineNo = machineNo == null ? null : machineNo.trim();
    }

    public String getPerson() {
        return person;
    }

    public void setPerson(String person) {
        this.person = person == null ? null : person.trim();
    }

    public String getContact() {
        return contact;
    }

    public void setContact(String contact) {
        this.contact = contact == null ? null : contact.trim();
    }

    public String getStartVoltage() {
        return startVoltage;
    }

    public void setStartVoltage(String startVoltage) {
        this.startVoltage = startVoltage == null ? null : startVoltage.trim();
    }

    public double getStartLng() {
        return startLng;
    }

    public void setStartLng(double startLng) {
        this.startLng = startLng;
    }

    public double getStartLat() {
        return startLat;
    }

    public void setStartLat(double startLat) {
        this.startLat = startLat;
    }

    public String getStartAddr() {
        return startAddr;
    }

    public void setStartAddr(String startAddr) {
        this.startAddr = startAddr == null ? null : startAddr.trim();
    }

    public String getEndVoltage() {
        return endVoltage;
    }

    public void setEndVoltage(String endVoltage) {
        this.endVoltage = endVoltage == null ? null : endVoltage.trim();
    }

    public double getEndLng() {
        return endLng;
    }

    public void setEndLng(double endLng) {
        this.endLng = endLng;
    }

    public double getEndLat() {
        return endLat;
    }

    public void setEndLat(double endLat) {
        this.endLat = endLat;
    }

    public String getEndAddr() {
        return endAddr;
    }

    public void setEndAddr(String endAddr) {
        this.endAddr = endAddr == null ? null : endAddr.trim();
    }

    public String getPic1() {
        return pic1;
    }

    public void setPic1(String pic1) {
        this.pic1 = pic1 == null ? null : pic1.trim();
    }

    public String getPic2() {
        return pic2;
    }

    public void setPic2(String pic2) {
        this.pic2 = pic2 == null ? null : pic2.trim();
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public int getCreatorId() {
        return creatorId;
    }

    public void setCreatorId(int creatorId) {
        this.creatorId = creatorId;
    }

    public int getCreatorAgentId() {
        return creatorAgentId;
    }

    public void setCreatorAgentId(int creatorAgentId) {
        this.creatorAgentId = creatorAgentId;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark == null ? null : remark.trim();
    }
}


text:
package org.htrace;

import org.htrace.impl.CountSampler;
import org.junit.Assert;
import org.junit.Test;

public class TestCountSampler {

  @Test
  public void testNext() {
    CountSampler half = new CountSampler(2);
    CountSampler hundred = new CountSampler(100);
    int halfCount = 0;
    int hundredCount = 0;
    for (int i = 0; i < 200; i++) {
      if (half.next(null))
        halfCount++;
      if (hundred.next(null))
        hundredCount++;
    }
    Assert.assertEquals(2, hundredCount);
    Assert.assertEquals(100, halfCount);
  }
}


text:
module Search
  class BestBetsChecker
    def initialize(query, metasearch_index)
      @query = query
      @fetched = false
      @metasearch_index = metasearch_index
    end

    def best_bets
      fetch
      @best_bets
    end

    def worst_bets
      fetch
      @worst_bets
    end

  private

    # Fetch the best bets, and populate @best_bets and @worst_bets
    def fetch
      return if @fetched

      if @query.nil?
        @best_bets = {}
        @worst_bets = []
      else
        best, worst = select_bets(fetch_bets)
        @best_bets = combine_best_bets(best)
        @worst_bets = combine_worst_bets(worst)
      end
      @fetched = true
    end

    # Combine all the best bets supplied and group them by position.
    #
    # Returns an array of [position, [list of links]] groups.
    #
    # If a link occurs at multiple positions, it will only occur in the group for
    # the highest position it occurred at.
    # Where high means the smallest positional value.
    def combine_best_bets(bets)
      bets
      .map { |bet| [bet["position"], bet["link"]] }
      .sort
      .uniq { |_, link| link }
      .each_with_object({}) do |(position, link), result|
        result[position] ||= []
        result[position] << link
      end
    end

    def combine_worst_bets(bets)
      bets.map { |bet| bet["link"] }.uniq
    end

    # Select the bet entries to use.
    #
    # Returns two arrays, one of best bets and one of worst bets.
    def select_bets(bets)
      exact_bet = bets.find do |bet_type, _best, _worst|
        bet_type == "exact"
      end
      return [exact_bet[1], exact_bet[2]] if exact_bet

      [
        bets.flat_map { |_, best, _| best },
        bets.flat_map { |_, _, worst| worst },
      ]
    end

    # Fetch bet information from elasticsearch
    #
    # Returns an array of 4-tuples, holding:
    #  - query the bet was for
    #  - type of match the bet is for
    #  - the best bets, as an array of hashes
    #  - the worst bets, as an array of hashes
    #
    # The hashes representing bets have a "link" key containing the link for
    # the bet, and for best bets also a "position" key containing the position
    # the best bet should appear at.
    def fetch_bets
      analyzed_users_query = " #{@metasearch_index.analyzed_best_bet_query(@query)} "
      es_response = timed_raw_search(lookup_payload)

      es_response["hits"]["hits"].map { |hit|
        details = JSON.parse(Array(hit["_source"]["details"]).first)
        _bet_query, _, bet_type = hit["_id"].rpartition("-")
        stemmed_query_as_term = Array(hit["_source"]["stemmed_query_as_term"]).first

        # The search on the stemmed_query field is overly broad, so here we need
        # to filter out such matches where the query in the bet is not a
        # substring (modulo stemming) of the user's query.
        if stemmed_query_as_term && !analyzed_users_query.include?(stemmed_query_as_term)
          nil
        else
          [bet_type, details["best_bets"], details["worst_bets"]]
        end
      }
      .compact
    end

    def timed_raw_search(payload)
      GovukStatsd.time("elasticsearch.best_bets_raw_search") do
        @metasearch_index.raw_search(payload)
      end
    end

    # Return a payload for a query across the best_bets type in the metasearch
    # index which will return the best and worst bet entries to use.  Each hit
    # contains a "details" field containing a JSON encoded list of best and worst
    # bets for a query.
    #
    # We limit the number of returned items to 1000: we don't expect to go
    # anywhere near this limit, and performance with 1000 should be okay, but
    # it's a good idea to avoid risking having to deal with huge numbers of
    # returned bets.
    #
    # It's not possible to build an elasticsearch query against the stemmed_query
    # field which only returns results where the entire stemmed_query field value
    # occurs as a phrase in the user's query.  Instead, we do an OR query to
    # obtain a set of candidates which match that field, and use the
    # stemmed_query_as_term field to look for substring matches in the user's query.
    def lookup_payload
      {
        query: {
          bool: {
            should: [
              { match: { exact_query: @query } },
              { match: { stemmed_query: @query } },
            ],
          },
        },
        post_filter: {
          bool: { must: { match: { document_type: "best_bet" } } },
        },
        size: 1000,
        _source: {
          includes: %i[details stemmed_query_as_term],
        },
      }
    end
  end
end


text:
package org.openqa.selenium.remote.session;

import com.google.common.collect.ImmutableMap;

import java.util.Map;
import java.util.Objects;

public class OperaFilter implements CapabilitiesFilter {
  @Override
  public Map<String, Object> apply(Map<String, Object> unmodifiedCaps) {
    ImmutableMap<String, Object> caps = unmodifiedCaps.entrySet().parallelStream()
        .filter(entry ->
                    ("browserName".equals(entry.getKey()) && "opera".equals(entry.getValue())) ||
                    ("browserName".equals(entry.getKey()) && "operablink".equals(entry.getValue())) ||
                    "operaOptions".equals(entry.getKey()))
        .distinct()
        .filter(entry -> Objects.nonNull(entry.getValue()))
        .collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));

    return caps.isEmpty() ? null : caps;
  }
}


text:
class AddSlugIndexToPages < ActiveRecord::Migration
  def change
    add_index(:pages, :slug, unique: true)
  end
end


text:
package org.zstack.utils.ctl;

/**
 * @Author: DaoDao
 * @Date: 2021/12/17
 */
public class RestoreMysqlCommand extends CtlCommandSpec{
    private String ctlName = "restore_mysql";

    @Override
    String getCtlName() {
        return ctlName;
    }

    public RestoreMysqlCommand fromFile(String fromFile) {
        CtlCommandParam param = new CtlCommandParam();
        param.option = "--from-file";
        param.arguments = fromFile;
        addOption(param);
        return this;
    }

    public RestoreMysqlCommand mysqlRootPassword(String password) {
        CtlCommandParam param = new CtlCommandParam();
        param.option = "--mysql-root-password";
        param.arguments = password;
        addOption(param);
        return this;
    }

    public RestoreMysqlCommand uiMysqlRootPassword(String password) {
        CtlCommandParam param = new CtlCommandParam();
        param.option = "--ui-mysql-root-password";
        param.arguments = password;
        addOption(param);
        return this;
    }

    public RestoreMysqlCommand skipUi() {
        CtlCommandParam param = new CtlCommandParam();
        param.option = "--skip-ui";
        addOption(param);
        return this;
    }

    public RestoreMysqlCommand onlyRestoreSelf() {
        CtlCommandParam param = new CtlCommandParam();
        param.option = "--only-restore-self";
        addOption(param);
        return this;
    }

    public RestoreMysqlCommand skipCheck() {
        CtlCommandParam param = new CtlCommandParam();
        param.option = "--skip-check";
        addOption(param);
        return this;
    }
}


text:
#include "pipe/p_screen.h"
#include "pipe/p_state.h"
#include "util/u_memory.h"

#include "id_public.h"
#include "id_screen.h"
#include "id_context.h"
#include "id_objects.h"

static void
identity_screen_destroy(struct pipe_screen *_screen)
{
   struct identity_screen *id_screen = identity_screen(_screen);
   struct pipe_screen *screen = id_screen->screen;

   screen->destroy(screen);

   FREE(id_screen);
}

static const char *
identity_screen_get_name(struct pipe_screen *_screen)
{
   struct identity_screen *id_screen = identity_screen(_screen);
   struct pipe_screen *screen = id_screen->screen;

   return screen->get_name(screen);
}

static const char *
identity_screen_get_vendor(struct pipe_screen *_screen)
{
   struct identity_screen *id_screen = identity_screen(_screen);
   struct pipe_screen *screen = id_screen->screen;

   return screen->get_vendor(screen);
}

static int
identity_screen_get_param(struct pipe_screen *_screen,
                          enum pipe_cap param)
{
   struct identity_screen *id_screen = identity_screen(_screen);
   struct pipe_screen *screen = id_screen->screen;

   return screen->get_param(screen,
                            param);
}

static int
identity_screen_get_shader_param(struct pipe_screen *_screen,
                          unsigned shader, enum pipe_shader_cap param)
{
   struct identity_screen *id_screen = identity_screen(_screen);
   struct pipe_screen *screen = id_screen->screen;

   return screen->get_shader_param(screen, shader,
                            param);
}

static float
identity_screen_get_paramf(struct pipe_screen *_screen,
                           enum pipe_cap param)
{
   struct identity_screen *id_screen = identity_screen(_screen);
   struct pipe_screen *screen = id_screen->screen;

   return screen->get_paramf(screen,
                             param);
}

static boolean
identity_screen_is_format_supported(struct pipe_screen *_screen,
                                    enum pipe_format format,
                                    enum pipe_texture_target target,
                                    unsigned sample_count,
                                    unsigned tex_usage)
{
   struct identity_screen *id_screen = identity_screen(_screen);
   struct pipe_screen *screen = id_screen->screen;

   return screen->is_format_supported(screen,
                                      format,
                                      target,
                                      sample_count,
                                      tex_usage);
}

static struct pipe_context *
identity_screen_context_create(struct pipe_screen *_screen,
                               void *priv)
{
   struct identity_screen *id_screen = identity_screen(_screen);
   struct pipe_screen *screen = id_screen->screen;
   struct pipe_context *result;

   result = screen->context_create(screen, priv);
   if (result)
      return identity_context_create(_screen, result);
   return NULL;
}

static struct pipe_resource *
identity_screen_resource_create(struct pipe_screen *_screen,
                                const struct pipe_resource *templat)
{
   struct identity_screen *id_screen = identity_screen(_screen);
   struct pipe_screen *screen = id_screen->screen;
   struct pipe_resource *result;

   result = screen->resource_create(screen,
                                    templat);

   if (result)
      return identity_resource_create(id_screen, result);
   return NULL;
}

static struct pipe_resource *
identity_screen_resource_from_handle(struct pipe_screen *_screen,
                                     const struct pipe_resource *templ,
                                     struct winsys_handle *handle)
{
   struct identity_screen *id_screen = identity_screen(_screen);
   struct pipe_screen *screen = id_screen->screen;
   struct pipe_resource *result;

   /* TODO trace call */

   result = screen->resource_from_handle(screen, templ, handle);

   result = identity_resource_create(identity_screen(_screen), result);

   return result;
}

static boolean
identity_screen_resource_get_handle(struct pipe_screen *_screen,
                                    struct pipe_resource *_resource,
                                    struct winsys_handle *handle)
{
   struct identity_screen *id_screen = identity_screen(_screen);
   struct identity_resource *id_resource = identity_resource(_resource);
   struct pipe_screen *screen = id_screen->screen;
   struct pipe_resource *resource = id_resource->resource;

   /* TODO trace call */

   return screen->resource_get_handle(screen, resource, handle);
}

static void
identity_screen_resource_destroy(struct pipe_screen *screen,
                                 struct pipe_resource *_resource)
{
   identity_resource_destroy(identity_resource(_resource));
}

static struct pipe_resource *
identity_screen_user_buffer_create(struct pipe_screen *_screen,
                                   void *ptr,
                                   unsigned bytes,
                                   unsigned usage)
{
   struct identity_screen *id_screen = identity_screen(_screen);
   struct pipe_screen *screen = id_screen->screen;
   struct pipe_resource *result;

   result = screen->user_buffer_create(screen,
                                       ptr,
                                       bytes,
                                       usage);

   if (result)
      return identity_resource_create(id_screen, result);
   return NULL;
}

static void
identity_screen_flush_frontbuffer(struct pipe_screen *_screen,
                                  struct pipe_resource *_resource,
                                  unsigned level, unsigned layer,
                                  void *context_private)
{
   struct identity_screen *id_screen = identity_screen(_screen);
   struct identity_resource *id_resource = identity_resource(_resource);
   struct pipe_screen *screen = id_screen->screen;
   struct pipe_resource *resource = id_resource->resource;

   screen->flush_frontbuffer(screen,
                             resource,
                             level, layer,
                             context_private);
}

static void
identity_screen_fence_reference(struct pipe_screen *_screen,
                                struct pipe_fence_handle **ptr,
                                struct pipe_fence_handle *fence)
{
   struct identity_screen *id_screen = identity_screen(_screen);
   struct pipe_screen *screen = id_screen->screen;

   screen->fence_reference(screen,
                           ptr,
                           fence);
}

static boolean
identity_screen_fence_signalled(struct pipe_screen *_screen,
                                struct pipe_fence_handle *fence)
{
   struct identity_screen *id_screen = identity_screen(_screen);
   struct pipe_screen *screen = id_screen->screen;

   return screen->fence_signalled(screen,
                                  fence);
}

static boolean
identity_screen_fence_finish(struct pipe_screen *_screen,
                             struct pipe_fence_handle *fence,
                             uint64_t timeout)
{
   struct identity_screen *id_screen = identity_screen(_screen);
   struct pipe_screen *screen = id_screen->screen;

   return screen->fence_finish(screen,
                               fence,
                               timeout);
}

struct pipe_screen *
identity_screen_create(struct pipe_screen *screen)
{
   struct identity_screen *id_screen;

   id_screen = CALLOC_STRUCT(identity_screen);
   if (!id_screen) {
      return NULL;
   }

   id_screen->base.winsys = NULL;

   id_screen->base.destroy = identity_screen_destroy;
   id_screen->base.get_name = identity_screen_get_name;
   id_screen->base.get_vendor = identity_screen_get_vendor;
   id_screen->base.get_param = identity_screen_get_param;
   id_screen->base.get_shader_param = identity_screen_get_shader_param;
   id_screen->base.get_paramf = identity_screen_get_paramf;
   id_screen->base.is_format_supported = identity_screen_is_format_supported;
   id_screen->base.context_create = identity_screen_context_create;
   id_screen->base.resource_create = identity_screen_resource_create;
   id_screen->base.resource_from_handle = identity_screen_resource_from_handle;
   id_screen->base.resource_get_handle = identity_screen_resource_get_handle;
   id_screen->base.resource_destroy = identity_screen_resource_destroy;
   id_screen->base.user_buffer_create = identity_screen_user_buffer_create;
   id_screen->base.flush_frontbuffer = identity_screen_flush_frontbuffer;
   id_screen->base.fence_reference = identity_screen_fence_reference;
   id_screen->base.fence_signalled = identity_screen_fence_signalled;
   id_screen->base.fence_finish = identity_screen_fence_finish;

   id_screen->screen = screen;

   return &id_screen->base;
}