<commit_before>import _filter from 'lodash-es/filter';

import { dispatch as d3_dispatch } from 'd3-dispatch';
import { select as d3_select } from 'd3-selection';

import { t } from '../util/locale';
import { data } from '../../data';
import { svgIcon } from '../svg';
import { uiDisclosure } from '../ui';
import { utilDetect } from '../util/detect';
import { utilRebind } from '../util/rebind';

export function uiSuccess(context) {
    var detected = utilDetect();
    var dispatch = d3_dispatch('cancel');
    var MAXEVENTS = 2;
    var _changeset;
    var _location;

    function success(selection) {
        var header = selection
            .append('div')
            .attr('class', 'header fillL');

        header
            .append('button')
            .attr('class', 'fr')
            .on('click', function() { dispatch.call('cancel'); })
            .call(svgIcon('#icon-close'));

        header
            .append('h3')
            .text(t('success.just_edited'));

        var body = selection
            .append('div')
            .attr('class', 'body save-success fillL');

        var summary = body
            .append('div')
            .attr('class', 'save-summary');

        summary
            .append('h3')
            .text(t('success.thank_you' + (_location ? '_location' : ''), { where: _location }));

        summary
            .append('p')
            .text(t('success.help_html'))
            .append('a')
            .attr('class', 'link-out')
            .attr('target', '_blank')
            .attr('tabindex', -1)
            .attr('href', t('success.help_link_url'))
            .call(svgIcon('#icon-out-link', 'inline'))
            .append('span')
            .text(t('success.help_link_text'));

        var osm = context.connection();
        if (!osm) return;

        var changesetURL = osm.changesetURL(_changeset.id);

        var table = summary
            .append('table')
            .attr('class', 'summary-table');

        var row = table
            .append('tr')
            .attr('class', 'summary-row');

        row
            .append('td')
            .attr('class', 'cell-icon summary-icon')
            .append('a')
            .attr('target', '_blank')
            .attr('href', changesetURL)
            .append('svg')
            .attr('class', 'logo-small')
            .append('use')
            .attr('xlink:href', '#logo-osm');

        var summaryDetail = row
            .append('td')
            .attr('class', 'cell-detail summary-detail');

        summaryDetail
            .append('a')
            .attr('class', 'cell-detail summary-view-on-osm')
            .attr('target', '_blank')
            .attr('href', changesetURL)
            .text(t('success.view_on_osm'));

        summaryDetail
            .append('div')
            .text(t('success.changeset_id', { changeset_id: _changeset.id }));

        // Gather community polygon IDs intersecting the map..
        var matchFeatures = data.community.query(context.map().center(), true);
        var matchIDs = matchFeatures.map(function(feature) { return feature.id; });

        // Gather community resources that are either global or match a polygon.
        var matchResources = _filter(data.community.resources, function(v) {
            return !v.featureId || matchIDs.indexOf(v.featureId) !== -1;
        });

        if (matchResources.length) {
            // sort by size ascending
            matchResources.sort(function(a, b) {
                var aSize = Infinity;
                var bSize = Infinity;
                if (a.featureId) {
                    aSize = data.community.features[a.featureId].properties.area;
                }
                if (b.featureId) {
                    bSize = data.community.features[b.featureId].properties.area;
                }
                return aSize < bSize ? -1 : aSize > bSize ? 1 : 0;
            });

            body
                .call(showCommunityLinks, matchResources);
        }
    }

    function showCommunityLinks(selection, matchResources) {
        var communityLinks = selection
            .append('div')
            .attr('class', 'save-communityLinks');

        communityLinks
            .append('h3')
            .text(t('success.like_osm'));

        var table = communityLinks
            .append('table')
            .attr('class', 'community-table');

        var row = table.selectAll('.community-row')
            .data(matchResources);

        var rowEnter = row.enter()
            .append('tr')
            .attr('class', 'community-row');

        rowEnter
            .append('td')
            .attr('class', 'cell-icon community-icon')
            .append('a')
            .attr('target', '_blank')
            .attr('href', function(d) { return d.url; })
            .append('svg')
            .attr('class', 'logo-small')
            .append('use')
            .attr('xlink:href', function(d) { return '#community-' + d.type; });

        var communityDetail = rowEnter
            .append('td')
            .attr('class', 'cell-detail community-detail');

        communityDetail
            .each(showCommunityDetails);

        communityLinks
            .append('div')
            .attr('class', 'community-missing')
            .text(t('success.missing'))
            .append('a')
            .attr('class', 'link-out')
            .attr('target', '_blank')
            .attr('tabindex', -1)
            .call(svgIcon('#icon-out-link', 'inline'))
            .attr('href', 'https://github.com/osmlab/osm-community-index/issues')
            .append('span')
            .text(t('success.tell_us'));
    }

    function showCommunityDetails(d) {
        var selection = d3_select(this);
        var communityID = d.id;
        var replacements = {
            url: linkify(d.url),
            signupUrl: linkify(d.signupUrl || d.url)
        };

        selection
            .append('div')
            .attr('class', 'community-name')
            .append('a')
            .attr('target', '_blank')
            .attr('href', d.url)
            .text(t('community.' + d.id + '.name'));

        selection
            .append('div')
            .attr('class', 'community-description')
            .html(t('community.' + d.id + '.description', replacements));

        if (d.extendedDescription || (d.languageCodes && d.languageCodes.length)) {
            selection
                .append('div')
                .call(uiDisclosure(context, 'community-more-' + d.id, false)
                    .expanded(false)
                    .updatePreference(false)
                    .title(t('success.more'))
                    .content(showMore)
                );
        }

        var nextEvents = (d.events || [])
            .map(function(event) {                  // add parsed date
                event.date = new Date(event.when);
                return event;
            })
            .filter(function(event) {               // date is valid and future (or today)
                var t = event.date.getTime();
                var now = (new Date()).setHours(0,0,0,0);
                return !isNaN(t) && t >= now;
            })
            .sort(function(a, b) {                  // sort by date ascending
                return a.date  b.date ? 1 : 0;
            })
            .slice(0, MAXEVENTS);                   // limit number of events shown

        if (nextEvents.length) {
            selection
                .append('div')
                .call(uiDisclosure(context, 'community-events-' + d.id, false)
                    .expanded(false)
                    .updatePreference(false)
                    .title(t('success.events'))
                    .content(showNextEvents)
                )
                .select('.hide-toggle')
                .append('span')
                .attr('class', 'badge-text')
                .text(nextEvents.length);
        }

        function showMore(selection) {
            var more = selection
                .append('div')
                .attr('class', 'community-more');

            if (d.extendedDescription) {
                more
                    .append('div')
                    .attr('class', 'community-extended-description')
                    .html(t('community.' + d.id + '.extendedDescription', replacements));
            }

            if (d.languageCodes && d.languageCodes.length) {
                more
                    .append('div')
                    .attr('class', 'community-languages')
                    .text(t('success.languages', { languages: d.languageCodes.join(', ') }));
            }
        }

        function showNextEvents(selection) {
            var events = selection
                .append('div')
                .attr('class', 'community-events');

            var item = events.selectAll('.community-event')
                .data(nextEvents);

            var itemEnter = item.enter()
                .append('div')
                .attr('class', 'community-event');

            itemEnter
                .append('div')
                .attr('class', 'community-event-name')
                .append('a')
                .attr('target', '_blank')
                .attr('href', function(d) { return d.url; })
                .text(function(d) {
                    var name = d.name;
                    if (d.i18n && d.id) {
                        name = t('community.' + communityID + '.events.' + d.id + '.name', { default: name });
                    }
                    return name;
                });

            itemEnter
                .append('div')
                .attr('class', 'community-event-when')
                .text(function(d) {
                    var options = {
                        weekday: 'short', day: 'numeric', month: 'short', year: 'numeric'
                    };
                    if (d.date.getHours() || d.date.getMinutes()) {   // include time if it has one
                        options.hour = 'numeric';
                        options.minute = 'numeric';
                    }
                    return d.date.toLocaleString(detected.locale, options);
                });

            itemEnter
                .append('div')
                .attr('class', 'community-event-where')
                .text(function(d) {
                    var where = d.where;
                    if (d.i18n && d.id) {
                        where = t('community.' + communityID + '.events.' + d.id + '.where', { default: where });
                    }
                    return where;
                });

            itemEnter
                .append('div')
                .attr('class', 'community-event-description')
                .text(function(d) {
                    var description = d.description;
                    if (d.i18n && d.id) {
                        description = t('community.' + communityID + '.events.' + d.id + '.description', { default: description });
                    }
                    return description;
                });
        }

        function linkify(url) {
            return '' + url + '';
        }
    }

    success.changeset = function(_) {
        if (!arguments.length) return _changeset;
        _changeset = _;
        return success;
    };

    success.location = function(_) {
        if (!arguments.length) return _location;
        _location = _;
        return success;
    };

    return utilRebind(success, dispatch, 'on');
}
<commit_msg>Adjust sort weight by community type<commit_after>import _filter from 'lodash-es/filter';

import { dispatch as d3_dispatch } from 'd3-dispatch';
import { select as d3_select } from 'd3-selection';

import { t } from '../util/locale';
import { data } from '../../data';
import { svgIcon } from '../svg';
import { uiDisclosure } from '../ui';
import { utilDetect } from '../util/detect';
import { utilRebind } from '../util/rebind';

export function uiSuccess(context) {
    var MAXEVENTS = 2;

    // All else being equal, rank more "social" communities higher
    // (anything not in this list receives no adjustment)
    var COMMUNITYRANK = {
        'meetup': +5,
        'slack': +4,
        'facebook': +3,
        'reddit': +2,
        'forum': -2,
        'mailinglist': -3,
        'irc': -4
    };

    var detected = utilDetect();
    var dispatch = d3_dispatch('cancel');
    var _changeset;
    var _location;

    function success(selection) {
        var header = selection
            .append('div')
            .attr('class', 'header fillL');

        header
            .append('button')
            .attr('class', 'fr')
            .on('click', function() { dispatch.call('cancel'); })
            .call(svgIcon('#icon-close'));

        header
            .append('h3')
            .text(t('success.just_edited'));

        var body = selection
            .append('div')
            .attr('class', 'body save-success fillL');

        var summary = body
            .append('div')
            .attr('class', 'save-summary');

        summary
            .append('h3')
            .text(t('success.thank_you' + (_location ? '_location' : ''), { where: _location }));

        summary
            .append('p')
            .text(t('success.help_html'))
            .append('a')
            .attr('class', 'link-out')
            .attr('target', '_blank')
            .attr('tabindex', -1)
            .attr('href', t('success.help_link_url'))
            .call(svgIcon('#icon-out-link', 'inline'))
            .append('span')
            .text(t('success.help_link_text'));

        var osm = context.connection();
        if (!osm) return;

        var changesetURL = osm.changesetURL(_changeset.id);

        var table = summary
            .append('table')
            .attr('class', 'summary-table');

        var row = table
            .append('tr')
            .attr('class', 'summary-row');

        row
            .append('td')
            .attr('class', 'cell-icon summary-icon')
            .append('a')
            .attr('target', '_blank')
            .attr('href', changesetURL)
            .append('svg')
            .attr('class', 'logo-small')
            .append('use')
            .attr('xlink:href', '#logo-osm');

        var summaryDetail = row
            .append('td')
            .attr('class', 'cell-detail summary-detail');

        summaryDetail
            .append('a')
            .attr('class', 'cell-detail summary-view-on-osm')
            .attr('target', '_blank')
            .attr('href', changesetURL)
            .text(t('success.view_on_osm'));

        summaryDetail
            .append('div')
            .text(t('success.changeset_id', { changeset_id: _changeset.id }));

        // Gather community polygon IDs intersecting the map..
        var matchFeatures = data.community.query(context.map().center(), true);
        var matchIDs = matchFeatures.map(function(feature) { return feature.id; });

        // Gather community resources that are either global or match a polygon.
        var matchResources = _filter(data.community.resources, function(v) {
            return !v.featureId || matchIDs.indexOf(v.featureId) !== -1;
        });

        if (matchResources.length) {
            // sort by size ascending, then by community rank
            matchResources.sort(function(a, b) {
                var aSize = Infinity;
                var bSize = Infinity;
                var aRank = COMMUNITYRANK[a.type] || 0;
                var bRank = COMMUNITYRANK[b.type] || 0;

                if (a.featureId) {
                    aSize = data.community.features[a.featureId].properties.area;
                }
                if (b.featureId) {
                    bSize = data.community.features[b.featureId].properties.area;
                }

                return aSize < bSize ? -1 : aSize > bSize ? 1 : bRank - aRank;
            });

            body
                .call(showCommunityLinks, matchResources);
        }
    }

    function showCommunityLinks(selection, matchResources) {
        var communityLinks = selection
            .append('div')
            .attr('class', 'save-communityLinks');

        communityLinks
            .append('h3')
            .text(t('success.like_osm'));

        var table = communityLinks
            .append('table')
            .attr('class', 'community-table');

        var row = table.selectAll('.community-row')
            .data(matchResources);

        var rowEnter = row.enter()
            .append('tr')
            .attr('class', 'community-row');

        rowEnter
            .append('td')
            .attr('class', 'cell-icon community-icon')
            .append('a')
            .attr('target', '_blank')
            .attr('href', function(d) { return d.url; })
            .append('svg')
            .attr('class', 'logo-small')
            .append('use')
            .attr('xlink:href', function(d) { return '#community-' + d.type; });

        var communityDetail = rowEnter
            .append('td')
            .attr('class', 'cell-detail community-detail');

        communityDetail
            .each(showCommunityDetails);

        communityLinks
            .append('div')
            .attr('class', 'community-missing')
            .text(t('success.missing'))
            .append('a')
            .attr('class', 'link-out')
            .attr('target', '_blank')
            .attr('tabindex', -1)
            .call(svgIcon('#icon-out-link', 'inline'))
            .attr('href', 'https://github.com/osmlab/osm-community-index/issues')
            .append('span')
            .text(t('success.tell_us'));
    }

    function showCommunityDetails(d) {
        var selection = d3_select(this);
        var communityID = d.id;
        var replacements = {
            url: linkify(d.url),
            signupUrl: linkify(d.signupUrl || d.url)
        };

        selection
            .append('div')
            .attr('class', 'community-name')
            .append('a')
            .attr('target', '_blank')
            .attr('href', d.url)
            .text(t('community.' + d.id + '.name'));

        selection
            .append('div')
            .attr('class', 'community-description')
            .html(t('community.' + d.id + '.description', replacements));

        if (d.extendedDescription || (d.languageCodes && d.languageCodes.length)) {
            selection
                .append('div')
                .call(uiDisclosure(context, 'community-more-' + d.id, false)
                    .expanded(false)
                    .updatePreference(false)
                    .title(t('success.more'))
                    .content(showMore)
                );
        }

        var nextEvents = (d.events || [])
            .map(function(event) {                  // add parsed date
                event.date = new Date(event.when);
                return event;
            })
            .filter(function(event) {               // date is valid and future (or today)
                var t = event.date.getTime();
                var now = (new Date()).setHours(0,0,0,0);
                return !isNaN(t) && t >= now;
            })
            .sort(function(a, b) {                  // sort by date ascending
                return a.date  b.date ? 1 : 0;
            })
            .slice(0, MAXEVENTS);                   // limit number of events shown

        if (nextEvents.length) {
            selection
                .append('div')
                .call(uiDisclosure(context, 'community-events-' + d.id, false)
                    .expanded(false)
                    .updatePreference(false)
                    .title(t('success.events'))
                    .content(showNextEvents)
                )
                .select('.hide-toggle')
                .append('span')
                .attr('class', 'badge-text')
                .text(nextEvents.length);
        }

        function showMore(selection) {
            var more = selection
                .append('div')
                .attr('class', 'community-more');

            if (d.extendedDescription) {
                more
                    .append('div')
                    .attr('class', 'community-extended-description')
                    .html(t('community.' + d.id + '.extendedDescription', replacements));
            }

            if (d.languageCodes && d.languageCodes.length) {
                more
                    .append('div')
                    .attr('class', 'community-languages')
                    .text(t('success.languages', { languages: d.languageCodes.join(', ') }));
            }
        }

        function showNextEvents(selection) {
            var events = selection
                .append('div')
                .attr('class', 'community-events');

            var item = events.selectAll('.community-event')
                .data(nextEvents);

            var itemEnter = item.enter()
                .append('div')
                .attr('class', 'community-event');

            itemEnter
                .append('div')
                .attr('class', 'community-event-name')
                .append('a')
                .attr('target', '_blank')
                .attr('href', function(d) { return d.url; })
                .text(function(d) {
                    var name = d.name;
                    if (d.i18n && d.id) {
                        name = t('community.' + communityID + '.events.' + d.id + '.name', { default: name });
                    }
                    return name;
                });

            itemEnter
                .append('div')
                .attr('class', 'community-event-when')
                .text(function(d) {
                    var options = {
                        weekday: 'short', day: 'numeric', month: 'short', year: 'numeric'
                    };
                    if (d.date.getHours() || d.date.getMinutes()) {   // include time if it has one
                        options.hour = 'numeric';
                        options.minute = 'numeric';
                    }
                    return d.date.toLocaleString(detected.locale, options);
                });

            itemEnter
                .append('div')
                .attr('class', 'community-event-where')
                .text(function(d) {
                    var where = d.where;
                    if (d.i18n && d.id) {
                        where = t('community.' + communityID + '.events.' + d.id + '.where', { default: where });
                    }
                    return where;
                });

            itemEnter
                .append('div')
                .attr('class', 'community-event-description')
                .text(function(d) {
                    var description = d.description;
                    if (d.i18n && d.id) {
                        description = t('community.' + communityID + '.events.' + d.id + '.description', { default: description });
                    }
                    return description;
                });
        }

        function linkify(url) {
            return '' + url + '';
        }
    }

    success.changeset = function(_) {
        if (!arguments.length) return _changeset;
        _changeset = _;
        return success;
    };

    success.location = function(_) {
        if (!arguments.length) return _location;
        _location = _;
        return success;
    };

    return utilRebind(success, dispatch, 'on');
}
<|endoftext|>


<commit_before>var async = require("async");
var cp = require("child_process");
var ralinkcmd ="/usr/bin/lsusb | /bin/egrep Ralink";
var huaweicmd = "/usr/bin/lsusb | /bin/egrep Huawei";
var cellcmd = "/usr/bin/wvdial IMEI; exit 0";

exports.deviceIds = function(callbackMain){
  async.parallel({
    ralink: function(callback){
      cp.exec(ralinkcmd,function(error,stdout,stderr){
        if (error) callback(null,false);
        if (stdout){
          var str = stdout.toString().trim();
          //TODO: check for second device
          //console.log(str);
          callback(null,str);
        }
        if (stderr) callback(null,false);
      });
    },
    huawei: function(callback){
      cp.exec(huaweicmd,function(error,stdout,stderr){
        if (error) callback(null,false);
        if (stdout){
          var str = stdout.toString().trim();
          //console.log(str);
          callback(null,str);
        }
        if (stderr) callback(null,false);
      });
    },
    cell: function(callback){
      cp.exec(cellcmd,function(error,stdout,stderr){
        if (error) {
          //console.log("error "+error);
          var imeiRX= /\nAT\+CGSN\n(\d+)\n/
          var iccidRX = /\^ICCID: "(\d+)\n/;
          var imei = stdout.match(imeiRX);
          var iccid = stdout.match(iccidRX);
          var obj = {};
          if(imei == null){
            obj["imei"] = false;
          }else{
            obj["imei"] = imei[1];
          }
          if(iccid == null){
            obj["iccid"] = false;
          }else{
            obj["iccid"] = iccid[1];
          }
          callback(null,obj);
        }
        if (stdout){
          //console.log("stdout "+stdout);
          var imeiRX= /\nAT\+CGSN\n(\d+)\n/
          var iccidRX = /\^ICCID: "(\d+)\n/;
          var imei = stdout.match(imeiRX);
          var iccid = stdout.match(iccidRX);
          var obj = {};
          if(imei == null){
            obj["imei"] = false;
          }else{
            obj["imei"] = imei[1];
          }
          if(iccid == null){
            obj["iccid"] = false;
          }else{
            obj["iccid"] = iccid[1];
          }
          callback(null,obj);

        }
        if (stderr){
          //console.log("stderr "+ stderr);
          var imeiRX= /\nAT\+CGSN\n(\d+)\n/
          var iccidRX = /\^ICCID: "(\d+)"\n/;
          var imei = stderr.match(imeiRX);
          var iccid = stderr.match(iccidRX);
          var obj = {};
          if(imei == null){
            obj["imei"] = false;
          }else{
            obj["imei"] = imei[1];
          }
          if(iccid == null){
            obj["iccid"] = false;
          }else{
            obj["iccid"] = iccid[1];
          }
          callback(null,obj);
        }// throw stderr;
      });
    }
},
function(err, results) {
    // results is now equals to: {one: 1, two: 2}
    callbackMain(err,results);
});

}
<commit_msg>try led init fault status<commit_after>var async = require("async");
var cp = require("child_process");
var ralinkcmd ="/usr/bin/lsusb | /bin/egrep Ralink";
var huaweicmd = "/usr/bin/lsusb | /bin/egrep Huawei";
var cellcmd = "/usr/bin/wvdial IMEI; exit 0";

exports.deviceIds = function(callbackMain){
  async.series({
    ralink: function(callback){
      cp.exec(ralinkcmd,function(error,stdout,stderr){
        if (error) callback(null,false);
        if (stdout){
          var str = stdout.toString().trim();
          //TODO: check for second device
          //console.log(str);
          callback(null,str);
        }
        if (stderr) callback(null,false);
      });
    },
    huawei: function(callback){
      cp.exec(huaweicmd,function(error,stdout,stderr){
        if (error) callback(null,false);
        if (stdout){
          var str = stdout.toString().trim();
          //console.log(str);
          callback(null,str);
        }
        if (stderr) callback(null,false);
      });
    },
    cell: function(callback){
      cp.exec(cellcmd,function(error,stdout,stderr){
        if (error) {
          //console.log("error "+error);
          var imeiRX= /\nAT\+CGSN\n(\d+)\n/
          var iccidRX = /\^ICCID: "(\d+)\n/;
          var imei = stdout.match(imeiRX);
          var iccid = stdout.match(iccidRX);
          var obj = {};
          if(imei == null){
            obj["imei"] = false;
          }else{
            obj["imei"] = imei[1];
          }
          if(iccid == null){
            obj["iccid"] = false;
          }else{
            obj["iccid"] = iccid[1];
          }
          callback(null,obj);
        }
        if (stdout){
          //console.log("stdout "+stdout);
          var imeiRX= /\nAT\+CGSN\n(\d+)\n/
          var iccidRX = /\^ICCID: "(\d+)\n/;
          var imei = stdout.match(imeiRX);
          var iccid = stdout.match(iccidRX);
          var obj = {};
          if(imei == null){
            obj["imei"] = false;
          }else{
            obj["imei"] = imei[1];
          }
          if(iccid == null){
            obj["iccid"] = false;
          }else{
            obj["iccid"] = iccid[1];
          }
          callback(null,obj);

        }
        if (stderr){
          //console.log("stderr "+ stderr);
          var imeiRX= /\nAT\+CGSN\n(\d+)\n/
          var iccidRX = /\^ICCID: "(\d+)"\n/;
          var imei = stderr.match(imeiRX);
          var iccid = stderr.match(iccidRX);
          var obj = {};
          if(imei == null){
            obj["imei"] = false;
          }else{
            obj["imei"] = imei[1];
          }
          if(iccid == null){
            obj["iccid"] = false;
          }else{
            obj["iccid"] = iccid[1];
          }
          callback(null,obj);
        }// throw stderr;
      });
    }
},
function(err, results) {
    // results is now equals to: {one: 1, two: 2}
    callbackMain(err,results);
});

}
<|endoftext|>


<commit_before>var wolfram = require('wolfram');
var wc = null;

module.exports.init = function(bot) {
  bot.getConfig("wolfram.json", function(err, conf) {
    if(err) console.log("Unable to load wolfram module: " + err);
    try {
      wc = new wolfram.createClient(conf.appid);
    } catch(ex) {
      bot.say("Error loading twitter library: " + ex);
    }
  });
};

module.exports.commands = ['wolf', 'wolfram', 'wolframalpha'];

module.exports.run = function(remainder, parts, reply, command, from, to, text, raw) {
  if(wc === null) {
    return reply("Unable to handle wolfram request; lib not loaded");
  }

  wc.query(remainder, function(err, res) {
    if(err) return reply("Wolfram error: " + err);

      if(res.length === 1) {
        return reply("No result for query: " + out[0].subpods[0].value);
      }

    var primary_pods = res.filter(function(x){return x.primary;});
    if(primary_pods.length === 0) {
      try {
        return reply(res[0].subpods[0].value + ': ' + res[1].subpods[0].value.split('\n').join(' ~ '));
      } catch(ex) {
        return reply("No primary pod, try http://www.wolframalpha.com/input/?i="+encodeURIComponent(remainder));
      }
    }

    var ppod = primary_pods[0];
    try {
      if(ppod.title && ppod.subpods[0].value) {
        reply(ppod.title + ": " + ppod.subpods[0].value);
      } else {
        throw("Can't handle this ppod");
      }
    } catch(ex) {
      console.log(ppod);
      reply("Not sure how to handle primary pod, someone should pull request this");
    }
  });
};
<commit_msg>Fix diagnostic messages<commit_after>var wolfram = require('wolfram');
var wc = null;

module.exports.init = function(bot) {
  bot.getConfig("wolfram.json", function(err, conf) {
    if(err) console.log("Unable to load wolfram module: " + err);
    try {
      wc = new wolfram.createClient(conf.appid);
    } catch(ex) {
      bot.say("Error loading wolfram library: " + ex);
    }
  });
};

module.exports.commands = ['wolf', 'wolfram', 'wolframalpha'];

module.exports.run = function(remainder, parts, reply, command, from, to, text, raw) {
  if(wc === null) {
    return reply("Unable to handle wolfram request; lib not loaded");
  }

  wc.query(remainder, function(err, res) {
    if(err) return reply("Wolfram error: " + err);

      if(res.length === 1) {
        return reply("No result for query: " + out[0].subpods[0].value);
      }

    var primary_pods = res.filter(function(x){return x.primary;});
    if(primary_pods.length === 0) {
      try {
        return reply(res[0].subpods[0].value + ': ' + res[1].subpods[0].value.split('\n').join(' ~ '));
      } catch(ex) {
        return reply("No primary pod, try http://www.wolframalpha.com/input/?i="+encodeURIComponent(remainder));
      }
    }

    var ppod = primary_pods[0];
    try {
      if(ppod.title && ppod.subpods[0].value) {
        reply(ppod.title + ": " + ppod.subpods[0].value);
      } else {
        throw("Can't handle this ppod");
      }
    } catch(ex) {
      console.log(ppod);
      reply("Not sure how to handle primary pod, someone should pull request this");
    }
  });
};
<|endoftext|>


<commit_before>import { readFile } from './fs.js';
import { resolve } from 'path';

import File from './File.js';
import Watcher from './Watcher.js';

const _origData = Symbol();
const _status = Symbol();
const _before = Symbol();
const _during = Symbol();
const _after = Symbol();
const _watchers = Symbol();
const _transform = Symbol();
const _generators = Symbol();
const _resolver = Symbol();
const _onerror = Symbol();
const _active = Symbol();
const _waitingFor = Symbol();
const _whenFound = Symbol();
const _deps = Symbol();
const _queue = Symbol();
const _isProcessing = Symbol();
const _startWave = Symbol();
const _endWave = Symbol();
const _enqueue = Symbol();
const _processPhysicalFile = Symbol();
const _processFile = Symbol();
const _callTransform = Symbol();
const _processGenerator = Symbol();
const _checkWave = Symbol();
const _current = Symbol();
const _newProxy = Symbol();
const _processDependents = Symbol();
const _markFound = Symbol();

export default class Defiler {
	constructor(...args) {
		const { transform, generators = [], resolver, onerror } = args.pop();
		if (typeof transform !== 'function') {
			throw new TypeError('defiler: transform must be a function');
		}
		if (
			!Array.isArray(generators) ||
			generators.some(generator => typeof generator !== 'function')
		) {
			throw new TypeError('defiler: generators must be an array of functions');
		}
		if (resolver && typeof resolver !== 'function') {
			throw new TypeError('defiler: resolver must be a function');
		}
		if (onerror && typeof onerror !== 'function') {
			throw new TypeError('defiler: onerror must be a function');
		}
		// set of original paths for all physical files
		this.paths = new Set();
		// original paths -> original file data for all physical files ({ path, stats, bytes, enc })
		this[_origData] = new Map();
		// original paths -> transformed files for all physical and virtual files
		this.files = new Map();
		// _before, _during, or _after exec has been called
		this[_status] = _before;
		// Watcher instances
		this[_watchers] = args.map(
			({
				dir,
				filter,
				read = true,
				enc = 'utf8',
				pre,
				watch = true,
				debounce = 10,
			}) => {
				if (typeof dir !== 'string') {
					throw new TypeError('defiler: dir must be a string');
				}
				if (filter && typeof filter !== 'function') {
					throw new TypeError('defiler: filter must be a function');
				}
				if (typeof read !== 'boolean' && typeof read !== 'function') {
					throw new TypeError('defiler: read must be a boolean or a function');
				}
				if (!Buffer.isEncoding(enc) && typeof enc !== 'function') {
					throw new TypeError(
						'defiler: enc must be a supported encoding or a function',
					);
				}
				if (pre && typeof pre !== 'function') {
					throw new TypeError('defiler: pre must be a function');
				}
				if (typeof watch !== 'boolean') {
					throw new TypeError('defiler: watch must be a boolean');
				}
				if (typeof debounce !== 'number') {
					throw new TypeError('defiler: debounce must be a number');
				}
				return new Watcher({
					dir: resolve(dir),
					filter,
					read,
					enc,
					pre,
					watch,
					debounce,
				});
			},
		);
		// the transform to run on all files
		this[_transform] = transform;
		// unique symbols -> registered generators
		this[_generators] = new Map(
			generators.map(generator => [Symbol(), generator]),
		);
		// (base, path) => path resolver function, used in defiler.get and defiler.add from transform
		this[_resolver] = resolver;
		// handler to call when errors occur
		this[_onerror] = onerror;
		// original paths of all files currently undergoing transformation and symbols of all generators currently running
		this[_active] = new Set();
		// original paths -> number of other files they're currently waiting on to exist
		this[_waitingFor] = new Map();
		// original paths -> { promise, resolve } objects for when awaited files become available
		this[_whenFound] = new Map();
		// (set via proxy) the current immediate dependent (path or generator symbol), for use in _deps, _waitingFor, and the resolver
		this[_current] = null;
		// array of [dependent, dependency] pairs, specifying changes to which files should trigger re-processing which other files
		this[_deps] = [];
		// queue of pending Watcher events to handle
		this[_queue] = [];
		// whether some Watcher event is currently already in the process of being handled
		this[_isProcessing] = false;
	}

	// execute everything, and return a promise that resolves when the first wave of processing is complete
	async exec() {
		if (this[_status] !== _before) {
			throw new Error('defiler.exec: cannot call more than once');
		}
		this[_status] = _during;
		this[_isProcessing] = true;
		const done = this[_startWave]();
		// init the Watcher instances
		const files = [];
		await Promise.all(
			this[_watchers].map(async watcher => {
				watcher.on('', event => this[_enqueue](watcher, event));
				// note that all files are pending transformation
				await Promise.all(
					(await watcher.init()).map(async file => {
						const { path } = file;
						if (watcher.pre) {
							await watcher.pre(file);
						}
						this.paths.add(file.path);
						this[_active].add(file.path);
						files.push([watcher, path, file]);
					}),
				);
			}),
		);
		for (const symbol of this[_generators].keys()) {
			this[_active].add(symbol);
		}
		// process each physical file
		for (const [watcher, path, file] of files) {
			this[_processPhysicalFile](watcher, path, file);
		}
		// process each generator
		for (const symbol of this[_generators].keys()) {
			this[_processGenerator](symbol);
		}
		// wait and finish up
		await done;
		this[_status] = _after;
		this[_isProcessing] = false;
		this[_enqueue]();
	}

	// wait for a file to be available and retrieve it, marking dependencies as appropriate
	async get(path) {
		if (Array.isArray(path)) {
			return Promise.all(path.map(path => this.get(path)));
		}
		const { [_current]: current, [_waitingFor]: waitingFor } = this;
		path = this.resolve(path);
		if (typeof path !== 'string') {
			throw new TypeError('defiler.get: path must be a string');
		}
		if (current) {
			this[_deps].push([current, path]);
		}
		if (this[_status] === _during && !this.files.has(path)) {
			if (current) {
				waitingFor.set(current, (waitingFor.get(current) || 0) + 1);
			}
			if (!this[_whenFound].has(path)) {
				let resolve;
				this[_whenFound].set(path, {
					promise: new Promise(res => (resolve = res)),
					resolve,
				});
			}
			await this[_whenFound].get(path).promise;
			if (current) {
				waitingFor.set(current, waitingFor.get(current) - 1);
			}
		}
		return this.files.get(path);
	}

	// add a new virtual file
	add(file) {
		if (this[_status] === _before) {
			throw new Error('defiler.add: cannot call before calling exec');
		}
		if (typeof file !== 'object') {
			throw new TypeError('defiler.add: file must be an object');
		}
		file.path = this.resolve(file.path);
		this[_origData].set(file.path, file);
		this[_processFile](file, true);
	}

	// resolve a given path from the file currently being transformed
	resolve(path) {
		return this[_resolver] && typeof this[_current] === 'string'
			? this[_resolver](this[_current], path)
			: path;
	}

	// private methods

	// return a Promise that we will resolve at the end of this wave, and save its resolver
	[_startWave]() {
		return new Promise(res => (this[_endWave] = res));
	}

	// add a Watcher event to the queue, and handle queued events
	async [_enqueue](watcher, event) {
		if (event) {
			this[_queue].push([watcher, event]);
		}
		if (this[_isProcessing]) {
			return;
		}
		this[_isProcessing] = true;
		while (this[_queue].length) {
			const done = this[_startWave]();
			const [watcher, { event, path, stats }] = this[_queue].shift();
			const file = { path, stats };
			if (watcher.pre) {
				await watcher.pre(file);
			}
			if (event === '+') {
				this[_processPhysicalFile](watcher, path, file);
			} else if (event === '-') {
				const { path } = file;
				const oldFile = this.files.get(path);
				this.paths.delete(path);
				this[_origData].delete(path);
				this.files.delete(path);
				await this[_callTransform](oldFile, false, true);
				this[_processDependents](path);
			}
			await done;
		}
		this[_isProcessing] = false;
	}

	// create a file object for a physical file and process it
	async [_processPhysicalFile]({ dir, read, enc }, path, file) {
		if (typeof read === 'function') {
			read = await read({ path, stats: file.stats });
		}
		if (read) {
			file.bytes = await readFile(dir + '/' + path);
		}
		if (typeof enc === 'function') {
			enc = await enc({ path, stats: file.stats, bytes: file.bytes });
		}
		file.enc = enc;
		this.paths.add(file.path);
		this[_origData].set(file.path, file);
		await this[_processFile](file, true);
	}

	// transform a file, store it, and process dependents
	async [_processFile](data, changed) {
		const file = Object.assign(new File(), data);
		const { path } = file;
		this[_active].add(path);
		await this[_callTransform](file, changed, false);
		this.files.set(path, file);
		this[_markFound](path);
		if (this[_status] === _after) {
			this[_processDependents](path);
		}
		this[_active].delete(path);
		this[_checkWave]();
	}

	// call the transform on a file with the given changed and deleted flags, and handle errors
	async [_callTransform](file, changed, deleted) {
		let defiler = this[_newProxy](file.path);
		try {
			await this[_transform]({ defiler, file, changed, deleted });
		} catch (error) {
			if (this[_onerror]) {
				this[_onerror]({ defiler, file, changed, deleted, error });
			}
		}
	}

	// run the generator given by the symbol
	async [_processGenerator](symbol) {
		this[_active].add(symbol);
		const generator = this[_generators].get(symbol);
		const defiler = this[_newProxy](symbol);
		try {
			await generator({ defiler });
		} catch (error) {
			if (this[_onerror]) {
				this[_onerror]({ defiler, generator, error });
			}
		}
		this[_active].delete(symbol);
		this[_checkWave]();
	}

	// re-process all files that depend on a particular path
	[_processDependents](path) {
		const dependents = new Set();
		for (const [dependent, dep] of this[_deps]) {
			if (dep === path) {
				dependents.add(dependent);
			}
		}
		this[_deps] = this[_deps].filter(
			([dependent]) => !dependents.has(dependent),
		);
		if (!dependents.size && !this[_active].size) {
			this[_endWave]();
		}
		for (const dependent of dependents) {
			if (this[_origData].has(dependent)) {
				this[_processFile](this[_origData].get(dependent), false);
			} else if (this[_generators].has(dependent)) {
				this[_processGenerator](dependent);
			}
		}
	}

	// check whether this wave is complete, and, if not, whether we need to break a deadlock
	[_checkWave]() {
		if (!this[_active].size) {
			this[_endWave]();
		} else if (
			this[_status] === _during &&
			[...this[_active]].every(path => this[_waitingFor].get(path))
		) {
			// all pending files are currently waiting for one or more other files to exist
			// break deadlock: assume all files that have not appeared yet will never do so
			for (const path of this[_whenFound].keys()) {
				if (!this[_active].has(path)) {
					this[_markFound](path);
				}
			}
		}
	}

	// create a defiler Proxy for the given path or generator symbol
	[_newProxy](path) {
		return new Proxy(this, {
			get: (_, key) => (key === _current ? path : this[key]),
		});
	}

	// mark a given awaited file as being found
	[_markFound](path) {
		if (this[_status] === _during && this[_whenFound].has(path)) {
			this[_whenFound].get(path).resolve();
			this[_whenFound].delete(path);
		}
	}
}
<commit_msg>split transform flags into read/added/deleted<commit_after>import { readFile } from './fs.js';
import { resolve } from 'path';

import File from './File.js';
import Watcher from './Watcher.js';

const _origData = Symbol();
const _status = Symbol();
const _before = Symbol();
const _during = Symbol();
const _after = Symbol();
const _watchers = Symbol();
const _transform = Symbol();
const _generators = Symbol();
const _resolver = Symbol();
const _onerror = Symbol();
const _active = Symbol();
const _waitingFor = Symbol();
const _whenFound = Symbol();
const _deps = Symbol();
const _queue = Symbol();
const _isProcessing = Symbol();
const _startWave = Symbol();
const _endWave = Symbol();
const _enqueue = Symbol();
const _processPhysicalFile = Symbol();
const _processFile = Symbol();
const _callTransform = Symbol();
const _processGenerator = Symbol();
const _checkWave = Symbol();
const _current = Symbol();
const _newProxy = Symbol();
const _processDependents = Symbol();
const _markFound = Symbol();

export default class Defiler {
	constructor(...args) {
		const { transform, generators = [], resolver, onerror } = args.pop();
		if (typeof transform !== 'function') {
			throw new TypeError('defiler: transform must be a function');
		}
		if (
			!Array.isArray(generators) ||
			generators.some(generator => typeof generator !== 'function')
		) {
			throw new TypeError('defiler: generators must be an array of functions');
		}
		if (resolver && typeof resolver !== 'function') {
			throw new TypeError('defiler: resolver must be a function');
		}
		if (onerror && typeof onerror !== 'function') {
			throw new TypeError('defiler: onerror must be a function');
		}
		// set of original paths for all physical files
		this.paths = new Set();
		// original paths -> original file data for all physical files ({ path, stats, bytes, enc })
		this[_origData] = new Map();
		// original paths -> transformed files for all physical and virtual files
		this.files = new Map();
		// _before, _during, or _after exec has been called
		this[_status] = _before;
		// Watcher instances
		this[_watchers] = args.map(
			({
				dir,
				filter,
				read = true,
				enc = 'utf8',
				pre,
				watch = true,
				debounce = 10,
			}) => {
				if (typeof dir !== 'string') {
					throw new TypeError('defiler: dir must be a string');
				}
				if (filter && typeof filter !== 'function') {
					throw new TypeError('defiler: filter must be a function');
				}
				if (typeof read !== 'boolean' && typeof read !== 'function') {
					throw new TypeError('defiler: read must be a boolean or a function');
				}
				if (!Buffer.isEncoding(enc) && typeof enc !== 'function') {
					throw new TypeError(
						'defiler: enc must be a supported encoding or a function',
					);
				}
				if (pre && typeof pre !== 'function') {
					throw new TypeError('defiler: pre must be a function');
				}
				if (typeof watch !== 'boolean') {
					throw new TypeError('defiler: watch must be a boolean');
				}
				if (typeof debounce !== 'number') {
					throw new TypeError('defiler: debounce must be a number');
				}
				return new Watcher({
					dir: resolve(dir),
					filter,
					read,
					enc,
					pre,
					watch,
					debounce,
				});
			},
		);
		// the transform to run on all files
		this[_transform] = transform;
		// unique symbols -> registered generators
		this[_generators] = new Map(
			generators.map(generator => [Symbol(), generator]),
		);
		// (base, path) => path resolver function, used in defiler.get and defiler.add from transform
		this[_resolver] = resolver;
		// handler to call when errors occur
		this[_onerror] = onerror;
		// original paths of all files currently undergoing transformation and symbols of all generators currently running
		this[_active] = new Set();
		// original paths -> number of other files they're currently waiting on to exist
		this[_waitingFor] = new Map();
		// original paths -> { promise, resolve } objects for when awaited files become available
		this[_whenFound] = new Map();
		// (set via proxy) the current immediate dependent (path or generator symbol), for use in _deps, _waitingFor, and the resolver
		this[_current] = null;
		// array of [dependent, dependency] pairs, specifying changes to which files should trigger re-processing which other files
		this[_deps] = [];
		// queue of pending Watcher events to handle
		this[_queue] = [];
		// whether some Watcher event is currently already in the process of being handled
		this[_isProcessing] = false;
	}

	// execute everything, and return a promise that resolves when the first wave of processing is complete
	async exec() {
		if (this[_status] !== _before) {
			throw new Error('defiler.exec: cannot call more than once');
		}
		this[_status] = _during;
		this[_isProcessing] = true;
		const done = this[_startWave]();
		// init the Watcher instances
		const files = [];
		await Promise.all(
			this[_watchers].map(async watcher => {
				watcher.on('', event => this[_enqueue](watcher, event));
				// note that all files are pending transformation
				await Promise.all(
					(await watcher.init()).map(async file => {
						const { path } = file;
						if (watcher.pre) {
							await watcher.pre(file);
						}
						this.paths.add(file.path);
						this[_active].add(file.path);
						files.push([watcher, path, file]);
					}),
				);
			}),
		);
		for (const symbol of this[_generators].keys()) {
			this[_active].add(symbol);
		}
		// process each physical file
		for (const [watcher, path, file] of files) {
			this[_processPhysicalFile](watcher, path, file);
		}
		// process each generator
		for (const symbol of this[_generators].keys()) {
			this[_processGenerator](symbol);
		}
		// wait and finish up
		await done;
		this[_status] = _after;
		this[_isProcessing] = false;
		this[_enqueue]();
	}

	// wait for a file to be available and retrieve it, marking dependencies as appropriate
	async get(path) {
		if (Array.isArray(path)) {
			return Promise.all(path.map(path => this.get(path)));
		}
		const { [_current]: current, [_waitingFor]: waitingFor } = this;
		path = this.resolve(path);
		if (typeof path !== 'string') {
			throw new TypeError('defiler.get: path must be a string');
		}
		if (current) {
			this[_deps].push([current, path]);
		}
		if (this[_status] === _during && !this.files.has(path)) {
			if (current) {
				waitingFor.set(current, (waitingFor.get(current) || 0) + 1);
			}
			if (!this[_whenFound].has(path)) {
				let resolve;
				this[_whenFound].set(path, {
					promise: new Promise(res => (resolve = res)),
					resolve,
				});
			}
			await this[_whenFound].get(path).promise;
			if (current) {
				waitingFor.set(current, waitingFor.get(current) - 1);
			}
		}
		return this.files.get(path);
	}

	// add a new virtual file
	add(file) {
		if (this[_status] === _before) {
			throw new Error('defiler.add: cannot call before calling exec');
		}
		if (typeof file !== 'object') {
			throw new TypeError('defiler.add: file must be an object');
		}
		file.path = this.resolve(file.path);
		this[_origData].set(file.path, file);
		this[_processFile](file, false, true);
	}

	// resolve a given path from the file currently being transformed
	resolve(path) {
		return this[_resolver] && typeof this[_current] === 'string'
			? this[_resolver](this[_current], path)
			: path;
	}

	// private methods

	// return a Promise that we will resolve at the end of this wave, and save its resolver
	[_startWave]() {
		return new Promise(res => (this[_endWave] = res));
	}

	// add a Watcher event to the queue, and handle queued events
	async [_enqueue](watcher, event) {
		if (event) {
			this[_queue].push([watcher, event]);
		}
		if (this[_isProcessing]) {
			return;
		}
		this[_isProcessing] = true;
		while (this[_queue].length) {
			const done = this[_startWave]();
			const [watcher, { event, path, stats }] = this[_queue].shift();
			const file = { path, stats };
			if (watcher.pre) {
				await watcher.pre(file);
			}
			if (event === '+') {
				this[_processPhysicalFile](watcher, path, file);
			} else if (event === '-') {
				const { path } = file;
				const oldFile = this.files.get(path);
				this.paths.delete(path);
				this[_origData].delete(path);
				this.files.delete(path);
				await this[_callTransform](oldFile, false, false, true);
				this[_processDependents](path);
			}
			await done;
		}
		this[_isProcessing] = false;
	}

	// create a file object for a physical file and process it
	async [_processPhysicalFile]({ dir, read, enc }, path, file) {
		if (typeof read === 'function') {
			read = await read({ path, stats: file.stats });
		}
		if (read) {
			file.bytes = await readFile(dir + '/' + path);
		}
		if (typeof enc === 'function') {
			enc = await enc({ path, stats: file.stats, bytes: file.bytes });
		}
		file.enc = enc;
		this.paths.add(file.path);
		this[_origData].set(file.path, file);
		await this[_processFile](file, true, false);
	}

	// transform a file, store it, and process dependents
	async [_processFile](data, read, added) {
		const file = Object.assign(new File(), data);
		const { path } = file;
		this[_active].add(path);
		await this[_callTransform](file, read, added, false);
		this.files.set(path, file);
		this[_markFound](path);
		if (this[_status] === _after) {
			this[_processDependents](path);
		}
		this[_active].delete(path);
		this[_checkWave]();
	}

	// call the transform on a file with the given changed and deleted flags, and handle errors
	async [_callTransform](file, read, added, deleted) {
		let defiler = this[_newProxy](file.path);
		try {
			await this[_transform]({ defiler, file, read, added, deleted });
		} catch (error) {
			if (this[_onerror]) {
				this[_onerror]({ defiler, file, read, added, deleted, error });
			}
		}
	}

	// run the generator given by the symbol
	async [_processGenerator](symbol) {
		this[_active].add(symbol);
		const generator = this[_generators].get(symbol);
		const defiler = this[_newProxy](symbol);
		try {
			await generator({ defiler });
		} catch (error) {
			if (this[_onerror]) {
				this[_onerror]({ defiler, generator, error });
			}
		}
		this[_active].delete(symbol);
		this[_checkWave]();
	}

	// re-process all files that depend on a particular path
	[_processDependents](path) {
		const dependents = new Set();
		for (const [dependent, dep] of this[_deps]) {
			if (dep === path) {
				dependents.add(dependent);
			}
		}
		this[_deps] = this[_deps].filter(
			([dependent]) => !dependents.has(dependent),
		);
		if (!dependents.size && !this[_active].size) {
			this[_endWave]();
		}
		for (const dependent of dependents) {
			if (this[_origData].has(dependent)) {
				this[_processFile](this[_origData].get(dependent), false, false);
			} else if (this[_generators].has(dependent)) {
				this[_processGenerator](dependent);
			}
		}
	}

	// check whether this wave is complete, and, if not, whether we need to break a deadlock
	[_checkWave]() {
		if (!this[_active].size) {
			this[_endWave]();
		} else if (
			this[_status] === _during &&
			[...this[_active]].every(path => this[_waitingFor].get(path))
		) {
			// all pending files are currently waiting for one or more other files to exist
			// break deadlock: assume all files that have not appeared yet will never do so
			for (const path of this[_whenFound].keys()) {
				if (!this[_active].has(path)) {
					this[_markFound](path);
				}
			}
		}
	}

	// create a defiler Proxy for the given path or generator symbol
	[_newProxy](path) {
		return new Proxy(this, {
			get: (_, key) => (key === _current ? path : this[key]),
		});
	}

	// mark a given awaited file as being found
	[_markFound](path) {
		if (this[_status] === _during && this[_whenFound].has(path)) {
			this[_whenFound].get(path).resolve();
			this[_whenFound].delete(path);
		}
	}
}
<|endoftext|>


<commit_before>$(function () {
    // $('.ef').textillate();

    $('#effect-in, #effect-out').change(function(){
    	var inVal = $('#effect-in').val();
    	var outVal = $('#effect-out').val();
    	effectIn(inVal, outVal);
    });
    function effectIn(inVal, outVal){
	    $('.ef').textillate({
	        // ループのオンオフ、falseの場合、outは発動しない
	        loop: true,
	        // テキストが置き換えられるまでの表示時間
	        minDisplayTime: 2000,
	        // 遅延時間
	        initialDelay: 0,
	        // アニメーションが自動的にスタートするかどうか
	        autoStart: true,
	        // フェードインのエフェクトの詳細設定
	        in: {
	            // エフェクトの名前（animate.cssをご参照下さい）
	            effect: inVal,
	            // 遅延時間の指数
	            delayScale: 1.5,
	            // 文字ごとの遅延時間
	            delay: 50,
	            // trueにすることでアニメーションをすべての文字に同時に適用される
	            sync: false,
	            // trueにすることで文字を順番にではなく、ランダムに入ってくるようにする
	            // (注：syncがtrueの場合は無効になる)
	            shuffle: false
	        },
	        out: {
	            effect: outVal,
	            delayScale: 1.5,
	            delay: 50,
	            sync: false,
	            shuffle: false
	        }
	    });
	}
})<commit_msg>説明文変更<commit_after>$(function () {
    // $('.ef').textillate();

    // セレクトボタン切り替えイベント
    $('#effect-in, #effect-out').change(function(){
    	var inVal = $('#effect-in').val();
    	var outVal = $('#effect-out').val();
    	effectIn(inVal, outVal);
    });
    // エフェクト処理
    function effectIn(inVal, outVal){
	    $('.ef').textillate({
	        // 繰り返し、trueにしないと2回目以降が実行されない
	        loop: true,
	        // アニメーション開始までの時間
	        minDisplayTime: 2000,
	        // 遅延時間
	        initialDelay: 0,
	        // アニメーションが自動的にスタートするか
	        autoStart: true,
	        // フェードインのエフェクトの詳細設定
	        in: {
	            // エフェクトの種類（引数から取得）
	            effect: inVal,
	            // 遅延時間の指数
	            delayScale: 1.5,
	            // 文字ごとの遅延時間
	            delay: 50,
	            // trueにすることでアニメーションをすべての文字に同時に適用される
	            sync: false,
	            // trueにすることで文字表示がランダムな順に表示される
	            // (注：syncがtrueの場合は無効になる)
	            shuffle: false
	        },
	        out: {
	            effect: outVal,
	            delayScale: 1.5,
	            delay: 50,
	            sync: false,
	            shuffle: false
	        }
	    });
	}
})<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Neutral } from './Color';
import DepIndicators from './DepIndicators';

class DepCard extends Component {
  render() {
    var width = 15;
    var height = 3;
    var color = Neutral;
    var style = {
      fill: color,
      opacity: '0.1',
      strokeWidth: 0,
    };
    return <g className="DepCard">
      <rect
        x={this.props.cx - width/2} y={this.props.cy - height/2}
        width={width} height={height} rx="0.5" ry="0.5" style={style}>
      </rect>
      <text x={this.props.cx} y={this.props.cy}
          transform={'translate(' + (-width/2 + 0.5) + ', ' + (-height/2 + 1.5) + ')'}>
        {this.props.title}
      </text>
      <DepIndicators
        cx={this.props.cx + width/2} cy={this.props.cy} dy={height/2}
        dependencies={this.props.dependencies}
        related={this.props.related}
        dependents={this.props.dependents}
        done={this.props.done} />
    </g>
  }
}

export default DepCard;
<commit_msg>DepCard: Add the GitHub logo as a clickable link<commit_after>import React, { Component } from 'react';
import github from './logo/github.svg';
import { Neutral } from './Color';
import DepIndicators from './DepIndicators';

class DepCard extends Component {
  render() {
    var width = 15;
    var height = 3;
    var color = Neutral;
    var style = {
      fill: color,
      opacity: '0.1',
      strokeWidth: 0,
    };
    var logo = github;
    var host = 'https://github.com';
    return <g className="DepCard" xmlnsXlink="http://www.w3.org/1999/xlink">
      <rect
        x={this.props.cx - width/2} y={this.props.cy - height/2}
        width={width} height={height} rx="0.5" ry="0.5" style={style}>
      </rect>
      <a xlinkHref={host}>
        <image
          x={this.props.cx - width/2 + 0.5} y={this.props.cy - 0.4 * height}
          width={0.8 * height} height={0.8 * height}
          xlinkHref={logo}>
        </image>
      </a>
      <text
        x={this.props.cx - width/2 + 0.5 + height}
        y={this.props.cy - height/2 + 1.5}>
        {this.props.title}
      </text>
      <DepIndicators
        cx={this.props.cx + width/2} cy={this.props.cy} dy={height/2}
        dependencies={this.props.dependencies}
        related={this.props.related}
        dependents={this.props.dependents}
        done={this.props.done} />
    </g>
  }
}

export default DepCard;
<|endoftext|>


<commit_before>// Return new array with duplicate values removed
function array_unique(arr) {
    var a = [];
    var l = arr.length;
    for(var i=0; i<l; i++) {
	for(var j=i+1; j<l; j++) {
	    // If arr[i] is found later in the array
	    if (arr[i] === arr[j])
		j = ++i;
	}
	a.push(arr[i]);
    }
    return a;
}

function array_average(arr) {
    return arr.reduce(function (a,b) {
	return (a + b);
    }) / arr.length;
}

function stringSize(str, font)
{
    var width = 0;
    var height = 0;
    var f = font || '12px arial';
    str.split("\n").forEach(function(x) {
	var o = $('
' + x + '
')
            .css({'position': 'absolute', 'float': 'left', 'visibility': 'hidden', 'font': f})
            .appendTo($('body'));
	if ( o.width() > width )
	    width = o.width();
	height += 5 + o.height();
	o.remove();
    }, this);
    return [width, height];
}

function rotatePoints(arr, x, y, degrees)
{
    arr.forEach(function(p) {
	p.rotate(x, y, degrees, true);
    }, this);
}

function positiveRectangle(x, y, w, h) {
    if ( w < 0 ) {
	w = -(w);
	x = x - w;
    }
    if ( h < 0 ) {
	h = -(h);
	y = y - h;
    }
    return new Phaser.Rectangle(x, y, w, h);
}

function nearestInGroup(sprite, group, sprite_group) {
    var nearest = null;
    var lastdist = 0.0;
    for ( var i = 0 ; i < group.length; i++ ) {
	console.log("Checking distance to group[" + i + "]");
	var spr = group.getChildAt(i);
	console.log(spr);
	if ( (typeof sprite_group !== undefined) &&
	     spr.sprite_group !== sprite_group )
	    continue;
	var dist = new Phaser.Line(sprite.x, sprite.y, spr.x, spr.y);
	if ( (lastdist == 0.0 ) || (dist.length < lastdist) ) {
	    lastdist = dist.length;
	    nearest = spr;
	}
    }
    return nearest;
}

function nearestWalkableTile(spr)
{
    var grid = gridWithAISprites();
    var sprgridx = parseInt(spr.x / 32);
    var sprgridy = parseInt(spr.y / 32);

    function _walkable_inner(multiplier) {
	var startx = parseInt(Math.max(sprgridx - (1 * multiplier), 0));
	var starty = parseInt(Math.max(sprgridy - (1 * multiplier), 0));
	var endx = parseInt(Math.min(sprgridx + 1 + (1 * multiplier), game.state.states.game.map.width));
	var endy = parseInt(Math.min(sprgridy + 1 + (1 * multiplier), game.state.states.game.map.height));

	for ( var x = startx ; x <= endx ; x++ ) {
	    for ( var y = starty ; y <= endy ; y++ ) {
		if ( (x == startx ) ||
		     (x == endx ) ||
		     (y == starty ) ||
		     (y == endy) ) {
		    if ( grid.nodes[y][x].walkable == true ) {
			return [x, y];
		    }
		}
	    }
	}
	return null;
    }

    if ( grid.nodes[sprgridy][sprgridx].walkable == true )
	return [sprgridx, sprgridy];
    for ( var i = 1 ; i < 100 ; i++ ) {
	var rv = _walkable_inner(i);
	if ( isSet(rv) ) {
	    return rv
	}
    }
    return [sprgridx, sprgridy];
}

function addAnimation(obj, anim)
{
    a = moonlightSettings['animations'][anim]
    obj.animations.add(anim, a['frames'], a['speed'], a['loop'])
}

function getAwarenessState(spr)
{
    if ( hasState(spr, STATE_UNAWARE) )
	return STATE_UNAWARE;
    if ( hasState(spr, STATE_CONCERNED) )
	return STATE_CONCERNED;
    if ( hasState(spr, STATE_ALERTED) )
	return STATE_ALERTED;
    if ( hasState(spr, STATE_LOSTHIM) )
	return STATE_LOSTHIM;
}

function faceStateFromString(face)
{
    var states = { "up": STATE_FACE_UP,
		   "down": STATE_FACE_DOWN,
		   "left": STATE_FACE_LEFT,
		   "right": STATE_FACE_RIGHT };
    return states[face.toLowerCase()];
}

function getFaceState(spr)
{
    if ( hasState(spr, STATE_FACE_LEFT) )
	return STATE_FACE_LEFT;
    if ( hasState(spr, STATE_FACE_RIGHT) )
	return STATE_FACE_RIGHT;
    if ( hasState(spr, STATE_FACE_DOWN) )
	return STATE_FACE_DOWN;
    if ( hasState(spr, STATE_FACE_UP) )
	return STATE_FACE_UP;
}

function getMoveState(spr)
{
    return ( hasState(spr, STATE_MOVING) ||
	     hasState(spr, STATE_RUNNING) );
}

function delState(spr, state)
{
    if ( hasState(spr, state) )
	spr.state = spr.state ^ state;
}

function addState(spr, state)
{
    spr.state = spr.state | state;
}

function setMovingState(spr, state)
{
    delState(spr, STATE_FACE_LEFT);
    delState(spr, STATE_FACE_RIGHT);
    delState(spr, STATE_FACE_DOWN);
    delState(spr, STATE_FACE_UP);
    delState(spr, STATE_MOVING);
    delState(spr, STATE_RUNNING);
    addState(spr, state);
}

function setAwarenessState(spr, state)
{
    delState(spr, STATE_UNAWARE);
    delState(spr, STATE_CONCERNED);
    delState(spr, STATE_ALERTED);
    delState(spr, STATE_LOSTHIM);
    addState(spr, state);
}

function exchangeState(spr, state1, state2)
{
    delState(spr, state1);
    addState(spr, state2);
}

function hasAnyState(spr, states)
{
    var hasstate = false;
    states.forEach(function(x) {
	if ( hasState(spr, x) )
	    hasstate = true;
    }, this);
    return hasstate;
}

function hasState(spr, state)
{
    if ( (spr.state & state) == state )
	return true;
    return false;
}

function spriteFacing(spr)
{
    if ( hasState(spr, STATE_FACE_LEFT) )
	return "left";
    if ( hasState(spr, STATE_FACE_RIGHT) )
	return "right";
    if ( hasState(spr, STATE_FACE_DOWN) )
	return "down";
    if ( hasState(spr, STATE_FACE_UP) )
	return "up";
}

function parseBoolean(val)
{
    return ( val == 'true' || val == true );
}

function getMovingAnimationName(spr)
{
    var sprbase = "bipedwalk";
    if ( hasState(spr, STATE_RUNNING) )
	sprbase = "bipedrun";
    return sprbase + spriteFacing(spr);
}

function setSpriteMovement(spr, velocity)
{
    var x = 0;
    var y = 0;
    var dir = spriteFacing(spr);
    velocity = ( typeof velocity == undefined ? velocity : [SPEED_WALKING,
							    SPEED_RUNNING] );

    spr.body.setSize(16, 16, 8, 16);

    if ( hasState(spr, STATE_RUNNING) ) {
	if ( velocity !== false )
	    velocity = velocity[1];
	spr.animations.play("bipedrun" + dir);
    } else if ( hasState(spr, STATE_MOVING) ) {
	if ( velocity !== false )
	    velocity = velocity[0];
	spr.animations.play("bipedwalk" + dir);
    } else {
	if ( velocity !== false ) {
	    spr.body.velocity.x = 0;
	    spr.body.velocity.y = 0;
	}
	spr.animations.stop();
	return;
    }

    if ( velocity !== false ) {
	if ( dir == "left" ) {
	    spr.body.velocity.x = -(velocity * velocity);
	    spr.body.velocity.y = 0;
	} else if ( dir == "right" ) {
	    spr.body.velocity.x = (velocity * velocity);
	    spr.body.velocity.y = 0;
	} else if ( dir == "up" ) {
	    spr.body.velocity.x = 0;
	    spr.body.velocity.y = -(velocity * velocity);
	} else if ( dir == "down" ) {
	    spr.body.velocity.x = 0;
	    spr.body.velocity.y = (velocity * velocity);
	}
    }
}

function genericGridClone()
{
    return pathfinder_grid.clone();
}

function gridWithAISprites()
{
    var grid = pathfinder_grid.clone();
    var aiSprites = game.state.states.game.aiSprites;
    for ( var i = 0 ; i < aiSprites.length ; i++ ) {
	var spr = aiSprites.getChildAt(i);
	// --- We have to normalize the (x,y) because this may be
	// called before the sprites are rebounded back inside the map,
	// and these references will go out of bounds
	var normx = Math.max(parseInt(spr.x/32), 0);
	var normy = Math.max(parseInt(spr.y/32), 0);
	grid.nodes[normy][normx].walkable = false;
    }
    return grid;
}

function stringifyInt(x)
{
    return ("" + x);
}

function isSet(x)
{
    return ( (typeof x !== 'undefined') &&
	     ( x !== null ) );
}

function getDOMValue(name) {
    return document.getElementById(name).value
}

function awardPlayerScoreByState(state)
{
    switch ( state ) {
	case STATE_ALERTED: {
	    player.score += SCORE_ALERTED;
	}
	case STATE_CONCERNED: {
	    player.score += SCORE_CONCERNED;
	}
	case STATE_LOSTHIM: {
	    player.score += SCORE_LOSTHIM;
	}
    }
}
<commit_msg>Snap sprites into the nearest edge of the grid when finding the nearest walkable tile<commit_after>// Return new array with duplicate values removed
function array_unique(arr) {
    var a = [];
    var l = arr.length;
    for(var i=0; i<l; i++) {
	for(var j=i+1; j<l; j++) {
	    // If arr[i] is found later in the array
	    if (arr[i] === arr[j])
		j = ++i;
	}
	a.push(arr[i]);
    }
    return a;
}

function array_average(arr) {
    return arr.reduce(function (a,b) {
	return (a + b);
    }) / arr.length;
}

function stringSize(str, font)
{
    var width = 0;
    var height = 0;
    var f = font || '12px arial';
    str.split("\n").forEach(function(x) {
	var o = $('
' + x + '
')
            .css({'position': 'absolute', 'float': 'left', 'visibility': 'hidden', 'font': f})
            .appendTo($('body'));
	if ( o.width() > width )
	    width = o.width();
	height += 5 + o.height();
	o.remove();
    }, this);
    return [width, height];
}

function rotatePoints(arr, x, y, degrees)
{
    arr.forEach(function(p) {
	p.rotate(x, y, degrees, true);
    }, this);
}

function positiveRectangle(x, y, w, h) {
    if ( w < 0 ) {
	w = -(w);
	x = x - w;
    }
    if ( h < 0 ) {
	h = -(h);
	y = y - h;
    }
    return new Phaser.Rectangle(x, y, w, h);
}

function nearestInGroup(sprite, group, sprite_group) {
    var nearest = null;
    var lastdist = 0.0;
    for ( var i = 0 ; i < group.length; i++ ) {
	console.log("Checking distance to group[" + i + "]");
	var spr = group.getChildAt(i);
	console.log(spr);
	if ( (typeof sprite_group !== undefined) &&
	     spr.sprite_group !== sprite_group )
	    continue;
	var dist = new Phaser.Line(sprite.x, sprite.y, spr.x, spr.y);
	if ( (lastdist == 0.0 ) || (dist.length < lastdist) ) {
	    lastdist = dist.length;
	    nearest = spr;
	}
    }
    return nearest;
}

function nearestWalkableTile(spr)
{
    var grid = gridWithAISprites();
    var sprgridx = parseInt(spr.x / 32);
    var sprgridy = parseInt(spr.y / 32);

    // Snap sprites outside the grid to the grid edge
    if ( sprgridy > grid.nodes.length ) {
	sprgridy = grid.nodes.length - 1;
    }
    if ( sprgridx > grid.nodes[sprgridy].length ) {
	sprgridx = grid.nodes[sprgridy].length - 1;
    }

    function _walkable_inner(multiplier) {
	var startx = parseInt(Math.max(sprgridx - (1 * multiplier), 0));
	var starty = parseInt(Math.max(sprgridy - (1 * multiplier), 0));
	var endx = parseInt(Math.min(sprgridx + 1 + (1 * multiplier), game.state.states.game.map.width));
	var endy = parseInt(Math.min(sprgridy + 1 + (1 * multiplier), game.state.states.game.map.height));

	for ( var x = startx ; x <= endx ; x++ ) {
	    for ( var y = starty ; y <= endy ; y++ ) {
		if ( (x == startx ) ||
		     (x == endx ) ||
		     (y == starty ) ||
		     (y == endy) ) {
		    if ( grid.nodes[y][x].walkable == true ) {
			return [x, y];
		    }
		}
	    }
	}
	throw "No walkable tile found near (" + spr.x + "," + spr.y + ")";
    }

    if ( grid.nodes[sprgridy][sprgridx].walkable == true )
	return [sprgridx, sprgridy];
    for ( var i = 1 ; i < 100 ; i++ ) {
	var rv = _walkable_inner(i);
	if ( isSet(rv) ) {
	    return rv
	}
    }
    return [sprgridx, sprgridy];
}

function addAnimation(obj, anim)
{
    a = moonlightSettings['animations'][anim]
    obj.animations.add(anim, a['frames'], a['speed'], a['loop'])
}

function getAwarenessState(spr)
{
    if ( hasState(spr, STATE_UNAWARE) )
	return STATE_UNAWARE;
    if ( hasState(spr, STATE_CONCERNED) )
	return STATE_CONCERNED;
    if ( hasState(spr, STATE_ALERTED) )
	return STATE_ALERTED;
    if ( hasState(spr, STATE_LOSTHIM) )
	return STATE_LOSTHIM;
}

function faceStateFromString(face)
{
    var states = { "up": STATE_FACE_UP,
		   "down": STATE_FACE_DOWN,
		   "left": STATE_FACE_LEFT,
		   "right": STATE_FACE_RIGHT };
    return states[face.toLowerCase()];
}

function getFaceState(spr)
{
    if ( hasState(spr, STATE_FACE_LEFT) )
	return STATE_FACE_LEFT;
    if ( hasState(spr, STATE_FACE_RIGHT) )
	return STATE_FACE_RIGHT;
    if ( hasState(spr, STATE_FACE_DOWN) )
	return STATE_FACE_DOWN;
    if ( hasState(spr, STATE_FACE_UP) )
	return STATE_FACE_UP;
}

function getMoveState(spr)
{
    return ( hasState(spr, STATE_MOVING) ||
	     hasState(spr, STATE_RUNNING) );
}

function delState(spr, state)
{
    if ( hasState(spr, state) )
	spr.state = spr.state ^ state;
}

function addState(spr, state)
{
    spr.state = spr.state | state;
}

function setMovingState(spr, state)
{
    delState(spr, STATE_FACE_LEFT);
    delState(spr, STATE_FACE_RIGHT);
    delState(spr, STATE_FACE_DOWN);
    delState(spr, STATE_FACE_UP);
    delState(spr, STATE_MOVING);
    delState(spr, STATE_RUNNING);
    addState(spr, state);
}

function setAwarenessState(spr, state)
{
    delState(spr, STATE_UNAWARE);
    delState(spr, STATE_CONCERNED);
    delState(spr, STATE_ALERTED);
    delState(spr, STATE_LOSTHIM);
    addState(spr, state);
}

function exchangeState(spr, state1, state2)
{
    delState(spr, state1);
    addState(spr, state2);
}

function hasAnyState(spr, states)
{
    var hasstate = false;
    states.forEach(function(x) {
	if ( hasState(spr, x) )
	    hasstate = true;
    }, this);
    return hasstate;
}

function hasState(spr, state)
{
    if ( (spr.state & state) == state )
	return true;
    return false;
}

function spriteFacing(spr)
{
    if ( hasState(spr, STATE_FACE_LEFT) )
	return "left";
    if ( hasState(spr, STATE_FACE_RIGHT) )
	return "right";
    if ( hasState(spr, STATE_FACE_DOWN) )
	return "down";
    if ( hasState(spr, STATE_FACE_UP) )
	return "up";
}

function parseBoolean(val)
{
    return ( val == 'true' || val == true );
}

function getMovingAnimationName(spr)
{
    var sprbase = "bipedwalk";
    if ( hasState(spr, STATE_RUNNING) )
	sprbase = "bipedrun";
    return sprbase + spriteFacing(spr);
}

function setSpriteMovement(spr, velocity)
{
    var x = 0;
    var y = 0;
    var dir = spriteFacing(spr);
    velocity = ( typeof velocity == undefined ? velocity : [SPEED_WALKING,
							    SPEED_RUNNING] );

    spr.body.setSize(16, 16, 8, 16);

    if ( hasState(spr, STATE_RUNNING) ) {
	if ( velocity !== false )
	    velocity = velocity[1];
	spr.animations.play("bipedrun" + dir);
    } else if ( hasState(spr, STATE_MOVING) ) {
	if ( velocity !== false )
	    velocity = velocity[0];
	spr.animations.play("bipedwalk" + dir);
    } else {
	if ( velocity !== false ) {
	    spr.body.velocity.x = 0;
	    spr.body.velocity.y = 0;
	}
	spr.animations.stop();
	return;
    }

    if ( velocity !== false ) {
	if ( dir == "left" ) {
	    spr.body.velocity.x = -(velocity * velocity);
	    spr.body.velocity.y = 0;
	} else if ( dir == "right" ) {
	    spr.body.velocity.x = (velocity * velocity);
	    spr.body.velocity.y = 0;
	} else if ( dir == "up" ) {
	    spr.body.velocity.x = 0;
	    spr.body.velocity.y = -(velocity * velocity);
	} else if ( dir == "down" ) {
	    spr.body.velocity.x = 0;
	    spr.body.velocity.y = (velocity * velocity);
	}
    }
}

function genericGridClone()
{
    return pathfinder_grid.clone();
}

function gridWithAISprites()
{
    var grid = pathfinder_grid.clone();
    var aiSprites = game.state.states.game.aiSprites;
    for ( var i = 0 ; i < aiSprites.length ; i++ ) {
	var spr = aiSprites.getChildAt(i);
	// --- We have to normalize the (x,y) because this may be
	// called before the sprites are rebounded back inside the map,
	// and these references will go out of bounds
	var normx = Math.max(parseInt(spr.x/32), 0);
	var normy = Math.max(parseInt(spr.y/32), 0);
	grid.nodes[normy][normx].walkable = false;
    }
    return grid;
}

function stringifyInt(x)
{
    return ("" + x);
}

function isSet(x)
{
    return ( (typeof x !== 'undefined') &&
	     ( x !== null ) );
}

function getDOMValue(name) {
    return document.getElementById(name).value
}

function awardPlayerScoreByState(state)
{
    switch ( state ) {
	case STATE_ALERTED: {
	    player.score += SCORE_ALERTED;
	}
	case STATE_CONCERNED: {
	    player.score += SCORE_CONCERNED;
	}
	case STATE_LOSTHIM: {
	    player.score += SCORE_LOSTHIM;
	}
    }
}
<|endoftext|>


<commit_before>/**
 * @file Define Entities
 */
/*#ifndef(UMD)*/
"use strict";
/*global _gpfDefineCheckDefinition*/ // Check the dictionary passed to gpf.define
/*exported _gpfDefine*/ // Shortcut for gpf.define
/*#endif*/

/**
 * Define an entity
 *
 * @param {Object} definition Entity definition
 * @return {Function} Entity constructor
 */
function _gpfDefine (definition) {
    _gpfDefineCheckDefinition(definition);
    return function () {};
}

/**
 * @sameas _gpfDefine
 */
gpf.define = _gpfDefine;
<commit_msg>Documentation<commit_after>/**
 * @file Entity (class, interface, attribute) definition
 */
/*#ifndef(UMD)*/
"use strict";
/*global _gpfDefineCheckDefinition*/ // Check the dictionary passed to gpf.define
/*exported _gpfDefine*/ // Shortcut for gpf.define
/*#endif*/

/**
 * Define an entity
 *
 * @param {Object} definition Entity definition
 * @return {Function} Entity constructor
 */
function _gpfDefine (definition) {
    _gpfDefineCheckDefinition(definition);
    return function () {};
}

/**
 * @sameas _gpfDefine
 */
gpf.define = _gpfDefine;
<|endoftext|>