text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.datavec.audio.dsp</title>
<meta name="date" content="2016-09-19">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package org.datavec.audio.dsp

Originally derived from musicg.

See: Description

Class Summary

Class
Description

FastFourierTransform

FFT object, transform amplitudes to frequency intensities

LinearInterpolation

Construct new data points within the range of a discrete set of known data points by linear equation

Resampler

Resample signal data (base on bytes)

WindowFunction

Window functions generator

Package org.datavec.audio.dsp Description

Originally derived from musicg.  Importing relevant snippets for working with basic audio data.

 https://code.google.com/p/musicg/

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
package datastructures.linked;

import java.util.Iterator;

public class SinglyLinkedList<T> implements Iterable<T> {
    private int size = 0;
    private Node<T> head = null;
    private Node<T> tail = null;

    class Node<T> {
        private T data;
        private Node<T> next;

        public Node(T data, Node<T> next) {
            this.data = data;
            this.next = next;
        }

        @Override
        public String toString() {
            return new StringBuilder("data:").append(data).append(" next:").append(next).toString();
        }
    }

    boolean isEmpty() {
        return size == 0;
    }

    Node<T> add(T item) {
        return addLast(item);
    }

    Node<T> get(int index) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException();
        }

        Node<T> temp = head;
        for (int i = 0; i < size; i++) {
            temp = temp.next;
        }
        return temp;
    }

    Node<T> find(T item) {
        Node<T> curr = head;
        while (curr != null && !curr.data.equals(item)) {
            curr = curr.next;
        }
        return curr;
    }

    Node<T> findPrev(T item) {
        Node<T> curr = head;
        while (curr != null && curr.next != null && !curr.next.data.equals(item)) {
            curr = curr.next;
        }
        return curr;
    }

    Node<T> addFirst(T item) {
        Node<T> node = new Node<>(item, null);
        if (this.isEmpty()) {
            head = tail = node;
        } else {
            node.next = head;
            head = node;
        }
        size++;
        return node;
    }

    Node<T> addLast(T item) {
        Node<T> node = new Node<>(item, null);
        if (this.isEmpty()) {
            head = tail = node;
        } else {
            tail.next = node;
            tail = node;
        }
        size++;
        return node;

    }

    void remove(T item) {
        Node<T> prev = findPrev(item);
        if (prev != null && prev.next != null) {
           prev.next = prev.next.next;
        } else {
            head = null;
        }
        size--;
    }

    @Override
    public Iterator<T> iterator() {
        return new Iterator<T>() {
            private Node<T> curr = head;

            public boolean hasNext() {
                return curr != null;
            }

            public T next() {
                T data = curr.data;
                curr = curr.next;
                return data;
            }

            public void remove() {
                if (curr == null) {
                    return;
                }
            }

        };
    }

    @Override
    public String toString() {
        Iterator<T> it = iterator();
        if (!it.hasNext()) {
            return "[]";
        }

        StringBuilder sb = new StringBuilder();
        sb.append('[');
        for (;;) {
            T item = it.next();
            sb.append(item);
            if (!it.hasNext()) {
                sb.append(']').toString();
                break;
            }
            sb.append(',').append(' ');
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        SinglyLinkedList<Integer> linkedList = new SinglyLinkedList();
        linkedList.add(1);
        linkedList.add(1);
        linkedList.add(1);
        linkedList.remove(1);
        System.out.println(linkedList);
    }
}

redpajama_set_name: RedPajamaGithub


text:
@font-face {
	font-family: 'icomoon';
	src:url('../fonts/icomoon/icomoon.eot?-rdnm34');
	src:url('../fonts/icomoon/icomoon.eot?#iefix-rdnm34') format('embedded-opentype'),
		url('../fonts/icomoon/icomoon.woff?-rdnm34') format('woff'),
		url('../fonts/icomoon/icomoon.ttf?-rdnm34') format('truetype'),
		url('../fonts/icomoon/icomoon.svg?-rdnm34#icomoon') format('svg');
	font-weight: normal;
	font-style: normal;
}

div.cs-skin-underline {
	background: transparent;
	font-size: 1.8em;
	max-width: 400px;
}

@media screen and (max-width: 30em) {
	div.cs-skin-underline { font-size: 1.2em; }
}

.cs-skin-underline > span {
	padding: 0.5em 3em 0.5em 0.5em;
	border-bottom: 3px solid #000;
	border-color: inherit;
	font-weight: bold;
}

.cs-skin-underline > span::after {
	font-family: 'icomoon';
	content: '\e003';
	right: 0.25em;
	-webkit-transform: translate3d(0,-50%,0) rotate3d(0,0,1,45deg);
	transform: translate3d(0,-50%,0) rotate3d(0,0,1,45deg);
	-webkit-transition: -webkit-transform 0.5s;
	transition: transform 0.5s;
}

.cs-skin-underline.cs-active > span::after {
	-webkit-transform: translate3d(0,-50%,0) rotate3d(0,0,1,270deg);
	transform: translate3d(0,-50%,0) rotate3d(0,0,1,270deg);
}

.cs-skin-underline .cs-options {
	background: #bbc7c8;
	opacity: 0;
	-webkit-transition: opacity 0.3s 0.4s, visibility 0s 0.7s;
	transition: opacity 0.3s 0.4s, visibility 0s 0.7s;
}

.cs-skin-underline.cs-active .cs-options {
	opacity: 1;
	-webkit-transition: opacity 0.3s;
	transition: opacity 0.3s;
}

.cs-skin-underline ul span {
	position: relative;
	text-transform: uppercase;
	font-size: 66%;
	font-weight: 700;
	letter-spacing: 1px;
	padding: 1.2em 0.8em;
	opacity: 0;
	-webkit-transform: translate3d(100%,0,0);
	transform: translate3d(100%,0,0);
	-webkit-transition: opacity 0.3s, -webkit-transform 0.3s;
	transition: opacity 0.3s, transform 0.3s;
}

.cs-select ul span::after {
	content: '';
	opacity: 0;
}

.cs-select .cs-selected span::after {
	font-family: 'icomoon';
	content: '\e010';
	opacity: 1;
	-webkit-transition: opacity 0.3s 0.7s;
	transition: opacity 0.3s 0.7s;
}

.cs-skin-underline ul span::before {
	content: '';
	position: absolute;
	bottom: 1px;
	left: 0;
	height: 3px;
	width: 100%;
	background-color: #fff;
	-webkit-transform: translate3d(200%,0,0);
	transform: translate3d(200%,0,0);
	-webkit-transition: -webkit-transform 0.3s;
	transition: transform 0.3s;
}

.cs-skin-underline.cs-active ul span,
.cs-skin-underline.cs-active ul span::before {
	opacity: 1;
	-webkit-transform: translate3d(0,0,0);
	transform: translate3d(0,0,0);
}

.cs-skin-underline li:nth-child(5) span,
.cs-skin-underline li:nth-child(5) span::before,
.cs-skin-underline.cs-active li:first-child span,
.cs-skin-underline.cs-active li:first-child span::before {
	-webkit-transition-delay: 0s;
	transition-delay: 0s;
}

.cs-skin-underline li:nth-child(4) span,
.cs-skin-underline li:nth-child(4) span::before,
.cs-skin-underline.cs-active li:nth-child(2) span,
.cs-skin-underline.cs-active li:nth-child(2) span::before {
	-webkit-transition-delay: 0.05s;
	transition-delay: 0.05s;
}

.cs-skin-underline li:nth-child(3) span,
.cs-skin-underline li:nth-child(3) span::before {
	-webkit-transition-delay: 0.1s;
	transition-delay: 0.1s;
}

.cs-skin-underline li:nth-child(2) span,
.cs-skin-underline li:nth-child(2) span::before,
.cs-skin-underline.cs-active li:nth-child(4) span,
.cs-skin-underline.cs-active li:nth-child(4) span::before {
	-webkit-transition-delay: 0.15s;
	transition-delay: 0.15s;
}

.cs-skin-underline li:first-child span,
.cs-skin-underline li:first-child span::before,
.cs-skin-underline.cs-active li:nth-child(5) span,
.cs-skin-underline.cs-active li:nth-child(5) span::before {
	-webkit-transition-delay: 0.2s;
	transition-delay: 0.2s;
} /* more items require more delay declarations */

.cs-skin-underline .cs-options li span:hover,
.cs-skin-underline .cs-options li.cs-focus span,
.cs-skin-underline li.cs-selected span {
	color: #566473;
	background: transparent;
}


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

  module.exports = function (gulp, plugins, config) {
    return function () {
      plugins.del(['**/*/.DS_Store']);
      plugins.del([config.buildPath]);
      return true;
    };
  };
})();


text:
FOUNDATION_EXPORT double Pods_glucose_ExampleVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_glucose_ExampleVersionString[];


text:
//// [mod.d.ts]
export = modObj;
declare const modObj: modObj.A & modObj.B;
declare namespace modObj {
    interface A { (): void; a: string; }
    interface B { (x: string): void; b: string; }
}
//// [idx.ts]
import * as mod from "./mod";
mod.a;
mod.b;

//// [idx.js]
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
exports.__esModule = true;
var mod = __importStar(require("./mod"));
mod.a;
mod.b;


text:
package rapture.persistence.storable.mapper;

import rapture.common.dp.Workflow;

/**
 * test mapper
 *
 * @author bardhi
 * @since 7/21/15.
 */
public class WorkflowSerDeserHelper implements StorableSerDeserHelper<Workflow, WorkflowExtended> {
    @Override
    public Class<Workflow> getStorableClass() {
        return Workflow.class;
    }

    @Override
    public Class<WorkflowExtended> getExtendedClass() {
        return WorkflowExtended.class;
    }

    @Override
    public void onSerialize(Workflow storable) {

    }

    @Override
    public void onDeserialize(WorkflowExtended user) {

    }
}


text:
import Ember from 'ember';
import ApplicationRouteMixin from 'simple-auth/mixins/application-route-mixin';

export default Ember.Route.extend(ApplicationRouteMixin, {
	actions: {
		sessionInvalidationSucceeded: function(){
			this.transitionTo('login');
		}
	}
});


text:
package com.gooddata.spring;

import com.gooddata.GoodData;
import com.gooddata.project.ProjectService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.testng.annotations.Test;

import java.lang.reflect.Method;
import java.util.Arrays;

import static org.testng.Assert.*;

public class GoodDataBeansAsServicesIT {

    @Test
    public void servicesRegisteredFromXmlUsingAnnotationConfig() throws Exception {
        final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/gd-annotationConfig.xml");
        Arrays.stream(GoodData.class.getDeclaredMethods())
                .map(Method::getReturnType)
                .filter(rt -> rt.getName().endsWith("Service"))
                .forEach(rt -> assertNotNull(context.getBean(rt), "Bean of type " + rt + " should be registered"));
    }
}


text:
package commonci

import (
	"testing"

	"github.com/google/go-cmp/cmp"
)

var (
	basicModelMap = OpenConfigModelMap{
		ModelRoot: "testdata",
		ModelInfoMap: map[string][]ModelInfo{
			"acl": []ModelInfo{{
				Name: "openconfig-acl",
				DocFiles: []string{
					"yang/acl/openconfig-packet-match-types.yang",
					"yang/acl/openconfig-acl.yang",
				},
				BuildFiles: []string{
					"testdata/acl/openconfig-acl.yang",
					"testdata/acl/openconfig-acl-evil-twin.yang",
				},
				RunCi: true,
			}},
			"optical-transport": []ModelInfo{{
				Name: "openconfig-terminal-device",
				DocFiles: []string{
					"yang/optical-transport/openconfig-transport-types.yang",
					"yang/platform/openconfig-platform-types.yang",
					"yang/optical-transport/openconfig-terminal-device.yang",
					"yang/platform/openconfig-platform-transceiver.yang",
				},
				RunCi: true,
			}, {
				Name: "openconfig-optical-amplifier",
				BuildFiles: []string{
					"testdata/optical-transport/openconfig-optical-amplifier.yang",
				},
				RunCi: true,
			}, {
				Name: "openconfig-wavelength-router",
				DocFiles: []string{
					"yang/optical-transport/openconfig-transport-types.yang",
					"yang/optical-transport/openconfig-transport-line-common.yang",
					"yang/optical-transport/openconfig-wavelength-router.yang",
					"yang/optical-transport/openconfig-channel-monitor.yang",
					"yang/optical-transport/openconfig-transport-line-connectivity.yang",
				},
				BuildFiles: []string{
					"testdata/optical-transport/openconfig-transport-line-connectivity.yang",
					"testdata/optical-transport/openconfig-wavelength-router.yang",
				},
				RunCi: false,
			}, {
				Name: "openconfig-transport-line-protection",
				DocFiles: []string{
					"yang/platform/openconfig-platform-types.yang",
					"yang/optical-transport/openconfig-transport-line-protection.yang",
					"yang/platform/openconfig-platform.yang",
				},
				BuildFiles: []string{
					"testdata/optical-transport/openconfig-transport-line-protection.yang",
				},
				RunCi: true,
			}, {
				Name: "openconfig-optical-attenuator",
				DocFiles: []string{
					"yang/optical-transport/openconfig-optical-attenuator.yang",
				},
				BuildFiles: []string{
					"testdata/optical-transport/openconfig-optical-attenuator.yang",
				},
				RunCi: false,
			}},
		},
	}
)

func TestParseOCModels(t *testing.T) {
	tests := []struct {
		name        string
		inModelRoot string
		want        OpenConfigModelMap
	}{{
		name:        "basic",
		inModelRoot: "testdata",
		want:        basicModelMap,
	}}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := ParseOCModels(tt.inModelRoot)
			if err != nil {
				t.Fatal(err)
			}

			if diff := cmp.Diff(tt.want, got); diff != "" {
				t.Errorf("(-want, +got):\n%s", diff)
			}
		})
	}
}

func TestGetValidatorAndVersionsFromString(t *testing.T) {
	tests := []struct {
		desc       string
		inStr      string
		wantVVList []ValidatorAndVersion
		wantVVMap  map[string]map[string]bool
	}{{
		desc:       "empty",
		inStr:      "",
		wantVVList: nil,
		wantVVMap:  map[string]map[string]bool{},
	}, {
		desc:       "empty with a comma",
		inStr:      ",",
		wantVVList: nil,
		wantVVMap:  map[string]map[string]bool{},
	}, {
		desc:       "single no version",
		inStr:      "pyang",
		wantVVList: []ValidatorAndVersion{{ValidatorId: "pyang"}},
		wantVVMap:  map[string]map[string]bool{"pyang": map[string]bool{"": true}},
	}, {
		desc:       "ending comma",
		inStr:      "pyang,",
		wantVVList: []ValidatorAndVersion{{ValidatorId: "pyang"}},
		wantVVMap:  map[string]map[string]bool{"pyang": map[string]bool{"": true}},
	}, {
		desc:       "ending comma with spaces around before",
		inStr:      "   pyang,   ",
		wantVVList: []ValidatorAndVersion{{ValidatorId: "pyang"}},
		wantVVMap:  map[string]map[string]bool{"pyang": map[string]bool{"": true}},
	}, {
		desc:       "single with version",
		inStr:      "pyang@1.7.2",
		wantVVList: []ValidatorAndVersion{{ValidatorId: "pyang", Version: "1.7.2"}},
		wantVVMap:  map[string]map[string]bool{"pyang": map[string]bool{"1.7.2": true}},
	}, {
		desc:       "single with version and comma",
		inStr:      "pyang@1.7.2,",
		wantVVList: []ValidatorAndVersion{{ValidatorId: "pyang", Version: "1.7.2"}},
		wantVVMap:  map[string]map[string]bool{"pyang": map[string]bool{"1.7.2": true}},
	}, {
		desc:  "more than one version with an extraneous comma",
		inStr: "pyang@1.7.2,,pyang,oc-pyang,pyang@head",
		wantVVList: []ValidatorAndVersion{
			{ValidatorId: "pyang", Version: "1.7.2"},
			{ValidatorId: "pyang", Version: ""},
			{ValidatorId: "oc-pyang", Version: ""},
			{ValidatorId: "pyang", Version: "head"},
		},
		wantVVMap: map[string]map[string]bool{
			"pyang": map[string]bool{
				"":      true,
				"head":  true,
				"1.7.2": true,
			},
			"oc-pyang": map[string]bool{
				"": true,
			},
		},
	}, {
		desc:  "more than one version with ending comma and with a duplicate",
		inStr: "pyang@1.7.2,pyang,oc-pyang,pyang@1.7.2,pyang@head,",
		wantVVList: []ValidatorAndVersion{
			{ValidatorId: "pyang", Version: "1.7.2"},
			{ValidatorId: "pyang", Version: ""},
			{ValidatorId: "oc-pyang", Version: ""},
			{ValidatorId: "pyang", Version: "head"},
		},
		wantVVMap: map[string]map[string]bool{
			"pyang": map[string]bool{
				"":      true,
				"head":  true,
				"1.7.2": true,
			},
			"oc-pyang": map[string]bool{
				"": true,
			},
		},
	}}

	for _, tt := range tests {
		t.Run(tt.desc, func(t *testing.T) {
			gotVVList, gotVVMap := GetValidatorAndVersionsFromString(tt.inStr)
			if diff := cmp.Diff(gotVVList, tt.wantVVList); diff != "" {
				t.Errorf("[]ValidatorAndVersion (-got, +want):\n%s", diff)
			}
			if diff := cmp.Diff(gotVVMap, tt.wantVVMap); diff != "" {
				t.Errorf("ValidatorAndVersion Map (-got, +want):\n%s", diff)
			}
		})
	}
}

func TestValidatorAndVersionsDiff(t *testing.T) {
	tests := []struct {
		desc    string
		inAStr  string
		inBStr  string
		wantStr string
	}{{
		desc:    "single no version",
		inAStr:  "pyang",
		inBStr:  "pyang",
		wantStr: "",
	}, {
		desc:    "single with ending comma",
		inAStr:  "pyang,",
		inBStr:  "pyang",
		wantStr: "",
	}, {
		desc:    "single version doesn't match latest",
		inAStr:  "pyang@1.7.2",
		inBStr:  "pyang",
		wantStr: "pyang@1.7.2",
	}, {
		desc:    "single version doesn't match",
		inAStr:  "pyang@1.7.2",
		inBStr:  "pyang@1.7.1",
		wantStr: "pyang@1.7.2",
	}, {
		desc:    "single with version",
		inAStr:  "pyang@1.7.2",
		inBStr:  "pyang@1.7.2",
		wantStr: "",
	}, {
		desc:    "more than one version and with an extraneous comma",
		inAStr:  "pyang@1.7.2,pyang,oc-pyang,,pyang@head",
		inBStr:  "pyang@head",
		wantStr: "pyang@1.7.2,pyang,oc-pyang",
	}, {
		desc:    "more than one version deletes",
		inAStr:  "pyang@1.7.2,pyang,oc-pyang,pyang@head",
		inBStr:  "oc-pyang,pyang@1.7.2",
		wantStr: "pyang,pyang@head",
	}, {
		desc:    "more than one version deletes with duplicates",
		inAStr:  "pyang@1.7.2,pyang,oc-pyang,pyang@head,oc-pyang,goyang-ygot",
		inBStr:  "pyang@1.7.2,goyang-ygot,oc-pyang,pyang@1.7.2",
		wantStr: "pyang,pyang@head",
	}, {
		desc:    "more than one version deletes with deleting something not there",
		inAStr:  "pyang@1.7.2,pyang,oc-pyang,pyang@head",
		inBStr:  "oc-pyang,pyang@1.7.2,super-check",
		wantStr: "pyang,pyang@head",
	}}

	for _, tt := range tests {
		t.Run(tt.desc, func(t *testing.T) {
			if gotStr := ValidatorAndVersionsDiff(tt.inAStr, tt.inBStr); gotStr != tt.wantStr {
				t.Errorf("got %q, want %q", gotStr, tt.wantStr)
			}
		})
	}
}


text:
import string
import os
import struct

voice_folder=u'C:\\S60\\devices\\S60_3rd_FP2_SDK_v1.1\\epoc32\\winscw\\c\\Data\\python\\voice\\'
file_extension=u'.wav'
nullstring='\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0'
voice=[]
voicefile=file(u'voice.pak','wb')
voicefiles=os.listdir(voice_folder)
voiceoffset=0
for voicefilename in voicefiles:
    if voicefilename.endswith(file_extension):
        voicesize=os.path.getsize(voice_folder+voicefilename)
        voice.append((voicefilename[:-len(file_extension)],voiceoffset,voicesize))
        voiceoffset+=voicesize
contentoffset=len(voice)*(32+4*2)+4
voicefile.write(struct.pack('i',len(voice)))
for voiceentry in voice:
    voicefile.write(voiceentry[0])
    voicefile.write(nullstring[:32-len(voiceentry[0])])
    voicefile.write(struct.pack('i',voiceentry[1]+contentoffset))
    voicefile.write(struct.pack('i',voiceentry[2]))
for voiceentry in voice:
    singlevoicefile=file(voice_folder+voiceentry[0]+file_extension,'rb')
    rawbuffer=singlevoicefile.read()
    voicefile.write(rawbuffer)
    singlevoicefile.close()
voicefile.close()


text:
namespace window_manager {

class FocusControllerObserver;
class FocusRules;

// FocusController handles focus and activation changes in a mojo window
// manager. Within the window manager, there can only be one focused and one
// active window at a time. When focus or activation changes, notifications are
// sent using the FocusControllerObserver interface.
class FocusController : public ui::EventHandler, public mojo::ViewObserver {
 public:
  // |rules| cannot be null.
  explicit FocusController(scoped_ptr<FocusRules> rules);
  ~FocusController() override;

  void AddObserver(FocusControllerObserver* observer);
  void RemoveObserver(FocusControllerObserver* observer);

  void ActivateView(mojo::View* view);
  void DeactivateView(mojo::View* view);
  mojo::View* GetActiveView();
  mojo::View* GetActivatableView(mojo::View* view);
  mojo::View* GetToplevelView(mojo::View* view);
  bool CanActivateView(mojo::View* view) const;

  void FocusView(mojo::View* view);

  void ResetFocusWithinActiveView(mojo::View* view);
  mojo::View* GetFocusedView();

  // Overridden from ui::EventHandler:
  void OnKeyEvent(ui::KeyEvent* event) override;
  void OnMouseEvent(ui::MouseEvent* event) override;
  void OnScrollEvent(ui::ScrollEvent* event) override;
  void OnTouchEvent(ui::TouchEvent* event) override;
  void OnGestureEvent(ui::GestureEvent* event) override;

  // Overridden from ViewObserver:
  void OnTreeChanging(const TreeChangeParams& params) override;
  void OnTreeChanged(const TreeChangeParams& params) override;
  void OnViewVisibilityChanged(mojo::View* view) override;
  void OnViewDestroying(mojo::View* view) override;

 private:
  // Internal implementation that sets the focused view, fires events etc.
  // This function must be called with a valid focusable view.
  void SetFocusedView(mojo::View* view);

  // Internal implementation that sets the active window, fires events etc.
  // This function must be called with a valid |activatable_window|.
  // |requested window| refers to the window that was passed in to an external
  // request (e.g. FocusWindow or ActivateWindow). It may be null, e.g. if
  // SetActiveWindow was not called by an external request. |activatable_window|
  // refers to the actual window to be activated, which may be different.
  void SetActiveView(mojo::View* requested_view, mojo::View* activatable_view);

  // Called when a window's disposition changed such that it and its hierarchy
  // are no longer focusable/activatable. |next| is a valid window that is used
  // as a starting point for finding a window to focus next based on rules.
  void ViewLostFocusFromDispositionChange(mojo::View* view, mojo::View* next);

  // Called when an attempt is made to focus or activate a window via an input
  // event targeted at that window. Rules determine the best focusable window
  // for the input window.
  void ViewFocusedFromInputEvent(mojo::View* view);

  mojo::View* active_view_;
  mojo::View* focused_view_;

  bool updating_focus_;
  bool updating_activation_;

  scoped_ptr<FocusRules> rules_;

  base::ObserverList<FocusControllerObserver> focus_controller_observers_;

  ScopedObserver<mojo::View, ViewObserver> observer_manager_;

  DISALLOW_COPY_AND_ASSIGN(FocusController);
};

// Sets/Gets the focus controller for a view.
void SetFocusController(mojo::View* view, FocusController* focus_controller);
FocusController* GetFocusController(mojo::View* view);

}  // namespace window_manager

#endif  // SERVICES_WINDOW_MANAGER_FOCUS_CONTROLLER_H_


text:
package com.redmintie.steelplate.input.event;

public class KeyAdapter implements KeyListener {
	@Override
	public void keyPressed(KeyEvent event) {
	}
	@Override
	public void keyReleased(KeyEvent event) {
	}
	@Override
	public void keyTyped(KeyEvent event) {
	}
}


text:
#ifndef __MEM_PROBES_BASE_HH__
#define __MEM_PROBES_BASE_HH__

#include <memory>
#include <vector>

#include "mem/packet.hh"
#include "sim/probe/probe.hh"
#include "sim/sim_object.hh"

struct BaseMemProbeParams;

/**
 * Base class for memory system probes accepting Packet instances.
 *
 * This is a helper base class for memory system probes that
 * instrument Packet handling. Unlike the ProbeListenerObject base
 * class, this class supports instrumentation of multiple ProbeManager
 * instances. However, it's limited to one probe point name. This
 * enables features like tracing or stack distance analysis of packets
 * from multiple components using the same probe. For example, a stack
 * distance probe could be hooked up to multiple memories in a
 * multi-channel configuration.
 */
class BaseMemProbe : public SimObject
{
  public:
    BaseMemProbe(BaseMemProbeParams *params);

    void regProbeListeners() M5_ATTR_OVERRIDE;

  protected:
    /**
     * Callback to analyse intercepted Packets.
     */
    virtual void handleRequest(const PacketPtr &pkt) = 0;

  private:
    class PacketListener : public ProbeListenerArgBase<PacketPtr>
    {
      public:
        PacketListener(BaseMemProbe &_parent,
                       ProbeManager *pm, const std::string &name)
            : ProbeListenerArgBase(pm, name),
              parent(_parent) {}

        void notify(const PacketPtr &pkt) M5_ATTR_OVERRIDE {
            parent.handleRequest(pkt);
        }

      protected:
        BaseMemProbe &parent;
    };

    std::vector<std::unique_ptr<PacketListener>> listeners;
};

#endif //  __MEM_PROBES_BASE_HH__


text:
namespace DotNetArchitectureCheckerTest2.dir1.dir3 {
    public struct Test2 {
        public int I;
    }
}


text:
package com.cloud.storage.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.inject.Inject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.cloud.server.ResourceTag.ResourceObjectType;
import com.cloud.storage.DataStoreRole;
import com.cloud.storage.Snapshot;
import com.cloud.storage.Snapshot.Event;
import com.cloud.storage.Snapshot.State;
import com.cloud.storage.Snapshot.Type;
import com.cloud.storage.SnapshotVO;
import com.cloud.storage.Volume;
import com.cloud.storage.VolumeVO;
import com.cloud.tags.dao.ResourceTagDao;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Filter;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.GenericSearchBuilder;
import com.cloud.utils.db.JoinBuilder.JoinType;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Func;
import com.cloud.utils.db.TransactionLegacy;
import com.cloud.utils.db.UpdateBuilder;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.dao.VMInstanceDao;

@Component
public class SnapshotDaoImpl extends GenericDaoBase<SnapshotVO, Long> implements SnapshotDao {
    public static final Logger s_logger = Logger.getLogger(SnapshotDaoImpl.class.getName());
    // TODO: we should remove these direct sqls
    private static final String GET_LAST_SNAPSHOT =
        "SELECT snapshots.id FROM snapshot_store_ref, snapshots where snapshots.id = snapshot_store_ref.snapshot_id AND snapshosts.volume_id = ? AND snapshot_store_ref.role = ? ORDER BY created DESC";

    private SearchBuilder<SnapshotVO> VolumeIdSearch;
    private SearchBuilder<SnapshotVO> VolumeIdTypeSearch;
    private SearchBuilder<SnapshotVO> VolumeIdTypeNotDestroyedSearch;
    private SearchBuilder<SnapshotVO> VolumeIdVersionSearch;
    private SearchBuilder<SnapshotVO> AccountIdSearch;
    private SearchBuilder<SnapshotVO> InstanceIdSearch;
    private SearchBuilder<SnapshotVO> StatusSearch;
    private SearchBuilder<SnapshotVO> notInStatusSearch;
    private GenericSearchBuilder<SnapshotVO, Long> CountSnapshotsByAccount;
    @Inject
    ResourceTagDao _tagsDao;
    @Inject
    protected VMInstanceDao _instanceDao;
    @Inject
    protected VolumeDao _volumeDao;

    @Override
    public List<SnapshotVO> listByVolumeIdTypeNotDestroyed(long volumeId, Type type) {
        SearchCriteria<SnapshotVO> sc = VolumeIdTypeNotDestroyedSearch.create();
        sc.setParameters("volumeId", volumeId);
        sc.setParameters("type", type.ordinal());
        sc.setParameters("status", State.Destroyed);
        return listBy(sc, null);
    }

    @Override
    public List<SnapshotVO> listByVolumeIdVersion(long volumeId, String version) {
        return listByVolumeIdVersion(null, volumeId, version);
    }

    @Override
    public List<SnapshotVO> listByVolumeId(long volumeId) {
        return listByVolumeId(null, volumeId);
    }

    @Override
    public List<SnapshotVO> listByVolumeId(Filter filter, long volumeId) {
        SearchCriteria<SnapshotVO> sc = VolumeIdSearch.create();
        sc.setParameters("volumeId", volumeId);
        return listBy(sc, filter);
    }

    @Override
    public List<SnapshotVO> listByVolumeIdIncludingRemoved(long volumeId) {
        SearchCriteria<SnapshotVO> sc = VolumeIdSearch.create();
        sc.setParameters("volumeId", volumeId);
        return listIncludingRemovedBy(sc, null);
    }

    public List<SnapshotVO> listByVolumeIdType(Filter filter, long volumeId, Type type) {
        SearchCriteria<SnapshotVO> sc = VolumeIdTypeSearch.create();
        sc.setParameters("volumeId", volumeId);
        sc.setParameters("type", type.ordinal());
        return listBy(sc, filter);
    }

    public List<SnapshotVO> listByVolumeIdVersion(Filter filter, long volumeId, String version) {
        SearchCriteria<SnapshotVO> sc = VolumeIdVersionSearch.create();
        sc.setParameters("volumeId", volumeId);
        sc.setParameters("version", version);
        return listBy(sc, filter);
    }

    public SnapshotDaoImpl() {
    }

    @PostConstruct
    protected void init() {
        VolumeIdSearch = createSearchBuilder();
        VolumeIdSearch.and("volumeId", VolumeIdSearch.entity().getVolumeId(), SearchCriteria.Op.EQ);
        VolumeIdSearch.done();

        VolumeIdTypeSearch = createSearchBuilder();
        VolumeIdTypeSearch.and("volumeId", VolumeIdTypeSearch.entity().getVolumeId(), SearchCriteria.Op.EQ);
        VolumeIdTypeSearch.and("type", VolumeIdTypeSearch.entity().getsnapshotType(), SearchCriteria.Op.EQ);
        VolumeIdTypeSearch.done();

        VolumeIdTypeNotDestroyedSearch = createSearchBuilder();
        VolumeIdTypeNotDestroyedSearch.and("volumeId", VolumeIdTypeNotDestroyedSearch.entity().getVolumeId(), SearchCriteria.Op.EQ);
        VolumeIdTypeNotDestroyedSearch.and("type", VolumeIdTypeNotDestroyedSearch.entity().getsnapshotType(), SearchCriteria.Op.EQ);
        VolumeIdTypeNotDestroyedSearch.and("status", VolumeIdTypeNotDestroyedSearch.entity().getState(), SearchCriteria.Op.NEQ);
        VolumeIdTypeNotDestroyedSearch.done();

        VolumeIdVersionSearch = createSearchBuilder();
        VolumeIdVersionSearch.and("volumeId", VolumeIdVersionSearch.entity().getVolumeId(), SearchCriteria.Op.EQ);
        VolumeIdVersionSearch.and("version", VolumeIdVersionSearch.entity().getVersion(), SearchCriteria.Op.EQ);
        VolumeIdVersionSearch.done();

        AccountIdSearch = createSearchBuilder();
        AccountIdSearch.and("accountId", AccountIdSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
        AccountIdSearch.done();

        StatusSearch = createSearchBuilder();
        StatusSearch.and("volumeId", StatusSearch.entity().getVolumeId(), SearchCriteria.Op.EQ);
        StatusSearch.and("status", StatusSearch.entity().getState(), SearchCriteria.Op.IN);
        StatusSearch.done();

        notInStatusSearch  = createSearchBuilder();
        notInStatusSearch.and("volumeId", notInStatusSearch.entity().getVolumeId(), SearchCriteria.Op.EQ);
        notInStatusSearch.and("status", notInStatusSearch.entity().getState(), SearchCriteria.Op.NOTIN);
        notInStatusSearch.done();

        CountSnapshotsByAccount = createSearchBuilder(Long.class);
        CountSnapshotsByAccount.select(null, Func.COUNT, null);
        CountSnapshotsByAccount.and("account", CountSnapshotsByAccount.entity().getAccountId(), SearchCriteria.Op.EQ);
        CountSnapshotsByAccount.and("status", CountSnapshotsByAccount.entity().getState(), SearchCriteria.Op.NIN);
        CountSnapshotsByAccount.and("removed", CountSnapshotsByAccount.entity().getRemoved(), SearchCriteria.Op.NULL);
        CountSnapshotsByAccount.done();

        InstanceIdSearch = createSearchBuilder();
        InstanceIdSearch.and("status", InstanceIdSearch.entity().getState(), SearchCriteria.Op.IN);

        SearchBuilder<VMInstanceVO> instanceSearch = _instanceDao.createSearchBuilder();
        instanceSearch.and("instanceId", instanceSearch.entity().getId(), SearchCriteria.Op.EQ);

        SearchBuilder<VolumeVO> volumeSearch = _volumeDao.createSearchBuilder();
        volumeSearch.and("state", volumeSearch.entity().getState(), SearchCriteria.Op.EQ);
        volumeSearch.join("instanceVolumes", instanceSearch, instanceSearch.entity().getId(), volumeSearch.entity().getInstanceId(), JoinType.INNER);

        InstanceIdSearch.join("instanceSnapshots", volumeSearch, volumeSearch.entity().getId(), InstanceIdSearch.entity().getVolumeId(), JoinType.INNER);
        InstanceIdSearch.done();
    }

    @Override
    public long getLastSnapshot(long volumeId, DataStoreRole role) {
        TransactionLegacy txn = TransactionLegacy.currentTxn();
        PreparedStatement pstmt = null;
        String sql = GET_LAST_SNAPSHOT;
        try {
            pstmt = txn.prepareAutoCloseStatement(sql);
            pstmt.setLong(1, volumeId);
            pstmt.setString(2, role.toString());
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                return rs.getLong(1);
            }
        } catch (Exception ex) {
            s_logger.error("error getting last snapshot", ex);
        }
        return 0;
    }

    @Override
    public Long countSnapshotsForAccount(long accountId) {
        SearchCriteria<Long> sc = CountSnapshotsByAccount.create();
        sc.setParameters("account", accountId);
        sc.setParameters("status", State.Error, State.Destroyed);
        return customSearch(sc, null).get(0);
    }

    @Override
    public List<SnapshotVO> listByInstanceId(long instanceId, Snapshot.State... status) {
        SearchCriteria<SnapshotVO> sc = InstanceIdSearch.create();

        if (status != null && status.length != 0) {
            sc.setParameters("status", (Object[])status);
        }

        sc.setJoinParameters("instanceSnapshots", "state", Volume.State.Ready);
        sc.setJoinParameters("instanceVolumes", "instanceId", instanceId);
        return listBy(sc, null);
    }

    @Override
    public List<SnapshotVO> listByStatus(long volumeId, Snapshot.State... status) {
        SearchCriteria<SnapshotVO> sc = StatusSearch.create();
        sc.setParameters("volumeId", volumeId);
        sc.setParameters("status", (Object[])status);
        return listBy(sc, null);
    }

    @Override
    @DB
    public boolean remove(Long id) {
        TransactionLegacy txn = TransactionLegacy.currentTxn();
        txn.start();
        SnapshotVO entry = findById(id);
        if (entry != null) {
            _tagsDao.removeByIdAndType(id, ResourceObjectType.Snapshot);
        }
        boolean result = super.remove(id);
        txn.commit();
        return result;
    }

    @Override
    public List<SnapshotVO> listAllByStatus(Snapshot.State... status) {
        SearchCriteria<SnapshotVO> sc = StatusSearch.create();
        sc.setParameters("status", (Object[])status);
        return listBy(sc, null);
    }

    @Override
    public boolean updateState(State currentState, Event event, State nextState, SnapshotVO snapshot, Object data) {
        TransactionLegacy txn = TransactionLegacy.currentTxn();
        txn.start();
        SnapshotVO snapshotVO = snapshot;
        snapshotVO.setState(nextState);
        super.update(snapshotVO.getId(), snapshotVO);
        txn.commit();
        return true;
    }

    @Override
    public void updateVolumeIds(long oldVolId, long newVolId) {
        SearchCriteria<SnapshotVO> sc = VolumeIdSearch.create();
        sc.setParameters("volumeId", oldVolId);
        SnapshotVO snapshot = createForUpdate();
        snapshot.setVolumeId(newVolId);
        UpdateBuilder ub = getUpdateBuilder(snapshot);
        update(ub, sc, null);
    }

    @Override
    public List<SnapshotVO> listByStatusNotIn(long volumeId, Snapshot.State... status) {
        SearchCriteria<SnapshotVO> sc = this.notInStatusSearch.create();
        sc.setParameters("volumeId", volumeId);
        sc.setParameters("status", (Object[]) status);
        return listBy(sc, null);
    }
}


text:
@interface PodsDummy_Pods_TFMDBDemo : NSObject
@end
@implementation PodsDummy_Pods_TFMDBDemo
@end


text:
require "serverkit/resources/base"

module Serverkit
  module Resources
    class Command < Base
      attribute :script, required: true, type: String

      # @note Override
      def apply
        run_command(script)
      end

      # @note Override
      def check
        false
      end

      private

      # @note Override
      def recheck
        if check_script
          check_command(check_script)
        else
          true
        end
      end
    end
  end
end


text:
subdir = src/backend/fts
top_builddir = ../../..
include $(top_builddir)/src/Makefile.global
override CPPFLAGS := -I$(libpq_srcdir) $(CPPFLAGS)

OBJS = fts.o ftsprobe.o
OBJS += ftsmessagehandler.o
include $(top_srcdir)/src/backend/common.mk


text:
require 'readline'

def load_config
  Skyline.load_config
end

def init
  Skyline.init
end

def reload
  Skyline.init(true)
end

def list(what = nil)
  case what
  when :all
    Skyline.as_groups.each do |name, group|
      puts name.to_s
      group[:instances].each do |instance|
        puts "   #{instance[:id].ljust(10)}  " +
             "#{instance[:public_ip].ljust(15)}  " +
             "#{instance[:private_ip].ljust(15)}  " +
             "#{instance[:ami].ljust(10)}  " +
             "#{instance[:type].ljust(10)}  " +
             "#{instance[:state].ljust(15)}  " +
             "#{instance[:launch_date].ljust(15)}"
      end
    end
  when :instances
    Skyline.instances.each do |i, instance|
      puts "   #{instance[:id].ljust(10)}  " +
           "#{instance[:public_ip].ljust(15)}  " +
           "#{instance[:private_ip].ljust(15)}  " +
           "#{instance[:ami].ljust(10)}  " +
           "#{instance[:type].ljust(10)}  " +
           "#{instance[:status].ljust(15)}  " +
           "#{instance[:launch_date].ljust(15)}"
    end
  else
    Skyline.as_groups.each { |name, group| puts name.to_s }
  end
  return
end

def selected
  puts Skyline.selected
end

def cmd(command)
  Skyline.cmd(command)
end

def icmd
  if Skyline.selected.nil?
    puts "ERROR: No AS Group selected. Please use"
    puts "the \"use\" command to select one."
    return nil
  end
  puts "Entering interactive remote-terminal mode."
  puts ""
  puts "All entered commands are executed on all remote"
  puts "instances within selected auto-scaling group."
  puts ""
  puts "Type \"exit\" \"halt\" or press CTRL+D to exit."
  puts ""
  while input = Readline.readline("irt$ ", true)
    if !input.nil? && input != ""
      if input =~ /^exit|halt$/
        break
      else
        cmd(input)
      end
    end
  end
end

def use
  groups = ["All"] + Skyline.as_groups.map { |name, group| name }
  valid_choice = false
  while !valid_choice
    puts "Please choose a group to use:"
    groups.each_with_index { |group, i| puts "#{i}. #{group}" }
    print "Enter your choice (0-9) or press Ctrl-C to abort: "
    s = STDIN.readline.strip
    s = (s =~ /^[\d]+$/) ? s.to_i : nil
    if !s.nil? && !groups[s].nil?
      valid_choice = true
      groups[0] = :all if s == 0
      puts groups[s].inspect
      return Skyline.use(groups[s])
    else
      puts "\nERROR: Not a valid choice\n\n"
    end
  end
end

def help_me
  cmds = [
    [:reload, "Force-reload instance and AutoScaling Group info."],
    [:list, <<-hd
List loaded information. Options are:
  :all            List AS Groups with instances.
  :instances      List all instances in your EC2 account.
hd
],
    [:use, "Call without any arguments to choose which AS Group to work with."],
    [:cmd, "Run a command on all selected remote machines."],
    [:icmd, "Enter an interactive shell which runs entered commands on selected remote machines."]
  ]
  puts "Available Skyline commands:"
  cmds.each do |cmd, desc|
    print "  #{cmd.to_s.ljust(10)}   "
    desc = desc.split("\n")
    if desc.size == 1
      puts desc[0]
    else
      puts desc.shift
      desc.each do |line|
        puts "                #{line}"
      end
    end
  end
  return
end

#
# Skyhook related commands
#

def skyhook(command)
  cmd("skyhook #{command}")
end

def update(project = nil, rev = nil)
  if project.nil?
    puts "Please specify a project."
    return
  end
  rev = rev.gsub(/[^0-9]/, "") if rev.is_a?(String)
  commands = [
    [ "skyhook update",
      "Updating Skyhook on remote machines..." ],
    [ "skyhook update.#{project} #{rev}",
      "Fetching latest files for #{project} project on remote machines..." ],
    [ "skyhook mode +maintenance",
      "Putting remote machines in maintenance mode..." ],
    [ "skyhook activate.#{project} #{rev}",
      "Activating newly fetched version of #{project} on remote machines..." ],
    [ "skyhook mode -maintenance",
      "Disabling maintenance mode on remote machines" ]
  ]
  commands.each do |command|
    puts command[1] if !command[1].nil?
    if !command[0].nil?
      puts "  Executing: #{command[0]}"
      cmd command[0]
    end
  end
  return
end


text:
namespace Gu.Units.Wpf.Proxies
{
    /// <summary>
    /// Proxy class for accessing units from xaml.
    /// </summary>
    public static class AmountOfSubstanceUnit
    {
        /// <summary>
        /// Gets the <see cref="Gu.Units.AmountOfSubstanceUnit.Moles"/> unit.
        /// </summary>
        public static Gu.Units.AmountOfSubstanceUnit Moles => Gu.Units.AmountOfSubstanceUnit.Moles;
    }
}


text:
'use strict';

// Root-only test cases
test.only('#Root-Suite, should run this qunit test-case #1', function() {
  expect(true, 'to be', true);
});

test('#Root-Suite, should not run this qunit test-case #2', function() {
  expect(false, 'to be', true);
});

test('#Root-Suite, should not run this qunit test-case #3', function() {
  expect(false, 'to be', true);
});


text:
package org.apache.shardingsphere.elasticjob.cloud.scheduler.state.failover;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.shardingsphere.elasticjob.cloud.scheduler.state.StateNode;
import org.apache.shardingsphere.elasticjob.infra.context.TaskContext.MetaInfo;

/**
 * Failover node.
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
final class FailoverNode {

    static final String ROOT = StateNode.ROOT + "/failover";

    private static final String FAILOVER_JOB = ROOT + "/%s";

    private static final String FAILOVER_TASK = FAILOVER_JOB + "/%s";

    static String getFailoverJobNodePath(final String jobName) {
        return String.format(FAILOVER_JOB, jobName);
    }

    static String getFailoverTaskNodePath(final String taskMetaInfo) {
        return String.format(FAILOVER_TASK, MetaInfo.from(taskMetaInfo).getJobName(), taskMetaInfo);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;

namespace resume.business.entities
{
    ///
    /// Types of email. For example:
    ///

    ///
Home

    ///
Office

    ///

    ///
    public class EmailType : EntityBase
    {
        ///
        /// Gets or sets the name of the email type.
        ///
        /// <value>
        /// The name.
        /// </value>
        [Display(Name = "Name")]
        [Required]
        [StringLength(20)]
        public String Name { get; set; }

        ///
        /// Gets or sets the French name of the email type.
        ///
        /// <value>
        /// The French name.
        /// </value>
        [Display(Name = "French name")]
        [Required]
        [StringLength(20)]
        public String NameFR { get; set; }
    }
}


text:
pid_t GraphViewer::procId = NULL;
#endif
short GraphViewer::port = 7772;

GraphViewer::GraphViewer(int width, int height, bool dynamic) {
	initialize(width, height, dynamic, GraphViewer::port);
	++GraphViewer::port;
}

GraphViewer::GraphViewer(int width, int height, bool dynamic, int port_n) {
	initialize(width, height, dynamic, port_n);
}

void GraphViewer::initialize(int width, int height, bool dynamic, int port_n) {
	this->width = width;
	this->height = height;
	this->isDynamic = dynamic;
	string command = "java -jar ";
	#ifdef PWD
		command += string(PWD) + "/";
	#endif
	command += "GraphViewerController.jar";
	std::stringstream ss;
	ss << port_n;
	string port_string = ss.str();
	command += " --port ";
	command += port_string;

#ifdef linux
	if (!(procId = fork())) {
		system(command.c_str());
		kill(getppid(), SIGINT);
		exit(0);
	}
	else {
		usleep(2000000);
		con = new Connection(port_n);

		char buff[200];
		sprintf(buff, "newGraph %d %d %s\n", width, height, (dynamic?"true":"false"));
		string str(buff);
		con->sendMsg(str);
	}
#else
	STARTUPINFO si;
	PROCESS_INFORMATION pi;
	ZeroMemory( &si, sizeof(si) );
	si.cb = sizeof(si);
	ZeroMemory( &pi, sizeof(pi) );
	LPSTR command_lpstr = const_cast<char *>(command.c_str());
	if( !CreateProcess( NULL,   // No module name (use command line)
			command_lpstr,        // Command line
			NULL,           // Process handle not inheritable
			NULL,           // Thread handle not inheritable
			FALSE,          // Set handle inheritance to FALSE
			0,              // No creation flags
			NULL,           // Use parent's environment block
			NULL,           // Use parent's starting directory
			&si,            // Pointer to STARTUPINFO structure
			&pi )           // Pointer to PROCESS_INFORMATION structure
	) {
		cerr << "CreateProcess failed " << GetLastError() << endl;
		return;
	}

	// Close process and thread handles.
	CloseHandle( pi.hProcess );
	CloseHandle( pi.hThread );

	Sleep(2000);
	con = new Connection(port_n);

	char buff[200];
	sprintf(buff, "newGraph %d %d %s\n", width, height, (dynamic?"true":"false"));
	string str(buff);
	con->sendMsg(str);
#endif

}

bool GraphViewer::createWindow(int width, int height) {
	char buff[200];
	sprintf(buff, "createWindow %d %d\n", width, height);
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::closeWindow() {
	char buff[200];
	sprintf(buff, "closeWindow\n");
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::addNode(int id) {
	if(!isDynamic) {
		cerr << "This graph is not dynamic,"
				"so you must use GraphViewer::addNode(int id, int x, int y) instead.\n"
				"The node " << id << " will be ignored" << endl;

		return false;
	}

	char buff[200];
	sprintf(buff, "addNode1 %d\n", id);
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::addNode(int id, int x, int y) {
	if(isDynamic) {
		cerr << "This graph is dynamic, "
				"so the provided x and y values for the node with id "
				<< id << " will be ignored" << endl;
	}

	char buff[200];
	sprintf(buff, "addNode3 %d %d %d\n", id, x, y);
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::addEdge(int id, int v1, int v2, int edgeType) {
	char buff[200];
	sprintf(buff, "addEdge %d %d %d %d\n", id, v1, v2, edgeType);
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::setEdgeLabel(int k, string label) {
	char buff[200];
	sprintf(buff, "setEdgeLabel %d %s\n", k, label.c_str());
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::clearEdgeLabel(int id) {
	char buff[200];
	sprintf(buff, "clearEdgeLabel %d\n", id);
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::setVertexLabel(int k, string label) {
	char buff[200];
	sprintf(buff, "setVertexLabel %d %s\n", k, label.c_str());
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::clearVertexLabel(int id) {
	char buff[200];
	sprintf(buff, "clearVertexLabel %d\n", id);
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::defineEdgeColor(string color) {
	char buff[200];
	sprintf(buff, "defineEdgeColor %s\n", color.c_str());
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::resetEdgeColor() {
	char buff[200];
	sprintf(buff, "resetEdgeColor\n");
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::removeNode(int id) {
	char buff[200];
	sprintf(buff, "removeNode %d\n", id);
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::removeEdge(int id) {
	char buff[200];
	sprintf(buff, "removeEdge %d\n", id);
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::setEdgeColor(int k, string color) {
	char buff[200];
	sprintf(buff, "setEdgeColor %d %s\n", k, color.c_str());
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::clearEdgeColor(int id) {
	char buff[200];
	sprintf(buff, "clearEdgeColor %d\n", id);
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::defineEdgeDashed(bool dashed) {
	char buff[200];
	sprintf(buff, "defineEdgeDashed %s\n", dashed? "true" : "false");
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::setEdgeDashed(int k, bool dashed) {
	char buff[200];
	sprintf(buff, "setEdgeDashed %d %s\n", k, dashed? "true" : "false");
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::defineEdgeCurved(bool curved) {
	char buff[200];
	sprintf(buff, "defineEdgeCurved %s\n", curved? "true" : "false");
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::setEdgeThickness(int k, int thickness) {
	char buff[200];
	sprintf(buff, "setEdgeThickness %d %d\n", k, thickness);
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::defineVertexColor(string color) {
	char buff[200];
	sprintf(buff, "defineVertexColor %s\n", color.c_str());
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::resetVertexColor() {
	char buff[200];
	sprintf(buff, "resetVertexColor\n");
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::setVertexColor(int k, string color) {
	char buff[200];
	sprintf(buff, "setVertexColor %d %s\n", k, color.c_str());
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::clearVertexColor(int id) {
	char buff[200];
	sprintf(buff, "clearVertexColor %d\n", id);
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::defineVertexIcon(string filepath) {
	char buff[200];
	sprintf(buff, "defineVertexIcon %s\n", filepath.c_str());
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::resetVertexIcon() {
	char buff[200];
	sprintf(buff, "resetVertexIcon\n");
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::setVertexIcon(int k, string filepath) {
	char buff[200];
	sprintf(buff, "setVertexIcon %d %s\n", k, filepath.c_str());
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::clearVertexIcon(int id) {
	char buff[200];
	sprintf(buff, "clearVertexIcon %d\n", id);
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::defineVertexSize(int size) {
	char buff[200];
	sprintf(buff, "defineVertexSize %d\n", size);
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::setVertexSize(int k, int size) {
	char buff[200];
	sprintf(buff, "setVertexSize %d %d\n", k, size);
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::setBackground(string path) {
	char buff[200];
	sprintf(buff, "setBackground %s\n", path.c_str());
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::clearBackground() {
	char buff[200];
	sprintf(buff, "clearBackground\n");
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::setEdgeWeight(int id, int weight) {
	char buff[200];
	sprintf(buff, "setEdgeWeight %d %d\n", id, weight);
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::setEdgeFlow(int id, int flow) {
	char buff[200];
	sprintf(buff, "setEdgeFlow %d %d\n", id, flow);
	string str(buff);
	return con->sendMsg(str);
}

bool GraphViewer::rearrange() {
	return con->sendMsg("rearrange\n");
}


text:
package org.onosproject.store.primitives.resources.impl;

import io.atomix.protocols.raft.event.EventType;
import org.onlab.util.KryoNamespace;
import org.onosproject.store.serializers.KryoNamespaces;
import org.onosproject.store.service.DocumentTreeEvent;

/**
 * Atomix document tree events.
 */
public enum AtomixDocumentTreeEvents implements EventType {
    CHANGE;

    @Override
    public String id() {
        return name();
    }

    public static final KryoNamespace NAMESPACE = KryoNamespace.newBuilder()
            .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID + 50)
            .register(DocumentTreeEvent.class)
            .register(DocumentTreeEvent.Type.class)
            .build("AtomixDocumentTreeEvents");
}


text:
<?php

namespace Illuminate\Tests\Support;

use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Support\Js;
use JsonSerializable;
use PHPUnit\Framework\TestCase;

class SupportJsTest extends TestCase
{
    public function testScalars()
    {
        $this->assertEquals('false', (string) Js::from(false));
        $this->assertEquals('true', (string) Js::from(true));
        $this->assertEquals('1', (string) Js::from(1));
        $this->assertEquals('1.1', (string) Js::from(1.1));
        $this->assertEquals(
            "'\\u003Cdiv class=\\u0022foo\\u0022\\u003E\\u0027quoted html\\u0027\\u003C\\/div\\u003E'",
            (string) Js::from('
\'quoted html\'
')
        );
    }

    public function testArrays()
    {
        $this->assertEquals(
            "JSON.parse('[\\u0022hello\\u0022,\\u0022world\\u0022]')",
            (string) Js::from(['hello', 'world'])
        );

        $this->assertEquals(
            "JSON.parse('{\\u0022foo\\u0022:\\u0022hello\\u0022,\\u0022bar\\u0022:\\u0022world\\u0022}')",
            (string) Js::from(['foo' => 'hello', 'bar' => 'world'])
        );
    }

    public function testObjects()
    {
        $this->assertEquals(
            "JSON.parse('{\\u0022foo\\u0022:\\u0022hello\\u0022,\\u0022bar\\u0022:\\u0022world\\u0022}')",
            (string) Js::from((object) ['foo' => 'hello', 'bar' => 'world'])
        );
    }

    public function testJsonSerializable()
    {
        // JsonSerializable should take precedence over Arrayable, so we'll
        // implement both and make sure the correct data is used.
        $data = new class() implements JsonSerializable, Arrayable
        {
            public $foo = 'not hello';

            public $bar = 'not world';

            public function jsonSerialize()
            {
                return ['foo' => 'hello', 'bar' => 'world'];
            }

            public function toArray()
            {
                return ['foo' => 'not hello', 'bar' => 'not world'];
            }
        };

        $this->assertEquals(
            "JSON.parse('{\\u0022foo\\u0022:\\u0022hello\\u0022,\\u0022bar\\u0022:\\u0022world\\u0022}')",
            (string) Js::from($data)
        );
    }

    public function testJsonable()
    {
        // Jsonable should take precedence over JsonSerializable and Arrayable, so we'll
        // implement all three and make sure the correct data is used.
        $data = new class() implements Jsonable, JsonSerializable, Arrayable
        {
            public $foo = 'not hello';

            public $bar = 'not world';

            public function toJson($options = 0)
            {
                return json_encode(['foo' => 'hello', 'bar' => 'world'], $options);
            }

            public function jsonSerialize()
            {
                return ['foo' => 'not hello', 'bar' => 'not world'];
            }

            public function toArray()
            {
                return ['foo' => 'not hello', 'bar' => 'not world'];
            }
        };

        $this->assertEquals(
            "JSON.parse('{\\u0022foo\\u0022:\\u0022hello\\u0022,\\u0022bar\\u0022:\\u0022world\\u0022}')",
            (string) Js::from($data)
        );
    }

    public function testArrayable()
    {
        $data = new class() implements Arrayable
        {
            public $foo = 'not hello';

            public $bar = 'not world';

            public function toArray()
            {
                return ['foo' => 'hello', 'bar' => 'world'];
            }
        };

        $this->assertEquals(
            "JSON.parse('{\\u0022foo\\u0022:\\u0022hello\\u0022,\\u0022bar\\u0022:\\u0022world\\u0022}')",
            (string) Js::from($data)
        );
    }
}


text:
#include "tensorflow/compiler/xla/service/hlo_ordering.h"

#include <utility>
#include <vector>

#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/logging.h"

namespace xla {

bool HloOrdering::ExecutesBefore(const HloInstruction* a,
                                 const HloInstruction* b) const {
  // 'a' and 'b' may be in different computations. In this case, find the
  // callgraph ancestor instructions which call (potentially transitively) the
  // computations containing 'a' and 'b' and use these ancestor instructions to
  // compare order.
  const HloInstruction* a_ancestor;
  const HloInstruction* b_ancestor;
  std::tie(a_ancestor, b_ancestor) =
      call_graph_->NearestAncestorsInSameComputation(
          const_cast<HloInstruction*>(a), const_cast<HloInstruction*>(b));

  if (a_ancestor == nullptr) {
    // Ancestors in a common computation could not be found so consider the
    // instructions 'a' and 'b' to be unordered.
    return false;
  }
  // a_ancestor and b_ancestor must be either both null or both non-null.
  CHECK_NE(b_ancestor, nullptr);
  CHECK_EQ(a_ancestor->parent(), b_ancestor->parent());

  // If the common ancestor is a while instruction there is an additional
  // ordering criteria which may apply. The condition computation is considered
  // to execute before the body computation so if 'a' is in the condition and
  // 'b' is in the body, then 'a' executes before 'b'.
  if (a_ancestor == b_ancestor && a_ancestor->opcode() == HloOpcode::kWhile) {
    const HloComputation* body = a_ancestor->while_body();
    const HloComputation* condition = a_ancestor->while_condition();
    if (call_graph_->InstructionIsNestedIn(a, condition) &&
        call_graph_->InstructionIsNestedIn(b, body)) {
      return true;
    }
  }

  // If the common ancestor is a conditional instruction, even though the true
  // and false computations are not really ordered per-se, we define the true
  // computation to be ordered before the false one.
  // This ensures that buffers can still be shared among the two computations
  // as they will forcibly have disjoint liveness.
  if (a_ancestor == b_ancestor &&
      a_ancestor->opcode() == HloOpcode::kConditional) {
    const HloComputation* true_computation = a_ancestor->true_computation();
    const HloComputation* false_computation = a_ancestor->false_computation();
    if (call_graph_->InstructionIsNestedIn(a, true_computation) &&
        call_graph_->InstructionIsNestedIn(b, false_computation)) {
      return true;
    }
    // If 'b' is the conditional ancestor, and 'a' is within the true or false
    // computations, 'a' executes before 'b'.
    if (b == a_ancestor &&
        (call_graph_->InstructionIsNestedIn(a, true_computation) ||
         call_graph_->InstructionIsNestedIn(a, false_computation))) {
      return true;
    }
  }

  return ExecutesBeforeInSameComputation(a_ancestor, b_ancestor);
}

bool HloOrdering::IsDefinedBefore(const HloValue& a, const HloValue& b) const {
  // Entry parameter should always be defined before other instructions.
  const HloModule* module = b.defining_instruction()->parent()->parent();
  if (b.defining_instruction()->parent() == module->entry_computation() &&
      b.defining_instruction()->opcode() == HloOpcode::kParameter) {
    return false;
  }

  if (a.defining_instruction()->parent() == module->entry_computation() &&
      a.defining_instruction()->opcode() == HloOpcode::kParameter) {
    return true;
  }

  // Phi values require special handling. Because XLA does not have a phi
  // instruction, the definition instruction of the phis values are
  // placeholders: either the subcomputation parameter (body or condition) or
  // the while instruction. However, the program point where these values are
  // logically defined does not necessarily coincide exactly with program point
  // of these place-holder instructions. So we explicitly define the following
  // order for phi values:
  //
  //   body/condition parameter phi:
  //     Defined before all values defined in its computation excepting other
  //     phis.
  //
  //   while phi:
  //     defined after all values defined in the condition or body.
  //
  auto is_body_or_condition_phi = [](const HloValue& v) {
    return v.is_phi() &&
           v.defining_instruction()->opcode() == HloOpcode::kParameter;
  };
  if (is_body_or_condition_phi(a) && !is_body_or_condition_phi(b) &&
      call_graph_->InstructionIsNestedIn(b.defining_instruction(),
                                         a.defining_instruction()->parent())) {
    return true;
  }
  if (is_body_or_condition_phi(b) &&
      call_graph_->InstructionIsNestedIn(a.defining_instruction(),
                                         b.defining_instruction()->parent())) {
    return false;
  }

  // If 'b' is a while phi and 'a' is in the body or condition, then 'a'
  // executes before 'b'.
  if (b.is_phi() && b.defining_instruction()->opcode() == HloOpcode::kWhile &&
      (call_graph_->InstructionIsNestedIn(
           a.defining_instruction(), b.defining_instruction()->while_body()) ||
       call_graph_->InstructionIsNestedIn(
           a.defining_instruction(),
           b.defining_instruction()->while_condition()))) {
    return true;
  }
  // If 'b' is a conditional phi and 'a' is in the true or false computation,
  // then 'a' executes before 'b'.
  if (b.is_phi() &&
      b.defining_instruction()->opcode() == HloOpcode::kConditional &&
      (call_graph_->InstructionIsNestedIn(
           a.defining_instruction(),
           b.defining_instruction()->true_computation()) ||
       call_graph_->InstructionIsNestedIn(
           a.defining_instruction(),
           b.defining_instruction()->false_computation()))) {
    return true;
  }
  return ExecutesBefore(a.defining_instruction(), b.defining_instruction());
}

/* static */
bool HloOrdering::UseIsBeforeValueDefinition(
    const HloUse& use, const HloValue& value,
    const HloDataflowAnalysis& dataflow) const {
  VLOG(4) << "UseIsBeforeValueDefinition(use=" << use
          << ", value=" << value.ToShortString() << ")";
  if (ExecutesBefore(use.instruction, value.defining_instruction())) {
    VLOG(4) << "  use instruction executes before value-defining instruction";
    return true;
  }

  // If the use is at the instruction where the value is defined, then the use
  // is before the def if the instruction allows buffer sharing (in place
  // computation).
  if (use.instruction == value.defining_instruction() &&
      dataflow.CanShareOperandBufferWithUser(
          use.instruction->mutable_operand(use.operand_number),
          use.operand_index, value.defining_instruction(),
          value.defining_index())) {
    VLOG(4) << "  use is value def, and instruction can share use buffer";
    return true;
  }

  // The use at a while is an input to a phi, and logically occurs before values
  // are defined in the body or condition computations.
  if (use.instruction->opcode() == HloOpcode::kWhile) {
    const HloInstruction* xla_while = use.instruction;
    if (call_graph_->InstructionIsNestedIn(value.defining_instruction(),
                                           xla_while->while_body()) ||
        call_graph_->InstructionIsNestedIn(value.defining_instruction(),
                                           xla_while->while_condition())) {
      VLOG(4) << "  use is while " << use.instruction->name()
              << " and def is in condition or body";
      return true;
    }
  }

  // Similarly if the value is defined at a while, it logically occurs after any
  // uses in the body or condition computations.
  if (value.defining_instruction()->opcode() == HloOpcode::kWhile) {
    CHECK(value.is_phi());
    const HloInstruction* xla_while = value.defining_instruction();
    if (call_graph_->InstructionIsNestedIn(use.instruction,
                                           xla_while->while_body()) ||
        call_graph_->InstructionIsNestedIn(use.instruction,
                                           xla_while->while_condition())) {
      VLOG(4) << "  value is while " << value.defining_instruction()->name()
              << " and use is in condition or body";
      return true;
    }
  }

  // The use at a call occurs before values that are defined in the called
  // computation.
  if (use.instruction->opcode() == HloOpcode::kCall) {
    const HloInstruction* call = use.instruction;
    if (call_graph_->InstructionIsNestedIn(value.defining_instruction(),
                                           call->to_apply())) {
      VLOG(4) << "  use is call " << use.instruction->name()
              << " and def is in called computation";
      return true;
    }
  }

  if (use.instruction->opcode() == HloOpcode::kConditional) {
    const HloInstruction* conditional = use.instruction;
    if (call_graph_->InstructionIsNestedIn(value.defining_instruction(),
                                           conditional->true_computation())) {
      VLOG(4) << "  use is conditional " << use.instruction->name()
              << " and def is in TRUE computation";
      return true;
    }
    if (call_graph_->InstructionIsNestedIn(value.defining_instruction(),
                                           conditional->false_computation())) {
      VLOG(4) << "  use is conditional " << use.instruction->name()
              << " and def is in FALSE computation";
      return true;
    }
    if (value.defining_instruction() == use.instruction) {
      VLOG(4) << "  use is conditional " << use << " and def is "
              << value.ToShortString();
      return true;
    }
  }

  VLOG(4) << "  use is not before value";
  return false;
}

bool HloOrdering::LiveRangeStrictlyBefore(
    const HloValue& a, const HloValue& b,
    const HloDataflowAnalysis& dataflow) const {
  VLOG(4) << "LiveRangeStrictlyBefore(a = " << a.ToShortString()
          << ", b = " << b.ToShortString() << ")";
  if (!IsDefinedBefore(a, b)) {
    VLOG(4) << a << " not defined before " << b;
    return false;
  }

  if (a.live_out_of_module()) {
    VLOG(4) << a << " is live out of module and defined before " << b;
    return false;
  }

  // All uses of 'a' must be before 'b' is defined.
  for (const HloUse& use : a.uses()) {
    if (dataflow.DoesNotUseOperandBuffer(a.instruction(), a.index(),
                                         use.instruction)) {
      continue;
    }
    if (!UseIsBeforeValueDefinition(use, b, dataflow)) {
      VLOG(4) << "use of " << a << " (" << use << ") not before " << b
              << " is defined";
      return false;
    }
  }

  if (a.instruction()->parent() == b.instruction()->parent()) {
    for (const HloPosition& position : a.positions()) {
      if (position.instruction ==
          a.instruction()->parent()->root_instruction()) {
        VLOG(4) << a << " is live out of computation and defined before " << b
                << " which is in same computation";
        return false;
      }
    }
  }

  return true;
}

bool HloOrdering::MayInterfere(const HloValue& a, const HloValue& b,
                               const HloDataflowAnalysis& dataflow) const {
  // Buffers without disjoint liveness may interfere.
  return !LiveRangeStrictlyBefore(a, b, dataflow) &&
         !LiveRangeStrictlyBefore(b, a, dataflow);
}

PredecessorHloOrdering::PredecessorHloOrdering(const HloModule* module)
    : HloOrdering(module) {}

bool PredecessorHloOrdering::ExecutesBeforeInSameComputation(
    const HloInstruction* a, const HloInstruction* b) const {
  CHECK_EQ(a->parent(), b->parent());

  // 'a' executes before 'b' if 'a' is in the strict predecessor set of 'b'.
  return a != b && predecessors_.at(a->parent())->IsReachable(a, b);
}

string PredecessorHloOrdering::ToStringHelper(const string& name) const {
  std::vector<string> pieces;
  pieces.push_back(name);
  for (auto* computation : module_->MakeNonfusionComputations()) {
    pieces.push_back(absl::StrFormat("computation %s:", computation->name()));
    const auto all = computation->MakeInstructionPostOrder();
    for (auto instruction : all) {
      pieces.push_back(
          absl::StrFormat("  %s predecessors:", instruction->name()));
      for (auto predecessor : all) {
        if (predecessors_.at(computation)
                ->IsReachable(predecessor, instruction)) {
          pieces.push_back(absl::StrFormat("    %s", predecessor->name()));
        }
      }
    }
  }
  return absl::StrJoin(pieces, "\n");
}

DependencyHloOrdering::DependencyHloOrdering(const HloModule* module)
    : PredecessorHloOrdering(module) {
  // Compute predecessor relationships between all instructions to determine
  // ordering based on dependencies. ExecutesBefore will return true iff there
  // exists a path in the HLO computation graph from 'a' to 'b'.
  for (auto* computation : module->MakeNonfusionComputations()) {
    predecessors_.emplace(computation, HloReachabilityMap::Build(computation));
  }
}

string DependencyHloOrdering::ToString() const {
  return ToStringHelper("DependencyHloOrdering");
}

SequentialHloOrdering::SequentialHloOrdering(const HloSchedule& schedule)
    : HloOrdering(schedule.module()), schedule_(schedule) {
  Initialize();
}

SequentialHloOrdering::SequentialHloOrdering(HloSchedule&& schedule)
    : HloOrdering(schedule.module()), schedule_(std::move(schedule)) {
  Initialize();
}

void SequentialHloOrdering::Initialize() {
  // Create a map from instruction to its order position.
  TF_DCHECK_OK(schedule_.Verify());
  for (const auto& computation_sequence : schedule_.sequences()) {
    const auto& order = computation_sequence.second.instructions();
    for (int i = 0; i < order.size(); ++i) {
      InsertOrDie(&order_position_, order[i], i);
    }
  }
}

bool SequentialHloOrdering::ExecutesBeforeInSameComputation(
    const HloInstruction* a, const HloInstruction* b) const {
  CHECK_EQ(a->parent(), b->parent());
  // If either instruction is not in the order, then 'a' and 'b' are unordered.
  if (!order_position_.contains(a) || !order_position_.contains(b)) {
    return false;
  }
  return order_position_.at(a) < order_position_.at(b);
}

const HloInstructionSequence* SequentialHloOrdering::SequentialOrder(
    const HloComputation& computation) const {
  return schedule_.is_computation_scheduled(&computation)
             ? &schedule_.sequence(&computation)
             : nullptr;
}

string SequentialHloOrdering::ToString() const {
  return absl::StrCat("SequentialHloOrdering\n", schedule_.ToString());
}

}  // namespace xla


text:
package restore

import (
	"sort"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	rbac "k8s.io/api/rbac/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime"

	api "github.com/vmware-tanzu/velero/pkg/apis/velero/v1"
	"github.com/vmware-tanzu/velero/pkg/plugin/velero"
	"github.com/vmware-tanzu/velero/pkg/test"
)

func TestClusterRoleBindingActionAppliesTo(t *testing.T) {
	action := NewClusterRoleBindingAction(test.NewLogger())
	actual, err := action.AppliesTo()
	require.NoError(t, err)
	assert.Equal(t, velero.ResourceSelector{IncludedResources: []string{"clusterrolebindings"}}, actual)
}

func TestClusterRoleBindingActionExecute(t *testing.T) {
	tests := []struct {
		name             string
		namespaces       []string
		namespaceMapping map[string]string
		expected         []string
	}{
		{
			name:             "namespace mapping disabled",
			namespaces:       []string{"foo"},
			namespaceMapping: map[string]string{},
			expected:         []string{"foo"},
		},
		{
			name:             "namespace mapping enabled",
			namespaces:       []string{"foo"},
			namespaceMapping: map[string]string{"foo": "bar", "fizz": "buzz"},
			expected:         []string{"bar"},
		},
		{
			name:             "namespace mapping enabled, not included namespace remains unchanged",
			namespaces:       []string{"foo", "xyz"},
			namespaceMapping: map[string]string{"foo": "bar", "fizz": "buzz"},
			expected:         []string{"bar", "xyz"},
		},
		{
			name:             "namespace mapping enabled, not included namespace remains unchanged",
			namespaces:       []string{"foo", "xyz"},
			namespaceMapping: map[string]string{"a": "b", "c": "d"},
			expected:         []string{"foo", "xyz"},
		},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			subjects := []rbac.Subject{}

			for _, ns := range tc.namespaces {
				subjects = append(subjects, rbac.Subject{
					Namespace: ns,
				})
			}

			clusterRoleBinding := rbac.ClusterRoleBinding{
				Subjects: subjects,
			}

			roleBindingUnstructured, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&clusterRoleBinding)
			require.NoError(t, err)

			action := NewClusterRoleBindingAction(test.NewLogger())
			res, err := action.Execute(&velero.RestoreItemActionExecuteInput{
				Item:           &unstructured.Unstructured{Object: roleBindingUnstructured},
				ItemFromBackup: &unstructured.Unstructured{Object: roleBindingUnstructured},
				Restore: &api.Restore{
					Spec: api.RestoreSpec{
						NamespaceMapping: tc.namespaceMapping,
					},
				},
			})
			require.NoError(t, err)

			var resClusterRoleBinding *rbac.ClusterRoleBinding
			err = runtime.DefaultUnstructuredConverter.FromUnstructured(res.UpdatedItem.UnstructuredContent(), &resClusterRoleBinding)
			require.NoError(t, err)

			actual := []string{}
			for _, subject := range resClusterRoleBinding.Subjects {
				actual = append(actual, subject.Namespace)
			}

			sort.Strings(tc.expected)
			sort.Strings(actual)

			assert.Equal(t, tc.expected, actual)
		})
	}
}


text:
\documentclass[12pt]{article}
\author{Daniel Bruckner}
\title{Data Tamer System Documentation}
\date{June 2012}

\usepackage{hyperref}

\usepackage[parfill]{parskip}

\begin{document}

\maketitle
\tableofcontents

\raggedright

\section{Setup and Installation}

\subsection{Hardware}

Mostly depends on how much data you have.  Data Tamer especially likes more memory and more disks -- it tends to be space hungry because it maintains it's own copy of the data it analyzes.  At the moment, it runs as single-core.

\subsection{Required Software}

Data Tamer relies on a few software systems to run.  Here's the short story:

\begin{itemize}
\item Your favorite Linux distribution (Ubuntu 10.10 and later, and RHEL5 have been used successfully)
\item PostgreSQL 8.4 or later
\item Python 2.6 or later
\item Django 1.2 or later
\item (optional) Apache 2.2 or other web server
\item (optional) MADlib 0.3 (a PostgreSQL library)
\end{itemize}

The somewhat longer story is that Data Tamer is primarily a database application coded for PostgreSQL running on Linux, with a Django web front end.  It hasn't been tested on Postgres earlier than 8.4 or Django earlier than 1.2.  It cannot run on Python earlier than 2.6, and mostly it's been run with 2.7.  Django comes with a built-in web server that is suitable for development and small demos, but for production it should be run through a real web server.

All of these systems should be available as binary packages on most Linux distros.  On some Linux distros (e.g. RHEL5) the default Python package is less than 2.6.  In this case, you may have do some manual installation from source.  Source packages for all these systems are easy to find on the web.  Python should be compiled with the enable-shared-libs flag given to the configure command.  Be sure to install Django with the proper version of Python (2.6+).

Postgres also uses Python as a procedural language through the plpythonu library.  This library can be added to a database with the SQL command \texttt{CREATE LANGUAGE plpythonu;}.  If Postgres was installed with a version of Python less than 2.6, you need to create the plpython shared library for a later version of Python.  To do this, compile Postgres from source with the \texttt{--with-python} and \texttt{PYTHON=/path/to/python2.6+} flags passed to configure.  After running make, there's no need to install, just move the new plpython2.so to Postgres's lib directory.  Detailed instructions can be found at \url{http://stackoverflow.com/questions/5921664/how-to-change-python-version-used-by-plpython-on-mac-osx}.

MADlib is a library for running machine learning algorithms inside of Postgres.  We've experimented with it in Data Tamer, but it is not currently used by the core system.  Binary and source packages, as well as installation instructions and documentation, can be found at madlib.net.

\subsection{Software Configuration}

Clean installs of Postgres should be configured to take advantage of available resources -- the default configuration allocates something like 32KB for the buffer pool.  Some quick tips are set shared\_buffers to 1/4 available memory, set effective\_cache\_size to 1/2 to 3/4 available memory, set working\_mem to a few hundred MB.  Configuration variables are found in postgres.conf.  A detailed discussion of tuning Postgres can be found at \url{http://wiki.postgresql.org/wiki/Tuning\_Your\_PostgreSQL\_Server}

\subsection{Installing Data Tamer}

At the moment, Data Tamer is just a collection of scripts.  To install, get a copy of the source tree (from github.com/bruckner/doit or elsewhere), and put it in some directory that we'll call \texttt{\$DTHOME}.  A shell script installs Data Tamer in Postgres:

run \texttt{\$DTHOME/init database-name}

to install.  The init script should be run by an OS user with a linked (ident authentication, i.e., same name) Postgres super-user account.  It installs into this user's default schema, which can be set by:

\texttt{ALTER USER mypgname SET search\_path = myschema;}

The schema should be empty before an install.  \texttt{init} will print errors to the terminal, and a complete log is written to \texttt{\$DTHOME/init.out}.

The Django application can be found in \texttt{\$DTHOME/www}.  Most likely, it will need some configuration to run.  The settings file can be found at \texttt{\$DTHOME/www/doitweb/settings.py}.  Settings that may need modification include \texttt{DATABASES}, the database connection parameters; \texttt{TEMPLATE\_DIRS}, should include \texttt{\$DTHOME/www/templates/}.

The web server will also have to handle serving static files from \texttt{\$DTHOME/www/static}.  The web server can either serve these files directly or let Django do it (when using the Django built-in server, only the latter is possible).  If Django will be serving the static files, make sure settings.py contains the following:

\begin{verbatim}
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    '/usca/home/bruckda1/doit/www/static/',
)
\end{verbatim}

and that \texttt{INSTALLED\_APPS} includes \texttt{'django.contrib.staticfiles'}.

\section{Using Data Tamer}

\subsection{Importing Data}

At the moment, loading data into Data Tamer is mostly a manual process.  Data assetes that can be loaded are:

\begin{enumerate}
\item Data sources to analyze
\item Global schema information
\item Training data, e.g., attribute mappings and entity clusterings
\item Auxiliary tables like dictionaries and templates
\end{enumerate}

For all of these, the procedure is to load a table into the Postgres public schema (or some other non-Data Tamer schema) from CSV.  Then, write queries to copy data to the appropriate Data Tamer schema.  The relevant tables will be enumerated below; detailed information about them can be found in the section on Data Tamer internals.

\subsubsection{Data Sources}

Data sources are the data sets that Data Tamer is meant to clean and integrate.  Data tamer stores information about these sources in four tables: \texttt{local\_sources, local\_fields, local\_entities,} and \texttt{local\_data}.  (Definitions of all four can be found in \texttt{\$DTHOME/core.sql}.)

If you consider a data source as a table, then \texttt{local\_sources} keeps information about the table as a whole, \texttt{local\_fields} about its columns, \texttt{local\_entities} about its rows, and \texttt{local\_data} about each of its non-null cell values.  Sources, fields, and entities each have an integer ID that is used as a foreign key and  that can either be serially generated by Postgres, or set via some external ID, as long as it's globally unique.

Additional meta data about sources and columns can be stored in \texttt{local\_source\_meta} and \texttt{local\_field\_meta}.

\subsubsection{Global Schema}

Attributes in the global schema are stored in the table \texttt{global\_attributes} (defined in \texttt{\$DTHOME/core.sql}).  This table has an integer ID column that acts as a foreign key.  This can be assigned automatically in serial by Postgres, or set manually from an external unique ID.  External IDs can also be saved in the \texttt{external\_id} field.

\subsubsection{Training Data}

Data Tamer uses training data for its schema mapping model and for its entity resolution model.

Training for the schema mapper is pairs of local and global fields, and should be loaded into the \texttt{attribute\_mappings} table (\texttt{\$DTHOME/core.sql}).  This table has fields for local and globals IDs that reference \texttt{local\_fields} and \texttt{global\_attributes} tables respectively.  It also has fields for the confidence and authority of mappings (1.0 = perfect) and for provenance (who, when, why) information.

Training for entity resolution is pairs of local entity IDs that are duplicates.  These IDs should reference the \texttt{local\_entities} table and be loaded into the \texttt{entity\_matches} table (\texttt{\$DTHOME/entity.sql}).

\subsubsection{Dictionaries and Templates}

Attribute dictionaries should be loaded into the \texttt{global\_data} table, and synonym dictionaries into the \texttt{global\_synonyms} table -- both these tables are defined in \texttt{\$DTHOME/core.sql} and both reference the \texttt{global\_attributes} table.

Attribute templates should be named in the \texttt{templates} table, and their contents specified in the \texttt{attribute\_templates}, which references \texttt{templates} and \texttt{global\_attributes}.  These tables are defined in \texttt{\$DTHOME/nameres/template.sql}, which is not currently loaded by the install script.

\subsubsection{Clean-up}

If at any time you would like to purge Data Tamer and start afresh, two functions are provided for clean-up.  The first, \texttt{unload\_local()}, clears out all data sources that have been loaded into the system, as well as all preprocessed data kept by the schema mapping experts that was derived from these sources.  The second, \texttt{clean\_house()}, clears both local and global data, i.e., it clears global schema, attribute mappings, and global dictionaries in addition to the loaded data sources.  This should accomplish the same effect as dropping the Data Tamer schema and reinstalling from scratch.

\subsection{Schema Mapping}

Schema mapping generates suggested mappings from fields in local data sources (in \texttt{local\_fields}) to fields in the global schema (\texttt{global\_attributes}).  Several expert algorithms give suggestion scores and a meta model combines the expert opinions into final scores.

Schema mapping operations include local preprocessing, global preprocessing, and computing results.

Local preprocessing includes tasks like tokenization and computation of weights and frequencies that are used by the expert algorithms.  It only has to be run once for each local data source.  The function \texttt{preprocess\_source( source\_id )}, defined in \texttt{core.sql}, performs all preprocessing for a given source.  Many variants are available, including preprocessing for only individual experts (via \texttt{mdl\_, ngrams\_, qgrams\_}, and \texttt{dist\_preprocess\_source( source\_id )}), and preprocessing for different groups of data (e.g., \texttt{\_field( field\_id ), \_all()}).

Global preprocessing uses the mappings in the \texttt{attribute\_mappings} table to train the various expert models.  The function \texttt{preprocess\_global()} builds each expert model from scratch based on the available attribtue mappings at the time it is run.  Individual expert models can be built by running \texttt{mdl\_, ngrams\_, qgrams\_}, and \texttt{dist\_preprocess\_global()}.  For the moment, these models cannot be updated incrementally as new mappings are added to the system.  Global preprocessing should be run after all local preprocessing is finished, and whenever the experts need to be ``current.''

After local data has been preprocessed, and the expert models are up to date, mapping suggestions can be computed by running \texttt{nr\_results\_for\_all()} or \texttt{nr\_results\_for\_all\_unmapped()} or \texttt{nr\_results\_for\_source( source\_id )}.  These functions are defined in \texttt{\$DTHOME/nameres/name\_resolve.sql}.  Results from individual experts can be obtained by a parallel set of functions whose names replace \texttt{nr} with the appropriate expert name, one of \texttt{mdl, ngrams, qgrams}, or \texttt{diff}.  Results are stored in the \texttt{nr\_raw\_results} table.

Composite scores are computed by running the \texttt{nr\_composite\_load()} function.  These composite results are based on the individual scores stored in \texttt{nr\_raw\_results}, and themselves are written to \texttt{nr\_ncomp\_results\_tbl} (old results are cleared before new ones are loaded).  These composite results are used by the web interface.

\subsection{Entity Resolution}

The entity resolution module is currently in transition, and its operational API is changing frequently.  To be filled in by George B....

An old test module for entity resolution can be found in \texttt{\$DTHOME/entityres/old.sql}.  This module allows simple ER operation on a small test data set, and its use is well documented in the file.

\subsection{Web Interface}

Once Django is set up with the desired web server, the Data Tamer web UI will be available at \url{http://local IP/doit/database name/}, where ``local IP'' is the domain or IP address of the host server, and ``database name'' is the name of the PostgreSQL database to which Data Tamer was installed.

If using the Django developer server to host the UI (strongly discouraged in production), then the server can be launched by entering the root directory of the Data Tamer Django application (\texttt{\$DTHOME/www/doitweb/}) and running the command \texttt{python manage.py runserver IP:port}.  You may want to run the Django server in the backgroup or in a separate shell session, e.g., using \texttt{screen}.

The main interface provides an index of loaded sources.  Clicking on a source brings the user to a review interface for schema mapping suggestions, where the user can fix and verify mapping suggestions and save them to the database.  On the index page, there is also a search box that allows the user to search for local fields by name.  The results page is again a schema mapping review interface.

\section{Data Tamer Internals --- the Core Schema}

The core Data Tamer tables cover three main categories of objects: \textit{i}. local data objects, i.e., local data sources and their components; \textit{ii}. global data objects, e.g., the global schema and dictionary objects; and \textit{iii}. mappings between local and global objects.

\subsection{Local Data Objects}

Data sources that are ingested by Data Tamer to be cleaned and integrated are called local data sources.  Data Tamer operates on data sources that can be modelled as sparse relational tables, i.e., a table that may contain a large number of null values.  Six tables store information about the local sources loaded into the system.

\begin{itemize}

\item \texttt{local\_sources}

This table gives each loaded data source a unique internal ID (column \texttt{id}), and can save an external name or ID as well (column \texttt{local\_id}).  It also has columns for the date each source was loaded, and for the number of unique entities (i.e. rows) belonging to the source.

\item \texttt{local\_fields}

This table holds information about individual columns of the loaded sources.  The \texttt{id} column is the primary key, and \texttt{source\_id} is a foreign key reference to \texttt{local\_sources}.  The three local columns, \texttt{local\_id, local\_name}, and \texttt{local\_desc}, contain external IDs, names, and descriptions, respectively, that belong to the fields.  The remaining fields keep statistics used to inform the proper display order when viewing the fields in tabular form.

\item \texttt{local\_source\_meta} and \texttt{local\_field\_meta}

These tables store arbitrary key-value property pairs that provide meta data about sources and their fields, respectively.

\item \texttt{local\_entities}

As \texttt{local\_fields} stores information about the columns of a source, \texttt{local\_entities} stores information about its rows.  It has a primary key, \texttt{id}, and a foreign key reference to its source in \texttt{local\_sources}, \texttt{source\_id}.

\item \texttt{local\_data}

The actual source data is stored in this table.  Each record is the value contained in one cell of the source table.  The columns \texttt{field\_id} and \texttt{entity\_id} are foreign key references to the cell's column and row in \texttt{local\_fields} and \texttt{local\_entities}, respectively.  The column \texttt{value} stores a string representation of the cell value.  All imported data is stored as text, though some algorithms detect and use other data types.

\end{itemize}

\subsection{Global Data Objects}

Global objects include the global schema definition and dictionary objects.  At the moment, the global schema is flat, and all global attributes belong to a single relation.

\begin{itemize}

\item \texttt{global\_attributes}

This table defines the attributes of the global schema.  Each attribute has a unique ID, \texttt{id}, and a name, \texttt{name}, and optionally an ID from an external application in the \texttt{external\_id} column.  The column \texttt{derived\_from} is a free text field to describe any relevant provenance information about the attribute, e.g., who imported it, when, why, and from where.  The remaining columns are statistics used by the schema context and template schema mapping algorithms.

\item \texttt{global\_data}

This table stored dictionaries of data values that belong to particular attributes in the global schema.  For example, a global attribute named ``STATE'' may contain a dictionary of the names of the 50 US states.  \texttt{att\_id} is a FK reference to \texttt{global\_attributes}, and \texttt{value} is a string representation of a dictionary value.  The column \texttt{n} is an integer frequency count that can be used by the cosine similarity experts in Data Tamer.  Ordinarily, \texttt{n} is 1.

\item \texttt{global\_synonyms}

This table stores synonym dictionaries for attributes in the global schema.  For example, in the context of an attribute named ``STATE,'' the values ``Massachusetts'' and ``MA'' may be equivalent.  \texttt{att\_id} is a FK reference to \texttt{global\_attributes}, and \texttt{value\_a} and \texttt{value\_b} store the synonym pair, represented as strings.  Order does not matter.

\end{itemize}

\subsection{Mappings}

The core Data Tamer schema has a table for mappings from local source fields to global schema fields.

\begin{itemize}

\item \texttt{attribute\_mappings}

This table maps local fields (\texttt{local\_id} is an FK to \texttt{local\_fields}) to global ones (\texttt{global\_id} is an FK to \texttt{global\_attributes}).  Each mapping has a \texttt{confidence}, the certainty of whoever made the mapping, and an \texttt{authority}, the expertise of the mapper.  Each is a float between zero and one.  \texttt{who\_created}, \texttt{when\_created}, and \texttt{why\_created} store provenance information about each mapping.  Note that mappings are not unique to local fields --- one field may have multiple mappings to the same or different global attributes.

\item \texttt{attribute\_affinities} and \texttt{attribute\_max\_affinities}

\texttt{attribute\_affinities} is a view on \texttt{attribute\_mappings} that aggregates confidence and authority scores for each unique local-to-global attribute pair.  \texttt{attribute\_max\_affinities} is a view on \texttt{attribute\_affinities} that for each local field selects only the mapping with the highest aggregate confidence and authority.

\item \texttt{attribute\_antimappings}

This table has the same schema as \texttt{attribute\_mappings}.  Its records, however, indicate the unlikelihood of a mapping between the given local and global fields.  This table encapsulates negative feedback from the web UI.  It is not currently used by the expert algorithms, but could be in the future.

\item \texttt{attribute\_new\_suggestions}

This table stores suggestions for additions to the global schema.  These suggestions can be made via the web UI.  Records have a FK reference to \texttt{local\_fields} (\texttt{reference\_field\_id}), the \texttt{suggested\_name}, and provenance information.

\end{itemize}

\end{document}


text:
@interface CustomBtn : UIButton

@end


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Framework.Core.Utility;

namespace Framework.Core.DomainObjects
{
    public class SiteUser : EntityMetadata
    {
        public int SiteUserId { get; set; }
        [Required]
        [MaxLength(50)]
        public string EmailAddress { get; set; }
        [Required]
        [MaxLength(50)]
        public string PasswordHash { get; protected set; }
        [Required]
        [MaxLength(50)]
        public string PasswordSalt { get; protected set; }
        [MaxLength(50)]
        public string FirstName { get; set; }
        [MaxLength(50)]
        public string LastName { get; set; }

        public SiteUser()
        {
        }

        public static SiteUser CreateNewUser(string emailAddress, string password)
        {
            SiteUser user = new SiteUser { SiteUserId = 1, EmailAddress = emailAddress };
            user.CreateSalt();
            user.SetPassword(password);

            user.UpdatedBy = 0;
            user.UpdatedOn = DateTime.Now;
            user.CreatedBy = 0;
            user.CreatedOn = DateTime.Now;

            return user;
        }

        public void CreateSalt()
        {
            PasswordSalt = Guid.NewGuid().ToString();
        }

        public bool VerifyPassword(string password)
        {
            return PasswordHash == HashUtility.HashPassword(password, PasswordSalt);
        }

        public void SetPassword(string password)
        {
            PasswordHash = HashUtility.HashPassword(password, PasswordSalt);
        }
    }
}


text:
describe "i18n integration" do
  let(:backend) { Hash.new }

  before :each do
    @old_backend = I18n.backend
    I18n.backend = I18n::Backend::KeyValue.new(backend)
  end

  after :each do
    I18n.backend = @old_backend
  end

  describe "with error params" do
    let(:errors) do
      Vldt::Number.greater_than(5).call(1)
    end

    it "should pass the params for interpolation" do
      backend["en.vldt.errors.greater_than"] = JSON.dump("Greater than %{min}, d00d")

      e = Vldt::I18n.t(errors)

      expect(e[[]].first[:message]).to eq "Greater than 5, d00d"
    end
  end

  describe "with a selector" do
    C = Vldt::Common

    let(:errors) do
      v = C.validate(:tires, C.each(C.validate(:radius, Vldt::Number.positive)))

      v.call({ tires: [{ radius: 20 }, { radius: 0 }] })
    end

    it "should translate the selector into a path" do
      backend["en.tires.radius.positive"] = JSON.dump("Tire radii must be positive")

      e = Vldt::I18n.t(errors)

      expect(e[[:tires, 1, :radius]].first[:message]).to eq "Tire radii must be positive"
    end

    it "should chop stuff off from the beginning to find translations" do
      backend["en.radius.positive"] = JSON.dump("But so do all radii")

      e = Vldt::I18n.t(errors)

      expect(e[[:tires, 1, :radius]].first[:message]).to eq "But so do all radii"
    end

    it "should fallback to the vldt.errors scope" do
      backend["en.vldt.errors.positive"] = JSON.dump("Must be positive")

      e = Vldt::I18n.t(errors)

      expect(e[[:tires, 1, :radius]].first[:message]).to eq "Must be positive"
    end

    it "should put the optional namespace in front" do
      backend["en.the.namespace.positive"] = JSON.dump("Must be positive")

      e = Vldt::I18n.t(errors, namespace: "the.namespace")

      expect(e[[:tires, 1, :radius]].first[:message]).to eq "Must be positive"
    end
  end
end


text:
import "./styles"

import React, { PropTypes } from "react"

const Settings = ({ title, children }) => (

    { title && (

        { title }

    ) }
    { children }

)

Settings.propTypes = {
  children: PropTypes.oneOfType([
    PropTypes.array,
    PropTypes.element,
  ]).isRequired,
}

export Setting from "./Setting"
export default Settings