text:
engine('handlebars', (function () {
    var renderData, partials, init, page, render, meta, partialsDir, renderJS, renderCSS,
        pagesDir, populate, serialize, globals, theme, renderersDir, helpersDir, translate, evalCode,
        languages = {},
        caramelData = 'X-Caramel-Data',
        CaramelCompiledTemplates = 'X-Compiled-Templates',
        log = new Log(),
        Handlebars = require('handlebars').Handlebars;

    evalCode = function (code, data, theme) {
        var template,
            file = new File(theme.resolve.call(theme, 'code/' + code));
        file.open('r');
        template = Handlebars.compile(file.readAll());
        file.close();
        return template(data);
    };

    /**
     * Registers  'include' handler for area inclusion within handlebars templates.
     * {{include body}}
     */
    Handlebars.registerHelper('include', function (contexts) {
        var i, type,
            length = contexts ? contexts.length : 0,
            html = '';
        if (log.isDebugEnabled()) {
            log.debug('Including : ' + stringify(contexts));
        }
        if (length == 0) {
            return html;
        }
        type = typeof contexts;
        if (contexts instanceof Array) {
            for (i = 0; i < length; i++) {
                html += renderData(contexts[i]);
            }
        } else if (contexts instanceof String || type === 'string' ||
            contexts instanceof Number || type === 'number' ||
            contexts instanceof Boolean || type === 'boolean') {
            html = contexts.toString();
        } else {
            html = renderData(contexts);
        }
        return new Handlebars.SafeString(html);
    });

    /**
     * {{#itr context}}key : {{key}} value : {{value}}{{/itr}}
     */
    Handlebars.registerHelper("itr", function (obj, options) {
        var key, buffer = '';
        for (key in obj) {
            if (obj.hasOwnProperty(key)) {
                buffer += options.fn({key: key, value: obj[key]});
            }
        }
        return buffer;
    });

    /**
     * {{#func myFunction}}{{/func}}
     */
    Handlebars.registerHelper("func", function (context, block) {
        var param,
            args = [],
            params = block.hash;
        for (param in params) {
            if (params.hasOwnProperty(param)) {
                args.push(params[param]);
            }
        }
        return block(context.apply(null, args));
    });

    /**
     * Registers  'js' handler for JavaScript inclusion within handlebars templates.
     * {{js .}}
     */
    Handlebars.registerHelper('js', function () {
        var i, url, length,
            html = '',
            theme = caramel.theme(),
            js = caramel.meta().js;
        if (!js) {
            return html;
        }
        length = js.length;
        html += meta(theme);
        if (length == 0) {
            return new Handlebars.SafeString(html);
        }
        url = theme.url;
        for (i = 0; i < length; i++) {
            //remove \n when production = true
            html += '\n' + renderJS(url.call(theme, 'js/' + js[i]));
        }
        return new Handlebars.SafeString(html);
    });

    /**
     * Registers  'css' handler for CSS inclusion within handlebars templates.
     * {{css .}}
     */
    Handlebars.registerHelper('css', function () {
        var i, url, length,
            html = '',
            theme = caramel.theme(),
            css = caramel.meta().css;
        if (!css) {
            return html;
        }
        length = css.length;
        if (length == 0) {
            return new Handlebars.SafeString(html);
        }
        url = theme.url;
        for (i = 0; i < length; i++) {
            html += renderCSS(url.call(theme, 'css/' + css[i]));
        }
        return new Handlebars.SafeString(html);
    });

    /**
     * Registers  'code' handler for JavaScript inclusion within handlebars templates.
     * {{code .}}
     */
    Handlebars.registerHelper('code', function () {
        var i, length,
            html = '',
            theme = caramel.theme(),
            meta = caramel.meta(),
            codes = meta.code;
        if (!codes) {
            return html;
        }
        length = codes.length;
        if (length == 0) {
            return html;
        }
        for (i = 0; i < length; i++) {
            html += evalCode(codes[i], meta.data, theme);
        }
        return new Handlebars.SafeString(html);
    });

    /**
     * Registers  'url' handler for resolving webapp files.
     * {{url "js/jquery-lates.js"}}
     */
    Handlebars.registerHelper('url', function (path) {
        if (path.indexOf('http://') === 0 || path.indexOf('https://') === 0) {
            return path;
        }
        return caramel.url(path);
    });

    /**
     * Registers  'encodeURIComponent' handler for resolving encode URI components
     * {{encodeURIComponent "test&test"}}
     */
    Handlebars.registerHelper('encodeURIComponent', function (comp) {
        return encodeURIComponent(comp);
    });

    /**
     * Serialize the current content to the out put
     */
    Handlebars.registerHelper('dump', function (o) {
        return stringify(o);
    });

    /**
     * Registers  'themeUrl' handler for resolving theme files.
     * {{themeUrl "js/jquery-lates.js"}}
     */
    Handlebars.registerHelper('themeUrl', function (path) {
        if (path.indexOf('http://') === 0 || path.indexOf('https://') === 0) {
            return path;
        }
        return caramel.themeUrl(path);
    });

    /**
     * Registers  't' handler for translating texts.
     * {{t "programming"}}
     */
    Handlebars.registerHelper('t', function (text) {
        return translate(text) || text;
    });

    function padWithLeadingZeros(string) {
        return new Array(5 - string.length).join("0") + string;
    }

    function unicodeCharEscape(charCode) {
        return "\\u" + padWithLeadingZeros(charCode.toString(16));
    }

    function unicodeEscape(string) {
        return string.split("")
            .map(function (ch) {
                var code = ch.charCodeAt(0);
                if(((code > 47 && code < 58) || // numeric (0-9)
                    (code > 64 && code < 91) || // upper alpha (A-Z)
                    (code > 96 && code < 123)||// lower alpha (a-z)
                    (ch == '.') || (ch == ',') || (ch == '{') ||(ch == '}') ||(ch == '"') || (ch == ':') || (ch == ' ') )){
                    return ch;
                }else{
                    return unicodeCharEscape(code);
                }
            })
            .join("");
    }

    /**
     * Registers  'json' handler for serializing objects.
     * {{json data}}
     */
    Handlebars.registerHelper('json', function (obj) {
        return obj ? new Handlebars.SafeString(unicodeEscape(stringify(obj))) : null;
    });

    /**
     * Registers  'cap' handler for resolving theme files.
     * {{url "js/jquery-lates.js"}}
     */
    Handlebars.registerHelper('cap', function (str) {
        return str.replace(/[^\s]+/g, function (str) {
            return str.substr(0, 1).toUpperCase() + str.substr(1).toLowerCase();
        });
    });

    /**
     * {{#slice start="1" end="10" count="2" size="2"}}{{name}}{{/slice}}
     */
    Handlebars.registerHelper('slice', function (context, block) {
        var html = "",
            length = context.length,
            start = parseInt(block.hash.start) || 0,
            end = parseInt(block.hash.end) || length,
            count = parseInt(block.hash.count) || length,
            size = parseInt(block.hash.size) || length,
            i = start,
            c = 0;
        while (i < end && c++ < count) {
            html += block(context.slice(i, (i += size)));
        }
        return html;
    });

    /*
     The snoop helper allows a query to be executed on objects stored inside
     an array.
     Usage: {{{snoop 'target(key=value).property' context}}}
     The target should be an array containing objects.
     The function works by recursively parsing a path expression
     */
    Handlebars.registerHelper('snoop', function (path, objectInstance) {

        /*
         Checks if the provided string is in the form of a query
         A query should be of the form (field=value)
         @str: The string expression that must be validated
         @return: True if the string is an expression.
         */
        function checkIfQuery(str) {
            return(((str.indexOf('(')) != -1) && (str.indexOf(')') != -1)) ? true : false;
        }

        /*
         The function travels recursively processing the object properties
         @loc: A path expression
         @object:The object in which the path occurs
         */
        function rec(loc, object) {

            //Determine if the path can be broken down
            var components = loc.split('.');

            //Stop traversal if the object is empty
            if (object == null) {
                return '';
            }
            else if (components.length == 1) {
                //Check if the current string is a key to the object
                return object[loc] || '';
            }
            else {

                /*Given a string path like: A(key=value).B.C
                 component[0]=A(key=value)
                 component[1]=B
                 component[2]=C
                 */

                //Get the starting point of A
                var currentStrIndex = loc.indexOf(components[0]);
                //Get the length of A
                var currentStrLength = components[0].length;
                //Extract just A from the string path A.B.C
                var currentStr = loc.substring(currentStrIndex, currentStrLength);

                //Remove A. so that the string is B.C
                var nextStr = loc.replace(currentStr + '.', '');

                //Get the property object[A] which should ideally return an object.
                //Note: This will evaluate to null if path is not found.e.g. The currentStr
                //is a query like A(key=value)
                var currentObj = object[currentStr];

                //Determine if the currentStr (e.g. A ) is a query
                if (checkIfQuery(components[0])) {

                    //Remove (   )
                    var indexStart = components[0].indexOf('(');
                    var indexEnd = components[0].indexOf(')');

                    //Extract the query expression (key=value)
                    var expression = components[0].substring(indexStart, indexEnd);

                    //Extract key
                    var operand = components[0].substring(0, indexStart);

                    //Get the object at property A
                    currentObj = object[operand];

                    //Get rid of the brackets in the (key=value)
                    var removed = expression.replace('(', '');
                    removed = removed.replace(')', '');

                    //Obtain the key and value pair
                    var kv = removed.split('=');

                    //If the key value pair is malformed we stop the search
                    if (kv.length == 0) {
                        return '';
                    }

                    //Obtain the value
                    var key = kv[0];
                    var value = kv[1];

                    var stop = false;

                    //Go through all items in the array(Assumption)
                    for (var index = 0; ((index < currentObj.length) && (!stop)); index++) {

                        //Check the property by the key
                        var item = currentObj[index];

                        //Compare the key to the value
                        if (item[key] == value) {

                            currentObj = item;
                            stop = true;	//Short circuit the search
                        }
                    }

                }

                return rec(nextStr, currentObj);

            }
        }

        return  rec(path, objectInstance);
    });

    /**
     *  Registers mergeContext handler which merge different contexts that needs to be passed in to a single partial.
     *
     * {{#mergeContext thisContext=this nameContext=../../name townContext=../town}}
     *      {{>child-partial}}
     * {{/mergeContext}}
     *
     * In the child-partial
     * {{nameContext.username}}
     *
     */
    Handlebars.registerHelper('mergeContext', function (options) {
        var context = {},
            mergeContext = function (obj) {
                for (var k in obj)context[k] = obj[k];
            };
        mergeContext(options.hash);
        return options.fn(context);
    });

    meta = function (theme) {
        var code, g,
            meta = caramel.meta(),
            config = caramel.configs();
        code = 'var caramel = caramel || {}; caramel.context = "' + config.context + '"; caramel.themer = "' + theme.name + '";';
        code += "caramel.url = function (path) { return this.context + (path.charAt(0) !== '/' ? '/' : '') + path; };";
        g = theme.engine.globals(meta.data, meta);
        code += g || '';
        return renderJS(code, true);
    };

    renderData = function (data) {
        var template,
            context = typeof data.context === 'function' ? data.context() : data.context;
        if (data.partial) {
            if (log.isDebugEnabled()) {
                log.debug('Rendering template ' + data.partial);
            }

            template = Handlebars.compile(Handlebars.partials[data.partial]);
        } else {
            if (log.isDebugEnabled()) {
                log.debug('No template, serializing data');
            }
            template = serialize;
        }
        return template(context);
    };

    serialize = function (o) {
        var type = typeof o;
        switch (type) {
            case 'string':
            case 'number':
                return o;
            default :
                return stringify(o);
        }
    };

    helpersDir = 'helpers';

    renderersDir = 'renderers';

    pagesDir = 'pages';

    partialsDir = 'partials';

    partials = function (Handlebars) {
        var theme = caramel.theme();
        (function register(prefix, file) {
            var i, length, name, files;
            if (file.isDirectory()) {
                files = file.listFiles();
                length = files.length;
                for (i = 0; i < length; i++) {
                    file = files[i];
                    register(prefix ? prefix + '.' + file.getName() : file.getName(), file);
                }
            } else {
                name = file.getName();
                if (name.substring(name.length - 4) !== '.hbs') {
                    return;
                }
                file.open('r');
                Handlebars.registerPartial(prefix.substring(0, prefix.length - 4), file.readAll());
                file.close();
            }
        })('', new File(theme.resolve(partialsDir)));
    };

    /**
     * Init function of handlebars engine. This can be overridden by new themes.
     * @param theme
     */
    init = function (theme) {
        if (log.isDebugEnabled()) {
            log.debug('Initializing engine handlebars with theme : ' + theme.name);
        }
        this.partials(Handlebars);
    };

    render = function (data, meta) {
        var fn,
            path = meta.request.getMappedPath() || meta.request.getRequestURI();

        path = caramel.theme().resolve(renderersDir + path.substring(0, path.length - 4) + '.js');
        if (log.isDebugEnabled()) {
            log.debug('Rendering data for the request using : ' + path);
        }
        //     'print(caramel.build(data)) : '+print(caramel.build(data)));
        if (!new File(path).isExists() || !(fn = require(path).render)) {
            print(caramel.build(data));
            return;
        }
        fn(theme, data, meta, function (path) {
            return require(caramel.theme().resolve(path));
        });
    };

    translate = function (text) {
        var language, dir, path,
            config = caramel.configs(),
            code = config.language ? config.language() : 'en';
        language = languages[code];
        if (!language) {
            dir = 'i18n';
            path = caramel.theme().resolve(dir + '/' + code + '.json');
            if (!new File(path).isExists()) {
                return text;
            }
            language = (languages[code] = require(path));
            if (log.isDebugEnabled()) {
                log.debug('Language json loaded : ' + path);
            }
        }
        return language[text] || caramel.translate(text);
    };

    /**
     * Render function of handlebars engine. This can be overridden by new themes.
     */
    theme = function (page, contexts, js, css, code) {
        var file, template, path, area, blocks, helper, length, i, o, areas, block,
            areaContexts, data, areaData, find, blockData, resolve, partials, findPartials, analyzePartials, testFunction,
            theme = caramel.theme(),
            meta = caramel.meta(),
            xcd = meta.request.getHeader(caramelData),
            cct = meta.request.getHeader(CaramelCompiledTemplates);

        js = js || [];
        css = css || [];
        code = code || [];

        /**
         * Set the Caramel-Compiled header to compile the required partial from the backend
         * and send the HTML block to the frontend.
         */
        if (cct) {
            areas = parse(cct);
            if (areas != null) {
                /**
                 * At the moment we only support one key-value pair of partials to be rendered using this function
                 * at once. Therefore retrieve the 0th element of the array.
                 */
                var areaKey = Object.keys(areas)[0];
                path = caramel.theme().resolve(partialsDir + '/' + areas[areaKey] + '.hbs');
                if (log.isDebugEnabled()) {
                    log.debug('Rendering page : ' + path);
                }
                try {
                    file = new File(path);
                    file.open('r');
                    template = Handlebars.compile(file.readAll());
                } catch (e) {
                    log.error(e.toString());
                    throw new Error('Error while reading the partial', e);
                } finally {
                    file.close();
                }
                areaContexts = contexts[areaKey];
                /**
                 * In the contexts object, areaContext is an array with a single element.
                 * Therefore the first element is selected.
                 */
                var output = template(areaContexts[0].context);
                response.contentType = "text";
                print(output);
            }
            return;
        }

        if (xcd) {
            find = function (areaContexts, partial) {
                var i, context,
                    length = areaContexts.length;
                for (i = 0; i < length; i++) {
                    if (areaContexts[i].partial === partial) {
                        context = areaContexts[i].context;
                        return typeof context === 'function' ? context() : context;
                    }
                }
                return null;
            };
            resolve = function (parent, paths) {
                if (paths instanceof Array) {
                    var p = [];
                    paths.forEach(function (path) {
                        p.push(theme.resolve.call(theme, parent + '/' + path));
                    });
                    return p;
                }
                return theme.resolve.call(theme, parent + '/' + paths);
            };
            analyzePartials = function (partials, ast) {
                switch (ast.type) {
                    case 'program':
                        if (ast.statements) {
                            ast.statements.forEach(function (program) {
                                analyzePartials(partials, program);
                            });
                        }
                        if (ast.inverse) {
                            analyzePartials(partials, ast.inverse);
                        }
                        break;
                    case 'block':
                        analyzePartials(partials, ast.program);
                        break;
                    case 'partial':
                        partials.push(ast.id.original);
                }
            };
            findPartials = function (partials, partial) {
                var file, o, ast, path;
                if (partials[partial]) {
                    return;
                }
                path = resolve('partials', partial + '.hbs');
                file = new File(path);
                file.open('r');
                ast = Handlebars.parse(file.readAll());
                file.close();
                partials[partial] = path;
                o = [];
                analyzePartials(o, ast);
                o.forEach(function (partial) {
                    findPartials(partials, partial);
                });
            };
            data = {
                _: {
                    partials: {}
                }
            };
            areas = parse(xcd);
            for (area in areas) {
                if (areas.hasOwnProperty(area)) {
                    areaContexts = contexts[area];
                    if (areaContexts instanceof Array) {
                        blocks = areas[area];
                        areaData = (data[area] = {});
                        length = blocks.length;
                        for (i = 0; i < length; i++) {
                            block = blocks[i];
                            blockData = (areaData[block] = {
                                resources: {}
                            });
                            findPartials(data._.partials, block);
                            blockData.context = find(areaContexts, block);
                            path = theme.resolve.call(theme, helpersDir + '/' + block + '.js');
                            if (new File(path).isExists()) {
                                helper = require(path);
                                if (helper.resources) {
                                    o = helper.resources(page, meta);
                                    blockData.resources.js = resolve('js', o.js);
                                    blockData.resources.css = resolve('css', o.css);
                                    blockData.resources.code = o.code ? o.code.reduce(function(pre,cur){
                                        return pre + evalCode(cur, meta.data, theme);
                                    },"") : null;
                                }
                            }
                        }
                    } else {
                        data[area] = areaContexts;
                    }
                }
            }
            data._.js = js;
            data._.css = css;
            data._.code = code;
            meta.response.addHeader('Content-Type', 'application/json');
            print(data);
            return;
        }

        for (area in contexts) {
            if (contexts.hasOwnProperty(area)) {
                blocks = contexts[area];
                if (blocks instanceof Array) {
                    length = blocks.length;
                    for (i = 0; i < length; i++) {
                        //this is executing when the top-assets page loads first time.
                        path = caramel.theme().resolve(helpersDir + '/' + blocks[i].partial + '.js');
                        if (new File(path).isExists()) {
                            helper = require(path);
                            if (helper.resources) {
                                o = helper.resources(page, meta);
                                js = o.js ? js.concat(o.js) : js;
                                css = o.css ? css.concat(o.css) : css;
                                code = o.code ? code.concat(o.code) : code;
                            }
                        }
                    }
                }
            }
        }
        meta.js = js;
        meta.css = css;
        meta.code = code;
        path = caramel.theme().resolve(pagesDir + '/' + page + '.hbs');
        if (log.isDebugEnabled()) {
            log.debug('Rendering page : ' + path);
        }
        file = new File(path);
        file.open('r');
        template = Handlebars.compile(file.readAll());
        file.close();
        print(template(contexts));
    };

    renderJS = function (js, inline) {
        return '<script' + (inline ? '>' + js : ' src="' + js + '">') + '</script>';
    };

    renderCSS = function (css) {
        return '<link rel="stylesheet" type="text/css" href="' + css + '"/>';
    };

    globals = function (data, meta) {
        return null;
    };

    populate = function (dir, ext, theme) {
        var i, n,
            a = [],
            files = new File(theme.resolve(dir + ext)),
            l1 = ext.length,
            l2 = files.length;
        for (i = 0; i < l2; i++) {
            n = files[i].getName();
            if (n.substring(n.length - l1) !== '.' + ext) {
                continue;
            }
            a.push(ext + '/' + n);
        }
        return a;
    };

    return {
        partials: partials,
        translate: translate,
        globals: globals,
        init: init,
        render: render
    };
})());


text:
import {Fonts} from "../../Common/Enums/Fonts";
import {FontStyles} from "../../Common/Enums/FontStyles";

export interface ITextMeasurer {
    fontSize: number;
    fontSizeStandard: number;
    computeTextWidthToHeightRatio(text: string, font: Fonts, style: FontStyles,
                                  fontFamily?: string, fontSize?: number): number;
    setFontSize(fontSize: number): number;
}

redpajama_set_name: RedPajamaGithub


text:
1. Implement hashtable put function in C++ without using STL stuff.

2. A client wants to build a software phone book that contains everyone in the world (7 billion people). Every person has only the first name and the name is unique. What data structure would you use to store the data?


text:
package fi.harism.lucidchat;

import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import fi.harism.lucidchat.api.Channel;
import fi.harism.lucidchat.api.ChatHandler;
import fi.harism.lucidchat.api.Conversation;
import fi.harism.lucidchat.api.Message;
import fi.harism.lucidchat.api.User;

/**
 * Main activity class - the one and only.
 */
public class MainActivity extends Activity implements ContainerCenter.Observer,
		ContainerMenu.Observer, ChatHandler.Observer {

	private ChatHandler mChatHandler = new ChatHandler();
	private ContainerCenter mContainerCenter;
	private ContainerMenu mContainerMenu;
	private PreferencesHandler mPreferences;
	private Conversation mPreviousConversation;
	private String mUserId, mUserAuth, mSessionId;

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			if (mContainerCenter.getX() > 0) {
				mContainerCenter.setMenuVisible(false);
				return true;
			}
			finish();
		}
		return super.dispatchKeyEvent(event);
	}

	@Override
	public void onConversationAdded(final Conversation conversation) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (conversation.getType() == Conversation.TYPE_CHANNEL) {
					Message message = new Message(Message.TYPE_LOG, getString(
							R.string.channel_joined, conversation.getTitle()));
					conversation.addMessage(message);
				}
				mContainerMenu.setConversation(conversation);
				mContainerMenu
						.setConversations(mChatHandler.getConversations());
				mContainerCenter.setConversation(conversation);
				mContainerCenter.setMenuVisible(false);
			}
		});
	}

	@Override
	public void onConversationRemoved(final Conversation conversation) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				mContainerMenu.removeConversation(conversation);
				if (mContainerCenter.getConversation() == conversation) {
					mContainerCenter.setConversation(mChatHandler
							.getServerLog());
					mContainerMenu.setConversation(mChatHandler.getServerLog());
				}
			}
		});
	}

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

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED);

		setContentView(R.layout.layout_main);

		mPreferences = new PreferencesHandler(this);

		mContainerCenter = (ContainerCenter) findViewById(R.id.container_center);
		mContainerMenu = (ContainerMenu) findViewById(R.id.container_menu);

		mContainerCenter.setMenuContainer(mContainerMenu);
		mContainerCenter.setCenterObserver(this);
		mContainerMenu.setMenuObserver(this);
		mChatHandler.addObserver(this);

		showDialogConnect();
		mContainerCenter.setConversation(mChatHandler.getServerLog());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		mChatHandler.disconnect();
	}

	@Override
	public void onInfoJoin(Conversation conversation, String userId, String name) {
		Message message = new Message(Message.TYPE_LOG, getString(
				R.string.channel_join, name));
		conversation.addMessage(message);
	}

	@Override
	public void onInfoPart(Conversation conversation, String userId, String name) {
		Message message = new Message(Message.TYPE_LOG, getString(
				R.string.channel_part, name));
		conversation.addMessage(message);
	}

	@Override
	public void onJoinChannel(Channel channel) {
		if (mChatHandler.hasConversation(channel)) {
			Conversation conversation = mChatHandler.getConversation(channel);
			mContainerMenu.setConversation(conversation);
			mContainerCenter.setConversation(conversation);
			mContainerCenter.setMenuVisible(false);
		} else {
			mChatHandler.joinChannel(channel.getId());
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_about: {
			showDialogAbout();
			return true;
		}
		case R.id.menu_serverlog: {
			mContainerMenu.setConversation(mChatHandler.getServerLog());
			mContainerCenter.setConversation(mChatHandler.getServerLog());
			mContainerCenter.setMenuVisible(false);
			return true;
		}
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onPartConversation(Conversation conversation) {
		mChatHandler.removeConversation(conversation);
	}

	@Override
	public void onSearch(String searchText) {
		mChatHandler.search(searchText);
	}

	@Override
	public void onSearchResults(final List<Channel> channels,
			final List<User> users) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				mContainerMenu.addSearchResults(users, channels);
			}
		});
	}

	@Override
	public boolean onSendMessage(Conversation conversation, String text) {
		return mChatHandler.sendMessage(conversation, text);
	}

	@Override
	public void onServerConnect(String userId, String userAuth, String sessionId) {
		mUserId = userId;
		mUserAuth = userAuth;
		mSessionId = sessionId;

		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (mPreviousConversation != null) {
					mContainerCenter.setConversation(mPreviousConversation);
					mContainerMenu.setConversation(mPreviousConversation);
					mPreviousConversation = null;
				}
			}
		});
	}

	@Override
	public void onServerDisconnect() {
		if (isFinishing()) {
			return;
		}
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				mPreviousConversation = mContainerCenter.getConversation();
				mContainerCenter.setMenuVisible(false);
				mContainerCenter.setConversation(mChatHandler.getServerLog());
				mContainerMenu.setConversation(mChatHandler.getServerLog());
				if (mUserId != null && mUserAuth != null && mSessionId != null) {
					showDialogReconnect();
				} else {
					showDialogConnect();
				}
			}
		});
	}

	@Override
	public void onShowConversation(Conversation conversation) {
		mContainerMenu.setConversation(conversation);
		mContainerCenter.setConversation(conversation);
		mContainerCenter.setMenuVisible(false);
	}

	@Override
	public void onStartConversation(User user) {
		if (mChatHandler.hasConversation(user)) {
			Conversation conversation = mChatHandler.getConversation(user);
			mContainerMenu.setConversation(conversation);
			mContainerCenter.setConversation(conversation);
			mContainerCenter.setMenuVisible(false);
		} else {
			mChatHandler.addConversation(user);
		}
	}

	/**
	 * Show about dialog.
	 */
	private void showDialogAbout() {
		final Dialog dlg = new Dialog(this);
		dlg.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dlg.setContentView(R.layout.dialog_about);
		dlg.findViewById(R.id.button_close).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						dlg.dismiss();
					}
				});
		dlg.show();
	}

	/**
	 * Show connect dialog.
	 */
	private void showDialogConnect() {
		DialogConnect dlg = new DialogConnect(this,
				new DialogConnect.DialogObserver() {
					@Override
					public void onCancel(DialogConnect dialog) {
						dialog.dismiss();
						finish();
					}

					@Override
					public void onConnect(DialogConnect dialog) {
						mPreferences.setName(dialog.getName());
						mPreferences.setRealName(dialog.getRealName());
						mPreferences.setAutojoin(dialog.getAutojoin());
						mPreferences.save();

						mChatHandler.connect(dialog.getName(),
								dialog.getRealName(), dialog.getAutojoin());
						dialog.dismiss();
					}
				});
		dlg.setName(mPreferences.getName());
		dlg.setRealName(mPreferences.getRealName());
		dlg.setAutojoin(mPreferences.getAutojoin());
		dlg.show();
	}

	/**
	 * Show reconnect dialog.
	 */
	private void showDialogReconnect() {
		final Dialog dlg = new Dialog(this);
		dlg.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dlg.setContentView(R.layout.dialog_reconnect);
		dlg.findViewById(R.id.button_cancel).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						dlg.dismiss();
						finish();
					}
				});
		dlg.findViewById(R.id.button_connect).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						dlg.dismiss();
						mChatHandler.reconnect(mUserId, mUserAuth, mSessionId);
					}
				});
		dlg.show();
	}

}


text:
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>{% if page.title %}{{ page.title }} - {% endif %}{{ site.title }}</title>
  <meta name="viewport" content="width=device-width">
  <link rel="apple-touch-icon" href="apple-touch-icon.png">
  <meta name="description" content="{% if page.description %}{{ page.description }}{% else %}{{ site.description }}{% endif %}">
  <link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}">

  <!-- Custom CSS & Bootstrap Core CSS - Uses Bootswatch Flatly Theme: http://bootswatch.com/flatly/ -->
  <link rel="stylesheet" href="{{ "/css/site.css" | prepend: site.baseurl }}">

  <!-- Custom Fonts -->
  <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">

  <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
    <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
  <![endif]-->
</head>


text:
module SpreeBulkUpload
  module Processors
    class VariantAttributes < Base
      attr_reader :variant_row

      def initialize(variant_row)
        @variant_row = variant_row
      end

      protected

      def attributes_mapping
        {
            'SKU' => 'sku',
            'Cost' => 'cost_price'
        }
      end

      def source_object
        variant_row
      end

    end
  end
end


text:
import React, { Component } from 'react';

export default class HomeProjects extends Component {
  render() {
    const styles = require('./Home.scss');

    return (

Projects h1

Projects h2

    );
  }
}


text:
package org.mitre.provenance.workflows;

import java.util.Date;
import java.util.GregorianCalendar;

import org.mitre.provenance.PLUSException;
import org.mitre.provenance.db.neo4j.Neo4JPLUSObjectFactory;
import org.mitre.provenance.plusobject.PLUSActor;
import org.mitre.provenance.plusobject.PLUSEdge;
import org.mitre.provenance.plusobject.PLUSInvocation;
import org.mitre.provenance.plusobject.PLUSObject;
import org.mitre.provenance.plusobject.PLUSString;
import org.mitre.provenance.plusobject.PLUSWorkflow;
import org.mitre.provenance.plusobject.ProvenanceCollection;
import org.mitre.provenance.surrogate.sgf.GenericSGF;
import org.mitre.provenance.user.PrivilegeClass;
import org.mitre.provenance.user.PrivilegeSet;

/**
 * Sample NGA human-in-the-loop analysis workflow, created to
 * support Chris Basel, Jan 2012
 * @author AGE
 */
public class IAWorkflow extends ProvenanceCollection {
	public IAWorkflow() throws PLUSException {
		super();

		PLUSWorkflow aw = new PLUSWorkflow();
		aw.setName("IA Workflow");
		aw.setWhenStart(new Date().toString());
		aw.setWhenEnd(new Date().toString());
                addNode(aw);

		PrivilegeSet TS = new PrivilegeSet();
		TS.addPrivilege(new PrivilegeClass(10));

		PrivilegeSet SEC = new PrivilegeSet();
		SEC.addPrivilege(new PrivilegeClass(5));

		PrivilegeSet PUBLIC = new PrivilegeSet();
		PUBLIC.addPrivilege(PrivilegeClass.PUBLIC);

                PLUSActor DOD = Neo4JPLUSObjectFactory.getActor("DOD", true);
                PLUSActor intel = Neo4JPLUSObjectFactory.getActor("Intel Community", true);

                PLUSString waasFile1 = new PLUSString("Air Surveillance Data", "Air Surveillance Data");
		waasFile1.setOwner(DOD);
                GregorianCalendar cref1 = new GregorianCalendar();
                cref1.set(2011, 6, 1);
                waasFile1.setCreated(cref1.getTimeInMillis());
		waasFile1.getMetadata().put("Location", "Baghdad");
                waasFile1.getMetadata().put("Latitude", "+33.348026");
                waasFile1.getMetadata().put("Longitude", "+44.362584");

		PLUSInvocation palan1 = new PLUSInvocation("Palantir Analyzer");
		palan1.setPrivileges(TS);
		palan1.setWorkflow(aw);
                GregorianCalendar chil = new GregorianCalendar();
                chil.set(2011, 7, 6, 16, 00);
                palan1.setCreated(chil.getTimeInMillis());
                palan1.getMetadata().put("Analyst", "Joe");
                palan1.setOwner(intel);
                palan1.getMetadata().put("Specialty", "WMDs");
                addNode(palan1);

		addNode(waasFile1);
		addEdge(new PLUSEdge(waasFile1, palan1, aw));

                PLUSString palModel = new PLUSString("Palantir Model", "Palantir Model");
		palModel.setOwner(intel);

                addNode(palModel);
                addEdge(new PLUSEdge(palan1, palModel, aw));

                PLUSInvocation etling = new PLUSInvocation("ETL Tool");
		etling.setPrivileges(TS);
		etling.setWorkflow(aw);
                GregorianCalendar chil2 = new GregorianCalendar();
                chil.set(2011, 7, 8, 16, 00);
                etling.setCreated(chil2.getTimeInMillis());
                etling.getMetadata().put("Analyst", "Joe");
                etling.setOwner(intel);
                etling.getMetadata().put("Specialty", "WMDs");
                addNode(etling);

                addNode(etling);
                addEdge(new PLUSEdge(palModel, etling, aw));

                PLUSString doka = new PLUSString("Person C");
		doka.setOwner(DOD);
		PLUSString  fatik = new PLUSString("Person D");
		fatik.setOwner(DOD);
                addNode(doka);
		addNode(fatik);

                addEdge(new PLUSEdge(etling, doka, aw));
                addEdge(new PLUSEdge(etling, fatik, aw));

                PLUSString waasFile2 = new PLUSString("Air Surveillance Data 2", "Air Surveillance Data 2");
		waasFile2.setOwner(intel);
		PLUSString iedThreat = new PLUSString("IED-threat intelligence", "IED-threat intelligence");
		iedThreat.setOwner(intel);

                addNode(waasFile2);

                PLUSInvocation meting = new PLUSInvocation("GeoTagger");
		meting.setPrivileges(TS);
		meting.setWorkflow(aw);
                GregorianCalendar chil3 = new GregorianCalendar();
                chil3.set(2011, 7, 7, 16, 00);
                meting.setCreated(chil3.getTimeInMillis());
                meting.getMetadata().put("Analyst", "Joe");
                meting.setOwner(intel);
                meting.getMetadata().put("Specialty", "WMDs");
                addNode(meting);

                addNode(meting);
                //choose 1 of these, based on what you're trying to say in the script
                addEdge(new PLUSEdge(waasFile1, meting, aw));
                //addEdge(new PLUSEdge(waasFile2, meting, aw));

                PLUSString anisah = new PLUSString("Person A");
		anisah.setOwner(DOD);
                PLUSString baahir = new PLUSString("Person B");
		baahir.setOwner(DOD);

		addNode(anisah);
		addNode(baahir);

                addEdge(new PLUSEdge(meting,anisah, aw));
                addEdge(new PLUSEdge(meting, baahir, aw));
                addEdge(new PLUSEdge(etling, anisah, aw));

		for(PLUSObject ob : getNodes()) {
			ob.useSurrogateComputation(new GenericSGF());
		}
	} // End AnalystWorkflow

	protected void finalize() {

	} // End finalize
} // End AnalystWorkflow


text:
package net.frakbot.android.location.adapter.gms.resolver;

import android.content.Context;

import net.frakbot.android.location.LocationHubAdapter;
import net.frakbot.android.location.adapter.android.AndroidLocationHubAdapter;
import net.frakbot.android.location.adapter.gms.GMSLocationHubAdapter;
import net.frakbot.android.location.resolver.DefaultLocationHubAdapterResolver;

import java.util.List;

/**
 * Default implementation for the {@link net.frakbot.android.location.LocationHubAdapter} interface. It
 * always returns the first available implementation in the list.
 * If you want to use this Adapter implementation, build the {@link java.util.List} of {@link net.frakbot.android.location.LocationHubAdapter}
 * implementations in an ordered way.
 */
public class GMSLocationHubAdapterResolver extends DefaultLocationHubAdapterResolver {
    public GMSLocationHubAdapterResolver(Context context) {
        super(context);
        mLocationAdapters.add(new GMSLocationHubAdapter());
        mLocationAdapters.add(new AndroidLocationHubAdapter());
    }
}


text:
class ResponseMate::Environment
  attr_accessor :filename

  delegate :[], to: :env

  def initialize(filename)
    @filename = filename || ResponseMate.configuration.environment
  end

  # Check for environment file existence
  # @return [TrueClass|FalseClass]
  def exists?
    File.exist? filename
  end

  # Set the env to the parsed YAML environment file
  def env
    @env ||= exists? ? YAML.load_file(filename) : {}
  end
end


text:
package org.broadinstitute.hellbender.tools.coveragemodel;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.math3.util.FastMath;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.broadinstitute.hellbender.utils.Utils;
import org.broadinstitute.hellbender.utils.hmm.interfaces.AlleleMetadataProducer;
import org.broadinstitute.hellbender.utils.hmm.interfaces.CallStringProducer;
import org.broadinstitute.hellbender.utils.hmm.interfaces.ScalarProducer;

import javax.annotation.Nonnull;
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * This class implements the EM algorithm for the GATK coverage model. It is used for:
 *
 * (1) performing max likelihood estimation of the model parameters AND calculating posterior expectations
 *     via calling {@link CoverageModelEMAlgorithm {@link #runExpectationMaximization()}}
 *
 * (2) Calculating posterior expectations for the model parameters already existing in the workspace
 *     via calling {@link CoverageModelEMAlgorithm {@link #runExpectation()}}
 *
 * (see CNV-methods.pdf for technical details).
 *
 * This class does not store or perform any of the calculations. Rather, it controls the flow of the EM
 * algorithm subroutines (E- and M- steps) and makes calls to various methods in the provided
 * {@link CoverageModelEMWorkspace} in order to perform the actual computations.
 *
 * @param <STATE> copy ratio (or copy number) hidden state type
 *
 * @author Mehrtash Babadi <mehrtash@broadinstitute.org>
 */

public final class CoverageModelEMAlgorithm<STATE extends AlleleMetadataProducer & CallStringProducer & ScalarProducer> {
    private static final Logger logger = LogManager.getLogger(CoverageModelEMAlgorithm.class);
    private final CoverageModelArgumentCollection config;
    private final CoverageModelEMWorkspace<STATE> workspace;
    private EMAlgorithmStatus status;

    /**
     * Extract iteration count from a {@link SubroutineSignal}
     */
    private static Function<SubroutineSignal, String> ITERATION_EXTRACTOR = s ->
            "iters: " + s.<Integer>get(StandardSubroutineSignals.ITERATIONS);

    /**
     * This supplies a "N/A" string no matter what; used when nothing needs to be reported from
     * the {@link SubroutineSignal}
     */
    private static Function<SubroutineSignal, String> NOT_APPLICABLE_EXTRACTOR = s -> "N/A";

    /**
     * Public constructor.
     *
     * @param config configuration of the EM algorithm
     * @param workspace workspace for actual calculations
     */
    public CoverageModelEMAlgorithm(@Nonnull final CoverageModelArgumentCollection config,
                                    @Nonnull CoverageModelEMWorkspace<STATE> workspace) {
        this.config = Utils.nonNull(config, "Coverage model EM algorithm configuration must be non-null");
        config.validate();
        this.workspace = Utils.nonNull(workspace, "The coverage modeller EM algorithm workspace must be non-null");
        this.status = EMAlgorithmStatus.TBD;
        logger.info("EM algorithm initialized.");
    }

    /**
     * Log the header for iteration info
     */
    private void showIterationHeader() {
        final String header = String.format("%-15s%-20s%-20s%-20s%-20s", "Iterations", "Type", "Log Likelihood", "Update Size", "Misc.");
        logger.info(header);
        logger.info(StringUtils.repeat("=", header.length()));
    }

    /**
     * Log the iteration info
     *
     * @param iter iteration number
     * @param title iteration title
     * @param logLikelihood current log likelihood
     * @param updateSize current update size
     * @param misc other miscellaneous info
     */
    private void showIterationInfo(final int iter, final String title, final double logLikelihood,
                                   final double updateSize, final String misc) {
        final String header = String.format("%-15d%-20s%-20.6e%-20.6e%-20s", iter, title, logLikelihood, updateSize, misc);
        logger.info(header);
    }

    /**
     * A generic runner of a step in the EM algorithm
     *
     * @param routine a routine to run
     * @param miscFactory a function from the routine signal to a miscellaneous iteration info string
     * @param title title of the routine
     * @param iterInfo the iteration info class (will be updated)
     */
    private void runRoutine(@Nonnull final Supplier<SubroutineSignal> routine,
                            @Nonnull final Function<SubroutineSignal, String> miscFactory,
                            @Nonnull final String title,
                            @Nonnull EMAlgorithmIterationInfo iterInfo) {
        final SubroutineSignal sig = routine.get();
        final String misc = miscFactory.apply(sig);
        iterInfo.errorNorm = sig.<Double>get(StandardSubroutineSignals.RESIDUAL_ERROR_NORM);
        iterInfo.logLikelihood = getLogLikelihood();
        finalizeIteration();
        showIterationInfo(iterInfo.getIterationCount(), title, iterInfo.getLogLikelihood(), iterInfo.getErrorNorm(), misc);
    }

    /**
     * Run the full EM algorithm stack for variational inference and model parameter optimization
     *
     * @return the exit status of the EM algorithm
     */
    public EMAlgorithmStatus runExpectationMaximization() {
        config.validate();
        /* If copy ratio posterior calling is enabled, the first few iterations need to be robust.
         * Therefore, we disable the target-resolved unexplained variance estimation (if enabled) and
         * enforce isotropic unexplained variance */
        CoverageModelArgumentCollection.TargetSpecificVarianceUpdateMode currentTargetSpecificVarianceUpdateMode =
                config.getTargetSpecificVarianceUpdateMode();
        if (config.adaptiveTargetSpecificVarianceSolverModeSwitchingEnabled() &&
                !currentTargetSpecificVarianceUpdateMode.equals(CoverageModelArgumentCollection.TargetSpecificVarianceUpdateMode.ISOTROPIC)) {
            currentTargetSpecificVarianceUpdateMode = CoverageModelArgumentCollection.TargetSpecificVarianceUpdateMode.ISOTROPIC;
            logger.info("Overriding the requested unexplained variance solver to " +
                    CoverageModelArgumentCollection.TargetSpecificVarianceUpdateMode.ISOTROPIC.name());
        }

        showIterationHeader();

        double prevMStepLikelihood = Double.NEGATIVE_INFINITY;
        double latestMStepLikelihood = Double.NEGATIVE_INFINITY;
        final EMAlgorithmIterationInfo iterInfo = new EMAlgorithmIterationInfo(Double.NEGATIVE_INFINITY, 0, 1);
        final boolean updateBiasCovariates = config.getNumLatents() > 0;

        /* initial states -- these will change over the course of the algorithm adaptively */
        boolean updateCopyRatioPosteriors = false;
        boolean updateARDCoefficients = false;
        boolean paramEstimationConverged = false;
        boolean performMStep = true;

        while (iterInfo.iter <= config.getMaxEMIterations()) {

            /* cycle through E-step mean-field equations until they are satisfied to the desired degree */
            int iterEStep = 0;
            double maxPosteriorErrorNorm = 2 * config.getPosteriorAbsTol();
            while (iterEStep < config.getMaxEStepCycles() && maxPosteriorErrorNorm > config.getPosteriorAbsTol()) {
                double posteriorErrorNormReadDepth;
                double posteriorErrorNormSampleUnexplainedVariance;
                double posteriorErrorNormBias;
                double posteriorErrorNormCopyRatio;
                double posteriorErrorNormBiasCovariates;

                runRoutine(this::updateReadDepthLatentPosteriorExpectations, NOT_APPLICABLE_EXTRACTOR, "E_STEP_D", iterInfo);
                posteriorErrorNormReadDepth = iterInfo.errorNorm;

                /* initially, we just want read depth estimate */
                if (iterInfo.iter == 1) {
                    break;
                }

                if (updateBiasCovariates) {
                    runRoutine(this::updateBiasLatentPosteriorExpectations, NOT_APPLICABLE_EXTRACTOR, "E_STEP_Z", iterInfo);
                    posteriorErrorNormBias = iterInfo.errorNorm;
                    runRoutine(this::updateBiasCovariates, NOT_APPLICABLE_EXTRACTOR, "E_STEP_W", iterInfo);
                    posteriorErrorNormBiasCovariates = iterInfo.errorNorm;
                } else {
                    posteriorErrorNormBias = 0;
                    posteriorErrorNormBiasCovariates = 0;
                }

                if (config.sampleSpecificVarianceUpdateEnabled()) {
                    runRoutine(this::updateSampleUnexplainedVariance, ITERATION_EXTRACTOR, "E_STEP_GAMMA", iterInfo);
                    posteriorErrorNormSampleUnexplainedVariance = iterInfo.errorNorm;
                } else {
                    posteriorErrorNormSampleUnexplainedVariance = 0;
                }

                if (updateCopyRatioPosteriors) {
                    runRoutine(this::updateCopyRatioLatentPosteriorExpectations, NOT_APPLICABLE_EXTRACTOR, "E_STEP_C", iterInfo);
                    posteriorErrorNormCopyRatio = iterInfo.errorNorm;
                } else {
                    posteriorErrorNormCopyRatio = 0;
                }

                /* calculate the maximum change of posteriors in this cycle */
                maxPosteriorErrorNorm = Collections.max(Arrays.asList(
                        posteriorErrorNormReadDepth,
                        posteriorErrorNormBiasCovariates,
                        posteriorErrorNormSampleUnexplainedVariance,
                        posteriorErrorNormBias,
                        posteriorErrorNormCopyRatio));

                iterEStep++;
            }

            if (maxPosteriorErrorNorm > config.getPosteriorAbsTol()) {
                logger.warn("E-step cycles did not fully converge. Increase the maximum number of E-step cycles." +
                        " Continuing...");
            }

            /* parameter estimation */
            if (performMStep && !paramEstimationConverged) {
                int iterMStep = 0;
                double maxParamErrorNorm;

                /* sequential M-steps */
                while (iterMStep < config.getMaxMStepCycles()) {
                    double errorNormMeanTargetBias;
                    double errorNormUnexplainedVariance;
                    double errorNormARDCoefficients;

                    /* neglect the contribution from principal components in the first iteration */
                    final boolean ignoreBiasCovariates = iterInfo.iter == 1;
                    runRoutine(() -> updateTargetMeanBias(ignoreBiasCovariates), NOT_APPLICABLE_EXTRACTOR, "M_STEP_M", iterInfo);
                    errorNormMeanTargetBias = iterInfo.errorNorm;

                    if (config.targetSpecificVarianceUpdateEnabled()) {
                        final CoverageModelArgumentCollection.TargetSpecificVarianceUpdateMode finalizedPsiUpdateMode = currentTargetSpecificVarianceUpdateMode;
                        runRoutine(() -> updateTargetUnexplainedVariance(finalizedPsiUpdateMode), ITERATION_EXTRACTOR, "M_STEP_PSI", iterInfo);
                        errorNormUnexplainedVariance = iterInfo.errorNorm;
                    } else {
                        errorNormUnexplainedVariance = 0;
                    }

                    if (updateARDCoefficients) {
                        runRoutine(this::updateBiasCovariatesARDCoefficients, NOT_APPLICABLE_EXTRACTOR, "M_STEP_ALPHA", iterInfo);
                        errorNormARDCoefficients = iterInfo.errorNorm;
                    } else {
                        errorNormARDCoefficients = 0;
                    }

                    maxParamErrorNorm = Collections.max(Arrays.asList(
                            errorNormMeanTargetBias,
                            errorNormUnexplainedVariance,
                            errorNormARDCoefficients));

                    /* check convergence of parameter estimation */
                    if (updateCopyRatioPosteriors && maxParamErrorNorm < config.getParameterEstimationAbsoluteTolerance()) {
                        status = EMAlgorithmStatus.SUCCESS_PARAMS_TOL;
                        paramEstimationConverged = true;
                    }
                    iterMStep++;
                }

                prevMStepLikelihood = latestMStepLikelihood;
                latestMStepLikelihood = iterInfo.logLikelihood;

                /* if partially converged, start updating copy number posteriors */
                final boolean partiallyConvergedForCRCalling = FastMath.abs(latestMStepLikelihood - prevMStepLikelihood) <
                        config.getLogLikelihoodTolThresholdCRCalling();
                if (partiallyConvergedForCRCalling && config.copyRatioUpdateEnabled() && !updateCopyRatioPosteriors) {
                    updateCopyRatioPosteriors = true;
                    logger.info("Partial convergence achieved; starting to update copy ratio posteriors in" +
                            " the next iteration");
                }

                /* if partially converged, switch to target-resolved psi update mode (if enabled) */
                final boolean partiallyConvergedForPsiSwitching = FastMath.abs(latestMStepLikelihood - prevMStepLikelihood) <
                        config.getLogLikelihoodTolThresholdTargetSpecificVarianceSwitching();
                if (partiallyConvergedForPsiSwitching && config.targetSpecificVarianceUpdateEnabled() &&
                        config.adaptiveTargetSpecificVarianceSolverModeSwitchingEnabled() &&
                        !currentTargetSpecificVarianceUpdateMode.equals(CoverageModelArgumentCollection.TargetSpecificVarianceUpdateMode.TARGET_RESOLVED)) {
                    currentTargetSpecificVarianceUpdateMode = CoverageModelArgumentCollection.TargetSpecificVarianceUpdateMode.TARGET_RESOLVED;
                    logger.info("Partial convergence achieved; switching to target-specific unexplained variance in" +
                            " the next iteration");
                }

                /* if partially converged, switch to target-resolved psi update mode (if enabled) */
                final boolean partiallyConvergedForARDUpdate = FastMath.abs(latestMStepLikelihood - prevMStepLikelihood) <
                        config.getLogLikelihoodTolThresholdARDUpdate();
                if (partiallyConvergedForARDUpdate && config.isARDEnabled() && !updateARDCoefficients) {
                    updateARDCoefficients = true;
                    logger.info("Partial convergence achieved; enabling update of ARD coefficients");
                    runRoutine(this::updateBiasCovariatesARDCoefficients, NOT_APPLICABLE_EXTRACTOR, "M_STEP_ALPHA", iterInfo);
                }
            }

            /* check convergence in log likelihood change */
            if (FastMath.abs(latestMStepLikelihood - prevMStepLikelihood) < config.getLogLikelihoodTolerance()) {
                /* make sure that we have either already called copy ratio posteriors, or we are not required to */
                if (!config.copyRatioUpdateEnabled() || updateCopyRatioPosteriors) {
                    status = EMAlgorithmStatus.SUCCESS_LIKELIHOOD_TOL;
                    break;
                }
            } else if (iterInfo.iter == config.getMaxEMIterations() - 2) {
                performMStep = false; /* so that we end with an E-step */
            }

            iterInfo.incrementIterationCount();

            /* checkpointing */
            if (config.isRunCheckpointingEnabled() && iterInfo.iter % config.getRunCheckpointingInterval() == 0) {
                final String modelOutputAbsolutePath = new File(config.getRunCheckpointingPath(),
                        String.format("%s_iter_%d", CoverageModelGlobalConstants.MODEL_CHECKPOINT_PATH_PREFIX, iterInfo.iter)).getAbsolutePath();
                final String posteriorOutputAbsolutePath = new File(config.getRunCheckpointingPath(),
                        String.format("%s_iter_%d", CoverageModelGlobalConstants.POSTERIOR_CHECKPOINT_PATH_PREFIX, iterInfo.iter)).getAbsolutePath();
                saveModel(modelOutputAbsolutePath);
                savePosteriors(posteriorOutputAbsolutePath, CoverageModelEMWorkspace.PosteriorVerbosityLevel.BASIC);
            }
        }

        if (iterInfo.iter == config.getMaxEMIterations()) {
            status = EMAlgorithmStatus.FAILURE_MAX_ITERS_REACHED;
        }

        performPostEMOperations();

        return status;
    }

    /**
     * Perform variational inference for given model parameters
     *
     * @return the exit status
     */
    public EMAlgorithmStatus runExpectation() {
        config.validate();
        showIterationHeader();

        double prevEStepLikelihood;
        double latestEStepLikelihood = Double.NEGATIVE_INFINITY;
        final EMAlgorithmIterationInfo iterInfo = new EMAlgorithmIterationInfo(Double.NEGATIVE_INFINITY, 0, 1);
        /* disable copy ratio posterior calculation until bias estimation is stabilized */
        boolean updateCopyRatioPosteriors = false;

        while (iterInfo.iter <= config.getMaxEMIterations()) {

            /* cycle through E-step mean-field equations until they are satisfied to the desired degree */
            double maxPosteriorErrorNorm;
            double posteriorErrorNormReadDepth;
            double posteriorErrorNormSampleUnexplainedVariance;
            double posteriorErrorNormBias;
            double posteriorErrorNormCopyRatio;

            runRoutine(this::updateReadDepthLatentPosteriorExpectations, NOT_APPLICABLE_EXTRACTOR, "E_STEP_D", iterInfo);
            posteriorErrorNormReadDepth = iterInfo.errorNorm;

            if (config.getNumLatents() > 0) {
                runRoutine(this::updateBiasLatentPosteriorExpectations, NOT_APPLICABLE_EXTRACTOR, "E_STEP_Z", iterInfo);
                posteriorErrorNormBias = iterInfo.errorNorm;
            } else {
                posteriorErrorNormBias = 0;
            }

            if (config.sampleSpecificVarianceUpdateEnabled()) {
                runRoutine(this::updateSampleUnexplainedVariance, ITERATION_EXTRACTOR, "E_STEP_GAMMA", iterInfo);
                posteriorErrorNormSampleUnexplainedVariance = iterInfo.errorNorm;
            } else {
                posteriorErrorNormSampleUnexplainedVariance = 0;
            }

            if (updateCopyRatioPosteriors) {
                runRoutine(this::updateCopyRatioLatentPosteriorExpectations, NOT_APPLICABLE_EXTRACTOR, "E_STEP_C", iterInfo);
                posteriorErrorNormCopyRatio = iterInfo.errorNorm;
            } else {
                posteriorErrorNormCopyRatio = 0;
            }

            /* calculate the maximum change of posteriors in this cycle */
            maxPosteriorErrorNorm = Collections.max(Arrays.asList(
                    posteriorErrorNormReadDepth,
                    posteriorErrorNormSampleUnexplainedVariance,
                    posteriorErrorNormBias,
                    posteriorErrorNormCopyRatio));

            prevEStepLikelihood = latestEStepLikelihood;
            latestEStepLikelihood = iterInfo.getLogLikelihood();

            /* check convergence of the E-step */
            if (maxPosteriorErrorNorm < config.getPosteriorAbsTol() &&
                    FastMath.abs(latestEStepLikelihood - prevEStepLikelihood) < config.getLogLikelihoodTolerance()) {
                if (!config.copyRatioUpdateEnabled() || updateCopyRatioPosteriors) {
                    status = EMAlgorithmStatus.SUCCESS_POSTERIOR_CONVERGENCE;
                    break;
                }
            }

            /* if the change in log likelihood is small enough, start updating copy number posteriors */
            if (config.copyRatioUpdateEnabled() && !updateCopyRatioPosteriors &&
                    FastMath.abs(latestEStepLikelihood - prevEStepLikelihood) < config.getLogLikelihoodTolThresholdCRCalling()) {
                updateCopyRatioPosteriors = true;
                logger.info("Partial convergence achieved; starting to update copy ratio posteriors in the next iteration");
            }

            iterInfo.incrementIterationCount();

            if (config.isRunCheckpointingEnabled() && iterInfo.iter % config.getRunCheckpointingInterval() == 0) {
                final String posteriorOutputAbsolutePath = new File(config.getRunCheckpointingPath(),
                        String.format("%s_iter_%d", CoverageModelGlobalConstants.POSTERIOR_CHECKPOINT_PATH_PREFIX, iterInfo.iter)).getAbsolutePath();
                /* the following will automatically create the directory if it doesn't exist */
                savePosteriors(posteriorOutputAbsolutePath, CoverageModelEMWorkspace.PosteriorVerbosityLevel.BASIC);
            }
        }

        if (iterInfo.iter == config.getMaxEMIterations()) {
            status = EMAlgorithmStatus.FAILURE_MAX_ITERS_REACHED;
        }

        performPostEMOperations();

        return status;
    }

    private void performPostEMOperations() {
        logger.info("EM algorithm status: " + status.getMessage());
    }

    /**
     * E-step -- Update E[z] and E[z z^T] for all samples using the current estimate of model parameters
     */
    public SubroutineSignal updateBiasLatentPosteriorExpectations() {
        return workspace.updateBiasLatentPosteriorExpectations();
    }

    /**
     * E-step -- Update E[log(d_s)] and E[log(d_s)^2]
     */
    public SubroutineSignal updateReadDepthLatentPosteriorExpectations() {
        return workspace.updateReadDepthPosteriorExpectations();
    }

    /**
     * E-step -- Update gamma_s
     */
    public SubroutineSignal updateSampleUnexplainedVariance() {
        return workspace.updateSampleUnexplainedVariance();
    }

    /**
     * E-step -- Update E[log(c_{st})] and E[log(c_{st})^2]
     */
    public SubroutineSignal updateCopyRatioLatentPosteriorExpectations() {
        return workspace.updateCopyRatioPosteriorExpectations();
    }

    /**
     * E-step -- Update W
     */
    public SubroutineSignal updateBiasCovariates() {
        return workspace.updateBiasCovariates();
    }

    /**
     * M-step -- Update m
     */
    public SubroutineSignal updateTargetMeanBias(final boolean neglectBiasCovariates) {
        return workspace.updateMeanLogBias(neglectBiasCovariates);
    }

    /**
     * M-step -- Update Psi
     */
    public SubroutineSignal updateTargetUnexplainedVariance(final CoverageModelArgumentCollection.TargetSpecificVarianceUpdateMode targetSpecificVarianceUpdateMode) {
        return workspace.updateTargetUnexplainedVariance(targetSpecificVarianceUpdateMode);
    }

    /**
     * M-step -- Update ARD coefficients
     */
    public SubroutineSignal updateBiasCovariatesARDCoefficients() {
        return workspace.updateBiasCovariatesARDCoefficients();
    }

    /**
     * This routine is called after each EM iteration
     */
    private void finalizeIteration() {
        workspace.performGarbageCollection();
    }

    /**
     * Calculate the log likelihood
     *
     * @return log likelihood
     */
    public double getLogLikelihood() {
        return workspace.getLogLikelihood();
    }

    /**
     * Query the latest status of the EM algorithm (reflecting the data in the workspace)
     *
     * @return an instance of {@link EMAlgorithmStatus}
     */
    public EMAlgorithmStatus getStatus() { return status; }

    /**
     * Save model
     *
     * @param modelOutputPath where to save
     */
    public void saveModel(final String modelOutputPath) {
        workspace.writeModel(modelOutputPath);
    }

    /**
     * Save posteriors
     *
     * @param posteriorOutputPath where to save
     * @param verbosity the verbosity level
     */
    public void savePosteriors(final String posteriorOutputPath, final CoverageModelEMWorkspace.PosteriorVerbosityLevel verbosity) {
        workspace.writePosteriors(posteriorOutputPath, verbosity);
    }

    /**
     * This enum represents the status of the EM algorithm
     */
    public enum EMAlgorithmStatus {
        TBD(false, "Status is not determined yet."),
        SUCCESS_LIKELIHOOD_TOL(true, "Success -- converged in likelihood change tolerance."),
        SUCCESS_PARAMS_TOL(true, "Success -- converged in parameters change tolerance."),
        FAILURE_MAX_ITERS_REACHED(false, "Failure -- maximum iterations reached."),
        SUCCESS_POSTERIOR_CONVERGENCE(true, "Success -- converged in posterior and likelihood change tolerance.");

        private final boolean success;
        private final String message;

        EMAlgorithmStatus(final boolean success, final String message) {
            this.success = success;
            this.message = message;
        }

        public String getMessage() {
            return message;
        }

        public boolean isSuccessful() {
            return success;
        }
    }

    /**
     * This class stores basic info about each iteration of the EM algorithm
     */
    private final class EMAlgorithmIterationInfo {
        private double logLikelihood;
        private double errorNorm;
        private int iter;

        EMAlgorithmIterationInfo(final double logLikelihood, final double errorNorm, final int iter) {
            this.logLikelihood = logLikelihood;
            this.errorNorm = errorNorm;
            this.iter = iter;
        }

        public double getLogLikelihood() {
            return logLikelihood;
        }

        public double getErrorNorm() {
            return errorNorm;
        }

        public int getIterationCount() {
            return iter;
        }

        void incrementIterationCount() {
            iter++;
        }
    }
}


text:
using System;

namespace UnityEditor.TestTools.TestRunner.CommandLineTest
{
    [Serializable]
    internal class ExecutionSettings
    {
        public string TestResultsFile;
        public string DeviceLogsDirectory;
    }
}


text:
/**
 * Le modèle de l'application JWS
 * @author Nicolas Surleraux et Julien Castiaux
 */
package be.ephec.nsjc.jws.model;


text:
#ifndef SHARE_VM_INTERPRETER_INTERPRETER_HPP
#define SHARE_VM_INTERPRETER_INTERPRETER_HPP

#include "code/stubs.hpp"
#include "interpreter/cppInterpreter.hpp"
#include "interpreter/templateInterpreter.hpp"
#ifdef ZERO
#ifdef TARGET_ARCH_zero
# include "entry_zero.hpp"
#endif
#endif

// This file contains the platform-independent parts
// of the interpreter and the interpreter generator.

//------------------------------------------------------------------------------------------------------------------------
// An InterpreterCodelet is a piece of interpreter code. All
// interpreter code is generated into little codelets which
// contain extra information for debugging and printing purposes.

class InterpreterCodelet: public Stub {
  friend class VMStructs;
 private:
  int         _size;                             // the size in bytes
  const char* _description;                      // a description of the codelet, for debugging & printing
  Bytecodes::Code _bytecode;                     // associated bytecode if any

 public:
  // Initialization/finalization
  void    initialize(int size)                   { _size = size; }
  void    finalize()                             { ShouldNotCallThis(); }

  // General info/converters
  int     size() const                           { return _size; }
  static  int code_size_to_size(int code_size)   { return round_to(sizeof(InterpreterCodelet), CodeEntryAlignment) + code_size; }

  // Code info
  address code_begin() const                     { return (address)this + round_to(sizeof(InterpreterCodelet), CodeEntryAlignment); }
  address code_end() const                       { return (address)this + size(); }

  // Debugging
  void    verify();
  void    print_on(outputStream* st) const;
  void    print() const { print_on(tty); }

  // Interpreter-specific initialization
  void    initialize(const char* description, Bytecodes::Code bytecode);

  // Interpreter-specific attributes
  int         code_size() const                  { return code_end() - code_begin(); }
  const char* description() const                { return _description; }
  Bytecodes::Code bytecode() const               { return _bytecode; }
};

// Define a prototype interface
DEF_STUB_INTERFACE(InterpreterCodelet);

//------------------------------------------------------------------------------------------------------------------------
// A CodeletMark serves as an automatic creator/initializer for Codelets
// (As a subclass of ResourceMark it automatically GC's the allocated
// code buffer and assemblers).

class CodeletMark: ResourceMark {
 private:
  InterpreterCodelet*         _clet;
  InterpreterMacroAssembler** _masm;
  CodeBuffer                  _cb;

  int codelet_size() {
    // Request the whole code buffer (minus a little for alignment).
    // The commit call below trims it back for each codelet.
    int codelet_size = AbstractInterpreter::code()->available_space() - 2*K;

    // Guarantee there's a little bit of code space left.
    guarantee (codelet_size > 0 && (size_t)codelet_size >  2*K,
               "not enough space for interpreter generation");

    return codelet_size;
  }

 public:
  CodeletMark(
    InterpreterMacroAssembler*& masm,
    const char* description,
    Bytecodes::Code bytecode = Bytecodes::_illegal):
    _clet((InterpreterCodelet*)AbstractInterpreter::code()->request(codelet_size())),
    _cb(_clet->code_begin(), _clet->code_size())

  { // request all space (add some slack for Codelet data)
    assert (_clet != NULL, "we checked not enough space already");

    // initialize Codelet attributes
    _clet->initialize(description, bytecode);
    // create assembler for code generation
    masm  = new InterpreterMacroAssembler(&_cb);
    _masm = &masm;
  }

  ~CodeletMark() {
    // align so printing shows nop's instead of random code at the end (Codelets are aligned)
    (*_masm)->align(wordSize);
    // make sure all code is in code buffer
    (*_masm)->flush();

    // commit Codelet
    AbstractInterpreter::code()->commit((*_masm)->code()->pure_insts_size());
    // make sure nobody can use _masm outside a CodeletMark lifespan
    *_masm = NULL;
  }
};

// Wrapper classes to produce Interpreter/InterpreterGenerator from either
// the c++ interpreter or the template interpreter.

class Interpreter: public CC_INTERP_ONLY(CppInterpreter) NOT_CC_INTERP(TemplateInterpreter) {

  public:
  // Debugging/printing
  static InterpreterCodelet* codelet_containing(address pc)     { return (InterpreterCodelet*)_code->stub_containing(pc); }
#ifdef TARGET_ARCH_x86
# include "interpreter_x86.hpp"
#endif
#ifdef TARGET_ARCH_sparc
# include "interpreter_sparc.hpp"
#endif
#ifdef TARGET_ARCH_zero
# include "interpreter_zero.hpp"
#endif
#ifdef TARGET_ARCH_arm
# include "interpreter_arm.hpp"
#endif
#ifdef TARGET_ARCH_ppc
# include "interpreter_ppc.hpp"
#endif

};

#endif // SHARE_VM_INTERPRETER_INTERPRETER_HPP


text:
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <defaults public="false" />

        <!-- Bus -->
        <service id="message_bus" class="Symfony\Component\Messenger\MessageBus" public="true">
            <argument type="tagged" tag="message_bus_middleware" /> <!-- Middlewares -->
        </service>

        <service id="Symfony\Component\Messenger\MessageBusInterface" alias="message_bus" />

        <!-- Handlers -->
        <service id="messenger.handler_resolver" class="Symfony\Component\Messenger\ContainerHandlerLocator">
            <argument type="service" id="service_container"/>
        </service>

        <service id="messenger.middleware.call_message_handler" class="Symfony\Component\Messenger\Middleware\HandleMessageMiddleware">
            <argument type="service" id="messenger.handler_resolver" />

            <tag name="message_bus_middleware" priority="-10" />
        </service>

        <service id="messenger.middleware.validator" class="Symfony\Component\Messenger\Middleware\ValidationMiddleware">
            <argument type="service" id="validator" />

            <tag name="message_bus_middleware" priority="100" />
        </service>

        <service id="messenger.middleware.doctrine_transaction" class="Symfony\Bridge\Doctrine\Messenger\DoctrineTransactionMiddleware">
            <argument type="service" id="doctrine" />
            <argument /> <!-- Entity manager name -->

            <tag name="message_bus_middleware" priority="9" />
        </service>

        <!-- Asynchronous -->
        <service id="messenger.asynchronous.routing.sender_locator" class="Symfony\Component\Messenger\Asynchronous\Routing\SenderLocator">
            <argument type="service" id="messenger.sender_locator" />
            <argument /> <!-- Message to sender ID mapping -->
        </service>
        <service id="messenger.asynchronous.middleware.send_message_to_producer" class="Symfony\Component\Messenger\Asynchronous\Middleware\SendMessageMiddleware">
            <argument type="service" id="messenger.asynchronous.routing.sender_locator" />

            <tag name="message_bus_middleware" priority="-5" />
        </service>

        <!-- Message encoding/decoding -->
        <service id="messenger.transport.serialize_message_with_type_in_headers" class="Symfony\Component\Messenger\Transport\Serialization\Serializer">
            <argument type="service" id="serializer" />
        </service>

        <service id="messenger.transport.default_encoder" alias="messenger.transport.serialize_message_with_type_in_headers" public="true" />
        <service id="messenger.transport.default_decoder" alias="messenger.transport.serialize_message_with_type_in_headers" public="true" />

        <!-- Logging & Debug -->
        <service id="messenger.middleware.debug.logging" class="Symfony\Component\Messenger\Debug\LoggingMiddleware">
            <argument type="service" id="logger" />

            <tag name="message_bus_middleware" priority="10" />
            <tag name="monolog.logger" channel="messenger" />
        </service>

        <service id="data_collector.messenger" class="Symfony\Bundle\FrameworkBundle\DataCollector\MessengerDataCollector">
            <tag name="data_collector" template="@WebProfiler/Collector/messenger.html.twig" id="messenger" priority="100" />
            <tag name="message_bus_middleware" />
        </service>

        <!-- Discovery -->
        <service id="messenger.receiver_locator">
            <tag name="container.service_locator" />
            <argument type="collection" />
        </service>
        <service id="messenger.sender_locator">
            <tag name="container.service_locator" />
            <argument type="collection" />
        </service>
    </services>
</container>


text:
.cjw-paged-list-select
{
}

.cjw-paged-list-select-disabled
{
}

.cjw-paged-list-select-container
{
	display: inline-block;
	overflow: hidden;
}

.cjw-paged-list-select-control
{
	display: inline-block;
	vertical-align: top;
	position: relative;
}

.cjw-paged-list-select-control-next
{
	position: absolute;
	bottom: 0px;
}

.cjw-paged-list-select-control-prev
{
	position: absolute;
	top: 0px;
}

.cjw-paged-list-select-page
{
	overflow: hidden;
}

.cjw-paged-list-select-item
{
	display: inline-block;
	position: relative;
	border: solid 1px #666;
	vertical-align: top;
}

.cjw-paged-list-select-item-selected
{
	border: solid 1px #E96;
}

.cjw-paged-list-select-item-label
{
}

.cjw-paged-list-select-item:hover
{
}

.cjw-paged-list-select-message
{
}

.cjw-paged-list-select-message-hidden
{
	display:none;
}


text:
var fs = require('hexo-fs');
var pathFn = require('path');
var Promise = require('bluebird');
var prettyHrtime = require('pretty-hrtime');
var chalk = require('chalk');
var _ = require('lodash');

function generateConsole(args){
  var route = this.route;
  var publicDir = this.public_dir;
  var log = this.log;
  var self = this;
  var start = process.hrtime();

  function generateFile(path){
    var data = route.get(path);
    var dest = pathFn.join(publicDir, path);

    // TODO: Retry when EMFILE error occurred
    return fs.ensureWriteStream(dest).then(function(stream){
      return pipeStream(data, stream);
    }).then(function(){
      log.info('Generated: %s', chalk.magenta(path));
    });
  }

  function deleteFile(path){
    var dest = pathFn.join(publicDir, path);

    return fs.unlink(dest).then(function(){
      log.info('Deleted: %s', chalk.magenta(path));
    }, function(err){
      // Skip ENOENT errors (file was deleted)
      if (err.cause.code !== 'ENOENT') throw err;
    });
  }

  function generateFiles(files){
    var list = route.list();

    return Promise.filter(list, function(path){
      // Skip a file which has existed already and is not modified
      var modified = route.isModified(path);
      return modified || !~files.indexOf(path);
    }).map(generateFile).then(function(arr){
      // Return the number of files generated
      return arr.length;
    });
  }

  function cleanFiles(files){
    var deleted = _.difference(files, route.list());

    return Promise.each(deleted, deleteFile);
  }

  function firstGenerate(){
    // Show the loading time
    var interval = prettyHrtime(process.hrtime(start));
    log.info('Files loaded in %s', chalk.cyan(interval));

    // Reset the timer for later usage
    start = process.hrtime();

    // Check the existance of public folder
    return fs.exists(publicDir).then(function(exist){
      if (!exist){
        // Create public folder if not exist
        return fs.mkdirs(publicDir);
      }

      // Get current file list in public folder
      return fs.listDir(publicDir).map(function(path){
        return path.replace(/\\/g, '/');
      });
    }).then(function(files){
      files = files || [];

      return Promise.all([
        generateFiles(files),
        cleanFiles(files)
      ]);
    }).spread(function(count){
      var interval = prettyHrtime(process.hrtime(start));
      log.info('%d files generatd in %s', count, chalk.cyan(interval));
    });
  }

  if (args.w || args.watch){
    return this.watch().then(firstGenerate).then(function(){
      log.info('Hexo is watching for file changes. Press Ctrl+C to exit.');

      // Watch changes of the route
      route.on('update', function(path){
        var modified = route.isModified(path);
        if (!modified) return;

        generateFile(path);
      });
    });
  }

  return this.load().then(firstGenerate).then(function(){
    if (args.d || args.deploy){
      return self.call('deploy', args);
    }
  });
}

// Pipe a stream from one to another
function pipeStream(rs, ws){
  return new Promise(function(resolve, reject){
    rs.pipe(ws)
      .on('error', reject);

    ws.on('close', resolve)
      .on('error', reject);
  });
}

module.exports = generateConsole;


text:
require 'spec_helper'

describe GH::Pagination do
  before { subject.backend = GH::MockBackend.new }

  it 'paginates' do
    counter = subject['users/rkh/repos'].map { 1 }.reduce(:+) # map/reduce!
    counter.should be > 120
  end

  it 'paginates with GH::Normalizer' do
    subject.backend = GH::Normalizer.new subject.backend
    counter = subject['users/rkh/repos'].map { 1 }.reduce(:+) # map/reduce!
    counter.should be > 120
  end

  it 'paginates on default stack' do
    counter = GH['users/rkh/repos'].map { 1 }.reduce(:+) # map/reduce!
    counter.should be > 120
  end

  it 'gives random access' do
    data = subject['users/rkh/repos']
    data.each_with_index do |value, index|
      data[index].should be == value
    end
  end

  it 'does not wrap hash responses' do
    subject['users/rkh'].should_not be_a(GH::Pagination::Paginated)
  end
end


text:
module Fayde.Collections {
    export enum CollectionChangedAction {
        Add = 1,
        Remove = 2,
        Replace = 3,
        Reset = 4,
    }
    Fayde.CoreLibrary.addEnum(CollectionChangedAction, "NotifyCollectionChangedAction");

    export class CollectionChangedEventArgs implements nullstone.IEventArgs {
        Action: CollectionChangedAction;
        OldStartingIndex: number;
        NewStartingIndex: number;
        OldItems: any[];
        NewItems: any[];

        static Reset(allValues: any[]): CollectionChangedEventArgs {
            var args = new CollectionChangedEventArgs();
            Object.defineProperty(args, "Action", { value: CollectionChangedAction.Reset, writable: false });
            Object.defineProperty(args, "OldStartingIndex", { value: 0, writable: false });
            Object.defineProperty(args, "NewStartingIndex", { value: -1, writable: false });
            Object.defineProperty(args, "OldItems", { value: allValues, writable: false });
            Object.defineProperty(args, "NewItems", { value: null, writable: false });
            return args;
        }
        static Replace(newValue: any, oldValue: any, index: number): CollectionChangedEventArgs {
            var args = new CollectionChangedEventArgs();
            Object.defineProperty(args, "Action", { value: CollectionChangedAction.Replace, writable: false });
            Object.defineProperty(args, "OldStartingIndex", { value: -1, writable: false });
            Object.defineProperty(args, "NewStartingIndex", { value: index, writable: false });
            Object.defineProperty(args, "OldItems", { value: [oldValue], writable: false });
            Object.defineProperty(args, "NewItems", { value: [newValue], writable: false });
            return args;
        }
        static Add(newValue: any, index: number): CollectionChangedEventArgs {
            var args = new CollectionChangedEventArgs();
            Object.defineProperty(args, "Action", { value: CollectionChangedAction.Add, writable: false });
            Object.defineProperty(args, "OldStartingIndex", { value: -1, writable: false });
            Object.defineProperty(args, "NewStartingIndex", { value: index, writable: false });
            Object.defineProperty(args, "OldItems", { value: null, writable: false });
            Object.defineProperty(args, "NewItems", { value: [newValue], writable: false });
            return args;
        }
        static AddRange(newValues: any[], index: number): CollectionChangedEventArgs {
            var args = new CollectionChangedEventArgs();
            Object.defineProperty(args, "Action", { value: CollectionChangedAction.Add, writable: false });
            Object.defineProperty(args, "OldStartingIndex", { value: -1, writable: false });
            Object.defineProperty(args, "NewStartingIndex", { value: index, writable: false });
            Object.defineProperty(args, "OldItems", { value: null, writable: false });
            Object.defineProperty(args, "NewItems", { value: newValues, writable: false });
            return args;
        }
        static Remove(oldValue: any, index: number): CollectionChangedEventArgs {
            var args = new CollectionChangedEventArgs();
            Object.defineProperty(args, "Action", { value: CollectionChangedAction.Remove, writable: false });
            Object.defineProperty(args, "OldStartingIndex", { value: index, writable: false });
            Object.defineProperty(args, "NewStartingIndex", { value: -1, writable: false });
            Object.defineProperty(args, "OldItems", { value: [oldValue], writable: false });
            Object.defineProperty(args, "NewItems", { value: null, writable: false });
            return args;
        }
    }
}


text:
<?php

namespace Storeman\Test\Tree;

abstract class AbstractTreeGenerator implements TreeGeneratorInterface
{
    protected function generateChildName(TreeNode $treeNode): string
    {
        do
        {
            $name = uniqid();
        }
        while($treeNode->getChildByName($name) !== null);

        return $name;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<RecordType xmlns="http://soap.sforce.com/2006/04/metadata">
    <fullName>Diploma</fullName>
    <active>true</active>
    <compactLayoutAssignment>EDA_Academic_Certification_Compact_Layout</compactLayoutAssignment>
    <description>A certification related to the completion of a course of study, such as a high school diploma in the United States.</description>
    <label>Diploma</label>
    <picklistValues>
        <picklist>Academic_Level__c</picklist>
        <values>
            <fullName>Adult Education</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>Doctoral</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>Elementary</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>Graduate</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>High School</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>Middle School</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>Post-Baccalaureate Certificate</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>Pre-K%2FPreschool</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>Professional Education</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>Undergraduate</fullName>
            <default>false</default>
        </values>
    </picklistValues>
    <picklistValues>
        <picklist>Field_Of_Study__c</picklist>
        <values>
            <fullName>Agriculture</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>Architecture</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>Biology</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>Business%2C Management%2C and Marketing</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>Communications</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>Computer and Information Sciences</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>Education</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>Engineering</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>English Language%2C Literature%2C and Letters</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>Family and Consumer Sciences</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>Foreign Languages</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>General Studies and Humanities</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>Health Professions</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>History</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>Legal Professions and Studies</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>Mathematics and Statistics</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>Natural Resources and Conservation</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>Philosophy and Religious Studies</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>Physical Sciences</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>Psychology</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>Social Sciences</fullName>
            <default>false</default>
        </values>
        <values>
            <fullName>Visual and Performing Arts</fullName>
            <default>false</default>
        </values>
    </picklistValues>
</RecordType>


text:
"""
Test that lldb watchpoint works for multiple threads.
"""

from __future__ import print_function

import os
import time
import re
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil

class WatchpointForMultipleThreadsTestCase(TestBase):

    mydir = TestBase.compute_mydir(__file__)
    NO_DEBUG_INFO_TESTCASE = True
    main_spec = lldb.SBFileSpec("main.cpp", False)

    @expectedFailureAll(
        oslist=["windows"],
        bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows")
    def test_watchpoint_before_thread_start(self):
        """Test that we can hit a watchpoint we set before starting another thread"""
        self.do_watchpoint_test("Before running the thread")

    @expectedFailureAll(
        oslist=["windows"],
        bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows")
    def test_watchpoint_after_thread_start(self):
        """Test that we can hit a watchpoint we set after starting another thread"""
        self.do_watchpoint_test("After running the thread")

    def do_watchpoint_test(self, line):
        self.build()
        lldbutil.run_to_source_breakpoint(self, line, self.main_spec)

        # Now let's set a write-type watchpoint for variable 'g_val'.
        self.expect(
            "watchpoint set variable -w write g_val",
            WATCHPOINT_CREATED,
            substrs=[
                'Watchpoint created',
                'size = 4',
                'type = w'])

        # Use the '-v' option to do verbose listing of the watchpoint.
        # The hit count should be 0 initially.
        self.expect("watchpoint list -v",
                    substrs=['hit_count = 0'])

        self.runCmd("process continue")

        self.runCmd("thread list")
        if "stop reason = watchpoint" in self.res.GetOutput():
            # Good, we verified that the watchpoint works!
            self.runCmd("thread backtrace all")
        else:
            self.fail("The stop reason should be either break or watchpoint")

        # Use the '-v' option to do verbose listing of the watchpoint.
        # The hit count should now be 1.
        self.expect("watchpoint list -v",
                    substrs=['hit_count = 1'])

    @expectedFailureAll(
        oslist=["windows"],
        bugnumber="llvm.org/pr24446: WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows")
    def test_watchpoint_multiple_threads_wp_set_and_then_delete(self):
        """Test that lldb watchpoint works for multiple threads, and after the watchpoint is deleted, the watchpoint event should no longer fires."""
        self.build()
        self.setTearDownCleanup()

        lldbutil.run_to_source_breakpoint(self, "After running the thread", self.main_spec)

        # Now let's set a write-type watchpoint for variable 'g_val'.
        self.expect(
            "watchpoint set variable -w write g_val",
            WATCHPOINT_CREATED,
            substrs=[
                'Watchpoint created',
                'size = 4',
                'type = w'])

        # Use the '-v' option to do verbose listing of the watchpoint.
        # The hit count should be 0 initially.
        self.expect("watchpoint list -v",
                    substrs=['hit_count = 0'])

        watchpoint_stops = 0
        while True:
            self.runCmd("process continue")
            self.runCmd("process status")
            if re.search("Process .* exited", self.res.GetOutput()):
                # Great, we are done with this test!
                break

            self.runCmd("thread list")
            if "stop reason = watchpoint" in self.res.GetOutput():
                self.runCmd("thread backtrace all")
                watchpoint_stops += 1
                if watchpoint_stops > 1:
                    self.fail(
                        "Watchpoint hits not supposed to exceed 1 by design!")
                # Good, we verified that the watchpoint works!  Now delete the
                # watchpoint.
                if self.TraceOn():
                    print(
                        "watchpoint_stops=%d at the moment we delete the watchpoint" %
                        watchpoint_stops)
                self.runCmd("watchpoint delete 1")
                self.expect("watchpoint list -v",
                            substrs=['No watchpoints currently set.'])
                continue
            else:
                self.fail("The stop reason should be either break or watchpoint")