text:
/**
 * Set of utilities to transform Shadow DOM v1 to v0.
 * Usefull when writing "hybrid" Web Components which are V1 ready,
 * but run in v0 environment/polyfill
 * @license MIT
 * @version: 0.0.5
 */
const TranslateShadowDOM = {
    /**
     * Utils to translate from V1 to V0
     */
    v1tov0: {
        /**
        * Replaces all <slot> tags with <content>,
        *  preserves all attributes, translates selector to slot name
        * @param  {String} string stringified HTML
        * @return {String}        translated HTML
        */
        html: function(string){
            return string.replace(/<\/slot(\s*)>/gi,'</content$1>')
                        .replace(/<slot([^>]+)(name=(?:"([^"]*)"|'([^']*)'))([^>]*)>/gi,'<content$1$2$5 select=\"[slot=\'$3$4\']\">')
                        .replace(/<slot(\s*|\s+[^>]*)>/gi,'<content$1>');
        },
        /**
        * Replaces single SlotElement with ContentElement,
        *  preserves all attributes, translates name to selector
        * @param  {SlotElement} slot
        * @return {ContentElement}
        */
        slot: function(slot) {
            var content = slot.ownerDocument.createElement('content');
            while (slot.firstChild) {
                content.appendChild(slot.firstChild);
            }
            var attrs = slot.attributes;
            for (var i=0; i<attrs.length; i++) {
                var attr = attrs[i];
                content.setAttribute(attr.name, attr.value);
            }
            var name = slot.getAttribute('name');
            if (name) {
                content.setAttribute('select', '[slot=\'' + name + '\']');
            }
            slot.parentNode.replaceChild(content, slot);
            return content;
        },
        /**
        * Replace all <slot> elements with <content> elements i given document fragment
        * @param  {Documentfragment|Node} root scope. Will be changed.
        * @param  {Boolean}                 withStyle should enclosed `style` tags be also translated
        * @param  {Boolean}                 withScript should enclosed `script` tags be also translated
        * @return {Documentfragment|Node}      modified scope
        */
        fragment: function fragment(root, withStyle, withScript) {
            if (root.firstChild) {
                var node = root.firstChild;
                while (node) {
                    var next = node.nextSibling;
                    if (node.localName === 'slot') {
                        node = TranslateShadowDOM.v1tov0.slot(node);
                    } else if (withStyle && node.localName === 'style') {
                        node.textContent = TranslateShadowDOM.v1tov0.css(node.textContent);
                    } else if (withScript && node.localName === 'script') {
                        node.textContent = TranslateShadowDOM.v1tov0.js(node.textContent);
                    }
                    fragment(node, withStyle, withScript);
                    node = next;
                }
            }
            return root;
        },
        /**
        * Replaces all ::slotted() tags with ::content
        * @param  {String} string stringified CSS
        * @return {String}        translated CSS
        */
        css: function(string) {
            return string.replace(/::slotted\(([^\)]*)\)/gi,'::content>$1');
        },
        /**
        * Replaces all `attachShadow(*)` with `createShadowRoot()`.
        * @param  {String} string stringified JS
        * @return {String}        translated JS
        */
        js: function(string){
            return string.replace(/attachShadow\([^\)]*\)/g, 'createShadowRoot()');
        }
    },
    /**
     * Utils to translate from V0 to V1
     */
    v0tov1: {
        /**
        * Replaces all <content> tags with <slot>,
        *  preserves all attributes **except** name, translates selector to slot name
        * @param  {String} string stringified HTML
        * @return {String}        translated HTML
        */
        html: function(string){
            return string.replace(/<\/content(\s*)>/gi,'</slot$1>')
                        .replace(/<content([^>]*?)(\s+name=(?:"([^"]*)"|'([^']*)'))([^>]*)>/gi,'<content$1$5>')
                        .replace(/<content([^>]+)(select="\s*\[slot=(?:"([^"]*)"|'([^']*)')\]\s*")([^>]*)>/gi,'<slot$1$2$5 name=\"$3$4\">')
                        .replace(/<content(\s*|\s+[^>]*)>/gi,'<slot$1>');
        },
        /**
        * Replaces single ContentElement with SlotElement,
        *  preserves all attributes, translates selector to slot name.
        *  If selector cannot be directly translated to slot name, default slot would be created.
        * @param  {ContentElement} content
        * @return {SlotElement}
        */
        content: function(content) {
            var slot = content.ownerDocument.createElement('slot');
            while (content.firstChild) {
                slot.appendChild(content.firstChild);
            }
            var attrs = content.attributes;
            for (var i=0; i<attrs.length; i++) {
                var attr = attrs[i];
                if(attr.name !== 'name'){
                    slot.setAttribute(attr.name, attr.value);
                }
            }
            var name = content.getAttribute('select');
            var match;
            if (name && (match = name.match(/\s*\[slot=(?:"([^"]*)"|'([^']*)')\]\s*/i))) {
                slot.setAttribute('name', match[1] || match[2]);
            }
            content.parentNode.replaceChild(slot, content);
            return slot;
        },
        /**
        * Replace all <slot> elements with <content> elements i given document fragment.
        * @param  {Documentfragment|Node} root scope. Will be changed.
        * @param  {Boolean}                 withStyle should enclosed `style` tags be also translated
        * @param  {Boolean}                 withStyle should enclosed `script` tags be also translated
        * @return {Documentfragment|Node}      modified scope
        */
        fragment: function fragment(root, withStyle, withScript) {
            if (root.firstChild) {
                var node = root.firstChild;
                while (node) {
                    var next = node.nextSibling;
                    if (node.localName === 'content') {
                        node = TranslateShadowDOM.v0tov1.content(node);
                    } else if (withStyle && node.localName === 'style') {
                        node.textContent = TranslateShadowDOM.v0tov1.css(node.textContent);
                    } else if (withScript && node.localName === 'script') {
                        node.textContent = TranslateShadowDOM.v0tov1.js(node.textContent);
                    }
                    fragment(node, withStyle, withScript);
                    node = next;
                }
            }
            return root;
        },
        /**
        * Replaces all ::content tags with ::slotted with warning if needed
        * @param  {String} string stringified CSS
        * @return {String}        translated CSS
        */
        css: function(string) {
            return string.replace(/::content\s*(>)?\s*([^,{\s]*?)([\+\s\~][^,{\s]+?)?(\s*[,{])/gi,
                    function(match, direct, compound, complex, rest){
                        let warning = '';
                        if(!direct){
                            warning += ' V1 matches only direct children;';
                        }
                        if(complex){
                            warning += ' V1 supports only compound selectors, selector skipped:'+complex+';';
                        }
                        if(warning){
                            console.warn('TranslateShadowDOM.v0tov1.css: ' + warning);
                            return '::slotted(' + compound + ')/* FIXME' + warning + '*/' + rest;
                        } else {
                            return '::slotted(' + compound + ')' + rest;
                        }
                    });
            ;
        },
        /**
        * Replaces all `createShadowRoot()` tags with `attachShadow({mode:'open'})`.
        * @param  {String} string stringified JS
        * @return {String}        translated JS
        */
        js: function(string){
            return string.replace(/createShadowRoot\(\s*\)/g, 'attachShadow({mode: \'open\'})');
        }
    }
}

if (typeof module !== 'undefined') {
  module.exports = TranslateShadowDOM;
  // export default TranslateShadowDOM;
}


text:
<!DOCTYPE html >

    <link rel="stylesheet" href="demos.css" type="text/css" media="screen" />

    <title>RGraph demo: A "rectangular" Pie chart</title>

    <meta name="robots" content="noindex,nofollow" />
    <meta name="description" content="A rectangular Pie chart" />

A "rectangular" Pie chart

        By using a large chart.radius setting the Pie will be too large for the canvas and you'll get a rectangular Pie chart effect.

    <canvas id="cvs" width="350" height="250" style="border: 1px solid #aaa">[No canvas support]</canvas>

    This goes in the documents header:

<script src="RGraph.common.core.js"></script>
<script src="RGraph.common.key.js"></script>
<script src="RGraph.common.effects.js"></script>
<script src="RGraph.pie.js"></script>

    Put this where you want the chart to show up:

<canvas id="cvs" width="350" height="250">
    [No canvas support]
</canvas>

    This is the code that generates the chart:

<script>
    window.onload = function ()
    {
        var pie = new RGraph.Pie({
            id: 'cvs',
            data: [4,8,4,6,5,3,2,5],
            options: {
                radius: 350,
                key: ['Alvin','Pete','Hoolio','Jack','Kev','Luis','Lou','Jesse'],
                strokestyle: 'white',
                linewidth: 3,
                textSize: 14,
                textAccessible: true
            }
        }).draw()

        if (RGraph.ISIE9UP || RGraph.ISCHROME) {
            pie.roundRobin();
            pie.implode();
        } else if (RGraph.ISOLD) {
            pie.draw()
        } else {
            pie.grow();
        }
    };
</script>

        « Back

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using Granular.Extensions;

namespace System.Windows.Media.Animation
{
    // dependency property animated value, contains animation layers with clocks
    public class AnimationExpression : IExpression
    {
        public event ObservableValueChangedEventHandler ValueChanged;
        public object Value { get { return observableValue.Value; } }

        private AnimationLayerCollection layers;
        private ObservableValue observableValue;
        private DependencyObject dependencyObject;
        private DependencyProperty dependencyProperty;

        public AnimationExpression(DependencyObject dependencyObject, DependencyProperty dependencyProperty)
        {
            this.dependencyObject = dependencyObject;
            this.dependencyProperty = dependencyProperty;

            observableValue = new ObservableValue();
            observableValue.ValueChanged += (sender, oldValue, newValue) => ValueChanged.Raise(this, oldValue, newValue);

            layers = new AnimationLayerCollection();
            layers.LayerInvalidated += OnLayerInvalidated;

            SetAnimationValue();
        }

        public bool SetValue(object value)
        {
            return false;
        }

        public void SetClocks(IEnumerable<AnimationTimelineClock> clocks, object layerOwner)
        {
            layers.SetClocks(clocks, GetAnimationBaseValue(), AnimationLayerKey.FromLayerOwner(layerOwner));
        }

        public void AddClocks(IEnumerable<AnimationTimelineClock> clocks, object layerOwner)
        {
            layers.AddClocks(clocks, AnimationLayerKey.FromLayerOwner(layerOwner));
        }

        public void RemoveClocks(IEnumerable<AnimationTimelineClock> clocks, object layerOwner)
        {
            layers.RemoveClocks(clocks, AnimationLayerKey.FromLayerOwner(layerOwner));
        }

        private void SetAnimationValue()
        {
            observableValue.BaseValue = layers.HasValue ? layers.GetValue(GetAnimationBaseValue()) : ObservableValue.UnsetValue;
        }

        private object GetAnimationBaseValue()
        {
            if (dependencyObject == null)
            {
                return ObservableValue.UnsetValue;
            }

            IDependencyPropertyValueEntry entry = dependencyObject.GetValueEntry(dependencyProperty);
            return entry.GetBaseValue(true);
        }

        private void OnLayerInvalidated(object sender, EventArgs e)
        {
            SetAnimationValue();
        }
    }
}


text:
import _ from 'lodash';
import i18next from 'i18next';
const t = i18next.t.bind(i18next);

if (_.get(i18next, 'options.returnEmptyString') === undefined) {
  // Return key if no translation is present
  i18next.init({ returnEmptyString: false, nsSeparator: '|' });
}

export const BG_HIGH = t('High');
export const BG_LOW = t('Low');

const STIFFNESS = 180;
const DAMPING = 40;
const PRECISION = 0.1;

export const springConfig = { stiffness: STIFFNESS, damping: DAMPING, precision: PRECISION };

export const MGDL_CLAMP_TOP = 400;
export const MMOLL_CLAMP_TOP = 22.5;

export const MGDL_UNITS = t('mg/dL');
export const MMOLL_UNITS = t('mmol/L');
export const MGDL_PER_MMOLL = 18.01559;

export const DEFAULT_BG_BOUNDS = {
  [MGDL_UNITS]: {
    veryLowThreshold: 54,
    targetLowerBound: 70,
    targetUpperBound: 180,
    veryHighThreshold: 250,
    clampThreshold: 600,
  },
  [MMOLL_UNITS]: {
    veryLowThreshold: 3.0,
    targetLowerBound: 3.9,
    targetUpperBound: 10.0,
    veryHighThreshold: 13.9,
    clampThreshold: 33.3,
  },
};

export const LBS_PER_KG = 2.2046226218;

const ONE_WEEK = 7;
const TWO_WEEKS = 14;
const FOUR_WEEKS = 28;

export const trends = { extentSizes: { ONE_WEEK, TWO_WEEKS, FOUR_WEEKS } };

export const MS_IN_DAY = 864e5;
export const MS_IN_HOUR = 864e5 / 24;
export const MS_IN_MIN = MS_IN_HOUR / 60;

export const CGM_READINGS_ONE_DAY = 288;
export const CGM_DATA_KEY = 'cbg';
export const BGM_DATA_KEY = 'smbg';

export const NO_SITE_CHANGE = 'noSiteChange';
export const SITE_CHANGE = 'siteChange';
export const SITE_CHANGE_RESERVOIR = 'reservoirChange';
export const SITE_CHANGE_TUBING = 'tubingPrime';
export const SITE_CHANGE_CANNULA = 'cannulaPrime';

export const AUTOMATED_DELIVERY = 'automatedDelivery';
export const AUTOMATED_SUSPEND = 'automatedSuspend';
export const SCHEDULED_DELIVERY = 'scheduledDelivery';
export const SETTINGS_OVERRIDE = 'settingsOverride';
export const SLEEP = 'sleep';
export const PHYSICAL_ACTIVITY = 'physicalActivity';
export const MAX_BOLUS = 'maxBolus';
export const MAX_BASAL = 'maxBasal';
export const INSULIN_DURATION = 'insulinDuration';

export const SITE_CHANGE_TYPE_UNDECLARED = 'undeclared';

export const INSULET = 'Insulet';
export const TANDEM = 'Tandem';
export const ANIMAS = 'Animas';
export const MEDTRONIC = 'Medtronic';
export const MICROTECH = 'Microtech';

export const pumpVocabulary = {
  [ANIMAS]: {
    [SITE_CHANGE_RESERVOIR]: t('Go Rewind'),
    [SITE_CHANGE_TUBING]: t('Go Prime'),
    [SITE_CHANGE_CANNULA]: t('Fill Cannula'),
  },
  [INSULET]: {
    [SITE_CHANGE_RESERVOIR]: t('Change Pod'),
    [SITE_CHANGE_TUBING]: t('Activate Pod'),
    [SITE_CHANGE_CANNULA]: t('Prime'),
    [MAX_BOLUS]: t('Maximum Bolus'),
    [MAX_BASAL]: t('Max Basal Rate'),
    [INSULIN_DURATION]: t('Duration of Insulin Action'),
  },
  [MEDTRONIC]: {
    [SITE_CHANGE_RESERVOIR]: t('Rewind'),
    [SITE_CHANGE_TUBING]: t('Prime'),
    [SITE_CHANGE_CANNULA]: t('Prime Cannula'),
    [AUTOMATED_DELIVERY]: t('Auto Mode'),
    [SCHEDULED_DELIVERY]: t('Manual'),
    [MAX_BOLUS]: t('Max Bolus'),
    [MAX_BASAL]: t('Max Basal'),
    [INSULIN_DURATION]: t('Active Insulin Time'),
  },
  [MICROTECH]: {
    [SITE_CHANGE_RESERVOIR]: t('Rewind'),
    [SITE_CHANGE_TUBING]: t('Prime Reservoir'),
    [SITE_CHANGE_CANNULA]: t('Prime Cannula'),
  },
  [TANDEM]: {
    [SITE_CHANGE_RESERVOIR]: t('Change Cartridge'),
    [SITE_CHANGE_TUBING]: t('Fill Tubing'),
    [SITE_CHANGE_CANNULA]: t('Fill Cannula'),
    [AUTOMATED_DELIVERY]: t('Automation'),
    [SCHEDULED_DELIVERY]: t('Manual'),
    [SETTINGS_OVERRIDE]: t('Activity'),
    [SLEEP]: { label: t('Sleep'), marker: t('Z') },
    [PHYSICAL_ACTIVITY]: { label: t('Exercise'), marker: t('E') },
    [MAX_BOLUS]: t('Max Bolus'),
    [INSULIN_DURATION]: t('Insulin Duration'),
  },
  default: {
    [SITE_CHANGE_RESERVOIR]: t('Change Cartridge'),
    [SITE_CHANGE_TUBING]: t('Fill Tubing'),
    [SITE_CHANGE_CANNULA]: t('Fill Cannula'),
    [AUTOMATED_DELIVERY]: t('Automated'),
    [AUTOMATED_SUSPEND]: t('Automated Suspend'),
    [SCHEDULED_DELIVERY]: t('Manual'),
    [SETTINGS_OVERRIDE]: t('Settings Override'),
    [SLEEP]: { label: t('Sleep'), marker: t('Z') },
    [PHYSICAL_ACTIVITY]: { label: t('Exercise'), marker: t('E') },
    [MAX_BOLUS]: t('Max Bolus'),
    [MAX_BASAL]: t('Max Basal'),
    [INSULIN_DURATION]: t('Insulin Duration'),
  },
};

export const AUTOMATED_BASAL_DEVICE_MODELS = {
  [MEDTRONIC]: ['1580', '1581', '1582', '1780', '1781', '1782'],
};

export const BG_COLORS = {
  veryLow: '#FB5951',
  low: '#FF8B7C',
  target: '#76D3A6',
  high: '#BB9AE7',
  veryHigh: '#8C65D6',
};


text:
import assert from 'power-assert';

import linkify from '../src/linkify';
import oneInP from './fixtures/one-in-p.html';
import severalInA from './fixtures/several-in-a.html';
import severalInP from './fixtures/several-in-p.html';

describe('linkify', () => {
  describe('default(rootNode)', () => {
    afterEach(() => {
      document.body.innerHTML = '';
    });

    it('creates a link in a <p>', () => {
      document.body.innerHTML = oneInP;
      linkify(document.body);
      const as = document.querySelectorAll('a');
      assert(as.length === 1);
      assert(as[0].textContent === '《abc》');
      assert(as[0].href);
      assert(as[0].target === '_blank');
    });

    it('creates links in a <p>', () => {
      document.body.innerHTML = severalInP;
      linkify(document.body);
      const as = document.querySelectorAll('a');
      assert(as.length === 3);
      assert(as[0].textContent === '《abc》');
      assert(as[1].textContent === '《def》');
      assert(as[2].textContent === '《ghi》');
    });

    it('does not create links in a <a>', () => {
      document.body.innerHTML = severalInA;
      linkify(document.body);
      const as = document.querySelectorAll('a');
      assert(as.length === 1);
      assert(as[0].textContent === '01《abc》23《def》456');
    });
  });
});


text:
package org.renjin.primitives;

import org.renjin.eval.Context;
import org.renjin.eval.EvalException;
import org.renjin.primitives.annotations.processor.ArgumentException;
import org.renjin.primitives.annotations.processor.ArgumentIterator;
import org.renjin.sexp.BuiltinFunction;
import org.renjin.sexp.Environment;
import org.renjin.sexp.FunctionCall;
import org.renjin.sexp.Null;
import org.renjin.sexp.PairList;
import org.renjin.sexp.SEXP;
import org.renjin.sexp.Symbol;

public class R$primitive$unlockBinding
    extends BuiltinFunction
{

    public R$primitive$unlockBinding() {
        super("unlockBinding");
    }

    public SEXP apply(Context context, Environment environment, FunctionCall call, PairList args) {
        try {
            ArgumentIterator argIt = new ArgumentIterator(context, environment, args);
            SEXP s0 = argIt.evalNext();
            SEXP s1 = argIt.evalNext();
            if (!argIt.hasNext()) {
                return this.doApply(context, environment, s0, s1);
            }
            throw new EvalException("unlockBinding: too many arguments, expected at most 2.");
        } catch (ArgumentException e) {
            throw new EvalException(context, "Invalid argument: %s. Expected:\n\tunlockBinding(Symbol, Environment)", e.getMessage());
        } catch (EvalException e) {
            e.initContext(context);
            throw e;
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new EvalException(e);
        }
    }

    public static SEXP doApply(Context context, Environment environment, FunctionCall call, String[] argNames, SEXP[] args) {
        try {
            if ((args.length) == 2) {
                return doApply(context, environment, args[ 0 ], args[ 1 ]);
            }
        } catch (EvalException e) {
            e.initContext(context);
            throw e;
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new EvalException(e);
        }
        throw new EvalException("unlockBinding: max arity is 2");
    }

    public SEXP apply(Context context, Environment environment, FunctionCall call, String[] argNames, SEXP[] args) {
        return R$primitive$unlockBinding.doApply(context, environment, call, argNames, args);
    }

    public static SEXP doApply(Context context, Environment environment, SEXP arg0, SEXP arg1)
        throws Exception
    {
        if ((arg0 instanceof Symbol)&&(arg1 instanceof Environment)) {
            Types.unlockBinding(((Symbol) arg0), ((Environment) arg1));
            return Null.INSTANCE;
        } else {
            throw new EvalException(String.format("Invalid argument:\n\tunlockBinding(%s, %s)\n\tExpected:\n\tunlockBinding(Symbol, Environment)", arg0 .getTypeName(), arg1 .getTypeName()));
        }
    }

}


text:
package etcd

import (
	"encoding/json"
	"fmt"
	"sort"
	"time"

	"github.com/NetSys/quilt/db"
	"github.com/NetSys/quilt/join"

	log "github.com/Sirupsen/logrus"
)

const containerPath = "/containers"

func runContainer(conn db.Conn, store Store) {
	etcdWatch := store.Watch(containerPath, 1*time.Second)
	trigg := conn.TriggerTick(60, db.ContainerTable)
	for range joinNotifiers(trigg.C, etcdWatch) {
		if err := runContainerOnce(conn, store); err != nil {
			log.WithError(err).Warn("Failed to sync containers with Etcd.")
		}
	}
}

func runContainerOnce(conn db.Conn, store Store) error {
	etcdStr, err := readEtcdNode(store, containerPath)
	if err != nil {
		return fmt.Errorf("etcd read error: %s", err)
	}

	if conn.EtcdLeader() {
		return updateLeader(conn, store, etcdStr)
	}

	updateNonLeader(conn, etcdStr)
	return nil
}

func updateLeader(conn db.Conn, store Store, etcdStr string) error {
	dbcs := conn.SelectFromContainer(func(dbc db.Container) bool {
		return dbc.Minion != "" && dbc.IP != ""
	})

	err := writeEtcdSlice(store, containerPath, etcdStr, db.ContainerSlice(dbcs))
	if err != nil {
		return fmt.Errorf("etcd write error: %s", err)
	}

	return nil
}

func updateNonLeader(conn db.Conn, etcdStr string) {
	self, err := conn.MinionSelf()
	if err != nil {
		return
	}

	var rawEtcdDBCs, etcdDBCs []db.Container
	json.Unmarshal([]byte(etcdStr), &rawEtcdDBCs)
	for _, dbc := range rawEtcdDBCs {
		if self.Role == db.Master || dbc.Minion == self.PrivateIP {
			etcdDBCs = append(etcdDBCs, dbc)
		}
	}

	conn.Txn(db.ContainerTable).Run(func(view db.Database) error {
		joinContainers(view, etcdDBCs)
		return nil
	})
}

func joinContainers(view db.Database, etcdDBCs []db.Container) {
	// The join contains only those fields that require restart of the container.
	key := func(iface interface{}) interface{} {
		dbc := iface.(db.Container)

		// The environment variables must be sorted to ensure they're consistent
		// in the join key.
		var env []string
		for k, v := range dbc.Env {
			env = append(env, fmt.Sprintf("%s=%s", k, v))
		}
		sort.Sort(sort.StringSlice(env))

		return struct {
			IP       string
			StitchID string
			Image    string
			Command  string
			Env      string
		}{
			IP:       dbc.IP,
			StitchID: dbc.StitchID,
			Image:    dbc.Image,
			Command:  fmt.Sprintf("%v", dbc.Command),
			Env:      fmt.Sprintf("%v", env),
		}
	}

	pairs, dbcIfaces, etcdDBCIfaces := join.HashJoin(
		db.ContainerSlice(view.SelectFromContainer(nil)),
		db.ContainerSlice(etcdDBCs), key, key)

	for _, dbcI := range dbcIfaces {
		view.Remove(dbcI.(db.Container))
	}

	for _, edbc := range etcdDBCIfaces {
		dbc := view.InsertContainer()
		pairs = append(pairs, join.Pair{L: dbc, R: edbc})
	}

	for _, pair := range pairs {
		dbc := pair.L.(db.Container)
		edbc := pair.R.(db.Container)

		dbc.IP = edbc.IP
		dbc.Minion = edbc.Minion
		dbc.StitchID = edbc.StitchID
		dbc.Image = edbc.Image
		dbc.Command = edbc.Command
		dbc.Labels = edbc.Labels
		dbc.Env = edbc.Env
		view.Commit(dbc)
	}
}


text:
package com.omis

import java.util.UUID

import play.api.libs.json.Json

case class EmpDetails(userId:UUID, firstName: String, lastName: String, department: String,
                      grade: String, salary: String, payScale: String, shortbio: String,
                      created: String)

object EmpDetails {
  implicit val format = Json.format[EmpDetails]
}

case class UserReg(regCode: String, password: String)

object UserReg{
  implicit val format = Json.format[UserReg]
}

case class User(id: java.util.UUID, role: String, created: String)

object User {
  implicit val format = Json.format[User]
}

case class UserProfile(userId: java.util.UUID, address: Option[String], phoneNumber: Option[String], firstName: Option[String],
                       lastName: Option[String], imgUrl: Option[String], nationality: Option[String], fatherName: Option[String],
                       motherName: Option[String], created: String, shortBio: Option[String])


text:
import { ContentBlock } from 'draft-js';
import { extractHashtagsWithIndices } from './utils/extractHashtags';

export default (
  contentBlock: ContentBlock,
  callback: (begin: number, end: number) => void
): void => {
  const text = contentBlock.getText();
  const results = extractHashtagsWithIndices(text);

  results.forEach(hashtag => {
    callback(hashtag.indices[0], hashtag.indices[1]);
  });
};


text:
Are you still there?

      To protect your privacy, we'll log you out in
       60">{{qqq.getCountdownInMinutes()}} minute(s)
      <span ng-if="qqq.countdown <= 60"> {{qqq.countdown}} second(s).
      <uib-progressbar max="qqq.max" value="qqq.countdown" animate="false" class="progress-striped active"></uib-progressbar>


text:
package org.motechproject.nms.masterdata.service;

import org.motechproject.nms.masterdata.domain.LanguageLocationCode;

/**
 * This interface is used for crud operations on LanguageLocationCode
 */

public interface LanguageLocationCodeService {

    /**
     * creates LanguageLocationCode in database
     *
     * @param record of LanguageLocationCode
     */
    LanguageLocationCode create(LanguageLocationCode record);

    /**
     * updates LanguageLocationCode in database
     *
     * @param record of LanguageLocationCode
     */
    LanguageLocationCode update(LanguageLocationCode record);

    /**
     * deletes LanguageLocationCode from database
     *
     * @param record of LanguageLocationCode
     */
    void delete(LanguageLocationCode record);

    /**
     * This method returns the language location code record for a location
     *
     * @param stateCode    code of the state
     * @param districtCode code of the district
     * @return returns null if record not found, else return the languagelocationCode object.
     */
    LanguageLocationCode getRecordByLocationCode(Long stateCode, Long districtCode);

    /**
     * This method returns the language location code record for a given circle and LanguageLocationCode
     *
     * @param circleCode  code of the circle
     * @param langLocCode languageLocationCode
     * @return returns null if record not found, else return the languagelocationCode object.
     */
    LanguageLocationCode getRecordByCircleCodeAndLangLocCode(String circleCode, Integer langLocCode);

    /**
     * This method returns the value of  language location code for a location (state, district)
     *
     * @param stateCode    code of the state
     * @param districtCode code of the district
     * @return null if a  LanguageLocationCode is not determined for location or no entry for location,
     * else returns the determined languageLocationCode value
     */
    Integer getLanguageLocationCodeByLocationCode(Long stateCode, Long districtCode);

    /**
     * This method returns the value of language location code for a circle
     *
     * @param circleCode code of the circle for which language location code is to determined
     * @return null if a unique LanguageLocationCode is not determined for Circle or no entry for circle,
     * else returns the determined languageLocationCode value
     */
    Integer getLanguageLocationCodeByCircleCode(String circleCode);

    /**
     * This method returns the value of default language location code for a circle
     *
     * @param circleCode code of the circle for which default language location code is to determined
     * @return null if unique Default LanguageLocationCode is not found or no entry found for circle,
     * else returns the determined value of default Language Location Code.
     */
    Integer getDefaultLanguageLocationCodeByCircleCode(String circleCode);
}


text:
#include "cache.h"
#include "object.h"
#include "blob.h"
#include "tree.h"
#include "commit.h"
#include "tag.h"

static struct object **obj_hash;
static int nr_objs, obj_hash_size;

unsigned int get_max_object_index(void)
{
	return obj_hash_size;
}

struct object *get_indexed_object(unsigned int idx)
{
	return obj_hash[idx];
}

static const char *object_type_strings[] = {
	NULL,		/* OBJ_NONE = 0 */
	"commit",	/* OBJ_COMMIT = 1 */
	"tree",		/* OBJ_TREE = 2 */
	"blob",		/* OBJ_BLOB = 3 */
	"tag",		/* OBJ_TAG = 4 */
};

const char *typename(unsigned int type)
{
	if (type >= ARRAY_SIZE(object_type_strings))
		return NULL;
	return object_type_strings[type];
}

int type_from_string(const char *str)
{
	int i;

	for (i = 1; i < ARRAY_SIZE(object_type_strings); i++)
		if (!strcmp(str, object_type_strings[i]))
			return i;
	die("invalid object type \"%s\"", str);
}

static unsigned int hash_obj(struct object *obj, unsigned int n)
{
	unsigned int hash;
	memcpy(&hash, obj->sha1, sizeof(unsigned int));
	return hash % n;
}

static void insert_obj_hash(struct object *obj, struct object **hash, unsigned int size)
{
	unsigned int j = hash_obj(obj, size);

	while (hash[j]) {
		j++;
		if (j >= size)
			j = 0;
	}
	hash[j] = obj;
}

static unsigned int hashtable_index(const unsigned char *sha1)
{
	unsigned int i;
	memcpy(&i, sha1, sizeof(unsigned int));
	return i % obj_hash_size;
}

struct object *lookup_object(const unsigned char *sha1)
{
	unsigned int i;
	struct object *obj;

	if (!obj_hash)
		return NULL;

	i = hashtable_index(sha1);
	while ((obj = obj_hash[i]) != NULL) {
		if (!hashcmp(sha1, obj->sha1))
			break;
		i++;
		if (i == obj_hash_size)
			i = 0;
	}
	return obj;
}

static void grow_object_hash(void)
{
	int i;
	int new_hash_size = obj_hash_size < 32 ? 32 : 2 * obj_hash_size;
	struct object **new_hash;

	new_hash = xcalloc(new_hash_size, sizeof(struct object *));
	for (i = 0; i < obj_hash_size; i++) {
		struct object *obj = obj_hash[i];
		if (!obj)
			continue;
		insert_obj_hash(obj, new_hash, new_hash_size);
	}
	free(obj_hash);
	obj_hash = new_hash;
	obj_hash_size = new_hash_size;
}

void *create_object(const unsigned char *sha1, int type, void *o)
{
	struct object *obj = o;

	obj->parsed = 0;
	obj->used = 0;
	obj->type = type;
	obj->flags = 0;
	hashcpy(obj->sha1, sha1);

	if (obj_hash_size - 1 <= nr_objs * 2)
		grow_object_hash();

	insert_obj_hash(obj, obj_hash, obj_hash_size);
	nr_objs++;
	return obj;
}

struct object *lookup_unknown_object(const unsigned char *sha1)
{
	struct object *obj = lookup_object(sha1);
	if (!obj)
		obj = create_object(sha1, OBJ_NONE, alloc_object_node());
	return obj;
}

struct object *parse_object_buffer(const unsigned char *sha1, enum object_type type, unsigned long size, void *buffer, int *eaten_p)
{
	struct object *obj;
	int eaten = 0;

	obj = NULL;
	if (type == OBJ_BLOB) {
		struct blob *blob = lookup_blob(sha1);
		if (blob) {
			if (parse_blob_buffer(blob, buffer, size))
				return NULL;
			obj = &blob->object;
		}
	} else if (type == OBJ_TREE) {
		struct tree *tree = lookup_tree(sha1);
		if (tree) {
			obj = &tree->object;
			if (!tree->object.parsed) {
				if (parse_tree_buffer(tree, buffer, size))
					return NULL;
				eaten = 1;
			}
		}
	} else if (type == OBJ_COMMIT) {
		struct commit *commit = lookup_commit(sha1);
		if (commit) {
			if (parse_commit_buffer(commit, buffer, size))
				return NULL;
			if (!commit->buffer) {
				commit->buffer = buffer;
				eaten = 1;
			}
			obj = &commit->object;
		}
	} else if (type == OBJ_TAG) {
		struct tag *tag = lookup_tag(sha1);
		if (tag) {
			if (parse_tag_buffer(tag, buffer, size))
			       return NULL;
			obj = &tag->object;
		}
	} else {
		warning("object %s has unknown type id %d\n", sha1_to_hex(sha1), type);
		obj = NULL;
	}
	if (obj && obj->type == OBJ_NONE)
		obj->type = type;
	*eaten_p = eaten;
	return obj;
}

struct object *parse_object(const unsigned char *sha1)
{
	unsigned long size;
	enum object_type type;
	int eaten;
	const unsigned char *repl = lookup_replace_object(sha1);
	void *buffer = read_sha1_file(sha1, &type, &size);

	if (buffer) {
		struct object *obj;
		if (check_sha1_signature(repl, buffer, size, typename(type)) < 0) {
			free(buffer);
			error("sha1 mismatch %s\n", sha1_to_hex(repl));
			return NULL;
		}

		obj = parse_object_buffer(sha1, type, size, buffer, &eaten);
		if (!eaten)
			free(buffer);
		return obj;
	}
	return NULL;
}

struct object_list *object_list_insert(struct object *item,
				       struct object_list **list_p)
{
	struct object_list *new_list = xmalloc(sizeof(struct object_list));
	new_list->item = item;
	new_list->next = *list_p;
	*list_p = new_list;
	return new_list;
}

int object_list_contains(struct object_list *list, struct object *obj)
{
	while (list) {
		if (list->item == obj)
			return 1;
		list = list->next;
	}
	return 0;
}

void add_object_array(struct object *obj, const char *name, struct object_array *array)
{
	add_object_array_with_mode(obj, name, array, S_IFINVALID);
}

void add_object_array_with_mode(struct object *obj, const char *name, struct object_array *array, unsigned mode)
{
	unsigned nr = array->nr;
	unsigned alloc = array->alloc;
	struct object_array_entry *objects = array->objects;

	if (nr >= alloc) {
		alloc = (alloc + 32) * 2;
		objects = xrealloc(objects, alloc * sizeof(*objects));
		array->alloc = alloc;
		array->objects = objects;
	}
	objects[nr].item = obj;
	objects[nr].name = name;
	objects[nr].mode = mode;
	array->nr = ++nr;
}

void object_array_remove_duplicates(struct object_array *array)
{
	unsigned int ref, src, dst;
	struct object_array_entry *objects = array->objects;

	for (ref = 0; ref + 1 < array->nr; ref++) {
		for (src = ref + 1, dst = src;
		     src < array->nr;
		     src++) {
			if (!strcmp(objects[ref].name, objects[src].name))
				continue;
			if (src != dst)
				objects[dst] = objects[src];
			dst++;
		}
		array->nr = dst;
	}
}


text:
package org.encog.util.datastruct;

import org.encog.EncogError;

public class StackObject<T> {

    private Object[] stack;
    private int head = 0;

    public StackObject(int size) {
        this.stack = new Object[size];
    }

    public boolean isEmpty() {
        return this.head == 0;
    }

    public void push(T str) {
        if (this.head == this.stack.length) {
            throw new EncogError("Stack overflow");
        }
        this.stack[this.head++] = str;
    }

    @SuppressWarnings("unchecked")
    public T pop() {
        if (this.head == 0) {
            throw new EncogError("Stack is empty");
        }
        return (T) this.stack[--this.head];
    }

    @SuppressWarnings("unchecked")
    public T peek() {
        if (this.head == 0) {
            throw new EncogError("Stack is empty");
        }
        return (T) this.stack[this.head - 1];
    }

    public int size() {
        return this.head;
    }

    public String toString() {
        StringBuilder result = new StringBuilder();
        result.append("[StackString: ");
        for (int i = head - 1; i >= 0; i--) {
            result.append(this.stack[i]);
            result.append(" ");
        }
        result.append("]");
        return result.toString();
    }
}


text:
using namespace std;
using namespace crypto::cipher;

int main(int argc, char const *argv[])
{
	string s;

	while (!cin.eof())
	{
		getline(cin, s);
		rot5(s);
		cout << s << endl;
	}

	return 0;
}


text:
<?php namespace models\admin;

class Admin extends \core\Model {
    public function __construct() {
        parent::__construct();
    }
    public function getUser($id) {
        $data = $this->_db->select('SELECT * FROM '.PREFIX.'members WHERE id = :id',
                array(':id' => $id));
        return $data[0];
    }
}


text:
<?php

// InvalidArgumentException.php

namespace Zapoyok\Tika\Exception;

class InvalidFileException extends  \Exception
{
}


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>Redirecting...</title>
<link rel=canonical href="../預/index.html">
<meta http-equiv=refresh content="0; url='../預/index.html'">

Redirecting...

Click here if you are not redirected.


text:
<?php

namespace CotaPreco\Postmon;

use PHPUnit_Framework_TestCase as TestCase;

/**
 * @author Andrey K. Vital <andreykvital@gmail.com>
 */
class CepTest extends TestCase
{
    /**
     * @test
     * @dataProvider provideInvalidCeps
     * @param string $cep
     */
    public function fromStringThrowsInvalidArgument($cep)
    {
        $this->setExpectedException(\InvalidArgumentException::class);

        Cep::fromString($cep);
    }

    /**
     * @test
     */
    public function fromString()
    {
        $cep = Cep::fromString('12312300');

        $this->assertInstanceOf(Cep::class, $cep);
        $this->assertEquals('12312300', (string) $cep);
    }

    /**
     * @return \string[][]
     */
    public function provideInvalidCeps()
    {
        return [
            ['1234567.8'],
            ['#123455678'],
            ['12345'],
            [''],
            [null]
        ];
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<parameters>

	<MQSenderThreadNum>1</MQSenderThreadNum>

	<MQSenderSosList>
		<ServiceId>40001</ServiceId>
		<ServiceTopic>mqtest:40001</ServiceTopic>
		<ServerAddr>127.0.0.1:2181</ServerAddr>
	</MQSenderSosList >

</parameters>


text:
keyName=$1
orchestratorbaseurl=$2
cckeyName=$3
componentBaseUrl=$4
nodename=$5
hostname=$6
vmUserName=$7
complianceadminusername=$8
env=$9
component=$10

URL="http://$orchestratorbaseurl:33001/key/$keyName"
echo $URL

#this API retrieves the validator.pem given a keyname, decodes it and stores it in validator.pem file
sudo curl -H "Content-Type: application/json" -X GET $URL | tr -d "\"" | base64 --decode > /etc/chef/validation.pem

URL2="http://$orchestratorbaseurl:33001/keys/$component/$complianceadminusername/envs/$env/nodes"
echo $URL2

sudo curl -H "Content-Type: application/json" -X POST -d '{"keyName":"'"$cckeyName"'", "componentBaseUrl":"'"$componentBaseUrl"'", "nodename":"'"$nodename"'", "hostname":"'"$hostname"'","vmUserName":"'"$vmUserName"'" }' $URL2 | tr -d "\""  > /home/$7/.ssh/id_rsa.pub

sudo cp /home/$7/.ssh/id_rsa.pub /home/$7/.ssh/authorized_keys

#Next step is run sudo chef-client so that it boot straps to server
sudo chef-client


text:
import sys
import os
import json
import re

from json_utils import clean_json

class FilterException(Exception):
    pass

class FilterAttributeError(FilterException):
    """
    Filter is missing one or more parameters
    """
    pass

class FilterParsingError(FilterException):
    """
    Filter file could not be parsed
    """
    pass

class _Filter(object):
    """
    Base filter class
    """
    def __init__(self, filter_text, case_sensitive):
        self.filter_text = filter_text
        self.case_sensitive = case_sensitive

    def matches(self, text):
        """
        Required function to check if the text given matches the filter's properties

        :param text: the text to check against the filter
        :type text: str
        :rtype: bool
        """
        raise NotImplementedError

class _FilterContains(_Filter):
    def matches(self, text):
        if self.case_sensitive:
            return self.filter_text in text
        return self.filter_text.lower() in text.lower()

class _FilterEndsWith(_Filter):
    def matches(self, text):
        if self.case_sensitive:
            return text.endswith(self.filter_text)
        return text.lower().endswith(self.filter_text.lower())

class _FilterStartsWith(_Filter):
    def matches(self, text):
        if self.case_sensitive:
            return text.startswith(self.filter_text)
        return text.lower().startswith(self.filter_text.lower())

class _FilterExact(_Filter):
    def matches(self, text):
        if self.case_sensitive:
            return text == self.filter_text
        return text.lower() == self.filter_text.lower()

class _FilterRegex(_Filter):
    def __init__(self, filter_text, case_sensitive):
        super(_FilterRegex, self).__init__(filter_text, case_sensitive)
        flags = None
        if not case_sensitive:
            flags = re.IGNORECASE
        self.pattern = re.compile(filter_text, flags=flags)

    def matches(self, text):
        return self.pattern.search(text) is not None

filters = {
    "contains": _FilterContains,
    "endswith": _FilterEndsWith,
    "startswith": _FilterStartsWith,
    "exact": _FilterExact,
    "regex":    _FilterRegex,
}

class FilterFile(object):
    # filter file parameters
    KEY_NAME = "name"
    KEY_FILTERS = "filters"
    KEY_EXCLUDE = "exclude"
    # filter parameters
    KEY_METHOD = "method"
    KEY_TEXT = "text"
    KEY_CASE_SENS = "case_sensitive"
    REQUIRED_FILTER_PARAMS = [KEY_TEXT, KEY_METHOD]
    REQUIRED_FILTER_FILE_PARAMS = [KEY_NAME, KEY_FILTERS]

    def __init__(self, name, filter_list, exclude=False):
        self.name = name
        self.filter_list = filter_list
        self.exclude = exclude

    @staticmethod
    def parse_filter_file(file_text, skip_invalid_filters=False):
        """
        Parses JSON text into a filter file object

        :param file_text: the text of the filter file
        :type file_text: str
        :param skip_invalid_filters: behavior to take when an invalid filter is discovered.
                                     If set to True, that specific filter will just be ignored and parsing will continue.
                                     If set to False, a FilterAttributeError will be thrown
        :type skip_invalid_filters: bool

        :return: the corresponding FilterFile object
        :rtype: FilterFile
        """
        try:
            file = json.loads(clean_json(file_text))
        except Exception as ex:
            raise FilterParsingError(ex.args[0])

        if not all(params in file for params in FilterFile.REQUIRED_FILTER_FILE_PARAMS):
            return None

        name = file[FilterFile.KEY_NAME]

        exclude = file.get(FilterFile.KEY_EXCLUDE, False)
        if not isinstance(exclude, bool):
            print("Bad exclude value {}. Defaulting to false".format(exclude))
            exclude = False

        filter_list = []
        i = -1
        for f in file[FilterFile.KEY_FILTERS]:
            i += 1
            # Check that the required parameters are in the dictionary
            if not all(params in f for params in FilterFile.REQUIRED_FILTER_PARAMS):
                msg = "Missing required params for filter {}: {}".format(i, FilterFile.REQUIRED_FILTER_PARAMS)
                if not skip_invalid_filters:
                    raise FilterAttributeError(msg)
                print(msg)

            method = f[FilterFile.KEY_METHOD]
            if method not in filters:
                msg = "Unknown filter method in filter {}: {}.  Possible methods: {}".format(i, method, filters.keys())
                if not skip_invalid_filters:
                    raise FilterAttributeError(msg)
                print(msg)

            filter_type = filters[method]

            case_sensitive = f.get(FilterFile.KEY_CASE_SENS, False)
            text = str(f[FilterFile.KEY_TEXT])

            if not isinstance(case_sensitive, bool):
                print("Bad case_sensitive value {}. Defaulting to false".format(case_sensitive))
                case_sensitive = False

            filter_list.append(filter_type(text, case_sensitive))
        return FilterFile(name, filter_list, exclude)

    def check_filters(self, text):
        """
        Checks the given text against all filters in the file

        :param text: the text to check
        :type text: str

        :return: True if the text satisfies one of the filters
        :rtype: bool
        """
        for f in self.filter_list:
            # Check the filter files.  If a match is found, return the correct value based on the exclude flag
            if f.matches(text):
                return not self.exclude

        # No match found, which means that if the exclude flag is set, then include the text, and opposite if exclude is not set
        return self.exclude


text:
/*****************************************************************************************
 *                                                                                *
 * ADXL345 Driver for Spark Core                                                         *
 * Original code from: https://github.com/jenschr/Arduino-libraries/tree/master/ADXL345  *
 *                                                                                *
 * This program is free software; you can redistribute it and/or modify                  *
 * it under the terms of the GNU License.                                                *
 * This program is distributed in the hope that it will be useful,                       *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of                        *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                         *
 * GNU License V2 for more details.                                                      *
 *                                                                                *
 * Bare bones ADXL345 i2c example for Arduino 1.0                                        *
 * by Jens C Brynildsen <http://www.flashgamer.com>                                      *
 * This version is not reliant of any external lib                                       *
 * (Adapted for Arduino 1.0 from http://code.google.com/p/adxl345driver)                 *
 *                                                                                *
 * Demonstrates use of ADXL345 (using the Sparkfun ADXL345 breakout)                     *
 * with i2c communication. Datasheet:                                                    *
 * http://www.sparkfun.com/datasheets/Sensors/Accelerometer/ADXL345.pdf                  *
 * If you need more advanced features such as freefall and tap                           *
 * detection, check out:                                                                 *
 * https://github.com/jenschr/Arduino-libraries                                          *
 *                                                                                *
 * Updated on: 25 April 2014                                                             *
 ****************************************************************************************/

// Cabling for i2c using Sparkfun breakout with a Spar Core
// Spark Core <-> Breakout board
// Gnd         -  GND
// 3.3v        -  VCC
// 3.3v        -  CS
// Digital 0   -  SDA
// Digital 1   -  SCL

#define DEVICE (0x53) // Device address as specified in data sheet

byte _buff[6];

char POWER_CTL = 0x2D;	//Power Control Register
char DATA_FORMAT = 0x31;
char DATAX0 = 0x32;	//X-Axis Data 0
char DATAX1 = 0x33;	//X-Axis Data 1
char DATAY0 = 0x34;	//Y-Axis Data 0
char DATAY1 = 0x35;	//Y-Axis Data 1
char DATAZ0 = 0x36;	//Z-Axis Data 0
char DATAZ1 = 0x37;	//Z-Axis Data 1

void setup()
{
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(57000);  // start serial for output. Make sure you set your Serial Monitor to the same!
  Serial.print("init");

  //Put the ADXL345 into +/- 4G range by writing the value 0x01 to the DATA_FORMAT register.
  writeTo(DATA_FORMAT, 0x01);
  //Put the ADXL345 into Measurement Mode by writing 0x08 to the POWER_CTL register.
  writeTo(POWER_CTL, 0x08);
}

void loop()
{
  readAccel(); // read the x/y/z tilt
  delay(500); // only read every 0,5 seconds
}

void readAccel() {
  uint8_t howManyBytesToRead = 6;
  readFrom( DATAX0, howManyBytesToRead, _buff); //read the acceleration data from the ADXL345

  // each axis reading comes in 10 bit resolution, ie 2 bytes.  Least Significat Byte first!!
  // thus we are converting both bytes in to one int
  int x = (((int)_buff[1]) << 8) | _buff[0];
  int y = (((int)_buff[3]) << 8) | _buff[2];
  int z = (((int)_buff[5]) << 8) | _buff[4];
  Serial.print("x: ");
  Serial.print( x );
  Serial.print(" y: ");
  Serial.print( y );
  Serial.print(" z: ");
  Serial.println( z );
}

void writeTo(byte address, byte val) {
  Wire.beginTransmission(DEVICE); // start transmission to device
  Wire.write(address);             // send register address
  Wire.write(val);                 // send value to write
  Wire.endTransmission();         // end transmission
}

// Reads num bytes starting from address register on device in to _buff array
void readFrom(byte address, int num, byte _buff[]) {
  Wire.beginTransmission(DEVICE); // start transmission to device
  Wire.write(address);             // sends address to read from
  Wire.endTransmission();         // end transmission

  Wire.beginTransmission(DEVICE); // start transmission to device
  Wire.requestFrom(DEVICE, num);    // request 6 bytes from device

  int i = 0;
  while(Wire.available())         // device may send less than requested (abnormal)
  {
    _buff[i] = Wire.read();    // receive a byte
    i++;
  }
  Wire.endTransmission();         // end transmission
}


text:
<?php

namespace h4cc\AliceFixturesBundle\Tests;

use h4cc\AliceFixturesBundle\ORM\Doctrine;

/**
 * Class DoctrineTest
 *
 * @author Julius Beckmann <github@h4cc.de>
 * @covers h4cc\AliceFixturesBundle\ORM\Doctrine
 */
class DoctrineTest extends \PHPUnit_Framework_TestCase
{
    /** @var  \PHPUnit_Framework_MockObject_MockObject */
    private $managerMock;

    /** @var  \PHPUnit_Framework_MockObject_MockObject */
    private $managerRegistryMock;

    private $objects = array();
    private $testObject;

    public function setUp()
    {
        $this->managerMock = $this->getMockBuilder('\Doctrine\Common\Persistence\ObjectManager')
            ->setMethods(array('persist', 'find', 'remove', 'merge', 'detach', 'flush'))
            ->getMockForAbstractClass();

        $this->managerRegistryMock = $this->getMockBuilder('\Doctrine\Common\Persistence\ManagerRegistry')
            ->setMethods(array('getManagerForClass'))
            ->getMockForAbstractClass();

        $this->managerRegistryMock->expects($this->any())
            ->method('getManagerForClass')
            ->will($this->returnValue($this->managerMock));

        $this->objects = range('a', 'c');
        $this->objects[] = $this->testObject = new \stdClass();
    }

    public function testConstruct()
    {
        $doctrine = new Doctrine($this->managerRegistryMock, true);

        $this->assertInstanceOf('\h4cc\AliceFixturesBundle\ORM\ORMInterface', $doctrine);
    }

    public function testPersist()
    {
        $this->managerMock->expects($this->exactly(count($this->objects)))->method('persist');
        $this->managerMock->expects($this->once())->method('flush');

        $doctrine = new Doctrine($this->managerRegistryMock, true);

        $doctrine->persist($this->objects);
    }

    public function testPersistWithoutFlush()
    {
        $this->managerMock->expects($this->exactly(count($this->objects)))->method('persist');
        $this->managerMock->expects($this->never())->method('flush');

        $doctrine = new Doctrine($this->managerRegistryMock, false);

        $doctrine->persist($this->objects);
    }

    public function testMerge()
    {
        $this->managerMock->expects($this->exactly(count($this->objects)))->method('merge')
            ->will($this->returnValueMap(array(
                array('a', 'a_merged'),
                array('b', 'b_merged'),
                array('c', 'c_merged'),
                array($this->testObject, 'testObject_merged'),
            )));
        $this->managerMock->expects($this->never())->method('flush');

        $doctrine = new Doctrine($this->managerRegistryMock, true);

        $mergedObjects = $doctrine->merge($this->objects);

        $this->assertEquals(array('a_merged', 'b_merged', 'c_merged', 'testObject_merged'), $mergedObjects);
    }

    public function testDetach()
    {
        $this->managerMock->expects($this->exactly(count($this->objects)))->method('detach');
        $this->managerMock->expects($this->never())->method('flush');

        $doctrine = new Doctrine($this->managerRegistryMock, true);

        $doctrine->detach($this->objects);
    }

    public function testRemove()
    {
        $this->managerMock->expects($this->exactly(count($this->objects)))->method('merge');
        $this->managerMock->expects($this->exactly(count($this->objects)))->method('remove');
        $this->managerMock->expects($this->once())->method('flush');

        $doctrine = new Doctrine($this->managerRegistryMock, true);

        $doctrine->remove($this->objects);
    }

    public function testRemoveWithoutFlush()
    {
        $this->managerMock->expects($this->exactly(count($this->objects)))->method('merge');
        $this->managerMock->expects($this->exactly(count($this->objects)))->method('remove');
        $this->managerMock->expects($this->never())->method('flush');

        $doctrine = new Doctrine($this->managerRegistryMock, false);

        $doctrine->remove($this->objects);
    }

    public function testFind()
    {
        $this->managerMock->expects($this->exactly(count($this->objects)))->method('find')
            ->will($this->returnValueMap(array(
                array('Some/Class', 0, 'a'),
                array('Some/Class', 1, 'b'),
                array('Some/Class', 2, 'c'),
                array('Some/Class', 3, $this->testObject),
            )));
        $this->managerMock->expects($this->never())->method('flush');

        $doctrine = new Doctrine($this->managerRegistryMock, true);

        foreach($this->objects as $index => $expectedEntity) {
            $entity = $doctrine->find('Some/Class', $index);
            $this->assertEquals($expectedEntity, $entity);
        }
    }

    /**
     * @expectedException \UnexpectedValueException
     * @expectedExceptionMessage Entity with Id 42 and Class Some/Class not found
     */
    public function testFindNotFoundException()
    {
        $this->managerMock->expects($this->once())->method('find')
            ->will($this->returnValueMap(array(
                array('Some/Class', 42, null),
            )));
        $this->managerMock->expects($this->never())->method('flush');

        $doctrine = new Doctrine($this->managerRegistryMock, true);

        $doctrine->find('Some/Class', 42);
    }

    /**
     * @expectedException \RuntimeException
     * @expectedExceptionMessage No ObjectManager for class Some/Class
     */
    public function testNoObjectManager()
    {
        $this->managerRegistryMock = $this->getMockBuilder('\Doctrine\Common\Persistence\ManagerRegistry')
            ->setMethods(array('getManagerForClass'))
            ->getMockForAbstractClass();
        $this->managerRegistryMock->expects($this->once())->method('getManagerForClass')->with('Some/Class')->willReturn(null);

        $doctrine = new Doctrine($this->managerRegistryMock, true);

        $doctrine->find('Some/Class', 42);
    }
}


text:
package ua.parus.pmo.parus8claims.objects.dicts;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

import ua.parus.pmo.parus8claims.db.DatabaseWrapper;

public class ReleaseHelper {

    public static final String TABLE_NAME = "releases";
    public static final String SQL_DROP_TABLE =
            "DROP TABLE IF EXISTS " + TABLE_NAME;
    public static final String COLUMN_RN = "rn";
    public static final String COLUMN_NAME = "name";
    private static final String COLUMN_VERSION = "version";
    private static final String COLUMN_BUILDS_CACHED = "builds_cached";
    @SuppressWarnings("unused")
    private static final String TAG = ReleaseHelper.class.getSimpleName();
    private static final String COMMA_SEP = ", ";
    public static final String SQL_INSERT =
            "INSERT INTO " + TABLE_NAME + "("
                    + COLUMN_RN + COMMA_SEP
                    + COLUMN_VERSION + COMMA_SEP
                    + COLUMN_NAME + COMMA_SEP
                    + COLUMN_BUILDS_CACHED
                    + ") VALUES (?,?,?,0)";
    private static final String TYPE_RN = "INTEGER PRIMARY KEY ";
    private static final String TYPE_VERSION = "TEXT";
    private static final String TYPE_RELEASE = "TEXT";
    private static final String TYPE_BUILDS_CACHED = "INTEGER";
    public static final String SQL_CREATE_TABLE =
            "CREATE TABLE " + TABLE_NAME + " (" +
                    COLUMN_RN + " " + TYPE_RN + COMMA_SEP +
                    COLUMN_VERSION + " " + TYPE_VERSION + COMMA_SEP +
                    COLUMN_NAME + " " + TYPE_RELEASE + COMMA_SEP +
                    COLUMN_BUILDS_CACHED + " " + TYPE_BUILDS_CACHED +
                    ")";

    public static List<String> getVersions(Context context, boolean mandatory, String nullText) {
        List<String> versions = new ArrayList<>();
        if (!mandatory) versions.add(nullText);
        DatabaseWrapper databaseWrapper = new DatabaseWrapper(context);
        SQLiteDatabase db = databaseWrapper.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT DISTINCT " + COLUMN_VERSION + " FROM " + TABLE_NAME + " ORDER BY " + COLUMN_VERSION + " DESC", null);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            versions.add(cursor.getString(cursor.getColumnIndex(COLUMN_VERSION)));
            cursor.moveToNext();
        }
        cursor.close();
        db.close();
        return versions;
    }

    private static List<Release> getReleases(Context context, String version, boolean mandatory, String nulltext) {
        List<Release> releases = new ArrayList<>();
        Release release;
        if (!mandatory) {
            release = new Release();
            release.name = nulltext;
            release.version = version;
            releases.add(release);
        }
        DatabaseWrapper databaseWrapper = new DatabaseWrapper(context);
        SQLiteDatabase db = databaseWrapper.getReadableDatabase();
        String[] columns = {
                COLUMN_RN,              //0
                COLUMN_VERSION,         //1
                COLUMN_NAME,            //2
                COLUMN_BUILDS_CACHED    //3
        };
        String selectClause = "";
        for (String lColumn : columns) {
            selectClause = selectClause + lColumn + COMMA_SEP;
        }
        selectClause = "SELECT " + selectClause.substring(0, selectClause.length() - COMMA_SEP.length());
        String lFromClause = " FROM " + TABLE_NAME;
        String lWhereClause;
        String[] queryParams;
        if (version != null) {
            lWhereClause = " WHERE " + COLUMN_VERSION + "= ?";
            queryParams = new String[]{version};
        } else {
            lWhereClause = "";
            queryParams = new String[]{};
        }
        String lOrderClause = " ORDER BY " + COLUMN_NAME + " DESC";
        String SQL = selectClause + lFromClause + lWhereClause + lOrderClause;
        Cursor cursor = db.rawQuery(SQL, queryParams);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            release = new Release();
            release.rn = cursor.getLong(0);
            release.version = cursor.getString(1);
            release.name = cursor.getString(2);
            release.buildsCached = cursor.getInt(3);
            releases.add(release);
            cursor.moveToNext();
        }
        cursor.close();
        db.close();
        return releases;
    }

    public static void setReleaseCached(Context context, long releaseRn) {
        DatabaseWrapper databaseWrapper = new DatabaseWrapper(context);
        SQLiteDatabase db = databaseWrapper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_BUILDS_CACHED, 1);
        db.update(TABLE_NAME, values, COLUMN_RN + " = ?", new String[]{String.valueOf(releaseRn)});
        db.close();
    }

    private static String getOneRowSql(String pByColumn) {
        String[] columns = {
                COLUMN_RN,              //0
                COLUMN_VERSION,         //1
                COLUMN_NAME,            //2
                COLUMN_BUILDS_CACHED    //3
        };
        String SQL = "";
        for (String column : columns) {
            SQL = SQL + column + COMMA_SEP;
        }
        SQL = SQL.substring(0, SQL.length() - COMMA_SEP.length());
        SQL = "SELECT " + SQL + " FROM " + TABLE_NAME + " WHERE " + pByColumn + "= ?";
        return SQL;
    }

    private static Release cursorToObject(Cursor cursor) {
        Release release = new Release();
        release.rn = cursor.getLong(0);
        release.version = cursor.getString(1);
        release.name = cursor.getString(2);
        release.buildsCached = cursor.getInt(3);
        return release;
    }

    public static Release getRelease(Context context, String releaseCode) {
        Release release = new Release();
        DatabaseWrapper databaseWrapper = new DatabaseWrapper(context);
        SQLiteDatabase db = databaseWrapper.getReadableDatabase();
        String SQL = getOneRowSql(COLUMN_NAME);
        Cursor cursor = db.rawQuery(SQL, new String[]{releaseCode});
        cursor.moveToFirst();
        if (cursor.getCount() > 0) {
            release = cursorToObject(cursor);
        }
        cursor.close();
        db.close();
        return release;
    }

    public static Release getRelease(Context context, long releaseRn) {
        Release release = new Release();
        DatabaseWrapper databaseWrapper = new DatabaseWrapper(context);
        SQLiteDatabase db = databaseWrapper.getReadableDatabase();
        String SQL = getOneRowSql(COLUMN_RN);
        Cursor cursor = db.rawQuery(SQL, new String[]{String.valueOf(releaseRn)});
        cursor.moveToFirst();
        if (cursor.getCount() > 0) {
            release = cursorToObject(cursor);
        }
        cursor.close();
        db.close();
        return release;
    }

    public static List<String> getReleasesNames(Context context, String version, boolean mandatory, String nulltext) {
        List<String> releasesNames = new ArrayList<>();
        List<Release> releases = getReleases(context, version, mandatory, nulltext);
        for (Release release : releases) releasesNames.add(release.name);
        return releasesNames;
    }

}


text:
/**
 * Loads an array of urls using the loadFunction given by the user.
 * Returns a promise.all of all the urls.
 */
function loadUrls(urls, loadFunction) {
  let promises = [];
  for (url of urls) {
    let promise = loadFunction(url);
    promises.push(promise);
  }
  return Promise.all(promises);
}

/**
 * Loads the template from the url.
 * Returns a promise of the template.
 */
function loadTemplate(url) {
  const templatePromise = fetch(url).then(promiseResponse => promiseResponse.text()).catch(error => console.log(error));
  return templatePromise;
}

/**
 * Loads the object from the url.
 * Returns a promise of the object.
 */
function loadObject(url) {
  const objPromise = fetch(url).then(promiseResponse => promiseResponse.json()).catch(error => console.log(error));
  return objPromise;
}


text:
#include "furn2.h"
#include <string>
#include <sstream>

using namespace std;
using namespace furn2;

unsigned int g_mod_index;
bool         g_enabled;

/************************************************************************/
/* Furnarchy2 entry points.                                             */
/* Feel free to leave out the ones you don't need.                      */
/* They're just all defined here for completness.                       */
/************************************************************************/

F2EXPORT intptr_t F2CALL on_module( Module_Event e, void* param )
{
   /* See definition of Module_Event for all module events. */
   switch (e)
   {
   case MOD_EVENT_START:
      g_mod_index = ((const MODULEINFO*) param)->mod;
      break;

   case MOD_EVENT_STOP:
      // module is unloading.
      break;

   case MOD_EVENT_TOUCH:
      f2_speak( "Dummy module 1.00.0 - Sits here and takes up space." );
      break;

   case MOD_EVENT_ENABLE:
      g_enabled = true;
      break;

   case MOD_EVENT_DISABLE:
      g_enabled = false;
      break;
   }

   return 0;
}

F2EXPORT intptr_t F2CALL on_client( Client_Event e, void* param )
{
   /* See definition of Client_Event for all client events. */
   return 0;
}

F2EXPORT bool F2CALL on_wndproc( WNDPROCPARAMS* params )
{
   /* All the regular WM messages come through here. */
   /* Return 'true' to tell furnarchy you handled it. */

   return false;
}

F2EXPORT intptr_t F2CALL on_world( World_Event e, void* param )
{
   /* See definition of World_Event for all world events. */
   return 0;
}

F2EXPORT bool F2CALL on_command( int argc, char* argv[] )
{
   /* @... commands come through here.  Return true if you handled it. */
   return false;
}

F2EXPORT void F2CALL on_inet( Revision rev, const char* line, int from, size_t num )
{
   /* Inbound network lines come through here.
   *  'line' is always null-terminated.
   *  'from' is FROM_SERVER if the line was originally from the server
   *     (not generated).
   *  'num' is the line number.
   *  Use f2_reviseline() to edit the line when rev == REV_REVISING. */
}

F2EXPORT void F2CALL on_onet( Revision rev, const char* line, int from, size_t num )
{
   /* Outbound network lines come through here.
   *  'line' is always null-terminated.
   *  'from' is FROM_CLIENT if the line was originally from the client
   *     (not generated).
   *  'num' is the line number.
   *  Use f2_reviseline() to edit the line when rev == REV_REVISING. */
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
        Copyright 2009 OW2 Chameleon Licensed under the Apache License,
        Version 2.0 (the "License"); you may not use this file except in
        compliance with the License. You may obtain a copy of the License at
        http://www.apache.org/licenses/LICENSE-2.0 Unless required by
        applicable law or agreed to in writing, software distributed under the
        License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
        CONDITIONS OF ANY KIND, either express or implied. See the License for
        the specific language governing permissions and limitations under the
        License.
-->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.ow2.chameleon.fuchsia</groupId>
        <artifactId>fuchsia-parent</artifactId>
        <version>0.0.5-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <groupId>org.ow2.chameleon.fuchsia.examples</groupId>
    <artifactId>fuchsia-examples</artifactId>

    <name>OW2 Chameleon - Fuchsia Examples</name>
    <packaging>pom</packaging>

    <modules>
        <module>fool-components</module>
        <module>upnp-components</module>
        <module>upnp-config</module>
        <module>push-config</module>
        <module>mdns-config</module>
        <module>mqtt-config</module>
        <module>cxf-base</module>
        <module>cxf-client</module>
        <module>jsonrpc-exporter-config</module>
        <module>philips-hue-config</module>
        <module>cxf-exporter-config</module>
        <module>cxf-importer-config</module>
        <module>fake-importer-config</module>
        <module>proto-class</module>
        <module>proto-client</module>
        <module>proto-config</module>
        <module>filebased-config</module>
        <!--
                <module>jax-ws</module>
        -->
    </modules>
</project>


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title> ModularAdmin - Free Dashboard Theme | HTML Version </title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="apple-touch-icon" href="apple-touch-icon.png">

        <link rel="stylesheet" href="css/vendor.css">

 ModularAdmin

PASSWORD RECOVER

                            Enter your email address to recover your password.

                        <form id="reset-form" action="/index.html" method="GET" novalidate="">

                                Email
                                <input type="email" class="form-control underlined" name="email1" id="email1" placeholder="Your email address" required>

                                <button type="submit" class="btn btn-block btn-primary">Reset</button>

                                return to Login
                                Sign Up!

                        </form>

                         Back to dashboard


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Hedwigia 36: 162 (1897)

#### Original name
Ascochyta doronici Allesch., 1897

### Remarks
null


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

The following is a test for DOM manipulation within <ruby>: Removing the last <rt>, leaving the base without ruby text.

<ruby> is defined in the <ruby id="R">HTML<rt>Hyper-text Markup Language</rt>5<rt id="RT" style="color:red">SHOULDN'T SHOW!</rt></ruby> spec.


text:
#include <aws/medialive/model/Eac3DrcRf.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace MediaLive
  {
    namespace Model
    {
      namespace Eac3DrcRfMapper
      {

        static const int FILM_LIGHT_HASH = HashingUtils::HashString("FILM_LIGHT");
        static const int FILM_STANDARD_HASH = HashingUtils::HashString("FILM_STANDARD");
        static const int MUSIC_LIGHT_HASH = HashingUtils::HashString("MUSIC_LIGHT");
        static const int MUSIC_STANDARD_HASH = HashingUtils::HashString("MUSIC_STANDARD");
        static const int NONE_HASH = HashingUtils::HashString("NONE");
        static const int SPEECH_HASH = HashingUtils::HashString("SPEECH");

        Eac3DrcRf GetEac3DrcRfForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == FILM_LIGHT_HASH)
          {
            return Eac3DrcRf::FILM_LIGHT;
          }
          else if (hashCode == FILM_STANDARD_HASH)
          {
            return Eac3DrcRf::FILM_STANDARD;
          }
          else if (hashCode == MUSIC_LIGHT_HASH)
          {
            return Eac3DrcRf::MUSIC_LIGHT;
          }
          else if (hashCode == MUSIC_STANDARD_HASH)
          {
            return Eac3DrcRf::MUSIC_STANDARD;
          }
          else if (hashCode == NONE_HASH)
          {
            return Eac3DrcRf::NONE;
          }
          else if (hashCode == SPEECH_HASH)
          {
            return Eac3DrcRf::SPEECH;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<Eac3DrcRf>(hashCode);
          }

          return Eac3DrcRf::NOT_SET;
        }

        Aws::String GetNameForEac3DrcRf(Eac3DrcRf enumValue)
        {
          switch(enumValue)
          {
          case Eac3DrcRf::FILM_LIGHT:
            return "FILM_LIGHT";
          case Eac3DrcRf::FILM_STANDARD:
            return "FILM_STANDARD";
          case Eac3DrcRf::MUSIC_LIGHT:
            return "MUSIC_LIGHT";
          case Eac3DrcRf::MUSIC_STANDARD:
            return "MUSIC_STANDARD";
          case Eac3DrcRf::NONE:
            return "NONE";
          case Eac3DrcRf::SPEECH:
            return "SPEECH";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return "";
          }
        }

      } // namespace Eac3DrcRfMapper
    } // namespace Model
  } // namespace MediaLive
} // namespace Aws


text:
describe('General', function () {
  require('./basic.js');
  require('./armor.js');
  require('./key.js');
  require('./keyring.js');
  require('./packet.js');
  require('./signature.js');
});


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Lightfootia calcarea Adamson

### Remarks
null


text:
<?xml version="1.0"?>
<x:doc xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:x="http://xsdtesting" xsi:schemaLocation="http://xsdtesting attO009.xsd">
	<x:elem x:att="X Y Z"/>
</x:doc>


text:
import unittest
from Kamaelia.Util.TestResult import TestResult, StopSystem, StopSystemException
from Axon.Component import component
from Axon.Linkage import linkage
from Axon.Postman import postman
from Axon.util import testInterface
from Axon.Scheduler import scheduler

class TestResult_test1(unittest.TestCase):
    def test_smoketest1(self):
        "__init__ - Object creation no arguments."
        self.failUnless(TestResult())

    def test_smoketest2(self):
        """__init__ - Checks the created component has the correct inboxes and outboxes ("inbox", "control", "outbox")."""
        self.failUnless(testInterface(TestResult(),(["inbox","control"],[])))

class TestResult_test2(unittest.TestCase):
    def setUp(self):
        self.tester = component()
        self.trcomp = TestResult()
        self.trcomp.activate()
        self.pm = postman()
        self.pm.activate()
        self.tester.activate()
        #pipewidth = 1 implies 2 items in the linkage.  One in outbox and one in sourcebox.  Need to change this code if these semantics change.
        self.pm.registerlinkage(linkage(source = self.tester, sink = self.trcomp, sourcebox = "outbox", sinkbox = "inbox"))
        self.pm.registerlinkage(linkage(source = self.tester, sink = self.trcomp, sourcebox = "signal", sinkbox = "control"))

    def runtestsystem(self):
        for i in xrange(5):
            self.trcomp.next()
            self.pm.domessagedelivery()

    def test_trueInput1(self):
        "mainBody - Checks that system keeps running when true value messages are sent to the inbox"
        self.tester.send(1)
        self.runtestsystem()

    def test_falseInput1(self):
        "mainBody - Checks that an AssertionError is raised when a false value message is sent to the inbox."
        self.tester.send(0)
        self.failUnlessRaises(AssertionError, self.runtestsystem)

    def test_trueInput2(self):
        "mainBody - Checks that system keeps running when true value messages are sent to the inbox. Repeated test."
        for i in xrange(1,100):
            self.tester.send(i)
            self.runtestsystem()

    def test_falseInput2(self):
        "mainBody - Checks that an AssertionError is raised when false value messages are sent to the inbox after a series of true ones. Repeated test."
        for i in xrange(1,100):
            self.tester.send(i)
            self.runtestsystem()
        self.tester.send(False)
        self.failUnlessRaises(AssertionError, self.runtestsystem)

    def test_stopSystem1(self):
        "mainBody - Checks that a StopSystem message sent to the control causes StopSystemException."
        self.tester.send(StopSystem(), "signal")
        self.failUnlessRaises(StopSystemException, self.runtestsystem)

    def test_stopSystem2(self):
        "mainBody - Checks that a StopSystem message sent to the control causes StopSystemException and that this stops the scheduler."
        self.tester.send(StopSystem(), "signal")
        self.failUnlessRaises(StopSystemException, scheduler.run.runThreads)

def suite():
   #This returns a TestSuite made from the tests in the linkage_Test class.  It is required for eric3's unittest tool.
   suite = unittest.makeSuite(TestResult_test1)
   suite.addTest(TestResult_test2)
   return suite

if __name__=='__main__':
   suite()
   unittest.main()


text:
<?php

namespace WindowsAzure\Blob\Models;

/**
 * Encapsulates blob types
 *
 * @category  Microsoft
 * @package   WindowsAzure\Blob\Models
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.0_2014-01
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class BlobType
{
    const BLOCK_BLOB = 'BlockBlob';
    const PAGE_BLOB  = 'PageBlob';
}


text:
/* See license.txt for terms of usage */

// RequireJS configuration
require.config({
  baseUrl: ".",
  paths: {
    "react": "./lib/react",
    "reps": "../node_modules/firebug.sdk/lib/reps",
  }
});

// Load the main tooltip module
requirejs(["markup-tooltip"]);


text:
package uaa

import (
	"code.cloudfoundry.org/cli/api/uaa/internal"
)

// SetupResources configures the client to use the specified settings and diescopers the UAA and Authentication resources
func (client *Client) SetupResources(uaaURL string, loginURL string) error {
	info := NewInfo(uaaURL, loginURL)

	resources := map[string]string{
		"uaa":                    uaaURL,
		"authorization_endpoint": loginURL,
	}

	client.router = internal.NewRouter(internal.APIRoutes, resources)
	client.Info = info

	client.config.SetUAAEndpoint(uaaURL)

	return nil
}


text:
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
    internal sealed class EELocalSymbol : EELocalSymbolBase
    {
        private readonly MethodSymbol _method;
        private readonly TypeSymbol _type;

        private readonly LocalDeclarationKind _declarationKind;
        private readonly bool _isCompilerGenerated;
        private readonly ImmutableArray<Location> _locations;
        private readonly string _nameOpt;
        private readonly int _ordinal; // index in locals of containing block
        private readonly bool _isPinned;
        private readonly RefKind _refKind;
        private readonly bool _canScheduleToStack;

        public EELocalSymbol(
            MethodSymbol method,
            ImmutableArray<Location> locations,
            string nameOpt,
            int ordinal,
            LocalDeclarationKind declarationKind,
            TypeSymbol type,
            RefKind refKind,
            bool isPinned,
            bool isCompilerGenerated,
            bool canScheduleToStack)
        {
            Debug.Assert(method != null);
            Debug.Assert(ordinal >= -1);
            Debug.Assert(!locations.IsDefault);
            Debug.Assert(type != null);

            _method = method;
            _locations = locations;
            _nameOpt = nameOpt;
            _ordinal = ordinal;
            _declarationKind = declarationKind;
            _type = type;
            _refKind = refKind;
            _isPinned = isPinned;
            _isCompilerGenerated = isCompilerGenerated;
            _canScheduleToStack = canScheduleToStack;
        }

        internal override EELocalSymbolBase ToOtherMethod(MethodSymbol method, TypeMap typeMap)
        {
            var type = typeMap.SubstituteType(_type);
            return new EELocalSymbol(method, _locations, _nameOpt, _ordinal, _declarationKind, type, _refKind, _isPinned, _isCompilerGenerated, _canScheduleToStack);
        }

        internal override LocalDeclarationKind DeclarationKind
        {
            get { return _declarationKind; }
        }

        internal override bool CanScheduleToStack
        {
            get { return _canScheduleToStack; }
        }

        internal int Ordinal
        {
            get { return _ordinal; }
        }

        public override string Name
        {
            get { return _nameOpt; }
        }

        internal override SyntaxToken IdentifierToken
        {
            get { throw ExceptionUtilities.Unreachable; }
        }

        public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
        {
            get { return ImmutableArray<SyntaxReference>.Empty; }
        }

        public override ImmutableArray<Location> Locations
        {
            get { return _locations; }
        }

        public override Symbol ContainingSymbol
        {
            get { return _method; }
        }

        public override TypeSymbol Type
        {
            get { return _type; }
        }

        internal override bool IsPinned
        {
            get { return _isPinned; }
        }

        internal override bool IsCompilerGenerated
        {
            get { return _isCompilerGenerated; }
        }

        internal override RefKind RefKind
        {
            get { return _refKind; }
        }
    }
}


text:
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^queryByStartCity/(?P<slug1>[-\w\d]+)/(?P<slug2>[-\w\d\']+)$', views.queryByStartCity, name='queryByStartCity'),
    url(r'^getCitiesInACountry/(?P<slug>[-\w\d]+)$', views.getCitiesInACountry, name='getCitiesInACountry'),
]