<commit_before>import React, {Component, PropTypes} from 'react'
import filter from 'lodash/collection/filter'
import keys from 'lodash/object/keys'
import cx from 'classnames'

import isRequirementName from '../lib/is-requirement-name'

import Expression from './expression'
import Button from './button'

import './requirement.scss'

export default class Requirement extends Component {
	static propTypes = {
		addOverride: PropTypes.func.isRequired,
		computed: PropTypes.bool,
		filter: PropTypes.object,
		message: PropTypes.string,
		name: PropTypes.string,
		overridden: PropTypes.bool,
		path: PropTypes.array.isRequired,
		removeOverride: PropTypes.func.isRequired,
		result: PropTypes.object,
		toggleOverride: PropTypes.func.isRequired,
		topLevel: PropTypes.bool,
	}

	static defaultProps = {
		topLevel: false,
	}

	render() {
		const childKeys = filter(keys(this.props), isRequirementName)

		const result = this.props.result &&

<Expression expr={this.props.result} ctx={this.props} />

		const message = this.props.message &&

{this.props.message}

		const filterEl = this.props.filter &&

Filter: {JSON.stringify(this.props.filter, null, 2)}

		const wasComputed = this.props.hasOwnProperty('computed')
		const computationResult = this.props.computed

		const title = !(this.props.topLevel) && (
			<h2 className={`requirement--heading ${wasComputed ? computationResult ? 'computed-success' : 'computed-failure' : 'computed-not'}`}>

					{/*{this.props.computed ? '✓' : '×'}*/}
					{this.props.computed ? '●' : '○'}
					{` ${this.props.name}`}
					{this.props.overridden && {' (Overridden)'}}

				<Button
					className='requirement--override-button'
					onClick={ev => this.props.toggleOverride({ev, path: this.props.path})}
					title={this.props.overridden ? `Remove Override` : `Apply Override`}
				>
					{/*`[${this.props.overridden ? '⇢' : '⭃ ⭆ ⇝ ⤳'}]`*/}
					{/*`[${this.props.overridden ? '◯ ◉' : '◎'}]`*/}
					{`${this.props.overridden ? '◉' : '◎'}`}
				</Button>

		)

		const children = childKeys.map(key => <Requirement key={key}
			name={key}
			{...this.props[key]}
			path={this.props.path.concat(key)}
			addOverride={this.props.addOverride}
			toggleOverride={this.props.toggleOverride}
			removeOverride={this.props.removeOverride}
		/>)

		let override = (this.props.message && !this.props.result) && (

				<Button onClick={ev => this.props.removeOverride({ev, path: this.props.path})} type='flat'>Not yet…</Button>
				<Button onClick={ev => this.props.addOverride({ev, path: this.props.path})} type='flat'>Done!</Button>

		)

		return (
			<div className={cx(`requirement`, {overridden: this.props.overridden})}>
				{title}
				{message}
				{override}
				{filterEl}
				{result}
				{children.length ?
{children}
 : null}

		)
	}
}
<commit_msg>add .compact-results to requirements with only a <Course/> result<commit_after>import React, {Component, PropTypes} from 'react'
import filter from 'lodash/collection/filter'
import keys from 'lodash/object/keys'
import cx from 'classnames'

import isRequirementName from '../lib/is-requirement-name'

import Expression from './expression'
import Button from './button'

import './requirement.scss'

export default class Requirement extends Component {
	static propTypes = {
		addOverride: PropTypes.func.isRequired,
		computed: PropTypes.bool,
		filter: PropTypes.object,
		message: PropTypes.string,
		name: PropTypes.string,
		overridden: PropTypes.bool,
		path: PropTypes.array.isRequired,
		removeOverride: PropTypes.func.isRequired,
		result: PropTypes.object,
		toggleOverride: PropTypes.func.isRequired,
		topLevel: PropTypes.bool,
	}

	static defaultProps = {
		topLevel: false,
	}

	render() {
		const childKeys = filter(keys(this.props), isRequirementName)

		const extraClasses = {overridden: this.props.overridden}
		if (this.props.result && this.props.result.$type === 'course') {
			extraClasses['compact-results'] = true
		}

		const result = this.props.result &&

<Expression expr={this.props.result} ctx={this.props} />

		const message = this.props.message &&

{this.props.message}

		const filterEl = this.props.filter &&

Filter: {JSON.stringify(this.props.filter, null, 2)}

		const wasComputed = this.props.hasOwnProperty('computed')
		const computationResult = this.props.computed

		const title = !(this.props.topLevel) && (
			<h2 className={`requirement--heading ${wasComputed ? computationResult ? 'computed-success' : 'computed-failure' : 'computed-not'}`}>

					{/*{this.props.computed ? '✓' : '×'}*/}
					{this.props.computed ? '●' : '○'}
					{` ${this.props.name}`}
					{this.props.overridden && {' (Overridden)'}}

				<Button
					className='requirement--override-button'
					onClick={ev => this.props.toggleOverride({ev, path: this.props.path})}
					title={this.props.overridden ? `Remove Override` : `Apply Override`}
				>
					{/*`[${this.props.overridden ? '⇢' : '⭃ ⭆ ⇝ ⤳'}]`*/}
					{/*`[${this.props.overridden ? '◯ ◉' : '◎'}]`*/}
					{`${this.props.overridden ? '◉' : '◎'}`}
				</Button>

		)

		const children = childKeys.map(key => <Requirement key={key}
			name={key}
			{...this.props[key]}
			path={this.props.path.concat(key)}
			addOverride={this.props.addOverride}
			toggleOverride={this.props.toggleOverride}
			removeOverride={this.props.removeOverride}
		/>)

		let override = (this.props.message && !this.props.result) && (

				<Button onClick={ev => this.props.removeOverride({ev, path: this.props.path})} type='flat'>Not yet…</Button>
				<Button onClick={ev => this.props.addOverride({ev, path: this.props.path})} type='flat'>Done!</Button>

		)

		return (
			<div className={cx(`requirement`, extraClasses)}>
				{title}
				{message}
				{override}
				{filterEl}
				{result}
				{children.length ?
{children}
 : null}

		)
	}
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import {cancelEdit} from "../actions/index"
// redux form import
import { Field, reduxForm } from 'redux-form'

/**
 * @description
 * @constructor
 */
class EditPost extends Component {

    submit = ( values ) => {
        console.log( values );
    }

    render() {
        const { title, author, category, voteScore, body, id, timestamp } = this.props.postData;
        // const { handleSubmit } = this.props;

        return (

                { this.props.editable &&

                        <form onSubmit={ this.submit }>

                                Post Title
                                <Field name="firstName" component="input" type="text" />

                                Post Body
                                <Field name="lastName" component="input" type="text" />

                            <button type="submit">Submit</button>
                        </form>

                }

        )
    }
}

function mapStateToProps(state) {
    console.log(state);
    // let postToEdit = state.posts.items.find()
    return { editable : state.posts.editing }
}

function mapDispatchToProps(dispatch){
    return {
        cancelEdit : () => dispatch(cancelEdit()),
    }
}

EditPost = reduxForm({
    // a unique name for the form
    form: 'EditPostForm'
})(EditPost)

//  redux form example init from state
// You have to connect() to any reducers that you wish to connect to yourself
// InitializeFromStateForm = connect(
//     state => ({
//         initialValues: state.account.data // pull initial values from account reducer
//     }),
//     { load: loadAccount } // bind account loading action creator
// )(InitializeFromStateForm)

export default connect(mapStateToProps, mapDispatchToProps)(EditPost);<commit_msg>Fea: initial values in redux form set from redux stor<commit_after>import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import {cancelEdit} from "../actions/index"
// redux form import
import { Field, reduxForm } from 'redux-form'

/**
 * @description
 * @constructor
 */
class EditPost extends Component {

    submit = ( values ) => {
        console.log( values );
    }

    render() {
        const { title, author, category, voteScore, body, id, timestamp } = this.props.postData;
        // const { handleSubmit } = this.props;

        return (

                { this.props.editable &&

                        <form onSubmit={ this.submit }>

                                Post Title
                                <Field name="title" component="input" type="text" />

                                Post Body
                                <Field name="body" component="input" type="text" />

                            <button type="submit">Submit</button>
                        </form>

                }

        )
    }
}

function mapStateToProps(state) {
    console.log(state);
    // let postToEdit = state.posts.items.find
    let targetPost =   state.posts.items.find((item) => item.id === state.posts.openTarget)
    console.log( targetPost );
    return { editable : state.posts.editing, initialValues :  state.posts.items.find((item) => item.id === state.posts.openTarget) }
}

function mapDispatchToProps(dispatch){
    return {
        cancelEdit : () => dispatch(cancelEdit()),
    }
}

EditPost = reduxForm({
    // a unique name for the form
    form: 'EditPostForm'
})(EditPost)

//  redux form example init from state
// You have to connect() to any reducers that you wish to connect to yourself
// InitializeFromStateForm = connect(
//     state => ({
//         initialValues: state.account.data // pull initial values from account reducer
//     }),
//     { load: loadAccount } // bind account loading action creator
// )(InitializeFromStateForm)

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


<commit_before>/*
	The below work is licensed under Creative Commons GNU LGPL License.

	Original work:

	License:     http://creativecommons.org/licenses/LGPL/2.1/
	Author:      Stefan Goessner/2006
	Web:         http://goessner.net/

	Modifications made:

	Version:     0.9-p5
	Description: Restructured code, JSLint validated (no strict whitespaces),
	             added handling of empty arrays, empty strings, and int/floats values.
	Author:      Michael Schøler/2008-01-29
	Web:         http://michael.hinnerup.net/blog/2008/01/26/converting-json-to-xml-and-xml-to-json/

	Description: json2xml added support to convert functions as CDATA
	             so it will be easy to write characters that cause some problems when convert
	Author:      Tony Tomov
*/

/*global alert */
var xmlJsonClass = {
	// Param "xml": Element or document DOM node.
	// Param "tab": Tab or indent string for pretty output formatting omit or use empty string "" to supress.
	// Returns:     JSON string
	xml2json: function(xml, tab) {
		if (xml.nodeType === 9) {
			// document node
			xml = xml.documentElement;
		}
		var nws = this.removeWhite(xml);
		var obj = this.toObj(nws);
		var json = this.toJson(obj, xml.nodeName, "\t");
		return "{\n" + tab + (tab ? json.replace(/\t/g, tab) : json.replace(/\t|\n/g, "")) + "\n}";
	},

	// Param "o":   JavaScript object
	// Param "tab": tab or indent string for pretty output formatting omit or use empty string "" to supress.
	// Returns:     XML string
	json2xml: function(o, tab) {
		var toXml = function(v, name, ind) {
			var xml = "";
			var i, n;
			if (v instanceof Array) {
				if (v.length === 0) {
					xml += ind + "<"+name+">__EMPTY_ARRAY_</"+name+">\n";
				}
				else {
					for (i = 0, n = v.length; i < n; i += 1) {
						var sXml = ind + toXml(v[i], name, ind+"\t") + "\n";
						xml += sXml;
					}
				}
			}
			else if (typeof(v) === "object") {
				var hasChild = false;
				xml += ind + "<" + name;
				var m;
				for (m in v) if (v.hasOwnProperty(m)) {
					if (m.charAt(0) === "@") {
						xml += " " + m.substr(1) + "=\"" + v[m].toString() + "\"";
					}
					else {
						hasChild = true;
					}
				}
				xml += hasChild ? ">" : "/>";
				if (hasChild) {
					for (m in v) if (v.hasOwnProperty(m)) {
						if (m === "#text") {
							xml += v[m];
						}
						else if (m === "#cdata") {
							xml += "<![CDATA[" + v[m] + "]]>";
						}
						else if (m.charAt(0) !== "@") {
							xml += toXml(v[m], m, ind+"\t");
						}
					}
					xml += (xml.charAt(xml.length - 1) === "\n" ? ind : "") + "</" + name + ">";
				}
			}
			else if (typeof(v) === "function") {
				xml += ind + "<" + name + ">" + "<![CDATA[" + v + "]]>" + "</" + name + ">";
			}
			else {
				if (v.toString() === "\"\"" || v.toString().length === 0) {
					xml += ind + "<" + name + ">__EMPTY_STRING_</" + name + ">";
				}
				else {
					xml += ind + "<" + name + ">" + v.toString() + "</" + name + ">";
				}
			}
			return xml;
		};
		var xml = "";
		var m;
		for (m in o) if (o.hasOwnProperty(m)) {
			xml += toXml(o[m], m, "");
		}
		return tab ? xml.replace(/\t/g, tab) : xml.replace(/\t|\n/g, "");
	},
	// Internal methods
	toObj: function(xml) {
		var o = {};
		var FuncTest = /function/i;
		if (xml.nodeType === 1) {
			// element node ..
			if (xml.attributes.length) {
				// element with attributes ..
				var i;
				for (i = 0; i < xml.attributes.length; i += 1) {
					o["@" + xml.attributes[i].nodeName] = (xml.attributes[i].nodeValue || "").toString();
				}
			}
			if (xml.firstChild) {
				// element has child nodes ..
				var textChild = 0, cdataChild = 0, hasElementChild = false;
				var n;
				for (n = xml.firstChild; n; n = n.nextSibling) {
					if (n.nodeType === 1) {
						hasElementChild = true;
					}
					else if (n.nodeType === 3 && n.nodeValue.match(/[^ \f\n\r\t\v]/)) {
						// non-whitespace text
						textChild += 1;
					}
					else if (n.nodeType === 4) {
						// cdata section node
						cdataChild += 1;
					}
				}
				if (hasElementChild) {
					if (textChild < 2 && cdataChild < 2) {
						// structured element with evtl. a single text or/and cdata node ..
						this.removeWhite(xml);
						for (n = xml.firstChild; n; n = n.nextSibling) {
							if (n.nodeType === 3) {
								// text node
								o["#text"] = this.escape(n.nodeValue);
							}
							else if (n.nodeType === 4) {
								// cdata node
								if (FuncTest.test(n.nodeValue)) {
									o[n.nodeName] = [o[n.nodeName], n.nodeValue];
								} else {
									o["#cdata"] = this.escape(n.nodeValue);
								}
							}
							else if (o[n.nodeName]) {
								// multiple occurence of element ..
								if (o[n.nodeName] instanceof Array) {
									o[n.nodeName][o[n.nodeName].length] = this.toObj(n);
								}
								else {
									o[n.nodeName] = [o[n.nodeName], this.toObj(n)];
								}
							}
							else {
								// first occurence of element ..
								o[n.nodeName] = this.toObj(n);
							}
						}
					}
					else {
						// mixed content
						if (!xml.attributes.length) {
							o = this.escape(this.innerXml(xml));
						}
						else {
							o["#text"] = this.escape(this.innerXml(xml));
						}
					}
				}
				else if (textChild) {
					// pure text
					if (!xml.attributes.length) {
						o = this.escape(this.innerXml(xml));
						if (o === "__EMPTY_ARRAY_") {
							o = "[]";
						} else if (o === "__EMPTY_STRING_") {
							o = "";
						}
					}
					else {
						o["#text"] = this.escape(this.innerXml(xml));
					}
				}
				else if (cdataChild) {
					// cdata
					if (cdataChild > 1) {
						o = this.escape(this.innerXml(xml));
					}
					else {
						for (n = xml.firstChild; n; n = n.nextSibling) {
							if(FuncTest.test(xml.firstChild.nodeValue)) {
								o = xml.firstChild.nodeValue;
								break;
							} else {
								o["#cdata"] = this.escape(n.nodeValue);
							}
						}
					}
				}
			}
			if (!xml.attributes.length && !xml.firstChild) {
				o = null;
			}
		}
		else if (xml.nodeType === 9) {
			// document.node
			o = this.toObj(xml.documentElement);
		}
		else {
			alert("unhandled node type: " + xml.nodeType);
		}
		return o;
	},
	toJson: function(o, name, ind, wellform) {
		if(wellform === undefined) wellform = true;
		var json = name ? ("\"" + name + "\"") : "", T = "\t", N = "\n";
		if(!wellform) {
			T= ""; N= "";
		}

		if (o === "[]") {
			json += (name ? ":[]" : "[]");
		}
		else if (o instanceof Array) {
			var n, i, ar=[];
			for (i = 0, n = o.length; i < n; i += 1) {
				ar[i] = this.toJson(o[i], "", ind + T, wellform);
			}
			json += (name ? ":[" : "[") + (ar.length > 1 ? (N + ind + T + ar.join(","+N + ind + T) + N + ind) : ar.join("")) + "]";
		}
		else if (o === null) {
			json += (name && ":") + "null";
		}
		else if (typeof(o) === "object") {
			var arr = [];
			var m;
			for (m in o) if (o.hasOwnProperty(m)) {
				arr[arr.length] = this.toJson(o[m], m, ind + T, wellform);
			}
			json += (name ? ":{" : "{") + (arr.length > 1 ? (N + ind + T + arr.join(","+N + ind + T) + N + ind) : arr.join("")) + "}";
		}
		else if (typeof(o) === "string") {
			var objRegExp  = /(^-?\d+\.?\d*$)/;
			var FuncTest = /function/i;
			var os = o.toString();
			if (objRegExp.test(os) || FuncTest.test(os) || os==="false" || os==="true") {
				// int or float
				json += (name && ":")  + "\"" +os + "\"";
			}
			else {
				json += (name && ":") + "\"" + o.replace(/\\/g,'\\\\').replace(/\"/g,'\\"') + "\"";
			}
		}
		else {
			json += (name && ":") +  "\"" + o.toString()+ "\"";
		}
		return json;
	},
	innerXml: function(node) {
		var s = "";
		if ("innerHTML" in node) {
			s = node.innerHTML;
		}
		else {
			var asXml = function(n) {
				var s = "", i;
				if (n.nodeType === 1) {
					s += "<" + n.nodeName;
					for (i = 0; i < n.attributes.length; i += 1) {
						s += " " + n.attributes[i].nodeName + "=\"" + (n.attributes[i].nodeValue || "").toString() + "\"";
					}
					if (n.firstChild) {
						s += ">";
						for (var c = n.firstChild; c; c = c.nextSibling) {
							s += asXml(c);
						}
						s += "</" + n.nodeName + ">";
					}
					else {
						s += "/>";
					}
				}
				else if (n.nodeType === 3) {
					s += n.nodeValue;
				}
				else if (n.nodeType === 4) {
					s += "<![CDATA[" + n.nodeValue + "]]>";
				}
				return s;
			};
			for (var c = node.firstChild; c; c = c.nextSibling) {
				s += asXml(c);
			}
		}
		return s;
	},
	escape: function(txt) {
		return txt.replace(/[\\]/g, "\\\\").replace(/[\"]/g, '\\"').replace(/[\n]/g, '\\n').replace(/[\r]/g, '\\r');
	},
	removeWhite: function(e) {
		e.normalize();
		var n;
		for (n = e.firstChild; n; ) {
			if (n.nodeType === 3) {
				// text node
				if (!n.nodeValue.match(/[^ \f\n\r\t\v]/)) {
					// pure whitespace text node
					var nxt = n.nextSibling;
					e.removeChild(n);
					n = nxt;
				}
				else {
					n = n.nextSibling;
				}
			}
			else if (n.nodeType === 1) {
				// element node
				this.removeWhite(n);
				n = n.nextSibling;
			}
			else {
				// any other node
				n = n.nextSibling;
			}
		}
		return e;
	}
};<commit_msg>Some fixes in toJson function. Thanks to Oleg<commit_after>/*
	The below work is licensed under Creative Commons GNU LGPL License.

	Original work:

	License:     http://creativecommons.org/licenses/LGPL/2.1/
	Author:      Stefan Goessner/2006
	Web:         http://goessner.net/

	Modifications made:

	Version:     0.9-p5
	Description: Restructured code, JSLint validated (no strict whitespaces),
	             added handling of empty arrays, empty strings, and int/floats values.
	Author:      Michael Schøler/2008-01-29
	Web:         http://michael.hinnerup.net/blog/2008/01/26/converting-json-to-xml-and-xml-to-json/

	Description: json2xml added support to convert functions as CDATA
	             so it will be easy to write characters that cause some problems when convert
	Author:      Tony Tomov
*/

/*global alert */
var xmlJsonClass = {
	// Param "xml": Element or document DOM node.
	// Param "tab": Tab or indent string for pretty output formatting omit or use empty string "" to supress.
	// Returns:     JSON string
	xml2json: function(xml, tab) {
		if (xml.nodeType === 9) {
			// document node
			xml = xml.documentElement;
		}
		var nws = this.removeWhite(xml);
		var obj = this.toObj(nws);
		var json = this.toJson(obj, xml.nodeName, "\t");
		return "{\n" + tab + (tab ? json.replace(/\t/g, tab) : json.replace(/\t|\n/g, "")) + "\n}";
	},

	// Param "o":   JavaScript object
	// Param "tab": tab or indent string for pretty output formatting omit or use empty string "" to supress.
	// Returns:     XML string
	json2xml: function(o, tab) {
		var toXml = function(v, name, ind) {
			var xml = "";
			var i, n;
			if (v instanceof Array) {
				if (v.length === 0) {
					xml += ind + "<"+name+">__EMPTY_ARRAY_</"+name+">\n";
				}
				else {
					for (i = 0, n = v.length; i < n; i += 1) {
						var sXml = ind + toXml(v[i], name, ind+"\t") + "\n";
						xml += sXml;
					}
				}
			}
			else if (typeof(v) === "object") {
				var hasChild = false;
				xml += ind + "<" + name;
				var m;
				for (m in v) if (v.hasOwnProperty(m)) {
					if (m.charAt(0) === "@") {
						xml += " " + m.substr(1) + "=\"" + v[m].toString() + "\"";
					}
					else {
						hasChild = true;
					}
				}
				xml += hasChild ? ">" : "/>";
				if (hasChild) {
					for (m in v) if (v.hasOwnProperty(m)) {
						if (m === "#text") {
							xml += v[m];
						}
						else if (m === "#cdata") {
							xml += "<![CDATA[" + v[m] + "]]>";
						}
						else if (m.charAt(0) !== "@") {
							xml += toXml(v[m], m, ind+"\t");
						}
					}
					xml += (xml.charAt(xml.length - 1) === "\n" ? ind : "") + "</" + name + ">";
				}
			}
			else if (typeof(v) === "function") {
				xml += ind + "<" + name + ">" + "<![CDATA[" + v + "]]>" + "</" + name + ">";
			}
			else {
				if (v.toString() === "\"\"" || v.toString().length === 0) {
					xml += ind + "<" + name + ">__EMPTY_STRING_</" + name + ">";
				}
				else {
					xml += ind + "<" + name + ">" + v.toString() + "</" + name + ">";
				}
			}
			return xml;
		};
		var xml = "";
		var m;
		for (m in o) if (o.hasOwnProperty(m)) {
			xml += toXml(o[m], m, "");
		}
		return tab ? xml.replace(/\t/g, tab) : xml.replace(/\t|\n/g, "");
	},
	// Internal methods
	toObj: function(xml) {
		var o = {};
		var FuncTest = /function/i;
		if (xml.nodeType === 1) {
			// element node ..
			if (xml.attributes.length) {
				// element with attributes ..
				var i;
				for (i = 0; i < xml.attributes.length; i += 1) {
					o["@" + xml.attributes[i].nodeName] = (xml.attributes[i].nodeValue || "").toString();
				}
			}
			if (xml.firstChild) {
				// element has child nodes ..
				var textChild = 0, cdataChild = 0, hasElementChild = false;
				var n;
				for (n = xml.firstChild; n; n = n.nextSibling) {
					if (n.nodeType === 1) {
						hasElementChild = true;
					}
					else if (n.nodeType === 3 && n.nodeValue.match(/[^ \f\n\r\t\v]/)) {
						// non-whitespace text
						textChild += 1;
					}
					else if (n.nodeType === 4) {
						// cdata section node
						cdataChild += 1;
					}
				}
				if (hasElementChild) {
					if (textChild < 2 && cdataChild < 2) {
						// structured element with evtl. a single text or/and cdata node ..
						this.removeWhite(xml);
						for (n = xml.firstChild; n; n = n.nextSibling) {
							if (n.nodeType === 3) {
								// text node
								o["#text"] = this.escape(n.nodeValue);
							}
							else if (n.nodeType === 4) {
								// cdata node
								if (FuncTest.test(n.nodeValue)) {
									o[n.nodeName] = [o[n.nodeName], n.nodeValue];
								} else {
									o["#cdata"] = this.escape(n.nodeValue);
								}
							}
							else if (o[n.nodeName]) {
								// multiple occurence of element ..
								if (o[n.nodeName] instanceof Array) {
									o[n.nodeName][o[n.nodeName].length] = this.toObj(n);
								}
								else {
									o[n.nodeName] = [o[n.nodeName], this.toObj(n)];
								}
							}
							else {
								// first occurence of element ..
								o[n.nodeName] = this.toObj(n);
							}
						}
					}
					else {
						// mixed content
						if (!xml.attributes.length) {
							o = this.escape(this.innerXml(xml));
						}
						else {
							o["#text"] = this.escape(this.innerXml(xml));
						}
					}
				}
				else if (textChild) {
					// pure text
					if (!xml.attributes.length) {
						o = this.escape(this.innerXml(xml));
						if (o === "__EMPTY_ARRAY_") {
							o = "[]";
						} else if (o === "__EMPTY_STRING_") {
							o = "";
						}
					}
					else {
						o["#text"] = this.escape(this.innerXml(xml));
					}
				}
				else if (cdataChild) {
					// cdata
					if (cdataChild > 1) {
						o = this.escape(this.innerXml(xml));
					}
					else {
						for (n = xml.firstChild; n; n = n.nextSibling) {
							if(FuncTest.test(xml.firstChild.nodeValue)) {
								o = xml.firstChild.nodeValue;
								break;
							} else {
								o["#cdata"] = this.escape(n.nodeValue);
							}
						}
					}
				}
			}
			if (!xml.attributes.length && !xml.firstChild) {
				o = null;
			}
		}
		else if (xml.nodeType === 9) {
			// document.node
			o = this.toObj(xml.documentElement);
		}
		else {
			alert("unhandled node type: " + xml.nodeType);
		}
		return o;
	},
	toJson: function(o, name, ind, wellform) {
		if(wellform === undefined) wellform = true;
		var json = name ? ("\"" + name + "\"") : "", tab = "\t", newline = "\n";
		if(!wellform) {
			tab= ""; newline= "";
		}

		if (o === "[]") {
			json += (name ? ":[]" : "[]");
		}
		else if (o instanceof Array) {
			var n, i, ar=[];
			for (i = 0, n = o.length; i < n; i += 1) {
				ar[i] = this.toJson(o[i], "", ind + tab, wellform);
			}
			json += (name ? ":[" : "[") + (ar.length > 1 ? (newline + ind + tab + ar.join(","+newline + ind + tab) + newline + ind) : ar.join("")) + "]";
		}
		else if (o === null) {
			json += (name && ":") + "null";
		}
		else if (typeof(o) === "object") {
			var arr = [], m;
			for (m in o) {
				if (o.hasOwnProperty(m)) {
					arr[arr.length] = this.toJson(o[m], m, ind + tab, wellform);
			}
		}
			json += (name ? ":{" : "{") + (arr.length > 1 ? (newline + ind + tab + arr.join(","+newline + ind + tab) + newline + ind) : arr.join("")) + "}";
		}
		else if (typeof(o) === "string") {
			/*
			var objRegExp  = /(^-?\d+\.?\d*$)/;
			var FuncTest = /function/i;
			var os = o.toString();
			if (objRegExp.test(os) || FuncTest.test(os) || os==="false" || os==="true") {
				// int or float
				json += (name && ":")  + "\"" +os + "\"";
			}
			else {
			*/
				json += (name && ":") + "\"" + o.replace(/\\/g,'\\\\').replace(/\"/g,'\\"') + "\"";
			//}
			}
		else {
			json += (name && ":") +  "\"" + o.toString()+ "\"";
		}
		return json;
	},
	innerXml: function(node) {
		var s = "";
		if ("innerHTML" in node) {
			s = node.innerHTML;
		}
		else {
			var asXml = function(n) {
				var s = "", i;
				if (n.nodeType === 1) {
					s += "<" + n.nodeName;
					for (i = 0; i < n.attributes.length; i += 1) {
						s += " " + n.attributes[i].nodeName + "=\"" + (n.attributes[i].nodeValue || "").toString() + "\"";
					}
					if (n.firstChild) {
						s += ">";
						for (var c = n.firstChild; c; c = c.nextSibling) {
							s += asXml(c);
						}
						s += "</" + n.nodeName + ">";
					}
					else {
						s += "/>";
					}
				}
				else if (n.nodeType === 3) {
					s += n.nodeValue;
				}
				else if (n.nodeType === 4) {
					s += "<![CDATA[" + n.nodeValue + "]]>";
				}
				return s;
			};
			for (var c = node.firstChild; c; c = c.nextSibling) {
				s += asXml(c);
			}
		}
		return s;
	},
	escape: function(txt) {
		return txt.replace(/[\\]/g, "\\\\").replace(/[\"]/g, '\\"').replace(/[\n]/g, '\\n').replace(/[\r]/g, '\\r');
	},
	removeWhite: function(e) {
		e.normalize();
		var n;
		for (n = e.firstChild; n; ) {
			if (n.nodeType === 3) {
				// text node
				if (!n.nodeValue.match(/[^ \f\n\r\t\v]/)) {
					// pure whitespace text node
					var nxt = n.nextSibling;
					e.removeChild(n);
					n = nxt;
				}
				else {
					n = n.nextSibling;
				}
			}
			else if (n.nodeType === 1) {
				// element node
				this.removeWhite(n);
				n = n.nextSibling;
			}
			else {
				// any other node
				n = n.nextSibling;
			}
		}
		return e;
	}
};<|endoftext|>


<commit_before>
/*!
 * Module dependencies.
 */

var mongoose = require('mongoose');
var LocalStrategy = require('passport-local').Strategy;
var User = mongoose.model('User');

var local = require('./passport/local');
var google = require('./passport/google');
var facebook = require('./passport/facebook');
var twitter = require('./passport/twitter');
var linkedin = require('./passport/linkedin');
var github = require('./passport/github');

/**
 * Expose
 */

module.exports = function (passport, config) {
  // serialize sessions
  passport.serializeUser(function(user, done) {
    done(null, user.id)
  })

  passport.deserializeUser(function(id, done) {
    User.findOne({ _id: id }, function (err, user) {
      done(err, user)
    })
  })

  // use these strategies
  passport.use(local);
  passport.use(google);
  passport.use(facebook);
  passport.use(twitter);
  passport.use(linkedin);
  passport.use(github);
};
<commit_msg>use the .load method to deserialize the user<commit_after>
/*!
 * Module dependencies.
 */

var mongoose = require('mongoose');
var LocalStrategy = require('passport-local').Strategy;
var User = mongoose.model('User');

var local = require('./passport/local');
var google = require('./passport/google');
var facebook = require('./passport/facebook');
var twitter = require('./passport/twitter');
var linkedin = require('./passport/linkedin');
var github = require('./passport/github');

/**
 * Expose
 */

module.exports = function (passport, config) {
  // serialize sessions
  passport.serializeUser(function(user, done) {
    done(null, user.id)
  })

  passport.deserializeUser(function(id, done) {
    User.load({ criteria: { _id: id } }, function (err, user) {
      done(err, user)
    })
  })

  // use these strategies
  passport.use(local);
  passport.use(google);
  passport.use(facebook);
  passport.use(twitter);
  passport.use(linkedin);
  passport.use(github);
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import {Form, FormControl, FormGroup, Button} from 'react-bootstrap';
import SignupModal from './SignupModal';
import * as config from '../../config';
import {Link} from 'react-router-dom';

import axios from 'axios';
axios.defaults.withCredentials = true;

class SignupForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            email: '',
            isModalOpen: false,
            isSignupButtonLoading: false,
            invalidEmail: false
        };
    }

    hideModal = () => {
        this.setState({isModalOpen: false});
    }

    handleEmailChange = (event) => {
        this.setState({email: event.target.value});
        if (this.state.invalidEmail) {
            this.setState({invalidEmail: false});
        }
    }

    signupSubmit = (event) => {
        event.preventDefault();
        this.setState({isSignupButtonLoading: true});

        axios.post(config.backendUrl + '/signup', {email: this.state.email})
        .then(res => {
            if (res.status === 200 && res.data === 'Signup OK') {
                this.setState({
                    isSignupButtonLoading: false,
                    isModalOpen: true,
                    email: ''
                });
            }
        })
        .catch(error => {
            if (error.response.status === 400 && error.response.data === 'Invalid univesity email') {
                console.log('Invalid mail');
                this.setState({
                    isSignupButtonLoading: false,
                    invalidEmail: true
                });
            }
            else {
                console.log(error);
            }
        })
    }

    render() {
        return (

                Το ακαδημαϊκό σου email:
                <Form horizontal className="signup-form" onSubmit={this.signupSubmit}>
                    <FormGroup
                        validationState={this.state.invalidEmail ? "warning" : null}
                        ref={(input) => { this.signupForm = input; }}
                    >
                        <FormControl
                            type="text"
                            name="email"
                            autoComplete="off"
                            placeholder="example@uoa.gr"
                            value={this.state.email}
                            disabled={this.state.isSignupButtonLoading}
                            onChange={this.handleEmailChange}
                        />
                    </FormGroup>
                    <Button
                        type="submit"
                        bsStyle="primary"
                        id="btn-signup"
                        disabled={this.state.isSignupButtonLoading}
                        onClick={!this.state.isSignupButtonLoading? this.signupSubmit : null}
                    >
                        {this.state.isSignupButtonLoading? 'Εγγραφή...' : 'Εγγραφή'}
                    </Button>
                    {this.state.invalidEmail ?

                            Υπήρξε κάποιο πρόβλημα! Χρησιμοποίησες ένα <Link to="/faq" target="_blank">έγκυρο ακαδημαϊκό</Link> email?

                    : null}
                </Form>

Η διεύθυνση email σου θα χρησιμοποιηθεί μόνο για να επιβεβαιωθεί ότι είσαι φοιτητής.

                <SignupModal isModalOpen={this.state.isModalOpen} hideModal={this.hideModal} />

        );
    }
}

export default SignupForm;
<commit_msg>Remove old console log<commit_after>import React, { Component } from 'react';
import {Form, FormControl, FormGroup, Button} from 'react-bootstrap';
import SignupModal from './SignupModal';
import * as config from '../../config';
import {Link} from 'react-router-dom';

import axios from 'axios';
axios.defaults.withCredentials = true;

class SignupForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            email: '',
            isModalOpen: false,
            isSignupButtonLoading: false,
            invalidEmail: false
        };
    }

    hideModal = () => {
        this.setState({isModalOpen: false});
    }

    handleEmailChange = (event) => {
        this.setState({email: event.target.value});
        if (this.state.invalidEmail) {
            this.setState({invalidEmail: false});
        }
    }

    signupSubmit = (event) => {
        event.preventDefault();
        this.setState({isSignupButtonLoading: true});

        axios.post(config.backendUrl + '/signup', {email: this.state.email})
        .then(res => {
            if (res.status === 200 && res.data === 'Signup OK') {
                this.setState({
                    isSignupButtonLoading: false,
                    isModalOpen: true,
                    email: ''
                });
            }
        })
        .catch(error => {
            if (error.response.status === 400 && error.response.data === 'Invalid univesity email') {
                this.setState({
                    isSignupButtonLoading: false,
                    invalidEmail: true
                });
            }
            else {
                console.log(error);
            }
        })
    }

    render() {
        return (

                Το ακαδημαϊκό σου email:
                <Form horizontal className="signup-form" onSubmit={this.signupSubmit}>
                    <FormGroup
                        validationState={this.state.invalidEmail ? "warning" : null}
                        ref={(input) => { this.signupForm = input; }}
                    >
                        <FormControl
                            type="text"
                            name="email"
                            autoComplete="off"
                            placeholder="example@uoa.gr"
                            value={this.state.email}
                            disabled={this.state.isSignupButtonLoading}
                            onChange={this.handleEmailChange}
                        />
                    </FormGroup>
                    <Button
                        type="submit"
                        bsStyle="primary"
                        id="btn-signup"
                        disabled={this.state.isSignupButtonLoading}
                        onClick={!this.state.isSignupButtonLoading? this.signupSubmit : null}
                    >
                        {this.state.isSignupButtonLoading? 'Εγγραφή...' : 'Εγγραφή'}
                    </Button>
                    {this.state.invalidEmail ?

                            Υπήρξε κάποιο πρόβλημα! Χρησιμοποίησες ένα <Link to="/faq" target="_blank">έγκυρο ακαδημαϊκό</Link> email?

                    : null}
                </Form>

Η διεύθυνση email σου θα χρησιμοποιηθεί μόνο για να επιβεβαιωθεί ότι είσαι φοιτητής.

                <SignupModal isModalOpen={this.state.isModalOpen} hideModal={this.hideModal} />

        );
    }
}

export default SignupForm;
<|endoftext|>


<commit_before>(function($){

	// ::::::::::::::::
	// Kerning Plugin
	// ::::::::::::::::
	//
	// by Naokazu Terada
	//
	// Usage
	// $.getJSON("/script/kerning-data.json" , function(data) {
	// 		$('h2,h3,h4,h5').kerning({"data":data});
	// });
	//

	$.fn.kerning=function(config){

		var defaults = {
			data: [
				{
			  	"kerning":{
						 "、":{"L":0,"R":-0.4}
						,"。":{"L":0,"R":-0.4}
						,"「":{"L":-0.4,"R":0}
						,"」":{"L":0,"R":-0.4}
						,"（":{"L":-0.4,"R":0}
						,"）":{"L":0,"R":-0.4}
						,"・":{"L":-0.22,"R":-0.22}
			  	}
				}
			]
		};
		var options=$.extend(defaults, config);
		console.log(options);
		var kdata = options['data'][0]["kerning"];

		return this.each(function(i){

			var me = $(this),
					container = me,
					strArray = me.html(),
					content = '';

			// 全タグ除去
			// var strArray = me.html().replace(/(<([^>]+)>)/ig,"").split('');

			// アンカー以外のタグ除去
			// if(me.children('a').length){
			// 	container = me.children('a');
			// 	strArray = container.html().replace(/(<([^>]+)>)/ig,"").split('');
			// }else{
			// 	container = me;
			// 	strArray = me.html().replace(/(<([^>]+)>)/ig,"").split('');
			// }

			// for test
			var delimiter = me.data('delimiter');
			var linebreak = me.data('linebreak');
			if(delimiter!=undefined){
				strArray = (delimiter+strArray.join(delimiter)+delimiter).split('');
			}

			for (var i = 0; i < strArray.length; i++) {
				var str = strArray[i];
				var left = 0;
				var right = 0;
				if(kdata[str]){
					// console.log(str,kdata[str]);
					if(kdata[str]["L"]) left = kdata[str]["L"];
					if(kdata[str]["R"]) right = kdata[str]["R"];

					// for test
					if(linebreak!=undefined) content += ''+linebreak+'';

					content += ''+str+'';

					// for test
					if(linebreak!=undefined) content += ''+linebreak+'
';
				}
				else{
					content += str;
				}
				// console.log(str,left,right);

			};
			container.html(content);
		});
	};
})(jQuery);<commit_msg>option項目を追加<commit_after>(function($){

	// ::::::::::::::::
	// Kerning Plugin
	// ::::::::::::::::
	//
	// by Naokazu Terada
	//
	// Usage
	// $.getJSON("/script/kerning-data.json" , function(data) {
	// 		$('h2,h3,h4,h5').kerning({"data":data});
	// });
	//

	$.fn.kerning=function(config){

		var defaults = {
			removeTags: false,
			removeAnchorTags: false,
			data: [
				{
			  	"kerning":{
						 "、":{"L":0,"R":-0.4}
						,"。":{"L":0,"R":-0.4}
						,"「":{"L":-0.4,"R":0}
						,"」":{"L":0,"R":-0.4}
						,"（":{"L":-0.4,"R":0}
						,"）":{"L":0,"R":-0.4}
						,"・":{"L":-0.22,"R":-0.22}
			  	}
				}
			]
		};
		var options = $.extend(defaults, config);
		var kdata = options['data'][0]["kerning"];

		return this.each(function(i){

			var me = $(this),
					container = me,
					strArray = me.html(),
					content = '';

			if(options.removeAnchorTags){
				// アンカー以外のタグ除去
				// TODO: タグ外の部分も対象に
				if(me.children('a').length){
					container = me.children('a');
					strArray = container.html().replace(/(<([^>]+)>)/ig,"").split('');
				}else{
					container = me;
					strArray = me.html().replace(/(<([^>]+)>)/ig,"").split('');
				}
			}else if(options.removeTags){
				// 全タグ除去
				strArray = me.html().replace(/(<([^>]+)>)/ig,"").split('');
			}

			// for test
			var delimiter = me.data('delimiter');
			var linebreak = me.data('linebreak');
			if(delimiter!=undefined){
				strArray = (delimiter+strArray.join(delimiter)+delimiter).split('');
			}

			for (var i = 0; i < strArray.length; i++) {
				var str = strArray[i];
				var left = 0;
				var right = 0;
				if(kdata[str]){
					// console.log(str,kdata[str]);
					if(kdata[str]["L"]) left = kdata[str]["L"];
					if(kdata[str]["R"]) right = kdata[str]["R"];

					// for test
					if(linebreak!=undefined) content += ''+linebreak+'';

					content += ''+str+'';

					// for test
					if(linebreak!=undefined) content += ''+linebreak+'
';
				}
				else{
					content += str;
				}
				// console.log(str,left,right);

			};
			container.html(content);
		});
	};
})(jQuery);<|endoftext|>


<commit_before>var INTERVAL = 60000; // runs every minute

// TODO what should it do?
// * it should update the "inline timer" regularly
// * in some conditions:
// * only if the task has been created already
// *
var $minutes,
    $hours;

// it should pause the timer and then hide itself to show the play button
var update_displayed_time = function() {
    var current_minutes = parseInt($minutes.text()),
        current_hours   = parseInt($hours.text());

    current_minutes++;

    if (current_minutes > 59) {
        current_minutes = 0;
        current_hours++;
    }

    $minutes.text(current_minutes);
    $hours.text(current_hours);
}

jQuery(document).ready(function($) {
    // timers
    var inline = $('#timer-bar-elapsed'),
        $timer;

    // timer spans
    $minutes = $('#minutes > .timer-val'),
    $hours   = $('#hours > .timer-val');

    // buttons
    var $pause_button = $('#pause-btn'),
        $play_button  = $('#play-btn');

    // init timer
    $timer = $.timer(function() {
      update_displayed_time();
    });

    // bindings
    $pause_button.bind('click', function() {
        $timer.pause();
        $(this).hide();
        $play_button.show();
    });

    // it should restart the timer and then hide itself to show the pause button
    $play_button.bind('click', function() {
        $timer.play();
        $(this).hide();
        $pause_button.show();
    });

    // initial timer values
    $minutes.text('00');
    $hours.text('00');

    // TODO when should it start?
    $timer.set({ time: INTERVAL, autostart: true });
});
<commit_msg>specify radix in parseInt<commit_after>var INTERVAL = 60000; // runs every minute

// TODO what should it do?
// * it should update the "inline timer" regularly
// * in some conditions:
// * only if the task has been created already
// *
var $minutes,
    $hours;

// it should pause the timer and then hide itself to show the play button
var update_displayed_time = function() {
    var current_minutes = parseInt($minutes.text(), 10),
        current_hours   = parseInt($hours.text(), 10);

    current_minutes++;

    if (current_minutes > 59) {
        current_minutes = 0;
        current_hours++;
    }

    $minutes.text(current_minutes);
    $hours.text(current_hours);
}

jQuery(document).ready(function($) {
    // timers
    var inline = $('#timer-bar-elapsed'),
        $timer;

    // timer spans
    $minutes = $('#minutes > .timer-val'),
    $hours   = $('#hours > .timer-val');

    // buttons
    var $pause_button = $('#pause-btn'),
        $play_button  = $('#play-btn');

    // init timer
    $timer = $.timer(function() {
      update_displayed_time();
    });

    // bindings
    $pause_button.bind('click', function() {
        $timer.pause();
        $(this).hide();
        $play_button.show();
    });

    // it should restart the timer and then hide itself to show the pause button
    $play_button.bind('click', function() {
        $timer.play();
        $(this).hide();
        $pause_button.show();
    });

    // initial timer values
    $minutes.text('00');
    $hours.text('00');

    // TODO when should it start?
    $timer.set({ time: INTERVAL, autostart: true });
});
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2008 Brad Harris - bmharris@gmail.com
 * http://slikcalc.selfcontained.us
 * Code licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * version 1.0
 */
var slikcalc;if(!slikcalc){slikcalc={};}else if(typeof slikcalc!='object'){throw new Error('slikcalc already exists and is not an object');}
slikcalc={adapter:null,getValue:function(el){var value=null;var element=this.get(el);if(element!==null){value=this.isInput(element)?element.value:element.innerHTML;}
return value;},setValue:function(el,value){var element=this.get(el);if(element!==null){if(this.isInput(element)){element.value=value;}else{element.innerHTML=value;}}},getAmount:function(el){var amount=this.getValue(el);amount=amount!==null?parseFloat(this.formatCurrency(amount)):parseFloat(this.formatCurrency(0));return amount;},setAmount:function(el,value){this.setValue(el,this.formatCurrency(value));},isInput:function(element){return element.tagName==='INPUT'||element.tagName==='TEXTAREA'||element.tagName==='SELECT';},formatCurrency:function(num){num=isNaN(num)||num===''||num===null?0.00:num;return parseFloat(num).toFixed(2);},trim:function(string){return string.replace(/^\s+|\s+$/g,'');},get:function(id){if(this.adapter===null){throw new Error('slikcalc requires an external javascript library adapter');}
return this.adapter.get(id);},validateAdapter:function(){if(this.adapter===null){throw new Error('slikcalc requires an external javascript library adapter');}},addListener:function(elementId,type,method,scope){this.validateAdapter();this.adapter.addListener(elementId,type,method,scope);},addOnLoad:function(method,scope){this.validateAdapter();this.adapter.addOnLoad(method,scope);},createCustomEvent:function(eventType){this.validateAdapter();return this.adapter.createCustomEvent(eventType);},bindEvent:function(event,method,scope){this.validateAdapter();this.adapter.bindEvent(event,method,scope);},fireEvent:function(event){this.validateAdapter();this.adapter.fireEvent(event);},extend:function(subc,superc){if(!superc||!subc){throw new Error('slikcalc.extend failed, please check that all dependencies are included.');}
var F=function(){};F.prototype=superc.prototype;subc.prototype=new F();subc.prototype.constructor=subc;subc.prototype.parent=superc.prototype;subc.prototype.parent.constructor=superc;}};slikcalc.BaseCalc=function(config){config.total=config.total||{};this.totalId=config.total.id||null;this.totalOperator=config.total.operator||'+';this.calcOnLoad=config.calcOnLoad||false;this.calculationComplete=slikcalc.createCustomEvent('calculationComplete');this.registerListeners=config.registerListeners||false;slikcalc.addOnLoad(this.baseInitialize,this);};slikcalc.BaseCalc.prototype={calculationComplete:null,lastKeyUp:null,calculations:0,totalId:null,totalOperator:null,calcOnLoad:false,registerListeners:false,keyupDelay:600,initialized:false,baseInitialize:function(){if(this.initialized===false){this.initialized=true;if(this.initialize!==undefined&&typeof this.initialize==='function'){this.initialize();}}},dependsOn:function(dependCalc){slikcalc.bindEvent(dependCalc.calculationComplete,this.processCalculation,this);return dependCalc;},triggers:function(triggeredCalc){slikcalc.bindEvent(this.calculationComplete,triggeredCalc.processCalculation,triggeredCalc);return triggeredCalc;},keyupEvent:function(){this.lastKeyup=new Date().getTime();var that=this;this.calculations=this.calculations+1;var calculation=this.calculations;setTimeout(function(){var currentTime=new Date().getTime();var difference=currentTime-that.lastKeyup;if(calculation==that.calculations&&difference>that.keyupDelay){that.processCalculation();}},(this.keyupDelay+100));},calculateTotal:function(total,amount){if(this.totalOperator==='+'){total=total===null?0.00:total;total=total+amount;}else if(this.totalOperator==='-'){if(total===null){total=amount;}else{total=total-amount;}}else if(this.totalOperator==='*'||this.totalOperator==='x'){total=total===null?1:total;total=total*amount;}else if(this.totalOperator==='/'){if(total===null){total=amount;}else{total=total/amount;}}
return total;},processCalculation:function(){if(this.initialized===false){this.baseInitialize();}
this.calculate();slikcalc.fireEvent(this.calculationComplete);},calculate:function(){throw new Error('Must implement calculate method in sub-class of BaseCalc');}};slikcalc.ColumnCalc=function(config){this.parent.constructor.call(this,config);this.rows=[];};slikcalc.extend(slikcalc.ColumnCalc,slikcalc.BaseCalc);slikcalc.ColumnCalc.prototype.rows=null;slikcalc.ColumnCalc.prototype.initialize=function(){if(this.calcOnLoad===true){this.processCalculation();}
if(this.registerListeners===true){this.setupEventListeners();}};slikcalc.ColumnCalc.prototype.calculate=function(){var total=null;for(var idx in this.rows){if(this.rows.hasOwnProperty(idx)){var includeRow=true;if(this.rows[idx].checkbox!==undefined){var checkbox=this.rows[idx].checkbox;includeRow=(checkbox.invert!==slikcalc.get(checkbox.id).checked);}
if(includeRow===true){total=this.calculateTotal(total,slikcalc.getAmount(this.rows[idx].id));}}}
slikcalc.setAmount(this.totalId,total);};slikcalc.ColumnCalc.prototype.setupEventListeners=function(){for(var idx in this.rows){if(this.rows.hasOwnProperty(idx)){var rowConfig=this.rows[idx];if(rowConfig.checkbox!==undefined){slikcalc.addListener(rowConfig.checkbox.id,'click',this.processCalculation,this);}
slikcalc.addListener(rowConfig.id,'keyup',this.keyupEvent,this);}}};slikcalc.ColumnCalc.prototype.addRow=function(rowConfig){rowConfig=rowConfig||{};if(rowConfig.checkbox!==undefined){rowConfig.checkbox.invert=rowConfig.checkbox.invert||false;}
this.rows.push(rowConfig);};slikcalc.FormulaCalc=function(config){this.parent.constructor.call(this,config);config=config||{};this.formula=config.formula||'';this.rows=[];this.variables=[];if(config.vars!==undefined){this.addRow({vars:config.vars});}};slikcalc.extend(slikcalc.FormulaCalc,slikcalc.BaseCalc);slikcalc.FormulaCalc.prototype.formula=null;slikcalc.FormulaCalc.prototype.formulaParsed=null;slikcalc.FormulaCalc.prototype.resultVar=null;slikcalc.FormulaCalc.prototype.varMatch=/\{(\w)\}/gi;slikcalc.FormulaCalc.prototype.rows=null;slikcalc.FormulaCalc.prototype.variables=null;slikcalc.FormulaCalc.prototype.initialize=function(){this.formulaParsed=this.formula;if(this.formulaParsed.indexOf('=')!==-1){var formulaSplit=this.formulaParsed.split('=');this.formulaParsed=formulaSplit[0];this.resultVar=this.varMatch.exec(slikcalc.trim(formulaSplit[1]))[1];}
this.varMatch.lastIndex=0;while((result=this.varMatch.exec(this.formulaParsed))!==null){this.variables.push(result[1]);}
this.varMatch.lastIndex=0;if(this.calcOnLoad===true){this.processCalculation();}};slikcalc.FormulaCalc.prototype.addRow=function(rowConfig){rowConfig=rowConfig||{};if(rowConfig.checkbox!==undefined){slikcalc.addListener(rowConfig.checkbox.id,'click',this.processCalculation,this);rowConfig.checkbox.invert=rowConfig.checkbox.invert||false;}
for(var idx in rowConfig.vars){if(rowConfig.vars.hasOwnProperty(idx)){var variable=rowConfig.vars[idx];variable.defaultValue=variable.defaultValue||0;rowConfig.registerListeners=rowConfig.registerListeners===true||(this.registerListeners===true&&rowConfig.registerListeners!==false);if(rowConfig.registerListeners===true){slikcalc.addListener(variable.id,'keyup',this.keyupEvent,this);}}}
this.rows.push(rowConfig);};slikcalc.FormulaCalc.prototype.calculate=function(){var total=0.00;for(var idx in this.rows){if(this.rows.hasOwnProperty(idx)){var includeRow=true;if(this.rows[idx].checkbox!==undefined){var checkbox=this.rows[idx].checkbox;includeRow=(checkbox.invert!==slikcalc.get(checkbox.id).checked);}
var rowTotal=0;var formulaString=this.formulaParsed;for(var varIdx in this.variables){if(this.variables.hasOwnProperty(varIdx)){var variableName=this.variables[varIdx];var variable=this.rows[idx].vars[variableName];var value=variable.defaultValue;if(slikcalc.get(variable.id)!==null){value=slikcalc.getValue(variable.id);value=value===''?variable.defaultValue:value;value=slikcalc.formatCurrency(value);}
var variableRegex=new RegExp("\\{"+variableName+"\\}");formulaString=formulaString.replace(variableRegex,value);}}
rowTotal=slikcalc.formatCurrency(eval(formulaString));if(this.resultVar!==null){var resultId=this.rows[idx].vars[this.resultVar].id;slikcalc.setAmount(resultId,rowTotal);}
if(includeRow===true&&this.totalOperator!==null){total=this.calculateTotal(total,parseFloat(rowTotal));}}}
if(this.totalId!==null){slikcalc.setAmount(this.totalId,total);}};<commit_msg>changed compression to use YUI compressor<commit_after>/*/**
 * Copyright (c) 2008 Brad Harris - bmharris@gmail.com
 * http://slikcalc.selfcontained.us
 * Code licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * version 1.0
 */
var slikcalc;if(!slikcalc){slikcalc={}}else{if(typeof slikcalc!="object"){throw new Error("slikcalc already exists and is not an object")}}slikcalc={adapter:null,getValue:function(B){var C=null;var A=this.get(B);if(A!==null){C=this.isInput(A)?A.value:A.innerHTML}return C},setValue:function(B,C){var A=this.get(B);if(A!==null){if(this.isInput(A)){A.value=C}else{A.innerHTML=C}}},getAmount:function(B){var A=this.getValue(B);A=A!==null?parseFloat(this.formatCurrency(A)):parseFloat(this.formatCurrency(0));return A},setAmount:function(A,B){this.setValue(A,this.formatCurrency(B))},isInput:function(A){return A.tagName==="INPUT"||A.tagName==="TEXTAREA"||A.tagName==="SELECT"},formatCurrency:function(A){A=isNaN(A)||A===""||A===null?0:A;return parseFloat(A).toFixed(2)},trim:function(A){return A.replace(/^\s+|\s+$/g,"")},get:function(A){if(this.adapter===null){throw new Error("slikcalc requires an external javascript library adapter")}return this.adapter.get(A)},validateAdapter:function(){if(this.adapter===null){throw new Error("slikcalc requires an external javascript library adapter")}},addListener:function(A,C,D,B){this.validateAdapter();this.adapter.addListener(A,C,D,B)},addOnLoad:function(B,A){this.validateAdapter();this.adapter.addOnLoad(B,A)},createCustomEvent:function(A){this.validateAdapter();return this.adapter.createCustomEvent(A)},bindEvent:function(B,C,A){this.validateAdapter();this.adapter.bindEvent(B,C,A)},fireEvent:function(A){this.validateAdapter();this.adapter.fireEvent(A)},extend:function(B,C){if(!C||!B){throw new Error("slikcalc.extend failed, please check that all dependencies are included.")}var A=function(){};A.prototype=C.prototype;B.prototype=new A();B.prototype.constructor=B;B.prototype.parent=C.prototype;B.prototype.parent.constructor=C}};slikcalc.BaseCalc=function(A){A.total=A.total||{};this.totalId=A.total.id||null;this.totalOperator=A.total.operator||"+";this.calcOnLoad=A.calcOnLoad||false;this.calculationComplete=slikcalc.createCustomEvent("calculationComplete");this.registerListeners=A.registerListeners||false;slikcalc.addOnLoad(this.baseInitialize,this)};slikcalc.BaseCalc.prototype={calculationComplete:null,lastKeyUp:null,calculations:0,totalId:null,totalOperator:null,calcOnLoad:false,registerListeners:false,keyupDelay:600,initialized:false,baseInitialize:function(){if(this.initialized===false){this.initialized=true;if(this.initialize!==undefined&&typeof this.initialize==="function"){this.initialize()}}},dependsOn:function(A){slikcalc.bindEvent(A.calculationComplete,this.processCalculation,this);return A},triggers:function(A){slikcalc.bindEvent(this.calculationComplete,A.processCalculation,A);return A},keyupEvent:function(){this.lastKeyup=new Date().getTime();var A=this;this.calculations=this.calculations+1;var B=this.calculations;setTimeout(function(){var C=new Date().getTime();var D=C-A.lastKeyup;if(B==A.calculations&&D>A.keyupDelay){A.processCalculation()}},(this.keyupDelay+100))},calculateTotal:function(B,A){if(this.totalOperator==="+"){B=B===null?0:B;B=B+A}else{if(this.totalOperator==="-"){if(B===null){B=A}else{B=B-A}}else{if(this.totalOperator==="*"||this.totalOperator==="x"){B=B===null?1:B;B=B*A}else{if(this.totalOperator==="/"){if(B===null){B=A}else{B=B/A}}}}}return B},processCalculation:function(){if(this.initialized===false){this.baseInitialize()}this.calculate();slikcalc.fireEvent(this.calculationComplete)},calculate:function(){throw new Error("Must implement calculate method in sub-class of BaseCalc")}};slikcalc.ColumnCalc=function(A){this.parent.constructor.call(this,A);this.rows=[]};slikcalc.extend(slikcalc.ColumnCalc,slikcalc.BaseCalc);slikcalc.ColumnCalc.prototype.rows=null;slikcalc.ColumnCalc.prototype.initialize=function(){if(this.calcOnLoad===true){this.processCalculation()}if(this.registerListeners===true){this.setupEventListeners()}};slikcalc.ColumnCalc.prototype.calculate=function(){var C=null;for(var A in this.rows){if(this.rows.hasOwnProperty(A)){var B=true;if(this.rows[A].checkbox!==undefined){var D=this.rows[A].checkbox;B=(D.invert!==slikcalc.get(D.id).checked)}if(B===true){C=this.calculateTotal(C,slikcalc.getAmount(this.rows[A].id))}}}slikcalc.setAmount(this.totalId,C)};slikcalc.ColumnCalc.prototype.setupEventListeners=function(){for(var A in this.rows){if(this.rows.hasOwnProperty(A)){var B=this.rows[A];if(B.checkbox!==undefined){slikcalc.addListener(B.checkbox.id,"click",this.processCalculation,this)}slikcalc.addListener(B.id,"keyup",this.keyupEvent,this)}}};slikcalc.ColumnCalc.prototype.addRow=function(A){A=A||{};if(A.checkbox!==undefined){A.checkbox.invert=A.checkbox.invert||false}this.rows.push(A)};slikcalc.FormulaCalc=function(A){this.parent.constructor.call(this,A);A=A||{};this.formula=A.formula||"";this.rows=[];this.variables=[];if(A.vars!==undefined){this.addRow({vars:A.vars})}};slikcalc.extend(slikcalc.FormulaCalc,slikcalc.BaseCalc);slikcalc.FormulaCalc.prototype.formula=null;slikcalc.FormulaCalc.prototype.formulaParsed=null;slikcalc.FormulaCalc.prototype.resultVar=null;slikcalc.FormulaCalc.prototype.varMatch=/\{(\w)\}/gi;slikcalc.FormulaCalc.prototype.rows=null;slikcalc.FormulaCalc.prototype.variables=null;slikcalc.FormulaCalc.prototype.initialize=function(){this.formulaParsed=this.formula;if(this.formulaParsed.indexOf("=")!==-1){var A=this.formulaParsed.split("=");this.formulaParsed=A[0];this.resultVar=this.varMatch.exec(slikcalc.trim(A[1]))[1]}this.varMatch.lastIndex=0;while((result=this.varMatch.exec(this.formulaParsed))!==null){this.variables.push(result[1])}this.varMatch.lastIndex=0;if(this.calcOnLoad===true){this.processCalculation()}};slikcalc.FormulaCalc.prototype.addRow=function(C){C=C||{};if(C.checkbox!==undefined){slikcalc.addListener(C.checkbox.id,"click",this.processCalculation,this);C.checkbox.invert=C.checkbox.invert||false}for(var A in C.vars){if(C.vars.hasOwnProperty(A)){var B=C.vars[A];B.defaultValue=B.defaultValue||0;C.registerListeners=C.registerListeners===true||(this.registerListeners===true&&C.registerListeners!==false);if(C.registerListeners===true){slikcalc.addListener(B.id,"keyup",this.keyupEvent,this)}}}this.rows.push(C)};slikcalc.FormulaCalc.prototype.calculate=function(){var total=0;for(var idx in this.rows){if(this.rows.hasOwnProperty(idx)){var includeRow=true;if(this.rows[idx].checkbox!==undefined){var checkbox=this.rows[idx].checkbox;includeRow=(checkbox.invert!==slikcalc.get(checkbox.id).checked)}var rowTotal=0;var formulaString=this.formulaParsed;for(var varIdx in this.variables){if(this.variables.hasOwnProperty(varIdx)){var variableName=this.variables[varIdx];var variable=this.rows[idx].vars[variableName];var value=variable.defaultValue;if(slikcalc.get(variable.id)!==null){value=slikcalc.getValue(variable.id);value=value===""?variable.defaultValue:value;value=slikcalc.formatCurrency(value)}var variableRegex=new RegExp("\\{"+variableName+"\\}");formulaString=formulaString.replace(variableRegex,value)}}rowTotal=slikcalc.formatCurrency(eval(formulaString));if(this.resultVar!==null){var resultId=this.rows[idx].vars[this.resultVar].id;slikcalc.setAmount(resultId,rowTotal)}if(includeRow===true&&this.totalOperator!==null){total=this.calculateTotal(total,parseFloat(rowTotal))}}}if(this.totalId!==null){slikcalc.setAmount(this.totalId,total)}};<|endoftext|>


<commit_before>import React, { PropTypes, Component } from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import moment from 'moment';
import { connect } from 'react-redux';
import { browserHistory } from 'react-router';

import MatchModel from '../../models/MatchModel.js';
import TeamModel from '../../models/TeamModel.js';
import { contextTypes } from '../../utils/decorators/withContext.js';
import withViewport from '../../utils/decorators/withViewport.js';

import CardText from 'material-ui/lib/card/card-text';
import Nav from 'react-bootstrap/lib/Nav';
import NavItem from 'react-bootstrap/lib/NavItem';
import PanelGroup from 'react-bootstrap/lib/PanelGroup';
import Panel from 'react-bootstrap/lib/Panel';

import { OwnClubId } from '../../models/ClubModel.js';

import { util as storeUtil } from '../../store.js';
import * as matchActions from '../../actions/matchActions.js';

import cn from 'classnames';
import styles from './Teams.css';
import withStyles from '../../utils/decorators/withStyles.js';

export const TeamsVttl = () => <Teams competition="Vttl" />;
export const TeamsSporta = () => <Teams competition="Sporta" />;

@withViewport
@withStyles(styles)
@connect(state => {
  return {
    config: state.config,
    user: state.user,
    players: state.players,
    clubs: state.clubs,
    matches: state.matches,
    teams: state.teams,
  };
}, matchActions)
export default class Teams extends Component {
  static contextTypes = contextTypes;
  constructor(props) {
    super(props);
    this.state = {openTabKey: this._getTeamIdOfATeam(props.teams)};
  }

  static propTypes = {
    competition: PropTypes.string.isRequired,
    config: PropTypes.object.isRequired,
    user: PropTypes.object.isRequired,
    matches: ImmutablePropTypes.listOf(PropTypes.instanceOf(MatchModel).isRequired).isRequired,
    teams: ImmutablePropTypes.listOf(PropTypes.instanceOf(TeamModel).isRequired).isRequired,
    viewport: PropTypes.object.isRequired,
    getMatchesForTeam: PropTypes.func.isRequired
  }

  componentDidMount(){
    this.props.getMatchesForTeam(this._getTeamIdOfATeam(this.props.teams));
  }

  _getTeamIdOfATeam(teams) {
    return teams.find(x => x.competition === this.props.competition && x.teamCode === 'A').id;
  }

  _showAccordion() {
    // Otherwise show tabs
    return this.props.viewport.width < 700;
  }
  _onTabSelect(teamId) {
    if (this.props.config.get('matchesForTeamLoaded').indexOf(teamId) === -1) {
      this.props.getMatchesForTeam(teamId);
    }
    this.setState({openTabKey: teamId});
  }

  _getTeamsPanel() {
    var teams = this.props.teams.filter(team => team.competition === this.props.competition);
    return teams.map(team =>
      <Panel header={this._renderRanking(team)} eventKey={team.id} onClick={this._onTabSelect.bind(this, team.id)}>
          {this._getTeamMatches(team)}
          {this._getRankingOfDivision(team)}
      </Panel>
    );
  }

  _renderRanking(team){
    var style = this._getLabelClassName(team);
    return (
{team.competition + ' ' + team.teamCode}
      {this._renderOwnTeamPosition(team)}

    );
  }

  _renderOwnTeamPosition(team) {
    const ranking = team.getDivisionRanking();
    return ranking ? ranking.position : '?';
  }

  _openMatch(matchId) {
    const matchRoute = this.context.t.route('match', {matchId: matchId});
    browserHistory.push(matchRoute);
  }

  _getTeamMatches(team){
    var matchesForTeam = team.getMatches().sort((a,b) => a.date - b.date);
    return (

                {this.context.t('teamCalendar.date')}
                {this.context.t('teamCalendar.hour')}
                {this.context.t('teamCalendar.match')}
                {this.context.t('teamCalendar.score')}

             {matchesForTeam.map(match => {
               return this._getMatch(match,team);
             })}

      );
  }

  _getMatch(match,team) {
    return (

          {match.date.format('DD/MM')}
          {match.date.format('HH:mm')}
          {match.isHomeMatch ? this._renderOwnTeamTitle(team) : this._renderOpponentTitle(match)} -
             {match.isHomeMatch ? ' ' + this._renderOpponentTitle(match) : ' ' + this._renderOwnTeamTitle(team)}
          {this._renderScores(match)}

    );
  }

  _won(match) {
    if (match.score.home === match.score.out) {
      return false;
    }

    if (match.isHomeMatch) {
      return match.score.home > match.score.out;
    }
    else {
      return match.score.out > match.score.home;
    }
  }

  _getRankingOfDivision(team) {
    var teamsForRanking = team.ranking;
    if (this._showAccordion()) {
      return (

                  {this.context.t('teamCalendar.position')}
                  {this.context.t('teamCalendar.name')}
                  {this.context.t('teamCalendar.points')}

               {teamsForRanking.map(teamRanking => {
                 return this._getRankingAccordeon(teamRanking);
               })}

      );
    }
    return (

                {this.context.t('teamCalendar.position')}
                {this.context.t('teamCalendar.name')}
                {this.context.t('teamCalendar.matchesWon')}
                {this.context.t('teamCalendar.matchesLost')}
                {this.context.t('teamCalendar.matchesDraw')}
                {this.context.t('teamCalendar.points')}

             {teamsForRanking.map(teamRanking => {
               return this._getRanking(teamRanking);
             })}

    );
  }

  _getTeamName(clubId) {
    return storeUtil.getClub(clubId).name;
  }

  _getRankingAccordeon(teamRanking) {
    return (

          {teamRanking.position}
          {storeUtil.getClub(teamRanking.clubId).name + ' ' + teamRanking.teamCode}
          {teamRanking.points}

    );
  }

  _getRanking(teamRanking) {
    return (

          {teamRanking.position}
          {storeUtil.getClub(teamRanking.clubId).name + ' ' + teamRanking.teamCode}
          {teamRanking.gamesWon}
          {teamRanking.gamesLost}
          {teamRanking.gamesDraw}
          {teamRanking.points}

     );
  }

  _renderScores(match){
    if (match.score.home === 0 && match.score.out === 0) {
      return '';
    } else {
      return match.score.home + ' - ' + match.score.out;
    }
  }

  _renderOwnTeamTitle(team) {
    return team.competition + ' ' + team.teamCode;
  }

  _renderOpponentTitle(match) {
    const club = match.getOpponentClub();
    return club.name + ' ' + match.opponent.teamCode;
  }

  _getTeamsNavigation() {
    var teams = this.props.teams.filter(team => team.competition === this.props.competition);
    return teams.map(team =>
       this._getTeamsNavigationTab(team)
    );
  }

  _getTeamsNavigationTab(team) {
    var style = this._getLabelClassName(team);
    return ( <NavItem eventKey={team.id}>

{team.competition + ' ' + team.teamCode}
          {this._renderOwnTeamPosition(team)}

      </NavItem>
    );
  }

  _getLabelClassName(team) {
    if (team.isTopper(this._renderOwnTeamPosition(team))) {return 'label label-as-badge label-success';}
    if (team.isInDegradationZone(this._renderOwnTeamPosition(team))) {return 'label label-as-badge label-danger';}
    return 'label label-as-badge label-default';
  }

  _getDivsForTeamsNavigation() {
    var team = this.props.teams.find(t => t.id === this.state.openTabKey);
    return (

        {this._getTeamMatches(team)}
        {this._getRankingOfDivision(team)}

    );
  }

  render() {

    if (this._showAccordion()) {
      return (

          <CardText expandable={true} style={{paddingTop: 0, paddingLeft: 5, paddingRight: 5}}>
            <PanelGroup activeKey={this.state.openTabKey} onSelect={::this._onTabSelect} accordion>
              {this._getTeamsPanel()}
            </PanelGroup>
          </CardText>

      );
    }

    return (

        <CardText expandable={true} style={{paddingTop: 0}}>

            {this._getTeamsNavigation()}

          {this._getDivsForTeamsNavigation()}
        </CardText>

    );
  }
}<commit_msg>Added icon to show thriller matches for teams in team calendar page<commit_after>import React, { PropTypes, Component } from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import moment from 'moment';
import { connect } from 'react-redux';
import { browserHistory } from 'react-router';

import MatchModel from '../../models/MatchModel.js';
import TeamModel from '../../models/TeamModel.js';
import { contextTypes } from '../../utils/decorators/withContext.js';
import withViewport from '../../utils/decorators/withViewport.js';

import CardText from 'material-ui/lib/card/card-text';
import Nav from 'react-bootstrap/lib/Nav';
import NavItem from 'react-bootstrap/lib/NavItem';
import PanelGroup from 'react-bootstrap/lib/PanelGroup';
import Panel from 'react-bootstrap/lib/Panel';

import { OwnClubId } from '../../models/ClubModel.js';

import { util as storeUtil } from '../../store.js';
import * as matchActions from '../../actions/matchActions.js';

import cn from 'classnames';
import styles from './Teams.css';
import withStyles from '../../utils/decorators/withStyles.js';
import Icon from '../controls/Icon.js';

export const TeamsVttl = () => <Teams competition="Vttl" />;
export const TeamsSporta = () => <Teams competition="Sporta" />;

@withViewport
@withStyles(styles)
@connect(state => {
  return {
    config: state.config,
    user: state.user,
    players: state.players,
    clubs: state.clubs,
    matches: state.matches,
    teams: state.teams,
  };
}, matchActions)
export default class Teams extends Component {
  static contextTypes = contextTypes;
  constructor(props) {
    super(props);
    this.state = {openTabKey: this._getTeamIdOfATeam(props.teams)};
  }

  static propTypes = {
    competition: PropTypes.string.isRequired,
    config: PropTypes.object.isRequired,
    user: PropTypes.object.isRequired,
    matches: ImmutablePropTypes.listOf(PropTypes.instanceOf(MatchModel).isRequired).isRequired,
    teams: ImmutablePropTypes.listOf(PropTypes.instanceOf(TeamModel).isRequired).isRequired,
    viewport: PropTypes.object.isRequired,
    getMatchesForTeam: PropTypes.func.isRequired
  }

  componentDidMount(){
    this.props.getMatchesForTeam(this._getTeamIdOfATeam(this.props.teams));
  }

  _getTeamIdOfATeam(teams) {
    return teams.find(x => x.competition === this.props.competition && x.teamCode === 'A').id;
  }

  _showAccordion() {
    // Otherwise show tabs
    return this.props.viewport.width < 700;
  }
  _onTabSelect(teamId) {
    if (this.props.config.get('matchesForTeamLoaded').indexOf(teamId) === -1) {
      this.props.getMatchesForTeam(teamId);
    }
    this.setState({openTabKey: teamId});
  }

  _getTeamsPanel() {
    var teams = this.props.teams.filter(team => team.competition === this.props.competition);
    return teams.map(team =>
      <Panel header={this._renderRanking(team)} eventKey={team.id} onClick={this._onTabSelect.bind(this, team.id)}>
          {this._getTeamMatches(team)}
          {this._getRankingOfDivision(team)}
      </Panel>
    );
  }

  _renderRanking(team){
    var style = this._getLabelClassName(team);
    return (
{team.competition + ' ' + team.teamCode}
      {this._renderOwnTeamPosition(team)}

    );
  }

  _renderOwnTeamPosition(team) {
    const ranking = team.getDivisionRanking();
    return ranking ? ranking.position : '?';
  }

  _openMatch(matchId) {
    const matchRoute = this.context.t.route('match', {matchId: matchId});
    browserHistory.push(matchRoute);
  }

  _getTeamMatches(team){
    var matchesForTeam = team.getMatches().sort((a,b) => a.date - b.date);
    return (

                {this.context.t('teamCalendar.date')}
                {this.context.t('teamCalendar.hour')}
                {this.context.t('teamCalendar.match')}
                {this.context.t('teamCalendar.score')}

             {matchesForTeam.map(match => {
               return this._getMatch(match,team);
             })}

      );
  }

  _getMatch(match,team) {
    return (

          {this._renderThrillerIcon(team,match)}{match.date.format('DD/MM')}
          {match.date.format('HH:mm')}
          {match.isHomeMatch ? this._renderOwnTeamTitle(team) : this._renderOpponentTitle(match)} -
             {match.isHomeMatch ? ' ' + this._renderOpponentTitle(match) : ' ' + this._renderOwnTeamTitle(team)}
          {this._renderScores(match)}

    );
  }

  _renderThrillerIcon(team,match){
    if(team.getThriller(match)){
      return (<Icon fa="fa fa-heartbeat faa-pulse animated" style={{marginLeft: 3, marginRight: 7, marginTop: 3}} />);
    }
  }

  _won(match) {
    if (match.score.home === match.score.out) {
      return false;
    }

    if (match.isHomeMatch) {
      return match.score.home > match.score.out;
    }
    else {
      return match.score.out > match.score.home;
    }
  }

  _getRankingOfDivision(team) {
    var teamsForRanking = team.ranking;
    if (this._showAccordion()) {
      return (

                  {this.context.t('teamCalendar.position')}
                  {this.context.t('teamCalendar.name')}
                  {this.context.t('teamCalendar.points')}

               {teamsForRanking.map(teamRanking => {
                 return this._getRankingAccordeon(teamRanking);
               })}

      );
    }
    return (

                {this.context.t('teamCalendar.position')}
                {this.context.t('teamCalendar.name')}
                {this.context.t('teamCalendar.matchesWon')}
                {this.context.t('teamCalendar.matchesLost')}
                {this.context.t('teamCalendar.matchesDraw')}
                {this.context.t('teamCalendar.points')}

             {teamsForRanking.map(teamRanking => {
               return this._getRanking(teamRanking);
             })}

    );
  }

  _getTeamName(clubId) {
    return storeUtil.getClub(clubId).name;
  }

  _getRankingAccordeon(teamRanking) {
    return (

          {teamRanking.position}
          {storeUtil.getClub(teamRanking.clubId).name + ' ' + teamRanking.teamCode}
          {teamRanking.points}

    );
  }

  _getRanking(teamRanking) {
    return (

          {teamRanking.position}
          {storeUtil.getClub(teamRanking.clubId).name + ' ' + teamRanking.teamCode}
          {teamRanking.gamesWon}
          {teamRanking.gamesLost}
          {teamRanking.gamesDraw}
          {teamRanking.points}

     );
  }

  _renderScores(match){
    if (match.score.home === 0 && match.score.out === 0) {
      return '';
    } else {
      return match.score.home + ' - ' + match.score.out;
    }
  }

  _renderOwnTeamTitle(team) {
    return team.competition + ' ' + team.teamCode;
  }

  _renderOpponentTitle(match) {
    const club = match.getOpponentClub();
    return club.name + ' ' + match.opponent.teamCode;
  }

  _getTeamsNavigation() {
    var teams = this.props.teams.filter(team => team.competition === this.props.competition);
    return teams.map(team =>
       this._getTeamsNavigationTab(team)
    );
  }

  _getTeamsNavigationTab(team) {
    var style = this._getLabelClassName(team);
    return ( <NavItem eventKey={team.id}>

{team.competition + ' ' + team.teamCode}
          {this._renderOwnTeamPosition(team)}

      </NavItem>
    );
  }

  _getLabelClassName(team) {
    if (team.isTopper(this._renderOwnTeamPosition(team))) {return 'label label-as-badge label-success';}
    if (team.isInDegradationZone(this._renderOwnTeamPosition(team))) {return 'label label-as-badge label-danger';}
    return 'label label-as-badge label-default';
  }

  _getDivsForTeamsNavigation() {
    var team = this.props.teams.find(t => t.id === this.state.openTabKey);
    return (

        {this._getTeamMatches(team)}
        {this._getRankingOfDivision(team)}

    );
  }

  render() {

    if (this._showAccordion()) {
      return (

          <CardText expandable={true} style={{paddingTop: 0, paddingLeft: 5, paddingRight: 5}}>
            <PanelGroup activeKey={this.state.openTabKey} onSelect={::this._onTabSelect} accordion>
              {this._getTeamsPanel()}
            </PanelGroup>
          </CardText>

      );
    }

    return (

        <CardText expandable={true} style={{paddingTop: 0}}>

            {this._getTeamsNavigation()}

          {this._getDivsForTeamsNavigation()}
        </CardText>

    );
  }
}<|endoftext|>


<commit_before>'use strict';

app.controller('WithdrawCtrl', ['$scope', '$location', '$modal', 'Withdraw', function($scope, $location, $modal, Withdraw) {

    $scope.withdraws = Withdraw.query();
    $scope.withdraw  = null;

    $scope.openModalSignature = function(withdraw) {

        Withdraw.get({id: withdraw.id}, function(withdraw) {

            $scope.withdraw = withdraw;

            $modal({
                title:    'Withdraw detail',
                template: 'js/app/withdraw/modal.html',
                animation:'am-fade-and-scale',
                placement:'center',
                show:     true,
                scope:    $scope
            });

        });

    };

    /**
     * Verify the submitted seed before signing
     *
     * @param seed
     */
    $scope.verify = function(seed)
    {
        // Create a wallet from the seed submitted
        var wallet = new bitcoin.Wallet(bitcoin.crypto.sha256(seed), bitcoin.networks.bitcoin);

        var accountPubKey = wallet.getExternalAccount().derive(0).pubKey.toHex();

        var identity = getIdentity(accountPubKey, $scope.withdraw.keychain.pub_keys);

        if (!identity) {
            return;
        }

        console.log(identity.name);

        sign(seed);
    };

    /**
     * Sign each inputs with the submitted seed
     *
     * @param seed
     */
    function sign(seed)
    {
        // Recover transaction from rawtransaction created by bitcoind
        var tx  = bitcoin.Transaction.fromHex($scope.withdraw.raw_transaction);

        // Build it into Transaction Builder
        var txb = bitcoin.TransactionBuilder.fromTransaction(tx);

        // Create a wallet from the seed submitted
        var wallet = new bitcoin.Wallet(bitcoin.crypto.sha256(seed), bitcoin.networks.bitcoin);

        // We sign the transaction for each inputs
        angular.forEach($scope.withdraw.withdraw_inputs, function(input, index) {
            var privKey;

            // Finding the good private key according to the derivation
            if (input.address.is_external === true) {
                privKey = wallet.getExternalAccount().derive(input.address.derivation).privKey;
            } else {
                privKey = wallet.getInternalAccount().derive(input.address.derivation).privKey;
            }

            console.log(privKey.toWIF());

            // Sign the input
            txb.sign(index, privKey, bitcoin.Script.fromHex(input.address.redeem_script));

//            console.log(txb.build());

            // Return the incomplete rawtransaction
            $scope.withdraw.raw_transaction = txb.buildIncomplete().toHex();
            console.log($scope.withdraw.raw_transaction);
        });

    }

    /**
     * @param seed    The public key submitted by the user
     * @param pubKeys Public keys that can sign the withdraw
     *
     * @returns {boolean|Object}
     */
    function getIdentity(seed, pubKeys)
    {
        var identity = false;

        pubKeys.forEach(function(pubKey) {
            if (pubKey.value === seed) {
                identity = pubKey;
            }
        });

        return identity;
    }

}]);<commit_msg>front: sign raw_signed_transaction<commit_after>'use strict';

app.controller('WithdrawCtrl', ['$scope', '$location', '$modal', 'Withdraw', function($scope, $location, $modal, Withdraw) {

    $scope.withdraws = Withdraw.query();
    $scope.withdraw  = null;

    $scope.openModalSignature = function(withdraw) {

        Withdraw.get({id: withdraw.id}, function(withdraw) {

            $scope.withdraw = withdraw;

            $modal({
                title:    'Withdraw detail',
                template: 'js/app/withdraw/modal.html',
                animation:'am-fade-and-scale',
                placement:'center',
                show:     true,
                scope:    $scope
            });

        });

    };

    /**
     * Verify the submitted seed before signing
     *
     * @param seed
     */
    $scope.verify = function(seed)
    {
        // Create a wallet from the seed submitted
        var wallet = new bitcoin.Wallet(bitcoin.crypto.sha256(seed), bitcoin.networks.bitcoin);

        var accountPubKey = wallet.getExternalAccount().derive(0).pubKey.toHex();

        var identity = getIdentity(accountPubKey, $scope.withdraw.keychain.pub_keys);

        if (!identity) {
            return;
        }

        console.log(identity.name);

        sign(seed);
    };

    /**
     * Sign each inputs with the submitted seed
     *
     * @param seed
     */
    function sign(seed)
    {
        // Recover transaction from raw_transaction created by bitcoind || or raw_signed_transaction
        var tx  = bitcoin.Transaction.fromHex(getRawTransaction($scope.withdraw));

        // Build it into Transaction Builder
        var txb = bitcoin.TransactionBuilder.fromTransaction(tx);

        // Create a wallet from the seed submitted
        var wallet = new bitcoin.Wallet(bitcoin.crypto.sha256(seed), bitcoin.networks.bitcoin);

        // We sign the transaction for each inputs
        angular.forEach($scope.withdraw.withdraw_inputs, function(input, index) {
            var privKey;

            // Finding the good private key according to the derivation
            if (input.address.is_external === true) {
                privKey = wallet.getExternalAccount().derive(input.address.derivation).privKey;
            } else {
                privKey = wallet.getInternalAccount().derive(input.address.derivation).privKey;
            }

            console.log(privKey.toWIF());

            // Sign the input
            txb.sign(index, privKey, bitcoin.Script.fromHex(input.address.redeem_script));

            try {
                $scope.withdraw.raw_signed_transaction = txb.build().toHex();
                console.log('Successfully signed.');
            } catch (e) {
                if ('Transaction is missing signatures' === e.message) {
                    // Normal, because every inputs not signed yet.

                    $scope.withdraw.raw_signed_transaction = txb.buildIncomplete().toHex();
                } else if ('Not enough signatures provided' === e.message) {
                    console.log('Not enough signatures provided');

                    $scope.withdraw.raw_signed_transaction = txb.buildIncomplete().toHex();
                }
            }

            // send the signed transaction there
            console.log($scope.withdraw.raw_signed_transaction);
        });

    }

    /**
     * @param seed    The public key submitted by the user
     * @param pubKeys Public keys that can sign the withdraw
     *
     * @returns {boolean|Object}
     */
    function getIdentity(seed, pubKeys)
    {
        var identity = false;

        pubKeys.forEach(function(pubKey) {
            if (pubKey.value === seed) {
                identity = pubKey;
            }
        });

        return identity;
    }

    function getRawTransaction(withdraw)
    {
        if (withdraw.raw_signed_transaction) {
            return withdraw.raw_signed_transaction;
        }

        return withdraw.raw_transaction;
    }

}]);<|endoftext|>


<commit_before>const JwtStrategy = require('passport-jwt').Strategy;

// Get user model
const User = require('../models/user');
const config = require('../config/database');

module.exports = function(passport) {
    var opts = {};
    opts.secretsOrKey = config.secret;
    passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
        User.findOne({id: jwt_payload.id}, function(err, user) {
            if (err) return done(err, false);
            if (user) return done(null, user);
            else {
                done(null, false);
            }
        });
    }));
}<commit_msg>wat a cuck :face_palm:<commit_after>const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;

// Get user model
const User = require('../models/user');
const config = require('../config/database');

module.exports = function(passport) {
    var opts = {};
    opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
    opts.secretOrKey = config.secret;
    passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
        User.findOne({id: jwt_payload.id}, function(err, user) {
            if (err) return done(err, false);
            if (user) return done(null, user);
            else {
                done(null, false);
            }
        });
    }));
}<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');

const tap = require('tap');
const glob = require('glob');

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

tap.test('saving compiled tests', assert => {
  const sourcepattern = path.join(process.cwd(), 'test/collateral-save/test/*.js');
  const resultpattern = path.join(process.cwd(), 'test/collateral-save/test/*.{fail,pass}');

  const sources = glob.sync(sourcepattern);

  tap.test('save all compiled tests with `--saveCompiledTests`', assert => {
    run([sourcepattern, '--saveCompiledTests'])
      .catch(assert.fail)
      .then(() => {
        const results = glob.sync(resultpattern);
        assert.equal(results.length, sources.length, 'Expecting an equal number of result files to source files.');

        return Promise.all(
          results.map(result => new Promise(resolve => fs.unlink(result, () => resolve())))
        );
      }).then(assert.done);
  });

  tap.test('save failed compiled tests with `--saveCompiledTests --saveOnlyFailed`', assert => {

    run([sourcepattern, '--saveCompiledTests', '--saveOnlyFailed'])
      .catch(assert.fail)
      .then(() => {
        const results = glob.sync(resultpattern);
        assert.equal(results.length, 3, 'Expecting 3 result files.');

        return Promise.all(
          results.map(result => new Promise(resolve => fs.unlink(result, () => resolve())))
        );
      }).catch(error => console.log(error)).then(assert.done);
  });

  tap.test('save failed compiled tests with `--saveOnlyFailed` (implies `--saveCompiledTests`)', assert => {

    run([sourcepattern, '--saveOnlyFailed'])
      .catch(assert.fail)
      .then(() => {
        const results = glob.sync(resultpattern);
        assert.equal(results.length, 3, 'Expecting 3 result files.');

        return Promise.all(
          results.map(result => new Promise(resolve => fs.unlink(result, () => resolve())))
        );
      }).catch(error => console.log(error)).then(assert.done);
  });

  assert.done();
});
<commit_msg>Remove unnecessary test<commit_after>const fs = require('fs');
const path = require('path');

const tap = require('tap');
const glob = require('glob');

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

const sourcepattern = path.join(process.cwd(), 'test/collateral-save/test/*.js');
const resultpattern = path.join(process.cwd(), 'test/collateral-save/test/*.{fail,pass}');

const sources = glob.sync(sourcepattern);

tap.test('save all compiled tests with `--saveCompiledTests`', assert => {
  run([sourcepattern, '--saveCompiledTests'])
    .catch(assert.fail)
    .then(() => {
      const results = glob.sync(resultpattern);
      assert.equal(results.length, sources.length, 'Expecting an equal number of result files to source files.');

      return Promise.all(
        results.map(result => new Promise(resolve => fs.unlink(result, () => resolve())))
      );
    }).then(assert.done);
});

tap.test('save failed compiled tests with `--saveCompiledTests --saveOnlyFailed`', assert => {

  run([sourcepattern, '--saveCompiledTests', '--saveOnlyFailed'])
    .catch(assert.fail)
    .then(() => {
      const results = glob.sync(resultpattern);
      assert.equal(results.length, 3, 'Expecting 3 result files.');

      return Promise.all(
        results.map(result => new Promise(resolve => fs.unlink(result, () => resolve())))
      );
    }).catch(error => console.log(error)).then(assert.done);
});

tap.test('save failed compiled tests with `--saveOnlyFailed` (implies `--saveCompiledTests`)', assert => {

  run([sourcepattern, '--saveOnlyFailed'])
    .catch(assert.fail)
    .then(() => {
      const results = glob.sync(resultpattern);
      assert.equal(results.length, 3, 'Expecting 3 result files.');

      return Promise.all(
        results.map(result => new Promise(resolve => fs.unlink(result, () => resolve())))
      );
    }).catch(error => console.log(error)).then(assert.done);
});
<|endoftext|>