<commit_before>'use strict';

const BaseEmbed = require('./BaseEmbed.js');

const founderEmoji = {
  grandmaster: '<:grandmaster:329484751876653076>',
  master: '<:master:329484751570468867>',
  hunter: '<:hunter:329484751972990977>',
  disciple: '<:disciple:329484752098951168>',
};

const mrSigil = [
  '',
  'https://vignette2.wikia.nocookie.net/warframe/images/4/4e/Initiate.jpg/revision/latest?cb=20131207082819',
  'https://vignette3.wikia.nocookie.net/warframe/images/a/a4/Silver-initiate.jpg/revision/latest?cb=20131207083232',
  'https://vignette2.wikia.nocookie.net/warframe/images/8/8f/Gold-initiate.jpg/revision/latest?cb=20131207083401',
  'https://vignette2.wikia.nocookie.net/warframe/images/9/91/Novice.jpg/revision/latest?cb=20131207083549',
  'https://vignette2.wikia.nocookie.net/warframe/images/9/99/Silver-novice.jpg/revision/latest?cb=20131207085318',
  'https://vignette1.wikia.nocookie.net/warframe/images/6/69/Gold-novice.jpg/revision/latest?cb=20131207085328',
  'https://vignette2.wikia.nocookie.net/warframe/images/9/92/Disciple.jpg/revision/latest?cb=20131207085340',
  'https://vignette3.wikia.nocookie.net/warframe/images/f/f8/Silver-disciple.jpg/revision/latest?cb=20131207085348',
  'https://vignette2.wikia.nocookie.net/warframe/images/8/84/Gold-disciple.jpg/revision/latest?cb=20131207085356',
  'https://vignette4.wikia.nocookie.net/warframe/images/4/4b/Seeker.jpg/revision/latest?cb=20131207085405',
  'https://vignette3.wikia.nocookie.net/warframe/images/0/0e/Silver-seeker.jpg/revision/latest?cb=20131207085412',
  'https://vignette2.wikia.nocookie.net/warframe/images/b/b9/Gold-seeker.jpg/revision/latest?cb=20131207085419',
  'https://vignette1.wikia.nocookie.net/warframe/images/2/2a/Hunter.jpg/revision/latest?cb=20131207085428',
  'https://vignette2.wikia.nocookie.net/warframe/images/1/19/Silver-hunter.jpg/revision/latest?cb=20131207085434',
  'https://vignette1.wikia.nocookie.net/warframe/images/7/75/Gold-hunter.jpg/revision/latest?cb=20131207085443',
  'https://vignette4.wikia.nocookie.net/warframe/images/0/0b/Eagle.jpg/revision/latest?cb=20131207085451',
  'https://vignette1.wikia.nocookie.net/warframe/images/c/c3/Silver-eagle.jpg/revision/latest?cb=20131207085458',
  'https://vignette3.wikia.nocookie.net/warframe/images/a/af/Gold-eagle.jpg/revision/latest?cb=20131207085504',
  'https://vignette3.wikia.nocookie.net/warframe/images/0/05/Tiger.jpg/revision/latest?cb=20131211200425',
  'https://vignette4.wikia.nocookie.net/warframe/images/d/d2/Silver-tiger.jpg/revision/latest?cb=20131211200435',
  'https://vignette2.wikia.nocookie.net/warframe/images/7/7e/Gold-tiger.jpg/revision/latest?cb=20131211200442',
  'https://vignette3.wikia.nocookie.net/warframe/images/b/bb/Dragon.jpg/revision/latest?cb=20131211200549',
  'https://vignette1.wikia.nocookie.net/warframe/images/3/3c/Silver-dragon.jpg/revision/latest?cb=20131211200600',
  'https://vignette2.wikia.nocookie.net/warframe/images/8/83/Gold-dragon.jpg/revision/latest?cb=20131211200607',
  'https://vignette3.wikia.nocookie.net/warframe/images/7/70/Sage.jpg/revision/latest?cb=20131211200700',
  'https://vignette4.wikia.nocookie.net/warframe/images/b/b0/Silver-sage.jpg/revision/latest?cb=20131211200711',
  'https://vignette3.wikia.nocookie.net/warframe/images/2/29/Gold-sage.jpg/revision/latest?cb=20131211200719',
  'https://vignette4.wikia.nocookie.net/warframe/images/7/7d/Master.jpg/revision/latest?cb=20131211200819',
  'https://vignette4.wikia.nocookie.net/warframe/images/f/f8/Middle-master.jpg/revision/latest?cb=20131211200826',
  'https://vignette3.wikia.nocookie.net/warframe/images/4/4d/Grand-master.jpg/revision/latest?cb=20131211200834',
];

/**
 * Generates enemy embeds
 */
class ProfileEmbed extends BaseEmbed {
  /**
   * @param {Genesis} bot - An instance of Genesis
   * @param {Object} player - The enhancement to send info on
   */
  constructor(bot, player) {
    super();

    if (player && typeof player !== 'undefined' && player.name) {
      this.author = {
        name: player.name,
      };
      this.thumbnail = { url: mrSigil[player.mastery.rank.number] };
      this.color = 0x4B458D;
      const accolades = [];
      if (player.accolades.founder) {
        accolades.push(`${founderEmoji[player.accolades.founder.toLowerCase().split(' ').join('')]} ${player.accolades.founder} Founder`);
      }
      if (player.accolades.guide) {
        accolades.push(`<:gotl:329511107536486400> ${player.accolades.guide}`);
      }
      if (player.accolades.moderator) {
        accolades.push('<:commod:329774757576704001> Community Moderator');
      }
      if (player.accolades.partner) {
        accolades.push('<:partner:329771535327952897> Warframe Partner');
      }
      if (player.accolades.staff) {
        accolades.push(' <:de:330057826133213194> Digital Extremes');
      }
      this.fields = [];

      if (accolades.length > 0) {
        this.fields.push({
          name: 'Accolades',
          value: accolades.length > 0 ? accolades.join('\n') : 'None',
          inline: false,
        });
      }

      this.fields.push({
        name: 'Mastery',
        value: `${player.mastery.rank.number} - ${player.mastery.rank.name}`,
        inline: true,
      },
        {
          name: 'Current Mastery',
          value: player.mastery.xp,
          inline: true,
        },
        {
          name: 'Next Rank',
          value: `${player.mastery.xpUntilNextRank} until **${player.mastery.rank.next}**`,
          inline: true,
        },
        {
          name: 'Clan',
          value: player.clan.type ? `${player.clan.name}\nRank **${player.clan.rank}** ${player.clan.type}` : player.clan.name,
          inline: true,
        },
        {
          name: 'Marked for Death',
          value: (player.marked.stalker || player.marked.g3 || player.marked.zanuka)
                ? `${player.marked.stalker ? '<:stalker:330021480169603076>' : ''} ` +
                  `${player.marked.g3 ? '<:g3:330021480442101771>' : ''} ` +
                  `${player.marked.zanuka ? '<:zanuka:330021480912125953>' : ''}`
                : 'Unmarked',
          inline: true,
        });
      this.footer.text = `Last Updated ${new Date(player.updatedAt).toLocaleString()} | Data provided by Nexus-Stats.com`;
    } else {
      this.fields = [{ name: '_ _', value: 'No Such Player' }];
    }
  }
}

module.exports = ProfileEmbed;
<commit_msg>higher res warframe partner emoji<commit_after>'use strict';

const BaseEmbed = require('./BaseEmbed.js');

const founderEmoji = {
  grandmaster: '<:grandmaster:329484751876653076>',
  master: '<:master:329484751570468867>',
  hunter: '<:hunter:329484751972990977>',
  disciple: '<:disciple:329484752098951168>',
};

const mrSigil = [
  '',
  'https://vignette2.wikia.nocookie.net/warframe/images/4/4e/Initiate.jpg/revision/latest?cb=20131207082819',
  'https://vignette3.wikia.nocookie.net/warframe/images/a/a4/Silver-initiate.jpg/revision/latest?cb=20131207083232',
  'https://vignette2.wikia.nocookie.net/warframe/images/8/8f/Gold-initiate.jpg/revision/latest?cb=20131207083401',
  'https://vignette2.wikia.nocookie.net/warframe/images/9/91/Novice.jpg/revision/latest?cb=20131207083549',
  'https://vignette2.wikia.nocookie.net/warframe/images/9/99/Silver-novice.jpg/revision/latest?cb=20131207085318',
  'https://vignette1.wikia.nocookie.net/warframe/images/6/69/Gold-novice.jpg/revision/latest?cb=20131207085328',
  'https://vignette2.wikia.nocookie.net/warframe/images/9/92/Disciple.jpg/revision/latest?cb=20131207085340',
  'https://vignette3.wikia.nocookie.net/warframe/images/f/f8/Silver-disciple.jpg/revision/latest?cb=20131207085348',
  'https://vignette2.wikia.nocookie.net/warframe/images/8/84/Gold-disciple.jpg/revision/latest?cb=20131207085356',
  'https://vignette4.wikia.nocookie.net/warframe/images/4/4b/Seeker.jpg/revision/latest?cb=20131207085405',
  'https://vignette3.wikia.nocookie.net/warframe/images/0/0e/Silver-seeker.jpg/revision/latest?cb=20131207085412',
  'https://vignette2.wikia.nocookie.net/warframe/images/b/b9/Gold-seeker.jpg/revision/latest?cb=20131207085419',
  'https://vignette1.wikia.nocookie.net/warframe/images/2/2a/Hunter.jpg/revision/latest?cb=20131207085428',
  'https://vignette2.wikia.nocookie.net/warframe/images/1/19/Silver-hunter.jpg/revision/latest?cb=20131207085434',
  'https://vignette1.wikia.nocookie.net/warframe/images/7/75/Gold-hunter.jpg/revision/latest?cb=20131207085443',
  'https://vignette4.wikia.nocookie.net/warframe/images/0/0b/Eagle.jpg/revision/latest?cb=20131207085451',
  'https://vignette1.wikia.nocookie.net/warframe/images/c/c3/Silver-eagle.jpg/revision/latest?cb=20131207085458',
  'https://vignette3.wikia.nocookie.net/warframe/images/a/af/Gold-eagle.jpg/revision/latest?cb=20131207085504',
  'https://vignette3.wikia.nocookie.net/warframe/images/0/05/Tiger.jpg/revision/latest?cb=20131211200425',
  'https://vignette4.wikia.nocookie.net/warframe/images/d/d2/Silver-tiger.jpg/revision/latest?cb=20131211200435',
  'https://vignette2.wikia.nocookie.net/warframe/images/7/7e/Gold-tiger.jpg/revision/latest?cb=20131211200442',
  'https://vignette3.wikia.nocookie.net/warframe/images/b/bb/Dragon.jpg/revision/latest?cb=20131211200549',
  'https://vignette1.wikia.nocookie.net/warframe/images/3/3c/Silver-dragon.jpg/revision/latest?cb=20131211200600',
  'https://vignette2.wikia.nocookie.net/warframe/images/8/83/Gold-dragon.jpg/revision/latest?cb=20131211200607',
  'https://vignette3.wikia.nocookie.net/warframe/images/7/70/Sage.jpg/revision/latest?cb=20131211200700',
  'https://vignette4.wikia.nocookie.net/warframe/images/b/b0/Silver-sage.jpg/revision/latest?cb=20131211200711',
  'https://vignette3.wikia.nocookie.net/warframe/images/2/29/Gold-sage.jpg/revision/latest?cb=20131211200719',
  'https://vignette4.wikia.nocookie.net/warframe/images/7/7d/Master.jpg/revision/latest?cb=20131211200819',
  'https://vignette4.wikia.nocookie.net/warframe/images/f/f8/Middle-master.jpg/revision/latest?cb=20131211200826',
  'https://vignette3.wikia.nocookie.net/warframe/images/4/4d/Grand-master.jpg/revision/latest?cb=20131211200834',
];

/**
 * Generates enemy embeds
 */
class ProfileEmbed extends BaseEmbed {
  /**
   * @param {Genesis} bot - An instance of Genesis
   * @param {Object} player - The enhancement to send info on
   */
  constructor(bot, player) {
    super();

    if (player && typeof player !== 'undefined' && player.name) {
      this.author = {
        name: player.name,
      };
      this.thumbnail = { url: mrSigil[player.mastery.rank.number] };
      this.color = 0x4B458D;
      const accolades = [];
      if (player.accolades.founder) {
        accolades.push(`${founderEmoji[player.accolades.founder.toLowerCase().split(' ').join('')]} ${player.accolades.founder} Founder`);
      }
      if (player.accolades.guide) {
        accolades.push(`<:gotl:329511107536486400> ${player.accolades.guide}`);
      }
      if (player.accolades.moderator) {
        accolades.push('<:commod:329774757576704001> Community Moderator');
      }
      if (player.accolades.partner) {
        accolades.push('<:partner:335483679285575700> Warframe Partner');
      }
      if (player.accolades.staff) {
        accolades.push('<:de:330057826133213194> Digital Extremes');
      }
      this.fields = [];

      if (accolades.length > 0) {
        this.fields.push({
          name: 'Accolades',
          value: accolades.length > 0 ? accolades.join('\n') : 'None',
          inline: false,
        });
      }

      this.fields.push({
        name: 'Mastery',
        value: `${player.mastery.rank.number} - ${player.mastery.rank.name}`,
        inline: true,
      },
        {
          name: 'Current Mastery',
          value: player.mastery.xp,
          inline: true,
        },
        {
          name: 'Next Rank',
          value: `${player.mastery.xpUntilNextRank} until **${player.mastery.rank.next}**`,
          inline: true,
        },
        {
          name: 'Clan',
          value: player.clan.type ? `${player.clan.name}\nRank **${player.clan.rank}** ${player.clan.type}` : player.clan.name,
          inline: true,
        },
        {
          name: 'Marked for Death',
          value: (player.marked.stalker || player.marked.g3 || player.marked.zanuka)
                ? `${player.marked.stalker ? '<:stalker:330021480169603076>' : ''} ` +
                  `${player.marked.g3 ? '<:g3:330021480442101771>' : ''} ` +
                  `${player.marked.zanuka ? '<:zanuka:330021480912125953>' : ''}`
                : 'Unmarked',
          inline: true,
        });
      this.footer.text = `Last Updated ${new Date(player.updatedAt).toLocaleString()} | Data provided by Nexus-Stats.com`;
    } else {
      this.fields = [{ name: '_ _', value: 'No Such Player' }];
    }
  }
}

module.exports = ProfileEmbed;
<|endoftext|>


<commit_before>/* File: synchronisationStoreService.js
 *
 * Copyright (c) 2014
 * Centre National d’Enseignement à Distance (Cned), Boulevard Nicephore Niepce, 86360 CHASSENEUIL-DU-POITOU, France
 * (direction-innovation@cned.fr)
 *
 * GNU Affero General Public License (AGPL) version 3.0 or later version
 *
 * This file is part of a program which is free software: you can
 * redistribute it and/or modify it under the terms of the
 * GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this program.
 * If not, see <http://www.gnu.org/licenses/>.
 *
 */

'use strict';
/* global spyOn:false */

describe(
		'Service: synchronisationStoreService',
		function() {

			var q, deferred, localForage, docToSyncArray, profilesToSyncArray;

			beforeEach(module('cnedApp'));

			beforeEach(function() {
			    docToSyncArray = undefined;
			    profilesToSyncArray = undefined;
				localForage = {
					getItem : function(item) {
					    deferred = q.defer();
					    if(item === 'docToSync') {
					        deferred.resolve(docToSyncArray);
					    } else if(item === 'profilesToSync'){
					        deferred.resolve(profilesToSyncArray);
					    } else {
					        deferred.reject();
					    }
                        return deferred.promise;
					},
					setItem : function(item) {
						deferred = q.defer();
						deferred.resolve();
						return deferred.promise;
					},
					removeItem : function(item) {
						deferred = q.defer();
						// Place the fake return object here
						deferred.resolve();
						return deferred.promise;
					}
				};
				spyOn(localForage, 'getItem').andCallThrough();
				spyOn(localForage, 'setItem').andCallThrough();
				spyOn(localForage, 'removeItem').andCallThrough();

				module(function($provide) {
					$provide.value('$localForage', localForage);
				});
			});

			it('synchronisationStoreService:storeDocumentToSynchronize', inject(function(synchronisationStoreService, $rootScope, $q) {
				q=$q;
				// test avec une liste de document à synchroniser vide au départ
				synchronisationStoreService.storeDocumentToSynchronize({docName:'doc'});
				$rootScope.$apply();
				expect(localForage.setItem).toHaveBeenCalledWith('docToSync', [{docName:'doc'}]);

				// test avec une liste de document à synchroniser contenant déjà un document
				docToSyncArray = [{docName:'doc1'}];
				synchronisationStoreService.storeDocumentToSynchronize({docName:'doc'});
                $rootScope.$apply();
                expect(localForage.setItem).toHaveBeenCalledWith('docToSync', [{docName:'doc1'}, {docName:'doc'}]);
			}));

			it('synchronisationStoreService:storeProfilToSynchronize', inject(function(synchronisationStoreService, $rootScope, $q) {
                q=$q;

                synchronisationStoreService.storeProfilToSynchronize({profil:'prof1'});
                $rootScope.$apply();
                expect(localForage.setItem).toHaveBeenCalledWith('profilesToSync', [{profil:'prof1'}]);

                profilesToSyncArray = [{profil:'prof0'}];
                synchronisationStoreService.storeProfilToSynchronize({profil:'prof1'});
                $rootScope.$apply();
                expect(localForage.setItem).toHaveBeenCalledWith('profilesToSync', [{profil:'prof0'}, {profil:'prof1'}]);
            }));

		});
<commit_msg>Add tests<commit_after>/* File: synchronisationStoreService.js
 *
 * Copyright (c) 2014
 * Centre National d’Enseignement à Distance (Cned), Boulevard Nicephore Niepce, 86360 CHASSENEUIL-DU-POITOU, France
 * (direction-innovation@cned.fr)
 *
 * GNU Affero General Public License (AGPL) version 3.0 or later version
 *
 * This file is part of a program which is free software: you can
 * redistribute it and/or modify it under the terms of the
 * GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this program.
 * If not, see <http://www.gnu.org/licenses/>.
 *
 */

'use strict';
/* global spyOn:false */

describe('Service: synchronisationStoreService', function() {

    var q, deferred, localForage, docToSyncArray, profilesToSyncArray;

    beforeEach(module('cnedApp'));

    beforeEach(function() {
        docToSyncArray = undefined;
        profilesToSyncArray = undefined;
        localForage = {
            getItem : function(item) {
                deferred = q.defer();
                if (item === 'docToSync') {
                    deferred.resolve(docToSyncArray);
                } else if (item === 'profilesToSync') {
                    deferred.resolve(profilesToSyncArray);
                } else {
                    deferred.reject();
                }
                return deferred.promise;
            },
            setItem : function() {
                deferred = q.defer();
                deferred.resolve();
                return deferred.promise;
            },
            removeItem : function() {
                deferred = q.defer();
                // Place the fake return object here
                deferred.resolve();
                return deferred.promise;
            }
        };
        spyOn(localForage, 'getItem').andCallThrough();
        spyOn(localForage, 'setItem').andCallThrough();
        spyOn(localForage, 'removeItem').andCallThrough();

        module(function($provide) {
            $provide.value('$localForage', localForage);
        });
    });

    it('synchronisationStoreService:storeDocumentToSynchronize', inject(function(synchronisationStoreService, $rootScope, $q) {
        q = $q;
        // test avec une liste de document à synchroniser vide au départ
        synchronisationStoreService.storeDocumentToSynchronize({
            docName : 'doc'
        });
        $rootScope.$apply();
        expect(localForage.setItem).toHaveBeenCalledWith('docToSync', [ {
            docName : 'doc'
        } ]);

        // test avec une liste de document à synchroniser contenant déjà un
        // document
        docToSyncArray = [ {
            docName : 'doc1'
        } ];
        synchronisationStoreService.storeDocumentToSynchronize({
            docName : 'doc'
        });
        $rootScope.$apply();
        expect(localForage.setItem).toHaveBeenCalledWith('docToSync', [ {
            docName : 'doc1'
        }, {
            docName : 'doc'
        } ]);
    }));

    it('synchronisationStoreService:storeProfilToSynchronize', inject(function(synchronisationStoreService, $rootScope, $q) {
        q = $q;

        synchronisationStoreService.storeProfilToSynchronize({
            profil : 'prof1'
        });
        $rootScope.$apply();
        expect(localForage.setItem).toHaveBeenCalledWith('profilesToSync', [ {
            profil : 'prof1'
        } ]);

        profilesToSyncArray = [ {
            profil : 'prof0'
        } ];
        synchronisationStoreService.storeProfilToSynchronize({
            profil : 'prof1'
        });
        $rootScope.$apply();
        expect(localForage.setItem).toHaveBeenCalledWith('profilesToSync', [ {
            profil : 'prof0'
        }, {
            profil : 'prof1'
        } ]);
    }));

});
<|endoftext|>


<commit_before>"use strict";

var browserSync = require("../../../../index");
var assert  = require("chai").assert;
var utils   = require("../../../utils");
var Rx      = require("rx");

describe("E2E server test with extension option", function () {

    it("serves using 'extensions'", function (done) {

        browserSync.reset();

        var config = {
            server: {
                baseDir: "test/fixtures"
            },
            extensions: ['html'],
            snippetOptions: {
                blacklist: ['/forms']
            },
            logLevel: "silent",
            open: false
        };

        browserSync.create().init(config, function (err, bs) {
            assert.equal(bs.options.getIn(["server", "serveStaticOptions", "extensions", 0]), "html");
            var reqs = utils.getRequests([
                ["/forms", require("fs").readFileSync("test/fixtures/forms.html", "utf-8")]
            ], bs.server);
            Rx.Observable.concat(reqs).subscribeOnCompleted(function () {
                bs.cleanup();
                done();
            });
        });
    });
});
<commit_msg>chore: lint<commit_after>"use strict";

var browserSync = require("../../../../index");
var assert  = require("chai").assert;
var utils   = require("../../../utils");
var Rx      = require("rx");

describe("E2E server test with extension option", function () {

    it("serves using 'extensions'", function (done) {

        browserSync.reset();

        var config = {
            server: {
                baseDir: "test/fixtures"
            },
            extensions: ["html"],
            snippetOptions: {
                blacklist: ["/forms"]
            },
            logLevel: "silent",
            open: false
        };

        browserSync.create().init(config, function (err, bs) {
            assert.equal(bs.options.getIn(["server", "serveStaticOptions", "extensions", 0]), "html");
            var reqs = utils.getRequests([
                ["/forms", require("fs").readFileSync("test/fixtures/forms.html", "utf-8")]
            ], bs.server);
            Rx.Observable.concat(reqs).subscribeOnCompleted(function () {
                bs.cleanup();
                done();
            });
        });
    });
});
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import { bindActionCreators } from 'redux'
import cx from 'classnames'

import { actions, selectors } from 'src/custom-lists'
import extStyles from './Index.css'
import MyCollection from './MyCollections'
import CreateListForm from './CreateListForm'
import ListItem from './ListItem'
import DeleteConfirmModal from 'src/overview/components/DeleteConfirmModal'
import { actions as filterActs } from '../../../../search-filters'
import * as sidebar from '../../../../overview/sidebar-left/selectors'
import { Wrapper } from '../../../../common-ui/components'

class ListContainer extends Component {
    static propTypes = {
        getListFromDB: PropTypes.func.isRequired,
        lists: PropTypes.array.isRequired,
        handleEditBtnClick: PropTypes.func.isRequired,
        isDeleteConfShown: PropTypes.bool.isRequired,
        resetListDeleteModal: PropTypes.func.isRequired,
        handleCrossBtnClick: PropTypes.func.isRequired,
        handleListItemClick: PropTypes.func.isRequired,
        createPageList: PropTypes.func.isRequired,
        updateList: PropTypes.func.isRequired,
        handleAddPageList: PropTypes.func.isRequired,
        handleDeleteList: PropTypes.func.isRequired,
        toggleCreateListForm: PropTypes.func.isRequired,
        showCreateList: PropTypes.bool.isRequired,
        showCommonNameWarning: PropTypes.bool.isRequired,
        isSidebarOpen: PropTypes.bool.isRequired,
        closeCreateListForm: PropTypes.func.isRequired,
        resetUrlDragged: PropTypes.func.isRequired,
    }

    constructor(props) {
        super(props)
        this.state = {
            listName: null,
            updatedListName: null,
            showWarning: false,
        }
    }

    async componentDidMount() {
        // Gets all the list from the DB to populate the sidebar.
        this.props.getListFromDB()
    }

    get inputBlockPattern() {
        return /[^\w\s-]/gi
    }

    setInputRef = el => (this.inputEl = el)

    handleSearchChange = field => event => {
        const { value } = event.target

        // Block input of non-words, spaces and hypens for tags
        if (this.inputBlockPattern.test(value)) {
            return
        }

        this.setState(state => ({
            ...state,
            [field]: value,
        }))
    }

    getSearchVal = value => value.trim().replace(/\s\s+/g, ' ')

    handleCreateListSubmit = event => {
        event.preventDefault()
        const { value } = event.target.elements['listName']
        // value = list name
        this.props.createPageList(
            this.getSearchVal(value),
            this.vacateInputField,
        )
    }

    vacateInputField = () => {
        this.setState(state => ({
            ...state,
            listName: null,
        }))
    }

    handleUpdateList = ({ id }, index) => event => {
        event.preventDefault()
        const { value } = event.target.elements['listName']
        // value = list name
        this.props.updateList(index, this.getSearchVal(value), id)
        this.setState(state => ({
            ...state,
            updatedListName: null,
        }))
    }

    renderAllLists = () => {
        return this.props.lists.map((list, i) => {
            if (list.isEditing) {
                return (
                    <CreateListForm
                        key={i}
                        onCheckboxClick={this.handleUpdateList(list, i)}
                        handleNameChange={this.handleSearchChange(
                            'updatedListName',
                        )}
                        value={
                            typeof this.state.updatedListName === 'string'
                                ? this.state.updatedListName
                                : list.name
                        }
                        showWarning={this.state.showWarning}
                        setInputRef={this.setInputRef}
                    />
                )
            }
            return (
                <ListItem
                    key={i}
                    listName={list.name}
                    isFiltered={list.isFilterIndex}
                    onEditButtonClick={this.props.handleEditBtnClick(i)}
                    onListItemClick={this.props.handleListItemClick(list, i)}
                    onAddPageToList={this.props.handleAddPageList(list, i)}
                    onCrossButtonClick={this.props.handleCrossBtnClick(list, i)}
                    resetUrlDragged={this.props.resetUrlDragged}
                />
            )
        })
    }

    renderCreateList = (shouldDisplayForm, value = null) =>
        shouldDisplayForm ? (
            <CreateListForm
                onCheckboxClick={this.handleCreateListSubmit}
                handleNameChange={this.handleSearchChange('listName')}
                value={this.state.listName}
                showWarning={this.props.showCommonNameWarning}
                setInputRef={this.setInputRef}
                closeCreateListForm={this.props.closeCreateListForm}
            />
        ) : null

    render() {
        return (
            <Wrapper>
                <MyCollection
                    handleRenderCreateList={this.props.toggleCreateListForm}
                />

                {this.renderCreateList(this.props.showCreateList)}
                <div
                    className={cx({
                        [extStyles.allLists]: this.props.isSidebarOpen,
                    })}
                >
                    <div
                        className={cx({
                            [extStyles.wrapper]: this.props.isSidebarOpen,
                            [extStyles.allListsInner]: this.props.isSidebarOpen,
                        })}
                    >
                        {this.renderAllLists()}
                    </div>
                </div>
                <DeleteConfirmModal
                    isShown={this.props.isDeleteConfShown}
                    onClose={this.props.resetListDeleteModal}
                    deleteDocs={this.props.handleDeleteList}
                />
            </Wrapper>
        )
    }
}

const mapStateToProps = state => ({
    lists: selectors.results(state),
    isDeleteConfShown: selectors.isDeleteConfShown(state),
    showCreateList: selectors.showCreateListForm(state),
    showCommonNameWarning: selectors.showCommonNameWarning(state),
    isSidebarOpen: sidebar.isSidebarOpen(state),
})

const mapDispatchToProps = (dispatch, getState) => ({
    ...bindActionCreators(
        {
            resetListDeleteModal: actions.resetListDeleteModal,
            getListFromDB: actions.getListFromDB,
            createPageList: actions.createPageList,
            updateList: actions.updateList,
            toggleCreateListForm: actions.toggleCreateListForm,
            closeCreateListForm: actions.closeCreateListForm,
            resetUrlDragged: actions.resetUrlDragged,
        },
        dispatch,
    ),
    handleEditBtnClick: index => event => {
        event.preventDefault()
        dispatch(actions.showEditBox(index))
    },
    handleCrossBtnClick: ({ id }, index) => event => {
        event.preventDefault()
        dispatch(actions.showListDeleteModal(id, index))
    },
    handleListItemClick: ({ id }, index) => () => {
        dispatch(actions.toggleListFilterIndex(index))
        dispatch(filterActs.toggleListFilter(id))
    },
    handleAddPageList: ({ id }, index) => url => {
        dispatch(actions.addUrltoList(url, index, id))
    },
    handleDeleteList: e => {
        e.preventDefault()
        dispatch(actions.deletePageList())
    },
})

export default connect(
    mapStateToProps,
    mapDispatchToProps,
)(ListContainer)
<commit_msg>Hide create list form when sidebar closes<commit_after>import React, { Component } from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import { bindActionCreators } from 'redux'
import cx from 'classnames'

import { actions, selectors } from 'src/custom-lists'
import extStyles from './Index.css'
import MyCollection from './MyCollections'
import CreateListForm from './CreateListForm'
import ListItem from './ListItem'
import DeleteConfirmModal from 'src/overview/components/DeleteConfirmModal'
import { actions as filterActs } from '../../../../search-filters'
import * as sidebar from '../../../../overview/sidebar-left/selectors'
import { Wrapper } from '../../../../common-ui/components'

class ListContainer extends Component {
    static propTypes = {
        getListFromDB: PropTypes.func.isRequired,
        lists: PropTypes.array.isRequired,
        handleEditBtnClick: PropTypes.func.isRequired,
        isDeleteConfShown: PropTypes.bool.isRequired,
        resetListDeleteModal: PropTypes.func.isRequired,
        handleCrossBtnClick: PropTypes.func.isRequired,
        handleListItemClick: PropTypes.func.isRequired,
        createPageList: PropTypes.func.isRequired,
        updateList: PropTypes.func.isRequired,
        handleAddPageList: PropTypes.func.isRequired,
        handleDeleteList: PropTypes.func.isRequired,
        toggleCreateListForm: PropTypes.func.isRequired,
        showCreateList: PropTypes.bool.isRequired,
        showCommonNameWarning: PropTypes.bool.isRequired,
        isSidebarOpen: PropTypes.bool.isRequired,
        closeCreateListForm: PropTypes.func.isRequired,
        resetUrlDragged: PropTypes.func.isRequired,
    }

    constructor(props) {
        super(props)
        this.state = {
            listName: null,
            updatedListName: null,
            showWarning: false,
        }
    }

    async componentDidMount() {
        // Gets all the list from the DB to populate the sidebar.
        this.props.getListFromDB()
    }

    get inputBlockPattern() {
        return /[^\w\s-]/gi
    }

    setInputRef = el => (this.inputEl = el)

    handleSearchChange = field => event => {
        const { value } = event.target

        // Block input of non-words, spaces and hypens for tags
        if (this.inputBlockPattern.test(value)) {
            return
        }

        this.setState(state => ({
            ...state,
            [field]: value,
        }))
    }

    getSearchVal = value => value.trim().replace(/\s\s+/g, ' ')

    handleCreateListSubmit = event => {
        event.preventDefault()
        const { value } = event.target.elements['listName']
        // value = list name
        this.props.createPageList(
            this.getSearchVal(value),
            this.vacateInputField,
        )
    }

    vacateInputField = () => {
        this.setState(state => ({
            ...state,
            listName: null,
        }))
    }

    handleUpdateList = ({ id }, index) => event => {
        event.preventDefault()
        const { value } = event.target.elements['listName']
        // value = list name
        this.props.updateList(index, this.getSearchVal(value), id)
        this.setState(state => ({
            ...state,
            updatedListName: null,
        }))
    }

    renderAllLists = () => {
        return this.props.lists.map((list, i) => {
            if (list.isEditing && this.props.isSidebarOpen) {
                return (
                    <CreateListForm
                        key={i}
                        onCheckboxClick={this.handleUpdateList(list, i)}
                        handleNameChange={this.handleSearchChange(
                            'updatedListName',
                        )}
                        value={
                            typeof this.state.updatedListName === 'string'
                                ? this.state.updatedListName
                                : list.name
                        }
                        showWarning={this.state.showWarning}
                        setInputRef={this.setInputRef}
                    />
                )
            }
            return (
                <ListItem
                    key={i}
                    listName={list.name}
                    isFiltered={list.isFilterIndex}
                    onEditButtonClick={this.props.handleEditBtnClick(i)}
                    onListItemClick={this.props.handleListItemClick(list, i)}
                    onAddPageToList={this.props.handleAddPageList(list, i)}
                    onCrossButtonClick={this.props.handleCrossBtnClick(list, i)}
                    resetUrlDragged={this.props.resetUrlDragged}
                />
            )
        })
    }

    renderCreateList = (shouldDisplayForm, value = null) =>
        shouldDisplayForm && this.props.isSidebarOpen ? (
            <CreateListForm
                onCheckboxClick={this.handleCreateListSubmit}
                handleNameChange={this.handleSearchChange('listName')}
                value={this.state.listName}
                showWarning={this.props.showCommonNameWarning}
                setInputRef={this.setInputRef}
                closeCreateListForm={this.props.closeCreateListForm}
            />
        ) : null

    render() {
        return (
            <Wrapper>
                <MyCollection
                    handleRenderCreateList={this.props.toggleCreateListForm}
                />

                {this.renderCreateList(this.props.showCreateList)}
                <div
                    className={cx({
                        [extStyles.allLists]: this.props.isSidebarOpen,
                    })}
                >
                    <div
                        className={cx({
                            [extStyles.wrapper]: this.props.isSidebarOpen,
                            [extStyles.allListsInner]: this.props.isSidebarOpen,
                        })}
                    >
                        {this.renderAllLists()}
                    </div>
                </div>
                <DeleteConfirmModal
                    isShown={this.props.isDeleteConfShown}
                    onClose={this.props.resetListDeleteModal}
                    deleteDocs={this.props.handleDeleteList}
                />
            </Wrapper>
        )
    }
}

const mapStateToProps = state => ({
    lists: selectors.results(state),
    isDeleteConfShown: selectors.isDeleteConfShown(state),
    showCreateList: selectors.showCreateListForm(state),
    showCommonNameWarning: selectors.showCommonNameWarning(state),
    isSidebarOpen: sidebar.isSidebarOpen(state),
})

const mapDispatchToProps = (dispatch, getState) => ({
    ...bindActionCreators(
        {
            resetListDeleteModal: actions.resetListDeleteModal,
            getListFromDB: actions.getListFromDB,
            createPageList: actions.createPageList,
            updateList: actions.updateList,
            toggleCreateListForm: actions.toggleCreateListForm,
            closeCreateListForm: actions.closeCreateListForm,
            resetUrlDragged: actions.resetUrlDragged,
        },
        dispatch,
    ),
    handleEditBtnClick: index => event => {
        event.preventDefault()
        dispatch(actions.showEditBox(index))
    },
    handleCrossBtnClick: ({ id }, index) => event => {
        event.preventDefault()
        dispatch(actions.showListDeleteModal(id, index))
    },
    handleListItemClick: ({ id }, index) => () => {
        dispatch(actions.toggleListFilterIndex(index))
        dispatch(filterActs.toggleListFilter(id))
    },
    handleAddPageList: ({ id }, index) => url => {
        dispatch(actions.addUrltoList(url, index, id))
    },
    handleDeleteList: e => {
        e.preventDefault()
        dispatch(actions.deletePageList())
    },
})

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


<commit_before>/**
 * FileReader.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/googledrive/file/FileReader
@private
*/
define("moxie/runtime/googledrive/file/FileReader", [
	"moxie/runtime/googledrive/Runtime",
	"moxie/core/utils/Encode",
	"moxie/core/utils/Basic"
], function(extensions, Encode, Basic) {

	function FileReader() {
		var self = this, _fr, _xhr, _convertToBinary = false;

		Basic.extend(this, {

			read: function(op, blob) {
				var comp = this;

				comp.result = '';

				blob = blob.getSource();

				_xhr = new window.XMLHttpRequest();
				_xhr.open('GET', blob.downloadUrl);

				if ('gapi' in window) {
					_xhr.setRequestHeader('Authorization', 'Bearer ' + gapi.auth.getToken().access_token);
				}

				if (blob.range) {
					_xhr.setRequestHeader('Range', 'bytes=' + blob.range[0] + '-' + (blob.range[1] - 1));
				}

				_xhr.responseType = 'blob';

				_xhr.onprogress = function(e) {
					comp.trigger(e);
				};

				_xhr.onload = function(e) {
					_fr = new window.FileReader();

					_fr.onload = function(e) {
						comp.result = _convertToBinary ? _toBinary(_fr.result) : _fr.result;
						comp.trigger(e);
					};

					_fr.onloadend = function() {
						self.destroy();
					};

					if (Basic.typeOf(_fr[op]) === 'function') {
						_convertToBinary = false;
						_fr[op](this.response);
					} else if (op === 'readAsBinaryString') { // readAsBinaryString is depricated in general and never existed in IE10+
						_convertToBinary = true;
						_fr.readAsDataURL(this.response);
					}
				};

				_xhr.onerror = function(e) {
					comp.trigger(e);
				};

				_xhr.send();
			},

			abort: function() {
				if (_xhr) {
					_xhr.abort();
				}

				if (_fr) {
					_fr.abort();
				}
			},

			destroy: function() {
				self = _xhr = _fr = null;
			}
		});

		function _toBinary(str) {
			return Encode.atob(str.substring(str.indexOf('base64,') + 7));
		}
	}

	return (extensions.FileReader = FileReader);
});
<commit_msg>FileReader, GoogleDrive: moxiecode/moxie@25912ef.<commit_after>/**
 * FileReader.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/googledrive/file/FileReader
@private
*/
define("moxie/runtime/googledrive/file/FileReader", [
	"moxie/runtime/googledrive/Runtime",
	"moxie/core/utils/Encode",
	"moxie/core/utils/Basic"
], function(extensions, Encode, Basic) {

	function FileReader() {
		var self = this, _fr, _xhr, _convertToBinary = false;

		Basic.extend(this, {

			read: function(op, blob) {
				var comp = this;

				comp.result = '';

				blob = blob.getSource();

				_xhr = new window.XMLHttpRequest();
				_xhr.open('GET', blob.downloadUrl);

				if ('gapi' in window) {
					_xhr.setRequestHeader('Authorization', 'Bearer ' + gapi.auth.getToken().access_token);
				}

				if (blob.range) {
					_xhr.setRequestHeader('Range', 'bytes=' + blob.range[0] + '-' + (blob.range[1] - 1));
				}

				_xhr.responseType = 'blob';

				_xhr.onprogress = function(e) {
					comp.trigger(e);
				};

				_xhr.onload = function(e) {
					_fr = new window.FileReader();

					_fr.onload = function(e) {
						comp.result = _convertToBinary ? _toBinary(_fr.result) : _fr.result;
						comp.trigger(e);
					};

					_fr.onloadend = function() {
						self.destroy();
						comp.trigger(e);
					};

					if (Basic.typeOf(_fr[op]) === 'function') {
						_convertToBinary = false;
						_fr[op](this.response);
					} else if (op === 'readAsBinaryString') { // readAsBinaryString is depricated in general and never existed in IE10+
						_convertToBinary = true;
						_fr.readAsDataURL(this.response);
					}
				};

				_xhr.onerror = function(e) {
					comp.trigger(e);
				};

				_xhr.send();
			},

			abort: function() {
				if (_xhr) {
					_xhr.abort();
				}

				if (_fr) {
					_fr.abort();
				}
			},

			destroy: function() {
				self = _xhr = _fr = null;
			}
		});

		function _toBinary(str) {
			return Encode.atob(str.substring(str.indexOf('base64,') + 7));
		}
	}

	return (extensions.FileReader = FileReader);
});
<|endoftext|>


<commit_before>import CellComponent from '../../../../core/cell/CellComponent.js';

export default function(cell, formatterParams, onRendered){ //progress bar
	var value = this.sanitizeHTML(cell.getValue()) || 0,
	element = cell.getElement(),
	max = formatterParams && formatterParams.max ? formatterParams.max : 100,
	min = formatterParams && formatterParams.min ? formatterParams.min : 0,
	legendAlign = formatterParams && formatterParams.legendAlign ? formatterParams.legendAlign : "center",
	percent, percentValue, color, legend, legendColor;

	//make sure value is in range
	percentValue = parseFloat(value) <= max ? parseFloat(value) : max;
	percentValue = parseFloat(percentValue) >= min ? parseFloat(percentValue) : min;

	//workout percentage
	percent = (max - min) / 100;
	percentValue = Math.round((percentValue - min) / percent);

	//set bar color
	switch(typeof formatterParams.color){
		case "string":
			color = formatterParams.color;
			break;
		case "function":
			color = formatterParams.color(value);
			break;
		case "object":
			if(Array.isArray(formatterParams.color)){
				let unit = 100 / formatterParams.color.length;
				let index = Math.floor(percentValue / unit);

				index = Math.min(index, formatterParams.color.length - 1);
				index = Math.max(index, 0);
				color = formatterParams.color[index];
				break;
			}
		default:
			color = "#2DC214";
	}

	//generate legend
	switch(typeof formatterParams.legend){
		case "string":
			legend = formatterParams.legend;
			break;
		case "function":
			legend = formatterParams.legend(value);
			break;
		case "boolean":
			legend = value;
			break;
		default:
			legend = false;
	}

	//set legend color
	switch(typeof formatterParams.legendColor){
		case "string":
			legendColor = formatterParams.legendColor;
			break;
		case "function":
			legendColor = formatterParams.legendColor(value);
			break;
		case "object":
			if(Array.isArray(formatterParams.legendColor)){
				let unit = 100 / formatterParams.legendColor.length;
				let index = Math.floor(percentValue / unit);

				index = Math.min(index, formatterParams.legendColor.length - 1);
				index = Math.max(index, 0);
				legendColor = formatterParams.legendColor[index];
			}
			break;
		default:
			legendColor = "#000";
	}

	element.style.minWidth = "30px";
	element.style.position = "relative";

	element.setAttribute("aria-label", percentValue);

	var barEl = document.createElement("div");
	barEl.style.display = "inline-block";
	barEl.style.position = "absolute";
	barEl.style.width = percentValue + "%";
	barEl.style.backgroundColor = color;
	barEl.style.height = "100%";

	barEl.setAttribute('data-max', max);
	barEl.setAttribute('data-min', min);

	var barContainer = document.createElement("div");
	barContainer.style.position = "relative";
	barContainer.style.width = "100%";
	barContainer.style.height = "100%";

	if(legend){
		var legendEl = document.createElement("div");
		legendEl.style.position = "absolute";
		legendEl.style.top = 0;
		legendEl.style.left = 0;
		legendEl.style.textAlign = legendAlign;
		legendEl.style.width = "100%";
		legendEl.style.color = legendColor;
		legendEl.innerHTML = legend;
	}

	onRendered(function(){

		//handle custom element needed if formatter is to be included in printed/downloaded output
		if(!(cell instanceof CellComponent)){
			var holderEl = document.createElement("div");
			holderEl.style.position = "absolute";
			holderEl.style.top = "4px";
			holderEl.style.bottom = "4px";
			holderEl.style.left = "4px";
			holderEl.style.right = "4px";

			element.appendChild(holderEl);

			element = holderEl;
		}

		element.appendChild(barContainer);
		barContainer.appendChild(barEl);

		if(legend){
			barContainer.appendChild(legendEl);
		}
	});

	return "";
}<commit_msg>fix param processing issue in progress formatter<commit_after>import CellComponent from '../../../../core/cell/CellComponent.js';

export default function(cell, formatterParams = {}, onRendered){ //progress bar
	var value = this.sanitizeHTML(cell.getValue()) || 0,
	element = cell.getElement(),
	max = formatterParams.max ? formatterParams.max : 100,
	min = formatterParams.min ? formatterParams.min : 0,
	legendAlign = formatterParams.legendAlign ? formatterParams.legendAlign : "center",
	percent, percentValue, color, legend, legendColor;

	//make sure value is in range
	percentValue = parseFloat(value) <= max ? parseFloat(value) : max;
	percentValue = parseFloat(percentValue) >= min ? parseFloat(percentValue) : min;

	//workout percentage
	percent = (max - min) / 100;
	percentValue = Math.round((percentValue - min) / percent);

	//set bar color
	switch(typeof formatterParams.color){
		case "string":
			color = formatterParams.color;
			break;
		case "function":
			color = formatterParams.color(value);
			break;
		case "object":
			if(Array.isArray(formatterParams.color)){
				let unit = 100 / formatterParams.color.length;
				let index = Math.floor(percentValue / unit);

				index = Math.min(index, formatterParams.color.length - 1);
				index = Math.max(index, 0);
				color = formatterParams.color[index];
				break;
			}
		default:
			color = "#2DC214";
	}

	//generate legend
	switch(typeof formatterParams.legend){
		case "string":
			legend = formatterParams.legend;
			break;
		case "function":
			legend = formatterParams.legend(value);
			break;
		case "boolean":
			legend = value;
			break;
		default:
			legend = false;
	}

	//set legend color
	switch(typeof formatterParams.legendColor){
		case "string":
			legendColor = formatterParams.legendColor;
			break;
		case "function":
			legendColor = formatterParams.legendColor(value);
			break;
		case "object":
			if(Array.isArray(formatterParams.legendColor)){
				let unit = 100 / formatterParams.legendColor.length;
				let index = Math.floor(percentValue / unit);

				index = Math.min(index, formatterParams.legendColor.length - 1);
				index = Math.max(index, 0);
				legendColor = formatterParams.legendColor[index];
			}
			break;
		default:
			legendColor = "#000";
	}

	element.style.minWidth = "30px";
	element.style.position = "relative";

	element.setAttribute("aria-label", percentValue);

	var barEl = document.createElement("div");
	barEl.style.display = "inline-block";
	barEl.style.position = "absolute";
	barEl.style.width = percentValue + "%";
	barEl.style.backgroundColor = color;
	barEl.style.height = "100%";

	barEl.setAttribute('data-max', max);
	barEl.setAttribute('data-min', min);

	var barContainer = document.createElement("div");
	barContainer.style.position = "relative";
	barContainer.style.width = "100%";
	barContainer.style.height = "100%";

	if(legend){
		var legendEl = document.createElement("div");
		legendEl.style.position = "absolute";
		legendEl.style.top = 0;
		legendEl.style.left = 0;
		legendEl.style.textAlign = legendAlign;
		legendEl.style.width = "100%";
		legendEl.style.color = legendColor;
		legendEl.innerHTML = legend;
	}

	onRendered(function(){

		//handle custom element needed if formatter is to be included in printed/downloaded output
		if(!(cell instanceof CellComponent)){
			var holderEl = document.createElement("div");
			holderEl.style.position = "absolute";
			holderEl.style.top = "4px";
			holderEl.style.bottom = "4px";
			holderEl.style.left = "4px";
			holderEl.style.right = "4px";

			element.appendChild(holderEl);

			element = holderEl;
		}

		element.appendChild(barContainer);
		barContainer.appendChild(barEl);

		if(legend){
			barContainer.appendChild(legendEl);
		}
	});

	return "";
}<|endoftext|>


<commit_before>goog.provide('app.CardController');
goog.provide('app.cardDirective');

goog.require('app');
goog.require('app.utils');
goog.require('app.Url');

/**
 * This directive is used to display a document card.
 *
 * @param {angular.$compile} $compile Angular compile service.
 * @param {angular.$templateCache} $templateCache service
 * @return {angular.Directive} The directive specs.
 * @ngInject
 */
app.cardDirective = function($compile, $templateCache) {
  var cardElementCache = {};

  var getCardElement = function(doctype) {
    if (cardElementCache[doctype] !== undefined) {
      return cardElementCache[doctype];
    }

    var path = '/static/partials/cards/' + doctype + '.html';
    var template = app.utils.getTemplate(path, $templateCache);

    var element = angular.element(template);
    cardElementCache[doctype] = $compile(element);

    return cardElementCache[doctype];
  };

  return {
    restrict: 'E',
    controller: 'AppCardController',
    controllerAs: 'cardCtrl',
    bindToController: true,
    scope: {
      'doc': '<appCardDoc'
    },
    link: function(scope, element, attrs, ctrl) {
      var cardElementFn = getCardElement(ctrl.type);
      cardElementFn(scope, function(clone) {
        element.append(clone);
      });
    }
  };
};

app.module.directive('appCard', app.cardDirective);

/**
 * @param {angularGettext.Catalog} gettextCatalog Gettext catalog.
 * @param {app.Url} appUrl URL service.
 * @param {!string} imageUrl URL to the image backend.
 * @constructor
 * @struct
 * @ngInject
 */
app.CardController = function(gettextCatalog, appUrl, imageUrl) {

  /**
   * @type {angularGettext.Catalog}
   * @private
   */
  this.gettextCatalog_ = gettextCatalog;

  /**
   * @type {app.Url}
   * @private
   */
  this.url_ = appUrl;

  /**
   * @type {string}
   * @private
   */
  this.imageUrl_ = imageUrl;

  /**
   * @type {string}
   * @export
   */
  this.lang = gettextCatalog.currentLanguage;

  /**
   * @type {appx.Document}
   * @export
   */
  this.doc;
  //console.log(this.doc)

  /**
   * @type {boolean}
   * @export
   */
  this.remainingActivities = false;

  /**
   * @type {string}
   * @public
   */
  this.type = app.utils.getDoctype(this.doc['type']);

  /**
   * @type {Object}
   * @export
   */

  this.locale = {};

  if(this.type === "feeds") {
    this.locale = this.doc.document.locales[0];
    for (var i = 0, n = this.doc.document.locales.length; i < n; i++) {
      var l = this.doc.document.locales[i];
      if (l['lang'] === this.lang) {
        this.locale = l;
        break;
      }
    }
  }  else {
    this.locale= this.doc.locales[0];
    for (var i = 0, n = this.doc.locales.length; i < n; i++) {
      var l = this.doc.locales[i];
      if (l['lang'] === this.lang) {
        this.locale = l;
        break;
      }
    }
  }

};

/**
 * Creates a HTML with action that user used on the document in the feed.
 * Will be useful for verbs like 'created', 'updated', 'associated xx', 'went hiking with xx'.
 * @return {string} line
 * @export
 */
app.CardController.prototype.createActionLine = function() {
  var line = '';

  switch (this.doc['change_type']) {
    case 'created':
      line += 'has created a new ';
      break;
    case 'updated':
      line += 'has updated the ';
      break;
    case 'added_photos':
      line += 'has added images to ';
      break;
    default:
      break;
                                 }
  return line + this.getDocumentType(this.doc['document']['type']);
};

/**
 * document type without 's' (singular form)
 * @export
 * @returns {string}
 */
app.CardController.prototype.getDocumentType = function(type) {
  return app.utils.getDoctype(type).slice(0, -1);
};

/**
 * @param {string} str String to translate.
 * @return {string} Translated string.
 * @export
 */
app.CardController.prototype.translate = function(str) {
  return this.gettextCatalog_.getString(str);
};

/**
 * Show only one of the area types, the first that is available:
 * 1) range 2) admin limits 3) country
 * @param {?Array<Object>} areas
 * @return {Object | null}
 * @export
 */
app.CardController.prototype.showArea = function(areas) {
  if (areas) {
    // the areas often come in different orders within 3 area objects.
    var orderedAreas = {'range': [], 'admin_limits': [], 'country': []};
    var type;

    console.log(areas);

    for (var i = 0; i < areas.length; i++) {
      type = areas[i]['area_type'];
      orderedAreas[type].push(areas[i]['locales'][0]['title']);
    }

    if(orderedAreas['admin_limits'].length > 0)
    {
      return orderedAreas['admin_limits'].join(' - ');
    } else if (orderedAreas['range'].length > 0) {
      return orderedAreas['range'].join(' - ');

    } else if (orderedAreas['country'].length > 0) {
       return orderedAreas['countru'].join(' - ');
    }

  }
  return null;
};

/**
 * Convert orientations array into a string
 * @param {?Array<string>} orientations
 * @return {string}
 * @export
 */
app.CardController.prototype.showOrientation = function(orientations) {
  var str = '';
  for (var i = 0; i < orientations.length; i++) {
    if (i == 0) {
      str = str + '' + orientations[i];
    } else {
      str = str + ', ' + orientations[i];
    }
  }
  return str;
};

/**
 * Create redirection to the document page
 * @export
 */
app.CardController.prototype.openDoc = function() {
  window.location = this.createURL();
};

/**
 * Creates a link to the document view-page
 * @export
 * @return {string | undefined}
 */
app.CardController.prototype.createURL = function() {
  var loc = window.location.pathname;
  // Don't create links on edit and add pages.
  if (loc.indexOf('/edit/') === -1 && loc.indexOf('/add') === -1) {
    if(this.type == "feeds") {
      return this.url_.buildDocumentUrl(
        app.utils.getDoctype(this.doc['document']['type']), this.doc['document']['document_id'], this.doc['document']['locales'][0]);
    } else {
      return this.url_.buildDocumentUrl(
        this.type, this.doc['document_id'], this.doc['locales'][0]);
    }

  }
};

/**
 * @param {string} filename
 * @param {string} suffix
 * @return {string}
 * @export
 */
app.CardController.prototype.createImageUrl = function(filename, suffix) {
  return this.imageUrl_ + app.utils.createImageUrl(filename, suffix);
};

/**
 * @param {Array} areas
 * @return {string | undefined}
 * @export
 */
app.CardController.prototype.createURLArea = function(areas) {
  if (areas !== undefined) {
    if (areas.length > 0) {
      var loc = window.location.pathname;
      // Don't create links on edit and add pages.
      var doc = areas[areas.length - 1];
      if (loc.indexOf('/edit/') === -1 && loc.indexOf('/add') === -1) {
        return this.url_.buildDocumentUrl(
          app.utils.getDoctype(doc['type']),  doc['document_id'],  doc['locales'][0]);
      }
    }
  }

};

/**
 * Don't create any url on edit and add pages.
 * @export
 * @param {string} suffix (BI, SI, MI)
 * @return {string}
 */
app.CardController.prototype.createImg = function(suffix) {
  return this.imageUrl_ + app.utils.createImageUrl(this.doc['filename'], 'MI');
};

/**
 * Gets the global ratings for each activity of a route.
 * @export
 * @return {Object | null} ratings
 */
app.CardController.prototype.getGlobalRatings = function() {
  var doc = this.doc;
  var ratings = {};

  doc.activities.forEach(function(a) {
    if (a === 'rock_climbing' || a === 'mountain_climbing' || a === 'snow_ice_mixed') {
      ratings['global_rating'] = doc.global_rating;

    } else if (a === 'via_ferrata') {
      ratings['via_ferrata_rating'] = doc.via_ferrata_rating;

    } else if (a === 'snowshoeing') {
      ratings['snowshoe_rating'] = doc.snowshoe_rating;

    } else if (a === 'hiking') {
      ratings['hiking_rating'] = doc.hiking_rating;

    } else if (a === 'ice_climbing') {
      ratings['ice_rating'] = this.slashSeparatedRating_(doc.ice_rating, doc.engagement_rating);

    } else if (a === 'skitouring') {
      ratings['labande_global_rating'] = this.slashSeparatedRating_(doc.ski_rating, doc.ski_exposition);
      ratings['labande_global_rating'] += doc.labande_global_rating ? doc.labande_global_rating : '';

    } else if (a === 'mountain_biking') {
      ratings['biking_rating'] = this.slashSeparatedRating_(doc.mtb_down_rating, doc.hiking_mtb_exposition);
    }
  }.bind(this));
  return ratings[Object.keys(ratings)[0]] ? ratings : null;
};

/**
 * Based on mako functions in helpers/view.html and route/detailed_route_attributes.html
 * @export
 * @return {Object} ratings
 */
app.CardController.prototype.getFullRatings = function() {
  var doc = {}
  if(this.type == "feeds") {
    doc = this.doc['document'];
  } else {
    doc = this.doc;
  }
  var ratings = {};
  var fullRatings = {};

  for (var p in doc) {
    // every property that has 'rating' in it but with some exceptions.
    if (doc.hasOwnProperty(p) && p.indexOf('rating') > -1 &&
        p !== 'rock_free_rating' && p !== 'rock_required_rating' && p !== 'ski_rating' &&
        p !== 'labande_global_rating' && p !== 'labande_ski_rating') {
      ratings[p] = doc[p];
    } else {
      ratings[p] = doc[p];
      if (p === 'hiking_mtb_exposition') {
        ratings['hiking_mtb_exposition'] = doc.hiking_mtb_exposition;

      } else if (p === 'ski_rating' || p === 'ski_exposition') {
        ratings['ski_rating'] = this.slashSeparatedRating_(doc.ski_rating, doc.ski_exposition);

      } else if (p === 'labande_global_rating' || p === 'labande_ski_rating') {
        ratings['labande_rating'] = this.slashSeparatedRating_(doc.labande_global_rating, doc.labande_ski_rating);

      } else if (p === 'rock_required_rating' || p === 'rock_free_rating') {
        ratings['rock_rating'] = doc.rock_free_rating;

        if (doc.rock_required_rating && doc.rock_free_rating) {
          // [A0] (without bracket) is showed only if equipment_rating = P1 or P1+, and if aid_rating is empty.
          var A0 = (doc.equipment_rating === 'P1' || doc.equipment_rating === 'P1+') && !doc.aid_rating;
          ratings['rock_rating'] += '>' + doc.rock_required_rating;
          ratings['rock_rating'] += A0 ? '[A0]' : '';
        }
      }
    }
  }
  app.constants.fullRatingOrdered.forEach(function(rating) {
    if (rating in ratings && ratings[rating]) {
      fullRatings[rating] = ratings[rating];
    }
  });

  return fullRatings[Object.keys(fullRatings)[0]] ? fullRatings : null;
};

/**
 * @param {string} rating1
 * @param {string} rating2
 * @return {string} rating
 */
app.CardController.prototype.slashSeparatedRating_ = function(rating1, rating2) {
  var rating = rating1 || '';
  rating += (rating1 && rating2) ? '/' : '';
  rating += rating2 || '';
  return rating;
};

/**
 * @export
 */
app.CardController.prototype.hasActivity = function(activities) {
  return (this.type === 'routes') ?
    app.utils.hasActivity(/** @type{appx.Route}*/ (this.doc), activities) : false;
};

app.module.controller('AppCardController', app.CardController);
<commit_msg>real fix for area url<commit_after>goog.provide('app.CardController');
goog.provide('app.cardDirective');

goog.require('app');
goog.require('app.utils');
goog.require('app.Url');

/**
 * This directive is used to display a document card.
 *
 * @param {angular.$compile} $compile Angular compile service.
 * @param {angular.$templateCache} $templateCache service
 * @return {angular.Directive} The directive specs.
 * @ngInject
 */
app.cardDirective = function($compile, $templateCache) {
  var cardElementCache = {};

  var getCardElement = function(doctype) {
    if (cardElementCache[doctype] !== undefined) {
      return cardElementCache[doctype];
    }

    var path = '/static/partials/cards/' + doctype + '.html';
    var template = app.utils.getTemplate(path, $templateCache);

    var element = angular.element(template);
    cardElementCache[doctype] = $compile(element);

    return cardElementCache[doctype];
  };

  return {
    restrict: 'E',
    controller: 'AppCardController',
    controllerAs: 'cardCtrl',
    bindToController: true,
    scope: {
      'doc': '<appCardDoc'
    },
    link: function(scope, element, attrs, ctrl) {
      var cardElementFn = getCardElement(ctrl.type);
      cardElementFn(scope, function(clone) {
        element.append(clone);
      });
    }
  };
};

app.module.directive('appCard', app.cardDirective);

/**
 * @param {angularGettext.Catalog} gettextCatalog Gettext catalog.
 * @param {app.Url} appUrl URL service.
 * @param {!string} imageUrl URL to the image backend.
 * @constructor
 * @struct
 * @ngInject
 */
app.CardController = function(gettextCatalog, appUrl, imageUrl) {

  /**
   * @type {angularGettext.Catalog}
   * @private
   */
  this.gettextCatalog_ = gettextCatalog;

  /**
   * @type {app.Url}
   * @private
   */
  this.url_ = appUrl;

  /**
   * @type {string}
   * @private
   */
  this.imageUrl_ = imageUrl;

  /**
   * @type {string}
   * @export
   */
  this.lang = gettextCatalog.currentLanguage;

  /**
   * @type {appx.Document}
   * @export
   */
  this.doc;
  //console.log(this.doc)

  /**
   * @type {boolean}
   * @export
   */
  this.remainingActivities = false;

  /**
   * @type {string}
   * @public
   */
  this.type = app.utils.getDoctype(this.doc['type']);

  /**
   * @type {Object}
   * @export
   */

  this.locale = {};

  if(this.type === "feeds") {
    this.locale = this.doc.document.locales[0];
    for (var i = 0, n = this.doc.document.locales.length; i < n; i++) {
      var l = this.doc.document.locales[i];
      if (l['lang'] === this.lang) {
        this.locale = l;
        break;
      }
    }
  }  else {
    this.locale= this.doc.locales[0];
    for (var i = 0, n = this.doc.locales.length; i < n; i++) {
      var l = this.doc.locales[i];
      if (l['lang'] === this.lang) {
        this.locale = l;
        break;
      }
    }
  }

};

/**
 * Creates a HTML with action that user used on the document in the feed.
 * Will be useful for verbs like 'created', 'updated', 'associated xx', 'went hiking with xx'.
 * @return {string} line
 * @export
 */
app.CardController.prototype.createActionLine = function() {
  var line = '';

  switch (this.doc['change_type']) {
    case 'created':
      line += 'has created a new ';
      break;
    case 'updated':
      line += 'has updated the ';
      break;
    case 'added_photos':
      line += 'has added images to ';
      break;
    default:
      break;
                                 }
  return line + this.getDocumentType(this.doc['document']['type']);
};

/**
 * document type without 's' (singular form)
 * @export
 * @returns {string}
 */
app.CardController.prototype.getDocumentType = function(type) {
  return app.utils.getDoctype(type).slice(0, -1);
};

/**
 * @param {string} str String to translate.
 * @return {string} Translated string.
 * @export
 */
app.CardController.prototype.translate = function(str) {
  return this.gettextCatalog_.getString(str);
};

/**
 * Show only one of the area types, the first that is available:
 * 1) range 2) admin limits 3) country
 * @param {?Array<Object>} areas
 * @return {Object | null}
 * @export
 */
app.CardController.prototype.showArea = function(areas) {
  if (areas) {
    // the areas often come in different orders within 3 area objects.
    var orderedAreas = {'range': [], 'admin_limits': [], 'country': []};
    var type;
    for (var i = 0; i < areas.length; i++) {
      type = areas[i]['area_type'];
      orderedAreas[type].push(areas[i]['locales'][0]['title']);
    }

    var str = '';

    if(orderedAreas['admin_limits'].length > 0)
    {
      str = orderedAreas['admin_limits'].join(' - ');
    }

    if (orderedAreas['range'].length > 0) {
      str = str + ' - ' + orderedAreas['range'].join(' - ');
    } else if (orderedAreas['country'].length > 0) {
      str = str + ' - ' +  orderedAreas['country'].join(' - ');
      return str;
    }
    return str;
  }
  return null;
};

/**
 * Convert orientations array into a string
 * @param {?Array<string>} orientations
 * @return {string}
 * @export
 */
app.CardController.prototype.showOrientation = function(orientations) {
  var str = '';
  for (var i = 0; i < orientations.length; i++) {
    if (i == 0) {
      str = str + '' + orientations[i];
    } else {
      str = str + ', ' + orientations[i];
    }
  }
  return str;
};

/**
 * Create redirection to the document page
 * @export
 */
app.CardController.prototype.openDoc = function() {
  window.location = this.createURL();
};

/**
 * Creates a link to the document view-page
 * @export
 * @return {string | undefined}
 */
app.CardController.prototype.createURL = function() {
  var loc = window.location.pathname;
  // Don't create links on edit and add pages.
  if (loc.indexOf('/edit/') === -1 && loc.indexOf('/add') === -1) {
    if(this.type == "feeds") {
      return this.url_.buildDocumentUrl(
        app.utils.getDoctype(this.doc['document']['type']), this.doc['document']['document_id'], this.doc['document']['locales'][0]);
    } else {
      return this.url_.buildDocumentUrl(
        this.type, this.doc['document_id'], this.doc['locales'][0]);
    }

  }
};

/**
 * @param {string} filename
 * @param {string} suffix
 * @return {string}
 * @export
 */
app.CardController.prototype.createImageUrl = function(filename, suffix) {
  return this.imageUrl_ + app.utils.createImageUrl(filename, suffix);
};

/**
 * @param {Array} areas
 * @return {string | undefined}
 * @export
 */
app.CardController.prototype.createURLArea = function(areas) {
  if (areas !== undefined) {
    if (areas.length > 0) {
      var type;
      var orderedAreas = {'range': [], 'admin_limits': [], 'country': []};

      for (var i = 0; i < areas.length; i++) {
        type = areas[i]['area_type'];
        orderedAreas[type].push(areas[i]);
      }

      var loc = window.location.pathname;
      // Don't create links on edit and add pages.
      //var doc = areas[areas.length - 1];

      var doc;
        if (orderedAreas['range'].length > 0) {
        doc = orderedAreas['range'];
      } else if (orderedAreas['range'].length > 0) {
        doc = orderedAreas['admin_limits'];
      }
      else {
        doc = orderedAreas['country'];
      }

      if (loc.indexOf('/edit/') === -1 && loc.indexOf('/add') === -1) {
        return this.url_.buildDocumentUrl(
          app.utils.getDoctype(doc[doc.length-1]['type']),  doc[doc.length-1]['document_id'],  doc[doc.length-1]['locales'][0]);
      }
    }
  }

};

/**
 * Don't create any url on edit and add pages.
 * @export
 * @param {string} suffix (BI, SI, MI)
 * @return {string}
 */
app.CardController.prototype.createImg = function(suffix) {
  return this.imageUrl_ + app.utils.createImageUrl(this.doc['filename'], 'MI');
};

/**
 * Gets the global ratings for each activity of a route.
 * @export
 * @return {Object | null} ratings
 */
app.CardController.prototype.getGlobalRatings = function() {
  var doc = this.doc;
  var ratings = {};

  doc.activities.forEach(function(a) {
    if (a === 'rock_climbing' || a === 'mountain_climbing' || a === 'snow_ice_mixed') {
      ratings['global_rating'] = doc.global_rating;

    } else if (a === 'via_ferrata') {
      ratings['via_ferrata_rating'] = doc.via_ferrata_rating;

    } else if (a === 'snowshoeing') {
      ratings['snowshoe_rating'] = doc.snowshoe_rating;

    } else if (a === 'hiking') {
      ratings['hiking_rating'] = doc.hiking_rating;

    } else if (a === 'ice_climbing') {
      ratings['ice_rating'] = this.slashSeparatedRating_(doc.ice_rating, doc.engagement_rating);

    } else if (a === 'skitouring') {
      ratings['labande_global_rating'] = this.slashSeparatedRating_(doc.ski_rating, doc.ski_exposition);
      ratings['labande_global_rating'] += doc.labande_global_rating ? doc.labande_global_rating : '';

    } else if (a === 'mountain_biking') {
      ratings['biking_rating'] = this.slashSeparatedRating_(doc.mtb_down_rating, doc.hiking_mtb_exposition);
    }
  }.bind(this));
  return ratings[Object.keys(ratings)[0]] ? ratings : null;
};

/**
 * Based on mako functions in helpers/view.html and route/detailed_route_attributes.html
 * @export
 * @return {Object} ratings
 */
app.CardController.prototype.getFullRatings = function() {
  var doc = {}
  if(this.type == "feeds") {
    doc = this.doc['document'];
  } else {
    doc = this.doc;
  }
  var ratings = {};
  var fullRatings = {};

  for (var p in doc) {
    // every property that has 'rating' in it but with some exceptions.
    if (doc.hasOwnProperty(p) && p.indexOf('rating') > -1 &&
        p !== 'rock_free_rating' && p !== 'rock_required_rating' && p !== 'ski_rating' &&
        p !== 'labande_global_rating' && p !== 'labande_ski_rating') {
      ratings[p] = doc[p];
    } else {
      ratings[p] = doc[p];
      if (p === 'hiking_mtb_exposition') {
        ratings['hiking_mtb_exposition'] = doc.hiking_mtb_exposition;

      } else if (p === 'ski_rating' || p === 'ski_exposition') {
        ratings['ski_rating'] = this.slashSeparatedRating_(doc.ski_rating, doc.ski_exposition);

      } else if (p === 'labande_global_rating' || p === 'labande_ski_rating') {
        ratings['labande_rating'] = this.slashSeparatedRating_(doc.labande_global_rating, doc.labande_ski_rating);

      } else if (p === 'rock_required_rating' || p === 'rock_free_rating') {
        ratings['rock_rating'] = doc.rock_free_rating;

        if (doc.rock_required_rating && doc.rock_free_rating) {
          // [A0] (without bracket) is showed only if equipment_rating = P1 or P1+, and if aid_rating is empty.
          var A0 = (doc.equipment_rating === 'P1' || doc.equipment_rating === 'P1+') && !doc.aid_rating;
          ratings['rock_rating'] += '>' + doc.rock_required_rating;
          ratings['rock_rating'] += A0 ? '[A0]' : '';
        }
      }
    }
  }
  app.constants.fullRatingOrdered.forEach(function(rating) {
    if (rating in ratings && ratings[rating]) {
      fullRatings[rating] = ratings[rating];
    }
  });

  return fullRatings[Object.keys(fullRatings)[0]] ? fullRatings : null;
};

/**
 * @param {string} rating1
 * @param {string} rating2
 * @return {string} rating
 */
app.CardController.prototype.slashSeparatedRating_ = function(rating1, rating2) {
  var rating = rating1 || '';
  rating += (rating1 && rating2) ? '/' : '';
  rating += rating2 || '';
  return rating;
};

/**
 * @export
 */
app.CardController.prototype.hasActivity = function(activities) {
  return (this.type === 'routes') ?
    app.utils.hasActivity(/** @type{appx.Route}*/ (this.doc), activities) : false;
};

app.module.controller('AppCardController', app.CardController);
<|endoftext|>


<commit_before>// ==UserScript==
// @name          KanyashreeHelper
// @namespace     https://github.com/abusalam/KanyashreeHelper
// @description   Helper Script For Kanyashree Approval and Sanction Generation
// @include       http://wbkanyashree.gov.in/*
// @grant         none
// @downloadURL   https://github.com/abusalam/KanyashreeHelper/raw/master/K2.user.js
// @updateURL     https://github.com/abusalam/KanyashreeHelper/raw/master/K2.user.js
// @version       1.0
// @icon          http://www.gravatar.com/avatar/43f0ea57b814fbdcb3793ca3e76971cf
// ==/UserScript==

/**
 * How can I use jQuery in Greasemonkey scripts in Google Chrome?
 * All Credits to Original Author for this wonderfull function.
 *
 * @author  Erik Vergobbi Vold & Tyler G. Hicks-Wright
 * @link    http://stackoverflow.com/questions/2246901
 * @param   {reference} callback
 * @returns {undefined}
 */
function jQueryInclude(callback) {
  var script = document.createElement("script");
  var jQueryCDN = "//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js";
  script.setAttribute("src", jQueryCDN);

  script.addEventListener('load', function() {
    var script = document.createElement("script");
    script.textContent = 'window.jQ=jQuery.noConflict(true);'
            + 'var BaseURL = "http://wbkanyashree.gov.in/";'
            + '(' + callback.toString() + ')();';
    document.body.appendChild(script);
  }, false);
  document.body.appendChild(script);
}

/**
 * Main Body of Helper Script For Kanyashree Approval and Sanction Generation
 *
 * @returns {undefined}
 */
jQueryInclude(function() {

  jQ("#CmdClearStorage").click(function() {
    localStorage.clear();
  });

  jQ("#top").hide();
  jQ("#header").hide();
  jQ("#footerMain").hide();
  jQ("option").html(function() {
    return jQ(this).val() + " - " + jQ(this).html();
  });
  /**
   * Continious Polling for Server Response
   *
   * @returns {Boolean}
   */
  var RefreshOnWait = function() {
    var RespDate = new Date(), TimeOut;
    var CurrentTime = RespDate.getTime();
    CurrentTime = CurrentTime - localStorage.getItem("LastRespTime");
    TimeOut = localStorage.getItem("RefreshTimeOut");
    if (TimeOut === null) {
      TimeOut = 300000;
    } else {
      TimeOut = 5000 + 60000 * TimeOut; // 5sec is minimum
      localStorage.removeItem("RefreshTimeOut");
    }

    if (CurrentTime > TimeOut) {

      var LastRespTime = new Date();
      localStorage.setItem("LastRespTime", LastRespTime.getTime());
      localStorage.setItem("TryLogin", "Yes");
      var URL = BaseURL + "admin_pages/kp_homepage.php";
      parent.window.open(URL, "_self");
    }
    setTimeout(RefreshOnWait, TimeOut);
    return true;
  };

  RefreshOnWait();

  var LastRespTime = new Date();
  localStorage.setItem("LastRespTime", LastRespTime.getTime());
});<commit_msg>Single Application Sanctioning Works<commit_after>// ==UserScript==
// @name          KanyashreeHelper
// @namespace     https://github.com/abusalam/KanyashreeHelper
// @description   Helper Script For Kanyashree Approval and Sanction Generation
// @include       http://wbkanyashree.gov.in/*
// @grant         none
// @downloadURL   https://github.com/abusalam/KanyashreeHelper/raw/master/K2.user.js
// @updateURL     https://github.com/abusalam/KanyashreeHelper/raw/master/K2.user.js
// @version       1.0
// @icon          http://www.gravatar.com/avatar/43f0ea57b814fbdcb3793ca3e76971cf
// ==/UserScript==

/**
 * How can I use jQuery in Greasemonkey scripts in Google Chrome?
 * All Credits to Original Author for this wonderfull function.
 *
 * @author  Erik Vergobbi Vold & Tyler G. Hicks-Wright
 * @link    http://stackoverflow.com/questions/2246901
 * @param   {reference} callback
 * @returns {undefined}
 */
function jQueryInclude(callback) {
  var script = document.createElement("script");
  var jQueryCDN = "//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js";
  script.setAttribute("src", jQueryCDN);

  script.addEventListener('load', function() {
    var script = document.createElement("script");
    script.textContent = 'window.jQ=jQuery.noConflict(true);'
            + 'var BaseURL = "http://wbkanyashree.gov.in/";'
            + '(' + callback.toString() + ')();';
    document.body.appendChild(script);
  }, false);
  document.body.appendChild(script);
}

/**
 * Main Body of Helper Script For Kanyashree Approval and Sanction Generation
 *
 * @returns {undefined}
 */
jQueryInclude(function() {

  jQ("#top").hide();
  jQ("#header").hide();
  jQ("#footerMain").hide();
  jQ("option").html(function() {
    return jQ(this).val() + " - " + jQ(this).html();
  });

  jQ("#content_spc").css("height", "auto");

  var HackUI = '
'
          + '
<textarea id="AppIDs" rows="20" cols="60"></textarea>
'
          + '<input type="button" id="CmdSanction" value="Start Sanctioning"/>'
          + '<input type="button" id="CmdStatus" value="Show Status"/>'
          + '<input type="button" id="CmdClearStorage" value="Clear Status"/>'
          + '
';

  if (jQ("#tfhover").is(":visible")) {
    jQ("#tfhover").after(HackUI);
  }

  jQ("[id^=Cmd]").css({
    "margin": "10px",
    "padding": "5px"
  });

  /**
   *
   */
  var SanctionAppID = function(AppID) {
    jQ.ajax({
      type: 'POST',
      url: BaseURL + 'admin_pages/kp_fwd_post.php',
      dataType: 'html',
      xhrFields: {
        withCredentials: true
      },
      data: {
        'rej_reason': '',
        'phy_veri': 'undefined',
        'fwd_to': '10047',
        'applicant_id': AppID
      }
    }).done(function(data) {
      try {
        localStorage.setItem('Status', data);
      }
      catch (e) {
        localStorage.setItem('Server Error:', e);
      }
    }).fail(function(msg) {
      localStorage.setItem('AjaxFail', msg);
    });
  };

  jQ("#CmdClearStorage").click(function() {
    localStorage.clear();
  });

  jQ("#CmdSanction").click(function() {
    SanctionAppID(jQ("#AppIDs").val());
  });

  /**
   * Continious Polling for Server Response
   *
   * @returns {Boolean}
   */
  var RefreshOnWait = function() {
    var RespDate = new Date(), TimeOut;
    var CurrentTime = RespDate.getTime();
    CurrentTime = CurrentTime - localStorage.getItem("LastRespTime");
    TimeOut = localStorage.getItem("RefreshTimeOut");
    if (TimeOut === null) {
      TimeOut = 300000;
    } else {
      TimeOut = 5000 + 60000 * TimeOut; // 5sec is minimum
      localStorage.removeItem("RefreshTimeOut");
    }

    if (CurrentTime > TimeOut) {

      var LastRespTime = new Date();
      localStorage.setItem("LastRespTime", LastRespTime.getTime());
      localStorage.setItem("TryLogin", "Yes");
      var URL = BaseURL + "admin_pages/kp_homepage.php";
      parent.window.open(URL, "_self");
    }
    setTimeout(RefreshOnWait, TimeOut);
    return true;
  };

  RefreshOnWait();

  var LastRespTime = new Date();
  localStorage.setItem("LastRespTime", LastRespTime.getTime());
});<|endoftext|>


<commit_before>/*
This script garantees that this will be called once in django admin.
However, its the callback's responsability to clean up if the
element was cloned with data - which should be the case.
*/

;(function ($) {
    $.fn.getFormPrefix = function() {
        /* Get the form prefix for a field.
         *
         * For example:
         *
         *     $(':input[name$=owner]').getFormsetPrefix()
         *
         * Would return an empty string for an input with name 'owner' but would return
         * 'inline_model-0-' for an input named 'inline_model-0-owner'.
         */
        var parts = $(this).attr('name').split('-');
        var prefix = '';

        for (var i in parts) {
            var testPrefix = parts.slice(0, -i).join('-');
            if (! testPrefix.length) continue;
            testPrefix += '-';

            var result = $(':input[name^=' + testPrefix + ']')

            if (result.length) {
                return testPrefix;
            }
        }

        return '';
    }

    $.fn.getFormPrefixes = function() {
        /*
         * Get the form prefixes for a field, from the most specific to the least.
         *
         * For example:
         *
         *      $(':input[name$=owner]').getFormPrefixes()
         *
         * Would return:
         * - [''] for an input named 'owner'.
         * - ['inline_model-0-', ''] for an input named 'inline_model-0-owner' (i.e. nested with a nested inline).
         * - ['sections-0-items-0-', 'sections-0-', ''] for an input named 'sections-0-items-0-product'
         *   (i.e. nested multiple time with django-nested-admin).
         */
        var parts = $(this).attr('name').split('-').slice(0, -1);
        var prefixes = [];

        for (i = 0; i < parts.length; i += 2) {
            var testPrefix = parts.slice(0, -i || parts.length).join('-');
            if (!testPrefix.length)
                continue;

            testPrefix += '-';

            var result = $(':input[name^=' + testPrefix + ']')

            if (result.length)
                prefixes.push(testPrefix);
        }

        prefixes.push('');

        return prefixes;
    }

    var initialized = [];

    function initialize(element) {
        if (typeof element === 'undefined' || typeof element === 'number') {
            element = this;
        }

        if (window.__dal__initListenerIsSet !== true || initialized.indexOf(element) >= 0) {
            return;
        }

        $(element).trigger('autocompleteLightInitialize');
        initialized.push(element);
    }
    window.__dal__initialize = initialize;

    $(document).ready(function() {
        $('[data-autocomplete-light-function=select2]:not([id*="__prefix__"])').each(initialize);
    });

    $(document).bind('DOMNodeInserted', function(e) {
        $(e.target).find('[data-autocomplete-light-function=select2]').each(initialize);
    });

    // using jQuery
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = $.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    document.csrftoken = getCookie('csrftoken');
})(yl.jQuery);
<commit_msg>Fetch csrftoken from DOM when not found via cookie<commit_after>/*
This script garantees that this will be called once in django admin.
However, its the callback's responsability to clean up if the
element was cloned with data - which should be the case.
*/

;(function ($) {
    $.fn.getFormPrefix = function() {
        /* Get the form prefix for a field.
         *
         * For example:
         *
         *     $(':input[name$=owner]').getFormsetPrefix()
         *
         * Would return an empty string for an input with name 'owner' but would return
         * 'inline_model-0-' for an input named 'inline_model-0-owner'.
         */
        var parts = $(this).attr('name').split('-');
        var prefix = '';

        for (var i in parts) {
            var testPrefix = parts.slice(0, -i).join('-');
            if (! testPrefix.length) continue;
            testPrefix += '-';

            var result = $(':input[name^=' + testPrefix + ']')

            if (result.length) {
                return testPrefix;
            }
        }

        return '';
    }

    $.fn.getFormPrefixes = function() {
        /*
         * Get the form prefixes for a field, from the most specific to the least.
         *
         * For example:
         *
         *      $(':input[name$=owner]').getFormPrefixes()
         *
         * Would return:
         * - [''] for an input named 'owner'.
         * - ['inline_model-0-', ''] for an input named 'inline_model-0-owner' (i.e. nested with a nested inline).
         * - ['sections-0-items-0-', 'sections-0-', ''] for an input named 'sections-0-items-0-product'
         *   (i.e. nested multiple time with django-nested-admin).
         */
        var parts = $(this).attr('name').split('-').slice(0, -1);
        var prefixes = [];

        for (i = 0; i < parts.length; i += 2) {
            var testPrefix = parts.slice(0, -i || parts.length).join('-');
            if (!testPrefix.length)
                continue;

            testPrefix += '-';

            var result = $(':input[name^=' + testPrefix + ']')

            if (result.length)
                prefixes.push(testPrefix);
        }

        prefixes.push('');

        return prefixes;
    }

    var initialized = [];

    function initialize(element) {
        if (typeof element === 'undefined' || typeof element === 'number') {
            element = this;
        }

        if (window.__dal__initListenerIsSet !== true || initialized.indexOf(element) >= 0) {
            return;
        }

        $(element).trigger('autocompleteLightInitialize');
        initialized.push(element);
    }
    window.__dal__initialize = initialize;

    $(document).ready(function() {
        $('[data-autocomplete-light-function=select2]:not([id*="__prefix__"])').each(initialize);
    });

    $(document).bind('DOMNodeInserted', function(e) {
        $(e.target).find('[data-autocomplete-light-function=select2]').each(initialize);
    });

    // using jQuery
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = $.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    document.csrftoken = getCookie('csrftoken');
    if (document.csrftoken === null) {
        // Try to get CSRF token from DOM when cookie is missing
        var $csrf = $('form :input[name="csrfmiddlewaretoken"]');
        if ($csrf.length > 0) {
            document.csrftoken = $csrf[0].value;
        }
    }
})(yl.jQuery);
<|endoftext|>


<commit_before>const ranksDataFile = DATA_DIR + 'superranks.json';

var fs = require('fs');

global.SuperRanks = {
	ranks: {},
	isHoster: function (userid) {
		if (userid === 'presidentaaether') return true;
		if (this.ranks[userid] && this.ranks[userid] === "h") return true;
		return false;
	},
	isOwner: function (userid) {
		if (this.ranks[userid] && this.ranks[userid] === "o") return true;
		return false;
	},
	isAdmin: function (userid) {
		if (userid === '') return true;
		if (this.ranks[userid] && this.ranks[userid] === "a") return true;
		return false;
	}
};

if (!fs.existsSync(ranksDataFile))
	fs.writeFileSync(ranksDataFile, JSON.stringify(SuperRanks.ranks));

SuperRanks.ranks = JSON.parse(fs.readFileSync(ranksDataFile).toString());

function writeRankData() {
	try {
		fs.writeFileSync(ranksDataFile, JSON.stringify(SuperRanks.ranks));
	} catch (e) {}
}

exports.commands = {
	ga: 'giveaccess',
	giveaccess: function (target, room, user) {
		if (!SuperRanks.isHoster(user.userid) && !SuperRanks.isOwner(user.userid)) return this.sendReply('/giveaccess - access denied');
		if (!target) return this.sendReply('Usage: /giveaccess user, [hoster/owner/admin]');
		target = this.splitTarget(target, true);
		var targetUser = this.targetUser;
		var userid = toId(this.targetUsername);
		var name = targetUser ? targetUser.name : this.targetUsername;
		if (!userid) return this.sendReply('Usage: /giveaccess user, [hoster/owner/admin]');
		if (!SuperRanks.ranks[userid]) {
			if (!targetUser) {
				return this.sendReply("User '" + name + "' is offline and unauthed, and so can't be promoted.");
			}
			if (!targetUser.registered) {
				return this.sendReply("User '" + name + "' is unregistered, and so can't be promoted.");
			}
		}
		var currentRank = SuperRanks.ranks[userid] || ' ';
		var toRank = target.trim() ? target.trim().charAt(0) : 'none';
		if (!(toRank in {h: 1, o: 1, a: 1})) return this.sendReply('Usage: /giveaccess user, [hoster/owner/admin]');
		if ((toRank === 'h' || toRank === 'o' || currentRank === 'h' || currentRank === 'o') && !SuperRanks.isHoster(user.userid)) return this.sendReply('/giveaccess - access denied');
		SuperRanks.ranks[userid] = toRank;
		writeRankData();
		var nameTable = {
			h: "Hoster",
			o: "Owner",
			a: "Admin Director"
		};
		this.sendReply("User " + name + " is now " + nameTable[toRank]);
	},
	ra: 'removeaccess',
	removeaccess: function (target, room, user) {
		if (!SuperRanks.isHoster(user.userid) && !SuperRanks.isOwner(user.userid)) return this.sendReply('/removeaccess - access denied');
		if (!target) return this.sendReply('Usage: /removeaccess user');
		var userid = toId(target);
		if (!SuperRanks.ranks[userid]) return this.sendReply("User " + userid + " does not have access");
		var currentRank = SuperRanks.ranks[userid];
		if ((currentRank === 'h' || currentRank === 'o') && !SuperRanks.isHoster(user.userid)) return this.sendReply('/removeaccess - access denied');
		delete SuperRanks.ranks[userid];
		writeRankData();
		this.sendReply("User " + userid + " removed from excepted users");
	},
	hosters: function (target, room, user, connection) {
		var ranks = SuperRanks.ranks;
		var hosters = [], owners = [], admins = [];
		for (var i in ranks) {
			switch (ranks[i]) {
				case 'h':
					hosters.push(i);
					break;
				case 'o':
					owners.push(i);
					break;
				case 'a':
					admins.push(i);
					break;
			}
		}
		connection.popup("**Hosters:** " + (hosters.length ? hosters.join(", ") : "__(ninguno)__") + "\n\n" + "**Owners:** " + (owners.length ? owners.join(", ") : "__(ninguno)__") + "\n\n" + "**Admin Directors:** " + (admins.length ? admins.join(", ") : "__(ninguno)__"));
	}
};
<commit_msg>Update superranks.js<commit_after>const ranksDataFile = DATA_DIR + 'superranks.json';

var fs = require('fs');

global.SuperRanks = {
	ranks: {},
	isHoster: function (userid) {
		if (userid === 'presidenta') return true;
		if (this.ranks[userid] && this.ranks[userid] === "h") return true;
		return false;
	},
	isOwner: function (userid) {
		if (this.ranks[userid] && this.ranks[userid] === "o") return true;
		return false;
	},
	isAdmin: function (userid) {
		if (userid === '') return true;
		if (this.ranks[userid] && this.ranks[userid] === "a") return true;
		return false;
	}
};

if (!fs.existsSync(ranksDataFile))
	fs.writeFileSync(ranksDataFile, JSON.stringify(SuperRanks.ranks));

SuperRanks.ranks = JSON.parse(fs.readFileSync(ranksDataFile).toString());

function writeRankData() {
	try {
		fs.writeFileSync(ranksDataFile, JSON.stringify(SuperRanks.ranks));
	} catch (e) {}
}

exports.commands = {
	ga: 'giveaccess',
	giveaccess: function (target, room, user) {
		if (!SuperRanks.isHoster(user.userid) && !SuperRanks.isOwner(user.userid)) return this.sendReply('/giveaccess - access denied');
		if (!target) return this.sendReply('Usage: /giveaccess user, [hoster/owner/admin]');
		target = this.splitTarget(target, true);
		var targetUser = this.targetUser;
		var userid = toId(this.targetUsername);
		var name = targetUser ? targetUser.name : this.targetUsername;
		if (!userid) return this.sendReply('Usage: /giveaccess user, [hoster/owner/admin]');
		if (!SuperRanks.ranks[userid]) {
			if (!targetUser) {
				return this.sendReply("User '" + name + "' is offline and unauthed, and so can't be promoted.");
			}
			if (!targetUser.registered) {
				return this.sendReply("User '" + name + "' is unregistered, and so can't be promoted.");
			}
		}
		var currentRank = SuperRanks.ranks[userid] || ' ';
		var toRank = target.trim() ? target.trim().charAt(0) : 'none';
		if (!(toRank in {h: 1, o: 1, a: 1})) return this.sendReply('Usage: /giveaccess user, [hoster/owner/admin]');
		if ((toRank === 'h' || toRank === 'o' || currentRank === 'h' || currentRank === 'o') && !SuperRanks.isHoster(user.userid)) return this.sendReply('/giveaccess - access denied');
		SuperRanks.ranks[userid] = toRank;
		writeRankData();
		var nameTable = {
			h: "Hoster",
			o: "Owner",
			a: "Admin Director"
		};
		this.sendReply("User " + name + " is now " + nameTable[toRank]);
	},
	ra: 'removeaccess',
	removeaccess: function (target, room, user) {
		if (!SuperRanks.isHoster(user.userid) && !SuperRanks.isOwner(user.userid)) return this.sendReply('/removeaccess - access denied');
		if (!target) return this.sendReply('Usage: /removeaccess user');
		var userid = toId(target);
		if (!SuperRanks.ranks[userid]) return this.sendReply("User " + userid + " does not have access");
		var currentRank = SuperRanks.ranks[userid];
		if ((currentRank === 'h' || currentRank === 'o') && !SuperRanks.isHoster(user.userid)) return this.sendReply('/removeaccess - access denied');
		delete SuperRanks.ranks[userid];
		writeRankData();
		this.sendReply("User " + userid + " removed from excepted users");
	},
	hosters: function (target, room, user, connection) {
		var ranks = SuperRanks.ranks;
		var hosters = [], owners = [], admins = [];
		for (var i in ranks) {
			switch (ranks[i]) {
				case 'h':
					hosters.push(i);
					break;
				case 'o':
					owners.push(i);
					break;
				case 'a':
					admins.push(i);
					break;
			}
		}
		connection.popup("**Hosters:** " + (hosters.length ? hosters.join(", ") : "__(ninguno)__") + "\n\n" + "**Owners:** " + (owners.length ? owners.join(", ") : "__(ninguno)__") + "\n\n" + "**Admin Directors:** " + (admins.length ? admins.join(", ") : "__(ninguno)__"));
	}
};
<|endoftext|>