<commit_before>/*
 * Sphinx search overrides
 */

var rtddata = require('./rtd-data');
var xss = require('xss/lib/index');
var MAX_RESULT_PER_SECTION = 3;
var MAX_SUBSTRING_LIMIT = 100;

/*
 * Search query override for hitting our local API instead of the standard
 * Sphinx indexer. This will fall back to the standard indexer on an API
 * failure,
 */
function attach_elastic_search_query(data) {
    var project = data.project;
    var version = data.version;
    var language = data.language || 'en';
    var api_host = data.api_host;

    var query_override = function (query) {
        var search_def = $.Deferred();
        var search_url = document.createElement('a');

        search_url.href = api_host;
        search_url.pathname = '/api/v2/docsearch/';
        search_url.search = '?q=' + $.urlencode(query) + '&project=' + project +
                            '&version=' + version + '&language=' + language;

        search_def
            .then(function (data) {
                var hit_list = data.results || [];
                var total_count = data.count || 0;

                if (hit_list.length) {
                    for (var i = 0; i < hit_list.length; i += 1) {
                        var doc = hit_list[i];
                        var highlight = doc.highlight;
                        var inner_hits = doc.inner_hits || [];
                        var list_item = $('

');

                        var title = doc.title;
                        // if highlighted title is present,
                        // use that.
                        if (highlight) {
                            if (highlight.title) {
                                title = xss(highlight.title[0]);
                            }
                        }

                        var link = doc.link + DOCUMENTATION_OPTIONS.FILE_SUFFIX + "?highlight=" + $.urlencode(query);
                        var item = $('', {'href': link});

                        item.html(title);
                        item.find('span').addClass('highlighted');
                        list_item.append(item);

                        // If the document is from subproject, add extra information
                        if (doc.project !== project) {
                            var text = " (from project " + doc.project + ")";
                            var extra = $('', {'text': text});
                            list_item.append(extra);
                        }

                        for (var j = 0; j < inner_hits.length; j += 1) {

                            var contents = $('
');

                            var section = "";
                            var section_subtitle = "";
                            var section_subtitle_link = "";
                            var section_content = "";
                            var content = "";

                            var domain = "";
                            var domain_role_name = "";
                            var domain_subtitle_link = "";
                            var domain_name = "";
                            var domain_subtitle = "";
                            var domain_content = "";
                            var domain_docstrings = "";

                            var section_template = '' +
                                '
' +
                                    '<a href="<%= section_subtitle_link %>">' +
                                        '<%= section_subtitle %>' +
                                    '' +
                                '
' +
                                '<% for (var i = 0; i < section_content.length; ++i) { %>' +
                                    '
' +
                                        '<%= section_content[i] %>' +
                                    '
' +
                                '<% } %>';

                            var domain_template = '' +
                                '
' +
                                    '<a href="<%= domain_subtitle_link %>">' +
                                        '<%= domain_subtitle %>' +
                                    '' +
                                '
' +
                                '
' +
                                    '<%= domain_content %>' +
                                '
';

                            // if the result is page section
                            if(inner_hits[j].type === "sections") {

                                section = inner_hits[j];
                                section_subtitle = section._source.title;
                                section_subtitle_link = link + "#" + section._source.id;
                                section_content = [section._source.content.substr(0, MAX_SUBSTRING_LIMIT) + " ..."];

                                if (section.highlight) {
                                    if (section.highlight["sections.title"]) {
                                        section_subtitle = xss(section.highlight["sections.title"][0]);
                                    }

                                    if (section.highlight["sections.content"]) {
                                        content = section.highlight["sections.content"];
                                        section_content = [];
                                        for (
                                            var k = 0;
                                            k < content.length && k < MAX_RESULT_PER_SECTION;
                                             k += 1
                                        ) {
                                            section_content.push("... " + xss(content[k]) + " ...");
                                        }
                                    }
                                }

                                contents.append(
                                    $u.template(
                                        section_template,
                                        {
                                            section_subtitle_link: section_subtitle_link,
                                            section_subtitle: section_subtitle,
                                            section_content: section_content
                                        }
                                    )
                                );
                            }

                            // if the result is a sphinx domain object
                            if (inner_hits[j].type === "domains") {

                                domain = inner_hits[j];
                                domain_role_name = domain._source.role_name;
                                domain_subtitle_link = link + "#" + domain._source.anchor;
                                domain_name = domain._source.name;
                                domain_subtitle = "";
                                domain_content = "";
                                domain_docstrings = "";

                                if (domain._source.docstrings !== "") {
                                    domain_docstrings = domain._source.docstrings.substr(0, MAX_SUBSTRING_LIMIT) + " ...";
                                }

                                if (domain.highlight) {
                                    if (domain.highlight["domains.docstrings"]) {
                                        domain_docstrings = "... " + xss(domain.highlight["domains.docstrings"][0]) + " ...";
                                    }

                                    if (domain.highlight["domains.name"]) {
                                        domain_name = xss(domain.highlight["domains.name"][0]);
                                    }
                                }

                                domain_subtitle = "[" + domain_role_name + "]: " + domain_name;
                                domain_content = domain_docstrings;

                                contents.append(
                                    $u.template(
                                        domain_template,
                                        {
                                            domain_subtitle_link: domain_subtitle_link,
                                            domain_subtitle: domain_subtitle,
                                            domain_content: domain_content
                                        }
                                    )
                                );
                            }

                            contents.find('span').addClass('highlighted');
                            list_item.append(contents);

                            // Create some spacing between the results.
                            // Also, don't add this spacing in the last hit.
                            if (j !== inner_hits.length - 1) {
                                list_item.append($("

"));
                            }
                        }

                        Search.output.append(list_item);
                        list_item.slideDown(5);
                    }
                }

                if (!hit_list.length) {
                    // Fallback to Sphinx's indexes
                    Search.query_fallback(query);
                    console.log('Read the Docs search failed. Falling back to Sphinx search.');
                }
                else {
                    Search.status.text(
                        _('Search finished, found %s page(s) matching the search query.').replace('%s', hit_list.length)
                    );
                }
            })
            .fail(function (error) {
                // Fallback to Sphinx's indexes
                Search.query_fallback(query);
            })
            .always(function () {
                $('#search-progress').empty();
                Search.stopPulse();
                Search.title.text(_('Search Results'));
                Search.status.fadeIn(500);
            });

        $.ajax({
            url: search_url.href,
            crossDomain: true,
            xhrFields: {
                withCredentials: true,
            },
            complete: function (resp, status_code) {
                if (
                    status_code !== 'success' ||
                    typeof (resp.responseJSON) === 'undefined' ||
                    resp.responseJSON.count === 0
                ) {
                    return search_def.reject();
                }
                return search_def.resolve(resp.responseJSON);
            }
        })
        .fail(function (resp, status_code, error) {
            return search_def.reject();
        });
    };

    if (typeof Search !== 'undefined' && project && version) {

        // Do not replace the built-in search if RTD's docsearch is disabled
        if (!data.features || !data.features.docsearch_disabled) {
            var query_fallback = Search.query;
            Search.query_fallback = query_fallback;
            Search.query = query_override;
        }
    }
    $(document).ready(function () {
        if (typeof Search !== 'undefined') {
            Search.init();
        }
    });
}

function init() {
    var data = rtddata.get();
    attach_elastic_search_query(data);
}

module.exports = {
    init: init
};
<commit_msg>add comment back<commit_after>/*
 * Sphinx search overrides
 */

var rtddata = require('./rtd-data');
var xss = require('xss/lib/index');
var MAX_RESULT_PER_SECTION = 3;
var MAX_SUBSTRING_LIMIT = 100;

/*
 * Search query override for hitting our local API instead of the standard
 * Sphinx indexer. This will fall back to the standard indexer on an API
 * failure,
 */
function attach_elastic_search_query(data) {
    var project = data.project;
    var version = data.version;
    var language = data.language || 'en';
    var api_host = data.api_host;

    var query_override = function (query) {
        var search_def = $.Deferred();
        var search_url = document.createElement('a');

        search_url.href = api_host;
        search_url.pathname = '/api/v2/docsearch/';
        search_url.search = '?q=' + $.urlencode(query) + '&project=' + project +
                            '&version=' + version + '&language=' + language;

        search_def
            .then(function (data) {
                var hit_list = data.results || [];
                var total_count = data.count || 0;

                if (hit_list.length) {
                    for (var i = 0; i < hit_list.length; i += 1) {
                        var doc = hit_list[i];
                        var highlight = doc.highlight;
                        var inner_hits = doc.inner_hits || [];
                        var list_item = $('

');

                        var title = doc.title;
                        // if highlighted title is present,
                        // use that.
                        if (highlight) {
                            if (highlight.title) {
                                title = xss(highlight.title[0]);
                            }
                        }

                        // Creating the result from elements
                        var link = doc.link + DOCUMENTATION_OPTIONS.FILE_SUFFIX + "?highlight=" + $.urlencode(query);
                        var item = $('', {'href': link});

                        item.html(title);
                        item.find('span').addClass('highlighted');
                        list_item.append(item);

                        // If the document is from subproject, add extra information
                        if (doc.project !== project) {
                            var text = " (from project " + doc.project + ")";
                            var extra = $('', {'text': text});
                            list_item.append(extra);
                        }

                        for (var j = 0; j < inner_hits.length; j += 1) {

                            var contents = $('
');

                            var section = "";
                            var section_subtitle = "";
                            var section_subtitle_link = "";
                            var section_content = "";
                            var content = "";

                            var domain = "";
                            var domain_role_name = "";
                            var domain_subtitle_link = "";
                            var domain_name = "";
                            var domain_subtitle = "";
                            var domain_content = "";
                            var domain_docstrings = "";

                            var section_template = '' +
                                '
' +
                                    '<a href="<%= section_subtitle_link %>">' +
                                        '<%= section_subtitle %>' +
                                    '' +
                                '
' +
                                '<% for (var i = 0; i < section_content.length; ++i) { %>' +
                                    '
' +
                                        '<%= section_content[i] %>' +
                                    '
' +
                                '<% } %>';

                            var domain_template = '' +
                                '
' +
                                    '<a href="<%= domain_subtitle_link %>">' +
                                        '<%= domain_subtitle %>' +
                                    '' +
                                '
' +
                                '
' +
                                    '<%= domain_content %>' +
                                '
';

                            // if the result is page section
                            if(inner_hits[j].type === "sections") {

                                section = inner_hits[j];
                                section_subtitle = section._source.title;
                                section_subtitle_link = link + "#" + section._source.id;
                                section_content = [section._source.content.substr(0, MAX_SUBSTRING_LIMIT) + " ..."];

                                if (section.highlight) {
                                    if (section.highlight["sections.title"]) {
                                        section_subtitle = xss(section.highlight["sections.title"][0]);
                                    }

                                    if (section.highlight["sections.content"]) {
                                        content = section.highlight["sections.content"];
                                        section_content = [];
                                        for (
                                            var k = 0;
                                            k < content.length && k < MAX_RESULT_PER_SECTION;
                                             k += 1
                                        ) {
                                            section_content.push("... " + xss(content[k]) + " ...");
                                        }
                                    }
                                }

                                contents.append(
                                    $u.template(
                                        section_template,
                                        {
                                            section_subtitle_link: section_subtitle_link,
                                            section_subtitle: section_subtitle,
                                            section_content: section_content
                                        }
                                    )
                                );
                            }

                            // if the result is a sphinx domain object
                            if (inner_hits[j].type === "domains") {

                                domain = inner_hits[j];
                                domain_role_name = domain._source.role_name;
                                domain_subtitle_link = link + "#" + domain._source.anchor;
                                domain_name = domain._source.name;
                                domain_subtitle = "";
                                domain_content = "";
                                domain_docstrings = "";

                                if (domain._source.docstrings !== "") {
                                    domain_docstrings = domain._source.docstrings.substr(0, MAX_SUBSTRING_LIMIT) + " ...";
                                }

                                if (domain.highlight) {
                                    if (domain.highlight["domains.docstrings"]) {
                                        domain_docstrings = "... " + xss(domain.highlight["domains.docstrings"][0]) + " ...";
                                    }

                                    if (domain.highlight["domains.name"]) {
                                        domain_name = xss(domain.highlight["domains.name"][0]);
                                    }
                                }

                                domain_subtitle = "[" + domain_role_name + "]: " + domain_name;
                                domain_content = domain_docstrings;

                                contents.append(
                                    $u.template(
                                        domain_template,
                                        {
                                            domain_subtitle_link: domain_subtitle_link,
                                            domain_subtitle: domain_subtitle,
                                            domain_content: domain_content
                                        }
                                    )
                                );
                            }

                            contents.find('span').addClass('highlighted');
                            list_item.append(contents);

                            // Create some spacing between the results.
                            // Also, don't add this spacing in the last hit.
                            if (j !== inner_hits.length - 1) {
                                list_item.append($("

"));
                            }
                        }

                        Search.output.append(list_item);
                        list_item.slideDown(5);
                    }
                }

                if (!hit_list.length) {
                    // Fallback to Sphinx's indexes
                    Search.query_fallback(query);
                    console.log('Read the Docs search failed. Falling back to Sphinx search.');
                }
                else {
                    Search.status.text(
                        _('Search finished, found %s page(s) matching the search query.').replace('%s', hit_list.length)
                    );
                }
            })
            .fail(function (error) {
                // Fallback to Sphinx's indexes
                Search.query_fallback(query);
            })
            .always(function () {
                $('#search-progress').empty();
                Search.stopPulse();
                Search.title.text(_('Search Results'));
                Search.status.fadeIn(500);
            });

        $.ajax({
            url: search_url.href,
            crossDomain: true,
            xhrFields: {
                withCredentials: true,
            },
            complete: function (resp, status_code) {
                if (
                    status_code !== 'success' ||
                    typeof (resp.responseJSON) === 'undefined' ||
                    resp.responseJSON.count === 0
                ) {
                    return search_def.reject();
                }
                return search_def.resolve(resp.responseJSON);
            }
        })
        .fail(function (resp, status_code, error) {
            return search_def.reject();
        });
    };

    if (typeof Search !== 'undefined' && project && version) {

        // Do not replace the built-in search if RTD's docsearch is disabled
        if (!data.features || !data.features.docsearch_disabled) {
            var query_fallback = Search.query;
            Search.query_fallback = query_fallback;
            Search.query = query_override;
        }
    }
    $(document).ready(function () {
        if (typeof Search !== 'undefined') {
            Search.init();
        }
    });
}

function init() {
    var data = rtddata.get();
    attach_elastic_search_query(data);
}

module.exports = {
    init: init
};
<|endoftext|>


<commit_before>if ( ! Detector.webgl ) Detector.addGetWebGLMessage();

var camera, scene, renderer;

init();

function init() {

  scene = new THREE.Scene();

  scene.add( new THREE.AmbientLight( 0x999999 ) );

  camera = new THREE.PerspectiveCamera( 35, window.innerWidth / window.innerHeight, 1, 500 );

  // Z is up for objects intended to be 3D printed.

  camera.up.set( 0, 0, 1 );
  camera.position.set(0, -43.94561965412779, 19.70416457024617);

  var light1 = new THREE.PointLight( 0xffffff, 1 );
  light1.position.set( 0, 0, -10);
  var light2 = new THREE.PointLight( 0xffffff, 1 );
  light2.position.set( 20, -25, 0);
  var light3 = new THREE.PointLight( 0xffffff, 1 );
  var light4 = new THREE.PointLight( 0xffffff, 1 );

  camera.add(light1);
  camera.add(light2);
  camera.add(light3);
  camera.add(light4);
  scene.add(camera);

  var grid = new THREE.GridHelper( 25, 50, 0x0f2045, 0x0f2045 );
  grid.rotateOnAxis( new THREE.Vector3( 1, 0, 0 ), 90 * ( Math.PI/180 ) );
  scene.add(grid);

  renderer = new THREE.WebGLRenderer( { antialias: true } );
  renderer.setClearColor( 0xffffff );
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );

  var loader = new THREE.STLLoader();

  // Binary files

  var material = new THREE.MeshPhongMaterial( { color: 0x0f2045, specular: 0x111111, shininess: 200 } );
  loader.load( 'https://s3.amazonaws.com/limbforgestls/EbeArm/Ebe_forearm_L/forearm_L_C4-200_L1-230.stl', function ( geometry ) {
    var mesh = new THREE.Mesh( geometry, material );

    mesh.position.set( 0, 0, 0 );
    mesh.rotation.set( 0, 0, 0 );
    mesh.scale.set( .02, .02, .02 );

    mesh.castShadow = false;
    mesh.receiveShadow = false;

    render();
  });

  var controls = new THREE.OrbitControls( camera, renderer.domElement );
  controls.addEventListener( 'change', render );
  controls.target.set( 0, 1.2, 2 );
  controls.update();
  window.addEventListener( 'resize', onWindowResize, false );

}

function onWindowResize() {

  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize( window.innerWidth, window.innerHeight );

  render();

}

function render() {

  renderer.render( scene, camera );

}

var renderThreeJS = render;

  $(document).on('turbolinks:load', function() {
    document.getElementById('display-hand').appendChild( renderer.domElement );
    render();
  });
<commit_msg>removing grid<commit_after>if ( ! Detector.webgl ) Detector.addGetWebGLMessage();

var camera, scene, renderer;

init();

function init() {

  scene = new THREE.Scene();

  scene.add( new THREE.AmbientLight( 0x999999 ) );

  camera = new THREE.PerspectiveCamera( 35, window.innerWidth / window.innerHeight, 1, 500 );

  // Z is up for objects intended to be 3D printed.

  camera.up.set( 0, 0, 1 );
  camera.position.set(0, -43.94561965412779, 19.70416457024617);

  var light1 = new THREE.PointLight( 0xffffff, 1 );
  light1.position.set( 0, 0, -10);
  var light2 = new THREE.PointLight( 0xffffff, 1 );
  light2.position.set( 20, -25, 0);
  var light3 = new THREE.PointLight( 0xffffff, 1 );
  var light4 = new THREE.PointLight( 0xffffff, 1 );

  camera.add(light1);
  camera.add(light2);
  camera.add(light3);
  camera.add(light4);
  scene.add(camera);

  var grid = new THREE.GridHelper( 25, 50, 0x0f2045, 0x0f2045 );
  grid.rotateOnAxis( new THREE.Vector3( 1, 0, 0 ), 90 * ( Math.PI/180 ) );

  renderer = new THREE.WebGLRenderer( { antialias: true } );
  renderer.setClearColor( 0xffffff );
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );

  var loader = new THREE.STLLoader();

  // Binary files

  var material = new THREE.MeshPhongMaterial( { color: 0x0f2045, specular: 0x111111, shininess: 200 } );
  loader.load( 'https://s3.amazonaws.com/limbforgestls/EbeArm/Ebe_forearm_L/forearm_L_C4-200_L1-230.stl', function ( geometry ) {
    var mesh = new THREE.Mesh( geometry, material );

    mesh.position.set( 0, 0, 0 );
    mesh.rotation.set( 0, 0, 0 );
    mesh.scale.set( .02, .02, .02 );

    mesh.castShadow = false;
    mesh.receiveShadow = false;

    render();
  });

  var controls = new THREE.OrbitControls( camera, renderer.domElement );
  controls.addEventListener( 'change', render );
  controls.target.set( 0, 1.2, 2 );
  controls.update();
  window.addEventListener( 'resize', onWindowResize, false );

}

function onWindowResize() {

  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize( window.innerWidth, window.innerHeight );

  render();

}

function render() {

  renderer.render( scene, camera );

}

var renderThreeJS = render;

  $(document).on('turbolinks:load', function() {
    document.getElementById('display-hand').appendChild( renderer.domElement );
    render();
  });
<|endoftext|>


<commit_before>// @flow

import { threadPermissions } from 'lib/types/thread-types';
import { threadSubscriptions } from 'lib/types/subscription-types';

import apn from '@parse/node-apn';
import invariant from 'invariant';

import { promiseAll } from 'lib/utils/promises';

import { dbQuery, SQL, SQLStatement } from '../database/database';
import { apnPush, fcmPush } from './utils';
import createIDs from '../creators/id-creator';

async function rescindPushNotifs(
  notifCondition: SQLStatement,
  inputCountCondition?: SQLStatement,
) {
  const notificationExtractString = `$.${threadSubscriptions.home}`;
  const visPermissionExtractString = `$.${threadPermissions.VISIBLE}.value`;
  const fetchQuery = SQL`
    SELECT n.id, n.user, n.thread, n.message, n.delivery, n.collapse_key, COUNT(
  `;
  fetchQuery.append(inputCountCondition ? inputCountCondition : SQL`m.thread`);
  fetchQuery.append(SQL`
      ) AS unread_count
    FROM notifications n
    LEFT JOIN memberships m ON m.user = n.user AND m.unread = 1 AND m.role > 0
      AND JSON_EXTRACT(subscription, ${notificationExtractString})
      AND JSON_EXTRACT(permissions, ${visPermissionExtractString})
    WHERE n.rescinded = 0 AND
  `);
  fetchQuery.append(notifCondition);
  fetchQuery.append(SQL` GROUP BY n.id, m.user`);
  const [fetchResult] = await dbQuery(fetchQuery);

  const deliveryPromises = {};
  const notifInfo = {};
  const rescindedIDs = [];
  for (let row of fetchResult) {
    const deliveries = Array.isArray(row.delivery)
      ? row.delivery
      : [row.delivery];
    const id = row.id.toString();
    const threadID = row.thread.toString();
    notifInfo[id] = {
      userID: row.user.toString(),
      threadID,
      messageID: row.message.toString(),
    };
    for (let delivery of deliveries) {
      if (delivery.iosID && delivery.iosDeviceTokens) {
        // Old iOS
        const notification = prepareIOSNotification(
          delivery.iosID,
          row.unread_count,
        );
        deliveryPromises[id] = apnPush(notification, delivery.iosDeviceTokens);
      } else if (delivery.androidID) {
        // Old Android
        const notification = prepareAndroidNotification(
          row.collapse_key ? row.collapse_key : id,
          row.unread_count,
          threadID,
          null,
        );
        deliveryPromises[id] = fcmPush(
          notification,
          delivery.androidDeviceTokens,
          null,
        );
      } else if (delivery.deviceType === 'ios') {
        // New iOS
        const { iosID, deviceTokens } = delivery;
        const notification = prepareIOSNotification(iosID, row.unread_count);
        deliveryPromises[id] = apnPush(notification, deviceTokens);
      } else if (delivery.deviceType === 'android') {
        // New Android
        const { deviceTokens, codeVersion } = delivery;
        const notification = prepareAndroidNotification(
          row.collapse_key ? row.collapse_key : id,
          row.unread_count,
          threadID,
          codeVersion,
        );
        deliveryPromises[id] = fcmPush(notification, deviceTokens, null);
      }
    }
    rescindedIDs.push(row.id);
  }

  const numRescinds = Object.keys(deliveryPromises).length;
  const promises = [promiseAll(deliveryPromises)];
  if (numRescinds > 0) {
    promises.push(createIDs('notifications', numRescinds));
  }
  if (rescindedIDs.length > 0) {
    const rescindQuery = SQL`
      UPDATE notifications SET rescinded = 1 WHERE id IN (${rescindedIDs})
    `;
    promises.push(dbQuery(rescindQuery));
  }

  const [deliveryResults, dbIDs] = await Promise.all(promises);
  const newNotifRows = [];
  if (numRescinds > 0) {
    invariant(dbIDs, 'dbIDs should be set');
    for (const rescindedID in deliveryResults) {
      const delivery = {};
      delivery.type = 'rescind';
      delivery.rescindedID = rescindedID;
      const { errors } = deliveryResults[rescindedID];
      if (errors) {
        delivery.errors = errors;
      }
      const dbID = dbIDs.shift();
      const { userID, threadID, messageID } = notifInfo[rescindedID];
      newNotifRows.push([
        dbID,
        userID,
        threadID,
        messageID,
        null,
        JSON.stringify([delivery]),
        1,
      ]);
    }
  }
  if (newNotifRows.length > 0) {
    const insertQuery = SQL`
      INSERT INTO notifications
        (id, user, thread, message, collapse_key, delivery, rescinded)
      VALUES ${newNotifRows}
    `;
    await dbQuery(insertQuery);
  }
}

function prepareIOSNotification(
  iosID: string,
  unreadCount: number,
): apn.Notification {
  const notification = new apn.Notification();
  notification.contentAvailable = true;
  notification.badge = unreadCount;
  notification.topic = 'org.squadcal.app';
  notification.payload = {
    managedAps: {
      action: 'CLEAR',
      notificationId: iosID,
    },
  };
  return notification;
}

function prepareAndroidNotification(
  notifID: string,
  unreadCount: number,
  threadID: string,
  codeVersion: ?number,
): Object {
  if (!codeVersion || codeVersion < 31) {
    return {
      data: {
        badge: unreadCount.toString(),
        custom_notification: JSON.stringify({
          rescind: 'true',
          notifID,
        }),
      },
    };
  }
  return {
    data: {
      badge: unreadCount.toString(),
      rescind: 'true',
      rescindID: notifID,
      threadID,
    },
  };
}

export { rescindPushNotifs };
<commit_msg>[server] Replace unread check with last messages condition in rescind<commit_after>// @flow

import { threadPermissions } from 'lib/types/thread-types';
import { threadSubscriptions } from 'lib/types/subscription-types';

import apn from '@parse/node-apn';
import invariant from 'invariant';

import { promiseAll } from 'lib/utils/promises';

import { dbQuery, SQL, SQLStatement } from '../database/database';
import { apnPush, fcmPush } from './utils';
import createIDs from '../creators/id-creator';

async function rescindPushNotifs(
  notifCondition: SQLStatement,
  inputCountCondition?: SQLStatement,
) {
  const notificationExtractString = `$.${threadSubscriptions.home}`;
  const visPermissionExtractString = `$.${threadPermissions.VISIBLE}.value`;
  const fetchQuery = SQL`
    SELECT n.id, n.user, n.thread, n.message, n.delivery, n.collapse_key, COUNT(
  `;
  fetchQuery.append(inputCountCondition ? inputCountCondition : SQL`m.thread`);
  fetchQuery.append(SQL`
      ) AS unread_count
    FROM notifications n
    LEFT JOIN memberships m ON m.user = n.user
      AND m.last_message > m.last_read_message
      AND m.role > 0
      AND JSON_EXTRACT(subscription, ${notificationExtractString})
      AND JSON_EXTRACT(permissions, ${visPermissionExtractString})
    WHERE n.rescinded = 0 AND
  `);
  fetchQuery.append(notifCondition);
  fetchQuery.append(SQL` GROUP BY n.id, m.user`);
  const [fetchResult] = await dbQuery(fetchQuery);

  const deliveryPromises = {};
  const notifInfo = {};
  const rescindedIDs = [];
  for (let row of fetchResult) {
    const deliveries = Array.isArray(row.delivery)
      ? row.delivery
      : [row.delivery];
    const id = row.id.toString();
    const threadID = row.thread.toString();
    notifInfo[id] = {
      userID: row.user.toString(),
      threadID,
      messageID: row.message.toString(),
    };
    for (let delivery of deliveries) {
      if (delivery.iosID && delivery.iosDeviceTokens) {
        // Old iOS
        const notification = prepareIOSNotification(
          delivery.iosID,
          row.unread_count,
        );
        deliveryPromises[id] = apnPush(notification, delivery.iosDeviceTokens);
      } else if (delivery.androidID) {
        // Old Android
        const notification = prepareAndroidNotification(
          row.collapse_key ? row.collapse_key : id,
          row.unread_count,
          threadID,
          null,
        );
        deliveryPromises[id] = fcmPush(
          notification,
          delivery.androidDeviceTokens,
          null,
        );
      } else if (delivery.deviceType === 'ios') {
        // New iOS
        const { iosID, deviceTokens } = delivery;
        const notification = prepareIOSNotification(iosID, row.unread_count);
        deliveryPromises[id] = apnPush(notification, deviceTokens);
      } else if (delivery.deviceType === 'android') {
        // New Android
        const { deviceTokens, codeVersion } = delivery;
        const notification = prepareAndroidNotification(
          row.collapse_key ? row.collapse_key : id,
          row.unread_count,
          threadID,
          codeVersion,
        );
        deliveryPromises[id] = fcmPush(notification, deviceTokens, null);
      }
    }
    rescindedIDs.push(row.id);
  }

  const numRescinds = Object.keys(deliveryPromises).length;
  const promises = [promiseAll(deliveryPromises)];
  if (numRescinds > 0) {
    promises.push(createIDs('notifications', numRescinds));
  }
  if (rescindedIDs.length > 0) {
    const rescindQuery = SQL`
      UPDATE notifications SET rescinded = 1 WHERE id IN (${rescindedIDs})
    `;
    promises.push(dbQuery(rescindQuery));
  }

  const [deliveryResults, dbIDs] = await Promise.all(promises);
  const newNotifRows = [];
  if (numRescinds > 0) {
    invariant(dbIDs, 'dbIDs should be set');
    for (const rescindedID in deliveryResults) {
      const delivery = {};
      delivery.type = 'rescind';
      delivery.rescindedID = rescindedID;
      const { errors } = deliveryResults[rescindedID];
      if (errors) {
        delivery.errors = errors;
      }
      const dbID = dbIDs.shift();
      const { userID, threadID, messageID } = notifInfo[rescindedID];
      newNotifRows.push([
        dbID,
        userID,
        threadID,
        messageID,
        null,
        JSON.stringify([delivery]),
        1,
      ]);
    }
  }
  if (newNotifRows.length > 0) {
    const insertQuery = SQL`
      INSERT INTO notifications
        (id, user, thread, message, collapse_key, delivery, rescinded)
      VALUES ${newNotifRows}
    `;
    await dbQuery(insertQuery);
  }
}

function prepareIOSNotification(
  iosID: string,
  unreadCount: number,
): apn.Notification {
  const notification = new apn.Notification();
  notification.contentAvailable = true;
  notification.badge = unreadCount;
  notification.topic = 'org.squadcal.app';
  notification.payload = {
    managedAps: {
      action: 'CLEAR',
      notificationId: iosID,
    },
  };
  return notification;
}

function prepareAndroidNotification(
  notifID: string,
  unreadCount: number,
  threadID: string,
  codeVersion: ?number,
): Object {
  if (!codeVersion || codeVersion < 31) {
    return {
      data: {
        badge: unreadCount.toString(),
        custom_notification: JSON.stringify({
          rescind: 'true',
          notifID,
        }),
      },
    };
  }
  return {
    data: {
      badge: unreadCount.toString(),
      rescind: 'true',
      rescindID: notifID,
      threadID,
    },
  };
}

export { rescindPushNotifs };
<|endoftext|>


<commit_before>function FeedbackControl($scope, FeedbackControlService, FeedbackSignal, Template, FeedbackService) {

    var qs = (function(a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i) {
            var p=a[i].split('=');
            if (p.length != 2) continue;
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    })(window.location.search.substr(1).split('&'));

    var is_empty = function(obj) {
        return Object.keys(obj).length === 0;
    }

    var update_selected = function(action, id) {
        if (action == 'add' && $scope.selected.indexOf(id) == -1) {
            $scope.selected.push(id);
        }

        if (action == 'remove' && $scope.selected.indexOf(id) != -1) {
            $scope.selected.splice($scope.selected.indexOf(id), 1);
        }
    }

    var feedback_collect = function(n, mode, collect_type) {

        var me = n;
        var entity = $(".dashboard-feedback[feedback=" + me + "]");
        var entity_parent = entity.parents('.feedback-group');
        var score = entity.attr('score');
        var permission = entity.attr('permission');
        var catid = entity.attr('catid');
        var flag_data = $.parseJSON($(".flag-action[feedid=" + me + "]").attr("data-feed"));
        var mystatus;

        if(entity.hasClass('featured')) {
            mystatus = 'feature';
        }

        if(entity.hasClass('published')) {
            mystatus = 'publish';
        }

        if(
               (score >= 3 && permission == 1)
           || ((score >= 3 && permission == 0) && (mode == 'delete' || mode == 'restore' || mode == 'remove'))
           || ((score == 1 || score == 2) && (mode == 'delete' || mode == 'restore' || mode == 'remove'))
          )  {

            entity.hide();
            var child_count = entity_parent.children('.dashboard-feedback:visible');

            if(child_count.length == 0) {
                entity_parent.hide();
            }

            if(collect_type == 'feedid') {
                return me;
            }

            if(collect_type == 'catid') {
                return catid;
            }

            if(collect_type == 'current_status') {
                return mystatus;
            }

            if(collect_type == 'flag_data') {
                flag_data.status = (flag_data.status == "unflag") ? "flag" : "unflag";
                return flag_data;
            }

        }
    }

    var current_url = window.location.pathname;

    var url_params = function() {
        var prmstr = window.location.search.substr(1);
        var prmarr = prmstr.split ("&");
        var params = {};

        for ( var i = 0; i < prmarr.length; i++) {
            var tmparr = prmarr[i].split("=");
                params[tmparr[0]] = tmparr[1];
        }

        return params;
    }

    $scope.selected   = [];
    $scope.uri_params = [];
    var checkboxes = $(".feed-checkbox");

    $scope.status_select_value = 'none';
    $scope.date_filter     = (!is_empty(qs) && qs['date']) ? qs['date'] : 'none';
    $scope.priority_filter = (!is_empty(qs) && qs['priority']) ? qs['priority'] : 'none';
    $scope.status_filter   = (!is_empty(qs) && qs['status']) ? qs['status'] : 'none';
    $scope.rating_filter   = (!is_empty(qs) && qs['rating']) ? qs['rating'] : 'none';

    $scope.feedback_status = function($event) {

        var target = $($event.target);
        //this is the intention feed. Feed that will go into the database for updating
        var feed = $.parseJSON(target.attr('data-feed'));

        //get flag data feed assuming you've clicked on feedback controls
        var ulflag = target.parents('ul').children('.flag-action').attr('data-feed');

        //get flag data feed assuming you've clicked on delete button
        var delflag = target.parents('.grids').siblings('.grids').children('ul').children('.flag-action').attr('data-feed');

        //either way, we are all fucked
        var flag_data, flagged;
        if(ulflag) {
            flag_data = $.parseJSON(ulflag);
        } else {
            flag_data = $.parseJSON(delflag);
        }

        flagged = (flag_data.status == "unflag") ? "flag" : "unflag";

        //below are the feed states used for undoing.
        if(current_url.match(/inbox\/all|deleted/g)) {
            var current = {
                id: feed.id
              , catid: Template.default_category_id
              , status: feed.status
              , isflag: flagged
              , origin: Template.current_inbox_state
            }
        }

        if(current_url.match(/published/g)) {
            var current = {
                id: feed.id
              , catid: Template.default_category_id
              , status: feed.status
              , isflag: flagged
              , origin: feed.origin
            }
        }

        if(current_url.match(/filed/g)) {
            var current = {
                id: feed.id
              , catid: feed.catid
              , status: feed.status
              , isflag: flagged
              , origin: Template.current_inbox_state
            }
        }

        var process = function() {
            FeedbackSignal.current_state(current);
            feed.origin = Template.current_inbox_state;
            FeedbackControlService.change_status(feed, true);
        }

        if(feed.status != "remove") {
            process();
        } else {
            if(confirm("Warning! You are about to permanently delete this feedback. There is no undo.")) {
                process();
            }
        }

    }

    $scope.update_selection = function($event, id) {
        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');
        update_selected(action, id);
    }

    $scope.change_value_status = function() {
        if( $('input[type=checkbox].feed-checkbox:checked').length > 0 ) {

            var selected  = [];
            var catids    = [];
            var origin    = [];
            var flag_data = [];
            var ids  = $scope.selected;
            var mode = $scope.status_select_value;
            var feed = {};

            //refactor this you lazy bastard
            if(mode == "remove") {
                if(confirm("Are you sure you want to permanently remove this feedback? There is no undo.")) {
                    for(var i=0; i < ids.length; ++i) {
                        selected.push(feedback_collect(ids[i], mode, 'feedid'));
                        catids.push(feedback_collect(ids[i], mode, 'catid'));
                        origin.push(feedback_collect(ids[i], mode, 'current_status'));
                        flag_data.push(feedback_collect(ids[i], mode, 'flag_data'));
                    }
                } else {
                    $('input[type=checkbox].feed-checkbox:checked, .sorter-checkbox:checked').click();
                }
            } else {
                for(var i=0; i < ids.length; ++i) {
                    selected.push(feedback_collect(ids[i], mode, 'feedid'));
                    catids.push(feedback_collect(ids[i], mode, 'catid'));
                    origin.push(feedback_collect(ids[i], mode, 'current_status'));
                    flag_data.push(feedback_collect(ids[i], mode, 'flag_data'));
                }
            }

            var clean_selection = selected.filter(function(n) { return n });

            if(clean_selection.length > 0) {

                if(current_url.match(/filed/g)) {
                    var feed = {
                        id: clean_selection
                      , status: mode
                      , isflag: flag_data
                      , catid:  catids
                      , origin: Template.current_inbox_state
                    }
                } else if(current_url.match(/published/g)) {
                    var feed = {
                        id: clean_selection
                      , status: mode
                      , isflag: flag_data
                      , catid: Template.default_category_id
                      , origin: origin
                    }
                } else {
                    var feed = {
                        id: clean_selection
                      , status: mode
                      , isflag: flag_data
                      , catid: Template.default_category_id
                      , origin: Template.current_inbox_state
                    }
                }

                //FeedbackSignal.current_state(feed);
                //FeedbackControlService.change_status(feed, true);

                $(".checky-box-container").show();

                if(mode == "remove") {

                    window.location = "/inbox/deleted/all";
                    $(".sorter-checkbox:checked").attr('checked', false);
                    /*
                    var status_message = FeedbackControlService.jsonmsg.feedback_status_change;
                    if(status_message == "success") {
                        window.location = "/inbox/deleted/all";
                        $(".sorter-checkbox:checked").attr('checked', false);
                    }
                    */
                }

            } else {
                if(mode != "remove") {
                    alert("I am sorry. I am unable to perform this operation. Your feedback is either rated as Poor or is given Private permission by it's sender.");
                }
            }

            if($('.feed-checkbox').is(":checked")) { $('.feed-checkbox').prop("checked", false); }

            selected = [];
            clean_selection = [];
            $scope.selected = [];
            $scope.status_select_value = 'none';
        }
    }

    $scope.select_all = function($event) {

        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');

        for(var i=0; i < checkboxes.length; i++) {

            var entity = $(checkboxes[i]);
            var myparent = entity.parents('.dashboard-feedback');

            //if action is add then click on checkboxes if not click again to deselect
            if(action == "add") {
                if(!entity.is(":checked")) {
                    entity.click();
                }
            } else {
                entity.click();
            }

            update_selected(action, parseInt(entity.val(), 10));
        }
    }

    $scope.process_filter = function() {
        var data = {}
        if($scope.rating_filter != 'none') {
            data.rating = $scope.rating_filter;
        }

        if($scope.status_filter != 'none') {
            data.status = $scope.status_filter;
        }

        if($scope.priority_filter != 'none') {
            data.priority = $scope.priority_filter;
        }

        if($scope.date_filter != 'none') {
            data.date = $scope.date_filter;
        }

        var result = $.param(data);
        var params = url_params();
        var page = '';
        if('page' in params) { page = '&page=' + params.page; }
        var str = '?' + result + page;
        document.location.search = str;
    }

    $scope.fast_forward = function(email, feedid) {
        FeedbackService.send_fastforward(email, feedid);
    }

    $scope.$on('expungeFeedId', function() {
        $scope.selected = [];
    })
}

function CheckyBox($scope, FeedbackSignal, FeedbackControlService) {

    $scope.status_selection, $scope.id, $scope.data;

    $scope.undo = function() {
        FeedbackControlService.change_status($scope.data);
    }

    $scope.close = function() {
        location.reload();
    }

    $scope.hide = function() {
        $(".checky-box-container").hide();
    }

    $scope.$on('checkFeedbackStatus', function() {
        console.log("Receiving...");
        var data = FeedbackSignal.get_data();
        $scope.data = data;
        $scope.status_selection = data.status;
    });
}
<commit_msg>qatar<commit_after>function FeedbackControl($scope, FeedbackControlService, FeedbackSignal, Template, FeedbackService) {

    var qs = (function(a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i) {
            var p=a[i].split('=');
            if (p.length != 2) continue;
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    })(window.location.search.substr(1).split('&'));

    var is_empty = function(obj) {
        return Object.keys(obj).length === 0;
    }

    var update_selected = function(action, id) {
        if (action == 'add' && $scope.selected.indexOf(id) == -1) {
            $scope.selected.push(id);
        }

        if (action == 'remove' && $scope.selected.indexOf(id) != -1) {
            $scope.selected.splice($scope.selected.indexOf(id), 1);
        }
    }

    var feedback_collect = function(n, mode, collect_type) {

        var me = n;
        var entity = $(".dashboard-feedback[feedback=" + me + "]");
        var entity_parent = entity.parents('.feedback-group');
        var score = entity.attr('score');
        var permission = entity.attr('permission');
        var catid = entity.attr('catid');
        var flag_data = $.parseJSON($(".flag-action[feedid=" + me + "]").attr("data-feed"));
        var mystatus;

        if(entity.hasClass('featured')) {
            mystatus = 'feature';
        }

        if(entity.hasClass('published')) {
            mystatus = 'publish';
        }

        if(
               (score >= 3 && permission == 1)
           || ((score >= 3 && permission == 0) && (mode == 'delete' || mode == 'restore' || mode == 'remove'))
           || ((score == 1 || score == 2) && (mode == 'delete' || mode == 'restore' || mode == 'remove'))
          )  {

            entity.hide();
            var child_count = entity_parent.children('.dashboard-feedback:visible');

            if(child_count.length == 0) {
                entity_parent.hide();
            }

            if(collect_type == 'feedid') {
                return me;
            }

            if(collect_type == 'catid') {
                return catid;
            }

            if(collect_type == 'current_status') {
                return mystatus;
            }

            if(collect_type == 'flag_data') {
                flag_data.status = (flag_data.status == "unflag") ? "flag" : "unflag";
                return flag_data;
            }

        }
    }

    var current_url = window.location.pathname;

    var url_params = function() {
        var prmstr = window.location.search.substr(1);
        var prmarr = prmstr.split ("&");
        var params = {};

        for ( var i = 0; i < prmarr.length; i++) {
            var tmparr = prmarr[i].split("=");
                params[tmparr[0]] = tmparr[1];
        }

        return params;
    }

    $scope.selected   = [];
    $scope.uri_params = [];
    var checkboxes = $(".feed-checkbox");

    $scope.status_select_value = 'none';
    $scope.date_filter     = (!is_empty(qs) && qs['date']) ? qs['date'] : 'none';
    $scope.priority_filter = (!is_empty(qs) && qs['priority']) ? qs['priority'] : 'none';
    $scope.status_filter   = (!is_empty(qs) && qs['status']) ? qs['status'] : 'none';
    $scope.rating_filter   = (!is_empty(qs) && qs['rating']) ? qs['rating'] : 'none';

    $scope.feedback_status = function($event) {

        var target = $($event.target);
        //this is the intention feed. Feed that will go into the database for updating
        var feed = $.parseJSON(target.attr('data-feed'));

        //get flag data feed assuming you've clicked on feedback controls
        var ulflag = target.parents('ul').children('.flag-action').attr('data-feed');

        //get flag data feed assuming you've clicked on delete button
        var delflag = target.parents('.grids').siblings('.grids').children('ul').children('.flag-action').attr('data-feed');

        //either way, we are all fucked
        var flag_data, flagged;
        if(ulflag) {
            flag_data = $.parseJSON(ulflag);
        } else {
            flag_data = $.parseJSON(delflag);
        }

        flagged = (flag_data.status == "unflag") ? "flag" : "unflag";

        //below are the feed states used for undoing.
        if(current_url.match(/inbox\/all|deleted/g)) {
            var current = {
                id: feed.id
              , catid: Template.default_category_id
              , status: feed.status
              , isflag: flagged
              , origin: Template.current_inbox_state
            }
        }

        if(current_url.match(/published/g)) {
            var current = {
                id: feed.id
              , catid: Template.default_category_id
              , status: feed.status
              , isflag: flagged
              , origin: feed.origin
            }
        }

        if(current_url.match(/filed/g)) {
            var current = {
                id: feed.id
              , catid: feed.catid
              , status: feed.status
              , isflag: flagged
              , origin: Template.current_inbox_state
            }
        }

        var process = function() {
            FeedbackSignal.current_state(current);
            feed.origin = Template.current_inbox_state;
            FeedbackControlService.change_status(feed, true);
        }

        if(feed.status != "remove") {
            process();
        } else {
            if(confirm("Warning! You are about to permanently delete this feedback. There is no undo.")) {
                process();
            }
        }

    }

    $scope.update_selection = function($event, id) {
        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');
        update_selected(action, id);
    }

    $scope.change_value_status = function() {
        if( $('input[type=checkbox].feed-checkbox:checked').length > 0 ) {

            var selected  = [];
            var catids    = [];
            var origin    = [];
            var flag_data = [];
            var ids  = $scope.selected;
            var mode = $scope.status_select_value;
            var feed = {};

            //refactor this you lazy bastard
            if(mode == "remove") {
                if(confirm("Are you sure you want to permanently remove this feedback? There is no undo.")) {
                    for(var i=0; i < ids.length; ++i) {
                        selected.push(feedback_collect(ids[i], mode, 'feedid'));
                        catids.push(feedback_collect(ids[i], mode, 'catid'));
                        origin.push(feedback_collect(ids[i], mode, 'current_status'));
                        flag_data.push(feedback_collect(ids[i], mode, 'flag_data'));
                    }
                } else {
                    $('input[type=checkbox].feed-checkbox:checked, .sorter-checkbox:checked').click();
                }
            } else {
                for(var i=0; i < ids.length; ++i) {
                    selected.push(feedback_collect(ids[i], mode, 'feedid'));
                    catids.push(feedback_collect(ids[i], mode, 'catid'));
                    origin.push(feedback_collect(ids[i], mode, 'current_status'));
                    flag_data.push(feedback_collect(ids[i], mode, 'flag_data'));
                }
            }

            var clean_selection = selected.filter(function(n) { return n });

            if(clean_selection.length > 0) {

                if(current_url.match(/filed/g)) {
                    var feed = {
                        id: clean_selection
                      , status: mode
                      , isflag: flag_data
                      , catid:  catids
                      , origin: Template.current_inbox_state
                    }
                } else if(current_url.match(/published/g)) {
                    var feed = {
                        id: clean_selection
                      , status: mode
                      , isflag: flag_data
                      , catid: Template.default_category_id
                      , origin: origin
                    }
                } else {
                    var feed = {
                        id: clean_selection
                      , status: mode
                      , isflag: flag_data
                      , catid: Template.default_category_id
                      , origin: Template.current_inbox_state
                    }
                }

                //FeedbackSignal.current_state(feed);
                //FeedbackControlService.change_status(feed, true);

                $(".checky-box-container").show();

                if(mode == "remove") {

                    window.location = "/inbox/deleted/all";
                    //$(".sorter-checkbox:checked").attr('checked', false);
                    /*
                    var status_message = FeedbackControlService.jsonmsg.feedback_status_change;
                    if(status_message == "success") {
                        window.location = "/inbox/deleted/all";
                        $(".sorter-checkbox:checked").attr('checked', false);
                    }
                    */
                }

            } else {
                if(mode != "remove") {
                    alert("I am sorry. I am unable to perform this operation. Your feedback is either rated as Poor or is given Private permission by it's sender.");
                }
            }

            if($('.feed-checkbox').is(":checked")) { $('.feed-checkbox').prop("checked", false); }

            selected = [];
            clean_selection = [];
            $scope.selected = [];
            $scope.status_select_value = 'none';
        }
    }

    $scope.select_all = function($event) {

        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');

        for(var i=0; i < checkboxes.length; i++) {

            var entity = $(checkboxes[i]);
            var myparent = entity.parents('.dashboard-feedback');

            //if action is add then click on checkboxes if not click again to deselect
            if(action == "add") {
                if(!entity.is(":checked")) {
                    entity.click();
                }
            } else {
                entity.click();
            }

            update_selected(action, parseInt(entity.val(), 10));
        }
    }

    $scope.process_filter = function() {
        var data = {}
        if($scope.rating_filter != 'none') {
            data.rating = $scope.rating_filter;
        }

        if($scope.status_filter != 'none') {
            data.status = $scope.status_filter;
        }

        if($scope.priority_filter != 'none') {
            data.priority = $scope.priority_filter;
        }

        if($scope.date_filter != 'none') {
            data.date = $scope.date_filter;
        }

        var result = $.param(data);
        var params = url_params();
        var page = '';
        if('page' in params) { page = '&page=' + params.page; }
        var str = '?' + result + page;
        document.location.search = str;
    }

    $scope.fast_forward = function(email, feedid) {
        FeedbackService.send_fastforward(email, feedid);
    }

    $scope.$on('expungeFeedId', function() {
        $scope.selected = [];
    })
}

function CheckyBox($scope, FeedbackSignal, FeedbackControlService) {

    $scope.status_selection, $scope.id, $scope.data;

    $scope.undo = function() {
        FeedbackControlService.change_status($scope.data);
    }

    $scope.close = function() {
        location.reload();
    }

    $scope.hide = function() {
        $(".checky-box-container").hide();
    }

    $scope.$on('checkFeedbackStatus', function() {
        console.log("Receiving...");
        var data = FeedbackSignal.get_data();
        $scope.data = data;
        $scope.status_selection = data.status;
    });
}
<|endoftext|>


<commit_before>module.exports = {
  email: email => {
    if (!/^[^@ ]+@[^@ ]+$/i.test(email)) {
      return 'invalidEmail'
    }
  },
  ssn: ssn => {
    if (!/^\d{11,12}$/.test(ssn) || !validateSSN(ssn.toString())) {
      return 'invalidSSN'
    }
  },
  zipcode: zipcode => {
    if (!/^\d{4}$/.test(zipcode)) {
      return 'invalidZipcode'
    }
  },
  mobile: mobile => {
    if (!/^((0047)?|(\+47)?|(47)?)\d{8}$/.test(mobile)) {
      return 'invalidPhoneNumber'
    }
  },
  city: city => {
    if (!/^[A-Za-z-øæåÆØÅ]{2,}$/.test(city)) {
      return 'invalidCity'
    }
  },
  year: year => {
    return validateYear(year)
  },
  yearFrom: year => {
    return validateAllYears(year)
  },
  yearTo: year => {
    return validateAllYears(year)
  },
  month: month => {
    if (!/^\d{1,2}$/.test(month) || month < 1 || month > 12) {
      return 'invalidMonth'
    }
  },
  day: day => {
    if (!/^\d{1,2}$/.test(day) || day < 1 || day > 31) {
      return 'invalidDay'
    }
  },
  pin: pin => {
    if (!/^\d{4}$/.test(pin)) {
      return 'invalidPin'
    }
  },
  repeatPin: (repeatPin, values) => {
    if (!values.pin) {
      return
    }
    if (!values.repeatPin) {
      return
    }
    if (values.pin !== values.repeatPin) {
      return 'pinsMustBeEqual'
    }
  },
  date: date => {
    if (!/(0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[012])\.(19|20)\d\d$/.test(date)) {
      return 'invalidNoDate'
    }
  },
  dateCurrentAndAbove: date => {
    return dateCurrentAndAbove(date)
  }

}

function dateCurrentAndAbove (date) {
  const pattern = /(\d{2})\.(\d{2})\.(\d{4})/
  if (!/(0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[012])\.(19|20)\d\d$/.test(date) || new Date (date.replace(pattern,'$3-$2-$1')) < new Date()) {
    return 'invalidNoDate'
  }
}

function validateYear (year) {
  if (!/^\d{4}$/.test(year) || year < 1900 || year >= new Date().getFullYear()) {
    return 'invalidYear'
  }
}

function validateAllYears (year) {
  if (!/^\d{4}$/.test(year)) {
    return 'invalidYear'
  }
}

function validateSSN (ssn) {
  if (ssn.length === 11) {
    return validateFNumber(ssn) || validateDNumber(ssn)
  } else if (ssn.length === 12) {
    return validateDUFNumber(ssn)
  } else {
    return false
  }
}

function validateFNumber (ssn) {
  if (parseInt(ssn.charAt(0)) > 3) {
    return false
  } else if (parseInt(ssn.charAt(2)) > 1) {
    return false
  } else {
    return isValidFNumberChecksum(ssn)
  }
}

function isValidFNumberChecksum (ssn) {
  const digits = []
  for (let i = 0; i < ssn.length; i++) {
    digits.push(parseInt(ssn.charAt(i)))
  }
  const multipliers1 = [ 3, 7, 6, 1, 8, 9, 4, 5, 2 ]
  let ctrl = 0
  for (let i = 0; i < multipliers1.length; i++) {
    ctrl += digits[ i ] * multipliers1[ i ]
  }
  ctrl = ctrl % 11
  let controlDigit1 = 0
  if (ctrl !== 0) {
    controlDigit1 = 11 - ctrl
  }
  if (controlDigit1 === 10) {
    return false
  }
  const multipliers2 = [ 5, 4, 3, 2, 7, 6, 5, 4, 3, 2 ]
  let ctrl2 = 0
  for (let i = 0; i < multipliers2.length - 1; i++) {
    ctrl2 += multipliers2[ i ] * digits[ i ]
  }
  ctrl2 += controlDigit1 * multipliers2[ multipliers2.length - 1 ]
  ctrl2 = ctrl2 % 11
  let controlDigit2 = 0
  if (ctrl2 !== 0) {
    controlDigit2 = 11 - ctrl2
  }
  if (controlDigit2 === 10) {
    return false
  }
  return controlDigit1 === digits[ 9 ] && controlDigit2 === digits[ 10 ]
}

function validateDNumber (ssn) {
  if (parseInt(ssn.charAt(0)) > 7 || parseInt(ssn.charAt(0) < 4)) {
    return false
  } else if (parseInt(ssn.charAt(2)) > 1) {
    return false
  } else {
    return isValidFNumberChecksum(ssn)
  }
}

function validateDUFNumber (ssn) {
  const control = parseInt(ssn.substring(10))
  const digits = ssn.substring(0, 10)
  const multipliers = [ 4, 6, 3, 2, 4, 6, 3, 2, 7, 5 ]

  let temp = 0
  for (let i = 0; i < 10; i++) {
    temp += multipliers[ i ] * parseInt(digits.charAt(i))
  }

  temp = temp % 11
  return temp === control
}
<commit_msg>Patron client: linting fix<commit_after>module.exports = {
  email: email => {
    if (!/^[^@ ]+@[^@ ]+$/i.test(email)) {
      return 'invalidEmail'
    }
  },
  ssn: ssn => {
    if (!/^\d{11,12}$/.test(ssn) || !validateSSN(ssn.toString())) {
      return 'invalidSSN'
    }
  },
  zipcode: zipcode => {
    if (!/^\d{4}$/.test(zipcode)) {
      return 'invalidZipcode'
    }
  },
  mobile: mobile => {
    if (!/^((0047)?|(\+47)?|(47)?)\d{8}$/.test(mobile)) {
      return 'invalidPhoneNumber'
    }
  },
  city: city => {
    if (!/^[A-Za-z-øæåÆØÅ]{2,}$/.test(city)) {
      return 'invalidCity'
    }
  },
  year: year => {
    return validateYear(year)
  },
  yearFrom: year => {
    return validateAllYears(year)
  },
  yearTo: year => {
    return validateAllYears(year)
  },
  month: month => {
    if (!/^\d{1,2}$/.test(month) || month < 1 || month > 12) {
      return 'invalidMonth'
    }
  },
  day: day => {
    if (!/^\d{1,2}$/.test(day) || day < 1 || day > 31) {
      return 'invalidDay'
    }
  },
  pin: pin => {
    if (!/^\d{4}$/.test(pin)) {
      return 'invalidPin'
    }
  },
  repeatPin: (repeatPin, values) => {
    if (!values.pin) {
      return
    }
    if (!values.repeatPin) {
      return
    }
    if (values.pin !== values.repeatPin) {
      return 'pinsMustBeEqual'
    }
  },
  date: date => {
    if (!/(0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[012])\.(19|20)\d\d$/.test(date)) {
      return 'invalidNoDate'
    }
  },
  dateCurrentAndAbove: date => {
    return dateCurrentAndAbove(date)
  }

}

function dateCurrentAndAbove (date) {
  const pattern = /(\d{2})\.(\d{2})\.(\d{4})/
  if (!/(0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[012])\.(19|20)\d\d$/.test(date) || new Date(date.replace(pattern, '$3-$2-$1')) < new Date()) {
    return 'invalidNoDate'
  }
}

function validateYear (year) {
  if (!/^\d{4}$/.test(year) || year < 1900 || year >= new Date().getFullYear()) {
    return 'invalidYear'
  }
}

function validateAllYears (year) {
  if (!/^\d{4}$/.test(year)) {
    return 'invalidYear'
  }
}

function validateSSN (ssn) {
  if (ssn.length === 11) {
    return validateFNumber(ssn) || validateDNumber(ssn)
  } else if (ssn.length === 12) {
    return validateDUFNumber(ssn)
  } else {
    return false
  }
}

function validateFNumber (ssn) {
  if (parseInt(ssn.charAt(0)) > 3) {
    return false
  } else if (parseInt(ssn.charAt(2)) > 1) {
    return false
  } else {
    return isValidFNumberChecksum(ssn)
  }
}

function isValidFNumberChecksum (ssn) {
  const digits = []
  for (let i = 0; i < ssn.length; i++) {
    digits.push(parseInt(ssn.charAt(i)))
  }
  const multipliers1 = [ 3, 7, 6, 1, 8, 9, 4, 5, 2 ]
  let ctrl = 0
  for (let i = 0; i < multipliers1.length; i++) {
    ctrl += digits[ i ] * multipliers1[ i ]
  }
  ctrl = ctrl % 11
  let controlDigit1 = 0
  if (ctrl !== 0) {
    controlDigit1 = 11 - ctrl
  }
  if (controlDigit1 === 10) {
    return false
  }
  const multipliers2 = [ 5, 4, 3, 2, 7, 6, 5, 4, 3, 2 ]
  let ctrl2 = 0
  for (let i = 0; i < multipliers2.length - 1; i++) {
    ctrl2 += multipliers2[ i ] * digits[ i ]
  }
  ctrl2 += controlDigit1 * multipliers2[ multipliers2.length - 1 ]
  ctrl2 = ctrl2 % 11
  let controlDigit2 = 0
  if (ctrl2 !== 0) {
    controlDigit2 = 11 - ctrl2
  }
  if (controlDigit2 === 10) {
    return false
  }
  return controlDigit1 === digits[ 9 ] && controlDigit2 === digits[ 10 ]
}

function validateDNumber (ssn) {
  if (parseInt(ssn.charAt(0)) > 7 || parseInt(ssn.charAt(0) < 4)) {
    return false
  } else if (parseInt(ssn.charAt(2)) > 1) {
    return false
  } else {
    return isValidFNumberChecksum(ssn)
  }
}

function validateDUFNumber (ssn) {
  const control = parseInt(ssn.substring(10))
  const digits = ssn.substring(0, 10)
  const multipliers = [ 4, 6, 3, 2, 4, 6, 3, 2, 7, 5 ]

  let temp = 0
  for (let i = 0; i < 10; i++) {
    temp += multipliers[ i ] * parseInt(digits.charAt(i))
  }

  temp = temp % 11
  return temp === control
}
<|endoftext|>


<commit_before>/*global ETHelper,TemplateUpdater,Technology*/
var TechnologiesForm = (function () {
    'use strict';

    var template = null;

    /*
     * Loops over all the technology <div> tags in the html and extract all the data
     * attributes.
     * It than writes the data several hidden <div> tags
     */
    function parseHarmonicaToJSON() {
        var tableProfile = $(".technologies .technology:not(.hidden)").toArray().map(function (target) {
                return $(target).underscorizedData();
            }),
            groupedByNode = ETHelper.groupBy(tableProfile, 'node');

        $("#technology_distribution").text(JSON.stringify(tableProfile));
        $("#testing_ground_technology_profile").text(JSON.stringify(groupedByNode));
    }

    function updateJSON() {
        var type   = $(this).data('type'),
            target = $(this).parents(".technology"),
            value  = $(this).val();

        target.set(type, value);

        parseHarmonicaToJSON();
    }

    function updateTemplate() {
        new TemplateUpdater(template, this).update();
    }

    function addOnChangeListener() {
        parseHarmonicaToJSON();

        $(this).find("input, select")
            .off('change.json_update')
            .on('change.json_update', updateJSON);
    }

    function addNewTechnologyRow(e) {
        e.preventDefault();

        var newTemplate = template.clone(true, true);

        new TemplateUpdater(newTemplate, $(this).parents(".input-group").find("select")).increaseCompositeValue();
        new Technology(newTemplate).add(this);

        AddedTechnologiesValidator.validate();

        addOnChangeListener.call(newTemplate);
    }

    function toggleAdvancedFeatures(e) {
        e.preventDefault();

        $(this).parents(".technology").find(".editable.advanced").toggleClass("hidden");
    }

    /*
     * Checks if a technology can be removed from the table.
     * For instance if you want to remove a buffer from the table and it still has
     * technologies attached to it, it should alert the user that that is not possible.
     */
    function removeable() {
        var canBeRemoved = true,
            technology = $(this).parents(".technology"),
            target = $(this).parents(".technologies");

        target.find(".technology .buffer select:visible").each(function () {
            if ($(this).val() === technology.data('compositeValue')) {
                canBeRemoved = false;
                return false;
            }
        });

        return canBeRemoved;
    }

    function removeBufferOption() {
        if (this.composite) {
            $(".buffer_template select, .technology .buffer select")
                .selectedOption(this.compositeValue).remove();
        }
    }

    function removeTechnologyRow(e) {
        e.preventDefault();

        var technology = $(this).parents(".technology");

        if (removeable.call(this)) {
            removeBufferOption.call(technology.data());

            technology.remove();

            AddedTechnologiesValidator.validate();
        } else {
            alert("There are technologies that use this buffer, remove these first before removing this buffer");
        }

        parseHarmonicaToJSON();
    }

    function addListenersToNewTechnology() {
        $(".technologies .technology").find("input, select").on('change', updateJSON);

        $(".add-technology select").off().on("change", updateTemplate);
        $(".add-technology button").on("click", addNewTechnologyRow);
        $(".technology .remove-row").on("click", removeTechnologyRow);
        $(".technology .show-advanced").on("click", toggleAdvancedFeatures);

        $(".add-technology select").first().trigger('change');
    }

    TechnologiesForm.prototype = {
        append: function () {
            $(".technologies .technology:not(.hidden)").each(function () {
                new Technology(this).update();

                addOnChangeListener.call(this);
            });

            addListenersToNewTechnology.call(this);
            parseHarmonicaToJSON.call(this);

            AddedTechnologiesValidator.validate();
        }
    };

    function TechnologiesForm() {
        template = $(".technology_template .technology");
    }

    return TechnologiesForm;
}());

$(document).on("page:change", function () {
    'use strict';

    if ($("#profiles-table").length > 0) {
        window.currentTechnologiesForm = new TechnologiesForm();
        window.currentTechnologiesForm.append();
    }
});
<commit_msg>Mark the form as 'edited' otherwise it doesn't save<commit_after>/*global ETHelper,TemplateUpdater,Technology*/
var TechnologiesForm = (function () {
    'use strict';

    var template = null;

    /*
     * Loops over all the technology <div> tags in the html and extract all the data
     * attributes.
     * It than writes the data several hidden <div> tags
     */
    function parseHarmonicaToJSON() {
        var tableProfile = $(".technologies .technology:not(.hidden)").toArray().map(function (target) {
                return $(target).underscorizedData();
            }),
            groupedByNode = ETHelper.groupBy(tableProfile, 'node');

        $("#technology_distribution").text(JSON.stringify(tableProfile));
        $("#testing_ground_technology_profile").text(JSON.stringify(groupedByNode));
    }

    function markAsEditing() {
      $("ul.nav.nav-tabs li a[href=#technologies]").addClass("editing");
    }

    function updateJSON() {
        var type   = $(this).data('type'),
            target = $(this).parents(".technology"),
            value  = $(this).val();

        target.set(type, value);

        parseHarmonicaToJSON();
        markAsEditing();
    }

    function updateTemplate() {
        new TemplateUpdater(template, this).update();
    }

    function addOnChangeListener() {
        parseHarmonicaToJSON();

        $(this).find("input, select")
            .off('change.json_update')
            .on('change.json_update', updateJSON);
    }

    function addNewTechnologyRow(e) {
        e.preventDefault();

        var newTemplate = template.clone(true, true);

        new TemplateUpdater(newTemplate, $(this).parents(".input-group").find("select")).increaseCompositeValue();
        new Technology(newTemplate).add(this);

        AddedTechnologiesValidator.validate();

        addOnChangeListener.call(newTemplate);
        markAsEditing();
    }

    function toggleAdvancedFeatures(e) {
        e.preventDefault();

        $(this).parents(".technology").find(".editable.advanced").toggleClass("hidden");
    }

    /*
     * Checks if a technology can be removed from the table.
     * For instance if you want to remove a buffer from the table and it still has
     * technologies attached to it, it should alert the user that that is not possible.
     */
    function removeable() {
        var canBeRemoved = true,
            technology = $(this).parents(".technology"),
            target = $(this).parents(".technologies");

        target.find(".technology .buffer select:visible").each(function () {
            if ($(this).val() === technology.data('compositeValue')) {
                canBeRemoved = false;
                return false;
            }
        });

        return canBeRemoved;
    }

    function removeBufferOption() {
        if (this.composite) {
            $(".buffer_template select, .technology .buffer select")
                .selectedOption(this.compositeValue).remove();
        }
    }

    function removeTechnologyRow(e) {
        e.preventDefault();

        var technology = $(this).parents(".technology");

        if (removeable.call(this)) {
            removeBufferOption.call(technology.data());

            technology.remove();

            AddedTechnologiesValidator.validate();
        } else {
            alert("There are technologies that use this buffer, remove these first before removing this buffer");
        }

        parseHarmonicaToJSON();
        markAsEditing();
    }

    function addListenersToNewTechnology() {
        $(".technologies .technology").find("input, select").on('change', updateJSON);

        $(".add-technology select").off().on("change", updateTemplate);
        $(".add-technology button").on("click", addNewTechnologyRow);
        $(".technology .remove-row").on("click", removeTechnologyRow);
        $(".technology .show-advanced").on("click", toggleAdvancedFeatures);

        $(".add-technology select").first().trigger('change');
    }

    TechnologiesForm.prototype = {
        append: function () {
            $(".technologies .technology:not(.hidden)").each(function () {
                new Technology(this).update();

                addOnChangeListener.call(this);
            });

            addListenersToNewTechnology.call(this);
            parseHarmonicaToJSON.call(this);

            AddedTechnologiesValidator.validate();
        }
    };

    function TechnologiesForm() {
        template = $(".technology_template .technology");
    }

    return TechnologiesForm;
}());

$(document).on("page:change", function () {
    'use strict';

    if ($("#profiles-table").length > 0) {
        window.currentTechnologiesForm = new TechnologiesForm();
        window.currentTechnologiesForm.append();
    }
});
<|endoftext|>


<commit_before>function SettingCtgyCtrl($scope, Category) {

    $scope.cat = Category.fetch().data;

    $scope.get_category = function() {
        return $scope.cat;
    }

    $scope.add = function() {
        if($scope.category_name == 'undefined' || $scope.category_name == null)  {
            alert("Please provide a category name.");
        } else {
            Category.write($scope.category_name);
            $scope.category_name = null;
        }
    }

    $scope.$on('fetchCategory', function()  {
        $scope.cat = Category.fetch().data;
    });
}
<commit_msg>oh ye<commit_after>function SettingCtgyCtrl($scope, Category) {

    $scope.cat = Category.fetch().data;

    $scope.get_category = function() {
        return $scope.cat;
    }

    $scope.add = function() {
        if($scope.category_name == 'undefined' || $scope.category_name == null)  {
            alert("Please provide a category name.");
        } else {
            Category.write($scope.category_name);
            $scope.category_name = null;
        }
    }

    $scope.$on('fetchCategory', function()  {
        console.log("Fetching Category");
        $scope.cat = Category.fetch().data;
    });
}
<|endoftext|>


<commit_before>ReportsKit.Chart = (function(options) {
  var self = this;

  self.initialize = function(options) {
    self.options = options;
    self.report = options.report;
    self.el = self.report.el;

    self.canvas = $('<canvas />').appendTo(self.report.visualizationEl);
  };

  self.render = function() {
    var path = self.el.data('path');
    var separator = path.indexOf('?') === -1 ? '?' : '&';
    path += separator + 'properties=' + encodeURIComponent(JSON.stringify(self.report.properties()));
    $.getJSON(path, function(response) {
      var data = response.data;
      var chartData = data.chart_data;
      var options = chartData.options;
      options = self.addAdditionalOptions(options, chartData.standard_options)

      var args = {
        type: data.type,
        data: chartData,
        options: options
      };

      if (self.chart) {
        self.chart.data.datasets = chartData.datasets;
        self.chart.data.labels = chartData.labels;
        self.chart.update();
      } else {
        self.chart = new Chart(self.canvas, args);
      }
    });
  };

  self.addAdditionalOptions = function(options, standardOptions) {
    var additionalOptions = {};
    var maxItems = standardOptions && standardOptions.legend && standardOptions.legend.max_items;
    if (maxItems) {
      additionalOptions = {
        legend: {
          labels: {
            filter: function(item) {
              return item.index < maxItems;
            }
          }
        }
      };
      options = $.extend(true, options, additionalOptions);
    }
    return options;
  };

  self.initialize(options);

  return self;
});
<commit_msg>Add copy for empty result sets in charts<commit_after>ReportsKit.Chart = (function(options) {
  var self = this;

  self.initialize = function(options) {
    self.options = options;
    self.report = options.report;
    self.el = self.report.el;

    self.noResultsEl = $('
No data was found
').appendTo(self.report.visualizationEl).hide();
    self.canvas = $('<canvas />').appendTo(self.report.visualizationEl);
  };

  self.render = function() {
    var path = self.el.data('path');
    var separator = path.indexOf('?') === -1 ? '?' : '&';
    path += separator + 'properties=' + encodeURIComponent(JSON.stringify(self.report.properties()));
    $.getJSON(path, function(response) {
      var data = response.data;
      var chartData = data.chart_data;
      var options = chartData.options;
      options = self.addAdditionalOptions(options, chartData.standard_options)

      var args = {
        type: data.type,
        data: chartData,
        options: options
      };

      if (self.chart) {
        self.chart.data.datasets = chartData.datasets;
        self.chart.data.labels = chartData.labels;
        self.chart.update();
      } else {
        self.chart = new Chart(self.canvas, args);
      }
      self.noResultsEl.toggle(self.chart.data.labels.length === 0);
    });
  };

  self.addAdditionalOptions = function(options, standardOptions) {
    var additionalOptions = {};
    var maxItems = standardOptions && standardOptions.legend && standardOptions.legend.max_items;
    if (maxItems) {
      additionalOptions = {
        legend: {
          labels: {
            filter: function(item) {
              return item.index < maxItems;
            }
          }
        }
      };
      options = $.extend(true, options, additionalOptions);
    }
    return options;
  };

  self.initialize(options);

  return self;
});
<|endoftext|>


<commit_before><commit_msg>small style fix<commit_after><|endoftext|>


<commit_before>Modernizr.load([{
  load: '//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js',
  callback: function() {
    if (!window.jQuery) {
      Modernizr.load('/javascripts/vendor/jquery.js');
    }
  },
  complete: function() {
    Modernizr.load([{
      test: window.JSON,
      nope: jsassets.json
    }, {
      test: navigator.geolocation,
      nope: jsassets.geolocation
    }, {
      load: jsassets.base
    }, {
      load: $.merge(jsassets.jqueryui, cssassets.jqueryui),
      complete: function() {
        $('.lang-fields').tabs();
        Effects.initialize();
      }
    }])
   $(document).ready(function() {
     Modernizr.load([{
      test: ($('.offline').length == 0 || (location.pathname != '/' && location.pathname.indexOf('/questions' != 0))),
      yep: jsassets.extra
    }, {
      test: Modernizr.websockets,
      nope: jsassets.websocket,
      complete: function() {
        ShapadoSocket.initialize();
        }
    },{
      test: $('meta[data-js=show]').length > 0 && $('.auto-link').length > 0,
      yep: jsassets.jqueryautovideo,
      complete: function(){
        if($.fn.autoVideo)
          $('.auto-link').autoVideo();
      }
    }, {
      test: $('meta[data-jqmath]').length > 0,
      yep: $.merge(eval($('meta[data-jqmath]').attr('data-jsassets')),eval($('meta[data-jqmath]').attr('data-cssassets')))
    }, {
      test: $('.autocomplete_for_tags').length > 0,
      yep: jsassets.jqautocomplete,
      callback: function() {
        $('.autocomplete_for_tags').ricodigoComplete();
      }
    },{
       test: $("input[type=color]").length>0,
       yep: jsassets.jpicker,
       complete: function(){
        if($.jPicker)
          Form.initialize();
       }
       }, {
          test: $("input[type=color]").length>0,
          yep: cssassets.jpicker
     }])
   })
  }
}]);<commit_msg>fix js length error<commit_after>Modernizr.load([{
  load: '//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js',
  callback: function() {
    if (!window.jQuery) {
      Modernizr.load('/javascripts/vendor/jquery.js');
    }
  },
  complete: function() {
    Modernizr.load([{
      test: window.JSON,
      nope: jsassets.json
    }, {
      test: navigator.geolocation,
      nope: jsassets.geolocation
    }, {
      load: jsassets.base
    }, {
      load: $.merge(jsassets.jqueryui, cssassets.jqueryui),
      complete: function() {
        $('.lang-fields').tabs();
        Effects.initialize();
      }
    }])
   $(document).ready(function() {
     Modernizr.load([{
      test: ($('.offline').length == 0 || (location.pathname != '/' && location.pathname.indexOf('/questions' != 0))),
      yep: jsassets.extra
    }, {
      test: Modernizr.websockets,
      nope: jsassets.websocket,
      complete: function() {
        ShapadoSocket.initialize();
        }
    },{
      test: $('meta[data-js=show]').length > 0 && $('.auto-link').length > 0,
      yep: jsassets.jqueryautovideo,
      complete: function(){
        if($.fn.autoVideo)
          $('.auto-link').autoVideo();
      }
    }, {
      test: $('meta[data-jqmath]').length > 0,
      yep: $.merge(eval($('meta[data-jqmath]').attr('data-jsassets'))||[],eval($('meta[data-jqmath]').attr('data-cssassets'))||[])
    }, {
      test: $('.autocomplete_for_tags').length > 0,
      yep: jsassets.jqautocomplete,
      callback: function() {
        $('.autocomplete_for_tags').ricodigoComplete();
      }
    },{
       test: $("input[type=color]").length>0,
       yep: jsassets.jpicker,
       complete: function(){
        if($.jPicker)
          Form.initialize();
       }
       }, {
          test: $("input[type=color]").length>0,
          yep: cssassets.jpicker
     }])
   })
  }
}]);<|endoftext|>