<commit_before>var extend = require('xtend')
var forEach = require('for-each')
var reduce = require('reduce')
var mapValues = require('map-values')
var mapKeys = require('object-keys-map')
var mapGraph = require('observ-graph/map')
var ObservComputed = require('observ/computed')
var ObservStruct = require('observ-struct')

module.exports = createType

function createType (defn) {

  //
  // default definition options
  //
  defn = defn || {}
  defn.type = defn.type || "ObservType"
  defn.version = defn.version || "0.0.0"
  defn.observPrefix = defn.observPrefix || '$'
  defn.props = defn.props || {}
  defn.derived = defn.derived || {}
  defn.extend = defn.extend || []

  // normalize type name(s) into array
  if (!Array.isArray(defn.type)) {
    defn.type = [defn.type]
  }

  // extend options
  defn = extendDefn(defn, defn.extend)

  // store definition for type extensions
  ObservType.definition = Object.freeze(defn)

  function ObservType (context) {

    // default args
    context = context || {}

    //
    // setup type props
    //
    var setProps = mapValues(defn.props, resolve)
    var derivedProps = computedProps(setProps, defn.derived)
    var typeProps = extend(setProps, derivedProps)

    // create type observable
    var observType = ObservStruct(
      prefixProps(
        defn.observPrefix,
        setProps
      )
    )

    forEach(derivedProps, function (propDef, propName) {
      observType[propName] = propDef
    })

    // create computed observable with unprefixed props
    var unprefixedType = ObservComputed([observType], function (props) {
      return unprefixProps(defn.observPrefix, props)
    })

    //
    // create dummy type to return
    //
    var type = function (listener) {
      return unprefixedType(listener)
    }

    // link methods on observ type to dummy type
    forEach(observType, function (attr, attrName) {
      if (typeof attr === 'function') {
        type[attrName] = attr
      }
    })

    type._type = defn.type
    type._version = defn.version
    type._graph = defn.graph

    //
    // setup methods
    //

    type.get = function (propName) {
      if (!propName) {
        return extend(
          unprefixedType(),
          mapValues(derivedProps, function (obs) {
            return obs()
          })
        )
      }
      return typeProps[propName]
    }

    type.getId = function () {
      return type.get(defn.idAttribute)
    }

    type.getType = function () {
      return type._type
    }

    type.getVersion = function () {
      return type._version
    }

    type.getGraph = function () {
      return type._graph
    }

    type.set = function (propName, newVal) {
      if (!newVal) {
        newVal = propName
        return observType.set(
          prefixProps(defn.observPrefix, newVal)
        )
      }
      var prop = setProps[propName]
      if (prop) {
        prop.set(newVal)
        return true
      }
      return false
    }

    // abstract function called when parent is destroyed
    type.destroy = function () {

    }

    return type
  }

  // abstract function to initialize class with graph
  ObservType.context = function (graph) {
    initTypeGraph(ObservType, graph)
    //initViewGraphs(ObservType, ObservType.definition.views, graph)
  }

  return ObservType
}

function prefixPropName (prefix, propName) {
  return prefix + propName
}

function unprefixPropName (prefix, propName) {
  return propName.substring(prefix.length)
}

function prefixProps (prefix, props) {
  return mapKeys(props, function (propName) {
    return prefixPropName(prefix, propName)
  })
}

function unprefixProps (prefix, props) {
  return mapKeys(props, function (propName) {
    return unprefixPropName(prefix, propName)
  })
}

function computedProps (typeProps, derivedDefs) {

  var derivedProps = {}

  forEach(derivedDefs, function (derivedDef, derivedName) {
    var deps = derivedDef.splice(0, derivedDef.length - 1)
    var fn = derivedDef[derivedDef.length - 1]

    var observDeps = deps.map(function (dep) {
      return typeProps[dep]
    })

    derivedProps[derivedName] = ObservComputed(observDeps, fn)
  })

  return derivedProps
}

function extendDefn (defn, extensionTypes) {

  if (!Array.isArray(extensionTypes)) {
    extensionTypes = [extensionTypes]
  }

  var extensionDefns = extensionTypes.map(function (type) {
    return type.definition
  })

  return reduce(extensionDefns, function (acc, item, index) {
    return extend(acc, item, mapValues(acc, function (val, key) {
      if (key === 'type') {
        return item[key].concat(val)
      }
      if (typeof val === 'object') {
        return extend(val, item[key])
      }
      return val
    }))
  }, defn)
}

function any (array, cb) {
  var item, val
  for (var i = 0; i < array.length; i++) {
    item = array[i]
    val = cb ? cb(item) : item
    if (val) return val
  }
  return false
}

function initTypeGraph (Type, graph) {
  var plural = Type.definition.plural

  if (!graph[plural]) {
    graph[plural] = mapGraph(graph, function (entity) {
      console.log("types", Type.definition.type, entity.getType())
      if (any(entity.getType(), function (typeName) {
        console.log("type match?", typeName)
        return Type.definition.type.indexOf(typeName) !== -1
      })) {
        console.log("matched", entity)
        return entity
      }
    })
  }
}

function initViewGraphs (Type, viewsDefns, graph) {

}

// TODO
function belongsTo () {}
function hasOne () {}
function hasMany () {}
function belongsToMany () {}

function resolve (fn) {
  return fn()
}
<commit_msg>remove console.logs<commit_after>var extend = require('xtend')
var forEach = require('for-each')
var reduce = require('reduce')
var mapValues = require('map-values')
var mapKeys = require('object-keys-map')
var mapGraph = require('observ-graph/map')
var ObservComputed = require('observ/computed')
var ObservStruct = require('observ-struct')

module.exports = createType

function createType (defn) {

  //
  // default definition options
  //
  defn = defn || {}
  defn.type = defn.type || "ObservType"
  defn.version = defn.version || "0.0.0"
  defn.observPrefix = defn.observPrefix || '$'
  defn.props = defn.props || {}
  defn.derived = defn.derived || {}
  defn.extend = defn.extend || []

  // normalize type name(s) into array
  if (!Array.isArray(defn.type)) {
    defn.type = [defn.type]
  }

  // extend options
  defn = extendDefn(defn, defn.extend)

  // store definition for type extensions
  ObservType.definition = Object.freeze(defn)

  function ObservType (context) {

    // default args
    context = context || {}

    //
    // setup type props
    //
    var setProps = mapValues(defn.props, resolve)
    var derivedProps = computedProps(setProps, defn.derived)
    var typeProps = extend(setProps, derivedProps)

    // create type observable
    var observType = ObservStruct(
      prefixProps(
        defn.observPrefix,
        setProps
      )
    )

    forEach(derivedProps, function (propDef, propName) {
      observType[propName] = propDef
    })

    // create computed observable with unprefixed props
    var unprefixedType = ObservComputed([observType], function (props) {
      return unprefixProps(defn.observPrefix, props)
    })

    //
    // create dummy type to return
    //
    var type = function (listener) {
      return unprefixedType(listener)
    }

    // link methods on observ type to dummy type
    forEach(observType, function (attr, attrName) {
      if (typeof attr === 'function') {
        type[attrName] = attr
      }
    })

    type._type = defn.type
    type._version = defn.version
    type._graph = defn.graph

    //
    // setup methods
    //

    type.get = function (propName) {
      if (!propName) {
        return extend(
          unprefixedType(),
          mapValues(derivedProps, function (obs) {
            return obs()
          })
        )
      }
      return typeProps[propName]
    }

    type.getId = function () {
      return type.get(defn.idAttribute)
    }

    type.getType = function () {
      return type._type
    }

    type.getVersion = function () {
      return type._version
    }

    type.getGraph = function () {
      return type._graph
    }

    type.set = function (propName, newVal) {
      if (!newVal) {
        newVal = propName
        return observType.set(
          prefixProps(defn.observPrefix, newVal)
        )
      }
      var prop = setProps[propName]
      if (prop) {
        prop.set(newVal)
        return true
      }
      return false
    }

    // abstract function called when parent is destroyed
    type.destroy = function () {

    }

    return type
  }

  // abstract function to initialize class with graph
  ObservType.context = function (graph) {
    initTypeGraph(ObservType, graph)
    //initViewGraphs(ObservType, ObservType.definition.views, graph)
  }

  return ObservType
}

function prefixPropName (prefix, propName) {
  return prefix + propName
}

function unprefixPropName (prefix, propName) {
  return propName.substring(prefix.length)
}

function prefixProps (prefix, props) {
  return mapKeys(props, function (propName) {
    return prefixPropName(prefix, propName)
  })
}

function unprefixProps (prefix, props) {
  return mapKeys(props, function (propName) {
    return unprefixPropName(prefix, propName)
  })
}

function computedProps (typeProps, derivedDefs) {

  var derivedProps = {}

  forEach(derivedDefs, function (derivedDef, derivedName) {
    var deps = derivedDef.splice(0, derivedDef.length - 1)
    var fn = derivedDef[derivedDef.length - 1]

    var observDeps = deps.map(function (dep) {
      return typeProps[dep]
    })

    derivedProps[derivedName] = ObservComputed(observDeps, fn)
  })

  return derivedProps
}

function extendDefn (defn, extensionTypes) {

  if (!Array.isArray(extensionTypes)) {
    extensionTypes = [extensionTypes]
  }

  var extensionDefns = extensionTypes.map(function (type) {
    return type.definition
  })

  return reduce(extensionDefns, function (acc, item, index) {
    return extend(acc, item, mapValues(acc, function (val, key) {
      if (key === 'type') {
        return item[key].concat(val)
      }
      if (typeof val === 'object') {
        return extend(val, item[key])
      }
      return val
    }))
  }, defn)
}

function any (array, cb) {
  var item, val
  for (var i = 0; i < array.length; i++) {
    item = array[i]
    val = cb ? cb(item) : item
    if (val) return val
  }
  return false
}

function initTypeGraph (Type, graph) {
  var plural = Type.definition.plural

  if (!graph[plural]) {
    graph[plural] = mapGraph(graph, function (entity) {
      if (any(entity.getType(), function (typeName) {
        return Type.definition.type.indexOf(typeName) !== -1
      })) {
        return entity
      }
    })
  }
}

function initViewGraphs (Type, viewsDefns, graph) {

}

// TODO
function belongsTo () {}
function hasOne () {}
function hasMany () {}
function belongsToMany () {}

function resolve (fn) {
  return fn()
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';
import socket from '../socket';
import { scene } from '../game/main';

import { keepPlaying } from '../reducers/gameStatus';

class Canvas extends Component {
	constructor(props){
    	super(props);
    	this.state = {
    		leaderboard: [],
    		displayVol : 4000
    	}
  	}

  	componentDidMount(){
		createjs.Sound.registerSound("eat.ogg", "eatSound");
  	}

	render = () => {
		if(this.props.players[socket.id] && scene){
			this.state.leaderboard = [];
			var myNick = scene.getObjectByName(socket.id).nickname;
			if (myNick.length > 15){
				myNick = myNick.slice(0,14) + "...";
			}

			for(let id in this.props.players){
				var nick = scene.getObjectByName(id).nickname;
				if (nick.length > 15){
					nick = nick.slice(0,14) + "...";
				}
				this.state.leaderboard.push({nick, vol: this.props.players[id].volume});
			}
			// sort leaders
			this.state.leaderboard.sort((a, b) => b.vol - a.vol);

			// add self to shortlist (if necessary)
			var me = this.state.leaderboard.find(e => e.nick === myNick)
			me.place = this.state.leaderboard.indexOf(me) + 1;
			this.state.leaderboard.splice(3);
			if(me.place > 3){
				this.state.leaderboard.push(me);
			}
		}

		// show score
		if(this.props.players[socket.id] && this.state.displayVol < this.props.players[socket.id].volume){
			this.state.displayVol = ~~(this.state.displayVol * 1.0011);
		}
		if(this.props.players[socket.id] && this.state.displayVol > this.props.players[socket.id].volume){
			this.state.displayVol = this.props.players[socket.id].volume;
		}

		// show eater/eaten status for 3 seconds before fading
		if(this.props.gameStatus.length){
			setTimeout(()=>this.props.keepPlaying(), 3000);
		}

		return (

							{this.props.players[socket.id] && this.state.leaderboard && this.state.leaderboard.map((person, index) => (
									<tr key={`leaderboard-row-${index+1}`} style={myNick === person.nick ? {backgroundColor: 'rgba(0,0,0,0.3)'} : {}}>
										{person.place || index + 1}
										{person.nick}
										{(index === 0) && person.vol}

								))
							}

						{this.props.gameStatus}

{this.props.players[socket.id] && this.props.abilities && this.props.abilities.meter}

{this.props.players[socket.id] && this.props.abilities && "launch ready"}

{this.props.players[socket.id] && 'volume'}

{this.props.players[socket.id] &&this.state.displayVol}

					<canvas id="canvas" style={{background: 'linear-gradient(#00ABD6,#4ECDC4)'}}></canvas>

		)
	}
}

const mapStateToProps = ({ players, gameStatus, abilities }) => ({ players, gameStatus, abilities });

const mapDispatchToProps = dispatch => ({
  keepPlaying: () => dispatch(keepPlaying())
  // close: () => dispatch(closeConsole()),
  // updateNickname: e => dispatch(setNickname(e.target.value)),
  // clearNickname: () => dispatch(resetNickname()),
  // updateError: error => dispatch(setError(error)),
  // clearError: () => dispatch(resetError()),
  // signInAsGuest: (nickname, socket) => dispatch(startAsGuest(nickname, socket))
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Canvas);<commit_msg>leaderboard<commit_after>import React, { Component } from 'react';
import { connect } from 'react-redux';
import socket from '../socket';
import { scene } from '../game/main';

import { keepPlaying } from '../reducers/gameStatus';

class Canvas extends Component {
	constructor(props){
    	super(props);
    	this.state = {
    		leaderboard: [],
    		displayVol : 4000
    	}
  	}

  	componentDidMount(){
		createjs.Sound.registerSound("eat.ogg", "eatSound");
  	}

	render = () => {
		if(this.props.players[socket.id] && scene){
			this.state.leaderboard = [];
			var myNick = scene.getObjectByName(socket.id).nickname;
			if (myNick.length > 15){
				myNick = myNick.slice(0,14) + "...";
			}

			for(let id in this.props.players){
				var nick = scene.getObjectByName(id).nickname;
				if (nick.length > 15){
					nick = nick.slice(0,14) + "...";
				}
				this.state.leaderboard.push({nick, vol: this.props.players[id].volume});
			}
			// sort leaders
			this.state.leaderboard.sort((a, b) => b.vol - a.vol);

			// add self to shortlist (if necessary)
			// var me = this.state.leaderboard.find(e => e.nick === myNick)
			// me.place = this.state.leaderboard.indexOf(me) + 1;
			this.state.leaderboard.splice(4);
			if(me.place > 3){
				// this.state.leaderboard.push(me);
			}
		}

		// show score
		if(this.props.players[socket.id] && this.state.displayVol < this.props.players[socket.id].volume){
			this.state.displayVol = ~~(this.state.displayVol * 1.0011);
		}
		if(this.props.players[socket.id] && this.state.displayVol > this.props.players[socket.id].volume){
			this.state.displayVol = this.props.players[socket.id].volume;
		}

		// show eater/eaten status for 3 seconds before fading
		if(this.props.gameStatus.length){
			setTimeout(()=>this.props.keepPlaying(), 3000);
		}

		return (

							{this.props.players[socket.id] && this.state.leaderboard && this.state.leaderboard.map((person, index) => (
									<tr key={`leaderboard-row-${index+1}`} style={myNick === person.nick ? {backgroundColor: 'rgba(0,0,0,0.3)'} : {}}>
										{person.place || index + 1}
										{person.nick}
										{person.vol}

								))
							}

						{this.props.gameStatus}

{this.props.players[socket.id] && this.props.abilities && this.props.abilities.meter}

{this.props.players[socket.id] && this.props.abilities && "launch ready"}

{this.props.players[socket.id] && 'volume'}

{this.props.players[socket.id] &&this.state.displayVol}

					<canvas id="canvas" style={{background: 'linear-gradient(#00ABD6,#4ECDC4)'}}></canvas>

		)
	}
}

const mapStateToProps = ({ players, gameStatus, abilities }) => ({ players, gameStatus, abilities });

const mapDispatchToProps = dispatch => ({
  keepPlaying: () => dispatch(keepPlaying())
  // close: () => dispatch(closeConsole()),
  // updateNickname: e => dispatch(setNickname(e.target.value)),
  // clearNickname: () => dispatch(resetNickname()),
  // updateError: error => dispatch(setError(error)),
  // clearError: () => dispatch(resetError()),
  // signInAsGuest: (nickname, socket) => dispatch(startAsGuest(nickname, socket))
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Canvas);
<|endoftext|>


<commit_before>var assert = require('assert'),
    _ = require('lodash'),
    events = require('../apis/github/users/carolinapowers/events.json');

function answer(){
    var pushEvents = _.filter(events, {
            'type': 'PushEvent'
    });
    console.log(pushEvents.length);

    return {
    'total': events.length,     // How many total events did you fetch?
    'PushEvent': {
      'total': "",  // How many total events of type `PushEvent` are there?
      'perDay': "", // On average, how many`PushEvent` entries per day?
    },
    'other': {
      'total': "",   // How many _other_ events are in the data?
      'perDay': "",  // How many per day, on average?
    }
  };
}

var theAnswer = answer();
console.log(events.length);

it('should assert that "answer" exists', function(){
   assert(answer);

});

it('should assert that "theAnswer.total" equals "events.length" exists', function(){
   assert(theAnswer.total == events.length);
});

it('should assert that "events.length" equals 30', function () {
   assert.equal((events.length), 30);
});

<commit_msg>totalDays<commit_after>var assert = require('assert'),
    _ = require('lodash'),
    events = require('../apis/github/users/carolinapowers/events.json');

var pushEvents = _.filter(events, {
        'type': 'PushEvent'
    });
    console.log(pushEvents.length);

var first = _.first(events);
var last = _.last(events);

var firstDay = first.created_at;
console.log(firstDay);

var lastDay = last.created_at;
console.log(lastDay);

var totalDays = lastDay - firstDay;
console.log(totalDays);

//var totalDays = last.created_at - first.created_at;
//console.log(first);
//console.log(last);

function answer(){
    return {
    'total': events.length,     // How many total events did you fetch?
    'PushEvent': {
      'total': pushEvents.length,  // How many total events of type `PushEvent` are there?
      'perDay': "", // On average, how many`PushEvent` entries per day?
    },
    'other': {
      'total': "",   // How many _other_ events are in the data?
      'perDay': "",  // How many per day, on average?
    }
  };
}

var theAnswer = answer();
console.log(events.length);

it('should assert that "answer" exists', function(){
   assert(answer);

});

it('should assert that "theAnswer.total" equals "events.length" exists', function(){
   assert(theAnswer.total == events.length);
});

it('should assert that "events.length" equals 30', function () {
   assert.equal((events.length), 30);
});

it('should assert that total of PushEvent equals pushEvents.length', function () {
    assert(theAnswer.PushEvent.total == pushEvents.length);
})

it('should assert that "pushEvents.length" equals 24', function () {
    assert.equal((pushEvents.length), 24);
})

<|endoftext|>


<commit_before>$(document).ready(function() {

var width = 500,
    height = 500,
    centered;

var packer = sm.packer();

projection = d3.geo.albersUsa()
  .scale(160000)
  .translate([-41630, 4900]);

var path = d3.geo.path().projection(projection)

svg = d3.select("#content")
  .append("svg:svg")
  .attr("width", width)
  .attr("height", height)

svg.append("rect")
    .attr("class", "background")
    .attr("width", width)
    .attr("height", height)
    .on("click", clicked);

var g = svg.append("g");
g.append("g").attr("id", "neighborhoods");
g.append("g").attr("id", "schools");

d3.json("data/neighborhood_boundaries.json", function(error, dc) {
  g.select("#neighborhoods")
    .selectAll("path")
      .data(dc.features)
    .enter().append("path")
      .attr("d", path)
      .on("click", clicked);
  g.append("path")
      .datum(topojson.mesh(dc, dc.features, function(a, b) { return a !== b; }))
      .attr("id", "state-borders")
      .attr("d", path);
});

d3.csv('data/schools.csv', function(data){
  var scale = d3.scale.sqrt().range([1,10])
  g.select("#schools").selectAll("circle")
    .data(data).enter().append("circle")
      .attr("r", 4)
      .attr("fill-opacity", 0.5)
      .attr("fill", "#FF0000")
      .attr("transform", function(d) {
        return "translate(" +
          projection([d.long, d.lat]) +
          ")";})
      .on("click", function(d) {
        $("#details").prepend("

"+d.name+"

enrollment: " +
                              d.enrollment + "

allocation: " +
                              d.alloc + "

");
      })
      .append("title").text(function(d){return d.name;});
	packMetros();
  d3.select("#school_enrollment").on("click", function() {changeSchoolData("enrollment")});
  d3.select("#school_allocation").on("click", function() {changeSchoolData("alloc")});
  d3.select("#school_location").on("click", noSchoolData);
  function noSchoolData() {
    g.select("#schools").selectAll("circle")
      .transition().duration(600)
      .attr("r", 4)
  }
  function changeSchoolData(new_data_column) {
    matchScaleToData(scale, function(d){return +d[new_data_column];})
    g.select("#schools").selectAll("circle")
      .transition().duration(600)
      .attr("r", function(d) {return scale(d[new_data_column])})
  }
  function matchScaleToData(scale, fieldFunction) {
    var minimum = d3.min(data, fieldFunction),
        maximum = d3.max(data, fieldFunction);
    scale.domain([minimum, maximum]);
  }
});

function packMetros() {
	var elements = d3.selectAll('#content circle')[0];
	packer.elements(elements).start();
}

function clicked(d) {
  var x, y, k;

  if (d && centered !== d) {
    var centroid = path.centroid(d);
    x = centroid[0];
    y = centroid[1];
    k = 4;
    centered = d;
  } else {
    x = width / 2;
    y = height / 2;
    k = 1;
    centered = null;
  }

  g.selectAll("path")
      .classed("active", centered && function(d) { return d === centered; });

  g.transition()
      .duration(750)
      .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + k + ")translate(" + -x + "," + -y + ")")
      .style("stroke-width", 1.5 / k + "px");
}

}); // end document ready function
<commit_msg>change school color<commit_after>$(document).ready(function() {

var width = 500,
    height = 500,
    centered;

var packer = sm.packer();

projection = d3.geo.albersUsa()
  .scale(160000)
  .translate([-41630, 4900]);

var path = d3.geo.path().projection(projection)

svg = d3.select("#content")
  .append("svg:svg")
  .attr("width", width)
  .attr("height", height)

svg.append("rect")
    .attr("class", "background")
    .attr("width", width)
    .attr("height", height)
    .on("click", clicked);

var g = svg.append("g");
g.append("g").attr("id", "neighborhoods");
g.append("g").attr("id", "schools");

d3.json("data/neighborhood_boundaries.json", function(error, dc) {
  g.select("#neighborhoods")
    .selectAll("path")
      .data(dc.features)
    .enter().append("path")
      .attr("d", path)
      .on("click", clicked);
  g.append("path")
      .datum(topojson.mesh(dc, dc.features, function(a, b) { return a !== b; }))
      .attr("id", "state-borders")
      .attr("d", path);
});

d3.csv('data/schools.csv', function(data){
  var scale = d3.scale.sqrt().range([1,10])
  g.select("#schools").selectAll("circle")
    .data(data).enter().append("circle")
      .attr("r", 4)
      .attr("fill-opacity", 0.7)
      .attr("fill", "#000099")
      .attr("transform", function(d) {
        return "translate(" +
          projection([d.long, d.lat]) +
          ")";})
      .on("click", function(d) {
        $("#details").prepend("

"+d.name+"

enrollment: " +
                              d.enrollment + "

allocation: " +
                              d.alloc + "

");
      })
      .append("title").text(function(d){return d.name;});
	packMetros();
  d3.select("#school_enrollment").on("click", function() {changeSchoolData("enrollment")});
  d3.select("#school_allocation").on("click", function() {changeSchoolData("alloc")});
  d3.select("#school_location").on("click", noSchoolData);
  function noSchoolData() {
    g.select("#schools").selectAll("circle")
      .transition().duration(600)
      .attr("r", 4)
  }
  function changeSchoolData(new_data_column) {
    matchScaleToData(scale, function(d){return +d[new_data_column];})
    g.select("#schools").selectAll("circle")
      .transition().duration(600)
      .attr("r", function(d) {return scale(d[new_data_column])})
  }
  function matchScaleToData(scale, fieldFunction) {
    var minimum = d3.min(data, fieldFunction),
        maximum = d3.max(data, fieldFunction);
    scale.domain([minimum, maximum]);
  }
});

function packMetros() {
	var elements = d3.selectAll('#content circle')[0];
	packer.elements(elements).start();
}

function clicked(d) {
  var x, y, k;

  if (d && centered !== d) {
    var centroid = path.centroid(d);
    x = centroid[0];
    y = centroid[1];
    k = 4;
    centered = d;
  } else {
    x = width / 2;
    y = height / 2;
    k = 1;
    centered = null;
  }

  g.selectAll("path")
      .classed("active", centered && function(d) { return d === centered; });

  g.transition()
      .duration(750)
      .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + k + ")translate(" + -x + "," + -y + ")")
      .style("stroke-width", 1.5 / k + "px");
}

}); // end document ready function
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import {
	Alert,
	View,
	Text,
	Linking,
	ActivityIndicator,
	TouchableOpacity,
	TextInput
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import { connect } from 'react-redux';
import Touchable from '../common/Touchable';
import AppSettings from '../../AppSettings';
import css from '../../styles/css';
import { getMaxCardWidth, openURL } from '../../util/general';
import Card from '../card/Card';

const auth = require('../../util/auth');

class UserAccount extends Component {

	componentDidMount() {
		Linking.addEventListener('url', this._handleOpenURL);

		// if we're mounting and we're somehow still in the
		// process of logging in, check if we've timed out.
		// otherwise, set a timeout
		if (this.props.user.isLoggingIn) {
			const now = new Date();
			const lastPostTime = new Date(this.props.user.timeRequested);
			if (now - lastPostTime >= AppSettings.SSO_TTL) {
				this.props.timeoutLogin();
			} else {
				// timeout after remaining time expires
				setTimeout(this.props.timeoutLogin, now - lastPostTime);
			}
		}
	}

	componentWillReceiveProps(nextProps) {
		if (nextProps.user.isLoggedIn) {
			this.props.doTokenRefresh();
			auth.retrieveAccessToken()
				.then((token) => {
					console.log('User Data: ', this.props.user);
					console.log('Access Token: ', token);
				});
		}
	}

	componentWillUnmount() {
		Linking.removeEventListener('url', this._handleOpenURL);
	}

	handleLogin = (user, pass) => {
		if (!this.props.user.isLoggingIn) this.props.doLogin(user, pass);
	}

	handleLogout = () => {
		this.props.doLogout();
	}

	render() {
		const { error } = this.props.user;
		if (error && !this.props.user.isLoggingIn) {
			Alert.alert(
				'Sign in error',
				error,
				[
					{ text: 'OK', onPress: () => { this.props.clearErrors(); } }
				],
				{ cancelable: false }
			);
		}
		return (
			<Card id="user" title={this.props.user.isLoggedIn ? 'Logged in as:' : 'Log in with SSO:'} hideMenu={true}>
				<View style={{ width: getMaxCardWidth() }}>
					{(this.props.user.isLoggedIn) ? (
						<AccountInfo
							username={this.props.user.profile.username}
							handleLogout={this.handleLogout}
						/>
					) : (
						<AccountLogin
							handleLogin={this.handleLogin}
							error={this.props.user.error}
							isLoggingIn={this.props.user.isLoggingIn}
						/>
					)}
				</View>
			</Card>
		);
	}
}

const AccountInfo = ({ username, handleLogout }) => (
	<View style={css.ua_accountinfo}>
		<View style={css.ua_loggedin}>
			<Icon
				name="check-circle"
				size={26}
				style={css.ua_username_checkmark}
			/>
			<Text style={css.ua_username_text}>
				c3bryant{username}
			</Text>
		</View>
		<View style={css.ua_logout}>
			<Touchable onPress={handleLogout}>
				<Text style={css.ua_loutout_text}>Log out</Text>
			</Touchable>
		</View>
	</View>
);

const AccountLogin = ({ handleLogin, error, isLoggingIn }) => (
	<View
		style={css.ua_loginContainer}
	>
		<TextInput
			style={css.ua_input}
			placeholder="User ID"
			returnKeyType="next"
			autoCapitalize="none"
			autoCorrect={false}
			underlineColorAndroid="transparent"
			editable={!isLoggingIn}
			onChange={(event) => {
				this._usernameText = event.nativeEvent.text;
			}}
			onSubmitEditing={(event) => {
				this._passwordInput.focus();
			}}
		/>
		<TextInput
			ref={(c) => { this._passwordInput = c; }}
			style={css.ua_input}
			placeholder="Password"
			returnKeyType="send"
			underlineColorAndroid="transparent"
			editable={!isLoggingIn}
			secureTextEntry
			onChange={(event) => {
				this._passwordText = event.nativeEvent.text;
			}}
			onSubmitEditing={(event) => {
				handleLogin(this._usernameText, event.nativeEvent.text);
			}}
		/>
		<Touchable
			onPress={() => handleLogin(this._usernameText, this._passwordText)}
			disabled={isLoggingIn}
			style={
				(isLoggingIn) ?
					(
						[css.ua_loginButton, css.ua_loginButtonDisabled]
					) : (
						css.ua_loginButton
					)
			}
		>
			<Text style={css.ua_loginText}>
				{
					(isLoggingIn) ?
						('Signing in...') :
						('Sign in')
				}
			</Text>
			{
				(isLoggingIn) ?
					(
						<ActivityIndicator
							size="small"
							style={css.ua_loading_icon}
							color="#fff"
						/>
					) : (null)
			}
		</Touchable>

		<Touchable
			onPress={() => openURL(AppSettings.FORGOT_PASSWORD_URL)}
			style={css.ua_forgotButton}
		>
			<Text style={css.ua_forgotText}>
				Forgot your password?
			</Text>
		</Touchable>
	</View>
);

function mapStateToProps(state, props) {
	return {
		user: state.user,
	};
}

function mapDispatchToProps(dispatch) {
	return {
		doLogin: (username, password) => {
			dispatch({ type: 'USER_LOGIN', username, password });
		},
		doTokenRefresh: () => {
			dispatch({ type: 'USER_TOKEN_REFRESH' });
		},
		doLogout: () => {
			dispatch({ type: 'USER_LOGOUT' });
		},
		timeoutLogin: () => {
			dispatch({ type: 'USER_LOGIN_TIMEOUT' });
		},
		clearErrors: () => {
			dispatch({ type: 'USER_CLEAR_ERRORS' });
		}
	};
}

module.exports = connect(
	mapStateToProps,
	mapDispatchToProps
)(UserAccount);
<commit_msg>Remove placeholder account info<commit_after>import React, { Component } from 'react';
import {
	Alert,
	View,
	Text,
	Linking,
	ActivityIndicator,
	TouchableOpacity,
	TextInput
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import { connect } from 'react-redux';
import Touchable from '../common/Touchable';
import AppSettings from '../../AppSettings';
import css from '../../styles/css';
import { getMaxCardWidth, openURL } from '../../util/general';
import Card from '../card/Card';

const auth = require('../../util/auth');

class UserAccount extends Component {

	componentDidMount() {
		Linking.addEventListener('url', this._handleOpenURL);

		// if we're mounting and we're somehow still in the
		// process of logging in, check if we've timed out.
		// otherwise, set a timeout
		if (this.props.user.isLoggingIn) {
			const now = new Date();
			const lastPostTime = new Date(this.props.user.timeRequested);
			if (now - lastPostTime >= AppSettings.SSO_TTL) {
				this.props.timeoutLogin();
			} else {
				// timeout after remaining time expires
				setTimeout(this.props.timeoutLogin, now - lastPostTime);
			}
		}
	}

	componentWillReceiveProps(nextProps) {
		if (nextProps.user.isLoggedIn) {
			this.props.doTokenRefresh();
			auth.retrieveAccessToken()
				.then((token) => {
					console.log('User Data: ', this.props.user);
					console.log('Access Token: ', token);
				});
		}
	}

	componentWillUnmount() {
		Linking.removeEventListener('url', this._handleOpenURL);
	}

	handleLogin = (user, pass) => {
		if (!this.props.user.isLoggingIn) this.props.doLogin(user, pass);
	}

	handleLogout = () => {
		this.props.doLogout();
	}

	render() {
		const { error } = this.props.user;
		if (error && !this.props.user.isLoggingIn) {
			Alert.alert(
				'Sign in error',
				error,
				[
					{ text: 'OK', onPress: () => { this.props.clearErrors(); } }
				],
				{ cancelable: false }
			);
		}
		return (
			<Card id="user" title={this.props.user.isLoggedIn ? 'Logged in as:' : 'Log in with SSO:'} hideMenu={true}>
				<View style={{ width: getMaxCardWidth() }}>
					{(this.props.user.isLoggedIn) ? (
						<AccountInfo
							username={this.props.user.profile.username}
							handleLogout={this.handleLogout}
						/>
					) : (
						<AccountLogin
							handleLogin={this.handleLogin}
							error={this.props.user.error}
							isLoggingIn={this.props.user.isLoggingIn}
						/>
					)}
				</View>
			</Card>
		);
	}
}

const AccountInfo = ({ username, handleLogout }) => (
	<View style={css.ua_accountinfo}>
		<View style={css.ua_loggedin}>
			<Icon
				name="check-circle"
				size={26}
				style={css.ua_username_checkmark}
			/>
			<Text style={css.ua_username_text}>
				{username}
			</Text>
		</View>
		<View style={css.ua_logout}>
			<Touchable onPress={handleLogout}>
				<Text style={css.ua_loutout_text}>Log out</Text>
			</Touchable>
		</View>
	</View>
);

const AccountLogin = ({ handleLogin, error, isLoggingIn }) => (
	<View
		style={css.ua_loginContainer}
	>
		<TextInput
			style={css.ua_input}
			placeholder="User ID"
			returnKeyType="next"
			autoCapitalize="none"
			autoCorrect={false}
			underlineColorAndroid="transparent"
			editable={!isLoggingIn}
			onChange={(event) => {
				this._usernameText = event.nativeEvent.text;
			}}
			onSubmitEditing={(event) => {
				this._passwordInput.focus();
			}}
		/>
		<TextInput
			ref={(c) => { this._passwordInput = c; }}
			style={css.ua_input}
			placeholder="Password"
			returnKeyType="send"
			underlineColorAndroid="transparent"
			editable={!isLoggingIn}
			secureTextEntry
			onChange={(event) => {
				this._passwordText = event.nativeEvent.text;
			}}
			onSubmitEditing={(event) => {
				handleLogin(this._usernameText, event.nativeEvent.text);
			}}
		/>
		<Touchable
			onPress={() => handleLogin(this._usernameText, this._passwordText)}
			disabled={isLoggingIn}
			style={
				(isLoggingIn) ?
					(
						[css.ua_loginButton, css.ua_loginButtonDisabled]
					) : (
						css.ua_loginButton
					)
			}
		>
			<Text style={css.ua_loginText}>
				{
					(isLoggingIn) ?
						('Signing in...') :
						('Sign in')
				}
			</Text>
			{
				(isLoggingIn) ?
					(
						<ActivityIndicator
							size="small"
							style={css.ua_loading_icon}
							color="#fff"
						/>
					) : (null)
			}
		</Touchable>

		<Touchable
			onPress={() => openURL(AppSettings.FORGOT_PASSWORD_URL)}
			style={css.ua_forgotButton}
		>
			<Text style={css.ua_forgotText}>
				Forgot your password?
			</Text>
		</Touchable>
	</View>
);

function mapStateToProps(state, props) {
	return {
		user: state.user,
	};
}

function mapDispatchToProps(dispatch) {
	return {
		doLogin: (username, password) => {
			dispatch({ type: 'USER_LOGIN', username, password });
		},
		doTokenRefresh: () => {
			dispatch({ type: 'USER_TOKEN_REFRESH' });
		},
		doLogout: () => {
			dispatch({ type: 'USER_LOGOUT' });
		},
		timeoutLogin: () => {
			dispatch({ type: 'USER_LOGIN_TIMEOUT' });
		},
		clearErrors: () => {
			dispatch({ type: 'USER_CLEAR_ERRORS' });
		}
	};
}

module.exports = connect(
	mapStateToProps,
	mapDispatchToProps
)(UserAccount);
<|endoftext|>


<commit_before>#!/usr/bin/env node

var Dissolve = require("./index");

var parser = Dissolve().loop(function(end) {
  var i = 0;
  this.uint8("id").uint8("data_len").loop("data", function(end) {
    if (i++ >= this.vars.data_len) {
      return end(true);
    }

    this.uint8("a").uint8("b");
  }).tap(function() {
    this.emit("data", this.vars);
    this.vars = Object.create(null);
  });
});

parser.on("data", function(e) {
  console.log(e);
});

parser.write(new Buffer([0x01, 0x03, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06]));
<commit_msg>made the loop example a bit more useful<commit_after>#!/usr/bin/env node

var Dissolve = require("./index");

var parser = Dissolve().loop(function(end) {
  this.uint8("id").loop("data", function(end) {
    this.uint8("type").tap(function() {
      if (this.vars.type === 0) {
        return end(true);
      }

      this.uint8("x").uint8("y");
    });
  }).tap(function() {
    this.emit("data", this.vars);
    this.vars = Object.create(null);
  });
});

parser.on("data", function(e) {
  console.log(e);
});

parser.write(new Buffer([0x01, 0x01, 0x11, 0x12, 0x01, 0x21, 0x22, 0x01, 0x31, 0x32, 0x00]));
<|endoftext|>


<commit_before>import $ from 'jquery';
import React from 'react';
import Reflux from "reflux";
import reactMixin from 'react-mixin';
import autoBind from 'react-autobind';
import bem from '../bem';
import actions from '../actions';
import stores from '../stores';
import Select from 'react-select';
import {
  t
} from '../utils';

import DocumentTitle from 'react-document-title';

export default class RESTServices extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      currentAsset: this.props.asset,
      services: false
    };
    autoBind(this);
  }

  componentDidMount() {
    console.log(this.state);
    this.listenTo(stores.asset, this.onAssetChange);
  }

  onAssetChange(data) {
    if (data.assetUid === this.state.currentAsset.uid) {
      this.setState({
        isAwaitingAssetChange: false,
        isCopyFormVisible: false
      });
    }
  }

  newServiceModal() {
    stores.pageState.showModal({
      type: 'rest-services',
      sid: false
    });
  }

  render () {
    var docTitle = this.props.asset.name || t('Untitled');
    return (
      <DocumentTitle title={`${docTitle} | KoboToolbox`}>
        <bem.FormView m={this.state.services ? 'form-settings-REST' : 'form-settings-REST-empty'}>
          {this.state.services &&

              <RESTServicesList/>
              <button
                className='mdl-button mdl-button--raised mdl-button--colored'
                onClick={this.newServiceModal}
              >
                {t('Register a New Service')}
              </button>

          }

          {!this.state.services &&
          <bem.Empty>
            <bem.Empty__inner>

{t('This project does not have any REST services yet!')}

                {t('You can use REST services to automatically post submissions to a third-party application.')}

                  {t('Learn more')}

              <button
                className='mdl-button mdl-button--raised mdl-button--colored'
                onClick={this.newServiceModal}
              >
                {t('Register a New Service')}
              </button>
            </bem.Empty__inner>
          </bem.Empty>
          }
        </bem.FormView>
      </DocumentTitle>
    );
  }
};
reactMixin(RESTServices.prototype, Reflux.ListenerMixin);

export class RESTServicesForm extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      currentAssetUid: "TODO",
      name: '',
      url: 'https://',
      type: 'json',
      securityType: 'oauth',
      securityOptions: [
        {
          value: 'oauth',
          label: t('OAuth')
        },
        {
          value: 'auth_header',
          label: t('Authorization Header')
        }
      ],
      auth_header: ''
    };
    autoBind(this);
  }

  formItemChange(evt) {
    if (evt.target) {
      var val = evt.target.value;
      var attr = evt.target.name;
    } else {
      var val = evt;
      var attr = 'securityType';
    }

    this.setState({
      [attr]: val
    })
  }

  onSubmit(evt) {
    evt.preventDefault();
    actions.resources.registerRESTService(this.state.currentAssetUid, {
      name: this.state.name,
      url: this.state.url,
      type: this.state.type
    })
    return false;
  }

  render() {
    return (
      <bem.FormModal__form onSubmit={this.onSubmit}>
        <bem.FormModal__item m='wrapper'>

          <bem.FormModal__item>

              {t('Name')}

            <input
              type='text'
              id='rest-service-form--name'
              name='name'
              placeholder={t('Service Name')}
              value={this.state.name}
              onChange={this.formItemChange}
            />
          </bem.FormModal__item>

          <bem.FormModal__item>

              {t('Endpoint URL')}

            <input
              type='text'
              id='rest-service-form--url'
              name='url'
              placeholder={t('https://')}
              value={this.state.url}
              onChange={this.formItemChange}
            />
          </bem.FormModal__item>

          <bem.FormModal__item m='type'>

              {t('Type')}

            <bem.FormModal__item m={['half-width', 'half-width-left']}>
              <bem.FormModal__radio>
                <bem.FormModal__radioInput
                  type='radio'
                  value='json'
                  name='type'
                  onChange={this.formItemChange}
                  checked={this.state.type === 'json'}
                />
                <bem.FormModal__radioText>
                  {t('JSON')}
                </bem.FormModal__radioText>
              </bem.FormModal__radio>
            </bem.FormModal__item>

            <bem.FormModal__item m='half-width'>
              <bem.FormModal__radio>
                <bem.FormModal__radioInput
                  type='radio'
                  value='xml'
                  name='type'
                  onChange={this.formItemChange}
                  checked={this.state.type === 'xml'}
                />
                <bem.FormModal__radioText>
                  {t('XML')}
                </bem.FormModal__radioText>
              </bem.FormModal__radio>
            </bem.FormModal__item>
          </bem.FormModal__item>

          <bem.FormModal__item m='security'>

              {t('Security')}

            <Select
              id='rest-service-form--security'
              name='securityType'
              value={this.state.securityType}
              onChange={this.formItemChange}
              options={this.state.securityOptions}
            />
          </bem.FormModal__item>

          {this.state.securityType && this.state.securityType.value == 'auth_header' &&
            <bem.FormModal__item>

                {t('Authorization Header')}

              <input
                type='text'
                id='rest-service-form--authorization-header'
                name='auth_header'
                value={this.state.auth_header}
                onChange={this.formItemChange}
              />
            </bem.FormModal__item>
          }

          <bem.FormModal__item m='fields'>

              {t('Advanced Users')}

              {t('Post selected questions only (use question names, comma-delimited)')}

            <textarea
              id='rest-service-form--fields'
              className='questions'
              name='questions'
              value={this.state.questions}
              onChange={this.formItemChange}
            />
          </bem.FormModal__item>

          <bem.FormModal__item m='actions'>
            <button
              onClick={this.onSubmit}
              className='mdl-button mdl-js-button mdl-button--raised mdl-button--colored'
            >
              {t('Create')}
            </button>
          </bem.FormModal__item>
        </bem.FormModal__item>
      </bem.FormModal__form>
    );
  }
};

export class RESTServicesList extends React.Component {
  constructor(props){
    super(props);
    this.state = {};
    autoBind(this);
  }

  render() {
    let services = [
      {
        name: 'Service 1',
        count: 20
      },
      {
        name: 'Service 2',
        count: 20
      },
      {
        name: 'Service 3',
        count: 20
      }
    ];
    return (
      <bem.FormView__cell m='REST-services-list'>
        <bem.FormView__group m='headings'>
          <bem.FormView__cell m='label'>
            X Services
          </bem.FormView__cell>
        </bem.FormView__group>
        <bem.FormView__cell m={['REST-services-table', 'box']}>
          <bem.FormView__group>
            <bem.FormView__group m={['items', 'headings']}>
              <bem.FormView__label m='name'>{t('Service Name')}</bem.FormView__label>
              <bem.FormView__label m='count'>{t('Count')}</bem.FormView__label>
              <bem.FormView__label m='actions'></bem.FormView__label>
            </bem.FormView__group>

            {services.map((item, n) => {
              return (
                <bem.FormView__group m='items' key={n} >
                  <bem.FormView__label m='name'>
                    {item.name}
                  </bem.FormView__label>
                  <bem.FormView__label m='count'>
                    {item.count}
                  </bem.FormView__label>
                  <bem.FormView__label m='actions'>
                    ACTIONS
                  </bem.FormView__label>
                </bem.FormView__group>
              );
            })}
          </bem.FormView__group>
        </bem.FormView__cell>
      </bem.FormView__cell>
    );
  }
}
<commit_msg>fix error pointed out by linter<commit_after>import $ from 'jquery';
import React from 'react';
import Reflux from "reflux";
import reactMixin from 'react-mixin';
import autoBind from 'react-autobind';
import bem from '../bem';
import actions from '../actions';
import stores from '../stores';
import Select from 'react-select';
import {
  t
} from '../utils';

import DocumentTitle from 'react-document-title';

export default class RESTServices extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      currentAsset: this.props.asset,
      services: false
    };
    autoBind(this);
  }

  componentDidMount() {
    console.log(this.state);
    this.listenTo(stores.asset, this.onAssetChange);
  }

  onAssetChange(data) {
    if (data.assetUid === this.state.currentAsset.uid) {
      this.setState({
        isAwaitingAssetChange: false,
        isCopyFormVisible: false
      });
    }
  }

  newServiceModal() {
    stores.pageState.showModal({
      type: 'rest-services',
      sid: false
    });
  }

  render () {
    var docTitle = this.props.asset.name || t('Untitled');
    return (
      <DocumentTitle title={`${docTitle} | KoboToolbox`}>
        <bem.FormView m={this.state.services ? 'form-settings-REST' : 'form-settings-REST-empty'}>
          {this.state.services &&

              <RESTServicesList/>
              <button
                className='mdl-button mdl-button--raised mdl-button--colored'
                onClick={this.newServiceModal}
              >
                {t('Register a New Service')}
              </button>

          }

          {!this.state.services &&
          <bem.Empty>
            <bem.Empty__inner>

{t('This project does not have any REST services yet!')}

                {t('You can use REST services to automatically post submissions to a third-party application.')}

                  {t('Learn more')}

              <button
                className='mdl-button mdl-button--raised mdl-button--colored'
                onClick={this.newServiceModal}
              >
                {t('Register a New Service')}
              </button>
            </bem.Empty__inner>
          </bem.Empty>
          }
        </bem.FormView>
      </DocumentTitle>
    );
  }
};
reactMixin(RESTServices.prototype, Reflux.ListenerMixin);

export class RESTServicesForm extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      currentAssetUid: "TODO",
      name: '',
      url: 'https://',
      type: 'json',
      securityType: 'oauth',
      securityOptions: [
        {
          value: 'oauth',
          label: t('OAuth')
        },
        {
          value: 'auth_header',
          label: t('Authorization Header')
        }
      ],
      auth_header: ''
    };
    autoBind(this);
  }

  formItemChange(evt) {
    if (evt.target) {
      var val = evt.target.value;
      var attr = evt.target.name;
    } else {
      var val = evt;
      var attr = 'securityType';
    }

    this.setState({
      [attr]: val
    })
  }

  onSubmit(evt) {
    evt.preventDefault();
    actions.resources.registerRESTService(this.state.currentAssetUid, {
      name: this.state.name,
      url: this.state.url,
      type: this.state.type
    })
    return false;
  }

  render() {
    return (
      <bem.FormModal__form onSubmit={this.onSubmit}>
        <bem.FormModal__item m='wrapper'>

          <bem.FormModal__item>

              {t('Name')}

            <input
              type='text'
              id='rest-service-form--name'
              name='name'
              placeholder={t('Service Name')}
              value={this.state.name}
              onChange={this.formItemChange}
            />
          </bem.FormModal__item>

          <bem.FormModal__item>

              {t('Endpoint URL')}

            <input
              type='text'
              id='rest-service-form--url'
              name='url'
              placeholder={t('https://')}
              value={this.state.url}
              onChange={this.formItemChange}
            />
          </bem.FormModal__item>

          <bem.FormModal__item m='type'>

              {t('Type')}

            <bem.FormModal__item m={['half-width', 'half-width-left']}>
              <bem.FormModal__radio>
                <bem.FormModal__radioInput
                  type='radio'
                  value='json'
                  name='type'
                  onChange={this.formItemChange}
                  checked={this.state.type === 'json'}
                />
                <bem.FormModal__radioText>
                  {t('JSON')}
                </bem.FormModal__radioText>
              </bem.FormModal__radio>
            </bem.FormModal__item>

            <bem.FormModal__item m='half-width'>
              <bem.FormModal__radio>
                <bem.FormModal__radioInput
                  type='radio'
                  value='xml'
                  name='type'
                  onChange={this.formItemChange}
                  checked={this.state.type === 'xml'}
                />
                <bem.FormModal__radioText>
                  {t('XML')}
                </bem.FormModal__radioText>
              </bem.FormModal__radio>
            </bem.FormModal__item>
          </bem.FormModal__item>

          <bem.FormModal__item m='security'>

              {t('Security')}

            <Select
              id='rest-service-form--security'
              name='securityType'
              value={this.state.securityType}
              onChange={this.formItemChange}
              options={this.state.securityOptions}
            />
          </bem.FormModal__item>

          {this.state.securityType && this.state.securityType.value == 'auth_header' &&
            <bem.FormModal__item>

                {t('Authorization Header')}

              <input
                type='text'
                id='rest-service-form--authorization-header'
                name='auth_header'
                value={this.state.auth_header}
                onChange={this.formItemChange}
              />
            </bem.FormModal__item>
          }

          <bem.FormModal__item m='fields'>

              {t('Advanced Users')}

              {t('Post selected questions only (use question names, comma-delimited)')}

            <textarea
              id='rest-service-form--fields'
              className='questions'
              name='questions'
              value={this.state.questions}
              onChange={this.formItemChange}
            />
          </bem.FormModal__item>

          <bem.FormModal__item m='actions'>
            <button
              onClick={this.onSubmit}
              className='mdl-button mdl-js-button mdl-button--raised mdl-button--colored'
            >
              {t('Create')}
            </button>
          </bem.FormModal__item>
        </bem.FormModal__item>
      </bem.FormModal__form>
    );
  }
};

export class RESTServicesList extends React.Component {
  constructor(props){
    super(props);
    this.state = {};
    autoBind(this);
  }

  render() {
    let services = [
      {
        name: 'Service 1',
        count: 20
      },
      {
        name: 'Service 2',
        count: 20
      },
      {
        name: 'Service 3',
        count: 20
      }
    ];
    return (
      <bem.FormView__cell m='REST-services-list'>
        <bem.FormView__group m='headings'>
          <bem.FormView__cell m='label'>
            X Services
          </bem.FormView__cell>
        </bem.FormView__group>
        <bem.FormView__cell m={['REST-services-table', 'box']}>
          <bem.FormView__group>
            <bem.FormView__group m={['items', 'headings']}>
              <bem.FormView__label m='name'>{t('Service Name')}</bem.FormView__label>
              <bem.FormView__label m='count'>{t('Count')}</bem.FormView__label>
              <bem.FormView__label m='actions' />
            </bem.FormView__group>

            {services.map((item, n) => {
              return (
                <bem.FormView__group m='items' key={n} >
                  <bem.FormView__label m='name'>
                    {item.name}
                  </bem.FormView__label>
                  <bem.FormView__label m='count'>
                    {item.count}
                  </bem.FormView__label>
                  <bem.FormView__label m='actions'>
                    ACTIONS
                  </bem.FormView__label>
                </bem.FormView__group>
              );
            })}
          </bem.FormView__group>
        </bem.FormView__cell>
      </bem.FormView__cell>
    );
  }
}
<|endoftext|>


<commit_before>/**
 * Created by Marek on 10. 10. 2014.
 */

var Flyable = (function () {
    var MAX_SIZE = 2,
        MIN_SIZE = 0.1,
        SPEED = 0.003;

    var potatoTexture = PIXI.Texture.fromImage("/img/components/rajce.png");
    var potatoSmashedTextture = PIXI.Texture.fromImage("/img/components/rajce_end.png");
    var potatoSmudgeTexture = PIXI.Texture.fromImage("/img/components/rajce_end2.png");

    function Flyable(stage, renderer, $window, path, onAnimationEnd) {
        this.stage = stage;
        this.renderer = renderer;
        this.$window = $window;
        this.path = path;
        this.speed = SPEED;
        this.t = 0;
        this.state = 'ON_MY_WAY';

        this.potatoSprites = {
            normal: new PIXI.Sprite(potatoTexture),
            smashed: new PIXI.Sprite(potatoSmashedTextture),
            smudge: new PIXI.Sprite(potatoSmudgeTexture)
        }
        this.sprite = this.potatoSprites.normal;// create a new Sprite using the texture

        // center the sprites anchor point
        this.sprite.anchor.x = 0.5;
        this.sprite.anchor.y = 0.5;

        // move the sprite t the center of the screen
        this.sprite.position.x = this.path.start.x;
        this.sprite.position.y = this.path.start.y;

        this.sprite.rotation = Math.random()*2*Math.PI - Math.PI;

        this.stage.addChild(this.sprite);
    }

    Flyable.prototype.changeSprite =  function (to){
        to.anchor.x = 0.5;
        to.anchor.y = 0.5;

        to.scale.x = MIN_SIZE;
        to.scale.y = MIN_SIZE;

        to.position.x = this.path.end.x;
        to.position.y = this.path.end.y;

        to.rotation = this.sprite.rotation;

        var i = this.stage.children.indexOf(this.sprite);
        this.stage.addChildAt(to, i);
        this.stage.removeChild(this.sprite);
        this.sprite = to;
    };

    Flyable.prototype.render = function (delta) {
        this.t += this.speed*delta;
        if (this.state === 'ON_MY_WAY' && this.t > 1) {
            this.state = 'smashed';
            this.changeSprite(this.potatoSprites.smashed)
            this.t = 3000;
            return;
        }
        if (this.state === 'smashed'){
            this.t -= delta;
            if(this.t < 0){
                this.state = 'smudge';
                this.changeSprite(this.potatoSprites.smudge);
            }
            return;
        }
        if(this.state === 'smudge'){
            return;
        }

        this.t = this.t > 1 ? 1 : this.t;

        this.sprite.rotation += 0.002*delta;

        var u = {
            x: this.path.end.x - this.path.start.x,
            y: this.path.end.y - this.path.start.y
        };

        var x = this.path.start.x + this.t*u.x,
            y = this.path.start.y + this.t*u.y;

        this.sprite.position.x = x;
        this.sprite.position.y = y;

        this.sprite.scale.x = (1-this.t)*MAX_SIZE + MIN_SIZE;
        this.sprite.scale.y = this.sprite.scale.x;

    };
    return Flyable;
})();

var Game = (function () {
    function Game($window) {
        var _this = this;

        this.$window = $window;

        // create an new instance of a pixi stage
        this.stage = new PIXI.Stage(0xecf0f1, true);
        this.stage.setInteractive(false);

        // create a renderer instance
        // the 5the parameter is the anti aliasing
        this.renderer = PIXI.autoDetectRenderer($window.innerWidth, $window.innerHeight, null);

        // set the canvas width and height to fill the screen
        this.renderer.view.style.width = $window.innerWidth + "px";
        this.renderer.view.style.height = $window.innerHeight + "px";
        this.renderer.view.style.display = "block";

        // add render view to DOM
        $('#foo').append(this.renderer.view);

        this.prev = Date.now();
        function animate() {
            var current = Date.now();
            var delta = current - _this.prev;
            _this.prev = current;

            _this.render(delta);

            _this.renderer.render(_this.stage);
            requestAnimFrame( animate );
        }

        this.flyables = [];

        requestAnimFrame(animate);
    }

    Game.prototype.render = function (delta) {
        this.flyables.forEach(function (flyable) {
            if(flyable && flyable.render)
                flyable.render(delta);
        })
    };

    Game.prototype.throw = function(data){
        var _this = this;
        var path = {
            start: {
                x: _this.$window.innerWidth/2,
                y: _this.$window.innerHeight
            },
            end: {
                x: data.pageX || Math.random()*_this.$window.innerWidth,
                y: data.pageY || Math.random()*_this.$window.innerHeight
            }
        };

        this.flyables.push(new Flyable(this.stage, this.renderer, this.$window, path), function (flyable) {
            _this.flyables.splice(_this.flyables.indexOf(flyable));
        });
    };

    return Game;
})();<commit_msg>orezani<commit_after>/**
 * Created by Marek on 10. 10. 2014.
 */

var Flyable = (function () {
    var MAX_SIZE = 2,
        MIN_SIZE = 0.1,
        SPEED = 0.003;

    var potatoTexture = PIXI.Texture.fromImage("/img/components/rajce.png");
    var potatoSmashedTextture = PIXI.Texture.fromImage("/img/components/rajce_end.png");
    var potatoSmudgeTexture = PIXI.Texture.fromImage("/img/components/rajce_end2.png");

    function Flyable(stage, renderer, $window, path, onAnimationEnd) {
        this.stage = stage;
        this.renderer = renderer;
        this.$window = $window;
        this.path = path;
        this.speed = SPEED;
        this.t = 0;
        this.state = 'ON_MY_WAY';

        this.potatoSprites = {
            normal: new PIXI.Sprite(potatoTexture),
            smashed: new PIXI.Sprite(potatoSmashedTextture),
            smudge: new PIXI.Sprite(potatoSmudgeTexture)
        }
        this.sprite = this.potatoSprites.normal;// create a new Sprite using the texture

        // center the sprites anchor point
        this.sprite.anchor.x = 0.5;
        this.sprite.anchor.y = 0.5;

        // move the sprite t the center of the screen
        this.sprite.position.x = this.path.start.x;
        this.sprite.position.y = this.path.start.y;

        this.sprite.rotation = Math.random()*2*Math.PI - Math.PI;

        this.stage.addChild(this.sprite);
    }

    Flyable.prototype.changeSprite =  function (to){
        to.anchor.x = 0.5;
        to.anchor.y = 0.5;

        to.scale.x = MIN_SIZE;
        to.scale.y = MIN_SIZE;

        to.position.x = this.path.end.x;
        to.position.y = this.path.end.y;

        to.rotation = this.sprite.rotation;

        var i = this.stage.children.indexOf(this.sprite);
        this.stage.addChildAt(to, i);
        this.stage.removeChild(this.sprite);
        this.sprite = to;
    };

    Flyable.prototype.render = function (delta) {
        this.t += this.speed*delta;
        if (this.state === 'ON_MY_WAY' && this.t > 1) {
            this.state = 'smashed';
            this.changeSprite(this.potatoSprites.smashed)
            this.t = 3000;
            return;
        }
        if (this.state === 'smashed'){
            this.t -= delta;
            if(this.t < 0){
                this.state = 'smudge';
                this.changeSprite(this.potatoSprites.smudge);
            }
            return;
        }
        if(this.state === 'smudge'){
            return;
        }

        this.t = this.t > 1 ? 1 : this.t;

        this.sprite.rotation += 0.002*delta;

        var u = {
            x: this.path.end.x - this.path.start.x,
            y: this.path.end.y - this.path.start.y
        };

        var x = this.path.start.x + this.t*u.x,
            y = this.path.start.y + this.t*u.y;

        this.sprite.position.x = x;
        this.sprite.position.y = y;

        this.sprite.scale.x = (1-this.t)*MAX_SIZE + MIN_SIZE;
        this.sprite.scale.y = this.sprite.scale.x;

    };
    return Flyable;
})();

var Game = (function () {
    function Game($window) {
        var _this = this;

        this.$window = $window;

        // create an new instance of a pixi stage
        this.stage = new PIXI.Stage(0xecf0f1, true);

        // create a renderer instance
        // the 5the parameter is the anti aliasing
        this.renderer = PIXI.autoDetectRenderer($window.innerWidth, $window.innerHeight, null);

        // set the canvas width and height to fill the screen
        this.renderer.view.style.width = $window.innerWidth + "px";
        this.renderer.view.style.height = $window.innerHeight + "px";
        this.renderer.view.style.display = "block";

        // add render view to DOM
        $('#foo').append(this.renderer.view);

        this.prev = Date.now();
        function animate() {
            var current = Date.now();
            var delta = current - _this.prev;
            _this.prev = current;

            _this.render(delta);

            _this.renderer.render(_this.stage);
            requestAnimFrame( animate );
        }

        this.flyables = [];
        this.flyablesContainer = new PIXI.DisplayObjectContainer();
        this.stage.addChild(this.flyablesContainer);

        this.flyablesMask = new PIXI.Graphics();
        this.flyablesMask.position.x = $window.innerWidth / 2;
        this.flyablesMask.position.y = $window.innerHeight / 2;
        this.flyablesMask.lineStyle(0);

        this.flyablesContainer.mask = this.flyablesMask;

        this.stage.addChild(this.flyablesMask);

        requestAnimFrame(animate);
    }

    Game.prototype.render = function (delta) {
        var _this = this;
        this.flyables.forEach(function (flyable) {
            if(flyable && flyable.render)
                flyable.render(delta);

            _this.flyablesMask.clear();
            _this.flyablesMask.beginFill(0x8bc5ff, 0.4);
            _this.flyablesMask.moveTo(200, -400);
            _this.flyablesMask.lineTo(1200 , -400);
            _this.flyablesMask.lineTo(1200, 400) ;
            _this.flyablesMask.lineTo(-1200, 400) ;
            _this.flyablesMask.lineTo(-1200, -400);
        })
    };

    Game.prototype.throw = function(data){
        var _this = this;
        var path = {
            start: {
                x: _this.$window.innerWidth/2,
                y: _this.$window.innerHeight
            },
            end: {
                x: data.pageX || Math.random()*_this.$window.innerWidth,
                y: data.pageY || Math.random()*_this.$window.innerHeight
            }
        };

        this.flyables.push(new Flyable(this.flyablesContainer, this.renderer, this.$window, path), function (flyable) {
            _this.flyables.splice(_this.flyables.indexOf(flyable));
        });
    };

    return Game;
})();<|endoftext|>


<commit_before>define(["sprd/manager/ITextConfigurationManager", "flow", 'sprd/entity/Size', "text/entity/TextFlow", "text/entity/ParagraphElement", "text/entity/SpanElement", "sprd/type/Style", "text/entity/TextRange", "underscore"], function (Base, flow, Size, TextFlow, ParagraphElement, SpanElement, Style, TextRange, _) {
    var NON_BREAKABLE_WHITESPACE = 160;
    return Base.inherit("sprd.manager.TextConfigurationManager", {
        addParagraph: function (previousParagraph, tspan, text, textFlow) {
            if (!tspan || !text || !textFlow) {
                return;
            }

            if (previousParagraph) {
                previousParagraph.mergeElements();
            }

            // new paragraph
            var paragraph = new ParagraphElement({
                style: new Style({
                    textAnchor: tspan.textAnchor || text.textAnchor
                })
            });

            textFlow.addChild(paragraph);
            return paragraph;
        },

        generateWhiteSpaceTspans: function (tspansAmount, startY, yDelta) {
            var tspans = [], tempTSpan;
            for (var i = 0; i < tspansAmount; i++) {
                tempTSpan = {
                    content: [String.fromCharCode(NON_BREAKABLE_WHITESPACE)],
                    y: startY + i * yDelta,
                    textAnchor: "middle"
                };
                tspans.push(tempTSpan);
            }

            return tspans;
        },

        addEmptyTspans: function (tspans) {
            if (!tspans || tspans.length < 2) {
                return tspans;
            }

            var tspan, successorTspan, retArray = [];

            retArray.push(tspans[0]);
            for (var i = 0; i < tspans.length - 1; i++) {
                tspan = tspans[i];
                successorTspan = tspans[i + 1];

                var lineHeight = 1.2 * tspan.fontSize;

                if(tspan.fontSize === "0") {
                    tspan.fontSize = "0";
                    lineHeight = 0.1;
                }

                var y = Number(tspan.y),
                    nextY = Number(successorTspan.y);

                if (y !== y  || nextY !== nextY) {
                    retArray.push(successorTspan);
                    continue;
                }

                var yDiff = nextY - y;
                var whiteSpaceParagraphsAmount = Math.round(yDiff / lineHeight) - 1;

                if(tspan.fontSize === "0") {
                    whiteSpaceParagraphsAmount = 0;
                }

                var startY = y + lineHeight,
                    whiteSpaceTspans = this.generateWhiteSpaceTspans(whiteSpaceParagraphsAmount, startY, lineHeight);

                retArray = retArray.concat(whiteSpaceTspans);
                retArray.push(successorTspan);
            }

            return retArray;
        },

        initializeConfiguration: function (configuration, options, callback) {
            options = options || {};

            var self = this,
                content = configuration.$$ || {},
                svg = content.svg,
                printType = configuration.$.printType,
                product = configuration.$context.$contextModel,
                printArea,
                fontFamilies = product.$context.$contextModel.getCollection("fontFamilies"),
                properties = configuration.$.properties;

            var autogrow = properties && properties.autoGrow || options.isExample;
            configuration.set('autoGrow', configuration.$.autoGrow || autogrow);
            configuration.set('isNew', !!options.isExample);

            if (configuration.$initializedByManager) {
                callback && callback(null);
                return;
            }

            flow()
                .par(function (cb) {
                    printType.fetch(null, cb);
                }, function (cb) {
                    fontFamilies.fetch({
                        fullData: true
                    }, cb);
                })
                .seq(function () {
                    if (content && content.printArea) {
                        printArea = product.$.productType.getPrintAreaById(content.printArea.$.id);
                    } else {
                        printArea = configuration.$.printArea;
                    }
                })
                .seq(function () {
                    configuration.set({
                        printArea: printArea
                    });
                })
                .seq(function () {

                    if (svg) {

                        var text = svg.text,
                            textFlow = new TextFlow(),
                            content = text.content,
                            configurationObject = {};

                        var regExp = /^(\w+)\(([^(]+)\)/ig,
                            match;
                        if ((match = regExp.exec(text.transform))) {
                            var type = match[1];
                            var values = match[2].split(",");
                            if (type === "rotate") {
                                configurationObject.rotation = parseFloat(values.shift());
                            }
                        }

                        var lastTSpan = null,
                            paragraph = null,
                            maxLineWidth = parseFloat(text.width),
                            printTypeColor;

                        content = self.addEmptyTspans(content);
                        for (var i = 0; i < content.length; i++) {
                            var tspan = content[i];

                            if (_.isString(tspan)) {
                                // text tag without tspans
                                tspan = {
                                    content: [tspan]
                                }
                            }

                            if (!lastTSpan || tspan.hasOwnProperty("y")) {
                                paragraph = self.addParagraph(paragraph, tspan, text, textFlow)
                            }

                            maxLineWidth = Math.max(maxLineWidth, tspan.lineWidth || 0);

                            lastTSpan = tspan;

                            if (text.hasOwnProperty("printColorId")) {
                                tspan.printColorId = tspan.printColorId || text.printColorId;
                            }

                            tspan.fill = tspan.fill || text.fill;
                            tspan.fontFamilyId = tspan.fontFamilyId || text.fontFamilyId;
                            tspan.fontId = tspan.fontId || text.fontId;
                            tspan.fontSize = tspan.fontSize || text.fontSize;

                            printTypeColor = null;

                            if (tspan.printColorId) {
                                printTypeColor = printType.getPrintColorById(tspan.printColorId);
                            }

                            printTypeColor = printTypeColor || printType.getClosestPrintColor(tspan.fill);

                            var span = new SpanElement({
                                style: new Style({
                                    lineHeight: 1.2,
                                    font: fontFamilies.createItem(tspan.fontFamilyId).getFontById(tspan.fontId),
                                    fontSize: tspan.fontSize,
                                    printTypeColor: printTypeColor
                                }),
                                text: tspan.content[0] || String.fromCharCode(NON_BREAKABLE_WHITESPACE)
                            });

                            paragraph.addChild(span);
                        }

                        configurationObject.textFlow = textFlow;
                        configurationObject.selection = TextRange.createTextRange(0, 0);
                        configurationObject.textArea = new Size({
                            width: maxLineWidth,
                            height: text.height
                        });

                        configuration.set(configurationObject);

                    } else {
                        if (!configuration.textArea) {

                            var size = printArea.get("defaultBox") || printArea.get("boundary.size");

                            configuration.set("textArea", new Size({
                                width: configuration.get(size, "width"),
                                height: configuration.get(size, "height")
                            }));
                        }
                    }
                })
                .seq(function () {
                    configuration.adjustOffsetForFlipped()
                })
                .seq(function () {
                    configuration.$initializedByManager = true;
                })
                .exec(callback);
        }
    });
});
<commit_msg>:pick: DEV-128667 refactored the text processor to not die on division to 0<commit_after>define(["sprd/manager/ITextConfigurationManager", "flow", 'sprd/entity/Size', "text/entity/TextFlow", "text/entity/ParagraphElement", "text/entity/SpanElement", "sprd/type/Style", "text/entity/TextRange", "underscore"], function (Base, flow, Size, TextFlow, ParagraphElement, SpanElement, Style, TextRange, _) {
    var NON_BREAKABLE_WHITESPACE = 160;
    return Base.inherit("sprd.manager.TextConfigurationManager", {
        addParagraph: function (previousParagraph, tspan, text, textFlow) {
            if (!tspan || !text || !textFlow) {
                return;
            }

            if (previousParagraph) {
                previousParagraph.mergeElements();
            }

            // new paragraph
            var paragraph = new ParagraphElement({
                style: new Style({
                    textAnchor: tspan.textAnchor || text.textAnchor
                })
            });

            textFlow.addChild(paragraph);
            return paragraph;
        },

        generateWhiteSpaceTspans: function (tspansAmount, startY, yDelta) {
            var tspans = [], tempTSpan;
            for (var i = 0; i < tspansAmount; i++) {
                tempTSpan = {
                    content: [String.fromCharCode(NON_BREAKABLE_WHITESPACE)],
                    y: startY + i * yDelta,
                    textAnchor: "middle"
                };
                tspans.push(tempTSpan);
            }

            return tspans;
        },

        addEmptyTspans: function (tspans) {
            if (!tspans || tspans.length < 2) {
                return tspans;
            }

            var tspan, successorTspan, retArray = [];

            retArray.push(tspans[0]);
            for (var i = 0; i < tspans.length - 1; i++) {
                tspan = tspans[i];
                successorTspan = tspans[i + 1];

                var y = Number(tspan.y),
                    nextY = Number(successorTspan.y),
                    lineHeight = 1.2 * tspan.fontSize;

                if (y !== y  || nextY !== nextY) {
                    retArray.push(successorTspan);
                    continue;
                }

                var yDiff = nextY - y;
                var whiteSpaceParagraphsAmount = lineHeight > 0 ? Math.round(yDiff / lineHeight) - 1 : 0,
                    startY = y + lineHeight,
                    whiteSpaceTspans = this.generateWhiteSpaceTspans(whiteSpaceParagraphsAmount, startY, lineHeight);

                retArray = retArray.concat(whiteSpaceTspans);
                retArray.push(successorTspan);
            }

            return retArray;
        },

        initializeConfiguration: function (configuration, options, callback) {
            options = options || {};

            var self = this,
                content = configuration.$$ || {},
                svg = content.svg,
                printType = configuration.$.printType,
                product = configuration.$context.$contextModel,
                printArea,
                fontFamilies = product.$context.$contextModel.getCollection("fontFamilies"),
                properties = configuration.$.properties;

            var autogrow = properties && properties.autoGrow || options.isExample;
            configuration.set('autoGrow', configuration.$.autoGrow || autogrow);
            configuration.set('isNew', !!options.isExample);

            if (configuration.$initializedByManager) {
                callback && callback(null);
                return;
            }

            flow()
                .par(function (cb) {
                    printType.fetch(null, cb);
                }, function (cb) {
                    fontFamilies.fetch({
                        fullData: true
                    }, cb);
                })
                .seq(function () {
                    if (content && content.printArea) {
                        printArea = product.$.productType.getPrintAreaById(content.printArea.$.id);
                    } else {
                        printArea = configuration.$.printArea;
                    }
                })
                .seq(function () {
                    configuration.set({
                        printArea: printArea
                    });
                })
                .seq(function () {

                    if (svg) {

                        var text = svg.text,
                            textFlow = new TextFlow(),
                            content = text.content,
                            configurationObject = {};

                        var regExp = /^(\w+)\(([^(]+)\)/ig,
                            match;
                        if ((match = regExp.exec(text.transform))) {
                            var type = match[1];
                            var values = match[2].split(",");
                            if (type === "rotate") {
                                configurationObject.rotation = parseFloat(values.shift());
                            }
                        }

                        var lastTSpan = null,
                            paragraph = null,
                            maxLineWidth = parseFloat(text.width),
                            printTypeColor;

                        content = self.addEmptyTspans(content);
                        for (var i = 0; i < content.length; i++) {
                            var tspan = content[i];

                            if (_.isString(tspan)) {
                                // text tag without tspans
                                tspan = {
                                    content: [tspan]
                                }
                            }

                            if (!lastTSpan || tspan.hasOwnProperty("y")) {
                                paragraph = self.addParagraph(paragraph, tspan, text, textFlow)
                            }

                            maxLineWidth = Math.max(maxLineWidth, tspan.lineWidth || 0);

                            lastTSpan = tspan;

                            if (text.hasOwnProperty("printColorId")) {
                                tspan.printColorId = tspan.printColorId || text.printColorId;
                            }

                            tspan.fill = tspan.fill || text.fill;
                            tspan.fontFamilyId = tspan.fontFamilyId || text.fontFamilyId;
                            tspan.fontId = tspan.fontId || text.fontId;
                            tspan.fontSize = tspan.fontSize || text.fontSize;

                            printTypeColor = null;

                            if (tspan.printColorId) {
                                printTypeColor = printType.getPrintColorById(tspan.printColorId);
                            }

                            printTypeColor = printTypeColor || printType.getClosestPrintColor(tspan.fill);

                            var span = new SpanElement({
                                style: new Style({
                                    lineHeight: 1.2,
                                    font: fontFamilies.createItem(tspan.fontFamilyId).getFontById(tspan.fontId),
                                    fontSize: tspan.fontSize,
                                    printTypeColor: printTypeColor
                                }),
                                text: tspan.content[0] || String.fromCharCode(NON_BREAKABLE_WHITESPACE)
                            });

                            paragraph.addChild(span);
                        }

                        configurationObject.textFlow = textFlow;
                        configurationObject.selection = TextRange.createTextRange(0, 0);
                        configurationObject.textArea = new Size({
                            width: maxLineWidth,
                            height: text.height
                        });

                        configuration.set(configurationObject);

                    } else {
                        if (!configuration.textArea) {

                            var size = printArea.get("defaultBox") || printArea.get("boundary.size");

                            configuration.set("textArea", new Size({
                                width: configuration.get(size, "width"),
                                height: configuration.get(size, "height")
                            }));
                        }
                    }
                })
                .seq(function () {
                    configuration.adjustOffsetForFlipped()
                })
                .seq(function () {
                    configuration.$initializedByManager = true;
                })
                .exec(callback);
        }
    });
});
<|endoftext|>