<commit_before>//'use strict';
var qs = require('querystring');
var twilio = require('twilio');
var cookie = require('cookie');
var crypto = require('crypto');
var encryptKey = "s0m3Rand0mStr!ng"; // this should be put into a config var, env var
var encryptStandard = "aes256";

module.exports = function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');
    var formValues = qs.parse(req.body);
    var cookieSession = getCookieSession(req.headers.cookie);
    //context.log(formValues);
    var twiml = new twilio.TwimlResponse();
    twiml.message('You said: ' + formValues.Body);

    var encryptSessionString = encrypt(JSON.stringify(session))
    var setCookie = cookie.serialize("session", encryptSessionString, {
        secure: true
    });

    res = {
        status: 200,
        body: twiml.toString(),
        headers: {
            'Content-Type': 'application/xml',
            'Set-Cookie': setCookie
        },
        isRaw: true
    };
    context.done(null, res);
};

function encrypt(text) {
    var cipher = crypto.createCipher(encryptStandard, encryptKey)
    var crypted = cipher.update(text, 'utf8', 'hex')
    crypted += cipher.final('hex');
    return crypted;
}

function decrypt(text) {
    var decipher = crypto.createDecipher(encryptStandard, encryptKey)
    var dec = decipher.update(text, 'hex', 'utf8')
    dec += decipher.final('utf8');
    return dec;
}

function getCookieSession(cookie) {
    var cookies = cookie.parse(req.headers.cookie || "", {
        secure: true
    });
    var cookieSession;

    if (cookies.session) {
        context.log("session cookie found");
        var decryptCookie = decrypt(cookies.session);
        context.log("session cookie : " + decryptCookie);

        cookieSession = JSON.parse(decryptCookie);
    }
    else { // set first time cookie for Twilio
        context.log("no cookie name found");
        cookieSession = { askQueued: false, name: "xbob" };
    }

    return cookieSession;
}<commit_msg>test refactored changes<commit_after>'use strict';
var qs = require('querystring');
var twilio = require('twilio');
var cookie = require('cookie');
var crypto = require('crypto');
var encryptKey = "s0m3Rand0mStr!ng"; // this should be put into a config var, env var
var encryptStandard = "aes256";

module.exports = function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');
    var formValues = qs.parse(req.body);
    req.session = getCookieSession(req);
    //context.log(formValues);
    var twiml = new twilio.TwimlResponse();
    twiml.message('You said: ' + formValues.Body);

    var encryptSessionString = encrypt(JSON.stringify(req.session))
    var setCookie = cookie.serialize("session", encryptSessionString, {
        secure: true
    });

    var res = {
        status: 200,
        body: twiml.toString(),
        headers: {
            'Content-Type': 'application/xml',
            'Set-Cookie': setCookie
        },
        isRaw: true
    };

    context.done(null, res);

    function getCookieSession(req) {
        var cookies = cookie.parse(req.headers.cookie || "", {
            secure: true
        });
        var cookieSession;

        if (cookies.session) {
            context.log("session cookie found");
            var decryptCookie = decrypt(cookies.session);
            context.log("session cookie : " + decryptCookie);

            cookieSession = JSON.parse(decryptCookie);
        }
        else { // set first time cookie for Twilio
            context.log("no cookie name found");
            cookieSession = { askQueued: false, name: "xbob" };
        }

        return cookieSession;
    }
};

function encrypt(text) {
    var cipher = crypto.createCipher(encryptStandard, encryptKey)
    var crypted = cipher.update(text, 'utf8', 'hex')
    crypted += cipher.final('hex');
    return crypted;
}

function decrypt(text) {
    var decipher = crypto.createDecipher(encryptStandard, encryptKey)
    var dec = decipher.update(text, 'hex', 'utf8')
    dec += decipher.final('utf8');
    return dec;
}

<|endoftext|>


<commit_before>module.exports = {
    metadata: {
        plugin: "jalousie",
        label: "Jalousie Control",
        role: "actor",
        family: "jalousie",
        deviceTypes: ["microcontroller/microcontroller"],
        services: [
            {id: "setState", label: "Set State"},
            {id: "up", label: "Up"},
            {id: "down", label: "Down"},
            {id: "stopMotion", label: "Stop Motion"}
        ],
        state: [
            {
                id: "position", label: "position",
                type: {
                    id: "decimal"
                }
            }, {
                id: "rotation", label: "rotation",
                type: {
                    id: "decimal"
                }
            }],
        configuration: [
            {
                label: "LED intensitiy",
                id: "ledIntensity",
                type: {
                    id: "integer"
                },
                defaultValue: 255
            }, {
                label: "Speed",
                id: "speed",
                type: {
                    id: "integer"
                },
                defaultValue: 500
            }, {
                label: "Daylight color code",
                id: "dayLightColorCode",
                type: {
                    id: "string"
                },
                defaultValue: "#ffe800"
            }]
    },
    create: function () {
        return new Jalousie();
    }
};

var q = require('q');

/**
 *
 */
function Jalousie() {
    /**
     *
     */
    Jalousie.prototype.start = function () {
        var deferred = q.defer();

        this.operationalState = {
            status: 'PENDING',
            message: 'Waiting for initialization...'
        };
        this.publishOperationalStateChange();

        this.state = {
            position: 100,
            rotation: 90
        };

        this.logLevel = 'debug';

        if (!this.isSimulated()) {

            try {
                var pixel = require("node-pixel");

                this.strip = new pixel.Strip({
                    board: this.device.board,
                    controller: "FIRMATA",
                    strips: [{
                        pin: 5, //TODO DEMOCASE
                        length: (24) //TODO DEMOCASE
                    },],
                    gamma: 2.8, // set to a gamma that works nicely for WS2812
                });

                this.strip.on("ready", function () {
                    this.strip.color("#000000");
                    this.showPixel();

                    this.logDebug("Jalousie initialized.");
                    this.logDebug(this.state);
                    this.publishStateChange();

                }.bind(this));

                this.operationalState = {
                    status: 'OK',
                    message: 'Jalousie Control successfully initialized'
                }
                this.publishOperationalStateChange();

                deferred.resolve();
            } catch (error) {
                this.operationalState = {
                    status: 'ERROR',
                    message: "Cannot initialize " +
                    this.device.id + "/" + this.id +
                    ":" + error
                }
                this.publishOperationalStateChange();

                this.device.node
                    .publishMessage("Cannot initialize " +
                        this.device.id + "/" + this.id +
                        ":" + error);

                deferred.reject(error);
            }
        } else {
            this.operationalState = {
                status: 'OK',
                message: 'Jalousie Control successfully initialized'
            }
            this.publishOperationalStateChange();

            deferred.resolve();
        }

        return deferred.promise;
    };

    /**
     *
     */
    Jalousie.prototype.getState = function () {
        return this.state;
    };

    /**
     *
     */
    Jalousie.prototype.setState = function (state) {
        if (this.state.position < state.position) {
            this.down(state);
        }

        if (this.state.position > state.position) {
            this.up(state);
        }

    };

    /**
     *
     */
    Jalousie.prototype.showPixel = function (parameters) {

        if (!this.isSimulated()) {
            let pixelToShow = (this.state.position / 12.5).toFixed();
            for (let i = 23; i >= 16; i--) {
                if (i <= (23 - pixelToShow)) {
                    this.strip.pixel(i).color(this.configuration.dayLightColorCode);
                    this.strip.pixel((i - 8)).color(this.configuration.dayLightColorCode);
                    this.strip.pixel((i - 16)).color(this.configuration.dayLightColorCode);
                } else {
                    this.strip.pixel(i).color("#000000");
                    this.strip.pixel(i - 8).color("#000000");
                    this.strip.pixel(i - 16).color("#000000");
                }
            }
            this.strip.show();
            //this.publishStateChange();
        }
    };

    /**
     *
     */
    Jalousie.prototype.up = function (pretarget) {
        this.stopMotion();

        this.logDebug("Jalousie Moving up");
        var target = {};
        if (typeof pretarget === "undefined") {
            target.position = 0;
        } else {
            target = pretarget;
        }

        this.upInterval = setInterval(function () {
            this.state.position -= 12.5;
            this.publishStateChange();
            this.showPixel();

            if (this.state.position <= 0) {
                clearInterval(this.upInterval);
            }

        }.bind(this), this.configuration.speed);
    };

    /**
     *
     */
    Jalousie.prototype.down = function (pretarget) {
        this.stopMotion();

        this.logDebug("Jalousie Moving down");

        var target = {};
        if (typeof pretarget === "undefined") {
            target.position = 100;
        } else {
            target = pretarget;
        }

        this.downInterval = setInterval(function () {
            this.state.position += 12.5;
            this.logDebug(this.state);
            this.publishStateChange();
            this.showPixel();

            console.log("actual state " + this.state.position);

            if (this.state.position >= 100) {
                clearInterval(this.downInterval);
            }

        }.bind(this), this.configuration.speed);
    };

    /**
     *
     */
    Jalousie.prototype.stopMotion = function () {
        if (this.upInterval) {
            clearInterval(this.upInterval);
        }

        if (this.downInterval) {
            clearInterval(this.downInterval);
        }

    };

    /**
     *
     */
    Jalousie.prototype.stop = function () {
        this.stopMotion();
        return this.state;
    };

}

<commit_msg>TI-5245<commit_after>module.exports = {
    metadata: {
        plugin: "jalousie",
        label: "Jalousie Control",
        role: "actor",
        family: "jalousie",
        deviceTypes: ["microcontroller/microcontroller"],
        services: [
            {id: "setState", label: "Set State"},
            {id: "up", label: "Up"},
            {id: "down", label: "Down"},
            {id: "stopMotion", label: "Stop Motion"}
        ],
        state: [
            {
                id: "position", label: "position",
                type: {
                    id: "decimal"
                }
            }, {
                id: "rotation", label: "rotation",
                type: {
                    id: "decimal"
                }
            },{
                id: "isMoving",
                label: "Is Moving",
                type: {
                    id: "boolean"
                }
            }
        ],
        configuration: [
            {
                label: "LED intensitiy",
                id: "ledIntensity",
                type: {
                    id: "integer"
                },
                defaultValue: 255
            }, {
                label: "Speed",
                id: "speed",
                type: {
                    id: "integer"
                },
                defaultValue: 500
            }, {
                label: "Daylight color code",
                id: "dayLightColorCode",
                type: {
                    id: "string"
                },
                defaultValue: "#ffe800"
            }]
    },
    create: function () {
        return new Jalousie();
    }
};

var q = require('q');

/**
 *
 */
function Jalousie() {
    /**
     *
     */
    Jalousie.prototype.start = function () {
        var deferred = q.defer();

        this.operationalState = {
            status: 'PENDING',
            message: 'Waiting for initialization...'
        };
        this.publishOperationalStateChange();

        this.state = {
            position: 100,
            rotation: 90,
            isMoving: fasle
        };

        this.logLevel = 'debug';

        if (!this.isSimulated()) {

            try {
                var pixel = require("node-pixel");

                this.strip = new pixel.Strip({
                    board: this.device.board,
                    controller: "FIRMATA",
                    strips: [{
                        pin: 5, //TODO DEMOCASE
                        length: (24) //TODO DEMOCASE
                    },],
                    gamma: 2.8, // set to a gamma that works nicely for WS2812
                });

                this.strip.on("ready", function () {
                    this.strip.color("#000000");
                    this.showPixel();

                    this.logDebug("Jalousie initialized.");
                    this.logDebug(this.state);
                    this.publishStateChange();

                }.bind(this));

                this.operationalState = {
                    status: 'OK',
                    message: 'Jalousie Control successfully initialized'
                }
                this.publishOperationalStateChange();

                deferred.resolve();
            } catch (error) {
                this.operationalState = {
                    status: 'ERROR',
                    message: "Cannot initialize " +
                    this.device.id + "/" + this.id +
                    ":" + error
                }
                this.publishOperationalStateChange();

                this.device.node
                    .publishMessage("Cannot initialize " +
                        this.device.id + "/" + this.id +
                        ":" + error);

                deferred.reject(error);
            }
        } else {
            this.operationalState = {
                status: 'OK',
                message: 'Jalousie Control successfully initialized'
            }
            this.publishOperationalStateChange();

            deferred.resolve();
        }

        return deferred.promise;
    };

    /**
     *
     */
    Jalousie.prototype.getState = function () {
        return this.state;
    };

    /**
     *
     */
    Jalousie.prototype.setState = function (state) {

        if (!_this.state.isMoving) {
            _this.isMoving = true;
        }

        if (this.state.position < state.position) {
            this.down(state);
        }

        if (this.state.position > state.position) {
            this.up(state);
        }

    };

    /**
     *
     */
    Jalousie.prototype.showPixel = function (parameters) {

        if (!this.isSimulated()) {
            let pixelToShow = (this.state.position / 12.5).toFixed();
            for (let i = 23; i >= 16; i--) {
                if (i <= (23 - pixelToShow)) {
                    this.strip.pixel(i).color(this.configuration.dayLightColorCode);
                    this.strip.pixel((i - 8)).color(this.configuration.dayLightColorCode);
                    this.strip.pixel((i - 16)).color(this.configuration.dayLightColorCode);
                } else {
                    this.strip.pixel(i).color("#000000");
                    this.strip.pixel(i - 8).color("#000000");
                    this.strip.pixel(i - 16).color("#000000");
                }
            }
            this.strip.show();
            //this.publishStateChange();
        }
    };

    /**
     *
     */
    Jalousie.prototype.up = function (pretarget) {
        this.stopMotion();

        this.logDebug("Jalousie Moving up");

        if (!_this.state.isMoving) {
            _this.state.isMoving = true;
            _this.publishStateChange({ isMoving: _this.state.isMoving });
        }

        var target = {};
        if (typeof pretarget === "undefined") {
            target.position = 0;
        } else {
            target = pretarget;
        }

        this.upInterval = setInterval(function () {
            this.state.position -= 12.5;
            this.publishStateChange();
            this.showPixel();

            if (this.state.position <= 0) {
                clearInterval(this.upInterval);
                if (_this.state.isMoving) {
                    _this.state.isMoving = false;
                    _this.publishStateChange({ isMoving: _this.state.isMoving });
                }
            }

        }.bind(this), this.configuration.speed);
    };

    /**
     *
     */
    Jalousie.prototype.down = function (pretarget) {
        this.stopMotion();

        this.logDebug("Jalousie Moving down");

        if (!_this.state.isMoving) {
            _this.state.isMoving = true;
            _this.publishStateChange({ isMoving: _this.state.isMoving });
        }

        var target = {};
        if (typeof pretarget === "undefined") {
            target.position = 100;
        } else {
            target = pretarget;
        }

        this.downInterval = setInterval(function () {
            this.state.position += 12.5;
            this.logDebug(this.state);
            this.publishStateChange();
            this.showPixel();

            console.log("actual state " + this.state.position);

            if (this.state.position >= 100) {
                clearInterval(this.downInterval);
                if (_this.state.isMoving) {
                    _this.state.isMoving = false;
                    _this.publishStateChange({ isMoving: _this.state.isMoving });
                }
            }

        }.bind(this), this.configuration.speed);
    };

    /**
     *
     */
    Jalousie.prototype.stopMotion = function () {

        if (_this.state.isMoving) {
            _this.state.isMoving = false;
            _this.publishStateChange({ isMoving: _this.state.isMoving });
        }

        if (this.upInterval) {
            clearInterval(this.upInterval);
        }

        if (this.downInterval) {
            clearInterval(this.downInterval);
        }

    };

    /**
     *
     */
    Jalousie.prototype.stop = function () {
        this.stopMotion();
        return this.state;
    };

}

<|endoftext|>


<commit_before>/* responsiveText */
(function(e){e.fn.responsiveText=function(){return this.each(function(){var t=e(this);var n=function(){var e=t.width()/parseInt(t.css("max-width"));t.css("font-size",e+"em")};n();e(window).bind("resize.responsiveText",n)})}})(jQuery)
<commit_msg>Adding minified version<commit_after>/* responsiveText */
(function(e){e.responsiveText=function(t,n){var r=this;r.settings={};var i=e(t),t=t;var s={minWidth:null,maxWidth:null};r.init=function(){r.settings=e.extend({},s,n)};r.resize=function(){var n=r.settings.maxWidth==null?parseInt(e(t).css("max-width")):parseInt(r.settings.maxWidth);var i=e(t).width();if(r.settings.minWidth!=null&&parseInt(r.settings.minWidth)>i){i=r.settings.minWidth}var s=i/n;e(t).css("font-size",s+"em")};r.init()};e.fn.responsiveText=function(t){return this.each(function(){if(undefined==e(this).data("responsiveText")){var n=new e.responsiveText(this,t);e(this).data("responsiveText",n)}e(this).data("responsiveText").resize();e(window).bind("resize.responsiveText",e(this).data("responsiveText").resize)})}})(jQuery)
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import {
	ReactiveBase,
	CategorySearch,
	ResultCard,
	MultiDropdownList,
	RangeSlider,
	DataSearch,
	SingleDropdownRange
} from '@appbaseio/reactivesearch';

import './Base.styl';

class Base extends Component {
	constructor() {
		super();
		this.state = {
			tags: [],
			showNav: false
		};
		this.toggleTag = this.toggleTag.bind(this);
		this.resetTag = this.resetTag.bind(this);
		this.handleToggleFilters = this.handleToggleFilters.bind(this);
	}

	handleToggleFilters() {
		const showNav = !this.state.showNav;
		this.setState({
			showNav
		});
	}

	toggleTag(tag) {
		const tags = [ ...this.state.tags ];
		const index = tags.indexOf(tag);
		let nextTags = [];
		if (index === -1) {
			nextTags = [ ...tags, tag ];
		} else {
			nextTags = tags.slice(0, index).concat(tags.slice(index + 1));
		}
		this.setState({
			tags: nextTags
		});
	}

	resetTag(tags) {
		this.setState({
			tags
		});
	}

	onData(res, toggleTag) {
		const result = {
			desc: (

									{res.owner}/{res.owner.length + res.name.length > 27 ?
 : ''}{res.name}

								{res.description}

							{
								res.topics.length > 0 ?

										{res.topics.slice(0, 7).map(tag => <span className="card-tag" key={`${res.name}-${tag}`} onClick={() => toggleTag(tag)}>#{tag})}

 :
								null
							}

								{res.stars}

								{res.forks}

								{res.watchers}

			)
		};
		return result;
	}

	render() {
		return (
			<ReactiveBase
				app="gitxplore-live"
				credentials="bYTSo47tj:d001826a-f4ef-42c5-b0aa-a94f29967ba0"
				theme="rbc-green"
			>
				<div className={`${this.state.showNav ? 'full-header' : ''}`}>

GitXplore

								Toggle Filters

								<MultiDropdownList
									componentId="language"
									appbaseField="language.raw"
									title="Language"
									searchPlaceholder="Search"
									initialLoader="Loading Languages..."
									size={500}
									URLParams={true}
								/>
								<MultiDropdownList
									componentId="topics"
									appbaseField="topics.raw"
									title="Repo Topics"
									searchPlaceholder="Search"
									initialLoader="Loading Topics..."
									defaultSelected={this.state.tags}
									onValueChange={value => this.resetTag(value)}
									size={800}
									URLParams={true}
								/>
								<SingleDropdownRange
									componentId="pushed"
									appbaseField="pushed"
									title="Last Active"
									URLParams={true}
									data={[
										{"start": "2017-05-30T00:00:13Z", "end": "2017-07-06T09:22:30Z", "label": "This month"},
										{"start": "2000-05-30T00:00:13Z", "end": "2017-05-29T05:41:13Z", "label": "Past"}
									]}
								/>
								<SingleDropdownRange
									componentId="created"
									appbaseField="created"
									title="Created"
									URLParams={true}
									data={[
										{"start": "2017-01-01T00:00:13Z", "end": "2017-07-06T09:22:30Z", "label": "This year"},
										{"start": "2016-01-01T00:00:13Z", "end": "2017-01-01T00:00:13Z", "label": "Last year"},
										{"start": "2000-05-30T00:00:13Z", "end": "2016-01-01T00:00:13Z", "label": "Past"},
									]}
								/>
								<RangeSlider
									title="Repo Stars"
									componentId="stars"
									appbaseField="stars"
									initialLoader="Loading data..."
									showHistogram={false}
									URLParams={true}
									range={{
										"start": 0,
										"end": 300000
									}}
									defaultSelected={{
										"start": 0,
										"end": 300000
									}}
									rangeLabels={{
										"start": "0 Stars",
										"end": "300K Stars"
									}}
									stepValue={100}
								/>
								<RangeSlider
									title="Repo Forks"
									componentId="forks"
									appbaseField="forks"
									initialLoader="Loading data..."
									showHistogram={false}
									URLParams={true}
									range={{
										"start": 0,
										"end": 300000
									}}
									defaultSelected={{
										"start": 0,
										"end": 300000
									}}
									rangeLabels={{
										"start": "0 Forks",
										"end": "300K Forks"
									}}
									stepValue={100}
								/>

					<CategorySearch
						componentId="repo"
						appbaseField={["name", "description"]}
						categoryField="language.raw"
						placeholder="Search Repos"
						autocomplete={false}
						URLParams={true}
					/>
					<ResultCard
						componentId="SearchResult"
						appbaseField="name"
						initialLoader="Loading data..."
						noResults="Oops! Nothing found."
						pagination={true}
						size={6}
						onData={(res) => this.onData(res, this.toggleTag)}
						react={{
							and: ["repo", "topics", "stars", "description", "forks", "pushed", "created", "language"]
						}}
						sortOptions={[
							{
								label: "Highest rated",
								appbaseField: "stars",
								sortBy: "desc"
							},
							{
								label: "Lowest rated",
								appbaseField: "stars",
								sortBy: "asc"
							},
							{
								label: "Most forked",
								appbaseField: "forks",
								sortBy: "desc"
							},
							{
								label: "Least forked",
								appbaseField: "forks",
								sortBy: "asc"
							},
							{
								label: "Alphabetic",
								appbaseField: "owner",
								sortBy: "asc"
							},
							{
								label: "Reverse alphabetic",
								appbaseField: "owner",
								sortBy: "desc"
							},
							{
								label: "Most recent",
								appbaseField: "pushed",
								sortBy: "desc"
							},
							{
								label: "Least recent",
								appbaseField: "pushed",
								sortBy: "asc"
							}
						]}
					/>

			</ReactiveBase>
		);
	}
}

export default Base;
<commit_msg>:rocket: Update dataset to 22K+ repos :fire:<commit_after>import React, { Component } from 'react';
import {
	ReactiveBase,
	CategorySearch,
	ResultCard,
	MultiDropdownList,
	RangeSlider,
	DataSearch,
	SingleDropdownRange
} from '@appbaseio/reactivesearch';

import './Base.styl';

class Base extends Component {
	constructor() {
		super();
		this.state = {
			tags: [],
			showNav: false
		};
		this.toggleTag = this.toggleTag.bind(this);
		this.resetTag = this.resetTag.bind(this);
		this.handleToggleFilters = this.handleToggleFilters.bind(this);
	}

	handleToggleFilters() {
		const showNav = !this.state.showNav;
		this.setState({
			showNav
		});
	}

	toggleTag(tag) {
		const tags = [ ...this.state.tags ];
		const index = tags.indexOf(tag);
		let nextTags = [];
		if (index === -1) {
			nextTags = [ ...tags, tag ];
		} else {
			nextTags = tags.slice(0, index).concat(tags.slice(index + 1));
		}
		this.setState({
			tags: nextTags
		});
	}

	resetTag(tags) {
		this.setState({
			tags
		});
	}

	onData(res, toggleTag) {
		const result = {
			desc: (

									{res.owner}/{res.owner.length + res.name.length > 27 ?
 : ''}{res.name}

								{res.description}

							{
								res.topics.length > 0 ?

										{res.topics.slice(0, 7).map(tag => <span className="card-tag" key={`${res.name}-${tag}`} onClick={() => toggleTag(tag)}>#{tag})}

 :
								null
							}

								{res.stars}

								{res.forks}

								{res.watchers}

			)
		};
		return result;
	}

	render() {
		return (
			<ReactiveBase
				app="gitxplore-live"
				credentials="bYTSo47tj:d001826a-f4ef-42c5-b0aa-a94f29967ba0"
				theme="rbc-green"
			>
				<div className={`${this.state.showNav ? 'full-header' : ''}`}>

GitXplore

								Toggle Filters

								<MultiDropdownList
									componentId="language"
									appbaseField="language.raw"
									title="Language"
									searchPlaceholder="Search"
									initialLoader="Loading Languages..."
									size={100}
									URLParams={true}
								/>
								<MultiDropdownList
									componentId="topics"
									appbaseField="topics.raw"
									title="Repo Topics"
									searchPlaceholder="Search"
									initialLoader="Loading Topics..."
									defaultSelected={this.state.tags}
									onValueChange={value => this.resetTag(value)}
									size={100}
									URLParams={true}
								/>
								<SingleDropdownRange
									componentId="pushed"
									appbaseField="pushed"
									title="Last Active"
									URLParams={true}
									data={[
										{"start": "2017-05-30T00:00:13Z", "end": "2017-07-06T09:22:30Z", "label": "This month"},
										{"start": "2000-05-30T00:00:13Z", "end": "2017-05-29T05:41:13Z", "label": "Past"}
									]}
								/>
								<SingleDropdownRange
									componentId="created"
									appbaseField="created"
									title="Created"
									URLParams={true}
									data={[
										{"start": "2017-01-01T00:00:13Z", "end": "2017-07-06T09:22:30Z", "label": "This year"},
										{"start": "2016-01-01T00:00:13Z", "end": "2017-01-01T00:00:13Z", "label": "Last year"},
										{"start": "2000-05-30T00:00:13Z", "end": "2016-01-01T00:00:13Z", "label": "Past"},
									]}
								/>
								<RangeSlider
									title="Repo Stars"
									componentId="stars"
									appbaseField="stars"
									initialLoader="Loading data..."
									showHistogram={false}
									URLParams={true}
									range={{
										"start": 0,
										"end": 300000
									}}
									defaultSelected={{
										"start": 0,
										"end": 300000
									}}
									rangeLabels={{
										"start": "0 Stars",
										"end": "300K Stars"
									}}
									stepValue={100}
								/>
								<RangeSlider
									title="Repo Forks"
									componentId="forks"
									appbaseField="forks"
									initialLoader="Loading data..."
									showHistogram={false}
									URLParams={true}
									range={{
										"start": 0,
										"end": 180000
									}}
									defaultSelected={{
										"start": 0,
										"end": 180000
									}}
									rangeLabels={{
										"start": "0 Forks",
										"end": "180K Forks"
									}}
									stepValue={100}
								/>

					<CategorySearch
						componentId="repo"
						appbaseField={["name", "description"]}
						categoryField="language.raw"
						placeholder="Search Repos"
						autocomplete={false}
						URLParams={true}
					/>
					<ResultCard
						componentId="SearchResult"
						appbaseField="name"
						initialLoader="Loading data..."
						noResults="Oops! Nothing found."
						pagination={true}
						size={6}
						onData={(res) => this.onData(res, this.toggleTag)}
						react={{
							and: ["repo", "topics", "stars", "description", "forks", "pushed", "created", "language"]
						}}
						sortOptions={[
							{
								label: "Highest rated",
								appbaseField: "stars",
								sortBy: "desc"
							},
							{
								label: "Lowest rated",
								appbaseField: "stars",
								sortBy: "asc"
							},
							{
								label: "Most forked",
								appbaseField: "forks",
								sortBy: "desc"
							},
							{
								label: "Least forked",
								appbaseField: "forks",
								sortBy: "asc"
							},
							{
								label: "Alphabetic",
								appbaseField: "owner",
								sortBy: "asc"
							},
							{
								label: "Reverse alphabetic",
								appbaseField: "owner",
								sortBy: "desc"
							},
							{
								label: "Most recent",
								appbaseField: "pushed",
								sortBy: "desc"
							},
							{
								label: "Least recent",
								appbaseField: "pushed",
								sortBy: "asc"
							}
						]}
					/>

			</ReactiveBase>
		);
	}
}

export default Base;
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Link } from 'react-router';
import styles from './Home.module.css';
const { TextField,Snackbar } = require('material-ui');
const GitHubApi = require("github-api");
var slug = require('limax');
var moment = require('moment');
var marked = require('marked');
var toMarkdown = require('to-markdown');

export default class Home extends Component {
  constructor() {
    super();
    this.state = {
      autoHideDuration: 0,
      sending: 0,
      title: "",
      author: "白米君",
      url: "",
      date: moment(Date.now()).format('YYYY-MM-DD'),
      message: ""
    };

    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleTitleChange = this.handleTitleChange.bind(this);
    this.handleAuthorChange = this.handleAuthorChange.bind(this);
    this.handleDateChange = this.handleDateChange.bind(this);
    this.handleURLChange = this.handleURLChange.bind(this);
  }

  handleSubmit() {
    var that = this;
    this.setState({
      sending: 1
    });

    if (localStorage.getItem('token') === null || localStorage.getItem('repo') === null) {
      that.setState({message: "跳转到设置中..."});
      that.refs.snackbar.show();
      return;
    }

    var token = localStorage.getItem('token');
    var username = localStorage.getItem('repo').split("/")[0];
    var reponame = localStorage.getItem('repo').split("/")[1];

    var github = new GitHubApi({
      token: token,
      auth: "oauth"
    });
    var repo = github.getRepo(username, reponame);

    var options = {
      author: {name: username, email: 'robot@baimizhou.net'},
      committer: {name: username, email: 'robot@baimizhou.net'},
      encode: true
    };

    var md = toMarkdown(document.getElementById('editor').innerHTML);

    var data = {
      title: that.state.title,
      author: that.state.author,
      url: '/' + that.state.url,
      date: '/' + that.state.date,
      content: md
    };

    //repo.write('master', 'path/to/file', 'YOUR_NEW_CONTENTS', 'YOUR_COMMIT_MESSAGE', options, function(err) {
    //  console.log(data);
    //});

    //repo.read('master', 'README.md', function (err, data) {
    //  that.setState({message: "上传成功" + data});
    //  that.refs.snackbar.show();
    //  that.setState({
    //    sending: 0
    //  });
    //});
  };

  handleTitleChange(e) {
    this.setState({
      title: e.target.value,
      url: slug(e.target.value, {tone: false})
    });
  };

  handleAuthorChange(e) {
    this.setState({
      author: e.target.value
    });
  };

  handleDateChange(e) {
    this.setState({
      date: e.target.value
    });
  };

  handleURLChange(e) {
    this.setState({
      url: e.target.value
    });
  };

  static getStyles() {
    return {
      link: {
        marginLeft: "2em"
      },
      author: {
        marginLeft: "2em",
        width: "4em"
      },
      date: {
        marginLeft: "2em",
        width: "10em"
      }
    };
  };

  render() {
    var inlineStyles = Home.getStyles();
    var Message = this.state.message;

    return (

              <TextField
                defaultValue={this.state.title}
                onChange={this.handleTitleChange}
                floatingLabelText="标题"
                hintText="标题"/>

              <TextField
                style={inlineStyles.author}
                defaultValue={this.state.author}
                onChange={this.handleAuthorChange}
                floatingLabelText="作者"
                hintText="白米粥"/>

              <TextField
                style={inlineStyles.link}
                defaultValue={this.state.url}
                value={this.state.url}
                onChange={this.handleURLChange}
                floatingLabelText="链接名"
                hintText="baimizhou-2014"/>

              <TextField
                style={inlineStyles.date}
                defaultValue={this.state.date}
                onChange={this.handleDateChange}
                type="date"
                floatingLabelText="日期" />

              <button type="submit" className="fa fa-fw fa-paper-plane-o mode" onClick={this.handleSubmit}
                      disabled={this.sending}/>

            说说你的故事...

        <Snackbar
          ref="snackbar"
          message={Message}
          autoHideDuration={this.state.autoHideDuration}/>

    );
  }
}
<commit_msg>add save to localstorage<commit_after>import React, { Component } from 'react';
import { Link } from 'react-router';
import styles from './Home.module.css';
const { TextField,Snackbar } = require('material-ui');
const GitHubApi = require("github-api");
var slug = require('limax');
var moment = require('moment');
var marked = require('marked');
var toMarkdown = require('to-markdown');

export default class Home extends Component {
  constructor() {
    super();
    this.state = {
      autoHideDuration: 0,
      sending: 0,
      title: "",
      author: "白米君",
      url: "",
      date: moment(Date.now()).format('YYYY-MM-DD'),
      message: ""
    };

    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleTitleChange = this.handleTitleChange.bind(this);
    this.handleAuthorChange = this.handleAuthorChange.bind(this);
    this.handleDateChange = this.handleDateChange.bind(this);
    this.handleURLChange = this.handleURLChange.bind(this);
  }

  componentDidMount() {
    if(localStorage.getItem('data') !== null ){
      var data = JSON.parse(localStorage.getItem('data'));
      this.setState({
        title: data.title,
        author: data.author,
        url: data.url,
        date: data.date,
        content: data.content
      });
      document.getElementById('editor').innerHTML = data.contentHTML;
    }
  }

  handleSubmit() {
    var that = this;
    this.setState({
      sending: 1
    });

    if (localStorage.getItem('token') === null || localStorage.getItem('repo') === null) {
      that.setState({message: "跳转到设置中..."});
      that.refs.snackbar.show();
      return;
    }

    var token = localStorage.getItem('token');
    var username = localStorage.getItem('repo').split("/")[0];
    var reponame = localStorage.getItem('repo').split("/")[1];

    var github = new GitHubApi({
      token: token,
      auth: "oauth"
    });
    var repo = github.getRepo(username, reponame);

    var options = {
      author: {name: username, email: 'robot@baimizhou.net'},
      committer: {name: username, email: 'robot@baimizhou.net'},
      encode: true
    };

    var innerHTML = document.getElementById('editor').innerHTML;
    var md = toMarkdown(innerHTML);

    var data = {
      title: that.state.title,
      author: that.state.author,
      url: that.state.url,
      date: that.state.date,
      contentHTML: innerHTML,
      content: md
    };

    localStorage.setItem('data', JSON.stringify(data));

    //repo.write('master', 'path/to/file', 'YOUR_NEW_CONTENTS', 'YOUR_COMMIT_MESSAGE', options, function(err) {
    //  console.log(data);
    //});

    //repo.read('master', 'README.md', function (err, data) {
    //  that.setState({message: "上传成功" + data});
    //  that.refs.snackbar.show();
    //  that.setState({
    //    sending: 0
    //  });
    //});
  };

  handleTitleChange(e) {
    this.setState({
      title: e.target.value,
      url: slug(e.target.value, {tone: false})
    });
  };

  handleAuthorChange(e) {
    this.setState({
      author: e.target.value
    });
  };

  handleDateChange(e) {
    this.setState({
      date: e.target.value
    });
  };

  handleURLChange(e) {
    this.setState({
      url: e.target.value
    });
  };

  static getStyles() {
    return {
      link: {
        marginLeft: "2em"
      },
      author: {
        marginLeft: "2em",
        width: "4em"
      },
      date: {
        marginLeft: "2em",
        width: "10em"
      }
    };
  };

  render() {
    var inlineStyles = Home.getStyles();
    var Message = this.state.message;

    return (

              <TextField
                defaultValue={this.state.title}
                onChange={this.handleTitleChange}
                floatingLabelText="标题"
                hintText="标题"/>

              <TextField
                style={inlineStyles.author}
                defaultValue={this.state.author}
                onChange={this.handleAuthorChange}
                floatingLabelText="作者"
                hintText="白米粥"/>

              <TextField
                style={inlineStyles.link}
                defaultValue={this.state.url}
                value={this.state.url}
                onChange={this.handleURLChange}
                floatingLabelText="链接名"
                hintText="baimizhou-2014"/>

              <TextField
                style={inlineStyles.date}
                defaultValue={this.state.date}
                onChange={this.handleDateChange}
                type="date"
                floatingLabelText="日期"/>

              <button type="submit" className="fa fa-fw fa-paper-plane-o mode" onClick={this.handleSubmit}
                      disabled={this.sending}/>

            说说你的故事...

        <Snackbar
          ref="snackbar"
          message={Message}
          autoHideDuration={this.state.autoHideDuration}/>

    );
  }
}
<|endoftext|>


<commit_before>'use strict';

var React = require('react-native');

var {
  StyleSheet,
  TouchableOpacity,
  View,
} = React;

var Constants = require('../constants');
var styles = require('../styles');
var Icon = require('react-native-vector-icons/Ionicons');

var currentTab = Constants.Views.Find.Home;

var TabBar = React.createClass({

  _changeTabs(tab) {
    // Switch to the selected tab
    currentTab = tab;
    this.props.navigator.push({id: tab});
  },

  render() {
    return (
      <View style={_styles.container}>
        <TouchableOpacity onPress={() => {this._changeTabs(Constants.Views.Find.Home)}} style={_styles.tab}>
          {currentTab === Constants.Views.Find.Home
              ? <Icon name={'navigate'} size={30} color='white' style={_styles.icon} />
              : <Icon name={'navigate'} size={30} color={Constants.Colors.darkGrey} style={_styles.icon} />}
        </TouchableOpacity>
        <TouchableOpacity onPress={() => {this._changeTabs(Constants.Views.Buses.Home)}} style={_styles.tab}>
        {currentTab === Constants.Views.Buses.Home
            ? <Icon name={'android-bus'} size={30} color='white' style={_styles.icon} />
            : <Icon name={'android-bus'} size={30} color={Constants.Colors.darkGrey} style={_styles.icon} />}
        </TouchableOpacity>
        <TouchableOpacity onPress={() => {this._changeTabs(Constants.Views.Discover.Home)}} style={_styles.tab}>
        {currentTab === Constants.Views.Discover.Home
            ? <Icon name={'compass'} size={30} color='white' style={_styles.icon} />
            : <Icon name={'compass'} size={30} color={Constants.Colors.darkGrey} style={_styles.icon} />}
        </TouchableOpacity>
        <TouchableOpacity onPress={() => {this._changeTabs(Constants.Views.Settings.Home)}} style={_styles.tab}>
        {currentTab === Constants.Views.Settings.Home
            ? <Icon name={'ios-gear'} size={30} color='white' style={_styles.icon} />
            : <Icon name={'ios-gear'} size={30} color={Constants.Colors.darkGrey} style={_styles.icon} />}
        </TouchableOpacity>
      </View>
    )
  },
});

var _styles = StyleSheet.create({
  container: {
    height: 45,
    flexDirection: 'row',
    paddingTop: 5,
    borderWidth: 1,
    borderTopWidth: 0,
    borderLeftWidth: 0,
    borderRightWidth: 0,
    borderBottomColor: 'rgba(0,0,0,0.05)',
  },
  tab: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingBottom: 10,
  },
  icon: {
    width: 30,
    height: 30,
    position: 'absolute',
    top: 0,
    left: 20,
  },
});

module.exports = TabBar;
<commit_msg>Formatted tabs<commit_after>'use strict';

var React = require('react-native');

var {
  Platform,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} = React;

var Constants = require('../constants');
var styles = require('../styles');
var Icon;
var tabIcons;

if (Platform.OS === 'ios') {
  Icon = require('react-native-vector-icons/Ionicons');
  tabIcons = {
    'Find': 'navigate',
    'Buses': 'android-bus',
    'Discover': 'compass',
    'Settings': 'ios-gear',
  };
} else {
  Icon = require('react-native-vector-icons/MaterialIcons');
  tabIcons = {
    'Find': 'directions',
    'Buses': 'directions-bus',
    'Discover': 'near-me',
    'Settings': 'settings',
  };
}

var currentTab = Constants.Views.Find.Home;

var TabBar = React.createClass({

  _changeTabs(tab) {
    // Switch to the selected tab
    currentTab = tab;
    this.props.navigator.push({id: tab});
  },

  render() {
    let findColor = Constants.Colors.charcoalGrey;
    let busColor = Constants.Colors.charcoalGrey;
    let discoverColor = Constants.Colors.charcoalGrey;
    let settingsColor = Constants.Colors.charcoalGrey;

    // Set the color of the current tab to garnet
    if (currentTab === Constants.Views.Find.Home) {
      findColor = Constants.Colors.garnet;
    } else if (currentTab === Constants.Views.Buses.Home) {
      busColor = Constants.Colors.garnet;
    } else if (currentTab === Constants.Views.Discover.Home) {
      discoverColor = Constants.Colors.garnet;
    } else if (currentTab === Constants.Views.Settings.Home) {
      settingsColor = Constants.Colors.garnet;
    }

    return (
      <View style={_styles.container}>
        <TouchableOpacity onPress={() => {this._changeTabs(Constants.Views.Find.Home)}} style={_styles.tab}>
          <Icon name={tabIcons['Find']} size={30} color={findColor} style={_styles.icon} />
        </TouchableOpacity>
        <TouchableOpacity onPress={() => {this._changeTabs(Constants.Views.Buses.Home)}} style={_styles.tab}>
          <Icon name={tabIcons['Buses']} size={30} color={busColor} style={_styles.icon} />
        </TouchableOpacity>
        <TouchableOpacity onPress={() => {this._changeTabs(Constants.Views.Discover.Home)}} style={_styles.tab}>
          <Icon name={tabIcons['Discover']} size={30} color={discoverColor} style={_styles.icon} />
        </TouchableOpacity>
        <TouchableOpacity onPress={() => {this._changeTabs(Constants.Views.Settings.Home)}} style={_styles.tab}>
          <Icon name={tabIcons['Settings']} size={30} color={settingsColor} style={_styles.icon} />
        </TouchableOpacity>
      </View>
    )
  },
});

var _styles = StyleSheet.create({
  container: {
    height: 50,
    flexDirection: 'row',
    borderWidth: 1,
    borderBottomWidth: 0,
    borderLeftWidth: 0,
    borderRightWidth: 0,
    borderTopColor: 'rgba(0, 0, 0, 0.4)',
    backgroundColor: Constants.Colors.polarGrey,
  },
  tab: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  icon: {
    width: 30,
    height: 30,
  },
});

module.exports = TabBar;
<|endoftext|>


<commit_before>var glOutputBinding = new Shiny.OutputBinding();
$.extend(glOutputBinding, {
  find: function(scope) {
    return $(scope).find('.shiny-gl-output');
  },
  renderValue: function(el, data) {

    if (!data || !data.html){
      return;
    }

    $(el).html(data.html);

    setTimeout(function() {
      // check to see whether we're using the old or new RGL function type.
      oldFun = window[data.prefix + "webGLStart"];
      newObj = window[data.prefix + "WebGL"];
      if(typeof oldFun === 'function'){
        oldFun();
      } else if(typeof newObj === 'object'){
        newObj.start();
        newObj.onZoom(function(zoom){
          Shiny.onInputChange('.clientdata_gl_output_' + el.id + '_zoom', zoom);
        });
        newObj.onFOV(function(fov){
          Shiny.onInputChange('.clientdata_gl_output_' + el.id + '_fov', fov);
        });
        newObj.onPan(function(pan){
          Shiny.onInputChange('.clientdata_gl_output_' + el.id + '_pan', pan.getAsArray());
        });

      } else{
        throw new Error("Could not find method of starting WebGL scene.");
      }

    }, 0);

  }
});
Shiny.outputBindings.register(glOutputBinding, 'shinyRGL.glbinding');

/**
 * Update the GL Size as the widget becomes visible.
 */
$(document).ready(function(){
  $('body').on('shown.sendOutputHiddenState hidden.sendOutputHiddenState', '*',
                 function(){sendGLSize();});
});

$(window).resize(debounce(500, sendGLSize));

// The server needs to know the size of each image and plot output element,
// in case it is auto-sizing
// Author: Joe Cheng
// https://github.com/rstudio/shiny/blob/master/inst/www/shared/shiny.js
// Modified by: Jeff Allen
function sendGLSize() {
  $('.shiny-gl-output').each(function() {
    if (this.offsetWidth !== 0 || this.offsetHeight !== 0) {
      Shiny.onInputChange('.clientdata_gl_output_' + this.id + '_width', this.offsetWidth);
      Shiny.onInputChange('.clientdata_gl_output_' + this.id + '_height', this.offsetHeight);
    }
  });
}
$(function() {
  // Init Shiny a little later than document ready, so user code can
  // run first (i.e. to register bindings)
  setTimeout(sendGLSize, 1);
});

// Returns a debounced version of the given function.
// Debouncing means that when the function is invoked,
// there is a delay of `threshold` milliseconds before
// it is actually executed, and if the function is
// invoked again before that threshold has elapsed then
// the clock starts over.
//
// For example, if a function is debounced with a
// threshold of 1000ms, then calling it 17 times at
// 900ms intervals will result in a single execution
// of the underlying function, 1000ms after the 17th
// call.
// Author: Joe Cheng
// https://github.com/rstudio/shiny/blob/master/inst/www/shared/shiny.js
  function debounce(threshold, func) {
    var timerId = null;
    var self, args;
    return function() {
      self = this;
      args = arguments;
      if (timerId !== null) {
        clearTimeout(timerId);
        timerId = null;
      }
      timerId = setTimeout(function() {
        timerId = null;
        func.apply(self, args);
      }, threshold);
    };
  }<commit_msg>Enable clicking on 3D plots (requires rgl modification)<commit_after>var glOutputBinding = new Shiny.OutputBinding();
$.extend(glOutputBinding, {
  find: function(scope) {
    return $(scope).find('.shiny-gl-output');
  },
  renderValue: function(el, data) {

    if (!data || !data.html){
      return;
    }

    $(el).html(data.html);

    setTimeout(function() {
      // check to see whether we're using the old or new RGL function type.
      oldFun = window[data.prefix + "webGLStart"];
      newObj = window[data.prefix + "WebGL"];
      if(typeof oldFun === 'function'){
        oldFun();
      } else if(typeof newObj === 'object'){
        newObj.start();
        newObj.onZoom(function(zoom){
          Shiny.onInputChange('.clientdata_gl_output_' + el.id + '_zoom', zoom);
        });
        newObj.onFOV(function(fov){
          Shiny.onInputChange('.clientdata_gl_output_' + el.id + '_fov', fov);
        });
        newObj.onPan(function(pan){
          Shiny.onInputChange('.clientdata_gl_output_' + el.id + '_pan', pan.getAsArray());
        });
        newObj.onClick(function(x, y){
          Shiny.onInputChange(el.id + '.click', [x,y]);
          Shiny.onInputChange('.clientdata_gl_output_' + el.id + '_click', [x,y]);
        });
      } else{
        throw new Error("Could not find method of starting WebGL scene.");
      }

    }, 0);

  }
});
Shiny.outputBindings.register(glOutputBinding, 'shinyRGL.glbinding');

/**
 * Update the GL Size as the widget becomes visible.
 */
$(document).ready(function(){
  $('body').on('shown.sendOutputHiddenState hidden.sendOutputHiddenState', '*',
                 function(){sendGLSize();});
});

$(window).resize(debounce(500, sendGLSize));

// The server needs to know the size of each image and plot output element,
// in case it is auto-sizing
// Author: Joe Cheng
// https://github.com/rstudio/shiny/blob/master/inst/www/shared/shiny.js
// Modified by: Jeff Allen
function sendGLSize() {
  $('.shiny-gl-output').each(function() {
    if (this.offsetWidth !== 0 || this.offsetHeight !== 0) {
      Shiny.onInputChange('.clientdata_gl_output_' + this.id + '_width', this.offsetWidth);
      Shiny.onInputChange('.clientdata_gl_output_' + this.id + '_height', this.offsetHeight);
    }
  });
}
$(function() {
  // Init Shiny a little later than document ready, so user code can
  // run first (i.e. to register bindings)
  setTimeout(sendGLSize, 1);
});

// Returns a debounced version of the given function.
// Debouncing means that when the function is invoked,
// there is a delay of `threshold` milliseconds before
// it is actually executed, and if the function is
// invoked again before that threshold has elapsed then
// the clock starts over.
//
// For example, if a function is debounced with a
// threshold of 1000ms, then calling it 17 times at
// 900ms intervals will result in a single execution
// of the underlying function, 1000ms after the 17th
// call.
// Author: Joe Cheng
// https://github.com/rstudio/shiny/blob/master/inst/www/shared/shiny.js
  function debounce(threshold, func) {
    var timerId = null;
    var self, args;
    return function() {
      self = this;
      args = arguments;
      if (timerId !== null) {
        clearTimeout(timerId);
        timerId = null;
      }
      timerId = setTimeout(function() {
        timerId = null;
        func.apply(self, args);
      }, threshold);
    };
  }<|endoftext|>


<commit_before>var mongoose         = require('mongoose')
var LocalStrategy    = require('passport-local').Strategy
var TwitterStrategy  = require('passport-twitter').Strategy;
var FacebookStrategy = require('passport-facebook').Strategy;
var User             = mongoose.model('User')

module.exports = function (app, passport) {

  // 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 local strategy
  passport.use(new LocalStrategy({
      usernameField: 'email',
      passwordField: 'password'
    },
    function(email, password, done) {

      User.findOne( { email: email } , function (err, user) {

        if (err) {
          return done(err)
        }

        if (!user) {
          return done(null, false, { message: 'Your email not register' })
        }

        if(user.is_confirm === false) {
          return done(null, false, { message: 'Your email not confirm yet' })
        }

        if(user.is_active === false) {
          return done(null, false, { message: 'Your account not approved yet. Please Wait' })
        }

        if (!user.authenticate(password)) {
          return done(null, false, { message: 'invalid login or password' })
        }

        return done(null, user)
      })
    }
  ))

  /**
   * Sign in with Twitter.
   */

  passport.use(new TwitterStrategy(app.config.twitter, function(req, accessToken, tokenSecret, profile, done) {
    if (req.user) {
      User.findOne({ 'twitter.id': profile.id }, function(err, existingUser) {
        if (existingUser) {
          req.flash('errors', { msg: 'There is already a Twitter account that belongs to you. Sign in with that account or delete it, then link it with your current account.' })
          done(err)
        } else {
          User.findById(req.user.id, function(err, user) {

            user.email    = profile.username + "@twitter.com"
            user.provider = 'twitter'
            user.twitter  = profile
            user.username = profile.screen_name
            user.tokens.push({ kind: 'twitter', accessToken: accessToken, tokenSecret: tokenSecret })

            user.save(function(err) {
              req.flash('info', { msg: 'Twitter account has been linked.' })
              done(err, user)
            });
          });
        }
      });

    } else {
      User.findOne({ 'twitter.id': profile.id }, function(err, existingUser) {
        if (existingUser) return done(null, existingUser)
        var user = new User()
        // Twitter will not provide an email address.  Period.
        // But a person’s twitter username is guaranteed to be unique
        // so we can "fake" a twitter email address as follows:

        user.email    = profile.username + "@twitter.com"
        user.provider = 'twitter'
        user.twitter  = profile
        user.username = profile.screen_name
        user.tokens.push({ kind: 'twitter', accessToken: accessToken, tokenSecret: tokenSecret })

        user.save(function(err) {
          done(err, user)
        });
      });
    }
  }));

  /**
   * Sign in with Facebook.
   */

  passport.use(new FacebookStrategy(app.config.facebook, function(req, accessToken, refreshToken, profile, done) {
    if (req.user) {
      User.findOne({ $or: [{ 'facebook.id' : profile.id }, { email: profile.email }] }, function(err, existingUser) {
        if (existingUser) {
          req.flash('errors', { msg: 'There is already a Facebook account that belongs to you. Sign in with that account or delete it, then link it with your current account.' });
          done(err);
        } else {
          User.findById(req.user.id, function(err, user) {
            user.facebook      = profile;
            user.username      = profile.username
            user.provider      = 'facebook',
            user.facebook      = profile._json
            user.firstname     = user.firstname || profile.first_name
            user.lastname      = user.lastname || profile.last_name
            user.photo_profile = user.photo_profile || 'https://graph.facebook.com/' + profile.id + '/picture?type=large';

            user.tokens.push({ kind: 'facebook', accessToken: accessToken });

            user.save(function(err) {
              req.flash('info', { msg: 'Facebook account has been linked.' });
              done(err, user);
            });
          });
        }
      });
    } else {
      User.findOne({ 'facebook.id' : profile.id }, function(err, existingUser) {

        if (existingUser) return done(null, existingUser);

        User.findOne({ email: profile._json.email }, function(err, existingEmailUser) {
          if (existingEmailUser) {
            req.flash('errors', { msg: 'There is already an account using this email address. Sign in to that account and link it with Facebook manually from Account Settings.' });
            done(err);
          } else {
            var user = new User();
            user.email         = profile._json.email;
            user.facebook      = profile;
            user.username      = profile.username
            user.provider      = 'facebook',
            user.facebook      = profile._json
            user.firstname     = user.firstname || profile.first_name
            user.lastname      = user.lastname || profile.last_name
            user.photo_profile = user.photo_profile || 'https://graph.facebook.com/' + profile.id + '/picture?type=large';

            user.tokens.push({ kind: 'facebook', accessToken: accessToken });

            user.save(function(err) {
              done(err, user);
            });
          }
        });
      });
    }
  }));

}
<commit_msg>fixing store data from twitter json<commit_after>var mongoose         = require('mongoose')
var LocalStrategy    = require('passport-local').Strategy
var TwitterStrategy  = require('passport-twitter').Strategy;
var FacebookStrategy = require('passport-facebook').Strategy;
var User             = mongoose.model('User')

module.exports = function (app, passport) {

  // 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 local strategy
  passport.use(new LocalStrategy({
      usernameField: 'email',
      passwordField: 'password'
    },
    function(email, password, done) {

      User.findOne( { email: email } , function (err, user) {

        if (err) {
          return done(err)
        }

        if (!user) {
          return done(null, false, { message: 'Your email not register' })
        }

        if(user.is_confirm === false) {
          return done(null, false, { message: 'Your email not confirm yet' })
        }

        if(user.is_active === false) {
          return done(null, false, { message: 'Your account not approved yet. Please Wait' })
        }

        if (!user.authenticate(password)) {
          return done(null, false, { message: 'invalid login or password' })
        }

        return done(null, user)
      })
    }
  ))

  /**
   * Sign in with Twitter.
   */

  passport.use(new TwitterStrategy(app.config.twitter, function(req, accessToken, tokenSecret, profile, done) {
    if (req.user) {
      User.findOne({ 'twitter.id': profile.id }, function(err, existingUser) {
        if (existingUser) {
          req.flash('errors', { msg: 'There is already a Twitter account that belongs to you. Sign in with that account or delete it, then link it with your current account.' })
          done(err)
        } else {
          User.findById(req.user.id, function(err, user) {

            user.email         = profile.username + "@twitter.com"
            user.provider      = 'twitter'
            user.twitter       = profile._json
            user.photo_profile = profile._json.profile_image_url
            user.username      = profile.username
            user.tokens.push({ kind: 'twitter', accessToken: accessToken, tokenSecret: tokenSecret })

            user.save(function(err) {
              req.flash('info', { msg: 'Twitter account has been linked.' })
              done(err, user)
            });
          });
        }
      });

    } else {
      User.findOne({ 'twitter.id': profile.id }, function(err, existingUser) {
        if (existingUser) return done(null, existingUser)
        var user = new User()
        // Twitter will not provide an email address.  Period.
        // But a person’s twitter username is guaranteed to be unique
        // so we can "fake" a twitter email address as follows:

        user.email         = profile.username + "@twitter.com"
        user.provider      = 'twitter'
        user.twitter       = profile._json
        user.photo_profile = profile._json.profile_image_url
        user.username      = profile.username
        user.tokens.push({ kind: 'twitter', accessToken: accessToken, tokenSecret: tokenSecret })

        user.save(function(err) {
          done(err, user)
        });
      });
    }
  }));

  /**
   * Sign in with Facebook.
   */

  passport.use(new FacebookStrategy(app.config.facebook, function(req, accessToken, refreshToken, profile, done) {
    if (req.user) {
      User.findOne({ $or: [{ 'facebook.id' : profile.id }, { email: profile.email }] }, function(err, existingUser) {
        if (existingUser) {
          req.flash('errors', { msg: 'There is already a Facebook account that belongs to you. Sign in with that account or delete it, then link it with your current account.' });
          done(err);
        } else {
          User.findById(req.user.id, function(err, user) {
            user.facebook      = profile;
            user.username      = profile.username
            user.provider      = 'facebook',
            user.facebook      = profile._json
            user.firstname     = user.firstname || profile.first_name
            user.lastname      = user.lastname || profile.last_name
            user.photo_profile = user.photo_profile || 'https://graph.facebook.com/' + profile.id + '/picture?type=large';

            user.tokens.push({ kind: 'facebook', accessToken: accessToken });

            user.save(function(err) {
              req.flash('info', { msg: 'Facebook account has been linked.' });
              done(err, user);
            });
          });
        }
      });
    } else {
      User.findOne({ 'facebook.id' : profile.id }, function(err, existingUser) {

        if (existingUser) return done(null, existingUser);

        User.findOne({ email: profile._json.email }, function(err, existingEmailUser) {
          if (existingEmailUser) {
            req.flash('errors', { msg: 'There is already an account using this email address. Sign in to that account and link it with Facebook manually from Account Settings.' });
            done(err);
          } else {
            var user = new User();
            user.email         = profile._json.email;
            user.facebook      = profile;
            user.username      = profile.username
            user.provider      = 'facebook',
            user.facebook      = profile._json
            user.firstname     = user.firstname || profile.first_name
            user.lastname      = user.lastname || profile.last_name
            user.photo_profile = user.photo_profile || 'https://graph.facebook.com/' + profile.id + '/picture?type=large';

            user.tokens.push({ kind: 'facebook', accessToken: accessToken });

            user.save(function(err) {
              done(err, user);
            });
          }
        });
      });
    }
  }));

}
<|endoftext|>


<commit_before>// This file requires papaparse.js to work
// The purpose of this file is to make it straight forward to open and extract information from CSV files. It is a wrapper for papaparse

function CSVFile(FileName){//file name in this instance is the URL
	var TempOpenCSVHolder=this;//A pointer to this file that can be called when the file is finished and ready to store
	this.CurrentlyLoading=true;

	Papa.parse(FileName, {download: true, complete: function(PapaResults){TempOpenCSVHolder.Data=PapaResults.data;TempOpenCSVHolder.CurrentlyLoading=false;} });
	//download informs Papa that it is an external CSV (http request), and the function is a handler to run when the file is ready

};

CSVFile.prototype.GetValues= function (y1, y2, x1, x2){//Changing to (row1, row2, column1, column2), as is expected in a CSV file
	//checking input is good
	if (x1>x2 || y1>y2 || x1<0 || y1<0 || this.IsNaturalNumber(x1)==false || this.IsNaturalNumber(x2)==false || this.IsNaturalNumber(y1)==false || this.IsNaturalNumber(y2)==false ){
		console.error("The range of values requested is invalid");
	}

	ReturnArray=[];
	newyindex=0;
	for (yindex=y1; yindex<=y2; yindex++){
		ReturnArray[newyindex]=[];
		newxindex=0;
		for (xindex=x1; xindex<=x2; xindex++){
			if (typeof this.Data[yindex][xindex]==="undefined"){// If this value is bigger than the largest value of data
				ReturnArray[newyindex][newxindex]=NaN;
			}
			else{
				ReturnArray[newyindex][newxindex]=Number(this.Data[yindex][xindex]);
			}
			newxindex++;
		}
		newyindex++;
	}
	return ReturnArray;
};

CSVFile.prototype.GetColumn= function (ColumnNum, StartRow, EndRow){//
	if (StartRow>EndRow || ColumnNum<0 || StartRow<0 || this.IsNaturalNumber(ColumnNum)==false || this.IsNaturalNumber(StartRow)==false || this.IsNaturalNumber(EndRow)==false){
		console.error("The range of values requested is invalid");
	}

	var TempVec=this.GetValues(StartRow, EndRow, ColumnNum, ColumnNum);

	//Refactor the vector into a proper vector
	var ReturnVec=[];
	for (var i=0; i<TempVec.length; i++ ){
		ReturnVec[i]=TempVec[i][0];
	}
	return ReturnVec;
}

CSVFile.prototype.GetRow= function (RowNum, StartColumn, EndColumn){//
	if (StartColumn>EndColumn || RowNum<0 || StartColumn<0 || this.IsNaturalNumber(RowNum)==false || this.IsNaturalNumber(StartColumn)==false || this.IsNaturalNumber(EndColumn)==false){
		console.error("The range of values requested is invalid");
	}

	var ReturnVec=this.GetValues(RowNum, RowNum, StartColumn, EndColumn);
	return ReturnVec[0];
}

CSVFile.prototype.Entries= function (y1, y2, x1, x2){
	//checking input is good
	if (x1>x2 || y1>y2 || x1<0 || y1<0 || this.IsNaturalNumber(x1)==false || this.IsNaturalNumber(x2)==false || this.IsNaturalNumber(y1)==false || this.IsNaturalNumber(y2)==false ){
		console.error("The range of values requested is invalid");
	}

};

CSVFile.prototype.IsNaturalNumber = function (value){
	if (Math.floor(value) == value){
		return true;
	}
	else{
		return false;
	}

	//var NaturalNumberRegex = /^(0|([1-9]\d*))$/;
	//return NaturalNumberRegex.test(StringToTest);
};

function DownloadableCSV(InputData, FileName){
	this.Data=InputData;
	if (typeof(FileName) != 'undefined'){
		this.FileName=FileName;
	}
	// // Specifying fields and data manually
// var csv = Papa.unparse({
	// fields: ["Column 1", "Column 2"],
	// data: [
		// ["foo", "bar"],
		// ["abc", "def"]
	// ]
// });
// http://papaparse.com/docs#json-to-csv

};

DownloadableCSV.prototype.Download=function(){
	var csv = Papa.unparse(this.Data);
	var blob = new Blob([csv], {type: "text/plain;charset=utf-8"});
	if (typeof(this.FileName) == 'undefined'){
		saveAs(blob, "data.csv");
	}
	else{
		saveAs(blob, this.FileName);
	}
};
<commit_msg>Attempt to fix CSV tools<commit_after>// This file requires papaparse.js to work
// The purpose of this file is to make it straight forward to open and extract information from CSV files. It is a wrapper for papaparse

function CSVFile(FileName){//file name in this instance is the URL
	var TempOpenCSVHolder=this;//A pointer to this file that can be called when the file is finished and ready to store
	this.CurrentlyLoading=true;

	Papa.parse(FileName, {download: true, complete: function(PapaResults){TempOpenCSVHolder.Data=PapaResults.data;TempOpenCSVHolder.CurrentlyLoading=false;} });
	//download informs Papa that it is an external CSV (http request), and the function is a handler to run when the file is ready

};

CSVFile.prototype.GetValues= function (y1, y2, x1, x2){//Changing to (row1, row2, column1, column2), as is expected in a CSV file
	//checking input is good
	if (x1>x2 || y1>y2 || x1<0 || y1<0 || this.IsNaturalNumber(x1)==false || this.IsNaturalNumber(x2)==false || this.IsNaturalNumber(y1)==false || this.IsNaturalNumber(y2)==false ){
		console.error("The range of values requested is invalid");
	}

	ReturnArray=[];
	newyindex=0;
	for (yindex=y1; yindex<=y2; yindex++){
		ReturnArray[newyindex]=[];
		newxindex=0;
		for (xindex=x1; xindex<=x2; xindex++){
			if (typeof this.Data[yindex][xindex]==="undefined"){// If this value is bigger than the largest value of data
				ReturnArray[newyindex][newxindex]=NaN;
			}
			else{
				ReturnArray[newyindex][newxindex]=Number(this.Data[yindex][xindex]);
			}
			newxindex++;
		}
		newyindex++;
	}
	return ReturnArray;
};

CSVFile.prototype.GetColumn= function (ColumnNum, StartRow, EndRow){//
	if (StartRow>EndRow || ColumnNum<0 || StartRow<0 || this.IsNaturalNumber(ColumnNum)==false || this.IsNaturalNumber(StartRow)==false || this.IsNaturalNumber(EndRow)==false){
		console.error("The range of values requested is invalid");
	}

	var TempVec=this.GetValues(StartRow, EndRow, ColumnNum, ColumnNum);

	//Refactor the vector into a proper vector
	var ReturnVec=[];
	for (var i=0; i<TempVec.length; i++ ){
		ReturnVec[i]=TempVec[i][0];
	}
	return ReturnVec;
}

CSVFile.prototype.GetRow= function (RowNum, StartColumn, EndColumn){//
	if (StartColumn>EndColumn || RowNum<0 || StartColumn<0 || this.IsNaturalNumber(RowNum)==false || this.IsNaturalNumber(StartColumn)==false || this.IsNaturalNumber(EndColumn)==false){
		console.error("The range of values requested is invalid");
	}

	var ReturnVec=this.GetValues(RowNum, RowNum, StartColumn, EndColumn);
	return ReturnVec[0];
}

CSVFile.prototype.Entries= function (y1, y2, x1, x2){
	//checking input is good
	if (x1>x2 || y1>y2 || x1<0 || y1<0 || this.IsNaturalNumber(x1)==false || this.IsNaturalNumber(x2)==false || this.IsNaturalNumber(y1)==false || this.IsNaturalNumber(y2)==false ){
		console.error("The range of values requested is invalid");
	}

};

CSVFile.prototype.IsNaturalNumber = function (value){
	if (Math.floor(value) == value){
		return true;
	}
	else{
		return false;
	}

	//var NaturalNumberRegex = /^(0|([1-9]\d*))$/;
	//return NaturalNumberRegex.test(StringToTest);
};

function DownloadableCSV(InputData, FileName){
	if (typeof(FileName) != 'undefined'){
		this.FileName=FileName;
	}

	this.UnparseInput={};
	this.UnparseInput.fields=[];
	this.UnparseInput.data=[];
	for (A in InputData){
		this.UnparseInput.fields.push(A);
		this.UnparseInput.data.push(InputData(A));
	}

	// // Specifying fields and data manually
// var csv = Papa.unparse({
	// fields: ["Column 1", "Column 2"],
	// data: [
		// ["foo", "bar"],
		// ["abc", "def"]
	// ]
// });
// http://papaparse.com/docs#json-to-csv

};

DownloadableCSV.prototype.Download=function(){
	var csv = Papa.unparse(this.UnparseInput);
	var blob = new Blob([csv], {type: "text/plain;charset=utf-8"});
	if (typeof(this.FileName) == 'undefined'){
		saveAs(blob, "data.csv");
	}
	else{
		saveAs(blob, this.FileName);
	}
};
<|endoftext|>


<commit_before>'use strict';

var drawChart = function(d3, svg, scope, iElement, iAttrs) {
    svg.selectAll("*").remove();

    var height = scope.height,
        width = scope.width || d3.select(iElement[0])[0][0].offsetWidth - 20,
        translator = makeTranslator(scope.dictionary);

    var dataset = [];
    var keys = _.keys(scope.data);
    for(var i = 0; i < keys.length; i++) {
        var k = keys[i];
        dataset.push( { key: k, value: scope.data[k] } );
    }

    svg.attr("width", width)
        .attr("height", height);

    var margin = { top: 30, bottom: 70, left: 30, right: 30};

    var barPadding = 5,
        yBottom = height - margin.bottom,
        yTop = margin.top,
        xLeft = margin.left,
        xRight = width - margin.right;
        // barWidth = ((xRight - xLeft) / dataset.length) - (barPadding * 2);

    // some numbers can be negative (e.g. leech). We'll take the absolute value
    // of all numbers for building the graphs, and use color styling to mark
    // these as negative

    var yScale = d3.scale.linear()
        .domain([0, d3.max(dataset, function(d) { return Math.abs(d.value); })])
        .range([yBottom, yTop]);

    var xScale = d3.scale.ordinal()
        .domain(dataset.map(function(d) { return translator(d.key); }))
        .rangeRoundBands([xLeft, xRight], .1);

    var bar = svg.selectAll("g")
        .data(dataset)
        .enter()
        .append("g")
        .attr("transform", function(d, i) {
            return "translate(" + xScale(translator(d.key)) + ",0)";
        });

    bar.append("rect")
        .attr("y", function(d) { return yScale(Math.abs(d.value)); })
        .attr("height", function(d) { return yBottom - yScale(Math.abs(d.value)); })
        // .attr("width", function(d) { return barWidth; })
        .attr("width", function(d) { return xScale.rangeBand(); })
        .attr("class", function(d) {
            if(d.value >= 0) {
                return "bar";
            }
            else {
                return "bar negative-bar"
            }
        });

    bar.append("text")
        .text(function(d) { return d.value; })
        .attr("y", function(d) { return yScale(Math.abs(d.value)) - 5; })
        // .attr("x", barWidth / 2)
        .attr("x", xScale.rangeBand() / 2)
        .attr("class", "bar-label");

    var xAxis = d3.svg.axis()
        .scale(xScale)
        .orient("bottom");

    svg.append("g")
        .attr("class", "axis")
        .attr("transform", "translate(0," + yBottom + ")")
        .call(xAxis)
        .selectAll("text")
        .style("text-anchor", "end")
        .attr("dx", "-.8em")
        .attr("dy", ".15em")
        .attr("transform", function(d) {
            return "rotate(-30)"
        });
}

// return a function that converts strings into a prettier form.
// if the string exists in the passed in diciontary, return that value;
// otherwise return the original string.
var makeTranslator = function(dictionary) {
    if(dictionary == undefined || dictionary == null) {
        return function(s) { return s; };
    }

    return function(s) {
        var t = dictionary[s];
        if(t != null) {
            return t;
        }
        else {
            return s;
        }
    }
}

angular.module('d3').directive('d3Scoregraph', ['d3', function(d3) {
    return {
        restrict: 'EA',
        scope: {
            data: '=', // binding to an angular object
            width: '@',    // static binding to a value
            height: '@',
            dictionary: '=',
        },
        link: function(scope, iElement, iAttrs) {
            var svg = d3.select(iElement[0])
                .append("svg");

            // use auto scaling for width
            if(scope.width == undefined) {
                svg.style("width", "100%");
            }

            // on window resize, re-render d3 canvas
            window.onresize = function() {
                return scope.$apply();
            };
            scope.$watch(function() {
                return angular.element(window)[0].innerWidth;
            }, function() {
                return scope.render();
            });

            // watch for data changes and re-render
            scope.$watch('data', function(newVals, oldVals) {
                return scope.render(newVals);
            }, true);

            // define render function
            scope.render = function() {
                drawChart(d3, svg, scope, iElement, iAttrs);
            };
        }
    };
}]);<commit_msg>cleanup of old commented code<commit_after>'use strict';

var drawChart = function(d3, svg, scope, iElement, iAttrs) {
    svg.selectAll("*").remove();

    var height = scope.height,
        width = scope.width || d3.select(iElement[0])[0][0].offsetWidth - 20,
        translator = makeTranslator(scope.dictionary);

    var dataset = [];
    var keys = _.keys(scope.data);
    for(var i = 0; i < keys.length; i++) {
        var k = keys[i];
        dataset.push( { key: k, value: scope.data[k] } );
    }

    svg.attr("width", width)
        .attr("height", height);

    var margin = { top: 30, bottom: 70, left: 30, right: 30};

    var barPadding = 5,
        yBottom = height - margin.bottom,
        yTop = margin.top,
        xLeft = margin.left,
        xRight = width - margin.right;

    // some numbers can be negative (e.g. leech). We'll take the absolute value
    // of all numbers for building the graphs, and use color styling to mark
    // these as negative

    var yScale = d3.scale.linear()
        .domain([0, d3.max(dataset, function(d) { return Math.abs(d.value); })])
        .range([yBottom, yTop]);

    var xScale = d3.scale.ordinal()
        .domain(dataset.map(function(d) { return translator(d.key); }))
        .rangeRoundBands([xLeft, xRight], .1);

    var bar = svg.selectAll("g")
        .data(dataset)
        .enter()
        .append("g")
        .attr("transform", function(d, i) {
            return "translate(" + xScale(translator(d.key)) + ",0)";
        });

    bar.append("rect")
        .attr("y", function(d) { return yScale(Math.abs(d.value)); })
        .attr("height", function(d) { return yBottom - yScale(Math.abs(d.value)); })
        .attr("width", function(d) { return xScale.rangeBand(); })
        .attr("class", function(d) {
            if(d.value >= 0) {
                return "bar";
            }
            else {
                return "bar negative-bar"
            }
        });

    bar.append("text")
        .text(function(d) { return d.value; })
        .attr("y", function(d) { return yScale(Math.abs(d.value)) - 5; })
        .attr("x", xScale.rangeBand() / 2)
        .attr("class", "bar-label");

    var xAxis = d3.svg.axis()
        .scale(xScale)
        .orient("bottom");

    svg.append("g")
        .attr("class", "axis")
        .attr("transform", "translate(0," + yBottom + ")")
        .call(xAxis)
        .selectAll("text")
        .style("text-anchor", "end")
        .attr("dx", "-.8em")
        .attr("dy", ".15em")
        .attr("transform", function(d) {
            return "rotate(-30)"
        });
}

// return a function that converts strings into a prettier form.
// if the string exists in the passed in diciontary, return that value;
// otherwise return the original string.
var makeTranslator = function(dictionary) {
    if(dictionary == undefined || dictionary == null) {
        return function(s) { return s; };
    }

    return function(s) {
        var t = dictionary[s];
        if(t != null) {
            return t;
        }
        else {
            return s;
        }
    }
}

angular.module('d3').directive('d3Scoregraph', ['d3', function(d3) {
    return {
        restrict: 'EA',
        scope: {
            data: '=', // binding to an angular object
            width: '@',    // static binding to a value
            height: '@',
            dictionary: '=',
        },
        link: function(scope, iElement, iAttrs) {
            var svg = d3.select(iElement[0])
                .append("svg");

            // use auto scaling for width
            if(scope.width == undefined) {
                svg.style("width", "100%");
            }

            // on window resize, re-render d3 canvas
            window.onresize = function() {
                return scope.$apply();
            };
            scope.$watch(function() {
                return angular.element(window)[0].innerWidth;
            }, function() {
                return scope.render();
            });

            // watch for data changes and re-render
            scope.$watch('data', function(newVals, oldVals) {
                return scope.render(newVals);
            }, true);

            // define render function
            scope.render = function() {
                drawChart(d3, svg, scope, iElement, iAttrs);
            };
        }
    };
}]);<|endoftext|>


<commit_before>define(function(require) {
    var system = require('durandal/system'),
        viewEngine = require('durandal/viewEngine'),
        composition = require('durandal/composition'),
        dom = require('durandal/dom');

    var widgetPartAttribute = 'data-widget-part',
        widgetPartSelector = "[" + widgetPartAttribute + "]";

    var kindModuleMaps = { },
        kindViewMaps = { };

    function isPart(node) {
        return node.nodeName == 'PART' || node.nodeName == 'part';
    }

    function findAllParts(element, parts) {
        if (isPart(element)) {
            parts.push({
                id: element.getAttribute('id'),
                node: element
            });
            return;
        }

        if (element.hasChildNodes()) {
            var child = element.firstChild;
            while (child) {
                if (isPart(child)) {
                    parts.push({
                        id: child.getAttribute('id'),
                        node: child
                    });
                } else if (child.nodeType === 1) {
                    findAllParts(child, parts);
                }

                child = child.nextSibling;
            }
        }
    }

    function findReplacementParts(element) {
        var children = element.childNodes;
        var parts = {};

        for (var i = 0; i < children.length; i++) {
            var node = children[i];

            if (isPart(node)) {
                parts[node.getAttribute('id')] = node.innerHTML;
            }
        }

        return parts;
    }

    function finalizeWidgetView(view, replacementParts) {
        var parts = [];

        findAllParts(view, parts);

        for (var i = 0; i < parts.length; i++) {
            var current = parts[i];
            var html = replacementParts[current.id] || current.node.innerHTML;

            var partView = dom.parseHTML(html);
            partView.setAttribute(widgetPartAttribute, current.id);
            current.node.parentNode.replaceChild(partView, current.node);

            finalizeWidgetView(partView, replacementParts);
        }
    }

    var widget = {
        getParts: function(elements) {
            var parts = {};

            if (!system.isArray(elements)) {
                elements = [elements];
            }

            for (var i = 0; i < elements.length; i++) {
                var element = elements[i];

                if (element.getAttribute) {
                    var id = element.getAttribute(widgetPartAttribute);
                    if (id) {
                        parts[id] = element;
                    }

                    var childParts = $(widgetPartSelector, element);

                    for (var j = 0; j < childParts.length; j++) {
                        var part = childParts.get(j);
                        parts[part.getAttribute(widgetPartAttribute)] = part;
                    }
                }
            }

            return parts;
        },
        getSettings: function(valueAccessor) {
            var settings = {},
                value = ko.utils.unwrapObservable(valueAccessor()) || {};

            if (typeof value == 'string') {
                settings = value;
            } else {
                for (var attrName in value) {
                    if (typeof attrName == 'string') {
                        var attrValue = ko.utils.unwrapObservable(value[attrName]);
                        settings[attrName] = attrValue;
                    }
                }
            }

            return settings;
        },
        registerKind: function(kind) {
            ko.bindingHandlers[kind] = {
                init: function() {
                    return { controlsDescendantBindings: true };
                },
                update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
                    var settings = widget.getSettings(valueAccessor);
                    settings.kind = kind;
                    widget.create(element, settings, bindingContext);
                }
            };

            ko.virtualElements.allowedBindings[kind] = true;
        },
        convertKindToModuleId: function(kind) {
            return kindModuleMaps[kind] || "widgets/" + kind + "/widget";
        },
        convertKindToView: function(kind) {
            return kindViewMaps[kind] || "widgets/" + kind + "/widget" + viewEngine.viewExtension;
        },
        beforeBind: function(element, view, settings) {
            finalizeWidgetView(view, findReplacementParts(element));
        },
        createCompositionSettings: function(settings) {
            if (!settings.model) {
                settings.model = this.convertKindToModuleId(settings.kind);
            }

            if (!settings.view) {
                settings.view = this.convertKindToView(settings.kind);
            }

            settings.preserveContext = true;
            settings.beforeBind = this.beforeBind;

            return settings;
        },
        create: function(element, settings, bindingContext) {
            if (typeof settings == 'string') {
                settings = {
                    kind: settings
                };
            }

            var compositionSettings = widget.createCompositionSettings(settings);
            composition.compose(element, compositionSettings, bindingContext);
        }
    };

    ko.bindingHandlers.widget = {
        init: function() {
            return { controlsDescendantBindings: true };
        },
        update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            var settings = widget.getSettings(valueAccessor);
            widget.create(element, settings, bindingContext);
        }
    };

    ko.virtualElements.allowedBindings.widget = true;

    return widget;
});<commit_msg>Removed an unnecessary dependency from widgets<commit_after>define(function(require) {
    var system = require('durandal/system'),
        composition = require('durandal/composition'),
        dom = require('durandal/dom');

    var widgetPartAttribute = 'data-widget-part',
        widgetPartSelector = "[" + widgetPartAttribute + "]";

    var kindModuleMaps = { },
        kindViewMaps = { };

    function isPart(node) {
        return node.nodeName == 'PART' || node.nodeName == 'part';
    }

    function findAllParts(element, parts) {
        if (isPart(element)) {
            parts.push({
                id: element.getAttribute('id'),
                node: element
            });
            return;
        }

        if (element.hasChildNodes()) {
            var child = element.firstChild;
            while (child) {
                if (isPart(child)) {
                    parts.push({
                        id: child.getAttribute('id'),
                        node: child
                    });
                } else if (child.nodeType === 1) {
                    findAllParts(child, parts);
                }

                child = child.nextSibling;
            }
        }
    }

    function findReplacementParts(element) {
        var children = element.childNodes;
        var parts = {};

        for (var i = 0; i < children.length; i++) {
            var node = children[i];

            if (isPart(node)) {
                parts[node.getAttribute('id')] = node.innerHTML;
            }
        }

        return parts;
    }

    function finalizeWidgetView(view, replacementParts) {
        var parts = [];

        findAllParts(view, parts);

        for (var i = 0; i < parts.length; i++) {
            var current = parts[i];
            var html = replacementParts[current.id] || current.node.innerHTML;

            var partView = dom.parseHTML(html);
            partView.setAttribute(widgetPartAttribute, current.id);
            current.node.parentNode.replaceChild(partView, current.node);

            finalizeWidgetView(partView, replacementParts);
        }
    }

    var widget = {
        getParts: function(elements) {
            var parts = {};

            if (!system.isArray(elements)) {
                elements = [elements];
            }

            for (var i = 0; i < elements.length; i++) {
                var element = elements[i];

                if (element.getAttribute) {
                    var id = element.getAttribute(widgetPartAttribute);
                    if (id) {
                        parts[id] = element;
                    }

                    var childParts = $(widgetPartSelector, element);

                    for (var j = 0; j < childParts.length; j++) {
                        var part = childParts.get(j);
                        parts[part.getAttribute(widgetPartAttribute)] = part;
                    }
                }
            }

            return parts;
        },
        getSettings: function(valueAccessor) {
            var settings = {},
                value = ko.utils.unwrapObservable(valueAccessor()) || {};

            if (typeof value == 'string') {
                settings = value;
            } else {
                for (var attrName in value) {
                    if (typeof attrName == 'string') {
                        var attrValue = ko.utils.unwrapObservable(value[attrName]);
                        settings[attrName] = attrValue;
                    }
                }
            }

            return settings;
        },
        registerKind: function(kind) {
            ko.bindingHandlers[kind] = {
                init: function() {
                    return { controlsDescendantBindings: true };
                },
                update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
                    var settings = widget.getSettings(valueAccessor);
                    settings.kind = kind;
                    widget.create(element, settings, bindingContext);
                }
            };

            ko.virtualElements.allowedBindings[kind] = true;
        },
        convertKindToModuleId: function(kind) {
            return kindModuleMaps[kind] || "widgets/" + kind + "/widget";
        },
        convertKindToView: function(kind) {
            return kindViewMaps[kind] || "widgets/" + kind + "/widget";
        },
        beforeBind: function(element, view, settings) {
            finalizeWidgetView(view, findReplacementParts(element));
        },
        createCompositionSettings: function(settings) {
            if (!settings.model) {
                settings.model = this.convertKindToModuleId(settings.kind);
            }

            if (!settings.view) {
                settings.view = this.convertKindToView(settings.kind);
            }

            settings.preserveContext = true;
            settings.beforeBind = this.beforeBind;

            return settings;
        },
        create: function(element, settings, bindingContext) {
            if (typeof settings == 'string') {
                settings = {
                    kind: settings
                };
            }

            var compositionSettings = widget.createCompositionSettings(settings);
            composition.compose(element, compositionSettings, bindingContext);
        }
    };

    ko.bindingHandlers.widget = {
        init: function() {
            return { controlsDescendantBindings: true };
        },
        update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            var settings = widget.getSettings(valueAccessor);
            widget.create(element, settings, bindingContext);
        }
    };

    ko.virtualElements.allowedBindings.widget = true;

    return widget;
});<|endoftext|>


<commit_before>'use strict';

import * as _ from 'lodash'
import hasDepartment from './hasDepartment'

function splitDeptNum(deptNumString) {
	// "AS/RE 230A" -> ["AS/RE 230A", "AS/RE", "AS", "RE", "230", "A"]
	// -> {depts: ['AS', 'RE'], num: 230}
	var combined = deptNumString.toUpperCase()
	var regex = /(([A-Z]+)(?=\/)(?:\/)([A-Z]+)|[A-Z]+) *([0-9]+) *([A-Z]?)/gi
	var matches = regex.exec(combined)

	return {
		depts: _.contains(matches[1], '/') ? [matches[2], matches[3]] : [matches[1]],
		num: parseInt(matches[4], 10)
	}
}

function buildDeptNum(course) {
	return course.depts.join('/') + ' ' + course.num
}

function hasDeptNumBetween(args, course) {
	var dept = args.dept
	var start = args.start
	var end = args.end

	if (_.any([dept, start, end], _.isUndefined)) {
		return false
	}

	return _.all([
		hasDepartment(dept, course),
		course.num >= start,
		course.num <= end
	])
}

export {
	splitDeptNum,
	buildDeptNum,
	hasDeptNumBetween
}
<commit_msg>hasDeptNumBetween needs to be curried; also add buildDept<commit_after>'use strict';

import * as _ from 'lodash'
import hasDepartment from './hasDepartment'

function splitDeptNum(deptNumString) {
	// "AS/RE 230A" -> ["AS/RE 230A", "AS/RE", "AS", "RE", "230", "A"]
	// -> {depts: ['AS', 'RE'], num: 230}
	var combined = deptNumString.toUpperCase()
	var regex = /(([A-Z]+)(?=\/)(?:\/)([A-Z]+)|[A-Z]+) *([0-9]+) *([A-Z]?)/gi
	var matches = regex.exec(combined)

	return {
		depts: _.contains(matches[1], '/') ? [matches[2], matches[3]] : [matches[1]],
		num: parseInt(matches[4], 10)
	}
}

function buildDept(course) {
	return course.depts.join('/')
}

function buildDeptNum(course) {
	return course.depts.join('/') + ' ' + course.num
}

let hasDeptNumBetween = _.curry(function(args, course) {
	var dept = args.dept
	var start = args.start
	var end = args.end

	if (_.any([dept, start, end], _.isUndefined)) {
		return false
	}

	return _.all([
		hasDepartment(dept, course),
		course.num >= start,
		course.num <= end
	])
})

export {
	splitDeptNum,
	buildDeptNum,
	hasDeptNumBetween
}
<|endoftext|>


<commit_before>var db = require('../database');
var messenger = require('../messenger');
var _ = require('lodash');

function User(doc) {

  // Call the new constructor in case your forgot it.
  if (!(this instanceof User)) {
    return new User(doc);
  }

  // Assume that if you just get a string, that it's a phone number.
  // TODO: Validate this with some regex or something.
  if (typeof doc === 'string') doc = { _id: doc };

  // Extend the User model with whatever is being stored in CouchDB.
  _.extend(this, doc);

  // Override the document type with 'user' no matter what.
  this.type = 'user';

}

User.create = function (doc) {
  if (typeof doc === 'string') doc = { _id: doc };
  return new User(doc);
};

User.find = function (phoneNumber, callback) {
  db.get(phoneNumber, function (err, doc) {
    if (err) { callback(err); return; }
    if (doc.type && doc.type === 'user') {
      callback(null, User.create(doc));
    } else {
      var error = { error: 'invalid_type', reason: 'type is not "user"' };
      callback(error, null);
    }
  });
};

User.findOrCreate = function (phoneNumber, callback) {
  User.find(phoneNumber, function (err, doc) {
    if (!err && doc) { callback(null, doc); return; }
    if (err.error === 'not_found' && err.reason === 'missing') {
      var user = User.create(phoneNumber);
      user.save(function () { callback(null, user); });
    } else {
      callback(err);
    }
  });
};

User.prototype.save = function (callback) {
  db.save(this, callback);
};

User.prototype.destroy = function (callback) {
  db.remove(this._id, callback);
};

User.prototype.message = function (message, callback) {
  console.log('Sending:', message);
  messenger.send(this._id, message);
  if (typeof callback === 'function') callback();
};

User.prototype.setStatus = function (status, callback) {
  this.status = status;
  this.save(callback);
};

module.exports = User;<commit_msg>Add some more logging to figure out what's going on<commit_after>var db = require('../database');
var messenger = require('../messenger');
var _ = require('lodash');

function User(doc) {

  // Call the new constructor in case your forgot it.
  if (!(this instanceof User)) {
    return new User(doc);
  }

  // Assume that if you just get a string, that it's a phone number.
  // TODO: Validate this with some regex or something.
  if (typeof doc === 'string') doc = { _id: doc };

  // Extend the User model with whatever is being stored in CouchDB.
  _.extend(this, doc);

  // Override the document type with 'user' no matter what.
  this.type = 'user';

}

User.create = function (doc) {
  if (typeof doc === 'string') doc = { _id: doc };
  return new User(doc);
};

User.find = function (phoneNumber, callback) {
  db.get(phoneNumber, function (err, doc) {
    if (err) { callback(err); return; }
    if (doc.type && doc.type === 'user') {
      callback(null, User.create(doc));
    } else {
      var error = { error: 'invalid_type', reason: 'type is not "user"' };
      callback(error, null);
    }
  });
};

User.findOrCreate = function (phoneNumber, callback) {
  User.find(phoneNumber, function (err, doc) {
    if (!err && doc) { callback(null, doc); return; }
    if (err.error === 'not_found' && err.reason === 'missing') {
      var user = User.create(phoneNumber);
      user.save(function () { callback(null, user); });
    } else {
      callback(err);
    }
  });
};

User.prototype.save = function (callback) {
  db.save(this, callback);
};

User.prototype.destroy = function (callback) {
  db.remove(this._id, callback);
};

User.prototype.message = function (message, callback) {
  console.log('Sending:', message);
  messenger.send(this._id, message);
  if (typeof callback === 'function') callback();
};

User.prototype.setStatus = function (status, callback) {
  console.log('Setting status of ' + this._id + ' to ' + status + '.');
  this.status = status;
  this.save(callback);
};

module.exports = User;<|endoftext|>