text:
/**
 * HOC enhancer
 * render Component into target node
 * @author: ryan.bian
 */
import React, { PureComponent } from 'react';
import ReactDOM from 'react-dom';
import hoistNonReactStatic from 'hoist-non-react-statics';

export default function renderTo(target = document.body) {
  return (WrappedComponent) => {
    class EnhancedComponent extends PureComponent {
      componentWillMount() {
        this.wrapNode = document.createElement('div');
        target.appendChild(this.wrapNode);
      }
      componentDidMount() {
        this.renderComponent();
      }
      componentDidUpdate() {
        this.renderComponent();
      }
      componentWillUnmount() {
        ReactDOM.unmountComponentAtNode(this.wrapNode);
        this.wrapNode.parentNode.removeChild(this.wrapNode);
      }
      renderComponent() {
        ReactDOM.unstable_renderSubtreeIntoContainer(
          this,
          <WrappedComponent {...this.props} />,
          this.wrapNode,
        );
      }
      render() {
        return null;
      }
    }
    hoistNonReactStatic(EnhancedComponent, WrappedComponent);
    return EnhancedComponent;
  };
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>lib/rmt.js - RmT</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="icon" href="../assets/favicon.ico">

            API Docs for: 0.1.0

APIs

Classes

Modules

                            <input type="search" id="api-filter" placeholder="Type to filter APIs">

Helpers

RmT

                    Show:

                        <input type="checkbox" id="api-show-inherited" checked>
                        Inherited

                        <input type="checkbox" id="api-show-protected">
                        Protected

                        <input type="checkbox" id="api-show-private">
                        Private

                        <input type="checkbox" id="api-show-deprecated">
                        Deprecated

File: lib/rmt.js

'use strict';

/**
 * Module Dependencies
 */

var inquirer = require('inquirer'),
    Twitter = require('twitter'),
    TwitterPinAuth = require('twitter-pin-auth'),
    P = require('bluebird'),
    _ = require('underscore'),
    async = require('async'),
    open = require('open'),
    join = require('path').join,
    debug = require('./debugger.js'),
    h = require('./helpers.js');

require('colors');

/**
 * @class RmT
 *
 * @constructor
 *
 * Constructor responsible for provide twitter authorization
 *
 * @example
 *
 *     var api = new RmT('consumerKey', 'consumerSecret');
 *
 * @param {String} consumerKey The twitter consumer key
 * @param {String} consumerSecret The twitter consumer secret
 */

var RmT = module.exports = function RmT(consumerKey, consumerSecret) {
    this.consumerKey = consumerKey;
    this.consumerSecret = consumerSecret;
    this.accessTokenKey = '';
    this.accessTokenSecret = '';
    this.tpa = new TwitterPinAuth(this.consumerKey, this.consumerSecret);
    this.client = null;
};

/*
 * Public Methods
 */

/**
 * Method responsible for asking questions
 *
 * @example
 *
 *     api.prompt(prompts, cb);
 *
 * @method prompt
 * @public
 * @param {Object} prompts Array of prompt options
 * @param {Function} cb A callback
 */

RmT.prototype.prompt = function prompt(prompts, cb) {
    inquirer.prompt(prompts, function(answers) {
        cb(answers);
    });
};

/**
 * Method responsible for create twitter client instance
 *
 * @example
 *
 *     api.createClient('accessTokenKey', 'accessTokenSecret');
 *
 * @method createClient
 * @public
 * @param {String} accessTokenKey The twitter access token key
 * @param {String} accessTokenSecret The twitter access token secret
 */

RmT.prototype.createClient = function createClient(accessTokenKey, accessTokenSecret) {
    this.client = new Twitter({
        consumer_key: this.consumerKey,
        consumer_secret: this.consumerSecret,
        access_token_key: accessTokenKey,
        access_token_secret: accessTokenSecret
    });
};

/**
 * Method responsible for save consumer credentials
 *
 * @example
 *
 *     api.setConfig('consumerKey', 'consumerSecret', function(err, data) {
 *          console.log(data);
 *     });
 *
 * @method setConfig
 * @public
 * @param {String} consumerKey The twitter consumer key
 * @param {String} consumerSecret The twitter consumer secret
 * @param {Function} cb A callback with error and api response
 */

RmT.prototype.setConfig = function setConfig(consumerKey, consumerSecret, cb) {
    return new P(function(resolve, reject) {
        //Write config
        if (consumerKey && consumerKey !== '' && consumerSecret && consumerSecret !== '') {
            h.write(join(__dirname, 'rmtConfig.json'), {
                consumerKey: consumerKey,
                consumerSecret: consumerSecret
            });
            resolve('Settings updated successfully!');
        } else {
            reject(new Error('Setup failed. Try again!'));
        }
    }).nodeify(cb);
};

/**
 * Method responsible for login
 *
 * @example
 *
 *     api.login(function(err, data) {
 *          console.log(data);
 *     });
 *
 * @method login
 * @public
 * @param {Function} cb A callback with error and api response
 */

RmT.prototype.login = function login(cb) {
    var that = this;
    return new P(function(resolve, reject) {
        //Get authUrl
        that.tpa.requestAuthUrl()
            .then(function(url) {
                debug('In your browser, on the opened window by RmT, log in to your twitter account, click on "Authorize" button and enter the PIN number below.', 'info');
                console.log();
                //Open authorize url
                open(url);
                //Ask
                that.prompt([{
                    type: 'input',
                    name: 'pin',
                    message: 'Enter the pin number: '
                }], function(answers) {
                    that.tpa.authorize(answers.pin)
                        .then(function(data) {
                            //Write config
                            if (data.accessTokenKey && data.accessTokenKey !== '' && data.accessTokenSecret && data.accessTokenSecret !== '') {
                                h.write(join(__dirname, 'rmtConfig.json'), {
                                    accessTokenKey: data.accessTokenKey,
                                    accessTokenSecret: data.accessTokenSecret
                                });
                                resolve('Logged successfully!');
                            } else {
                                reject(new Error('Login failed. Try again!'));
                            }
                        }).catch(function(err) {
                            reject(err);
                        });
                });
            }).catch(function(err) {
                reject(err);
            });
    }).nodeify(cb);
};

/**
 * Method responsible for remove twitter credentials
 *
 * @example
 *
 *     api.logout(function(err, message) {
 *          console.log(message);
 *     });
 *
 * @method logout
 * @public
 * @param {Function} cb A callback with error and api response
 */

RmT.prototype.logout = function logout(cb) {
    return new P(function(resolve) {
        //Write config
        h.write(join(__dirname, 'rmtConfig.json'), {
            accessTokenKey: '',
            accessTokenSecret: ''
        });
        resolve('Your twitter credentials has been removed successfully!');
    }).nodeify(cb);
};

/**
 * Method responsible for showing the user profile
 *
 * @example
 *
 *     api.profile();
 *
 * @method profile
 * @public
 * @param {Function} cb A callback with error and api response
 */

RmT.prototype.profile = function profile(cb) {
    var that = this;
    return new P(function(resolve, reject) {
        that.client.get('account/verify_credentials', function(err, data) {
            if (err) {
                reject(new Error(err[0].message));
            } else {
                resolve({
                    id: data.id_str,
                    name: data.name,
                    username: data.screen_name,
                    location: data.location,
                    followers: data.followers_count,
                    tweets: data.statuses_count,
                    createdAt: data.created_at
                });
            }
        });
    }).nodeify(cb);
};

/**
 * Method responsible for show your all tweets
 *
 * @example
 *
 *     api.show();
 *
 * @method show
 * @public
 * @param {Number} limit A number to limit the number of tweets returned
 * @param {Function} cb A callback with error and api response
 */

RmT.prototype.show = function show(limit, cb) {
    var that = this;
    return new P(function(resolve, reject) {
        that.client.get('statuses/user_timeline', {
            count: limit
        }, function(err, tweets) {
            if (err) {
                reject(new Error(err[0].message));
            } else {
                if (limit) {
                    var tweetsList = _.map(tweets, function(tweet) {
                        return tweet.text;
                    });
                    resolve(tweetsList);
                } else {
                    resolve(tweets[0].text);
                }
            }
        });
    }).nodeify(cb);
};

/**
 * Method responsible for delete all tweets
 *
 * @example
 *
 *     api.remove();
 *
 * @method remove
 * @public
 * @param {Boolean} removeAll A boolean to enable to remove all tweets
 * @param {Function} cb A callback with error and api response
 */

RmT.prototype.remove = function remove(removeAll, cb) {
    var that = this;
    return new P(function(resolve, reject) {
        that.client.get('statuses/user_timeline', {
            include_rts: true
        }, function(err, tweets) {
            if (err) {
                reject(new Error(err[0].message));
            } else {
                var msg;
                if (removeAll) {
                    msg = 'You really want to remove all your tweets?';
                } else {
                    msg = 'You really want to remove your last tweet?';
                }
                that.prompt([{
                    type: 'confirm',
                    name: 'remove',
                    message: msg
                }], function(answers) {
                    if (answers.remove) {
                        if (removeAll) {
                            async.eachSeries(tweets, function(tweet, callback) {
                                debug('Removing ' + ' "'.red + tweet.text.white + '"'.red, 'error');
                                that.client.post('statuses/destroy/' + tweet.id_str, function(err) {
                                    if (err) {
                                        callback(new Error(err[0].message));
                                    } else {
                                        callback();
                                    }
                                });
                            }, function(err) {
                                if (err) {
                                    reject(err);
                                } else {
                                    resolve('All your tweets are deleted successfully!');
                                }
                            });
                        } else {
                            debug('Removing ' + ' "'.red + tweets[0].text.white + '"'.red, 'error');
                            that.client.post('statuses/destroy/' + tweets[0].id_str, function(err) {
                                if (err) {
                                    reject(new Error(err[0].message));
                                } else {
                                    resolve('Tweet removed successfully!');
                                }
                            });
                        }
                    } else {
                        process.exit(1);
                    }
                });
            }
        });
    }).nodeify(cb);
};

redpajama_set_name: RedPajamaGithub


text:
/*
 * This module can be executed standalone in node, to build CSS files, inlining imports, and
 * pre-processing extensions for faster run-time execution. This module is also
 * used by the AMD build process.
 */
var operatorMatch = {
	'{': '}',
	'[': ']',
	'(': ')'
};
var nextId = 1;

document = {
	createElement: function(){
		return {style:
			{// TODO: may want to import static has features to determine if some of these exist
			}
		};
	},
	getElementsByTagName: function(){
		return [];
	},
	addEventListener: function(){}
};
navigator = {
	userAgent: "build"
};

var pseudoDefine = function(id, deps, factory){
		parse = factory({
				isBuild: true,
				isTagSupported: function(){
					return true;
				}
		});
	};
var requiredModules = [], base64Module;

if(typeof define == 'undefined'){
	var fs = require('fs'),
		pathModule = require('path'),
		parse;
	define = pseudoDefine;
	require('./core/parser');
}else{
	define(['build/fs', 'build/fileUtils', './build/base64'], function(fsModule, fileUtils, base64){
		fs = fsModule;
		base64Module = base64;
		// must create our own path module for Rhino :/
		pathModule = {
			resolve: function(base, target){
				target = (base.replace(/[^\/]+$/, '') + target);
				var newTarget = target.replace(/\/[^\/]*\/\.\./g, '');
				while(target !== (newTarget = target.replace(/\/[^\/]*\/\.\./g, ''))){
					target = newTarget;
				}
				return target.replace(/\/\.\//g,'/');
			},
			dirname: function(path){
				return path.replace(/[\/\\][^\/\\]*$/, '');
			},
			relative: function(basePath, path){
				basePath = this.dirname(basePath);
				var baseParts = basePath.split(/[\/\\]/);
				var parts = path.split(/[\/\\]/);
				var l = parts.length;
				for (var i = 0; i < l; i++){
					if (parts[i] !== baseParts[i]){
						break;
					}
				}
				parts.splice(0, i);
				for (; i < baseParts.length; i++){
					parts.unshift('..');
				}
				return parts.join('/');
			},
			join: function(base, target){
				return fileUtils.compactPath((base[base.length - 1] == '/' ? base : (base + '/')) + target);
			}
		};
		return function(xstyleText){
			var define = pseudoDefine;
			var vm;
			try {
				require(['dojo/node!vm']);
				vm = require('dojo/node!vm');
			} catch (e) {
			}
			vm ?
				vm.runInNewContext(xstyleText, {
					define: define,
					console: console
				}, 'xstyle/core/parser.js') :
				eval(xstyleText);
			return processCss;
		};
	});
}
function main(source, target){
	var imported = {};
	var basePath = source.replace(/[^\/]*$/, '');
	var cssText = fs.readFileSync(source).toString("utf-8");
	var processed = processCss(cssText, basePath, basePath);
	var output = processed.standardCss;
	if(processed.xstyleCss){
		output += 'x-xstyle{content:"' +
				processed.xstyleCss.replace(/["\\\n\r]/g, '\\$&') +
					'";}';
	}
	if(target){
		fs.writeFileSync(target, output);
	}else{
		console.log(output);
	}
}
function minify(cssText){
	return cssText.
			replace(/\/\*([^\*]|\*[^\/])*\*\//g, ' ').
			replace(/\s*("(\\\\|[^\"])*"|'(\\\\|[^\'])*'|[;}{:])\s*/g,"$1").
			replace(/[^\x00-\x7F]([0-9a-fA-F])?/g, function(character, hexComesNext){
				// escape non-ascii characters to be safe
				return '\\' + character.charCodeAt(0).toString(16) + (hexComesNext ? ' ' + hexComesNext : '');
			});
}
var mimeTypes = {
	eot: "application/vnd.ms-fontobject",
	woff: "application/font-woff",
	gif: "image/gif",
	jpg: "image/jpeg",
	jpeg: "image/jpeg",
	png: "image/png"
}
function processCss(cssText, basePath, cssPath, inlineAllResources){
	function XRule(){
	}
	var ruleCount = 0;
	XRule.prototype = {
		newCall: function(name){
			var call = new Call(name);
			call.parent = this;
			return call;
		},
		childRules: 0,
		newRule: function(name){
			var rule = (this.rules || (this.rules = {}))[name] = new XRule();
			rule.ruleIndex = this.childRules++;
			rule.parent = this;
			return rule;
		},
		getDefinition: function(name, includeRules){
			var parentRule = this;
			do{
				var target = parentRule.definitions && parentRule.definitions[name]
					|| (includeRules && parentRule.rules && parentRule.rules[name]);
				parentRule = parentRule.parent;
			}while(!target && parentRule);
			if(target){
				target.name = name;
			}
			return target;
		},
		declareDefinition: function(name, value, conditional){
			// TODO: access staticHasFeatures to check conditional
			var valueString = {
				toString: function(){
					return value.toString(2);
				}
			};
			(this.xstyleCss = this.xstyleCss || []).push(name + '=', valueString, ';');
			var definitions = (this.definitions || (this.definitions = {}));
			definitions[name] = value || new XRule();
		},
		setValue: function(name, value){
			var target = this.getDefinition(name);
			var browserCss = this.browserCss = this.browserCss || [];
			if(!this.ruleStarted && !this.root){
				this.ruleStarted = true;
				browserCss.push(this.selector, '{');
			}
			if(!target){
				browserCss.push(name, ':', value, ';');
			}
			if(target || typeof value == 'object'){
				if(!this.xstyleStarted){
					this.xstyleStarted = true;
					this.xstyleCss = this.xstyleCss || [];
				}
				this.xstyleCss.push(name + ':' + value + ';');
			}
		},
		onArguments: function(){},
		setMediaSelector: function(selector){
			this.selector = '';
			browserCss.push(selector, '{');
			this.isMediaBlock = true;
		},
		toString: function(mode){
			var str = '';
			str += this.xstyleCss ? this.xstyleCss.join('') : '';
			for(var i in this.rules){
				var rule = this.rules[i];
				if(rule.ref && !rule.creating){
					str += rule.toString(1);
				}
			}
			if(!this.root && !this.isMediaBlock && this.xstyleStarted && (str || mode != 1)){
				str = ((mode == 2 && this.bases) || this.tagName || '') + '{' + this.ref + str.replace(/\s+/g, ' ') + '}';
			}
			return str;
		},
		onRule: function(){
			if(this.browserCss){
				this.browserCss.push('}');
				this.ref = '/' + ruleCount;
				ruleCount++;
				browserCss.push(this.browserCss.join(''));
			}
			if(this.isMediaBlock){
				browserCss.push('}');
			}
		},
		extend: function(derivative, fullExtension){
			var definitions = this.definitions;
			if(definitions && fullExtension){
				// TODO: need to mixin this in, if it already exists
				derivative.definitions = Object.create(definitions);
			}
			(derivative.bases = derivative.bases || []).push(this.name);
		}
	};
	// a class representing function calls
	function Call(value){
		// we store the caller and the arguments
		this.caller = value;
		this.args = [];
	}
	var CallPrototype = Call.prototype = new XRule;
	CallPrototype.declareProperty = CallPrototype.setValue = function(name, value){
		// handle these both as addition of arguments
		this.args.push(value);
	};
	CallPrototype.toString = function(){
		var operator = this.operator;
		return operator + this.args + operatorMatch[operator];
	};

	function insertRule(cssText){
		//browserCss.push(cssText);
	}
	function correctUrls(cssText, path){
		// correct all the URLs in the stylesheets
		// determine the directory path
		path = pathModule.dirname(path) + '/';
		//console.log("starting path", basePath , path);
		// compute the relative path from where we are to the base path where the stylesheet will go
		var relativePath = pathModule.relative(basePath, path);
		return cssText.replace(/url\s*\(\s*['"]?([^'"\)]*)['"]?\s*\)/g, function(t, url){
			if(inlineAllResources || /#inline$/.test(url)){
				// we can inline the resource
				suffix = url.match(/\.(\w+)(#|\?|$)/);
				suffix = suffix && suffix[1];
				url = url.replace(/[\?#].*/,'');

				if(typeof java !== 'undefined'){
					// reading binary is hard in rhino
					var file = new java.io.File(pathModule.join(path, url));
					var length = file.length();
					var fis = new java.io.FileInputStream(file);
					var bytes = java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, length);
					fis.read(bytes, 0, length);
					var jsBytes = new Array(length);
					for(var i = 0; i < bytes.length;i++){
						var singleByte = bytes[i];
						if(singleByte < 0){
							singleByte = 256 + singleByte;
						}
						jsBytes[i] = singleByte;
					}
					var moduleText =base64Module.encode(jsBytes);
				}else{
					// in node base64 encoding is easy
					var moduleText = fs.readFileSync(pathModule.join(path, url)).toString("base64");
				}
				return 'url("data:' + (mimeTypes[suffix] || 'application/octet-stream') +
							';base64,' + moduleText + '")';
			}
			// or we adjust the URL
			var adjustedPath = pathModule.resolve(relativePath, url);
			return 'url("' + adjustedPath + '")';
		});
	};
	parse.getStyleSheet = function(importRule, sequence, styleSheet){
		var importValue = sequence[1];
		var path;
		try{
			if(importValue.operator === '('){
				// a url() call
				var firstArg = importValue.args[0];
				// extract  from a literal string, or just grab the raw text
				// note that the correctUrls should have already resolved this path
				path = firstArg.length? firstArg[0].value : firstArg.toString();
			}else{
				// assume it is a string
				path  = pathModule.resolve(styleSheet.href, importValue.value);
			}
		}catch(error){
			console.error('Can not parse import value of ', error, importValue, firstArg);
		}
		var localSource = '';
		try{
			localSource = fs.readFileSync(path).toString('utf-8');
		}catch(e){
			console.error(e.stack || e);
		}
		localSource = correctUrls(localSource, path);
		return {
			localSource: localSource,
			href: path || '.',
			insertRule: insertRule,
			cssRules: []
		};
	};
	var browserCss = [];//[correctUrls(cssText, basePath + "placeholder.css")];
	var rootRule = new XRule;
	rootRule.root = true;
	parse(rootRule, correctUrls(cssText, cssPath),
			{href: cssPath || '.', cssRules:[], insertRule: insertRule});
	rootRule.definitions = {
		Math:1,
		require:1,
		item: 1,
		'native': 1,
		prefixed: 1
	}
	function visit(parent){
		//browserCss.push(parent.selector + '{' + parent.cssText + '}');
		/*for(var i in parent.variables){
			if(!intrinsicVariables.hasOwnProperty(i)){
				xstyleCss.push(i,'=',parent.variables[i]);
			}
		}*/
	}
	visit(rootRule);
	return {
		standardCss: minify(browserCss.join('')),
		xstyleCss: rootRule.toString(),
		requiredModules: requiredModules
	};
}
if(typeof module != 'undefined' && require.main == module){
	main.apply(this, process.argv.slice(2));
}


text:
package org.apache.spark.sql.execution

import scala.io.Source

import org.apache.spark.sql.AnalysisException
import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, OneRowRelation}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.test.SharedSQLContext

case class QueryExecutionTestRecord(
    c0: Int, c1: Int, c2: Int, c3: Int, c4: Int,
    c5: Int, c6: Int, c7: Int, c8: Int, c9: Int,
    c10: Int, c11: Int, c12: Int, c13: Int, c14: Int,
    c15: Int, c16: Int, c17: Int, c18: Int, c19: Int,
    c20: Int, c21: Int, c22: Int, c23: Int, c24: Int,
    c25: Int, c26: Int)

class QueryExecutionSuite extends SharedSQLContext {
  import testImplicits._

  def checkDumpedPlans(path: String, expected: Int): Unit = {
    assert(Source.fromFile(path).getLines.toList
      .takeWhile(_ != "== Whole Stage Codegen ==") == List(
      "== Parsed Logical Plan ==",
      s"Range (0, $expected, step=1, splits=Some(2))",
      "",
      "== Analyzed Logical Plan ==",
      "id: bigint",
      s"Range (0, $expected, step=1, splits=Some(2))",
      "",
      "== Optimized Logical Plan ==",
      s"Range (0, $expected, step=1, splits=Some(2))",
      "",
      "== Physical Plan ==",
      s"*(1) Range (0, $expected, step=1, splits=2)",
      ""))
  }
  test("dumping query execution info to a file") {
    withTempDir { dir =>
      val path = dir.getCanonicalPath + "/plans.txt"
      val df = spark.range(0, 10)
      df.queryExecution.debug.toFile(path)

      checkDumpedPlans(path, expected = 10)
    }
  }

  test("dumping query execution info to an existing file") {
    withTempDir { dir =>
      val path = dir.getCanonicalPath + "/plans.txt"
      val df = spark.range(0, 10)
      df.queryExecution.debug.toFile(path)

      val df2 = spark.range(0, 1)
      df2.queryExecution.debug.toFile(path)
      checkDumpedPlans(path, expected = 1)
    }
  }

  test("dumping query execution info to non-existing folder") {
    withTempDir { dir =>
      val path = dir.getCanonicalPath + "/newfolder/plans.txt"
      val df = spark.range(0, 100)
      df.queryExecution.debug.toFile(path)
      checkDumpedPlans(path, expected = 100)
    }
  }

  test("dumping query execution info by invalid path") {
    val path = "1234567890://plans.txt"
    val exception = intercept[IllegalArgumentException] {
      spark.range(0, 100).queryExecution.debug.toFile(path)
    }

    assert(exception.getMessage.contains("Illegal character in scheme name"))
  }

  test("limit number of fields by sql config") {
    def relationPlans: String = {
      val ds = spark.createDataset(Seq(QueryExecutionTestRecord(
        0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
        16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26)))
      ds.queryExecution.toString
    }
    withSQLConf(SQLConf.MAX_TO_STRING_FIELDS.key -> "26") {
      assert(relationPlans.contains("more fields"))
    }
    withSQLConf(SQLConf.MAX_TO_STRING_FIELDS.key -> "27") {
      assert(!relationPlans.contains("more fields"))
    }
  }

  test("check maximum fields restriction") {
    withTempDir { dir =>
      val path = dir.getCanonicalPath + "/plans.txt"
      val ds = spark.createDataset(Seq(QueryExecutionTestRecord(
        0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
        16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26)))
      ds.queryExecution.debug.toFile(path)
      val localRelations = Source.fromFile(path).getLines().filter(_.contains("LocalRelation"))

      assert(!localRelations.exists(_.contains("more fields")))
    }
  }

  test("toString() exception/error handling") {
    spark.experimental.extraStrategies = Seq(
        new SparkStrategy {
          override def apply(plan: LogicalPlan): Seq[SparkPlan] = Nil
        })

    def qe: QueryExecution = new QueryExecution(spark, OneRowRelation())

    // Nothing!
    assert(qe.toString.contains("OneRowRelation"))

    // Throw an AnalysisException - this should be captured.
    spark.experimental.extraStrategies = Seq(
      new SparkStrategy {
        override def apply(plan: LogicalPlan): Seq[SparkPlan] =
          throw new AnalysisException("exception")
      })
    assert(qe.toString.contains("org.apache.spark.sql.AnalysisException"))

    // Throw an Error - this should not be captured.
    spark.experimental.extraStrategies = Seq(
      new SparkStrategy {
        override def apply(plan: LogicalPlan): Seq[SparkPlan] =
          throw new Error("error")
      })
    val error = intercept[Error](qe.toString)
    assert(error.getMessage.contains("error"))
  }
}


text:
__author__ = 'Marten Fischer (m.fischer@hs-osnabrueck.de)'

from virtualisation.misc.jsonobject import JSONObject
import copy
import _strptime # A bug in Python, that may cause a AttributeError (http://stackoverflow.com/questions/2427240/thread-safe-equivalent-to-pythons-time-strptime)
import datetime
import uuid

class SensorDescription(JSONObject):
    def __init__(self, obj=None):
        super(SensorDescription, self).__init__(obj)

    def deepcopy(self):
        return SensorDescription(copy.deepcopy(self.__dict__["data"]))

    def __deepcopy__(self, memo):
        return SensorDescription(copy.deepcopy(self.__dict__["data"]))

    def test(self):

        # default projection system
        if not "location_epsg" in self.__dict__["data"]:
            self.__dict__["data"]["location_epsg"] = None

        # flag to avoid publishing observations on the messagebus
        if not "no_publish_messagebus" in self.__dict__["data"]:
            self.__dict__["data"]["no_publish_messagebus"] = False

        if not "uuid" in self.__dict__["data"]:
            if "fullSensorID" in self.__dict__["data"]:
                self.__dict__["data"]["uuid"] = str(uuid.uuid5(uuid.NAMESPACE_URL, self.fullSensorID))
            else:
                self.__dict__["data"]["uuid"] = str(uuid.uuid4())
        else:
            if isinstance(self.uuid, int):
                self.uuid = str(self.uuid)

        required = ["sensorName",  "author", "source", "sensorType", "sourceType", "sourceFormat", "information", "sensorID", "fullSensorID", "uuid", "location", "movementBuffer", "updateInterval", "fields", "messagebus", "namespace", "location_epsg"]
        for r in required:
            if not r in self.__dict__["data"]:
                raise Exception("invalid sensor description. Property " + r + " is required.")

        required = ["propertyName", "propertyURI", "dataType"]
        required_datatype = {"str": [], "int": ["min", "max"], "long": ["min", "max"], "float": ["min", "max"], "datetime.datetime": ["min", "format"], "enum": []}
        for f in self.fields:
            if not "aggregationMethod" in self.field[f]:
                self.field[f].aggregagationMethod = None
            if not "showOnCityDashboard" in self.field[f]:
                self.field[f].showOnCityDashboard = False
            for r in required:
                if r not in self.field[f]:
                    raise Exception("invalid sensor description. " + f + " requires field-property" + r + ".")
            # at this point we can be sure there is a 'dataType'
            # let's see if all required attributes for the dataType are present
            for r in required_datatype[self.field[f].dataType]:
                if r not in self.field[f]:
                    raise Exception("The attribute %s is required for dataType %s" % (r, self.field[f].dataType))

        valid_epsg = [None, 4326, 31700]
        if not self.location_epsg in valid_epsg:
            raise Exception("Invalid EPSG. Only " + ", ".join(valid_epsg) + " are supported.")

        # After a telco with Dan and Ioana we agreed to provide the descriptions of all fields also in an array
        # instead of a dictionary. This will allow them to use popular libraries such as GSON to parse the JSON
        # response. In addition each of the field-description in the list will get an attribute 'name', specifying
        # the fieldname.
        self.field_array = []
        for f in self.fields:
            field_description = self.field[f]
            field_description.name = f
            self.field_array.append(field_description)

    def isTimestampedStream(self):
        return "timestamp" in self.__dict__["data"] and "inField" in self.__dict__["data"]["timestamp"]

    def parseTimestamp(self, value):
        if self.timestamp.format == "UNIX5":
            if not isinstance(value, int):
                value = int(value)
            value = value / 1000
            return datetime.datetime.fromtimestamp(value)
        if self.timestamp.format == "UNIX":
            if not isinstance(value, int):
                value = int(value)
            return datetime.datetime.fromtimestamp(value)
        else:
            return datetime.datetime.strptime(value, self.timestamp.format)


text:
package com.luv2code.hibernate.demo;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.luv2code.hibernate.demo.entity.Student;

public class CreateStudentDemo {

	public static void main(String[] args) {

		// create session factory
		SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Student.class)
				.buildSessionFactory();

		// create session
		Session session = factory.getCurrentSession();

		try {
			// create a student object
			System.out.println("Creating new student object...");
			Student tempStudent = new Student("Paul", "Doe", "paul@luv2code.com");

			// start a transaction
			session.beginTransaction();

			// save the student object
			System.out.println("Saving the student...");
			session.save(tempStudent);

			// commit transaction
			session.getTransaction().commit();

			System.out.println("Done!");
		} finally {
			factory.close();
		}
	}

}


text:
//===- MCJITTest.cpp - Unit tests for the MCJIT ---------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This test suite verifies basic MCJIT functionality such as making function
// calls, using global variables, and compiling multpile modules.
//
//===----------------------------------------------------------------------===//

#include "llvm/ExecutionEngine/MCJIT.h"
#include "MCJITTestBase.h"
#include "gtest/gtest.h"

using namespace llvm;

namespace {

class MCJITTest : public testing::Test, public MCJITTestBase {
protected:
  void SetUp() override { M.reset(createEmptyModule("<main>")); }
};

// FIXME: Ensure creating an execution engine does not crash when constructed
//        with a null module.
/*
TEST_F(MCJITTest, null_module) {
  createJIT(0);
}
*/

// FIXME: In order to JIT an empty module, there needs to be
// an interface to ExecutionEngine that forces compilation but
// does not require retrieval of a pointer to a function/global.
/*
TEST_F(MCJITTest, empty_module) {
  createJIT(M.take());
  //EXPECT_NE(0, TheJIT->getObjectImage())
  //  << "Unable to generate executable loaded object image";
}
*/

TEST_F(MCJITTest, global_variable) {
  SKIP_UNSUPPORTED_PLATFORM;

  int initialValue = 5;
  GlobalValue *Global = insertGlobalInt32(M.get(), "test_global", initialValue);
  createJIT(std::move(M));
  void *globalPtr =  TheJIT->getPointerToGlobal(Global);
  EXPECT_TRUE(nullptr != globalPtr)
    << "Unable to get pointer to global value from JIT";

  EXPECT_EQ(initialValue, *(int32_t*)globalPtr)
    << "Unexpected initial value of global";
}

TEST_F(MCJITTest, add_function) {
  SKIP_UNSUPPORTED_PLATFORM;

  Function *F = insertAddFunction(M.get());
  createJIT(std::move(M));
  uint64_t addPtr = TheJIT->getFunctionAddress(F->getName().str());
  EXPECT_TRUE(0 != addPtr)
    << "Unable to get pointer to function from JIT";

  ASSERT_TRUE(addPtr != 0) << "Unable to get pointer to function .";
  int (*AddPtr)(int, int) = (int(*)(int, int))addPtr ;
  EXPECT_EQ(0,   AddPtr(0, 0));
  EXPECT_EQ(1,   AddPtr(1, 0));
  EXPECT_EQ(3,   AddPtr(1, 2));
  EXPECT_EQ(-5,  AddPtr(-2, -3));
  EXPECT_EQ(30,  AddPtr(10, 20));
  EXPECT_EQ(-30, AddPtr(-10, -20));
  EXPECT_EQ(-40, AddPtr(-10, -30));
}

TEST_F(MCJITTest, run_main) {
  SKIP_UNSUPPORTED_PLATFORM;

  int rc = 6;
  Function *Main = insertMainFunction(M.get(), 6);
  createJIT(std::move(M));
  uint64_t ptr = TheJIT->getFunctionAddress(Main->getName().str());
  EXPECT_TRUE(0 != ptr)
    << "Unable to get pointer to main() from JIT";

  int (*FuncPtr)(void) = (int(*)(void))ptr;
  int returnCode = FuncPtr();
  EXPECT_EQ(returnCode, rc);
}

TEST_F(MCJITTest, return_global) {
  SKIP_UNSUPPORTED_PLATFORM;

  int32_t initialNum = 7;
  GlobalVariable *GV = insertGlobalInt32(M.get(), "myglob", initialNum);

  Function *ReturnGlobal = startFunction<int32_t(void)>(M.get(),
                                                        "ReturnGlobal");
  Value *ReadGlobal = Builder.CreateLoad(GV);
  endFunctionWithRet(ReturnGlobal, ReadGlobal);

  createJIT(std::move(M));
  uint64_t rgvPtr = TheJIT->getFunctionAddress(ReturnGlobal->getName().str());
  EXPECT_TRUE(0 != rgvPtr);

  int32_t(*FuncPtr)(void) = (int32_t(*)(void))rgvPtr;
  EXPECT_EQ(initialNum, FuncPtr())
    << "Invalid value for global returned from JITted function";
}

// FIXME: This case fails due to a bug with getPointerToGlobal().
// The bug is due to MCJIT not having an implementation of getPointerToGlobal()
// which results in falling back on the ExecutionEngine implementation that
// allocates a new memory block for the global instead of using the same
// global variable that is emitted by MCJIT. Hence, the pointer (gvPtr below)
// has the correct initial value, but updates to the real global (accessed by
// JITted code) are not propagated. Instead, getPointerToGlobal() should return
// a pointer into the loaded ObjectImage to reference the emitted global.
/*
TEST_F(MCJITTest, increment_global) {
  SKIP_UNSUPPORTED_PLATFORM;

  int32_t initialNum = 5;
  Function *IncrementGlobal = startFunction<int32_t(void)>(M.get(), "IncrementGlobal");
  GlobalVariable *GV = insertGlobalInt32(M.get(), "my_global", initialNum);
  Value *DerefGV = Builder.CreateLoad(GV);
  Value *AddResult = Builder.CreateAdd(DerefGV,
                                       ConstantInt::get(Context, APInt(32, 1)));
  Builder.CreateStore(AddResult, GV);
  endFunctionWithRet(IncrementGlobal, AddResult);

  createJIT(M.take());
  void *gvPtr = TheJIT->getPointerToGlobal(GV);
  EXPECT_EQ(initialNum, *(int32_t*)gvPtr);

  void *vPtr = TheJIT->getFunctionAddress(IncrementGlobal->getName().str());
  EXPECT_TRUE(0 != vPtr)
    << "Unable to get pointer to main() from JIT";

  int32_t(*FuncPtr)(void) = (int32_t(*)(void))(intptr_t)vPtr;

  for(int i = 1; i < 3; ++i) {
    int32_t result = FuncPtr();
    EXPECT_EQ(initialNum + i, result);            // OK
    EXPECT_EQ(initialNum + i, *(int32_t*)gvPtr);  // FAILS
  }
}
*/

// PR16013: XFAIL this test on ARM, which currently can't handle multiple relocations.
#if !defined(__arm__)

TEST_F(MCJITTest, multiple_functions) {
  SKIP_UNSUPPORTED_PLATFORM;

  unsigned int numLevels = 23;
  int32_t innerRetVal= 5;

  Function *Inner = startFunction<int32_t(void)>(M.get(), "Inner");
  endFunctionWithRet(Inner, ConstantInt::get(Context, APInt(32, innerRetVal)));

  Function *Outer;
  for (unsigned int i = 0; i < numLevels; ++i) {
    std::stringstream funcName;
    funcName << "level_" << i;
    Outer = startFunction<int32_t(void)>(M.get(), funcName.str());
    Value *innerResult = Builder.CreateCall(Inner);
    endFunctionWithRet(Outer, innerResult);

    Inner = Outer;
  }

  createJIT(std::move(M));
  uint64_t ptr = TheJIT->getFunctionAddress(Outer->getName().str());
  EXPECT_TRUE(0 != ptr)
    << "Unable to get pointer to outer function from JIT";

  int32_t(*FuncPtr)(void) = (int32_t(*)(void))ptr;
  EXPECT_EQ(innerRetVal, FuncPtr())
    << "Incorrect result returned from function";
}

#endif /*!defined(__arm__)*/

TEST_F(MCJITTest, multiple_decl_lookups) {
  SKIP_UNSUPPORTED_PLATFORM;

  Function *Foo = insertExternalReferenceToFunction<void(void)>(M.get(), "_exit");
  createJIT(std::move(M));
  void *A = TheJIT->getPointerToFunction(Foo);
  void *B = TheJIT->getPointerToFunction(Foo);

  EXPECT_TRUE(A != 0) << "Failed lookup - test not correctly configured.";
  EXPECT_EQ(A, B) << "Repeat calls to getPointerToFunction fail.";
}

}


text:
namespace android.content.pm
{
	[global::MonoJavaBridge.JavaClass()]
	public partial class ServiceInfo : android.content.pm.ComponentInfo, android.os.Parcelable
	{
		internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
		static ServiceInfo()
		{
			InitJNI();
		}
		protected ServiceInfo(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
		{
		}
		internal static global::MonoJavaBridge.MethodId _toString2180;
		public override global::java.lang.String toString()
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (!IsClrObject)
				return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.pm.ServiceInfo._toString2180)) as java.lang.String;
			else
				return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.pm.ServiceInfo.staticClass, global::android.content.pm.ServiceInfo._toString2180)) as java.lang.String;
		}
		internal static global::MonoJavaBridge.MethodId _dump2181;
		public virtual void dump(android.util.Printer arg0, java.lang.String arg1)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (!IsClrObject)
				@__env.CallVoidMethod(this.JvmHandle, global::android.content.pm.ServiceInfo._dump2181, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
			else
				@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.pm.ServiceInfo.staticClass, global::android.content.pm.ServiceInfo._dump2181, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
		}
		internal static global::MonoJavaBridge.MethodId _writeToParcel2182;
		public override void writeToParcel(android.os.Parcel arg0, int arg1)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (!IsClrObject)
				@__env.CallVoidMethod(this.JvmHandle, global::android.content.pm.ServiceInfo._writeToParcel2182, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
			else
				@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.pm.ServiceInfo.staticClass, global::android.content.pm.ServiceInfo._writeToParcel2182, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
		}
		internal static global::MonoJavaBridge.MethodId _describeContents2183;
		public virtual int describeContents()
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (!IsClrObject)
				return @__env.CallIntMethod(this.JvmHandle, global::android.content.pm.ServiceInfo._describeContents2183);
			else
				return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.pm.ServiceInfo.staticClass, global::android.content.pm.ServiceInfo._describeContents2183);
		}
		internal static global::MonoJavaBridge.MethodId _ServiceInfo2184;
		public ServiceInfo()  : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.pm.ServiceInfo.staticClass, global::android.content.pm.ServiceInfo._ServiceInfo2184);
			Init(@__env, handle);
		}
		internal static global::MonoJavaBridge.MethodId _ServiceInfo2185;
		public ServiceInfo(android.content.pm.ServiceInfo arg0)  : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.pm.ServiceInfo.staticClass, global::android.content.pm.ServiceInfo._ServiceInfo2185, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
			Init(@__env, handle);
		}
		internal static global::MonoJavaBridge.FieldId _permission2186;
		public global::java.lang.String permission
		{
			get
			{
				return default(global::java.lang.String);
			}
			set
			{
			}
		}
		internal static global::MonoJavaBridge.FieldId _CREATOR2187;
		public static global::android.os.Parcelable_Creator CREATOR
		{
			get
			{
				return default(global::android.os.Parcelable_Creator);
			}
		}
		private static void InitJNI()
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			global::android.content.pm.ServiceInfo.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/pm/ServiceInfo"));
			global::android.content.pm.ServiceInfo._toString2180 = @__env.GetMethodIDNoThrow(global::android.content.pm.ServiceInfo.staticClass, "toString", "()Ljava/lang/String;");
			global::android.content.pm.ServiceInfo._dump2181 = @__env.GetMethodIDNoThrow(global::android.content.pm.ServiceInfo.staticClass, "dump", "(Landroid/util/Printer;Ljava/lang/String;)V");
			global::android.content.pm.ServiceInfo._writeToParcel2182 = @__env.GetMethodIDNoThrow(global::android.content.pm.ServiceInfo.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V");
			global::android.content.pm.ServiceInfo._describeContents2183 = @__env.GetMethodIDNoThrow(global::android.content.pm.ServiceInfo.staticClass, "describeContents", "()I");
			global::android.content.pm.ServiceInfo._ServiceInfo2184 = @__env.GetMethodIDNoThrow(global::android.content.pm.ServiceInfo.staticClass, "<init>", "()V");
			global::android.content.pm.ServiceInfo._ServiceInfo2185 = @__env.GetMethodIDNoThrow(global::android.content.pm.ServiceInfo.staticClass, "<init>", "(Landroid/content/pm/ServiceInfo;)V");
		}
	}
}


text:
<?php
/*
Plugin Name: Demo Tax meta class
Plugin URI: http://en.bainternet.info
Description: Tax meta class usage demo
Version: 2.0.2
Author: Bainternet, Ohad Raz
Author URI: http://en.bainternet.info
*/

//include the main class file
require_once("Tax-meta-class/Tax-meta-class.php");
if (is_admin()){
  /*
   * prefix of meta keys, optional
   */
  $prefix = 'ba_';
  /*
   * configure your meta box
   */
  $config = array(
    'id' => 'demo_meta_box',          // meta box id, unique per meta box
    'title' => 'Demo Meta Box',          // meta box title
    'pages' => array('category'),        // taxonomy name, accept categories, post_tag and custom taxonomies
    'context' => 'normal',            // where the meta box appear: normal (default), advanced, side; optional
    'fields' => array(),            // list of meta fields (can be added by field arrays)
    'local_images' => false,          // Use local or hosted images (meta box images for add/remove)
    'use_with_theme' => false          //change path if used with theme set to true, false for a plugin or anything else for a custom path(default false).
  );

  /*
   * Initiate your meta box
   */
  $my_meta =  new Tax_Meta_Class($config);

  /*
   * Add fields to your meta box
   */

  //text field
  $my_meta->addText($prefix.'text_field_id',array('name'=> __('My Text ','tax-meta'),'desc' => 'this is a field desription'));
  //textarea field
  $my_meta->addTextarea($prefix.'textarea_field_id',array('name'=> __('My Textarea ','tax-meta')));
  //checkbox field
  $my_meta->addCheckbox($prefix.'checkbox_field_id',array('name'=> __('My Checkbox ','tax-meta')));
  //select field
  $my_meta->addSelect($prefix.'select_field_id',array('selectkey1'=>'Select Value1','selectkey2'=>'Select Value2'),array('name'=> __('My select ','tax-meta'), 'std'=> array('selectkey2')));
  //radio field
  $my_meta->addRadio($prefix.'radio_field_id',array('radiokey1'=>'Radio Value1','radiokey2'=>'Radio Value2'),array('name'=> __('My Radio Filed','tax-meta'), 'std'=> array('radionkey2')));
  //date field
  $my_meta->addDate($prefix.'date_field_id',array('name'=> __('My Date ','tax-meta')));
  //Time field
  $my_meta->addTime($prefix.'time_field_id',array('name'=> __('My Time ','tax-meta')));
  //Color field
  $my_meta->addColor($prefix.'color_field_id',array('name'=> __('My Color ','tax-meta')));
  //Image field
  $my_meta->addImage($prefix.'image_field_id',array('name'=> __('My Image ','tax-meta')));
  //file upload field
  $my_meta->addFile($prefix.'file_field_id',array('name'=> __('My File ','tax-meta')));
  //wysiwyg field
  $my_meta->addWysiwyg($prefix.'wysiwyg_field_id',array('name'=> __('My wysiwyg Editor ','tax-meta')));
  //taxonomy field
  $my_meta->addTaxonomy($prefix.'taxonomy_field_id',array('taxonomy' => 'category'),array('name'=> __('My Taxonomy ','tax-meta')));
  //posts field
  $my_meta->addPosts($prefix.'posts_field_id',array('args' => array('post_type' => 'page')),array('name'=> __('My Posts ','tax-meta')));

  /*
   * To Create a reapeater Block first create an array of fields
   * use the same functions as above but add true as a last param
   */

  $repeater_fields[] = $my_meta->addText($prefix.'re_text_field_id',array('name'=> __('My Text ','tax-meta')),true);
  $repeater_fields[] = $my_meta->addTextarea($prefix.'re_textarea_field_id',array('name'=> __('My Textarea ','tax-meta')),true);
  $repeater_fields[] = $my_meta->addCheckbox($prefix.'re_checkbox_field_id',array('name'=> __('My Checkbox ','tax-meta')),true);
  $repeater_fields[] = $my_meta->addImage($prefix.'image_field_id',array('name'=> __('My Image ','tax-meta')),true);

  /*
   * Then just add the fields to the repeater block
   */
  //repeater block
  $my_meta->addRepeaterBlock($prefix.'re_',array('inline' => true, 'name' => __('This is a Repeater Block','tax-meta'),'fields' => $repeater_fields));
  /*
   * Don't Forget to Close up the meta box decleration
   */
  //Finish Meta Box Decleration
  $my_meta->Finish();
}


text:
class ServiceHasManyItineraries < ActiveRecord::Migration[5.0]
  def change
    add_reference :itineraries, :service, index: true, foreign_key: true
  end
end


text:
'use strict';

function cdUserProfileCtrl($scope, $rootScope, $state, auth, cdUsersService, cdDojoService, alertService,
  $translate, profile, utils, loggedInUser, usersDojos, $stateParams, hiddenFields,
  Upload, cdBadgesService, utilsService, initUserTypes, cdProgrammingLanguagesService,
  agreement ,championsForUser, parentsForUser, badgeCategories, dojoAdminsForUser, $window, usSpinnerService, atomicNotifyService, $timeout) {

  if(profile.err || loggedInUser.err || usersDojos.err || hiddenFields.err || agreement.err){
    alertService.showError($translate.instant('error.general'));
    return;
  }

  $scope.currentStateName = $state.current.name;

  if ($stateParams.showBannerMessage) {
    atomicNotifyService.info($translate.instant('Please complete your profile before continuing.'), 5000);
  }

  $scope.$on('$destroy', function(){
    atomicNotifyService.dismissAll();
  });

  $scope.editMode = false;
  var profileUserId = $state.params.userId;
  var loggedInUserId = loggedInUser.data && loggedInUser.data.id;
  var getHighestUserType = utilsService.getHighestUserType;

  if($state.current.name === 'edit-user-profile') {
    if(profileUserId === loggedInUserId || loggedInUserIsParent()) {
      $scope.editMode = true;
      $scope.inviteNinjaPopover = {
        title: $translate.instant('Invite Ninja over 13'),
        templateUrl: '/profiles/template/invite-ninja-over-13',
        placement: 'top',
        placeholder: $translate.instant('Enter Ninja Email Address'),
        show: false
      };
    } else {
      //No permission
      $state.go('error-404-no-headers');
    }
  }

  if($state.current.name === 'add-child') {
    if($state.params.parentId === loggedInUserId) {
      $scope.editMode = true;
    } else {
      //No permission
      $state.go('error-404-no-headers');
    }
  }

  $scope.upload = function (files) {
    if($scope.profile.id) {
      if (files && files.length) {
        for (var i = 0; i < files.length; i++) {
          var file = files[i];
          Upload.upload({
            url: '/api/1.0/profiles/change-avatar',
            headers : {
              'Content-Type': 'multipart/form-data'
            },
            file: file,
            fields: {profileId: profile.data.id, fileName: file.name, fileType: file.type}
          }).progress(function (evt) {
          }).success(function (data, status, headers, config) {
            cdUsersService.getAvatar($scope.profile.id, function(response){
              $scope.profile.avatar = 'data:' + response.imageInfo.type + ';base64,' + response.imageData;
            })
          }).error(function (data, status, headers, config) {
            alertService.showError($translate.instant('There was an error uploading your profile picture.'));
          });
        }
      }
    }
  };

  $scope.hiddenFields =  getHiddenFields(hiddenFields.data, profile.data.userTypes);
  $scope.badgeInfo = {};
  $scope.badgeInfoIsCollapsed = {};
  var lastClicked = {};

  function getHiddenFields(hiddenFields, userTypes){
    var retHiddenFields = [];

    _.each(userTypes, function(userType){
      var filteredFields = _.filter(hiddenFields, function(hiddenField){
        return _.contains(hiddenField.allowedUserTypes, userType);
      });

      retHiddenFields = _.union(retHiddenFields, filteredFields);
    });

    return retHiddenFields;
  }

  $scope.hasAccess = utils.hasAccess;

  if(profile.data.dob) profile.data.formattedDateOfBirth = moment(profile.data.dob).format('DD MMMM YYYY');
  $scope.highestUserType = getHighestUserType(profile.data.userTypes);
  var userTypeFound = _.find(initUserTypes.data, function (initUserType) {
    return initUserType.name === $scope.highestUserType;
  });

  if(userTypeFound) {
    switch(userTypeFound.title) {
      case 'Ninja Under 13':
        userTypeFound.title = $translate.instant('Ninja');
        break;
      case 'Ninja Over 13':
        userTypeFound.title = $translate.instant('Ninja');
        break;
    }
    profile.data.userTypeTitle = userTypeFound.title;
  }

  $scope.isPrivate = profile.data.private;

  //Load user's badges
  $scope.categories = [];
  $scope.badges = {};
  var profileBadges = angular.copy(profile.data.badges);

  _.each(badgeCategories.data.categories, function (mainCategory) {
    _.each(profileBadges, function (badge) {
      if(badge.status === 'accepted') {
        var indexFound;
        var mainCategoryFound = _.find(badge.tags, function (tag, index) {
          indexFound = index;
          return tag.value === mainCategory;
        });
        badge.formattedDateAccepted = moment(badge.dateAccepted).format('Do MMMM YYYY');
        if(mainCategoryFound) {
          badge.tags.splice(indexFound, 1);
          if(!$scope.badges[mainCategoryFound.value]) $scope.badges[mainCategoryFound.value] = {};
          _.each(badge.tags, function (tag) {
            if(!$scope.badges[mainCategoryFound.value][tag.value]) $scope.badges[mainCategoryFound.value][tag.value] = [];
            $scope.badges[mainCategoryFound.value][tag.value].push(badge);
          });
          var categoryAdded = _.find($scope.categories, function (category) {
            return category === mainCategoryFound.value;
          });
          if(!categoryAdded) $scope.categories.push(mainCategoryFound.value);
        }
      }
    });
  });

  $scope.profile = profile.data;

  cdUsersService.getAvatar($scope.profile.id, function(response){
    if(!_.isEmpty(response)) {
      $scope.profile.avatar = 'data:' + response.imageInfo.type + ';base64,' + response.imageData;
    }
  });

  $scope.capitalizeFirstLetter = utilsService.capitalizeFirstLetter;

  $scope.showBadgeInfo = function (tag, badge) {
    if(lastClicked[tag] !== badge.id && $scope.badgeInfoIsCollapsed[tag]) {
      $scope.badgeInfo[tag] = badge;
    } else {
      $scope.badgeInfo[tag] = badge;
      $scope.badgeInfoIsCollapsed[tag] = !$scope.badgeInfoIsCollapsed[tag];
    }
    lastClicked[tag] = badge.id;
  }

  $scope.loggedInUser = loggedInUser.data;

  $scope.loadProgrammmingLanguagesTags = function(query) {
    return cdProgrammingLanguagesService.get();
  };

  $scope.inviteParent = function(data){
    var win = function(response){
      if(response.ok === false) return alertService.showError($translate.instant(response.why));
      return alertService.showAlert($translate.instant('Invitation was sent successfully.'));
    };

    var fail = function(){
      alertService.showError($translate.instant('An error has occurred while sending invitation') );
    };

    data.emailSubject = $translate.instant('Invitation to become a Parent/Guardian');
    cdUsersService.inviteParent(data, win, fail);
  };

  if($stateParams.userType){
    $scope.profile = {
      ownProfileFlag: true,
      userTypes: [$stateParams.userType]
    };
  }

  if(!_.isEmpty($scope.profile)){
    $scope.profile.programmingLanguages = utils.toTags($scope.profile.programmingLanguages);
    $scope.profile.languagesSpoken = utils.toTags($scope.profile.languagesSpoken);
    $scope.profile.private =  $scope.profile.private ? "true" : "false";

    $scope.profile.widget = {};
    $scope.profile.widget.programmingLanguages = utils.frTags($scope.profile.programmingLanguages);
    $scope.profile.widget.languagesSpoken = utils.frTags($scope.profile.languagesSpoken);
  }

  if(loggedInUser.data && $stateParams.userId){

    cdDojoService.dojosForUser($stateParams.userId, function (response) {
      $scope.dojos = response;
      if(_.isEmpty($scope.dojos)) {
        //This user has no Dojos.
        //Use init user type to setup profile.

        $scope.userType = loggedInUser.data.initUserType;
      } else {
        //Search usersdojos for highest user type
        findHighestUserType();
      }
    }, function (err) {
      alertService.showError( $translate.instant('Error loading Dojos') + ' ' + err);
    });
  }

  function findHighestUserType() {
    var highestTypeFound = false;

    function checkLinks(userType) {
      for(var i = 0; i < usersDojos.length; i++) {
        var userDojoLink = usersDojos[i];
        var userTypes = userDojoLink.userTypes;
        if(_.contains(userTypes, userType)) {
          highestTypeFound = true;
          return userType;
        }
      }
    }

    //If no champion found, search for next user type
    var searchForUserTypes = ['champion', 'mentor', 'parent-guardian', 'attendee-o13', 'attendee-u13'];

    _.each(searchForUserTypes, function (searchForUserType) {
      if(!highestTypeFound){
        $scope.userType = checkLinks(searchForUserType);
      }
    });

  }

  $scope.parentProfile = _.contains(profile.data.userTypes, 'parent-guardian');

  $scope.save = function(profile){
    _.each(['http://', 'https://', 'www.'], function(prefix){
      _.each(['linkedin', 'twitter'], function(field){
        // if prefixed, remove prefix
        if (profile[field]){
          var str = profile[field].toString();
          if (str.substring(0, prefix.length).indexOf(prefix) > -1) profile[field] = str.substring(prefix.length);
        }
      });
    });

    var profileCopy = angular.copy(profile);

    profileCopy = _.omit(profileCopy, ['countryName', 'countryNumber', 'ownProfileFlag', 'widget', 'dojos',
      'passwordConfirm', 'myChild', 'resolvedChildren', 'resolvedParents', 'isTicketingAdmin',
      'formattedDateOfBirth', 'userTypeTitle', 'requestingUserIsDojoAdmin']);

    if($stateParams.userType === 'attendee-o13' || $stateParams.userType === 'attendee-u13' || profile.myChild){
      saveYouthViaParent(profileCopy);
    } else {
      saveDirect(profileCopy);
    }
  };

  function saveYouthViaParent(profile){
    profile = _.omit(profile, ['dojos']);
    profile.programmingLanguages = profile.programmingLanguages && utils.frTags(profile.programmingLanguages);
    profile.languagesSpoken = profile.languagesSpoken && utils.frTags(profile.languagesSpoken);

    cdUsersService.saveYouthProfile(profile, function (response) {
      alertService.showAlert($translate.instant('Profile has been saved successfully'));
      $state.go('user-profile', {userId: response.userId});
    }, function(){
      alertService.showError($translate.instant('An error has occurred while saving profile'));
    });
  }

  function saveDirect(profile){
    profile = _.omit(profile, ['userTypes', 'dojos']);

    profile.programmingLanguages = profile.programmingLanguages && utils.frTags(profile.programmingLanguages);
    profile.languagesSpoken = profile.languagesSpoken && utils.frTags(profile.languagesSpoken);

    function win(profile){
      if(profile.ok === false) {
        alertService.showError($translate.instant(profile.why));
        $state.go('user-profile', {userId: $stateParams.userId});
      } else {
        $scope.profile = profile;
        $scope.profile.private =  $scope.profile.private ? "true" : "false";
        alertService.showAlert($translate.instant('Profile has been saved successfully'));
        auth.instance(function(data){
          if( data.user ) $rootScope.$broadcast('user-updated', data.user);
          $state.go('user-profile', {userId: $stateParams.userId});
        });
      }
    }

    function fail(){
      alertService.showError($translate.instant('An error has occurred while saving profile'));
    }

    cdUsersService.saveProfile(profile, win, fail);
  }

  $scope.toggleEdit = function(field){
    $scope[field] = $scope[field] ? false : true;
  };

  $scope.toggleMin = function() {
    $scope.minDate = $scope.minDate ? null : new Date();
  };
  $scope.toggleMin();

  $scope.picker = {opened: false};

  $scope.open = function ($event) {
    $event.preventDefault();
    $event.stopPropagation();
    $scope.picker.opened = true;
  };

  cdDojoService.listCountries(function(countries) {
    $scope.countries = countries;
  });

  var initialDate = new Date();
  initialDate.setFullYear(initialDate.getFullYear()-18);
  $scope.dobDateOptions = {
    formatYear: 'yyyy',
    startingDay: 1,
    'datepicker-mode': "'year'",
    initDate: initialDate
  };

  $scope.setCountry = function(profile, country) {
    profile.countryName = country.countryName;
    profile.countryNumber = country.countryNumber;
    profile.continent = country.continent;
    profile.alpha2 = country.alpha2;
    profile.alpha3 = country.alpha3;
  };

  $scope.getPlaces = function (countryCode, $select) {
    return utilsService.getPlaces(countryCode, $select).then(function (data) {
      $scope.places = data;
    }, function (err) {
      $scope.places = [];
      console.error(err);
    });
  }

  $scope.setPlace = function(profile, place) {
    profile.placeName = place.name;
    profile.placeGeonameId = place.geonameId;
    profile.county = {};
    profile.state = {};
    profile.city = {};
    for (var adminidx=1; adminidx<=4; adminidx++) {
      profile['admin'+ adminidx + 'Code'] = place['admin'+ adminidx + 'Code'];
      profile['admin'+ adminidx + 'Name'] = place['admin'+ adminidx + 'Name'];
    }
  };

  $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
  $scope.fullDateFormat = $scope.formats[0];
  $scope.today = new Date();

  $scope.validatePassword = function (password, email) {
    var validationResult = utilsService.validatePassword(password, email);
    if(!validationResult.valid) $scope.invalidPasswordMessage = $translate.instant(validationResult.msg);
    return validationResult.valid;
  }

  $scope.matchesPassword = function(password, passwordConfirm) {
    if(passwordConfirm !== password) {
      $scope.invalidConfirmPasswordMessage = $translate.instant('Passwords do not match');
      return false;
    }
    return true;
  }

  $scope.exportBadges = function () {
    cdBadgesService.exportBadges(function (response) {
      //TODO
    });
  }

  $scope.editProfile = function () {
    $state.go('edit-user-profile', {userId: $stateParams.userId});
  }

  $scope.viewProfile = function () {
    $state.go('user-profile', {userId: $stateParams.userId});
  }

  $scope.viewDojo = function(dojo) {
    var urlSlugArray = dojo.urlSlug.split('/');
    var country = urlSlugArray[0].toString();
    urlSlugArray.splice(0, 1);
    var path = urlSlugArray.join('/');
    $state.go('dojo-detail',{country:country, path:path});
  }

  $scope.profileVisible = function () {
    if($state.current.name === 'add-child') return true;
    var highestUserType = getHighestUserType(profile.data.userTypes);
    switch (highestUserType) {
      case 'champion':
        return true; //Always public
      case 'mentor':
        if($scope.profile.ownProfileFlag) return true;
        if(loggedInUserIsChampion()) return true;
        if(loggedInUserIsDojoAdmin()) return true;
        return !$scope.isPrivate;
      case 'parent-guardian':
        if($scope.profile.ownProfileFlag) return true;
        if(loggedInUserIsChampion()) return true;
        if(loggedInUserIsDojoAdmin()) return true;
        return false; //Always private
      case 'attendee-o13':
        if($scope.profile.ownProfileFlag) return true;
        if(loggedInUserIsChampion()) return true;
        if(loggedInUserIsDojoAdmin()) return true;
        if(loggedInUserIsParent()) return true;
        return !$scope.isPrivate;
      case 'attendee-u13':
        if($scope.profile.ownProfileFlag) return true;
        if(loggedInUserIsChampion()) return true;
        if(loggedInUserIsDojoAdmin()) return true;
        if(loggedInUserIsParent()) return true;
        return false; //Always private
      default:
        return false;
    }
  }

  function loggedInUserIsParent() {
    if(!loggedInUser.data) return false;
    return _.find(parentsForUser.data, function (parentForUser) {
      return parentForUser.id === loggedInUser.data.id;
    });
  }

  function loggedInUserIsChampion() {
    if(!loggedInUser.data) return false;
    return _.find(championsForUser.data, function (championForUser) {
      return championForUser.id === loggedInUser.data.id;
    });
  }

  function loggedInUserIsDojoAdmin() {
    if(!loggedInUser.data) return false;
    return _.find(dojoAdminsForUser.data, function (dojoAdminForUser) {
      return dojoAdminForUser.id === loggedInUser.data.id;
    });
  }

  $scope.hideProfileBlock = function (block) {
    if($scope.highestUserType === 'attendee-o13' || $scope.highestUserType === 'mentor') {
      if(loggedInUserIsChampion()) return false;
      if(loggedInUserIsDojoAdmin()) return false;
      if(loggedInUserIsParent()) return false;
      if($scope.profile.ownProfileFlag) return false;
      if(block && $scope.profile.optionalHiddenFields) {
        if(!$scope.profile.optionalHiddenFields[block]) return false;
        return true;
      }
      return true;
    }
    return false;
  }

  $scope.hideGeneralInfoBlock = function () {
    if(loggedInUserIsChampion()) return false;
    if(loggedInUserIsDojoAdmin()) return false;
    if(loggedInUserIsParent()) return false;
    if($scope.profile.ownProfileFlag) return false;
    return true;
  }

  $scope.canMakeProfilePrivate = function () {
    if($scope.highestUserType === 'attendee-o13' || $scope.highestUserType === 'mentor') return true;
    return false;
  }

  $scope.canUpdateHiddenField = function (hiddenField) {
    return _.contains(hiddenField.allowedUserTypes, $scope.highestUserType);
  }

  $scope.hideChampionProfileBlock = function (block) {
    if($scope.profile.ownProfileFlag) return false;
    if($scope.profile.optionalHiddenFields && $scope.profile.optionalHiddenFields[block]) return true;
    return false;
  }

  $scope.inviteNinja = function (ninjaEmail) {
    usSpinnerService.spin('user-profile-spinner');
    var ninjaData = {
      ninjaEmail: ninjaEmail,
      emailSubject: $translate.instant('Approve Parent Request')
    };
    cdUsersService.inviteNinja(ninjaData, function (response) {
      usSpinnerService.stop('user-profile-spinner');
      $scope.inviteNinjaPopover.show = false;
      $scope.inviteNinjaPopover.email = '';
      if(response.ok === false) return alertService.showError($translate.instant(response.why));
      return alertService.showAlert($translate.instant('Invite Sent'));
    }, function (err) {
      usSpinnerService.stop('user-profile-spinner');
      alertService.showError($translate.instant('Error inviting Ninja'));
      $scope.inviteNinjaPopover.show = false;
      $scope.inviteNinjaPopover.email = '';
    });
  }

  $scope.toggleInviteNinjaPopover = function () {
    $scope.inviteNinjaPopover.show = !$scope.inviteNinjaPopover.show;
  }

}

angular.module('cpZenPlatform')
  .controller('user-profile-controller', ['$scope', '$rootScope', '$state', 'auth', 'cdUsersService', 'cdDojoService', 'alertService',
    '$translate', 'profile', 'utilsService', 'loggedInUser', 'usersDojos', '$stateParams',
    'hiddenFields', 'Upload', 'cdBadgesService', 'utilsService', 'initUserTypes', 'cdProgrammingLanguagesService',
    'agreement','championsForUser', 'parentsForUser', 'badgeCategories', 'dojoAdminsForUser', '$window', 'usSpinnerService', 'atomicNotifyService', '$timeout', cdUserProfileCtrl]);


text:
package org.apereo.cas.util.crypto;

import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

/**
 * This tests {@link GlibcCryptPasswordEncoder}.
 *
 * @author Martin Böhmer
 * @since 5.3.10
 */
@Slf4j
@Tag("PasswordOps")
public class GlibcCryptPasswordEncoderTests {

    private static final String PASSWORD_CLEAR = "12345abcDEF!$";

    @Test
    public void sha512EncodingTest() {
        assertTrue(testEncodingRoundtrip("SHA-512"));
        assertTrue(testEncodingRoundtrip("6"));
        assertTrue(testMatchWithDifferentSalt("SHA-512",
            "$6$rounds=1000$df273de606d3609a$GAPcq.K4jO3KkfusCM7Zr8Cci4qf.jOsWj5hkGBpwRg515bKk93afAXHy/lg.2LPr8ZItHoR3AR5X3XOXndZI0"));
    }

    @Test
    public void ha256EncodingTest() {
        assertTrue(testEncodingRoundtrip("SHA-256"));
        assertTrue(testEncodingRoundtrip("5"));
        assertTrue(testMatchWithDifferentSalt("SHA-256", "$5$rounds=1000$e98244bb01b64f47$2qphrK8axtGjgmCJFYwaH7czw5iK9feLl7tKjyTlDy0"));
    }

    @Test
    public void md5EncodingTest() {
        assertTrue(testEncodingRoundtrip("MD5"));
        assertTrue(testEncodingRoundtrip("1"));
        assertTrue(testMatchWithDifferentSalt("MD5", "$1$c4676fd0$HOHZ2CYp45lZAAQyvF4C21"));
    }

    @Test
    public void desUnixCryptEncodingTest() {
        assertTrue(testEncodingRoundtrip("aB"));
        assertTrue(testEncodingRoundtrip("42xyz"));
        assertTrue(testMatchWithDifferentSalt("aB", "aB4fMcNOggJoQ"));
    }

    @Test
    public void verifyBadInput() {
        val encoder = new GlibcCryptPasswordEncoder(null, 0, null);
        assertNull(encoder.encode(null));
        assertNull(encoder.encode("password"));
        assertFalse(encoder.matches("rawPassword", null));
    }

    @Test
    public void verifyNoSalt() {
        val encoder = new GlibcCryptPasswordEncoder("MD5", 10, "secret");
        assertNotNull(encoder.encode("value"));
    }

    private static boolean testEncodingRoundtrip(final String algorithm) {
        val encoder = new GlibcCryptPasswordEncoder(algorithm, 0, null);

        val passwordHash = encoder.encode(PASSWORD_CLEAR);
        LOGGER.debug("Password [{}] was encoded by algorithm [{}] to hash [{}]", PASSWORD_CLEAR, algorithm, passwordHash);

        val match = encoder.matches(PASSWORD_CLEAR, passwordHash);
        LOGGER.debug("Does password [{}] match original password [{}]: [{}]", passwordHash, PASSWORD_CLEAR, match);

        return match;
    }

    private static boolean testMatchWithDifferentSalt(final String algorithm, final String encodedPassword) {
        val encoder = new GlibcCryptPasswordEncoder(algorithm, 0, null);
        val match = encoder.matches(PASSWORD_CLEAR, encodedPassword);
        LOGGER.debug("Does password [{}] match original password [{}]: [{}]", encodedPassword, PASSWORD_CLEAR, match);
        return match;
    }

}


text:
export var BAR_MAP = {
  vertical: {
    offset: 'offsetHeight',
    scroll: 'scrollTop',
    scrollSize: 'scrollHeight',
    size: 'height',
    key: 'vertical',
    axis: 'Y',
    client: 'clientY',
    direction: 'top'
  },
  horizontal: {
    offset: 'offsetWidth',
    scroll: 'scrollLeft',
    scrollSize: 'scrollWidth',
    size: 'width',
    key: 'horizontal',
    axis: 'X',
    client: 'clientX',
    direction: 'left'
  }
};

export function renderThumbStyle(_ref) {
  var move = _ref.move,
      size = _ref.size,
      bar = _ref.bar;

  var style = {};
  var translate = 'translate' + bar.axis + '(' + move + '%)';

  style[bar.size] = size;
  style.transform = translate;
  style.msTransform = translate;
  style.WebkitTransform = translate;

  return style;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using QuantConnect.Indicators;
using QuantConnect.Data.Market;

namespace QuantConnect.Tests.Indicators
{
    [TestFixture]
    public class VolumeWeightedAveragePriceIndicatorTests
    {
        [Test]
        public void VWAPComputesCorrectly()
        {
            const int period = 4;
            const int volume = 100;
            var ind = new VolumeWeightedAveragePriceIndicator(period);
            var data = new[] {1m, 10m, 100m, 1000m, 10000m, 1234m, 56789m};

            var seen = new List<decimal>();
            for (int i = 0; i < data.Length; i++)
            {
                var datum = data[i];
                seen.Add(datum);
                ind.Update(new TradeBar(DateTime.Now.AddSeconds(i), "SPY", datum, datum, datum, datum, volume));
                // When volume is constant, VWAP is a simple moving average
                Assert.AreEqual(Enumerable.Reverse(seen).Take(period).Average(), ind.Current.Value);
            }
        }

        [Test]
        public void IsReadyAfterPeriodUpdates()
        {
            var ind = new VolumeWeightedAveragePriceIndicator(3);

            ind.Update(new TradeBar(DateTime.UtcNow, "SPY", 1m, 1m, 1m, 1m, 1));
            ind.Update(new TradeBar(DateTime.UtcNow, "SPY", 1m, 1m, 1m, 1m, 1));
            Assert.IsFalse(ind.IsReady);
            ind.Update(new TradeBar(DateTime.UtcNow, "SPY", 1m, 1m, 1m, 1m, 1));
            Assert.IsTrue(ind.IsReady);
        }

        [Test]
        public void ResetsProperly()
        {
            var ind = new VolumeWeightedAveragePriceIndicator(50);

            foreach (var data in TestHelper.GetTradeBarStream("spy_with_vwap.txt"))
            {
                ind.Update(data);
            }
            Assert.IsTrue(ind.IsReady);

            ind.Reset();

            TestHelper.AssertIndicatorIsInDefaultState(ind);
            ind.Update(new TradeBar(DateTime.UtcNow, "SPY", 2m, 2m, 2m, 2m, 1));
            Assert.AreEqual(ind.Current.Value, 2m);
        }

        [Test]
        public void CompareAgainstExternalData()
        {
            var ind = new VolumeWeightedAveragePriceIndicator(50);
            TestHelper.TestIndicator(ind, "spy_with_vwap.txt", "Moving VWAP 50",
                (x, expected) => Assert.AreEqual(expected, (double)((VolumeWeightedAveragePriceIndicator)x).Current.Value, 1e-3));

        }
    }
}


text:
layout: post
title: "Jenius Engineer reading list #198"
author: "dedenf"
tags:
    - news
    - jenius

categories:
    - readinglist
    - engineer
published: true
---

- [Infrastructure Development Environment -- A docker image that contains the necessary tools for doing Infrastructure Development](https://github.com/shawnxlw/infra-dev-env)
- [8 Ruby frameworks that aren't Rails](https://naturaily.com/blog/8-frameworks-ruby-not-rails)
- [Creating Raspberry Pi applications with Raylib and Ruby](https://medium.com/@avik.das/creating-raspberry-pi-applications-with-raylib-and-ruby-fba3d35b2877)
- [Enjoy a slice of QUIC, and Rust!](https://blog.cloudflare.com/enjoy-a-slice-of-quic-and-rust/)
- [Scylla Summit Video: Grab and Scylla Driving Southeast Asia Forward](https://www.scylladb.com/2019/01/21/scylla-summit-video-grab-and-scylla-driving-southeast-asia-forward/)
- [Sail - lightweight Rails engine for admin panel](https://github.com/vinistock/sail)


text:
require 'rmagick'
require 'fileutils'
require 'yaml'
require 'pry'
require_relative "nakal/version"
require_relative 'nakal/base_screen'
require_relative 'nakal/android/screen'
require_relative 'nakal/ios/screen'
require_relative 'nakal/dsl'

module Nakal

  class<<self
    attr_accessor :device_name, :directory, :platform, :image_location, :default_crop_params
    attr_accessor :diff_screens, :embed_screenshot, :timeout, :image_relative_dir, :fuzz, :config_location

    def configure
      yield self
    end

    def create_image_dir image_relative_dir
      @image_relative_dir = image_relative_dir
      @image_location = "#{@directory}/#{@device_name}/#{image_relative_dir}"
      FileUtils.mkdir_p @image_location unless File.directory?(@image_location)
    end

    def load_config
      @default_crop_params ||= YAML.load(File.open Nakal.config_location)
    end

    def set relative_location
      create_image_dir relative_location
      load_config
    end

    def current_platform
      Nakal.const_get Nakal.platform.capitalize
    end

  end
end

Nakal.configure do |config|
  config.device_name = "default_device"
  config.directory = "baseline_images"
  config.config_location = "./config/nakal.yml"
  config.embed_screenshot = false
  config.diff_screens = []
  config.timeout = 30
  config.fuzz = 10
end