<commit_before>$(document).ready(function () {
    ///////////////////////////////////
    // Trash & Restore Functionality //
    ///////////////////////////////////
    $(".trash-button, .restore-button").click(function (event) {
        event.preventDefault();
        var button = $(this),
            id = button.data('id'),
            buttonIcon = button.find('i'),
            parentRow = button.closest('tr'),
            pageType,
            message;

        buttonIcon.removeClass("fa-trash-o");
        buttonIcon.addClass("fa-spinner fa-pulse");
        if (window.location.href.indexOf("deleted") >= 0){
            // We're on the deleted page, trying to restore.
            pageType = "trash";
        } else {
            pageType = "active";
        }

        $.ajax({
            method: "POST",
            url: "/visualizations/scotus-mapper" + (pageType == 'trash' ? "/restore/" : "/delete/"),
            data: {pk: id},
            success: function () {
                $('.bootstrap-growl').alert("close");
                parentRow.fadeOut('slow');
                if (pageType == "trash") {
                    message = "Your item was restored successfully."
                } else {
                    message = "Your item was moved to the trash."
                }
                $.bootstrapGrowl(
                    message,
                    {
                        type: "success",
                        align: "center",
                        width: "auto",
                        delay: 2000,
                        allow_dismiss: false,
                        offset: {from: 'top', amount: 80}
                    }
                );
            },
            error: function () {
                buttonIcon.removeClass("fa-spinner fa-pulse");
                buttonIcon.addClass("fa-trash-o");
                if (pageType == "trash") {
                    message = "An error occurred. Unable to restore your item."
                } else {
                    message = "An error occurred. Unable to move your item to the trash."
                }
                $.bootstrapGrowl(
                    message,
                    {
                        type: "danger",
                        align: "center",
                        width: "auto",
                        delay: 2000,
                        allow_dismiss: false,
                        offset: {from: 'top', amount: 80}
                    }
                );
            }
        });
    });
    $(function () {
        // Initialize tooltips on this page.
        $('[data-toggle="tooltip"]').tooltip()
    });

    ///////////////////////////
    // New Viz Functionality //
    ///////////////////////////
    var dateFiledQ = '((dateFiled:[1945-01-01T00:00:00Z TO ' + last_year + 'Z] AND scdb_id:["" TO *]) OR (dateFiled:[' + last_year + 'Z TO *]))';
    var authorityIDs = {};
    var updateAuthorityCache = function (suggestion, callback) {
        // Check if we have the ID in our cache. If so, do nothing. If not,
        // load up the cache.
        if (suggestion.id in authorityIDs) {
            // All good; do nothing; pass
        } else {
            // Get the IDs, add them as a new key.
            // Get a list of the IDs cited by the item and cache it. This cache
            // is needed to do the reverse lookup for authorities.
            $.ajax({
                'method': 'GET',
                'url': "/api/rest/v3/search/",
                'data': {
                    q: "id:" + suggestion.id,
                    format: 'json'
                }
            }).done(function (data) {
                authorityIDs[suggestion.id] = {'ids': data.results[0].cites || []};
                if (authorityIDs[suggestion.id]['ids'].length > 0) {
                    $.ajax({
                        // We have the authority IDs, but we don't know how many
                        // are SCOTUS cases in the right date range.
                        'method': 'GET',
                        'url': "/api/rest/v3/search/",
                        'data': {
                            q: dateFiledQ +
                            " AND id:(" +
                                authorityIDs[suggestion.id].ids.join(" OR ") +
                            ")",
                            court: 'scotus',
                            format: 'json'
                        }
                    }).done(function (data) {
                        authorityIDs[suggestion.id]['count'] = data.count;
                        callback(suggestion);
                    });
                } else {
                    authorityIDs[suggestion.id]['count'] = 0;
                    callback(suggestion);
                }
            });
        }
    };

    var identify = function (obj) {
        // Return the item ID so the system can have a unique id for it
        // in its caches.
        return obj.id;
    };
    var transform = function (response) {
        // Pull the results dict out of the main object.
        return response.results
    };
    var remotePrepare = function (query, settings) {
        // This query is anything with the case name typed in...
        // ...in the supreme court...
        // ...between 1945 and a year ago that has an SCDB id... OR
        // ...in the last year, with or without an SCDB id.
        var params = {
            court: 'scotus',
            q: dateFiledQ,
            format: 'json'
        };
        if ($.trim(query).length > 0) {
            // Add a case name parameter, if the user has typed something.
            params.case_name = "(%QUERY) OR (%QUERY*)".replace(
                /%QUERY/g, $.trim(query));
        }

        var start_id = $('#id_cluster_start').val();
        if ($("#ending-cluster-typeahead-search").is(":focus")) {
            // Pass. No extra params required to do simple search.
        } else if ($("#ending-cluster-typeahead-authorities").is(":focus")) {
            // Append the authority IDs onto the end of the query.
            params.q += " AND id:(" + authorityIDs[start_id].ids.join(" OR ") + ")";
            // Add a cache busting param to defeat bloodhound's cache.
            params.bust = 'authorities';
        } else if ($("#ending-cluster-typeahead-citing").is(":focus")) {
            // Append the cited_by ID onto the end of the query.
            params.q += " AND cites:(" + start_id + ")";
            params.bust = 'citing';
        }

        return settings.url + $.param(params);
    };

    var searchResults = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('caseName'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        sufficient: 21,
        matchAnyQueryToken: true,
        identify: identify,
        remote: {
            url: '/api/rest/v3/search/?',
            prepare: remotePrepare,
            transform: transform
        }
    });

    $('.typeahead').typeahead({
            'hint': false,
            'highlight': true,
            'minLength': 0
        },
        {
            display: function (obj) {
                // Make a nice concatenation of citations, case name and year.
                var parts = [obj.caseName];
                if (obj.dateFiled) {
                    parts.push(new Date(obj.dateFiled).getUTCFullYear());
                }
                if (obj.citation) {
                    parts.push(obj.citation.join(", "));
                }
                return parts.join(" – ");
            },
            limit: 19,  // Must be less than the 'sufficient' param in searchResults.
            source: searchResults
        }
    );

    $('#starting-cluster-typeahead').bind(
        'typeahead:select',
        function (ev, suggestion) {
            updateAuthorityCache(suggestion, function(suggestion) {
                $('.authority-count').text("(" + authorityIDs[suggestion.id].count + ")");
                $('input[disabled="disabled"]').prop('disabled', false);
            });
            $('#id_cluster_start').val(suggestion.id);
            $('.first-selection').text(suggestion.caseNameShort || suggestion.caseName);
            // Clear bloodhound, in case somebody selects a first case, then
            // loads authorities for it, then selects a new first case. In that
            // instance, we'll need the old authorities to be nuked.
            searchResults.clear();
            searchResults.clearRemoteCache();
            searchResults.clearPrefetchCache();
        });
    $('.ending-typeahead').bind(
        'typeahead:select',
        function (ev, suggestion) {
            $('#id_cluster_end').val(suggestion.id);
        });
    $('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
        $('.ending-typeahead').val("");
    });

    // Extra options JS
    $('#more').click(function(e){
        $('#center-buttons').addClass('hidden');
        $('#extra-options').removeClass('hidden');
    });
});
<commit_msg>Should begin providing default results -- experimental though.<commit_after>$(document).ready(function () {
    ///////////////////////////////////
    // Trash & Restore Functionality //
    ///////////////////////////////////
    $(".trash-button, .restore-button").click(function (event) {
        event.preventDefault();
        var button = $(this),
            id = button.data('id'),
            buttonIcon = button.find('i'),
            parentRow = button.closest('tr'),
            pageType,
            message;

        buttonIcon.removeClass("fa-trash-o");
        buttonIcon.addClass("fa-spinner fa-pulse");
        if (window.location.href.indexOf("deleted") >= 0){
            // We're on the deleted page, trying to restore.
            pageType = "trash";
        } else {
            pageType = "active";
        }

        $.ajax({
            method: "POST",
            url: "/visualizations/scotus-mapper" + (pageType == 'trash' ? "/restore/" : "/delete/"),
            data: {pk: id},
            success: function () {
                $('.bootstrap-growl').alert("close");
                parentRow.fadeOut('slow');
                if (pageType == "trash") {
                    message = "Your item was restored successfully."
                } else {
                    message = "Your item was moved to the trash."
                }
                $.bootstrapGrowl(
                    message,
                    {
                        type: "success",
                        align: "center",
                        width: "auto",
                        delay: 2000,
                        allow_dismiss: false,
                        offset: {from: 'top', amount: 80}
                    }
                );
            },
            error: function () {
                buttonIcon.removeClass("fa-spinner fa-pulse");
                buttonIcon.addClass("fa-trash-o");
                if (pageType == "trash") {
                    message = "An error occurred. Unable to restore your item."
                } else {
                    message = "An error occurred. Unable to move your item to the trash."
                }
                $.bootstrapGrowl(
                    message,
                    {
                        type: "danger",
                        align: "center",
                        width: "auto",
                        delay: 2000,
                        allow_dismiss: false,
                        offset: {from: 'top', amount: 80}
                    }
                );
            }
        });
    });
    $(function () {
        // Initialize tooltips on this page.
        $('[data-toggle="tooltip"]').tooltip()
    });

    ///////////////////////////
    // New Viz Functionality //
    ///////////////////////////
    var dateFiledQ = '((dateFiled:[1945-01-01T00:00:00Z TO ' + last_year + 'Z] AND scdb_id:["" TO *]) OR (dateFiled:[' + last_year + 'Z TO *]))';
    var authorityIDs = {};
    var updateAuthorityCache = function (suggestion, callback) {
        // Check if we have the ID in our cache. If so, do nothing. If not,
        // load up the cache.
        if (suggestion.id in authorityIDs) {
            // All good; do nothing; pass
        } else {
            // Get the IDs, add them as a new key.
            // Get a list of the IDs cited by the item and cache it. This cache
            // is needed to do the reverse lookup for authorities.
            $.ajax({
                'method': 'GET',
                'url': "/api/rest/v3/search/",
                'data': {
                    q: "id:" + suggestion.id,
                    format: 'json'
                }
            }).done(function (data) {
                authorityIDs[suggestion.id] = {'ids': data.results[0].cites || []};
                if (authorityIDs[suggestion.id]['ids'].length > 0) {
                    $.ajax({
                        // We have the authority IDs, but we don't know how many
                        // are SCOTUS cases in the right date range.
                        'method': 'GET',
                        'url': "/api/rest/v3/search/",
                        'data': {
                            q: dateFiledQ +
                            " AND id:(" +
                                authorityIDs[suggestion.id].ids.join(" OR ") +
                            ")",
                            court: 'scotus',
                            format: 'json'
                        }
                    }).done(function (data) {
                        authorityIDs[suggestion.id]['count'] = data.count;
                        callback(suggestion);
                    });
                } else {
                    authorityIDs[suggestion.id]['count'] = 0;
                    callback(suggestion);
                }
            });
        }
    };

    var identify = function (obj) {
        // Return the item ID so the system can have a unique id for it
        // in its caches.
        return obj.id;
    };
    var transform = function (response) {
        // Pull the results dict out of the main object.
        return response.results
    };
    var remotePrepare = function (query, settings) {
        // This query is anything with the case name typed in...
        // ...in the supreme court...
        // ...between 1945 and a year ago that has an SCDB id... OR
        // ...in the last year, with or without an SCDB id.
        var params = {
            court: 'scotus',
            q: dateFiledQ,
            format: 'json'
        };
        if ($.trim(query).length > 0) {
            // Add a case name parameter, if the user has typed something.
            params.case_name = "(%QUERY) OR (%QUERY*)".replace(
                /%QUERY/g, $.trim(query));
        }

        var start_id = $('#id_cluster_start').val();
        if ($("#ending-cluster-typeahead-search").is(":focus")) {
            // Pass. No extra params required to do simple search.
        } else if ($("#ending-cluster-typeahead-authorities").is(":focus")) {
            // Append the authority IDs onto the end of the query.
            params.q += " AND id:(" + authorityIDs[start_id].ids.join(" OR ") + ")";
            // Add a cache busting param to defeat bloodhound's cache.
            params.bust = 'authorities';
        } else if ($("#ending-cluster-typeahead-citing").is(":focus")) {
            // Append the cited_by ID onto the end of the query.
            params.q += " AND cites:(" + start_id + ")";
            params.bust = 'citing';
        }

        return settings.url + $.param(params);
    };

    var searchResults = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('caseName'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        sufficient: 21,
        matchAnyQueryToken: true,
        identify: identify,
        remote: {
            url: '/api/rest/v3/search/?',
            prepare: remotePrepare,
            transform: transform
        }
    });

    $('.typeahead').typeahead({
            'hint': false,
            'highlight': true,
            'minLength': 0
        },
        {
            display: function (obj) {
                // Make a nice concatenation of citations, case name and year.
                var parts = [obj.caseName];
                if (obj.dateFiled) {
                    parts.push(new Date(obj.dateFiled).getUTCFullYear());
                }
                if (obj.citation) {
                    parts.push(obj.citation.join(", "));
                }
                return parts.join(" – ");
            },
            limit: 19,  // Must be less than the 'sufficient' param in searchResults.
            source: searchResults
        }
    );

    $('#starting-cluster-typeahead').bind(
        'typeahead:select',
        function (ev, suggestion) {
            updateAuthorityCache(suggestion, function(suggestion) {
                $('.authority-count').text("(" + authorityIDs[suggestion.id].count + ")");
                $('input[disabled="disabled"]').prop('disabled', false);
            });
            $('#id_cluster_start').val(suggestion.id);
            $('.first-selection').text(suggestion.caseNameShort || suggestion.caseName);
            // Clear bloodhound, in case somebody selects a first case, then
            // loads authorities for it, then selects a new first case. In that
            // instance, we'll need the old authorities to be nuked.
            searchResults.clear();
            searchResults.clearRemoteCache();
            searchResults.clearPrefetchCache();
        });
    $('.ending-typeahead').bind(
        'typeahead:select',
        function (ev, suggestion) {
            $('#id_cluster_end').val(suggestion.id);
        });
    $('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
        $('.ending-typeahead').typeahead('val', "");
    });

    // Extra options JS
    $('#more').click(function(e){
        $('#center-buttons').addClass('hidden');
        $('#extra-options').removeClass('hidden');
    });
});
<|endoftext|>


<commit_before>"use strict";
var assert = require('assert');

var Suit = {
  Spades: 1,
  Diamonds: 2,
  Clubs: 3,
  Hearts: 4
};

var Deck = function() {
  return this;
};

var Card = function(suit,value) {
  this._suit = suit;
  this._value = value;

  Card.prototype.suit = function() {
    return this._suit;
  };

  Card.prototype.value = function() {
    return this._value;
  };

  return this;
};

describe('klondike', function() {
  describe('card', function() {
    it('has a suit and a value', function() {
      var card = new Card(Suit.Spades,1);
      assert.equal(Suit.Spades, card.suit());
      assert.equal(1, card.value());
    });
  });

  describe('deck', function() {
    it('consists of 52 cards', function() {
      var deck = new Deck();
    });
  });

  describe('stack', function() {
    it('is a concept', function() {
      assert(new Stack().empty());
    });
  });

});
<commit_msg>simplest possible pass<commit_after>"use strict";
var assert = require('assert');

var Suit = {
  Spades: 1,
  Diamonds: 2,
  Clubs: 3,
  Hearts: 4
};

var Stack = function() {
  Stack.prototype.empty = function() {
    return true;
  };

  return this;
};

var Deck = function() {
  return this;
};

var Card = function(suit,value) {
  this._suit = suit;
  this._value = value;

  Card.prototype.suit = function() {
    return this._suit;
  };

  Card.prototype.value = function() {
    return this._value;
  };

  return this;
};

describe('klondike', function() {
  describe('card', function() {
    it('has a suit and a value', function() {
      var card = new Card(Suit.Spades,1);
      assert.equal(Suit.Spades, card.suit());
      assert.equal(1, card.value());
    });
  });

  describe('deck', function() {
    it('consists of 52 cards', function() {
      var deck = new Deck();
    });
  });

  describe('stack', function() {
    it('is a concept', function() {
      assert(new Stack().empty());
    });
  });

});
<|endoftext|>


<commit_before>/* Import mongoose and define any variables needed to create the schema */
var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

/* Create your schema */
var teamSchema = new Schema({
  name: {
    type: String,
    required: true,
    unique: true
  },
  code: {
    type: Number,
    required: true
  },
  created_at: Date,
  updated_at: Date
});

/* create a 'pre' function that adds the updated_at (and created_at if not already there) property */
teamSchema.pre('save', function(next) {
  var currentTime = new Date;
  this.updated_at = currentTime;
  if(!this.created_at)
  {
    this.created_at = currentTime;
  }
  next();
});

/* Use your schema to instantiate a Mongoose model */
var Team = mongoose.model('Team', teamSchema);

/* Export the model to make it avaiable to other parts of your Node application */
module.exports = Team;

<commit_msg>Delete team-registration.server.model.js<commit_after><|endoftext|>


<commit_before>(function($) {
    "use strict";

    try {

        Object.defineProperties($, {
            unit: {
                value: function(number) {
                    var
                        pattern = /[^0-9\.]+/;

                    return number.match(pattern)[0];
                }
            },

            // usage: (m)[".."](n)
            '..': {
                value: function(until, step) {
                    if (typeof step != "number") {step = 1;}

                    var
                        range = [],
                        self = this;

                    while (self <= until) {
                        range.push(self);
                        self += step;
                    }

                    return range;
                }
            }
        });

    } catch(e) {}

})(Number);
<commit_msg>fix number Range<commit_after>(function($) {
    "use strict";

    try {

        Object.defineProperties($, {
            unit: {
                value: function(number) {
                    var
                        pattern = /[^0-9\.]+/;

                    return number.match(pattern)[0];
                }
            }
        });

        Object.defineProperties($.prototype, {
            // usage: (m)[".."](n)
            '..': {
                value: function(until, step) {
                    if (typeof step != "number") {step = 1;}

                    var
                        range = [],
                        self = this;

                    while (self <= until) {
                        range.push(self);
                        self += step;
                    }

                    return range;
                }
            }
        });

    } catch(e) {}

})(Number);
<|endoftext|>


<commit_before>var util = require('util');
var path = require('path');

var AbstractFile = require('./abstract_file').AbstractFile;

var VirtualFile = function (path) {
  AbstractFile.apply(this);

  this._path = path;
};

util.inherits(VirtualFile, AbstractFile);

VirtualFile.prototype.getRealPath = function () {
  return this._path;
};

exports.VirtualFile = VirtualFile;
<commit_msg>[FIX] Correct BuiltinFile name<commit_after>var util = require('util');
var path = require('path');

var AbstractFile = require('./abstract_file').AbstractFile;

var BuiltinFile = function (path) {
  AbstractFile.apply(this);

  this._path = path;
};

util.inherits(BuiltinFile, AbstractFile);

BuiltinFile.prototype.getRealPath = function () {
  return this._path;
};

exports.BuiltinFile = BuiltinFile;
<|endoftext|>


<commit_before>import store from '../store.js';
import AppConstants  from '../constants/AppConstants';
import app from '../lib/app';

const add = (notificationData) => {
  if (app.config.get('displayNotifications')) {
    const notification =
            new Notification(
        notificationData.title,
        {
          body: notificationData.body,
          icon: notificationData.icon,
          silent: true,
        }
      );

    notification.onclick = () => {
      app.browserWindows.main.show();
      app.browserWindows.main.focus();
    };

    store.dispatch({
      type   : AppConstants.APP_NOTIFICATION_NEW,
      notification,
    });
  }
};

export default {
  add,
};
<commit_msg>When songs are skipped, the notification gets updated.<commit_after>import store from '../store.js';
import AppConstants  from '../constants/AppConstants';
import app from '../lib/app';

const add = (notificationData) => {
  if (app.config.get('displayNotifications')) {
    const notification =
            new Notification(
        notificationData.title,
        {
          body: notificationData.body,
          icon: notificationData.icon,
          silent: true,
          tag: 'onlyOneNotification',
        }
      );

    notification.onclick = () => {
      app.browserWindows.main.show();
      app.browserWindows.main.focus();
    };

    store.dispatch({
      type   : AppConstants.APP_NOTIFICATION_NEW,
      notification,
    });
  }
};

export default {
  add,
};
<|endoftext|>


<commit_before>// Copyright 2014 Mike Tsao <mike@sowbug.com>

// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

'use strict';

function Address() {
  this.init = function() {
    this.address = undefined;
    this.balance = 0;
    this.index = 0;
    this.key = undefined;
    this.path = undefined;
    this.tx_count = 0;
  };
  this.init();

  this.toStorableObject = function() {
    var o = {};
    o.address = this.address;
    o.balance = this.balance;
    o.index = this.index;
    o.path = this.path;
    o.tx_count = this.tx_count;

    return o;
  };
}

Address.fromStorableObject = function(o) {
  var s = new Address();

  if (o.address != undefined) s.address = o.address;
  if (o.balance != undefined) s.balance = o.balance;
  if (o.index != undefined) s.index = o.index;
  if (o.path != undefined) s.path = o.path;
  if (o.tx_count != undefined) s.tx_count = o.tx_count;

  // Items that shouldn't be passed from a truly persisted object, but
  // that might be serialized in-memory.
  if (o.key != undefined) s.key = o.key;

  return s;
};
<commit_msg>obsolete<commit_after><|endoftext|>


<commit_before>$(document).ready(function () {
    ///////////////////////////////////
    // Trash & Restore Functionality //
    ///////////////////////////////////
    $(".trash-button, .restore-button").click(function (event) {
        event.preventDefault();
        var button = $(this),
            id = button.data('id'),
            buttonIcon = button.find('i'),
            parentRow = button.closest('tr'),
            pageType,
            message;

        buttonIcon.removeClass("fa-trash-o");
        buttonIcon.addClass("fa-spinner fa-pulse");
        if (window.location.href.indexOf("deleted") >= 0){
            // We're on the deleted page, trying to restore.
            pageType = "trash";
        } else {
            pageType = "active";
        }

        $.ajax({
            method: "POST",
            url: "/visualizations/scotus-mapper" + (pageType == 'trash' ? "/restore/" : "/delete/"),
            data: {pk: id},
            success: function () {
                $('.bootstrap-growl').alert("close");
                parentRow.fadeOut('slow');
                if (pageType == "trash") {
                    message = "Your item was restored successfully."
                } else {
                    message = "Your item was moved to the trash."
                }
                $.bootstrapGrowl(
                    message,
                    {
                        type: "success",
                        align: "center",
                        width: "auto",
                        delay: 2000,
                        allow_dismiss: false,
                        offset: {from: 'top', amount: 80}
                    }
                );
            },
            error: function () {
                buttonIcon.removeClass("fa-spinner fa-pulse");
                buttonIcon.addClass("fa-trash-o");
                if (pageType == "trash") {
                    message = "An error occurred. Unable to restore your item."
                } else {
                    message = "An error occurred. Unable to move your item to the trash."
                }
                $.bootstrapGrowl(
                    message,
                    {
                        type: "danger",
                        align: "center",
                        width: "auto",
                        delay: 2000,
                        allow_dismiss: false,
                        offset: {from: 'top', amount: 80}
                    }
                );
            }
        });
    });
    $(function () {
        // Initialize tooltips on this page.
        $('[data-toggle="tooltip"]').tooltip()
    });

    ///////////////////////////
    // New Viz Functionality //
    ///////////////////////////
    var dateFiledQ = '((dateFiled:[1945-01-01T00:00:00Z TO ' + last_year + 'Z] AND scdb_id:["" TO *]) OR (dateFiled:[' + last_year + 'Z TO *]))';
    var authorityIDs = {};
    var updateAuthorityCache = function (suggestion, callback) {
        // Check if we have the ID in our cache. If so, do nothing. If not,
        // load up the cache.
        if (suggestion.id in authorityIDs) {
            // All good; do nothing; pass
        } else {
            // Get the IDs, add them as a new key.
            // Get a list of the IDs cited by the item and cache it. This cache
            // is needed to do the reverse lookup for authorities.
            $.ajax({
                'method': 'GET',
                'url': "/api/rest/v3/search/",
                'data': {
                    q: "id:" + suggestion.id,
                    format: 'json'
                }
            }).done(function (data) {
                authorityIDs[suggestion.id] = {'ids': data.results[0].cites || []};
                if (authorityIDs[suggestion.id]['ids'].length > 0) {
                    $.ajax({
                        // We have the authority IDs, but we don't know how many
                        // are SCOTUS cases in the right date range.
                        'method': 'GET',
                        'url': "/api/rest/v3/search/",
                        'data': {
                            q: dateFiledQ +
                            " AND id:(" +
                                authorityIDs[suggestion.id].ids.join(" OR ") +
                            ")",
                            court: 'scotus',
                            format: 'json'
                        }
                    }).done(function (data) {
                        authorityIDs[suggestion.id]['count'] = data.count;
                        callback(suggestion);
                    });
                } else {
                    authorityIDs[suggestion.id]['count'] = 0;
                    callback(suggestion);
                }
            });
        }
    };

    var identify = function (obj) {
        // Return the item ID so the system can have a unique id for it
        // in its caches.
        return obj.id;
    };
    var transform = function (response) {
        // Pull the results dict out of the main object.
        return response.results
    };
    var remotePrepare = function (query, settings) {
        // This query is anything with the case name typed in...
        // ...in the supreme court...
        // ...between 1945 and a year ago that has an SCDB id... OR
        // ...in the last year, with or without an SCDB id.
        var params = {
            court: 'scotus',
            q: dateFiledQ,
            format: 'json'
        };
        if (query.length > 0) {
            // Add a case name parameter, if the user has typed something.
            params.case_name = "(%QUERY) OR (%QUERY*)".replace(
                /%QUERY/g, $.trim(query));
        }

        var start_id = $('#id_cluster_start').val();
        if ($("#ending-cluster-typeahead-search").is(":focus")) {
            // Pass. No extra params required to do simple search.
        } else if ($("#ending-cluster-typeahead-authorities").is(":focus")) {
            // Append the authority IDs onto the end of the query.
            params.q += " AND id:(" + authorityIDs[start_id].ids.join(" OR ") + ")";
            // Add a cache busting param to defeat bloodhound's cache.
            params.bust = 'authorities';
        } else if ($("#ending-cluster-typeahead-citing").is(":focus")) {
            // Append the cited_by ID onto the end of the query.
            params.q += " AND cites:(" + start_id + ")";
            params.bust = 'citing';
        }

        return settings.url + $.param(params);
    };

    var searchResults = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('caseName'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        sufficient: 21,
        matchAnyQueryToken: true,
        identify: identify,
        remote: {
            url: '/api/rest/v3/search/?',
            prepare: remotePrepare,
            transform: transform
        }
    });

    $('.typeahead').typeahead({
            'hint': false,
            'highlight': true,
            'minLength': 0
        },
        {
            display: function (obj) {
                // Make a nice concatenation of citations, case name and year.
                var parts = [obj.caseName];
                if (obj.dateFiled) {
                    parts.push(new Date(obj.dateFiled).getUTCFullYear());
                }
                if (obj.citation) {
                    parts.push(obj.citation.join(", "));
                }
                return parts.join(" – ");
            },
            limit: 19,  // Must be less than the 'sufficient' param in searchResults.
            source: searchResults
        }
    );

    $('#starting-cluster-typeahead').bind(
        'typeahead:select',
        function (ev, suggestion) {
            updateAuthorityCache(suggestion, function(suggestion) {
                $('.authority-count').text("(" + authorityIDs[suggestion.id].count + ")");
                $('input[disabled="disabled"]').prop('disabled', false);
            });
            $('#id_cluster_start').val(suggestion.id);
            $('.first-selection').text(suggestion.caseNameShort || suggestion.caseName);
            // Clear bloodhound, in case somebody selects a first case, then
            // loads authorities for it, then selects a new first case. In that
            // instance, we'll need the old authorities to be nuked.
            searchResults.clear();
        });
    $('.ending-typeahead').bind(
        'typeahead:select',
        function (ev, suggestion) {
            $('#id_cluster_end').val(suggestion.id);
        });
    $('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
        $('.ending-typeahead').val("");
    });

    // Extra options JS
    $('#more').click(function(e){
        $('#center-buttons').addClass('hidden');
        $('#extra-options').removeClass('hidden');
    });
});
<commit_msg>Should begin providing default results -- experimental though.<commit_after>$(document).ready(function () {
    ///////////////////////////////////
    // Trash & Restore Functionality //
    ///////////////////////////////////
    $(".trash-button, .restore-button").click(function (event) {
        event.preventDefault();
        var button = $(this),
            id = button.data('id'),
            buttonIcon = button.find('i'),
            parentRow = button.closest('tr'),
            pageType,
            message;

        buttonIcon.removeClass("fa-trash-o");
        buttonIcon.addClass("fa-spinner fa-pulse");
        if (window.location.href.indexOf("deleted") >= 0){
            // We're on the deleted page, trying to restore.
            pageType = "trash";
        } else {
            pageType = "active";
        }

        $.ajax({
            method: "POST",
            url: "/visualizations/scotus-mapper" + (pageType == 'trash' ? "/restore/" : "/delete/"),
            data: {pk: id},
            success: function () {
                $('.bootstrap-growl').alert("close");
                parentRow.fadeOut('slow');
                if (pageType == "trash") {
                    message = "Your item was restored successfully."
                } else {
                    message = "Your item was moved to the trash."
                }
                $.bootstrapGrowl(
                    message,
                    {
                        type: "success",
                        align: "center",
                        width: "auto",
                        delay: 2000,
                        allow_dismiss: false,
                        offset: {from: 'top', amount: 80}
                    }
                );
            },
            error: function () {
                buttonIcon.removeClass("fa-spinner fa-pulse");
                buttonIcon.addClass("fa-trash-o");
                if (pageType == "trash") {
                    message = "An error occurred. Unable to restore your item."
                } else {
                    message = "An error occurred. Unable to move your item to the trash."
                }
                $.bootstrapGrowl(
                    message,
                    {
                        type: "danger",
                        align: "center",
                        width: "auto",
                        delay: 2000,
                        allow_dismiss: false,
                        offset: {from: 'top', amount: 80}
                    }
                );
            }
        });
    });
    $(function () {
        // Initialize tooltips on this page.
        $('[data-toggle="tooltip"]').tooltip()
    });

    ///////////////////////////
    // New Viz Functionality //
    ///////////////////////////
    var dateFiledQ = '((dateFiled:[1945-01-01T00:00:00Z TO ' + last_year + 'Z] AND scdb_id:["" TO *]) OR (dateFiled:[' + last_year + 'Z TO *]))';
    var authorityIDs = {};
    var updateAuthorityCache = function (suggestion, callback) {
        // Check if we have the ID in our cache. If so, do nothing. If not,
        // load up the cache.
        if (suggestion.id in authorityIDs) {
            // All good; do nothing; pass
        } else {
            // Get the IDs, add them as a new key.
            // Get a list of the IDs cited by the item and cache it. This cache
            // is needed to do the reverse lookup for authorities.
            $.ajax({
                'method': 'GET',
                'url': "/api/rest/v3/search/",
                'data': {
                    q: "id:" + suggestion.id,
                    format: 'json'
                }
            }).done(function (data) {
                authorityIDs[suggestion.id] = {'ids': data.results[0].cites || []};
                if (authorityIDs[suggestion.id]['ids'].length > 0) {
                    $.ajax({
                        // We have the authority IDs, but we don't know how many
                        // are SCOTUS cases in the right date range.
                        'method': 'GET',
                        'url': "/api/rest/v3/search/",
                        'data': {
                            q: dateFiledQ +
                            " AND id:(" +
                                authorityIDs[suggestion.id].ids.join(" OR ") +
                            ")",
                            court: 'scotus',
                            format: 'json'
                        }
                    }).done(function (data) {
                        authorityIDs[suggestion.id]['count'] = data.count;
                        callback(suggestion);
                    });
                } else {
                    authorityIDs[suggestion.id]['count'] = 0;
                    callback(suggestion);
                }
            });
        }
    };

    var identify = function (obj) {
        // Return the item ID so the system can have a unique id for it
        // in its caches.
        return obj.id;
    };
    var transform = function (response) {
        // Pull the results dict out of the main object.
        return response.results
    };
    var remotePrepare = function (query, settings) {
        // This query is anything with the case name typed in...
        // ...in the supreme court...
        // ...between 1945 and a year ago that has an SCDB id... OR
        // ...in the last year, with or without an SCDB id.
        var params = {
            court: 'scotus',
            q: dateFiledQ,
            format: 'json'
        };
        if (query.length > 0) {
            // Add a case name parameter, if the user has typed something.
            params.case_name = "(%QUERY) OR (%QUERY*)".replace(
                /%QUERY/g, $.trim(query));
        }

        var start_id = $('#id_cluster_start').val();
        if ($("#ending-cluster-typeahead-search").is(":focus")) {
            // Pass. No extra params required to do simple search.
        } else if ($("#ending-cluster-typeahead-authorities").is(":focus")) {
            // Append the authority IDs onto the end of the query.
            params.q += " AND id:(" + authorityIDs[start_id].ids.join(" OR ") + ")";
            // Add a cache busting param to defeat bloodhound's cache.
            params.bust = 'authorities';
        } else if ($("#ending-cluster-typeahead-citing").is(":focus")) {
            // Append the cited_by ID onto the end of the query.
            params.q += " AND cites:(" + start_id + ")";
            params.bust = 'citing';
        }

        return settings.url + $.param(params);
    };

    var searchResults = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('caseName'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        sufficient: 21,
        matchAnyQueryToken: true,
        identify: identify,
        remote: {
            url: '/api/rest/v3/search/?',
            prepare: remotePrepare,
            transform: transform
        }
    });

    $('.typeahead').typeahead({
            'hint': false,
            'highlight': true,
            'minLength': 0
        },
        {
            display: function (obj) {
                // Make a nice concatenation of citations, case name and year.
                var parts = [obj.caseName];
                if (obj.dateFiled) {
                    parts.push(new Date(obj.dateFiled).getUTCFullYear());
                }
                if (obj.citation) {
                    parts.push(obj.citation.join(", "));
                }
                return parts.join(" – ");
            },
            limit: 19,  // Must be less than the 'sufficient' param in searchResults.
            source: searchResults
        }
    );

    $('#starting-cluster-typeahead').bind(
        'typeahead:select',
        function (ev, suggestion) {
            updateAuthorityCache(suggestion, function(suggestion) {
                $('.authority-count').text("(" + authorityIDs[suggestion.id].count + ")");
                $('input[disabled="disabled"]').prop('disabled', false);
            });
            $('#id_cluster_start').val(suggestion.id);
            $('.first-selection').text(suggestion.caseNameShort || suggestion.caseName);
            // Clear bloodhound, in case somebody selects a first case, then
            // loads authorities for it, then selects a new first case. In that
            // instance, we'll need the old authorities to be nuked.
            searchResults.clear();
            searchResults.clearRemoteCache();
            searchResults.clearPrefetchCache();
        });
    $('.ending-typeahead').bind(
        'typeahead:select',
        function (ev, suggestion) {
            $('#id_cluster_end').val(suggestion.id);
        });
    $('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
        $('.ending-typeahead').val("");
    });

    // Extra options JS
    $('#more').click(function(e){
        $('#center-buttons').addClass('hidden');
        $('#extra-options').removeClass('hidden');
    });
});
<|endoftext|>


<commit_before>import _ from 'lodash';
import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { Link } from 'react-router-dom';
import queryString from 'query-string';
import Badge from '@folio/stripes-components/lib/Badge';
import { Accordion } from '@folio/stripes-components/lib/Accordion';
import Icon from '@folio/stripes-components/lib/Icon';
import List from '@folio/stripes-components/lib/List';

/**
 * User-details "Loans" accordian pane.
 *
 * Show links to the open- and closed-loans in the body; include the
 * number of open-loans in the preview.
 */
class UserLoans extends React.Component {
  static propTypes = {
    resources: PropTypes.shape({
      loansHistory: PropTypes.shape({
        records: PropTypes.arrayOf(PropTypes.object),
      }),
    }),
    onClickViewOpenLoans: PropTypes.func.isRequired,
    onClickViewClosedLoans: PropTypes.func.isRequired,
    accordionId: PropTypes.string,
    expanded: PropTypes.bool,
    onToggle: PropTypes.func,
    location: PropTypes.shape({
      search: PropTypes.string,
      pathname: PropTypes.string,
    }),
  };

  // "limit=1" on the openLoansCount and closedLoansCount fields is a hack
  // to get at the "totalRecords" field without pulling down too much other
  // data. Instead we should be able to construct a query to retrieve this
  // metadata directly without pulling any item records.
  // see https://issues.folio.org/browse/FOLIO-773
  static manifest = Object.freeze({
    loansHistory: {
      type: 'okapi',
      records: 'loans',
      GET: {
        path: 'circulation/loans?query=(userId==:{id})&limit=100',
      },
    },
    openLoansCount: {
      type: 'okapi',
      GET: {
        path: 'circulation/loans?query=(userId==:{id} and status.name<>Closed)&limit=1',
      },
    },
    closedLoansCount: {
      type: 'okapi',
      GET: {
        path: 'circulation/loans?query=(userId==:{id} and status.name==Closed)&limit=1',
      },
    },
    userid: {},
  });

  render() {
    const resources = this.props.resources;
    const openLoansTotal = _.get(resources.openLoansCount, ['records', '0', 'totalRecords'], 0);
    const closedLoansTotal = _.get(resources.closedLoansCount, ['records', '0', 'totalRecords'], 0);
    const { expanded, onToggle, accordionId } = this.props;

    const openLoansCount = (_.get(resources.openLoansCount, ['isPending'], true)) ? -1 : openLoansTotal;
    const closedLoansCount = (_.get(resources.closedLoansCount, ['isPending'], true)) ? -1 : closedLoansTotal;

    const loansLoaded = openLoansCount >= 0 && closedLoansCount >= 0;
    const displayWhenClosed = loansLoaded ? (<Badge>{openLoansCount}</Badge>) : (<Icon icon="spinner-ellipsis" width="10px" />);

    const query = this.props.location.search ? queryString.parse(this.props.location.search) : {};

    return (
      <Accordion
        open={expanded}
        id={accordionId}
        onToggle={onToggle}
        label={<FormattedMessage id="ui-users.loans.title" />}
        displayWhenClosed={displayWhenClosed}
      >
        {loansLoaded ?
          <List
            listStyle="bullets"
            itemFormatter={(item, index) => (

                <Link
                  id={item.id}
                  to={`${this.props.location.pathname}?${queryString.stringify({ ...query, layer: item.layer })}`}
                  onClick={item.onClick}
                >
                  {item.label}
                  <FormattedMessage id={item.formattedMessageId} />
                </Link>

)}
            items={[
              {
                id: 'clickable-viewcurrentloans',
                onClick: this.props.onClickViewOpenLoans,
                label: openLoansCount,
                formattedMessageId: 'ui-users.loans.openLoans',
                layer: 'open-loans',
              },
              {
                id: 'clickable-viewclosedloans',
                onClick: this.props.onClickViewClosedLoans,
                label: closedLoansCount,
                formattedMessageId: 'ui-users.loans.closedLoans',
                layer: 'closed-loans',
              },
            ]}
          /> : <Icon icon="spinner-ellipsis" width="10px" />
        }
      </Accordion>
    );
  }
}

export default UserLoans;
<commit_msg>Fix text typo<commit_after>import _ from 'lodash';
import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { Link } from 'react-router-dom';
import queryString from 'query-string';
import Badge from '@folio/stripes-components/lib/Badge';
import { Accordion } from '@folio/stripes-components/lib/Accordion';
import Icon from '@folio/stripes-components/lib/Icon';
import List from '@folio/stripes-components/lib/List';

/**
 * User-details "Loans" accordion pane.
 *
 * Show links to the open- and closed-loans in the body; include the
 * number of open-loans in the preview.
 */
class UserLoans extends React.Component {
  static propTypes = {
    resources: PropTypes.shape({
      loansHistory: PropTypes.shape({
        records: PropTypes.arrayOf(PropTypes.object),
      }),
    }),
    onClickViewOpenLoans: PropTypes.func.isRequired,
    onClickViewClosedLoans: PropTypes.func.isRequired,
    accordionId: PropTypes.string,
    expanded: PropTypes.bool,
    onToggle: PropTypes.func,
    location: PropTypes.shape({
      search: PropTypes.string,
      pathname: PropTypes.string,
    }),
  };

  // "limit=1" on the openLoansCount and closedLoansCount fields is a hack
  // to get at the "totalRecords" field without pulling down too much other
  // data. Instead we should be able to construct a query to retrieve this
  // metadata directly without pulling any item records.
  // see https://issues.folio.org/browse/FOLIO-773
  static manifest = Object.freeze({
    loansHistory: {
      type: 'okapi',
      records: 'loans',
      GET: {
        path: 'circulation/loans?query=(userId==:{id})&limit=100',
      },
    },
    openLoansCount: {
      type: 'okapi',
      GET: {
        path: 'circulation/loans?query=(userId==:{id} and status.name<>Closed)&limit=1',
      },
    },
    closedLoansCount: {
      type: 'okapi',
      GET: {
        path: 'circulation/loans?query=(userId==:{id} and status.name==Closed)&limit=1',
      },
    },
    userid: {},
  });

  render() {
    const resources = this.props.resources;
    const openLoansTotal = _.get(resources.openLoansCount, ['records', '0', 'totalRecords'], 0);
    const closedLoansTotal = _.get(resources.closedLoansCount, ['records', '0', 'totalRecords'], 0);
    const { expanded, onToggle, accordionId } = this.props;

    const openLoansCount = (_.get(resources.openLoansCount, ['isPending'], true)) ? -1 : openLoansTotal;
    const closedLoansCount = (_.get(resources.closedLoansCount, ['isPending'], true)) ? -1 : closedLoansTotal;

    const loansLoaded = openLoansCount >= 0 && closedLoansCount >= 0;
    const displayWhenClosed = loansLoaded ? (<Badge>{openLoansCount}</Badge>) : (<Icon icon="spinner-ellipsis" width="10px" />);

    const query = this.props.location.search ? queryString.parse(this.props.location.search) : {};

    return (
      <Accordion
        open={expanded}
        id={accordionId}
        onToggle={onToggle}
        label={<FormattedMessage id="ui-users.loans.title" />}
        displayWhenClosed={displayWhenClosed}
      >
        {loansLoaded ?
          <List
            listStyle="bullets"
            itemFormatter={(item, index) => (

                <Link
                  id={item.id}
                  to={`${this.props.location.pathname}?${queryString.stringify({ ...query, layer: item.layer })}`}
                  onClick={item.onClick}
                >
                  {item.label}
                  <FormattedMessage id={item.formattedMessageId} />
                </Link>

)}
            items={[
              {
                id: 'clickable-viewcurrentloans',
                onClick: this.props.onClickViewOpenLoans,
                label: openLoansCount,
                formattedMessageId: 'ui-users.loans.openLoans',
                layer: 'open-loans',
              },
              {
                id: 'clickable-viewclosedloans',
                onClick: this.props.onClickViewClosedLoans,
                label: closedLoansCount,
                formattedMessageId: 'ui-users.loans.closedLoans',
                layer: 'closed-loans',
              },
            ]}
          /> : <Icon icon="spinner-ellipsis" width="10px" />
        }
      </Accordion>
    );
  }
}

export default UserLoans;
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2014 Vanderbilt University, All rights reserved.
 *
 * Authors: Robert Kereskenyi
 *          Dana Zhang
 */

define(['js/Panels/ModelEditor/ModelEditorControl',
    'js/Constants',
    'js/NodePropertyNames',
    'widgets/NetLabel/NetLabelWidget.Constants',
    './NetLabelControl.EventHandlers'], function (ModelEditorControl,
                                                  CONSTANTS,
                                                  NodePropertyNames,
                                                  NetLabelWidgetConstants,
                                                  NetLabelControlEventHandlers) {

    "use strict";

    var NetLabelControl;

    NetLabelControl = function (options) {
        ModelEditorControl.call(this, options);
    };

    _.extend(NetLabelControl.prototype, ModelEditorControl.prototype);
    _.extend(NetLabelControl.prototype, NetLabelControlEventHandlers.prototype);

    // todo: return src/dst texts instead -- in the initprop method these changes are made
    NetLabelControl.prototype.getConnectionDescriptor = function (gmeID) {

        var self = this,
            CONSTS =  CONSTANTS, // CONSTANTS can only be loaded by assigning it to a var
            gmeClient = self._client,
            connectionObj = gmeClient.getNode(gmeID),
            name = connectionObj.getAttribute(NodePropertyNames.Attributes.name),
            showAsLabel = connectionObj.getAttribute(NetLabelWidgetConstants.SHOW_AS_LABEL),
            connectionBaseId = connectionObj.getBaseId(),
            connectionBaseObj = gmeClient.getNode(connectionBaseId),
            defaultName = connectionBaseObj.getAttribute(NodePropertyNames.Attributes.name),
            srcID = connectionObj.getPointer(CONSTANTS.POINTER_SOURCE).to,
            dstID = connectionObj.getPointer(CONSTANTS.POINTER_TARGET).to,
            srcObj = gmeClient.getNode(srcID),
            dstObj = gmeClient.getNode(dstID),
            srcParentId = srcObj.getParentId(),
            dstParentId = dstObj.getParentId(),
            srcParentObj = gmeClient.getNode(srcParentId),
            dstParentObj = gmeClient.getNode(dstParentId);

        return {'name': name,
                'defaultName': defaultName,
                'showAsLabel': showAsLabel,
                'srcObj': srcObj,
                'dstObj': dstObj,
                'srcParentObj': srcParentObj,
                'dstParentObj': dstParentObj,
                'srcText': '',
                'dstText': ''};
    };

    return NetLabelControl;
});<commit_msg>GH-18 Passed in utils to widget from controller<commit_after>/*
 * Copyright (C) 2014 Vanderbilt University, All rights reserved.
 *
 * Authors: Robert Kereskenyi
 *          Dana Zhang
 */

define(['js/Panels/ModelEditor/ModelEditorControl',
    'js/Constants',
    'js/NodePropertyNames',
    'widgets/NetLabel/NetLabelWidget.Constants',
    './NetLabelControl.EventHandlers',
    'js/Utils/PreferencesHelper'], function (ModelEditorControl,
                                             CONSTANTS,
                                             NodePropertyNames,
                                             NetLabelWidgetConstants,
                                             NetLabelControlEventHandlers,
                                             PreferencesHelper) {

    "use strict";

    var NetLabelControl;

    NetLabelControl = function (options) {
        ModelEditorControl.call(this, options);
        this.designerCanvas._client = this._client;
    };

    _.extend(NetLabelControl.prototype, ModelEditorControl.prototype);
    _.extend(NetLabelControl.prototype, NetLabelControlEventHandlers.prototype);

    // todo: return src/dst texts instead -- in the initprop method these changes are made
    NetLabelControl.prototype.getConnectionDescriptor = function (gmeID) {

        var self = this,
            CONSTS =  CONSTANTS, // CONSTANTS can only be loaded by assigning it to a var
            gmeClient = self._client,
            connectionObj = gmeClient.getNode(gmeID),
            name = connectionObj.getAttribute(NodePropertyNames.Attributes.name),
            showAsLabel = connectionObj.getAttribute(NetLabelWidgetConstants.SHOW_AS_LABEL),
            connectionBaseId = connectionObj.getBaseId(),
            connectionBaseObj = gmeClient.getNode(connectionBaseId),
            defaultName = connectionBaseObj.getAttribute(NodePropertyNames.Attributes.name),
            srcID = connectionObj.getPointer(CONSTANTS.POINTER_SOURCE).to,
            dstID = connectionObj.getPointer(CONSTANTS.POINTER_TARGET).to,
            srcObj = gmeClient.getNode(srcID),
            dstObj = gmeClient.getNode(dstID),
            srcParentId = srcObj.getParentId(),
            dstParentId = dstObj.getParentId(),
            srcParentObj = gmeClient.getNode(srcParentId),
            dstParentObj = gmeClient.getNode(dstParentId);

        return {'name': name,
                'defaultName': defaultName,
                'showAsLabel': showAsLabel,
                'srcObj': srcObj,
                'dstObj': dstObj,
                'srcParentObj': srcParentObj,
                'dstParentObj': dstParentObj,
                'srcText': '',
                'dstText': ''};
    };

    NetLabelControl.prototype._onLoad = function (gmeID, objD) {
        var uiComponent,
            decClass,
            objDesc,
            sources = [],
            destinations = [],
            getDecoratorTerritoryQueries,
            territoryChanged = false,
            self = this;

        getDecoratorTerritoryQueries = function (decorator) {
            var query,
                entry;

            if (decorator) {
                query = decorator.getTerritoryQuery();

                if (query) {
                    for (entry in query) {
                        if (query.hasOwnProperty(entry)) {
                            self._selfPatterns[entry] = query[entry];
                            territoryChanged = true;
                        }
                    }
                }
            }
        };

        //component loaded
        //we are interested in the load of sub_components of the opened component
        if (this.currentNodeInfo.id !== gmeID) {
            if (objD) {
                if (objD.parentId == this.currentNodeInfo.id) {
                    objDesc = _.extend({}, objD);
                    this._GmeID2ComponentID[gmeID] = [];

                    if (objDesc.kind === "MODEL") {

                        this._GMEModels.push(gmeID);

                        decClass = this._getItemDecorator(objDesc.decorator);

                        objDesc.decoratorClass = decClass;
                        objDesc.control = this;
                        objDesc.metaInfo = {};
                        objDesc.metaInfo[CONSTANTS.GME_ID] = gmeID;
                        objDesc.preferencesHelper = PreferencesHelper.getPreferences();
                        objDesc.aspect = this._selectedAspect;

                        uiComponent = this.designerCanvas.createDesignerItem(objDesc);

                        this._GmeID2ComponentID[gmeID].push(uiComponent.id);
                        this._ComponentID2GmeID[uiComponent.id] = gmeID;

                        getDecoratorTerritoryQueries(uiComponent._decoratorInstance);

                    }

                    if (objDesc.kind === "CONNECTION") {

                        this._GMEConnections.push(gmeID);

                        var srcDst = this._getAllSourceDestinationPairsForConnection(objDesc.source, objDesc.target);
                        sources = srcDst.sources;
                        destinations = srcDst.destinations;

                        var k = sources.length;
                        var l = destinations.length;

                        if (k > 0 && l > 0) {
                            while (k--) {
                                while (l--) {
                                    objDesc.srcObjId = sources[k].objId;
                                    objDesc.srcSubCompId = sources[k].subCompId;
                                    objDesc.dstObjId = destinations[l].objId;
                                    objDesc.dstSubCompId = destinations[l].subCompId;
                                    objDesc.reconnectable = true;
                                    objDesc.editable = true;

                                    delete objDesc.source;
                                    delete objDesc.target;

                                    _.extend(objDesc, this.getConnectionDescriptor(gmeID));
                                    uiComponent = this.designerCanvas.createConnection(objDesc);

                                    this.logger.debug('Connection: ' + uiComponent.id + ' for GME object: ' + objDesc.id);

                                    this._GmeID2ComponentID[gmeID].push(uiComponent.id);
                                    this._ComponentID2GmeID[uiComponent.id] = gmeID;
                                }
                            }
                        } else {
                            //the connection is here, but no valid endpoint on canvas
                            //save the connection
                            this._delayedConnections.push(gmeID);
                        }
                    }
                } else {
                    //supposed to be the grandchild of the currently open node
                    //--> load of port
                    /*if(this._GMEModels.indexOf(objD.parentId) !== -1){
                     this._onUpdate(objD.parentId,this._getObjectDescriptor(objD.parentId));
                     }*/
                    this._checkComponentDependency(gmeID, CONSTANTS.TERRITORY_EVENT_LOAD);
                }
            }
        } else {
            //currently opened node
            this._updateSheetName(objD.name);
            this._updateAspects();
        }

        this.designerCanvas._ComponentID2GmeID = this._ComponentID2GmeID;
        return territoryChanged;

    };

    return NetLabelControl;
});<|endoftext|>


<commit_before>/**
 * @description binds model data to an element
 * @example Mold/Test/Lib/Template#binding
 */
Seed({
		name : "Mold.Lib.VDom.Components.MoldBind",
		dna : "component",
		include : [
			"->Mold.DNA.Component"
		],
		directives : [
			{
				at : "attribute",
				name : "mold-bind",
				//watchable : true,
				collect : {
					attribute : [
						"mold-bind"
					]
				}
			}
		]
	},
	function(node, element, collection){
		var path = element.moldModel.path;
		var model = element.moldModel.model;

		var setData = function(data){
			if(element.val() !== data){
				element.val(data);
			}
		}

		var bindingName = collection["mold-bind"];

		var initBinding = function(){

			if(path && model){

				if(~bindingName.indexOf('.')){
					var subPath = bindingName.substring(0, bindingName.indexOf('.'))
					var modelName = bindingName.substring(bindingName.indexOf('.') + 1, bindingName.length);
				}else{
					var modelName = bindingName;
				}
				switch(element.attr('type')){

					case "range":
					case "radio":
					case "checkbox":
						element.on("change", function(){
							console.log("value", element.val())
							model.set(path + "." + collection["mold-bind"], element.val());
						})
						break;

					default :
						element.on("keyup", function(){
							model.set(path + "." + collection["mold-bind"], element.val());
						})
						break;
				}

				if(element.tagName.toLowerCase() === "select"){
					element.on("change", function(){
						console.log("value", element.val())
						model.set(path + "." + collection["mold-bind"], element.val());
					})
				}

				model.on(path + ".changed", function(e){

					setData(e.data[modelName]);
				})

				if(subPath){
					var data = model.get(path + "." + subPath);
				}else{
					var data = model.get(path);
				}

				setData(data[modelName]);
			}
		}

		Mold.watch(element.moldModel, "model", function(name, value, newValue){
			model = newValue;
			initBinding();
		})

		Mold.watch(element.moldModel, "path", function(name, value, newValue){
			path = newValue;
			initBinding();
		})

		initBinding();
	}
);<commit_msg>log removed<commit_after>/**
 * @description binds model data to an element
 * @example Mold/Test/Lib/Template#binding
 */
Seed({
		name : "Mold.Lib.VDom.Components.MoldBind",
		dna : "component",
		include : [
			"->Mold.DNA.Component"
		],
		directives : [
			{
				at : "attribute",
				name : "mold-bind",
				//watchable : true,
				collect : {
					attribute : [
						"mold-bind"
					]
				}
			}
		]
	},
	function(node, element, collection){
		var path = element.moldModel.path;
		var model = element.moldModel.model;

		var setData = function(data){
			if(element.val() !== data){
				element.val(data);
			}
		}

		var bindingName = collection["mold-bind"];

		var initBinding = function(){

			if(path && model){

				if(~bindingName.indexOf('.')){
					var subPath = bindingName.substring(0, bindingName.indexOf('.'))
					var modelName = bindingName.substring(bindingName.indexOf('.') + 1, bindingName.length);
				}else{
					var modelName = bindingName;
				}
				switch(element.attr('type')){

					case "range":
					case "radio":
					case "checkbox":
						element.on("change", function(){
							model.set(path + "." + collection["mold-bind"], element.val());
						})
						break;

					default :
						element.on("keyup", function(){
							model.set(path + "." + collection["mold-bind"], element.val());
						})
						break;
				}

				if(element.tagName.toLowerCase() === "select"){
					element.on("change", function(){
						model.set(path + "." + collection["mold-bind"], element.val());
					})
				}

				model.on(path + ".changed", function(e){

					setData(e.data[modelName]);
				})

				if(subPath){
					var data = model.get(path + "." + subPath);
				}else{
					var data = model.get(path);
				}

				setData(data[modelName]);
			}
		}

		Mold.watch(element.moldModel, "model", function(name, value, newValue){
			model = newValue;
			initBinding();
		})

		Mold.watch(element.moldModel, "path", function(name, value, newValue){
			path = newValue;
			initBinding();
		})

		initBinding();
	}
);<|endoftext|>


<commit_before>/* eslint-env node */
'use strict';

var defaultAllowedBaseStrings = ['(', ')', ',', '.', '&', '+', '-', '=', '*', '/', '#', '%', '!', '?', ':', '[', ']', '{', '}', '<', '>', '•', '—', ' ', '|'];

module.exports = {
  extends: 'recommended',
  rules: {
    'bare-strings': ['?', '»', '—'].concat(defaultAllowedBaseStrings),
    'block-indentation': true,
    'html-comments': true,
    'nested-interactive': true,
    'self-closing-void-elements': true,
    'img-alt-attributes': false,
    'link-rel-noopener': true,
    'invalid-interactive': false,
    'inline-link-to': true,
    'style-concatenation': true,
    'triple-curlies': false,
    'deprecated-each-syntax': true,
  }
};
<commit_msg>Disable deprecated-inline-view-helper rule<commit_after>/* eslint-env node */
'use strict';

var defaultAllowedBaseStrings = ['(', ')', ',', '.', '&', '+', '-', '=', '*', '/', '#', '%', '!', '?', ':', '[', ']', '{', '}', '<', '>', '•', '—', ' ', '|'];

module.exports = {
  extends: 'recommended',
  rules: {
    'bare-strings': ['?', '»', '—'].concat(defaultAllowedBaseStrings),
    'block-indentation': true,
    'html-comments': true,
    'nested-interactive': true,
    'self-closing-void-elements': true,
    'img-alt-attributes': false,
    'link-rel-noopener': true,
    'invalid-interactive': false,
    'inline-link-to': true,
    'style-concatenation': true,
    'triple-curlies': false,
    'deprecated-each-syntax': true,
    'deprecated-inline-view-helper': false,
  }
};
<|endoftext|>


<commit_before>//	***********************************************
//	WINE LIFE
//	CHECK-IN WINDOW  - CheckInWindow.js
//
//	MEN+1
//	Programmer:  Ivan Rodriguez & David Wells
//	***********************************************

//red wine = category 124
//white wine = category 125

function CheckInsWindow(title) {
	var global = require('ui/common/globals');
	// Creates the default window with global color scheme
	var self = global.createWindow(title);
	var overview = Ti.UI.createView({
		width: '100%',
		height: '100%',
		layout: 'vertical'
	});
	var search_view = Titanium.UI.createView({
		width: 'auto',
		height: Ti.UI.SIZE,
		left: 0,
		right: 0,
		layout: 'vertical',
		bottom: 0,
		zIndex: 1
	});
	// "Search for wine" text field
	var search_bar = Ti.UI.createTextField({
		//backgroundColor:'#FFF',
		top:5,
		width:'80%',
		height:40,
		hintText:'  Search for a wine...',
		//backgroundColor:'transparent',
		borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED
	});
	var search_bar_wrapper = Ti.UI.createView({
		width: '100%',
		height: 65,
		backgroundColor: global.colors.dark,
		top: 0,
		left: 0,
		right: 0,
		layout: 'vertical',
		//backgroundImage: 'images/wood_texture.png'
	});
	var search_button = Titanium.UI.createButton({
		color: 'white',
		title:"Search",
		borderRadius: 15,
		borderWidth: 0,
		backgroundColor: global.colors.dark,
		backgroundImage: 'none',
		font:{fontSize:16,fontWeight:'normal',fontFamily:'Helvetica Neue'},
		top: -15,
		width:'35%',
		height:30,
		//backgroundImage: 'images/wood_texture.png'
	});

	search_bar_wrapper.add(search_bar);
	// Creates "Look-Up" button
	search_view.height = search_bar_wrapper.height + search_button.height + search_button.top;

	search_view.add(search_bar_wrapper);
	search_view.add(search_button);

	overview.add(search_view);

	var results_table = null;

	var search_view_top = search_view.top;
	//Ti.API.info("Search height: " + search_view_height);
	function search(){
		if(Ti.Platform.osname != 'android')
		{
			search_button.removeEventListener('click', search);
			search_button.addEventListener('click', search_again);
					//search_view.visible = false
			search_view.animate({
				top: 0 - search_bar.height - search_bar.top - 10,
				duration: 500
			});
		}
		if(results_table)
				overview.remove(results_table);
		global.api.search(search_bar.value, function(result){
			results_table = global.api.search_results(result, function(wine){
				alert('Wine: ' + wine.id);
			});
			results_table.top = -15;

			if(Ti.Platform.osname == 'android'){
				alert('got this far');
				var res_win = global.createWindow("Search_results");
				alert('got to here');
				res_win.exitOnClose = false;

				res_win.add(results_table);

				self.containingTab.open(res_win);
			}
			else
				overview.add(results_table);
		});

	};
	search_button.addEventListener('click', search);
	function search_again(e){
		search_button.removeEventListener('click', search_again);
		search_button.addEventListener('click', search);
		search_view.animate({
			top: 0,
			duration: 500
		});
		search_view.bottom = 0;

		Ti.API.info('Setup animation');
	};

	self.add(overview);
	global.outputHook(self);
	return self;
};
module.exports = CheckInsWindow;<commit_msg>Made checkin open wine review page. Mods for android<commit_after>//	***********************************************
//	WINE LIFE
//	CHECK-IN WINDOW  - CheckInWindow.js
//
//	MEN+1
//	Programmer:  Ivan Rodriguez & David Wells
//	***********************************************

//red wine = category 124
//white wine = category 125

function CheckInsWindow(title) {
	var global = require('ui/common/globals');
	// Creates the default window with global color scheme
	var self = global.createWindow(title);
	var overview = Ti.UI.createView({
		width: '100%',
		height: '100%',
		layout: 'vertical'
	});
	var search_view = Titanium.UI.createView({
		width: 'auto',
		height: Ti.UI.SIZE,
		left: 0,
		right: 0,
		layout: 'vertical',
		bottom: 0,
		zIndex: 1
	});
	// "Search for wine" text field
	var search_bar = Ti.UI.createTextField({
		//backgroundColor:'#FFF',
		top:5,
		width:'80%',
		height:40,
		hintText:'  Search for a wine...',
		//backgroundColor:'transparent',
		borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED
	});
	var search_bar_wrapper = Ti.UI.createView({
		width: '100%',
		height: 65,
		backgroundColor: global.colors.dark,
		top: 0,
		left: 0,
		right: 0,
		layout: 'vertical',
		//backgroundImage: 'images/wood_texture.png'
	});
	var search_button = Titanium.UI.createButton({
		color: 'white',
		title:"Search",
		borderRadius: 15,
		borderWidth: 0,
		backgroundColor: global.colors.dark,
		backgroundImage: 'none',
		font:{fontSize:16,fontWeight:'normal',fontFamily:'Helvetica Neue'},
		top: -15,
		width:'35%',
		height:30,
		//backgroundImage: 'images/wood_texture.png'
	});

	search_bar_wrapper.add(search_bar);
	// Creates "Look-Up" button
	search_view.height = search_bar_wrapper.height + search_button.height + search_button.top;

	search_view.add(search_bar_wrapper);
	search_view.add(search_button);

	overview.add(search_view);

	var results_table = null;

	var search_view_top = search_view.top;
	//Ti.API.info("Search height: " + search_view_height);
	function search(){
		if(Ti.Platform.osname != 'android')
		{
			search_button.removeEventListener('click', search);
			search_button.addEventListener('click', search_again);
					//search_view.visible = false
			search_view.animate({
				top: 0 - search_bar.height - search_bar.top - 10,
				duration: 500
			});
		}
		if(results_table)
				overview.remove(results_table);
		global.api.search(search_bar.value, function(result){
			results_table = global.api.search_results(result, function(wine){
				var wine_review = require('ui/handheld/WineReview');
				self.containingTab.open(wine_review(wine));
			});

			if(Ti.Platform.osname == 'android'){
				var res_win = global.createWindow("Search_results");
				res_win.exitOnClose = false;

				res_win.add(results_table);

				self.containingTab.open(res_win);
			}
			else{
				results_table.top = -15;
				overview.add(results_table);
			}

		});

	};
	search_button.addEventListener('click', search);
	function search_again(e){
		search_button.removeEventListener('click', search_again);
		search_button.addEventListener('click', search);
		search_view.animate({
			top: 0,
			duration: 500
		});
		search_view.bottom = 0;

		Ti.API.info('Setup animation');
	};

	self.add(overview);
	global.outputHook(self);
	return self;
};
module.exports = CheckInsWindow;<|endoftext|>


<commit_before>var ram = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];//32(8cmd) 16byte(include cache)
var register = [0,0,0,0];//4(1cmd) 2byte
var disk = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];//128(32cmd) 64byte
var code = ["NUL","SET","RTN","PRT","IF","FOR","STR","END","INP"];
var tmp = 0;
var tmp2 = 0;
var tmp3 = 0;
// Note : a command is 0.5 byte (1 command + 3 parameters)

function writeRam(adr,input)
{
if(adr>=0&&adr<=31)
{
if(input>=0&&input<=15)
{
ram[adr] = Math.floor(input); // input only integers
}
}
return;
}

function readRam(adr)
{
if(adr>=0&&adr<=31)
{
return ram[adr];
}
else return;
}

function interpret()
{
switch(register[0])
{
case 0 : //NUL
break;
case 1 : //SET
switch(register[3])
{
case 0 : //set
ram[register[1]+16] = register[2]
break;
case 1 : //add
if(ram[register[1]+16] + register[2] > 15 || ram[register[1]+16] + register[2] < 0)
{
ram[register[1]+16] = 0; //overflow
}
else
{
ram[register[1]+16] += register[2];
}
break;
case 2 : //subtract
if(ram[register[1] - 16] - register[2] > 15 || ram[register[1]+16] - register[2] < 0)
{
ram[register[1]+16] = 0; //overflow
}
else
{
ram[register[1]+16] -= register[2];
}
break;
case 3 : //setvar
ram[register[1]+16] = ram[register[2]+16];
break;
case 4 : //addvar
if(ram[register[1] - 16] + ram[register[2]+16] > 15 || ram[register[1]+16] + ram[register[2]+16] < 0)
{
ram[register[1]+16] = 0; //overflow
}
else
{
ram[register[1]+16] = ram[register[2]+16];
}
break;
}
break;
}
return ram[31];
}

function runProgram()
{
for(tmp=0;tmp==7;tmp++)
{
for(tmp2=0;tmp2==15;tmp2++)
{
writeRam(tmp2,disk[tmp2+tmp*16]);
for(tmp3=0;tmp3==3;tmp3++)
{
register[0] = ram[tmp3*4]
register[1] = ram[tmp3*4+1]
register[2] = ram[tmp3*4+2]
register[3] = ram[tmp3*4+3]
interpret();
}
}
}
}
<commit_msg>0x000012<commit_after>/*
   Copyright 2015 7thGrader
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
       http://www.apache.org/licenses/LICENSE-2.0
*/

var ram = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];//32(8cmd) 16byte(include cache)
var register = [0,0,0,0];//4(1cmd) 2byte
var disk = [1,15,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];//128(32cmd) 64byte
var code = ["NUL","SET","RTN","PRT","IF","FOR","STR","END","INP"];
var tmp = 0;
var tmp2 = 0;
var tmp3 = 0;
// Note : a command is 2 byte (1 command + 3 parameters)

function writeRam(adr,input)
{
if(adr>=0&&adr<=31)
{
if(input>=0&&input<=15)
{
ram[adr] = Math.floor(input); // input only integers
}
}
return;
}

function readRam(adr)
{
if(adr>=0&&adr<=31)
{
return ram[adr];
}
else return;
}

function interpret()
{
switch(register[0])
{
case 0 : //NUL
break;
case 1 : //SET
switch(register[3])
{
case 0 : //set
ram[register[1]+16] = register[2]
break;
case 1 : //add
if(ram[register[1]+16] + register[2] > 15 || ram[register[1]+16] + register[2] < 0)
{
ram[register[1]+16] = 0; //overflow
}
else
{
ram[register[1]+16] += register[2];
}
break;
case 2 : //subtract
if(ram[register[1] - 16] - register[2] > 15 || ram[register[1]+16] - register[2] < 0)
{
ram[register[1]+16] = 0; //overflow
}
else
{
ram[register[1]+16] -= register[2];
}
break;
case 3 : //setvar
ram[register[1]+16] = ram[register[2]+16];
break;
case 4 : //addvar
if(ram[register[1] - 16] + ram[register[2]+16] > 15 || ram[register[1]+16] + ram[register[2]+16] < 0)
{
ram[register[1]+16] = 0; //overflow
}
else
{
ram[register[1]+16] = ram[register[2]+16];
}
break;
}
break;
}
return ram[31];
}

function useItem(x,y,z,i,b,id,bd)
{
clientMessage(runProgram());
}

function runProgram()
{
for(tmp=0;tmp==7;tmp++)
{
for(tmp2=0;tmp2==15;tmp2++)
{
writeRam(tmp2,disk[tmp2+tmp*16]);
for(tmp3=0;tmp3==3;tmp3++)
{
register[0] = ram[tmp3*4]
register[1] = ram[tmp3*4+1]
register[2] = ram[tmp3*4+2]
register[3] = ram[tmp3*4+3]
interpret();
}
}
}
}
<|endoftext|>


<commit_before>// ==UserScript==
// @name        Stack Exchange - Add link to network profile
// @namespace   https://github.com/Glorfindel83/
// @description Adds a link to the network profile for all user profile pages (even if they've hidden the current community)
// @author      Glorfindel
// @updateURL   https://raw.githubusercontent.com/Glorfindel83/SE-Userscripts/master/add-network-profile-link/add-network-profile-link.user.js
// @downloadURL https://raw.githubusercontent.com/Glorfindel83/SE-Userscripts/master/add-network-profile-link/add-network-profile-link.user.js
// @version     0.1
// @match       *://*.stackexchange.com/users/*
// @match       *://*.stackoverflow.com/users/*
// @match       *://*.superuser.com/users/*
// @match       *://*.serverfault.com/users/*
// @match       *://*.askubuntu.com/users/*
// @match       *://*.stackapps.com/users/*
// @match       *://*.mathoverflow.net/users/*
// @exclude     *://stackexchange.com/users/*
// @grant       none
// ==/UserScript==
(function () {
  'use strict';

  // Some pages (e.g. https://*.stackexchange.com/users/message/create/*) need to be skipped
  if (typeof(StackExchange.user) == 'undefined')
    return;

  StackExchange.ready(function() {
    // Check if link already present
    let user = $(".user-show-new");
    if (user.find("button[aria-controls='profiles-menu']").length > 0 ||
        user.find("a.s-btn[href^='https://stackexchange.com/users/']").length > 0)
      return;

    // Find network account ID
    let accountID = StackExchange.user.options.accountId;

    // Add to profile
    let profile = user[0].children[0];
    let container = profile.children[profile.children.length - 1];
    container.innerHTML = '

\n' +
      '\n' +
      '<svg aria-hidden="true" class="native mln2 mr2 svg-icon iconLogoSEXxs" width="18" height="18" viewBox="0 0 18 18"><path d="M3 4c0-1.1.9-2 2-2h8a2 2 0 012 2H3Z" fill="#8FD8F7"></path><path d="M15 11H3c0 1.1.9 2 2 2h5v3l3-3a2 2 0 002-2Z" fill="#155397"></path><path fill="#46A2D9" d="M3 5h12v2H3z"></path><path fill="#2D6DB5" d="M3 8h12v2H3z"></path></svg>\n' +
      'Network profile\n' +
      '

';
  });
})();<commit_msg>Add link to network & chat profile v0.2<commit_after>// ==UserScript==
// @name        Stack Exchange - Add link to network and chat profiles
// @namespace   https://github.com/Glorfindel83/
// @description Adds a link to the network profile for all user profile pages (even if they've hidden the current community) and a link to the chat profile
// @author      Glorfindel
// @updateURL   https://raw.githubusercontent.com/Glorfindel83/SE-Userscripts/master/add-network-profile-link/add-network-profile-link.user.js
// @downloadURL https://raw.githubusercontent.com/Glorfindel83/SE-Userscripts/master/add-network-profile-link/add-network-profile-link.user.js
// @version     0.2
// @match       *://*.stackexchange.com/users/*
// @match       *://*.stackoverflow.com/users/*
// @match       *://*.superuser.com/users/*
// @match       *://*.serverfault.com/users/*
// @match       *://*.askubuntu.com/users/*
// @match       *://*.stackapps.com/users/*
// @match       *://*.mathoverflow.net/users/*
// @exclude     *://stackexchange.com/users/*
// @grant       none
// ==/UserScript==
(function () {
  'use strict';

  // Some pages (e.g. https://*.stackexchange.com/users/message/create/*) need to be skipped
  if (typeof(StackExchange.user) == 'undefined')
    return;

  StackExchange.ready(function() {
    // Find user IDs
    let userID = StackExchange.user.options.userId;
    let accountID = StackExchange.user.options.accountId;

    // Check if link already present
    let user = $(".user-show-new");
    var existingButton = user.find("button[aria-controls='profiles-menu']");
    if (existingButton.length == 0) {
      existingButton = user.find("a.s-btn[href^='https://stackexchange.com/users/']").parents("ul");
    }
    if (existingButton.length == 0) {
      // Add link to network profile
      let profile = user[0].children[0];
      let container = profile.children[profile.children.length - 1];
      container.innerHTML = '\n' +
        '<svg aria-hidden="true" class="native mln2 mr2 svg-icon iconLogoSEXxs" width="18" height="18" viewBox="0 0 18 18"><path d="M3 4c0-1.1.9-2 2-2h8a2 2 0 012 2H3Z" fill="#8FD8F7"></path><path d="M15 11H3c0 1.1.9 2 2 2h5v3l3-3a2 2 0 002-2Z" fill="#155397"></path><path fill="#46A2D9" d="M3 5h12v2H3z"></path><path fill="#2D6DB5" d="M3 8h12v2H3z"></path></svg>\n' +
        'Network profile';
      existingButton = $(container).children();
    }

    // Add link to chat profile
    // NICETOHAVE: add as part of dropdown menu
    var chatProfile;
    switch (location.host) {
      case 'meta.stackexchange.com':
        chatProfile = 'https://chat.meta.stackexchange.com/users/' + userID;
        break;
      case 'stackoverflow.com':
      case 'meta.stackoverflow.com':
        chatProfile = 'https://chat.stackoverflow.com/users/' + userID;
        break;
      default:
        chatProfile = 'https://chat.stackexchange.com/account/' + accountID;
        break;
    }
    existingButton.before('\n' +
        'Chat profile');
  });
})();<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
<commit_msg>Disable react strict mode<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  // <React.StrictMode>
  <App />,
  // </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
<|endoftext|>


<commit_before>// This is the main Backbone Boilerplate build configuration file.
//
// This is a JavaScript file, you can define any functions you would like in
// here.
config.init({

  lint: {
    files: ["build/config.js", "app/modules/**/*.js"]
  },

  concat: {

    // The core library files
    "dist/debug/js/libs.js": [
      "assets/js/libs/jquery.js",
      "assets/js/libs/underscore.js",
      "assets/js/libs/backbone.js"
    ],

    // Application files
    "dist/debug/js/app.js": ["app/namespace.js", "app/modules/**/*.js", "app/index.js"],

    // Your CSS
    "dist/debug/css/style.css": ["assets/css/**/*.css"]
  },

  jst: {
    "dist/debug/js/templates.js": ["app/templates/**/*.html"]
  },

  min: {
    "dist/release/js/libs.js": ["dist/debug/js/libs.js"],
    "dist/release/js/app.js": ["dist/debug/js/app.js"],
    "dist/release/js/templates.js": ["dist/debug/js/templates.js"]
  },

  mincss: {
    "dist/release/css/style.css": ["dist/debug/css/style.css"]
  },

  watch: {
    files: ["assets/**/*", "app/**/*"],
    tasks: "lint:files concat jst",

    min: {
      files: ["assets/**/*", "app/**/*"],
      tasks: "default"
    }
  },

  clean: {
    folder: "dist/"
  }

});

// Run the following tasks...
task.registerTask("default", "clean lint:files concat jst min mincss");
<commit_msg>Now linting all .js files under app during build<commit_after>// This is the main Backbone Boilerplate build configuration file.
//
// This is a JavaScript file, you can define any functions you would like in
// here.
config.init({

  lint: {
    files: ["build/config.js", "app/**/*.js"]
  },

  concat: {

    // The core library files
    "dist/debug/js/libs.js": [
      "assets/js/libs/jquery.js",
      "assets/js/libs/underscore.js",
      "assets/js/libs/backbone.js"
    ],

    // Application files
    "dist/debug/js/app.js": ["app/namespace.js", "app/modules/**/*.js", "app/index.js"],

    // Your CSS
    "dist/debug/css/style.css": ["assets/css/**/*.css"]
  },

  jst: {
    "dist/debug/js/templates.js": ["app/templates/**/*.html"]
  },

  min: {
    "dist/release/js/libs.js": ["dist/debug/js/libs.js"],
    "dist/release/js/app.js": ["dist/debug/js/app.js"],
    "dist/release/js/templates.js": ["dist/debug/js/templates.js"]
  },

  mincss: {
    "dist/release/css/style.css": ["dist/debug/css/style.css"]
  },

  watch: {
    files: ["assets/**/*", "app/**/*"],
    tasks: "lint:files concat jst",

    min: {
      files: ["assets/**/*", "app/**/*"],
      tasks: "default"
    }
  },

  clean: {
    folder: "dist/"
  }

});

// Run the following tasks...
task.registerTask("default", "clean lint:files concat jst min mincss");
<|endoftext|>


<commit_before>"use strict";
var assert = require('assert');

var Color = {
    White: 0
};

var Orientation = {
    Up: 0
};

var Ant = function() {

    var position = {x: 0, y: 0};
    var orientation = Orientation.Up;

    this.position = function() {
	return position;
    };

    this.faces = function() {
	return orientation;
    };

    return this;
};

var makeAnt = function() {
    return new Ant();
};

var Square = function() {

    var color = Color.White;

    this.color = function() {
	return color;
    };

    this.flip = function() {
	color = (color == Color.White ? Color.Black : Color.White);
    };

    return this;
};

var makeSquare = function() {
    return new Square();
};

describe('langton\'s ant', function() {
    describe('ant', function() {
	it('exists', function() {
	    assert(makeAnt());
	});

	it('has a location', function() {
	    var ant = makeAnt();
	    assert.equal(0, ant.position().x);
	    assert.equal(0, ant.position().y);
	});

	it('faces up', function() {
	    var ant = makeAnt();
	    assert.equal(Orientation.Up, ant.faces());
	});
    });

    describe('square', function() {
	it('exists', function() {
	    assert(makeSquare());
	});

	it('initially white', function() {
	    assert.equal(Color.White, makeSquare().color());
	});

	it('flips', function() {
	    var sq = makeSquare();
	    sq.flip();
	    assert.equal(Color.Black, sq.color());
	});
    });
});
<commit_msg>rename<commit_after>"use strict";
var assert = require('assert');

var Color = {
    White: 0
};

var Orientation = {
    Up: 0
};

var Ant = function() {

    var position = {x: 0, y: 0};
    var orientation = Orientation.Up;

    this.position = function() {
	return position;
    };

    this.orientation = function() {
	return orientation;
    };

    return this;
};

var makeAnt = function() {
    return new Ant();
};

var Square = function() {

    var color = Color.White;

    this.color = function() {
	return color;
    };

    this.flip = function() {
	color = (color == Color.White ? Color.Black : Color.White);
    };

    return this;
};

var makeSquare = function() {
    return new Square();
};

describe('langton\'s ant', function() {
    describe('ant', function() {
	it('exists', function() {
	    assert(makeAnt());
	});

	it('has a location', function() {
	    var ant = makeAnt();
	    assert.equal(0, ant.position().x);
	    assert.equal(0, ant.position().y);
	});

	it('orientation up', function() {
	    var ant = makeAnt();
	    assert.equal(Orientation.Up, ant.orientation());
	});
    });

    describe('square', function() {
	it('exists', function() {
	    assert(makeSquare());
	});

	it('initially white', function() {
	    assert.equal(Color.White, makeSquare().color());
	});

	it('flips', function() {
	    var sq = makeSquare();
	    sq.flip();
	    assert.equal(Color.Black, sq.color());
	});
    });
});
<|endoftext|>