text:
require 'rdoc/test_case'

class TestRDocMarkupPreProcess < RDoc::TestCase

  def setup
    super

    @tempfile = Tempfile.new 'test_rdoc_markup_pre_process'
    @file_name = File.basename @tempfile.path
    @dir  = File.dirname @tempfile.path

    @pp = RDoc::Markup::PreProcess.new __FILE__, [@dir]
  end

  def teardown
    super

    @tempfile.close
  end

  def test_class_register
    RDoc::Markup::PreProcess.register 'for_test' do raise 'fail' end

    assert_equal %w[for_test], RDoc::Markup::PreProcess.registered.keys
  end

  def test_class_post_process
    RDoc::Markup::PreProcess.post_process do end

    assert_equal 1, RDoc::Markup::PreProcess.post_processors.length
  end

  def test_include_file
    @tempfile.write <<-INCLUDE
# -*- mode: rdoc; coding: utf-8; fill-column: 74; -*-

Regular expressions (regexps) are patterns which describe the
contents of a string.
    INCLUDE

    @tempfile.flush
    @tempfile.rewind

    content = @pp.include_file @file_name, '', nil

    expected = <<-EXPECTED
Regular expressions (regexps) are patterns which describe the
contents of a string.
    EXPECTED

    assert_equal expected, content
  end

  def test_include_file_encoding_incompatible
    skip "Encoding not implemented" unless Object.const_defined? :Encoding

    @tempfile.write <<-INCLUDE
# -*- mode: rdoc; coding: utf-8; fill-column: 74; -*-

π
    INCLUDE

    @tempfile.flush
    @tempfile.rewind

    content = @pp.include_file @file_name, '', Encoding::US_ASCII

    expected = "?\n"

    assert_equal expected, content
  end

  def test_handle
    text = "# :main: M\n"
    out = @pp.handle text

    assert_same out, text
    assert_equal "#\n", text
  end

  def test_handle_comment
    text = "# :main: M\n"
    c = comment text

    out = @pp.handle c

    assert_same out, text
    assert_equal "#\n", text
  end

  def test_handle_markup
    c = comment ':markup: rd'

    @pp.handle c

    assert_equal 'rd', c.format
  end

  def test_handle_markup_empty
    c = comment ':markup:'

    @pp.handle c

    assert_equal 'rdoc', c.format
  end

  def test_handle_post_process
    cd = RDoc::CodeObject.new

    RDoc::Markup::PreProcess.post_process do |text, code_object|
      code_object.metadata[:stuff] = text

      :junk
    end

    text = "# a b c\n"

    out = @pp.handle text, cd

    assert_same out, text
    assert_equal "# a b c\n", text
    assert_equal "# a b c\n", cd.metadata[:stuff]
  end

  def test_handle_unregistered
    text = "# :x: y\n"
    out = @pp.handle text

    assert_same out, text
    assert_equal "# :x: y\n", text
  end

  def test_handle_directive_blankline
    result = @pp.handle_directive '#', 'arg', 'a, b'

    assert_equal "#\n", result
  end

  def test_handle_directive_downcase
    method = RDoc::AnyMethod.new nil, 'm'

    @pp.handle_directive '', 'ARG', 'a, b', method

    assert_equal 'a, b', method.params
  end

  def test_handle_directive_arg
    method = RDoc::AnyMethod.new nil, 'm'

    @pp.handle_directive '', 'arg', 'a, b', method

    assert_equal 'a, b', method.params
  end

  def test_handle_directive_arg_no_context
    result = @pp.handle_directive '', 'arg', 'a, b', nil

    assert_equal "\n", result
  end

  def test_handle_directive_args
    method = RDoc::AnyMethod.new nil, 'm'

    @pp.handle_directive '', 'args', 'a, b', method

    assert_equal 'a, b', method.params
  end

  def test_handle_directive_block
    result = @pp.handle_directive '', 'x', 'y' do |directive, param|
      ''
    end

    assert_empty result
  end

  def test_handle_directive_block_false
    result = @pp.handle_directive '', 'x', 'y' do |directive, param|
      false
    end

    assert_equal ":x: y\n", result
  end

  def test_handle_directive_block_nil
    result = @pp.handle_directive '', 'x', 'y' do |directive, param|
      nil
    end

    assert_equal ":x: y\n", result
  end

  def test_handle_directive_category
    context = RDoc::Context.new
    original_section = context.current_section

    @pp.handle_directive '', 'category', 'other', context

    refute_equal original_section, context.current_section
  end

  def test_handle_directive_doc
    code_object = RDoc::CodeObject.new
    code_object.document_self = false
    code_object.force_documentation = false

    @pp.handle_directive '', 'doc', nil, code_object

    assert code_object.document_self
    assert code_object.force_documentation
  end

  def test_handle_directive_doc_no_context
    result = @pp.handle_directive '', 'doc', nil

    assert_equal "\n", result
  end

  def test_handle_directive_enddoc
    code_object = RDoc::CodeObject.new

    @pp.handle_directive '', 'enddoc', nil, code_object

    assert code_object.done_documenting
  end

  def test_handle_directive_include
    @tempfile.write 'included'
    @tempfile.flush

    result = @pp.handle_directive '', 'include', @file_name

    assert_equal 'included', result
  end

  def test_handle_directive_main
    @pp.options = RDoc::Options.new

    @pp.handle_directive '', 'main', 'M'

    assert_equal 'M', @pp.options.main_page
  end

  def test_handle_directive_notnew
    m = RDoc::AnyMethod.new nil, 'm'

    @pp.handle_directive '', 'notnew', nil, m

    assert m.dont_rename_initialize
  end

  def test_handle_directive_not_new
    m = RDoc::AnyMethod.new nil, 'm'

    @pp.handle_directive '', 'not_new', nil, m

    assert m.dont_rename_initialize
  end

  def test_handle_directive_not_dash_new
    m = RDoc::AnyMethod.new nil, 'm'

    @pp.handle_directive '', 'not-new', nil, m

    assert m.dont_rename_initialize
  end

  def test_handle_directive_nodoc
    code_object = RDoc::CodeObject.new
    code_object.document_self = true
    code_object.document_children = true

    @pp.handle_directive '', 'nodoc', nil, code_object

    refute code_object.document_self
    assert code_object.document_children
  end

  def test_handle_directive_nodoc_all
    code_object = RDoc::CodeObject.new
    code_object.document_self = true
    code_object.document_children = true

    @pp.handle_directive '', 'nodoc', 'all', code_object

    refute code_object.document_self
    refute code_object.document_children
  end

  def test_handle_directive_nodoc_no_context
    result = @pp.handle_directive '', 'nodoc', nil

    assert_equal "\n", result
  end

  def test_handle_directive_registered
    RDoc::Markup::PreProcess.register 'x'

    result = @pp.handle_directive '', 'x', 'y'

    assert_nil result

    result = @pp.handle_directive '', 'x', 'y' do |directive, param|
      false
    end

    assert_equal ":x: y\n", result

    result = @pp.handle_directive '', 'x', 'y' do |directive, param|
      ''
    end

    assert_equal '', result
  end

  def test_handle_directive_registered_block
    called = nil

    RDoc::Markup::PreProcess.register 'x' do |directive, param|
      called = [directive, param]
      'blah'
    end

    result = @pp.handle_directive '', 'x', 'y'

    assert_equal 'blah', result
    assert_equal %w[x y], called
  end

  def test_handle_directive_registered_code_object
    RDoc::Markup::PreProcess.register 'x'
    code_object = RDoc::CodeObject.new

    @pp.handle_directive '', 'x', 'y', code_object

    assert_equal 'y', code_object.metadata['x']

    code_object.metadata.clear

    result = @pp.handle_directive '', 'x', 'y' do |directive, param|
      false
    end

    assert_equal ":x: y\n", result
    assert_empty code_object.metadata

    result = @pp.handle_directive '', 'x', 'y' do |directive, param|
      ''
    end

    assert_equal '', result
    assert_empty code_object.metadata
  end

  def test_handle_directive_startdoc
    code_object = RDoc::CodeObject.new
    code_object.stop_doc
    code_object.force_documentation = false

    @pp.handle_directive '', 'startdoc', nil, code_object

    assert code_object.document_self
    assert code_object.document_children
    assert code_object.force_documentation
  end

  def test_handle_directive_stopdoc
    code_object = RDoc::CodeObject.new

    @pp.handle_directive '', 'stopdoc', nil, code_object

    refute code_object.document_self
    refute code_object.document_children
  end

  def test_handle_directive_title
    @pp.options = RDoc::Options.new

    @pp.handle_directive '', 'title', 'T'

    assert_equal 'T', @pp.options.title
  end

  def test_handle_directive_unhandled
    code_object = RDoc::CodeObject.new

    @pp.handle_directive '', 'x', 'y', code_object

    assert_equal 'y', code_object.metadata['x']

    code_object.metadata.clear

    @pp.handle_directive '', 'x', '', code_object

    assert_includes code_object.metadata, 'x'
  end

  def test_handle_directive_unhandled_block
    code_object = RDoc::CodeObject.new

    @pp.handle_directive '', 'x', 'y', code_object do
      false
    end

    assert_empty code_object.metadata

    @pp.handle_directive '', 'x', 'y', code_object do
      nil
    end

    assert_equal 'y', code_object.metadata['x']

    code_object.metadata.clear

    @pp.handle_directive '', 'x', 'y', code_object do
      ''
    end

    assert_empty code_object.metadata
  end

  def test_handle_directive_yield
    method = RDoc::AnyMethod.new nil, 'm'
    method.params = 'index, &block'

    @pp.handle_directive '', 'yield', 'item', method

    assert_equal 'item', method.block_params
    assert_equal 'index', method.params
  end

  def test_handle_directive_yield_block_param
    method = RDoc::AnyMethod.new nil, 'm'
    method.params = '&block'

    @pp.handle_directive '', 'yield', 'item', method

    assert_equal 'item', method.block_params
    assert_empty method.params
  end

  def test_handle_directive_yield_no_context
    method = RDoc::AnyMethod.new nil, 'm'

    @pp.handle_directive '', 'yield', 'item', method

    assert_equal 'item', method.block_params
  end

  def test_handle_directive_yields
    method = RDoc::AnyMethod.new nil, 'm'

    @pp.handle_directive '', 'yields', 'item', method

    assert_equal 'item', method.block_params
  end

end


text:
/**!
 * AngularJS Nested Resource
 * @author  Roy  <peled.roy@gmail.com>
 * @version 2.0.0
 */
(function() {
    var angularNested = angular.module('ngNestedResource', []);

    angularNested.factory('nestedResource', ['$http', '$q', function($http, $q) {

        var noop = angular.noop,
            forEach = angular.forEach,
            extend = angular.extend,
            copy = angular.copy,
            isFunction = angular.isFunction,
            isObject = angular.isObject;

        var KEYS_TO_REMOVE = {
            params: true, isArray: true, interceptor: true, construct: true, nested: true, route: true
        }

        function cleanParams(params){
            var result = {};
            forEach(params, function(value, key){
                if(!/^\$/.test(key))
                    result[key] = value;
            });
            return result;
        }

        function defaultResponseInterceptor(response) {
            return response;
        }

        function Route(template){
            var builtRoute = template;

            return {
                build: function(param){
                    if(typeof param == "object") {
                        builtRoute = template.replace(/@([^/]*)/, function(match, group){
                            return param[group];
                        });
                    } else
                        builtRoute = template.replace(/@([^/]*)/, param);

                    isBuilt = true;
                },
                parameterize: function(obj){
                    if(!obj)
                        return;

                    builtRoute = builtRoute.replace(/:([^/]*)/gi, function(match, group){
                        return obj[group];
                    });
                },
                url: function(){
                    return builtRoute;
                },
                template: function(){
                    return template;
                }

            }
        }

        return (function Factory(root, setup, type){

            var constructObject, rootObject;

            type = type || "resource";

            function NestedAction(parentRoute, setupParams){

                var currentRoute, httpConfig = {}, parameters, FutureActions;

                var DEFAULT_SETTINGS = {
                    method: "GET",
                    route: ""
                }

                forEach(setupParams, function(value, key) {
                    if (!KEYS_TO_REMOVE[key]) {
                        httpConfig[key] = copy(value);
                    }
                });

                return function callNestedAction(param, payload, success, error){
                    /**
                     * Fallback variables
                     */
                    if(isObject(param)){
                        error = success;
                        success = payload
                        payload = param;
                        param = null;
                    } else if(isFunction(param)){
                        error = payload;
                        success = param;
                        payload = {};
                        param = null;
                    } else if(isFunction(payload)){
                        error = success;
                        success = payload;
                        payload = {};
                    }

                    parameters = copy(payload || {});
                    extend(parameters, this);

                    currentRoute = new Route(parentRoute.url() + (setupParams.route || DEFAULT_SETTINGS.route));
                    FutureActions = innerStepFactory(currentRoute, setupParams.nested);

                    currentRoute.build(param || parameters);
                    currentRoute.parameterize(parameters);

                    httpConfig.url = currentRoute.url();

                    // If the request if GET, send in querystring only the supplied arguments. Else (PUT, POST, DELETE), send the entire object:
                    if(httpConfig.method == "GET")
                        httpConfig.params = payload;
                    else
                        httpConfig.data = cleanParams(parameters);

                    var responseInterceptor = setupParams.interceptor && setupParams.interceptor.response ||
                        defaultResponseInterceptor;
                    var responseErrorInterceptor = setupParams.interceptor && setupParams.interceptor.responseError ||
                        undefined;

                    var value;
                    if(setupParams.isArray)
                        value = [];
                    else if(!setupParams.scoped)
                        value = this.$$type ? this : new FutureActions(this);
                    else
                        value =  new FutureActions();

                    var result = $http(httpConfig)
                        .then(function(response){
                            var data = response.data;

                            if (data) {
                                if (setupParams.isArray) {
                                    if(setupParams.iterator){
                                        var wrapped = setupParams.iterator(data, function(item){
                                            return new FutureActions(item, true);
                                        });
                                        value = value.concat(wrapped);
                                    } else {
                                        for (var i = 0; i < data.length; i++) {
                                            value.push(new FutureActions(data[i], true));
                                        }
                                    }
                                } else if(isObject(data)) {
                                    extend(value, data);
                                }
                            }

                            response.resource = value;

                            return response;

                        }, function(response) {

                            (error||noop)(response);

                            return $q.reject(response);
                        });

                    result = result.then(
                        function(response) {
                            var value = responseInterceptor(response.resource);
                            (success||noop)(value, response.headers);
                            return value;
                        },
                        responseErrorInterceptor);

                    return value;

                }

            }

            function rootStepFactory(baseRoute, setupActions){
                var actions = {};

                function NestedResource(data){
                    if(data && constructObject)
                        data = new constructObject(data);
                    else
                        extend(this, actions);
                    extend(this, data);
                }

                NestedResource.prototype["$$type"] = type;

                forEach(setupActions, function(action, name){
                    actions[name] = new NestedAction(baseRoute, action);
                });

                extend(NestedResource, actions);

                return NestedResource;
            }

            function innerStepFactory(baseRoute, setupActions){
                if(!setupActions)
                    return constructObject || rootObject;

                var actions = {};

                function NestedResource(data){
                    extend(this, data);
                    extend(this, actions);
                }

                actions["$$type"] = type;

                forEach(setupActions, function(action, name){
                    actions["$" + name] = new NestedAction(baseRoute, action);
                });

                return NestedResource;
            }

            function constructStepFactory(baseRoute, setupActions){
                forEach(setupActions, function(action, name){
                    if(action.construct) {
                        var newRoute = new Route(baseRoute.url() + action.route)
                        constructObject = innerStepFactory(newRoute, action.nested);
                    }
                });
            }

            var root = new Route(root);

            constructStepFactory(root, setup);

            rootObject = rootStepFactory(root, setup);

            return rootObject;

        })

    }]);
})();

redpajama_set_name: RedPajamaGithub


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

 /**
 * Export It - JSON Library
 *
 * A wrapper to create JSON
 *
 * @package 	mithra62:Export_it
 * @author		Eric Lamb
 * @filesource 	./system/expressionengine/third_party/export_it/libraries/Export_data/Export_json.php
 */
class Export_json
{
	public function __construct()
	{
		$this->EE =& get_instance();
	}

	public function generate(array $arr)
	{
		if(!isset($this->EE->javascript))
		{
			$this->EE->load->library('javascript');
		}
		return $this->EE->javascript->generate_json($arr);
	}
}


text:
import click
import os

from . import settings
from .formats import readers, writers

PLUGIN_BOILERPLATE = '''# tackle plugin

def read_x(f, options):
    """Describe x"""

def write_x(data, options):
    """Describe x"""

TACKLE_READER_FORMATS = {
    'json': read_x,
}

TACKLE_WRITER_FORMATS = {
    'json': write_x,
}
'''

def mkdir(path):
    try:
        os.mkdir(path)
    except OSError, e:
        raise click.ClickException("Coudn't create directory: %s" % e)

def touch(filename):
    try:
        f = open(filename, 'w')
        f.write('')
    except Exception, e:
        raise click.ClickException("Coudn't create file: %s" % e)

@click.group()
def mgmt():
    """Tackle management commands"""

@mgmt.command()
@click.option('--path', type=click.Path(exists=False),
              default=settings.plugin_dir())
def createdir(path):
    """Create tackle directory"""
    if os.path.exists(path):
        click.echo("Path %s already exists." % path)
    else:
        mkdir(path)
        click.echo("Created tackle directory %s" % path)

    pluginpath = os.path.join(path, "plugins")
    if not os.path.exists(pluginpath):
        mkdir(pluginpath)
    initpy = os.path.join(pluginpath, '__init__.py')
    if not os.path.exists(initpy):
        touch(os.path.join(initpy))
    click.echo("You can now place plugins in %s" % pluginpath)

@mgmt.command()
@click.argument('name')
def createplugin(name):
    """Create tackle plugin"""
    try:
        if not name.endswith(".py"):
            name += ".py"
        path = os.path.join(settings.plugin_dir(), name)
        if (os.path.exists(path)):
            raise click.ClickException("File %s already exists, not rewriting.")
        f = open(path, 'w')
        f.write(PLUGIN_BOILERPLATE)
    except Exception, e:
        raise click.ClickException("Couldn't create plugin: %s" % e)
    else:
        click.echo("Wrote plugin %s" % path)
        click.launch(path)

def firstline(obj):
    return obj.splitlines()[0] if isinstance(obj, str) and len(obj) else ""

@mgmt.command()
@click.option('-r', '--readers', 'showread', is_flag=True, help='show only readers')
@click.option('-w', '--writers', 'showwrite', is_flag=True, help='show only writers')
def show(showread, showwrite):
    """Show available formatters"""
    showall = showread == showwrite
    if showread or showall:
        click.echo("Readers:")
        for r, fun in readers.iteritems():
            click.echo("\t%s\t\t%s" % (r, firstline(fun.__doc__)))
    if showwrite or showall:
        click.echo("Writers:")
        for r, fun in writers.iteritems():
            click.echo("\t%s\t\t%s" % (r, fun.__doc__))


text:
(function () {
    "use strict";

    /* local storage used to enable longterm storage
     * could fall back or use cookies but for this demo only local storage is used
    */
    var localstore = {
        init: function () {
            //localStorage initalisation or falback code could be added here
        },
        get: function (key) {
            return localStorage[key];

        },
        set: function (key, value) {
            localStorage.setItem(key, value);
        }
    };

    window.localstore = localstore;
}());


text:
layout: page
title: Storm Electronics Trade Fair
date: 2016-05-24
author: Thomas Rubio
tags: weekly links, java
status: published
summary: Nulla varius tortor ac tellus dictum, eget convallis.
banner: images/banner/leisure-03.jpg
booking:
  startDate: 08/29/2019
  endDate: 09/02/2019
  ctyhocn: TCCHHHX
  groupCode: SETF
published: true
---
Aenean elit elit, pharetra in finibus vitae, mattis at ipsum. Cras blandit scelerisque lobortis. Sed tincidunt tempor scelerisque. Etiam at neque arcu. Proin vel tellus a urna sollicitudin aliquam. Donec interdum finibus sem, eu rhoncus arcu ornare at. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed id velit sem. Ut a erat enim. In at maximus enim, at lobortis tellus.
Etiam commodo eros dolor, sit amet egestas risus maximus a. Nulla vel sem non mi interdum blandit. Vestibulum venenatis pharetra lacus, id posuere tellus pulvinar eu. Praesent blandit mollis est et commodo. Ut accumsan nisi eros, a fermentum tellus vehicula non. Sed eget consequat magna, non aliquam arcu. In bibendum, nisl ac aliquam laoreet, felis leo sollicitudin leo, at egestas odio velit ut nunc.

* Nulla lacinia ex vel sapien feugiat, ut euismod sem bibendum
* Maecenas vel neque semper, congue libero ut, finibus ante
* Integer tempor mi in semper viverra
* Praesent eu urna ut libero placerat maximus eu ut massa.

Maecenas felis nulla, tempor eu condimentum eget, molestie nec sem. In molestie, dui vel dapibus euismod, lectus urna mollis odio, ac finibus sem urna vitae odio. Vestibulum at metus facilisis diam iaculis rutrum. Nam malesuada libero consectetur aliquet laoreet. Aliquam tempus quam ac tortor sollicitudin, quis accumsan lacus auctor. Nam vestibulum tellus quis velit tincidunt vestibulum. Quisque ultrices imperdiet tortor et scelerisque. Aenean fermentum ipsum at mi dictum aliquet. Duis sapien lacus, maximus at eros quis, ullamcorper volutpat quam. Suspendisse a magna et lacus auctor maximus et vel tellus. Donec luctus pretium nibh, ut lacinia risus dignissim non. Integer quis ex laoreet, luctus turpis nec, malesuada neque. Duis pretium sem sit amet magna tempus, sed maximus enim feugiat. Nam faucibus, nisl quis placerat pretium, massa lacus commodo metus, sit amet varius ligula massa non magna. Fusce id ante vitae nunc luctus fringilla.


text:
Logging. Home Work 1
===============

[![Join the chat at https://gitter.im/changerequest/logging.hw1](https://badges.gitter.im/changerequest/logging.hw1.svg)](https://gitter.im/changerequest/logging.hw1?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

1 SLF4J + Logback
-----------------

 1. Add latest dependencies of SLF4J + Logback.
 2. Add logging messages with TRACE, DEBUG, INFO, WARN, ERROR levels for modules:
    * **in-memory-storage**, on each of CRUD operations
    * **api**, for each repository class and basket api
    * **store**, for each class

NOTE: Your log messages **must** be meaningful have appropriate log level.

2 Custom Logback configuration
------------------------------

Create custom Logback configuration.

* **in-memory-storage**:
  * should print messages with level TRACE and above to console;
  * should print messages with level WARN and above to file;
* **api**:
  * should print messages with level INFO and above to console;
  * should print messages with exactly WARN level to HTML file
* **store**:
  * should print messages with DEBUG level to console

3 Rolling File Appender:
------------------------

* **in-memory-storage**:
  * file with WARN level messages should contains only 1 day logs;
  * history for 10 days should be stored;
* **api**:
  * new file should be created if current file size > 1KB
  * you should store at least 10 latest files

Note
------------------------
This task is connected with https://github.com/ChangeRequest/dependency-management.hw1


text:
import * as React from 'react';
import { View } from 'react-native';
import ShallowRenderer from 'react-test-renderer/shallow';
import { Translation } from '@kiwicom/mobile-localization';

import Touchable from '../Touchable';

const renderer = new ShallowRenderer();
const VoidAction = () => {};

describe('Touchable with children', () => {
  it('throws error for multiple children', () => {
    // this is fine - only one child
    expect(
      renderer.render(
        <Touchable onPress={VoidAction}>
          <Translation passThrough="this is OK" />
        </Touchable>,
      ),
    ).toMatchSnapshot();

    // this is fine - only one child
    expect(
      renderer.render(
        <Touchable onPress={VoidAction}>
          <View>
            <Translation passThrough="line 1" />
            <Translation passThrough="line 2" />
          </View>
        </Touchable>,
      ),
    ).toMatchSnapshot();

    // this is not fine - two children
    expect(() =>
      renderer.render(
        <Touchable onPress={VoidAction}>
          <Translation passThrough="line 1" />
          <Translation passThrough="line 2" />
        </Touchable>,
      ),
    ).toThrowErrorMatchingSnapshot();
  });
});


text:
const os = require('os');
const totalMem = os.totalmem();
const { VERSION } = require('eris');
const botVersion = require(`${__dirname}/../../../package.json`).version;

async function statsCommand (msg) {
  const memUsage = process.memoryUsage().rss;
  const shard = msg.channel.guild ?
    msg.channel.guild.shard :
    this.client.shards.get(0);

  return {
    title: `RemindMeBot ${botVersion}`,
    url: 'http://remindmebot.xyz',
    fields: [
      { name: 'Guilds', value: this.client.guilds.size, inline: true },
      { name: 'Uptime', value: this.utils.parseDuration(process.uptime()), inline: true },
      { name: 'Ping', value: `${shard.latency.toFixed()} ms`, inline: true },
      { name: 'RAM Usage', value: `${(memUsage / 1048576).toFixed()}MB/${(totalMem / 1073741824).toFixed(1)} GB\n(${(memUsage / totalMem * 100).toFixed(2)}%)`, inline: true
      },
      { name: 'System Info', value: `${process.platform} (${process.arch})\n${(totalMem > 1073741824 ? `${(totalMem / 1073741824).toFixed(1)} GB` : `${(totalMem / 1048576).toFixed(2)} MB`)}`, inline: true },
      { name: 'Libraries', value: `[Eris](https://abal.moe/Eris) v${VERSION}\n[Node.js](https://nodejs.org/en/) ${process.version}`, inline: true },
      { name: 'Links', value: [
        `[Bot invite](https://discordapp.com/oauth2/authorize?permissions=27648&scope=bot&client_id=${this.client.user.id})`,
        '[Support server invite](https://discord.gg/Yphr6WG)',
        '[GitHub](https://github.com/Aetheryx/remindme)',
        '[Website](http://remindmebot.xyz)'
      ].join(' | ') },
    ],
    footer: { text: 'Created by Aetheryx#2222' }
  };
}

module.exports = {
  command: statsCommand,
  name: 'stats',
  aliases: ['info'],
  description: 'Returns information and statistics about RemindMeBot.'
};


text:
Sunfounder Super Kit for Raspberry Pi 2 and Windows 10 IoT

This repository contains a Visual Studio 2015 solution containing all Sunfounder SuperKit examples to use with the Windows 10 IoT Core edition on a Raspberry Pi 2.

## Raspberry Pi Lesson 1
#### Bliking LED

## Raspberry Pi Lesson 2
#### Controlling a LED by a button

## Raspberry Pi Lesson 3
#### Flowing LED lights

## Raspberry Pi Lesson 4
#### Breathing LED

## Raspberry Pi Lesson 5
#### RGB LED

## Raspberry Pi Lesson 6
#### Buzzer

## Raspberry Pi Lesson 7
#### How to drive a DC motor

## Raspberry Pi Lesson 8
#### Rotary encoder

## Raspberry Pi Lesson 9
#### 555 timer

## Raspberry Pi Lesson 10
#### Driving LEDs by 74HC595

## Raspberry Pi Lesson 11
#### Driving 7 segment display by 74HC595

## Raspberry Pi Lesson 12
#### Driving dot matrix by 74HC595

## Raspberry Pi Lesson 13
#### LCD1602

## Raspberry Pi Lesson 14
#### ADXL345


text:
package strategy

import (
	"fmt"
	"strconv"
	"strings"

	. "github.com/cloudfoundry/cli/cf/i18n"
)

type Version struct {
	Major int64
	Minor int64
	Patch int64
}

func ParseVersion(input string) (Version, error) {
	parts := strings.Split(input, ".")
	if len(parts) != 3 {
		return Version{}, fmt.Errorf(T("Could not parse version number: {{.Input}}",
			map[string]interface{}{"Input": input}))
	}

	major, err1 := strconv.ParseInt(parts[0], 10, 64)
	minor, err2 := strconv.ParseInt(parts[1], 10, 64)
	patch, err3 := strconv.ParseInt(parts[2], 10, 64)
	if err1 != nil || err2 != nil || err3 != nil {
		return Version{}, fmt.Errorf(T("Could not parse version number: {{.Input}}",
			map[string]interface{}{"Input": input}))
	}

	return Version{major, minor, patch}, nil
}

func (version Version) LessThan(other Version) bool {
	if version.Major < other.Major {
		return true
	}

	if version.Major > other.Major {
		return false
	}

	if version.Minor < other.Minor {
		return true
	}

	if version.Minor > other.Minor {
		return false
	}

	if version.Patch < other.Patch {
		return true
	}

	return false
}

func (version Version) GreaterThanOrEqualTo(other Version) bool {
	return !version.LessThan(other)
}


text:
'use strict';

describe('myApp.gameView module', function() {

  beforeEach(module('myApp.gameView'));

  describe('gameView controller', function(){

    it('should ....', inject(function($controller) {
      //spec body
      var view1Ctrl = $controller('gameViewCtrl');
      expect(view1Ctrl).toBeDefined();
    }));

  });
});


text:
from django.contrib import admin

from common.admin import ApplicationAdminInline, TeamInvitationAdminInline, TeamMemberAdminInline
from teams.admin_forms import TeamAdminForm
from teams.models import Team

class TeamAdminInline(admin.TabularInline):
    model = Team
    fields = ('name', 'players', 'regions', 'available_positions', 'interests', 'languages', 'captain', 'created', )
    readonly_fields = fields
    extra = 0
    show_change_link = True

class TeamAdmin(admin.ModelAdmin):
    model = Team
    form = TeamAdminForm
    readonly_fields = ('id', 'players', 'created', 'updated', )
    list_display = ('name', 'captain', 'creator', 'search_score', 'created', 'updated', )
    list_filter = ('regions', 'available_positions', 'interests', 'languages', 'created', 'updated', )
    search_fields = ('name', 'bio', 'captain__username', 'creator__username', )
    ordering = ('-created', )
    inlines = (
        TeamMemberAdminInline,
        ApplicationAdminInline,
        TeamInvitationAdminInline,
    )

    def get_date_joined(self, obj):
        return obj.user.date_joined
    get_date_joined.short_description = 'Date joined'
    get_date_joined.admin_order_field = 'user__date_joined'

admin.site.register(Team, TeamAdmin)


text:
module ShouldaMatchmakers
  module Model
    module ActiveRecord
      module FactorySmModelHelper

        def factory_attributes
          attributes_for_factory = get_validation_attributes(@app_class_name)
          attributes_for_factory = attributes_for_factory | get_required_attributes(@app_class_name)
          attributes_for_factory = attributes_for_factory - get_attributes_with_defaults(@app_class_name)
          attributes_for_factory = attributes_for_factory.flatten.compact.uniq.sort
          factory_attributes_string = ""
          attributes_for_factory.each do |attribute|
            factory_attributes_string.concat("    # " + attribute.to_s + "\n")
          end
          factory_attributes_string
        end

        private

        def get_validation_attributes(app_class_name)
          validation_attributes = []
          validation_attributes = validation_attributes | get_absence_attributes(app_class_name)
          validation_attributes = validation_attributes | get_acceptance_attributes(app_class_name)
          validation_attributes = validation_attributes | get_confirmation_attributes(app_class_name)
          validation_attributes = validation_attributes | get_exclusion_attributes(app_class_name)
          validation_attributes = validation_attributes | get_inclusion_attributes(app_class_name)
          validation_attributes = validation_attributes | get_length_attributes(app_class_name)
          validation_attributes = validation_attributes | get_numericality_attributes(app_class_name)
          validation_attributes = validation_attributes | get_presence_attributes(app_class_name)
          validation_attributes | get_uniqueness_attributes(app_class_name)
        end

        def get_attributes_with_defaults(app_class_name)
          app_class_name.constantize.columns.select{ |column| !column.default.nil? }.map(&:name).map(&:to_sym)
          # The following line of code doesn't work for the class 'SuperAdminUser', but only that class.
          # app_class_name.constantize.column_defaults.select{ |attribute, default| !default.nil? }.keys.map(&:to_sym)
        end

        def get_required_attributes(app_class_name)
          required_attributes = []
          required_attributes.concat(app_class_name.constantize.columns.select{ |column| !column.null }.map(&:name))
          required_attributes.map(&:to_sym) - [:id, :encrypted_password, :created_at, :updated_at]
        end

        def get_absence_attributes(app_class_name)
          absence_attributes = []
          extract_validators(app_class_name, ::ActiveModel::Validations::AbsenceValidator).flatten.map do |validator|
            absence_attributes.concat(validator.attributes)
          end
          absence_attributes
        end

        def get_acceptance_attributes(app_class_name)
          acceptance_attributes = []
          extract_validators(app_class_name, ::ActiveModel::Validations::AcceptanceValidator).flatten.map do |validator|
            acceptance_attributes.concat(validator.attributes)
          end
          acceptance_attributes
        end

        def get_confirmation_attributes(app_class_name)
          confirmation_attributes = []
          extract_validators(app_class_name, ::ActiveModel::Validations::ConfirmationValidator).flatten.map do |validator|
            confirmation_attributes.concat(validator.attributes)
          end
          confirmation_attributes
        end

        def get_exclusion_attributes(app_class_name)
          exclusion_attributes = []
          extract_validators(app_class_name, ::ActiveModel::Validations::ExclusionValidator).flatten.map do |validator|
            exclusion_attributes.concat(validator.attributes)
          end
          exclusion_attributes
        end

        def get_inclusion_attributes(app_class_name)
          inclusion_attributes = []
          extract_validators(app_class_name, ::ActiveModel::Validations::InclusionValidator).flatten.map do |validator|
            inclusion_attributes.concat(validator.attributes)
          end
          inclusion_attributes
        end

        def get_length_attributes(app_class_name)
          length_attributes = []
          extract_validators(app_class_name, ::ActiveModel::Validations::LengthValidator).flatten.map do |validator|
            length_attributes.concat(validator.attributes)
          end
          length_attributes
        end

        def get_numericality_attributes(app_class_name)
          numericality_attributes = []
          extract_validators(app_class_name, ::ActiveModel::Validations::NumericalityValidator).flatten.map do |validator|
            numericality_attributes.concat(validator.attributes)
          end
          numericality_attributes
        end

        def get_presence_attributes(app_class_name)
          presence_attributes = []
          extract_validators(app_class_name, ::ActiveRecord::Validations::PresenceValidator).flatten.map do |validator|
            presence_attributes.concat(validator.attributes)
          end
          presence_attributes
        end

        def get_uniqueness_attributes(app_class_name)
          uniqueness_attributes = []
          extract_validators(app_class_name, ::ActiveRecord::Validations::UniquenessValidator).flatten.map do |validator|
            uniqueness_attributes.concat(validator.attributes)
          end
          uniqueness_attributes
        end

      end
    end
  end
end


text:
source ../common.sh

subsection "oh-my-zsh"

sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"
chsh -s /bin/zsh

mv "${HOME}/.zshrc.pre-oh-my-zsh" "${HOME}/.zshrc"


text:
use anyhow::{bail, Result};

use pueue_lib::network::message::*;
use pueue_lib::settings::*;
use pueue_lib::state::State;

use super::*;

/// Convenience function for getting the current state from the daemon.
pub async fn get_state(shared: &Shared) -> Result<Box<State>> {
    let response = send_message(shared, Message::Status).await?;
    match response {
        Message::StatusResponse(state) => Ok(state),
        _ => bail!("Didn't get status response in get_state"),
    }
}


text:
<?php
/**
 * Class to resolve some specific redirections
 */
namespace Embed;

class UrlRedirect
{
    protected static $urls = array(
        'google' => 'https?://www.google.com/url*',
        'googleTranslator' => 'https?://translate.google.com/translate*',
        'hashBang' => '*#!*'
    );

    /**
     * Resolve the url redirection
     *
     * @param string $oldUrl Url to resolve
     *
     * @return string The new url
     */
    public static function resolve($oldUrl)
    {
        $url = new Url($oldUrl);

        foreach (static::$urls as $method => $matches) {
            if ($url->match($matches)) {
                static::$method($url);

                break;
            }
        }

        return $url->getUrl();
    }

    /**
     * Resolve a google redirection url
     *
     * @param Url $url
     */
    protected static function google(Url $url)
    {
        if (($urlString = $url->getParameter('url'))) {
            $url->setUrl($urlString);
        }
    }

    /**
     * Resolve a google translation url
     *
     * @param Url $url
     */
    protected static function googleTranslator(Url $url)
    {
        if (($urlString = $url->getParameter('u'))) {
            $url->setUrl($urlString);
        }
    }

    /**
     * Resolve an url with hashbang
     *
     * @param Url $url
     */
    protected static function hashBang(Url $url)
    {
        if (($path = preg_replace('|^(/?!)|', '', $url->getFragment()))) {
            $url->setPath($url->getPath().$path);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using StardewValley;
using StardewValley.TerrainFeatures;
using StardewValley.Objects;
using StardewModdingAPI;

namespace StardewValleyMP.Packets
{
    public enum ID
    {
        Version = 0,
        YourID,
        ClientFarmerData,
        OtherFarmerData,
        WorldData,
        MovingState,
        Location,
        Animation,
        HeldItem,
        Debris,
        TerrainFeature, // 10
        Object,
        HoeDirtUpdate,
        FruitTreeUpdate,
        ObjectUpdate,
        DoorUpdate,
        FenceUpdate,
        CrabPotUpdate,
        ChestUpdate,
        PauseTime,
        TimeSync, //20
        CoopUpdate,
        FestivalDancePartner,
        ContinueEvent,
        NextDay,
        ShippingBin,
        NPCUpdate,
        FarmAnimalUpdate,
        Spouse,
        Chat,
        BeachBridgeFixed, // 30
        MuseumUpdated,
        CommunityCenterUpdated,
        TreeUpdate,
        FarmUpdate,
        Building,
        BuildingUpdate,
        FarmAnimal,
        LatestId,
        LostBooks,
		ResourceClumps,
        // Stuff...
    };

    public abstract class Packet
    {
        protected Packet( ID theId )
        {
            id = theId;
        }

        public readonly ID id;

        protected abstract void read(BinaryReader reader);
        protected abstract void write( BinaryWriter writer );
        public virtual void process(Client client) { }
        public virtual void process(Server server, Server.Client client) { }

        public static Packet readFrom( Stream s )
        {
            BinaryReader reader = new BinaryReader( s );
            byte type = reader.ReadByte();

            Packet packet = null;
            switch ( type )
            {
                case (byte)ID.Version: packet = new VersionPacket(); break;
                case (byte)ID.YourID: packet = new YourIDPacket(); break;
                case (byte)ID.ClientFarmerData: packet = new ClientFarmerDataPacket(); break;
                case (byte)ID.OtherFarmerData: packet = new OtherFarmerDataPacket(); break;
                case (byte)ID.WorldData: packet = new WorldDataPacket(); break;
                case (byte)ID.MovingState: packet = new MovingStatePacket(); break;
                case (byte)ID.Location: packet = new LocationPacket(); break;
                case (byte)ID.Animation: packet = new AnimationPacket(); break;
                case (byte)ID.HeldItem: packet = new HeldItemPacket(); break;
                case (byte)ID.Debris: packet = new DebrisPacket(); break;
                case (byte)ID.TerrainFeature: packet = new TerrainFeaturePacket(); break;
                case (byte)ID.Object: packet = new ObjectPacket(); break;
                case (byte)ID.HoeDirtUpdate: packet = new TerrainFeatureUpdatePacket<HoeDirt>(); break;
                case (byte)ID.FruitTreeUpdate: packet = new TerrainFeatureUpdatePacket<FruitTree>(); break;
                case (byte)ID.ObjectUpdate: packet = new ObjectUpdatePacket<StardewValley.Object>(); break;
                case (byte)ID.DoorUpdate: packet = new ObjectUpdatePacket<Door>(); break;
                case (byte)ID.FenceUpdate: packet = new FenceUpdatePacket(); break;
                case (byte)ID.CrabPotUpdate: packet = new ObjectUpdatePacket<CrabPot>(); break;
                case (byte)ID.ChestUpdate: packet = new ChestUpdatePacket(); break;
                case (byte)ID.PauseTime: packet = new PauseTimePacket(); break;
                case (byte)ID.TimeSync: packet = new TimeSyncPacket(); break;
                case (byte)ID.CoopUpdate: packet = new CoopUpdatePacket(); break;
                case (byte)ID.FestivalDancePartner: packet = new FestivalDancePartnerPacket(); break;
                case (byte)ID.ContinueEvent: packet = new ContinueEventPacket(); break;
                case (byte)ID.NextDay: packet = new NextDayPacket(); break;
                case (byte)ID.ShippingBin: packet = new ShippingBinPacket(); break;
                case (byte)ID.NPCUpdate: packet = new NPCUpdatePacket(); break;
                case (byte)ID.FarmAnimalUpdate: packet = new FarmAnimalUpdatePacket(); break;
                case (byte)ID.Spouse: packet = new SpousePacket(); break;
                case (byte)ID.Chat: packet = new ChatPacket(); break;
                case (byte)ID.BeachBridgeFixed: packet = new BeachBridgeFixedPacket(); break;
                case (byte)ID.MuseumUpdated: packet = new MuseumUpdatedPacket(); break;
                case (byte)ID.CommunityCenterUpdated: packet = new CommunityCenterUpdatedPacket(); break;
                case (byte)ID.TreeUpdate: packet = new TerrainFeatureUpdatePacket<Tree>(); break;
                case (byte)ID.FarmUpdate: packet = new FarmUpdatePacket(); break;
                case (byte)ID.Building: packet = new BuildingPacket(); break;
                case (byte)ID.BuildingUpdate: packet = new BuildingUpdatePacket(); break;
                case (byte)ID.FarmAnimal: packet = new FarmAnimalPacket(); break;
                case (byte)ID.LatestId: packet = new LatestIdPacket(); break;
                case (byte)ID.LostBooks: packet = new LostBooksPacket(); break;
				case (byte)ID.ResourceClumps: packet = new ResourceClumpsPacket(); break;
            }

            if (packet == null)
            {
                Log.Async("Bad packet?!?!?!?! ID = " + type);
                return null;
            }
            //Log.Async("Got packet " + type);
            packet.read(reader);

            return packet;
        }

        /// <summary>
        /// Writes this packet to the specified stream and returns the amount of bytes written.
        /// </summary>
        public int writeTo( Stream s )
        {
            // Wrapped into a memory stream in order to figure out how many data was sent.
            using (MemoryStream ms = new MemoryStream())
            {
                BinaryWriter writer = new BinaryWriter(ms);
                writer.Write((byte)id);
                write(writer);

                byte[] data = ms.ToArray();
                s.Write(data, 0, data.Length);
                return data.Length;
            }
        }
    }
}


text:
package edu.umd.cs.findbugs.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Rectangle;

import javax.swing.JComponent;
import javax.swing.JTextArea;

public class LineNumberer extends JComponent
{
    public static final int PAD = 10;
    public static final String PROTOTYPE = "00000";

    private JTextArea textArea;
    private FontMetrics fm;

    public LineNumberer(JTextArea ta) {
        setFont( ta.getFont() );
        textArea = ta;
        setForeground( Color.BLUE );

        fm = this.getFontMetrics(ta.getFont());
        setWidths();
    }

    @Override
    public void setFont(Font font)
    {
        //ignore
    }

    private void setWidths() {
        int width = fm.stringWidth( PROTOTYPE );
        Dimension d = getPreferredSize();
        d.setSize(PAD + width, Integer.MAX_VALUE);
        setPreferredSize( d );
        setSize( d );
    }

    @Override
    public void paintComponent(Graphics g)
    {
        int lineHeight = fm.getHeight();
        int startOffset = textArea.getInsets().top + fm.getAscent();

        Rectangle clip = g.getClipBounds();

        g.setColor( getBackground() );
        g.fillRect(clip.x, clip.y, clip.width, clip.height);

        g.setColor( getForeground() );
        int beginLineNumber = (clip.y / lineHeight) + 1;
        int endLineNumber = beginLineNumber + (clip.height / lineHeight);

        int y = (clip.y / lineHeight) * lineHeight + startOffset;

        for (int i = beginLineNumber; i <= endLineNumber; i++)
        {
            String ln = String.valueOf(i);
            int width = fm.stringWidth( ln );
            int rowWidth = getSize().width;
            g.drawString(ln, rowWidth - width - PAD, y);
            y += lineHeight;
        }
    }
}


text:
package org.keycloak.example.oauth;

import org.jboss.resteasy.annotations.cache.NoCache;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Bill Burke
 * @version $Revision: 1 $
 */
@Path("products")
public class ProductService {
    @GET
    @Produces("application/json")
    @NoCache
    public List<String> getProducts() {
        ArrayList<String> rtn = new ArrayList<String>();
        rtn.add("iphone");
        rtn.add("ipad");
        rtn.add("ipod");
        return rtn;
    }
}


text:
using namespace clang::threadSafety::til;
using namespace Jagger;

#ifdef _MSC_VER
extern "C" unsigned char _BitScanForward(unsigned long * Index, unsigned long Mask);
#endif

static int lowIndex(unsigned x) {
  unsigned long a;
  _BitScanReverse(&a, (unsigned long)x);
  return (int)a;
}

template <typename Type>
struct RangeAdaptor {
  RangeAdaptor(Type* data, size_t size) : _begin(data), _end(data + size) {}
  RangeAdaptor(Type* begin, Type* end) : _begin(begin), _end(end) {}
  Type* begin() const { return _begin; }
  Type* end() const { return _end; }

 private:
  Type* _begin;
  Type* _end;
};

template <typename Type>
RangeAdaptor<Type> AdaptRange(Type* data, size_t size) {
  return RangeAdaptor<Type>(data, size);
}

template <typename Type>
RangeAdaptor<Type> AdaptRange(Type* begin, Type* end) {
  return RangeAdaptor<Type>(begin, end);
}

struct LiveRange {
  struct Iterator {
    Iterator(Instruction* instr) : i(instr), skipUntil(i) {}
    Instruction& operator*() const { return *i; }
    Iterator& operator++() {
      if (i->opcode.code == Opcode::HEADER) {
        if (i->opcode.flags)
          skipUntil = i + i->arg1;
        else if (i <= skipUntil)
          i = i + i->arg1;
      }
      i--;
      return *this;
    }
    bool operator!=(const Iterator& a) const { return i != a.i; }

   private:
    Instruction* i;
    Instruction* skipUntil;
  };

  LiveRange(Instruction* def, Instruction* use) : def(def), use(use) {}
  Iterator begin() const { return use - 1; }
  Iterator end() const { return def; }

 private:
  Instruction* def;
  Instruction* use;
};

namespace Jagger {
Instruction countedMarker;
}  // namespace Jagger

//namespace {
struct InstructionStream {
  void encode(SCFG* const* cfg, size_t numCFGs);

  static size_t countInstrs(SExpr* expr);
  Instruction* emitBlockHeader(Instruction* nextInstr, Block* block);
  Instruction* emitArgument(Instruction* nextInstr, Phi* phi);
  Instruction* emitInstrs(Instruction* nextInstr, SExpr* expr);
  Instruction* emitTerminator(Instruction* nextInstr, Terminator* term, BasicBlock* basicBlock);

  void traverse(Instruction* use, Instruction* def);

  Block* blocks;
  Instruction* instrs;
  size_t numBlocks;
  size_t numInstrs;
  std::vector<std::pair<int, int>> interactions;
};
//}  // namespace

void InstructionStream::traverse(Instruction* use, Instruction* def) {
  Instruction* skipUntil = use;
  auto defIndex = (int)(def - instrs);
  auto keyIndex = defIndex + def->key;
#if 0
  for (Instruction* i = use - 1; i > def; --i) {
    if (i->opcode.code == Opcode::HEADER) {
      if (i->opcode.flags)
        skipUntil = i + i->arg1;
      else if (i <= skipUntil)
        i = i + i->arg1;
      continue;
    }
    if (!i->opcode.hasResult) continue;
    if (def->key == i->key) continue;
    auto iKeyIndex = (int)(i->getKey() - instrs);
    interactions.push_back(std::make_pair(std::min(keyIndex, iKeyIndex),
                                          std::max(keyIndex, iKeyIndex)));
  }
#else
  for (auto instr : LiveRange(def, use)) {
    if (!instr.opcode.hasResult) continue;
    if (def->key == instr.key) continue;
    auto iKeyIndex = (int)(instr.getKey() - instrs);
    interactions.push_back(std::make_pair(std::min(keyIndex, iKeyIndex),
                                          std::max(keyIndex, iKeyIndex)));
  }
#endif
}

void InstructionStream::encode(SCFG* const* cfgs, size_t numCFGs) {
  if (!numCFGs) return;

  {
    // Count the blocks.
    size_t numBlocks = 0;
    for (auto cfg : AdaptRange(cfgs, numCFGs))
      numBlocks += cfg->numBlocks();
    this->numBlocks = numBlocks;
  }

  assert(numBlocks);
  blocks = new Block[numBlocks];

  {
    // Initialize blocks and count instructions.
    Block* nextBlock = blocks;
    size_t numInstrs = 0;
    for (auto cfg : AdaptRange(cfgs, numCFGs))
      for (auto basicBlock : *cfg) {
        basicBlock->setBackendID(nextBlock);
        nextBlock->dominator = nullptr;
        nextBlock->head = nextBlock;
        size_t size = 0;
        if (BasicBlock* parent = basicBlock->parent()) {
          size++;  // block header
          nextBlock->dominator = (Block*)parent->getBackendID();
          if (basicBlock->PostDominates(*parent) ||
              nextBlock->dominator + 1 == nextBlock)
            nextBlock->head = nextBlock->dominator->head;
        }
        for (auto arg : basicBlock->arguments()) size += countInstrs(arg);
        for (auto instr : basicBlock->instructions())
          size += countInstrs(instr);
        size += countInstrs(basicBlock->terminator());
        nextBlock->firstInstr = numInstrs;
        nextBlock->numInstrs = size;
        numInstrs += size;
        nextBlock++;
      }
    this->numInstrs = numInstrs;
  }

  assert(numInstrs);
  instrs = new Instruction[numInstrs];

  {
    // Emit instructions.
    Instruction* nextInstr = instrs;
    Block* nextBlock = blocks;
    for (auto cfg : AdaptRange(cfgs, numCFGs))
      for (auto basicBlock : *cfg) {
        nextInstr = emitBlockHeader(nextInstr, nextBlock);
        for (auto arg : basicBlock->arguments())
          nextInstr = emitArgument(nextInstr, cast<Phi>(arg));
        for (auto instr : basicBlock->instructions())
          nextInstr = emitInstrs(nextInstr, instr);
        nextInstr =
            emitTerminator(nextInstr, basicBlock->terminator(), basicBlock);
        assert(nextInstr == nextBlock->instrs + nextBlock->numInstrs);
        nextBlock++;
      }
  }

  // Determine last uses.
  for (auto uses : AdaptRange(instrs, numInstrs)) {
    auto arg0 = uses.arg0;
    auto arg1 = uses.arg1;
    if (arg0 | arg1) {
      if (arg0 == arg1)
        uses.opcode.isArg0NotLastUse = true;
      for (auto instr :
           LiveRange(std::min(uses.getArg0(), uses.getArg1()), &uses)) {
        if (instr.arg0 == arg0 || instr.arg0 == arg1)
          instr.opcode.isArg0NotLastUse = true;
        if (instr.arg1 == arg0 || instr.arg1 == arg1)
          instr.opcode.isArg1NotLastUse = true;
      }
    }
  }

#if 0
  // Link phis
  for (auto uses : AdaptRange(instrs, numInstrs)) {
    if (uses.opcode.code == Opcode::COPY) uses.key = uses.arg0;
    if (uses.opcode == Opcodes::phi) {
      // TODO, FIX ME: could be coming from many places
      auto key = i;
      uses.getArg0()->updateKey(i);
      uses.getArg1()->updateKey(i);
      continue;
    }
  }
#endif

  //
  for (auto instr : AdaptRange(instrs, numInstrs)) {
    if (instr.opcode.code == Opcode::COPY)
      if (instr.opcode.isArg0NotLastUse) instr.key = 0;
  }

  // Finalize the keys.
  for (Instruction* i = instrs, *e = instrs + numInstrs; i != e; ++i)
    i->updateKey();

  for (Instruction* i = instrs, *e = instrs + numInstrs; i != e; ++i) {
    if (i->opcode == &globalOpcodes.phi)
      continue;
    if (i->opcode->hasArg0 && !i->arg0Live) traverse(i, i->arg0);
    if (i->opcode->hasArg1 && !i->arg1Live) traverse(i, i->arg1);
  }

  assert(!interactions.empty());
  // We should really just return in this case.

  std::sort(interactions.begin(), interactions.end());
  std::vector<std::pair<int, int>> uniqued;
  uniqued.push_back(*interactions.begin());
  for (auto i = interactions.begin() + 1, e = interactions.end(); i != e; ++i)
    if (*i != i[-1]) uniqued.push_back(*i);
  for (auto i : uniqued) printf("> %d, %d\n", i.first, i.second);
  for (auto i : uniqued) {
    instrs[i.first].pressure++;
    instrs[i.second].pressure++;
  }

  std::vector<std::<int, int>> shared;
  for (Instruction* i = instrs, *e = instrs + numInstrs; i != e; ++i)
    if (i->opcode == &globalOpcodes.add || i->opcode == &globalOpcodes.mul ||
        i->opcode == &globalOpcodes.cmpeq) {
    shared.push_back(std::make_pair());
    }

  std::vector<Instruction*> work;
  for (auto i = instrs, e = instrs + numInstrs; i != e; ++i) work.push_back(i);
  std::sort(work.begin(), work.end(), [](Instruction* a, Instruction* b) {
    return a->pressure < b->pressure || a->pressure == b->pressure && a < b;
  });
  for (auto i : work) printf("%d : %d\n", i - instrs, i->pressure);

  for (auto& i : uniqued)
    if (instrs[i.first].pressure > instrs[i.second].pressure ||
        instrs[i.first].pressure == instrs[i.second].pressure &&
            i.first > i.second) {
      i = std::make_pair(i.second, i.first);
      printf("*");
    } else
      printf(".");
  printf("\n");

  // for (auto i : uniqued) printf("> %d, %d\n", i.first, i.second);
  // printf("\n");
  std::sort(uniqued.begin(), uniqued.end(),
            [&](std::pair<int, int> a, std::pair<int, int> b) {
    return instrs[a.first].pressure < instrs[b.first].pressure ||
           instrs[a.first].pressure == instrs[b.first].pressure &&
               a.first < b.first;
  });
  for (auto i : uniqued) printf("> %d, %d\n", i.first, i.second);

  auto interaction = uniqued.begin();
  for (auto i : work) {
    i->reg = ~i->invalidRegs & -~i->invalidRegs;
    while (interaction != uniqued.end() && instrs + interaction->first == i)
      instrs[interaction++->second].invalidRegs |= i->reg;
  }

#if 1
      // for debugging
      std::vector<std::pair<int, int>> ranges;
  auto point = uniqued.begin();
  for (auto i = uniqued.begin() + 1, e = uniqued.end(); i != e; ++i)
    if (i->first != i[-1].first) {
      ranges.push_back(
          std::make_pair(point - uniqued.begin(), i - uniqued.begin()));
      point = i;
    }
  ranges.push_back(std::make_pair(point - uniqued.begin(), uniqued.size()));
  for (auto i : ranges) printf("[%d, %d) : %d : %d\n", i.first, i.second, uniqued[i.first].first, i.second - i.first);
#endif

  printf("blocks = %d\ninstrs = %d\n", (int)numBlocks, (int)numInstrs);
  for (size_t i = 0; i < numBlocks; i++)
    printf("block%d\n  parent = %d\n  first = %d\n  instrs = %d\n", (int)i,
           blocks[i].dominator ? (int)(blocks[i].dominator - blocks) : -1,
           (int)(blocks[i].instrs - instrs), (int)blocks[i].numInstrs);

#if 0
  // Patch up all of the jump targets.
  for (auto block : *cfg) {
    if (!block->terminator())
      continue;
    switch (block->terminator()->opcode()) {
    case COP_Goto:
      instrs[block->VX64BlockEnd].arg1 =
        cast<Goto>(block->terminator())->targetBlock()->VX64BlockStart - block->VX64BlockEnd;
      break;
    case COP_Branch:
      instrs[block->VX64BlockEnd].arg1 =
        cast<Branch>(block->terminator())->elseBlock()->VX64BlockStart - block->VX64BlockEnd;
      break;
    }
  }
#endif
}

size_t InstructionStream::countInstrs(SExpr* expr) {
  if (expr->getBackendID()) return 0;
  expr->setBackendID(&countedMarker);
  switch (expr->opcode()) {
    case COP_Literal:
      return 1;
    case COP_Variable:
      return countInstrs(cast<Variable>(expr)->definition());
    case COP_BinaryOp:
      return countInstrs(cast<BinaryOp>(expr)->expr0()) +
             countInstrs(cast<BinaryOp>(expr)->expr1()) + 1;
    case COP_Phi:
      // Because phi instructions are binary we need n-1 of them to make a tree
      // of phi/tie instructions with n leaves.
      assert(cast<Phi>(expr)->values().size() == 2);
      return cast<Phi>(expr)->values().size() - 1;
    case COP_Goto:
      return cast<Goto>(expr)->targetBlock()->arguments().size() + 1;
    case COP_Branch:
      return countInstrs(cast<Branch>(expr)->condition()) + 1;
    case COP_Return:
      return countInstrs(cast<Return>(expr)->returnValue()) + 1;
    default:
      printf("unknown opcode: %d\n", expr->opcode());
      assert(false);
      return 0;
  }
}

Instruction* InstructionStream::emitBlockHeader(Instruction* nextInstr,
                                                Block* block) {
  if (!block->dominator) return nextInstr;
  if (block->head != block)
    nextInstr->init(Opcodes::headerDominates, 0, block->head->instrs);
  else
    nextInstr->init(Opcodes::header, 0,
                    block->dominator->instrs + block->dominator->numInstrs);
  return ++nextInstr;
}

Instruction* InstructionStream::emitArgument(Instruction* nextInstr, Phi* phi) {
  // Because phi instructions are binary we need n-1 of them to make a tree
  // of phi/tie instructions with n leaves.
  if (phi->values().size() == 1) {
    // TODO: eliminate this case in the middle-end
    phi->setBackendID(phi->values()[0]->getBackendID());
    return nextInstr;
  }
  assert(phi->values().size() == 2);
  nextInstr->init(Opcodes::phi,
    (Instruction*)phi->values()[0]->getBackendID(),
    (Instruction*)phi->values()[1]->getBackendID());
  phi->setBackendID(nextInstr);
  return ++nextInstr;
}

Instruction* InstructionStream::emitInstrs(Instruction* nextInstr,
                                           SExpr* expr) {
  if (expr->getBackendID() != &countedMarker) return nextInstr;
  expr->setBackendID(nextInstr);
  switch (expr->opcode()) {
    case COP_Literal: {
      Literal* literal = cast<Literal>(expr);
      switch (literal->valueType().Base) {
        case ValueType::BT_Int:
          nextInstr->init(Opcodes::intValue,
                                   (Instruction*)literal->as<int>().value());
          break;
        default:
          assert(false);
      }
      break;
    }
    case COP_Variable: {
      auto instr = emitInstrs(nextInstr, cast<Variable>(expr)->definition());
      expr->setBackendID(instr - 1);
      return instr;
    }
    case COP_BinaryOp: {
      auto binaryOp = cast<BinaryOp>(expr);
      nextInstr = emitInstrs(nextInstr, binaryOp->expr0());
      nextInstr = emitInstrs(nextInstr, binaryOp->expr1());
      Opcode opcode = Opcodes::nop;
      switch (binaryOp->binaryOpcode()) {
        case BOP_Add: opcode = Opcodes::add; break;
        case BOP_Mul: opcode = Opcodes::mul; break;
        case BOP_Eq: opcode = Opcodes::cmpeq; break;
        case BOP_Lt: opcode = Opcodes::cmplt; break;
        case BOP_Leq: opcode = Opcodes::cmple; break;
        default: assert(false);
      }
      printf("?? %d : %d %d\n", binaryOp->binaryOpcode(),
             (Instruction*)binaryOp->expr0()->opcode(),
             (Instruction*)binaryOp->expr1()->opcode());
      nextInstr->init(opcode,
                      (Instruction*)binaryOp->expr0()->getBackendID(),
                      (Instruction*)binaryOp->expr1()->getBackendID());
      break;
    }
    default:
      printf("unknown opcode: %d\n", expr->opcode());
      assert(false);
      return 0;
  }
  expr->setBackendID(nextInstr);
  return ++nextInstr;
}

// the index for this block in the target's phis
// TODO: make this not a search;
static size_t getPhiIndex(BasicBlock* basicBlock, BasicBlock* targetBlock) {
  auto& predecessors = targetBlock->predecessors();
  for (size_t i = 0, e = predecessors.size(); i != e; ++i)
    if (predecessors[i] == basicBlock)
      return i;
  return 0;
}

Instruction* InstructionStream::emitTerminator(Instruction* nextInstr,
                                               Terminator* term,
                                               BasicBlock* basicBlock) {
  switch (term->opcode()) {
    case COP_Goto: {
      auto jump = cast<Goto>(term);
      auto targetBlock = jump->targetBlock();
      size_t phiIndex = getPhiIndex(basicBlock, targetBlock);
      auto& arguments = targetBlock->arguments();
      // This loop should emit nothing! TODO: validate and remove
      for (auto arg : arguments)
        nextInstr = emitInstrs(nextInstr, cast<Phi>(arg)->values()[phiIndex]);
      for (auto arg : arguments) {
        auto instr =
            (Instruction*)cast<Phi>(arg)->values()[phiIndex]->getBackendID();
        (nextInstr++)->init(&Opcodes::copy, instr, nextInstr, instr);
      }
      nextInstr->init(Opcodes::jump);
      break;
    }
    case COP_Branch: {
      auto branch = cast<Branch>(term);
      auto condition = branch->condition();
      nextInstr = emitInstrs(nextInstr, condition);
      nextInstr->init(Opcodes::branch, (Instruction*)condition->getBackendID());
      break;
    }
    case COP_Return: {
      auto ret = cast<Return>(term);
      auto value = ret->returnValue();
      nextInstr = emitInstrs(nextInstr, value);
      nextInstr->init(Opcodes::ret, (Instruction*)value->getBackendID());
      break;
    }
  }
  term->setBackendID(nextInstr);
  return ++nextInstr;
}

#if 0

#if 0
namespace {
struct Pool {
  Pool() : data((char*)malloc(0x100)), capacity(0x100), size(0) {}

  template <typename T>
  T* allocate(size_t quantity) {
    assert(!(sizeof(T) % 4) && __alignof(T) <= 4);
    size_t offset = size;
    if (quantity) {
      size += sizeof(T) * quantity;
      while (size > capacity) data = (char*)realloc(data, capacity *= 2);
    }
    return (T*)(data + offset);
  }

  size_t getSize() const { return size; }
  int getOffset() const { assert((int)size == size); return (int)size; }
  char* getBase() const { return data; }

 private:
  char* data;
  size_t capacity;
  size_t size;
};
#endif

struct InstructionStream {
#if 0
  int getNewInstr() const { return pool.getOffset(); }
  int getLastInstr() const { return getNewInstr() - sizeof(Instruction); }
  int getNewBlock() const { return pool.getOffset(); }
  int getLastBlock() const { return getNewBlock() - sizeof(Block); }
#endif

  int countBytes(SCFG* cfg) const;
  int countInstrs(SExpr* expr) const;
  int countInstrs(BasicBlock* block) const;

#if 0
  void emitBlock(BasicBlock* block);
  //void emitBlockLink(BasicBlock* block);
  void emitEchos(Phi* phi);
  void emitPhi(Phi* phi);
  void encode(SCFG* cfg);

  int emitExpression(SExpr* expr);
  void emitTerminator(BasicBlock* basicBlock);

  void emitLiteral(Literal* literal);
  void emitBinaryOp(BinaryOp* binaryOp);
  void emitJump(BasicBlock* basicBlock, Goto* jump);
  void emitBranch(BasicBlock* basicBlock, Branch* branch);

  void printWalk(Instruction* instr, Instruction* target);
  void printWalks();
#endif

#if 0
  void computePressure(Event* event);
  unsigned computeValidRegs(Event* event, Event*& source);
  void markInvalidRegs(Event* event);
  void propegateCopies(Event* source, unsigned reg);
  void untwistPairs(Event* event);
#endif

private:
  //Block* currentBlock;
  //Pool pool;
  //void* root;
  void* root;
};
} // namespace

int InstructionStream::countBytes(SCFG* cfg) const {
  int numBlocks = 0;
  int numInstrs = 0;
  for (auto block : *cfg) {
    numBlocks++;
    numInstrs += countInstrs(block);
  }
  printf("blocks = %d\ninstrs = %d\n", numBlocks, numInstrs);
  return numBlocks * (int)sizeof(Block) + numInstrs * (int)sizeof(Instruction);
}

int InstructionStream::countInstrs(BasicBlock* block) const {
  int x = 0;
  // count the number of phi instructions.  Because phi instructions are binary
  // we need n-1 of them to make a tree of phi/tie instructions with n leaves.
  x += block->arguments().size() * (block->predecessors().size() - 1);
  for (auto instr : block->instructions()) x += countInstrs(instr);
  auto terminator = block->terminator();
  if (!terminator)
    x++;  // ret instruction special case
  else
    x += countInstrs(terminator);
  return x;
}

int InstructionStream::countInstrs(SExpr* expr) const {
  if (expr->id()) return 0;
  expr->setId(1);  // all ids < 4 are special
  switch (expr->opcode()) {
    case COP_Literal:
      return 1;
    case COP_Variable:
      return countInstrs(cast<Variable>(expr)->definition());
    case COP_BinaryOp:
      return countInstrs(cast<BinaryOp>(expr)->expr0()) +
             countInstrs(cast<BinaryOp>(expr)->expr1()) + 1;
    case COP_Goto:
      return cast<Goto>(expr)->targetBlock()->arguments().size() + 1;
    case COP_Branch:
      return countInstrs(cast<Branch>(expr)->condition()) + 1;
    default:
      assert(false);
      return 0;
  }
}

void InstructionStream::emitBlock(BasicBlock* block) {
  int blockID = block->blockID();
  assert(blockID == (int)blocks.size());
  BasicBlock* parent = block->DominatorNode.Parent;
  while (parent && block->PostDominates(*parent)) // TODO: || parent is previous block
    parent = parent->DominatorNode.Parent;
  blocks.push_back(Block(parent ? parent->blockID() - blockID : 0, getNewID()));
  currentBlock = &blocks.back();
  for (auto arg : block->arguments())
    emitPhi(cast<clang::threadSafety::til::Phi>(arg->definition()));
  for (auto instr : block->instructions())
    emitExpression(instr);
  emitTerminator(block);
  currentBlock->lastInstr = getLastID();
}

#if 0
void InstructionStream::emitBlockLink(BasicBlock* block) {
  if (!block->DominatorNode.Parent)
    return;
  int targetOffset = block->DominatorNode.Parent->VX64BlockEnd - getNewID();
  // In this case the previous block is immediately prior and we don't need to
  // walk or skip.
  if (targetOffset == -1)
    return;
  if (block->PostDominates(*block->DominatorNode.Parent))
    events.push_back(Link().initWalkBack(targetOffset));
  else
    events.push_back(Link().initSkipBack(targetOffset));
}
#endif

void InstructionStream::emitPhi(Phi* phi) {
  int id = getNewID();
  if (phi->values().size() == 1) {
    // TODO: eliminate this case in the middle-end
    phi->setId((phi->values()[0])->id());
    return;
  }
  assert(phi->values().size() == 2);
  instrs.push_back(Instruction(
      currentBlock,
      &OpCodes::phi,
      cast<Variable>(phi->values()[0])->id() - id,
      cast<Variable>(phi->values()[1])->id() - id));
  phi->setId(id);
}

void InstructionStream::emitLiteral(Literal* literal) {
  switch (literal->valueType().Base) {
  case ValueType::BT_Int:
    instrs.push_back(Instruction(
      currentBlock,
      &OpCodes::intValue,
      literal->as<int>().value()));
    break;
  default:
    assert(false);
  }
}

void InstructionStream::emitBinaryOp(BinaryOp* binaryOp) {
  int expr0ID = emitExpression(binaryOp->expr0());
  int expr1ID = emitExpression(binaryOp->expr1());
  const OpCode* opcode = &OpCodes::nop;
  switch (binaryOp->binaryOpcode()) {
  case BOP_Add: opcode = &OpCodes::add; break;
  case BOP_Mul: opcode = &OpCodes::mul; break;
  case BOP_Eq : opcode = &OpCodes::cmpeq; break;
  case BOP_Lt : opcode = &OpCodes::cmplt; break;
  case BOP_Leq: opcode = &OpCodes::cmple; break;
  default:
    assert(false);
  }
  int site = getNewID();
  instrs.push_back(Instruction(currentBlock, opcode, expr0ID - site, expr1ID - site));
}

int InstructionStream::emitExpression(SExpr* expr) {
  if (expr->id())
    return expr->id();
  switch (expr->opcode()) {
  case COP_Literal: emitLiteral(cast<Literal>(expr)); break;
  case COP_Variable: emitExpression(cast<Variable>(expr)->definition()); break;
  case COP_BinaryOp: emitBinaryOp(cast<BinaryOp>(expr)); break;
  }
  expr->setId(getLastID());
  return expr->id();
}

void InstructionStream::emitTerminator(BasicBlock* basicBlock) {
  auto expr = basicBlock->terminator();
  if (!expr) {
    // Presently Ohmu IR doesn't have/use ret instructions.
    // We should figure out how to differentiate functions that return values
    // and those that don't.
    //assert(!instrs.empty() && instrs.back().opcode->hasResult);
    //assert(basicBlock->instructions().size() != 0);
    instrs.push_back(Instruction(currentBlock, &OpCodes::ret, -1));
    return;
  }
  switch (expr->opcode()) {
  case COP_Goto: emitJump(basicBlock, cast<Goto>(expr)); break;
  case COP_Branch: emitBranch(basicBlock, cast<Branch>(expr)); break;
  }
}

// the index for this block in the target's phis
static size_t getPhiIndex(BasicBlock* basicBlock, BasicBlock* targetBlock) {
  auto& predecessors = targetBlock->predecessors();
  for (size_t i = 0, e = predecessors.size(); i != e; ++i)
    if (predecessors[i] == basicBlock)
      return i;
  return 0;
}

void InstructionStream::emitJump(BasicBlock* basicBlock, Goto* jump) {
  auto targetBlock = jump->targetBlock();
  size_t phiIndex = getPhiIndex(basicBlock, targetBlock);
  auto& arguments = targetBlock->arguments();
  for (auto arg : arguments) {
    SExpr* expr = cast<Phi>(arg->definition())->values()[phiIndex];
    int argid = emitExpression(expr);
    int echoid = getNewID();
    instrs.push_back(Instruction(currentBlock, &OpCodes::echo, argid - echoid));
    expr->setId(echoid);
  }
  instrs.push_back(Instruction(currentBlock, &OpCodes::jump));
}

void InstructionStream::emitBranch(BasicBlock* basicBlock, Branch* branch) {
  // There should be no critical edges.
  emitExpression(branch->condition());
  instrs.push_back(Instruction(currentBlock, &OpCodes::branch,
                               branch->condition()->id() - getNewID()));
}

void InstructionStream::encode(SCFG* cfg) {
  for (auto block : *cfg)
    emitBlock(block);
  instrs.push_back(Instruction(currentBlock, &OpCodes::nop));
  for (auto block : *cfg) {
    Block* b = new Block();
    // TODO:b.init();
    emitBlock(block);
  }
  // Patch up all of the jump targets.
  for (auto block : *cfg) {
    if (!block->terminator())
      continue;
    switch (block->terminator()->opcode()) {
    case COP_Goto:
      instrs[block->VX64BlockEnd].arg1 =
          cast<Goto>(block->terminator())->targetBlock()->VX64BlockStart - block->VX64BlockEnd;
      break;
    case COP_Branch:
      instrs[block->VX64BlockEnd].arg1 =
          cast<Branch>(block->terminator())->elseBlock()->VX64BlockStart - block->VX64BlockEnd;
      break;
    }
  }
#if 0
  // Compute pressure generated by the pairs.
  for (auto& event : instrs) {
    if (event.kind != Object::USE)
      continue;
    computePressure(&event);
  }
  std::vector<Event*> ptrs;
  for (auto& event : instrs)
    if (event.kind == Object::USE)
      ptrs.push_back(&event);
  std::sort(ptrs.begin(), ptrs.end(), [](Event *a, Event *b) {
    a = a + a->use.offsetToValue;
    b = b + b->use.offsetToValue;
    return a->liveRange.pressure < b->liveRange.pressure;
  });
#endif
#if 0
  for (auto ptr : ptrs) {
    Event* source = nullptr;
    auto registerSet = computeValidRegs(ptr, source);
    unsigned sourceCopySet = source->value.copySet;
    unsigned destCopySet = ptr->value.copySet;
// FIXME if we have c = a - b, a must survive, and the total number of allocated
// registers for c, b, and a is 2 then we have no place to squirl away a during
// computation of c so we need to add an artifical use of a so that we get
// another register allocated as a place to store it.
#if 1
    // printf(">> %x %x %x", registerSet, sourceCopySet, destCopySet);
    if (registerSet & sourceCopySet & destCopySet) {
      registerSet &= sourceCopySet & destCopySet;
      //printf(" <SD>");
    }
    else if (registerSet & destCopySet) {
      registerSet &= destCopySet;
      //printf(" <D>");
    }
    else if (registerSet & sourceCopySet) {
      registerSet &= sourceCopySet;
      //printf(" <S>");
    }
#endif
    unsigned reg = registerSet & -registerSet;
    //printf(" %x : %x\n", registerSet, reg);
    ptr->liveRange.reg = reg;
    markInvalidRegs(ptr);
    propegateCopies(source, reg);
  }
#endif
}

#if 0
void InstructionStream::computePressure(Event* event) {
  Event* walkTo = event;
  for (Event* i = event - 1, *e = event + event->use.offsetToValue; i != e; --i)
    switch (i->kind) {
    case Object::HOLE: break;
    case Object::WALK_BACK:
      walkTo = std::min(walkTo, i + i->link.offsetToTarget);
      break;
    case Object::SKIP_BACK:
      if (i + i->link.offsetToTarget < walkTo)
        i += i->link.offsetToTarget;
      break;
    case Object::USE:
      // TODO: this will double count some values
      if (i < walkTo && i + i->use.offsetToValue == e)
        return;
      break;
    case Object::JUMP:
    case Object::BRANCH: break;
    default:
      assert(i->value.isValue());
      assert((i + i->value.offsetToRep)->value.isValue());
      (i + i->value.offsetToRep)->value.pressure++;
  }
}
#endif

#if 0
unsigned InstructionStream::computeValidRegs(Event* event, Event*& source) {
  unsigned validSet = ~event->liveRange.invalidRegs;
  Event* walkTo = event;
  for (Event* i = event - 1, *e = event + event->liveRange.offsetToOrigin; i != e; --i)
    switch (i->kind) {
    case Object::WALK_BACK:
      walkTo = std::min(walkTo, i + i->link.offsetToTarget);
      break;
    case Object::SKIP_BACK:
      if (i + i->link.offsetToTarget < walkTo)
        i += i->link.offsetToTarget;
      break;
    case Object::LIVE_RANGE:
      if (i < walkTo && i + i->liveRange.offsetToOrigin == e) {
        source = i;
        return validSet;
      }
      validSet &= ~(i->liveRange.reg | i->value.copySet | i->liveRange.invalidRegs);
    }
  source = event + event->liveRange.offsetToOrigin;
  return validSet;
}
#endif

#if 0
void InstructionStream::markInvalidRegs(Event* event) {
  unsigned reg = event->liveRange.reg;
  Event* walkTo = event;
  for (Event* i = event - 1, *e = event + event->liveRange.offsetToOrigin; i != e; --i)
    switch (i->kind) {
    case Object::WALK_BACK:
      walkTo = std::min(walkTo, i + i->link.offsetToTarget);
      break;
    case Object::SKIP_BACK:
      if (i + i->link.offsetToTarget < walkTo)
        i += i->link.offsetToTarget;
      break;
    case Object::LIVE_RANGE:
      if (i < walkTo && i + i->liveRange.offsetToOrigin == e)
        return;
      i->liveRange.invalidRegs |= reg;
    }
}
#endif

#if 0
void InstructionStream::propegateCopies(Event* source, unsigned reg) {
  if (source->kind == Object::PHI) {
    int key = source->phiLink.key;
    do {
      propegateCopies(source + source->phiLink.offsetToTarget, reg);
      --source;
    } while (source->kind == Object::PHI && source->phiLink.key == key);
    return;
  }
  assert(source->object.isValue());
  source->value.copySet |= reg;
}
#endif

#if 0
void InstructionStream::untwistPairs(Event* event) {
  if (event->kind != Object::ADD)
    return;
  unsigned copySet = event->instruction.copySet;
  unsigned reg0 = event[-2].liveRange.reg;
  unsigned reg1 = event[-1].liveRange.reg;
  if (!(reg0 & copySet) && (reg1 & copySet))
    std::swap(event[-2].liveRange.reg, event[-1].liveRange.reg);
}
#endif

void InstructionStream::printWalk(Instruction* instr, Instruction* target) {
  Instruction* first = instrs.data() + instr->block->firstInstr;
}

void InstructionStream::printWalks() {
  //return;
  for (size_t i = 0, e = instrs.size(); i != e; ++i) {
    Instruction* instr = &instrs[i];
    if (!instr->opcode->hasArg0)
      continue;
    Instruction* first = instrs.data() + instr->block->firstInstr;
    //printf("first = %d\n", first - instrs.data());
    if (instr->opcode->hasArg0) {
      Instruction* target = instr + instr->arg0;
      printf("? %d => %d\n", i, i + instr->arg0);
      for (;;) {
        for (; instr != target && instr >= first; instr--)
          printf("%d->", instr - instrs.data());
        if (instr == target)
          break;
        //break;
        const Block* block = instr->block;
        assert(instrs.data() + block->firstInstr == instr + 1);
        if (!block->parent)
          break;
        //printf("block : %d parent : %d current : %d next : %d target : %d\n",
        //  block - blocks.data(), );
        instr += (block + block->parent)->lastInstr - block->firstInstr - 1;
      }
      printf("%d\n", instr - instrs.data());
      instr = &instrs[i];
    }
#if 0
    if (instr->opcode->hasArg1) {
      Instruction* target = instr + instr->arg1;
      printf("? %d => %d\n", i, i + instr->arg1);
      for (;;) {
        for (; instr != target && instr >= first; instr--)
          printf("%d->", instr - instrs.data());
        if (instr == target)
          break;
        //break;
        const Block* block = instr->block;
        assert(instrs.data() + block->firstInstr == instr + 1);
        if (!block->parent)
          break;
        //printf("block : %d parent : %d current : %d next : %d target : %d\n",
        //  block - blocks.data(), );
        instr += (block + block->parent)->lastInstr - block->firstInstr - 1;
      }
      printf("%d\n", instr - instrs.data());
    }
#endif
  }
}

// FIXME put me in a header
//extern void emitASM(X64Builder& builder, Event* events, size_t numEvents);
#endif

void encode(SCFG* cfg, char* output) {
  InstructionStream stream;
  stream.encode(&cfg, 1);

  print(stream.instrs, stream.numInstrs);
  //stream.printWalks();
  //X64Builder builder;
  //emitASM(builder, InstructionStream.events.data(), InstructionStream.events.size());
}


text:
//
// Copyright (c) 2009 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty.  In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
//    claim that you wrote the original software. If you use this software
//    in a product, an acknowledgment in the product documentation would be
//    appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
//    misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//

// Version 1.0 - Initial version
// Version 1.1 - Fixed path parsing, implemented curves, implemented circle.

#ifndef NANOSVG_H
#define NANOSVG_H

#ifdef __cplusplus
extern "C" {
#endif

/* Example Usage:
	// Load
	struct SVGPath* plist;
	plist = svgParseFromFile("test.svg.");
	// Use...
	for (SVGPath* it = plist; it; it = it->next)
		...
	// Delete
	svgDelete(plist);
*/

struct SVGPath
{
	float* pts;
	int npts;
	unsigned int fillColor;
	unsigned int strokeColor;
	float strokeWidth;
	char hasFill;
	char hasStroke;
	char closed;
	struct SVGPath* next;
};

// Parses SVG file from a file, returns linked list of paths.
struct SVGPath* svgParseFromFile(const char* filename);

// Parses SVG file from a null terminated string, returns linked list of paths.
struct SVGPath* svgParse(char* input);

// Deletes list of paths.
void svgDelete(struct SVGPath* plist);

#ifdef __cplusplus
};
#endif

#endif // NANOSVG_H


text:
package main

import (
	"bytes"
	"fmt"
	"os"

	log "github.com/cihub/seelog"
)

const baseStdErrLogConfig = `<seelog minlevel="loglevel">
	<outputs formatid="common">
		<custom name="stderr" />
	</outputs>
	<formats>
		<format id="common" format="%Msg%n"/>
	</formats>
</seelog>`

type StdErrReceiver struct{}

// Implement seelog.CustomReceiver to log to stderr instead of stdout
func (sr *StdErrReceiver) ReceiveMessage(message string, level log.LogLevel, context log.LogContextInterface) error {
	fmt.Fprintf(os.Stderr, message)
	return nil
}

func (sr *StdErrReceiver) AfterParse(initArgs log.CustomReceiverInitArgs) error {
	return nil
}

func (sr *StdErrReceiver) Flush() {}

func (sr *StdErrReceiver) Close() error {
	return nil
}

func initLogging(logLevel string) error {
	log.RegisterReceiver("stderr", &StdErrReceiver{})

	logConfig := bytes.Replace([]byte(baseStdErrLogConfig), []byte("loglevel"), []byte(logLevel), 1)
	logger, err := log.LoggerFromConfigAsBytes(logConfig)
	if err != nil {
		return err
	}

	log.ReplaceLogger(logger)

	return nil
}


text:
import numpy as np

from tensorflow_similarity.indexer import Indexer

from . import DATA_DIR

def test_calibration():
    # CALIB TEST
    SIZE = 20

    FNAME = str(DATA_DIR / "mnist_fashion_embeddings.npz")
    data = np.load(FNAME, allow_pickle=True)
    thresholds_targets = {"0.5": 0.5}

    index = Indexer(3)
    index.batch_add(data["embeddings_idx"][:SIZE], labels=data["y_idx"][:SIZE])
    calibration = index.calibrate(data["embeddings_cal"][:SIZE], data["y_cal"][:SIZE], thresholds_targets, verbose=1)
    # assert 'vl' in cutpoints
    assert "optimal" in calibration.cutpoints
    assert "0.5" in calibration.cutpoints
    assert len(calibration.thresholds["distance"]) == len(calibration.thresholds["value"])
    assert index.is_calibrated

def test_indexer_basic_flow():

    prediction = np.array([[1, 1, 2]], dtype="float32")
    embs = np.array([[1, 1, 3], [3, 1, 2]], dtype="float32")

    indexer = Indexer(3)

    # index data
    indexer.batch_add(embs, labels=[0, 1], data=["test", "test2"])

    # lookup
    matches = indexer.single_lookup(prediction)

    assert isinstance(matches, list)
    assert matches[0].distance < 0.016

    assert np.array_equal(matches[0].embedding, embs[0])
    assert matches[0].label == 0
    assert matches[0].data == "test"

def test_indexer_batch_add():

    prediction = np.array([[1, 1, 2]], dtype="float32")
    embs = np.array([[1, 1, 3], [3, 1, 2]], dtype="float32")

    indexer = Indexer(3)

    # index data
    indexer.batch_add(embs, [0, 1], data=["test", "test2"])
    assert indexer.size() == 2
    # check results
    matches = indexer.single_lookup(prediction)

    assert isinstance(matches, list)
    assert matches[0].distance < 0.016

    assert np.array_equal(matches[0].embedding, embs[0])
    assert matches[0].label == 0
    assert matches[0].data == "test"

def test_multiple_add():

    # arrays of preds which contains a single embedding list(list(embedding))
    predictions = np.array([[[1, 1, 3]], [[3, 1, 2]]], dtype="float32")

    indexer = Indexer(3)
    indexer.add(predictions[0])
    assert indexer.size() == 1

    indexer.add(predictions[1])
    assert indexer.size() == 2

def test_multiple_add_mix_data():

    embs = np.array([[1, 1, 3], [3, 1, 2]], dtype="float32")

    indexer = Indexer(3)
    indexer.batch_add(embs)
    assert indexer.size() == 2

    indexer.batch_add(embs, data=embs)
    assert indexer.size() == 4

def test_reload(tmp_path):

    embs = np.array([[1, 1, 3], [3, 1, 2]], dtype="float32")

    indexer = Indexer(3)
    indexer.batch_add(embs, verbose=0)
    assert indexer.size() == 2

    # save
    path = tmp_path / "test_save_and_add/"
    indexer.save(path)

    # reload
    indexer2 = Indexer.load(path)
    assert indexer2.size() == 2

    # add more
    indexer2.batch_add(embs, data=embs)
    assert indexer2.size() == 4

def test_uncompress_reload(tmp_path):
    "Ensure uncompressed index work"

    embs = np.array([[1, 1, 3], [3, 1, 2]], dtype="float32")

    indexer = Indexer(3)
    indexer.batch_add(embs, verbose=0)
    assert indexer.size() == 2

    # save
    path = tmp_path / "test_save_and_add/"
    indexer.save(path, compression=False)

    # reload
    indexer2 = Indexer.load(path)
    assert indexer2.size() == 2

def test_index_reset():

    prediction = np.array([[1, 1, 2]], dtype="float32")
    embs = np.array([[1, 1, 3], [3, 1, 2], [3, 2, 3]], dtype="float32")

    indexer = Indexer(3)

    # index data
    indexer.batch_add(embs, labels=[0, 1, 2])

    # lookup
    matches = indexer.single_lookup(prediction)

    # get stats
    stats = indexer.stats()

    # check results
    assert len(matches) == 3
    assert len(matches[0].embedding) == 3
    assert matches[0].label == 0
    assert list(matches[0].embedding) == list(embs[0])

    # reset
    indexer.reset()
    stats = indexer.stats()
    assert stats["num_lookups"] == 0
    assert stats["num_items"] == 0

    # do-over
    indexer.add([embs[0]], label=42)
    indexer.add([embs[1]], label=43)

    matches = indexer.single_lookup(prediction)
    stats = indexer.stats()

    assert len(matches) == 2
    assert len(matches[0].embedding) == 3
    assert matches[0].label == 42
    assert matches[1].label == 43
    assert list(matches[0].embedding) == list(embs[0])
    assert list(matches[1].embedding) == list(embs[1])
    assert stats["num_lookups"] == 1

def test_indexer_batch_ops():
    NUM_ELTS = 100
    NUM_DIMS = 10
    K = 3
    data = np.random.randn(NUM_ELTS, NUM_DIMS).astype(np.float32)
    indexer = Indexer(NUM_DIMS)
    indexer.batch_add(data)
    results = indexer.batch_lookup(data, k=K)
    indexer.stats()
    assert len(results) == 100
    assert len(results[0]) == K

def test_single_vs_batch_ops():
    "ensure batch and single ops are consistent"
    NUM_ELTS = 100
    NUM_DIMS = 10
    K = 3
    data = np.random.randn(NUM_ELTS, NUM_DIMS).astype(np.float32)
    indexer = Indexer(NUM_DIMS)
    indexer.batch_add(data)
    batch_results = indexer.batch_lookup(data, k=K)

    single_results = []
    for d in data:
        single_results.append(indexer.single_lookup([d], k=K))

    for idx in range(len(single_results)):
        assert single_results[idx][0].label == batch_results[idx][0].label


text:
package provisioner

import (
	bosherr "github.com/cloudfoundry/bosh-utils/errors"
	boshlog "github.com/cloudfoundry/bosh-utils/logger"

	bpdep "github.com/cppforlife/bosh-provisioner/deployment"
	bpeventlog "github.com/cppforlife/bosh-provisioner/eventlog"
	bpinstance "github.com/cppforlife/bosh-provisioner/instance"
	bpvm "github.com/cppforlife/bosh-provisioner/vm"
)

// SingleConfiguredVMProvisioner interprets deployment manifest and
// configures 1 VM just like regular BOSH VM.
type SingleConfiguredVMProvisioner struct {
	manifestPath            string
	deploymentReaderFactory bpdep.ReaderFactory

	vmProvisioner       bpvm.Provisioner
	releaseCompiler     ReleaseCompiler
	instanceProvisioner bpinstance.Provisioner

	eventLog bpeventlog.Log
	logger   boshlog.Logger
}

func NewSingleConfiguredVMProvisioner(
	manifestPath string,
	deploymentReaderFactory bpdep.ReaderFactory,
	vmProvisioner bpvm.Provisioner,
	releaseCompiler ReleaseCompiler,
	instanceProvisioner bpinstance.Provisioner,
	eventLog bpeventlog.Log,
	logger boshlog.Logger,
) SingleConfiguredVMProvisioner {
	return SingleConfiguredVMProvisioner{
		manifestPath:            manifestPath,
		deploymentReaderFactory: deploymentReaderFactory,

		vmProvisioner:       vmProvisioner,
		releaseCompiler:     releaseCompiler,
		instanceProvisioner: instanceProvisioner,

		eventLog: eventLog,
		logger:   logger,
	}
}

func (p SingleConfiguredVMProvisioner) Provision() error {
	stage := p.eventLog.BeginStage("Setting up instance", 2)

	reader := p.deploymentReaderFactory.NewManifestReader(p.manifestPath)

	task := stage.BeginTask("Reading deployment manifest")

	deployment, err := reader.Read()
	if task.End(err) != nil {
		return bosherr.WrapError(err, "Reading deployment")
	}

	task = stage.BeginTask("Validating instance")

	job, depInstance, err := p.validateInstance(deployment)
	if task.End(err) != nil {
		return bosherr.WrapError(err, "Validating instance")
	}

	// todo VM was possibly provisioned last time
	vm, err := p.vmProvisioner.Provision(depInstance)
	if err != nil {
		return bosherr.WrapError(err, "Provisioning VM")
	}

	instance := p.instanceProvisioner.PreviouslyProvisioned(vm.AgentClient(), job, depInstance)

	err = instance.Deprovision()
	if err != nil {
		return bosherr.WrapError(err, "Deprovisioning instance")
	}

	// Deprovision VM before using release compiler since it will try to provision its own VM
	err = vm.Deprovision()
	if err != nil {
		return bosherr.WrapError(err, "Deprovisioning VM")
	}

	err = p.releaseCompiler.Compile(deployment.CompilationInstance, deployment.Releases)
	if err != nil {
		return bosherr.WrapError(err, "Compiling releases")
	}

	vm, err = p.vmProvisioner.Provision(depInstance)
	if err != nil {
		return bosherr.WrapError(err, "Provisioning VM")
	}

	_, err = p.instanceProvisioner.Provision(vm.AgentClient(), job, depInstance)
	if err != nil {
		return bosherr.WrapError(err, "Starting instance")
	}

	// Do not Deprovision() VM to keep instance running

	return nil
}

func (p SingleConfiguredVMProvisioner) validateInstance(deployment bpdep.Deployment) (bpdep.Job, bpdep.Instance, error) {
	var job bpdep.Job
	var instance bpdep.Instance

	if len(deployment.Jobs) > 1 {
		return job, instance, bosherr.Error("Must have exactly 1 job")
	}

	job = deployment.Jobs[0]

	if len(job.Instances) != 1 {
		return job, instance, bosherr.Error("Must have exactly 1 instance")
	}

	instance = job.Instances[0]

	return job, instance, nil
}


text:
/**
 * Provides examples and tutorials on using JKernelMachines.
 */
package net.jkernelmachines.example;


text:
@interface LoadPageComponent : CKCompositeComponent

@end


text:
"""
    Models to manage users and profiles
"""
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.dispatch import receiver
from django.contrib.auth.signals import user_logged_in

from geotrek.common.utils import reify

class Structure(models.Model):
    """
    Represents an organisational structure, to which users are related.
    """
    name = models.CharField(max_length=256, verbose_name=_(u"Nom"))

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name = _(u"Structure")
        verbose_name_plural = _(u"Structures")
        ordering = ['name']
        permissions = (("can_bypass_structure", _("Can bypass structure")),)

def default_structure():
    """ Create default structure if necessary """
    return Structure.objects.get_or_create(name=settings.DEFAULT_STRUCTURE_NAME)[0]

class StructureRelatedQuerySet(models.query.QuerySet):
    def for_user(self, user):
        return StructureRelatedQuerySet.queryset_for_user(self, user)

    @staticmethod
    def queryset_for_user(queryset, user):
        return queryset.filter(structure=user.profile.structure)

class StructureRelatedManager(models.Manager):
    """ A simple manager to manage structure related objects"""
    def get_queryset(self):
        return StructureRelatedQuerySet(self.model, using=self._db)

    def for_user(self, user):
        """ Filter by user's structure """
        return self.get_queryset().for_user(user)

class StructureRelated(models.Model):
    """
    A mixin used for any entities that belong to a structure
    """
    structure = models.ForeignKey(Structure, default=default_structure,
                                  verbose_name=_(u"Related structure"), db_column='structure')

    objects = models.Manager()
    in_structure = StructureRelatedManager()

    @classmethod
    def for_user(cls, user):
        """ Shortcut to manager's filter by user """
        return cls.in_structure.for_user(user)

    def same_structure(self, user):
        """ Returns True if the user is in the same structure or has
            bypass_structure permission, False otherwise. """
        return (user.profile.structure == self.structure or
                user.is_superuser or
                user.has_perm('authent.can_bypass_structure'))

    class Meta:
        abstract = True
        verbose_name = _(u"Related structures")
        verbose_name_plural = _(u"Related structure")

class UserProfile(StructureRelated):
    """
    A custom user profile
    """
    user = models.OneToOneField(User, unique=True)

    language = models.CharField(_(u"Language"), max_length=10,
                                choices=settings.LANGUAGES,
                                default=settings.LANGUAGE_CODE)

    class Meta:
        verbose_name = _(u"User's profile")
        verbose_name_plural = _(u"User's profiles")

    def __unicode__(self):
        return _("Profile for %s") % self.user

User.profile = reify(lambda u: UserProfile.objects.get_or_create(user=u)[0])

@receiver(user_logged_in)
def lang(sender, **kwargs):
    """ Set user's language in session when he logs in. """
    lang_code = kwargs['user'].profile.language
    kwargs['request'].session['django_language'] = lang_code


text:
import React from 'react';
import { render, mount } from 'enzyme';
import { renderToJson } from 'enzyme-to-json';
import List from '../list';
import Checkbox from '../../checkbox';

const listCommonProps = {
  prefixCls: 'ant-transfer-list',
  dataSource: [{
    key: 'a',
    title: 'a',
  }, {
    key: 'b',
    title: 'b',
  }, {
    key: 'c',
    title: 'c',
    disabled: true,
  }],
  checkedKeys: ['a'],
  notFoundContent: 'Not Found',
  lazy: false,
};

describe('List', () => {
  it('should render correctly', () => {
    const wrapper = render(<List {...listCommonProps} />);
    expect(renderToJson(wrapper)).toMatchSnapshot();
  });

  it('should check top Checkbox while all available items are checked', () => {
    const wrapper = mount(<List {...listCommonProps} checkedKeys={['a', 'b']} />);
    expect(wrapper.find('.ant-transfer-list-header').find(Checkbox).prop('checked'))
      .toBeTruthy();
  });
});