code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
/** * The javascript file for list view. * * @version $Id: $ * @copyright Copyright (C) 2011 Migur Ltd. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ //TODO: Tottaly refacktoring. Create and use widgets! Migur.dnd.makeDND = function(el, droppables){ var avatar = el; avatar.makeDraggable({ droppables: droppables, onBeforeStart: function(draggable, droppable){ var coords = draggable.getCoordinates($$('body')[0]); $(draggable).store('source', draggable.getParent()); $$('body').grab(draggable); draggable.setStyles({ left: coords.left + 'px', top: coords.top + 'px', position: 'absolute', zIndex: 1000 }); }, onEnter: function(draggable, droppable){ var maxElsCount = droppable.retrieve('maxElsCount'); var elsCount = $(droppable).getChildren('.drag').length; if (maxElsCount == null || elsCount < maxElsCount) { droppable.addClass('overdropp'); } }, onLeave: function(draggable, droppable){ droppable.removeClass('overdropp'); }, onDrop: function(draggable, droppable){ var maxElsCount = (droppable)? parseInt(droppable.retrieve('maxElsCount')) : null; var elsCount = (droppable)? $(droppable).getChildren('.drag').length : null; var source = $(draggable).retrieve('source'); if (!droppable || (maxElsCount != null && elsCount >= maxElsCount) || source == droppable) { // out of dropable source.grab(draggable); draggable.setStyles({ left: 0, top: 0, position: 'relative', zIndex: 1000 }); } else { // hit in dropable droppable.grab(draggable); draggable.setStyles({ left: 0, top: 0, position: 'relative', zIndex: 'auto' }); } }, onCancel: function() { this.droppables.removeClass('overdropp'); }, onComplete: function() { this.droppables.removeClass('overdropp'); } }); return avatar; } window.addEvent('domready', function() { try { if ( typeof(Uploader) == 'undefined' ) Uploader = {}; Uploader.getHead = function(target, type) { var settings = Uploader.getSettings(type) || {}; Uploader.uploadControl = target; var id = $$('[name=list_id]')[0].get('value'); new Request.JSON({ url: '?option=com_newsletter&task=list.gethead', onComplete: Uploader.headParser }).send( '&list_id=' + id + '&jsondata=' + JSON.encode(settings) ); } Uploader.headParser = function(req) { var parser = new Migur.jsonResponseParser(); parser.setResponse(req); var data = parser.getData(); if (parser.isError()) { alert( parser.getMessagesAsList(Joomla.JText._('AN_UNKNOWN_ERROR_OCCURED', 'An unknown error occured!')) ); return; } if(!data || !data.fields || data.fields.length == 0) { alert(Joomla.JText._('NO_FIELDS_FOUND', 'No fields found!')); return; } var ctr = $(Uploader.uploadControl); if (ctr.getProperty('id') == 'import-file') { $('import-file').removeClass('hide'); $$('#import-file .drag').destroy(); for(var i=0; i < data.fields.length; i++) { var newEl = new Element( 'div', { 'html' : data.fields[i], 'class' : 'drag', 'position': 'relative', 'rel' : i } ) $('import-founded-fields').grab(newEl); Migur.dnd.makeDND(newEl, $$('#import-file .drop')); newEl.setStyle('position', 'relative'); } } else { $('exclude-file').removeClass('hide'); ctr.getElements('.drag').destroy(); for(var i=0; i < data.fields.length; i++) { var newEl = new Element( 'div', { 'html' : data.fields[i], 'class' : 'drag', 'position': 'relative', 'rel' : i } ) $('exclude-founded-fields').grab(newEl); Migur.dnd.makeDND(newEl, $$('#exclude-file .drop')); newEl.setStyle('position', 'relative'); } } } Uploader.getSettings = function(type) { var res = { fields: {}, delimiter: null, enclosure: null }; if (type == 'import') { if ( !$('import-delimiter').hasClass('hide') ) { res.delimiter = $('import-delimiter').get('value'); } else { res.delimiter = $('import-delimiter-custom').get('value'); } if ( !$('import-enclosure').hasClass('hide') ) { res.enclosure = $('import-enclosure').get('value'); } else { res.enclosure = $('import-enclosure-custom').get('value'); } res.overwrite = $('import-overwrite').getProperty('checked'); res.skipHeader = $('import-skip-header').getProperty('checked'); } if (type == 'exclude') { if ( !$('exclude-delimiter').hasClass('hide') ) { res.delimiter = $('exclude-delimiter').get('value'); } else { res.delimiter = $('exclude-delimiter-custom').get('value'); } if ( !$('exclude-enclosure').hasClass('hide') ) { res.enclosure = $('exclude-enclosure').get('value'); } else { res.enclosure = $('exclude-enclosure-custom').get('value'); } res.skipHeader = $('exclude-skip-header').getProperty('checked'); } if (!res.delimiter) { alert(Joomla.JText._('THE_DELIMITER_IS_NOT_SET','The delimiter is not set')); return false; } return res; } /** * Create wigets for each template control **/ $('unsubscribed_filter_search').addEvent('keyup', function() { var filter = $('unsubscribed_filter_search').get('value'); var count = 0; $$('#tab-container-unsubscribed tbody tr').each(function(tr){ var matchedRow = true; if (filter != '') { matchedRow = tr.getChildren('td').some(function(td, idx){ if (idx > 2) return false; var cell = $(td).get('text').trim(); return (cell.indexOf(filter) != -1); }); } if(matchedRow) { $(tr).removeClass('row0'); $(tr).removeClass('row1'); $(tr).addClass('row' + (count%2)); $(tr).removeClass('invisible'); } else { $(tr).addClass('invisible'); } count++; }); }); $('unsubscribed_filter_search').fireEvent('keyup'); Migur.lists.sortable.setup($('table-subs')); Migur.lists.sortable.setup($('table-unsubscribed')); Migur.lists.sortable.setup($('table-exclude')); $('jform_description').addEvent('keydown', function(){ if ( $(this).get('value').length > 255) { $(this).set('value', $(this).get('value').substr(0,255)); } }); $('exclude-tab-button').addEvent('click', function(){ var data = []; $$('#exclude-tab-scroller [name=cid[]]').each(function(el){ if (el.get('checked')) { data.push(el.get('value')); } }); data = {'lists': data}; var id = $$('[name=list_id]').get('value'); new Request.JSON({ url: '?option=com_newsletter&task=list.exclude&subtask=lists', onComplete: function(res){ var parser = new Migur.jsonResponseParser(); parser.setResponse(res); var data = parser.getData(); if (parser.isError()) { alert( parser.getMessagesAsList(Joomla.JText._('AN_UNKNOWN_ERROR_OCCURED', 'An unknown error occured!')) ); return; } alert(parser.getMessagesAsList() + "\n\n"+Joomla.JText._('TOTAL_PROCESSED', 'Total processed')+": " + data.total); Cookie.write('jpanetabs_tabs-list', 3); window.location.reload(); } }).send('&list_id=' + id + '&jsondata='+JSON.encode(data)); }); $('import-upload-submit').addEvent('click', function(){ if ($('import-upload-file').get('value')) { $$('[name=task]')[0].set('value', 'list.upload'); $$('[name=subtask]')[0].set('value', 'import'); //$('listForm').submit(); } else { return false; } }); $('exclude-upload-submit').addEvent('click', function(){ if ($('exclude-upload-file').get('value')) { $$('[name=task]')[0].set('value', 'list.upload'); $$('[name=subtask]')[0].set('value', 'exclude'); //$('listForm').submit(); } else { return false; } }); $('import-file-refresh').addEvent('click', function(){ Uploader.getHead( $('import-file'), 'import' ); }); $('exclude-file-refresh').addEvent('click', function(){ Uploader.getHead( $('exclude-file'), 'exclude' ); }); $('import-file-apply').addEvent('click', function(){ var res = Uploader.getSettings('import'); var notEnough = false; $$('#import-fields .drop').each(function(el){ var field = el.getProperty('rel'); var drag = el.getChildren('.drag')[0]; var def = null; var mapped = null; if (field == 'html') { def = $('import-file-html-default').get('value'); } if (!drag) { if (field != 'html') { notEnough = true; } } else { mapped = drag.getProperty('rel'); } res.fields[field] = { 'mapped' : mapped, 'default': def }; }); if (notEnough == true) { alert(Joomla.JText._('PLEASE_FILL_ALL_REQUIRED_FIELDS','Please fill all required fields')); } else { $$('[name=subtask]').set('value', 'import-file-apply'); var id = $$('[name=list_id]')[0].get('value'); var importMan = new Migur.iterativeAjax({ url: '?option=com_newsletter&task=list.import', data: { jsondata: JSON.encode(res), list_id: id }, limit: 1000, messagePath: '#import-file #import-message', preloaderPath: '#import-file #import-preloader', onComplete: function(messages, data){ this.showAlert( messages, Joomla.JText._('TOTAL','Total')+": " + data.total + "\n"+ Joomla.JText._('SKIPPED','Skipped')+": " + data.skipped + "\n"+ Joomla.JText._('ERRORS', 'Errors')+": " + data.errors + "\n"+ Joomla.JText._('ADDED', 'Added')+": " + data.added + "\n"+ Joomla.JText._('UPDATED', 'Updated')+": " + data.updated + "\n"+ Joomla.JText._('ASSIGNED', 'Assigned')+": " + data.assigned + "\n" ); document.location.reload(); } }); importMan.start(); } }); $('exclude-file-apply').addEvent('click', function(){ var res = Uploader.getSettings('exclude'); var notEnough = false; $$('#exclude-fields .drop').each(function(el){ var field = el.getProperty('rel'); var drag = el.getChildren('.drag')[0]; var def = null; var mapped = null; if (field == 'html') { def = $('exclude-file-html-default').get('value'); } if (!drag) { if (field != 'html') { notEnough = true; } } else { mapped = drag.getProperty('rel'); } res.fields[field] = { 'mapped' : mapped, 'default': def }; }); if (notEnough == true) { alert(Joomla.JText._('PLEASE_FILL_ALL_REQUIRED_FIELDS','Please fill all required fields')); } else { $$('[name=subtask]').set('value', 'exclude-file-apply'); var id = $$('[name=list_id]').get('value'); //$$('#exclude-del-cont .active') new Request.JSON({ url: '?option=com_newsletter&task=list.exclude&subtask=parse', onComplete: function(res){ var parser = new Migur.jsonResponseParser(); parser.setResponse(res); var data = parser.getData(); if (parser.isError()) { alert( parser.getMessagesAsList(Joomla.JText._('AN_UNKNOWN_ERROR_OCCURED', 'An unknown error occured!')) ); return; } alert(parser.getMessagesAsList() + "\n\n"+Joomla.JText._('PROCESSED', 'Processed')+": " + data.processed + "\n"+Joomla.JText._('ABSENT', 'Absent')+": " + data.absent + "\n" + Joomla.JText._('TOTAL','Total')+": " + data.total); document.location.reload(); } }).send( '&list_id=' + id + '&jsondata=' + JSON.encode(res) ); } }); if ( ! $$('[name=list_id]')[0].get('value') ) { $$('#import-toolbar span').addClass('toolbar-inactive'); $$('#exclude-toolbar span').addClass('toolbar-inactive'); } else { $('import-toolbar-export').addEvent('click', function(){ $('import-file').toggleClass('hide'); $$('.plugin-pane')[0].addClass('hide'); }); $('exclude-toolbar-lists').addEvent('click', function(){ $('exclude-lists').toggleClass('hide'); $('exclude-file').addClass('hide'); }); $('exclude-toolbar-file').addEvent('click', function(){ $('exclude-file').toggleClass('hide'); $('exclude-lists').addClass('hide'); }); } $$('.tab-import a').addEvent('click', function(){ $('import-uploadform').grab('flash-form'); }); $$('.tab-exclude a').addEvent('click', function(){ $('exclude-uploadform').grab('flash-form'); }); $$('#import-fields .drop, #export-fields .drop').each(function(el){ el.store('maxElsCount', 1); }); $('import-del-toggle-button').addEvent('click', function(){ $('import-delimiter').toggleClass('hide'); $('import-delimiter-custom').toggleClass('hide'); var rel = $(this).getProperty('rel'); var val = $(this).get('value'); $(this).setProperty('rel', val); $(this).setProperty('value', rel); }); $('import-enc-toggle-button').addEvent('click', function(){ $('import-enclosure').toggleClass('hide'); $('import-enclosure-custom').toggleClass('hide'); var rel = $(this).getProperty('rel'); var val = $(this).get('value'); $(this).setProperty('rel', val); $(this).setProperty('value', rel); }); $$('#import-enclosure-custom, #import-delimiter-custom') .addEvent('keypress', function(event){ if (event.code >= 32) { $(this).set('value', ''); } }); if ( typeof(uploadData) != 'undefined' ) { var color, msg; // The IMPORT tab if (subtask == 1) { $('import-toolbar-export').fireEvent('click'); if (uploadData.status == 1) { color = '#00AA00'; Uploader.getHead( $('import-file'), 'import' ); } else { color = '#AA0000'; } msg = '<span style="color:' + color + ';"><h3>' + uploadData.error + '<h3></span>'; $$('#import-uploadform .upload-queue li')[0].set('html', msg); } else { // The EXCLUDE tab if (subtask == 2) { $('exclude-toolbar-file').fireEvent('click'); if (uploadData.status == 1) { color = '#00AA00'; Uploader.getHead( $('exclude-file'), 'exclude' ); } else { color = '#AA0000'; } msg = '<span style="color:' + color + ';"><h3>' + uploadData.error + '<h3></span>'; $$('#exclude-uploadform .upload-queue li')[0].set('html', msg); } } } $$('input, select, textarea').addEvent('blur', function(){ Migur.validator.tabIndicator( '#listForm', 'span h3 a', 'tab-invalid', '.invalid' ); }); var handler = function(){ var checked = $(this).getProperty('checked'); $('jform_send_at_reg').setProperty('disabled', checked); $('jform_send_at_reg').setProperty('readonly', checked); }; $('jform_autoconfirm').addEvent('click', handler); handler.apply($('jform_autoconfirm')); delete handler; } catch(e){ if (console && console.log) console.log(e); } });
thmarkos/k12finance
administrator/components/com_newsletter/views/list/list.js
JavaScript
gpl-2.0
18,126
'use strict'; /** * External dependencies */ const fs = require('fs'); const JSZip = require('jszip'); /** * Internal dependencies */ const log = require('./')('desktop:lib:archiver'); module.exports = { /** * Compresses `contents` to the archive at `dst`. * * @param {String[]} contents Paths to be zipped * @param {String} dst Path to destination archive * @param {function():void} onZipped Callback invoked when archive is complete */ zipContents: (logPath, dst, onZipped) => { const zip = new JSZip(); zip.file( 'simplenote.log', new Promise((resolve, reject) => fs.readFile(logPath, (error, data) => { if (error) { log.warn('Unexpected error: ', error); reject(error); } else { resolve(data); } }) ) ); const output = fs.createWriteStream(dst); // Catch warnings (e.g. stat failures and other non-blocking errors) output.on('warning', function (err) { log.warn('Unexpected error: ', err); }); output.on('error', function (err) { throw err; }); zip .generateNodeStream({ type: 'nodebuffer', streamFiles: true }) .pipe(output) .on('finish', function () { log.debug('Archive finalized'); if (typeof onZipped === 'function') { onZipped(); } }); }, };
Automattic/simplenote-electron
desktop/logger/archiver.js
JavaScript
gpl-2.0
1,397
/* -*- mode: js2 - indent-tabs-mode: nil - js2-basic-offset: 4 -*- */ const Lang = imports.lang; const St = imports.gi.St; const Main = imports.ui.main; const PopupMenu = imports.ui.popupMenu; const Gettext = imports.gettext.domain('gnome-shell-extensions'); const _ = Gettext.gettext; const ExtensionUtils = imports.misc.extensionUtils; const Me = ExtensionUtils.getCurrentExtension(); const Convenience = Me.imports.convenience; let suspend_item = null; let hibernate_item = null; let poweroff_item = null; let suspend_signal_id = 0, hibernate_signal_id = 0; let settings = null; let setting_changed_id = 0; function updateSuspend(object, pspec, item) { item.actor.visible = object.get_can_suspend() && settings.get_boolean('allow-suspend'); } function updateHibernate(object, pspec, item) { item.actor.visible = object.get_can_hibernate() && settings.get_boolean('allow-hibernate'); } function onSuspendActivate(item) { Main.overview.hide(); this._screenSaverProxy.LockRemote(Lang.bind(this, function() { this._upClient.suspend_sync(null); })); } function onHibernateActivate(item) { Main.overview.hide(); this._screenSaverProxy.LockRemote(Lang.bind(this, function() { this._upClient.hibernate_sync(null); })); } // Put your extension initialization code here function init(metadata) { Convenience.initTranslations(); } function enable() { let statusMenu = Main.panel._statusArea.userMenu; settings = Convenience.getSettings(); let children = statusMenu.menu._getMenuItems(); let index = children.length; /* find and destroy the old entry */ for (let i = children.length - 1; i >= 0; i--) { if (children[i] == statusMenu._suspendOrPowerOffItem) { children[i].destroy(); index = i; break; } } /* add the new entries */ suspend_item = new PopupMenu.PopupMenuItem(_("Suspend")); suspend_item.connect('activate', Lang.bind(statusMenu, onSuspendActivate)); suspend_signal_id = statusMenu._upClient.connect('notify::can-suspend', Lang.bind(statusMenu, updateSuspend, suspend_item)); updateSuspend(statusMenu._upClient, null, suspend_item); hibernate_item = new PopupMenu.PopupMenuItem(_("Hibernate")); hibernate_item.connect('activate', Lang.bind(statusMenu, onHibernateActivate)); hibernate_signal_id = statusMenu._upClient.connect('notify::can-hibernate', Lang.bind(statusMenu, updateHibernate, hibernate_item)); updateHibernate(statusMenu._upClient, null, hibernate_item); poweroff_item = new PopupMenu.PopupMenuItem(_("Power Off")); poweroff_item.connect('activate', Lang.bind(statusMenu, function() { this._session.ShutdownRemote(); })); /* insert the entries at the found position */ statusMenu.menu.addMenuItem(suspend_item, index); statusMenu.menu.addMenuItem(hibernate_item, index + 1); statusMenu.menu.addMenuItem(poweroff_item, index + 2); // clear out this to avoid criticals (we don't mess with // updateSuspendOrPowerOff) statusMenu._suspendOrPowerOffItem = null; setting_changed_id = settings.connect('changed', function() { updateSuspend(statusMenu._upClient, null, suspend_item); updateHibernate(statusMenu._upClient, null, hibernate_item); }); } function disable() { let statusMenu = Main.panel._statusArea.userMenu; let children = statusMenu.menu._getMenuItems(); let index = children.length; /* find the index for the previously created suspend entry */ for (let i = children.length - 1; i >= 0; i--) { if (children[i] == suspend_item) { index = i; break; } } /* disconnect signals */ statusMenu._upClient.disconnect(suspend_signal_id); statusMenu._upClient.disconnect(hibernate_signal_id); suspend_signal_id = hibernate_signal_id = 0; settings.disconnect(setting_changed_id); setting_changed_id = 0; settings = null; /* destroy the entries we had created */ suspend_item.destroy(); hibernate_item.destroy(); poweroff_item.destroy(); /* create a new suspend/poweroff entry */ /* empty strings are fine for the labels, since we immediately call updateSuspendOrPowerOff */ let item = new PopupMenu.PopupAlternatingMenuItem("", ""); /* restore the userMenu field */ statusMenu._suspendOrPowerOffItem = item; statusMenu.menu.addMenuItem(item, index); item.connect('activate', Lang.bind(statusMenu, statusMenu._onSuspendOrPowerOffActivate)); statusMenu._updateSuspendOrPowerOff(); }
BastienDurel/gnome-shell-extensions-bd
extensions/alternative-status-menu/extension.js
JavaScript
gpl-2.0
4,593
jQuery(document).ready(function($){ $('#quick_contact').submit(function(){ var action = $(this).attr('action'); var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; var error = 0; //Validations if($("#quick_name").val() == ''){ $("#quick_name").next().fadeOut(100); $(".name-error").fadeIn('slow'); error = 1; } if($("#quick_email").val() == ''){ $("#quick_email").next().fadeOut(100); $(".email-error").fadeIn('slow'); error = 1; }else if(!emailReg.test(jQuery.trim($("#email").val()))) { $(".email-error").fadeIn('slow'); error = 1; } if($("#quick_comments").val() == ''){ $(".comments-error").fadeIn('slow'); error = 1; } //If no errors send email if(error == 0){ $('.mesage') .after('<div class="sending">Sending...</div>') $.post(action, { name: $('#quick_name').val(), email: $('#quick_email').val(), remail: $('#quick_remail').val(), phone: $('#quick_phone').val(), subject: $('#quick_subject').val(), comments: $('#quick_comments').val() }, function(data){ $(".mesage").html(data); $('.form div.sending').fadeOut('slow',function(){$(this).remove()}); if(data.match('Email Sent') != null) $('#quick_contact').slideUp('slow'); } ); } return false; }); });
amolc/theartfellas
wp-content/themes/elitist/js/contact-form.js
JavaScript
gpl-2.0
1,386
/** * External dependencies */ export default function Placeholder( { height } ) { return <div style={ height ? { height } : null } className="placeholder" />; }
aduth/dones
src/components/placeholder/index.js
JavaScript
gpl-2.0
166
/** * DO NOT EDIT THIS FILE. * See the following change record for more information, * https://www.drupal.org/node/2815083 * @preserve **/ (function ($, Drupal, displace) { function TableHeader(table) { var $table = $(table); this.$originalTable = $table; this.$originalHeader = $table.children('thead'); this.$originalHeaderCells = this.$originalHeader.find('> tr > th'); this.displayWeight = null; this.$originalTable.addClass('sticky-table'); this.tableHeight = $table[0].clientHeight; this.tableOffset = this.$originalTable.offset(); this.$originalTable.on('columnschange', { tableHeader: this }, function (e, display) { var tableHeader = e.data.tableHeader; if (tableHeader.displayWeight === null || tableHeader.displayWeight !== display) { tableHeader.recalculateSticky(); } tableHeader.displayWeight = display; }); this.createSticky(); } function forTables(method, arg) { var tables = TableHeader.tables; var il = tables.length; for (var i = 0; i < il; i++) { tables[i][method](arg); } } function tableHeaderInitHandler(e) { var $tables = $(e.data.context).find('table.sticky-enabled').once('tableheader'); var il = $tables.length; for (var i = 0; i < il; i++) { TableHeader.tables.push(new TableHeader($tables[i])); } forTables('onScroll'); } Drupal.behaviors.tableHeader = { attach: function attach(context) { $(window).one('scroll.TableHeaderInit', { context: context }, tableHeaderInitHandler); } }; function scrollValue(position) { return document.documentElement[position] || document.body[position]; } function tableHeaderResizeHandler(e) { forTables('recalculateSticky'); } function tableHeaderOnScrollHandler(e) { forTables('onScroll'); } function tableHeaderOffsetChangeHandler(e, offsets) { forTables('stickyPosition', offsets.top); } $(window).on({ 'resize.TableHeader': tableHeaderResizeHandler, 'scroll.TableHeader': tableHeaderOnScrollHandler }); $(document).on({ 'columnschange.TableHeader': tableHeaderResizeHandler, 'drupalViewportOffsetChange.TableHeader': tableHeaderOffsetChangeHandler }); $.extend(TableHeader, { tables: [] }); $.extend(TableHeader.prototype, { minHeight: 100, tableOffset: null, tableHeight: null, stickyVisible: false, createSticky: function createSticky() { var $stickyHeader = this.$originalHeader.clone(true); this.$stickyTable = $('<table class="sticky-header"/>').css({ visibility: 'hidden', position: 'fixed', top: '0px' }).append($stickyHeader).insertBefore(this.$originalTable); this.$stickyHeaderCells = $stickyHeader.find('> tr > th'); this.recalculateSticky(); }, stickyPosition: function stickyPosition(offsetTop, offsetLeft) { var css = {}; if (typeof offsetTop === 'number') { css.top = offsetTop + 'px'; } if (typeof offsetLeft === 'number') { css.left = this.tableOffset.left - offsetLeft + 'px'; } return this.$stickyTable.css(css); }, checkStickyVisible: function checkStickyVisible() { var scrollTop = scrollValue('scrollTop'); var tableTop = this.tableOffset.top - displace.offsets.top; var tableBottom = tableTop + this.tableHeight; var visible = false; if (tableTop < scrollTop && scrollTop < tableBottom - this.minHeight) { visible = true; } this.stickyVisible = visible; return visible; }, onScroll: function onScroll(e) { this.checkStickyVisible(); this.stickyPosition(null, scrollValue('scrollLeft')); this.$stickyTable.css('visibility', this.stickyVisible ? 'visible' : 'hidden'); }, recalculateSticky: function recalculateSticky(event) { this.tableHeight = this.$originalTable[0].clientHeight; displace.offsets.top = displace.calculateOffset('top'); this.tableOffset = this.$originalTable.offset(); this.stickyPosition(displace.offsets.top, scrollValue('scrollLeft')); var $that = null; var $stickyCell = null; var display = null; var il = this.$originalHeaderCells.length; for (var i = 0; i < il; i++) { $that = $(this.$originalHeaderCells[i]); $stickyCell = this.$stickyHeaderCells.eq($that.index()); display = $that.css('display'); if (display !== 'none') { $stickyCell.css({ width: $that.css('width'), display: display }); } else { $stickyCell.css('display', 'none'); } } this.$stickyTable.css('width', this.$originalTable.outerWidth()); } }); Drupal.TableHeader = TableHeader; })(jQuery, Drupal, window.parent.Drupal.displace);
coderdojo-hirakata/coderdojo-hirakata.github.io
core/misc/tableheader.js
JavaScript
gpl-2.0
4,836
(function (module) { 'use strict'; module.factory('NavToggleSvc', NavToggleSvc); function NavToggleSvc($mdSidenav) { function toggleLeftMenu() { $mdSidenav('left').toggle(); } return { toggleLeftMenu: toggleLeftMenu }; } })(angular.module('app.services'));
ride-share-market/app
app/components/app/services/app-service-nav-toggle.js
JavaScript
gpl-2.0
300
<<<<<<< HEAD /* Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ (function() { var stylesManager; CKEDITOR.plugins.add( 'stylescombo', { requires : [ 'richcombo', 'styles' ], init : function( editor ) { var config = editor.config, lang = editor.lang.stylesCombo, pluginPath = this.path, styles; if ( !stylesManager ) stylesManager = CKEDITOR.stylesSet; var comboStylesSet = config.stylesCombo_stylesSet.split( ':' ), styleSetName = comboStylesSet[ 0 ], externalPath = comboStylesSet[ 1 ]; stylesManager.addExternal( styleSetName, externalPath ? comboStylesSet.slice( 1 ).join( ':' ) : pluginPath + 'styles/' + styleSetName + '.js', '' ); editor.ui.addRichCombo( 'Styles', { label : lang.label, title : lang.panelTitle, className : 'cke_styles', panel : { css : editor.skin.editor.css.concat( config.contentsCss ), multiSelect : true, attributes : { 'aria-label' : lang.panelTitle } }, init : function() { var combo = this; CKEDITOR.stylesSet.load( styleSetName, function( stylesSet ) { var stylesDefinitions = stylesSet[ styleSetName ], style, styleName, stylesList = []; styles = {}; // Put all styles into an Array. for ( var i = 0 ; i < stylesDefinitions.length ; i++ ) { var styleDefinition = stylesDefinitions[ i ]; styleName = styleDefinition.name; style = styles[ styleName ] = new CKEDITOR.style( styleDefinition ); style._name = styleName; stylesList.push( style ); } // Sorts the Array, so the styles get grouped // by type. stylesList.sort( sortStyles ); // Loop over the Array, adding all items to the // combo. var lastType; for ( i = 0 ; i < stylesList.length ; i++ ) { style = stylesList[ i ]; styleName = style._name; var type = style.type; if ( type != lastType ) { combo.startGroup( lang[ 'panelTitle' + String( type ) ] ); lastType = type; } combo.add( styleName, style.type == CKEDITOR.STYLE_OBJECT ? styleName : buildPreview( style._.definition ), styleName ); } combo.commit(); combo.onOpen(); }); }, onClick : function( value ) { editor.focus(); editor.fire( 'saveSnapshot' ); var style = styles[ value ], selection = editor.getSelection(); if ( style.type == CKEDITOR.STYLE_OBJECT ) { var element = selection.getSelectedElement(); if ( element ) style.applyToObject( element ); return; } var elementPath = new CKEDITOR.dom.elementPath( selection.getStartElement() ); if ( style.type == CKEDITOR.STYLE_INLINE && style.checkActive( elementPath ) ) style.remove( editor.document ); else style.apply( editor.document ); editor.fire( 'saveSnapshot' ); }, onRender : function() { editor.on( 'selectionChange', function( ev ) { var currentValue = this.getValue(); var elementPath = ev.data.path, elements = elementPath.elements; // For each element into the elements path. for ( var i = 0, element ; i < elements.length ; i++ ) { element = elements[i]; // Check if the element is removable by any of // the styles. for ( var value in styles ) { if ( styles[ value ].checkElementRemovable( element, true ) ) { if ( value != currentValue ) this.setValue( value ); return; } } } // If no styles match, just empty it. this.setValue( '' ); }, this); }, onOpen : function() { if ( CKEDITOR.env.ie ) editor.focus(); var selection = editor.getSelection(); var element = selection.getSelectedElement(), elementName = element && element.getName(), elementPath = new CKEDITOR.dom.elementPath( element || selection.getStartElement() ); var counter = [ 0, 0, 0, 0 ]; this.showAll(); this.unmarkAll(); for ( var name in styles ) { var style = styles[ name ], type = style.type; if ( type == CKEDITOR.STYLE_OBJECT ) { if ( element && style.element == elementName ) { if ( style.checkElementRemovable( element, true ) ) this.mark( name ); counter[ type ]++; } else this.hideItem( name ); } else { if ( style.checkActive( elementPath ) ) this.mark( name ); counter[ type ]++; } } if ( !counter[ CKEDITOR.STYLE_BLOCK ] ) this.hideGroup( lang[ 'panelTitle' + String( CKEDITOR.STYLE_BLOCK ) ] ); if ( !counter[ CKEDITOR.STYLE_INLINE ] ) this.hideGroup( lang[ 'panelTitle' + String( CKEDITOR.STYLE_INLINE ) ] ); if ( !counter[ CKEDITOR.STYLE_OBJECT ] ) this.hideGroup( lang[ 'panelTitle' + String( CKEDITOR.STYLE_OBJECT ) ] ); } }); } }); function buildPreview( styleDefinition ) { var html = []; var elementName = styleDefinition.element; // Avoid <bdo> in the preview. if ( elementName == 'bdo' ) elementName = 'span'; html = [ '<', elementName ]; // Assign all defined attributes. var attribs = styleDefinition.attributes; if ( attribs ) { for ( var att in attribs ) { html.push( ' ', att, '="', attribs[ att ], '"' ); } } // Assign the style attribute. var cssStyle = CKEDITOR.style.getStyleText( styleDefinition ); if ( cssStyle ) html.push( ' style="', cssStyle, '"' ); html.push( '>', styleDefinition.name, '</', elementName, '>' ); return html.join( '' ); } function sortStyles( styleA, styleB ) { var typeA = styleA.type, typeB = styleB.type; return typeA == typeB ? 0 : typeA == CKEDITOR.STYLE_OBJECT ? -1 : typeB == CKEDITOR.STYLE_OBJECT ? 1 : typeB == CKEDITOR.STYLE_BLOCK ? 1 : -1; } })(); /** * The "styles definition set" to load into the styles combo. The styles may * be defined in the page containing the editor, or can be loaded on demand * from an external file when opening the styles combo for the fist time. In * the second case, if this setting contains only a name, the styles definition * file will be loaded from the "styles" folder inside the stylescombo plugin * folder. Otherwise, this setting has the "name:url" syntax, making it * possible to set the URL from which loading the styles file. * @type string * @default 'default' * @example * // Load from the stylescombo styles folder (mystyles.js file). * config.stylesCombo_stylesSet = 'mystyles'; * @example * // Load from a relative URL. * config.stylesCombo_stylesSet = 'mystyles:/editorstyles/styles.js'; * @example * // Load from a full URL. * config.stylesCombo_stylesSet = 'mystyles:http://www.example.com/editorstyles/styles.js'; */ CKEDITOR.config.stylesCombo_stylesSet = 'default'; ======= /* Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ (function() { var stylesManager; CKEDITOR.plugins.add( 'stylescombo', { requires : [ 'richcombo', 'styles' ], init : function( editor ) { var config = editor.config, lang = editor.lang.stylesCombo, pluginPath = this.path, styles; if ( !stylesManager ) stylesManager = CKEDITOR.stylesSet; var comboStylesSet = config.stylesCombo_stylesSet.split( ':' ), styleSetName = comboStylesSet[ 0 ], externalPath = comboStylesSet[ 1 ]; stylesManager.addExternal( styleSetName, externalPath ? comboStylesSet.slice( 1 ).join( ':' ) : pluginPath + 'styles/' + styleSetName + '.js', '' ); editor.ui.addRichCombo( 'Styles', { label : lang.label, title : lang.panelTitle, className : 'cke_styles', panel : { css : editor.skin.editor.css.concat( config.contentsCss ), multiSelect : true, attributes : { 'aria-label' : lang.panelTitle } }, init : function() { var combo = this; CKEDITOR.stylesSet.load( styleSetName, function( stylesSet ) { var stylesDefinitions = stylesSet[ styleSetName ], style, styleName, stylesList = []; styles = {}; // Put all styles into an Array. for ( var i = 0 ; i < stylesDefinitions.length ; i++ ) { var styleDefinition = stylesDefinitions[ i ]; styleName = styleDefinition.name; style = styles[ styleName ] = new CKEDITOR.style( styleDefinition ); style._name = styleName; stylesList.push( style ); } // Sorts the Array, so the styles get grouped // by type. stylesList.sort( sortStyles ); // Loop over the Array, adding all items to the // combo. var lastType; for ( i = 0 ; i < stylesList.length ; i++ ) { style = stylesList[ i ]; styleName = style._name; var type = style.type; if ( type != lastType ) { combo.startGroup( lang[ 'panelTitle' + String( type ) ] ); lastType = type; } combo.add( styleName, style.type == CKEDITOR.STYLE_OBJECT ? styleName : buildPreview( style._.definition ), styleName ); } combo.commit(); combo.onOpen(); }); }, onClick : function( value ) { editor.focus(); editor.fire( 'saveSnapshot' ); var style = styles[ value ], selection = editor.getSelection(); if ( style.type == CKEDITOR.STYLE_OBJECT ) { var element = selection.getSelectedElement(); if ( element ) style.applyToObject( element ); return; } var elementPath = new CKEDITOR.dom.elementPath( selection.getStartElement() ); if ( style.type == CKEDITOR.STYLE_INLINE && style.checkActive( elementPath ) ) style.remove( editor.document ); else style.apply( editor.document ); editor.fire( 'saveSnapshot' ); }, onRender : function() { editor.on( 'selectionChange', function( ev ) { var currentValue = this.getValue(); var elementPath = ev.data.path, elements = elementPath.elements; // For each element into the elements path. for ( var i = 0, element ; i < elements.length ; i++ ) { element = elements[i]; // Check if the element is removable by any of // the styles. for ( var value in styles ) { if ( styles[ value ].checkElementRemovable( element, true ) ) { if ( value != currentValue ) this.setValue( value ); return; } } } // If no styles match, just empty it. this.setValue( '' ); }, this); }, onOpen : function() { if ( CKEDITOR.env.ie ) editor.focus(); var selection = editor.getSelection(); var element = selection.getSelectedElement(), elementName = element && element.getName(), elementPath = new CKEDITOR.dom.elementPath( element || selection.getStartElement() ); var counter = [ 0, 0, 0, 0 ]; this.showAll(); this.unmarkAll(); for ( var name in styles ) { var style = styles[ name ], type = style.type; if ( type == CKEDITOR.STYLE_OBJECT ) { if ( element && style.element == elementName ) { if ( style.checkElementRemovable( element, true ) ) this.mark( name ); counter[ type ]++; } else this.hideItem( name ); } else { if ( style.checkActive( elementPath ) ) this.mark( name ); counter[ type ]++; } } if ( !counter[ CKEDITOR.STYLE_BLOCK ] ) this.hideGroup( lang[ 'panelTitle' + String( CKEDITOR.STYLE_BLOCK ) ] ); if ( !counter[ CKEDITOR.STYLE_INLINE ] ) this.hideGroup( lang[ 'panelTitle' + String( CKEDITOR.STYLE_INLINE ) ] ); if ( !counter[ CKEDITOR.STYLE_OBJECT ] ) this.hideGroup( lang[ 'panelTitle' + String( CKEDITOR.STYLE_OBJECT ) ] ); } }); } }); function buildPreview( styleDefinition ) { var html = []; var elementName = styleDefinition.element; // Avoid <bdo> in the preview. if ( elementName == 'bdo' ) elementName = 'span'; html = [ '<', elementName ]; // Assign all defined attributes. var attribs = styleDefinition.attributes; if ( attribs ) { for ( var att in attribs ) { html.push( ' ', att, '="', attribs[ att ], '"' ); } } // Assign the style attribute. var cssStyle = CKEDITOR.style.getStyleText( styleDefinition ); if ( cssStyle ) html.push( ' style="', cssStyle, '"' ); html.push( '>', styleDefinition.name, '</', elementName, '>' ); return html.join( '' ); } function sortStyles( styleA, styleB ) { var typeA = styleA.type, typeB = styleB.type; return typeA == typeB ? 0 : typeA == CKEDITOR.STYLE_OBJECT ? -1 : typeB == CKEDITOR.STYLE_OBJECT ? 1 : typeB == CKEDITOR.STYLE_BLOCK ? 1 : -1; } })(); /** * The "styles definition set" to load into the styles combo. The styles may * be defined in the page containing the editor, or can be loaded on demand * from an external file when opening the styles combo for the fist time. In * the second case, if this setting contains only a name, the styles definition * file will be loaded from the "styles" folder inside the stylescombo plugin * folder. Otherwise, this setting has the "name:url" syntax, making it * possible to set the URL from which loading the styles file. * @type string * @default 'default' * @example * // Load from the stylescombo styles folder (mystyles.js file). * config.stylesCombo_stylesSet = 'mystyles'; * @example * // Load from a relative URL. * config.stylesCombo_stylesSet = 'mystyles:/editorstyles/styles.js'; * @example * // Load from a full URL. * config.stylesCombo_stylesSet = 'mystyles:http://www.example.com/editorstyles/styles.js'; */ CKEDITOR.config.stylesCombo_stylesSet = 'default'; >>>>>>> origin/master
marvoey/live-web
sites/all/libraries/ckeditor/_source/plugins/stylescombo/plugin.js
JavaScript
gpl-2.0
14,693
import "../../css/matrix.css"; import * as $ from "jquery"; import * as _ from "underscore"; import {BaseFrameView} from "../ui-utils/base-frame-view"; import { crosslinkCountPerProteinPairing, findResiduesInSquare, getDistanceSquared, radixSort } from "../modelUtils"; import {getChainNameFromChainIndex, make3DAlignID} from "./ngl/NGLUtils"; import {commonLabels, declutterAxis, makeBackboneButtons} from "../utils"; import d3 from "d3"; import {makeTooltipContents, makeTooltipTitle} from "../make-tooltip"; export const DistanceMatrixViewBB = BaseFrameView.extend({ events: function () { let parentEvents = BaseFrameView.prototype.events; if (_.isFunction(parentEvents)) { parentEvents = parentEvents(); } return _.extend({}, parentEvents, { "mousemove .mouseMat": "brushNeighbourhood", "mousemove .clipg": "brushNeighbourhood", "mouseleave .viewport": "cancelHighlights", "mouseleave .clipg": "cancelHighlights", "input .dragPanRB": "setMatrixDragMode", }); }, defaultOptions: { xlabel: "Residue Index 1", ylabel: "Residue Index 2", chartTitle: "Cross-Link Matrix", chainBackground: "white", matrixObj: null, selectedColour: "#ff0", highlightedColour: "#f80", linkWidth: 5, tooltipRange: 7, matrixDragMode: "Pan", margin: { top: 30, right: 20, bottom: 40, left: 60 }, exportKey: true, exportTitle: true, canHideToolbarArea: true, canTakeImage: true, }, initialize: function (viewOptions) { DistanceMatrixViewBB.__super__.initialize.apply(this, arguments); const self = this; const marginLimits = { top: this.options.chartTitle ? 30 : undefined, bottom: this.options.xlabel ? 40 : undefined, left: this.options.ylabel ? 60 : undefined }; $.extend(this.options.margin, marginLimits); this.colourScaleModel = viewOptions.colourScaleModel; // targetDiv could be div itself or id of div - lets deal with that // Backbone handles the above problem now - element is now found in this.el //avoids prob with 'save - web page complete' const mainDivSel = d3.select(this.el).classed("matrixView", true); const flexWrapperPanel = mainDivSel.append("div") .attr("class", "verticalFlexContainer"); this.controlDiv = flexWrapperPanel.append("div").attr("class", "toolbar toolbarArea"); this.controlDiv.append("button") .attr("class", "downloadButton btn btn-1 btn-1a") .text(commonLabels.downloadImg + "SVG"); const buttonHolder = this.controlDiv.append("span").attr("class", "noBreak reducePadding"); // Radio Button group to decide pan or select const toggleButtonData = [{ class: "dragPanRB", label: "Drag to Pan", id: "dragPan", tooltip: "Left-click and drag pans the matrix. Mouse-wheel zooms.", group: "matrixDragMode", value: "Pan" }, { class: "dragPanRB", label: "Or Select", id: "dragSelect", tooltip: "Left-click and drag selects an area in the matrix", group: "matrixDragMode", value: "Select" }, ]; toggleButtonData .forEach(function (d) { $.extend(d, { type: "radio", inputFirst: false, value: d.value || d.label }); if (d.initialState === undefined && d.group && d.value) { // set initial values for radio button groups d.initialState = (d.value === this.options[d.group]); } }, this); makeBackboneButtons(buttonHolder, self.el.id, toggleButtonData); const setSelectTitleString = function () { const selElem = d3.select(d3.event.target); selElem.attr("title", selElem.selectAll("option") .filter(function () { return d3.select(this).property("selected"); }) .text() ); }; this.controlDiv.append("label") .attr("class", "btn selectHolder") .append("span") //.attr("class", "noBreak") .text("Show Protein Pairing ►") .append("select") .attr("id", mainDivSel.attr("id") + "chainSelect") .on("change", function () { // const value = this.value; const selectedDatum = d3.select(this).selectAll("option") .filter(function () { return d3.select(this).property("selected"); }) .datum(); self.setAndShowPairing(selectedDatum.value); const selElem = d3.select(d3.event.target); setSelectTitleString(selElem); }); const chartDiv = flexWrapperPanel.append("div") .attr("class", "panelInner") .attr("flex-grow", 1) .style("position", "relative"); const viewDiv = chartDiv.append("div") .attr("class", "viewDiv"); // Scales this.x = d3.scale.linear(); this.y = d3.scale.linear(); this.zoomStatus = d3.behavior.zoom() .scaleExtent([1, 8]) .on("zoom", function () { self.zoomHandler(self); }); // Canvas viewport and element const canvasViewport = viewDiv.append("div") .attr("class", "viewport") .style("top", this.options.margin.top + "px") .style("left", this.options.margin.left + "px") .call(self.zoomStatus); this.canvas = canvasViewport .append("canvas") .attr("class", "toSvgImage") .style("background", this.options.background) // override standard background colour with option .style("display", "none"); canvasViewport.append("div") .attr("class", "mouseMat"); // SVG element this.svg = viewDiv.append("svg"); // Defs this.svg.append("defs") .append("clipPath") .attr("id", "matrixClip") .append("rect") .attr("x", 0) .attr("y", 0) .attr("width", 0) .attr("height", 0); this.vis = this.svg.append("g") .attr("transform", "translate(" + this.options.margin.left + "," + this.options.margin.top + ")"); this.brush = d3.svg.brush() .x(self.x) .y(self.y) //.clamp ([false, false]) .on("brush", function () { }) .on("brushend", function () { self.selectNeighbourhood(self.brush.extent()); }); // Add clippable and pan/zoomable viewport made of two group elements this.clipGroup = this.vis.append("g") .attr("class", "clipg") .attr("clip-path", "url(#matrixClip)"); this.clipGroup.append("rect").attr("width", "100%").attr("height", "100%").style("fill", "#e4e4e4"); this.zoomGroup = this.clipGroup.append("g"); this.zoomGroup.append("g").attr("class", "blockAreas"); this.zoomGroup.append("g").attr("class", "backgroundImage").append("image"); this.zoomGroup.append("g").attr("class", "crosslinkPlot"); this.zoomGroup.append("g") .attr("class", "brush") .call(self.brush); // Axes setup this.xAxis = d3.svg.axis().scale(this.x).orient("bottom"); this.yAxis = d3.svg.axis().scale(this.y).orient("left"); this.vis.append("g").attr("class", "y axis"); this.vis.append("g").attr("class", "x axis"); // Add labels const labelInfo = [{ class: "axis", text: this.options.xlabel, dy: "0em" }, { class: "axis", text: this.options.ylabel, dy: "1em" }, { class: "matrixHeader", text: this.options.chartTitle, dy: "-0.5em" }, ]; this.vis.selectAll("g.label") .data(labelInfo) .enter() .append("g") .attr("class", "label") .append("text") .attr("class", function (d) { return d.class; }) .text(function (d) { return d.text; }) .attr("dy", function (d) { return d.dy; }); // rerender crosslinks if selection/highlight changed, filteringDone or colourmodel changed this.listenTo(this.model, "change:selection filteringDone", this.renderCrossLinks); this.listenTo(this.model, "currentColourModelChanged", function (colourModel, domain) { if (colourModel.get("id") !== this.colourScaleModel.get("id")) { // todo - test if model is distances, if so rendering is already guaranteed this.renderCrossLinks(); } }); this.listenTo(this.model, "change:highlights", function () { this.renderCrossLinks({rehighlightOnly: true}); }); this.listenTo(this.model, "change:linkColourAssignment", this.render); this.listenTo(this.model, "change:selectedProteins", this.makeProteinPairingOptions); this.listenTo(this.colourScaleModel, "colourModelChanged", function () { this.render({noResize: true}); }); // colourScaleModel is pointer to distance colour model, so this triggers even if not current colour model (redraws background) this.listenTo(this.model.get("clmsModel"), "change:distancesObj", this.distancesChanged); // Entire new set of distances this.listenTo(this.model.get("clmsModel"), "change:matches", this.matchesChanged); // New matches added (via csv generally) this.listenTo(window.vent, "proteinMetadataUpdated", function () { this.makeProteinPairingOptions(); this.updateAxisLabels(); }); this.listenTo(window.vent, "PDBPermittedChainSetsUpdated changeAllowInterModelDistances", this.distancesChanged); // New PDB or existing residues/pdb but distances changed const entries = this.makeProteinPairingOptions(); const startPairing = _.isEmpty(entries) ? undefined : entries[0].value; this.setAndShowPairing(startPairing); this.setMatrixDragMode({ target: { value: this.options.matrixDragMode } }); }, relayout: function () { this.resize(); return this; }, setAndShowPairing: function (pairing) { this .matrixChosen(pairing) .resetZoomHandler(this) .render(); }, makeProteinPairingOptions: function () { const crosslinks = this.model.getAllTTCrossLinks(); const totals = crosslinkCountPerProteinPairing(crosslinks); const entries = d3.entries(totals); let nonEmptyEntries = entries.filter(function (entry) { return entry.value.crosslinks.length; }); // If there are selected proteins, reduce the choice to pairs within this set const selectedProteins = this.model.get("selectedProteins"); if (selectedProteins.length) { const selectedProteinSet = d3.set(_.pluck(selectedProteins, "id")); nonEmptyEntries = nonEmptyEntries.filter(function (entry) { const value = entry.value; return selectedProteinSet.has(value.fromProtein.id) && selectedProteinSet.has(value.toProtein.id); }); } nonEmptyEntries.sort(function (a, b) { return b.value.crosslinks.length - a.value.crosslinks.length; }); const mainDivSel = d3.select(this.el); const matrixOptions = mainDivSel.select("#" + mainDivSel.attr("id") + "chainSelect") .selectAll("option") .data(nonEmptyEntries, function (d) { return d.key; }); matrixOptions.exit().remove(); matrixOptions .enter() .append("option"); matrixOptions .order() .property("value", function (d) { return d.key; }) .text(function (d) { return "[" + d.value.crosslinks.length + "] " + d.value.label; }); return nonEmptyEntries.length ? nonEmptyEntries : entries; }, getCurrentPairing: function (pairing, onlyIfNoneSelected) { const mainDivSel = d3.select(this.el); const selected = mainDivSel.select("#" + mainDivSel.attr("id") + "chainSelect") .selectAll("option") .filter(function () { return d3.select(this).property("selected"); }); return (selected.size() === 0 && onlyIfNoneSelected) ? pairing : selected.datum().value; }, matchesChanged: function () { const entries = this.makeProteinPairingOptions(); const pairing = this.getCurrentPairing(entries[0], true); this.matrixChosen(pairing); this.render(); return this; }, // Either new PDB File in town, or change to existing distances distancesChanged: function () { this.render(); return this; }, updateAxisLabels: function () { const protIDs = this.getCurrentProteinIDs(); this.vis.selectAll("g.label text").data(protIDs) .text(function (d) { return d.labelText; }); }, matrixChosen: function (proteinPairValue) { if (proteinPairValue) { this.options.matrixObj = proteinPairValue; const seqLengths = this.getSeqLengthData(); this.x.domain([1, seqLengths.lengthA + 1]); this.y.domain([seqLengths.lengthB + 1, 1]); // Update x/y labels and axes tick formats this.xAxis.tickFormat(this.alignedIndexAxisFormat); this.yAxis.tickFormat(this.alignedIndexAxisFormat); this.updateAxisLabels(); } return this; }, // chain may show if checked in dropdown and if allowed by chainset in distancesobj (i.e. not cutoff by assembly choice) chainMayShow: function (dropdownIndex, chainIndex) { const distanceObj = this.model.get("clmsModel").get("distancesObj"); const allowedChains = distanceObj ? distanceObj.permittedChainIndicesSet : null; return allowedChains ? allowedChains.has(chainIndex) : true; }, alignedIndexAxisFormat: function (searchIndex) { return d3.format(",.0f")(searchIndex); }, getCurrentProteinIDs: function () { const mObj = this.options.matrixObj; return mObj ? [{ chainIDs: null, proteinID: mObj.fromProtein.id, labelText: mObj.fromProtein.name.replace("_", " ") }, { chainIDs: null, proteinID: mObj.toProtein.id, labelText: mObj.toProtein.name.replace("_", " ") } ] : [null, null]; }, getChainsForProtein: function (proteinID) { return this.model.get("clmsModel").get("distancesObj").chainMap[proteinID]; }, addAlignIDs: function (proteinIDsObj) { const distancesObj = this.model.get("clmsModel").get("distancesObj"); proteinIDsObj.forEach(function (pid) { pid.alignID = null; if (pid.proteinID) { const chainName = getChainNameFromChainIndex(distancesObj.chainMap, pid.chainID); pid.alignID = make3DAlignID(distancesObj.structureName, chainName, pid.chainID); } }, this); return proteinIDsObj; }, getOverallScale: function (sizeData) { const sd = sizeData || this.getSizeData(); const baseScale = Math.min(sd.width / sd.lengthA, sd.height / sd.lengthB); return baseScale * this.zoomStatus.scale(); }, // Tooltip functions convertEvtToXY: function (evt) { const sd = this.getSizeData(); // *****!$$$ finally, cross-browser const elem = d3.select(this.el).select(".viewport"); let px = evt.pageX - $(elem.node()).offset().left; let py = evt.pageY - $(elem.node()).offset().top; //console.log ("p", evt, px, py, evt.target, evt.originalEvent.offsetX); const t = this.zoomStatus.translate(); const scale = this.getOverallScale(sd); //console.log ("XXXY", this.zoomStatus.scale(), baseScale, scale, t); px -= t[0]; // translate py -= t[1]; //console.log ("p2", px, py); px /= scale; // scale py /= scale; //console.log ("p3", px, py); px++; // +1 cos crosslinks are 1-indexed py = (sd.lengthB - 1) - py; // flip because y is bigger at top //console.log ("p4", px, py); return [Math.round(px), Math.round(py)]; }, grabNeighbourhoodLinks: function (extent) { const filteredCrossLinks = this.model.getFilteredCrossLinks(); const filteredCrossLinkMap = d3.map(filteredCrossLinks, function (d) { return d.id; }); const proteinIDs = this.getCurrentProteinIDs(); const convFunc = function (x, y) { // x and y are 0-indexed return { convX: x, convY: y, proteinX: proteinIDs[0] ? proteinIDs[0].proteinID : undefined, proteinY: proteinIDs[1] ? proteinIDs[1].proteinID : undefined, }; }; const neighbourhoodLinks = findResiduesInSquare(convFunc, filteredCrossLinkMap, extent[0][0], extent[0][1], extent[1][0], extent[1][1], true); return neighbourhoodLinks; }, selectNeighbourhood: function (extent) { const add = d3.event.ctrlKey || d3.event.shiftKey; // should this be added to current selection? const linkWrappers = this.grabNeighbourhoodLinks(extent); const crosslinks = _.pluck(linkWrappers, "crosslink"); this.model.setMarkedCrossLinks("selection", crosslinks, false, add); }, // Brush neighbourhood and invoke tooltip brushNeighbourhood: function (evt) { const xy = this.convertEvtToXY(evt); const halfRange = this.options.tooltipRange / 2; const highlightExtent = d3.transpose(xy.map(function (xory) { return [xory - halfRange, xory + halfRange]; })); // turn xy into extent equivalent const linkWrappers = this.grabNeighbourhoodLinks(highlightExtent); const crosslinks = _.pluck(linkWrappers, "crosslink"); // invoke tooltip before setting highlights model change for quicker tooltip response this.invokeTooltip(evt, linkWrappers); this.model.setMarkedCrossLinks("highlights", crosslinks, true, false); }, cancelHighlights: function () { this.model.setMarkedCrossLinks("highlights", [], true, false); }, setMatrixDragMode: function (evt) { this.options.matrixDragMode = evt.target.value; const top = d3.select(this.el); if (this.options.matrixDragMode === "Pan") { top.select(".viewport").call(this.zoomStatus); top.selectAll(".clipg .brush rect").style("pointer-events", "none"); } else { top.select(".viewport").on(".zoom", null); top.selectAll(".clipg .brush rect").style("pointer-events", null); } return this; }, invokeTooltip: function (evt, linkWrappers) { if (this.options.matrixObj) { const crosslinks = _.pluck(linkWrappers, "crosslink"); crosslinks.sort(function (a, b) { return a.getMeta("distance") - b.getMeta("distance"); }); const linkDistances = crosslinks.map(function (crosslink) { return crosslink.getMeta("distance"); }); this.model.get("tooltipModel") .set("header", makeTooltipTitle.linkList(crosslinks.length)) .set("contents", makeTooltipContents.linkList(crosslinks, {"Distance": linkDistances})) .set("location", evt); //this.trigger("change:location", this.model, evt); // necessary to change position 'cos d3 event is a global property, it won't register as a change } }, // end of tooltip functions zoomHandler: function (self) { const sizeData = this.getSizeData(); const width = sizeData.width; const height = sizeData.height; // bounded zoom behavior adapted from https://gist.github.com/shawnbot/6518285 // (d3 events translate and scale values are just copied from zoomStatus) const widthRatio = width / sizeData.lengthA; const heightRatio = height / sizeData.lengthB; const minRatio = Math.min(widthRatio, heightRatio); const fx = sizeData.lengthA * minRatio; const fy = sizeData.lengthB * minRatio; const tx = Math.min(0, Math.max(d3.event.translate[0], fx - (fx * d3.event.scale))); const ty = Math.min(0, Math.max(d3.event.translate[1], fy - (fy * d3.event.scale))); //console.log ("tx", tx, ty, fx, fy, width, height); self.zoomStatus.translate([tx, ty]); self.panZoom(); }, resetZoomHandler: function (self) { self.zoomStatus.scale(1.0).translate([0, 0]); return this; }, // That's how you define the value of a pixel // // http://stackoverflow.com/questions/7812514/drawing-a-dot-on-html5-canvas // moved from out of render() as firefox in strict mode objected drawPixel: function (cd, pixi, r, g, b, a) { const index = pixi * 4; cd[index] = r; cd[index + 1] = g; cd[index + 2] = b; cd[index + 3] = a; }, render: function (renderOptions) { renderOptions = renderOptions || {}; if (this.options.matrixObj && this.isVisible()) { if (!renderOptions.noResize) { this.resize(); } this .renderBackgroundMap() .renderCrossLinks({ isVisible: true }); } return this; }, // draw white blocks in background to demarcate areas covered by active pdb chains renderChainBlocks: function (alignInfo) { const seqLengths = this.getSeqLengthData(); const seqLengthB = seqLengths.lengthB - 1; // Find continuous blocks for each chain when mapped to search sequence (as chain sequence may have gaps in) (called in next bit of code) const blockMap = {}; d3.merge(alignInfo).forEach(function (alignDatum) { blockMap[alignDatum.alignID] = this.model.get("alignColl").get(alignDatum.proteinID).blockify(alignDatum.alignID); }, this); //console.log ("blockMap", blockMap); // Draw backgrounds for each pairing of chains const blockAreas = this.zoomGroup.select(".blockAreas"); const blockSel = blockAreas.selectAll(".chainArea"); blockSel.remove(); //console.log ("BLOX", blockMap); const allowInterModel = this.model.get("stageModel").get("allowInterModelDistances"); alignInfo[0].forEach(function (alignInfo1) { const blocks1 = blockMap[alignInfo1.alignID]; alignInfo[1].forEach(function (alignInfo2) { if ((alignInfo1.modelID === alignInfo2.modelID) || allowInterModel) { const blocks2 = blockMap[alignInfo2.alignID]; blocks1.forEach(function (brange1) { blocks2.forEach(function (brange2) { blockAreas.append("rect") .attr("x", brange1.begin - 1) .attr("y", seqLengthB - (brange2.end - 1)) .attr("width", brange1.end - brange1.begin + 1) .attr("height", brange2.end - brange2.begin + 1) .attr("class", "chainArea") .style("fill", this.options.chainBackground); }, this); }, this); } }, this); }, this); }, renderBackgroundMap: function () { let z = performance.now(); const distancesObj = this.model.get("clmsModel").get("distancesObj"); const stageModel = this.model.get("stageModel"); // only render background if distances available if (distancesObj) { // Get alignment info for chains in the two proteins, filtering to chains that are marked as showable const proteinIDs = this.getCurrentProteinIDs(); const alignInfo = proteinIDs.map(function (proteinID, i) { const pid = proteinID.proteinID; const chains = distancesObj.chainMap[pid]; if (chains) { const chainIDs = chains .filter(function (chain) { return this.chainMayShow(i, chain.index); }, this) .map(function (chain) { return { proteinID: pid, chainID: chain.index, modelID: chain.modelIndex, }; }); return this.addAlignIDs(chainIDs); } return []; }, this); //console.log ("ALLL", alignInfo); // draw the areas covered by pdb chain data this.renderChainBlocks(alignInfo); const seqLengths = this.getSeqLengthData(); // Don't draw backgrounds for huge protein combinations (5,000,000 =~ 2250 x 2250 is limit), begins to be memory issue if (seqLengths.lengthA * seqLengths.lengthB > 5e6) { // shrink canvas / hide image if not showing it this.canvas .attr("width", 1) .attr("height", 1); this.zoomGroup.select(".backgroundImage").select("image").style("display", "none"); } else { this.canvas .attr("width", seqLengths.lengthA) .attr("height", seqLengths.lengthB); const canvasNode = this.canvas.node(); const ctx = canvasNode.getContext("2d"); //ctx.fillStyle = "rgba(255, 0, 0, 0)"; ctx.clearRect(0, 0, canvasNode.width, canvasNode.height); const rangeDomain = this.colourScaleModel.get("colScale").domain(); const min = rangeDomain[0]; const max = rangeDomain[1]; const rangeColours = this.colourScaleModel.get("colScale").range(); const cols = rangeColours; //.slice (1,3); // have slightly different saturation/luminance for each colour so shows up in black & white const colourArray = cols.map(function (col, i) { col = d3.hsl(col); col.s = 0.4; // - (0.1 * i); col.l = 0.85; // - (0.1 * i); const col2 = col.rgb(); return (255 << 24) + (col2.b << 16) + (col2.g << 8) + col2.r; // 32-bit value of colour }); const seqLengthB = seqLengths.lengthB - 1; // let times = window.times || []; // const start = performance.now(); // function to draw one matrix according to a pairing of two chains (called in loop later) const drawDistanceMatrix = function (imgDataArr, minArray, matrixValue, alignInfo1, alignInfo2) { const alignColl = this.model.get("alignColl"); const distanceMatrix = matrixValue.distanceMatrix; const pw = this.canvas.attr("width"); const atoms1 = stageModel.getAllResidueCoordsForChain(matrixValue.chain1); const atoms2 = (matrixValue.chain1 !== matrixValue.chain2) ? stageModel.getAllResidueCoordsForChain(matrixValue.chain2) : atoms1; // precalc some stuff that would get recalculatd a lot in the inner loop const preCalcSearchIndices = d3.range(atoms2.length).map(function (seqIndex) { return alignColl.getAlignedIndex(seqIndex + 1, alignInfo2.proteinID, true, alignInfo2.alignID, true) - 1; }); const preCalcRowIndices = preCalcSearchIndices.map(function (i) { return i >= 0 ? (seqLengthB - i) * pw : -1; }); //console.log ("pcsi", preCalcSearchIndices); //console.log ("atoms", atoms1, atoms2); // draw chain values, aligned to search sequence const max2 = max * max; const min2 = min * min; //var p = performance.now(); const len = atoms2.length; for (let i = 0; i < atoms1.length; i++) { const searchIndex1 = alignColl.getAlignedIndex(i + 1, alignInfo1.proteinID, true, alignInfo1.alignID, true) - 1; if (searchIndex1 >= 0) { const row = distanceMatrix[i]; for (let j = 0; j < len; j++) { // was seqLength const distance2 = row && row[j] ? row[j] * row[j] : getDistanceSquared(atoms1[i], atoms2[j]); if (distance2 < max2) { const searchIndex2 = preCalcRowIndices[j]; if (searchIndex2 >= 0) { const aindex = searchIndex1 + searchIndex2; //((seqLengthB - searchIndex2) * pw); const val = minArray ? minArray[aindex] : 0; const r = distance2 > min2 ? 1 : 2; if (r > val) { imgDataArr[aindex] = colourArray[2 - r]; // 32-bit array view can take colour directly if (minArray) { minArray[aindex] = r;//val; } } } } } } } //p = performance.now() - p; //console.log (atoms1.length * atoms2.length, "coordinates drawn to canvas in ", p, " ms."); }; // const middle = performance.now(); const canvasData = ctx.getImageData(0, 0, this.canvas.attr("width"), this.canvas.attr("height")); const cd = new Uint32Array(canvasData.data.buffer); // canvasData.data // 32-bit view of buffer let minArray = (alignInfo[0].length * alignInfo[1].length) > 1 ? new Uint8Array(this.canvas.attr("width") * this.canvas.attr("height")) : undefined; // draw actual content of chain pairings alignInfo[0].forEach(function (alignInfo1) { const chainIndex1 = alignInfo1.chainID; alignInfo[1].forEach(function (alignInfo2) { const chainIndex2 = alignInfo2.chainID; const distanceMatrixValue = distancesObj.matrices[chainIndex1 + "-" + chainIndex2]; drawDistanceMatrix.call(this, cd, minArray, distanceMatrixValue, alignInfo1, alignInfo2); }, this); }, this); ctx.putImageData(canvasData, 0, 0); // const end = performance.now(); // window.times.push(Math.round(end - middle)); //console.log ("window.times", window.times); this.zoomGroup.select(".backgroundImage").select("image") .style("display", null) // default value .attr("width", this.canvas.attr("width")) .attr("height", this.canvas.attr("height")) .attr("xlink:href", canvasNode.toDataURL("image/png")); } } z = performance.now() - z; console.log("render background map", z, "ms"); return this; }, renderCrossLinks: function (renderOptions) { renderOptions = renderOptions || {}; //console.log ("renderCrossLinks", renderOptions); if (renderOptions.isVisible || (this.options.matrixObj && this.isVisible())) { const self = this; if (this.options.matrixObj) { const highlightOnly = renderOptions.rehighlightOnly; const colourScheme = this.model.get("linkColourAssignment"); const seqLengths = this.getSeqLengthData(); const seqLengthB = seqLengths.lengthB - 1; const xStep = 1; //minDim / seqLengthA; const yStep = 1; //minDim / seqLengthB; let linkWidth = this.options.linkWidth / 2; const overallScale = this.getOverallScale(); if (overallScale < 1 && overallScale > 0) { linkWidth /= overallScale; linkWidth = Math.ceil(linkWidth); } //console.log ("os", overallScale); const xLinkWidth = linkWidth * xStep; // const yLinkWidth = linkWidth * yStep; const proteinIDs = this.getCurrentProteinIDs(); const filteredCrossLinks = this.model.getFilteredCrossLinks(); //.values(); const selectedCrossLinkIDs = d3.set(_.pluck(this.model.getMarkedCrossLinks("selection"), "id")); const highlightedCrossLinkIDs = d3.set(_.pluck(this.model.getMarkedCrossLinks("highlights"), "id")); const finalCrossLinks = Array.from(filteredCrossLinks).filter(function (crosslink) { return (crosslink.toProtein.id === proteinIDs[0].proteinID && crosslink.fromProtein.id === proteinIDs[1].proteinID) || (crosslink.toProtein.id === proteinIDs[1].proteinID && crosslink.fromProtein.id === proteinIDs[0].proteinID); }, this); // sort so that selected links appear on top let sortedFinalCrossLinks; if (highlightOnly) { sortedFinalCrossLinks = finalCrossLinks.filter(function (link) { return highlightedCrossLinkIDs.has(link.id); }); } else { sortedFinalCrossLinks = radixSort(3, finalCrossLinks, function (link) { return highlightedCrossLinkIDs.has(link.id) ? 2 : (selectedCrossLinkIDs.has(link.id) ? 1 : 0); }); } const fromToStore = sortedFinalCrossLinks.map(function (crosslink) { return [crosslink.fromResidue - 1, crosslink.toResidue - 1]; }); const indLinkPlot = function (d) { const high = highlightedCrossLinkIDs.has(d.id); const selected = high ? false : selectedCrossLinkIDs.has(d.id); const ambig = d.ambiguous; d3.select(this) .attr("class", "crosslink" + (high ? " high" : "")) .style("fill-opacity", ambig ? 0.6 : null) .style("fill", high ? self.options.highlightedColour : (selected ? self.options.selectedColour : colourScheme.getColour(d))) .style("stroke-dasharray", ambig ? 3 : null) .style("stroke", high || selected ? "black" : (ambig ? colourScheme.getColour(d) : null)); //.style ("stroke-opacity", high || selected ? 0.4 : null) }; // if redoing highlights only, find previously highlighted links not part of current set and restore them // to a non-highlighted state if (highlightOnly) { const oldHighLinkSel = this.zoomGroup.select(".crosslinkPlot").selectAll(".high") .filter(function (d) { return !highlightedCrossLinkIDs.has(d.id); }) .each(indLinkPlot); } const linkSel = this.zoomGroup.select(".crosslinkPlot").selectAll(".crosslink") .data(sortedFinalCrossLinks, function (d) { return d.id; }) // Equivalent of d3 v4 selection.raise - https://github.com/d3/d3-selection/blob/master/README.md#selection_raise .each(function () { this.parentNode.appendChild(this); }); //.order() if (!highlightOnly) { linkSel.exit().remove(); linkSel.enter().append("circle") // replacing rect .attr("class", "crosslink") .attr("r", xLinkWidth); //.attr("width", xLinkWidth) //.attr("height", yLinkWidth) } //var linkWidthOffset = (linkWidth - 1) / 2; // for rects linkSel .attr("cx", function (d, i) { // cx/cy for circle, x/y for rect return fromToStore[i][0];// - linkWidthOffset; }) .attr("cy", function (d, i) { return (seqLengthB - fromToStore[i][1]);// - linkWidthOffset; }) .each(indLinkPlot); } } return this; }, getSizeData: function () { // Firefox returns 0 for an svg element's clientWidth/Height, so use zepto/jquery width function instead const jqElem = $(this.svg.node()); const cx = jqElem.width(); //this.svg.node().clientWidth; const cy = jqElem.height(); //this.svg.node().clientHeight; const width = Math.max(0, cx - this.options.margin.left - this.options.margin.right); const height = Math.max(0, cy - this.options.margin.top - this.options.margin.bottom); //its going to be square and fit in containing div const minDim = Math.min(width, height); const sizeData = this.getSeqLengthData(); $.extend(sizeData, { cx: cx, cy: cy, width: width, height: height, minDim: minDim, }); return sizeData; }, getSeqLengthData: function () { const mObj = this.options.matrixObj; const size = mObj ? [mObj.fromProtein.size, mObj.toProtein.size] : [0, 0]; return { lengthA: size[0], lengthB: size[1] }; }, // called when things need repositioned, but not re-rendered from data resize: function () { console.log("matrix resize"); const sizeData = this.getSizeData(); const minDim = sizeData.minDim; // fix viewport new size, previously used .attr, but then setting the size on the child canvas element expanded it, some style trumps attr thing //var widthRatio = minDim / sizeData.lengthA; //var heightRatio = minDim / sizeData.lengthB; const widthRatio = sizeData.width / sizeData.lengthA; const heightRatio = sizeData.height / sizeData.lengthB; const minRatio = Math.min(widthRatio, heightRatio); // const diffRatio = widthRatio / heightRatio; const viewPort = d3.select(this.el).select(".viewport"); const fx = sizeData.lengthA * minRatio; const fy = sizeData.lengthB * minRatio; //console.log (sizeData, "rr", widthRatio, heightRatio, minRatio, diffRatio, "FXY", fx, fy); viewPort .style("width", fx + "px") .style("height", fy + "px"); d3.select(this.el).select("#matrixClip > rect") .attr("width", fx) .attr("height", fy); // Need to rejig x/y scales and d3 translate coordinates if resizing // set x/y scales to full domains and current size (range) this.x .domain([1, sizeData.lengthA + 1]) .range([0, fx]); // y-scale (inverted domain) this.y .domain([sizeData.lengthB + 1, 1]) .range([0, fy]); // update brush this.brush .x(this.x.copy().range(this.x.domain().slice())) .y(this.y.copy().range(this.y.domain().slice().reverse())); this.zoomGroup.select(".brush").call(this.brush); //console.log ("BRUSH", this.brush); // make sure brush rectangle is big enough to cover viewport (accommodate for scaling) this.zoomGroup.select(".brush rect.background") .attr("width", sizeData.lengthA) .attr("height", sizeData.lengthB); //var approxTicks = Math.round (minDim / 50); // 50px minimum spacing between ticks this.xAxis.ticks(Math.round(fx / 50)).outerTickSize(0); this.yAxis.ticks(Math.round(fy / 50)).outerTickSize(0); // then store the current pan/zoom values const curt = this.zoomStatus.translate(); const curs = this.zoomStatus.scale(); // reset reference x and y scales in zoomStatus object to be x and y scales above this.zoomStatus.x(this.x).y(this.y); // modify translate coordinates by change (delta) in display size const deltaz = this.last ? (minDim / this.last) : 1; //console.log ("deltaz", deltaz); this.last = minDim; curt[0] *= deltaz; curt[1] *= deltaz; // feed current pan/zoom values back into zoomStatus object // (as setting .x and .y above resets them inside zoomStatus) // this adjusts domains of x and y scales this.zoomStatus.scale(curs).translate(curt); // Basically the point is to readjust the axes when the display space is resized, but preserving their current zoom/pan settings // separately from the scaling due to the resizing // pan/zoom canvas this.panZoom(); return this; }, // Used to do this just on resize, but rectangular areas mean labels often need re-centred on panning repositionLabels: function (sizeData) { // reposition labels //console.log ("SD", sizeData, this.options.margin); const labelCoords = [{ x: sizeData.right / 2, y: sizeData.bottom + this.options.margin.bottom - 5, rot: 0 }, { x: -this.options.margin.left, y: sizeData.bottom / 2, rot: -90 }, { x: sizeData.right / 2, y: 0, rot: 0 } ]; this.vis.selectAll("g.label text") .data(labelCoords) .attr("transform", function (d) { return "translate(" + d.x + " " + d.y + ") rotate(" + d.rot + ")"; }); return this; }, // called when panning and zooming performed panZoom: function () { const self = this; const sizeData = this.getSizeData(); // rescale and position canvas according to pan/zoom settings and available space const scale = this.getOverallScale(sizeData); const scaleString = "scale(" + scale + ")"; const translateString = "translate(" + this.zoomStatus.translate()[0] + "px," + this.zoomStatus.translate()[1] + "px)"; const translateStringAttr = "translate(" + this.zoomStatus.translate()[0] + "," + this.zoomStatus.translate()[1] + ")"; const transformStrings = { attr: translateStringAttr + " " + scaleString, style: translateString + " " + scaleString }; // for some reason using a css transform style on an svg group doesn't play nice in firefox (i.e. wrong positions reported, offsetx/y mangled etc) // , so use attr transform instead [ /*{elem: d3.select(this.el).select(".mouseMat"), type: "style"},*/ { elem: this.zoomGroup, type: "attr" }].forEach(function (d3sel) { if (d3sel.type === "attr") { d3sel.elem.attr("transform", transformStrings[d3sel.type]); } else { const tString = transformStrings[d3sel.type]; ["-ms-transform", "-moz-transform", "-o-transform", "-webkit-transform", "transform"].forEach(function (styleName) { d3sel.elem.style(styleName, tString); }); } }); // If bottom edge of canvas is higher up than bottom of viewport put the x axis beneath it const cvs = $(this.canvas.node()); const viewport = cvs.parent(); sizeData.viewHeight = $.zepto ? viewport.height() : viewport.outerHeight(true); sizeData.viewWidth = $.zepto ? viewport.width() : viewport.outerWidth(true); const bottom = sizeData.viewHeight; /*Math.min ( cvs.position().top + (($.zepto ? cvs.height() : cvs.outerHeight(true)) * scale), sizeData.viewHeight ); */ const right = sizeData.viewWidth; /*Math.min ( cvs.position().left + (($.zepto ? cvs.width() : cvs.outerWidth(true)) * scale), sizeData.viewWidth );*/ // redraw axes this.vis.select(".y") .call(self.yAxis); this.vis.select(".x") .attr("transform", "translate(0," + bottom + ")") .call(self.xAxis); declutterAxis(this.vis.select(".x")); sizeData.bottom = bottom; sizeData.right = right; this.repositionLabels(sizeData); //console.log ("sizeData", sizeData); return this; }, identifier: "Matrix View", optionsToString: function () { const matrixObj = this.options.matrixObj; return [matrixObj.fromProtein, matrixObj.toProtein] .map(function (protein) { return protein.name.replace("_", " "); }) .join("-"); }, });
Rappsilber-Laboratory/CLMS-UI
js/views/matrixViewBB.js
JavaScript
gpl-2.0
47,172
import { expect } from 'chai'; import deepFreeze from 'deep-freeze'; import { DOMAINS_SUGGESTIONS_RECEIVE, DOMAINS_SUGGESTIONS_REQUEST, DOMAINS_SUGGESTIONS_REQUEST_FAILURE, DOMAINS_SUGGESTIONS_REQUEST_SUCCESS, } from 'calypso/state/action-types'; import { serialize, deserialize } from 'calypso/state/utils'; import { useSandbox } from 'calypso/test-helpers/use-sinon'; import reducer, { items, requesting, errors } from '../reducer'; describe( 'reducer', () => { let sandbox; useSandbox( ( newSandbox ) => { sandbox = newSandbox; sandbox.stub( console, 'warn' ); } ); test( 'should export expected reducer keys', () => { expect( reducer( undefined, {} ) ).to.have.keys( [ 'items', 'requesting', 'errors' ] ); } ); describe( '#items()', () => { test( 'should default to an empty object', () => { const state = items( undefined, {} ); expect( state ).to.eql( {} ); } ); test( 'should index suggestions by serialized query', () => { const queryObject = { query: 'example', quantity: 2, vendor: 'domainsbot', include_wordpressdotcom: false, }; const suggestions = [ { domain_name: 'example.me', cost: '$25.00', product_id: 46, product_slug: 'dotme_domain' }, { domain_name: 'example.org', cost: '$18.00', product_id: 6, product_slug: 'domain_reg' }, ]; const state = items( undefined, { type: DOMAINS_SUGGESTIONS_RECEIVE, queryObject, suggestions, } ); expect( state ).to.eql( { '{"query":"example","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': [ { domain_name: 'example.me', cost: '$25.00', product_id: 46, product_slug: 'dotme_domain', }, { domain_name: 'example.org', cost: '$18.00', product_id: 6, product_slug: 'domain_reg' }, ], } ); } ); test( 'should accumulate domain suggestions', () => { const original = deepFreeze( { '{"query":"example","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': [ { domain_name: 'example.me', cost: '$25.00', product_id: 46, product_slug: 'dotme_domain', }, { domain_name: 'example.org', cost: '$18.00', product_id: 6, product_slug: 'domain_reg' }, ], } ); const queryObject = { query: 'foobar', quantity: 2, vendor: 'domainsbot', include_wordpressdotcom: false, }; const suggestions = [ { domain_name: 'foobar.me', cost: '$25.00', product_id: 46, product_slug: 'dotme_domain' }, { domain_name: 'foobar.org', cost: '$18.00', product_id: 6, product_slug: 'domain_reg' }, ]; const state = items( original, { type: DOMAINS_SUGGESTIONS_RECEIVE, queryObject, suggestions, } ); expect( state ).to.eql( { '{"query":"example","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': [ { domain_name: 'example.me', cost: '$25.00', product_id: 46, product_slug: 'dotme_domain', }, { domain_name: 'example.org', cost: '$18.00', product_id: 6, product_slug: 'domain_reg' }, ], '{"query":"foobar","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': [ { domain_name: 'foobar.me', cost: '$25.00', product_id: 46, product_slug: 'dotme_domain', }, { domain_name: 'foobar.org', cost: '$18.00', product_id: 6, product_slug: 'domain_reg' }, ], } ); } ); test( 'should override previous domains suggestions', () => { const original = deepFreeze( { '{"query":"example","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': [ { domain_name: 'example.me', cost: '$25.00', product_id: 46, product_slug: 'dotme_domain', }, { domain_name: 'example.org', cost: '$18.00', product_id: 6, product_slug: 'domain_reg' }, ], '{"query":"foobar","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': [ { domain_name: 'foobar.me', cost: '$25.00', product_id: 46, product_slug: 'dotme_domain', }, { domain_name: 'foobar.org', cost: '$18.00', product_id: 6, product_slug: 'domain_reg' }, ], } ); const suggestions = [ { domain_name: 'foobarbaz.me', cost: '$25.00', product_id: 46, product_slug: 'dotme_domain', }, { domain_name: 'foobarbaz.org', cost: '$18.00', product_id: 6, product_slug: 'domain_reg' }, ]; const queryObject = { query: 'foobar', quantity: 2, vendor: 'domainsbot', include_wordpressdotcom: false, }; const state = items( original, { type: DOMAINS_SUGGESTIONS_RECEIVE, queryObject, suggestions, } ); expect( state ).to.eql( { '{"query":"example","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': [ { domain_name: 'example.me', cost: '$25.00', product_id: 46, product_slug: 'dotme_domain', }, { domain_name: 'example.org', cost: '$18.00', product_id: 6, product_slug: 'domain_reg' }, ], '{"query":"foobar","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': [ { domain_name: 'foobarbaz.me', cost: '$25.00', product_id: 46, product_slug: 'dotme_domain', }, { domain_name: 'foobarbaz.org', cost: '$18.00', product_id: 6, product_slug: 'domain_reg', }, ], } ); } ); describe( 'persistence', () => { test( 'persists state', () => { const original = deepFreeze( { '{"query":"example","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': [ { domain_name: 'example.me', cost: '$25.00', product_id: 46, product_slug: 'dotme_domain', }, { domain_name: 'example.org', cost: '$18.00', product_id: 6, product_slug: 'domain_reg', }, ], } ); const state = serialize( items, original ); expect( state ).to.eql( original ); } ); test( 'loads valid persisted state', () => { const original = deepFreeze( { '{"query":"example","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': [ { domain_name: 'example.me', cost: '$25.00', product_id: 46, product_slug: 'dotme_domain', }, { domain_name: 'example.org', cost: '$18.00', product_id: 6, product_slug: 'domain_reg', }, ], } ); const state = deserialize( items, original ); expect( state ).to.eql( original ); } ); test( 'loads default state when schema does not match', () => { const original = deepFreeze( { '{"query":"example","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': [ { cost: '$25.00', product_id: 46, product_slug: 'dotme_domain' }, { cost: '$18.00', product_id: 6, product_slug: 'domain_reg' }, ], } ); const state = deserialize( items, original ); expect( state ).to.eql( {} ); } ); } ); } ); describe( '#requesting()', () => { test( 'should default to an empty object', () => { const state = requesting( undefined, {} ); expect( state ).to.eql( {} ); } ); test( 'should index requesting state by serialized query', () => { const queryObject = { query: 'example', quantity: 2, vendor: 'domainsbot', include_wordpressdotcom: false, }; const state = requesting( undefined, { type: DOMAINS_SUGGESTIONS_REQUEST, queryObject, } ); expect( state ).to.eql( { '{"query":"example","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': true, } ); } ); test( 'should update requesting state on success', () => { const originalState = deepFreeze( { '{"query":"example","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': true, } ); const queryObject = { query: 'example', quantity: 2, vendor: 'domainsbot', include_wordpressdotcom: false, }; const state = requesting( originalState, { type: DOMAINS_SUGGESTIONS_REQUEST_SUCCESS, queryObject, } ); expect( state ).to.eql( { '{"query":"example","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': false, } ); } ); test( 'should update requesting state on failure', () => { const originalState = deepFreeze( { '{"query":"example","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': true, } ); const queryObject = { query: 'example', quantity: 2, vendor: 'domainsbot', include_wordpressdotcom: false, }; const state = requesting( originalState, { type: DOMAINS_SUGGESTIONS_REQUEST_FAILURE, queryObject, } ); expect( state ).to.eql( { '{"query":"example","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': false, } ); } ); test( 'should accumulate requesting state by query', () => { const originalState = deepFreeze( { '{"query":"example","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': true, } ); const queryObject = { query: 'foobar', quantity: 2, vendor: 'domainsbot', include_wordpressdotcom: false, }; const state = requesting( originalState, { type: DOMAINS_SUGGESTIONS_REQUEST, queryObject, } ); expect( state ).to.eql( { '{"query":"example","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': true, '{"query":"foobar","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': true, } ); } ); } ); describe( '#errors()', () => { test( 'should default to an empty object', () => { const state = errors( undefined, {} ); expect( state ).to.eql( {} ); } ); test( 'should update errors on failure', () => { const originalState = deepFreeze( { '{"query":"example","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': true, } ); const queryObject = { query: 'example', quantity: 2, vendor: 'domainsbot', include_wordpressdotcom: false, }; const error = new Error( 'something bad happened' ); const state = errors( originalState, { type: DOMAINS_SUGGESTIONS_REQUEST_FAILURE, queryObject, error, } ); expect( state ).to.eql( { '{"query":"example","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': error, } ); } ); test( 'should update errors on success', () => { const error = new Error( 'something bad happened' ); const originalState = deepFreeze( { '{"query":"example","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': error, } ); const queryObject = { query: 'example', quantity: 2, vendor: 'domainsbot', include_wordpressdotcom: false, }; const state = errors( originalState, { type: DOMAINS_SUGGESTIONS_REQUEST_SUCCESS, queryObject, } ); expect( state ).to.eql( { '{"query":"example","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': null, } ); } ); test( 'should update errors on request', () => { const error = new Error( 'something bad happened' ); const originalState = deepFreeze( { '{"query":"example","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': error, } ); const queryObject = { query: 'example', quantity: 2, vendor: 'domainsbot', include_wordpressdotcom: false, }; const state = errors( originalState, { type: DOMAINS_SUGGESTIONS_REQUEST, queryObject, } ); expect( state ).to.eql( { '{"query":"example","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': null, } ); } ); test( 'should update errors on error', () => { const originalState = deepFreeze( { '{"query":"example","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': true, } ); const queryObject = { query: 'example', quantity: 2, vendor: 'domainsbot', include_wordpressdotcom: false, }; const error = new Error( 'something bad happened' ); const state = errors( originalState, { type: DOMAINS_SUGGESTIONS_REQUEST_FAILURE, queryObject, error, } ); expect( state ).to.eql( { '{"query":"example","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': error, } ); } ); test( 'should accumulate errors by queries', () => { const error = new Error( 'something bad happened' ); const originalState = deepFreeze( { '{"query":"example","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': error, } ); const queryObject = { query: 'foobar', quantity: 2, vendor: 'domainsbot', include_wordpressdotcom: false, }; const error2 = new Error( 'something else bad happened' ); const state = errors( originalState, { type: DOMAINS_SUGGESTIONS_REQUEST_FAILURE, queryObject, error: error2, } ); expect( state ).to.eql( { '{"query":"example","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': error, '{"query":"foobar","quantity":2,"vendor":"domainsbot","include_wordpressdotcom":false}': error2, } ); } ); } ); } );
Automattic/wp-calypso
client/state/domains/suggestions/test/reducer.js
JavaScript
gpl-2.0
13,151
// Ionic Starter App // angular.module is a global place for creating, registering and retrieving Angular modules // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html) // the 2nd parameter is an array of 'requires' var GPDF = angular.module('starter', ['ionic', 'ngCordova']) .run(function($ionicPlatform) { $ionicPlatform.ready(function() { if(window.cordova && window.cordova.plugins.Keyboard) { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); // Don't remove this line unless you know what you are doing. It stops the viewport // from snapping when text inputs are focused. Ionic handles this internally for // a much nicer keyboard experience. cordova.plugins.Keyboard.disableScroll(true); } if(window.StatusBar) { StatusBar.styleDefault(); } }); })
andrebalen/gpdf
www/js/app.js
JavaScript
gpl-2.0
998
/* * Timeglider for Javascript / jQuery * http://timeglider.com/jquery * * Copyright 2011, Mnemograph LLC * Licensed under Timeglider Dual License * http://timeglider.com/jquery/?p=license * * /* * TG_Date * * dependencies: jQuery, Globalize * * You might be wondering why we're not extending JS Date(). * That might be a good idea some day. There are some * major issues with Date(): the "year zero" (or millisecond) * in JS and other date APIs is 1970, so timestamps are negative * prior to that; JS's Date() can't handle years prior to * -271820, so some extension needs to be created to deal with * times (on the order of billions of years) existing before that. * * This TG_Date object also has functionality which goes hand-in-hand * with the date hashing system: each event on the timeline is hashed * according to day, year, decade, century, millenia, etc * */ /* IMPORTED DATE STANDARD http://www.w3.org/TR/NOTE-datetime "a profile of" ISO 8601 date format Complete date plus hours, minutes and seconds: YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00) Acceptable: YYYY YYYY-MM YYYY-MM-DD YYYY-MM-DDT13 YYYY-MM-DD 08:15 (strlen 16) YYYY-MM-DD 08:15:30 (strlen 19) (above would assume either a timeline-level timezone, or UTC) containing its own timezone, this would ignore timeline timezone YYYY-MM-DD 08:15:30-07:00 */ import j from '../../util/jquery-global'; import timeglider from './timeglider'; import Globalize from 'globalize'; import 'globalize/lib/cultures/globalize.culture.de'; import 'globalize/lib/cultures/globalize.culture.en-GB'; import 'globalize/lib/cultures/globalize.culture.fr'; import _ from 'underscore'; const $ = j.getJQuery(); timeglider.TG_Date = {}; var tg = timeglider; // caches speed up costly calculations var getRataDieCache = {}, getDaysInYearSpanCache = {}, getBCRataDieCache = {}, getDateFromRDCache = {}, getDateFromSecCache = {}; var VALID_DATE_PATTERN = /^(\-?\d+)?(\-\d{1,2})?(\-\d{1,2})?(?:T| )?(\d{1,2})?(?::)?(\d{1,2})?(?::)?(\d{1,2})?(\+|\-)?(\d{1,2})?(?::)?(\d{1,2})?/; // MAIN CONSTRUCTOR tg.TG_Date = function (strOrNum, date_display, offSec) { var dateStr, isoStr, gotSec, offsetSeconds = offSec || 0; if (typeof(strOrNum) == "number") { // SERIAL SECONDS dateStr = isoStr = TG_Date.getDateFromSec(strOrNum); gotSec = (strOrNum + offsetSeconds); } else if (typeof(strOrNum) === "object") { // TODO: JS Date object? // dateStr = strOrNum.ye + "-" + strOrNum.mo + "-" + strOrNum.da } else { // STRING if (strOrNum == "today") { strOrNum = TG_Date.getToday(); } dateStr = isoStr = strOrNum; } if (VALID_DATE_PATTERN.test(dateStr)) { // !TODO: translate strings like "today" and "now" // "next week", "a week from thursday", "christmas" var parsed = TG_Date.parse8601(dateStr); if (parsed.tz_ho) { // this is working ------ timezones in the string translate correctly // OK: transforms date properly to UTC since it should have been there parsed = TG_Date.toFromUTC(parsed, {hours:parsed.tz_ho, minutes:parsed.tz_mi}, "to"); } // ye, mo, da, ho, mi, se arrive in parsed (with tz_) $.extend(this,parsed); // SERIAL day from year zero this.rd = TG_Date.getRataDie(this); // SERIAL month from year 0 this.mo_num = getMoNum(this); // SERIAL second from year 0 this.sec = gotSec || getSec(this); this.date_display = (date_display) ? (date_display.toLowerCase()).substr(0,2) : "da"; // TODO: get good str from parse8601 this.dateStr = isoStr; } else { return {error:"invalid date"}; } return this; } // end TG_Date Function var TG_Date = tg.TG_Date; /* * getTimeUnitSerial * gets the serial number of specified time unit, using a ye-mo-da date object * used in addToTicksArray() in Mediator * * @param fd {object} i.e. the focus date: {ye:1968, mo:8, da:20} * @param unit {string} scale-unit (da, mo, ye, etc) * * @return {number} a non-zero serial for the specified time unit */ TG_Date.getTimeUnitSerial = function (fd, unit) { var ret = 0; var floorCeil; if (fd.ye < 0) { floorCeil = Math.ceil; } else { floorCeil = Math.floor; } switch (unit) { case "da": ret = fd.rd; break; // set up mo_num inside TG_Date constructor case "mo": ret = fd.mo_num; break; case "ye": ret = fd.ye; break; case "de": ret = floorCeil(fd.ye / 10); break; case "ce": ret = floorCeil(fd.ye / 100); break; case "thou": ret = floorCeil(fd.ye / 1000); break; case "tenthou": ret = floorCeil(fd.ye / 10000); break; case "hundredthou": ret = floorCeil(fd.ye / 100000); break; case "mill": ret = floorCeil(fd.ye / 1000000); break; case "tenmill": ret = floorCeil(fd.ye / 10000000); break; case "hundredmill": ret = floorCeil(fd.ye / 100000000); break; case "bill": ret = floorCeil(fd.ye / 1000000000); break; } return ret; }; TG_Date.getMonthDays = function(mo,ye) { if ((TG_Date.isLeapYear(ye) == true) && (mo==2)) { return 29; } else { return TG_Date.monthsDayNums[mo]; } }; TG_Date.twentyFourToTwelve = function (e) { var dob = {}; dob.ye = e.ye; dob.mo = e.mo || 1; dob.da = e.da || 1; dob.ho = e.ho || 0; dob.mi = e.mi || 0; dob.ampm = "am"; if (e.ho >= 12) { dob.ampm = "pm"; if (e.ho > 12) { dob.ho = e.ho - 12; } else { dob.ho = 12; } } else if (e.ho == 0) { dob.ho = 12; dob.ampm = "am"; } else { dob.ho = e.ho; } if (dob.mi < 9) { dob.mi = "0" + dob.mi; } return dob; }; /* * RELATES TO TICK WIDTH: SPECIFIC TO TIMELINE VIEW */ TG_Date.getMonthAdj = function (serial, tw) { var d = TG_Date.getDateFromMonthNum(serial); var w; switch (d.mo) { // 31 days case 1: case 3: case 5: case 7: case 8: case 10: case 12: var w = Math.floor(tw + ((tw/28) * 3)); return {"width":w, "days":31}; break; // Blasted February! case 2: if (TG_Date.isLeapYear(d.ye) == true) { w = Math.floor(tw + (tw/28)); return {"width":w, "days":29}; } else { return {"width":tw, "days":28}; } break; default: // 30 days w = Math.floor(tw + ((tw/28) * 2)); return {"width":w, "days":30}; } }; /* * getDateFromMonthNum * Gets a month (1-12) and year from a serial month number * @param mn {number} serial month number * @return {object} ye, mo (numbers) */ TG_Date.getDateFromMonthNum = function(mn) { var rem = 0; var ye, mo; if (mn > 0) { rem = mn % 12; if (rem == 0) { rem = 12 }; mo = rem; ye = Math.ceil(mn / 12); } else { // BCE! rem = Math.abs(mn) % 12; mo = (12 - rem) + 1; if (mo == 13) mo = 1; // NOYEARZERO problem: here we would subtract // a year from the results to eliminate the year 0 ye = -1 * Math.ceil(Math.abs(mn) / 12); // -1 } return {ye:ye, mo:mo}; }; /* * getMonthWidth * Starting with a base-width for a 28-day month, calculate * the width for any month with the possibility that it might * be a leap-year February. * * @param mo {number} month i.e. 1 = January, 12 = December * @param ye {number} year * * RELATES TO TICK WIDTH: SPECIFIC TO TIMELINE VIEW */ TG_Date.getMonthWidth = function(mo,ye,tickWidth) { var dayWidth = tickWidth / 28; var ad; var nd = 28; switch (mo) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: ad = 3; break; case 4: case 6: case 9: case 11: ad = 2; break; // leap year case 2: if (TG_Date.isLeapYear(ye) == true) { ad = 1; } else { ad=0; }; break; } var width = Math.floor(tickWidth + (dayWidth * ad)); var days = nd + ad; return {width:width, numDays:days}; }; TG_Date.getToday = function () { var d = new Date(); return d.getUTCFullYear() + "-" + (d.getUTCMonth() + 1) + "-" + d.getUTCDate() + " " + d.getUTCHours() + ":" + d.getUTCMinutes() + ":" + d.getUTCSeconds(); } /* * Helps calculate the position of a modulo remainder in getRataDie() */ TG_Date.getMonthFromRemDays = function (dnum, yr) { var tack = 0; var rem = 0; var m = 0; if (TG_Date.isLeapYear(yr)){ tack = 1; } else { tack=0; } if (dnum <= 31) { m = 1; rem = dnum; } else if ((dnum >31) && (dnum <= 59 + tack)) { m = 2; rem = dnum - (31 + tack); } else if ((dnum > 59 + tack) && (dnum <= 90 + tack)) { m = 3; rem = dnum - (59 + tack); } else if ((dnum > 90 + tack) && (dnum <= 120 + tack)) { m = 4; rem = dnum - (90 + tack); } else if ((dnum > 120 + tack) && (dnum <= 151 + tack)) { m = 5; rem = dnum - (120 + tack); } else if ((dnum > 151 + tack) && (dnum <= 181 + tack)) { m = 6; rem = dnum - (151 + tack); } else if ((dnum > 181 + tack) && (dnum <= 212 + tack)) { m = 7; rem = dnum - (181 + tack); } else if ((dnum > 212 + tack) && (dnum <= 243 + tack)) { m = 8; rem = dnum - (212 + tack); } else if ((dnum > 243 + tack) && (dnum <= 273 + tack)) { m = 9; rem = dnum - (243 + tack); } else if ((dnum > 273 + tack) && (dnum <= 304 + tack)) { m = 10; rem = dnum - (273 + tack); } else if ((dnum > 304 + tack) && (dnum <= 334 + tack)) { m = 11; rem = dnum - (304 + tack); } else { m = 12; rem = dnum - (334 + tack); } return {mo:m, da:rem}; }; /* GET YYYY.MM.DD FROM (serial) rata die @param snum is the rata die or day serial number */ TG_Date.getDateFromRD = function (snum) { if (getDateFromRDCache[snum]) { return getDateFromRDCache[snum] } // in case it arrives as an RD-decimal var snumAb = Math.floor(snum); var bigP = 146097; // constant days in big cal cycle var chunk1 = Math.floor(snumAb / bigP); var chunk1days = chunk1 * bigP; var chunk1yrs = Math.floor(snumAb / bigP) * 400; var chunk2days = snumAb - chunk1days; var dechunker = chunk2days; var ct = 1; var ia = chunk1yrs + 1; var iz = ia + 400; for (var i = ia; i <= iz; i++) { if (dechunker > 365) { dechunker -= 365; if (TG_Date.isLeapYear(i)) { dechunker -= 1; } ct++; } else { i = iz; } } var yt = chunk1yrs + ct; if (dechunker == 0) dechunker = 1; var inf = TG_Date.getMonthFromRemDays(dechunker,yt); // in case... var miLong = (snum - snumAb) * 1440; var mi = Math.floor(miLong % 60); var ho = Math.floor(miLong / 60); if ((TG_Date.isLeapYear(yt)) && (inf['mo'] == 2)) { inf['da'] += 1; } var ret = yt + "-" + inf['mo'] + "-" + inf['da'] + " " + ho + ":" + mi + ":00"; getDateFromRDCache[snum] = ret; return ret; }, // end getDateFromRD TG_Date.getDateFromSec = function (sec) { // FIRST GET Rata die if (getDateFromSecCache[sec]) { return getDateFromSecCache[sec] } // the sec/86400 represents a "rd-decimal form" // that will allow extraction of hour, minute, second var ret = TG_Date.getDateFromRD(sec / 86400); getDateFromSecCache[sec] = ret; return ret; }; TG_Date.isLeapYear = function(y) { if (y % 400 == 0) { return true; } else if (y % 100 == 0){ return false; } else if (y % 4 == 0) { return true; } else { return false; } }; /* * getRataDie * Core "normalizing" function for dates, the serial number day for * any date, starting with year 1 (well, zero...), wraps a getBCRataDie() * for getting negative year serial days * * @param dat {object} date object with {ye, mo, da} * @return {number} the serial day */ TG_Date.getRataDie = function (dat) { var ye = dat.ye; var mo = dat.mo; var da = dat.da; var ret = 0; if (getRataDieCache[ye + "-" + mo + "-" + da]) { return getRataDieCache[ye + "-" + mo + "-" + da]; } if (ye >= 0) { // THERE IS NO YEAR ZERO!!! if (ye == 0) ye = 1; var fat = (Math.floor(ye / 400)) * 146097, remStart = (ye - (ye % 400)), moreDays = parseInt(getDaysInYearSpan(remStart, ye)), daysSoFar = parseInt(getDaysSoFar(mo,ye)); ret = (fat + moreDays + daysSoFar + da) - 366; } else if (ye < 0) { ret = TG_Date.getBCRataDie({ye:ye, mo:mo, da:da}); } getRataDieCache[ye + "-" + mo + "-" + da] = ret; return ret; ////// internal RataDie functions /* * getDaysInYearSpan * helps calculate chunks of whole years * @param a {number} initial year in span * @param z {number} last year in span * * @return {number} days in span of arg. years */ function getDaysInYearSpan (a, z) { if (getDaysInYearSpanCache[a + "-" + z]) { return getDaysInYearSpanCache[a + "-" + z]; } var t = 0; for (var i = a; i < z; i++){ if (TG_Date.isLeapYear(i)) { t += 366; } else { t += 365; } } getDaysInYearSpanCache[a + "-" + z] = t; return t; }; function getDaysSoFar (mo,ye) { var d; switch (mo) { case 1: d=0; break; // 31 case 2: d=31; break; // 29 case 3: d=59; break; // 31 case 4: d=90; break; // 30 case 5: d=120; break; // 31 case 6: d=151; break; // 30 case 7: d=181; break; // 31 case 8: d=212; break; // 31 case 9: d=243; break; // 30 case 10: d=273;break; // 31 case 11: d=304;break; // 30 case 12: d=334;break; // 31 } if (mo > 2) { if (TG_Date.isLeapYear(ye)) { d += 1; } } return d; }; }; TG_Date.monthNamesLet = ["","J","F","M","A","M","J","J","A","S","O","N","D"]; TG_Date.monthsDayNums = [0,31,28,31,30,31,30,31,31,30,31,30,31,29]; // NON-CULTURE TG_Date.units = ["da", "mo", "ye", "de", "ce", "thou", "tenthou", "hundredthou", "mill", "tenmill", "hundredmill", "bill"]; /* Counts serial days starting with -1 in year -1. Visualize a number counting from "right to left" on top of the other calendrical pieces chunking away from "left to right". But since there's no origin farther back before 0 we have no choice. @param dat object with .ye, .mo, .da */ TG_Date.getBCRataDie = function (dat) { var ye = dat.ye, mo = dat.mo, da = dat.da; if (getBCRataDieCache[ye + "-" + mo + "-" + da]) { return getBCRataDieCache[ye + "-" + mo + "-" + da]; } if (mo == 0) mo = 1; if (da == 0) da = 1; var absYe = Math.abs(ye); var chunks = [0,335,306,275,245,214,184,153,122,92,61,31,0]; var mdays = TG_Date.monthsDayNums[mo]; var rawYeDays = (absYe - 1) * 366; var rawMoDays = chunks[mo]; var rawDaDays = (mdays - da) + 1; var ret = -1 * (rawYeDays + rawMoDays + rawDaDays); getBCRataDieCache[ye + "-" + mo + "-" + da] = ret; return ret; }; TG_Date.setCulture = function(culture_str) { var cult = tg.culture = Globalize.culture(culture_str || "default"); // ["","January", "February", "March", etc]; TG_Date.monthNames = $.merge([""], cult.calendar.months.names); // ["","Jan", "Feb", "Mar", etc]; TG_Date.monthNamesAbbr = $.merge([""], cult.calendar.months.namesAbbr); // ["Sunday", "Monday", "Tuesday", etc]; TG_Date.dayNames = cult.calendar.days.names; // ["Sun", "Mon", "Tue", etc]; TG_Date.dayNamesAbbr = cult.calendar.days.namesAbbr; TG_Date.dayNamesShort = cult.calendar.days.namesShort; TG_Date.patterns = cult.calendar.patterns; switch(cult.name){ default: TG_Date.decadeAbreviation = 's'; // 1770s break; case 'de': TG_Date.decadeAbreviation = 'er'; // 1770er break; case 'fr': TG_Date.decadeAbreviation = ''; // 1770 break } }; /* * INSTANCE METHODS * */ TG_Date.prototype = { format : function (sig, useLimit, tz_off) { var offset = tz_off || {"hours":0, "minutes":0}; var jsDate, ddlim = "da", fromUTC; // jsDate var tgFormatDate = function(fromUTC, display) { var tgd = timeglider.TG_Date, f = "", d = fromUTC, ampm, hoPack = {}, disp = display || "da", bceYe = function(ye) { var y = parseInt(ye,10); if (y < 0) { return Math.abs(y) + " bce"; } else { return y; } }; switch (disp) { case "no": return ""; break; case "ye": f = bceYe(d.ye); break; case "mo": f = tgd.monthNamesAbbr[d.mo] + " " + bceYe(d.ye); break; case "da": switch (tg.culture.name) { default: f = tgd.monthNames[d.mo] + ' ' + d.da + ', ' + bceYe(d.ye); break; case 'de': f = d.da + '. ' + tgd.monthNames[d.mo] + " " + bceYe(d.ye); break; case 'fr': f = d.da + ' ' + tgd.monthNames[d.mo] + " " + bceYe(d.ye); break; } break; case "ho": ampm = "AM"; hoPack = tgd.twentyFourToTwelve(d); f = tgd.monthNamesAbbr[d.mo] + " " + d.da + ", " + bceYe(d.ye) + " " + hoPack.ho + ":" + hoPack.mi + " " + hoPack.ampm; break; } // end switch return f; }; if (useLimit == true) { // reduce to 2 chars for consistency ddlim = this.date_display.substr(0,2); switch (ddlim) { case "no": return ""; break; case "ye": sig = "yyyy"; break; case "mo": sig = "MMM yyyy"; break; case "da": sig = "d. MMMMM yyyy"; break; case "ho": sig = "MMM d, yyyy h:mm tt"; break; default: sig = "f"; } } var cloner = _.clone(this), fromUTC = TG_Date.toFromUTC(cloner, offset, "from"); if (timeglider.i18n) { // make use of possible other culture via i18n return timeglider.i18n.formatDate(fromUTC, ddlim); } else { // dates before roughly this time do not work in JS if (fromUTC.ye < -270000){ return this.ye; } else { // jsDate = new Date(fromUTC.ye, (fromUTC.mo-1), fromUTC.da, fromUTC.ho, fromUTC.mi, fromUTC.se, 0); // return Globalize.format(jsDate, sig); return tgFormatDate(fromUTC, ddlim); } } } } // end .prototype TG_Date.getTimeOffset = function(offsetString) { // remove all but numbers, minus, colon var oss = offsetString.replace(/[^-\d:]/gi, ""), osA = oss.split(":"), ho = parseInt(osA[0], 10), mi = parseInt(osA[1], 10), // minutes negative if hours are sw = (ho < 0) ? -1 : 1, miDec = sw * ( mi / 60 ), dec = (ho + miDec), se = dec * 3600; var ob = {"decimal":dec, "hours":ho, "minutes":mi, "seconds":se, "string":oss}; return ob; }; TG_Date.tzOffsetStr = function (datestr, offsetStr) { if (datestr) { if (datestr.length == 19) { datestr += offsetStr; } else if (datestr.length == 16) { datestr += ":00" + offsetStr; } return datestr; } }; /* * TG_parse8601 * transforms string into TG Date object */ TG_Date.parse8601 = function(str){ /* len str 4 YyYyYyY 7 YyYyYyY-MM 10 YyYyYyY-MM-DD 13 YyYyYyY-MM-DDTHH (T is optional between day and hour) 16 YyYyYyY-MM-DD HH:MM 19 YyYyYyY-MM-DDTHH:MM:SS 25 YyYyYyY-MM-DD HH:MM:SS-ZH:ZM */ var ye, mo, da, ho, mi, se, bce, bce_ye, tz_pm, tz_ho, tz_mi, mo_default = 1, da_default = 1, ho_default = 0, mi_default = 0, se_default = 0, dedash = function (n){ if (n) { return parseInt(n.replace("-", ""), 10); } else { return 0; } }, // YyYyYyY MM DD reg = VALID_DATE_PATTERN; var rx = str.match(reg); // picks up positive OR negative (bce) ye = parseInt(rx[1]); if (!ye) return {"error":"invalid date; no year provided"}; mo = dedash(rx[2]) || mo_default; da = dedash(rx[3]) || da_default; // rx[4] is the "T" or " " ho = dedash(rx[4]) || ho_default; // rx[6] is ":" mi = dedash(rx[5]) || mi_default; // rx[8] is ":" se = dedash(rx[6]) || se_default; // if year is < 1 or > 9999, override // tz offset, set it to 0/UTC no matter what // If the offset is negative, we want to make // sure that minutes are considered negative along // with the hours"-07:00" > {tz_ho:-7; tz_mi:-30} tz_pm = rx[7] || "+"; tz_ho = parseInt(rx[8], 10) || 0; if (tz_pm == "-") {tz_ho = tz_ho * -1;} tz_mi = parseInt(rx[9], 10) || 0; if (tz_pm == "-") {tz_mi = tz_mi * -1;} return {"ye":ye, "mo":mo, "da":da, "ho":ho, "mi":mi, "se":se, "tz_ho":tz_ho, "tz_mi":tz_mi}; }; // parse8601 TG_Date.getLastDayOfMonth = function(ye, mo) { var lastDays = [0,31,28,31,30,31,30,31,31,30,31,30,31], da = 0; if (mo == 2 && TG_Date.isLeapYear(ye) == true) { da = 29; } else { da = lastDays[mo]; } return da; }; /* * getDateTimeStrings * * @param str {String} ISO8601 date string * @return {Object} date, time as strings with am or pm */ TG_Date.getDateTimeStrings = function (str) { var obj = TG_Date.parse8601(str); if (str == "today" || str == "now") { return {"date": str, "time":""} } else { var date_val = obj.ye + "-" + unboil(obj.mo) + "-" + unboil(obj.da); } var ampm = "pm"; if (obj.ho >= 12) { if (obj.ho > 12) obj.ho -= 12; ampm = "pm"; } else { if (obj.ho == 0) { obj.ho = "12"; } ampm = "am"; } var time_val = boil(obj.ho) + ":" + unboil(obj.mi) + " " + ampm; return {"date": date_val, "time":time_val} }; // This is for a separate date input field --- YYYY-MM-DD (DATE ONLY) // field needs to be restricted by the $.alphanumeric plugin TG_Date.transValidateDateString = function (date_str) { if (date_str == "today" || date_str == "now"){ return date_str; } if (!date_str) return false; // date needs some value var reg = /^(\-?\d+|today|now) ?(bce?)?-?(\d{1,2})?-?(\d{1,2})?/, valid = "", match = date_str.match(reg), zb = TG_Date.zeroButt; if (match) { // now: 9999-09-09 // today: get today // translate var ye = match[1], bc = match[2] || "", mo = match[3] || "07", da = match[4] || "1"; if (parseInt(ye, 10) < 0 || bc.substr(0,1) == "b") { ye = -1 * (Math.abs(ye)); } if (TG_Date.validateDate(ye, mo, da)) { return ye + "-" + zb(mo) + "-" + zb(da); } else { return false; } } else { return false; } }; // This is for a separate TIME input field: 12:30 pm // field needs to be restricted by the $.alphanumeric plugin TG_Date.transValidateTimeString = function (time_str) { if (!time_str) return "12:00:00"; var reg = /^(\d{1,2}|noon):?(\d{1,2})?:?(\d{1,2})? ?(am|pm)?/i, match = time_str.toLowerCase().match(reg), valid = "", zb = TG_Date.zeroButt; if (match[1]) { // translate if (match[0] == "noon") { valid = "12:00:00" } else { // HH MM var ho = parseInt(match[1], 10) || 12; var mi = parseInt(match[2], 10) || 0; var se = parseInt(match[3], 10) || 0; var ampm = match[4] || "am"; if (TG_Date.validateTime(ho, mi, se) == false) return false; if (ampm == "pm" && ho < 12) { ho += 12; } else if (ampm == "am" && ho ==12){ ho = 0; } valid = zb(ho) + ":" + zb(mi) + ":" + zb(se); } } else { valid = false; } return valid; }; // make sure hours and minutes are valid numbers TG_Date.validateTime = function (ho, mi, se) { if ((ho < 0 || ho > 23) || (mi < 0 || mi > 59) || (se < 0 || se > 59)) { return false; } return true; }; /* * validateDate * Rejects dates like "2001-13-32" and such * */ TG_Date.validateDate = function (ye, mo, da) { // this takes care of leap year var ld = TG_Date.getMonthDays(mo, ye); if ((da > ld) || (da <= 0)) { return false; } // invalid month numbers if ((mo > 12) || (mo < 0)) { return false; } // there's no year "0" if (ye == 0) { return false; } return true; }; // make sure hours and minutes are valid numbers TG_Date.zeroButt = function (n) { var num = parseInt(n, 10); if (num > 9) { return String(num); } else { return "0" + num; } } /* * toFromUTC * transforms TG_Date object to be either in UTC (GMT!) or in non-UTC * * @param ob: {Object} date object including ye, mo, da, etc * @param offset: {Object} eg: hours, minutes {Number} x 2 * @param toFrom: either "to" UTC or "from" * * with offsets made clear. Used for formatting dates at all times * since all event dates are stored in UTC * * @ return {Object} returns SIMPLE DATE OBJECT: not a full TG_Date instance * since we don't want the overhead of calculating .rd etc. */ TG_Date.toFromUTC = function (ob, offset, toFrom) { var nh_dec = 0, lastDays = [0,31,28,31,30,31,30,31,31,30,31,30,31,29], deltaFloatToHM = function (flt){ var fl = Math.abs(flt), h = Math.floor(fl), dec = fl - h, m = Math.round(dec * 60); return {"ho":h, "mi":m, "se":0}; }, delta = {}; // Offset is the "timezone setting" on the timeline, // or the timezone to which to translate from UTC if (toFrom == "from") { delta.ho = -1 * offset.hours; delta.mi = -1 * offset.minutes; } else if (toFrom == "to"){ delta.ho = offset.hours; delta.mi = offset.minutes; } else { delta.ho = -1 * ob.tz_ho; delta.mi = -1 * ob.tz_mi; } // no change, man! if (delta.ho == 0 && delta.mi ==0) { return ob; } // decimal overage or underage after adding offset var ho_delta = (ob.ho + (ob.mi / 60)) + ((-1 * delta.ho) + ((delta.mi * -1) / 60)); // FWD OR BACK ? if (ho_delta < 0) { // go back a day nh_dec = 24 + ho_delta; if (ob.da > 1) { ob.da = ob.da - 1; } else { // day is 1.... if (ob.mo == 1) { // & month is JAN, go back to DEC ob.ye = ob.ye - 1; ob.mo = 12; ob.da = 31; } else { ob.mo = ob.mo-1; // now that we know month, what is the last day number? ob.da = TG_Date.getLastDayOfMonth(ob.ye, ob.mo) } } } else if (ho_delta >= 24) { // going fwd a day nh_dec = ho_delta - 24; if (TG_Date.isLeapYear(ob.ye) && ob.mo == 2 && ob.da==28){ ob.da = 29; } else if (ob.da == lastDays[ob.mo]) { if (ob.mo == 12) { ob.ye = ob.ye + 1; ob.mo = 1; } else { ob.mo = ob.mo + 1; } ob.da = 1; } else { ob.da = ob.da + 1; } } else { nh_dec = ho_delta; } // delta did not take us from one day to another // only adjust the hour and minute var hm = deltaFloatToHM(nh_dec); ob.ho = hm.ho; ob.mi = hm.mi; if (!offset) { ob.tz_ho = 0; ob.tz_mi = 0; } else { ob.tz_ho = offset.tz_ho; ob.tz_mi = offset.tz_mi; } ////// // return ob; var retob = {ye:ob.ye, mo:ob.mo, da:ob.da, ho:ob.ho, mi:ob.mi, se:ob.se}; return retob; }; // toFromUTC /* * TGSecToUnixSec * translates Timeglider seconds to unix-usable * SECONDS. Multiply by 1000 to get unix milliseconds * for JS dates, etc. * * @return {Number} SECONDS (not milliseconds) * */ TG_Date.TGSecToUnixSec = function(tg_sec) { // 62135686740 return tg_sec - (62135686740 - 24867); }; TG_Date.JSDateToISODateString = function (d){ var pad = function(n){return n<10 ? '0'+n : n} return d.getUTCFullYear()+'-' + pad(d.getUTCMonth()+1)+'-' + pad(d.getUTCDate())+' ' + pad(d.getUTCHours())+':' + pad(d.getUTCMinutes())+':' + pad(d.getUTCSeconds()); }; TG_Date.timezones = [ {"offset": "-12:00", "name": "Int'l Date Line West"}, {"offset": "-11:00", "name": "Bering & Nome"}, {"offset": "-10:00", "name": "Alaska-Hawaii Standard Time"}, {"offset": "-10:00", "name": "U.S. Hawaiian Standard Time"}, {"offset": "-10:00", "name": "U.S. Central Alaska Time"}, {"offset": "-09:00", "name": "U.S. Yukon Standard Time"}, {"offset": "-08:00", "name": "U.S. Pacific Standard Time"}, {"offset": "-07:00", "name": "U.S. Mountain Standard Time"}, {"offset": "-07:00", "name": "U.S. Pacific Daylight Time"}, {"offset": "-06:00", "name": "U.S. Central Standard Time"}, {"offset": "-06:00", "name": "U.S. Mountain Daylight Time"}, {"offset": "-05:00", "name": "U.S. Eastern Standard Time"}, {"offset": "-05:00", "name": "U.S. Central Daylight Time"}, {"offset": "-04:00", "name": "U.S. Atlantic Standard Time"}, {"offset": "-04:00", "name": "U.S. Eastern Daylight Time"}, {"offset": "-03:30", "name": "Newfoundland Standard Time"}, {"offset": "-03:00", "name": "Brazil Standard Time"}, {"offset": "-03:00", "name": "Atlantic Daylight Time"}, {"offset": "-03:00", "name": "Greenland Standard Time"}, {"offset": "-02:00", "name": "Azores Time"}, {"offset": "-01:00", "name": "West Africa Time"}, {"offset": "00:00", "name": "Greenwich Mean Time/UTC"}, {"offset": "00:00", "name": "Western European Time"}, {"offset": "01:00", "name": "Central European Time"}, {"offset": "01:00", "name": "Middle European Time"}, {"offset": "01:00", "name": "British Summer Time"}, {"offset": "01:00", "name": "Middle European Winter Time"}, {"offset": "01:00", "name": "Swedish Winter Time"}, {"offset": "01:00", "name": "French Winter Time"}, {"offset": "02:00", "name": "Eastean EU"}, {"offset": "02:00", "name": "USSR-zone1"}, {"offset": "02:00", "name": "Middle European Summer Time"}, {"offset": "02:00", "name": "French Summer Time"}, {"offset": "03:00", "name": "Baghdad Time"}, {"offset": "03:00", "name": "USSR-zone2"}, {"offset": "03:30", "name": "Iran"}, {"offset": "04:00", "name": "USSR-zone3"}, {"offset": "05:00", "name": "USSR-zone4"}, {"offset": "05:30", "name": "Indian Standard Time"}, {"offset": "06:00", "name": "USSR-zone5"}, {"offset": "06:30", "name": "North Sumatra Time"}, {"offset": "07:00", "name": "USSR-zone6"}, {"offset": "07:00", "name": "West Australian Standard Time"}, {"offset": "07:30", "name": "Java"}, {"offset": "08:00", "name": "China & Hong Kong"}, {"offset": "08:00", "name": "USSR-zone7"}, {"offset": "08:00", "name": "West Australian Daylight Time"}, {"offset": "09:00", "name": "Japan"}, {"offset": "09:00", "name": "Korea"}, {"offset": "09:00", "name": "USSR-zone8"}, {"offset": "09:30", "name": "South Australian Standard Time"}, {"offset": "09:30", "name": "Central Australian Standard Time"}, {"offset": "10:00", "name": "Guam Standard Time"}, {"offset": "10:00", "name": "USSR-zone9"}, {"offset": "10:00", "name": "East Australian Standard Time"}, {"offset": "10:30", "name": "Central Australian Daylight Time"}, {"offset": "10:30", "name": "South Australian Daylight Time"}, {"offset": "11:00", "name": "USSR-zone10"}, {"offset": "11:00", "name": "East Australian Daylight Time"}, {"offset": "12:00", "name": "New Zealand Standard Time"}, {"offset": "12:00", "name": "Int'l Date Line East"}, {"offset": "13:00", "name": "New Zealand Daylight Time"} ]; /* * boil * basic wrapper for parseInt to clean leading zeros, * as in dates */ function boil (n) { return parseInt(n, 10); }; TG_Date.boil = boil; function unboil (n) { var no = parseInt(n, 10); if (no > 9 || no < 0) { return String(n); } else { return "0" + no; } }; TG_Date.unboil = unboil; function getSec (fd) { var daSec = Math.abs(fd.rd) * 86400; var hoSec = (fd.ho) * 3600; var miSec = (fd.mi - 1) * 60; var bc = (fd.rd > 0) ? 1 : -1; var ret = bc * (daSec + hoSec + miSec); return ret; }; /* getMoNum * * @param mo {Number} month from 1 to 12 * @param ye {Number} straight year * */ function getMoNum (ob) { if (ob.ye > 0) { return ((ob.ye -1) * 12) + ob.mo; } else { return getMoNumBC(ob.mo, ob.ye); } }; /* * getMoNumBC * In BC time, serial numbers for months are going backward * starting with December of 1 bce. So, a month that is actually * "month 12 of year -1" is actually just -1, and November of * year 1 bce is -2. Capiche!? * * @param {object} ob ---> .ye (year) .mo (month) * @return {number} serial month number (negative in this case) */ function getMoNumBC (mo, ye) { var absYe = Math.abs(ye); var n = ((absYe - 1) * 12) + (12-(mo -1)); return -1 * n; }; function show(ob){ return ob.ye + "-" + ob.mo + "-" + ob.da + " " + ob.ho + ":" + ob.mi; }
KplusH/jsbach-timeline
src/jsb/js/lib/timeglider/TG_Date.js
JavaScript
gpl-2.0
30,612
/** * Created by ELatA on 14-2-19. */ exports.routes = function(app){ app.get('/editor',function(req,res){ res.render('editor'); }) }
gastrodia/SceneEditor
routes/editor.js
JavaScript
gpl-2.0
151
var PacketReader = require('../PacketReader'), PacketWriter = require('../PacketWriter'), ExecuteQueryPacket = require('../ExecuteQueryPacket'), FetchPacket = require('../FetchPacket'), CAS = require('../../constants/CASConstants'), assert = require('assert'); function testFetchPacket() { var packetReader = new PacketReader(); var packetWriter = new PacketWriter(); var options = { casInfo : [0, 255, 255, 255], dbVersion : '8.4.1' }; packetReader = new PacketReader(); packetWriter = new PacketWriter(); options = {sql : 'select * from code', casInfo : [0, 255, 255, 255], autoCommitMode : 1, dbVersion : '8.4.1'}; var executeQueryPacket = new ExecuteQueryPacket(options); executeQueryPacket.write(packetWriter); packetReader.write(new Buffer([0, 0, 1, 57, 0, 255, 255, 255, 0, 0, 0, 4, 255, 255, 255, 255, 21, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 7, 115, 95, 110, 97, 109, 101, 0, 0, 0, 0, 1, 0, 0, 0, 0, 5, 99, 111, 100, 101, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 6, 0, 0, 0, 7, 102, 95, 110, 97, 109, 101, 0, 0, 0, 0, 1, 0, 0, 0, 0, 5, 99, 111, 100, 101, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 1, 21, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 88, 0, 0, 0, 0, 6, 77, 105, 120, 101, 100, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 87, 0, 0, 0, 0, 6, 87, 111, 109, 97, 110, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 77, 0, 0, 0, 0, 4, 77, 97, 110, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 66, 0, 0, 0, 0, 7, 66, 114, 111, 110, 122, 101, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 83, 0, 0, 0, 0, 7, 83, 105, 108, 118, 101, 114, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 71, 0, 0, 0, 0, 5, 71, 111, 108, 100, 0])); var resultSet = executeQueryPacket.parse(packetReader).resultSet; assert.equal(resultSet, '{"ColumnNames":["s_name","f_name"],"ColumnDataTypes":["Char","String"],"RowsCount":6,"ColumnValues":[["X","Mixed"],["W","Woman"],["M","Man"],["B","Bronze"],["S","Silver"],["G","Gold"]]}'); packetReader = new PacketReader(); packetWriter = new PacketWriter(); var fetchPacket = new FetchPacket(options); fetchPacket.write(packetWriter, executeQueryPacket); assert.equal(packetWriter._toBuffer()[3], 38); // Total length assert.equal(packetWriter._toBuffer()[8], CAS.CASFunctionCode.CAS_FC_FETCH); assert.equal(packetWriter._toBuffer()[16], 4); assert.equal(packetWriter._toBuffer()[24], 7); assert.equal(packetWriter._toBuffer()[32], 100); assert.equal(packetWriter._toBuffer()[37], 0); assert.equal(packetWriter._toBuffer()[45], 0); packetReader.write(new Buffer([0, 0, 0, 0, 0, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0])); fetchPacket.parse(packetReader, executeQueryPacket); assert.equal(fetchPacket.casInfo[0], 0); // CasInfo assert.equal(fetchPacket.casInfo[1], 255); // CasInfo assert.equal(fetchPacket.casInfo[2], 255); // CasInfo assert.equal(fetchPacket.casInfo[3], 255); // CasInfo assert.equal(fetchPacket.responseCode, 0); assert.equal(fetchPacket.errorCode, 0); assert.equal(fetchPacket.errorMsg, ''); assert.equal(fetchPacket.tupleCount, 0); } console.log('Unit test ' + module.filename.toString() + ' started...'); testFetchPacket(); console.log('Unit test ended OK.');
teeple/pns_server
work/node_modules/node-cubrid/test/old_tests/packets/test_FetchPacket.js
JavaScript
gpl-2.0
3,751
/** * @copyright Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ window.customElements.define('joomla-toolbar-button', class extends HTMLElement { // Attribute getters get task() { return this.getAttribute('task'); } get listSelection() { return this.hasAttribute('list-selection'); } get form() { return this.getAttribute('form'); } get formValidation() { return this.hasAttribute('form-validation'); } get confirmMessage() { return this.getAttribute('confirm-message'); } /** * Lifecycle */ constructor() { super(); if (!Joomla) { throw new Error('Joomla API is not properly initiated'); } this.onChange = this.onChange.bind(this); this.executeTask = this.executeTask.bind(this); } /** * Lifecycle */ connectedCallback() { // We need a button to support button behavior, // because we cannot currently extend HTMLButtonElement this.buttonElement = this.querySelector('button, a'); this.addEventListener('click', this.executeTask); // Check whether we have a form const formSelector = this.form || 'adminForm'; this.formElement = document.getElementById(formSelector); this.disabled = false; // If list selection is required, set button to disabled by default if (this.listSelection) { this.setDisabled(true); } if (this.listSelection) { if (!this.formElement) { throw new Error(`The form "${formSelector}" is required to perform the task, but the form was not found on the page.`); } // Watch on list selection this.formElement.boxchecked.addEventListener('change', this.onChange); } } /** * Lifecycle */ disconnectedCallback() { if (this.formElement.boxchecked) { this.formElement.boxchecked.removeEventListener('change', this.onChange); } this.removeEventListener('click', this.executeTask); } onChange(event) { // Check whether we have selected something this.setDisabled(event.target.value < 1); } setDisabled(disabled) { // Make sure we have a boolean value this.disabled = !!disabled; // Switch attribute for current element if (this.disabled) { this.setAttribute('disabled', true); } else { this.removeAttribute('disabled'); } // Switch attribute for native element // An anchor does not support "disabled" attribute, so use class if (this.buttonElement) { if (this.disabled) { if (this.buttonElement.nodeName === 'BUTTON') { this.buttonElement.setAttribute('disabled', true); } else { this.buttonElement.classList.add('disabled'); } } else if (this.buttonElement.nodeName === 'BUTTON') { this.buttonElement.removeAttribute('disabled'); } else { this.buttonElement.classList.remove('disabled'); } } } executeTask() { if (this.disabled) { return false; } // eslint-disable-next-line no-restricted-globals if (this.confirmMessage && !confirm(this.confirmMessage)) { return false; } if (this.task) { Joomla.submitbutton(this.task, this.form, this.formValidation); } return true; } });
astridx/joomla-cms
build/media_source/system/js/joomla-toolbar-button.w-c.es6.js
JavaScript
gpl-2.0
3,312
var BillModel = Backbone.Model.extend({ defaults:{ DueBy: '', Months: { 'jan' : '', 'feb' : '', 'mar' : '', 'apr' : '', 'may' : '', 'jun' : '', 'jul' : '', 'aug' : '', 'sep' : '', 'oct' : '', 'nov' : '', 'dec' : '', }, Payment: new PaymentModel(), }, initialize:function () { this.on("invalid", function(model, error){ console.log(error); }); }, getTemplate: function(view){ var templateModel = new TemplateModel({ViewBasePath: 'Scripts/views/Bills/'}); return templateModel.getTemplate(view); }, getSavedItems: function (controls) { var self = this; var rows = _.map(self.get('Payment').get('Payments').toJSON(), function(item) { var template = _.template(self.getTemplate('listItem')); // TODO: need to group the collectors and then determine the months that have been paid and show that self.verifyPaid(item); return template({ collector: item.Collector.get('Label'), jan: self.get('Months').jan, feb: self.get('Months').feb, mar: self.get('Months').mar, apr: self.get('Months').apr, may: self.get('Months').may, jun: self.get('Months').jun, jul: self.get('Months').jul, aug: self.get('Months').aug, sep: self.get('Months').sep, oct: self.get('Months').oct, nov: self.get('Months').nov, dec: self.get('Months').dec, }); }); return rows; }, verifyPaid: function (item) { var paymentMonth = new Date(item.DatePaid).getMonth(); this.get('Months').jan = (paymentMonth == 0) ? 'Paid' : ''; this.get('Months').feb = (paymentMonth == 1) ? 'Paid' : ''; this.get('Months').mar = (paymentMonth == 2) ? 'Paid' : ''; this.get('Months').apr = (paymentMonth == 3) ? 'Paid' : ''; this.get('Months').may = (paymentMonth == 4) ? 'Paid' : ''; this.get('Months').jun = (paymentMonth == 5) ? 'Paid' : ''; this.get('Months').jul = (paymentMonth == 6) ? 'Paid' : ''; this.get('Months').aug = (paymentMonth == 7) ? 'Paid' : ''; this.get('Months').sep = (paymentMonth == 8) ? 'Paid' : ''; this.get('Months').oct = (paymentMonth == 9) ? 'Paid' : ''; this.get('Months').nov = (paymentMonth == 10) ? 'Paid' : ''; this.get('Months').dec = (paymentMonth == 11) ? 'Paid' : ''; }, validate: function(attributes){ }, });
jrbdeveloper/backbone-sample
Scripts/models/BillsModel.js
JavaScript
gpl-2.0
2,287
jQuery(document).ready(function($) { $('#the-list').sortable({ items: 'tr', opacity: 0.6, cursor: 'move', axis: 'y', update: function() { var order = $(this).sortable('serialize') + '&action=pado_order_update_taxonomies'; $.post(ajaxurl, order, function(response) { }); } }); });
rinodung/live-theme
wp-content/plugins/pa-document/assets/js/order-taxonomies.js
JavaScript
gpl-2.0
305
//= require_self //= require leaflet.sidebar //= require leaflet.locate //= require leaflet.layers //= require leaflet.key //= require leaflet.note //= require leaflet.share //= require leaflet.polyline //= require leaflet.query //= require index/search //= require index/search_algolia //= require index/browse //= require index/export //= require index/notes //= require index/history //= require index/note //= require index/new_note //= require index/directions //= require index/changeset //= require index/query //= require router $(document).ready(function () { var loaderTimeout; OSM.loadSidebarContent = function(path, callback) { map.setSidebarOverlaid(false); clearTimeout(loaderTimeout); loaderTimeout = setTimeout(function() { $('#sidebar_loader').show(); }, 200); // IE<10 doesn't respect Vary: X-Requested-With header, so // prevent caching the XHR response as a full-page URL. if (path.indexOf('?') >= 0) { path += '&xhr=1'; } else { path += '?xhr=1'; } $('#sidebar_content') .empty(); $.ajax({ url: path, dataType: "html", complete: function(xhr) { clearTimeout(loaderTimeout); $('#flash').empty(); $('#sidebar_loader').hide(); var content = $(xhr.responseText); if (xhr.getResponseHeader('X-Page-Title')) { var title = xhr.getResponseHeader('X-Page-Title'); document.title = decodeURIComponent(title); } $('head') .find('link[type="application/atom+xml"]') .remove(); $('head') .append(content.filter('link[type="application/atom+xml"]')); $('#sidebar_content').html(content.not('link[type="application/atom+xml"]')); if (callback) { callback(); } } }); }; var params = OSM.mapParams(); var map = new L.OSM.Map("map", { zoomControl: false, layerControl: false }); map.attributionControl.setPrefix(''); map.updateLayers(params.layers); map.on("baselayerchange", function (e) { if (map.getZoom() > e.layer.options.maxZoom) { map.setView(map.getCenter(), e.layer.options.maxZoom, { reset: true }); } }); var position = $('html').attr('dir') === 'rtl' ? 'topleft' : 'topright'; L.OSM.zoom({position: position}) .addTo(map); L.control.locate({ position: position, strings: { title: I18n.t('javascripts.map.locate.title'), popup: I18n.t('javascripts.map.locate.popup') } }).addTo(map); var sidebar = L.OSM.sidebar('#map-ui') .addTo(map); L.OSM.layers({ position: position, layers: map.baseLayers, sidebar: sidebar }).addTo(map); L.OSM.key({ position: position, sidebar: sidebar }).addTo(map); L.OSM.share({ position: position, sidebar: sidebar, short: true }).addTo(map); L.OSM.note({ position: position, sidebar: sidebar }).addTo(map); L.OSM.query({ position: position, sidebar: sidebar }).addTo(map); L.control.scale() .addTo(map); if (OSM.STATUS !== 'api_offline' && OSM.STATUS !== 'database_offline') { OSM.initializeNotes(map); if (params.layers.indexOf(map.noteLayer.options.code) >= 0) { map.addLayer(map.noteLayer); } OSM.initializeBrowse(map); if (params.layers.indexOf(map.dataLayer.options.code) >= 0) { map.addLayer(map.dataLayer); } } var placement = $('html').attr('dir') === 'rtl' ? 'right' : 'left'; $('.leaflet-control .control-button').tooltip({placement: placement, container: 'body'}); var expiry = new Date(); expiry.setYear(expiry.getFullYear() + 10); map.on('moveend layeradd layerremove', function() { updateLinks( map.getCenter().wrap(), map.getZoom(), map.getLayersCode(), map._object); $.removeCookie("_osm_location"); $.cookie("_osm_location", OSM.locationCookie(map), { expires: expiry, path: "/" }); }); if ($.cookie('_osm_donate2015') === 'hide') { $('#donate').hide(); } $('#donate .close').on('click', function() { $('#donate').hide(); $.cookie("_osm_donate2015", 'hide', { expires: expiry }); }); if ($.cookie('_osm_welcome') === 'hide') { $('.welcome').hide(); } $('.welcome .close').on('click', function() { $('.welcome').hide(); $.cookie("_osm_welcome", 'hide', { expires: expiry }); }); if (OSM.PIWIK) { map.on('layeradd', function (e) { if (e.layer.options) { var goal = OSM.PIWIK.goals[e.layer.options.keyid]; if (goal) { $('body').trigger('piwikgoal', goal); } } }); } if (params.bounds) { map.fitBounds(params.bounds); } else { map.setView([params.lat, params.lon], params.zoom); } var marker = L.marker([0, 0], {icon: OSM.getUserIcon()}); if (params.marker) { marker.setLatLng([params.mlat, params.mlon]).addTo(map); } $("#homeanchor").on("click", function(e) { e.preventDefault(); var data = $(this).data(), center = L.latLng(data.lat, data.lon); map.setView(center, data.zoom); marker.setLatLng(center).addTo(map); }); function remoteEditHandler(bbox, object) { var loaded = false, url = document.location.protocol === "https:" ? "https://127.0.0.1:8112/load_and_zoom?" : "http://127.0.0.1:8111/load_and_zoom?", query = { left: bbox.getWest() - 0.0001, top: bbox.getNorth() + 0.0001, right: bbox.getEast() + 0.0001, bottom: bbox.getSouth() - 0.0001 }; if (object) query.select = object.type + object.id; var iframe = $('<iframe>') .hide() .appendTo('body') .attr("src", url + querystring.stringify(query)) .on('load', function() { $(this).remove(); loaded = true; }); setTimeout(function () { if (!loaded) { alert(I18n.t('site.index.remote_failed')); iframe.remove(); } }, 1000); return false; } $("a[data-editor=remote]").click(function(e) { var params = OSM.mapParams(this.search); remoteEditHandler(map.getBounds(), params.object); e.preventDefault(); }); if (OSM.params().edit_help) { $('#editanchor') .removeAttr('title') .tooltip({ placement: 'bottom', title: I18n.t('javascripts.edit_help') }) .tooltip('show'); $('body').one('click', function() { $('#editanchor').tooltip('hide'); }); } OSM.Index = function(map) { var page = {}; page.pushstate = page.popstate = function() { map.setSidebarOverlaid(true); document.title = I18n.t('layouts.project_name.title'); }; page.load = function() { var params = querystring.parse(location.search.substring(1)); if (params.query) { $("#sidebar .search_form input[name=query]").value(params.query); } if (!("autofocus" in document.createElement("input"))) { $("#sidebar .search_form input[name=query]").focus(); } return map.getState(); }; return page; }; OSM.Browse = function(map, type) { var page = {}; page.pushstate = page.popstate = function(path, id) { OSM.loadSidebarContent(path, function() { addObject(type, id); }); }; page.load = function(path, id) { addObject(type, id, true); }; function addObject(type, id, center) { map.addObject({type: type, id: parseInt(id)}, function(bounds) { if (!window.location.hash && bounds.isValid() && (center || !map.getBounds().contains(bounds))) { OSM.router.withoutMoveListener(function () { map.fitBounds(bounds); }); } }); } page.unload = function() { map.removeObject(); }; return page; }; var history = OSM.History(map); OSM.router = OSM.Router(map, { "/": OSM.Index(map), "/search": OSM.Search(map), "/directions": OSM.Directions(map), "/export": OSM.Export(map), "/note/new": OSM.NewNote(map), "/history/friends": history, "/history/nearby": history, "/history": history, "/user/:display_name/history": history, "/note/:id": OSM.Note(map), "/node/:id(/history)": OSM.Browse(map, 'node'), "/way/:id(/history)": OSM.Browse(map, 'way'), "/relation/:id(/history)": OSM.Browse(map, 'relation'), "/changeset/:id": OSM.Changeset(map), "/query": OSM.Query(map) }); if (OSM.preferred_editor === "remote" && document.location.pathname === "/edit") { remoteEditHandler(map.getBounds(), params.object); OSM.router.setCurrentPath("/"); } OSM.router.load(); $(document).on("click", "a", function(e) { if (e.isDefaultPrevented() || e.isPropagationStopped()) return; // Open links in a new tab as normal. if (e.which > 1 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return; // Ignore cross-protocol and cross-origin links. if (location.protocol !== this.protocol || location.host !== this.host) return; if (OSM.router.route(this.pathname + this.search + this.hash)) e.preventDefault(); }); });
stanBienaives/openstreetmap-website
app/assets/javascripts/index.js
JavaScript
gpl-2.0
9,414
const keys = Object.keys const getOwnPropertyNames = Object.getOwnPropertyNames function def (v) { return (typeof v !== 'undefined') } function objToStr (o) { return o.toString() } function inject (o1, o2, lk) { if (typeof lk === 'function') { lk = getOwnPropertyNames(o2).filter(lk) } (lk || getOwnPropertyNames(o2)).forEach(k => { o1[k] = o2[k] }) return o1 } function consume (h, keys) { const ret = {} for (const k of keys) { ret[k] = h[k] delete h[k] } return ret } function hmap (f, o1, o2) { keys(o2).forEach(k => { o1[k] = f(o2[k], k) }) return o1 } // function union (obj1, obj2) { // return inject(inject({}, obj1), obj2) // } // function isObj(v){ // return (typeof v === 'object'); // } // function pushDef(v,h){ // if (typeof v !== 'undefined'){ // h.push(v); // } // } function clone (obj) { if (obj == null || typeof obj !== 'object') return obj return hmap(clone, obj.constructor(), obj) } function get (h, v) { if (h) { return h[v] } } const eventEmitterMixin = { _listeners: {}, _listeners_one_shot: {}, on (eventName, handler) { if (!this._listeners[eventName]) { this._listeners[eventName] = [] } else { this.off(eventName, handler) // no double } this._listeners[eventName].push(handler) }, off (eventName, handler) { const handlers = this._listeners[eventName] for (let i = 0; i < handlers.length; i++) { if (handlers[i] === handler) { handlers.splice(i--, 1) } } }, onNext (eventName, handler) { if (!this._listeners_one_shot[eventName]) { this._listeners_one_shot[eventName] = [] } this._listeners_one_shot[eventName].push(handler) }, emit (eventList, target) { console.log('emit', eventList, target) // DEBUGINFO const functions = [] for (const i in eventList) { const listeners = this._listeners[eventList[i]] const listeners_one_shot = this._listeners_one_shot[eventList[i]] if (listeners) for (const e in listeners) { const f = listeners[e] if (f && functions.indexOf(f) === -1) { functions.push(f) } } if (listeners_one_shot) while (listeners_one_shot.length) { const f = listeners_one_shot.shift() if (f && functions.indexOf(f) === -1) { functions.push(f) } } } for (const i in functions) { functions[i].call(this, target) } } } // if (!Object.keys) { // Object.keys = function (obj) { // var arr = [], // key; // for (key in obj) { // if (obj.hasOwnProperty(key)) { // arr.push(key); // } // } // return arr; // }; // } const addonMixin = { addon (f, args) { if (typeof f === 'function') { f.call(this, args) } else { for (var i in f) { if (f.hasOwnProperty(i)) { this[i] = f[i] } } } return this } } const waiterMixin = { /// How to see some interface is busy to do things : i don't know /// so i add check busy state every n millisecond waiting_fus: [], busy: false, wait_free (fu) { this.waiting_fus.push(fu) }, loop_waiting () { var wcnt = 0; var t = this if (!t.waiting_interval) { t.waiting_interval = setInterval(function () { if (t.busy) { wcnt = 0 } else if ((t.waiting_fus.length > 0)) { const fu = t.waiting_fus.shift() if (fu) fu(t) } else { wcnt++ if (wcnt > 10) { clearInterval(t.waiting_interval) } } }, 500) } } }
luffah/Terminus
engine/js/utils/object.js
JavaScript
gpl-2.0
3,682
/* * File: app/store/LogStore.js * * This file was generated by Sencha Architect version 2.1.0. * http://www.sencha.com/products/architect/ * * This file requires use of the Ext JS 4.1.x library, under independent license. * License of Sencha Architect does not include license for Ext JS 4.1.x. For more * details see http://www.sencha.com/license or contact license@sencha.com. * * This file will be auto-generated each and everytime you save your project. * * Do NOT hand edit this file. */ Ext.define('MyApp.store.LogStore', { extend: 'Ext.data.Store', requires: [ 'MyApp.model.FiscalDataLogModel' ], constructor: function(cfg) { var me = this; cfg = cfg || {}; me.callParent([Ext.apply({ storeId: 'MyJsonStore2', model: 'MyApp.model.FiscalDataLogModel', proxy: { type: 'ajax', reader: { type: 'json', idProperty: 'log_id' }, writer: { type: 'json', writeAllFields: false, allowSingle: false } }, listeners: { update: { fn: me.onJsonstoreUpdate, scope: me } } }, cfg)]); }, onJsonstoreUpdate: function(abstractstore, record, operation, modifiedFieldNames, options) { //GLOB.updateLogRecord(); } });
vadim-ivlev/PSCF
pages/app/store/LogStore.js
JavaScript
gpl-2.0
1,520
var async = require('async'), test_Setup = require('./testSetup/test_Setup'); exports['single query(sql, callback)'] = function (test) { var client = test_Setup.createDefaultCUBRIDDemodbConnection(); test.expect(4); async.waterfall([ function (cb) { client.connect(cb); }, function (cb) { client.query('SHOW TABLES', cb); }, function (result, queryHandle, cb) { test.ok(result); test.ok(queryHandle > 0); result = JSON.parse(result); test.ok(result.RowsCount == 10); client.closeQuery(queryHandle, cb); } ], function (err) { if (err) { throw err; } else { test.ok(client._queriesPacketList.length == 0); client.close(function (err) { test.done(err); }) } }); }; exports['multiple query(sql, callback) in the queue with closeQuery()'] = function (test) { var client = test_Setup.createDefaultCUBRIDDemodbConnection(); var arr = [1, 2, 3, 4, 5]; test.expect(arr.length * 4 + 1); async.each(arr, function (ix, done) { client.query('SHOW TABLES', function (err, result, queryHandle) { test.ok(!err); test.ok(result); test.ok(queryHandle > 0); result = JSON.parse(result); test.ok(result.RowsCount == 10); client.closeQuery(queryHandle, done); }); }, function (err) { if (err) { throw err; } else { test.ok(client._queriesPacketList.length == 0); client.close(function (err) { test.done(err); }) } }); }; exports['multiple query(sql, callback) in the queue without closeQuery()'] = function (test) { var client = test_Setup.createDefaultCUBRIDDemodbConnection(); var arr = [1, 2, 3, 4, 5]; test.expect(arr.length * 4 + 1); async.each(arr, function (ix, done) { client.query('SHOW TABLES', function (err, result, queryHandle) { test.ok(!err); test.ok(result); test.ok(queryHandle > 0); result = JSON.parse(result); test.ok(result.RowsCount == 10); done(); }); }, function (err) { if (err) { throw err; } else { test.ok(client._queriesPacketList.length > 0); client.close(function (err) { test.done(err); }) } }); // ActionQueue.enqueue([ // function (cb) { // client.connect(cb); // }, // function (cb) { // function handleResults(err, results, queryHandle) { // if (err) // } // // for (var i = 0; i < max; ++i) { // client.genericQuery('SHOW TABLES', handleResults); // } // }, // function (results, queryHandle, cb) { // console.log(++i, results); // // client.closeQuery(queryHandle, cb); //// client.genericQuery('SELECT 1; SELECT 1;', function (err, results) { //// if (err) { //// cb(err); //// } else { //// console.log(results); //// test.deepEqual(results, ['SELECT 1', 'SELECT 1']); //// cb(); //// } //// }); //// }, //// function (cb) { //// client.genericQuery(['SELECT 1;', 'SELECT 1;'], function (err, results) { //// if (err) { //// cb(err); //// } else { //// console.log(results); //// test.deepEqual(results, ['SELECT 1;', 'SELECT 1;']); //// cb(); //// } //// }); //// }, //// function (cb) { //// client.genericQuery(['SELECT 1', 'SELECT 1'], function (err, results) { //// if (err) { //// cb(err); //// } else { //// console.log(results); //// test.deepEqual(results, ['SELECT 1', 'SELECT 1']); //// cb(); //// } //// }); //// }, // function (cb) { // client.genericQuery(['SELECT 1'], function (err, results) { // if (err) { // cb(err); // } else { // console.log(results); // test.deepEqual(results, ['SELECT 1']); // cb(); // } // }); //// }, //// function (cb) { //// client.genericQuery([' SELECT 1; '], function (err, results) { //// if (err) { //// cb(err); //// } else { //// console.log(results); //// test.deepEqual(results, ['SELECT 1;']); //// cb(); //// } //// }); //// }, //// function (cb) { //// client.genericQuery('SELECT * FROM game WHERE id = ?', [1], function (err, results) { //// if (err) { //// cb(err); //// } else { //// console.log(results); //// test.deepEqual(results, ['SELECT * FROM game WHERE id = 1']); //// cb(); //// } //// }); //// }, //// function (cb) { //// client.genericQuery('SELECT * FROM game WHERE id = ? AND name = ?', [1, 'soccer'], function (err, results) { //// if (err) { //// cb(err); //// } else { //// console.log(results); //// test.deepEqual(results, ["SELECT * FROM game WHERE id = 1 AND name = 'soccer'"]); //// cb(); //// } //// }); // } // ], function (err) { // // }); }; exports['single query(sql, params, callback)'] = function (test) { var client = test_Setup.createDefaultCUBRIDDemodbConnection(); test.expect(4); async.waterfall([ function (cb) { client.connect(cb); }, function (cb) { client.query('SELECT * FROM nation WHERE continent = ?', ['Asia'], cb); }, function (result, queryHandle, cb) { test.ok(result); test.ok(queryHandle > 0); result = JSON.parse(result); test.ok(result.RowsCount == 47); client.closeQuery(queryHandle, cb); } ], function (err) { if (err) { throw err; } else { test.ok(client._queriesPacketList.length == 0); client.close(function (err) { test.done(err); }) } }); }; exports['multiple query(sql, params, callback) in the queue without closeQuery()'] = function (test) { var client = test_Setup.createDefaultCUBRIDDemodbConnection(); var arr = [ { sql: "SHOW TABLES", params: null, rowsCount: 10 }, { sql: "SELECT * FROM nation", params: [], rowsCount: 215 }, { sql: "SELECT * FROM nation WHERE continent = ?", params: ['Asia'], rowsCount: 47 }, { sql: "SELECT * FROM nation WHERE continent = ?", params: 'Asia', rowsCount: 47 }, { sql: "SELECT * FROM history WHERE host_year = ?", params: [2004], rowsCount: 64 }, { sql: "SELECT * FROM history WHERE host_year = ?", params: 2004, rowsCount: 64 }, { sql: "SELECT * FROM history WHERE host_year = ?", params: ['2004'], rowsCount: 64 }, { sql: "SELECT * FROM history WHERE host_year = ?", params: '2004', rowsCount: 64 }, { sql: "SELECT * FROM game WHERE game_date = ?", params: ['08/28/2004'], rowsCount: 311 }, { sql: "SELECT * FROM game WHERE game_date = ?", params: '08/28/2004', rowsCount: 311 }, { sql: "SELECT * FROM game WHERE game_date = ?", params: [new Date('8/28/2004')], rowsCount: 311 }, { sql: "SELECT * FROM game WHERE game_date = ?", params: new Date('8/28/2004'), rowsCount: 311 }, { sql: "SELECT * FROM game WHERE game_date = ?", params: [new Date()], rowsCount: 0 }, { sql: "SELECT * FROM game WHERE game_date = ?", params: new Date(), rowsCount: 0 } ]; test.expect(arr.length * 4 + 1); async.each(arr, function (query, done) { client.query(query.sql, query.params, function (err, result, queryHandle) { test.ok(!err); test.ok(result); test.ok(queryHandle > 0); result = JSON.parse(result); test.ok(result.RowsCount == query.rowsCount); done(); }); }, function (err) { if (err) { throw err; } else { test.ok(client._queriesPacketList.length > 0); client.close(function (err) { test.done(err); }) } }); }; exports['single execute(sql, callback)'] = function (test) { var client = test_Setup.createDefaultCUBRIDDemodbConnection(); test.expect(1); async.waterfall([ function (cb) { client.connect(cb); }, function (cb) { client.setAutoCommitMode(false, cb); }, function (cb) { client.execute("DELETE FROM code WHERE s_name = 'ZZZZ'", cb); } ], function (err) { if (err) { throw err; } else { test.ok(client._queriesPacketList.length == 0); client.close(function (err) { test.done(err); }) } }); }; exports['multiple execute(sql, callback) in the queue'] = function (test) { var client = test_Setup.createDefaultCUBRIDDemodbConnection(); var arr = [ { sql: "CREATE TABLE tbl_test(id INT)" }, { sql: "INSERT INTO tbl_test (id) VALUES (1), (2), (3)" }, { sql: "DROP TABLE tbl_test" } ]; test.expect(arr.length * 2 + 1 + 4 + 1); async.waterfall([ function (cb) { async.each(arr, function (query, done) { client.execute(query.sql, function (err) { test.ok(!err); test.ok(client._queriesPacketList.length == 0); done(); }); }, cb); }, function (cb) { test.ok(client._queriesPacketList.length == 0); client.query('SHOW TABLES', function (err, result, queryHandle) { test.ok(!err); test.ok(result); test.ok(queryHandle > 0); result = JSON.parse(result); test.ok(result.RowsCount == 10); cb(); }); } ], function (err) { if (err) { throw err; } else { test.ok(client._queriesPacketList.length == 1); client.close(function (err) { test.done(err); }) } }); };
teeple/pns_server
work/node_modules/node-cubrid/test/test.CUBRIDConnection.query.js
JavaScript
gpl-2.0
8,933
/** * Ratings Element - List * * @copyright: Copyright (C) 2005-2013, fabrikar.com - All rights reserved. * @license: GNU/GPL http://www.gnu.org/copyleft/gpl.html */ define(['jquery'], function (jQuery) { var FbRatingList = new Class({ options: { 'userid': 0, 'mode' : '', 'formid': 0 }, Implements: [Events, Options], initialize: function (id, options) { options.element = id; this.setOptions(options); if (this.options.canRate === false) { return; } if (this.options.mode === 'creator-rating') { return; } this.col = $$('.' + id); this.origRating = {}; this.col.each(function (tr) { var stars = tr.getElements('.starRating'); stars.each(function (star) { star.addEvent('mouseover', function (e) { this.origRating[tr.id] = star.getParent('.fabrik_element').getElement('.ratingMessage').innerHTML.toInt(); stars.each(function (ii) { if (this._getRating(star) >= this._getRating(ii)) { if (Fabrik.bootstrapped) { ii.removeClass('icon-star-empty').addClass('icon-star'); } else { ii.src = this.options.insrc; } } else { if (Fabrik.bootstrapped) { ii.addClass('icon-star-empty').removeClass('icon-star'); } else { ii.src = this.options.insrc; } } }.bind(this)); star.getParent('.fabrik_element').getElement('.ratingMessage').innerHTML = star.get('data-fabrik-rating'); }.bind(this)); star.addEvent('mouseout', function (e) { stars.each(function (ii) { if (this.origRating[tr.id] >= this._getRating(ii)) { if (Fabrik.bootstrapped) { ii.removeClass('icon-star-empty').addClass('icon-star'); } else { ii.src = this.options.insrc; } } else { if (Fabrik.bootstrapped) { ii.addClass('icon-star-empty').removeClass('icon-star'); } else { ii.src = this.options.insrc; } } }.bind(this)); star.getParent('.fabrik_element').getElement('.ratingMessage').innerHTML = this.origRating[tr.id]; }.bind(this)); }.bind(this)); stars.each(function (star) { star.addEvent('click', function (e) { this.doAjax(e, star); }.bind(this)); }.bind(this)); }.bind(this)); }, _getRating: function (i) { var r = i.get('data-fabrik-rating'); return r.toInt(); }, doAjax: function (e, star) { e.stop(); this.rating = this._getRating(star); var ratingmsg = star.getParent('.fabrik_element').getElement('.ratingMessage'); Fabrik.loader.start(ratingmsg); var starRatingCover = new Element('div', {id: 'starRatingCover', styles : { bottom : 0, top : 0, right : 0, left : 0, position: 'absolute', cursor : 'progress' } }); var starRatingContainer = star.getParent('.fabrik_element').getElement('div'); starRatingContainer.grab(starRatingCover, 'top'); var row = document.id(star).getParent('.fabrik_row'); var rowid = row.id.replace('list_' + this.options.listRef + '_row_', ''); var data = { 'option' : 'com_fabrik', 'format' : 'raw', 'task' : 'plugin.pluginAjax', 'plugin' : 'rating', 'g' : 'element', 'method' : 'ajax_rate', 'formid' : this.options.formid, 'element_id' : this.options.elid, 'row_id' : rowid, 'elementname': this.options.elid, 'userid' : this.options.userid, 'rating' : this.rating, 'mode' : this.options.mode }; new Request({ url : '', 'data' : data, onComplete: function (r) { r = r.toInt(); this.rating = r; ratingmsg.set('html', this.rating); Fabrik.loader.stop(ratingmsg); var tag = Fabrik.bootstrapped ? 'i' : 'img'; star.getParent('.fabrik_element').getElements(tag).each(function (i, x) { if (x < r) { if (Fabrik.bootstrapped) { i.removeClass('icon-star-empty').addClass('icon-star'); } else { i.src = this.options.insrc; } } else { if (Fabrik.bootstrapped) { i.addClass('icon-star-empty').removeClass('icon-star'); } else { i.src = this.options.insrc; } } }.bind(this)); document.id('starRatingCover').destroy(); }.bind(this) }).send(); } }); return FbRatingList; });
NarthanaSathsara/joomla_fruitshop
plugins/fabrik_element/rating/list-rating.js
JavaScript
gpl-2.0
4,443
var fb = require('fbgraph'), auth = require('../../secret/oauth').token, cron = require('cron').CronJob, logger = require('../util/logger'); function tokenRenewer() { fb.extendAccessToken(auth, function(err, facebookRes) { logger.log("Token Renewed"); }); }; var tokenRenewingCronJob = new cron({ cronTime: '00 45 * * * *', onTick: tokenRenewer, start: false }); module.exports = tokenRenewingCronJob
rishibaldawa/FacebookReport
js/fb/renewToken.js
JavaScript
gpl-2.0
443
// Generated by LiveScript 1.2.0 (function(){ var ref$, signum, abs, Four; ref$ = require('prelude-ls'), signum = ref$.signum, abs = ref$.abs; this.Level.Four = Four = (function(superclass){ var prototype = extend$((import$(Four, superclass).displayName = 'Four', Four), superclass).prototype, constructor = Four; prototype.levelWidth = 1500; prototype.levelHeight = 1200; prototype.init = function(level){ var x$, y$, z$; x$ = level; x$.background('black'); y$ = x$.platform; y$.white(515, 739, 187, 131, this.canMove); y$.white(0, 1080, 1500, 33); y$.white(110, 787, 36, 294); y$.white(265, 895, 330, 31); y$.white(1418, 588, 82, 493); y$.white(7, 640, 139, 271); y$.white(39, 515, 433, 158); y$.white(1144, 899, 189, 31); y$.white(468, 595, 814, 69); y$.white(1237, 662, 45, 77); x$.text(275, 779, ">\nSlowly..."); x$.danger(1426, 615, 74, 305); z$ = x$.player; z$.black(602, 787); z$.white(367, 984); x$.gray(494, 520, 170, 170, Level.Five); return x$; }; prototype.canMove = function(platform){ platform.inside.body.immovable = false; return platform.customUpdate = null; }; function Four(){ Four.superclass.apply(this, arguments); } return Four; }(Level)); function extend$(sub, sup){ function fun(){} fun.prototype = (sub.superclass = sup).prototype; (sub.prototype = new fun).constructor = sub; if (typeof sup.extended == 'function') sup.extended(sub); return sub; } function import$(obj, src){ var own = {}.hasOwnProperty; for (var key in src) if (own.call(src, key)) obj[key] = src[key]; return obj; } }).call(this);
Resonious/gray-area
server/game/src/levels/four.js
JavaScript
gpl-2.0
1,755
module.exports = { purge: [ './templates/**/*.html.twig', './templates/jsx/trip/*.html.twig', ], darkMode: false, prefix: 'u-', important: false, separator: ':', theme: { screens: { sm: '600px', md: '900px', lg: '1200px', }, colors: { 'bewelcome': '#f37000', 'bewelcome-dark': '#cd5e00', 'notice' : '#cce6fd', 'red': '#f3000a', 'yellow': '#f3ea00', 'green': '#00f370', 'green-dark': '#00b855', 'blue': '#7000f3', 'black': '#000', 'white': '#fff', 'gray-5': '#f9f9f9', 'gray-10': '#eee', 'gray-15': '#ddd', 'gray-20': '#ccc', 'gray-30': '#bbb', 'gray-40':'#999', 'gray-50':'#808080', 'gray-60':'#6f6f6f', 'gray-65':'#595959', 'gray-70':'#454545', 'gray-80':'#3F3F3F', 'black-o-30': 'rgba(0, 0, 0, 0.3)' }, spacing: { px: '1px', '__24': '-24px', '__18': '-18px', '__16': '-16px', '__12': '-12px', '__8': '-8px', '__4': '-4px', '__2': '-2px', '0': '0', '4': '4px', '6': '6px', '8': '8px', '12': '12px', '16': '16px', '20': '20px', '24': '24px', '32': '32px', '40': '40px', '48': '48px', '56': '56px', '60': '60px', '64': '64px', '72': '72px', '96': '96px', }, backgroundColor: theme => theme('colors'), backgroundPosition: { bottom: 'bottom', center: 'center', left: 'left', 'left-bottom': 'left bottom', 'left-top': 'left top', right: 'right', 'right-bottom': 'right bottom', 'right-top': 'right top', top: 'top', }, backgroundSize: { auto: 'auto', cover: 'cover', contain: 'contain', }, borderColor: theme => ({ ...theme('colors'), default: theme('colors.gray.300', 'currentColor'), }), borderRadius: { 'none': '0', '1': '1px', '2': '2px', '3': '3px', '4': '4px', '6': '6px', '8': '8px', '16': '16px', 'full': '100%', }, borderWidth: { default: '1px', '0': '0', '2': '2px', '4': '4px', '8': '8px', }, boxShadow: { default: '0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)', md: '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)', lg: '0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)', xl: '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)', '2xl': '0 25px 50px -12px rgba(0, 0, 0, 0.25)', inner: 'inset 0 2px 4px 0 rgba(0, 0, 0, 0.06)', outline: '0 0 0 3px rgba(66, 153, 225, 0.5)', none: 'none', }, container: {}, cursor: { auto: 'auto', default: 'default', pointer: 'pointer', wait: 'wait', text: 'text', move: 'move', 'not-allowed': 'not-allowed', }, fill: { current: 'currentColor', }, flex: { '1': '1 1 0%', auto: '1 1 auto', initial: '0 1 auto', none: 'none', }, flexGrow: { '0': '0', default: '1', }, flexShrink: { '0': '0', default: '1', }, fontFamily: { sans: [ 'Lato', 'Helvetica Neue', 'sans-serif', ], display: [ 'Signika' ] }, fontSize: { '10': '10px', '12': '12px', '14': '14px', '16': '16px', '18': '18px', '20': '20px', '22': '22px', '24': '24px', '26': '26px', '32': '32px', '36': '36px', '48': '48px', '56': '56px', '64': '64px', '72': '72px' }, fontWeight: { 100: '100', 200: '200', 300: '300', 400: '400', 500: '500', 600: '600', 700: '700', 800: '800', 900: '900' }, height: theme => ({ auto: 'auto', ...theme('spacing'), full: '100%', screen: '100vh', }), inset: { '0': '0', '8': '8px', '16': '16px', '24': '24px', auto: 'auto', }, letterSpacing: { tighter: '-0.05em', tight: '-0.025em', normal: '0', wide: '0.025em', wider: '0.05em', widest: '0.1em', }, lineHeight: { '16': '16px', '20': '20px', '24': '24px', '28': '28px', '30': '30px', '32': '32px', '36': '36px', '40': '40px', '48': '48px', '60': '60px', }, listStyleType: { none: 'none', disc: 'disc', decimal: 'decimal', }, margin: (theme, { negative }) => ({ auto: 'auto', ...theme('spacing'), ...negative(theme('spacing')), }), maxHeight: { full: '100%', screen: '100vh', }, maxWidth: { '1168': '1168px', '1200': '1200px', full: '100%', }, minHeight: { '0': '0', full: '100%', screen: '100vh', }, minWidth: { '0': '0', full: '100%', }, objectPosition: { bottom: 'bottom', center: 'center', left: 'left', 'left-bottom': 'left bottom', 'left-top': 'left top', right: 'right', 'right-bottom': 'right bottom', 'right-top': 'right top', top: 'top', }, opacity: { '0': '0', '20': '0.2', '40': '0.4', '50': '0.5', '60': '0.6', '70': '0.7', '80': '0.8', '90': '0.9', '100': '1', }, order: { first: '-9999', last: '9999', none: '0', '1': '1', '2': '2', '3': '3', '4': '4', '5': '5', '6': '6', '7': '7', '8': '8', '9': '9', '10': '10', '11': '11', '12': '12', }, padding: theme => theme('spacing'), placeholderColor: theme => theme('colors'), stroke: { current: 'currentColor', }, textColor: theme => theme('colors'), width: theme => ({ auto: 'auto', ...theme('spacing'), '1/2': '50%', '1/3': '33.333333%', '2/3': '66.666667%', '1/4': '25%', '2/4': '50%', '3/4': '75%', '1/5': '20%', '2/5': '40%', '3/5': '60%', '4/5': '80%', '1/6': '16.666667%', '2/6': '33.333333%', '3/6': '50%', '4/6': '66.666667%', '5/6': '83.333333%', '1/12': '8.333333%', '2/12': '16.666667%', '3/12': '25%', '4/12': '33.333333%', '5/12': '41.666667%', '6/12': '50%', '7/12': '58.333333%', '8/12': '66.666667%', '9/12': '75%', '10/12': '83.333333%', '11/12': '91.666667%', '720': '720px', '1168':'1168px', '1200':'1200px', full: '100%', screen: '100vw', }), zIndex: { auto: 'auto', '0': '0', '10': '10', '20': '20', '30': '30', '40': '40', '50': '50', }, }, variants: { accessibility: ['responsive', 'focus'], alignContent: ['responsive'], alignItems: ['responsive'], alignSelf: ['responsive'], appearance: ['responsive'], backgroundAttachment: ['responsive'], backgroundColor: ['responsive', 'hover', 'focus'], backgroundPosition: ['responsive'], backgroundRepeat: ['responsive'], backgroundSize: ['responsive'], borderCollapse: ['responsive'], borderColor: ['responsive', 'hover', 'focus'], borderRadius: ['responsive'], borderStyle: ['responsive'], borderWidth: ['responsive'], boxShadow: ['responsive', 'hover', 'focus'], cursor: ['responsive'], display: ['responsive'], fill: ['responsive'], flex: ['responsive'], flexDirection: ['responsive'], flexGrow: ['responsive'], flexShrink: ['responsive'], flexWrap: ['responsive'], float: ['responsive'], fontFamily: ['responsive'], fontSize: ['responsive'], fontSmoothing: ['responsive'], fontStyle: ['responsive'], fontWeight: ['responsive', 'hover', 'focus'], height: ['responsive'], inset: ['responsive'], justifyContent: ['responsive'], letterSpacing: ['responsive'], lineHeight: ['responsive'], listStylePosition: ['responsive'], listStyleType: ['responsive'], margin: ['responsive'], maxHeight: ['responsive'], maxWidth: ['responsive'], minHeight: ['responsive'], minWidth: ['responsive'], objectFit: ['responsive'], objectPosition: ['responsive'], opacity: ['responsive', 'hover', 'focus'], order: ['responsive'], outline: ['responsive', 'focus'], overflow: ['responsive'], padding: ['responsive'], placeholderColor: ['responsive', 'focus'], pointerEvents: ['responsive'], position: ['responsive'], resize: ['responsive'], stroke: ['responsive'], tableLayout: ['responsive'], textAlign: ['responsive'], textColor: ['responsive', 'hover', 'focus'], textDecoration: ['responsive', 'hover', 'focus'], textTransform: ['responsive'], userSelect: ['responsive'], verticalAlign: ['responsive'], visibility: ['responsive'], whitespace: ['responsive'], width: ['responsive'], wordBreak: ['responsive'], zIndex: ['responsive'], }, plugins: [ require('@tailwindcss/line-clamp'), ], corePlugins: { preflight: false, } }
BeWelcome/rox
tailwind.config.js
JavaScript
gpl-2.0
9,388
showWord(["n. ","Zouti pou koupe bwa, planch. Ou dwe sere goyin nan lwen paske si timoun yo al jwe avè l, li kapab blese yo." ])
georgejhunt/HaitiDictionary.activity
data/words/goyin.js
JavaScript
gpl-2.0
129
// Provide a destination, create a grid from that destination I guess // Should be used with some sort of broad phase collision checking via callback // See http://www.redblobgames.com/pathfinding/a-star/introduction.html // Todo: Implement Heap structure + Priority Queue function breadthFirstSearch(polygon, callback, options) { var defaults = { xMin: undefined, xMax: undefined, yMin: undefined, yMax: undefined, range: undefined, nodeCallback: undefined, nodeTest: undefined, targetPosition: undefined }; var x; var y; var width; var height; var nodeSize = 0; var nodeCallback; var nodeTest; var range; var targetX; var targetY; var currentGridX = 0; var currentGridY = 0; var startNode; var nextNodes; // = new PriorityQueue({isMin: true}); var needsExit = false; var costSoFar = 0; /** * @function extend * @description Returns an object that has 'default' values overwritten by 'options', otherwise default values. Properties not found in defaults are skipped. * @param {object} defaults - Object with the default values * @param {object} options - Object with values * @returns {object} - Object that has 'default' values overwritten by 'options', otherwise default values. */ function extend(defaults, options) { var prop, result = {}; if(typeof options === 'undefined') return defaults; for(prop in defaults) { if(options.hasOwnProperty(prop)) result[prop] = options[prop]; else result[prop] = defaults[prop]; } return result; } /** * @function getDistance * @description Returns the Manhattan distance between two grid coordinates * @param {object} a - Object containing x, y grid values * @param {object} b - Object containing x, y grid values * @return {number} - Manhattan distance between two grid coordinates */ function getDistance(a, b) { return Math.abs(a.x - b.x) + Math.abs(a.y - b.y); } /** * @function PriorityQueue * @description A priority queue implementation where elements are ordered based on whether the queue is set to be a min/max queue * @param {...Array} var_args - Array of starting elements, they will be prioritized based on index value * @param {...boolean} var_args - Whether this is a min (true) or a max array (false/default); * @see http://pages.cs.wisc.edu/~vernon/cs367/notes/11.PRIORITY-Q.html */ function PriorityQueue(isMin) { var i = 0; var arguementProperty; var argument; var startingElements = []; //var isMin; /* for(arguementProperty in arguments) { if(arguments.hasOwnProperty(arguementProperty)) { argument = arguments[arguementProperty]; if(typeof argument === 'object' && argument instanceof Array) startingElements = argument; if(typeof argument === 'boolean') isMin = argument; } } */ options = extend(defaults, options); this.queueArray = ['']; // Empty element so root is one this.isMin = true; /* // Automatically assign priority based on index for(i = 0; i < startingElements.length; i++) { this.insert(startingElements[i], startingElements.length-1-i); } */ return this; } PriorityQueue.prototype = { /** * @function PriorityQueue.prototype.swap * @description Swaps value at destination with value at target * @param {number} target - Target index to swap from * @param {number} destination - Target index to swap to */ swap: function (target, destination) { var temp; //if(typeof this.queueArray[destination] !== 'number' || typeof this.queueArray[target] !== 'number' || target > this.queueArray.length || destination > this.queueArray.length) //return; temp = this.queueArray[destination]; this.queueArray[destination] = this.queueArray[target]; this.queueArray[target] = temp; }, /** * @function PriorityQueue.prototype.queueHelper * @description Traverses up a the priority queue from an index, until the priority of the value at index doesn't satisfy min/max priority queue conditions. This rebalances the heap. * @param {number} index - Index to traverse the priority queue upwards from */ queueHelper: function(index) { var parentIndex = ~~(index/2); if(index == 1 || parentIndex <= 1) return; if(this.isMin ? this.queueArray[parentIndex].priority > this.queueArray[index].priority : this.queueArray[parentIndex].priority < this.queueArray[index].priority) this.swap(index, parentIndex); else // Do nothing if priority is equal return; // Run until at root (index 1) node this.queueHelper(parentIndex); }, /** * @function PriorityQueue.prototype.queueHelper * @description Inserts a value into the priority queue and rebalances the tree based on min/max position * @param {object} value - Value to insert * @param {number} priority - Priority of the value inserted. In a max heap, high priority value is moved to up the heap, opposite in a min heap. */ queue: function (value, priority) { if(typeof value === 'undefined' || typeof priority === 'undefined') return; this.queueArray.push({value: value, priority: priority}); this.queueHelper(this.queueArray.length-1); }, /** * @function PriorityQueue.prototype.dequeueHelper * @description Traverses down the priority queue from an index until there are no more leaves in the heap to check * @param {number} index - Index value to travers the priority queue downwards from */ dequeueHelper: function(index) { var leftIndex; var rightIndex; var leftElement; var rightElement; if(typeof index === 'undefined') index = 1; leftIndex = index * 2; rightIndex = index * 2 + 1; if (typeof this.queueArray[leftIndex] !== 'undefined') { if(this.isMin ? this.queueArray[leftIndex].priority < this.queueArray[index].priority : this.queueArray[leftIndex].priority > this.queueArray[index].priority) leftElement = this.queueArray[leftIndex]; } if (typeof this.queueArray[rightIndex] !== 'undefined') { if(this.isMin ? this.queueArray[rightIndex].priority < this.queueArray[index].priority : this.queueArray[rightIndex].priority > this.queueArray[index].priority) rightElement = this.queueArray[rightIndex]; } // Run until there are no more left/right leafs if(typeof leftElement === 'undefined' && typeof rightElement === 'undefined') return; // If one or the other is undefined, use the one that has value if(typeof leftElement !== 'undefined' && typeof rightElement === 'undefined') { this.swap(leftIndex, index); this.dequeueHelper(leftIndex); } else if(typeof leftElement === 'undefined' && typeof rightElement !== 'undefined') { this.swap(rightIndex, index); this.dequeueHelper(rightIndex); // If both are defined, use value based on priority } else { if (this.isMin ? leftElement.priority < rightElement.priority : leftElement.priority > rightElement.priority) { this.swap(leftIndex, index); this.dequeueHelper(leftIndex); } else if (this.isMin ? leftElement.priority >= rightElement.priority : leftElement.priority <= rightElement.priority) { this.swap(rightIndex, index); this.dequeueHelper(rightIndex); } } }, /** * @function PriorityQueue.prototype.dequeue * @description Removes the top most element from the priority queue and rebalances the heap * @returns {*} Returns the value stored in the priority queue */ dequeue: function() { var result; if(this.queueArray.length === 0) return; this.swap(1, this.queueArray.length-1); result = this.queueArray.splice(this.queueArray.length-1, 1); this.dequeueHelper(); if(result.length !== 0 && typeof result[0] !== 'undefined') { return result[0].value; } else return; }, /** * @function PriorityQueue.prototype.isEmpty * @description Returns if the queue is empty or not * @returns {boolean} - true if empty, false otherwise */ isEmpty: function() { return this.queueArray.length === 1; } }; if(typeof polygon === 'undefined') return []; options = extend(defaults, options); nodeCallback = options.nodeCallback; nodeTest = options.nodeTest; range = options.range; x = polygon.x; y = polygon.y; width = polygon.width; height = polygon.height; nodeSize = Math.max(width, height); // Largest dimension is used for cell size nextNodes = new PriorityQueue(true); if(typeof options.targetPosition !== 'undefined') { // Calculate grid position here targetX = options.targetPosition.x/nodeSize; targetY = options.targetPosition.y/nodeSize; } /* A Node Object { x: Unrounded x coordinate y: Unrounded y coordinate gridX: Rounded x coordinate gridY: Rounded y coordinate size: node size cost: distance from starting position (gridwise) with added weights origin: Origin of node } */ Node.grid = { }; /** * @function Node.testSpace * @description Tests a given (grid) space to see if it is available for a node * @params {number} x - x coordinate of grid position * @params {number} y - y coordinate of grid position * @returns {boolean} - True if node has available space, false otherwise */ Node.testSpace = function (x, y, gridX, gridY) { var result = false; if(typeof Node.grid[gridX + '_' + gridY] === 'undefined') result = true; if(result && typeof nodeTest === 'function') result = nodeTest(x, y, gridX, gridY, nodeSize); // Reaching target triggers early exit if(gridX === Math.round(targetX) && gridY === Math.round(targetY)) needsExit = true; return result; }; /** * @function Node.addToGrid * @description Adds a node instance to the node.grid * @param {object} nodeInstance - node instance to add to the grid */ Node.addToGrid = function(nodeObject) { if(typeof nodeObject === 'undefined') return; if(typeof Node.grid[nodeObject.gridX + '_' + nodeObject.gridY] === 'undefined') Node.grid[nodeObject.gridX + '_' + nodeObject.gridY] = nodeObject; return nodeObject; }; /** * @function Node.pathToTarget */ Node.pathToTarget = function() { var currentNode; var dirs = [ [0, -1], // up [1, 0], // right [0, 1], // Down [-1, 0] // left ]; var d = 0; var tempNextGridX; var tempNextGridY; var nextGridX; var nextGridY; var nextGrid; var nextNode; var minCost; var resultPath = []; // No target: Return empty if(typeof Node.grid[Math.round(targetX) + '_' + Math.round(targetY)] === 'undefined') { return resultPath; } currentGridX = Math.round(targetX); currentGridY = Math.round(targetY); currentNode = Node.grid[currentGridX + '_' + currentGridY]; currentNode.visited = true; costSoFar += currentNode.cost; while(currentNode !== startNode && typeof currentNode.origin !== 'undefined') { nextNode = undefined; for(d = 0; d < dirs.length; d++) { tempNextGridX = currentGridX+dirs[d][0]; tempNextGridY = currentGridY+dirs[d][1]; nextGrid = tempNextGridX + '_' + tempNextGridY; /* Pick next node based on distance */ if(typeof Node.grid[nextGrid] !== 'undefined' && Node.grid[nextGrid].visited === false) { if((typeof minCost === 'undefined' && typeof minDistance === 'undefined') || minCost >= Node.grid[nextGrid].cost) { minCost = Node.grid[nextGrid].cost; nextNode = Node.grid[nextGrid]; nextGridX = tempNextGridX; nextGridY = tempNextGridY; } } } //console.log('asdf2'); if(typeof nextNode !== 'undefined') { resultPath.push(nextNode); currentNode = nextNode; currentNode.visited = true; costSoFar += minCost; currentGridX = nextGridX; currentGridY = nextGridY; } else break; } return resultPath; }; Node.createNeighbors = function(nodeObject) { var dirs = [ [0, -1], // up [1, 0], // right [0, 1], // Down [-1, 0] // left ]; var arrows = [ 'V', '<', '^', '>' ]; var dirCurrent; var d = 0; var nodeObjectNew; var xNext; var yNext; var gridXNext; var gridYNext; var testSpaceValue; if(typeof nodeObject === 'undefined' || nodeObject.cost >= range) return; if((nodeObject.gridX + nodeObject.gridY) % 2 === 0) { dirs.reverse(); arrows.reverse(); } for(d = 0; d < dirs.length; d++) { dirCurrent = dirs[d]; xNext = nodeObject.x+dirCurrent[0]*nodeSize; yNext = nodeObject.y+dirCurrent[1]*nodeSize; gridXNext = nodeObject.gridX+dirCurrent[0]; gridYNext = nodeObject.gridY+dirCurrent[1]; testSpaceValue = Node.testSpace(xNext, yNext, gridXNext, gridYNext); // Skip spaces that cost beyond range if(typeof testSpaceValue === 'number' && testSpaceValue + nodeObject.cost >= range) continue; if((typeof testSpaceValue === 'boolean' && testSpaceValue) || typeof testSpaceValue === 'number') { nodeObjectNew = Node.addToGrid({ cost: nodeObject.cost + (typeof testSpaceValue === 'number' ? testSpaceValue : 1), costOffset: typeof testSpaceValue === 'number' ? testSpaceValue : 0, x: xNext, y: yNext, gridX: gridXNext, gridY: gridYNext, size: nodeSize, origin: nodeObject, arrow: arrows[d], visited: false }); if(typeof nodeObjectNew !== 'undefined') { nextNodes.queue( nodeObjectNew, getDistance({x: Math.round(targetX), y: Math.round(targetY)}, {x: gridXNext, y: gridYNext})); } } nodeObjectNew = undefined; // Early Exit if(needsExit) break; } }; // Generate grid from start position (function() { var nextNode; var startNode = { x: x, y: y, gridX: Math.round(x/nodeSize), gridY: Math.round(y/nodeSize), size: nodeSize, cost: 0, costOffset: 0, origin: undefined, arrow: '*' }; var initialCost = Node.testSpace(x, y, startNode.gridX, startNode.gridY) if((typeof initialCost === 'boolean' && initialCost) || typeof initialCost === 'number') { Node.addToGrid(startNode); Node.createNeighbors(startNode); while(!nextNodes.isEmpty() && !needsExit) { nextNode = nextNodes.dequeue(); Node.createNeighbors(nextNode); } } })(); return Node.pathToTarget(); }
DSMK2/JS-Collision-Tools
Pathfinding/js/pathfinding.js
JavaScript
gpl-3.0
14,272
/** * Directive to solve the form autofill data */ angular.module('ajpmApp').directive('formAutofillFix', function($timeout) { return function(scope, element, attrs) { element.prop('method', 'post'); if (attrs.ngSubmit) { $timeout(function() { element.unbind('submit').bind( 'submit', function(event) { event.preventDefault(); element.find('input, textarea, select') .trigger('input').trigger('change') .trigger('keydown'); scope.$apply(attrs.ngSubmit); }); }); } }; }); /* this will help in implementing href in button */ angular.module('ajpmApp').directive('clickLink', ['$location', function($location) { return { link: function(scope, element, attrs) { element.on('click', function() { scope.$apply(function() { $location.path(attrs.clickLink); }); }); } } }]); angular.module('ajpmApp').directive("printImageSlider", function() { var d = {}; d.restrict = 'E'; d.templateUrl = '/common/modules/web_page/print_image_slider.html'; d.scope = { paramSliderImageRecords : "=argSliderImageRecords" }; d.link = function (scope, iElement, iAttr, ctrls, transcludeFn) { scope.currentSliderImage=0; }; d.controller = function($scope, $interval) { // store the interval promise in this variable var promise; $scope.playing = false; // starts the interval $scope.playSlider = function() { // stops any running interval to avoid two intervals running at the same time $scope.stopSlider(); // store the interval promise $scope.playing = true; promise = $interval(rotateImageCount, 4000); }; // stops the interval $scope.stopSlider = function() { $scope.playing = false; $interval.cancel(promise); }; // starting the interval by default $scope.playSlider(); // stops the interval when the scope is destroyed, // this usually happens when a route is changed and // the ItemsController $scope gets destroyed. The // destruction of the Controller scope does not // guarantee the stopping of any intervals, you must // be responsible of stopping it when the scope is // is destroyed. $scope.$on('$destroy', function() { $scope.stopSlider(); }); function rotateImageCount() { if ($scope.currentSliderImage < ($scope.paramSliderImageRecords.length -1)) { $scope.currentSliderImage = $scope.currentSliderImage + 1; } else { $scope.currentSliderImage = 0; } }; }; /* counter management functions */ d.increaseCounter = function(counter, limit, step) { if ((counter+step) <= limit) { counter = counter + step; } else { counter = 0; } return counter; }; d.decreaseCounter = function(counter, limit, step) { if ((counter-step) >= limit) counter = counter - step; return counter; }; return d; }); angular.module('ajpmApp').directive("printPanel", function() { var d = {}; d.restrict = 'E'; d.transclude = true; d.templateUrl = '/common/modules/web_page/print_panel.html'; d.scope = { paramTitleOne : "=argTitleOne", paramTitleTwo : "=argTitleTwo", paramTitleThree : "=argTitleThree", paramContentOne : "=argContentOne", paramContentTwo : "=argContentTwo", paramContentThree : "=argContentThree" }; return d; }); /* <print-field ng-model="ef.phone_number" arg-read-tag="'input'" arg-read-tag-type="phone" arg-read-tag-size="" arg-title="'Your Phone Number'" arg-name="'phone_number'" arg-help="'Enter your phone number starting with country code'" arg-required arg-max-length="18" arg-min-length="10" arg-pattern="(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}" arg-pattern-format="'+### ### ### ####'" arg-left-icon="'phone'" arg-right-icon="'home'" ></print-field> */ angular.module('ajpmApp').directive("printField", function($compile) { var d = {}; d.restrict = 'E'; d.require = ['^form', 'ngModel']; d.scope = { paramTitle : "=argTitle", paramName : "=argName", paramHelp : "=argHelp", paramReadTag : "=argReadTag", paramPatternFormat : "=argPatternFormat", paramLeftIcon : "=argLeftIcon", paramRightIcon : "=argRightIcon", paramClass : "=argClass", paramClick : "=argClick", paramNgModel : "=ngModel" }; d.link = function (scope, iElement, iAttr, ctrls, transcludeFn) { scope.form = ctrls[0]; var ngModelCtrl = ctrls[1]; if (typeof iAttr.argMaxLength !== 'undefined') { if (varNotNull(iAttr.argMaxLength)) { scope.paramMaxLength = iAttr.argMaxLength; } else { scope.paramMaxLength = 254; } } else { scope.paramMaxLength = 254; } if (typeof iAttr.argMinLength !== 'undefined') { if (varNotNull(iAttr.argMinLength)) { scope.paramMinLength = iAttr.argMinLength; } else { scope.paramMinLength = 0; } } else { scope.paramMinLength = 0; } if (typeof iAttr.argRequired !== 'undefined') { scope.paramRequired = 'required'; } if (typeof iAttr.argReadTagSize !== 'undefined') { if (varNotNull(iAttr.argReadTagSize)) { scope.paramReadTagSize = iAttr.argReadTagSize; } else { if (scope.paramReadTag == 'input') { scope.paramReadTagSize = 20; } else if (scope.paramReadTag == 'select') { scope.paramReadTagSize = 1; } } } else { scope.paramReadTagSize = 20; } if (typeof iAttr.argPattern !== 'undefined') { if (varNotNull(iAttr.argPattern)) { scope.paramPattern = iAttr.argPattern; } } scope.paramReadTagType = "text"; if (typeof iAttr.argReadTagType !== 'undefined') { if (varNotNull(iAttr.argReadTagType)) { scope.paramReadTagType = iAttr.argReadTagType.toLowerCase(); } } //get the value from ngModel scope.paramNgModel = ngModelCtrl.$viewValue; //set the value of ngModel when the local date property changes scope.$watch('paramNgModel', function(value) { if(ngModelCtrl.$viewValue != value) { ngModelCtrl.$setViewValue(value); } }); //run the ng-click function scope.$watch('paramClick', function(value) { scope.value; }); }; d.templateUrl = function(iElement, iAttr) { return '/common/modules/form/print_' + iAttr.argReadTag.toLowerCase() + '_field.html'; } return d; });
hybr/ajpm
public/common/modules/application/directive.js
JavaScript
gpl-3.0
6,503
import React from 'react'; import PropTypes from 'prop-types'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import MapHOC from '../HOC/MapHOC'; import * as uiActions from '../actions/ui'; const handleMapLoad = _map => window._map = _map; const Map = props => { const handleMapZoom = () => { if (window._map) { const zoom = window._map.getZoom(); props.uiActions.uiZoom(zoom); } }; const handleMarkerMouseEnter = (marker) => { props.uiActions.uiMarkerHover(marker); } const handleMarkerCardMouseLeave = () => { props.uiActions.uiMarkerHover(false); } return ( <div className={`map zoom-${props.store.getState().ui.zoom}`}> <MapHOC {...props} containerElement={ <div className={"map__container"} /> } loadingElement={ <div className={"map__loading"} > <div className={"map__loading-spinner"} /> </div> } mapElement={ <div className={"map__element"} /> } onMapLoad={handleMapLoad} onMarkerCardMouseLeave={handleMarkerCardMouseLeave} onMarkerMouseEnter={handleMarkerMouseEnter} onZoomChanged={handleMapZoom} /> {props.wiretap.updating && <div className={"map__updating"} /> } </div> ); } Map.propTypes = { center: PropTypes.shape({ lat: PropTypes.number, lng: PropTypes.number, }), filter: PropTypes.shape({ hcUnits: PropTypes.bool, }), store: PropTypes.object, ui: PropTypes.object, uiActions: PropTypes.object, wiretap: PropTypes.object, zoom: PropTypes.number, }; function mapDispatchToProps(dispatch) { return { uiActions: bindActionCreators(uiActions, dispatch), }; } function mapStateToProps(state) { return { center: state.map.center, filter: state.filter, wiretap: state.wiretap, zoom: state.map.zoom, ui: state.ui, }; } export default connect( mapStateToProps, mapDispatchToProps )(Map);
IgorSzyporyn/wwiionline-webmap
src/containers/Map.js
JavaScript
gpl-3.0
2,028
var searchData= [ ['daytimelineconfig',['DayTimeLineConfig',['../class_general_health_care_elements_1_1_staff_handling_1_1_day_time_line_config.html',1,'GeneralHealthCareElements::StaffHandling']]], ['delegateavailabilitiesforrequest',['DelegateAvailabilitiesForRequest',['../class_general_health_care_elements_1_1_special_facility_1_1_delegate_availabilities_for_request.html',1,'GeneralHealthCareElements::SpecialFacility']]], ['delegaterequestdocsforassisting',['DelegateRequestDocsForAssisting',['../class_general_health_care_elements_1_1_delegates_1_1_delegate_request_docs_for_assisting.html',1,'GeneralHealthCareElements::Delegates']]], ['delegatesentdocforassistedtreatment',['DelegateSentDocForAssistedTreatment',['../class_general_health_care_elements_1_1_delegates_1_1_delegate_sent_doc_for_assisted_treatment.html',1,'GeneralHealthCareElements::Delegates']]], ['distributions',['Distributions',['../class_simulation_core_1_1_math_tool_1_1_distributions_1_1_distributions.html',1,'SimulationCore::MathTool::Distributions']]], ['drawanalogclockwithdate',['DrawAnalogClockWithDate',['../class_w_p_f_visualization_base_1_1_draw_analog_clock_with_date.html',1,'WPFVisualizationBase']]], ['drawbasetreatmentfacility',['DrawBaseTreatmentFacility',['../class_simulation_w_p_f_visualization_tools_1_1_health_care_objects_1_1_draw_base_treatment_facility.html',1,'SimulationWPFVisualizationTools::HealthCareObjects']]], ['drawdoctor',['DrawDoctor',['../class_wpf_health_care_objects_1_1_draw_doctor.html',1,'WpfHealthCareObjects']]], ['drawdynamicholdingentity',['DrawDynamicHoldingEntity',['../class_simulation_w_p_f_visualization_tools_1_1_health_care_objects_1_1_draw_dynamic_holding_entity.html',1,'SimulationWPFVisualizationTools::HealthCareObjects']]], ['drawingobject',['DrawingObject',['../class_w_p_f_visualization_base_1_1_drawing_object.html',1,'WPFVisualizationBase']]], ['drawingobjectforentity',['DrawingObjectForEntity',['../class_simulation_w_p_f_visualization_tools_1_1_drawing_object_for_entity.html',1,'SimulationWPFVisualizationTools']]], ['drawingobjectstring',['DrawingObjectString',['../class_w_p_f_visualization_base_1_1_drawing_object_string.html',1,'WPFVisualizationBase']]], ['drawingoncoordinatesystem',['DrawingOnCoordinateSystem',['../class_w_p_f_visualization_base_1_1_drawing_on_coordinate_system.html',1,'WPFVisualizationBase']]], ['drawingrectangleobject',['DrawingRectangleObject',['../class_w_p_f_visualization_base_1_1_basic_objects_1_1_drawing_rectangle_object.html',1,'WPFVisualizationBase::BasicObjects']]], ['drawmrictfacility',['DrawMRICTFacility',['../class_simulation_w_p_f_visualization_tools_1_1_health_care_objects_1_1_draw_m_r_i_c_t_facility.html',1,'SimulationWPFVisualizationTools::HealthCareObjects']]], ['drawnurse',['DrawNurse',['../class_wpf_health_care_objects_1_1_draw_nurse.html',1,'WpfHealthCareObjects']]], ['drawobjectline',['DrawObjectLine',['../class_w_p_f_visualization_base_1_1_draw_object_line.html',1,'WPFVisualizationBase']]], ['drawpatient',['DrawPatient',['../class_wpf_health_care_objects_1_1_draw_patient.html',1,'WpfHealthCareObjects']]], ['drawperson',['DrawPerson',['../class_w_p_f_visualization_base_1_1_draw_person.html',1,'WPFVisualizationBase']]], ['drawregisterbooth',['DrawRegisterBooth',['../class_simulation_w_p_f_visualization_tools_1_1_health_care_objects_1_1_draw_register_booth.html',1,'SimulationWPFVisualizationTools::HealthCareObjects']]], ['drawtreatmentfacility',['DrawTreatmentFacility',['../class_wpf_health_care_objects_1_1_draw_treatment_facility.html',1,'WpfHealthCareObjects']]], ['drawxray',['DrawXRay',['../class_simulation_w_p_f_visualization_tools_1_1_health_care_objects_1_1_draw_x_ray.html',1,'SimulationWPFVisualizationTools::HealthCareObjects']]] ];
nikolausfurian/HCDESLib
API/search/classes_3.js
JavaScript
gpl-3.0
3,801
/** * Reaction Accounts handlers * creates a login type "anonymous" * default for all unauthenticated visitors */ Accounts.registerLoginHandler(function (options) { if (!options.anonymous) { return {}; } let loginHandler; let stampedToken = Accounts._generateStampedLoginToken(); let userId = Accounts.insertUserDoc({ services: { anonymous: true }, token: stampedToken.token }); loginHandler = { type: "anonymous", userId: userId }; return loginHandler; }); /** * Accounts.onCreateUser event * adding either a guest or anonymous role to the user on create * adds Accounts record for reaction user profiles * we clone the user into accounts, as the user collection is * only to be used for authentication. * * @see: http://docs.meteor.com/#/full/accounts_oncreateuser */ Accounts.onCreateUser(function (options, user) { const shop = ReactionCore.getCurrentShop(); const shopId = shop._id; const defaultVisitorRole = ["anonymous", "guest", "product", "tag", "index", "cart/checkout", "cart/completed"]; const defaultRoles = ["guest", "account/profile", "product", "tag", "index", "cart/checkout", "cart/completed"]; let roles = {}; let additionals = { profile: {} }; if (!user.emails) user.emails = []; // init default user roles // we won't create users unless we have a shop. if (shop) { // if we don't have user.services we're an anonymous user if (!user.services) { roles[shopId] = shop.defaultVisitorRole || defaultVisitorRole; } else { roles[shopId] = shop.defaultRoles || defaultRoles; // also add services with email defined to user.emails[] for (let service in user.services) { if (user.services[service].email) { let email = { provides: "default", address: user.services[service].email, verified: true }; user.emails.push(email); } if (user.services[service].name) { user.username = user.services[service].name; additionals.profile.name = user.services[service].name; } // TODO: For now we have here instagram, twitter and google avatar cases // need to make complete list if (user.services[service].picture) { additionals.profile.picture = user.services[service].picture; } else if (user.services[service].profile_image_url_https) { additionals.profile.picture = user.services[service]. dprofile_image_url_https; } else if (user.services[service].profile_picture) { additionals.profile.picture = user.services[service].profile_picture; } } } // clone before adding roles let account = Object.assign({}, user, additionals); account.userId = user._id; ReactionCore.Collections.Accounts.insert(account); // send a welcome email to new users, // but skip the first default admin user // (default admins already get a verification email) if (!(Meteor.users.find().count() === 0)) { Meteor.call("accounts/sendWelcomeEmail", shopId, user._id); } // assign default user roles user.roles = roles; // run onCreateUser hooks // (the user object must be returned by all callbacks) const userDoc = ReactionCore.Hooks.Events.run("onCreateUser", user, options); return userDoc; } }); /** * Accounts.onLogin event * let's remove "anonymous" role, if the login type isn't "anonymous" * @param {Object} options - user account creation options * @fires "cart/mergeCart" Method */ Accounts.onLogin(function (opts) { // run onLogin hooks // (the options object must be returned by all callbacks) options = ReactionCore.Hooks.Events.run("onLogin", opts); // remove anonymous role // all users are guest, but anonymous user don't have profile access // or ability to order history, etc. so ensure its removed upon login. if (options.type !== "anonymous" && options.type !== "resume") { let update = { $pullAll: {} }; update.$pullAll["roles." + ReactionCore.getShopId()] = ["anonymous"]; Meteor.users.update({ _id: options.user._id }, update, { multi: true }); // debug info ReactionCore.Log.debug("removed anonymous role from user: " + options.user._id); // do not call `cart/mergeCart` on methodName === `createUser`, because // in this case `cart/mergeCart` calls from cart publication if (options.methodName === "createUser") return true; // onLogin, we want to merge session cart into user cart. const cart = ReactionCore.Collections.Cart.findOne({ userId: options.user._id }); // for a rare use cases if (typeof cart !== "object") return false; // in current version currentSessionId will be available for anonymous // users only, because it is unknown for me how to pass sessionId when user // logged in const currentSessionId = options.methodArguments && options.methodArguments.length === 1 && options.methodArguments[0].sessionId; // changing of workflow status from now happens within `cart/mergeCart` return Meteor.call("cart/mergeCart", cart._id, currentSessionId); } }); /** * Reaction Account Methods */ Meteor.methods({ /* * check if current user has password */ "accounts/currentUserHasPassword": function () { let user; user = Meteor.users.findOne(Meteor.userId()); if (user.services.password) { return true; } return false; }, /** * accounts/addressBookAdd * @description add new addresses to an account * @param {Object} address - address * @param {String} [accountUserId] - `account.userId` used by admin to edit * users * @return {Object} with keys `numberAffected` and `insertedId` if doc was * inserted */ "accounts/addressBookAdd": function (address, accountUserId) { check(address, ReactionCore.Schemas.Address); check(accountUserId, Match.Optional(String)); // security, check for admin access. We don't need to check every user call // here because we are calling `Meteor.userId` from within this Method. if (typeof accountUserId === "string") { // if this will not be a String - // `check` will not pass it. if (!ReactionCore.hasAdminAccess()) { throw new Meteor.Error(403, "Access denied"); } } this.unblock(); const userId = accountUserId || Meteor.userId(); // required default id if (!address._id) { address._id = Random.id(); } // clean schema ReactionCore.Schemas.Address.clean(address); // if address got shippment or billing default, we need to update cart // addresses accordingly if (address.isShippingDefault || address.isBillingDefault) { const cart = ReactionCore.Collections.Cart.findOne({ userId: userId }); // if cart exists // First amend the cart, if (typeof cart === "object") { if (address.isShippingDefault) { Meteor.call("cart/setShipmentAddress", cart._id, address); } if (address.isBillingDefault) { Meteor.call("cart/setPaymentAddress", cart._id, address); } } // then change the address that has been affected if (address.isShippingDefault) { ReactionCore.Collections.Accounts.update({ "userId": userId, "profile.addressBook.isShippingDefault": true }, { $set: { "profile.addressBook.$.isShippingDefault": false } }); } if (address.isBillingDefault) { ReactionCore.Collections.Accounts.update({ "userId": userId, "profile.addressBook.isBillingDefault": true }, { $set: { "profile.addressBook.$.isBillingDefault": false } }); } } return ReactionCore.Collections.Accounts.upsert({ userId: userId }, { $set: { userId: userId }, $addToSet: { "profile.addressBook": address } }); }, /** * accounts/addressBookUpdate * @description update existing address in user's profile * @param {Object} address - address * @param {String|null} [accountUserId] - `account.userId` used by admin to * edit users * @param {shipping|billing} [type] - name of selected address type * @return {Number} The number of affected documents */ "accounts/addressBookUpdate": function (address, accountUserId, type) { check(address, ReactionCore.Schemas.Address); check(accountUserId, Match.OneOf(String, null, undefined)); check(type, Match.Optional(String)); // security, check for admin access. We don't need to check every user call // here because we are calling `Meteor.userId` from within this Method. if (typeof accountUserId === "string") { // if this will not be a String - // `check` will not pass it. if (!ReactionCore.hasAdminAccess()) { throw new Meteor.Error(403, "Access denied"); } } this.unblock(); const userId = accountUserId || Meteor.userId(); // we need to compare old state of isShippingDefault, isBillingDefault with // new state and if it was enabled/disabled reflect this changes in cart const account = ReactionCore.Collections.Accounts.findOne({ userId: userId }); const oldAddress = account.profile.addressBook.find(function (addr) { return addr._id === address._id; }); // happens when the user clicked the address in grid. We need to set type // to `true` if (typeof type === "string") { Object.assign(address, { [type]: true }); } if (oldAddress.isShippingDefault !== address.isShippingDefault || oldAddress.isBillingDefault !== address.isBillingDefault) { const cart = ReactionCore.Collections.Cart.findOne({ userId: userId }); // Cart should exist to this moment, so we doesn't need to to verify its // existence. if (oldAddress.isShippingDefault !== address.isShippingDefault) { // if isShippingDefault was changed and now it is `true` if (address.isShippingDefault) { // we need to add this address to cart Meteor.call("cart/setShipmentAddress", cart._id, address); // then, if another address was `ShippingDefault`, we need to unset it ReactionCore.Collections.Accounts.update({ "userId": userId, "profile.addressBook.isShippingDefault": true }, { $set: { "profile.addressBook.$.isShippingDefault": false } }); } else { // if new `isShippingDefault` state is false, then we need to remove // this address from `cart.shipping` Meteor.call("cart/unsetAddresses", address._id, userId, "shipping"); } } // the same logic used for billing if (oldAddress.isBillingDefault !== address.isBillingDefault) { if (address.isBillingDefault) { Meteor.call("cart/setPaymentAddress", cart._id, address); ReactionCore.Collections.Accounts.update({ "userId": userId, "profile.addressBook.isBillingDefault": true }, { $set: { "profile.addressBook.$.isBillingDefault": false } }); } else { Meteor.call("cart/unsetAddresses", address._id, userId, "billing"); } } } return ReactionCore.Collections.Accounts.update({ "userId": userId, "profile.addressBook._id": address._id }, { $set: { "profile.addressBook.$": address } }); }, /** * accounts/addressBookRemove * @description remove existing address in user's profile * @param {String} addressId - address `_id` * @param {String} [accountUserId] - `account.userId` used by admin to edit * users * @return {Number|Object} The number of removed documents or error object */ "accounts/addressBookRemove": function (addressId, accountUserId) { check(addressId, String); check(accountUserId, Match.Optional(String)); // security, check for admin access. We don't need to check every user call // here because we are calling `Meteor.userId` from within this Method. if (typeof accountUserId === "string") { // if this will not be a String - // `check` will not pass it. if (!ReactionCore.hasAdminAccess()) { throw new Meteor.Error(403, "Access denied"); } } this.unblock(); const userId = accountUserId || Meteor.userId(); // remove this address in cart, if used, before completely removing Meteor.call("cart/unsetAddresses", addressId, userId); return ReactionCore.Collections.Accounts.update({ "userId": userId, "profile.addressBook._id": addressId }, { $pull: { "profile.addressBook": { _id: addressId } } }); }, /** * accounts/inviteShopMember * invite new admin users * (not consumers) to secure access in the dashboard * to permissions as specified in packages/roles * @param {String} shopId - shop to invite user * @param {String} email - email of invitee * @param {String} name - name to address email * @returns {Boolean} returns true */ "accounts/inviteShopMember": function (shopId, email, name) { let currentUserName; let shop; let token; let user; let userId; check(shopId, String); check(email, String); check(name, String); this.unblock(); shop = ReactionCore.Collections.Shops.findOne(shopId); if (!ReactionCore.hasPermission("reaction-accounts", Meteor.userId(), shopId)) { throw new Meteor.Error(403, "Access denied"); } ReactionCore.configureMailUrl(); // don't send account emails unless email server configured if (!process.env.MAIL_URL) { ReactionCore.Log.info(`Mail not configured: suppressing invite email output`); return true; } // everything cool? invite user if (shop && email && name) { let currentUser = Meteor.user(); if (currentUser) { if (currentUser.profile) { currentUserName = currentUser.profile.name; } else { currentUserName = currentUser.username; } } else { currentUserName = "Admin"; } user = Meteor.users.findOne({ "emails.address": email }); ReactionCore.i18nextInitForServer(i18next); if (!user) { userId = Accounts.createUser({ email: email, username: name }); user = Meteor.users.findOne(userId); if (!user) { throw new Error("Can't find user"); } token = Random.id(); Meteor.users.update(userId, { $set: { "services.password.reset": { token: token, email: email, when: new Date() } } }); SSR.compileTemplate("accounts/inviteShopMember", ReactionEmailTemplate("accounts/inviteShopMember")); try { return Email.send({ to: email, from: `${shop.name} <${shop.emails[0].address}>`, subject: i18next.t('accountsUI.mails.invited.subject', {shopName: shop.name, defaultValue: `You have been invited to join ${shop.name}`}), html: SSR.render("accounts/inviteShopMember", { homepage: Meteor.absoluteUrl(), shop: shop, currentUserName: currentUserName, invitedUserName: name, url: Accounts.urls.enrollAccount(token) }) }); } catch (_error) { throw new Meteor.Error(403, "Unable to send invitation email."); } } else { SSR.compileTemplate("accounts/inviteShopMember", ReactionEmailTemplate("accounts/inviteShopMember")); try { return Email.send({ to: email, from: `${shop.name} <${shop.emails[0].address}>`, subject: i18next.t('accountsUI.mails.invited.subject', {shopName: shop.name, defaultValue: `You have been invited to join ${shop.name}`}), html: SSR.render("accounts/inviteShopMember", { homepage: Meteor.absoluteUrl(), shop: shop, currentUserName: currentUserName, invitedUserName: name, url: Meteor.absoluteUrl() }) }); } catch (_error) { throw new Meteor.Error(403, "Unable to send invitation email."); } } } else { throw new Meteor.Error(403, "Access denied"); } return true; }, /** * accounts/sendWelcomeEmail * send an email to consumers on sign up * @param {String} shopId - shopId of new User * @param {String} userId - new userId to welcome * @returns {Boolean} returns boolean */ "accounts/sendWelcomeEmail": function (shopId, userId) { check(shopId, String); check(userId, String); this.unblock(); const user = ReactionCore.Collections.Accounts.findOne(userId); const shop = ReactionCore.Collections.Shops.findOne(shopId); let shopEmail; // anonymous users arent welcome here if (!user.emails || !user.emails.length > 0) { return true; } let userEmail = user.emails[0].address; // provide some defaults for missing shop email. if (!shop.emails) { shopEmail = `${shop.name}@localhost`; ReactionCore.Log.debug(`Shop email address not configured. Using ${shopEmail}`); } else { shopEmail = shop.emails[0].address; } // configure email ReactionCore.configureMailUrl(); // don't send account emails unless email server configured if (!process.env.MAIL_URL) { ReactionCore.Log.info(`Mail not configured: suppressing welcome email output`); return true; } ReactionCore.i18nextInitForServer(i18next); ReactionCore.Log.info("sendWelcomeEmail: i18n server test:", i18next.t('accountsUI.mails.welcome.subject')); // fetch and send templates SSR.compileTemplate("accounts/sendWelcomeEmail", ReactionEmailTemplate("accounts/sendWelcomeEmail")); try { return Email.send({ to: userEmail, from: `${shop.name} <${shopEmail}>`, subject: i18next.t('accountsUI.mails.welcome.subject', {shopName: shop.name, defaultValue: `Welcome to ${shop.name}!`}), html: SSR.render("accounts/sendWelcomeEmail", { homepage: Meteor.absoluteUrl(), shop: shop, user: Meteor.user() }) }); } catch (e) { ReactionCore.Log.warn("Unable to send email, check configuration and port.", e); } }, /** * accounts/addUserPermissions * @param {String} userId - userId * @param {Array|String} permissions - * Name of role/permission. If array, users * returned will have at least one of the roles * specified but need not have _all_ roles. * @param {String} [group] Optional name of group to restrict roles to. * User"s Roles.GLOBAL_GROUP will also be checked. * @returns {Boolean} success/failure */ "accounts/addUserPermissions": function (userId, permissions, group) { if (!ReactionCore.hasPermission("reaction-accounts", Meteor.userId(), group)) { throw new Meteor.Error(403, "Access denied"); } check(userId, Match.OneOf(String, Array)); check(permissions, Match.OneOf(String, Array)); check(group, Match.Optional(String)); this.unblock(); try { return Roles.addUsersToRoles(userId, permissions, group); } catch (error) { return ReactionCore.Log.info(error); } }, /* * accounts/removeUserPermissions */ "accounts/removeUserPermissions": function (userId, permissions, group) { if (!ReactionCore.hasPermission("reaction-accounts", Meteor.userId(), group)) { throw new Meteor.Error(403, "Access denied"); } check(userId, String); check(permissions, Match.OneOf(String, Array)); check(group, Match.Optional(String, null)); this.unblock(); try { return Roles.removeUsersFromRoles(userId, permissions, group); } catch (error) { ReactionCore.Log.info(error); throw new Meteor.Error(403, "Access Denied"); } }, /** * accounts/setUserPermissions * @param {String} userId - userId * @param {String|Array} permissions - string/array of permissions * @param {String} group - group * @returns {Boolean} returns Roles.setUserRoles result */ "accounts/setUserPermissions": function (userId, permissions, group) { if (!ReactionCore.hasPermission("reaction-accounts", Meteor.userId(), group)) { throw new Meteor.Error(403, "Access denied"); } check(userId, String); check(permissions, Match.OneOf(String, Array)); check(group, Match.Optional(String)); this.unblock(); try { return Roles.setUserRoles(userId, permissions, group); } catch (error) { ReactionCore.Log.info(error); return error; } } });
ScyDev/reaction
packages/reaction-accounts/server/methods/accounts.js
JavaScript
gpl-3.0
21,176
app.service('perfilServicio', function($http){ var perfilServicio = this perfilServicio.perfil = {} perfilServicio.conseguirPerfil = () => { return $http.get('/logeo/cuenta') } perfilServicio.editarPerfil = (perfil) => { return $http.patch('/logeo/cuenta', perfil) } perfilServicio.actualizarPerfil = () => { const pedido = perfilServicio.conseguirPerfil() pedido.then((respuesta) => { perfilServicio.perfil = respuesta.data }) return pedido } })
makmm/manejador-de-tareas
public/servicios/perfil.servicio.js
JavaScript
gpl-3.0
499
/** * jspsych-survey-text * a jspsych plugin for free response survey questions * * Josh de Leeuw * * documentation: docs.jspsych.org * */ (function($) { jsPsych['survey-text'] = (function() { var plugin = {}; plugin.create = function(params) { //params = jsPsych.pluginAPI.enforceArray(params, ['data']); var trials = []; for (var i = 0; i < params.questions.length; i++) { var rows = [], cols = []; if(typeof params.rows == 'undefined' || typeof params.columns == 'undefined'){ for(var j = 0; j < params.questions[i].length; j++){ cols.push(40); rows.push(1); } } trials.push({ preamble: typeof params.preamble == 'undefined' ? "" : params.preamble[i], questions: params.questions[i], rows: typeof params.rows == 'undefined' ? rows : params.rows[i], columns: typeof params.columns == 'undefined' ? cols : params.columns[i] }); } return trials; }; plugin.trial = function(display_element, trial) { // if any trial variables are functions // this evaluates the function and replaces // it with the output of the function trial = jsPsych.pluginAPI.evaluateFunctionParameters(trial); // show preamble text display_element.append($('<div>', { "id": 'jspsych-survey-likert-preamble', "class": 'jspsych-survey-likert-preamble' })); $('#jspsych-survey-likert-preamble').html(trial.preamble); // add questions for (var i = 0; i < trial.questions.length; i++) { // create div display_element.append($('<div>', { "id": 'jspsych-survey-text-' + i, "class": 'jspsych-survey-text-question' })); // add question text $("#jspsych-survey-text-" + i).append('<p class="jspsych-survey-text">' + trial.questions[i] + '</p>'); // add text box $("#jspsych-survey-text-" + i).append('<textarea name="#jspsych-survey-text-response-' + i + '" cols="'+trial.columns[i]+'" rows="'+trial.rows[i]+'"></textarea>'); } // add submit button display_element.append($('<button>', { 'id': 'jspsych-survey-text-next', 'class': 'jspsych-survey-text' })); $("#jspsych-survey-text-next").html('Abschicken'); $("#jspsych-survey-text-next").click(function() { // measure response time var endTime = (new Date()).getTime(); var response_time = endTime - startTime; // create object to hold responses var question_data = {}; $("div.jspsych-survey-text-question").each(function(index) { var id = "Q" + index; var val = $(this).children('textarea').val(); var obje = {}; obje[id] = val; $.extend(question_data, obje); }); // save data jsPsych.data.write({ "rt": response_time, "responses": JSON.stringify(question_data) }); display_element.html(''); // next trial jsPsych.finishTrial(); }); var startTime = (new Date()).getTime(); }; return plugin; })(); })(jQuery);
hartmast/sprachgeschichte
experimente/plugins/jspsych-survey-text.js
JavaScript
gpl-3.0
3,224
/* GCompris - target.js * * Copyright (C) 2014 Bruno coudoin * * Authors: * Bruno Coudoin <bruno.coudoin@gcompris.net> (GTK+ version) * Bruno Coudoin <bruno.coudoin@gcompris.net> (Qt Quick port) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <https://www.gnu.org/licenses/>. */ .pragma library .import QtQuick 2.6 as Quick var url = "qrc:/gcompris/src/activities/target/resource/" var colors = [ "#ff1b00", "#7edee2", "#f1f500", "#3dff00", "#b7d2d4", "#6db5ba" ] var levels = [ [ {size: 50, color: colors[0], score: 5}, {size: 100, color: colors[1], score: 4}, {size: 150, color: colors[2], score: 3}, {size: 200, color: colors[3], score: 2}, {size: 250, color: colors[4], score: 1} ], [ {size: 50, color: colors[0], score: 10}, {size: 100, color: colors[1], score: 5}, {size: 150, color: colors[2], score: 3}, {size: 200, color: colors[3], score: 2}, {size: 250, color: colors[4], score: 1} ], [ {size: 50, color: colors[0], score: 20}, {size: 100, color: colors[1], score: 10}, {size: 150, color: colors[2], score: 8}, {size: 200, color: colors[3], score: 5}, {size: 250, color: colors[4], score: 3}, {size: 300, color: colors[5], score: 2} ], [ {size: 50, color: colors[0], score: 30}, {size: 100, color: colors[1], score: 20}, {size: 150, color: colors[2], score: 10}, {size: 200, color: colors[3], score: 5}, {size: 250, color: colors[4], score: 3}, {size: 300, color: colors[5], score: 2} ], [ {size: 50, color: colors[0], score: 50}, {size: 100, color: colors[1], score: 30}, {size: 150, color: colors[2], score: 20}, {size: 200, color: colors[3], score: 8}, {size: 250, color: colors[4], score: 3}, {size: 300, color: colors[5], score: 2} ], [ {size: 50, color: colors[0], score: 100}, {size: 100, color: colors[1], score: 50}, {size: 150, color: colors[2], score: 12}, {size: 200, color: colors[3], score: 8}, {size: 250, color: colors[4], score: 3}, {size: 300, color: colors[5], score: 2} ], [ {size: 50, color: colors[0], score: 500}, {size: 100, color: colors[1], score: 100}, {size: 150, color: colors[2], score: 50}, {size: 200, color: colors[3], score: 15}, {size: 250, color: colors[4], score: 7}, {size: 300, color: colors[5], score: 3} ], [ {size: 50, color: colors[0], score: 64}, {size: 100, color: colors[1], score: 32}, {size: 150, color: colors[2], score: 16}, {size: 200, color: colors[3], score: 8}, {size: 250, color: colors[4], score: 4}, {size: 300, color: colors[5], score: 2} ] ] var currentLevel = 0 var numberOfLevel = levels.length var items function start(items_) { items = items_ currentLevel = 0 items.currentSubLevel = 0 items.numberOfSubLevel = 5 initLevel() } function stop() { } function initLevel() { items.bar.level = currentLevel + 1 items.targetModel.clear() items.arrowFlying = false for(var i = levels[currentLevel].length - 1; i >= 0 ; --i) { items.targetModel.append(levels[currentLevel][i]) } // Reset the arrows first items.nbArrow = 0 items.nbArrow = Math.min(currentLevel + 3, 6) items.targetItem.start() items.userEntry.text = "" } function nextSubLevel() { if(items.numberOfSubLevel <= ++items.currentSubLevel ) { nextLevel() } else { initLevel(); } } function nextLevel() { items.currentSubLevel = 0 if(numberOfLevel <= ++currentLevel ) { currentLevel = 0 } initLevel(); } function previousLevel() { items.currentSubLevel = 0 if(--currentLevel < 0) { currentLevel = numberOfLevel - 1 } initLevel(); }
bdoin/GCompris-qt
src/activities/target/target.js
JavaScript
gpl-3.0
5,128
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'removeformat', 'sr', { toolbar: 'Уклони форматирање' } );
ernestbuffington/PHP-Nuke-Titanium
includes/wysiwyg/ckeditor/plugins/removeformat/lang/sr.js
JavaScript
gpl-3.0
266
function search() { let searchText = $('#searchText').val(); let matchedElements = $(`#towns li:contains('${searchText}')`); $('#towns li').css('font-weight', ''); matchedElements.css('font-weight', 'bold'); $('#result').text(matchedElements.length + ' matches found.'); }
kostovhg/SoftUni
JSCore/JSAdvanced/d_JQuery_lab/b_SearchInList/search.js
JavaScript
gpl-3.0
293
function SCXMLEventProcessor() {} SCXMLEventProcessor.toXML = function(event, data) { if(!data) data = {}; var propertyNodes = ""; for ( var key in data) { propertyNodes += '<scxml:property name="' + key +'">' + JSON.stringify(data[key]) +'</scxml:property>'; } return '<scxml:message language="json" name="' + event +'" sendid="" source="" sourcetype="javascript" target="" type="scxml" ' + 'version="1.0" xmlns:scxml="http://www.w3.org/2005/07/scxml"><scxml:payload>' + propertyNodes +'</scxml:payload></scxml:message>'; } SCXMLEventProcessor.fromXML = function(xml) { if (typeof xml == "string" && window.DOMParser) { parser = new DOMParser(); xmlDoc = parser.parseFromString(xml, "text/xml"); } else if(typeof xml == "string")// Internet Explorer { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.loadXML(xml); } else { xmlDoc = xml; } var output = {}; for ( var i = 0; i < xmlDoc.firstChild.attributes.length; i++) { var attr = xmlDoc.firstChild.attributes[i]; output[attr.name] = attr.nodeValue; } var data = {}; var propNodes = xmlDoc.getElementsByTagNameNS("http://www.w3.org/2005/07/scxml", "property") for ( var i = 0; i < propNodes.length; i++) { var prop = propNodes[i]; if(output["language"] == "json") { data[prop.attributes[0].nodeValue] = JSON.parse(prop.firstChild.nodeValue); } else { data[prop.attributes[0].nodeValue] = prop.firstChild.nodeValue; } } output["data"] = data; return output; }
jroxendal/PySCXML
examples/scxml_sandbox/SCXMLEventProcessor.js
JavaScript
gpl-3.0
1,518
#pragma strict var finalPos : Vector3; var speedRate = 10.0; function Start () { while(transform.position != finalPos) { transform.position = Vector3.MoveTowards(transform.position, finalPos, speedRate * Time.deltaTime); yield WaitForSeconds(0.001); } }
VesuviusEntertainment/ProjectCircuitry
ProjectCircuitry/Assets/Scripts/Misc/MoveCamera.js
JavaScript
gpl-3.0
260
/** * JavaScript permettant de vérifier les formulires */ function validate() { // On commence par effacer tous les spanErreur de la page (s'ils existent) deleteAllError(); console.log('----Entrée dans validate---'); // Initialisation de la valeur de retour var retour = false; if (verifCompanyName() & verifCompanyCity() & verifPostalCode() & verifSecteur() & verifSiteWeb() & verifLangage() ) { retour = true; } else { retour = false; } return retour; } /** * Permet de vérifier que le nom de l'entreprise est bien renseigné * * @returns boolean */ function verifCompanyName() { // Récupération du nom de l'entreprise à partir du formulaire deleteAllError(); var companyNameForm = document.companyForm.companyName.value; console.log(companyNameForm); // Test pour vérifier que le nom a bien été récupéré // console.log('Nom entreprise: ' + companyNameForm); if (companyNameForm == null || companyNameForm == '') { document.getElementById("companyName").setAttribute("style", "border:1px solid red"); messErreur("companyName", " Veuillez renseigner ce champ"); return false; } else { return true; } } /** * Permet de vérifier si la ville de l'entreprise a bien été renseignée * * @return boolean * */ function verifCompanyCity() { // Récupération du nom de la ville à partir du formulaire var companyCityForm = document.companyForm.companyCity.value; // Test pour la récupération de la ville // console.log('Ville: ' + companyCityForm); if (companyCityForm == null || companyCityForm == '') { document.getElementById("companyCity").setAttribute("style", "border:1px solid red"); messErreur("companyCity", " Veuillez renseigner ce champ"); return false; } else { return true; } } /** * Vérification du code postal : s'il est renseigné et si son format est bien de * la forme 5 chiffres de 0 à 9 (avec prise en compte des départements corses) * * @returns {Boolean} * */ function verifPostalCode() { // Récupération de la valeur du code postal à partir du formulaire var companyPostalCodeForm = document.companyForm.companyPostalCode.value; // Test pour vérification récupération code postal // console.log('Code postal: ' + companyPostalCodeForm); // Définition d'une expression régulière pour vérifier le code postal var regex = /^((0[1-9])|([1-8][0-9])|(9[0-8])|(2A)|(2B))[0-9]{3}$/; if (companyPostalCodeForm == null || companyPostalCodeForm == '') { document.getElementById("companyPostalCode").setAttribute("style", "border:1px solid red"); messErreur("companyPostalCode", " Veuillez renseigner ce champ!"); return false; } else if (!regex.test(companyPostalCodeForm)) { messErreur("companyPostalCode", " Le code postal n'est pas au bon format (5 chiffres)"); return false; } else { return true; } } /** * Vérifie qu'un langage a bien été renseignée * * @returns boolean */ function verifLangage() { var selectElmt = document.getElementById("languages"); var element = selectElmt.options.lenght; console.log(element); if (element == undefined) { return true; } else { document.getElementById("languages").setAttribute("style", "border:1px solid red"); messErreur("languages", " Veuillez selectionner un langage informatique"); return false; } } /** * Vérifie que le secteur a bien été renseigné * * @returns boolean */ function verifSecteur() { // Récupération du secteur renseigné dans le formulaire var companySectorForm = document.companyForm.companySector.value; if (companySectorForm == null || companySectorForm == '') { document.getElementById("companySector").setAttribute('style', 'border:1px solid red'); messErreur("companySector", " Veuillez renseigner ce champ") return false; } else { return true; } } /** * Vérifie que le site web est bien renseigné * * @returns boolean */ function verifSiteWeb() { // Récupération du site Web renseigné dans le formulaire var companyWebSiteForm = document.companyForm.companyWebSite.value; // Test pour vérifier que l'on a bien récupérer le site Web // console.log("site web: " + companyWebSiteForm); if (companyWebSiteForm == null || companyWebSiteForm == '') { document.getElementById("companyWebSite").setAttribute('style', 'border:1px solid red'); messErreur("companyWebSite", " Veuillez renseigner ce champ") return false; } else { return true; } } ///** // * Permet de vérifier que le nom de l'entreprise a rechercher est bien renseigné // * Utilisé dans la jsp companySearchList // * // * @returns company // */ //function selectCompany() { // console.log("---- Dans méthode --- "); // var selectElmt = document.getElementById("companiesSelec"); // var company = selectElmt.options[selectElmt.selectedIndex].value; // console.log(company); // return company; //} /** * Permet de supprimer tous les spanErreurs de la page * @author: Anaïs * @version: 22/11/2016 * */ function deleteAllError() { var link = document.querySelectorAll('.spanErreur'); if (link != null) { for (i = 0; i < link.length; i++) { var element = link.item(i); element.parentNode.removeChild(element); } } } /** * Fonction qui permet de supprimer le span erreur associée à l'élement passé en * entrée Elle est utilisée lors de la perte de focus du champ en paramètre * * @param element */ function changeElement(element) { var link = document.querySelector('.spanErreur'); console.log(link); link.parentNode.removeChild(link); console.log(element); var idel = element.id; console.log(idel); // TODO switch pour les différentes valeurs que pourra prendre id var elem = document.getElementById(idel); elem.setAttribute("style", "border:1px solid"); } /** * Permet d'indiquer les champs manquants à l'utilisateur (coloration de la * bordure de l'élément passé en paramètre) et le texte à afficher * * @param idElement * @param text * @returns */ function messErreur(idElement, text) { var afficheErreur = document.createElement('span'); afficheErreur.setAttribute('class', 'spanErreur') afficheErreur.setAttribute("style", "color : red"); var txt = document.createTextNode(text); afficheErreur.appendChild(txt); var nodeParent = document.getElementById(idElement); nodeParent.parentNode.insertBefore(afficheErreur, nodeParent.nextSibling); } /** * Pour reset le formulaire * * @returns */ function reset() { deleteAllError(); }
CDI-Enterprise/ecf-16035-b
WebContent/JavaScript/company.js
JavaScript
gpl-3.0
6,728
import AppDispatcher from '../dispatcher/AppDispatcher'; import Constants from '../constants/AppConstants'; import api from '../api'; const Actions = { loadUsers() { AppDispatcher.dispatch({ type: Constants.LOAD_USER_REQUEST }); api.listUsers() .then(({ data }) => AppDispatcher.dispatch({ type: Constants.LOAD_USER_SUCCESS, users: data }) ) .catch(err => AppDispatcher.dispatch({ type: Constants.LOAD_USER_FAIL, error: err }) ); }, loadUser(id) { AppDispatcher.dispatch({ type: Constants.LOAD_USER_REQUEST }); api.getUser(id) .then(({ data }) => AppDispatcher.dispatch({ type: Constants.LOAD_USER_SUCCESS, users: data }) ) .catch(err => AppDispatcher.dispatch({ type: Constants.LOAD_USER_FAIL, error: err }) ); }, createUser(note) { api.createUser(note) .then(() => this.loadUsers() ) .catch(err => console.error(err) ); }, updateUser(note) { api.updateUser(note) .then(() => this.loadUsers() ) .catch(err => console.error(err) ); }, loadProducts() { AppDispatcher.dispatch({ type: Constants.LOAD_PRODUCT_REQUEST }); api.listProducts() .then(({ data }) => AppDispatcher.dispatch({ type: Constants.LOAD_PRODUCT_SUCCESS, products: data }) ) .catch(err => AppDispatcher.dispatch({ type: Constants.LOAD_PRODUCT_FAIL, error: err }) ); }, loadProduct(id) { AppDispatcher.dispatch({ type: Constants.LOAD_PRODUCT_REQUEST }); api.getProduct(id) .then(({ data }) => AppDispatcher.dispatch({ type: Constants.LOAD_PRODUCT_SUCCESS, products: data }) ) .catch(err => AppDispatcher.dispatch({ type: Constants.LOAD_PRODUCT_FAIL, error: err }) ); }, createProduct(note) { api.createProduct(note) .then(() => this.loadProducts() ) .catch(err => console.error(err) ); }, deleteProduct(noteId) { api.deleteProduct(noteId) .then(() => this.loadProducts() ) .catch(err => console.error(err) ); } }; export default Actions;
iilinegor/auto-repair-shop
src/actions/actions.js
JavaScript
gpl-3.0
2,856
$("#buzzerOn" ).click(function() { $.getJSON("/api/set?buzzer=1", function(data) { console.log(data); });}); $("#buzzerOff" ).click(function() { $.getJSON("/api/set?buzzer=0", function(data) { console.log(data); });}); $("#prickOn" ).click(function() { $.getJSON("/api/set?prick=1", function(data) { console.log(data); });}); $("#prickOff" ).click(function() { $.getJSON("/api/set?prick=0", function(data) { console.log(data); });}); $("#pumpOn" ).click(function() { $.getJSON("/api/set?pump=1", function(data) { console.log(data); });}); $("#pumpOff" ).click(function() { $.getJSON("/api/set?pump=0", function(data) { console.log(data); });}); $("#blowing1On" ).click(function() { $.getJSON("/api/set?blowing1=1", function(data) { console.log(data); });}); $("#blowing1Off" ).click(function() { $.getJSON("/api/set?blowing1=0", function(data) { console.log(data); });}); $("#blowing2On" ).click(function() { $.getJSON("/api/set?blowing2=1", function(data) { console.log(data); });}); $("#blowing2Off" ).click(function() { $.getJSON("/api/set?blowing2=0", function(data) { console.log(data); });}); $("#vacuum1On" ).click(function() { $.getJSON("/api/set?vacuum1=1", function(data) { console.log(data); });}); $("#vacuum1Off" ).click(function() { $.getJSON("/api/set?vacuum1=0", function(data) { console.log(data); });}); $("#vacuum2On" ).click(function() { $.getJSON("/api/set?vacuum2=1", function(data) { console.log(data); });}); $("#vacuum2Off" ).click(function() { $.getJSON("/api/set?vacuum2=0", function(data) { console.log(data); });}); $("#ledsOn" ).click(function() { $.getJSON("/api/set?leds=1", function(data) { console.log(data); });}); $("#ledsOff" ).click(function() { $.getJSON("/api/set?leds=0", function(data) { console.log(data); });}); $("#yPlus" ).click(function() { $.getJSON("/api/move?StepY=10", function(data) { console.log(data); });}); $("#yMinus" ).click(function() { $.getJSON("/api/move?StepY=-10", function(data) { console.log(data); });}); $("#xPlus" ).click(function() { $.getJSON("/api/move?StepX=10", function(data) { console.log(data); });}); $("#xMinus" ).click(function() { $.getJSON("/api/move?StepX=-10", function(data) { console.log(data); });}); $("#stopAll" ).click(function() { $.getJSON("/api/move?StopAll=1", function(data) { console.log(data); });}); $("#home" ).click(function() { $.getJSON("/api/home", function(data) { console.log(data); });});
TVM802/TVM802-WEB-API
static/js/main.js
JavaScript
gpl-3.0
2,427
/* globals ElGatoEnLaCalle */ import bloques from 'pilas-engine-bloques/actividades/bloques'; var {AccionBuilder,Procedimiento} = bloques; var Saludar = AccionBuilder.build({ descripcion: 'Saludar', icono: 'icono.saludar.png', comportamiento: 'ComportamientoAnimado', argumentos: '{nombreAnimacion: "saludando"}', }); var AbrirOjos = AccionBuilder.build({ descripcion: 'Abrir ojos', icono: 'icono.abrirOjos.png', comportamiento: 'AnimarSiNoEstoyYa', argumentos: '{nombreAnimacion: "abrirOjos", valorEstar: "con los ojos abiertos", descripcionEstar: "estadoOjos", nombreAnimacionSiguiente: "parado", arrancoAsi:true}', }); var CerrarOjos = AccionBuilder.build({ descripcion: 'Cerrar ojos', icono: 'icono.cerrarOjos.png', comportamiento: 'AnimarSiNoEstoyYa', argumentos: '{nombreAnimacion: "cerrarOjos", valorEstar: "con los ojos cerrados", descripcionEstar: "estadoOjos", nombreAnimacionSiguiente: "ojosCerrados"}', }); var Acostarse = AccionBuilder.build({ descripcion: 'Acostarse', icono: 'icono.acostarse.png', comportamiento: 'ModificarRotacionYAltura', argumentos: '{alturaIr: -180 ,rotacionIr: 90, nombreAnimacion:"acostado", valorEstar: "acostado", descripcionEstar: "posicionCuerpo"}', }); var Pararse = AccionBuilder.build({ descripcion: 'Pararse', icono: 'icono.pararse.png', comportamiento: 'ModificarRotacionYAltura', argumentos: '{alturaIr: -150 ,rotacionIr: 0, nombreAnimacion:"acostado", valorEstar: "parado", descripcionEstar: "posicionCuerpo", arrancoAsi:true}', }); var Volver = AccionBuilder.build({ descripcion: 'Volver', icono: '../../iconos/izquierda.png', comportamiento: 'MovimientoAnimado', argumentos: '{direccion: new Direct(-1,0), distancia: 50}', }); var Avanzar = AccionBuilder.build({ descripcion: 'Avanzar', icono: '../../iconos/derecha.png', comportamiento: 'MovimientoAnimado', argumentos: '{direccion: new Direct(1,0), distancia: 50}', }); var Soniar = AccionBuilder.build({ descripcion: 'Soñar', icono: 'icono.soniar.png', comportamiento: 'Pensar', argumentos: '{mensaje: "ZZzzZzZ..." }', }); export default { nombre: 'El gato en la calle', id: 'ElGatoEnLaCalle', enunciado: 'Hacé que el gato avance un paso, se duerma, se despierte, salude y vuelva a su lugar.', consignaInicial: 'Se pueden crear nuevas acciones en Procedimientos definiendo nuevos bloques que incluyan otras acciones.', esDeExploracion: true, escena: ElGatoEnLaCalle, puedeComentar: false, puedeDesactivar: false, puedeDuplicar: false, bloques: [Procedimiento,Saludar,Avanzar,Volver,AbrirOjos,CerrarOjos,Acostarse,Pararse,Soniar], };
sawady/pilas-engine-bloques
app/actividades/actividadElGatoEnLaCalle.js
JavaScript
gpl-3.0
2,636
function generateTopicsTree(rawData) { var data = Defiant.getSnapshot(rawData); var topicSessions = JSON.search(data, '/*/sessions[(./topics[(id)])]'); var topics = _(JSON.search(data, '/*/sessions/topics[(id)]')).uniq(_.property('id')).sortBy('id').value(); // var noTopicSessions = JSON.search(data, '/*/sessions[not(./topics)]'); var noTopicSessions = JSON.search(data, '/*/sessions[(./topics[not(id)])]'); _.each(topicSessions, function(session){ if(session.time && !_.isDate(session.time)){ session.time = new Date(session.time); } }); _.each(noTopicSessions, function(session){ if(session.time && !_.isDate(session.time)){ session.time = new Date(session.time); } }); var topicsTree = _.flatten([ _.map(topics, function (topic) { return { topic: topic, name: topic.name, sessions: _.filter(topicSessions, function (session) { return _.find(session.topics, topic); }) } }), _.map(noTopicSessions, function (session) { return { name: session.name, sessions: [session] } }) ]); return (topicsTree); }
meiriko/confttDisplay
src/list/build-tree.js
JavaScript
gpl-3.0
1,304
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'flash', 'ka', { access: 'სკრიპტის წვდომა', accessAlways: 'ყოველთვის', accessNever: 'არასდროს', accessSameDomain: 'იგივე დომენი', alignAbsBottom: 'ჩარჩოს ქვემოთა ნაწილის სწორება ტექსტისთვის', alignAbsMiddle: 'ჩარჩოს შუა ნაწილის სწორება ტექსტისთვის', alignBaseline: 'საბაზისო ხაზის სწორება', alignTextTop: 'ტექსტი ზემოდან', bgcolor: 'ფონის ფერი', chkFull: 'მთელი ეკრანის დაშვება', chkLoop: 'ჩაციკლვა', chkMenu: 'Flash-ის მენიუს დაშვება', chkPlay: 'ავტო გაშვება', flashvars: 'ცვლადები Flash-ისთვის', hSpace: 'ჰორიზ. სივრცე', properties: 'Flash-ის პარამეტრები', propertiesTab: 'პარამეტრები', quality: 'ხარისხი', qualityAutoHigh: 'მაღალი (ავტომატური)', qualityAutoLow: 'ძალიან დაბალი', qualityBest: 'საუკეთესო', qualityHigh: 'მაღალი', qualityLow: 'დაბალი', qualityMedium: 'საშუალო', scale: 'მასშტაბირება', scaleAll: 'ყველაფრის ჩვენება', scaleFit: 'ზუსტი ჩასმა', scaleNoBorder: 'ჩარჩოს გარეშე', title: 'Flash-ის პარამეტრები', vSpace: 'ვერტ. სივრცე', validateHSpace: 'ჰორიზონტალური სივრცე არ უნდა იყოს ცარიელი.', validateSrc: 'URL არ უნდა იყოს ცარიელი.', validateVSpace: 'ვერტიკალური სივრცე არ უნდა იყოს ცარიელი.', windowMode: 'ფანჯრის რეჟიმი', windowModeOpaque: 'გაუმჭვირვალე', windowModeTransparent: 'გამჭვირვალე', windowModeWindow: 'ფანჯარა' });
tsmaryka/hitc
public/javascripts/ckeditor/plugins/flash/lang/ka.js
JavaScript
gpl-3.0
2,502
import React from 'react'; import Input from './common/Input'; const AuthForm = ({ onChange, credentials, errors, submit }) => ( <div> <Input inputType="email" name="username" placeholder="Имя пользователя" onChange={onChange} value={credentials.username} error={errors.username} /> <Input inputType="password" name="password" placeholder="Пароль" onChange={onChange} value={credentials.pasword} error={errors.password} /> <button className="btn btn-success btn-block" onClick={submit}>Войти</button> </div> ); AuthForm.propTypes = { onChange: React.PropTypes.func.isRequired, submit: React.PropTypes.func.isRequired, credentials: React.PropTypes.object.isRequired, errors: React.PropTypes.object.isRequired, }; export default AuthForm;
a-omsk/Vegreact
js/components/AuthForm.js
JavaScript
gpl-3.0
948
(function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(factory); } else if (typeof exports === 'object') { // Node. Does not work with strict CommonJS, but // only CommonJS-like enviroments that support module.exports, // like Node. module.exports = factory(); } else { // Browser globals (root is window) root.Sparkline = factory(); } }(this, function () { function extend(specific, general){ var obj = {}; for(var key in general){ obj[key] = key in specific ? specific[key] : general[key]; } return obj; } function Sparkline(element, options){ this.element = element; this.options = extend(options || {}, Sparkline.options); init: { this.element.innerHTML = "<canvas></canvas>"; this.canvas = this.element.firstChild; this.context = this.canvas.getContext("2d"); this.ratio = window.devicePixelRatio || 1; if(this.options.tooltip){ this.canvas.style.position = "relative"; this.canvas.onmousemove = showTooltip.bind(this); } } } Sparkline.options = { width: 100, lineColor: "black", lineWidth: 1, startColor: "transparent", endColor: "red", maxColor: "transparent", minColor: "transparent", minValue: null, maxValue: null, dotRadius: 2.5, tooltip: null }; Sparkline.init = function(element, options){ return new Sparkline(element, options); }; Sparkline.draw = function(element, points, options){ var sparkline = new Sparkline(element, options); sparkline.draw(points); return sparkline; } function getY(minValue, maxValue, offsetY, height, index){ var range = maxValue - minValue; if(range == 0){ return offsetY + height/2; }else{ return (offsetY + height) - ((this[index] - minValue) / range)*height; } } function drawDot(radius, color, x, y){ this.beginPath(); this.fillStyle = color; this.arc(x, y, radius, 0, Math.PI*2, false); this.fill(); } function showTooltip(e){ var x = e.offsetX || e.layerX || 0; var delta = ((this.options.width - this.options.dotRadius*2) / (this.points.length - 1)); var index = minmax(0, Math.round((x - this.options.dotRadius)/delta), this.points.length - 1); this.canvas.title = this.options.tooltip(this.points[index], index, this.points); } Sparkline.prototype.draw = function(points){ points = points || []; this.points = points; this.canvas.width = this.options.width * this.ratio; this.canvas.height = this.element.offsetHeight * this.ratio; this.canvas.style.width = this.options.width + 'px'; this.canvas.style.height = this.element.offsetHeight + 'px'; var offsetX = this.options.dotRadius*this.ratio; var offsetY = this.options.dotRadius*this.ratio; var width = this.canvas.width - offsetX*2; var height = this.canvas.height - offsetY*2; var minValue = this.options.minValue || Math.min.apply(Math, points); var maxValue = this.options.maxValue || Math.max.apply(Math, points); var minX = offsetX; var maxX = offsetX; var x = offsetX; var y = getY.bind(points, minValue, maxValue, offsetY, height); var delta = width / (points.length - 1); var dot = drawDot.bind(this.context, this.options.dotRadius*this.ratio); this.context.beginPath(); this.context.strokeStyle = this.options.lineColor; this.context.lineWidth = this.options.lineWidth*this.ratio; this.context.moveTo(x, y(0)); for(var i=1; i<points.length; i++){ x += delta; this.context.lineTo(x, y(i)); minX = points[i] == minValue ? x : minX; maxX = points[i] == maxValue ? x : maxX; } this.context.stroke(); dot(this.options.startColor, offsetX + (points.length == 1 ? width/2 : 0), y(0)); dot(this.options.endColor, offsetX + (points.length == 1 ? width/2 : width), y(i - 1)); dot(this.options.minColor, minX + (points.length == 1 ? width/2 : 0), y(points.indexOf(minValue))); dot(this.options.maxColor, maxX + (points.length == 1 ? width/2 : 0), y(points.indexOf(maxValue))); } function minmax(a, b, c){ return Math.max(a, Math.min(b, c)); } return Sparkline; }));
j9recurses/whirld
vendor/assets/components/sparklines/source/sparkline.js
JavaScript
gpl-3.0
4,766
var searchData= [ ['info',['info',['../structst__waste.html#a643488047849a351240860ad30555cfd',1,'st_waste']]], ['is_5fduplicate',['is_duplicate',['../structrmw__target.html#a510ce2f785554a0d08ae7da0d725717c',1,'rmw_target']]] ];
andy5995/rmw
docs/doxygen/html/search/variables_5.js
JavaScript
gpl-3.0
234
/* * Copyright (C) 2016-2022 phantombot.github.io/PhantomBot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * commandPause.js * * Pause using ANY command */ (function() { var isActive = $.getSetIniDbBoolean('commandPause', 'commandsPaused', false), defaultTime = $.getSetIniDbNumber('commandPause', 'defaultTime', 300), timerId = -1; /** * @function pause * @export $.commandPause * @param {Number} [seconds] */ function pause(seconds) { seconds = (seconds ? seconds : defaultTime); if (isActive) { clearTimeout(timerId); } else { $.setIniDbBoolean('commandPause', 'commandsPaused', true); isActive = true; } timerId = setTimeout(function() { unPause(); }, seconds * 1e3); $.say($.lang.get('commandpause.initiated', $.getTimeString(seconds))); }; /** * @function isPaused * @export $.commandPause * @returns {boolean} */ function isPaused() { return isActive; }; /** * @function clear * @export $.commandPause */ function unPause() { if (timerId > -1) { clearTimeout(timerId); $.setIniDbBoolean('commandPause', 'commandsPaused', false); isActive = false; timerId = -1; $.say($.lang.get('commandpause.ended')); } }; /** * @event event */ $.bind('command', function(event) { var command = event.getCommand(), args = event.getArgs(); /** * @commandpath pausecommands [seconds] - Pause all command usage for the given amount of time. If [seconds] is not present, uses a default value * @commandpath pausecommands clear - Unpause commands */ if (command.equalsIgnoreCase('pausecommands')) { if (args[0] != undefined || args[0] != null) { if (args[0] == 'clear') { unPause(); return; } if (!isNaN(parseInt(args[0]))) { pause(parseInt(args[0])); } else { pause(); } } else { $.say($.lang.get('pausecommands.usage')); } } }); /** * @event initReady */ $.bind('initReady', function() { if ($.bot.isModuleEnabled('./core/commandPause.js')) { $.registerChatCommand('./core/commandPause.js', 'pausecommands', 2); } }); /** Export functions to API */ $.commandPause = { pause: pause, isPaused: isPaused, unPause: unPause, }; })();
PhantomBot/PhantomBot
javascript-source/core/commandPause.js
JavaScript
gpl-3.0
3,333
MODX Evolution 1.0.5 = 88239e0bc76e72d1666ff144cf8ecc01
gohdan/DFC
known_files/hashes/assets/plugins/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/langs/pt_dlg.js
JavaScript
gpl-3.0
56
Meteor.subscribe("allItems"); Meteor.subscribe("communities");
ilri/ckm-cgspace-mass-tweeter
client/lib/subscriptions.js
JavaScript
gpl-3.0
63
import { color } from '../properties'; export default { name: 'Small', type: 'small', style: (props) => ({ display: 'inline-block', fontSize: '12px', lineHeight: '12px', alignItems: 'center', color: color(props) || props.theme.colors.disabled, }), };
eveningkid/react-pur
src/components/Small.js
JavaScript
gpl-3.0
280
var _ = require('lodash'); var debug = require('debug')('route:getMixed'); var moment = require('moment'); var nconf = require('nconf'); var mongo = require('../lib/mongo'); function getMixed(req) { var daysago = _.parseInt(req.params.daysago) || 0; var when = moment().startOf('day').subtract(daysago, 'd'); var min = when.toISOString(); var max = when.add(24, 'h').toISOString(); debug("looking for 'surface' and 'details' %d days ago [%s-%s] campaign %s", daysago, min, max, req.params.cname); var filter = { "when": { "$gte": new Date( min ), "$lt": new Date( max ) }, "campaign": req.params.cname }; return Promise.all([ mongo.read(nconf.get('schema').surface, filter), mongo.read(nconf.get('schema').details, filter) ]) .then(function(mixed) { debug("returning %d from surface and %d details", _.size(mixed[0]), _.size(mixed[1])); return { 'json': mixed } }); }; module.exports = getMixed;
vecna/invi.sible.link
routes/getMixed.js
JavaScript
gpl-3.0
1,069
Ext.define('Onlineshopping.onlineshopping.shared.shop.viewmodel.retailcontext.retail.PaymentInfoViewModel', { "extend": "Ext.app.ViewModel", "alias": "viewmodel.PaymentInfoViewModel", "model": "PaymentInfoModel" });
applifireAlgo/OnlineShopEx
onlineshopping/src/main/webapp/app/onlineshopping/shared/shop/viewmodel/retailcontext/retail/PaymentInfoViewModel.js
JavaScript
gpl-3.0
230
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity 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 General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. import { PROCESS_EXTRACTIONS, FETCH_ADDRESS } from '../background/processor'; import Extractions from './extractions'; export default class Accounts { accounts = {}; store = null; constructor (store) { this.store = store; } find (address) { return this.accounts[address]; } fetch (address) { return this.fetchAddress(address); } processExtractions (extractions) { return this.store.runner.execute(PROCESS_EXTRACTIONS, extractions.toObject()) .then((results) => { const nextExtractions = Extractions.fromObject(results); const addresses = nextExtractions.addresses; // Replace the extractions with the new ones extractions.replaceWith(nextExtractions); // Fetch addresses info return this.fetchAddresses(addresses); }); } fetchAddresses (addresses = []) { const promises = addresses.map((address) => this.fetchAddress(address)); return Promise.all(promises); } fetchAddress (address) { if (!this.accounts[address]) { this.accounts[address] = this.store.runner.execute(FETCH_ADDRESS, address) .then((data) => { this.accounts[address] = data; return data; }); } return Promise.resolve(this.accounts[address]); } }
ethcore/parity-extension
content/accounts.js
JavaScript
gpl-3.0
2,000
'use strict'; const common = require('../common'); var assert = require('assert'); var fork = require('child_process').fork; var args = ['foo', 'bar']; var n = fork(common.fixturesDir + '/child-process-spawn-node.js', args); assert.strictEqual(n.channel, n._channel); assert.deepStrictEqual(args, ['foo', 'bar']); n.on('message', function(m) { console.log('PARENT got message:', m); assert.ok(m.foo); }); // https://github.com/joyent/node/issues/2355 - JSON.stringify(undefined) // returns "undefined" but JSON.parse() cannot parse that... assert.throws(function() { n.send(undefined); }, TypeError); assert.throws(function() { n.send(); }, TypeError); n.send({ hello: 'world' }); n.on('exit', common.mustCall(function(c) { assert.strictEqual(c, 0); }));
TrossSoftwareAndTech/webvt
lib/node-v7.2.0/test/parallel/test-child-process-fork.js
JavaScript
gpl-3.0
767
/** * @author qiao / https://github.com/qiao * @author mrdoob / http://mrdoob.com * @author alteredq / http://alteredqualia.com/ * @author WestLangley / http://github.com/WestLangley * @author erich666 / http://erichaines.com */ /*global THREE, console */ // This set of controls performs orbiting, dollying (zooming), and panning. It maintains // the "up" direction as +Y, unlike the TrackballControls. Touch on tablet and phones is // supported. // // Orbit - left mouse / touch: one finger move // Zoom - middle mouse, or mousewheel / touch: two finger spread or squish // Pan - right mouse, or arrow keys / touch: three finter swipe // // This is a drop-in replacement for (most) TrackballControls used in examples. // That is, include this js file and wherever you see: // controls = new THREE.TrackballControls( camera ); // controls.target.z = 150; // Simple substitute "OrbitControls" and the control should work as-is. THREE.OrbitControls = function ( object, domElement ) { this.object = object; this.domElement = ( domElement !== undefined ) ? domElement : document; // API // Set to false to disable this control this.enabled = true; // "target" sets the location of focus, where the control orbits around // and where it pans with respect to. this.target = new THREE.Vector3(); // center is old, deprecated; use "target" instead this.center = this.target; // This option actually enables dollying in and out; left as "zoom" for // backwards compatibility this.noZoom = false; this.zoomSpeed = 1.0; // Limits to how far you can dolly in and out this.minDistance = 0; this.maxDistance = Infinity; // Set to true to disable this control this.noRotate = false; this.rotateSpeed = 1.0; // Set to true to disable this control this.noPan = false; this.keyPanSpeed = 7.0; // pixels moved per arrow key push // Set to true to automatically rotate around the target this.autoRotate = false; this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60 // How far you can orbit vertically, upper and lower limits. // Range is 0 to Math.PI radians. this.minPolarAngle = 0; // radians this.maxPolarAngle = Math.PI; // radians // How far you can orbit horizontally, upper and lower limits. // If set, must be a sub-interval of the interval [ - Math.PI, Math.PI ]. this.minAzimuthAngle = - Infinity; // radians this.maxAzimuthAngle = Infinity; // radians // Set to true to disable use of the keys this.noKeys = true; // The four arrow keys this.keys = { LEFT: 37, UP: 38, RIGHT: 39, BOTTOM: 40 }; // Mouse buttons this.mouseButtons = { ORBIT: THREE.MOUSE.LEFT, ZOOM: THREE.MOUSE.MIDDLE, PAN: THREE.MOUSE.RIGHT }; //////////// // internals var scope = this; var EPS = 0.000001; var rotateStart = new THREE.Vector2(); var rotateEnd = new THREE.Vector2(); var rotateDelta = new THREE.Vector2(); var panStart = new THREE.Vector2(); var panEnd = new THREE.Vector2(); var panDelta = new THREE.Vector2(); var panOffset = new THREE.Vector3(); var offset = new THREE.Vector3(); var dollyStart = new THREE.Vector2(); var dollyEnd = new THREE.Vector2(); var dollyDelta = new THREE.Vector2(); var theta; var phi; var phiDelta = 0; var thetaDelta = 0; var scale = 1; var pan = new THREE.Vector3(); var lastPosition = new THREE.Vector3(); var lastQuaternion = new THREE.Quaternion(); var STATE = { NONE : -1, ROTATE : 0, DOLLY : 1, PAN : 2, TOUCH_ROTATE : 3, TOUCH_DOLLY : 4, TOUCH_PAN : 5 }; var state = STATE.NONE; // for reset this.target0 = this.target.clone(); this.position0 = this.object.position.clone(); // so camera.up is the orbit axis var quat = new THREE.Quaternion().setFromUnitVectors( object.up, new THREE.Vector3( 0, 1, 0 ) ); var quatInverse = quat.clone().inverse(); // events var changeEvent = { type: 'change' }; var startEvent = { type: 'start'}; var endEvent = { type: 'end'}; this.rotateLeft = function ( angle ) { if ( angle === undefined ) { angle = getAutoRotationAngle(); } thetaDelta -= angle; }; this.rotateUp = function ( angle ) { if ( angle === undefined ) { angle = getAutoRotationAngle(); } phiDelta -= angle; }; // pass in distance in world space to move left this.panLeft = function ( distance ) { var te = this.object.matrix.elements; // get X column of matrix panOffset.set( te[ 0 ], te[ 1 ], te[ 2 ] ); panOffset.multiplyScalar( - distance ); pan.add( panOffset ); }; // pass in distance in world space to move up this.panUp = function ( distance ) { var te = this.object.matrix.elements; // get Y column of matrix panOffset.set( te[ 4 ], te[ 5 ], te[ 6 ] ); panOffset.multiplyScalar( distance ); pan.add( panOffset ); }; // pass in x,y of change desired in pixel space, // right and down are positive this.pan = function ( deltaX, deltaY ) { var element = scope.domElement === document ? scope.domElement.body : scope.domElement; if ( scope.object.fov !== undefined ) { // perspective var position = scope.object.position; var offset = position.clone().sub( scope.target ); var targetDistance = offset.length(); // half of the fov is center to top of screen targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 ); // we actually don't use screenWidth, since perspective camera is fixed to screen height scope.panLeft( 2 * deltaX * targetDistance / element.clientHeight ); scope.panUp( 2 * deltaY * targetDistance / element.clientHeight ); } else if ( scope.object.top !== undefined ) { // orthographic scope.panLeft( deltaX * (scope.object.right - scope.object.left) / element.clientWidth ); scope.panUp( deltaY * (scope.object.top - scope.object.bottom) / element.clientHeight ); } else { // camera neither orthographic or perspective console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' ); } }; this.dollyIn = function ( dollyScale ) { if ( dollyScale === undefined ) { dollyScale = getZoomScale(); } scale /= dollyScale; }; this.dollyOut = function ( dollyScale ) { if ( dollyScale === undefined ) { dollyScale = getZoomScale(); } scale *= dollyScale; }; this.update = function () { var position = this.object.position; offset.copy( position ).sub( this.target ); // rotate offset to "y-axis-is-up" space offset.applyQuaternion( quat ); // angle from z-axis around y-axis theta = Math.atan2( offset.x, offset.z ); // angle from y-axis phi = Math.atan2( Math.sqrt( offset.x * offset.x + offset.z * offset.z ), offset.y ); if ( this.autoRotate && state === STATE.NONE ) { this.rotateLeft( getAutoRotationAngle() ); } theta += thetaDelta; phi += phiDelta; // restrict theta to be between desired limits theta = Math.max( this.minAzimuthAngle, Math.min( this.maxAzimuthAngle, theta ) ); // restrict phi to be between desired limits phi = Math.max( this.minPolarAngle, Math.min( this.maxPolarAngle, phi ) ); // restrict phi to be betwee EPS and PI-EPS phi = Math.max( EPS, Math.min( Math.PI - EPS, phi ) ); var radius = offset.length() * scale; // restrict radius to be between desired limits radius = Math.max( this.minDistance, Math.min( this.maxDistance, radius ) ); // move target to panned location this.target.add( pan ); offset.x = radius * Math.sin( phi ) * Math.sin( theta ); offset.y = radius * Math.cos( phi ); offset.z = radius * Math.sin( phi ) * Math.cos( theta ); // rotate offset back to "camera-up-vector-is-up" space offset.applyQuaternion( quatInverse ); position.copy( this.target ).add( offset ); this.object.lookAt( this.target ); thetaDelta = 0; phiDelta = 0; scale = 1; pan.set( 0, 0, 0 ); // update condition is: // min(camera displacement, camera rotation in radians)^2 > EPS // using small-angle approximation cos(x/2) = 1 - x^2 / 8 if ( lastPosition.distanceToSquared( this.object.position ) > EPS || 8 * (1 - lastQuaternion.dot(this.object.quaternion)) > EPS ) { this.dispatchEvent( changeEvent ); lastPosition.copy( this.object.position ); lastQuaternion.copy (this.object.quaternion ); } }; this.reset = function () { state = STATE.NONE; this.target.copy( this.target0 ); this.object.position.copy( this.position0 ); this.update(); }; this.getPolarAngle = function () { return phi; }; this.getAzimuthalAngle = function () { return theta }; function getAutoRotationAngle() { return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed; } function getZoomScale() { return Math.pow( 0.95, scope.zoomSpeed ); } function onMouseDown( event ) { if ( scope.enabled === false ) return; event.preventDefault(); if ( event.button === scope.mouseButtons.ORBIT ) { if ( scope.noRotate === true ) return; state = STATE.ROTATE; rotateStart.set( event.clientX, event.clientY ); } else if ( event.button === scope.mouseButtons.ZOOM ) { if ( scope.noZoom === true ) return; state = STATE.DOLLY; dollyStart.set( event.clientX, event.clientY ); } else if ( event.button === scope.mouseButtons.PAN ) { if ( scope.noPan === true ) return; state = STATE.PAN; panStart.set( event.clientX, event.clientY ); } if ( state !== STATE.NONE ) { document.addEventListener( 'mousemove', onMouseMove, false ); document.addEventListener( 'mouseup', onMouseUp, false ); scope.dispatchEvent( startEvent ); } } function onMouseMove( event ) { if ( scope.enabled === false ) return; event.preventDefault(); var element = scope.domElement === document ? scope.domElement.body : scope.domElement; if ( state === STATE.ROTATE ) { if ( scope.noRotate === true ) return; rotateEnd.set( event.clientX, event.clientY ); rotateDelta.subVectors( rotateEnd, rotateStart ); // rotating across whole screen goes 360 degrees around scope.rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientWidth * scope.rotateSpeed ); // rotating up and down along whole screen attempts to go 360, but limited to 180 scope.rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight * scope.rotateSpeed ); rotateStart.copy( rotateEnd ); } else if ( state === STATE.DOLLY ) { if ( scope.noZoom === true ) return; dollyEnd.set( event.clientX, event.clientY ); dollyDelta.subVectors( dollyEnd, dollyStart ); if ( dollyDelta.y > 0 ) { scope.dollyIn(); } else { scope.dollyOut(); } dollyStart.copy( dollyEnd ); } else if ( state === STATE.PAN ) { if ( scope.noPan === true ) return; panEnd.set( event.clientX, event.clientY ); panDelta.subVectors( panEnd, panStart ); scope.pan( panDelta.x, panDelta.y ); panStart.copy( panEnd ); } if ( state !== STATE.NONE ) scope.update(); } function onMouseUp( /* event */ ) { if ( scope.enabled === false ) return; document.removeEventListener( 'mousemove', onMouseMove, false ); document.removeEventListener( 'mouseup', onMouseUp, false ); scope.dispatchEvent( endEvent ); state = STATE.NONE; } function onMouseWheel( event ) { if ( scope.enabled === false || scope.noZoom === true || state !== STATE.NONE ) return; event.preventDefault(); event.stopPropagation(); var delta = 0; if ( event.wheelDelta !== undefined ) { // WebKit / Opera / Explorer 9 delta = event.wheelDelta; } else if ( event.detail !== undefined ) { // Firefox delta = - event.detail; } if ( delta > 0 ) { scope.dollyOut(); } else { scope.dollyIn(); } scope.update(); scope.dispatchEvent( startEvent ); scope.dispatchEvent( endEvent ); } function onKeyDown( event ) { if ( scope.enabled === false || scope.noKeys === true || scope.noPan === true ) return; switch ( event.keyCode ) { case scope.keys.UP: scope.pan( 0, scope.keyPanSpeed ); scope.update(); break; case scope.keys.BOTTOM: scope.pan( 0, - scope.keyPanSpeed ); scope.update(); break; case scope.keys.LEFT: scope.pan( scope.keyPanSpeed, 0 ); scope.update(); break; case scope.keys.RIGHT: scope.pan( - scope.keyPanSpeed, 0 ); scope.update(); break; } } function touchstart( event ) { if ( scope.enabled === false ) return; switch ( event.touches.length ) { case 1: // one-fingered touch: rotate if ( scope.noRotate === true ) return; state = STATE.TOUCH_ROTATE; rotateStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); break; case 2: // two-fingered touch: dolly if ( scope.noZoom === true ) return; state = STATE.TOUCH_DOLLY; var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX; var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY; var distance = Math.sqrt( dx * dx + dy * dy ); dollyStart.set( 0, distance ); break; case 3: // three-fingered touch: pan if ( scope.noPan === true ) return; state = STATE.TOUCH_PAN; panStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); break; default: state = STATE.NONE; } if ( state !== STATE.NONE ) scope.dispatchEvent( startEvent ); } function touchmove( event ) { if ( scope.enabled === false ) return; event.preventDefault(); event.stopPropagation(); var element = scope.domElement === document ? scope.domElement.body : scope.domElement; switch ( event.touches.length ) { case 1: // one-fingered touch: rotate if ( scope.noRotate === true ) return; if ( state !== STATE.TOUCH_ROTATE ) return; rotateEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); rotateDelta.subVectors( rotateEnd, rotateStart ); // rotating across whole screen goes 360 degrees around scope.rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientWidth * scope.rotateSpeed ); // rotating up and down along whole screen attempts to go 360, but limited to 180 scope.rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight * scope.rotateSpeed ); rotateStart.copy( rotateEnd ); scope.update(); break; case 2: // two-fingered touch: dolly if ( scope.noZoom === true ) return; if ( state !== STATE.TOUCH_DOLLY ) return; var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX; var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY; var distance = Math.sqrt( dx * dx + dy * dy ); dollyEnd.set( 0, distance ); dollyDelta.subVectors( dollyEnd, dollyStart ); if ( dollyDelta.y > 0 ) { scope.dollyOut(); } else { scope.dollyIn(); } dollyStart.copy( dollyEnd ); scope.update(); break; case 3: // three-fingered touch: pan if ( scope.noPan === true ) return; if ( state !== STATE.TOUCH_PAN ) return; panEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY ); panDelta.subVectors( panEnd, panStart ); scope.pan( panDelta.x, panDelta.y ); panStart.copy( panEnd ); scope.update(); break; default: state = STATE.NONE; } } function touchend( /* event */ ) { if ( scope.enabled === false ) return; scope.dispatchEvent( endEvent ); state = STATE.NONE; } this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false ); this.domElement.addEventListener( 'mousedown', onMouseDown, false ); this.domElement.addEventListener( 'mousewheel', onMouseWheel, false ); this.domElement.addEventListener( 'DOMMouseScroll', onMouseWheel, false ); // firefox this.domElement.addEventListener( 'touchstart', touchstart, false ); this.domElement.addEventListener( 'touchend', touchend, false ); this.domElement.addEventListener( 'touchmove', touchmove, false ); window.addEventListener( 'keydown', onKeyDown, false ); // force an update at start this.update(); }; THREE.OrbitControls.prototype = Object.create( THREE.EventDispatcher.prototype ); THREE.OrbitControls.prototype.constructor = THREE.OrbitControls;
momega/spacesimulator
web/src/main/webapp/js/orbitcontrols.js
JavaScript
gpl-3.0
16,062
(function ($) { "use strict"; Drupal.behaviors.build_counter = { attach: function (context, settings) { $('.header-alerts-list, .footer-alerts-list', context).once('header-alert-list-arrows').each(function () { $('.slick__arrow', this).wrap('<div class="container"></div>'); if ($(this).find('.slick__counter').length === 0) { var current = $(this).find('.slick-active button').text(), total = $(this).find('.slick-dots li:last').text(); $('<div class="slick__counter">' + Drupal.t('<span class="current">@current</span> of <span class="total">@total</span>', { '@current': current, '@total': total }) + '</div>').insertBefore($(this).find('.slick__arrow')); } $(this).on('afterChange', function (event, slick, direction) { var current = $(this).find('.slick-active button').text(), total = $(this).find('.slick-dots li:last').text(); $(this).find('.slick__counter .current').text(current); $(this).find('.slick__counter .total').text(total); }); }); } }; Drupal.behaviors.alert_dismiss = { attach: function (context, settings) { var dismissed = Drupal.behaviors.alert_dismiss.getDismissed(); $('.site-alert', context).once('alert-dismiss').each(function () { var self = $(this); var nid = parseInt(self.data('nid')); var slick = self.parents('.slick__slider').first(); // Remove dismissed alerts. if ($.inArray(nid, dismissed) != -1) { var index = self.parents('.slick__slide').eq(0).index(); if (slick.length > 0 && index > 0) { var slickCheck = slick.slick('slickRemove', index -1); if(!slickCheck) { self.remove(); slick.parents('.slick-track').prevObject.remove(); } } else { self.remove(); } } $('.site-alert__dismiss', self).on('click', function () { if (slick.length > 0) { var slickCheck = slick.slick('slickRemove', self.parents('.slick__slide').eq(0).index()-1); if(!slickCheck) { self.remove(); slick.parents('.slick-track').prevObject.remove(); } } else { self.remove(); } // Store dimsmissed alerts ids into cookie. dismissed = Drupal.behaviors.alert_dismiss.getDismissed(); if ($.inArray(nid, dismissed) == -1) { dismissed.push(nid); } Drupal.behaviors.alert_dismiss.setDismissed(dismissed); return false; }); }); $('.header-alerts-list').addClass('header-alerts-list-processed'); }, getDismissed: function () { var jQueryCookieJson = $.cookie.json; $.cookie.json = true; var dismissed = $.cookie('alerts_dismiss') || []; $.cookie.json = jQueryCookieJson; return dismissed; }, setDismissed: function (dismissed) { var jQueryCookieJson = $.cookie.json; $.cookie.json = true; $.cookie('alerts_dismiss', dismissed, { expires: 7, path: '/' }); $.cookie.json = jQueryCookieJson; } }; Drupal.behaviors.removeUnneededAria = { attach: function (context, settings) { $('.slick-list', context).once().each(function () { $(this).removeAttr('aria-live'); }); $('.slick-track', context).once().each(function () { $(this).removeAttr('role'); }); $('.slick__slide', context).once().each(function () { $(this).removeAttr('aria-describedby'); $(this).removeAttr('role'); }); } }; })(jQuery);
ddrozdik/openy
modules/openy_features/openy_node/modules/openy_node_alert/js/openy_node_alert.js
JavaScript
gpl-3.0
3,773
const async = require('async'); const mongojs = require('mongojs'); const db = mongojs('pkdex'); // Abilities const dbAbilities = function (callback) { console.log('Running dbAbilities...'); db.abilities.aggregate([ { $match: { is_main_series: 1 } }, { $lookup: { from: 'ability_flavor_text', localField: 'id', foreignField: 'ability_id', as: 'flavor_text' } }, { $unwind: { path: '$flavor_text', preserveNullAndEmptyArrays: true } }, { $match: { 'flavor_text.language_id': 9, 'flavor_text.version_group_id': 16 } }, { $lookup: { from: 'ability_names', localField: 'id', foreignField: 'ability_id', as: 'names' } }, { $unwind: { path: '$names', preserveNullAndEmptyArrays: true } }, { $match: { 'names.local_language_id': 9 } }, { $lookup: { from: 'ability_prose', localField: 'id', foreignField: 'ability_id', as: 'prose' } }, { $unwind: { path: '$prose', preserveNullAndEmptyArrays: true } }, { $match: { 'prose.local_language_id': 9 } }, { $project: { _id: '$id', identifier: 1, name: '$names.name', description: { stub: '$flavor_text.flavor_text', short: '$prose.short_effect', long: '$prose.effect' } } }, { $out: 'A_NEW_abilities' } ], (err) => { callback(err); }); }; // Pokemon const dbPokemon = function (callback) { console.log('Running dbPokemon...'); db.pokemon.aggregate([ { $lookup: { from: 'pokemon_forms', localField: 'id', foreignField: 'pokemon_id', as: 'forms' } }, { $unwind: { path: '$forms', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'pokemon_form_names', localField: 'forms.id', foreignField: 'pokemon_form_id', as: 'forms.names' } }, { $unwind: { path: '$forms.names', preserveNullAndEmptyArrays: true } }, { $match: { $or: [ { 'forms.names.local_language_id': 9 }, { 'forms.names': { $exists: false } } ] } }, { $lookup: { from: 'pokemon_form_generations', localField: 'forms.id', foreignField: 'pokemon_form_id', as: 'forms.generations' } }, { $unwind: { path: '$forms.generations', preserveNullAndEmptyArrays: true } }, { $group: { _id: '$forms.id', pokemon_id: { $first: '$id' }, pokemonIdentifier: { $first: '$identifier' }, pokemonSpecies_id: { $first: '$species_id' }, pokemonHeight: { $first: '$height' }, pokemonWeight: { $first: '$weight' }, pokemonBaseXP: { $first: '$base_experience' }, pokemonOrder: { $first: '$order' }, pokemonIsDefault: { $first: '$is_default' }, formsIdentifier: { $first: '$forms.identifier' }, formsFormIdentifier: { $first: '$forms.form_identifier' }, formsIsDefault: { $first: '$forms.is_default' }, formsIsBattleOnly: { $first: '$forms.is_battle_only' }, formsIsMega: { $first: '$forms.is_mega' }, formsFormOrder: { $first: '$forms.form_order' }, formsOrder: { $first: '$forms.order' }, formsName: { $first: '$forms.names.form_name' }, formsGenerations: { $push: '$forms.generations.generation_id' } } }, { $sort: { _id: 1 } }, { $group: { _id: '$pokemon_id', identifier: { $first: '$pokemonIdentifier' }, species_id: { $first: '$pokemonSpecies_id' }, height: { $first: '$pokemonHeight' }, weight: { $first: '$pokemonWeight' }, baseXP: { $first: '$pokemonBaseXP' }, order: { $first: '$pokemonOrder' }, isDefault: { $first: '$pokemonIsDefault' }, forms: { $push: { _id: '$_id', identifier: '$formsIdentifier', formIdentifier: '$formsFormIdentifier', name: '$formsName', isDefault: '$formsIsDefault', isBattleOnly: '$formsIsBattleOnly', isMega: '$formsIsMega', formOrder: '$formsFormOrder', order: '$formsOrder', generations: '$formsGenerations' } } } }, { $lookup: { from: 'pokemon_abilities', localField: '_id', foreignField: 'pokemon_id', as: 'abilities' } }, { $unwind: { path: '$abilities', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'A_NEW_abilities', localField: 'abilities.ability_id', foreignField: '_id', as: 'abilities.ability' } }, { $unwind: { path: '$abilities.ability', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'pokemon_stats', localField: '_id', foreignField: 'pokemon_id', as: 'stats' } }, { $unwind: { path: '$stats', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'stats', localField: 'stats.stat_id', foreignField: 'id', as: 'stats.stat' } }, { $unwind: { path: '$stats.stat', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'stat_names', localField: 'stats.stat.id', foreignField: 'stat_id', as: 'stats.stat.names' } }, { $unwind: { path: '$stats.stat.names', preserveNullAndEmptyArrays: true } }, { $match: { 'stats.stat.names.local_language_id': 9 } }, { $lookup: { from: 'pokemon_types', localField: '_id', foreignField: 'pokemon_id', as: 'types' } }, { $unwind: { path: '$types', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'types', localField: 'types.type_id', foreignField: 'id', as: 'types.type' } }, { $unwind: { path: '$types.type', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'type_names', localField: 'types.type_id', foreignField: 'type_id', as: 'types.type.names' } }, { $unwind: { path: '$types.type.names', preserveNullAndEmptyArrays: true } }, { $match: { 'types.type.names.local_language_id': 9 } }, { $group: { _id: '$_id', identifier: { $first: '$identifier' }, species_id: { $first: '$species_id' }, height: { $first: '$height' }, weight: { $first: '$weight' }, baseXP: { $first: '$baseXP' }, order: { $first: '$order' }, isDefault: { $first: '$isDefault' }, forms: { $first: '$forms' }, abilities: { $addToSet: { _id: '$abilities.ability._id', identifier: '$abilities.ability.identifier', name: '$abilities.ability.name', description: '$abilities.ability.description', slot: '$abilities.slot', isHidden: '$abilities.is_hidden' } }, stats: { $addToSet: { _id: '$stats.stat.id', identifier: '$stats.stat.identifier', name: '$stats.stat.names.name', baseStat: '$stats.base_stat', effort: '$stats.effort', damageClass_id: '$stats.stat.damage_class_id', isBattleOnly: '$stats.stat.is_battle_only' } }, types: { $addToSet: { _id: '$types.type_id', identifier: '$types.type.identifier', name: '$types.type.names.name', slot: '$types.slot', damageClass_id: '$types.damage_class_id', generation_id: '$types.type.generation_id' } } } }, { $sort: { _id: 1 } }, { $out: 'A_NEW_pokemon' } ], (err) => { callback(err); }); }; // Pokemon Species const dbPokemonSpecies = function (callback) { console.log('Running dbPokemonSpecies...'); db.pokemon_species.aggregate([ { $lookup: { from: 'pokemon_colors', localField: 'color_id', foreignField: 'id', as: 'color' } }, { $unwind: { path: '$color', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'pokemon_color_names', localField: 'color.id', foreignField: 'pokemon_color_id', as: 'color.names' } }, { $unwind: { path: '$color.names', preserveNullAndEmptyArrays: true } }, { $match: { 'color.names.local_language_id': 9 } }, { $lookup: { from: 'pokemon_shapes', localField: 'shape_id', foreignField: 'id', as: 'shape' } }, { $unwind: { path: '$shape', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'pokemon_shape_prose', localField: 'shape_id', foreignField: 'pokemon_shape_id', as: 'shape.prose' } }, { $unwind: { path: '$shape.prose', preserveNullAndEmptyArrays: true } }, { $match: { 'shape.prose.local_language_id': 9 } }, { $lookup: { from: 'pokemon_habitats', localField: 'habitat_id', foreignField: 'id', as: 'habitat' } }, { $unwind: { path: '$habitat', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'pokemon_habitat_names', localField: 'habitat.id', foreignField: 'pokemon_habitat_id', as: 'habitat.names' } }, { $unwind: { path: '$habitat.names', preserveNullAndEmptyArrays: true } }, { $match: { $or: [ { 'habitat.names.local_language_id': 9 }, { 'habitat.names': { $exists: false } } ] } }, { $lookup: { from: 'pokemon_evolution', localField: 'id', foreignField: 'evolved_species_id', as: 'evolutions' } }, { $lookup: { from: 'pokemon_egg_groups', localField: 'id', foreignField: 'species_id', as: 'eggGroups' } }, { $lookup: { from: 'pokemon_species_names', localField: 'id', foreignField: 'pokemon_species_id', as: 'names' } }, { $unwind: { path: '$names', preserveNullAndEmptyArrays: true } }, { $match: { 'names.local_language_id': 9 } }, { $lookup: { from: 'pokemon_species_flavor_text', localField: 'id', foreignField: 'species_id', as: 'flavorText' } }, { $unwind: { path: '$flavorText', preserveNullAndEmptyArrays: true } }, { $match: { 'flavorText.language_id': 9, 'flavorText.version_id': 26 } }, { $lookup: { from: 'pokemon_species_prose', localField: 'id', foreignField: 'pokemon_species_id', as: 'prose' } }, { $unwind: { path: '$prose', preserveNullAndEmptyArrays: true } }, { $match: { $or: [ { 'prose.local_language_id': 9 }, { 'prose': { $exists: false } } ] } }, { $unwind: { path: '$evolutions', preserveNullAndEmptyArrays: true } }, { $unwind: { path: '$eggGroups', preserveNullAndEmptyArrays: true } }, { $group: { _id: '$id', identifier: { $first: '$identifier' }, generation_id: { $first: '$generation_id' }, evolvesFromSpecies_id: { $first: '$evolves_from_species_id' }, evolutionChain_id: { $first: '$evolution_chain_id' }, genderRate: { $first: '$gender_rate' }, captureRate: { $first: '$capture_rate' }, baseHappiness: { $first: '$base_happiness' }, isBaby: { $first: '$is_baby' }, hatchCounter: { $first: '$hatch_counter' }, hasGenderDifferences: { $first: '$has_gender_differences' }, growthRate_id: { $first: '$growthRate_id' }, formsSwitchable: { $first: '$forms_switchable' }, order: { $first: '$order' }, color: { $addToSet: { _id: '$color.id', identifier: '$color.identifier', name: '$color.names.name' } }, shape: { $addToSet: { _id: '$shape.id', identifier: '$shape.identifier', name: '$shape.prose.name', awesomeName: '$shape.prose.awesome_name', description: '$shape.prose.description' } }, habitat: { $addToSet: { _id: '$habitat.id', identifier: '$habitat.identifier', name: '$habitat.names.name' } }, evolutions: { $addToSet: { trigger_id: '$evolutions.trigger_id', triggerItem_id: '$evolutions.trigger_item_id', minimumLevel: '$evolutions.minimum_level', gender_id: '$evolutions.gender_id', location_id: '$evolutions.location_id', heldItem_id: '$evolutions.held_item_id', timeOfDay: '$evolutions.time_of_day', knownMove_id: '$evolutions.known_move_id', knownMoveType_id: '$evolutions.known_move_type_id', minimumHappiness: '$evolutions.minimum_happiness', minimumBeauty: '$evolutions.minimum_beauty', minimumAffection: '$evolutions.minimum_affection', relativePhysicalStats: '$evolutions.relative_physical_stats', partySpecies_id: '$evolutions.partySpecies_id', partyType_id: '$evolutions.party_type_id', tradeSpecies_id: '$evolutions.trade_species_id', needsOverworldRain: '$evolutions.needs_overworld_rain', turnUpsideDown: '$evolutions.turn_upside_down' } }, eggGroups: { $addToSet: '$eggGroups.egg_group_id' }, name: { $first: '$names.name' }, genus: { $first: '$names.genus' }, description: { $first: '$flavorText.flavor_text' } } }, { $unwind: { path: '$color', preserveNullAndEmptyArrays: true } }, { $unwind: { path: '$shape', preserveNullAndEmptyArrays: true } }, { $unwind: { path: '$habitat', preserveNullAndEmptyArrays: true } }, { $sort: { _id: 1 } }, { $out: 'A_NEW_pokemonSpecies' } ], (err) => { callback(err); }); } // Berries const dbBerries = function (callback) { console.log('Running dbBerries...'); db.berries.aggregate([ { $lookup: { from: 'berry_firmness', localField: 'firmness_id', foreignField: 'id', as: 'firmness' } }, { $unwind: { path: '$firmness', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'berry_firmness_names', localField: 'firmness.id', foreignField: 'berry_firmness_id', as: 'firmness.names' } }, { $unwind: { path: '$firmness.names', preserveNullAndEmptyArrays: true } }, { $match: { 'firmness.names.local_language_id': 9 } }, { $project: { _id: '$id', item_id: 1, size: 1, maxHarvest: '$max_harvest', growthTime: '$growth_time', soilDryness: '$soil_dryness', smoothness: 1, firmness: { identifier: 1, name: '$firmness.names.name' } } }, { $out: 'A_NEW_berries' } ], (err) => { callback(err); }); }; // Characteristics const dbCharacteristics = function (callback) { console.log('Running dbCharacteristics...'); db.characteristics.aggregate([ { $lookup: { from: 'characteristic_text', localField: 'id', foreignField: 'characteristic_id', as: 'text' } }, { $unwind: { path: '$text', preserveNullAndEmptyArrays: true } }, { $match: { 'text.local_language_id': 9 } }, { $project: { _id: '$id', stat_id: 1, geneMod5: '$gene_mod_5', description: '$text.message' } }, { $out: 'A_NEW_characteristics' } ], (err) => { callback(err); }); }; // Egg Groups const dbEggGroups = function (callback) { console.log('Running dbEggGroups...'); db.egg_groups.aggregate([ { $lookup: { from: 'egg_group_prose', localField: 'id', foreignField: 'egg_group_id', as: 'prose' } }, { $unwind: { path: '$prose', preserveNullAndEmptyArrays: true } }, { $match: { 'prose.local_language_id': 9 } }, { $project: { _id: '$id', identifier: 1, name: '$prose.name' } }, { $out: 'A_NEW_eggGroups' } ], (err) => { callback(err); }); }; // Encounter Conditions const dbEncounterConditions = function (callback) { console.log('Running dbEncounterConditions...'); db.encounter_conditions.aggregate([ { $lookup: { from: 'encounter_condition_prose', localField: 'id', foreignField: 'encounter_condition_id', as: 'prose' } }, { $unwind: { path: '$prose', preserveNullAndEmptyArrays: true } }, { $match: { 'prose.local_language_id': 9 } }, { $project: { _id: '$id', identifier: 1, name: '$prose.name' } }, { $out: 'A_NEW_encounterConditions' } ], (err) => { callback(err); }); }; // Encounter Condition Values const dbEncounterConditionValues = function (callback) { console.log('Running dbEncounterConditionValues...'); db.encounter_condition_values.aggregate([ { $lookup: { from: 'encounter_condition_value_prose', localField: 'id', foreignField: 'encounter_condition_value_id', as: 'prose' } }, { $unwind: { path: '$prose', preserveNullAndEmptyArrays: true } }, { $match: { 'prose.local_language_id': 9 } }, { $project: { _id: '$id', encounterCondition_id: '$encounter_condition_id', identifier: 1, isDefault: '$is_default', name: '$prose.name' } }, { $out: 'A_NEW_encounterConditionValues' } ], (err) => { callback(err); }); }; // Encounter Methods const dbEncounterMethods = function (callback) { console.log('Running dbEncounterMethods...'); db.encounter_methods.aggregate([ { $lookup: { from: 'encounter_method_prose', localField: 'id', foreignField: 'encounter_method_id', as: 'prose' } }, { $unwind: { path: '$prose', preserveNullAndEmptyArrays: true } }, { $match: { 'prose.local_language_id': 9 } }, { $project: { _id: '$id', identifier: 1, description: '$prose.name', order: 1 } }, { $out: 'A_NEW_encounterMethods' } ], (err) => { callback(err); }); }; // Encounters const dbEncounters = function (callback) { console.log('Running dbEncounters...'); db.encounters.aggregate([ { $project: { _id: '$id', version_id: 1, locationArea_id: '$location_area_id', encounterSlot_id: '$encounter_slot_id', pokemon_id: 1, minLevel: '$min_level', maxLevel: '$max_level' } }, { $out: 'A_NEW_encounters' } ], (err) => { if (!err) { db.encounter_condition_value_map.aggregate([ { $group: { _id: '$encounter_id', conditionValue: { $addToSet: '$encounter_condition_value_id' } } } ]).forEach((err, doc) => { if (!err && doc) { db.A_NEW_encounters.findAndModify({ query: { _id: doc._id }, update: { $set: { conditionValues: doc.conditionValue } } }, (err) => { if (err) callback(err); }); } else { callback(err); } }); } else { callback(err); } }); }; // Encounter Slots const dbEncounterSlots = function (callback) { console.log('Running dbEncounterSlots...'); db.encounter_slots.aggregate([ { $project: { _id: '$id', versionGroup_id: '$version_group_id', encounterMethod_id: '$encounter_method_id', slot: 1, rarity: 1 } }, { $out: 'A_NEW_encounterSlots' } ], (err) => { callback(err); }); }; // Evolution Chains const dbEvolutionChains = function (callback) { console.log('Running dbEvolutionChains...'); db.evolution_chains.aggregate([ { $project: { _id: '$id', babyTriggerItem_id: '$baby_trigger_item_id' } }, { $out: 'A_NEW_evolutionChains' } ], (err) => { callback(err); }); }; // Evolution Triggers const dbEvolutionTriggers = function (callback) { console.log('Running dbEvolutionTriggers...'); db.evolution_triggers.aggregate([ { $lookup: { from: 'evolution_trigger_prose', localField: 'id', foreignField: 'evolution_trigger_id', as: 'prose' } }, { $unwind: { path: '$prose', preserveNullAndEmptyArrays: true } }, { $match: { 'prose.local_language_id': 9 } }, { $project: { _id: '$id', identifier: 1, name: '$prose.name' } }, { $out: 'A_NEW_evolutionTriggers' } ], (err) => { callback(err); }); }; // Growth Rates const dbGrowthRates = function (callback) { console.log('Running dbGrowthRates...'); db.growth_rates.aggregate([ { $lookup: { from: 'experience', localField: 'id', foreignField: 'growth_rate_id', as: 'experience' } }, { $unwind: { path: '$experience', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'growth_rate_prose', localField: 'id', foreignField: 'growth_rate_id', as: 'prose' } }, { $unwind: { path: '$prose', preserveNullAndEmptyArrays: true } }, { $match: { 'prose.local_language_id': 9 } }, { $group: { _id: '$id', identifier: { $first: '$identifier' }, name: { $first: '$prose.name' }, formula: { $first: '$formula' }, experience: { $push: '$experience.experience' } } }, { $sort: { _id: 1 } }, { $out: 'A_NEW_growthRates' } ], (err) => { callback(err); }); }; // Genders const dbGenders = function (callback) { console.log('Running dbGenders...'); db.genders.aggregate([ { $project: { _id: '$id', identifier: 1 } }, { $out: 'A_NEW_genders' } ], (err) => { callback(err); }); }; // Generations const dbGenerations = function (callback) { console.log('Running dbGenerations...'); db.generations.aggregate([ { $lookup: { from: 'generation_names', localField: 'id', foreignField: 'generation_id', as: 'names' } }, { $unwind: { path: '$names', preserveNullAndEmptyArrays: true } }, { $match: { 'names.local_language_id': 9 } }, { $project: { _id: '$id', mainRegion_id: '$main_region_id', identifier: 1, name: '$names.name' } }, { $out: 'A_NEW_generations' } ], (err) => { callback(err); }); }; // Items const dbItems = function (callback) { console.log('Running dbItems...'); db.items.aggregate([ { $lookup: { from: 'item_names', localField: 'id', foreignField: 'item_id', as: 'names' } }, { $unwind: { path: '$names', preserveNullAndEmptyArrays: true } }, { $match: { 'names.local_language_id': 9 } }, { $lookup: { from: 'item_categories', localField: 'category_id', foreignField: 'id', as: 'category' } }, { $unwind: { path: '$category', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'item_category_prose', localField: 'category.id', foreignField: 'item_category_id', as: 'category.names' } }, { $unwind: { path: '$category.names', preserveNullAndEmptyArrays: true } }, { $match: { 'category.names.local_language_id': 9 } }, { $lookup: { from: 'item_prose', localField: 'id', foreignField: 'item_id', as: 'prose' } }, { $unwind: { path: '$prose', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'item_pockets', localField: 'category.pocket_id', foreignField: 'id', as: 'category.pocket' } }, { $unwind: { path: '$category.pocket', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'item_pocket_names', localField: 'category.pocket.id', foreignField: 'item_pocket_id', as: 'category.pocket.names' } }, { $unwind: { path: '$category.pocket.names', preserveNullAndEmptyArrays: true } }, { $match: { 'category.pocket.names.local_language_id': 9 } }, { $lookup: { from: 'item_flavor_text', localField: 'id', foreignField: 'item_id', as: 'flavor_text' } }, { $unwind: { path: '$flavor_text', preserveNullAndEmptyArrays: true } }, { $match: { 'flavor_text.language_id': 9 } }, { $lookup: { from: 'item_flag_map', localField: 'id', foreignField: 'item_id', as: 'flags' } }, { $unwind: { path: '$flags', preserveNullAndEmptyArrays: true } }, { $group: { _id: '$id', identifier: { $first: '$identifier' }, name: { $first: '$names.name' }, cost: { $first: '$cost' }, categoryIdentifier: { $first: '$category.identifier' }, categoryName: { $first: '$category.names.name' }, pocketIdentifier: { $first: '$category.pocket.identifier' }, pocketName: { $first: '$category.pocket.names.name' }, descriptionStub: { $first: '$flavor_text.flavor_text' }, descriptionShort: { $first: '$prose.short_effect' }, descriptionLong: { $first: '$prose.effect' }, flags: { $push: '$flags.item_flag_id' } } }, { $project: { _id: 1, identifier: 1, name: 1, cost: 1, category: { identifier: '$categoryIdentifier', name: '$categoryName' }, pocket: { identifier: '$pocketIdentifier', name: '$pocketName' }, description: { stub: '$descriptionStub', short: '$descriptionShort', long: '$descriptionLong' }, flags: 1 } }, { $sort: { _id: 1 } }, { $out: 'A_NEW_items' } ], (err) => { callback(err); }); }; // Item Flags const dbItemFlags = function (callback) { console.log('Running dbItemFlags...'); db.item_flags.aggregate([ { $lookup: { from: 'item_flag_prose', localField: 'id', foreignField: 'item_flag_id', as: 'prose' } }, { $unwind: { path: '$prose', preserveNullAndEmptyArrays: true } }, { $match: { 'prose.local_language_id': 9 } }, { $project: { _id: '$id', identifier: 1, name: '$prose.name', description: '$prose.description' } }, { $out: 'A_NEW_itemFlags' } ], (err) => { callback(err); }); }; // Location Areas const dbLocationAreas = function (callback) { console.log('Running dbLocationAreas...'); db.location_areas.aggregate([ { $lookup: { from: 'location_area_prose', localField: 'id', foreignField: 'location_area_id', as: 'prose' } }, { $unwind: { path: '$prose', preserveNullAndEmptyArrays: true } }, { $match: { $or: [ { 'prose.local_language_id': 9 }, { 'prose': { $exists: false } } ] } }, { $project: { _id: '$id', location_id: 1, identifier: 1, name: '$prose.name' } }, { $out: 'A_NEW_locationAreas' } ], (err) => { callback(err); }); }; const dbLocations = function (callback) { console.log('Running dbLocations...'); // Locations db.locations.aggregate([ { $lookup: { from: 'location_names', localField: 'id', foreignField: 'location_id', as: 'names' } }, { $unwind: { path: '$names', preserveNullAndEmptyArrays: true } }, { $match: { 'names.local_language_id': 9 } }, { $lookup: { from: 'A_NEW_locationAreas', localField: 'id', foreignField: 'location_id', as: 'areas' } }, { $unwind: { path: '$areas', preserveNullAndEmptyArrays: true } }, { $group: { _id: '$id', region_id: { $first: '$region_id' }, identifier: { $first: '$identifier' }, name: { $first: '$names.name' }, areas: { $addToSet: '$areas._id' } } }, { $sort: { _id: 1 } }, { $out: 'A_NEW_locations' } ], (err) => { callback(err); }); }; const dbRegions = function (callback) { console.log('Running dbRegions...'); // Regions db.regions.aggregate([ { $lookup: { from: 'region_names', localField: 'id', foreignField: 'region_id', as: 'names' } }, { $unwind: { path: '$names', preserveNullAndEmptyArrays: true } }, { $match: { 'names.local_language_id': 9 } }, { $lookup: { from: 'A_NEW_locations', localField: 'id', foreignField: 'region_id', as: 'locations' } }, { $unwind: { path: '$locations', preserveNullAndEmptyArrays: true } }, { $group: { _id: '$id', identifier: { $first: '$identifier' }, name: { $first: '$names.name' }, locations: { $push: '$locations._id' } } }, { $out: 'A_NEW_regions' } ], (err) => { callback(err); }); }; // Machines const dbMachines = function (callback) { console.log('Running dbMachines...'); db.machines.aggregate([ { $group: { _id: '$machine_number', versionGroups: { $push: { _id: '$version_group_id', item_id: '$item_id', move_id: '$move_id' } } } }, { $sort: { _id: 1 } }, { $out: 'A_NEW_machines' } ], (err) => { callback(err); }); }; // Move Battle Styles const dbMoveBattleStyles = function (callback) { console.log('Running dbMoveBattleStyles...'); db.move_battle_styles.aggregate([ { $lookup: { from: 'move_battle_style_prose', localField: 'id', foreignField: 'move_battle_style_id', as: 'prose' } }, { $unwind: { path: '$prose', preserveNullAndEmptyArrays: true } }, { $match: { 'prose.local_language_id': 9 } }, { $project: { _id: '$id', identifier: 1, name: '$prose.name' } }, { $out: 'A_NEW_moveBattleStyles' } ], (err) => { callback(err); }); }; // Natures const dbNatures = function (callback) { console.log('Running dbNatures...'); db.natures.aggregate([ { $lookup: { from: 'nature_names', localField: 'id', foreignField: 'nature_id', as: 'names' } }, { $unwind: { path: '$names', preserveNullAndEmptyArrays: true } }, { $match: { 'names.local_language_id': 9 } }, { $lookup: { from: 'nature_battle_style_preferences', localField: 'id', foreignField: 'nature_id', as: 'battle_style_preferences' } }, { $unwind: { path: '$battle_style_preferences', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'A_NEW_moveBattleStyles', localField: 'battle_style_preferences.move_battle_style_id', foreignField: '_id', as: 'battle_style_preferences.style' } }, { $unwind: { path: '$battle_style_preferences.style', preserveNullAndEmptyArrays: true } }, { $project: { _id: '$id', identifier: 1, name: '$names.name', stats: { decreased: '$decreased_stat_id', increased: '$increased_stat_id' }, flavors: { hates: '$hates_flavor_id', likes: '$likes_flavor_id' }, battleStylePreferences: { identifier: '$battle_style_preferences.style.identifier', low: '$battle_style_preferences.low_hp_preference', high: '$battle_style_preferences.high_hp_preference' } } }, { $group: { _id: '$_id', identifier: { $first: '$identifier' }, name: { $first: '$name' }, stats: { $first: '$stats' }, flavors: { $first: '$flavors' }, battleStylePreferences: { $push: '$battleStylePreferences' } } }, { $out: 'A_NEW_natures' } ], (err) => { callback(err); }); }; // Moves const dbMoves = function (callback) { console.log('Running dbMoves...'); db.moves.aggregate([ { $lookup: { from: 'move_names', localField: 'id', foreignField: 'move_id', as: 'names' } }, { $unwind: { path: '$names', preserveNullAndEmptyArrays: true } }, { $match: { 'names.local_language_id': 9 } }, { $lookup: { from: 'move_flavor_text', localField: 'id', foreignField: 'move_id', as: 'flavor_text' } }, { $unwind: { path: '$flavor_text', preserveNullAndEmptyArrays: true } }, { $match: { $or: [ { 'flavor_text.language_id': 9 }, { 'flavor_text.flavor_text': { $exists: false } } ] } }, { $lookup: { from: 'move_targets', localField: 'target_id', foreignField: 'id', as: 'target' } }, { $unwind: { path: '$target', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'move_target_prose', localField: 'target.id', foreignField: 'move_target_id', as: 'target.prose' } }, { $unwind: { path: '$target.prose', preserveNullAndEmptyArrays: true } }, { $match: { 'target.prose.local_language_id': 9 } }, { $lookup: { from: 'move_damage_classes', localField: 'damage_class_id', foreignField: 'id', as: 'damage_class' } }, { $unwind: { path: '$damage_class', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'move_damage_class_prose', localField: 'damage_class.id', foreignField: 'move_damage_class_id', as: 'damage_class.prose' } }, { $unwind: { path: '$damage_class.prose', preserveNullAndEmptyArrays: true } }, { $match: { 'damage_class.prose.local_language_id': 9 } }, { $lookup: { from: 'move_effects', localField: 'effect_id', foreignField: 'id', as: 'effect' } }, { $unwind: { path: '$effect', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'move_effect_prose', localField: 'effect.id', foreignField: 'move_effect_id', as: 'effect.prose' } }, { $unwind: { path: '$effect.prose', preserveNullAndEmptyArrays: true } }, { $match: { 'effect.prose.local_language_id': 9 } }, { $lookup: { from: 'move_meta', localField: 'id', foreignField: 'move_id', as: 'meta' } }, { $unwind: { path: '$meta', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'move_meta_ailments', localField: 'meta.meta_ailment_id', foreignField: 'id', as: 'meta.ailment' } }, { $unwind: { path: '$meta.ailment', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'move_meta_ailment_names', localField: 'meta.ailment.id', foreignField: 'move_meta_ailment_id', as: 'meta.ailment.names' } }, { $unwind: { path: '$meta.ailment.names', preserveNullAndEmptyArrays: true } }, { $match: { $or: [ { 'meta.ailment.names.local_language_id': 9 }, { 'meta.ailment.names': { $exists: false } } ] } }, { $lookup: { from: 'move_meta_categories', localField: 'meta.meta_category_id', foreignField: 'id', as: 'meta.category' } }, { $unwind: { path: '$meta.category', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'move_meta_category_prose', localField: 'meta.category.id', foreignField: 'move_meta_category_id', as: 'meta.category.prose' } }, { $unwind: { path: '$meta.category.prose', preserveNullAndEmptyArrays: true } }, { $match: { $or: [ { 'meta.category.prose.local_language_id': 9 }, { 'meta.category.prose': { $exists: false } } ] } }, { $lookup: { from: 'move_meta_stat_changes', localField: 'id', foreignField: 'move_id', as: 'stat_changes' } }, { $unwind: { path: '$stat_changes', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'stats', localField: 'stat_changes.stat_id', foreignField: 'id', as: 'stat_changes.stat' } }, { $unwind: { path: '$stat_changes.stat', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'stat_names', localField: 'stat_changes.stat.id', foreignField: 'stat_id', as: 'stat_changes.stat.names' } }, { $unwind: { path: '$stat_changes.stat.names', preserveNullAndEmptyArrays: true } }, { $match: { $or: [ { 'stat_changes.stat.names.local_language_id': 9 }, { 'stat_changes.stat.names': { $exists: false } } ] } }, { $lookup: { from: 'move_flag_map', localField: 'id', foreignField: 'move_id', as: 'flags' } }, { $unwind: { path: '$flags', preserveNullAndEmptyArrays: true } }, { $group: { _id: '$id', identifier: { $first: '$identifier' }, name: { $first: '$names.name' }, description: { $first: '$flavor_text.flavor_text' }, type_id: { $first: '$type_id' }, power: { $first: '$power' }, pp: { $first: '$pp' }, accuracy: { $first: '$accuracy' }, priority: { $first: '$priority' }, targetIdentifier: { $first: '$target.identifier' }, targetName: { $first: '$target.prose.name' }, targetDescription: { $first: '$target.prose.description' }, damageClassIdentifier: { $first: '$damage_class.identifier' }, damageClassName: { $first: '$damage_class.prose.name' }, damageClassDescription: { $first: '$damage_class.prose.description' }, effectChance: { $first: '$effect_chance' }, effectDescriptionShort: { $first: '$effect.prose.short_effect' }, effectDescriptionLong: { $first: '$effect.prose.effect' }, minHits: { $first: '$meta.min_hits' }, maxHits: { $first: '$meta.max_hits' }, minTurns: { $first: '$meta.min_turns' }, maxTurns: { $first: '$meta.max_turns' }, drain: { $first: '$meta.drain' }, healing: { $first: '$meta.healing' }, critRate: { $first: '$meta.crit_rate' }, ailmentChance: { $first: '$meta.ailment_chance' }, flinchChance: { $first: '$meta.flinch_chance' }, statChance: { $first: '$meta.stat_chance' }, ailmentIdentifier: { $first: '$meta.ailment.identifier' }, ailmentName: { $first: '$meta.ailment.names.name' }, categoryIdentifier: { $first: '$category.identifier' }, categoryDescription: { $first: '$category.prose.description' }, statChanges: { $addToSet: { id: '$stat_changes.stat.id', identifier: '$stat_changes.stat.identifier', name: '$stat_changes.stat.names.name', change: '$stat_changes.change' } }, flags: { $addToSet: '$flags.move_flag_id' } } }, { $project: { _id: 1, identifier: 1, name: 1, description: 1, type_id: 1, power: 1, pp: 1, accuracy: 1, priority: 1, target: { identifier: '$targetIdentifier', name: '$targetName', description: '$targetDescription' }, damageClass: { identifier: '$damageClassIdentifier', name: '$damageClassName', description: '$damageClassDescription' }, effect: { chance: '$effectChance', description: { short: '$effectDescriptionShort', long: '$effectDescriptionLong' } }, minHits: { $ifNull: [ '$minHits', '' ] }, maxHits: { $ifNull: [ '$maxHits', '' ] }, minTurns: { $ifNull: [ '$minTurns', '' ] }, maxTurns: { $ifNull: [ '$maxTurns', '' ] }, drain: { $ifNull: [ '$minHits', '' ] }, healing: { $ifNull: [ '$healing', '' ] }, critRate: { $ifNull: [ '$critRate', '' ] }, ailmentChance: { $ifNull: [ '$ailmentChance', '' ] }, flinchChance: { $ifNull: [ '$flinchChance', '' ] }, statChance: { $ifNull: [ '$statChance', '' ] }, ailment: { identifier: { $ifNull: [ '$ailmentIdentifier', '' ] }, name: { $ifNull: [ '$ailmentName', '' ] } }, category: { identifier: { $ifNull: [ '$categoryIdentifier', '' ] }, description: { $ifNull: [ '$categoryDescription', '' ] } }, flags: 1, statChanges: 1 } }, { $sort: { _id: 1 } }, { $out: 'A_NEW_moves' } ], (err) => { callback(err); }); }; // Move Flags const dbMoveFlags = function (callback) { console.log('Running dbMoveFlags...'); db.move_flags.aggregate([ { $lookup: { from: 'move_flag_prose', localField: 'id', foreignField: 'move_flag_id', as: 'prose' } }, { $unwind: { path: '$prose', preserveNullAndEmptyArrays: true } }, { $match: { 'prose.local_language_id': 9 } }, { $project: { _id: '$id', identifier: 1, name: '$prose.name', description: '$prose.description' } }, { $out: 'A_NEW_moveFlags' } ], (err) => { callback(err); }); }; // Pal Park const dbPalPark = function (callback) { console.log('Running dbPalPark...'); db.pal_park.aggregate([ { $lookup: { from: 'pal_park_areas', localField: 'area_id', foreignField: 'id', as: 'area' } }, { $unwind: { path: '$area', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'pal_park_area_names', localField: 'area_id', foreignField: 'pal_park_area_id', as: 'area.names' } }, { $unwind: { path: '$area.names', preserveNullAndEmptyArrays: true } }, { $match: { 'area.names.local_language_id': 9 } }, { $project: { _id: '$species_id', baseScore: '$base_score', rate: 1, area: { identifier: 1, name: '$area.names.name' } } }, { $out: 'A_NEW_palPark' } ], (err) => { callback(err); }); }; // Pokedexes const dbPokedexes = function (callback) { console.log('Running dbPokedexes...'); db.pokedexes.aggregate([ { $match: { 'is_main_series': 1 } }, { $lookup: { from: 'pokedex_version_groups', localField: 'id', foreignField: 'pokedex_id', as: 'versionGroups' } }, { $unwind: { path: '$versionGroups', preserveNullAndEmptyArrays: true } }, { $group: { _id: '$id', region_id: { $first: '$region_id' }, identifier: { $first: '$identifier' }, versionGroups: { $push: '$versionGroups.version_group_id' } } }, { $lookup: { from: 'pokedex_prose', localField: '_id', foreignField: 'pokedex_id', as: 'prose' } }, { $unwind: { path: '$prose', preserveNullAndEmptyArrays: true } }, { $match: { 'prose.local_language_id': 9 } }, { $project: { _id: 1, region_id: 1, identifier: 1, versionGroups: 1, name: '$prose.name', description: '$prose.description' } }, { $sort: { _id: 1 } }, { $out: 'A_NEW_pokedexes' } ], (err) => { callback(err); }); }; // Pokemon Move Methods const dbPokemonMoveMethods = function (callback) { console.log('Running dbPokemonMoveMethods...'); db.pokemon_move_methods.aggregate([ { $lookup: { from: 'pokemon_move_method_prose', localField: 'id', foreignField: 'pokemon_move_method_id', as: 'prose' } }, { $unwind: { path: '$prose', preserveNullAndEmptyArrays: true } }, { $match: { 'prose.local_language_id': 9 } }, { $project: { _id: '$id', identifier: 1, name: '$prose.name', description: '$prose.description' } }, { $out: 'A_NEW_pokemonMoveMethods' } ], (err) => { callback(err); }); }; // Pokemon Moves const dbPokemonMoves = function (callback) { console.log('Running dbPokemonMoves...'); db.pokemon_moves.aggregate([ { $project: { pokemon_id: 1, versionGroup_id: '$version_group_id', move_id: 1, moveMethod_id: '$pokemon_move_method_id', level: 1, order: 1 } }, { $out: 'A_NEW_pokemonMoves' } ], (err) => { callback(err); }); }; // Stats const dbStats = function (callback) { console.log('Running dbStats...'); db.collection('stats').aggregate([ { $lookup: { from: 'stat_names', localField: 'id', foreignField: 'stat_id', as: 'names' } }, { $unwind: { path: '$names', preserveNullAndEmptyArrays: true } }, { $match: { 'names.local_language_id': 9 } }, { $project: { _id: '$id', damageClass_id: '$damage_class_id', identifier: 1, isBattleOnly: '$is_battle_only', name: '$names.name' } }, { $out: 'A_NEW_stats' } ], (err) => { callback(err); }); }; // Types const dbTypes = function (callback) { console.log('Running dbTypes...'); db.types.aggregate([ { $lookup: { from: 'type_names', localField: 'id', foreignField: 'type_id', as: 'names' } }, { $unwind: { path: '$names', preserveNullAndEmptyArrays: true } }, { $match: { 'names.local_language_id': 9 } }, { $lookup: { from: 'type_efficacy', localField: 'id', foreignField: 'damage_type_id', as: 'efficacy' } }, { $unwind: { path: '$efficacy', preserveNullAndEmptyArrays: true } }, { $group: { _id: '$id', identifier: { $first: '$identifier' }, damageClass_id: { $first: '$damage_class_id' }, name: { $first: '$names.name' }, efficacy: { $push: { _id: '$efficacy.target_type_id', damageFactor: '$efficacy.damage_factor' } } } }, { $sort: { _id: 1 } }, { $out: 'A_NEW_types' } ], (err) => { callback(err); }); }; // Versions const dbVersions = function (callback) { console.log('Running dbVersions...'); db.versions.aggregate([ { $lookup: { from: 'version_names', localField: 'id', foreignField: 'version_id', as: 'names' } }, { $unwind: { path: '$names', preserveNullAndEmptyArrays: true } }, { $match: { 'names.local_language_id': 9 } }, { $lookup: { from: 'version_groups', localField: 'version_group_id', foreignField: 'id', as: 'version_group' } }, { $unwind: { path: '$version_group', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'version_group_pokemon_move_methods', localField: 'version_group.id', foreignField: 'version_group_id', as: 'move_methods' } }, { $unwind: { path: '$move_methods', preserveNullAndEmptyArrays: true } }, { $lookup: { from: 'version_group_regions', localField: 'version_group.id', foreignField: 'version_group_id', as: 'regions' } }, { $unwind: { path: '$regions', preserveNullAndEmptyArrays: true } }, { $group: { _id: '$id', identifier: { $first: '$identifier' }, name: { $first: '$names.name' }, generation_id: { $first: '$version_group.generation_id' }, moveMethods: { $addToSet: '$move_methods.pokemon_move_method_id' }, regions: { $addToSet: '$regions.region_id' } } }, { $sort: { _id: 1 } }, { $out: 'A_NEW_versions' } ], (err) => { callback(err); }); }; // Drop Old dbs const dropOld = (callback) => { console.log('Dropping old collections...'); async.parallel([ function (innerCallback) { db.ability_changelog.drop(innerCallback); }, function (innerCallback) { db.ability_changelog_prose.drop(innerCallback); }, function (innerCallback) { db.abilities.drop(innerCallback); }, function (innerCallback) { db.ability_flavor_text.drop(innerCallback); }, function (innerCallback) { db.ability_names.drop(innerCallback); }, function (innerCallback) { db.ability_prose.drop(innerCallback); }, function (innerCallback) { db.pokemon_egg_groups.drop(innerCallback); }, function (innerCallback) { db.pokemon_evolution.drop(innerCallback); }, function (innerCallback) { db.pokemon_colors.drop(innerCallback); }, function (innerCallback) { db.pokemon_color_names.drop(innerCallback); }, function (innerCallback) { db.pokemon_shapes.drop(innerCallback); }, function (innerCallback) { db.pokemon_shape_prose.drop(innerCallback); }, function (innerCallback) { db.pokemon_habitats.drop(innerCallback); }, function (innerCallback) { db.pokemon_habitat_names.drop(innerCallback); }, function (innerCallback) { db.pokemon_species_flavor_text.drop(innerCallback); }, function (innerCallback) { db.pokemon_species_names.drop(innerCallback); }, function (innerCallback) { db.pokemon_species_prose.drop(innerCallback); }, function (innerCallback) { db.pokemon_forms.drop(innerCallback); }, function (innerCallback) { db.pokemon_form_names.drop(innerCallback); }, function (innerCallback) { db.pokemon_abilities.drop(innerCallback); }, function (innerCallback) { db.pokemon_stats.drop(innerCallback); }, function (innerCallback) { db.pokemon_types.drop(innerCallback); }, function (innerCallback) { db.pokemon.drop(innerCallback); }, function (innerCallback) { db.pokemon_species.drop(innerCallback); }, function (innerCallback) { db.pokemon_dex_numbers.drop(innerCallback); }, function (innerCallback) { db.pokemon_form_generations.drop(innerCallback); }, function (innerCallback) { db.pokemon_form_pokeathlon_stats.drop(innerCallback); }, function (innerCallback) { db.pokemon_game_indices.drop(innerCallback); }, function (innerCallback) { db.pokemon_items.drop(innerCallback); }, function (innerCallback) { db.berries.drop(innerCallback); }, function (innerCallback) { db.berry_firmness.drop(innerCallback); }, function (innerCallback) { db.berry_firmness_names.drop(innerCallback); }, function (innerCallback) { db.berry_flavors.drop(innerCallback); }, function (innerCallback) { db.characteristics.drop(innerCallback); }, function (innerCallback) { db.characteristic_text.drop(innerCallback); }, function (innerCallback) { db.egg_groups.drop(innerCallback); }, function (innerCallback) { db.egg_group_prose.drop(innerCallback); }, function (innerCallback) { db.encounter_conditions.drop(innerCallback); }, function (innerCallback) { db.encounter_condition_prose.drop(innerCallback); }, function (innerCallback) { db.encounter_condition_values.drop(innerCallback); }, function (innerCallback) { db.encounter_condition_value_map.drop(innerCallback); }, function (innerCallback) { db.encounter_condition_value_prose.drop(innerCallback); }, function (innerCallback) { db.encounter_methods.drop(innerCallback); }, function (innerCallback) { db.encounter_method_prose.drop(innerCallback); }, function (innerCallback) { db.encounters.drop(innerCallback); }, function (innerCallback) { db.encounter_slots.drop(innerCallback); }, function (innerCallback) { db.evolution_chains.drop(innerCallback); }, function (innerCallback) { db.evolution_triggers.drop(innerCallback); }, function (innerCallback) { db.evolution_trigger_prose.drop(innerCallback); }, function (innerCallback) { db.growth_rates.drop(innerCallback); }, function (innerCallback) { db.experience.drop(innerCallback); }, function (innerCallback) { db.growth_rate_prose.drop(innerCallback); }, function (innerCallback) { db.genders.drop(innerCallback); }, function (innerCallback) { db.generations.drop(innerCallback); }, function (innerCallback) { db.generation_names.drop(innerCallback); }, function (innerCallback) { db.items.drop(innerCallback); }, function (innerCallback) { db.item_names.drop(innerCallback); }, function (innerCallback) { db.item_categories.drop(innerCallback); }, function (innerCallback) { db.item_category_prose.drop(innerCallback); }, function (innerCallback) { db.item_prose.drop(innerCallback); }, function (innerCallback) { db.item_pockets.drop(innerCallback); }, function (innerCallback) { db.item_pocket_names.drop(innerCallback); }, function (innerCallback) { db.item_flag_map.drop(innerCallback); }, function (innerCallback) { db.item_flavor_text.drop(innerCallback); }, function (innerCallback) { db.item_fling_effect_prose.drop(innerCallback); }, function (innerCallback) { db.item_fling_effects.drop(innerCallback); }, function (innerCallback) { db.item_flags.drop(innerCallback); }, function (innerCallback) { db.item_flag_prose.drop(innerCallback); }, function (innerCallback) { db.location_area_encounter_rates.drop(innerCallback); }, function (innerCallback) { db.location_area_prose.drop(innerCallback); }, function (innerCallback) { db.location_areas.drop(innerCallback); }, function (innerCallback) { db.location_names.drop(innerCallback); }, function (innerCallback) { db.locations.drop(innerCallback); }, function (innerCallback) { db.region_names.drop(innerCallback); }, function (innerCallback) { db.regions.drop(innerCallback); }, function (innerCallback) { db.machines.drop(innerCallback); }, function (innerCallback) { db.move_battle_styles.drop(innerCallback); }, function (innerCallback) { db.move_battle_style_prose.drop(innerCallback); }, function (innerCallback) { db.natures.drop(innerCallback); }, function (innerCallback) { db.nature_names.drop(innerCallback); }, function (innerCallback) { db.nature_battle_style_preferences.drop(innerCallback); }, function (innerCallback) { db.nature_pokeathlon_stats.drop(innerCallback); }, function (innerCallback) { db.moves.drop(innerCallback); }, function (innerCallback) { db.move_names.drop(innerCallback); }, function (innerCallback) { db.move_targets.drop(innerCallback); }, function (innerCallback) { db.move_target_prose.drop(innerCallback); }, function (innerCallback) { db.move_damage_classes.drop(innerCallback); }, function (innerCallback) { db.move_damage_class_prose.drop(innerCallback); }, function (innerCallback) { db.move_effects.drop(innerCallback); }, function (innerCallback) { db.move_effect_prose.drop(innerCallback); }, function (innerCallback) { db.move_meta.drop(innerCallback); }, function (innerCallback) { db.move_meta_ailments.drop(innerCallback); }, function (innerCallback) { db.move_meta_ailment_names.drop(innerCallback); }, function (innerCallback) { db.move_meta_categories.drop(innerCallback); }, function (innerCallback) { db.move_meta_category_prose.drop(innerCallback); }, function (innerCallback) { db.move_meta_stat_changes.drop(innerCallback); }, function (innerCallback) { db.move_flag_map.drop(innerCallback); }, function (innerCallback) { db.move_changelog.drop(innerCallback); }, function (innerCallback) { db.move_effect_changelog.drop(innerCallback); }, function (innerCallback) { db.move_effect_changelog_prose.drop(innerCallback); }, function (innerCallback) { db.move_flavor_text.drop(innerCallback); }, function (innerCallback) { db.move_flags.drop(innerCallback); }, function (innerCallback) { db.move_flag_prose.drop(innerCallback); }, function (innerCallback) { db.pal_park.drop(innerCallback); }, function (innerCallback) { db.pal_park_area_names.drop(innerCallback); }, function (innerCallback) { db.pal_park_areas.drop(innerCallback); }, function (innerCallback) { db.pokedex_prose.drop(innerCallback); }, function (innerCallback) { db.pokedex_version_groups.drop(innerCallback); }, function (innerCallback) { db.pokedexes.drop(innerCallback); }, function (innerCallback) { db.pokemon_move_method_prose.drop(innerCallback); }, function (innerCallback) { db.pokemon_move_methods.drop(innerCallback); }, function (innerCallback) { db.pokemon_moves.drop(innerCallback); }, function (innerCallback) { db.stat_names.drop(innerCallback); }, function (innerCallback) { db.collection('stats').drop(innerCallback); }, function (innerCallback) { db.type_efficacy.drop(innerCallback); }, function (innerCallback) { db.type_names.drop(innerCallback); }, function (innerCallback) { db.types.drop(innerCallback); }, function (innerCallback) { db.version_group_pokemon_move_methods.drop(innerCallback); }, function (innerCallback) { db.version_group_regions.drop(innerCallback); }, function (innerCallback) { db.version_groups.drop(innerCallback); }, function (innerCallback) { db.version_names.drop(innerCallback); }, function (innerCallback) { db.versions.drop(innerCallback); } ], (err) => { callback(err); }); }; const dropUnused = (callback) => { console.log('Dropping unused collections...'); async.parallel([ function (innerCallback) { db.conquest_episode_names.drop(innerCallback); }, function (innerCallback) { db.conquest_episode_warriors.drop(innerCallback); }, function (innerCallback) { db.conquest_episodes.drop(innerCallback); }, function (innerCallback) { db.conquest_kingdom_names.drop(innerCallback); }, function (innerCallback) { db.conquest_kingdoms.drop(innerCallback); }, function (innerCallback) { db.conquest_max_links.drop(innerCallback); }, function (innerCallback) { db.conquest_move_data.drop(innerCallback); }, function (innerCallback) { db.conquest_move_displacement_prose.drop(innerCallback); }, function (innerCallback) { db.conquest_move_displacements.drop(innerCallback); }, function (innerCallback) { db.conquest_move_effect_prose.drop(innerCallback); }, function (innerCallback) { db.conquest_move_effects.drop(innerCallback); }, function (innerCallback) { db.conquest_move_range_prose.drop(innerCallback); }, function (innerCallback) { db.conquest_move_ranges.drop(innerCallback); }, function (innerCallback) { db.conquest_pokemon_abilities.drop(innerCallback); }, function (innerCallback) { db.conquest_pokemon_evolution.drop(innerCallback); }, function (innerCallback) { db.conquest_pokemon_moves.drop(innerCallback); }, function (innerCallback) { db.conquest_pokemon_stats.drop(innerCallback); }, function (innerCallback) { db.conquest_stat_names.drop(innerCallback); }, function (innerCallback) { db.conquest_stats.drop(innerCallback); }, function (innerCallback) { db.conquest_transformation_pokemon.drop(innerCallback); }, function (innerCallback) { db.conquest_transformation_warriors.drop(innerCallback); }, function (innerCallback) { db.conquest_warrior_archetypes.drop(innerCallback); }, function (innerCallback) { db.conquest_warrior_names.drop(innerCallback); }, function (innerCallback) { db.conquest_warrior_rank_stat_map.drop(innerCallback); }, function (innerCallback) { db.conquest_warrior_ranks.drop(innerCallback); }, function (innerCallback) { db.conquest_warrior_skill_names.drop(innerCallback); }, function (innerCallback) { db.conquest_warrior_skills.drop(innerCallback); }, function (innerCallback) { db.conquest_warrior_specialties.drop(innerCallback); }, function (innerCallback) { db.conquest_warrior_stat_names.drop(innerCallback); }, function (innerCallback) { db.conquest_warrior_stats.drop(innerCallback); }, function (innerCallback) { db.conquest_warrior_transformation.drop(innerCallback); }, function (innerCallback) { db.conquest_warriors.drop(innerCallback); }, function (innerCallback) { db.contest_combos.drop(innerCallback); }, function (innerCallback) { db.contest_effect_prose.drop(innerCallback); }, function (innerCallback) { db.contest_effects.drop(innerCallback); }, function (innerCallback) { db.contest_type_names.drop(innerCallback); }, function (innerCallback) { db.contest_types.drop(innerCallback); }, function (innerCallback) { db.languages.drop(innerCallback); }, function (innerCallback) { db.language_names.drop(innerCallback); }, function (innerCallback) { db.pokeathlon_stat_names.drop(innerCallback); }, function (innerCallback) { db.pokeathlon_stats.drop(innerCallback); }, function (innerCallback) { db.item_game_indices.drop(innerCallback); }, function (innerCallback) { db.location_game_indices.drop(innerCallback); }, function (innerCallback) { db.super_contest_combos.drop(innerCallback); }, function (innerCallback) { db.super_contest_effect_prose.drop(innerCallback); }, function (innerCallback) { db.super_contest_effects.drop(innerCallback); }, function (innerCallback) { db.type_game_indices.drop(innerCallback); } ], (err) => { callback(err); }); }; async.parallel([ function (outerCallback) { async.series([ function (innerCallback) { dbAbilities(innerCallback); }, function (innerCallback) { dbPokemon(innerCallback); } ], (err) => { outerCallback(err); }); }, function (callback) { dbPokemonSpecies(callback); }, function (callback) { dbBerries(callback); }, function (callback) { dbCharacteristics(callback); }, function (callback) { dbEggGroups(callback); }, function (callback) { dbEncounterConditions(callback); }, function (callback) { dbEncounterConditionValues(callback); }, function (callback) { dbEncounterMethods(callback); }, function (callback) { dbEncounters(callback); }, function (callback) { dbEncounterSlots(callback); }, function (callback) { dbEvolutionChains(callback); }, function (callback) { dbEvolutionTriggers(callback); }, function (callback) { dbGrowthRates(callback); }, function (callback) { dbGenders(callback); }, function (callback) { dbGenerations(callback); }, function (callback) { dbItems(callback); }, function (callback) { dbItemFlags(callback); }, function (outerCallback) { async.series([ function (innerCallback) { dbLocationAreas(innerCallback); }, function (innerCallback) { dbLocations(innerCallback); }, function (innerCallback) { dbRegions(innerCallback); } ], (err) => { outerCallback(err); }); }, function (callback) { dbMachines(callback); }, function (outerCallback) { async.series([ function (innerCallback) { dbMoveBattleStyles(innerCallback); }, function (innerCallback) { dbNatures(innerCallback); } ], (err) => { outerCallback(err); }); }, function (callback) { dbMoves(callback); }, function (callback) { dbMoveFlags(callback); }, function (callback) { dbPalPark(callback); }, function (callback) { dbPokedexes(callback); }, function (callback) { dbPokemonMoveMethods(callback); }, function (callback) { dbPokemonMoves(callback); }, function (callback) { dbStats(callback); }, function (callback) { dbTypes(callback); }, function (callback) { dbVersions(callback); } ], (err) => { if (err) throw new Error(err); async.parallel([ function (callback) { dropUnused(callback); }, function (callback) { dropOld(callback); } ], (err) => { if (err) throw new Error(err); db.getCollectionNames((err, collections) => { if (err) throw new Error(err); console.log('Renaming collections...'); async.each(collections, (collection, callback) => { if (collection.indexOf('A_NEW_') === -1) { callback(); } else { db.collection(collection).aggregate({ $out: collection.replace('A_NEW_', '') }, (err) => { if (!err) { db.collection(collection).drop(); console.log('Renamed ' + collection + ' to ' + collection.replace('A_NEW_', '')); } callback(err); }); } }, (err) => { if (err) throw new Error(err); db.close(); console.log('Done!'); return; }); }); }); });
gabeotisbenson/pkdex
convertVeekun.js
JavaScript
gpl-3.0
63,511
export const defaultOptions = { workerUrl: "./worker.js" }; export default class Doctored { constructor(options) { this.options = { ...defaultOptions, ...options }; this.worker = new Worker(this.options.workerUrl); } }
holloway/xml-zero.js
packages/doctored/src/doctored.js
JavaScript
gpl-3.0
251
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'indent', 'uk', { indent: 'Збільшити відступ', outdent: 'Зменшити відступ' });
tsmaryka/hitc
public/javascripts/ckeditor/plugins/indent/lang/uk.js
JavaScript
gpl-3.0
286
angular.module('starter.services', []) .factory('ClockService', function () { var riseTime = function () { return moment('2014-01-09 19:47'); }; var currentTime = function () { return moment(); }; var duration = function () { return '2분' }; var ratio = function () { return (riseTime() - currentTime()) / duration(); }; return { riseTime: riseTime, currentTime: currentTime, duration: duration, ratio: ratio }; })
newsun15/newsun-app
myApp/www/js/services.js
JavaScript
gpl-3.0
469
/* * PLUGIN AUTOTOOLS * * Polish language file. * * Author: Dare (piczok@gmail.com) */ var s_PluginFail = "Wtyczka nie będzie działać."; theUILang.autotools = "Autotools"; theUILang.autotoolsEnableLabel = "Włącz funkcję \"AutoEtykieta\", Template: "; theUILang.autotoolsEnableMove = "Wlacz \"AutoMove\" jezeli funkcja torrentu pasuje do funkcji"; theUILang.autotoolsPathToFinished = "Ścieżka dla ukończonych pobierań"; theUILang.autotoolsEnableWatch = "Włącz funkcję \"AutoWatch\" "; theUILang.autotoolsPathToWatch = "Ścieżka do bazowego katalogu obserwowanego"; theUILang.autotoolsWatchStart = "Uruchom pobieranie automatycznie"; theUILang.autotoolsNoPathToFinished = "Wtyczka Autotools: ścieżka dla ukończonych pobierań nie jest skonfigurowana. " + s_PluginFail; theUILang.autotoolsNoPathToWatch = "Autotools plugin: ścieżka bazowa jest nieustawiona. " + s_PluginFail; theUILang.autotoolsFileOpType = "Rodzaj operacji"; theUILang.autotoolsFileOpMove = "Przenieś"; theUILang.autotoolsFileOpHardLink = "Hard link"; theUILang.autotoolsFileOpCopy = "Kopia"; theUILang.autotoolsFileOpSoftLink = "Soft link"; theUILang.autotoolsAddLabel = "Dodaj funkcje torrentu do sciezki"; theUILang.autotoolsAddName = "Dodaj nazwe torrentu do sciezki"; thePlugins.get("autotools").langLoaded();
Rapiddot/ruTorrent
plugins/autotools/lang/pl.js
JavaScript
gpl-3.0
1,344
module.exports = (client, event) => { console.log("Disconnected: " + event.reason + " (" + event.code + ")"); };
ShadeBot/ShadeBot-Discord-Bot
events/disconnect.js
JavaScript
gpl-3.0
118
Bitrix 16.5 Business Demo = 2f5d0080efc973a4fb7c15270caba0f2
gohdan/DFC
known_files/hashes/bitrix/modules/main/install/js/main/amcharts/3.11/lang/fi.js
JavaScript
gpl-3.0
61
/** Copyright 2011, 2012 Kevin Hausmann * * This file is part of PodCatcher Deluxe. * * PodCatcher Deluxe is free software: you can redistribute it * and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * PodCatcher Deluxe 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PodCatcher Deluxe. If not, see <http://www.gnu.org/licenses/>. */ /** * Displays a nice popup for the user to enter login data */ enyo.kind({ name: "Net.Alliknow.PodCatcher.LoginPopup", kind: "ModalDialog", caption: $L("Login"), scrim: false, dismissWithClick: true, events: { onLogin: "" }, components: [ {kind: "Input", name: "userInput", hint: $L("Username"), alwaysLooksFocused: true, selectAllOnFocus: true, spellcheck: false}, {kind: "PasswordInput", name: "passInput", hint: $L("Password"), alwaysLooksFocused: true, selectAllOnFocus: true, spellcheck: false, style: "margin-top: 5px;"}, {kind: "Button", name: "loginButton", caption: $L("Submit"), onclick: "doLogin", style: "margin-top: 8px;", className: "enyo-button-affirmative"} ], open: function() { this.inherited(arguments); this.$.passInput.setValue(""); }, getUser: function() { if (this.$.userInput) return this.$.userInput.getValue(); }, getPass: function() { if (this.$.passInput) return this.$.passInput.getValue(); } });
salema/PodCatcher-Deluxe-webOS
source/LoginPopup.js
JavaScript
gpl-3.0
1,722
describe('drugs', function() { it('should test something', function() { expect(true).toBeTruthy(); }); });
medien-dresden/comprot-frontend
test/unit/app/drugs/drugs.spec.js
JavaScript
gpl-3.0
112
function AssumptionRule(){}; AssumptionRule.prototype.validate = function(proofGraph, curProofLine){ var lnoErrStr = "[line: "+curProofLine.lineNo+"]: " var depAssumptions = curProofLine.depAssumptions; if (depAssumptions.length!=1) { throw lnoErrStr + "An asusmtption rule should have only one dependency, itself!" } if (depAssumptions[0]!=curProofLine.lineNo) { throw lnoErrStr + "An asusmtption rule's dependency should be same as its own line number." } return true; } module.exports = AssumptionRule;
surajx/proof-assistant
FOL/proof/rules/AssumptionRule.js
JavaScript
gpl-3.0
531
/*** * Copyright (c) 2012 John Krauss. * * This file is part of Openscrape. * * Openscrape is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Openscrape 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Openscrape. If not, see <http://www.gnu.org/licenses/>. * ***/ /*global define*/ // location of our jquery svgpan library define(['http://talos.github.com/jquery-svgpan/jquery-svgpan.min.js']);
talos/openscrape
client/js/src/lib/jquery-svgpan-link.js
JavaScript
gpl-3.0
863
angular.module("myApp", ["ngTouch", "ngq"]).service("Data", function() { return { itemList: [], itemListEmpty: !1, itemListErr: !1, itemListLoaded: !1, patientName: "", idcard: "", state: "", _patientName: "", _idcard: "", _state: -1, isFilterPageActive: !1 } }).service("getList", ["$timeout", "Data", function(t, e) { return function() { if (!e.loading) { e.loading = !0; var i = { rId: qlib.getUser().loginId, patientName: e.patientName, idcard: e.idcard, state: e.state, index: qlib.getNextPageNumber(e.itemList.length), pageSize: PAGE_SIZE_DEFAULT, version:"1", times:"1" }; console.log(i), console.log($.param(i)), appcan.request.ajax({ type: "GET", url: SimcereConfig.server.edzy + "patient/page", data: i, contentType: "application/json", dataType: "json", timeout: REQUEST_TIMEOUT, success: function(i, a, n, o, r) { e.loading = !1, appcan.window.closeToast(), console.log(i), "2" == i.status && (i.status = "0", i.data = {}, i.data.rows = []), "0" != i.status ? (appcan.window.openToast(i.msg, SimcereConfig.ui.toastDuration), console.error("res error"), t(function() { e.itemListErr = !e.itemList.length })) : t(function() { e.itemList = e.itemList.concat(i.data.rows), e.itemListEmpty = !e.itemList.length }) }, error: function(i, a, n, o) { e.loading = !1, appcan.window.openToast("网络连接不可用", SimcereConfig.ui.toastDuration), console.error(a), t(function() { e.itemListErr = !e.itemList.length }) } }) } } }]).service("subscribe", ["$timeout", "Data", "getList", function(t, e, i) { return function() { appcan.window.subscribe("EDZY/PatientList.toggleFilter", function() { t(function() { e.isFilterPageActive = !e.isFilterPageActive }) }), appcan.window.subscribe("EDZY/PatientList.filterChange", function() { var a = localStorage.getItem("EDZY/PatientList.filter"), n = JSON.parse(a); angular.extend(e, { patientName: n._patientName, idcard: n._idcard, state: n.state }), t(function() { e.isFilterPageActive = !1, e.itemList.length = 0, i() }) }), appcan.window.subscribe("EDZY/PatientList.refresh", function() { t(function() { e.isFilterPageActive = !1 }), e.itemList.length = 0, i() }), appcan.window.subscribe("EDZY/PatientList.load", function() { t(function() { e.isFilterPageActive = !1 }), i() }) } }]).service("openDetail", ["$timeout", "Data", function(t, e) { return function(t) { return 3 == t.flowType && 4 == t.state ? void appcan.window.alert("提示", "无法查看封存的数据", "知道了") : (console.log(t), localStorage.setItem("EDZY/PatientDetail.patientId", t.id), void appcan.window.open("EDZY_PatientDetail", "PatientDetail.html", 10)) } }]).service("openZyList", ["$timeout", "Data", function(t, e) { return function(t) { return 3 == t.flowType && 4 == t.state ? void appcan.window.alert("提示", "无法查看封存的数据", "知道了") : (console.log(JSON.stringify(t)), localStorage.setItem("EDZY/PatientDetail.patientId", t.id), localStorage.setItem("EDZY/PatientDetail.patientRowId", t.id), void appcan.window.open("EDZY_ZyPatientDetail", "ZyPatientDetail.html", 10)) } }]).service("openYyList", ["$timeout", "Data", function(t, e) { return function(t) { return 3 == t.flowType && 4 == t.state ? void appcan.window.alert("提示", "无法查看封存的数据", "知道了") : (console.log(JSON.stringify(t)), localStorage.setItem("EDZY/PatientDetail.patientId", t.id), void appcan.window.open("EDZY_YyPatientDetail", "YyPatientDetail.html", 10)) } }]).controller("ItemListController", ["$scope", "$timeout", "Data", "getList", "openDetail","openZyList", "openYyList","getStatTxt", function(t, e, i, a, n, z, y, o) { t.openDetail = n, t.openZyList= z, t.openYyList = y, t.getStatTxt = o, a() }]).controller("GlbController", ["$scope", "$timeout", "Data", "subscribe", "getList", function(t, e, i, a, n) { t.Data = i, t.sMAP = { "": "全部", 0: "待审核", 1: "通过", 2: "不通过" }, t.clearPatientName = function() { i.patientName = "", i.itemList.length = 0, n() }, t.clearIdcard = function() { i.idcard = "", i.itemList.length = 0, n() }, t.clearState = function() { "" !== i.state && (i.state = "", i.itemList.length = 0, n()) }, a(), t.$watch("Data.isFilterPageActive", function(t, e) { if (t != e) { var a = $(window).width(); i.isFilterPageActive ? qlib.filterSlideIn(a) : qlib.filterSlideOut(a) } }) }]);
Jerryisokay/enduranceDev
phone/js/ng.ZyPatientList.js
JavaScript
gpl-3.0
4,834
(function () { angular .module("WebAppMaker", ["ngRoute", "textAngular", "wamDirectives"]); })();
knuevena/knueven-andrew-webdev
public/assignment/js/app.js
JavaScript
gpl-3.0
106
// discussions.js module.exports = function(app, db) { var log = require('util').log, DiscussionService = require('../../services/discussion'); app.get('/api/discussion/threads', function(req, res) { //log("getting all items"); DiscussionService.getByThread().then(function(threads) { res.send(threads); }, function(error) { res.send(error, 500); }); }); // create a new item template, editor only function app.post('/api/discussion/threads', app.ensureAuthenticated, function(req, res) { var data = { subject: req.body.subject, body: req.body.body, author_id: req.body.author_id, tags: req.body.tags }; DiscussionService.createThread(data.subject, data.body, data.author_id, data.tags) .then(function(post) { res.send(post); }, function(err) { res.send(500, err); }); }); };
ironbane/IronbaneServerLegacy
src/server/http/routes/discussions.js
JavaScript
gpl-3.0
1,007
// Takes the gutter width from the bottom margin of .post var gutter = parseInt(jQuery('.post').css('marginBottom')); var container = jQuery('#posts'); // Creates an instance of Masonry on #posts container.masonry({ gutter: gutter, itemSelector: '.post', columnWidth: '.post' }); // This code fires every time a user resizes the screen and only affects .post elements // whose parent class isn't .container. Triggers resize first so nothing looks weird. jQuery(window).bind('resize', function() { if (!jQuery('#posts').parent().hasClass('container')) { // Resets all widths to 'auto' to sterilize calculations post_width = jQuery('.post').width() + gutter; jQuery('#posts, body > #grid').css('width', 'auto'); // Calculates how many .post elements will actually fit per row. Could this code be cleaner? posts_per_row = jQuery('#posts').innerWidth() / post_width; floor_posts_width = (Math.floor(posts_per_row) * post_width) - gutter; ceil_posts_width = (Math.ceil(posts_per_row) * post_width) - gutter; posts_width = (ceil_posts_width > jQuery('#posts').innerWidth()) ? floor_posts_width : ceil_posts_width; if (posts_width == jQuery('.post').width()) { posts_width = '100%'; } // Ensures that all top-level elements have equal width and stay centered jQuery('#posts, #grid').css('width', posts_width); jQuery('#grid').css({ 'margin': '0 auto' }); } }).trigger('resize');
mrvinceo/wp-vinceo-bootstrap
js/masonryCode.js
JavaScript
gpl-3.0
1,494
/*global Ext, i18n*/ //<debug> console.log(new Date().toLocaleTimeString() + ": Log: Load: WPAKD.view.accesscontrol.groups.GroupsList"); //</debug> Ext.define("WPAKD.view.accesscontrol.groups.GroupsList", { extend: "Ext.grid.Panel", alias : "widget.accesscontrolgroupsgroupslist", store: "accesscontrol.groups.Groups", stateful: true, stateId: "accesscontrolgroupsgroupslist", autoScroll: true, columns: [ {text: i18n.gettext("GRO_ID"), dataIndex: "GRO_ID", align: "right", width: 40, sortable: true, hidden: true }, {text: i18n.gettext("Name"), dataIndex: "NAME", align: "left", flex: 1, sortable: true, allowBlank: false, field: {xtype: "textfield"} }, {text: i18n.gettext("Notes"), dataIndex: "NOTES", align: "left", flex: 3, sortable: true, field: {xtype: "textfield"} } ], selType: "rowmodel", plugins: [ Ext.create("Ext.grid.plugin.RowEditing", { clicksToEdit: 2, pluginId: "rowediting" }), Ext.create("Ext.grid.plugin.BufferedRenderer", {}) ] });
Webcampak/ui
Sencha/App6.0/workspace/Desktop/app/view/accesscontrol/groups/GroupsList.js
JavaScript
gpl-3.0
1,181
// ceb.po i18n_lang = {" days." : "", "(all)" : "", "(any)" : "", "(anyone)" : "", "(available)" : "", "(blank)" : "", "(both)" : "", "(everyone)" : "", "(master user, not editable)" : "", "(no change)" : "", "(no deduction)" : "", "(none)" : "", "(unknown)" : "", "(use system)" : "", "({0} given, {1} remaining)" : "", "1 treatment" : "", "1 week" : "", "1 year" : "", "2 weeks" : "", "3 months" : "", "4 weeks" : "", "5 Year" : "", "6 months" : "", "6 weeks" : "", "8 weeks" : "", "9 months" : "", "A (Stray Dog)" : "", "A description or other information about the animal" : "", "A list of areas this person will homecheck - eg: S60 S61" : "", "A movement must have a reservation date or type." : "", "A person is required for this movement type." : "", "A publish job is already running." : "", "A short version of the reference number" : "", "A task is already running." : "", "A unique number to identify this movement" : "", "A unique reference for this litter" : "", "A4" : "", "ACO" : "", "AM" : "", "ASM" : "", "ASM 3 is compatible with your iPad and other tablets." : "", "ASM News" : "", "ASM can track detailed monthly and annual figures for your shelter. Install the Monthly Figures and Annual Figures reports from Settings-Reports-Browse sheltermanager.com" : "", "ASM comes with a dictionary of 4,000 animal names. Just click the generate random name button when adding an animal." : "", "ASM will remove this animal from the waiting list after a set number of weeks since the last owner contact date." : "", "Abandoned" : "", "Abuse" : "", "Abyssinian" : "", "Access System Menu" : "", "Account" : "", "Account Types" : "", "Account code '{0}' has already been used." : "", "Account code '{0}' is not valid." : "", "Account code cannot be blank." : "", "Account disabled." : "", "Accountant" : "", "Accounts" : "", "Accounts need a code." : "", "Active" : "", "Active Incidents" : "", "Active Trap Loans" : "", "Active users: {0}" : "", "Add" : "", "Add Accounts" : "", "Add Animal" : "", "Add Animals" : "", "Add Appointment" : "", "Add Call" : "", "Add Citations" : "", "Add Clinic Appointment" : "", "Add Cost" : "", "Add Diary" : "", "Add Diets" : "", "Add Document to Repository" : "", "Add Flag" : "", "Add Found Animal" : "", "Add Incidents" : "", "Add Investigation" : "", "Add Invoice Item" : "", "Add Licenses" : "", "Add Litter" : "", "Add Log" : "", "Add Log to Animal" : "", "Add Lost Animal" : "", "Add Media" : "", "Add Medical Records" : "", "Add Message" : "", "Add Movement" : "", "Add Payments" : "", "Add Person" : "", "Add Report" : "", "Add Rota" : "", "Add Stock" : "", "Add Tests" : "", "Add Transport" : "", "Add Trap Loans" : "", "Add Users" : "", "Add Vaccinations" : "", "Add Vouchers" : "", "Add Waiting List" : "", "Add a diary note" : "", "Add a found animal" : "", "Add a log entry" : "", "Add a lost animal" : "", "Add a medical regimen" : "", "Add a new animal" : "", "Add a new log" : "", "Add a new person" : "", "Add a person" : "", "Add a photo" : "", "Add a test" : "", "Add a vaccination" : "", "Add account" : "", "Add additional field" : "", "Add an animal to the waiting list" : "", "Add citation" : "", "Add cost" : "", "Add details of this email to the log after sending" : "", "Add diary" : "", "Add diary task" : "", "Add diet" : "", "Add extra images for use in reports and documents" : "", "Add form field" : "", "Add found animal" : "", "Add investigation" : "", "Add license" : "", "Add litter" : "", "Add log" : "", "Add lost animal" : "", "Add medical profile" : "", "Add medical regimen" : "", "Add message" : "", "Add movement" : "", "Add online form" : "", "Add payment" : "", "Add person" : "", "Add report" : "", "Add role" : "", "Add rota item" : "", "Add stock" : "", "Add template" : "", "Add test" : "", "Add this text to all animal descriptions" : "", "Add to log" : "", "Add transport" : "", "Add trap loan" : "", "Add user" : "", "Add vaccination" : "", "Add voucher" : "", "Add waiting list" : "", "Add {0}" : "", "Added" : "", "Added by {0} on {1}" : "", "Additional" : "", "Additional Fields" : "", "Additional date field '{0}' contains an invalid date." : "", "Additional fields" : "", "Additional fields need a name, label and type." : "", "Address" : "", "Address Contains" : "", "Address contains" : "", "Administered" : "", "Administering Vet" : "", "Adopt" : "", "Adopt an animal" : "", "Adoptable" : "", "Adoptable Animal" : "", "Adoptable and published for the first time" : "", "Adopted" : "", "Adopted Animals" : "", "Adopted Transferred In {0}" : "", "Adoption" : "", "Adoption Coordinator" : "", "Adoption Coordinator and Fosterer" : "", "Adoption Event" : "", "Adoption Fee" : "", "Adoption Number" : "", "Adoption fee donations" : "", "Adoption movements must have a valid adoption date." : "", "Adoption successfully created." : "", "Adoptions {0}" : "", "Adult" : "", "Advanced" : "", "Advanced find animal screen defaults to on shelter" : "", "Affenpinscher" : "", "Afghan Hound" : "", "African Grey" : "", "After the user presses submit and ASM has accepted the form, redirect the user to this URL" : "", "Age" : "", "Age Group" : "", "Age Group 1" : "", "Age Group 2" : "", "Age Group 3" : "", "Age Group 4" : "", "Age Group 5" : "", "Age Group 6" : "", "Age Group 7" : "", "Age Group 8" : "", "Age Groups" : "", "Age groups are assigned based on the age of an animal. The figure in the left column is the upper limit in years for that group." : "", "Aged Between" : "", "Aged From" : "", "Aged To" : "", "Aggression" : "", "Airedale Terrier" : "", "Akbash" : "", "Akita" : "", "Alaskan Malamute" : "", "Alerts" : "", "All Animals" : "", "All On-Shelter Animals" : "", "All Publishers" : "", "All accounts" : "", "All animal care officers on file." : "", "All animal shelters on file." : "", "All animals matching current publishing options." : "", "All animals on the shelter." : "", "All animals where the hold ends today." : "", "All animals who are currently held in case of reclaim." : "", "All animals who are currently quarantined." : "", "All animals who are flagged as not for adoption." : "", "All animals who have been on the shelter longer than {0} months." : "", "All animals who have not been microchipped" : "", "All banned owners on file." : "", "All diary notes" : "", "All donors on file." : "", "All drivers on file." : "", "All existing data in your database will be REMOVED before importing the CSV file. This removal cannot be reversed." : "", "All fields should be completed." : "", "All fosterers on file." : "", "All homechecked owners on file." : "", "All homecheckers on file." : "", "All members on file." : "", "All notes upto today" : "", "All people on file." : "", "All retailers on file." : "", "All staff on file." : "", "All time" : "", "All vets on file." : "", "All volunteers on file." : "", "Allergies" : "", "Allow a fosterer to be selected" : "", "Allow an adoption coordinator to be selected" : "", "Allow creation of payments on the Move-Reserve screen" : "", "Allow drag and drop to move animals between locations" : "", "Allow duplicate license numbers" : "", "Allow duplicate microchip numbers" : "", "Allow overriding of the movement number on the Move menu screens" : "", "Allow use of OpenOffice document templates" : "", "Alphabetically A-Z" : "", "Alphabetically Z-A" : "", "Already Signed" : "", "Already fostered to this person." : "", "Altered" : "", "Altered Date" : "", "Altered Dog - 1 year" : "", "Altered Dog - 3 year" : "", "Altering Vet" : "", "Always show an emblem to indicate the current location" : "", "Amazon" : "", "Amber" : "", "American" : "", "American Bulldog" : "", "American Curl" : "", "American Eskimo Dog" : "", "American Fuzzy Lop" : "", "American Sable" : "", "American Shorthair" : "", "American Staffordshire Terrier" : "", "American Water Spaniel" : "", "American Wirehair" : "", "Amount" : "", "An age in years, eg: 1, 0.5" : "", "An animal cannot have multiple open movements." : "", "An optional comma separated list of email addresses to send the output of this report to" : "", "Anatolian Shepherd" : "", "Angora Rabbit" : "", "Animal" : "", "Animal '{0}' created with code {1}" : "", "Animal '{0}' successfully marked deceased." : "", "Animal (optional)" : "", "Animal (via animalname field)" : "", "Animal - Additional" : "", "Animal - Death" : "", "Animal - Details" : "", "Animal - Entry" : "", "Animal - Health and Identification" : "", "Animal - Notes" : "", "Animal Codes" : "", "Animal Control" : "", "Animal Control Caller" : "", "Animal Control Incident" : "", "Animal Control Officer" : "", "Animal Control Victim" : "", "Animal Emblems" : "", "Animal Flags" : "", "Animal Links" : "", "Animal Name" : "", "Animal Selection" : "", "Animal Shelter Manager" : "", "Animal Shelter Manager Login" : "", "Animal Sponsorship" : "", "Animal Type" : "", "Animal Types" : "", "Animal board costs" : "", "Animal cannot be deceased before it was brought to the shelter" : "", "Animal code format" : "", "Animal comments MUST contain this phrase in order to match." : "", "Animal control calendar" : "", "Animal control incidents matching '{0}'." : "", "Animal defecation" : "", "Animal descriptions" : "", "Animal destroyed" : "", "Animal emblems are the little icons that appear next to animal names in shelter view, the home page and search results." : "", "Animal food costs" : "", "Animal picked up" : "", "Animal shortcode format" : "", "Animals" : "", "Animals at large" : "", "Animals left in vehicle" : "", "Animals matching '{0}'." : "", "Animals per page" : "", "Annual" : "", "Annually" : "", "Anonymize" : "", "Anonymize personal data after this many years" : "", "Any animal types, species, breeds, colors, locations, etc. in the CSV file that aren't already in the database will be created during the import." : "", "Any health problems the animal has" : "", "Any information about the animal" : "", "Any markings or distinguishing features the animal has" : "", "Appaloosa" : "", "Appenzell Mountain Dog" : "", "Applehead Siamese" : "", "Appointment" : "", "Appointment date must be a valid date" : "", "Appointment {0}. {1} on {2} for {3}" : "", "Appointments need a date and time." : "", "Approved" : "", "Apr" : "", "April" : "", "Arabian" : "", "Area" : "", "Area Found" : "", "Area Lost" : "", "Area Postcode" : "", "Area where the animal was found" : "", "Area where the animal was lost" : "", "Areas" : "", "Arrived" : "", "Asset" : "", "Asset::Premises" : "", "At least the last name should be completed." : "", "Attach" : "", "Attach File" : "", "Attach Link" : "", "Attach a file" : "", "Attach a link to a web resource" : "", "Attach link" : "", "Audit Trail" : "", "Aug" : "", "August" : "", "Australian Cattle Dog/Blue Heeler" : "", "Australian Kelpie" : "", "Australian Shepherd" : "", "Australian Terrier" : "", "Auto log users out after this many minutes of inactivity" : "", "Auto removed due to lack of owner contact." : "", "Automatically cancel any outstanding reservations on an animal when it is adopted" : "", "Automatically remove" : "", "Automatically return any outstanding foster movements on an animal when it is adopted" : "", "Automatically return any outstanding foster movements on an animal when it is transferred" : "", "Available for adoption" : "", "Available sheltermanager.com reports" : "", "B (Boarding Animal)" : "", "Baby" : "", "Balance" : "", "Balinese" : "", "Bank" : "", "Bank account interest" : "", "Bank current account" : "", "Bank deposit account" : "", "Bank savings account" : "", "Bank::Current" : "", "Bank::Deposit" : "", "Bank::Savings" : "", "Banned" : "", "Base Color" : "", "Basenji" : "", "Basset Hound" : "", "Batch" : "", "Batch Number" : "", "Beagle" : "", "Bearded Collie" : "", "Beauceron" : "", "Bedlington Terrier" : "", "Beginning of month" : "", "Belgian Hare" : "", "Belgian Shepherd Dog Sheepdog" : "", "Belgian Shepherd Laekenois" : "", "Belgian Shepherd Malinois" : "", "Belgian Shepherd Tervuren" : "", "Bengal" : "", "Bernese Mountain Dog" : "", "Beveren" : "", "Bichon Frise" : "", "Bird" : "", "Birman" : "", "Bite" : "", "Biting" : "", "Black" : "", "Black Labrador Retriever" : "", "Black Mouth Cur" : "", "Black Tortie" : "", "Black and Brindle" : "", "Black and Brown" : "", "Black and Tan" : "", "Black and Tan Coonhound" : "", "Black and White" : "", "Bloodhound" : "", "Blue" : "", "Blue Tortie" : "", "Bluetick Coonhound" : "", "Board and Food" : "", "Boarding" : "", "Boarding Cost" : "", "Boarding cost type" : "", "Bobtail" : "", "Body" : "", "Bombay" : "", "Bonded" : "", "Bonded With" : "", "Books" : "", "Border Collie" : "", "Border Terrier" : "", "Bordetella" : "", "Born in Shelter" : "", "Born on Foster {0}" : "", "Born on Shelter {0}" : "", "Borzoi" : "", "Boston Terrier" : "", "Both" : "", "Bouvier des Flanders" : "", "Boxer" : "", "Boykin Spaniel" : "", "Breed" : "Pasanay", "Breed to use when publishing to third party services and adoption sites" : "", "Breeds" : "", "Briard" : "", "Brindle" : "", "Brindle and Black" : "", "Brindle and White" : "", "Britannia Petite" : "", "British Shorthair" : "", "Brittany Spaniel" : "", "Brotogeris" : "", "Brought In" : "", "Brought In By" : "", "Brown" : "", "Brown and Black" : "", "Brown and White" : "", "Browse sheltermanager.com" : "", "Browse sheltermanager.com and install some reports, charts and mail merges into your new system." : "", "Brussels Griffon" : "", "Budgie/Budgerigar" : "", "Bulk Complete Diary" : "", "Bulk Complete Medical Records" : "", "Bulk Complete Vaccinations" : "", "Bulk Complete Waiting List" : "", "Bulk Regimen" : "", "Bulk Test" : "", "Bulk Transport" : "", "Bulk Vaccination" : "", "Bulk change animals" : "", "Bull Terrier" : "", "Bullmastiff" : "", "Bunny Rabbit" : "", "Burmese" : "", "Burmilla" : "", "By" : "", "CC" : "", "CSV of animal/adopter data" : "", "CSV of animal/medical data" : "", "CSV of incident data" : "", "CSV of license data" : "", "CSV of payment data" : "", "CSV of person data" : "", "Caique" : "", "Cairn Terrier" : "", "Calendar View" : "", "Calendar view" : "", "Calico" : "", "Californian" : "", "Call" : "", "Call Date/Time" : "", "Caller" : "", "Caller Name" : "", "Caller Phone" : "", "Camel" : "", "Can Login" : "", "Can afford donation?" : "", "Can't reserve an animal that has an active movement." : "", "Canaan Dog" : "", "Canadian Hairless" : "", "Canary" : "", "Cancel" : "", "Cancel holds on animals this many days after the brought in date, or 0 to never cancel" : "", "Cancel unadopted reservations after" : "", "Cancel unadopted reservations after this many days, or 0 to never cancel" : "", "Cancelled" : "", "Cancelled Reservation" : "", "Cane Corso Mastiff" : "", "Carolina Dog" : "", "Cash" : "", "Cat" : "", "Catahoula Leopard Dog" : "", "Category" : "", "Cats" : "", "Cattery" : "", "Cattle Dog" : "", "Cavalier King Charles Spaniel" : "", "Cell" : "", "Cell Phone" : "", "Champagne D'Argent" : "", "Change" : "", "Change Accounts" : "", "Change Animals" : "", "Change Citations" : "", "Change Clinic Apointment" : "", "Change Cost" : "", "Change Date Required" : "", "Change Diets" : "", "Change Found Animal" : "", "Change Incidents" : "", "Change Investigation" : "", "Change Licenses" : "", "Change Litter" : "", "Change Log" : "", "Change Lost Animal" : "", "Change Media" : "", "Change Medical Records" : "", "Change Movement" : "", "Change Password" : "", "Change Payments" : "", "Change Person" : "", "Change Publishing Options" : "", "Change Report" : "", "Change Rota" : "", "Change Stock" : "", "Change System Options" : "", "Change Tests" : "", "Change Transactions" : "", "Change Transport" : "", "Change Trap Loans" : "", "Change User Settings" : "", "Change Vaccinations" : "", "Change Vouchers" : "", "Change Waiting List" : "", "Change date required on selected treatments" : "", "Changed Mind" : "", "Chart" : "", "Chart (Bar)" : "", "Chart (Line)" : "", "Chart (Pie)" : "", "Chart (Point)" : "", "Chart (Steps)" : "", "Chartreux" : "", "Check" : "", "Check License" : "", "Check No" : "", "Checkbox" : "", "Checked By" : "", "Checkered Giant" : "", "Cheque" : "", "Chesapeake Bay Retriever" : "", "Chicken" : "", "Chihuahua" : "", "Children" : "", "Chinchilla" : "", "Chinese Crested Dog" : "", "Chinese Foo Dog" : "", "Chlamydophila" : "", "Chocolate" : "", "Chocolate Labrador Retriever" : "", "Chocolate Tortie" : "", "Chow Chow" : "", "Cinnamon" : "", "Cinnamon Tortoiseshell" : "", "Citation Type" : "", "Citation Types" : "", "Citations" : "", "City" : "", "City contains" : "", "Class" : "", "Clear" : "", "Clear and sign again" : "", "Clear tables before importing" : "", "Clinic" : "", "Clinic Calendar" : "", "Clinic Invoice - {0}" : "", "Clinic Statuses" : "", "Clone" : "", "Clone Animals" : "", "Clone Rota" : "", "Clone the rota this week to another week" : "", "Cloning..." : "", "Close" : "", "Clumber Spaniel" : "", "Clydesdale" : "", "Coat" : "", "Coat Type" : "", "Coat Types" : "", "Cockapoo" : "", "Cockatiel" : "", "Cockatoo" : "", "Cocker Spaniel" : "", "Code" : "Kodigo", "Code contains" : "", "Code format tokens:" : "", "Collie" : "", "Color" : "Kolor", "Color to use when publishing to third party services and adoption sites" : "", "Colors" : "", "Columns" : "", "Columns displayed" : "", "Comma separated list of units for this location, eg: 1,2,3,4,Isolation,Pen 5" : "", "Comments" : "", "Comments Contain" : "", "Comments contain" : "", "Comments copied to web preferred media." : "", "Complaint" : "", "Complete" : "", "Complete Tasks" : "", "Completed" : "", "Completed Between" : "", "Completed Type" : "", "Completed notes upto today" : "", "Completion Date" : "", "Completion Type" : "", "Configuration" : "", "Confirm" : "", "Confirm Password" : "", "Confirmation message" : "", "Confirmed" : "", "Consulting Room" : "", "Consulting Room - {0}" : "", "Consumed" : "", "Contact" : "", "Contact Contains" : "", "Conure" : "", "Convert this reservation to an adoption" : "", "Coonhound" : "", "Copy animal comments to the notes field of the web preferred media for this animal" : "", "Copy from animal comments" : "", "Copy of {0}" : "", "Corded" : "", "Corgi" : "", "Cornish Rex" : "", "Cost" : "", "Cost For" : "", "Cost Type" : "", "Cost Types" : "", "Cost date must be a valid date" : "", "Cost record" : "", "Costs" : "", "Costs need a date and amount." : "", "Coton de Tulear" : "", "Could not find animal with name '{0}'" : "", "Country" : "", "Courtesy Listing" : "", "Cow" : "", "Cream" : "", "Create" : "", "Create Animal" : "", "Create Log" : "", "Create Payment" : "", "Create Waiting List" : "", "Create a cost record" : "", "Create a due or received payment record from this appointment" : "", "Create a new animal by copying this one" : "", "Create a new animal from this found animal record" : "", "Create a new animal from this incident" : "", "Create a new animal from this waiting list entry" : "", "Create a new document" : "", "Create a new template" : "", "Create a new template by copying the selected template" : "", "Create a new waiting list entry from this found animal record" : "", "Create and edit" : "", "Create boarding cost record when animal is adopted" : "", "Create diary notes from a task" : "", "Create missing lookup values" : "", "Create note this many days from today, or 9999 to ask" : "", "Create this message" : "", "Create this person" : "", "Created By" : "", "Creating cost and cost types creates matching accounts and transactions" : "", "Creating payments and payments types creates matching accounts and transactions" : "", "Creating..." : "", "Credit Card" : "", "Creme D'Argent" : "", "Criteria:" : "", "Crossbreed" : "", "Cruelty Case" : "", "Culling" : "", "Curly" : "", "Current" : "", "Current Vet" : "", "Cymric" : "", "D (Dog)" : "", "DD = current day" : "", "DDL dump (DB2)" : "", "DDL dump (MySQL)" : "", "DDL dump (PostgreSQL)" : "", "DHLPP" : "", "DO NOT use this field to store notes about what the person is looking for." : "", "DOA {0}" : "", "DOB" : "", "Dachshund" : "", "Daily Boarding Cost" : "", "Dalmatian" : "", "Dandi Dinmont Terrier" : "", "Data" : "", "Data Protection" : "", "Database" : "", "Date" : "", "Date '{0}' is not valid." : "", "Date Brought In" : "", "Date Found" : "", "Date Lost" : "", "Date Of Birth" : "", "Date Put On" : "", "Date Removed" : "", "Date Reported" : "", "Date and notes are mandatory." : "", "Date brought in cannot be blank" : "", "Date brought in cannot be in the future." : "", "Date brought in is not valid" : "", "Date found cannot be blank" : "", "Date found cannot be blank." : "", "Date lost cannot be blank" : "", "Date lost cannot be blank." : "", "Date of Birth" : "", "Date of birth cannot be blank" : "", "Date of birth cannot be in the future." : "", "Date of birth is not valid" : "", "Date of last owner contact" : "", "Date put on" : "", "Date put on cannot be blank" : "", "Date put on list" : "", "Date removed" : "", "Date reported cannot be blank" : "", "Date reported cannot be blank." : "", "Date/Time" : "", "Day" : "", "Day Pivot" : "", "Days On Shelter" : "", "Dead On Arrival" : "", "Dead animal" : "", "Dead on arrival" : "", "Death" : "", "Death Comments" : "", "Death Reason" : "", "Death Reasons" : "", "Debit Card" : "", "Dec" : "", "Deceased" : "", "Deceased Date" : "", "December" : "", "Declawed" : "", "Declined" : "", "Default Breed" : "", "Default Brought In By" : "", "Default Coat Type" : "", "Default Color" : "", "Default Cost" : "", "Default Death Reason" : "", "Default Diary Person" : "", "Default Entry Reason" : "", "Default Incident Type" : "", "Default Location" : "", "Default Log Filter" : "", "Default Log Type" : "", "Default Payment Method" : "", "Default Payment Type" : "", "Default Reservation Status" : "", "Default Return Reason" : "", "Default Rota Shift" : "", "Default Size" : "", "Default Species" : "", "Default Test Type" : "", "Default Type" : "", "Default Vaccination Type" : "", "Default Value" : "", "Default daily boarding cost" : "", "Default destination account for payments" : "", "Default image for documents" : "", "Default image for this record and the web" : "", "Default source account for costs" : "", "Default to advanced find animal screen" : "", "Default to advanced find person screen" : "", "Default transaction view" : "", "Default urgency" : "", "Default video for publishing" : "", "Default view" : "", "Defaults" : "", "Defaults formats for code and shortcode are TYYYYNNN and NNT" : "", "Delete" : "", "Delete Accounts" : "", "Delete Animals" : "", "Delete Citations" : "", "Delete Clinic Appointment" : "", "Delete Cost" : "", "Delete Diary" : "", "Delete Diets" : "", "Delete Document from Repository" : "", "Delete Found Animal" : "", "Delete Incidents" : "", "Delete Incoming Forms" : "", "Delete Investigation" : "", "Delete Licenses" : "", "Delete Litter" : "", "Delete Log" : "", "Delete Lost Animal" : "", "Delete Media" : "", "Delete Medical Records" : "", "Delete Movement" : "", "Delete Payments" : "", "Delete Person" : "", "Delete Regimen" : "", "Delete Report" : "", "Delete Rota" : "", "Delete Stock" : "", "Delete Tests" : "", "Delete Transport" : "", "Delete Trap Loans" : "", "Delete Treatments" : "", "Delete Vaccinations" : "", "Delete Vouchers" : "", "Delete Waiting List" : "", "Delete all rota entries for this week" : "", "Delete this animal" : "", "Delete this incident" : "", "Delete this person" : "", "Delete this record" : "", "Delete this waiting list entry" : "", "Denied" : "", "Deposit" : "", "Deposit Account" : "", "Deposit Returned" : "", "Description" : "", "Description Contains" : "", "Description cannot be blank" : "", "Deselect" : "", "Details" : "", "Devon Rex" : "", "Dialog title" : "", "Diary" : "", "Diary Task" : "", "Diary Task: {0}" : "", "Diary Tasks" : "", "Diary and Messages" : "", "Diary calendar" : "", "Diary date cannot be blank" : "", "Diary date is not valid" : "", "Diary for {0}" : "", "Diary note cannot be blank" : "", "Diary note {0} marked completed" : "", "Diary note {0} rediarised for {1}" : "", "Diary notes for: {0}" : "", "Diary notes need a date and subject." : "", "Diary subject cannot be blank" : "", "Diary task items need a pivot, subject and note." : "", "Diary tasks need a name." : "", "Did not ask" : "", "Did you know?" : "", "Died" : "", "Died off shelter" : "", "Died {0}" : "", "Diet" : "", "Diets" : "", "Diets need a start date." : "", "Dispatch" : "", "Dispatch Address" : "", "Dispatch Between" : "", "Dispatch Date/Time" : "", "Dispatch {0}: {1}" : "", "Dispatched ACO" : "", "Display" : "", "Display Index" : "", "Display a search button at the right side of the search box" : "", "Distemper" : "", "Do Not Publish" : "", "Do Not Register Microchip" : "", "Do not show" : "", "Doberman Pinscher" : "", "Document" : "", "Document Link" : "", "Document Repository" : "", "Document Templates" : "", "Document file" : "", "Document signed" : "", "Document signing request" : "", "Document templates" : "", "Documents" : "", "Dog" : "", "Dogo Argentino" : "", "Dogs" : "", "Dogue de Bordeaux" : "", "Domestic Long Hair" : "", "Domestic Medium Hair" : "", "Domestic Short Hair" : "", "Don't create a cost record" : "", "Don't scale" : "", "Donated" : "", "Donation" : "", "Donation?" : "", "Donations for animals entering the shelter" : "", "Done" : "", "Donkey" : "", "Donkey/Mule" : "", "Donor" : "", "Dosage" : "", "Dove" : "", "Download" : "", "Draft" : "", "Driver" : "", "Drop files here..." : "", "Dropoff" : "", "Duck" : "", "Due" : "", "Due in next month" : "", "Due in next week" : "", "Due in next year" : "", "Due today" : "", "Duration" : "", "Dutch" : "", "Dutch Shepherd" : "", "Dwarf" : "", "Dwarf Eared" : "", "E = first letter of animal entry category" : "", "EE = first and second letter of animal entry category" : "", "Eclectus" : "", "Edit" : "", "Edit All Diary Notes" : "", "Edit Appointment" : "", "Edit Diary Tasks" : "", "Edit HTML publishing templates" : "", "Edit Header/Footer" : "", "Edit Invoice Item" : "", "Edit Lookups" : "", "Edit My Diary Notes" : "", "Edit Online Forms" : "", "Edit Reports" : "", "Edit Roles" : "", "Edit Users" : "", "Edit account" : "", "Edit additional field" : "", "Edit citation" : "", "Edit cost" : "", "Edit diary" : "", "Edit diary notes" : "", "Edit diary task" : "", "Edit diary tasks" : "", "Edit diet" : "", "Edit document" : "", "Edit form field" : "", "Edit investigation" : "", "Edit invoice" : "", "Edit license" : "", "Edit litter" : "", "Edit litters" : "", "Edit log" : "", "Edit media notes" : "", "Edit medical profile" : "", "Edit medical regimen" : "", "Edit movement" : "", "Edit my diary notes" : "", "Edit my diary notes" : "", "Edit notes" : "", "Edit online form" : "", "Edit online form HTML header/footer" : "", "Edit payment" : "", "Edit report" : "", "Edit report template HTML header/footer" : "", "Edit role" : "", "Edit roles" : "", "Edit rota item" : "", "Edit stock" : "", "Edit system users" : "", "Edit template" : "", "Edit test" : "", "Edit the current waiting list" : "", "Edit transaction" : "", "Edit transport" : "", "Edit trap loan" : "", "Edit user" : "", "Edit vaccination" : "", "Edit voucher" : "", "Edit {0}" : "", "Egyptian Mau" : "", "Electricity Bills" : "", "Email" : "", "Email Address" : "", "Email PDF" : "", "Email Person" : "", "Email To" : "", "Email a copy of the selected HTML documents as PDFs" : "", "Email a copy of the selected media files" : "", "Email address" : "", "Email document for electronic signature" : "", "Email incident notes to ACO" : "", "Email incoming form submissions to this comma separated list of email addresses" : "", "Email media" : "", "Email person" : "", "Email signature" : "", "Email submissions to" : "", "Email this message to all matching users" : "", "Email this person" : "", "Email users their diary notes each day" : "", "Emu" : "", "Enable FTP uploading" : "", "Enable accounts functionality" : "", "Enable location filters" : "", "Enable lost and found functionality" : "", "Enable multiple sites" : "", "Enable the waiting list functionality" : "", "Enable visual effects" : "", "Enabled" : "", "End Of Day" : "", "End Time" : "", "End at" : "", "End of month" : "", "End of year" : "", "Ends" : "", "Ends after" : "", "English Bulldog" : "", "English Cocker Spaniel" : "", "English Coonhound" : "", "English Lop" : "", "English Pointer" : "", "English Setter" : "", "English Shepherd" : "", "English Spot" : "", "English Springer Spaniel" : "", "English Toy Spaniel" : "", "Entered (newest first)" : "", "Entered (oldest first)" : "", "Entered From" : "", "Entered To" : "", "Entered shelter" : "", "Entering 'activelost' or 'activefound' in the search box will show you lost and found animals reported in the last 30 days." : "", "Entering 'deceased' in the search box will show you recently deceased animals." : "", "Entering 'fosterers', 'homecheckers', 'staff', 'volunteers', 'aco' or 'members' in the search box will show you those groups of people." : "", "Entering 'notforadoption' in the search box will show you all shelter animals with the not for adoption flag set." : "", "Entering 'os' in the search box will show you all shelter animals." : "", "Entlebucher" : "", "Entry" : "", "Entry Category" : "", "Entry Donation" : "", "Entry Reason" : "", "Entry Reason Category" : "", "Entry Reasons" : "", "Entry reason" : "", "Error contacting server." : "", "Escaped" : "", "Escaped {0}" : "", "Eskimo Dog" : "", "Estimate" : "", "Euthanized" : "", "Euthanized {0}" : "", "Every day" : "", "Exclude animals who are aged under" : "", "Exclude from bulk email" : "", "Exclude new animal photos from publishing" : "", "Exclude this image when publishing" : "", "Execute" : "", "Execute Script" : "", "Execute the SQL in the box below" : "", "Executing Task" : "", "Executing..." : "", "Exotic Shorthair" : "", "Expense" : "", "Expense::" : "", "Expenses::Board" : "", "Expenses::Electricity" : "", "Expenses::Food" : "", "Expenses::Gas" : "", "Expenses::Phone" : "", "Expenses::Postage" : "", "Expenses::Stationary" : "", "Expenses::Water" : "", "Expire in next month" : "", "Expired" : "", "Expired in the last month" : "", "Expired in the last week" : "", "Expires" : "", "Expiry" : "", "Expiry date" : "", "Export" : "", "Export Animals as CSV" : "", "Export Report" : "", "Export Reports as CSV" : "", "Export a CSV file of animal records that ASM can import into another database." : "", "Export this database in various formats" : "", "Exporting the complete database can take some time and generate a very large file, are you sure?" : "", "Extra Images" : "", "Extra images" : "", "Extra-Toes Cat (Hemingway Polydactyl)" : "", "F (Feral Cat)" : "", "FECV/FeCoV" : "", "FIPV" : "", "FIV" : "", "FIV Result" : "", "FIV+" : "", "FIV/L Test Date" : "", "FIV/L Tested" : "", "FLV" : "", "FLV Result" : "", "FLV+" : "", "FTP hostname" : "", "FTP password" : "", "FTP username" : "", "FVRCP" : "", "Facebook" : "", "Failed sending email" : "", "Failed to create payment." : "", "Failed to renew license." : "", "Fawn" : "", "Fawn Tortoiseshell" : "", "FeLV" : "", "Features" : "", "Feb" : "", "February" : "", "Fee" : "", "Female" : "", "Feral" : "", "Ferret" : "", "Field Spaniel" : "", "Field names should not contain spaces." : "", "Fila Brasileiro" : "", "File" : "", "Filter" : "", "Financial" : "", "Finch" : "", "Find Animal" : "", "Find Animal/Person" : "", "Find Found Animal" : "", "Find Incident" : "", "Find Lost Animal" : "", "Find Person" : "", "Find a found animal" : "", "Find a lost animal" : "", "Find aco" : "", "Find an incident" : "", "Find animal" : "", "Find animal columns" : "", "Find animal control incidents returned {0} results." : "", "Find animals matching the looking for criteria of this person" : "", "Find donor" : "", "Find driver" : "", "Find fosterer" : "", "Find found animal returned {0} results." : "", "Find homechecked" : "", "Find homechecker" : "", "Find incident" : "", "Find lost animal returned {0} results." : "", "Find member" : "", "Find person" : "", "Find person columns" : "", "Find retailer" : "", "Find shelter" : "", "Find staff" : "", "Find staff/volunteer" : "", "Find this address on a map" : "", "Find vet" : "", "Find volunteer" : "", "Fine Amount" : "", "Finnish Lapphund" : "", "Finnish Spitz" : "", "First Last" : "", "First Names" : "", "First name(s)" : "", "First offence" : "", "Fish" : "", "Flag" : "", "Flags" : "", "Flat-coated Retriever" : "", "Flemish Giant" : "", "Florida White" : "", "Followup" : "", "Followup Between" : "", "Followup Date/Time" : "", "Footer" : "", "For" : "", "Forbidden" : "", "Forenames" : "", "Forget" : "", "Form URL" : "", "Forms need a name." : "", "Foster" : "", "Foster Book" : "", "Foster Capacity" : "", "Foster Transfer" : "", "Foster an animal" : "", "Foster book" : "", "Foster movements must have a valid foster date." : "", "Foster successfully created." : "", "Fostered" : "", "Fostered Animals" : "", "Fostered to {0} since {1}" : "", "Fosterer" : "", "Fosterer (Active Only)" : "", "Fosterer Medical Report" : "", "Found" : "", "Found Animal" : "", "Found Animal - Additional" : "", "Found Animal - Details" : "", "Found Animal Contact" : "", "Found Animal {0}" : "", "Found Animal: {0}" : "", "Found animal - {0} {1} [{2}]" : "", "Found animal entries matching '{0}'." : "", "Found animals must have a contact" : "", "Found animals reported in the last 30 days." : "", "Found from" : "", "Found to" : "", "FoundLost animal entry {0} successfully created." : "", "Fox Terrier" : "", "Foxhound" : "", "Fr" : "", "French Bulldog" : "", "French-Lop" : "", "Frequency" : "", "Frequently Asked Questions" : "", "Fri" : "", "Friday" : "", "From" : "", "From Fostering" : "", "From Other" : "", "From retailer is only valid on adoption movements." : "", "Future notes" : "", "GDPR Contact Opt-In" : "", "Gaited" : "", "Gas Bills" : "", "Gecko" : "", "General" : "", "Generate" : "", "Generate Documents" : "", "Generate HTML from this SQL" : "", "Generate Report" : "", "Generate a document from this animal" : "", "Generate a document from this incident" : "", "Generate a document from this movement" : "", "Generate a document from this person" : "", "Generate a document from this record" : "", "Generate a javascript database for the search page" : "", "Generate a new animal code" : "", "Generate a random name for this animal" : "", "Generate document from this appointment" : "", "Generate document from this license" : "", "Generate document from this payment" : "", "Generate document from this transport" : "", "Generate documentation" : "", "Generate documents" : "", "Generate image thumbnails as tn_$$IMAGE$$" : "", "Generated document '{0}'" : "", "Gerbil" : "", "German Pinscher" : "", "German Shepherd Dog" : "", "German Shorthaired Pointer" : "", "German Wirehaired Pointer" : "", "Get more reports from sheltermanager.com" : "", "Gift Aid" : "", "GiftAid" : "", "Giftaid" : "", "Ginger" : "", "Ginger and White" : "", "Give" : "", "Give Treatments" : "", "Give Vaccination" : "", "Given" : "", "Glen of Imaal Terrier" : "", "Go" : "", "Go the lookup data screen and add/remove breeds, species and animal types according to the animals your shelter deals with." : "", "Go the options screen and set your shelter's contact details and other settings." : "", "Go the system users screen and add user accounts for your staff." : "", "Goat" : "", "Golden" : "", "Golden Retriever" : "", "Goldfish" : "", "Good With Cats" : "", "Good With Children" : "", "Good With Dogs" : "", "Good with Cats" : "", "Good with Children" : "", "Good with Dogs" : "", "Good with cats" : "", "Good with children" : "", "Good with dogs" : "", "Good with kids" : "", "Google+" : "", "Goose" : "", "Gordon Setter" : "", "Grade" : "", "Great Dane" : "", "Great Pyrenees" : "", "Greater Swiss Mountain Dog" : "", "Green" : "", "Grey" : "", "Grey and White" : "", "Greyhound" : "", "Guinea Pig" : "", "Guinea fowl" : "", "HMRC Gift Aid Spreadsheet" : "", "HTML" : "", "HTML Publishing Templates" : "", "HTML/FTP Publisher" : "", "Hairless" : "", "Half-Yearly" : "", "Hamster" : "", "Harlequin" : "", "Havana" : "", "Havanese" : "", "Header" : "", "Health Problems" : "", "Health and Identification" : "", "Healthy" : "", "Heartworm" : "", "Heartworm Test Date" : "", "Heartworm Test Result" : "", "Heartworm Tested" : "", "Heartworm+" : "", "Hedgehog" : "", "Held" : "", "Help" : "", "Hepatitis" : "", "Here are some things you should do before you start adding animals and people to your database." : "", "Hidden" : "", "Hidden Comments" : "", "Hidden comments about the animal" : "", "Hide deceased animals from the home page" : "", "High" : "", "Highlight" : "", "Himalayan" : "", "History" : "", "Hold" : "", "Hold the animal until this date or blank to hold indefinitely" : "", "Hold until" : "", "Hold until {0}" : "", "Holland Lop" : "", "Home" : "", "Home Phone" : "", "Home page" : "", "Homecheck Areas" : "", "Homecheck Date" : "", "Homecheck History" : "", "Homecheck areas" : "", "Homechecked" : "", "Homechecked By" : "", "Homechecked by" : "", "Homechecker" : "", "Horizontal Pitch" : "", "Horse" : "", "Hotot" : "", "Hound" : "", "Hours" : "", "Housetrained" : "", "Hovawart" : "", "How urgent is it that we take this animal?" : "", "Husky" : "", "I've finished, Don't show me this popup again." : "", "IP Restriction" : "", "IP restriction is a space-separated list of IP netblocks in CIDR notation that this user is *only* permitted to login from (eg: 192.168.0.0/24 127.0.0.0/8). If left blank, the user can login from any address." : "", "Ibizan Hound" : "", "If the shelter provides initial insurance cover to new adopters, the policy number" : "", "If this form has a populated emailaddress field during submission, send a confirmation email to it" : "", "If this is the web preferred image, web publishers will use these notes as the animal description" : "", "If this person is a fosterer, the maximum number of animals they can care for." : "", "If this person is a member, the date that membership expires." : "", "If this person is a member, their membership number" : "", "If this person is a member, their membership number." : "", "If this stock record is for a drug, the batch number from the container" : "", "If this stock record is for a perishable good, the expiry date on the container" : "", "If you assign view or edit roles, only users within those roles will be able to view and edit this account." : "", "If you don't select any locations, publishers will include animals in all locations." : "", "Iguana" : "", "Illyrian Sheepdog" : "", "Image" : "", "Image file" : "", "Import" : "", "Import a CSV file" : "", "Import a PayPal CSV file" : "", "Import from file" : "", "Important" : "", "In" : "", "In SubTotal" : "", "In the last month" : "", "In the last quarter" : "", "In the last week" : "", "In the last year" : "", "In-Kind Donation" : "", "Inactive" : "", "Inactive - do not include" : "", "Incident" : "", "Incident - Additional" : "", "Incident - Citation" : "", "Incident - Details" : "", "Incident - Dispatch" : "", "Incident - Owner" : "", "Incident Between" : "", "Incident Completed Types" : "", "Incident Date/Time" : "", "Incident Type" : "", "Incident Types" : "", "Incident date cannot be blank" : "", "Incident followup" : "", "Incident {0} successfully created." : "", "Incident {0}, {1}: {2}" : "", "Incidents" : "", "Incidents Requiring Followup" : "", "Include CSV header line" : "", "Include Removed" : "", "Include animals in the following locations" : "", "Include animals on trial adoption" : "", "Include animals who don't have a description" : "", "Include animals who don't have a picture" : "", "Include cruelty case animals" : "", "Include deceased animals" : "", "Include fostered animals" : "", "Include found" : "", "Include held animals" : "", "Include incomplete medical records when generating document templates" : "", "Include incomplete vaccination and test records when generating document templates" : "", "Include non-shelter animals" : "", "Include off-shelter animals in medical calendar and books" : "", "Include preferred photo" : "", "Include quarantined animals" : "", "Include reserved animals" : "", "Include retailer animals" : "", "Include returned" : "", "Include this image when publishing" : "", "Include unaltered animals" : "", "Income" : "", "Income from an on-site shop" : "", "Income::" : "", "Income::Adoption" : "", "Income::Donation" : "", "Income::EntryDonation" : "", "Income::Interest" : "", "Income::OpeningBalances" : "", "Income::Shop" : "", "Income::Sponsorship" : "", "Income::WaitingList" : "", "Incoming" : "", "Incoming Forms" : "", "Incoming donations (misc)" : "", "Incoming forms are online forms that have been completed and submitted by people on the web." : "", "Incomplete incidents" : "", "Incomplete notes upto today" : "", "Index" : "", "Individual/Couple" : "", "Induct a new animal" : "", "Information" : "", "Initials" : "", "Install" : "", "Install the selected reports to your database" : "", "Insurance" : "", "Insurance No" : "", "Intake" : "", "Intakes {0}" : "", "Internal Location" : "", "Internal Locations" : "", "Invalid email address" : "", "Invalid email address '{0}'" : "", "Invalid microchip number length" : "", "Invalid time '{0}', times should be in 00:00 format" : "", "Invalid time, times should be in HH:MM format" : "", "Invalid username or password." : "", "Investigation" : "", "Investigations" : "", "Investigator" : "", "Invoice Only" : "", "Invoice items need a description and amount." : "", "Irish Setter" : "", "Irish Terrier" : "", "Irish Water Spaniel" : "", "Irish Wolfhound" : "", "Is this a permanent foster?" : "", "Is this a trial adoption?" : "", "Issue a new insurance number for this animal/adoption" : "", "Issue date and expiry date must be valid dates." : "", "Issued" : "", "Issued in the last month" : "", "Issued in the last week" : "", "Italian Greyhound" : "", "Italian Spinone" : "", "Item" : "", "Jack Russell Terrier" : "", "Jan" : "", "January" : "", "Japanese Bobtail" : "", "Japanese Chin" : "", "Javanese" : "", "Jersey Wooly" : "", "Jindo" : "", "Jul" : "", "July" : "", "Jump to diary" : "", "Jump to donations" : "", "Jump to media" : "", "Jump to movements" : "", "Jun" : "", "June" : "", "Jurisdiction" : "", "Jurisdictions" : "", "Kai Dog" : "", "Kakariki" : "", "Karelian Bear Dog" : "", "Keep table headers visible when scrolling" : "", "Keeshond" : "", "Kennel" : "", "Kerry Blue Terrier" : "", "Kishu" : "", "Kittens (under {0} months)" : "", "Km" : "", "Komondor" : "", "Korat" : "", "Kuvasz" : "", "Kyi Leo" : "", "Label" : "", "Labrador Retriever" : "", "Lakeland Terrier" : "", "Lancashire Heeler" : "", "Large" : "", "Last First" : "", "Last Location" : "", "Last Month" : "", "Last Name" : "", "Last Week" : "", "Last changed by {0} on {1}" : "", "Last name" : "", "Last, First" : "", "Latency" : "", "Latency Tester" : "", "Least recently changed" : "", "Leave" : "", "Leave of absence" : "", "Left Margin" : "", "Left shelter" : "", "Leonberger" : "", "Leptospirosis" : "", "Letter" : "", "Lhasa Apso" : "", "Liability" : "", "Licence for {0} successfully renewed {1} - {2}" : "", "License" : "", "License Number" : "", "License Types" : "", "License number '{0}' has already been issued." : "", "License numbers matching '{0}'." : "", "License requires a number" : "", "License requires a person" : "", "License requires issued and expiry dates" : "", "Licenses" : "", "Licensing" : "", "Lifetime" : "", "Light Amber" : "", "Lilac" : "", "Lilac Tortie" : "", "Limited to {0} matches" : "", "Link" : "", "Link an animal" : "", "Link to an external web resource" : "", "Link to this animal" : "", "Links" : "", "List" : "", "Litter" : "", "Litter Ref" : "", "Litter Reference" : "", "Littermates" : "", "Litters" : "", "Litters need at least a required date and number." : "", "Live Releases {0}" : "", "Liver" : "", "Liver and White" : "", "Lizard" : "", "Llama" : "", "Loading..." : "", "Loan" : "", "Local" : "", "Locale" : "", "Location" : "", "Location Filter" : "", "Location and Species" : "", "Location and Type" : "", "Location and Unit" : "", "Locations" : "", "Log" : "", "Log Text" : "", "Log Type" : "", "Log Types" : "", "Log date must be a valid date" : "", "Log entries need a date and text." : "", "Log requires a date." : "", "Log requires a person." : "", "Log requires an animal." : "", "Log successfully added." : "", "Login" : "", "Logout" : "", "Long" : "", "Long term" : "", "Longest On Shelter" : "", "Looking For" : "", "Looking for" : "", "Lookup" : "", "Lookup (Multiple Select)" : "", "Lookup Values" : "", "Lookup data" : "", "Lookups" : "", "Lop Eared" : "", "Lory/Lorikeet" : "", "Lost" : "", "Lost Animal" : "", "Lost Animal - Additional" : "", "Lost Animal - Details" : "", "Lost Animal Contact" : "", "Lost Animal: {0}" : "", "Lost and Found" : "", "Lost and found entries must have a contact" : "", "Lost animal - {0} {1} [{2}]" : "", "Lost animal entries matching '{0}'." : "", "Lost animal entry {0} successfully created." : "", "Lost animals must have a contact" : "", "Lost animals reported in the last 30 days." : "", "Lost from" : "", "Lost to" : "", "Lost/Found" : "", "Lots of reports installed? Clean up the Reports menu with Settings-Options- Display-Show report menu items in collapsed categories." : "", "Lovebird" : "", "Low" : "", "Lowchen" : "", "Lowest" : "", "M (Miscellaneous)" : "", "MM = current month" : "", "Macaw" : "", "Mail" : "", "Mail Merge" : "", "Mail Merge - {0}" : "", "Maine Coon" : "", "Make this the default image when creating documents" : "", "Make this the default image when viewing this record and publishing to the web" : "", "Make this the default video link when publishing to the web" : "", "Male" : "", "Maltese" : "", "Manchester Terrier" : "", "Mandatory" : "", "Manual" : "", "Manually enter codes (do not generate)" : "", "Manufacturer" : "", "Manx" : "", "Map" : "", "Map of active incidents" : "", "Mar" : "", "March" : "", "Maremma Sheepdog" : "", "Mark Deceased" : "", "Mark an animal deceased" : "", "Mark dispatched now" : "", "Mark new animals as not for adoption" : "", "Mark responded now" : "", "Mark selected payments received" : "", "Mark this owner homechecked" : "", "Mark treatments given" : "", "Marketer" : "", "Markings" : "", "Markup" : "", "Marriage/Relationship split" : "", "Mastiff" : "", "Match" : "", "Match Lost and Found" : "", "Match against other lost/found animals" : "", "Match lost and found animals" : "", "Match this animal with the lost and found database" : "", "Maternity" : "", "May" : "", "McNab" : "", "Media" : "", "Media Notes" : "", "Media notes contain" : "", "Medical" : "", "Medical Book" : "", "Medical Profiles" : "", "Medical book" : "", "Medical calendar" : "", "Medical profiles" : "", "Medical profiles need a profile name, treatment, dosage and frequencies." : "", "Medical regimens need an animal, name, dosage, a start date and frequencies." : "", "Medicate" : "", "Medicate Animal" : "", "Medium" : "", "Member" : "", "Membership Expiry" : "", "Membership Number" : "", "Merge" : "", "Merge Person" : "", "Merge another animal into this one" : "", "Merge another person into this one" : "", "Merge bonded animals into a single record" : "", "Merge duplicate records" : "", "Message" : "", "Message Board" : "", "Message from {0}" : "", "Message successfully sent to {0}" : "", "Messages" : "", "Messages successfully sent" : "", "Method" : "", "Microchip" : "", "Microchip Date" : "", "Microchip Number" : "", "Microchip number {0} has already been allocated to another animal." : "", "Microchipped" : "", "Miles" : "", "Mini Rex" : "", "Mini-Lop" : "", "Miniature Pinscher" : "", "Minutes" : "", "Missouri Foxtrotter" : "", "Mixed Breed" : "Pasanay", "Mo" : "", "Mobile signing pad" : "", "Modify Additional Fields" : "", "Modify Document Templates" : "", "Modify Lookups" : "", "Mon" : "", "Monday" : "", "Money" : "", "Month" : "", "Monthly" : "", "More Info Needed" : "", "More Medications" : "", "More Tests" : "", "More Vaccinations" : "", "More diary notes" : "", "Morgan" : "", "Most browsers let you search in dropdowns by typing the first few letters of the item you want." : "", "Most browsers will let you visit a record you have been to in this session by typing part of its name in the address bar." : "", "Most recently changed" : "", "Most relevant" : "", "Mother" : "", "Mountain Cur" : "", "Mountain Dog" : "", "Mouse" : "", "Move" : "", "Move an animal to a retailer" : "", "Moved to animal record {0}" : "", "Movement" : "", "Movement Date" : "", "Movement Number" : "", "Movement Type" : "", "Movement Types" : "", "Movement dates clash with an existing movement." : "", "Movement numbers must be unique." : "", "Movements" : "", "Movements require an animal" : "", "Movements require an animal." : "", "Moving..." : "", "Multi-Lookup" : "", "Multiple Treatments" : "", "Munchkin" : "", "Munsterlander" : "", "Mustang" : "", "My Fosters" : "", "My Incidents" : "", "My Undispatched Incidents" : "", "My diary notes" : "", "My sheltermanager.com account" : "", "Mynah" : "", "N (Non-Shelter Animal)" : "", "NNN or NN = number unique for this type of animal for this year" : "", "Name" : "Pangalan", "Name Contains" : "", "Name and Address" : "", "Name cannot be blank" : "", "Name contains" : "", "Neapolitan Mastiff" : "", "Negative" : "", "Neglect" : "", "Netherland Dwarf" : "", "Neuter/Spay" : "", "Neutered" : "", "Neutered/Spayed Non-Shelter Animals In {0}" : "", "Neutered/Spayed Shelter Animals In {0}" : "", "New" : "", "New Account" : "", "New Appointment" : "", "New Citation" : "", "New Cost" : "", "New Diary" : "", "New Diet" : "", "New Document" : "", "New Field" : "", "New Fosterer" : "", "New Guinea Singing Dog" : "", "New Item" : "", "New License" : "", "New Litter" : "", "New Log" : "", "New Movement" : "", "New Owner" : "", "New Password" : "", "New Payment" : "", "New Profile" : "", "New Record" : "", "New Regimen" : "", "New Report" : "", "New Role" : "", "New Stock" : "", "New Task" : "", "New Template" : "", "New Test" : "", "New Transport" : "", "New Trap Loan" : "", "New User" : "", "New Vaccination" : "", "New Voucher" : "", "New Waiting List Entry" : "", "New Zealand" : "", "New diary task" : "", "New form field" : "", "New name" : "", "New online form" : "", "New password and confirmation password don't match." : "", "New task detail" : "", "New template" : "", "Newfoundland Dog" : "", "Next" : "", "No" : "", "No adjustment" : "", "No data to show on the report." : "", "No data." : "", "No description" : "", "No longer retained" : "", "No matches found." : "", "No picture" : "", "No publishers are running." : "", "No results found." : "", "No results." : "", "No tasks are running." : "", "No view permission for this report" : "", "Noise" : "", "Non-Shelter" : "", "Non-Shelter Animal" : "", "Non-Shelter Animals" : "", "Non-shelter Animals" : "", "None" : "", "Norfolk Terrier" : "", "Normal user" : "", "Norwegian Buhund" : "", "Norwegian Elkhound" : "", "Norwegian Forest Cat" : "", "Norwegian Lundehund" : "", "Norwich Terrier" : "", "Not Arrived" : "", "Not Available For Adoption" : "", "Not Available for Adoption" : "", "Not For Adoption" : "", "Not Microchipped" : "", "Not Reconciled" : "", "Not available for adoption" : "", "Not dispatched" : "", "Not for adoption" : "", "Not for adoption flag set" : "", "Not in chosen publisher location" : "", "Not reconciled" : "", "Note" : "", "Notes" : "", "Notes about the death of the animal" : "", "Nov" : "", "Nova Scotia Duck-Tolling Retriever" : "", "November" : "", "Now" : "", "Number" : "", "Number in litter" : "", "Number of Tasks" : "", "Number of animal links to show" : "", "Number of fields" : "", "Number of pets" : "", "Ocicat" : "", "Oct" : "", "October" : "", "Office" : "", "Old English Sheepdog" : "", "Old Password" : "", "Omit criteria" : "", "Omit header/footer" : "", "On Foster (in figures)" : "", "On Shelter" : "", "On shelter for {0} days, daily cost {1}, cost record total <b>{2}</b>" : "", "On shelter for {0} days. Total cost: {1}" : "", "Once assigned, codes cannot be changed" : "", "Once signed, this document cannot be edited or tampered with." : "", "One Off" : "", "One-Off" : "", "Online Form: {0}" : "", "Online Forms" : "", "Online form fields need a name and label." : "", "Online forms can be linked to from your website and used to take information from visitors for applications, etc." : "", "Only PDF, HTML and JPG image files can be attached." : "", "Only active accounts" : "", "Only allow users with one of these roles to view this incident" : "", "Only show account totals for the current period, which starts on " : "", "Only show declawed" : "", "Only show pickups" : "", "Only show special needs" : "", "Only show transfers" : "", "Open Incidents" : "", "Open records in a new browser tab" : "", "Open reports in a new browser tab" : "", "Opening balances" : "", "Optional, the date the vaccination \"wears off\" and needs to be administered again" : "", "Options" : "", "Or move this diary on to" : "", "Order published animals by" : "", "Organisation" : "", "Organization" : "", "Organization name" : "", "Oriental Long Hair" : "", "Oriental Short Hair" : "", "Oriental Tabby" : "", "Original Owner" : "", "Ostrich" : "", "Other Account" : "", "Other Organisation" : "", "Other Shelter" : "", "Otterhound" : "", "Our shelter does trial adoptions, allow us to mark these on movement screens" : "", "Out" : "", "Out Between" : "", "Out SubTotal" : "", "Output a deceased animals page" : "", "Output a page with links to available online forms" : "", "Output a separate page for each animal type" : "", "Output a separate page for each species" : "", "Output an adopted animals page" : "", "Output an rss.xml page" : "", "Overdue" : "", "Overdue medical items" : "", "Overtime" : "", "Owl" : "", "Owner" : "", "Owner Vet" : "", "Owner given citation" : "", "Owners Vet" : "", "PM" : "", "Page extension" : "", "Paid" : "", "Paint/Pinto" : "", "Palomino" : "", "Paper Size" : "", "Papillon" : "", "Parainfluenza" : "", "Parakeet (Other)" : "", "Parent" : "", "Parrot (Other)" : "", "Parrotlet" : "", "Parvovirus" : "", "Paso Fino" : "", "Pass Homecheck" : "", "Password" : "", "Password for '{0}' has been reset." : "", "Password is incorrect." : "", "Password successfully changed." : "", "Passwords cannot be blank." : "", "Path" : "", "Patterdale Terrier (Fell Terrier)" : "", "PayPal" : "", "Payment" : "", "Payment Book" : "", "Payment From" : "", "Payment Methods" : "", "Payment Type" : "", "Payment Types" : "", "Payment book" : "", "Payment calendar" : "", "Payment of {0} successfully received ({1})." : "", "Payments" : "", "Payments need at least one date, an amount and a person." : "", "Payments of type" : "", "Payments require a person" : "", "Payments require a received date" : "", "Peacock/Pea fowl" : "", "Pekingese" : "", "Pending Adoption" : "", "Pending Apartment Verification" : "", "Pending Home Visit" : "", "Pending Vet Check" : "", "Pension" : "", "People" : "", "People Looking For" : "", "People matching '{0}'." : "", "People or animal records that already exist in the database will not be imported again and movement/payment data will be attached to the existing records instead." : "", "People with active reservations, but no homecheck has been done." : "", "People with overdue donations." : "", "Percheron" : "", "Perform" : "", "Perform Homecheck" : "", "Perform Test" : "", "Performed" : "", "Permanent Foster" : "", "Persian" : "", "Person" : "", "Person - Additional" : "", "Person - Name and Address" : "", "Person - Type" : "", "Person Flags" : "", "Person looking for report" : "", "Person successfully created" : "", "Personal" : "", "Peruvian Inca Orchid" : "", "Peruvian Paso" : "", "Petit Basset Griffon Vendeen" : "", "Pharaoh Hound" : "", "Pheasant" : "", "Phone" : "", "Phone contains" : "", "Photo successfully uploaded." : "", "Picked Up" : "", "Picked Up By" : "", "Pickup" : "", "Pickup Address" : "", "Pickup Location" : "", "Pickup Locations" : "", "Pig" : "", "Pig (Farm)" : "", "Pigeon" : "", "Pinterest" : "", "Pionus" : "", "Pit Bull Terrier" : "", "Pixie-Bob" : "", "Please click the Sign button when you are finished." : "", "Please see the manual for more information." : "", "Please select a PDF, HTML or JPG image file to attach" : "", "Please tighten the scope of your email campaign to {0} emails or less." : "", "Please use the links below to electronically sign these documents." : "", "Plott Hound" : "", "Poicephalus/Senegal" : "", "Pointer" : "", "Points for being found within 2 weeks of being lost" : "", "Points for matching age group" : "", "Points for matching breed" : "", "Points for matching color" : "", "Points for matching features" : "", "Points for matching lost/found area" : "", "Points for matching sex" : "", "Points for matching species" : "", "Points for matching zipcode" : "", "Points required to appear on match report" : "", "Polish" : "", "Polish Lowland Sheepdog" : "", "Pomeranian" : "", "Pony" : "", "Poodle" : "", "Portugese Podengo" : "", "Portuguese Water Dog" : "", "Positive" : "", "Positive for Heartworm, FIV or FLV" : "", "Positive/Negative" : "", "Post" : "", "Postage costs" : "", "Pot Bellied" : "", "Prairie Dog" : "", "Prefill new media notes for animal images with animal comments if left blank" : "", "Prefill new media notes with the filename if left blank" : "", "Premises" : "", "Presa Canario" : "", "Press F11 in HTML or SQL code editing boxes to edit in fullscreen mode" : "", "Preview" : "", "Previous" : "", "Previous Adopter" : "", "Print" : "", "Print Preview" : "", "Print selected forms" : "", "Printable Manual" : "", "Printing word processor documents uses hidden iframe and window.print" : "", "Priority" : "", "Priority Floor" : "", "Produce a CSV File" : "", "Produce a PDF of printable labels" : "", "Profile" : "", "Profile name cannot be blank" : "", "Public Holiday" : "", "Publish Animals to the Internet" : "", "Publish HTML via FTP" : "", "Publish now" : "", "Publish to folder" : "", "Published to Website" : "", "Publisher" : "", "Publisher Breed" : "", "Publisher Color" : "", "Publisher Logs" : "", "Publisher Species" : "", "Publishing" : "", "Publishing History" : "", "Publishing Logs" : "", "Publishing Options" : "", "Publishing complete." : "", "Publishing template" : "", "Pug" : "", "Puli" : "", "Pumi" : "", "Puppies (under {0} months)" : "", "Purchased" : "", "Qty" : "", "Quaker Parakeet" : "", "Quantity" : "", "Quarantine" : "", "Quarterhorse" : "", "Quarterly" : "", "Quick Links" : "", "Quicklinks" : "", "Quicklinks are shown on the home page and allow quick access to areas of the system." : "", "R" : "", "Rabbit" : "", "Rabies" : "", "Rabies Tag" : "", "RabiesTag" : "", "Radio Buttons" : "", "Ragamuffin" : "", "Ragdoll" : "", "Rank" : "", "Rat" : "", "Rat Terrier" : "", "Raw Markup" : "", "Read the manual for more information about Animal Shelter Manager." : "", "Real name" : "", "Reason" : "", "Reason For Appointment" : "", "Reason Not From Owner" : "", "Reason for Entry" : "", "Reason for entry" : "", "Reason not from Owner" : "", "Reason the owner did not bring in the animal themselves" : "", "Recalculate ALL animal ages/times" : "", "Recalculate ALL animal locations" : "", "Recalculate on-shelter animal locations" : "", "Receipt No" : "", "Receipt/Invoice" : "", "Receive" : "", "Receive a donation" : "", "Receive a payment" : "", "Received" : "", "Received in last day" : "", "Received in last month" : "", "Received in last week" : "", "Received in last year" : "", "Received today" : "", "Recently Adopted" : "", "Recently Changed" : "", "Recently Entered Shelter" : "", "Recently Fostered" : "", "Recently deceased" : "", "Recently deceased shelter animals (last 30 days)." : "", "Reception" : "", "Reclaim" : "", "Reclaim an animal" : "", "Reclaim movements must have a valid reclaim date." : "", "Reclaim successfully created." : "", "Reclaimed" : "", "Reconcile" : "", "Reconciled" : "", "Redbone Coonhound" : "", "Rediarised" : "", "Redirect to URL after POST" : "", "Reference" : "", "Refresh" : "", "Regenerate 'Match lost and found animals' report" : "", "Regenerate 'Person looking for' report" : "", "Regenerate annual animal figures for" : "", "Regenerate monthly animal figures for" : "", "Regenerate person names in selected format" : "", "Register Microchip" : "", "Register microchips after" : "", "Released To Wild" : "", "Released To Wild {0}" : "", "Reload" : "", "Remaining" : "", "Remember me on this computer" : "", "Removal" : "", "Removal Reason" : "", "Removal reason" : "", "Remove" : "", "Remove HTML and PDF document media after this many years" : "", "Remove clinic functionality from screens and menus" : "", "Remove fine-grained animal control incident permissions" : "", "Remove holds after" : "", "Remove move menu and the movements tab from animal and person screens" : "", "Remove personally identifiable data" : "", "Remove previously published files before uploading" : "", "Remove retailer functionality from the movement screens and menus" : "", "Remove short shelter code box from the animal details screen" : "", "Remove the FIV/L test fields from animal health details" : "", "Remove the Litter ID field from animal details" : "", "Remove the Rabies Tag field from animal health details" : "", "Remove the adoption coordinator field from animal entry details" : "", "Remove the adoption fee field from animal details" : "", "Remove the animal control functionality from menus and screens" : "", "Remove the bonded with fields from animal entry details" : "", "Remove the city/state fields from person details" : "", "Remove the coat type field from animal details" : "", "Remove the declawed box from animal health details" : "", "Remove the document repository functionality from menus" : "", "Remove the good with fields from animal notes" : "", "Remove the heartworm test fields from animal health details" : "", "Remove the insurance number field from the movement screens" : "", "Remove the location unit field from animal details" : "", "Remove the microchip fields from animal identification details" : "", "Remove the neutered fields from animal health details" : "", "Remove the online form functionality from menus" : "", "Remove the picked up fields from animal entry details" : "", "Remove the rota functionality from menus and screens" : "", "Remove the size field from animal details" : "", "Remove the stock control functionality from menus and screens" : "", "Remove the tattoo fields from animal identification details" : "", "Remove the transport functionality from menus and screens" : "", "Remove the trap loan functionality from menus and screens" : "", "Remove the weight field from animal details" : "", "Removed" : "", "Rename" : "", "Renew License" : "", "Renew licence" : "", "Renew license" : "", "Report" : "", "Report Title" : "", "Report a new incident" : "", "Reports" : "", "Request signature by email" : "", "Requested" : "", "Require followup" : "", "Required" : "", "Required date must be a valid date" : "", "Reschedule" : "", "Reservation" : "", "Reservation Book" : "", "Reservation Cancelled" : "", "Reservation Date" : "", "Reservation For" : "", "Reservation Status" : "", "Reservation Statuses" : "", "Reservation book" : "", "Reservation date cannot be after cancellation date." : "", "Reservation successfully created." : "", "Reservations must have a valid reservation date." : "", "Reserve" : "", "Reserve an animal" : "", "Reserved" : "", "Reset" : "", "Reset Password" : "", "Respond" : "", "Responded" : "", "Responded Between" : "", "Responded Date/Time" : "", "Result" : "", "Results" : "", "Results for '{0}'." : "", "Retailer" : "", "Retailer Animals" : "", "Retailer Book" : "", "Retailer book" : "", "Retailer movement successfully created." : "", "Retailer movements must have a valid movement date." : "", "Retriever" : "", "Return" : "", "Return Category" : "", "Return Date" : "", "Return a transferred animal" : "", "Return an animal from adoption" : "", "Return an animal from another movement" : "", "Return an animal from transfer" : "", "Return date cannot be before the movement date." : "", "Return this movement and bring the animal back to the shelter" : "", "Returned" : "", "Returned By" : "", "Returned To Owner" : "", "Returned from" : "", "Returned to" : "", "Returned to Owner {0}" : "", "Returning" : "", "Returns {0}" : "", "Reupload animal images every time" : "", "Rex" : "", "Rhea" : "", "Rhinelander" : "", "Rhodesian Ridgeback" : "", "Ringneck/Psittacula" : "", "Role is in use and cannot be deleted." : "", "Roles" : "", "Roles need a name." : "", "Rosella" : "", "Rostered day off" : "", "Rota" : "", "Rota Types" : "", "Rota cloned successfully." : "", "Rotate image 90 degrees anticlockwis" : "", "Rotate image 90 degrees clockwise" : "", "Rottweiler" : "", "Rough" : "", "Rows" : "", "Ruddy" : "", "Russian Blue" : "", "S (Stray Cat)" : "", "S = first letter of animal species" : "", "SM Account" : "", "SMS" : "", "SQL" : "", "SQL Interface" : "", "SQL dump" : "", "SQL dump (ASM2 HSQLDB Format)" : "", "SQL editor: Press F11 to go full screen and press CTRL+SPACE to autocomplete table and column names" : "", "SQL interface" : "", "SQL is syntactically correct." : "", "SS = first and second letter of animal species" : "", "Sa" : "", "Saddlebred" : "", "Saint Bernard St. Bernard" : "", "Sales Tax" : "", "Saluki" : "", "Samoyed" : "", "Sat" : "", "Satin" : "", "Saturday" : "", "Save" : "", "Save and leave" : "", "Save this incident" : "", "Save this person" : "", "Save this record" : "", "Save this waiting list entry" : "", "Saving..." : "", "Scale published animal images to" : "", "Scheduled" : "", "Schipperke" : "", "Schnauzer" : "", "Scottish Deerhound" : "", "Scottish Fold" : "", "Scottish Terrier Scottie" : "", "Script" : "", "Seal" : "", "Sealyham Terrier" : "", "Search" : "", "Search Results for '{0}'" : "", "Search returned {0} results." : "", "Search sort order" : "", "Searchable" : "", "Second offence" : "", "Select" : "", "Select a person" : "", "Select a person to attach this form to." : "", "Select a person to merge into this record. The selected person will be removed, and their movements, diary notes, log entries, etc. will be reattached to this record." : "", "Select all" : "", "Select an animal" : "", "Select an animal to attach this form to." : "", "Select an animal to merge into this record. The selected animal will be removed, and their movements, diary notes, log entries, etc. will be reattached to this record." : "", "Select animal to merge" : "", "Select animals" : "", "Select date for diary task" : "", "Select person to merge" : "", "Select recommended" : "", "Selected On-Shelter Animals" : "", "Selkirk Rex" : "", "Send" : "", "Send Emails" : "", "Send a weekly email to fosterers with medical information about their animals" : "", "Send confirmation email to form submitter" : "", "Send emails" : "", "Send mass emails and perform mail merges" : "", "Send via email" : "", "Sending {0} emails is considered abusive and will damage the reputation of the email server." : "", "Sending..." : "", "Senior" : "", "Sent to mobile signing pad." : "", "Sep" : "", "Separate waiting list rank by species" : "", "September" : "", "Server clock adjustment" : "", "Set publishing options" : "", "Set this to 0 to never automatically remove." : "", "Set to 0 to never update urgencies." : "", "Set wether or not this user account can log in to the user interface." : "", "Setter" : "", "Setting a location filter will prevent this user seeing animals who are not in these locations on shelterview, find animal and search." : "", "Settings" : "", "Settings, Lookup data" : "", "Settings, Options" : "", "Settings, Reports" : "", "Settings, System user accounts" : "", "Sex" : "", "Sex and Species" : "", "Sexes" : "", "Shar Pei" : "", "Share" : "", "Shared weblink" : "", "Shares" : "", "Sheep" : "", "Sheep Dog" : "", "Shelter" : "", "Shelter Animal" : "", "Shelter Animals" : "", "Shelter Details" : "", "Shelter animal {0} '{1}'" : "", "Shelter animals" : "", "Shelter code cannot be blank" : "", "Shelter code {0} has already been allocated to another animal." : "", "Shelter stats (all time)" : "", "Shelter stats (this month)" : "", "Shelter stats (this week)" : "", "Shelter stats (this year)" : "", "Shelter stats (today)" : "", "Shelter view" : "", "Shepherd" : "", "Shetland Sheepdog Sheltie" : "", "Shiba Inu" : "", "Shift" : "", "Shih Tzu" : "", "Short" : "", "Show GDPR Contact Opt-In field on person screens" : "", "Show PDF files inline instead of sending them as attachments" : "", "Show a cost field on medical/test/vaccination screens" : "", "Show a minimap of the address on person screens" : "", "Show a separate paid date field with costs" : "", "Show alerts on the home page" : "", "Show animal thumbnails in movement and medical books" : "", "Show animals adopted" : "", "Show codes on the shelter view screen" : "", "Show complete comments in table views" : "", "Show empty locations" : "", "Show on new record screens" : "", "Show quick links on all pages" : "", "Show quick links on the home page" : "", "Show report menu items in collapsed categories" : "", "Show short shelter codes on screens" : "", "Show the adoption fee field" : "", "Show the altered fields" : "", "Show the breed fields" : "", "Show the brought in by field" : "", "Show the color field" : "", "Show the date brought in field" : "", "Show the entry category field" : "", "Show the full diary (instead of just my notes) on the home page" : "", "Show the hold fields" : "", "Show the internal location field" : "", "Show the litter ID field" : "", "Show the location unit field" : "", "Show the microchip fields" : "", "Show the original owner field" : "", "Show the size field" : "", "Show the tattoo fields" : "", "Show the time brought in field" : "", "Show the transfer in field" : "", "Show the weight field" : "", "Show timeline on the home page" : "", "Show tips on the home page" : "", "Show transactions from" : "", "Show weight as lb rather than kg" : "", "Showing {0} timeline events." : "", "Siamese" : "", "Siberian" : "", "Siberian Husky" : "", "Sick leave" : "", "Sick/Injured" : "", "Sick/injured animal" : "", "Sign" : "", "Sign document" : "", "Sign on screen" : "", "Signature" : "", "Signed" : "", "Signing" : "", "Signing Pad" : "", "Signup" : "", "Silky Terrier" : "", "Silver" : "", "Silver Fox" : "", "Silver Marten" : "", "Similar Animal" : "", "Similar Person" : "", "Simple" : "", "Singapura" : "", "Single Treatment" : "", "Site" : "", "Sites" : "", "Size" : "", "Sizes" : "", "Skunk" : "", "Skye Terrier" : "", "Sloughi" : "", "Small" : "", "SmartTag PETID" : "", "Smooth Fox Terrier" : "", "Snake" : "", "Snowshoe" : "", "Social" : "", "Softbill (Other)" : "", "Sold" : "", "Somali" : "", "Some batch processes may take a few minutes to run and could prevent other users being able to use the system for a short time." : "", "Some browsers allow shortcut keys, press SHIFT+ALT+A in Chrome or Firefox to jump to the animal adoption screen." : "", "Some info text" : "", "Sorrel" : "", "Sorrel Tortoiseshell" : "", "Sorry, this document has already been signed" : "", "South Russian Ovcharka" : "", "Spaniel" : "", "Special Needs" : "", "Species" : "", "Species A-Z" : "", "Species Z-A" : "", "Species to use when publishing to third party services and adoption sites" : "", "Specifying a reschedule date will make copies of the selected vaccinations and mark them to be given on the reschedule date. Example: If this vaccination needs to be given every year, set the reschedule date to be 1 year from today." : "", "Sphynx (hairless cat)" : "", "Spitz" : "", "Split baby/adult age at" : "", "Split species pages with a baby/adult prefix" : "", "Sponsorship donations" : "", "Staff" : "", "Staff Rota" : "", "Staff record" : "", "Staff rota" : "", "Staffordshire Bull Terrier" : "", "Standard" : "", "Standardbred" : "", "Start Date" : "", "Start Of Day" : "", "Start Time" : "", "Start at" : "", "Start date" : "", "Start date must be a valid date" : "", "Start of year" : "", "Started" : "", "Starts" : "", "State" : "", "State contains" : "", "Stationary costs" : "", "Stats" : "", "Stats period" : "", "Stats show running figures for the selected period of animals entering and leaving the shelter on the home page." : "", "Status" : "", "Status and Species" : "", "Stay" : "", "Stock" : "", "Stock Control" : "", "Stock Levels" : "", "Stock Locations" : "", "Stock Take" : "", "Stock Usage Type" : "", "Stock level must have a name" : "", "Stock level must have a unit" : "", "Stock needs a name and unit." : "", "Stocktake" : "", "Stolen" : "", "Stolen {0}" : "", "Stop" : "", "Stop Publishing" : "", "Stores" : "", "Stray" : "", "Su" : "", "SubTotal" : "", "Subject" : "", "Submission received: {0}" : "", "Success" : "", "Successfully attached to {0}" : "", "Sugar Glider" : "", "Sun" : "", "Sunday" : "", "Super user" : "", "Superuser" : "", "Surname" : "", "Surrender" : "", "Surrender Pickup" : "", "Suspect" : "", "Suspect 1" : "", "Suspect 2" : "", "Suspect 3" : "", "Suspect/Animal" : "", "Swan" : "", "Swedish Vallhund" : "", "Syntax check this SQL" : "", "System" : "", "System Admin" : "", "System Options" : "", "System user accounts" : "", "T = first letter of animal type" : "", "TNR" : "", "TNR - Trap/Neuter/Release" : "", "TT = first and second letter of animal type" : "", "Tabby" : "", "Tabby and White" : "", "Take another payment" : "", "Taken By" : "", "Tan" : "", "Tan and Black" : "", "Tan and White" : "", "Task complete." : "", "Task items are executed in order of index, lowest to highest" : "", "Tattoo" : "", "Tattoo Date" : "", "Tattoo Number" : "", "Tax" : "", "Tax Amount" : "", "Tax Rate %" : "", "Telephone" : "", "Telephone Bills" : "", "Template" : "", "Template Name" : "", "Template names can include a path portion with /, eg: Vets/Rabies Certificate" : "", "Tennessee Walker" : "", "Terrapin" : "", "Terrier" : "", "Test" : "", "Test Animal" : "", "Test Book" : "", "Test Performed" : "", "Test Results" : "", "Test Types" : "", "Test book" : "", "Test marked as performed for {0} - {1}" : "", "Tests" : "", "Tests need an animal and at least a required date." : "", "Text" : "", "Text Encoding" : "", "Th" : "", "Thai Ridgeback" : "", "Thank you for choosing Animal Shelter Manager for your shelter!" : "", "Thank you, the document is now signed." : "", "That animal is already linked to the incident" : "", "The CSV file should be created by PayPal's \"All Activity\" report." : "", "The SmartTag PETID number" : "", "The SmartTag type" : "", "The URL is the address of a web resource, eg: www.youtube.com/watch?v=xxxxxx" : "", "The animal name" : "", "The animal record to merge must be different from the original." : "", "The animal sex" : "", "The base color of this animal" : "", "The coat type of this animal" : "", "The confirmation email message to send to the form submitter. Leave blank to send a copy of the completed form." : "", "The database will be inaccessible to all users while the export is in progress." : "", "The date reported to the shelter" : "", "The date the animal died" : "", "The date the animal was FIV/L tested" : "", "The date the animal was adopted" : "", "The date the animal was altered" : "", "The date the animal was born" : "", "The date the animal was brought into the shelter" : "", "The date the animal was heartworm tested" : "", "The date the animal was microchipped" : "", "The date the animal was reclaimed" : "", "The date the animal was tattooed" : "", "The date the foster animal will be returned if known" : "", "The date the foster is effective from" : "", "The date the litter entered the shelter" : "", "The date the owner last contacted the shelter" : "", "The date the payment was received" : "", "The date the reservation is effective from" : "", "The date the retailer movement is effective from" : "", "The date the transfer is effective from" : "", "The date the trial adoption is over" : "", "The date the vaccination is required/due to be administered" : "", "The date the vaccination was administered" : "", "The date this animal was found" : "", "The date this animal was lost" : "", "The date this animal was put on the waiting list" : "", "The date this animal was removed from the waiting list" : "", "The date this animal was reserved" : "", "The date this animal was returned to its owner" : "", "The date this person was homechecked." : "", "The default username is 'user' with the password 'letmein'" : "", "The entry reason for this animal" : "", "The litter this animal belongs to" : "", "The locale determines the language ASM will use when displaying text, dates and currencies." : "", "The location where the animal was picked up" : "", "The microchip number" : "", "The movement number '{0}' is not unique." : "", "The number of stock records to create" : "", "The period in days before waiting list urgency is increased" : "", "The person record to merge must be different from the original." : "", "The primary breed of this animal" : "", "The reason the owner wants to part with the animal" : "", "The reason this animal was removed from the waiting list" : "", "The remaining units in the container" : "", "The result of the FIV test" : "", "The result of the FLV test" : "", "The result of the heartworm test" : "", "The retail/resale price per unit" : "", "The secondary breed of this animal" : "", "The selected file is not an image." : "", "The shelter category for this animal" : "", "The shelter reference number" : "", "The sheltermanager.com admin account password cannot be changed here, please visit {0}" : "", "The size of this animal" : "", "The species of this animal" : "", "The tattoo number" : "", "The type of unit in the container, eg: tablet, vial, etc." : "", "The veterinary license number." : "", "The wholesale/trade price the container was bought for" : "", "There is not enough information in the form to attach to a shelter animal record (need an animal name)." : "", "There is not enough information in the form to create a found animal record (need a description and area found)." : "", "There is not enough information in the form to create a lost animal record (need a description and area lost)." : "", "There is not enough information in the form to create a person record (need a surname)." : "", "There is not enough information in the form to create a transport record (need animalname)." : "", "There is not enough information in the form to create a transport record (need pickupdate and dropoffdate)." : "", "There is not enough information in the form to create a waiting list record (need a description)." : "", "There is not enough information in the form to create an incident record (need call notes and dispatch address)." : "", "These are the HTML headers and footers used when displaying online forms." : "", "These are the HTML headers and footers used when generating reports." : "", "These are the default values for these fields when creating new records." : "", "These batch processes are run each night by the system and should not need to be run manually." : "", "These fields allow you to deduct stock for the test(s) given. This single deduction should cover the selected tests being performed." : "", "These fields allow you to deduct stock for the treatment(s) given. This single deduction should cover the selected treatments being administered." : "", "These fields allow you to deduct stock for the vaccination(s) given. This single deduction should cover the selected vaccinations being administered." : "", "These fields determine which columns are shown on the find animal and find person screens." : "", "These numbers are for shelters who have agreements with insurance companies and are given blocks of policy numbers to allocate." : "", "These options change the behaviour of the search box at the top of the page." : "", "These values are required for correct operation of the system. ONLY change them if you are translating to another language." : "", "Third offence" : "", "This Month" : "", "This Week" : "", "This Year" : "", "This animal already has an active reservation." : "", "This animal has a SmartTag PETID" : "", "This animal has a tattoo" : "", "This animal has active reservations, they will be cancelled." : "", "This animal has an adoption fee of {0}" : "", "This animal has been FIV/L tested" : "", "This animal has been altered" : "", "This animal has been declawed" : "", "This animal has been heartworm tested" : "", "This animal has movements and cannot be removed." : "", "This animal has not been altered." : "", "This animal has not been microchipped." : "", "This animal has special needs" : "", "This animal has the same name as another animal recently added to the system." : "", "This animal is a crossbreed" : "", "This animal is bonded with {0}" : "", "This animal is bonded with {0}. Adoption movement records will be created for all bonded animals." : "", "This animal is currently at a retailer, it will be automatically returned first." : "", "This animal is currently fostered, it will be automatically returned first." : "", "This animal is currently held and cannot be adopted." : "", "This animal is currently quarantined and should not leave the shelter." : "", "This animal is marked not for adoption." : "", "This animal is microchipped" : "", "This animal is not on the shelter." : "", "This animal is part of a cruelty case and should not leave the shelter." : "", "This animal should be held in case it is reclaimed" : "", "This animal should not be shown in figures and is not in the custody of the shelter" : "", "This animal was dead on arrival to the shelter" : "", "This animal was euthanized" : "", "This animal was picked up" : "", "This animal was transferred from another shelter" : "", "This code has already been used." : "", "This database is locked and in read-only mode. You cannot add, change or delete records." : "", "This database is locked." : "", "This date of birth is an estimate" : "", "This expense account is the source for costs of this type" : "", "This income account is the source for payments received of this type" : "", "This item is referred to in the database ({0}) and cannot be deleted until it is no longer in use." : "", "This many years after creation of a person record, the name, address and telephone data will be anonymized." : "", "This month" : "", "This movement cannot be from a retailer when the animal has no prior retailer movements." : "", "This person has an animal control incident against them" : "", "This person has an animal control incident against them." : "", "This person has been banned from adopting animals" : "", "This person has been banned from adopting animals." : "", "This person has been under investigation" : "", "This person has been under investigation." : "", "This person has movements and cannot be removed." : "", "This person has not passed a homecheck" : "", "This person has not passed a homecheck." : "", "This person has payments and cannot be removed." : "", "This person has previously surrendered an animal." : "", "This person is linked to a waiting list record and cannot be removed." : "", "This person is linked to an animal and cannot be removed." : "", "This person is linked to an investigation and cannot be removed." : "", "This person is linked to animal control and cannot be removed." : "", "This person is linked to animal licenses and cannot be removed." : "", "This person is linked to animal transportation and cannot be removed." : "", "This person is linked to citations and cannot be removed." : "", "This person is linked to found animals and cannot be removed." : "", "This person is linked to lost animals and cannot be removed." : "", "This person is linked to trap loans and cannot be removed." : "", "This person is not flagged as a fosterer and cannot foster animals." : "", "This person is not flagged as a retailer and cannot handle retailer movements." : "", "This person is very similar to another person on file, carry on creating this record?" : "", "This person lives in the same area as the person who brought the animal to the shelter." : "", "This record has been changed by another user, please reload." : "", "This report cannot be sent by email as it requires criteria to run." : "", "This screen allows you to add extra documents to your database, for staff training, reference materials, etc." : "", "This screen allows you to add extra images to your database, for use in reports and documents." : "", "This type of movement requires a date." : "", "This type of movement requires a person." : "", "This week" : "", "This will permanently remove the selected records, are you sure?" : "", "This will permanently remove the selected roles, are you sure?" : "", "This will permanently remove the selected user accounts. Are you sure?" : "", "This will permanently remove this account and ALL TRANSACTIONS HELD AGAINST IT. This action is irreversible, are you sure you want to do this?" : "", "This will permanently remove this additional field and ALL DATA CURRENTLY HELD AGAINST IT. This action is irreversible, are you sure you want to do this?" : "", "This will permanently remove this animal, are you sure?" : "", "This will permanently remove this incident, are you sure?" : "", "This will permanently remove this person, are you sure?" : "", "This will permanently remove this record, are you sure?" : "", "This will permanently remove this waiting list entry, are you sure?" : "", "This will remove ALL rota entries for the week beginning {0}. This action is irreversible, are you sure?" : "", "This year" : "", "Thoroughbred" : "", "Thu" : "", "Thumbnail size" : "", "Thursday" : "", "Tibetan Mastiff" : "", "Tibetan Spaniel" : "", "Tibetan Terrier" : "", "Tiger" : "", "Time" : "", "Time Brought In" : "", "Time On List" : "", "Time On Shelter" : "", "Time on list" : "", "Time on shelter" : "", "Timeline" : "", "Timeline ({0})" : "", "Times should be in HH:MM format, eg: 09:00, 16:30" : "", "Title" : "", "Title First Last" : "", "Title Initials Last" : "", "To" : "", "To Adoption" : "", "To Fostering" : "", "To Other" : "", "To Retailer" : "", "To add people to the rota, create new person records with the staff or volunteer flag." : "", "To continue using ASM, please renew {0}" : "", "To week beginning" : "", "Today" : "", "Tonkinese" : "", "Too Many Animals" : "", "Tooltip" : "", "Top Margin" : "", "Tortie" : "", "Tortie and White" : "", "Tortoise" : "", "Tosa Inu" : "", "Total" : "", "Total number of units in the container" : "", "Total payments" : "", "Toucan" : "", "Toy Fox Terrier" : "", "Training" : "", "Transactions" : "", "Transactions need a date and description." : "", "Transfer" : "", "Transfer In" : "", "Transfer To" : "", "Transfer an animal" : "", "Transfer from Municipal Shelter" : "", "Transfer from Other Shelter" : "", "Transfer successfully created." : "", "Transfer?" : "", "Transferred" : "", "Transferred From" : "", "Transferred In" : "", "Transferred In {0}" : "", "Transferred Out" : "", "Transferred Out {0}" : "", "Transfers must have a valid transfer date." : "", "Transport" : "", "Transport Book" : "", "Transport Types" : "", "Transport book" : "", "Transport requires an animal" : "", "Transports must have valid pickup and dropoff dates and times." : "", "Trap Loans" : "", "Trap Number" : "", "Trap Types" : "", "Trap loan" : "", "Trap loans" : "", "Treat animals at retailers as part of the shelter inventory" : "", "Treat foster animals as part of the shelter inventory" : "", "Treat trial adoptions as part of the shelter inventory" : "", "Treatment" : "", "Treatment Given" : "", "Treatment marked as given for {0} - {1}" : "", "Treatment name cannot be blank" : "", "Treatments" : "", "Treeing Walker Coonhound" : "", "Trial Adoption" : "", "Trial adoption" : "", "Trial adoption book" : "", "Trial ends on" : "", "Tricolour" : "", "Trigger Batch Processes" : "", "Tu" : "", "Tue" : "", "Tuesday" : "", "Tumblr" : "", "Turkey" : "", "Turkish Angora" : "", "Turkish Van" : "", "Turtle" : "", "Twitter" : "", "Type" : "", "Type of animal links to show" : "", "U (Unwanted Cat)" : "", "UK Giftaid" : "", "URL" : "", "UUUUUUUUUU or UUUU = unique number" : "", "Unable to Afford" : "", "Unable to Cope" : "", "Unaltered" : "", "Unaltered Adopted Animals" : "", "Unaltered Dog - 1 year" : "", "Unaltered Dog - 3 year" : "", "Unavailable" : "", "Under {0} weeks old" : "", "Unit" : "", "Unit Price" : "", "Unit within the location, eg: pen or cage number" : "", "Units" : "", "Unknown" : "", "Unknown microchip brand" : "", "Unpaid Fines" : "", "Unreserved" : "", "Unsaved Changes" : "", "Unspecified" : "", "Unsuitable Accomodation" : "", "Up for adoption" : "", "Upcoming medical items" : "", "Update" : "", "Update publishing options" : "", "Update system options" : "", "Update the daily boarding cost for this animal" : "", "Updated database to version {0}" : "", "Updated." : "", "Updating..." : "", "Upload" : "", "Upload Document" : "", "Upload ODT" : "", "Upload Photo" : "", "Upload a new OpenOffice template" : "", "Upload all available images for animals" : "", "Upload an SQL script" : "", "Upload splash.jpg and logo.jpg to override the login screen image and logo at the top left of ASM." : "", "Uploading..." : "", "Urgencies" : "", "Urgency" : "", "Urgent" : "", "Usage Date" : "", "Usage Type" : "", "Usage explains why this stock record was created or adjusted. Usage records will only be created if the balance changes." : "", "Use Automatic Insurance Numbers" : "", "Use HTML5 client side image scaling where available to speed up image uploads" : "", "Use SQL Interface" : "", "Use a single breed field" : "", "Use animal comments" : "", "Use fancy tooltips" : "", "Use notes from preferred photo" : "", "Use the icon in the lower right of notes fields to view them in a separate window." : "", "User Accounts" : "", "User Roles" : "", "User accounts that will only ever call the Service API should set this to No." : "", "User roles" : "", "Username" : "", "Username '{0}' already exists" : "", "Users" : "", "Users need a username, password and at least one role or the superuser flag setting." : "", "Vacation" : "", "Vaccinate" : "", "Vaccinate Animal" : "", "Vaccination" : "", "Vaccination Book" : "", "Vaccination Given" : "", "Vaccination Types" : "", "Vaccination book" : "", "Vaccination marked as given for {0} - {1}" : "", "Vaccinations" : "", "Vaccinations need an animal and at least a required date." : "", "Vaccinations require an animal" : "", "Vaccinations: {0}, Tests: {1}, Medical Treatments: {2}, Transport: {3}, Costs: {4}, Total Costs: {5} Total Payments: {6}, Balance: {7}" : "", "Valid tokens for the subject and text" : "", "Value" : "", "Various" : "", "Vertical Pitch" : "", "Very Large" : "", "Vet" : "", "Vet Visit" : "", "Victim" : "", "Victim Name" : "", "Video Link" : "", "Vietnamese Pot Bellied" : "", "View" : "", "View Accounts" : "", "View Animals" : "", "View Audit Trail" : "", "View Citations" : "", "View Clinic Appointment" : "", "View Cost" : "", "View Diary" : "", "View Diets" : "", "View Document" : "", "View Document Repository" : "", "View Found Animal" : "", "View Incidents" : "", "View Incoming Forms" : "", "View Investigations" : "", "View Licenses" : "", "View Litter" : "", "View Log" : "", "View Lost Animal" : "", "View Manual" : "", "View Media" : "", "View Medical Records" : "", "View Movement" : "", "View PDF" : "", "View Payments" : "", "View Person" : "", "View Person Links" : "", "View Report" : "", "View Roles" : "", "View Rota" : "", "View Shelter Animals" : "", "View Staff Person Records" : "", "View Stock" : "", "View Tests" : "", "View Training Videos" : "", "View Transport" : "", "View Trap Loans" : "", "View Vaccinations" : "", "View Volunteer Person Records" : "", "View Vouchers" : "", "View Waiting List" : "", "View animals matching publishing options" : "", "View littermates" : "", "View matching records" : "", "View media" : "", "View publishing logs" : "", "Visual Theme" : "", "Vizsla" : "", "Volunteer" : "", "Voucher Types" : "", "Vouchers" : "", "Vouchers need an issue and expiry date." : "", "WARNING: This animal has not been microchipped" : "", "WARNING: This animal is over 6 months old and has not been neutered/spayed" : "", "Waiting" : "", "Waiting List" : "", "Waiting List - Additional" : "", "Waiting List - Details" : "", "Waiting List - Removal" : "", "Waiting List Contact" : "", "Waiting List Donation" : "", "Waiting List {0}" : "", "Waiting List: {0}" : "", "Waiting Room" : "", "Waiting for documents..." : "", "Waiting list donations" : "", "Waiting list entries matching '{0}'." : "", "Waiting list entries must have a contact" : "", "Waiting list entry for {0} ({1})" : "", "Waiting list entry successfully added." : "", "Waiting list urgency update period in days" : "", "Warmblood" : "", "Warn if the name of the new animal is similar to one entered recently" : "", "Warn when adopting an animal who has not been microchipped" : "", "Warn when adopting an unaltered animal" : "", "Warn when adopting to a person who has been banned from adopting animals" : "", "Warn when adopting to a person who has not been homechecked" : "", "Warn when adopting to a person who has previously brought an animal to the shelter" : "", "Warn when adopting to a person who lives in the same area as the original owner" : "", "Warn when creating multiple reservations on the same animal" : "", "Warnings" : "", "Wasted" : "", "Water Bills" : "", "We" : "", "Wed" : "", "Wednesday" : "", "Week" : "", "Week beginning {0}" : "", "Weekly" : "", "Weight" : "", "Weimaraner" : "", "Welcome!" : "", "Welsh Corgi" : "", "Welsh Springer Spaniel" : "", "Welsh Terrier" : "", "West Highland White Terrier Westie" : "", "Wheaten Terrier" : "", "When" : "", "When ASM should stop showing this message" : "", "When I change the location of an animal, make a note of it in the log with this type" : "", "When I change the weight of an animal, make a note of it in the log with this type" : "", "When I generate a document, make a note of it in the log with this type" : "", "When I mark an animal held, make a note of it in the log with this type" : "", "When I set a new GDPR Opt-In contact option, make a note of it in the log with this type" : "", "When a message is created, email it to each matching user" : "", "When creating payments from the Move menu screens, mark them due instead of received" : "", "When displaying calendars, the first day of the week is" : "", "When displaying person names, use the format" : "", "When entering dates, hold down CTRL and use the cursor keys to move around the calendar. Press t to go to today." : "", "When entering vaccinations, default the last batch number and manufacturer for that type" : "", "When matching lost animals, include shelter animals" : "", "When publishing to third party services, add this extra text to the bottom of all animal descriptions" : "", "When receiving multiple payments, allow the due and received dates to be set" : "", "When receiving payments, allow a quantity and unit price to be set" : "", "When receiving payments, allow recording of sales tax with a default rate of" : "", "When receiving payments, allow the deposit account to be overridden" : "", "When you use Move > Adopt an animal, ASM will automatically return any open foster or retailer movement before creating the adoption." : "", "When you use Move > Foster an animal, ASM will automatically return any open foster movement before moving the animal to its new home." : "", "Where this animal is located within the shelter" : "", "Whippet" : "", "White" : "", "White German Shepherd" : "", "White and Black" : "", "White and Brindle" : "", "White and Brown" : "", "White and Grey" : "", "White and Liver" : "", "White and Tabby" : "", "White and Tan" : "", "White and Torti" : "", "Will this owner give a donation?" : "", "Wire-haired Pointing Griffon" : "", "Wirehaired Terrier" : "", "With Vet" : "", "With overnight batch" : "", "Withdrawal" : "", "Wk" : "", "Work" : "", "Work Phone" : "", "Work Types" : "", "XXX or XX = number unique for this year" : "", "Xoloitzcuintle/Mexican Hairless" : "", "YY or YYYY = current year" : "", "Yellow Labrador Retriever" : "", "Yellow and Grey" : "", "Yes" : "", "Yes/No" : "", "Yes/No/Unknown" : "", "Yorkshire Terrier Yorkie" : "", "You can bookmark search results, animals, people and most data entry screens." : "", "You can drag and drop animals in shelter view to change their locations." : "", "You can middle click a link to open it in a new browser tab (push the wheel on most modern mice)." : "", "You can override the search result sort by adding one of the following to the end of your search - sort:az, sort:za, sort:mr, sort:lr" : "", "You can prefix your term in the search box with a: to search only animals, p: to search only people, wl: to search waiting list entries, la: to search lost animals and fa: to search found animals." : "", "You can set a default amount for different payment types in the Settings- Lookup Data screen. Very handy when creating adoptions." : "", "You can sort tables by clicking on the column headings." : "", "You can upload images called logo.jpg and splash.jpg to the Settings- Reports-Extra Images screen to override the login splash screen and logo in the upper left corner of the application." : "", "You can use incoming forms to create new records or attach them to existing records." : "", "You can't have a return without a movement." : "", "You didn't specify any search criteria, so an on-shelter search was assumed." : "", "You have unsaved changes, are you sure you want to leave this page?" : "", "You must supply a code." : "", "Young Adult" : "", "Your CSV file should have a header row with field names ASM recognises." : "", "Your sheltermanager.com account is due to expire on {0}, please renew {1}" : "", "Zipcode" : "", "Zipcode contains" : "", "[None]" : "", "after connecting, chdir to" : "", "and" : "", "are sent to" : "", "at" : "", "cm" : "", "days" : "", "estimate" : "", "filters: a:animal, p:person, wl:waitinglist, la:lostanimal, fa:foundanimal keywords: onshelter/os, notforadoption, aco, banned, donors, deceased, vets, retailers, staff, fosterers, volunteers, homecheckers, members, activelost, activefound" : "", "inches" : "", "invalid" : "", "kg" : "", "lb" : "", "less" : "", "mins" : "", "months" : "", "more" : "", "on" : "", "or" : "", "or estimated age in years" : "", "oz" : "", "to" : "", "today" : "", "treatments" : "", "treatments, every" : "", "weekdays" : "", "weeks" : "", "weeks after last contact." : "", "years" : "", "yesterday" : "", "{0} (under {1} months)" : "", "{0} - {1} ({2} {3} aged {4})" : "", "{0} - {1} {2}" : "", "{0} - {1} {2} ({3}), contact {4} ({5}) - lost in {6}, postcode {7}, on {8}" : "", "{0} animals successfully updated." : "", "{0} cannot be blank" : "", "{0} fine, paid" : "", "{0} fine, unpaid" : "", "{0} incurred in costs" : "", "{0} is running ({1}&#37; complete)." : "", "{0} payment records created." : "", "{0} received" : "", "{0} record(s) match the mail merge." : "", "{0} results." : "", "{0} rows affected." : "", "{0} selected" : "", "{0} treatments every {1} days" : "", "{0} treatments every {1} months" : "", "{0} treatments every {1} weekdays" : "", "{0} treatments every {1} weeks" : "", "{0} treatments every {1} years" : "", "{0} {1} ({2} treatments)" : "", "{0} {1} aged {2}" : "", "{0} {1} {2} aged {3}" : "", "{0} {1}: Moved from {2} to {3}" : "", "{0} {1}: adopted by {2}" : "", "{0} {1}: altered" : "", "{0} {1}: available for adoption" : "", "{0} {1}: died ({2})" : "", "{0} {1}: entered the shelter" : "", "{0} {1}: escaped" : "", "{0} {1}: euthanised ({2})" : "", "{0} {1}: fostered to {2}" : "", "{0} {1}: held" : "", "{0} {1}: microchipped" : "", "{0} {1}: not available for adoption" : "", "{0} {1}: quarantined" : "", "{0} {1}: received {2}" : "", "{0} {1}: reclaimed by {2}" : "", "{0} {1}: released" : "", "{0} {1}: reserved by {2}" : "", "{0} {1}: returned by {2}" : "", "{0} {1}: sent to retailer {2}" : "", "{0} {1}: stolen" : "", "{0} {1}: tested positive for FIV" : "", "{0} {1}: tested positive for FeLV" : "", "{0} {1}: tested positive for Heartworm" : "", "{0} {1}: transferred to {2}" : "", "{0}, Week {1}" : "", "{0}: Entered shelter {1}, Last changed on {2} by {3}. {4} {5} {6} aged {7}" : "", "{0}: closed {1} ({2})" : "", "{0}: opened {1}" : "", "{0}: waiting list - {1}" : "", "{0}: {1} {2} - {3} {4}" : "", "{2}: found in {1}: {0}" : "", "{2}: lost in {1}: {0}" : "", "{plural0} animal as dead on arrival" : "", "{plural0} animal control call due for followup today" : "", "{plural0} animal died" : "", "{plural0} animal entered the shelter" : "", "{plural0} animal has a hold ending today" : "", "{plural0} animal has been on the shelter longer than {0} months" : "", "{plural0} animal is not available for adoption" : "", "{plural0} animal was adopted" : "", "{plural0} animal was euthanized" : "", "{plural0} animal was reclaimed by its owner" : "", "{plural0} animal was transferred to another shelter" : "", "{plural0} day." : "", "{plural0} incomplete animal control call" : "", "{plural0} item of stock expires in the next month" : "", "{plural0} item of stock has expired" : "", "{plural0} medical treatment needs to be administered today" : "", "{plural0} month." : "", "{plural0} new online form submission" : "", "{plural0} person has an overdue payment" : "", "{plural0} person with an active reservation has not been homechecked" : "", "{plural0} potential match for a lost animal" : "", "{plural0} recent publisher run had errors" : "", "{plural0} reservation has been active over a week without adoption" : "", "{plural0} result found in {1} seconds. Order: {2}" : "", "{plural0} shelter animal has not been microchipped" : "", "{plural0} shelter animal has people looking for them" : "", "{plural0} test needs to be performed today" : "", "{plural0} transport does not have a driver assigned" : "", "{plural0} trap is overdue for return" : "", "{plural0} trial adoption has ended" : "", "{plural0} unaltered animal has been adopted in the last month" : "", "{plural0} undispatched animal control call" : "", "{plural0} unpaid fine" : "", "{plural0} urgent entry on the waiting list" : "", "{plural0} vaccination has expired" : "", "{plural0} vaccination needs to be administered today" : "", "{plural0} week." : "", "{plural0} year." : "", "{plural1} animal control calls due for followup today" : "", "{plural1} animals are not available for adoption" : "", "{plural1} animals died" : "", "{plural1} animals entered the shelter" : "", "{plural1} animals have been on the shelter longer than {0} months" : "", "{plural1} animals have holds ending today" : "", "{plural1} animals were adopted" : "", "{plural1} animals were dead on arrival" : "", "{plural1} animals were euthanized" : "", "{plural1} animals were reclaimed by their owners" : "", "{plural1} animals were transferred to other shelters" : "", "{plural1} days." : "", "{plural1} incomplete animal control calls" : "", "{plural1} items of stock expire in the next month" : "", "{plural1} items of stock have expired" : "", "{plural1} medical treatments need to be administered today" : "", "{plural1} months." : "", "{plural1} new online form submissions" : "", "{plural1} people have overdue payments" : "", "{plural1} people with active reservations have not been homechecked" : "", "{plural1} potential matches for lost animals" : "", "{plural1} recent publisher runs had errors" : "", "{plural1} reservations have been active over a week without adoption" : "", "{plural1} results found in {1} seconds. Order: {2}" : "", "{plural1} shelter animals have not been microchipped" : "", "{plural1} shelter animals have people looking for them" : "", "{plural1} tests need to be performed today" : "", "{plural1} transports do not have a driver assigned" : "", "{plural1} traps are overdue for return" : "", "{plural1} trial adoptions have ended" : "", "{plural1} unaltered animals have been adopted in the last month" : "", "{plural1} undispatched animal control calls" : "", "{plural1} unpaid fines" : "", "{plural1} urgent entries on the waiting list" : "", "{plural1} vaccinations have expired" : "", "{plural1} vaccinations need to be administered today" : "", "{plural1} weeks." : "", "{plural1} years." : "", "{plural2} animal control calls due for followup today" : "", "{plural2} animals are not available for adoption" : "", "{plural2} animals died" : "", "{plural2} animals entered the shelter" : "", "{plural2} animals have been on the shelter longer than {0} months" : "", "{plural2} animals have holds ending today" : "", "{plural2} animals were adopted" : "", "{plural2} animals were dead on arrival" : "", "{plural2} animals were euthanized" : "", "{plural2} animals were reclaimed by their owners" : "", "{plural2} animals were transferred to other shelters" : "", "{plural2} days." : "", "{plural2} incomplete animal control calls" : "", "{plural2} items of stock expire in the next month" : "", "{plural2} items of stock have expired" : "", "{plural2} medical treatments need to be administered today" : "", "{plural2} months." : "", "{plural2} new online form submissions" : "", "{plural2} people have overdue payments" : "", "{plural2} people with active reservations have not been homechecked" : "", "{plural2} potential matches for lost animals" : "", "{plural2} recent publisher runs had errors" : "", "{plural2} reservations have been active over a week without adoption" : "", "{plural2} results found in {1} seconds. Order: {2}" : "", "{plural2} shelter animals have not been microchipped" : "", "{plural2} shelter animals have people looking for them" : "", "{plural2} tests need to be performed today" : "", "{plural2} transports do not have a driver assigned" : "", "{plural2} traps are overdue for return" : "", "{plural2} trial adoptions have ended" : "", "{plural2} unaltered animals have been adopted in the last month" : "", "{plural2} undispatched animal control calls" : "", "{plural2} unpaid fines" : "", "{plural2} urgent entries on the waiting list" : "", "{plural2} vaccinations have expired" : "", "{plural2} vaccinations need to be administered today" : "", "{plural2} weeks." : "", "{plural2} years." : "", "{plural3} animal control calls due for followup today" : "", "{plural3} animals are not available for adoption" : "", "{plural3} animals died" : "", "{plural3} animals entered the shelter" : "", "{plural3} animals have been on the shelter longer than {0} months" : "", "{plural3} animals have holds ending today" : "", "{plural3} animals were adopted" : "", "{plural3} animals were dead on arrival" : "", "{plural3} animals were euthanized" : "", "{plural3} animals were reclaimed by their owners" : "", "{plural3} animals were transferred to other shelters" : "", "{plural3} days." : "", "{plural3} incomplete animal control calls" : "", "{plural3} items of stock expire in the next month" : "", "{plural3} items of stock have expired" : "", "{plural3} medical treatments need to be administered today" : "", "{plural3} months." : "", "{plural3} new online form submissions" : "", "{plural3} people have overdue payments" : "", "{plural3} people with active reservations have not been homechecked" : "", "{plural3} potential matches for lost animals" : "", "{plural3} recent publisher runs had errors" : "", "{plural3} reservations have been active over a week without adoption" : "", "{plural3} results found in {1} seconds. Order: {2}" : "", "{plural3} shelter animals have not been microchipped" : "", "{plural3} shelter animals have people looking for them" : "", "{plural3} tests need to be performed today" : "", "{plural3} transports do not have a driver assigned" : "", "{plural3} traps are overdue for return" : "", "{plural3} trial adoptions have ended" : "", "{plural3} unaltered animals have been adopted in the last month" : "", "{plural3} undispatched animal control calls" : "", "{plural3} unpaid fines" : "", "{plural3} urgent entries on the waiting list" : "", "{plural3} vaccinations have expired" : "", "{plural3} vaccinations need to be administered today" : "", "{plural3} weeks." : "" }; _ = function(key) { try { var v = key; if (i18n_lang.hasOwnProperty(key)) { if ($.trim(i18n_lang[key]) != "" && i18n_lang[key].indexOf("??") != 0 && i18n_lang[key].indexOf("(??") != 0) { v = i18n_lang[key]; } else { v = key; } } else { v = key; } return $("<div></div>").html(v).text(); } catch (err) { return "[error]"; } };
bobintetley/asm3
src/static/js/locales/locale_ceb.js
JavaScript
gpl-3.0
109,226
/* * This file is part of ARSnova Click. * Copyright (C) 2016 The ARSnova Team * * ARSnova Click is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ARSnova Click 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ARSnova Click. If not, see <http://www.gnu.org/licenses/>.*/ import {Meteor} from 'meteor/meteor'; import {MusicSessionConfiguration} from './session_config_music.js'; import {NickSessionConfiguration} from './session_config_nicks.js'; const hashtag = Symbol("hashtag"); const music = Symbol("music"); const nicks = Symbol("nicks"); const theme = Symbol("theme"); const readingConfirmationEnabled = Symbol("readingConfirmationEnabled"); const showResponseProgress = Symbol("showResponseProgress"); const confidenceSliderEnabled = Symbol("confidenceSliderEnabled"); export class AbstractSessionConfiguration { constructor(options) { if (this.constructor === AbstractSessionConfiguration) { throw new TypeError("Cannot construct Abstract instances directly"); } if (typeof options.hashtag === "undefined") { throw new Error("Invalid argument list for SessionConfiguration instantiation"); } if (options.music instanceof Object) { if (!(options.music instanceof MusicSessionConfiguration)) { options.music = new MusicSessionConfiguration(options); } } else { options.music = {}; options.music = new MusicSessionConfiguration(options); } if (options.nicks instanceof Object) { if (!(options.nicks instanceof NickSessionConfiguration)) { options.nicks = new NickSessionConfiguration(options); } } else { options.nicks = {}; options.nicks = new NickSessionConfiguration(options); } this[hashtag] = options.hashtag; this[music] = options.music; this[nicks] = options.nicks; this[theme] = options.theme || Meteor.settings.public.default.theme; this[readingConfirmationEnabled] = typeof options.readingConfirmationEnabled === "undefined" ? Meteor.settings.public.default.sessionConfiguration.readingConfirmationEnabled : options.readingConfirmationEnabled; this[showResponseProgress] = typeof options.showResponseProgress === "undefined" ? Meteor.settings.public.default.sessionConfiguration.showResponseProgress : options.showResponseProgress === true; this[confidenceSliderEnabled] = typeof options.confidenceSliderEnabled === "undefined" ? Meteor.settings.public.default.sessionConfiguration.confidenceSliderEnabled : options.confidenceSliderEnabled === true; } serialize() { return { hashtag: this.getHashtag(), music: this.getMusicSettings().serialize(), nicks: this.getNickSettings().serialize(), theme: this.getTheme(), readingConfirmationEnabled: this.getReadingConfirmationEnabled(), showResponseProgress: this.getShowResponseProgress(), confidenceSliderEnabled: this.getConfidenceSliderEnabled() }; } equals(value) { return this.getHashtag() === value.getHashtag() && this.getMusicSettings().equals(value.getMusicSettings()) && this.getNickSettings().equals(value.getNickSettings()) && this.getTheme() === value.getTheme() && this.getReadingConfirmationEnabled() === value.getReadingConfirmationEnabled() && this.getShowResponseProgress() === value.getShowResponseProgress() && this.getConfidenceSliderEnabled() === value.getConfidenceSliderEnabled(); } /** * Part of EJSON interface * @see AbstractSessionConfiguration.serialize() * @see http://docs.meteor.com/api/ejson.html#EJSON-CustomType-toJSONValue * @returns Object */ toJSONValue() { return this.serialize(); } getHashtag() { return this[hashtag]; } setHashtag(value) { this[hashtag] = value; this.getMusicSettings().setHashtag(value); this.getNickSettings().setHashtag(value); } getTheme() { return this[theme]; } setTheme(value) { this[theme] = value; } getMusicSettings() { return this[music]; } setMusicSettings(value) { if (value instanceof Object && !(value instanceof MusicSessionConfiguration)) { value = new MusicSessionConfiguration(value); } this[music] = value; } getNickSettings() { return this[nicks]; } setNickSettings(value) { if (value instanceof Object && !(value instanceof NickSessionConfiguration)) { value = new NickSessionConfiguration(value); } this[nicks] = value; } getReadingConfirmationEnabled() { return this[readingConfirmationEnabled]; } setReadingConfirmationEnabled(value) { if (typeof value !== "boolean") { throw new Error("Invalid argument for AbstractSessionConfiguration.setReadingConfirmationEnabled"); } this[readingConfirmationEnabled] = value; } getShowResponseProgress() { return this[showResponseProgress]; } setShowResponseProgress(value) { if (typeof value !== "boolean") { throw new Error("Invalid argument for AbstractSessionConfiguration.setShowResponseProgress"); } this[showResponseProgress] = value; } getConfidenceSliderEnabled() { return this[confidenceSliderEnabled]; } setConfidenceSliderEnabled(value) { if (typeof value !== "boolean") { throw new Error("Invalid argument for AbstractSessionConfiguration.setConfidenceSliderEnabled"); } this[confidenceSliderEnabled] = value; } }
thm-projects/arsnova.click
arsnova.click/lib/session_configuration/session_config_abstract.js
JavaScript
gpl-3.0
5,624
module.exports = Marionette.Region.extend( { storage: null, storageSizeKeys: null, constructor: function() { Marionette.Region.prototype.constructor.apply( this, arguments ); var savedStorage = elementorCommon.storage.get( this.getStorageKey() ); this.storage = savedStorage ? savedStorage : this.getDefaultStorage(); this.storageSizeKeys = Object.keys( this.storage.size ); }, saveStorage: function( key, value ) { this.storage[ key ] = value; elementorCommon.storage.set( this.getStorageKey(), this.storage ); }, saveSize: function() { this.saveStorage( 'size', elementor.helpers.getElementInlineStyle( this.$el, this.storageSizeKeys ) ); }, } );
joshmarom/elementor
assets/dev/js/editor/regions/base.js
JavaScript
gpl-3.0
680
function MilleniumFalcon(context, teclado, imagem, imagemExplosao, touch) { "use strict" this.context = context; this.teclado = teclado; this.touch = touch; this.imagem = imagem; this.x = 0; this.y = 0; this.velocidade = 0; this.imagemExplosao = imagemExplosao; this.acabaramVidas = null; this.vidasExtras = 3; this.stringUnica = 'falcon'; this.ultimoTiro = new Date().getTime(); } MilleniumFalcon.prototype = { atualizar: function () { this.chewbaccaAtirar(); if (!this.teclado.hasPressed()) { this.x = this.touch.posicaoX() - (this.imagem.width / 2); this.y = this.touch.posicaoY() - (this.imagem.height / 2 + 50); return; } var incremento = this.velocidade * this.animacao.decorrido / 1000; if (this.teclado.pressionada(SETA_ESQUERDA) && this.x > 0) this.x -= incremento; if (this.teclado.pressionada(SETA_DIREITA) && this.x < this.context.canvas.width - this.imagem.width) this.x += incremento; if (this.teclado.pressionada(SETA_ACIMA) && this.y > 0) this.y -= incremento; if (this.teclado.pressionada(SETA_ABAIXO) && this.y < this.context.canvas.height - this.imagem.height) this.y += incremento; }, chewbaccaAtirar: function () { var agora = new Date().getTime(); var decorrido = agora - this.ultimoTiro; if (decorrido < 290) return; this.atirar(); this.ultimoTiro = agora; }, desenhar: function () { this.context.drawImage(this.imagem, this.x, this.y, this.imagem.width, this.imagem.height); }, atirar: function () { var t = new Tiro(this.context, this); this.animacao.novoSprite(t); this.colisor.novoSprite(t); }, retangulosColisao: function () { return [ { x: this.x + 13, y: this.y + 22, largura: 60, altura: 80 } ]; }, colidiuCom: function (outro) { if (outro instanceof TieFighter || outro instanceof Asteroid) { this.animacao.excluirSprite(this); this.animacao.excluirSprite(outro); this.colisor.excluirSprite(this); this.colisor.excluirSprite(outro); window.navigator.vibrate(300); //Gera uma explosão para a nave e uma para //o inimigo var exp1 = new Explosao(this.context, this.imagemExplosao, this.x, this.y); var exp2 = new Explosao(this.context, this.imagemExplosao, outro.x, outro.y); this.animacao.novoSprite(exp1); this.animacao.novoSprite(exp2); var nave = this; exp1.fimDaExplosao = function () { nave.vidasExtras--; if (nave.vidasExtras < 0) { if (nave.acabaramVidas) nave.acabaramVidas(); } else { nave.colisor.novoSprite(nave); nave.animacao.novoSprite(nave); nave.posicionar(); } } } }, posicionar: function () { var canvas = this.context.canvas; this.x = canvas.width / 2 - 40.83333; this.y = canvas.height - 110; } }
rafaelguinho/millenium-falcon-attack
game/milleniumFalcon.js
JavaScript
gpl-3.0
3,331
import React from 'react'; import { Link } from 'react-router-dom'; import Nav from './Nav'; import NavProfile from './NavProfile'; /** * SFC for displaying site branding / logo within the Header. */ const Branding = () => { return( <Link className='button' to='/'> <h4>SR</h4> </Link> ); } /** * Stateless Functional Component to display branding, Nav, and other elements * at the top of the page. */ const Header = () => { return( <div className='header-container'> <div className='branding-container'> <Branding /> </div> <div className='nav-container'> <Nav /> </div> <div className='user-container'> <NavProfile /> </div> </div> ); } export default Header;
stratigos/stormsreach
app/components/Header.js
JavaScript
gpl-3.0
761
var class_n_i_vissim_district_connection = [ [ "DictType", "d9/d07/class_n_i_vissim_district_connection.html#afd48c4f5080f42fa92716ba384039a8b", null ], [ "DistrictPercentages", "d9/d07/class_n_i_vissim_district_connection.html#ae35b69635f8aab9dc337110c9a710ec7", null ], [ "NIVissimDistrictConnection", "d9/d07/class_n_i_vissim_district_connection.html#a7d3b9f0d4e192294ecc95529f7677be5", null ], [ "~NIVissimDistrictConnection", "d9/d07/class_n_i_vissim_district_connection.html#a6418c97c6d9c41b80b040ece6fe37107", null ], [ "checkEdgeEnd", "d9/d07/class_n_i_vissim_district_connection.html#a8bf3a85e7900513834fcf9f678d5e5c1", null ], [ "clearDict", "d9/d07/class_n_i_vissim_district_connection.html#ac532c6c73d669dee8584a0f52e11cbde", null ], [ "dict_BuildDistrictConnections", "d9/d07/class_n_i_vissim_district_connection.html#a58f3ad5a2fb2986687793fcb77e7d5d9", null ], [ "dict_BuildDistrictNodes", "d9/d07/class_n_i_vissim_district_connection.html#a8e80b61a2ef189131ebab1f5abfecc7b", null ], [ "dict_BuildDistricts", "d9/d07/class_n_i_vissim_district_connection.html#a04d647e0c8a1d00eef247058c55e6d14", null ], [ "dict_CheckEdgeEnds", "d9/d07/class_n_i_vissim_district_connection.html#a73b663786de4e5bf7c4e35fefea0549a", null ], [ "dict_findForEdge", "d9/d07/class_n_i_vissim_district_connection.html#a691a41a47c621646e3ec2384e1ce0f5e", null ], [ "dictionary", "d9/d07/class_n_i_vissim_district_connection.html#a16a5f0f22b11bfca7328123099e767a9", null ], [ "dictionary", "d9/d07/class_n_i_vissim_district_connection.html#a3ba9a58ea9cba6590193914f5071b762", null ], [ "dictionary", "d9/d07/class_n_i_vissim_district_connection.html#a67e3109a7b448d8cc63d2a08bb701cbd", null ], [ "geomPosition", "d9/d07/class_n_i_vissim_district_connection.html#ac3561a14850e5644f9dacb0607b6338f", null ], [ "getID", "d9/d07/class_n_i_vissim_district_connection.html#a9354a9e572a049bb766b97d20f671033", null ], [ "getMeanSpeed", "d9/d07/class_n_i_vissim_district_connection.html#a603979a0e228237da527137f2533e731", null ], [ "getPosition", "d9/d07/class_n_i_vissim_district_connection.html#ace9828318bf2cde658a054da54a6496b", null ], [ "getRealSpeed", "d9/d07/class_n_i_vissim_district_connection.html#a9fcf00897ffd1dfd176962243d2c1344", null ], [ "myAssignedVehicles", "d9/d07/class_n_i_vissim_district_connection.html#a823b4f8366264b1bc702e11a7bff6ef9", null ], [ "myDict", "d9/d07/class_n_i_vissim_district_connection.html#ad9a8fb33b9aa5794ddf8634ce025fcac", null ], [ "myDistricts", "d9/d07/class_n_i_vissim_district_connection.html#a46b9471f0d0a90020bf808ba8a44d314", null ], [ "myDistrictsConnections", "d9/d07/class_n_i_vissim_district_connection.html#a6ff3e34d5635725917f14cf7fffdec56", null ], [ "myEdgeID", "d9/d07/class_n_i_vissim_district_connection.html#affaba41eb45e91672d32019c875f2d95", null ], [ "myID", "d9/d07/class_n_i_vissim_district_connection.html#aaa00983103cc254b772442378e688b85", null ], [ "myName", "d9/d07/class_n_i_vissim_district_connection.html#aa517ee4bab6c396764a1f5517979da48", null ], [ "myPercentages", "d9/d07/class_n_i_vissim_district_connection.html#a10f5d0f7313032bec2244f1e9a0df879", null ], [ "myPosition", "d9/d07/class_n_i_vissim_district_connection.html#a179e0877a4ee8d448da33102fb68d229", null ] ];
cathyyul/sumo-0.18
docs/doxygen/d9/d07/class_n_i_vissim_district_connection.js
JavaScript
gpl-3.0
3,344
document.addEventListener("DOMContentLoaded", function(event) { var names = ["Maria", "João", "Carlos", "Joana"]; var PersonJSON = { name: "Adriano", yearBirth: 1987, gender: "M" }; console.log(names); console.log(PersonJSON.name); //-------------------------------------------------------------------------- function Person(name, yearBirth){ this.name = name; this.yearBirth = yearBirth; this.getAge = function(){ return new Date().getFullYear() - this.yearBirth; } }; var maria = new Person("Maria", 1987); console.log(maria.name); console.log(maria.getAge()); Person.prototype.getName = function(){ return this.name; } console.log(maria.getName()); });
adrianomargarin/curso-js-vendabem
cursojs/static/aulas/js/aula-03/objects.js
JavaScript
gpl-3.0
798
const Clutter = imports.gi.Clutter; const St = imports.gi.St; const Main = imports.ui.main; // const Tweener = imports.ui.tweener; const Gio = imports.gi.Gio; const Mainloop = imports.mainloop; // const GLib = imports.gi.GLib; const ExtensionUtils = imports.misc.extensionUtils; const Me = ExtensionUtils.getCurrentExtension(); const PREFS_SCHEMA = 'org.gnome.shell.extensions.harddiskled'; const refreshTime = 2.0; const ledThreshold = 500000; const ledMinThreshold = 100000; let settings; let button, timeout; // let icon, iconDark; let cur; let ioSpeed; let lastCount, lastSpeed; let mode; let layoutManager; let ioSpeedStaticIcon; let ioSpeedIcon; function init() { cur = 0; lastCount = 0; } function changeMode() { mode++; if (mode > 5) { mode = 0; } settings.set_int('mode', mode); parseStat(true); } function parseStat(forceDot = false) { try { let input_file = Gio.file_new_for_path('/proc/diskstats'); let fstream = input_file.read(null); let dstream = Gio.DataInputStream.new(fstream); let count = 0; let line; while ((line = dstream.read_line(null))) { line = String(line); let fields = line.split(/ +/); if (fields.length<=2) break; if (parseInt(fields[2])%16 === 0 && fields[3].indexOf('md0') != 0 && fields[3].indexOf('ram0') != 0 && fields[3].indexOf('dm-0') != 0 && fields[3].indexOf('zram0') != 0 && fields[3].indexOf('loop0') != 0) { count = count + parseInt(fields[6]) + parseInt(fields[10]); // log(fields[3] + ':' + fields[6] + ' ' + fields[10] + ' ' + count); } } fstream.close(null); if (lastCount === 0) lastCount = count; let speed = (count - lastCount) / refreshTime * 512; let dot = " "; if (speed > lastSpeed || forceDot || speed > ledThreshold) { if (speed > ledMinThreshold) { if (mode == 0 || mode == 2 || mode == 4) { dot = "●"; } else if (mode == 1 || mode == 3) { dot = "⬤"; } } } if (mode == 2 || mode == 3) { ioSpeed.hide(); } else { ioSpeed.show(); } if (mode == 4 || mode == 5) { ioSpeedStaticIcon.hide(); } else { ioSpeedStaticIcon.show(); } if (mode == 5) { ioSpeedIcon.hide(); } else { ioSpeedIcon.show(); } ioSpeedIcon.set_text(dot); ioSpeed.set_text(speedToString(speed)); lastCount = count; lastSpeed = speed; } catch (e) { ioSpeed.set_text(e.message); } /* let curDiskstats = GLib.file_get_contents('/proc/diskstats'); if (diskstats == curDiskstats) { if (cur !== 0) { button.set_child(iconDark); cur = 0; } } else { if (cur != 1) { button.set_child(icon); cur = 1; } diskstats = curDiskstats; }*/ return true; } function speedToString(amount) { let digits; let speed_map; speed_map = ["B/s", "K/s", "M/s", "G/s"]; if (amount === 0) return "0" + speed_map[0]; let unit = 0; while (amount >= 1000) { // 1M=1024K, 1MB/s=1000MB/s amount /= 1000; ++unit; } if (amount >= 100) // 100MB 100KB 200KB digits = 0; else if (amount >= 10) // 10MB 10.2 digits = 1; else digits = 2; return String(amount.toFixed(digits)) + speed_map[unit]; } function enable() { settings = ExtensionUtils.getSettings(PREFS_SCHEMA); mode = settings.get_int('mode'); // default mode button = new St.Button({ style_class: 'panel-button', reactive: true, can_focus: true, x_expand: true, y_expand: false, track_hover: true }); layoutManager = new St.BoxLayout({ vertical: false, style_class: 'harddiskled-container'}); /* icon = new St.Icon({ gicon: Gio.icon_new_for_string(Me.path + "/icons/harddisk.svg") }); iconDark = new St.Icon({ gicon: Gio.icon_new_for_string(Me.path + "/icons/harddisk-dark.svg") });*/ ioSpeedStaticIcon = new St.Icon({ style_class: 'system-status-icon', y_align: Clutter.ActorAlign.CENTER, gicon: Gio.icon_new_for_string('drive-harddisk-symbolic') }); ioSpeed = new St.Label({ text: '---', y_align: Clutter.ActorAlign.CENTER, style_class: 'harddiskled-label' }); ioSpeedIcon = new St.Label({ text: '', y_align: Clutter.ActorAlign.CENTER, style_class: 'harddiskled-icon' }); layoutManager.add(ioSpeedStaticIcon); layoutManager.add(ioSpeedIcon); layoutManager.add(ioSpeed); button.connect('button-press-event', changeMode); button.set_child(layoutManager); Main.panel._rightBox.insert_child_at_index(button, 0); timeout = Mainloop.timeout_add_seconds(refreshTime, parseStat); } function disable() { Mainloop.source_remove(timeout); timeout = null; Main.panel._rightBox.remove_child(button); button.destroy(); settings = button = layoutManager = ioSpeedStaticIcon = ioSpeed = ioSpeedIcon = null; }
biji/harddiskled
extension.js
JavaScript
gpl-3.0
5,493
var eventServiceModule = require("../src/eventService.js"); var eventService = new eventServiceModule(); var eventFactory = eventService.getEventFactory(); var closureStrings = ["All lanes are closed", "All lanes will be closed"]; var slipString = ["exit slip", "entry slip"]; var slanesStrings = ["three of four lanes", "two of three lanes", "one of two lanes"]; var today = new Date(); var tomorrow = new Date(); tomorrow.setDate(today.getDate() + 1); var yesterday = new Date().setDate(new Date().getDate() - 1); var eventOne = { eventStart: today.toDateString(), category: ["Road Works","Barrier/Bridge Repairs"], title:"A1 Works", road:"A1", reference:"RW0001", status: "Active", description: closureStrings[0] }; var eventTwo = { eventStart: today.toDateString(), category: ["Road Works","Barrier/Bridge Repairs"], title:"A2 Works", road:"A2", reference:"RW0002", status: "Active", description: closureStrings[1] }; var eventThree = { eventStart: today.toDateString(), category: ["Barrier/Bridge Repairs", "Road Works"], title:"A3 Works", road:"A3", reference:"RW0003", status: "Active", description: closureStrings[1] + " " + slipString[0] }; var eventFour = { eventStart: today.toDateString(), category: ["Barrier/Bridge Repairs", "Road Works"], title:"A4 Works", road:"A4", reference:"RW0004", status: "Active", description: closureStrings[0] + " " + slipString[1] }; var eventFive = { eventStart: today.toDateString(), category: ["Road Works","Barrier/Bridge Repairs"], title:"A5 Works", road:"A5", reference:"RW0005", status: "Active", description: slanesStrings[0] }; var customEventOne = { eventStart: today.toDateString(), category: ["Road Works","Barrier/Bridge Repairs"], title:"A6 Works", road:"A6", reference:"RW0006", status: "Active", description: slanesStrings[2] }; var customEventTwo = { eventStart: today.toDateString(), category: ["Barrier/Bridge Repairs", "Road Works"], title:"A7 Works", road:"A7", reference:"RW0007", status: "Active", description: slanesStrings[1] + " " + slipString[0] }; var customEventThree = { eventStart: today.toDateString(), category: ["Barrier/Bridge Repairs", "Road Works"], title:"A8 Works", road:"A8", reference:"RW0008", status: "Active", description:" "}; var customEventFour = { eventStart: today.toDateString(), category: ["Road Works","Barrier/Bridge Repairs"], title:"A9 Works", road:"A9", reference:"RW0009", status: "Active", description:" " }; var customEventFive = { eventStart: tomorrow.toDateString(), category: ["Road Works","Barrier/Bridge Repairs"], title:"A10 Works", road:"A10", reference:"RW0010", status: "Active", description: closureStrings[0] }; eventFactory.addEvent(eventOne); eventFactory.addEvent(eventTwo); eventFactory.addEvent(eventThree); eventFactory.addEvent(eventFour); eventFactory.addEvent(eventFive); eventFactory.addCustomEvent(customEventOne); eventFactory.addCustomEvent(customEventTwo); eventFactory.addCustomEvent(customEventThree); eventFactory.addCustomEvent(customEventFour); eventFactory.addCustomEvent(customEventFive); describe("Request events and check search criteria", function(){ it("Gets full closures on main carriageways today", function(done){ eventService.getEvents({ slips: "N", slanes: "N", startDate: new Date() }, function(error, results){ var targetArray = []; targetArray.push(eventOne); targetArray.push(eventTwo); expect(results).toContain(eventOne); expect(results).toContain(eventTwo); expect(results).not.toContain(eventThree); expect(results).not.toContain(eventFour); expect(results).not.toContain(eventFive); expect(results).not.toContain(customEventOne); expect(results).not.toContain(customEventTwo); expect(results).not.toContain(customEventThree); expect(results).not.toContain(customEventFour); expect(results).not.toContain(customEventFive); done(); }); }); it("Gets full closures on slips and main carriageway today",function(done){ eventService.getEvents({ slips: "Y", slanes: "N", startDate: new Date() }, function(error, results){ var targetArray = []; targetArray.push(eventOne); targetArray.push(eventTwo); targetArray.push(eventThree); targetArray.push(eventFour); expect(results).toContain(eventOne); expect(results).toContain(eventTwo); expect(results).toContain(eventThree); expect(results).toContain(eventFour); expect(results).not.toContain(eventFive); expect(results).not.toContain(customEventOne); expect(results).not.toContain(customEventTwo); expect(results).not.toContain(customEventThree); expect(results).not.toContain(customEventFour); expect(results).not.toContain(customEventFive); done(); }); }); it("Gets lane closures on main carriageway today",function(done){ eventService.getEvents({ slips: "N", slanes: "Y", startDate: new Date() }, function(error, results){ var targetArray = []; targetArray.push(eventOne); targetArray.push(eventTwo); targetArray.push(eventFive); targetArray.push(customEventOne); expect(results).toContain(eventOne); expect(results).toContain(eventTwo); expect(results).not.toContain(eventThree); expect(results).not.toContain(eventFour); expect(results).toContain(eventFive); expect(results).toContain(customEventOne); expect(results).not.toContain(customEventTwo); expect(results).not.toContain(customEventThree); expect(results).not.toContain(customEventFour); expect(results).not.toContain(customEventFive); done(); }); }); it("Gets lane closures on main carriageway and slips today",function(done){ eventService.getEvents({ slips: "Y", slanes: "Y", startDate: new Date() }, function(error, results){ var targetArray = []; targetArray.push(eventOne); targetArray.push(eventTwo); targetArray.push(eventThree); targetArray.push(eventFour); targetArray.push(eventFive); targetArray.push(customEventOne); targetArray.push(customEventTwo); expect(results).toContain(eventOne); expect(results).toContain(eventTwo); expect(results).toContain(eventThree); expect(results).toContain(eventFour); expect(results).toContain(eventFive); expect(results).toContain(customEventOne); expect(results).toContain(customEventTwo); expect(results).not.toContain(customEventThree); expect(results).not.toContain(customEventFour); expect(results).not.toContain(customEventFive); done(); }); }); it("Gets full closures on main carriageway tomorrow",function(done){ eventService.getEvents({ slips: "Y", slanes: "Y", startDate: tomorrow }, function(error, results){ var targetArray = []; targetArray.push(eventOne); targetArray.push(eventTwo); targetArray.push(eventThree); targetArray.push(eventFour); targetArray.push(eventFive); targetArray.push(customEventOne); targetArray.push(customEventTwo); expect(results).toContain(eventOne); expect(results).toContain(eventTwo); expect(results).toContain(eventThree); expect(results).toContain(eventFour); expect(results).toContain(eventFive); expect(results).toContain(customEventOne); expect(results).toContain(customEventTwo); expect(results).not.toContain(customEventThree); expect(results).not.toContain(customEventFour); expect(results).toContain(customEventFive); done(); }); }); });
mrlount/closures
specs/eventService.spec.js
JavaScript
gpl-3.0
8,126
var gulp = require("gulp"), sass = require("gulp-sass"), autoprefixer = require("gulp-autoprefixer"); var sourcemaps = require('gulp-sourcemaps'); const imagemin = require('gulp-imagemin'); // Compile SCSS files to CSS var scss_asset_folder = "themes/wefight/static/scss/**/"; gulp.task("scss", function () { gulp.src(scss_asset_folder + '*.scss') .pipe(sourcemaps.init()) .pipe(sass({ outputStyle : "compressed", includePaths: ['node_modules'] })) .pipe(autoprefixer({ browsers : ["last 20 versions"] })) .pipe(sourcemaps.write()) .pipe(gulp.dest("themes/wefight/static/css/")) }); // Watch asset folder for changes gulp.task("watch", ["scss"], function () { gulp.watch(scss_asset_folder + '/*', ["scss"]) }); gulp.task("images", function(){ gulp.src('static/**/*') .pipe(imagemin([ imagemin.gifsicle({interlaced: true}), imagemin.jpegtran({progressive: true}), imagemin.optipng({optimizationLevel: 5}) ])) .pipe(gulp.dest('static')) }); gulp.task("default", ["scss"]); gulp.task("build", ["scss", "images"]);
vladfr/wefightwithcards
gulpfile.js
JavaScript
gpl-3.0
1,204
// Python to Javascript translation engine ;(function($B){ var js,$pos,res,$op /* Utility functions ================= */ // Keys of an object var keys = $B.keys = function(obj){ var res = [], pos=0 for(var attr in obj){res[pos++]=attr} res.sort() return res } // Return a clone of an object var clone = $B.clone = function(obj){ var res = {} for(var attr in obj){res[attr]=obj[attr]} return res } // Last element in a list $B.last = function(table){return table[table.length-1]} // Convert a list to an object indexed with list values $B.list2obj = function(list, value){ var res = {}, i = list.length if(value===undefined){value=true} while(i-->0){res[list[i]]=value} return res } /* Internal variables ================== */ // Mapping between operators and special Python method names var $operators = { "//=":"ifloordiv",">>=":"irshift","<<=":"ilshift", "**=":"ipow","**":"pow","//":"floordiv","<<":"lshift",">>":"rshift", "+=":"iadd","-=":"isub","*=":"imul","/=":"itruediv", "%=":"imod","&=":"iand","|=":"ior","^=":"ixor", "+":"add","-":"sub","*":"mul", "/":"truediv","%":"mod","&":"and","|":"or","~":"invert", "^":"xor","<":"lt",">":"gt", "<=":"le",">=":"ge","==":"eq","!=":"ne", "or":"or","and":"and", "in":"in", "not": "not", "is":"is","not_in":"not_in","is_not":"is_not" // fake } // Mapping between augmented assignment operators and method names var $augmented_assigns = { "//=":"ifloordiv",">>=":"irshift","<<=":"ilshift", "**=":"ipow","+=":"iadd","-=":"isub","*=":"imul","/=":"itruediv", "%=":"imod", "&=":"iand","|=":"ior","^=":"ixor" } // Names that can't be assigned to var noassign = $B.list2obj(['True','False','None','__debug__']) // Operators weight for precedence var $op_order = [['or'],['and'],['not'], ['in','not_in'], ['<','<=','>','>=','!=','==','is','is_not'], ['|'], ['^'], ['&'], ['>>','<<'], ['+'], ['-'], ['*','/','//','%'], ['unary_neg','unary_inv','unary_pos'], ['**'] ] var $op_weight={} var $weight=1 for (var $i=0;$i<$op_order.length;$i++){ var _tmp=$op_order[$i] for(var $j=0;$j<_tmp.length;$j++){ $op_weight[_tmp[$j]]=$weight } $weight++ } // Variable used to generate random names used in loops var $loop_num = 0 // Magic value passed as first argument to functions in simple cases $B.func_magic = Math.random().toString(36).substr(2,8) /* Function called in case of SyntaxError ====================================== */ function $_SyntaxError(context,msg,indent){ //console.log('syntax error, context '+context,' msg ',msg) var ctx_node = context while(ctx_node.type!=='node'){ctx_node=ctx_node.parent} var tree_node = ctx_node.node, root = tree_node while(root.parent!==undefined){root=root.parent} var module = tree_node.module var line_num = tree_node.line_num if(root.line_info){ line_num = root.line_info } if(indent!==undefined){line_num++} if(indent===undefined){ if(Array.isArray(msg)){$B.$SyntaxError(module,msg[0],$pos)} if(msg==="Triple string end not found"){ // add an extra argument : used in interactive mode to // prompt for the rest of the triple-quoted string $B.$SyntaxError(module,'invalid syntax : triple string end not found',$pos, line_num) } $B.$SyntaxError(module,'invalid syntax',$pos, line_num) }else{throw $B.$IndentationError(module,msg,$pos)} } /* Class for Python abstract syntax tree ===================================== An instance is created for the whole Python program as the root of the tree For each instruction in the Python source code, an instance is created as a child of the block where it stands : the root for instructions at module level, or a function definition, a loop, a condition, etc. */ function $Node(type){ this.type = type this.children=[] this.yield_atoms = [] this.add = function(child){ // Insert as the last child this.children[this.children.length]=child child.parent = this child.module = this.module } this.insert = function(pos,child){ // Insert child at position pos this.children.splice(pos,0,child) child.parent = this child.module = this.module } this.toString = function(){return "<object 'Node'>"} this.show = function(indent){ // For debugging purposes var res = '' if(this.type==='module'){ for(var i=0;i<this.children.length;i++){ res += this.children[i].show(indent) } return res } indent = indent || 0 res += ' '.repeat(indent) res += this.context if(this.children.length>0) res += '{' res +='\n' for(var i=0;i<this.children.length;i++){ res += '['+i+'] '+this.children[i].show(indent+4) } if(this.children.length>0){ res += ' '.repeat(indent) res+='}\n' } return res } this.to_js = function(indent){ // Convert the node into a string with the translation in Javascript if(this.js!==undefined) return this.js this.res = [] var pos=0 this.unbound = [] if(this.type==='module'){ for(var i=0;i<this.children.length;i++){ this.res[pos++]=this.children[i].to_js() this.children[i].js_index = pos //this.res.length+0 } this.js = this.res.join('') return this.js } indent = indent || 0 var ctx_js = this.context.to_js() if(ctx_js){ // empty for "global x" this.res[pos++]=' '.repeat(indent) this.res[pos++]=ctx_js this.js_index = pos //this.res.length+0 if(this.children.length>0) this.res[pos++]='{' this.res[pos++]='\n' for(var i=0;i<this.children.length;i++){ this.res[pos++]=this.children[i].to_js(indent+4) this.children[i].js_index = pos //this.res.length+0 } if(this.children.length>0){ this.res[pos++]=' '.repeat(indent) this.res[pos++]='}\n' } } this.js = this.res.join('') return this.js } this.transform = function(rank){ // Apply transformations to each node recursively // Returns an offset : in case children were inserted by transform(), // we must jump to the next original node, skipping those that have // just been inserted if(this.yield_atoms.length>0){ // If the node contains 'yield' atoms, we must split the node into // several nodes // The line 'a = yield X' is transformed into 4 lines : // $yield_value0 = X // yield $yield_value0 // $yield_value0 = <value sent to generator > or None // a = $yield_value // remove original line this.parent.children.splice(rank,1) var offset = 0 for(var i=0;i<this.yield_atoms.length;i++){ // create a line to store the yield expression in a // temporary variable var temp_node = new $Node() var js = '$yield_value'+$loop_num js += '='+(this.yield_atoms[i].to_js() || 'None') new $NodeJSCtx(temp_node,js) this.parent.insert(rank+offset, temp_node) // create a node to yield the yielded value var yield_node = new $Node() this.parent.insert(rank+offset+1, yield_node) var yield_expr = new $YieldCtx(new $NodeCtx(yield_node)) new $StringCtx(yield_expr,'$yield_value'+$loop_num) // create a node to set the yielded value to the last // value sent to the generator, if any var set_yield = new $Node() set_yield.is_set_yield_value=true // the JS code will be set in py_utils.$B.make_node js = $loop_num new $NodeJSCtx(set_yield,js) this.parent.insert(rank+offset+2, set_yield) // in the original node, replace yield atom by None this.yield_atoms[i].to_js = (function(x){ return function(){return '$yield_value'+x} })($loop_num) $loop_num++ offset += 3 } // insert the original node after the yield nodes this.parent.insert(rank+offset, this) this.yield_atoms = [] // Because new nodes were inserted in node parent, return the // offset for iteration on parent's children return offset+1 } if(this.type==='module'){ // module doc string this.doc_string = $get_docstring(this) var i=0 while(i<this.children.length){ var offset = this.children[i].transform(i) if(offset===undefined){offset=1} i += offset } }else{ var elt=this.context.tree[0], ctx_offset if(elt.transform !== undefined){ ctx_offset = elt.transform(this,rank) } var i=0 while(i<this.children.length){ var offset = this.children[i].transform(i) if(offset===undefined){offset=1} i += offset } if(ctx_offset===undefined){ctx_offset=1} return ctx_offset } } this.clone = function(){ var res = new $Node(this.type) for(var attr in this){res[attr] = this[attr]} return res } } /* Context classes =============== In the parser, for each token found in the source code, a new context is created by a call like : new_context = $transition(current_context, token_type, token_value) For each new instruction, an instance of $Node is created ; it receives an attribute "context" which is an initial, empty context. For instance, if the first token is the keyword "assert", the new_context is an instance of class $AssertCtx, in a state where it expects an expression. Most contexts have an attribute "tree", a list of the elements associated with the keyword or the syntax element (eg the arguments in a function definition). For context that need transforming the Python instruction into several Javascript instructions, a method transform(node, rank) is defined. It is called by the method transform() on the root node (the top level instance of $Node). Most contexts have a method to_js() that return the Javascript code for this context. It is called by the method to_js() of the root node. */ function $AbstractExprCtx(context,with_commas){ this.type = 'abstract_expr' // allow expression with comma-separted values, or a single value ? this.with_commas = with_commas this.parent = context this.tree = [] context.tree[context.tree.length]=this this.toString = function(){return '(abstract_expr '+with_commas+') '+this.tree} this.to_js = function(){ this.js_processed=true if(this.type==='list') return '['+$to_js(this.tree)+']' return $to_js(this.tree) } } function $AliasCtx(context){ // Class for context manager alias this.type = 'ctx_manager_alias' this.parent = context this.tree = [] context.tree[context.tree.length-1].alias = this } function $AnnotationCtx(context){ // Class for annotations, eg "def f(x:int) -> list:" this.type = 'annotation' this.parent = context this.tree = [] // annotation is stored in attribute "annotations" of parent, not "tree" context.annotation = this this.toString = function(){return '(annotation) '+this.tree} this.to_js = function(){return $to_js(this.tree)} } function $AssertCtx(context){ // Context for keyword "assert" this.type = 'assert' this.toString = function(){return '(assert) '+this.tree} this.parent = context this.tree = [] context.tree[context.tree.length]=this this.transform = function(node,rank){ if(this.tree[0].type==='list_or_tuple'){ // form "assert condition,message" var condition = this.tree[0].tree[0] var message = this.tree[0].tree[1] }else{ var condition = this.tree[0] var message = null } // transform "assert cond" into "if not cond: throw AssertionError" var new_ctx = new $ConditionCtx(node.context,'if') var not_ctx = new $NotCtx(new_ctx) not_ctx.tree = [condition] node.context = new_ctx var new_node = new $Node() var js = 'throw AssertionError("AssertionError")' if(message !== null){ js = 'throw AssertionError(str('+message.to_js()+'))' } new $NodeJSCtx(new_node,js) node.add(new_node) } } function $AssignCtx(context){ //, check_unbound){ /* Class for the assignment operator "=" context is the left operand of assignment check_unbound is used to check unbound local variables This check is done when the AssignCtx object is created, but must be disabled if a new AssignCtx object is created afterwards by method transform() */ var ctx = context while(ctx){ if(ctx.type=='assert'){$_SyntaxError(context,'invalid syntax - assign')} ctx = ctx.parent } //check_unbound = check_unbound === undefined this.type = 'assign' // replace parent by "this" in parent tree context.parent.tree.pop() //context.parent.tree.push(this) context.parent.tree[context.parent.tree.length]=this this.parent = context.parent this.tree = [context] var scope = $get_scope(this) if(context.type=='expr' && context.tree[0].type=='call'){ $_SyntaxError(context,["can't assign to function call "]) }else if(context.type=='list_or_tuple' || (context.type=='expr' && context.tree[0].type=='list_or_tuple')){ if(context.type=='expr'){context = context.tree[0]} // Bind all the ids in the list or tuple for(var name in context.ids()){ $bind(name, scope.id, scope.level) } }else if(context.type=='assign'){ for(var i=0;i<context.tree.length;i++){ var assigned = context.tree[i].tree[0] if(assigned.type=='id'){ $bind(assigned.value, scope.id, scope.level) } } }else{ var assigned = context.tree[0] if(assigned && assigned.type=='id'){ if(noassign[assigned.value]===true){ $_SyntaxError(context,["can't assign to keyword"]) } // Attribute bound of an id indicates if it is being // bound, as it is the case in the left part of an assignment assigned.bound = true if(!$B._globals[scope.id] || $B._globals[scope.id][assigned.value]===undefined){ // A value is going to be assigned to a name // After assignment the name will be bound to the current // scope // We must keep track of the list of bound names before // this assignment, because in code like // // range = range // // the right part of the assignement must be evaluated // first, and it is the builtin "range" var node = $get_node(this) node.bound_before = $B.keys($B.bound[scope.id]) $bind(assigned.value, scope.id, scope.level) } } }//if this.guess_type = function(){ if(this.tree[0].type=="expr" && this.tree[0].tree[0].type=="id"){ $set_type(scope,this.tree[0],this.tree[1]) }else if(this.tree[0].type=='assign'){ var left = this.tree[0].tree[0].tree[0] var right = this.tree[0].tree[1].tree[0] $set_type(scope, right, this.tree[1].tree[0]) this.tree[0].guess_type() }else{ //console.log('guess type', this.tree[0]) } } this.toString = function(){return '(assign) '+this.tree[0]+'='+this.tree[1]} this.transform = function(node,rank){ // rank is the rank of this line in node var scope = $get_scope(this) var left = this.tree[0], right = this.tree[1], assigned = [] while(left.type=='assign'){ assigned.push(left.tree[1]) left = left.tree[0] } if(assigned.length>0){ assigned.push(left) // replace current node by '$tempXXX = <right>' var ctx = node.context ctx.tree = [] var nleft = new $RawJSCtx(ctx, 'var $temp'+$loop_num) nleft.tree = ctx.tree nassign = new $AssignCtx(nleft) nassign.tree[1] = right // create nodes with target set to right, from left to right for(var i=0;i<assigned.length;i++){ var new_node = new $Node(), node_ctx = new $NodeCtx(new_node) node.parent.insert(rank+1,new_node) assigned[i].parent = node_ctx var assign = new $AssignCtx(assigned[i]) new $RawJSCtx(assign, '$temp'+$loop_num) } return assigned.length-1 } /* var left = this.tree[0] while(left.type==='assign'){ // chained assignment : x=y=z // transform current node to "y=z" // and add a new node "x=y" var new_node = new $Node() var node_ctx = new $NodeCtx(new_node) node_ctx.tree = [left] //node.parent.insert(rank+1,new_node) this.tree[0] = left.tree[1] left = this.tree[0] } */ var left_items = null switch(left.type) { case 'expr': if(left.tree.length>1){ left_items = left.tree } else if (left.tree[0].type==='list_or_tuple'||left.tree[0].type==='target_list'){ left_items = left.tree[0].tree }else if(left.tree[0].type=='id'){ // simple assign : set attribute "bound" for name resolution var name = left.tree[0].value // check if name in globals if($B._globals && $B._globals[scope.id] && $B._globals[scope.id][name]){ void(0) }else{ left.tree[0].bound = true } } break case 'target_list': case 'list_or_tuple': left_items = left.tree } if(left_items===null) {return} var right = this.tree[1] var right_items = null if(right.type==='list'||right.type==='tuple'|| (right.type==='expr' && right.tree.length>1)){ right_items = right.tree } if(right_items!==null){ // form x,y=a,b if(right_items.length>left_items.length){ throw Error('ValueError : too many values to unpack (expected '+left_items.length+')') }else if(right_items.length<left_items.length){ throw Error('ValueError : need more than '+right_items.length+' to unpack') } var new_nodes = [], pos=0 // replace original line by dummy line : the next one might also // be a multiple assignment var new_node = new $Node() new $NodeJSCtx(new_node,'void(0)') new_nodes[pos++]=new_node var $var='$temp'+$loop_num var new_node = new $Node() new $NodeJSCtx(new_node,'var '+$var+'=[], $pos=0') new_nodes[pos++]=new_node for(var i=0;i<right_items.length;i++){ var js = $var+'[$pos++]='+right_items[i].to_js() var new_node = new $Node() new $NodeJSCtx(new_node,js) new_nodes[pos++]=new_node } for(var i=0;i<left_items.length;i++){ var new_node = new $Node() new_node.id = $get_node(this).module var context = new $NodeCtx(new_node) // create ordinary node left_items[i].parent = context // assignment to left operand // set "check_unbound" to false var assign = new $AssignCtx(left_items[i], false) assign.tree[1] = new $JSCode($var+'['+i+']') new_nodes[pos++]=new_node } node.parent.children.splice(rank,1) // remove original line for(var i=new_nodes.length-1;i>=0;i--){ node.parent.insert(rank,new_nodes[i]) } $loop_num++ }else{ // form x,y=a // evaluate right argument (it might be a function call) var new_node = new $Node() // set attribute line_num for debugging new_node.line_num = node.line_num var js = 'var $right'+$loop_num+'=getattr' js += '(iter('+right.to_js()+'),"__next__");' new $NodeJSCtx(new_node,js) var new_nodes = [new_node], pos=1 var rlist_node = new $Node() var $var='$rlist'+$loop_num js = 'var '+$var+'=[], $pos=0;' js += 'while(1){try{'+$var+'[$pos++]=$right' js += $loop_num+'()}catch(err){break}};' new $NodeJSCtx(rlist_node, js) new_nodes[pos++]=rlist_node // If there is a packed tuple in the list of left items, store // its rank in the list var packed = null for(var i=0;i<left_items.length;i++){ var expr = left_items[i] if(expr.type=='packed' || (expr.type=='expr' && expr.tree[0].type=='packed')){ packed = i break } } // Test if there were enough values in the right part var check_node = new $Node() var min_length = left_items.length if(packed!==null){min_length--} js = 'if($rlist'+$loop_num+'.length<'+min_length+')' js += '{throw ValueError("need more than "+$rlist'+$loop_num js += '.length+" value" + ($rlist'+$loop_num+'.length>1 ?' js += ' "s" : "")+" to unpack")}' new $NodeJSCtx(check_node,js) new_nodes[pos++]=check_node // Test if there were enough variables in the left part if(packed==null){ var check_node = new $Node() var min_length = left_items.length js = 'if($rlist'+$loop_num+'.length>'+min_length+')' js += '{throw ValueError("too many values to unpack ' js += '(expected '+left_items.length+')")}' new $NodeJSCtx(check_node,js) new_nodes[pos++]=check_node } var j=0 for(var i=0;i<left_items.length;i++){ var new_node = new $Node() new_node.id = scope.id var context = new $NodeCtx(new_node) // create ordinary node left_items[i].parent = context var assign = new $AssignCtx(left_items[i], false) // assignment to left operand var js = '$rlist'+$loop_num if(packed==null || i<packed){ js += '['+i+']' }else if(i==packed){ js += '.slice('+i+',$rlist'+$loop_num+'.length-' js += (left_items.length-i-1)+')' }else{ js += '[$rlist'+$loop_num+'.length-'+(left_items.length-i)+']' } assign.tree[1] = new $JSCode(js) // right part of the assignment new_nodes[pos++]=new_node } node.parent.children.splice(rank,1) // remove original line for(var i=new_nodes.length-1;i>=0;i--){ node.parent.insert(rank,new_nodes[i]) } $loop_num++ } } this.to_js = function(){ this.js_processed=true if(this.parent.type==='call'){// like in foo(x=0) return '{$nat:"kw",name:'+this.tree[0].to_js()+',value:'+this.tree[1].to_js()+'}' } // assignment var left = this.tree[0] if(left.type==='expr') left=left.tree[0] var right = this.tree[1] if(left.type == 'attribute' || left.type== 'sub'){ // In case of an assignment to an attribute or a subscript, we // use setattr() and setitem // If the right part is a call to exec or eval, it must be // evaluated and stored in a temporary variable, before // setting the attribute to this variable // This is because the code generated for exec() or eval() // can't be inserted as the third parameter of a function var node = $get_node(this), right_js = right.to_js() var res='', rvar='', $var='$temp'+$loop_num if(right.type=='expr' && right.tree[0]!==undefined && right.tree[0].type=='call' && ('eval' == right.tree[0].func.value || 'exec' == right.tree[0].func.value)) { res += 'var '+$var+'='+right_js+';\n' rvar = $var }else if(right.type=='expr' && right.tree[0]!==undefined && right.tree[0].type=='sub'){ res += 'var '+$var+'='+right_js+';\n' rvar = $var }else{ rvar = right_js } if(left.type==='attribute'){ // assign to attribute $loop_num++ left.func = 'setattr' res += left.to_js() left.func = 'getattr' res = res.substr(0,res.length-1) // remove trailing ) return res + ','+rvar+');None;' } if(left.type==='sub'){ // assign to item var seq = left.value.to_js(), temp='$temp'+$loop_num, type if(left.value.type=='id'){ type = $get_node(this).locals[left.value.value] } $loop_num++ var res = 'var '+temp+'='+seq+'\n' if(type!=='list'){ res += 'if(Array.isArray('+temp+') && !'+temp+'.__class__){' } if(left.tree.length==1){ res += '$B.set_list_key('+temp+','+ (left.tree[0].to_js()+''||'null')+','+ right.to_js()+')' }else if(left.tree.length==2){ res += '$B.set_list_slice('+temp+','+ (left.tree[0].to_js()+''||'null')+','+ (left.tree[1].to_js()+''||'null')+','+ right.to_js()+')' }else if(left.tree.length==3){ res += '$B.set_list_slice_step('+temp+','+ (left.tree[0].to_js()+''||'null')+','+ (left.tree[1].to_js()+''||'null')+','+ (left.tree[2].to_js()+''||'null')+','+ right.to_js()+')' } if(type=='list'){return res} res += '\n}else{' if(left.tree.length==1){ res += '$B.$setitem('+left.value.to_js() res += ','+left.tree[0].to_js()+','+right_js+')};None;' }else{ left.func = 'setitem' // just for to_js() res += left.to_js() res = res.substr(0,res.length-1) // remove trailing ) left.func = 'getitem' // restore default function res += ','+right_js+')};None;' } return res } } return left.to_js()+'='+right.to_js() } } function $AttrCtx(context){ // Class for object attributes (eg x in obj.x) this.type = 'attribute' this.value = context.tree[0] this.parent = context context.tree.pop() context.tree[context.tree.length]=this this.tree = [] this.func = 'getattr' // becomes setattr for an assignment this.toString = function(){return '(attr) '+this.value+'.'+this.name} this.to_js = function(){ this.js_processed=true return this.func+'('+this.value.to_js()+',"'+this.name+'")' } } function $AugmentedAssignCtx(context, op){ // Class for augmented assignments such as "+=" this.type = 'augm_assign' this.parent = context.parent context.parent.tree.pop() //context.parent.tree.push(this) context.parent.tree[context.parent.tree.length]=this this.op = op this.tree = [context] var scope = this.scope = $get_scope(this) if(context.type=='expr' && context.tree[0].type=='id'){ var name = context.tree[0].value if(noassign[name]===true){ $_SyntaxError(context,["can't assign to keyword"]) }else if((scope.ntype=='def'||scope.ntype=='generator') && $B.bound[scope.id][name]===undefined){ if(scope.globals===undefined || scope.globals.indexOf(name)==-1){ // Augmented assign to a variable not yet defined in // local scope : set attribute "unbound" to the id. If not defined // in the rest of the block this will raise an UnboundLocalError context.tree[0].unbound = true } } } // Store the names already bound $get_node(this).bound_before = $B.keys($B.bound[scope.id]) this.module = scope.module this.toString = function(){return '(augm assign) '+this.tree} this.transform = function(node,rank){ var func = '__'+$operators[op]+'__' var offset=0, parent=node.parent // remove current node var line_num = node.line_num, lnum_set = false parent.children.splice(rank,1) var left_is_id = (this.tree[0].type=='expr' && this.tree[0].tree[0].type=='id') if(left_is_id){ // Set attribute "augm_assign" of $IdCtx instance, so that // the id will not be resolved with $B.$check_undef() this.tree[0].tree[0].augm_assign = true // If left part is an id we must check that it is defined, otherwise // raise NameError // Example : // // if False: // a = 0 // a += 1 // For performance reasons, this is only implemented in debug mode if($B.debug>0){ var check_node = $NodeJS('if('+this.tree[0].to_js()+ '===undefined){throw NameError("name \''+ this.tree[0].tree[0].value+'\' is not defined")}') node.parent.insert(rank, check_node) offset++ } var left_id = this.tree[0].tree[0].value, was_bound = $B.bound[this.scope.id][left_id]!==undefined, left_id_unbound = this.tree[0].tree[0].unbound } var right_is_int = (this.tree[1].type=='expr' && this.tree[1].tree[0].type=='int') var right = right_is_int ? this.tree[1].tree[0].to_js() : '$temp' if(!right_is_int){ // Create temporary variable var new_node = new $Node() new_node.line_num = line_num lnum_set = true new $NodeJSCtx(new_node,'var $temp,$left;') parent.insert(rank,new_node) offset++ // replace current node by "$temp = <placeholder>" // at the end of $augmented_assign, control will be // passed to the <placeholder> expression var new_node = new $Node() new_node.id = this.scope.id var new_ctx = new $NodeCtx(new_node) var new_expr = new $ExprCtx(new_ctx,'js',false) // The id must be a "raw_js", otherwise if scope is a class, // it would create a class attribute "$class.$temp" var _id = new $RawJSCtx(new_expr,'$temp') var assign = new $AssignCtx(new_expr) assign.tree[1] = this.tree[1] _id.parent = assign parent.insert(rank+offset, new_node) offset++ } var prefix = '', in_class = false switch(op) { case '+=': case '-=': case '*=': case '/=': if(left_is_id){ var scope = this.scope, local_ns = '$local_'+scope.id.replace(/\./g,'_'), global_ns = '$local_'+scope.module.replace(/\./g,'_'), prefix switch(scope.ntype) { case 'module': prefix = global_ns break case 'def': case 'generator': if(scope.globals && scope.globals.indexOf(context.tree[0].value)>-1){ prefix = global_ns }else{prefix='$locals'} break; case 'class': var new_node = new $Node() if(!lnum_set){new_node.line_num=line_num;lnum_set=true} new $NodeJSCtx(new_node,'var $left='+context.to_js()) parent.insert(rank+offset, new_node) in_class = true offset++ } } } var left = context.tree[0].to_js() // Generate code to use Javascript operator if the object type is // str, int or float // If the left part is a name not defined in the souce code, which is // the case with "from A import *", the name is replaced by a // function call "$B.$search(name, globals_name)" // Since augmented assignement can't be applied to a function call // the shortcut will not be used in this case prefix = prefix && !context.tree[0].unknown_binding && left_id_unbound===undefined var op1 = op.charAt(0) if(prefix){ var left1 = in_class ? '$left' : left var new_node = new $Node() if(!lnum_set){new_node.line_num=line_num;lnum_set=true} js = right_is_int ? 'if(' : 'if(typeof $temp.valueOf()=="number" && ' js += left1+'.constructor===Number' // If both arguments are integers, we must check that the result // is a safe integer js += '&& '+left+op1+right+'>$B.min_int && '+left+op1+right+ '< $B.max_int){' js += right_is_int ? '(' : '(typeof $temp=="number" && ' js += 'typeof '+left1+'=="number") ? ' js += left+op+right js += ' : ('+left1+'.constructor===Number ? ' // result is a float js += left+'=float('+left+op1 js += right_is_int ? right : right+'.valueOf()' js += ') : '+left + op js += right_is_int ? right : right+'.valueOf()' js += ')}' new $NodeJSCtx(new_node,js) parent.insert(rank+offset,new_node) offset++ } var aaops = {'+=':'add','-=':'sub','*=':'mul'} if(context.tree[0].type=='sub' && ( '+=' == op || '-=' == op || '*=' == op) && //['+=','-=','*='].indexOf(op)>-1 && context.tree[0].tree.length==1){ var js1 = '$B.augm_item_'+aaops[op]+'(' js1 += context.tree[0].value.to_js() js1 += ','+context.tree[0].tree[0].to_js()+',' js1 += right+');None;' var new_node = new $Node() if(!lnum_set){new_node.line_num=line_num;lnum_set=true} new $NodeJSCtx(new_node,js1) parent.insert(rank+offset, new_node) offset++ return } // insert node 'if(!hasattr(foo,"__iadd__")) var new_node = new $Node() if(!lnum_set){new_node.line_num=line_num;lnum_set=true} var js = '' if(prefix){js += 'else '} js += 'if(!hasattr('+context.to_js()+',"'+func+'"))' new $NodeJSCtx(new_node,js) parent.insert(rank+offset,new_node) offset ++ // create node for "foo = foo + bar" var aa1 = new $Node() aa1.id = this.scope.id var ctx1 = new $NodeCtx(aa1) var expr1 = new $ExprCtx(ctx1,'clone',false) if(left_id_unbound){ new $RawJSCtx(expr1, '$locals["'+left_id+'"]') }else{ expr1.tree = context.tree for(var i=0;i<expr1.tree.length;i++){ expr1.tree[i].parent = expr1 } } var assign1 = new $AssignCtx(expr1) var new_op = new $OpCtx(expr1,op.substr(0,op.length-1)) new_op.parent = assign1 new $RawJSCtx(new_op,right) assign1.tree.push(new_op) expr1.parent.tree.pop() expr1.parent.tree.push(assign1) new_node.add(aa1) // create node for "else" var aa2 = new $Node() new $NodeJSCtx(aa2,'else') parent.insert(rank+offset,aa2) // create node for "foo.__iadd__(bar)" var aa3 = new $Node() var js3 = 'getattr('+context.to_js()+',"'+func+'")('+right+')' new $NodeJSCtx(aa3,js3) aa2.add(aa3) // Augmented assignment doesn't bind names ; if the variable name has // been bound in the code above (by a call to $AssignCtx), remove it if(left_is_id && !was_bound && !this.scope.blurred){ $B.bound[this.scope.id][left_id] = undefined } return offset } this.to_js = function(){return ''} } function $BodyCtx(context){ // inline body for def, class, if, elif, else, try... // creates a new node, child of context node var ctx_node = context.parent while(ctx_node.type!=='node'){ctx_node=ctx_node.parent} var tree_node = ctx_node.node var body_node = new $Node() body_node.line_num = tree_node.line_num tree_node.insert(0,body_node) return new $NodeCtx(body_node) } function $BreakCtx(context){ // Used for the keyword "break" // A flag is associated to the enclosing "for" or "while" loop // If the loop exits with a break, this flag is set to true // so that the "else" clause of the loop, if present, is executed this.type = 'break' this.toString = function(){return 'break '} this.parent = context context.tree[context.tree.length]=this // get loop context var ctx_node = context while(ctx_node.type!=='node'){ctx_node=ctx_node.parent} var tree_node = ctx_node.node var loop_node = tree_node.parent var break_flag=false while(1){ if(loop_node.type==='module'){ // "break" is not inside a loop $_SyntaxError(context,'break outside of a loop') }else{ var ctx = loop_node.context.tree[0] //var _ctype=ctx.type if(ctx.type==='condition' && ctx.token==='while'){ this.loop_ctx = ctx ctx.has_break = true break } switch(ctx.type) { case 'for': //if(_ctype==='for' || (_ctype==='condition' && ctx.token==='while')){ this.loop_ctx = ctx ctx.has_break = true break_flag=true break case 'def': case 'generator': case 'class': //}else if('def'==_ctype || 'generator'==_ctype || 'class'==_ctype){ // "break" must not be inside a def or class, even if they are // enclosed in a loop $_SyntaxError(context,'break outside of a loop') default: //}else{ loop_node=loop_node.parent }//switch if (break_flag) break }//if }//while this.to_js = function(){ this.js_processed=true var scope = $get_scope(this) var res = ';$locals_'+scope.id.replace(/\./g,'_')+ '["$no_break'+this.loop_ctx.loop_num+'"]=false' if(this.loop_ctx.type!='asyncfor'){ res += ';break' }else{ res += ';throw StopIteration('+this.loop_ctx.loop_num+')' } return res } } function $CallArgCtx(context){ // Base class for arguments in a function call this.type = 'call_arg' this.toString = function(){return 'call_arg '+this.tree} this.parent = context this.start = $pos this.tree = [] context.tree[context.tree.length]=this this.expect='id' this.to_js = function(){ this.js_processed=true return $to_js(this.tree) } } function $CallCtx(context){ // Context of a call on a callable, ie what is inside the parenthesis // in "callable(...)" this.type = 'call' this.func = context.tree[0] if(this.func!==undefined){ // undefined for lambda this.func.parent = this } this.parent = context if(context.type!='class'){ context.tree.pop() context.tree[context.tree.length]=this }else{ // class parameters context.args = this } this.expect = 'id' this.tree = [] this.start = $pos this.toString = function(){return '(call) '+this.func+'('+this.tree+')'} this.to_js = function(){ this.js_processed=true if(this.tree.length>0){ if(this.tree[this.tree.length-1].tree.length==0){ // from "foo(x,)" this.tree.pop() } } var func_js = this.func.to_js() if(this.func!==undefined) { switch(this.func.value) { case 'classmethod': return 'classmethod('+$to_js(this.tree)+')' case '$$super': if(this.tree.length==0){ // super() called with no argument : if inside a class, add the // class parent as first argument var scope = $get_scope(this) if(scope.ntype=='def' || scope.ntype=='generator'){ var def_scope = $get_scope(scope.context.tree[0]) if(def_scope.ntype=='class'){ new $IdCtx(this,def_scope.context.tree[0].name) } } } if(this.tree.length==1){ // second argument omitted : add the instance var scope = $get_scope(this) if(scope.ntype=='def' || scope.ntype=='generator'){ var args = scope.context.tree[0].args if(args.length>0){ new $IdCtx(this,args[0]) } } } break default: if(this.func.type=='unary'){ // form " -(x+2) " switch(this.func.op) { case '+': return 'getattr('+$to_js(this.tree)+',"__pos__")()' case '-': return 'getattr('+$to_js(this.tree)+',"__neg__")()' case '~': return 'getattr('+$to_js(this.tree)+',"__invert__")()' }//switch }//if }//switch var _block=false if ($B.async_enabled) { var scope = $get_scope(this.func) if ($B.block[scope.id] === undefined) { //console.log('block for ' + scope.id + ' is undefined') } else if ($B.block[scope.id][this.func.value]) _block=true } // build positional arguments list and keyword arguments object var pos_args = [], kw_args = [], star_args = null, dstar_args = null for(var i=0;i<this.tree.length;i++){ var arg = this.tree[i], type switch(arg.type){ case 'star_arg': star_args = arg.tree[0].tree[0].to_js() break case 'double_star_arg': dstar_args = arg.tree[0].tree[0].to_js() break case 'id': pos_args.push(arg.to_js()) break default: if(arg.tree[0]===undefined){console.log('bizarre', arg)} else{type=arg.tree[0].type} //console.log(this.func.value+' pas de tree pour arg '+arg)} switch(type){ case 'expr': pos_args.push(arg.to_js()) break case 'kwarg': kw_args.push(arg.tree[0].tree[0].value+':'+arg.tree[0].tree[1].to_js()) break case 'list_or_tuple': case 'op': pos_args.push(arg.to_js()) break case 'star_arg': star_args = arg.tree[0].tree[0].to_js() break case 'double_star_arg': dstar_args = arg.tree[0].tree[0].to_js() break default: pos_args.push(arg.to_js()) break } break } } var args_str = pos_args.join(', ') if(star_args){ args_str = '$B.extend_list('+args_str if(pos_args.length>0){args_str += ','} args_str += '_b_.list('+star_args+'))' } if(this.func.value=="fghjk"){ console.log('fghjk') var kw_args_str = '{'+kw_args.join(', ')+'}' if(dstar_args){ kw_args_str = '$B.extend("'+this.func.value+'",'+kw_args_str kw_args_str += ','+dstar_args+')' }else if(kw_args_str=='{}'){ kw_args_str = '' } var res = 'getattr('+func_js+',"__call__")(['+args_str+']' if(kw_args_str.length>0){res += ', '+kw_args_str} return res + ')' } var kw_args_str = '{'+kw_args.join(', ')+'}' if(dstar_args){ kw_args_str = '{$nat:"kw",kw:$B.extend("'+this.func.value+'",'+kw_args_str kw_args_str += ','+dstar_args+')}' }else if(kw_args_str!=='{}'){ kw_args_str = '{$nat:"kw",kw:'+kw_args_str+'}' }else{ kw_args_str = '' } if(star_args && kw_args_str){ args_str += '.concat(['+kw_args_str+'])' }else{ if(args_str && kw_args_str){args_str += ','+kw_args_str} else if(!args_str){args_str=kw_args_str} } if(star_args){ // If there are star args, we use an internal function // $B.extend_list to produce the list of positional // arguments. In this case the function must be called // with apply args_str = '.apply(null,'+args_str+')' }else{ args_str = '('+args_str+')' } if($B.debug>0){ // On debug mode, always use getattr(func,"__call__") to manage // the call stack and get correct error messages // somehow we need to loop up through the context parents // until we reach the root, or until we reach a node // that has not been processed yet (js_processed=false) // we then do a to_js (setting each js_processed to true) // from this node until we reach the current node being processed. // Take output from to_js and append to execution_object. var res = 'getattr('+func_js+',"__call__")' return res+args_str } if(this.tree.length>-1){ if(this.func.type=='id'){ if(this.func.is_builtin){ // simplify code for built-in functions if($B.builtin_funcs[this.func.value]!==undefined){ return func_js+args_str } }else{ var bound_obj = this.func.found if(bound_obj && (bound_obj.type=='class' || bound_obj.type=='def')){ return func_js+args_str } } var res = '('+func_js+'.$is_func ? ' res += func_js+' : ' res += 'getattr('+func_js+',"__call__"))'+args_str }else{ var res = 'getattr('+func_js+',"__call__")'+args_str } return res } return 'getattr('+func_js+',"__call__")()' } } } function $ClassCtx(context){ // Class for keyword "class" this.type = 'class' this.parent = context this.tree = [] context.tree[context.tree.length]=this this.expect = 'id' this.toString = function(){return '(class) '+this.name+' '+this.tree+' args '+this.args} var scope = this.scope = $get_scope(this) this.parent.node.parent_block = scope this.parent.node.bound = {} // will store the names bound in the function this.set_name = function(name){ this.random = $B.UUID() this.name = name this.id = context.node.module+'_'+name+'_'+this.random $B.bound[this.id] = {} $B.type[this.id] = {} if ($B.async_enabled) $B.block[this.id] = {} $B.modules[this.id] = this.parent.node this.parent.node.id = this.id var parent_block = scope while(parent_block.context && parent_block.context.tree[0].type=='class'){ parent_block = parent_block.parent } while(parent_block.context && 'def' !=parent_block.context.tree[0].type && 'generator' != parent_block.context.tree[0].type){ parent_block = parent_block.parent } this.parent.node.parent_block = parent_block // bind name this.level = this.scope.level $B.bound[this.scope.id][name] = this $B.type[this.scope.id][name] = 'class' // if function is defined inside another function, add the name // to local names if(scope.is_function){ if(scope.context.tree[0].locals.indexOf(name)==-1){ scope.context.tree[0].locals.push(name) } } } this.transform = function(node,rank){ // doc string this.doc_string = $get_docstring(node) var instance_decl = new $Node() var local_ns = '$locals_'+this.id.replace(/\./g,'_') var js = ';var '+local_ns+'={}' //if($B.debug>0){js += '{$def_line:$B.line_info}'} //else{js += '{}'} js += ', $locals = '+local_ns+';' new $NodeJSCtx(instance_decl,js) node.insert(0,instance_decl) // return local namespace at the end of class definition var ret_obj = new $Node() new $NodeJSCtx(ret_obj,'return '+local_ns+';') node.insert(node.children.length,ret_obj) // close function and run it var run_func = new $Node() new $NodeJSCtx(run_func,')();') node.parent.insert(rank+1,run_func) // class constructor var scope = $get_scope(this) var name_ref = ';$locals_'+scope.id.replace(/\./g,'_') name_ref += '["'+this.name+'"]' if(this.name=="FF"){ // experimental var js = [name_ref +'=$B.$class_constructor1("'+this.name], pos=1 }else{ var js = [name_ref +'=$B.$class_constructor("'+this.name], pos=1 } js[pos++]= '",$'+this.name+'_'+this.random if(this.args!==undefined){ // class def has arguments var arg_tree = this.args.tree,args=[],kw=[] for(var i=0;i<arg_tree.length;i++){ var _tmp=arg_tree[i] if(_tmp.tree[0].type=='kwarg'){kw.push(_tmp.tree[0])} else{args.push(_tmp.to_js())} } js[pos++]=',tuple(['+args.join(',')+']),[' // add the names - needed to raise exception if a value is undefined var _re=new RegExp('"','g') var _r=[], rpos=0 for(var i=0;i<args.length;i++){ _r[rpos++]='"'+args[i].replace(_re,'\\"')+'"' } js[pos++]= _r.join(',') + ']' _r=[], rpos=0 for(var i=0;i<kw.length;i++){ var _tmp=kw[i] _r[rpos++]='["'+_tmp.tree[0].value+'",'+_tmp.tree[1].to_js()+']' } js[pos++]= ',[' + _r.join(',') + ']' }else{ // form "class foo:" js[pos++]=',tuple([]),[],[]' } js[pos++]=')' var cl_cons = new $Node() new $NodeJSCtx(cl_cons,js.join('')) rank++ node.parent.insert(rank+1,cl_cons) // add doc string rank++ var ds_node = new $Node() js = name_ref+'.$dict.__doc__=' js += (this.doc_string || 'None')+';' new $NodeJSCtx(ds_node,js) node.parent.insert(rank+1,ds_node) // add attribute __module__ rank++ js = name_ref+'.$dict.__module__=$locals_'+ $get_module(this).module.replace(/\./g, '_')+'.__name__' var mod_node = new $Node() new $NodeJSCtx(mod_node,js) node.parent.insert(rank+1,mod_node) // if class is defined at module level, add to module namespace if(scope.ntype==='module'){ var w_decl = new $Node() new $NodeJSCtx(w_decl,'$locals["'+ this.name+'"]='+this.name) } // end by None for interactive interpreter var end_node = new $Node() new $NodeJSCtx(end_node,'None;') node.parent.insert(rank+2,end_node) this.transformed = true } this.to_js = function(){ this.js_processed=true return 'var $'+this.name+'_'+this.random+'=(function()' } } function $CompIfCtx(context){ // Class for keyword "if" inside a comprehension this.type = 'comp_if' context.parent.intervals.push($pos) this.parent = context this.tree = [] context.tree[context.tree.length]=this this.toString = function(){return '(comp if) '+this.tree} this.to_js = function(){ this.js_processed=true return $to_js(this.tree) } } function $ComprehensionCtx(context){ // Class for comprehensions this.type = 'comprehension' this.parent = context this.tree = [] context.tree[context.tree.length]=this this.toString = function(){return '(comprehension) '+this.tree} this.to_js = function(){ this.js_processed=true var _i = [], pos=0 //intervals for(var j=0;j<this.tree.length;j++) _i[pos++]=this.tree[j].start return _i } } function $CompForCtx(context){ // Class for keyword "for" in a comprehension this.type = 'comp_for' context.parent.intervals.push($pos) this.parent = context this.tree = [] this.expect = 'in' context.tree[context.tree.length]=this this.toString = function(){return '(comp for) '+this.tree} this.to_js = function(){ this.js_processed=true return $to_js(this.tree) } } function $CompIterableCtx(context){ // Class for keyword "in" in a comprehension this.type = 'comp_iterable' this.parent = context this.tree = [] context.tree[context.tree.length]=this this.toString = function(){return '(comp iter) '+this.tree} this.to_js = function(){ this.js_processed=true return $to_js(this.tree) } } function $ConditionCtx(context,token){ // Class for keywords "if", "elif", "while" this.type = 'condition' this.token = token this.parent = context this.tree = [] if(token==='while'){this.loop_num=$loop_num++} context.tree[context.tree.length]=this this.toString = function(){return this.token+' '+this.tree} this.transform = function(node,rank){ var scope = $get_scope(this) if(this.token=="while"){ if(scope.ntype=='generator'){ this.parent.node.loop_start = this.loop_num } var new_node = new $Node() var js = '$locals["$no_break'+this.loop_num+'"]=true' new $NodeJSCtx(new_node,js) node.parent.insert(rank, new_node) // because a node was inserted, return 2 to avoid infinite loop return 2 } } this.to_js = function(){ this.js_processed=true var tok = this.token if(tok==='elif'){ tok='else if' } // In a "while" loop, the flag "$no_break" is initially set to false. // If the loop exits with a "break" this flag will be set to "true", // so that an optional "else" clause will not be run. var res = [tok+'(bool('], pos=1 if(tok=='while'){ // If a timeout has been set for loops by // browser.timer.set_loop_timeout(), create code to control // execution time if(__BRYTHON__.loop_timeout){ var h = '\n'+' '.repeat($get_node(this).indent), h4 = h+' '.repeat(4), num = this.loop_num, test_timeout = h+'var $time'+num+' = new Date()'+h+ 'function $test_timeout'+num+'()'+h4+ '{if((new Date())-$time'+num+'>'+ __BRYTHON__.loop_timeout*1000+ '){throw _b_.RuntimeError("script timeout")}'+ h4+'return true'+h+'}\n' res.splice(0,0,test_timeout) res.push('$test_timeout'+num+'() && ') } res.push('$locals["$no_break'+this.loop_num+'"] && ') }else if(tok=='else if'){ var line_info = $get_node(this).line_num+','+$get_scope(this).id res.push('($locals.$line_info="'+line_info+'") && ') } if(this.tree.length==1){ res.push($to_js(this.tree)+'))') }else{ // syntax "if cond : do_something" in the same line res.push(this.tree[0].to_js()+'))') if(this.tree[1].tree.length>0){ res.push('{'+this.tree[1].to_js()+'}') } } return res.join('') } } function $ContinueCtx(context){ // Class for keyword "continue" this.type = 'continue' this.parent = context context.tree[context.tree.length]=this this.toString = function(){return '(continue)'} this.to_js = function(){ this.js_processed=true return 'continue' } } function $DebuggerCtx(context){ // Class for keyword "continue" this.type = 'continue' this.parent = context context.tree[context.tree.length]=this this.toString = function(){return '(debugger)'} this.to_js = function(){ this.js_processed=true return 'debugger' } } function $DecoratorCtx(context){ // Class for decorators this.type = 'decorator' this.parent = context context.tree[context.tree.length]=this this.tree = [] this.toString = function(){return '(decorator) '+this.tree} this.transform = function(node,rank){ var func_rank=rank+1,children=node.parent.children var decorators = [this.tree] while(1){ if(func_rank>=children.length){$_SyntaxError(context,['decorator expects function'])} else if(children[func_rank].context.type=='node_js'){func_rank++} else if(children[func_rank].context.tree[0].type==='decorator'){ decorators.push(children[func_rank].context.tree[0].tree) children.splice(func_rank,1) }else{break} } // Associate a random variable name to each decorator // In a code such as // class Cl(object): // def __init__(self): // self._x = None // // @property // def x(self): // return self._x // // @x.setter // def x(self, value): // self._x = value // // we can't replace the decorated methods by something like // // def x(self): // return self._x // x = property(x) # [1] // // def x(self,value): # [2] // self._x = value // x = x.setter(x) # [3] // // because when we want to use x.setter in [3], x is no longer the one // defined in [1] : it has been reset by the function declaration in [2] // The technique used here is to replace these lines by : // // $vth93h6g = property # random variable name // def $dec001(self): # another random name // return self._x // x = $vth93h6g($dec001) // // $h3upb5s8 = x.setter // def $dec002(self, value): // self._x = value // x = $h3upb5s8($dec002) // this.dec_ids = [] var pos=0 for(var i=0;i<decorators.length;i++){ this.dec_ids[pos++]='$id'+ $B.UUID() } if ($B.async_enabled) { var _block_async_flag=false; for(var i=0;i<decorators.length;i++){ try { // decorator name var name=decorators[i][0].tree[0].value if (name == "brython_block" || name == "brython_async") _block_async_flag=true } catch (err) {console.log(i); console.log(decorators[i][0])} } } var obj = children[func_rank].context.tree[0] if(obj.type=='def'){ obj.decorated = true obj.alias = '$dec'+$B.UUID() } // add a line after decorated element var callable = children[func_rank].context var tail='' var scope = $get_scope(this) var ref = '$locals["'+obj.name+'"]' var res = ref+'=' for(var i=0;i<decorators.length;i++){ //var dec = this.dec_ids[i] res += 'getattr('+this.dec_ids[i]+',"__call__")(' tail +=')' } res += (obj.decorated ? obj.alias : ref)+tail+';' // If obj is a function or a class we must set $B.bound to 'true' // instead of "def" or "class" because the result might have an // attribute "__call__" $B.bound[scope.id][obj.name] = true var decor_node = new $Node() new $NodeJSCtx(decor_node,res) node.parent.insert(func_rank+1,decor_node) this.decorators = decorators // Pierre, I probably need some help here... // we can use brython_block and brython_async as decorators so we know // that we need to generate javascript up to this point in python code // and $append that javascript code to $B.execution_object. // if a delay is supplied (on brython_block only), use that value // as the delay value in the execution_object's setTimeout. // fix me... if ($B.async_enabled && _block_async_flag) { /* // this would be a good test to see if async (and blocking) works @brython_block def mytest(): print("10") for _i in range(10): print(_i) mytest() for _i in range(11,20): print(_i) */ if ($B.block[scope.id] === undefined) $B.block[scope.id]={} $B.block[scope.id][obj.name] = true } } this.to_js = function(){ if ($B.async_enabled) { if (this.processing !== undefined) return "" } this.js_processed=true var res = [], pos=0 for(var i=0;i<this.decorators.length;i++){ res[pos++]='var '+this.dec_ids[i]+'='+$to_js(this.decorators[i])+';' } return res.join('') } } function $DefCtx(context){ this.type = 'def' this.name = null this.parent = context this.tree = [] this.locals = [] this.yields = [] // list of nodes with "yield" context.tree[context.tree.length]=this // store id of enclosing functions this.enclosing = [] var scope = this.scope = $get_scope(this) // For functions inside classes, the parent scope is not the class body // but the block where the class is defined // // Example // // a = 9 // class A: // a = 7 // def f(self): // print(a) // // A().f() # must print 9, not 7 var parent_block = scope while(parent_block.context && parent_block.context.tree[0].type=='class'){ parent_block = parent_block.parent } while(parent_block.context && 'def' !=parent_block.context.tree[0].type && 'generator' != parent_block.context.tree[0].type){ parent_block = parent_block.parent } this.parent.node.parent_block = parent_block // this.inside_function : set if the function is defined inside another // function var pb = parent_block while(pb && pb.context){ if(pb.context.tree[0].type=='def'){ this.inside_function = true break } pb = pb.parent_block } this.module = scope.module // Arrays for arguments this.positional_list = [] this.default_list = [] this.other_args = null this.other_kw = null this.after_star = [] this.set_name = function(name){ var id_ctx = new $IdCtx(this,name) this.name = name this.id = this.scope.id+'_'+name this.id = this.id.replace(/\./g,'_') // for modules inside packages this.id += '_'+ $B.UUID() this.parent.node.id = this.id this.parent.node.module = this.module // Add to modules dictionary - used in list comprehensions $B.added = $B.added || {} $B.added[this.module] = $B.added[this.module] || {} $B.added[this.module][this.id] = true //console.log('add', this.id, 'to modules of', this.module) $B.modules[this.id] = this.parent.node $B.bound[this.id] = {} $B.type[this.id] = {} this.level = this.scope.level $B.bound[this.scope.id][name]=this try{ $B.type[this.scope.id][name]='function' }catch(err){ console.log(err, this.scope.id) } // If function is defined inside another function, add the name // to local names id_ctx.bound = true if(scope.is_function){ if(scope.context.tree[0].locals.indexOf(name)==-1){ scope.context.tree[0].locals.push(name) } } } this.toString = function(){return 'def '+this.name+'('+this.tree+')'} this.transform = function(node,rank){ // already transformed ? if(this.transformed!==undefined) return var scope = this.scope // this.inside_function : set if the function is defined inside // another function var pb = this.parent.node while(pb && pb.context){ if(pb.context.tree[0].type=='def'){ this.inside_function = true break } pb = pb.parent } // search doc string this.doc_string = $get_docstring(node) this.rank = rank // save rank if we must add generator declaration // list of names declared as "global" var fglobs = this.parent.node.globals // block indentation var indent = node.indent+16 var header = $ws(indent) // List of enclosing functions // For lambdas, test if the parent block is a function if(this.name.substr(0,15)=='lambda_'+$B.lambda_magic){ var pblock = $B.modules[scope.id].parent_block if(pblock.context && pblock.context.tree[0].type=="def"){ this.enclosing.push(pblock) } } var pnode = this.parent.node while(pnode.parent && pnode.parent.is_def_func){ this.enclosing.push(pnode.parent.parent) pnode = pnode.parent.parent } var defaults = [], apos=0, dpos=0,defs1=[],dpos1=0 this.argcount = 0 this.kwonlyargcount = 0 // number of args after a star arg this.varnames = {} this.args = [] this.__defaults__ = [] this.slots = [] var slot_list = [] var annotations = [] if(this.annotation){annotations.push('"return":'+this.annotation.to_js())} var func_args = this.tree[1].tree for(var i=0;i<func_args.length;i++){ var arg = func_args[i] this.args[apos++]=arg.name this.varnames[arg.name]=true if(arg.type==='func_arg_id'){ if(this.star_arg){this.kwonlyargcount++} else{this.argcount++} this.slots.push(arg.name+':null') slot_list.push('"'+arg.name+'"') if(arg.tree.length>0){ defaults[dpos++]='"'+arg.name+'"' defs1[dpos1++]=arg.name+':'+$to_js(arg.tree) this.__defaults__.push($to_js(arg.tree)) } }else if(arg.type=='func_star_arg'){ if(arg.op == '*'){this.star_arg = arg.name} else if(arg.op=='**'){this.kw_arg = arg.name} } if(arg.annotation){ annotations.push(arg.name+': '+arg.annotation.to_js()) } } // Flags var flags = 67 if(this.star_arg){flags |= 4} if(this.kw_arg){ flags |= 8} if(this.type=='generator'){ flags |= 32} // String to pass positional arguments var positional_str=[], positional_obj=[], pos=0 for(var i=0, _len=this.positional_list.length;i<_len;i++){ positional_str[pos]='"'+this.positional_list[i]+'"' positional_obj[pos++]=this.positional_list[i]+':null' } positional_str = positional_str.join(',') positional_obj = '{'+positional_obj.join(',')+'}' // String to pass arguments with default values var dobj = [], pos=0 for(var i=0;i<this.default_list.length;i++){ dobj[pos++]=this.default_list[i]+':null' } dobj = '{'+dobj.join(',')+'}' var nodes=[], js // Get id of global scope var global_scope = scope if(global_scope.parent_block===undefined){alert('undef '+global_scope);console.log(global_scope)} while(global_scope.parent_block.id !== '__builtins__'){ global_scope=global_scope.parent_block } var global_ns = '$locals_'+global_scope.id.replace(/\./g,'_') // Add lines of code to node children // Declare object holding local variables var local_ns = '$locals_'+this.id js = 'var '+local_ns+'={}, ' js += '$local_name="'+this.id+'",$locals='+local_ns+';' var new_node = new $Node() new_node.locals_def = true new $NodeJSCtx(new_node,js) nodes.push(new_node) // Push id in frames stack var enter_frame_node = new $Node(), enter_frame_node_rank = nodes.length var js = ';$B.frames_stack.push([$local_name, $locals,'+ '"'+global_scope.id+'", '+global_ns+']);' enter_frame_node.enter_frame = true new $NodeJSCtx(enter_frame_node,js) nodes.push(enter_frame_node) this.env = [] // Code in the worst case, uses $B.args in py_utils.js var make_args_nodes = [], func_ref = '$locals_'+scope.id.replace(/\./g,'_')+'["'+this.name+'"]' // If function is not a generator, $locals is the result of $B.args var js = this.type=='def' ? local_ns+' = $locals' : 'var $ns' js += ' = $B.args("'+this.name+'", '+ this.argcount+', {'+this.slots.join(', ')+'}, '+ '['+slot_list.join(', ')+'], arguments, ' if(defs1.length){js += '$defaults, '} else{js += '{}, '} js += this.other_args+', '+this.other_kw+');' var new_node = new $Node() new $NodeJSCtx(new_node,js) make_args_nodes.push(new_node) if(this.type=='generator'){ // Update $locals with the result of $B.args var new_node = new $Node() new $NodeJSCtx(new_node,'for(var $var in $ns){$locals[$var]=$ns[$var]};') make_args_nodes.push(new_node) } var only_positional = false if(defaults.length==0 && this.other_args===null && this.other_kw===null && this.after_star.length==0){ // If function only takes positional arguments, we can generate // a faster version of argument parsing than by calling function // $B.args only_positional = true var pos_nodes = [] if($B.debug>0 || this.positional_list.length>0){ // Test if all the arguments passed to the function // are positional, not keyword arguments // In calls, keyword arguments are passed as the last // argument, an object with attribute $nat set to "kw" nodes.push($NodeJS('var $len = arguments.length;')) var new_node = new $Node() var js = 'if($len>0 && arguments[$len-1].$nat)' new $NodeJSCtx(new_node,js) nodes.push(new_node) // If at least one argument is not "simple", fall back to // $B.args() new_node.add(make_args_nodes[0]) if(make_args_nodes.length>1){new_node.add(make_args_nodes[1])} var else_node = new $Node() new $NodeJSCtx(else_node,'else') nodes.push(else_node) } if($B.debug>0){ // If all arguments are "simple" all there is to check is that // we got the right number of arguments var pos_len = this.positional_list.length js = 'if(arguments.length!='+pos_len+')' var wrong_nb_node = new $Node() new $NodeJSCtx(wrong_nb_node,js) else_node.add(wrong_nb_node) if(pos_len>0){ // Test if missing arguments js = 'if(arguments.length<'+pos_len+')'+ '{var $missing='+pos_len+'-arguments.length;'+ 'throw TypeError("'+this.name+'() missing "+$missing+'+ '" positional argument"+($missing>1 ? "s" : "")+": "'+ '+new Array('+positional_str+').slice(arguments.length))}' new_node = new $Node() new $NodeJSCtx(new_node,js) wrong_nb_node.add(new_node) js = 'else if' }else{ js = 'if' } // Test if too many arguments js += '(arguments.length>'+pos_len+')' js += '{throw TypeError("'+this.name+'() takes '+pos_len js += ' positional argument' js += (pos_len>1 ? "s" : "") js += ' but more were given")}' new_node = new $Node() new $NodeJSCtx(new_node,js) wrong_nb_node.add(new_node) } if(this.positional_list.length>0){ if(this.type=='generator'){ for(var i=0;i<this.positional_list.length;i++){ var arg = this.positional_list[i] var new_node = new $Node() var js = '$locals["'+arg+'"]='+arg new $NodeJSCtx(new_node,js) else_node.add(new_node) } }else{ var pargs = [] for(var i=0;i<this.positional_list.length;i++){ var arg = this.positional_list[i] pargs.push(arg+':'+arg) } else_node.add($NodeJS(local_ns+'=$locals={'+pargs.join(', ')+'}')) } } }else{ nodes.push(make_args_nodes[0]) if(make_args_nodes.length>1){nodes.push(make_args_nodes[1])} } nodes.push($NodeJS('$B.frames_stack[$B.frames_stack.length-1][1] = $locals;')) for(var i=nodes.length-1;i>=0;i--){ node.children.splice(0,0,nodes[i]) } // Node that replaces the original "def" line var def_func_node = new $Node() if(only_positional){ var params = Object.keys(this.varnames).join(', ') new $NodeJSCtx(def_func_node,'return function('+params+')') }else{ new $NodeJSCtx(def_func_node,'return function()') } def_func_node.is_def_func = true def_func_node.module = this.module // Add function body to def_func_node for(var i=0;i<node.children.length;i++){ def_func_node.add(node.children[i]) } var last_instr = node.children[node.children.length-1].context.tree[0] if(last_instr.type!=='return' && this.type!='generator'){ def_func_node.add($NodeJS('return None')) } // Remove children of original node node.children = [] // Start with a line to define default values, if any // This line must be outside of the function body because default // values are set once, when the function is defined // If function has no default value, insert a no-op "None" to have // the same number of lines for subsequent transformations var default_node = new $Node() var js = ';_b_.None;' if(defs1.length>0){js = 'var $defaults = {'+defs1.join(',')+'};'} new $NodeJSCtx(default_node,js) node.insert(0,default_node) // Add the new function definition node.add(def_func_node) // Final line to run close and run the closure var ret_node = new $Node() new $NodeJSCtx(ret_node,')();') node.parent.insert(rank+1,ret_node) var offset = 2 // If function is a generator, add a line to build the generator // function, based on the original function if(this.type==='generator' && !this.declared){ var code = ['var env=[], module=$B.last($B.frames_stack)[2]', 'for(var i=$B.frames_stack.length-1; i>=0; i--){', ' var frame = $B.frames_stack[i]', ' if(frame[2]!=module){break}', ' env.push([frame[0], frame[1]])', '}', 'env.push([module, $B.last($B.frames_stack)[3]])', //'console.log("generator env", env, $B.frames_stack)' ] for(var i=0;i<code.length;i++){ node.parent.insert(rank+offset, $NodeJS(code[i])) offset++ } var sc = scope var env = [], pos=0 while(sc && sc.id!=='__builtins__'){ var sc_id = sc.id.replace(/\./g,'_') if(sc===scope){ env[pos++]='["'+sc_id+'",$locals]' }else{ env[pos++]='["'+sc_id+'",$locals_'+sc_id+']' } sc = sc.parent_block } var env_string = '['+env.join(', ')+']' js = '$B.$BRgenerator(env,"'+this.name+'", $locals_'+ scope.id.replace(/\./g, '_')+'["'+this.name+'"],"'+this.id+'")' var gen_node = new $Node() gen_node.id = this.module var ctx = new $NodeCtx(gen_node) var expr = new $ExprCtx(ctx,'id',false) var name_ctx = new $IdCtx(expr,this.name) var assign = new $AssignCtx(expr) var expr1 = new $ExprCtx(assign,'id',false) var js_ctx = new $NodeJSCtx(assign,js) expr1.tree.push(js_ctx) node.parent.insert(rank+offset,gen_node) this.declared = true offset++ } var prefix = this.tree[0].to_js() if(this.decorated){prefix=this.alias} var indent = node.indent // Create attribute $infos for the function // Adding only one attribute is much faster than adding all the // keys/values in $infos js = prefix+'.$infos = {' var name_decl = new $Node() new $NodeJSCtx(name_decl,js) node.parent.insert(rank+offset,name_decl) offset++ // Add attribute __name__ js = ' __name__:"' if(this.scope.ntype=='class'){js+=this.scope.context.tree[0].name+'.'} js += this.name+'",' var name_decl = new $Node() new $NodeJSCtx(name_decl,js) node.parent.insert(rank+offset,name_decl) offset++ // Add attribute __defaults__ var module = $get_module(this) new_node = new $Node() new $NodeJSCtx(new_node,' __defaults__ : ['+this.__defaults__.join(', ')+'],') node.parent.insert(rank+offset,new_node) offset++ // Add attribute __module__ var module = $get_module(this) new_node = new $Node() new $NodeJSCtx(new_node,' __module__ : "'+module.module+'",') node.parent.insert(rank+offset,new_node) offset++ // Add attribute __doc__ js = ' __doc__: '+(this.doc_string || 'None')+',' new_node = new $Node() new $NodeJSCtx(new_node,js) node.parent.insert(rank+offset,new_node) offset++ // Add attribute __annotations__ js = ' __annotations__: {'+annotations.join(',')+'},' new_node = new $Node() new $NodeJSCtx(new_node,js) node.parent.insert(rank+offset,new_node) offset++ for(var attr in $B.bound[this.id]){this.varnames[attr]=true} var co_varnames = [] for(var attr in this.varnames){co_varnames.push('"'+attr+'"')} // Add attribute __code__ var h = '\n'+' '.repeat(indent+8) js = ' __code__:{'+h+'__class__:$B.$CodeDict' h = ','+h js += h+'co_argcount:'+this.argcount js += h+'co_filename:$locals_'+scope.module.replace(/\./g,'_')+'["__file__"]' js += h+'co_firstlineno:'+node.line_num js += h+'co_flags:'+flags js += h+'co_kwonlyargcount:'+this.kwonlyargcount js += h+'co_name: "'+this.name+'"' js += h+'co_nlocals: '+co_varnames.length js += h+'co_varnames: ['+co_varnames.join(', ')+']' js += '}\n};' // End with None for interactive interpreter js += 'None;' new_node = new $Node() new $NodeJSCtx(new_node,js) node.parent.insert(rank+offset, new_node) /* var _block=false if ($B.async_enabled) { //earney if ($B.block[scope.id] && $B.block[scope.id][this.name]) { //earney var js="@@;$B.execution_object.$append($jscode, 10); " js+="$B.execution_object.$execute_next_segment(); " js+="$jscode=@@" var new_node = new $Node() new $NodeJSCtx(new_node,js) nodes.push(new_node) } } */ // wrap everything in a try/finally to be sure to exit from frame if(this.type=='def'){ var parent = enter_frame_node.parent for(var pos=0;pos<parent.children.length && parent.children[pos]!==enter_frame_node;pos++){} var try_node = new $Node(), children = parent.children.slice(pos+1, parent.children.length), ctx = new $NodeCtx(try_node) parent.insert(pos+1, try_node) new $TryCtx(ctx) for(var i=0;i<children.length;i++){ try_node.add(children[i]) } parent.children.splice(pos+2,parent.children.length) var finally_node = new $Node(), ctx = new $NodeCtx(finally_node) new $SingleKwCtx(ctx, 'finally') finally_node.add($NodeJS('$B.frames_stack.pop()')) parent.add(finally_node) } this.transformed = true return offset } this.to_js = function(func_name){ this.js_processed=true func_name = func_name || this.tree[0].to_js() if(this.decorated){func_name='var '+this.alias} return func_name+'=(function()' } } function $DelCtx(context){ // Class for keyword "del" this.type = 'del' this.parent = context context.tree[context.tree.length]=this this.tree = [] this.toString = function(){return 'del '+this.tree} this.to_js = function(){ this.js_processed=true if(this.tree[0].type=='list_or_tuple'){ // Syntax "del a, b, c" var res = [], pos=0 for(var i=0;i<this.tree[0].tree.length;i++){ var subdel = new $DelCtx(context) // this adds an element to context.tree subdel.tree = [this.tree[0].tree[i]] res[pos++]=subdel.to_js() context.tree.pop() // remove the element from context.tree } this.tree = [] return res.join(';') }else{ var expr = this.tree[0].tree[0] var scope = $get_scope(this) switch(expr.type) { case 'id': return 'delete '+expr.to_js()+';' case 'list_or_tuple': var res = [], pos=0 for(var i=0;i<expr.tree.length;i++){ res[pos++]='delete '+expr.tree[i].to_js() } return res.join(';') case 'sub': // Delete an item in a list : "del a[x]" expr.func = 'delitem' js = expr.to_js() expr.func = 'getitem' return js case 'op': $_SyntaxError(this,["can't delete operator"]) case 'call': $_SyntaxError(this,["can't delete function call"]) case 'attribute': return 'delattr('+expr.value.to_js()+',"'+expr.name+'")' default: $_SyntaxError(this,["can't delete "+expr.type]) } } } } function $DictOrSetCtx(context){ // Context for literal dictionaries or sets // Rhe real type (dist or set) is set inside $transition // as the attribute 'real' this.type = 'dict_or_set' this.real = 'dict_or_set' this.expect = 'id' this.closed = false this.start = $pos this.parent = context this.tree = [] context.tree[context.tree.length]=this this.toString = function(){ switch(this.real) { case 'dict': return '(dict) {'+this.items+'}' case 'set': return '(set) {'+this.tree+'}' } return '(dict_or_set) {'+this.tree+'}' } this.to_js = function(){ this.js_processed=true switch(this.real) { case 'dict': var res = [], pos=0 for(var i=0;i<this.items.length;i+=2){ res[pos++]='['+this.items[i].to_js()+','+this.items[i+1].to_js()+']' } return 'dict(['+res.join(',')+'])'+$to_js(this.tree) case 'set_comp': return 'set('+$to_js(this.items)+')'+$to_js(this.tree) case 'dict_comp': return 'dict('+$to_js(this.items)+')'+$to_js(this.tree) } return 'set(['+$to_js(this.items)+'])'+$to_js(this.tree) } } function $DoubleStarArgCtx(context){ // Class for syntax "**kw" in a call this.type = 'double_star_arg' this.parent = context this.tree = [] context.tree[context.tree.length]=this this.toString = function(){return '**'+this.tree} this.to_js = function(){ this.js_processed=true return '{$nat:"pdict",arg:'+$to_js(this.tree)+'}' } } function $EllipsisCtx(context){ // Class for "..." this.type = 'ellipsis' this.parent = context this.nbdots = 1 context.tree[context.tree.length]=this this.toString = function(){return 'ellipsis'} this.to_js = function(){ this.js_processed=true return '$B.builtins["Ellipsis"]' } } function $ExceptCtx(context){ // Class for keyword "except" this.type = 'except' this.parent = context context.tree[context.tree.length]=this this.tree = [] this.expect = 'id' this.scope = $get_scope(this) this.toString = function(){return '(except) '} this.set_alias = function(alias){ this.tree[0].alias = alias $B.bound[this.scope.id][alias] = {level: this.scope.level} try{ $B.type[this.scope.id][alias] = 'exception' }catch(err){ console.log(err,this.scope.id) } } this.to_js = function(){ // in method "transform" of $TryCtx instances, related // $ExceptCtx instances receive an attribute __name__ this.js_processed=true switch(this.tree.length) { case 0: return 'else' case 1: if(this.tree[0].name==='Exception') return 'else if(1)' } var res=[], pos=0 for(var i=0;i<this.tree.length;i++){ res[pos++]=this.tree[i].to_js() } var lnum = '' if($B.debug>0){ lnum = '($locals.$line_info="'+$get_node(this).line_num+','+ this.scope.id+'") && ' } return 'else if('+lnum+'$B.is_exc('+this.error_name+',['+res.join(',')+']))' } } function $ExprCtx(context,name,with_commas){ // Base class for expressions this.type = 'expr' this.name = name // allow expression with comma-separted values, or a single value ? this.with_commas = with_commas this.expect = ',' // can be 'expr' or ',' this.parent = context this.tree = [] context.tree[context.tree.length]=this this.toString = function(){return '(expr '+with_commas+') '+this.tree} this.to_js = function(arg){ this.js_processed=true if(this.type==='list') return '['+$to_js(this.tree)+']' if(this.tree.length===1) return this.tree[0].to_js(arg) return 'tuple('+$to_js(this.tree)+')' } } function $ExprNot(context){ // Class used temporarily for 'x not', only accepts 'in' as next token // Never remains in the final tree, so there is no need to define to_js() this.type = 'expr_not' this.parent = context this.tree = [] context.tree[context.tree.length]=this this.toString = function(){return '(expr_not)'} } function $FloatCtx(context,value){ // Class for literal floats this.type = 'float' this.value = value this.toString = function(){return 'float '+this.value} this.parent = context this.tree = [] context.tree[context.tree.length]=this this.to_js = function(){ this.js_processed=true return 'float('+this.value+')' } } function $ForExpr(context){ // Class for keyword "for" outside of comprehensions this.type = 'for' this.parent = context this.tree = [] context.tree[context.tree.length]=this this.loop_num = $loop_num this.module = $get_scope(this).module $loop_num++ this.toString = function(){return '(for) '+this.tree} this.transform = function(node,rank){ var scope = $get_scope(this), mod_name = scope.module, target = this.tree[0], target_is_1_tuple = target.tree.length==1 && target.expect == 'id', iterable = this.tree[1], num = this.loop_num, local_ns = '$locals_'+scope.id.replace(/\./g,'_'), h = '\n'+' '.repeat(node.indent+4) if(__BRYTHON__.loop_timeout){ // If the option "loop_timeout" has been set by // browser.timer.set_loop_timeout, create code to initialise // the timer, and the function to test at each iteration var test_timeout = 'var $time'+num+' = new Date()'+h+ 'function $test_timeout'+num+'(){if((new Date())-$time'+ num+'>'+__BRYTHON__.loop_timeout*1000+ '){throw _b_.RuntimeError("script timeout")}'+h+'return true}' } // Because loops like "for x in range(...)" are very common and can be // optimised, check if the target is a call to the builtin function // "range" var $range = false if(target.tree.length==1 && target.expct != 'id' && iterable.type=='expr' && iterable.tree[0].type=='expr' && iterable.tree[0].tree[0].type=='call'){ var call = iterable.tree[0].tree[0] if(call.func.type=='id'){ var func_name = call.func.value if(func_name=='range' && call.tree.length<3){ $range = call } } } // nodes that will be inserted at the position of the original "for" loop var new_nodes = [], pos=0 // save original children (loop body) var children = node.children var offset = 1 if($range && scope.ntype!='generator'){ if(this.has_break){ // If there is a "break" in the loop, add a boolean // used if there is an "else" clause and in generators new_node = new $Node() new $NodeJSCtx(new_node,local_ns+'["$no_break'+num+'"]=true') new_nodes[pos++]=new_node } var range_is_builtin = false if(!scope.blurred){ var _scope = $get_scope(this), found=[], fpos=0 while(1){ if($B.bound[_scope.id]['range']){found[fpos++]=_scope.id} if(_scope.parent_block){_scope=_scope.parent_block} else{break} } range_is_builtin = found.length==1 && found[0]=="__builtins__" if(found==['__builtins__']){range_is_builtin = true} } // Line to test if the callable "range" is the built-in "range" var test_range_node = new $Node() if(range_is_builtin){ new $NodeJSCtx(test_range_node,'if(1)') }else{ new $NodeJSCtx(test_range_node, 'if('+call.func.to_js()+'===$B.builtins.range)') } new_nodes[pos++]=test_range_node // Build the block with the Javascript "for" loop var idt = target.to_js() if($range.tree.length==1){ var start=0,stop=$range.tree[0].to_js() }else{ var start=$range.tree[0].to_js(),stop=$range.tree[1].to_js() } var js = idt+'='+start+';'+h+'var $stop_'+num +'=$B.int_or_bool('+ stop+'),'+h+ ' $next'+num+'= '+idt+','+h+ ' $safe'+num+'= typeof $next'+num+'=="number" && typeof '+ '$stop_'+num+'=="number";'+h if(__BRYTHON__.loop_timeout){ js += test_timeout+h+'while($test_timeout'+num+'())' }else{ js += 'while(true)' } var for_node = new $Node() new $NodeJSCtx(for_node,js) for_node.add($NodeJS('if($safe'+num+' && $next'+num+'>= $stop_'+ num+'){break}')) for_node.add($NodeJS('else if(!$safe'+num+ ' && $B.ge($next'+num+', $stop_'+num+ ')){break}')) for_node.add($NodeJS(idt+' = $next'+num)) for_node.add($NodeJS('if($safe'+num+'){$next'+num+'+=1'+'}')) for_node.add($NodeJS('else{$next'+num+'=$B.add($next'+num+',1)}')) // Add the loop body for(var i=0;i<children.length;i++){ for_node.add(children[i].clone()) } // Add a line to reset the line number for_node.add($NodeJS('$locals.$line_info="'+node.line_num+','+ scope.id+'"; None;')) // Check if current "for" loop is inside another "for" loop var in_loop=false if(scope.ntype=='module'){ var pnode = node.parent while(pnode){ if(pnode.for_wrapper){in_loop=true;break} pnode = pnode.parent } } // If we are at module level, and if the "for" loop is not already // in a wrapper function, wrap it in a function to increase // performance if(scope.ntype=='module' && !in_loop){ var func_node = new $Node() func_node.for_wrapper = true js = 'function $f'+num+'(' if(this.has_break){js += '$no_break'+num} js += ')' new $NodeJSCtx(func_node,js) // the function is added to the test_range_node test_range_node.add(func_node) // Add the "for" loop func_node.add(for_node) // Return break flag if(this.has_break){ new_node = new $Node() new $NodeJSCtx(new_node,'return $no_break'+num) func_node.add(new_node) } // Line to call the function var end_func_node = new $Node() new $NodeJSCtx(end_func_node,'var $res'+num+'=$f'+num+'();') test_range_node.add(end_func_node) if(this.has_break){ var no_break = new $Node() new $NodeJSCtx(no_break,'$no_break'+num+'=$res'+num) test_range_node.add(no_break) } }else{ // If the loop is already inside a function, don't // wrap it test_range_node.add(for_node) } if(range_is_builtin){ node.parent.children.splice(rank,1) var k = 0 if(this.has_break){ node.parent.insert(rank, new_nodes[0]) k++ } for(var i=new_nodes[k].children.length-1;i>=0;i--){ node.parent.insert(rank+k, new_nodes[k].children[i]) } node.parent.children[rank].line_num = node.line_num node.children = [] return 0 } // Add code in case the callable "range" is *not* the // built-in function var else_node = new $Node() new $NodeJSCtx(else_node,'else') new_nodes[pos++]=else_node // Add lines at module level, after the original "for" loop for(var i=new_nodes.length-1;i>=0;i--){ node.parent.insert(rank+1,new_nodes[i]) } this.test_range = true new_nodes = [], pos=0 } // Line to declare the function that produces the next item from // the iterable var new_node = new $Node() new_node.line_num = $get_node(this).line_num var js = '$locals["$next'+num+'"]' js += '=getattr(iter('+iterable.to_js()+'),"__next__");\n' new $NodeJSCtx(new_node,js) new_nodes[pos++]=new_node if(this.has_break){ // If there is a "break" in the loop, add a boolean // used if there is an "else" clause and in generators new_node = new $Node() new $NodeJSCtx(new_node,local_ns+'["$no_break'+num+'"]=true;') new_nodes[pos++]=new_node } var while_node = new $Node() if(__BRYTHON__.loop_timeout){ js = test_timeout+h if(this.has_break){js += 'while($test_timeout'+num+'() && '+ local_ns+'["$no_break'+num+'"])'} else{js += 'while($test_timeout'+num+'())'} }else{ if(this.has_break){js = 'while('+local_ns+'["$no_break'+num+'"])'} else{js='while(1)'} } new $NodeJSCtx(while_node,js) while_node.context.loop_num = num // used for "else" clauses while_node.context.type = 'for' // used in $add_line_num while_node.line_num = node.line_num if(scope.ntype=='generator'){ // used in generators to signal a loop start while_node.loop_start = num } new_nodes[pos++]=while_node node.parent.children.splice(rank,1) if(this.test_range){ for(var i=new_nodes.length-1;i>=0;i--){ else_node.insert(0,new_nodes[i]) } }else{ for(var i=new_nodes.length-1;i>=0;i--){ node.parent.insert(rank,new_nodes[i]) offset += new_nodes.length } } var try_node = new $Node() new $NodeJSCtx(try_node,'try') while_node.add(try_node) var iter_node = new $Node() // Parent of iter_node must be the same as current node, otherwise // targets are bound in global scope iter_node.parent = $get_node(this).parent iter_node.id = this.module var context = new $NodeCtx(iter_node) // create ordinary node var target_expr = new $ExprCtx(context,'left',true) if(target_is_1_tuple){ // assign to a one-element tuple for "for x, in ..." var t = new $ListOrTupleCtx(target_expr) t.real = 'tuple' t.tree = target.tree }else{ target_expr.tree = target.tree } var assign = new $AssignCtx(target_expr) // assignment to left operand assign.tree[1] = new $JSCode('$locals["$next'+num+'"]()') try_node.add(iter_node) var catch_node = new $Node() var js = 'catch($err){if($B.is_exc($err,[StopIteration]))' js += '{delete $locals["$next'+num+'"];$B.clear_exc();break;}' js += 'else{throw($err)}}' new $NodeJSCtx(catch_node,js) while_node.add(catch_node) // set new loop children for(var i=0;i<children.length;i++){ while_node.add(children[i].clone()) } node.children = [] return 0 } this.to_js = function(){ this.js_processed=true var iterable = this.tree.pop() return 'for '+$to_js(this.tree)+' in '+iterable.to_js() } } function $FromCtx(context){ // Class for keyword "from" for imports this.type = 'from' this.parent = context this.module = '' this.names = [] this.aliases = {} context.tree[context.tree.length]=this this.expect = 'module' this.scope = $get_scope(this) this.add_name = function(name){ this.names[this.names.length]=name if(name=='*'){this.scope.blurred = true} } this.transform = function(node, rank){ if(!this.blocking){ // Experimental : for non blocking import, wrap code after the // "from" statement in a function var mod_name = this.module.replace(/\$/g,'') if(this.names[0]=='*'){ node.add($NodeJS('for(var $attr in $B.imported["'+mod_name+ '"]){if($attr.charAt(0)!=="_"){$locals[$attr]=$B.imported["'+mod_name+'"][$attr]}};')) }else{ for(var i=0;i<this.names.length;i++){ var name = this.names[i] node.add($NodeJS('$locals["'+(this.aliases[name]||name)+ '"]=$B.imported["'+mod_name+'"]["'+name+'"]')) } } for(var i=rank+1;i<node.parent.children.length;i++){ node.add(node.parent.children[i]) } node.parent.children.splice(rank+1, node.parent.children.length) node.parent.add($NodeJS(')')) } } this.bind_names = function(){ // Called at the end of the 'from' statement // Binds the names or aliases in current scope var scope = $get_scope(this) for(var i=0;i<this.names.length;i++){ var name = this.aliases[this.names[i]] || this.names[i] $B.bound[scope.id][name] = {level: scope.level} $B.type[scope.id][name] = false // impossible to know... } } this.toString = function(){ return '(from) '+this.module+' (import) '+this.names+'(as)'+this.aliases } this.to_js = function(){ this.js_processed=true var scope = $get_scope(this), mod = $get_module(this).module, res = [], pos = 0, indent = $get_node(this).indent, head= ' '.repeat(indent); var _mod = this.module.replace(/\$/g,''), package, packages=[] while(_mod.length>0){ if(_mod.charAt(0)=='.'){ if(package===undefined){ if($B.imported[mod]!==undefined){ package = $B.imported[mod].__package__ } }else{ package = $B.imported[package] } if(package===undefined){ return 'throw SystemError("Parent module \'\' not loaded,'+ ' cannot perform relative import")' }else if(package=='None'){ console.log('package is None !') }else{ packages.push(package) } _mod = _mod.substr(1) }else{ break } } if(_mod){packages.push(_mod)} this.module = packages.join('.') // FIXME : Replacement still needed ? var mod_name = this.module.replace(/\$/g,''), localns = '$locals_'+scope.id.replace(/\./g,'_'); if(this.blocking){ res[pos++] = '$B.$import("'; res[pos++] = mod_name+'",["'; res[pos++] = this.names.join('","')+'"], {'; var sep = ''; for (var attr in this.aliases) { res[pos++] = sep + '"'+attr+'": "'+this.aliases[attr]+'"'; sep = ','; } res[pos++] = '}, {}, true);'; // Add names to local namespace if(this.names[0]=='*'){ res[pos++] = '\n'+head+'for(var $attr in $B.imported["'+mod_name+ '"]){if($attr.charAt(0)!=="_"){'+ '$locals[$attr]=$B.imported["'+mod_name+'"][$attr]}};' }else{ for(var i=0;i<this.names.length;i++){ var name = this.names[i] res[pos++] = '\n'+head+'$locals["'+(this.aliases[name]||name)+ '"]=$B.imported["'+mod_name+'"]["'+name+'"];' } } res[pos++] = '\n'+head+'None;'; }else{ res[pos++] = '$B.$import_non_blocking("'+mod_name+'", function()' } if(this.names[0]=='*'){ // Set attribute to indicate that the scope has a // 'from X import *' : this will make name resolution harder :-( scope.blurred = true } return res.join(''); } } function $FuncArgs(context){ // Class for arguments in a function definition this.type = 'func_args' this.parent = context this.tree = [] this.names = [] context.tree[context.tree.length]=this this.toString = function(){return 'func args '+this.tree} this.expect = 'id' this.has_default = false this.has_star_arg = false this.has_kw_arg = false this.to_js = function(){ this.js_processed=true return $to_js(this.tree) } } function $FuncArgIdCtx(context,name){ // id in function arguments // may be followed by = for default value this.type = 'func_arg_id' this.name = name this.parent = context if(context.has_star_arg){ context.parent.after_star.push('"'+name+'"') }else{ context.parent.positional_list.push(name) } // bind name to function scope var node = $get_node(this) if($B.bound[node.id][name]){ $_SyntaxError(context,["duplicate argument '"+name+"' in function definition"]) } $B.bound[node.id][name] = {level:1} // we are sure the name is defined in function $B.type[node.id][name] = false this.tree = [] context.tree[context.tree.length]=this // add to locals of function var ctx = context while(ctx.parent!==undefined){ if(ctx.type==='def'){ ctx.locals.push(name) break } ctx = ctx.parent } this.expect = '=' this.toString = function(){return 'func arg id '+this.name +'='+this.tree} this.to_js = function(){ this.js_processed=true return this.name+$to_js(this.tree) } } function $FuncStarArgCtx(context,op){ // Class for "star argument" in a function definition : f(*args) this.type = 'func_star_arg' this.op = op this.parent = context this.node = $get_node(this) context.has_star_arg= op == '*' context.has_kw_arg= op == '**' context.tree[context.tree.length]=this this.toString = function(){return '(func star arg '+this.op+') '+this.name} this.set_name = function(name){ this.name = name if(name=='$dummy'){return} // bind name to function scope if($B.bound[this.node.id][name]){ $_SyntaxError(context,["duplicate argument '"+name+"' in function definition"]) } $B.bound[this.node.id][name] = {level:1} $B.type[this.node.id][name] = false // add to locals of function var ctx = context while(ctx.parent!==undefined){ if(ctx.type==='def'){ ctx.locals.push(name) break } ctx = ctx.parent } if(op=='*'){ctx.other_args = '"'+name+'"'} else{ctx.other_kw = '"'+name+'"'} } } function $GlobalCtx(context){ // Class for keyword "global" this.type = 'global' this.parent = context this.tree = [] context.tree[context.tree.length]=this this.expect = 'id' this.toString = function(){return 'global '+this.tree} this.scope = $get_scope(this) $B._globals[this.scope.id] = $B._globals[this.scope.id] || {} this.add = function(name){ $B._globals[this.scope.id][name] = true } this.to_js = function(){ this.js_processed=true return '' } } function $IdCtx(context,value){ // Class for identifiers (variable names) this.type = 'id' this.toString = function(){return '(id) '+this.value+':'+(this.tree||'')} this.value = value this.parent = context this.tree = [] context.tree[context.tree.length]=this if(context.parent.type==='call_arg') this.call_arg=true this.scope = $get_scope(this) this.blurred_scope = this.scope.blurred this.env = clone($B.bound[this.scope.id]) var ctx = context while(ctx.parent!==undefined){ switch(ctx.type) { case 'list_or_tuple': case 'dict_or_set': case 'call_arg': case 'def': case 'lambda': if(ctx.vars===undefined){ctx.vars=[value]} else if(ctx.vars.indexOf(value)===-1){ctx.vars.push(value)} if(this.call_arg&&ctx.type==='lambda'){ if(ctx.locals===undefined){ctx.locals=[value]} else{ctx.locals.push(value)} } } ctx = ctx.parent } var scope = this.scope = $get_scope(this) if(context.type=='target_list' || context.type=='packed' || (context.type=='expr' && context.parent.type=='target_list')){ // An id defined as a target in a "for" loop, or as "packed" // (eg "a, *b = [1, 2, 3]") is bound $B.bound[scope.id][value]={level: scope.level} $B.type[scope.id][value] = false // can be improved ! this.bound = true } if(scope.ntype=='def' || scope.ntype=='generator'){ // if variable is declared inside a comprehension, // don't add it to function namespace var _ctx=this.parent while(_ctx){ if(_ctx.type=='list_or_tuple' && _ctx.is_comp()) return _ctx = _ctx.parent } if(context.type=='expr' && context.parent.type=='comp_if'){ // form {x for x in foo if x>5} : don't put x in referenced names return }else if(context.type=='global'){ if(scope.globals === undefined){ scope.globals = [value] }else if(scope.globals.indexOf(value)==-1){ scope.globals.push(value) } } } this.to_js = function(arg){ // Store the result in this.result // For generator expressions, to_js() is called in $make_node and // $B.bound has been deleted if(this.result!==undefined && this.scope.ntype=='generator'){ return this.result } this.js_processed=true var val = this.value var is_local = $B.bound[this.scope.id][val]!==undefined var bound_before = $get_node(this).bound_before if(this.scope.nonlocals && this.scope.nonlocals[val]!==undefined){ this.nonlocal = true } // If name is bound in the scope, but not yet bound when this // instance of $IdCtx was created, it is resolved by a call to // $search or $local_search this.unbound = this.unbound || (is_local && !this.bound && bound_before && bound_before.indexOf(val)==-1) if(this.unbound && !this.nonlocal){ if(this.scope.ntype=='def' || this.scope.ntype=='generator'){ return '$B.$local_search("'+val+'")' }else{ return '$B.$search("'+val+'")' } } // Special cases //if(val=='eval') val = '$eval' if(val=='__BRYTHON__' || val == '$B'){return val} var innermost = $get_scope(this) var scope = innermost, found=[], module = scope.module // get global scope var gs = innermost while(gs.parent_block && gs.parent_block.id!=='__builtins__'){ gs = gs.parent_block } var global_ns = '$locals_'+gs.id.replace(/\./g,'_') // Build the list of scopes where the variable name is bound while(1){ if($B.bound[scope.id]===undefined){ console.log('name '+val+' undef '+scope.id) } if($B.type[scope.id]===undefined){console.log('name '+val+' type undef '+scope.id)} if($B._globals[scope.id]!==undefined && $B._globals[scope.id][val]!==undefined){ // Variable is declared as global. If the name is bound in the global // scope, use it ; if the name is being bound, bind it in the global namespace. // Else return a call to a function that searches the name in globals, // and throws NameError if not found if($B.bound[gs.id][val]!==undefined || this.bound){ this.result = global_ns+'["'+val+'"]' return this.result }else{ this.result = '$B.$global_search("'+val+'")' return this.result } found = [gs] break } if(scope===innermost){ // Handle the case when the same name is used at both sides // of an assignment and the right side is defined in an // upper scope, eg "range = range" var bound_before = $get_node(this).bound_before if(bound_before && !this.bound){ if(bound_before.indexOf(val)>-1){found.push(scope)} else if(scope.context && scope.context.tree[0].type=='def' && scope.context.tree[0].env.indexOf(val)>-1){ found.push(scope) } }else{ if($B.bound[scope.id][val]){found.push(scope)} } }else{ //console.log(val, scope.id, Object.keys($B.bound)) if($B.bound[scope.id] === undefined){ console.log('no bound', scope.id) } if($B.bound[scope.id][val]){found.push(scope)} } if(scope.parent_block){scope=scope.parent_block} else{break} } this.found = found if(this.nonlocal && found[0]===innermost){found.shift()} if(val=='fghj'){console.log('found for', val, found)} if(found.length>0){ // If name is not in the left part of an assignment, // and it is bound in the current block but not yet bound when the // line is parsed, // and it is not declared as nonlocal, // and it is not an internal variable starting with "$", // return the execution of function $B.$local_search(val) in // py_utils.js that searches the name in the local namespace // and raises UnboundLocalError if it is undefined // The id may be valid in code like : // def f(): // for i in range(2): // if i==1: // return x # x is local but not yet found by parser // elif i==0: // x = 'ok' if(!this.bound && found[0].context && found[0]===innermost && val.charAt(0)!='$'){ var locs = $get_node(this).locals || {}, nonlocs = innermost.nonlocals if(locs[val]===undefined && ((innermost.type!='def' || innermost.type!='generator') && innermost.context.tree[0].args.indexOf(val)==-1) && (nonlocs===undefined || nonlocs[val]===undefined)){ this.result = '$B.$local_search("'+val+'")' return this.result } } if(found.length>1 && found[0].context){ if(found[0].context.tree[0].type=='class' && !this.bound){ var ns0='$locals_'+found[0].id.replace(/\./g,'_'), ns1='$locals_'+found[1].id.replace(/\./g,'_'), res // If the id is referenced in a class body, and an id of // the same name is bound in an upper scope, we must check // if it has already been bound in the class, else we use // the upper scope // This happens in code like // // x = 0 // class A: // print(x) # should print 0 // def x(self): // pass // print(x) # should print '<function x>' // if(bound_before){ if(bound_before.indexOf(val)>-1){ this.found = $B.bound[found[0].id][val] res = ns0 }else{ this.found = $B.bound[found[1].id][val] res = ns1 } this.result = res+'["'+val+'"]' return this.result }else{ this.found = false var res = ns0 + '["'+val+'"]!==undefined ? ' res += ns0 + '["'+val+'"] : ' this.result = res + ns1 + '["'+val+'"]' return this.result } } } var scope = found[0] this.found = $B.bound[scope.id][val] var scope_ns = '$locals_'+scope.id.replace(/\./g,'_') if(scope.context===undefined){ // name found at module level if(scope.id=='__builtins__'){ if(gs.blurred){ // If the program has "from <module> import *" we // can't be sure by syntax analysis that the builtin // name is not overridden val = '('+global_ns+'["'+val+'"] || '+val+')' }else{ // Builtin name ; it might be redefined inside the // script, eg to redefine open() if(val!=='__builtins__'){val = '$B.builtins.'+val} this.is_builtin = true } }else if(scope.id==scope.module){ // Name found at module level if(this.bound || this.augm_assign){ // If the id is in the left part of a binding or // an augmented assign, eg "x = 0" or "x += 5" val = scope_ns+'["'+val+'"]' }else{ if(scope===innermost && this.env[val]===undefined){ var locs = $get_node(this).locals || {} if(locs[val]===undefined){ // Name is bound in scope, but after the current node // If it is a builtin name, use the builtin // Cf issue #311 if(found.length>1 && found[1].id == '__builtins__'){ this.is_builtin = true this.result = '$B.builtins.'+val+$to_js(this.tree,'') return this.result } } // Call a function to return the value if it is defined // in locals or globals, or throw a NameError this.result = '$B.$search("'+val+'")' return this.result }else{ if(scope.level<=2){ // Name was bound in an instruction at indentation // level 0 in the block : we are sure the name is // defined in local scope val = scope_ns+'["'+val+'"]' }else{ // Else we must check if the name is actually // defined, cf issue #362. This can be the case // in code like : // if False: // x = 0 val = '$B.$check_def("'+val+'",'+scope_ns+'["'+val+'"])' } } } }else{ val = scope_ns+'["'+val+'"]' } }else if(scope===innermost){ if($B._globals[scope.id] && $B._globals[scope.id][val]){ val = global_ns+'["'+val+'"]' }else if(!this.bound && !this.augm_assign){ if(scope.level<=3){ // Name is bound at indentation level 0 in the block : // we are sure that it is defined in locals val = '$locals["'+val+'"]' }else{ // The name might not have actually been bound, eg in // def f(): // if False: // x = 0 // print(x) val = '$B.$check_def_local("'+val+'",$locals["'+val+'"])' } }else{ val = '$locals["'+val+'"]' } }else if(!this.bound && !this.augm_assign){ // name was found between innermost and the global of builtins // namespace if(scope.ntype=='generator'){ // If the name is bound in a generator, we must search the value // in the locals object for the currently executed function. It // can be found as the second element of the frame stack at the // same level up than the generator function var up = 0, // number of levels of the generator above innermost sc = innermost while(sc!==scope){up++;sc=sc.parent_block} var scope_name = "$B.frames_stack[$B.frames_stack.length-1-"+up+"][1]" val = '$B.$check_def_free("'+val+'",'+scope_name+'["'+val+'"])' }else{ val = '$B.$check_def_free("'+val+'",'+scope_ns+'["'+val+'"])' } }else{ val = scope_ns+'["'+val+'"]' } this.result = val+$to_js(this.tree,'') return this.result }else{ // Name was not found in bound names // It may have been introduced in the globals namespace by an exec, // or by "from A import *" // First set attribute "unknown_binding", used to avoid using // augmented assignement operators in this case this.unknown_binding = true // If the name exists at run time in the global namespace, use it, // else raise a NameError // Function $search is defined in py_utils.js this.result = '$B.$search("'+val+'")' return this.result } } } function $ImaginaryCtx(context,value){ // Class for the imaginary part of a complex number this.type = 'imaginary' this.value = value this.toString = function(){return 'imaginary '+this.value} this.parent = context this.tree = [] context.tree[context.tree.length]=this this.to_js = function(){ this.js_processed=true return 'complex(0,'+this.value+')' } } function $ImportCtx(context){ // Class for keyword "import" this.type = 'import' this.parent = context this.tree = [] context.tree[context.tree.length]=this this.expect = 'id' this.toString = function(){return 'import '+this.tree} this.bind_names = function(){ // For "import X", set X in the list of names bound in current scope var scope = $get_scope(this) for(var i=0;i<this.tree.length;i++){ if(this.tree[i].name==this.tree[i].alias){ var name = this.tree[i].name, parts = name.split('.'), bound = name if(parts.length>1){ bound = parts[0] } }else{ bound = this.tree[i].alias } $B.bound[scope.id][bound] = {level: scope.level} $B.type[scope.id][bound] = 'module' } } this.to_js = function(){ this.js_processed=true var scope = $get_scope(this) var mod = scope.module var res = [], pos=0 for(var i=0;i<this.tree.length;i++){ var mod_name = this.tree[i].name, aliases = (this.tree[i].name == this.tree[i].alias)? '{}' : ('{"' + mod_name + '" : "' + this.tree[i].alias + '"}'), localns = '$locals_'+scope.id.replace(/\./g,'_'); res[pos++] = '$B.$import("'+mod_name+'", [],'+aliases+',' + localns + ', true);' } // add None for interactive console return res.join('') + 'None;' } } function $ImportedModuleCtx(context,name){ this.type = 'imported module' this.toString = function(){return ' (imported module) '+this.name} this.parent = context this.name = name this.alias = name context.tree[context.tree.length]=this this.to_js = function(){ this.js_processed=true return '"'+this.name+'"' } } function $IntCtx(context,value){ // Class for literal integers // value is a 2-elt tuple [base, value_as_string] where // base is one of 16 (hex literal), 8 (octal), 2 (binary) or 10 (int) this.type = 'int' this.value = value this.parent = context this.tree = [] context.tree[context.tree.length]=this this.toString = function(){return 'int '+this.value} this.to_js = function(){ this.js_processed=true var v = parseInt(value[1], value[0]) if(v>$B.min_int && v<$B.max_int){return v} else{return '$B.LongInt("'+value[1]+'", '+value[0]+')'} } } function $JSCode(js){ this.js = js this.toString = function(){return this.js} this.to_js = function(){ this.js_processed=true return this.js } } function $KwArgCtx(context){ // Class for keyword argument in a call this.type = 'kwarg' this.parent = context.parent this.tree = [context.tree[0]] // operation replaces left operand context.parent.tree.pop() context.parent.tree.push(this) // put id in list of kwargs // used to avoid passing the id as argument of a list comprehension var value = this.tree[0].value var ctx = context.parent.parent // type 'call' if(ctx.kwargs===undefined){ctx.kwargs=[value]} else if(ctx.kwargs.indexOf(value)===-1){ctx.kwargs.push(value)} else{$_SyntaxError(context,['keyword argument repeated'])} // If the keyword argument occurs inside a function, remove the occurence // from referenced variables in the function var scope = $get_scope(this) this.toString = function(){return 'kwarg '+this.tree[0]+'='+this.tree[1]} this.to_js = function(){ this.js_processed=true var key = this.tree[0].value if(key.substr(0,2)=='$$'){key=key.substr(2)} var res = '{$nat:"kw",name:"'+key+'",' return res + 'value:'+$to_js(this.tree.slice(1,this.tree.length))+'}' } } function $LambdaCtx(context){ // Class for keyword "lambda" this.type = 'lambda' this.parent = context context.tree[context.tree.length]=this this.tree = [] this.args_start = $pos+6 this.vars = [] this.locals = [] this.toString = function(){return '(lambda) '+this.args_start+' '+this.body_start} this.to_js = function(){ this.js_processed=true var module = $get_module(this) var src = $B.$py_src[module.id] var qesc = new RegExp('"',"g"), // to escape double quotes in arguments args = src.substring(this.args_start,this.body_start), body = src.substring(this.body_start+1,this.body_end) body = body.replace(/\n/g,' ') var scope = $get_scope(this) var rand = $B.UUID(), func_name = 'lambda_'+$B.lambda_magic+'_'+rand, py = 'def '+func_name+'('+args+'):\n' py += ' return '+body var lambda_name = 'lambda'+rand, module_name = module.id.replace(/\./g, '_'), scope_id = scope.id.replace(/\./g, '_') var js = $B.py2js(py, module_name, lambda_name, scope_id).to_js() js = '(function(){\n'+js+'\nreturn $locals.'+func_name+'\n})()' delete $B.modules[lambda_name] $B.clear_ns(lambda_name) return js } } function $ListOrTupleCtx(context,real){ // Class for literal lists or tuples // The real type (list or tuple) is set inside $transition // as attribute 'real' this.type = 'list_or_tuple' this.start = $pos this.real = real this.expect = 'id' this.closed = false this.parent = context this.tree = [] context.tree[context.tree.length]=this this.toString = function(){ switch(this.real) { case 'list': return '(list) ['+this.tree+']' case 'list_comp': case 'gen_expr': return '('+this.real+') ['+this.intervals+'-'+this.tree+']' default: return '(tuple) ('+this.tree+')' } } this.is_comp = function(){ switch(this.real) { case 'list_comp': case 'gen_expr': case 'dict_or_set_comp': return true } return false } this.get_src = function(){ // Return the Python source code var scope = $get_scope(this) var ident = scope.id while($B.$py_src[ident]===undefined && $B.modules[ident].parent_block){ ident = $B.modules[ident].parent_block.id } if($B.$py_src[ident]===undefined){ // this is ugly return $B.$py_src[scope.module] } return $B.$py_src[ident] } this.ids = function(){ // Return an object indexed by all "simple" variable names in the list // or tuple, ie not calls, subscriptions etc. var _ids = {} for(var i=0;i<this.tree.length;i++){ var item = this.tree[i] if(item.type=='id'){_ids[item.value]=true} else if(item.type=='expr' && item.tree[0].type=="id"){ _ids[item.tree[0].value]=true }else if(item.type=='list_or_tuple' || (item.type=="expr" && item.tree[0].type=='list_or_tuple')){ if(item.type=="expr"){item=item.tree[0]} for(var attr in item.ids()){_ids[attr]=true} } } return _ids } this.to_js = function(){ this.js_processed=true var scope = $get_scope(this) var sc = scope, scope_id = scope.id.replace(/\//g, '_') var env = [], pos=0 while(sc && sc.id!=='__builtins__'){ if(sc===scope){ env[pos++]='["'+sc.id+'",$locals]' }else{ env[pos++]='["'+sc.id+'",$locals_'+sc.id.replace(/\./g,'_')+']' } sc = sc.parent_block } var env_string = '['+env.join(', ')+']' var module_name = $get_module(this).module switch(this.real) { case 'list': return '$B.$list(['+$to_js(this.tree)+'])' case 'list_comp': case 'gen_expr': case 'dict_or_set_comp': var src = this.get_src() var res1 = [], items = [] var qesc = new RegExp('"',"g") // to escape double quotes in arguments for(var i=1;i<this.intervals.length;i++){ var txt = src.substring(this.intervals[i-1],this.intervals[i]) items.push(txt) var lines = txt.split('\n') var res2=[], pos=0 for(var j=0;j<lines.length;j++){ var txt = lines[j] // ignore empty lines if(txt.replace(/ /g,'').length==0){continue} txt = txt.replace(/\n/g,' ') txt = txt.replace(/\\/g,'\\\\') txt = txt.replace(qesc,'\\"') res2[pos++]='"'+txt+'"' } res1.push('['+res2.join(',')+']') } var line_num = $get_node(this).line_num switch(this.real) { case 'list_comp': var local_name = scope.id.replace(/\./g,'_') var lc = $B.$list_comp(items), // defined in py_utils.js py = lc[0], ix=lc[1], listcomp_name = 'lc'+ix, local_name = scope.id.replace(/\./g,'_') var save_pos = $pos var root = $B.py2js(py,module_name,listcomp_name,local_name, line_num) $pos = save_pos var js = root.to_js() delete $B.modules[listcomp_name] $B.clear_ns(listcomp_name) js += 'return $locals_lc'+ix+'["x'+ix+'"]' js = '(function(){'+js+'})()' return js case 'dict_or_set_comp': if(this.expression.length===1){ return '$B.$gen_expr('+env_string+','+res1+')' } return '$B.$dict_comp('+env_string+','+res1+')' } // Generator expression // Pass the module name and the id of current block return $B.$gen_expr1(module_name, scope_id, items, line_num) //return '$B.$gen_expr('+env_string+','+res1+')' case 'tuple': if(this.tree.length===1 && this.has_comma===undefined){ return this.tree[0].to_js() } return 'tuple(['+$to_js(this.tree)+'])' } } } function $NodeCtx(node){ // Base class for the context in a node this.node = node node.context = this this.tree = [] this.type = 'node' var scope = null var tree_node = node while(tree_node.parent && tree_node.parent.type!=='module'){ var ntype = tree_node.parent.context.tree[0].type var _break_flag=false switch(ntype) { case 'def': case 'class': case 'generator': //if(['def', 'class', 'generator'].indexOf(ntype)>-1){ scope = tree_node.parent _break_flag=true } if (_break_flag) break tree_node = tree_node.parent } if(scope==null){ scope = tree_node.parent || tree_node // module } // When a new node is created, a copy of the names currently // bound in the scope is created. It is used in $IdCtx to detect // names that are referenced but not yet bound in the scope this.node.locals = clone($B.bound[scope.id]) this.toString = function(){return 'node '+this.tree} this.to_js = function(){ if(this.js!==undefined){return this.js} this.js_processed=true if(this.tree.length>1){ var new_node = new $Node() var ctx = new $NodeCtx(new_node) ctx.tree = [this.tree[1]] new_node.indent = node.indent+4 this.tree.pop() node.add(new_node) } if(node.children.length==0){ this.js = $to_js(this.tree)+';' }else{ this.js = $to_js(this.tree) } return this.js } } function $NodeJS(js){ var node = new $Node() new $NodeJSCtx(node, js) return node } function $NodeJSCtx(node,js){ // Class used for raw JS code this.node = node node.context = this this.type = 'node_js' this.tree = [js] this.toString = function(){return 'js '+js} this.to_js = function(){ this.js_processed=true return js } } function $NonlocalCtx(context){ // Class for keyword "nonlocal" this.type = 'global' this.parent = context this.tree = [] this.names = {} context.tree[context.tree.length]=this this.expect = 'id' this.scope = $get_scope(this) this.scope.nonlocals = this.scope.nonlocals || {} if(this.scope.context===undefined){ $_SyntaxError(context,["nonlocal declaration not allowed at module level"]) } this.toString = function(){return 'global '+this.tree} this.add = function(name){ if($B.bound[this.scope.id][name]=='arg'){ $_SyntaxError(context,["name '"+name+"' is parameter and nonlocal"]) } this.names[name] = [false, $pos] this.scope.nonlocals[name] = true } this.transform = function(node, rank){ var pscope = this.scope.parent_block if(pscope.context===undefined){ $_SyntaxError(context,["no binding for nonlocal '"+ $B.last(Object.keys(this.names))+"' found"]) }else{ while(pscope!==undefined && pscope.context!==undefined){ for(var name in this.names){ if($B.bound[pscope.id][name]!==undefined){ this.names[name] = [true] } } pscope = pscope.parent_block } for(var name in this.names){ if(!this.names[name][0]){ console.log('nonlocal error, context '+context) // restore $pos to get the correct error line $pos = this.names[name][1] $_SyntaxError(context,["no binding for nonlocal '"+name+"' found"]) } } //if(this.scope.globals.indexOf(name)==-1){this.scope.globals.push(name)} } } this.to_js = function(){ this.js_processed=true return '' } } function $NotCtx(context){ // Class for keyword "not" this.type = 'not' this.parent = context this.tree = [] context.tree[context.tree.length]=this this.toString = function(){return 'not ('+this.tree+')'} this.to_js = function(){ this.js_processed=true return '!bool('+$to_js(this.tree)+')' } } function $OpCtx(context,op){ // Class for operators ; context is the left operand this.type = 'op' this.op = op this.parent = context.parent this.tree = [context] this.scope = $get_scope(this) // Get type of left operand if(context.type=="expr"){ if(['int','float','str'].indexOf(context.tree[0].type)>-1){ this.left_type = context.tree[0].type }else if(context.tree[0].type=="id"){ var binding = $B.bound[this.scope.id][context.tree[0].value] if(binding){this.left_type=binding.type} } } // operation replaces left operand context.parent.tree.pop() context.parent.tree.push(this) this.toString = function(){return '(op '+this.op+') ['+this.tree+']'} this.to_js = function(){ this.js_processed=true var comps = {'==':'eq','!=':'ne','>=':'ge','<=':'le', '<':'lt','>':'gt'} if(comps[this.op]!==undefined){ var method=comps[this.op] if(this.tree[0].type=='expr' && this.tree[1].type=='expr'){ var t0=this.tree[0].tree[0],t1=this.tree[1].tree[0] switch(t1.type) { case 'int': switch (t0.type) { case 'int': return t0.to_js()+this.op+t1.to_js() case 'str': return '$B.$TypeError("unorderable types: int() < str()")' case 'id': var res = 'typeof '+t0.to_js()+'=="number" ? ' res += t0.to_js()+this.op+t1.to_js()+' : ' res += 'getattr('+this.tree[0].to_js() res += ',"__'+method+'__")('+this.tree[1].to_js()+')' return res } break; case 'str': switch(t0.type) { case 'str': return t0.to_js()+this.op+t1.to_js() case 'int': return '$B.$TypeError("unorderable types: str() < int()")' case 'id': var res = 'typeof '+t0.to_js()+'=="string" ? ' res += t0.to_js()+this.op+t1.to_js()+' : ' res += 'getattr('+this.tree[0].to_js() res += ',"__'+method+'__")('+this.tree[1].to_js()+')' return res } break; case 'id': if(t0.type=='id'){ var res = 'typeof '+t0.to_js()+'!="object" && ' res += 'typeof '+t0.to_js()+'==typeof '+t1.to_js() res += ' ? '+t0.to_js()+this.op+t1.to_js()+' : ' res += 'getattr('+this.tree[0].to_js() res += ',"__'+method+'__")('+this.tree[1].to_js()+')' return res } break; } //switch } } switch(this.op) { case 'and': var res ='$B.$test_expr($B.$test_item('+this.tree[0].to_js()+')&&' return res + '$B.$test_item('+this.tree[1].to_js()+'))' case 'or': var res ='$B.$test_expr($B.$test_item('+this.tree[0].to_js()+')||' return res + '$B.$test_item('+this.tree[1].to_js()+'))' case 'in': return '$B.$is_member('+$to_js(this.tree)+')' case 'not_in': return '!$B.$is_member('+$to_js(this.tree)+')' case 'unary_neg': case 'unary_pos': case 'unary_inv': // For unary operators, the left operand is the unary sign(s) var op, method if(this.op=='unary_neg'){op='-';method='__neg__'} else if(this.op=='unary_pos'){op='+';method='__pos__'} else{op='~';method='__invert__'} // for integers or float, replace their value using // Javascript operators if(this.tree[1].type=="expr"){ var x = this.tree[1].tree[0] switch(x.type) { case 'int': var v = parseInt(x.value[1], x.value[0]) if(v>$B.min_int && v<$B.max_int){return op+v} // for long integers, use __neg__ or __invert__ return 'getattr('+x.to_js()+', "'+method+'")()' case 'float': return 'float('+op+x.value+')' case 'imaginary': return 'complex(0,'+op+x.value+')' } } return 'getattr('+this.tree[1].to_js()+',"'+method+'")()' case 'is': return this.tree[0].to_js() + '===' + this.tree[1].to_js() case 'is_not': return this.tree[0].to_js() + '!==' + this.tree[1].to_js() case '*': case '+': case '-': var op = this.op, vars = [], has_float_lit = false, scope = $get_scope(this) function is_simple(elt){ if(elt.type=='expr' && elt.tree[0].type=='int'){return true} else if(elt.type=='expr' && elt.tree[0].type=='float'){ has_float_lit = true return true }else if(elt.type=='expr' && elt.tree[0].type=='list_or_tuple' && elt.tree[0].real=='tuple' && elt.tree[0].tree.length==1 && elt.tree[0].tree[0].type=='expr'){ return is_simple(elt.tree[0].tree[0].tree[0]) }else if (elt.type=='expr' && elt.tree[0].type=='id'){ var _var = elt.tree[0].to_js() if(vars.indexOf(_var)==-1){vars.push(_var)} return true }else if(elt.type=='op' && ['*','+','-'].indexOf(elt.op)>-1){ for(var i=0;i<elt.tree.length;i++){ if(!is_simple(elt.tree[i])){return false} } return true } return false } function get_type(ns, v){ var t if(['int','float','str'].indexOf(v.type)>-1){ t = v.type }else if(v.type=='id' && ns[v.value]){ t = ns[v.value].type } return t } var e0=this.tree[0],e1=this.tree[1] if(is_simple(this)){ var v0 = this.tree[0].tree[0] var v1 = this.tree[1].tree[0] if(vars.length==0 && !has_float_lit){ // only integer literals return this.simple_js() }else if(vars.length==0){ // numeric literals with at least one float return 'new Number('+this.simple_js()+')' }else{ // at least one variable var ns = $B.bound[scope.id], t0 = get_type(ns, v0), t1 = get_type(ns, v1) // Static analysis told us the type of both ids if((t0=='float' && t1=='float') || (this.op=='+' && t0=='str' && t1=='str')){ this.result_type = t0 return v0.to_js()+this.op+v1.to_js() }else if(['int','float'].indexOf(t0)>-1 && ['int','float'].indexOf(t1)>-1){ if(t0=='int' && t1=='int'){this.result_type='int'} else{this.result_type='float'} switch(this.op){ case '+': return '$B.add('+v0.to_js()+','+v1.to_js()+')' case '-': return '$B.sub('+v0.to_js()+','+v1.to_js()+')' case '*': return '$B.mul('+v0.to_js()+','+v1.to_js()+')' } } var tests = [], tests1=[], pos=0 for(var i=0;i<vars.length;i++){ // Test if all variables are numbers tests[pos]='typeof '+vars[i]+'.valueOf() == "number"' // Test if all variables are integers tests1[pos++]='typeof '+vars[i]+' == "number"' } var res = [tests.join(' && ')+' ? '], pos=1 res[pos++]='('+tests1.join(' && ')+' ? ' // If true, use basic formula res[pos++]=this.simple_js() // Else wrap simple formula in a float res[pos++]=' : new $B.$FloatClass('+this.simple_js()+')' // Close integers test res[pos++]=')' // If at least one variable is not a number // For addition, test if both arguments are strings if(this.op=='+'){ res[pos++]=' : (typeof '+this.tree[0].to_js()+'=="string"' res[pos++]=' && typeof '+this.tree[1].to_js() res[pos++]='=="string") ? '+this.tree[0].to_js() res[pos++]='+'+this.tree[1].to_js() } res[pos++]= ': getattr('+this.tree[0].to_js()+',"__' res[pos++]= $operators[this.op]+'__")'+'('+this.tree[1].to_js()+')' //if(this.op=='+'){console.log(res)} return '('+res.join('')+')' } } var res = 'getattr('+e0.to_js()+',"__' return res + $operators[this.op]+'__")'+'('+e1.to_js()+')' default: var res = 'getattr('+this.tree[0].to_js()+',"__' return res + $operators[this.op]+'__")'+'('+this.tree[1].to_js()+')' } } this.simple_js = function(){ function sjs(elt){ if(elt.type=='op'){return elt.simple_js()} else if(elt.type=='expr' && elt.tree[0].type=='list_or_tuple' && elt.tree[0].real=='tuple' && elt.tree[0].tree.length==1 && elt.tree[0].tree[0].type=='expr'){ return '('+elt.tree[0].tree[0].tree[0].simple_js()+')' }else{return elt.tree[0].to_js()} } if(op=='+'){return '$B.add('+sjs(this.tree[0])+','+sjs(this.tree[1])+')'} else if(op=='-'){return '$B.sub('+sjs(this.tree[0])+','+sjs(this.tree[1])+')'} else if(op=='*'){return '$B.mul('+sjs(this.tree[0])+','+sjs(this.tree[1])+')'} else if(op=='/'){return '$B.div('+sjs(this.tree[0])+','+sjs(this.tree[1])+')'} else{return sjs(this.tree[0])+op+sjs(this.tree[1])} } } function $PackedCtx(context){ // used for packed tuples in expressions, eg // a, *b, c = [1, 2, 3, 4} this.type = 'packed' if(context.parent.type=='list_or_tuple'){ for(var i=0;i<context.parent.tree.length;i++){ var child = context.parent.tree[i] if(child.type=='expr' && child.tree.length>0 && child.tree[0].type=='packed'){ $_SyntaxError(context,["two starred expressions in assignment"]) } } } this.parent = context this.tree = [] context.tree[context.tree.length]=this this.toString = function(){return '(packed) '+this.tree} this.to_js = function(){ this.js_processed=true return $to_js(this.tree) } } function $PassCtx(context){ // Class for keyword "pass" this.type = 'pass' this.parent = context this.tree = [] context.tree[context.tree.length]=this this.toString = function(){return '(pass)'} this.to_js = function(){ this.js_processed=true return 'void(0)' } } function $RaiseCtx(context){ // Class for keyword "raise" this.type = 'raise' this.parent = context this.tree = [] context.tree[context.tree.length]=this this.toString = function(){return ' (raise) '+this.tree} this.to_js = function(){ this.js_processed=true var res = '' if(this.tree.length===0) return '$B.$raise()' var exc = this.tree[0], exc_js = exc.to_js() if(exc.type==='id' || (exc.type==='expr' && exc.tree[0].type==='id')){ res = 'if(isinstance('+exc_js+',type)){throw '+exc_js+'()}' return res + 'else{throw '+exc_js+'}' } // if raise had a 'from' clause, ignore it while(this.tree.length>1) this.tree.pop() return res+'throw '+$to_js(this.tree) } } function $RawJSCtx(context,js){ this.type = "raw_js" context.tree[context.tree.length]=this this.parent = context this.toString = function(){return '(js) '+js} this.to_js = function(){ this.js_processed=true return js } } function $ReturnCtx(context){ // Class for keyword "return" this.type = 'return' this.parent = context this.tree = [] context.tree[context.tree.length]=this // Check if return is inside a "for" loop // In this case, the loop will not be included inside a function // for optimisation var node = $get_node(this) while(node.parent){ if(node.parent.context && node.parent.context.tree[0].type=='for'){ node.parent.context.tree[0].has_return = true break } node = node.parent } this.toString = function(){return 'return '+this.tree} this.to_js = function(){ this.js_processed=true if(this.tree.length==1 && this.tree[0].type=='abstract_expr'){ // "return" must be transformed into "return None" this.tree.pop() new $IdCtx(new $ExprCtx(this,'rvalue',false),'None') } var scope = $get_scope(this) if(scope.ntype=='generator'){ return 'return [$B.generator_return(' + $to_js(this.tree)+')]' } // In most cases, returning from a function means leaving the // execution frame ; but if the return is in a "try" with a "finally" // clause, we must remain in the same frame var node = $get_node(this), pnode, flag, leave_frame = true, in_try = false while(node && leave_frame){ if(node.is_try){ in_try = true pnode = node.parent, flag=false for(var i=0;i<pnode.children.length;i++){ var child = pnode.children[i] if(!flag && child===node){flag=true;continue} if(flag){ if(child.context.tree[0].type=="single_kw" && child.context.tree[0].token=="finally"){ leave_frame = false break } } } } node = node.parent } // Executing the target of "return" might raise an exception. if(leave_frame && !in_try){ // Computing the target of "return" may raise an exception // If the return is in a try clause, this exception is handled // somewhere else var res = 'try{var $res = '+$to_js(this.tree)+';'+ '$B.leave_frame($local_name);return $res}catch(err){'+ '$B.leave_frame($local_name);throw err}' }else if(leave_frame){ var res = 'var $res = '+$to_js(this.tree)+';'+ '$B.leave_frame($local_name);return $res' }else{ var res = "return "+$to_js(this.tree) } var res = "return "+$to_js(this.tree) return res } } function $SingleKwCtx(context,token){ // Class for keywords "finally", "else" this.type = 'single_kw' this.token = token this.parent = context this.tree = [] context.tree[context.tree.length]=this // If token is "else" inside a "for" loop, set the flag "has_break" // on the loop, to force the creation of a boolean "$no_break" if(token=="else"){ var node = context.node var pnode = node.parent for(var rank=0;rank<pnode.children.length;rank++){ if(pnode.children[rank]===node) break } var pctx = pnode.children[rank-1].context if(pctx.tree.length>0){ var elt = pctx.tree[0] if(elt.type=='for' || elt.type=='asyncfor' || (elt.type=='condition' && elt.token=='while')){ elt.has_break = true elt.else_node = $get_node(this) this.loop_num = elt.loop_num } } } this.toString = function(){return this.token} this.to_js = function(){ this.js_processed=true if(this.token=='finally') return this.token // For "else" we must check if the previous block was a loop // If so, check if the loop exited with a "break" to decide // if the block below "else" should be run if(this.loop_num!==undefined){ var scope = $get_scope(this) var res = 'if($locals_'+scope.id.replace(/\./g,'_') return res +'["$no_break'+this.loop_num+'"])' } return this.token } } function $StarArgCtx(context){ // Class for star args in calls, eg f(*args) this.type = 'star_arg' this.parent = context this.tree = [] context.tree[context.tree.length]=this this.toString = function(){return '(star arg) '+this.tree} this.to_js = function(){ this.js_processed=true return '{$nat:"ptuple",arg:'+$to_js(this.tree)+'}' } } function $StringCtx(context,value){ // Class for literal strings this.type = 'str' this.parent = context this.tree = [value] // may be extended if consecutive strings eg 'a' 'b' this.raw = false context.tree[context.tree.length]=this this.toString = function(){return 'string '+(this.tree||'')} this.to_js = function(){ this.js_processed=true var res = '', type = null for(var i=0;i<this.tree.length;i++){ if(this.tree[i].type=="call"){ // syntax like "hello"(*args, **kw) raises TypeError // cf issue 335 var js = '(function(){throw TypeError("'+"'str'"+ ' object is not callable")}())' return js }else{ var value=this.tree[i], is_bytes = value.charAt(0)=='b' if(type==null){ type=is_bytes if(is_bytes){res+='bytes('} }else if(type!=is_bytes){ return '$B.$TypeError("can\'t concat bytes to str")' } if(!is_bytes){ res += value.replace(/\n/g,'\\n\\\n') }else{ res += value.substr(1).replace(/\n/g,'\\n\\\n') } if(i<this.tree.length-1){res+='+'} } } if(is_bytes){res += ',"ISO-8859-1")'} return res } } function $SubCtx(context){ // Class for subscription or slicing, eg x in t[x] this.type = 'sub' this.func = 'getitem' // set to 'setitem' if assignment this.value = context.tree[0] context.tree.pop() context.tree[context.tree.length]=this this.parent = context this.tree = [] this.toString = function(){ return '(sub) (value) '+this.value+' (tree) '+this.tree } this.to_js = function(){ this.js_processed=true if(this.func=='getitem' && this.value.type=='id'){ var type = $get_node(this).locals[this.value.value], val = this.value.to_js() if(type=='list'||type=='tuple'){ if(this.tree.length==1){ return '$B.list_key('+val+ ', '+this.tree[0].to_js()+')' }else if(this.tree.length==2){ return '$B.list_slice('+val+ ', '+(this.tree[0].to_js()||"null")+','+ (this.tree[1].to_js()||"null")+')' }else if(this.tree.length==3){ return '$B.list_slice_step('+val+ ', '+(this.tree[0].to_js()||"null")+','+ (this.tree[1].to_js()||"null")+','+ (this.tree[2].to_js()||"null")+')' } } } if(this.func=='getitem' && this.tree.length==1){ return '$B.$getitem('+this.value.to_js()+',' + this.tree[0].to_js()+')' } var res='', shortcut = false if(this.func!=='delitem' && Array.isArray && this.tree.length==1 && !this.in_sub){ var expr = '', x = this shortcut = true while(x.value.type=='sub'){ expr += '['+x.tree[0].to_js()+']' x.value.in_sub = true x = x.value } var subs = x.value.to_js()+'['+x.tree[0].to_js()+']' res += '((Array.isArray('+x.value.to_js()+') || ' res += 'typeof '+x.value.to_js()+'=="string")' res += ' && '+subs+'!==undefined ?' res += subs+expr+ ' : ' } var val = this.value.to_js() res += 'getattr('+val+',"__'+this.func+'__")(' if(this.tree.length===1){ res += this.tree[0].to_js()+')' }else{ var res1=[], pos=0 for(var i=0;i<this.tree.length;i++){ if(this.tree[i].type==='abstract_expr'){res1[pos++]='None'} else{res1[pos++]=this.tree[i].to_js()} } res += 'slice(' + res1.join(',') + '))' } return shortcut ? res+')' : res } } function $TargetListCtx(context){ // Class for target of "for" in loops or comprehensions, // eg x in "for x in A" this.type = 'target_list' this.parent = context this.tree = [] this.expect = 'id' context.tree[context.tree.length]=this this.toString = function(){return '(target list) '+this.tree} this.to_js = function(){ this.js_processed=true return $to_js(this.tree) } } function $TernaryCtx(context){ // Class for the ternary operator : "x if C else y" this.type = 'ternary' this.parent = context.parent context.parent.tree.pop() context.parent.tree.push(this) context.parent = this this.tree = [context] this.toString = function(){return '(ternary) '+this.tree} this.to_js = function(){ this.js_processed=true var res = 'bool('+this.tree[1].to_js()+') ? ' // condition res += this.tree[0].to_js()+' : ' // result if true return res + this.tree[2].to_js() // result if false } } function $TryCtx(context){ // Class for the keyword "try" this.type = 'try' this.parent = context context.tree[context.tree.length]=this this.toString = function(){return '(try) '} this.transform = function(node,rank){ if(node.parent.children.length===rank+1){ $_SyntaxError(context,"missing clause after 'try' 1") }else{ var next_ctx = node.parent.children[rank+1].context.tree[0] switch(next_ctx.type) { case 'except': case 'finally': case 'single_kw': break default: $_SyntaxError(context,"missing clause after 'try' 2") } } var scope = $get_scope(this) var $var='var $failed'+$loop_num // Transform node into Javascript 'try' (necessary if // "try" inside a "for" loop) // add a boolean $failed, used to run the 'else' clause var js = $var+'=false;'+ // '$locals["$frame'+$loop_num+'"]=$B.frames_stack.slice();'+ // 'console.log("save frames", $B.last($B.frames_stack)[0]);'+ 'try' new $NodeJSCtx(node, js) node.is_try = true // used in generators // Insert new 'catch' clause var catch_node = new $Node() new $NodeJSCtx(catch_node,'catch($err'+$loop_num+')') catch_node.is_catch = true node.parent.insert(rank+1,catch_node) // Fake line to start the 'else if' clauses var new_node = new $Node() // Set the boolean $failed to true // Set attribute "pmframe" (post mortem frame) to $B in case an error // happens in a callback function ; in this case the frame would be // lost at the time the exception is handled by $B.exception new $NodeJSCtx(new_node,$var+'=true;$B.pmframe=$B.last($B.frames_stack);if(0){}') catch_node.insert(0,new_node) var pos = rank+2 var has_default = false // is there an "except:" ? var has_else = false // is there an "else" clause ? var has_finally = false while(1){ if(pos===node.parent.children.length){break} var ctx = node.parent.children[pos].context.tree[0] if(ctx.type==='except'){ // move the except clauses below catch_node if(has_else){$_SyntaxError(context,"'except' or 'finally' after 'else'")} if(has_finally){$_SyntaxError(context,"'except' after 'finally'")} ctx.error_name = '$err'+$loop_num if(ctx.tree.length>0 && ctx.tree[0].alias!==null && ctx.tree[0].alias!==undefined){ // syntax "except ErrorName as Alias" var new_node = new $Node() var alias = ctx.tree[0].alias var js = '$locals["'+alias+'"]' js += '=$B.exception($err'+$loop_num+')' new $NodeJSCtx(new_node,js) node.parent.children[pos].insert(0,new_node) } catch_node.insert(catch_node.children.length, node.parent.children[pos]) if(ctx.tree.length===0){ if(has_default){$_SyntaxError(context,'more than one except: line')} has_default=true } node.parent.children.splice(pos,1) }else if(ctx.type==='single_kw' && ctx.token==='finally'){ has_finally = true pos++ }else if(ctx.type==='single_kw' && ctx.token==='else'){ if(has_else){$_SyntaxError(context,"more than one 'else'")} if(has_finally){$_SyntaxError(context,"'else' after 'finally'")} has_else = true var else_body = node.parent.children[pos] node.parent.children.splice(pos,1) }else{break} } if(!has_default){ // If no default except clause, add a line to throw the // exception if it was not caught var new_node = new $Node(), ctx = new $NodeCtx(new_node) catch_node.insert(catch_node.children.length,new_node) new $SingleKwCtx(ctx, 'else') new_node.add($NodeJS('throw $err'+$loop_num)) } if(has_else){ var else_node = new $Node() else_node.module = scope.module new $NodeJSCtx(else_node,'if(!$failed'+$loop_num+')') for(var i=0;i<else_body.children.length;i++){ else_node.add(else_body.children[i]) } node.parent.insert(pos,else_node) pos++ } // restore frames stack as before the try clause /* var frame_node = new $Node() var js = ';$B.frames_stack = $locals["$frame'+$loop_num+'"];'+ 'console.log("restore frames", $B.last($B.frames_stack)[0]);' new $NodeJSCtx(frame_node, js) node.parent.insert(pos, frame_node) */ $loop_num++ } this.to_js = function(){ this.js_processed=true return 'try' } } function $UnaryCtx(context,op){ // Class for unary operators : - and ~ this.type = 'unary' this.op = op this.parent = context context.tree[context.tree.length]=this this.toString = function(){return '(unary) '+this.op} this.to_js = function(){ this.js_processed=true return this.op } } function $WithCtx(context){ // Class for keyword "with" this.type = 'with' this.parent = context context.tree[context.tree.length]=this this.tree = [] this.expect = 'as' this.scope = $get_scope(this) this.toString = function(){return '(with) '+this.tree} this.set_alias = function(arg){ this.tree[this.tree.length-1].alias = arg $B.bound[this.scope.id][arg] = {level: this.scope.level} $B.type[this.scope.id][arg] = false if(this.scope.ntype !== 'module'){ // add to function local names this.scope.context.tree[0].locals.push(arg) } } this.transform = function(node,rank){ while(this.tree.length>1){ /* with A() as a, B() as b: suite is equivalent to with A() as a: with B() as b: suite */ var suite = node.children, item = this.tree.pop(), new_node = new $Node(), ctx = new $NodeCtx(new_node), with_ctx = new $WithCtx(ctx) item.parent = with_ctx with_ctx.tree = [item] for(var i=0;i<suite.length;i++){ new_node.add(suite[i]) } node.children = [new_node] } /* PEP 243 says that with EXPR as VAR: BLOCK is transformed into mgr = (EXPR) exit = type(mgr).__exit__ # Not calling it yet value = type(mgr).__enter__(mgr) exc = True try: try: VAR = value # Only if "as VAR" is present BLOCK except: # The exceptional case is handled here exc = False if not exit(mgr, *sys.exc_info()): raise # The exception is swallowed if exit() returns true finally: # The normal and non-local-goto cases are handled here if exc: exit(mgr, None, None, None) */ node.is_try = true // for generators that use a context manager if(this.transformed) return // used if inside a for loop // If there are several "with" clauses, create a new child // For instance : // with x as x1, y as y1: // ... // becomes // with x as x1: // with y as y1: // ... if(this.tree.length>1){ var nw = new $Node() var ctx = new $NodeCtx(nw) nw.parent = node nw.module = node.module nw.indent = node.indent+4 var wc = new $WithCtx(ctx) wc.tree = this.tree.slice(1) for(var i=0;i<node.children.length;i++){ nw.add(node.children[i]) } node.children = [nw] this.transformed = true return } var num = this.num = $loop_num if(this.tree[0].alias===null){this.tree[0].alias = '$temp'} // Form "with (a,b,c) as (x,y,z)" if(this.tree[0].type=='expr' && this.tree[0].tree[0].type=='list_or_tuple'){ if(this.tree[1].type!='expr' || this.tree[1].tree[0].type!='list_or_tuple'){ $_SyntaxError(context) } if(this.tree[0].tree[0].tree.length!=this.tree[1].tree[0].tree.length){ $_SyntaxError(context,['wrong number of alias']) } // this.tree[1] is a list of alias for items in this.tree[0] var ids = this.tree[0].tree[0].tree var alias = this.tree[1].tree[0].tree this.tree.shift() this.tree.shift() for(var i=ids.length-1;i>=0;i--){ ids[i].alias = alias[i].value this.tree.splice(0,0,ids[i]) } } var block = node.children // the block of code to run node.children = [] var try_node = new $Node() try_node.is_try = true new $NodeJSCtx(try_node, 'try') node.add(try_node) // if there is an alias, insert the value if(this.tree[0].alias){ var alias = this.tree[0].alias var js = '$locals'+'["'+alias+'"] = $value'+num var value_node = new $Node() new $NodeJSCtx(value_node, js) try_node.add(value_node) } // place blcok inside a try clause for(var i=0;i<block.length;i++){try_node.add(block[i])} var catch_node = new $Node() catch_node.is_catch = true // for generators new $NodeJSCtx(catch_node,'catch($err'+$loop_num+')') var fbody = new $Node(), indent=node.indent+4 var js = '$exc'+num+' = false;$err'+$loop_num+'=$B.exception($err'+ $loop_num+')\n'+' '.repeat(indent)+ 'if(!bool($ctx_manager_exit'+num+'($err'+$loop_num+ '.__class__.$factory,'+'$err'+$loop_num+ ',getattr($err'+$loop_num+',"traceback"))))' js += '{throw $err'+$loop_num+'}' new $NodeJSCtx(fbody,js) catch_node.add(fbody) node.add(catch_node) var finally_node = new $Node() new $NodeJSCtx(finally_node,'finally') finally_node.context.type = 'single_kw' finally_node.context.token = 'finally' finally_node.is_except = true var fbody = new $Node() new $NodeJSCtx(fbody,'if($exc'+num+'){$ctx_manager_exit'+num+ '(None,None,None)}') finally_node.add(fbody) node.parent.insert(rank+1,finally_node) $loop_num++ this.transformed = true } this.to_js = function(){ this.js_processed=true var indent = $get_node(this).indent, h=' '.repeat(indent), num = this.num, scope = $get_scope(this) var res = 'var $ctx_manager'+num+' = '+this.tree[0].to_js()+ '\n'+h+'var $ctx_manager_exit'+num+ '= getattr($ctx_manager'+num+',"__exit__")\n'+ h+'var $value'+num+' = getattr($ctx_manager'+num+ ',"__enter__")()\n' /* if(this.tree[0].alias){ var alias = this.tree[0].alias res += h+'$locals_'+scope.id.replace(/\./g,'_') res += '["'+alias+'"] = getattr($ctx_manager'+num+ ',"__enter__")()\n' } */ res += h+'var $exc'+num+' = true\n' return res + h+'try' } } function $YieldCtx(context){ // Class for keyword "yield" this.type = 'yield' this.toString = function(){return '(yield) '+this.tree} this.parent = context this.tree = [] context.tree[context.tree.length]=this // Syntax control : 'yield' can start a 'yield expression' switch(context.type) { case 'node': break; // or start a 'yield atom' // a 'yield atom' without enclosing "(" and ")" is only allowed as the // right-hand side of an assignment case 'assign': case 'tuple': case 'list_or_tuple': // mark the node as containing a yield atom var ctx = context while(ctx.parent) ctx=ctx.parent ctx.node.yield_atoms.push(this) break; default: // else it is a SyntaxError $_SyntaxError(context,'yield atom must be inside ()') } var scope = $get_scope(this) if(!scope.is_function){ $_SyntaxError(context,["'yield' outside function"]) }else if(scope.has_return_with_arguments){ $_SyntaxError(context,["'return' with argument inside generator"]) } // Change type of function to generator var def = scope.context.tree[0] def.type = 'generator' // Add to list of "yields" in function def.yields.push(this) this.toString = function(){return '(yield) '+(this.from ? '(from) ' : '')+this.tree} this.transform = function(node, rank){ if(this.from===true){ // replace "yield from X" by "for $temp in X: yield $temp" var new_node = new $Node() node.parent.children.splice(rank,1) node.parent.insert(rank, new_node) var for_ctx = new $ForExpr(new $NodeCtx(new_node)) new $IdCtx(new $ExprCtx(for_ctx,'id',false),'$temp'+$loop_num) for_ctx.tree[1] = this.tree[0] this.tree[0].parent = for_ctx var yield_node = new $Node() new_node.add(yield_node) new $IdCtx(new $YieldCtx(new $NodeCtx(yield_node)),'$temp'+$loop_num) var ph_node = new $Node() new $NodeJSCtx(ph_node,'// placeholder for generator sent value') ph_node.set_yield_value = true new_node.add(ph_node) // apply "transform" to the newly created "for" for_ctx.transform(new_node, rank) $loop_num++ }else{ var new_node = new $Node() new $NodeJSCtx(new_node,'// placeholder for generator sent value') new_node.set_yield_value = true node.parent.insert(rank+1,new_node) } } this.to_js = function(){ this.js_processed=true //var scope = $get_scope(this) //var res = '' if(this.from===undefined) return $to_js(this.tree) || 'None' // form "yield from <expr>" : <expr> is this.tree[0] return $to_js(this.tree) } } function $add_line_num(node,rank){ if(node.type==='module'){ var i=0 while(i<node.children.length){ i += $add_line_num(node.children[i],i) } }else{ var elt=node.context.tree[0],offset=1 var flag = true var pnode = node while(pnode.parent!==undefined){pnode=pnode.parent} var mod_id = pnode.id // ignore lines added in transform() if(node.line_num===undefined){flag=false} // Don't add line num before try,finally,else,elif // because it would throw a syntax error in Javascript if(elt.type==='condition' && elt.token==='elif'){flag=false} else if(elt.type==='except'){flag=false} else if(elt.type==='single_kw'){flag=false} if(flag){ // add a trailing None for interactive mode var js=';$locals.$line_info="'+node.line_num+','+mod_id+'";' var new_node = new $Node() new $NodeJSCtx(new_node,js) node.parent.insert(rank,new_node) offset = 2 } var i=0 while(i<node.children.length) i+=$add_line_num(node.children[i],i) // At the end of a "while" or "for" loop body, add a line to reset // line number to that of the "while" or "for" loop (cf issue #281) if((elt.type=='condition' && elt.token=="while") || node.context.type=='for'){ node.add($NodeJS('$locals.$line_info="'+node.line_num+','+ mod_id+'";')) } return offset } } function $bind(name, scope_id, level){ // Bind a name in scope_id if($B.bound[scope_id][name]!==undefined){ // If the name is already bound, use the smallest level if(level>=$B.bound[scope_id][name].level){ $B.bound[scope_id][name].level = level } }else{ $B.bound[scope_id][name] = {level: level} } } function $previous(context){ var previous = context.node.parent.children[context.node.parent.children.length-2] if(!previous || !previous.context){ $_SyntaxError(context, 'keyword not following correct keyword') } return previous.context.tree[0] } function $get_docstring(node){ var doc_string='' if(node.children.length>0){ var firstchild = node.children[0] if(firstchild.context.tree && firstchild.context.tree[0].type=='expr'){ if(firstchild.context.tree[0].tree[0].type=='str') doc_string = firstchild.context.tree[0].tree[0].to_js() } } return doc_string } function $get_scope(context){ // Return the instance of $Node indicating the scope of context // Return null for the root node var ctx_node = context.parent while(ctx_node.type!=='node'){ctx_node=ctx_node.parent} var tree_node = ctx_node.node, scope = null, level = 1 while(tree_node.parent && tree_node.parent.type!=='module'){ var ntype = tree_node.parent.context.tree[0].type switch (ntype) { case 'def': case 'class': case 'generator': var scope = tree_node.parent scope.ntype = ntype scope.is_function = ntype!='class' scope.level = level return scope } tree_node = tree_node.parent level++ } var scope = tree_node.parent || tree_node // module scope.ntype = "module" scope.level = level return scope } function $get_module(context){ // Return the instance of $Node for the module where context // is defined var ctx_node = context.parent while(ctx_node.type!=='node'){ctx_node=ctx_node.parent} var tree_node = ctx_node.node var scope = null while(tree_node.parent.type!=='module'){ tree_node = tree_node.parent } var scope = tree_node.parent // module scope.ntype = "module" return scope } function $get_node(context){ var ctx = context while(ctx.parent){ctx=ctx.parent} return ctx.node } function $get_blocks(name, scope){ var res = [] while(true){ if($B.bound[scope.id][name]!==undefined){res.push(scope.id)} if(scope.parent_block){ if(scope.parent_block.id=='__builtins__'){ if(scope.blurred){return false} } }else{break} scope = scope.parent_block } return res } function $set_type(scope, expr, value){ // If expr is an id, set its type if we can extract something from value if(expr.type=='expr'){expr=expr.tree[0]} while(value.type=='expr' && value.tree.length==1){value=value.tree[0]} if(value.type=='list_or_tuple' && value.real=='tuple' && value.tree.length==1){ return $set_type(scope.id, expr, value.tree[0]) } if($B.type[scope.id]===undefined){return} if(expr.type=="id"){ switch(value.type){ case 'int': case 'str': $B.type[scope.id][expr.value] = value.type return case 'list_or_tuple': case 'dict_or_set': $B.type[scope.id][expr.value] = value.real return case 'id': $B.type[scope.id][expr.value] = $B.type[scope.id][value.value] return case 'call': var func_name = value.func.value if($B.bound.__builtins__[func_name]!==undefined){ var blocks = $get_blocks(func_name, scope) if(blocks.length==1 && blocks[0]=='__builtins__'){ switch(func_name){ case 'int': case 'list': case 'str': $B.type[scope.id][expr.value] = func_name return } } } break default: break } } $B.type[scope.id][expr.value] = false } function $ws(n){ return ' '.repeat(n) } function $to_js_map(tree_element) { if (tree_element.to_js !== undefined) return tree_element.to_js() throw Error('no to_js() for '+tree_element) } function $to_js(tree,sep){ if(sep===undefined){sep=','} return tree.map($to_js_map).join(sep) } // expression starters var $expr_starters = ['id','imaginary','int','float','str','bytes','[','(','{','not','lambda'] function $arbo(ctx){ while(ctx.parent!=undefined){ctx=ctx.parent} return ctx } // Function called in function $tokenise for each token found in the // Python source code function $transition(context,token){ //console.log('context '+context+' token '+token, arguments[2]) switch(context.type) { case 'abstract_expr': switch(token) { case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case '.': case 'not': case 'lambda': case 'yield': context.parent.tree.pop() // remove abstract expression var commas = context.with_commas context = context.parent } switch(token) { case 'id': return new $IdCtx(new $ExprCtx(context,'id',commas),arguments[2]) case 'str': return new $StringCtx(new $ExprCtx(context,'str',commas),arguments[2]) case 'bytes': return new $StringCtx(new $ExprCtx(context,'bytes',commas),arguments[2]) case 'int': return new $IntCtx(new $ExprCtx(context,'int',commas),arguments[2]) case 'float': return new $FloatCtx(new $ExprCtx(context,'float',commas),arguments[2]) case 'imaginary': return new $ImaginaryCtx(new $ExprCtx(context,'imaginary',commas),arguments[2]) case '(': return new $ListOrTupleCtx(new $ExprCtx(context,'tuple',commas),'tuple') case '[': return new $ListOrTupleCtx(new $ExprCtx(context,'list',commas),'list') case '{': return new $DictOrSetCtx(new $ExprCtx(context,'dict_or_set',commas)) case '.': return new $EllipsisCtx(new $ExprCtx(context,'ellipsis',commas)) case 'not': if(context.type==='op'&&context.op==='is'){ // "is not" context.op = 'is_not' return context } return new $NotCtx(new $ExprCtx(context,'not',commas)) case 'lambda': return new $LambdaCtx(new $ExprCtx(context,'lambda',commas)) case 'op': var tg = arguments[2] switch(tg) { case '*': context.parent.tree.pop() // remove abstract expression var commas = context.with_commas context = context.parent return new $PackedCtx(new $ExprCtx(context,'expr',commas)) case '-': case '~': case '+': // create a left argument for operator "unary" context.parent.tree.pop() var left = new $UnaryCtx(context.parent,tg) // create the operator "unary" if(tg=='-'){var op_expr = new $OpCtx(left,'unary_neg')} else if(tg=='+'){var op_expr = new $OpCtx(left,'unary_pos')} else{var op_expr = new $OpCtx(left,'unary_inv')} return new $AbstractExprCtx(op_expr,false) case 'not': context.parent.tree.pop() // remove abstract expression var commas = context.with_commas context = context.parent return new $NotCtx(new $ExprCtx(context,'not',commas)) } $_SyntaxError(context,'token '+token+' after '+context) case '=': $_SyntaxError(context,token) case 'yield': return new $AbstractExprCtx(new $YieldCtx(context),true) case ':': return $transition(context.parent,token,arguments[2]) case ')': case ',': switch(context.parent.type) { case 'list_or_tuple': case 'call_arg': case 'op': case 'yield': break default: $_SyntaxError(context,token) }// switch }// switch return $transition(context.parent,token,arguments[2]) case 'annotation': return $transition(context.parent, token) case 'assert': if(token==='eol') return $transition(context.parent,token) $_SyntaxError(context,token) case 'assign': if(token==='eol'){ if(context.tree[1].type=='abstract_expr'){ $_SyntaxError(context,'token '+token+' after '+context) } // If left is an id, update binding to the type of right operand context.guess_type() return $transition(context.parent,'eol') } $_SyntaxError(context,'token '+token+' after '+context) case 'attribute': if(token==='id'){ var name = arguments[2] if(noassign[name]===true){$_SyntaxError(context, ["cannot assign to "+name])} context.name=name return context.parent } $_SyntaxError(context,token) case 'augm_assign': if(token==='eol'){ if(context.tree[1].type=='abstract_expr'){ $_SyntaxError(context,'token '+token+' after '+context) } return $transition(context.parent,'eol') } $_SyntaxError(context,'token '+token+' after '+context) case 'break': if(token==='eol') return $transition(context.parent,'eol') $_SyntaxError(context,token) case 'call': switch(token) { case ',': if(context.expect=='id'){$_SyntaxError(context, token)} return context case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case '.': case 'not': case 'lambda': if(context.has_dstar) $_SyntaxError(context,token) context.expect = ',' return $transition(new $CallArgCtx(context),token,arguments[2]) case ')': context.end=$pos return context.parent case 'op': context.expect = ',' switch(arguments[2]) { case '-': case '~': case '+': context.expect = ',' return $transition(new $CallArgCtx(context),token,arguments[2]) case '*': context.has_star = true; return new $StarArgCtx(context) case '**': context.has_dstar = true return new $DoubleStarArgCtx(context) } //switch(arguments[2]) throw Error('SyntaxError') } //switch (token) return $transition(context.parent,token,arguments[2]) case 'call_arg': switch(token) { case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case '.': case 'not': case 'lambda': if(context.expect === 'id') { context.expect=',' var expr = new $AbstractExprCtx(context,false) return $transition(expr,token,arguments[2]) } break case '=': if (context.expect===',') { return new $ExprCtx(new $KwArgCtx(context),'kw_value',false) } break case 'for': // comprehension var lst = new $ListOrTupleCtx(context,'gen_expr') lst.vars = context.vars // copy variables lst.locals = context.locals lst.intervals = [context.start] context.tree.pop() lst.expression = context.tree context.tree = [lst] lst.tree = [] var comp = new $ComprehensionCtx(lst) return new $TargetListCtx(new $CompForCtx(comp)) case 'op': if (context.expect === 'id') { var op = arguments[2] context.expect = ',' switch(op) { case '+': case '-': case '~': return $transition(new $AbstractExprCtx(context,false),token,op) case '*': return new $StarArgCtx(context) case '**': return new $DoubleStarArgCtx(context) }//switch } $_SyntaxError(context,'token '+token+' after '+context) case ')': if(context.parent.kwargs && $B.last(context.parent.tree).tree[0] && // if call ends with ,) ['kwarg','star_arg','double_star_arg'].indexOf($B.last(context.parent.tree).tree[0].type)==-1){ $_SyntaxError(context, ['non-keyword arg after keyword arg']) } if(context.tree.length>0){ var son = context.tree[context.tree.length-1] if(son.type==='list_or_tuple'&&son.real==='gen_expr'){ son.intervals.push($pos) } } return $transition(context.parent,token) case ':': if (context.expect ===',' && context.parent.parent.type==='lambda') { return $transition(context.parent.parent,token) } break case ',': if (context.expect===',') { if(context.parent.kwargs && ['kwarg','star_arg', 'double_star_arg'].indexOf($B.last(context.parent.tree).tree[0].type)==-1){ console.log('err2') $_SyntaxError(context, ['non-keyword arg after keyword arg']) } //return new $CallArgCtx(context.parent) return $transition(context.parent, token, arguments[2]) } console.log('context '+context+'token '+token+' expect '+context.expect) }// switch $_SyntaxError(context,'token '+token+' after '+context) case 'class': switch(token) { case 'id': if (context.expect === 'id') { context.set_name(arguments[2]) context.expect = '(:' return context } break case '(': return new $CallCtx(context) case ':': return $BodyCtx(context) }//switch $_SyntaxError(context,'token '+token+' after '+context) case 'comp_if': return $transition(context.parent,token,arguments[2]) case 'comp_for': if(token==='in' && context.expect==='in'){ context.expect = null return new $AbstractExprCtx(new $CompIterableCtx(context),true) } if(context.expect===null){ // ids in context.tree[0] are local to the comprehension return $transition(context.parent,token,arguments[2]) } $_SyntaxError(context,'token '+token+' after '+context) case 'comp_iterable': return $transition(context.parent,token,arguments[2]) case 'comprehension': switch(token) { case 'if': return new $AbstractExprCtx(new $CompIfCtx(context),false) case 'for': return new $TargetListCtx(new $CompForCtx(context)) } return $transition(context.parent,token,arguments[2]) case 'condition': if(token===':') return $BodyCtx(context) $_SyntaxError(context,'token '+token+' after '+context) case 'continue': if(token=='eol') return context.parent $_SyntaxError(context,'token '+token+' after '+context) case 'ctx_manager_alias': switch(token){ case ',': case ':': return $transition(context.parent, token, arguments[2]) } $_SyntaxError(context,'token '+token+' after '+context) case 'decorator': if(token==='id' && context.tree.length===0){ return $transition(new $AbstractExprCtx(context,false),token,arguments[2]) } if(token==='eol') { return $transition(context.parent,token) } $_SyntaxError(context,'token '+token+' after '+context) case 'def': switch(token) { case 'id': if(context.name) { $_SyntaxError(context,'token '+token+' after '+context) } context.set_name(arguments[2]) return context case '(': if(context.name===null){ $_SyntaxError(context,'token '+token+' after '+context) } context.has_args=true; return new $FuncArgs(context) case 'annotation': return new $AbstractExprCtx(new $AnnotationCtx(context), true) case ':': if(context.has_args) return $BodyCtx(context) }//switch $_SyntaxError(context,'token '+token+' after '+context) case 'del': if(token==='eol') return $transition(context.parent,token) $_SyntaxError(context,'token '+token+' after '+context) case 'dict_or_set': if(context.closed){ switch(token) { case '[': return new $SubCtx(context.parent) case '(': return new $CallArgCtx(new $CallCtx(context)) case 'op': return new $AbstractExprCtx(new $OpCtx(context,arguments[2]),false) } return $transition(context.parent,token,arguments[2]) }else{ if(context.expect===','){ switch(token) { case '}': switch(context.real) { case 'dict_or_set': if (context.tree.length !== 1) break context.real='set' // is this needed? case 'set': case 'set_comp': case 'dict_comp': context.items = context.tree context.tree = [] context.closed = true return context case 'dict': if (context.tree.length%2 === 0) { context.items = context.tree context.tree = [] context.closed = true return context } }//switch $_SyntaxError(context,'token '+token+' after '+context) case ',': if(context.real==='dict_or_set'){context.real='set'} if(context.real==='dict' && context.tree.length%2){ $_SyntaxError(context,'token '+token+' after '+context) } context.expect = 'id' return context case ':': if(context.real==='dict_or_set'){context.real='dict'} if(context.real==='dict'){ context.expect=',' return new $AbstractExprCtx(context,false) }else{$_SyntaxError(context,'token '+token+' after '+context)} case 'for': // comprehension if(context.real==='dict_or_set'){context.real = 'set_comp'} else{context.real='dict_comp'} var lst = new $ListOrTupleCtx(context,'dict_or_set_comp') lst.intervals = [context.start+1] lst.vars = context.vars context.tree.pop() lst.expression = context.tree context.tree = [lst] lst.tree = [] var comp = new $ComprehensionCtx(lst) return new $TargetListCtx(new $CompForCtx(comp)) } //switch(token) $_SyntaxError(context,'token '+token+' after '+context) }else if(context.expect==='id'){ switch(token) { case '}': if(context.tree.length==0){ // empty dict context.items = [] context.real = 'dict' }else{ // trailing comma, eg {'a':1,'b':2,} context.items = context.tree } context.tree = [] context.closed = true return context case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case '.': case 'not': case 'lambda': context.expect = ',' var expr = new $AbstractExprCtx(context,false) return $transition(expr,token,arguments[2]) case 'op': switch(arguments[2]) { case '+': // ignore unary + return context case '-': case '~': // create a left argument for operator "unary" context.expect = ',' var left = new $UnaryCtx(context,arguments[2]) // create the operator "unary" if(arguments[2]=='-'){var op_expr = new $OpCtx(left,'unary_neg')} else if(arguments[2]=='+'){var op_expr = new $OpCtx(left,'unary_pos')} else{var op_expr = new $OpCtx(left,'unary_inv')} return new $AbstractExprCtx(op_expr,false) }//switch $_SyntaxError(context,'token '+token+' after '+context) } //switch $_SyntaxError(context,'token '+token+' after '+context) } return $transition(context.parent,token,arguments[2]) } break case 'double_star_arg': switch(token) { case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case '.': case 'not': case 'lambda': return $transition(new $AbstractExprCtx(context,false),token,arguments[2]) case ',': return context.parent case ')': return $transition(context.parent,token) case ':': if (context.parent.parent.type==='lambda'){ return $transition(context.parent.parent,token) } } $_SyntaxError(context,'token '+token+' after '+context) case 'ellipsis': if(token=='.'){context.nbdots++;return context} else{ if(context.nbdots!=3){ $pos--;$_SyntaxError(context,'token '+token+' after '+context) }else{ return $transition(context.parent, token, arguments[2]) } } case 'except': switch(token) { case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case 'not': case 'lamdba': if (context.expect === 'id') { context.expect = 'as' return $transition(new $AbstractExprCtx(context,false),token,arguments[2]) } case 'as': // only one alias allowed if (context.expect === 'as' && context.has_alias===undefined){ context.expect = 'alias' context.has_alias = true return context } case 'id': if (context.expect === 'alias') { context.expect=':' context.set_alias(arguments[2]) return context } break case ':': var _ce=context.expect if (_ce == 'id' || _ce == 'as' || _ce == ':') { return $BodyCtx(context) } break case '(': if (context.expect === 'id' && context.tree.length ===0) { context.parenth = true return context } break case ')': if (context.expect == ',' || context.expect == 'as') { context.expect = 'as' return context } case ',': if (context.parenth!==undefined && context.has_alias === undefined && (context.expect == 'as' || context.expect == ',')) { context.expect='id' return context } }// switch $_SyntaxError(context,'token '+token+' after '+context.expect) case 'expr': switch(token) { case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case 'lamdba': $_SyntaxError(context,'token '+token+' after '+context) break case '[': case '(': case '{': case '.': case 'not': if(context.expect==='expr'){ context.expect = ',' return $transition(new $AbstractExprCtx(context,false),token,arguments[2]) } } switch(token) { case 'not': if (context.expect === ',') return new $ExprNot(context) break case 'in': if(context.parent.type=='target_list'){ // expr used for target list return $transition(context.parent, token) } if(context.expect===',') return $transition(context,'op','in') break case ',': if(context.expect===','){ if(context.with_commas){ // implicit tuple context.parent.tree.pop() var tuple = new $ListOrTupleCtx(context.parent,'tuple') tuple.implicit = true tuple.has_comma = true tuple.tree = [context] context.parent = tuple return tuple } } return $transition(context.parent,token) case '.': return new $AttrCtx(context) case '[': return new $AbstractExprCtx(new $SubCtx(context),true) case '(': return new $CallCtx(context) case 'op': // handle operator precedence var op_parent=context.parent,op=arguments[2] // conditional expressions have the lowest priority if(op_parent.type=='ternary' && op_parent.in_else){ var new_op = new $OpCtx(context,op) return new $AbstractExprCtx(new_op,false) } var op1 = context.parent,repl=null while(1){ if(op1.type==='expr'){op1=op1.parent} else if(op1.type==='op' &&$op_weight[op1.op]>=$op_weight[op] && !(op1.op=='**' && op=='**') // cf. issue #250 ){ repl=op1;op1=op1.parent }else if(op1.type=="not" && $op_weight['not']>$op_weight[op]){ repl=op1;op1=op1.parent }else{break} } if(repl===null){ while(1){ if(context.parent!==op1){ context = context.parent op_parent = context.parent }else{ break } } context.parent.tree.pop() var expr = new $ExprCtx(op_parent,'operand',context.with_commas) expr.expect = ',' context.parent = expr var new_op = new $OpCtx(context,op) return new $AbstractExprCtx(new_op,false) }else{ // issue #371 if(op === 'and' || op === 'or'){ while(repl.parent.type==='not'|| (repl.parent.type==='expr'&&repl.parent.parent.type==='not')){ // 'and' and 'or' have higher precedence than 'not' repl = repl.parent op_parent = repl.parent } } } if(repl.type==='op') { var _flag=false switch(repl.op) { case '<': case '<=': case '==': case '!=': case 'is': case '>=': case '>': _flag=true }//switch if (_flag) { switch(op) { case '<': case '<=': case '==': case '!=': case 'is': case '>=': case '>': // chained comparisons such as c1 <= c2 < c3 // replace by (c1 op1 c2) and (c2 op c3) // save c2 var c2 = repl.tree[1] // right operand of op1 // clone c2 var c2_clone = new Object() for(var attr in c2){c2_clone[attr]=c2[attr]} // If there are consecutive chained comparisons // we must go up to the uppermost 'and' operator while(repl.parent && repl.parent.type=='op'){ if($op_weight[repl.parent.op]<$op_weight[repl.op]){ repl = repl.parent }else{break} } repl.parent.tree.pop() // Create a new 'and' operator, with the left operand // equal to c1 <= c2 var and_expr = new $OpCtx(repl,'and') c2_clone.parent = and_expr // For compatibility with the interface of $OpCtx, // add a fake element to and_expr : it will be removed // when new_op is created at the next line and_expr.tree.push('xxx') var new_op = new $OpCtx(c2_clone,op) return new $AbstractExprCtx(new_op,false) }// switch }// if _flag } repl.parent.tree.pop() var expr = new $ExprCtx(repl.parent,'operand',false) expr.tree = [op1] repl.parent = expr var new_op = new $OpCtx(repl,op) // replace old operation return new $AbstractExprCtx(new_op,false) case 'augm_assign': if(context.expect===','){ return new $AbstractExprCtx(new $AugmentedAssignCtx(context,arguments[2]),true) } break case '=': if(context.expect===','){ if(context.parent.type==="call_arg"){ return new $AbstractExprCtx(new $KwArgCtx(context),true) }else if(context.parent.type=="annotation"){ return $transition(context.parent.parent, token, arguments[2]) } while(context.parent!==undefined){ context=context.parent if(context.type=='condition'){ $_SyntaxError(context,'token '+token+' after '+context) } } context = context.tree[0] return new $AbstractExprCtx(new $AssignCtx(context),true) } break case 'if': if(context.parent.type!=='comp_iterable'){ // Ternary operator : "expr1 if cond else expr2" // If the part before "if" is an operation, apply operator // precedence // Example : print(1+n if n else 0) var ctx = context while(ctx.parent && ctx.parent.type=='op'){ ctx=ctx.parent if(ctx.type=='expr' && ctx.parent && ctx.parent.type=='op'){ ctx=ctx.parent } } return new $AbstractExprCtx(new $TernaryCtx(ctx),false) } }//switch return $transition(context.parent,token) case 'expr_not': if(token=='in'){ // expr not in : operator context.parent.tree.pop() return new $AbstractExprCtx(new $OpCtx(context.parent,'not_in'),false) } $_SyntaxError(context,'token '+token+' after '+context) case 'for': switch(token) { case 'in': return new $AbstractExprCtx(new $ExprCtx(context,'target list', true),false) case ':': return $BodyCtx(context) } $_SyntaxError(context,'token '+token+' after '+context) case 'from': switch(token) { case 'id': if(context.expect=='id'){ context.add_name(arguments[2]) context.expect = ',' return context } if(context.expect==='alias'){ context.aliases[context.names[context.names.length-1]]= arguments[2] context.expect=',' return context } case '.': if(context.expect=='module'){ if(token=='id'){context.module += arguments[2]} else{context.module += '.'} return context } case 'import': context.blocking = token=='import' if(context.expect=='module'){ context.expect = 'id' return context } case 'op': if(arguments[2]=='*' && context.expect=='id' && context.names.length ==0){ if($get_scope(context).ntype!=='module'){ $_SyntaxError(context,["import * only allowed at module level"]) } context.add_name('*') context.expect = 'eol' return context } case ',': if(context.expect==','){ context.expect = 'id' return context } case 'eol': switch(context.expect) { case ',': case 'eol': context.bind_names() return $transition(context.parent,token) default: $_SyntaxError(context,['trailing comma not allowed without surrounding parentheses']) } case 'as': if (context.expect ==',' || context.expect=='eol'){ context.expect='alias' return context } case '(': if (context.expect == 'id') { context.expect='id' return context } case ')': if (context.expect == ',' || context.expect=='id') { context.expect='eol' return context } } $_SyntaxError(context,'token '+token+' after '+context) case 'func_arg_id': switch(token) { case '=': if (context.expect==='='){ context.parent.has_default = true var def_ctx = context.parent.parent if(context.parent.has_star_arg){ def_ctx.default_list.push(def_ctx.after_star.pop()) }else{ def_ctx.default_list.push(def_ctx.positional_list.pop()) } return new $AbstractExprCtx(context,false) } break case ',': case ')': if(context.parent.has_default && context.tree.length==0 && context.parent.has_star_arg===undefined){ console.log('parent '+context.parent, context.parent) $pos -= context.name.length $_SyntaxError(context,['non-default argument follows default argument']) }else{ return $transition(context.parent,token) } case ':': // annotation associated with a function parameter return new $AbstractExprCtx(new $AnnotationCtx(context), false) } $_SyntaxError(context,'token '+token+' after '+context) case 'func_args': switch (token) { case 'id': if (context.expect==='id'){ context.expect = ',' if(context.names.indexOf(arguments[2])>-1){ $_SyntaxError(context,['duplicate argument '+arguments[2]+' in function definition']) } } return new $FuncArgIdCtx(context,arguments[2]) case ',': if(context.has_kw_arg) $_SyntaxError(context,'duplicate kw arg') if(context.expect===','){ context.expect = 'id' return context } $_SyntaxError(context,'token '+token+' after '+context) case ')': return context.parent case 'op': var op = arguments[2] context.expect = ',' if(op=='*'){ if(context.has_star_arg){$_SyntaxError(context,'duplicate star arg')} return new $FuncStarArgCtx(context,'*') } if(op=='**') return new $FuncStarArgCtx(context,'**') $_SyntaxError(context,'token '+op+' after '+context) }//switch $_SyntaxError(context,'token '+token+' after '+context) case 'func_star_arg': switch(token) { case 'id': if (context.name===undefined){ if(context.parent.names.indexOf(arguments[2])>-1){ $_SyntaxError(context,['duplicate argument '+arguments[2]+' in function definition']) } } context.set_name(arguments[2]) context.parent.names.push(arguments[2]) return context //.parent case ',': case ')': if (context.name===undefined){ // anonymous star arg - found in configparser context.set_name('$dummy') context.parent.names.push('$dummy') } return $transition(context.parent,token) case ':': // annotation associated with a function parameter if(context.name===undefined){ $_SyntaxError(context, 'annotation on an unnamed parameter') } return new $AbstractExprCtx(new $AnnotationCtx(context), false) }// switch $_SyntaxError(context,'token '+token+' after '+context) case 'global': switch(token) { case 'id': if (context.expect==='id'){ new $IdCtx(context,arguments[2]) context.add(arguments[2]) context.expect=',' return context } break case ',': if (context.expect===','){ context.expect='id' return context } break case 'eol': if (context.expect===','){ return $transition(context.parent,token) } break } // switch $_SyntaxError(context,'token '+token+' after '+context) case 'id': switch(token) { case '=': if(context.parent.type==='expr' && context.parent.parent !== undefined && context.parent.parent.type ==='call_arg'){ return new $AbstractExprCtx(new $KwArgCtx(context.parent),false) } return $transition(context.parent,token,arguments[2]) case 'op': return $transition(context.parent,token,arguments[2]) case 'id': case 'str': case 'int': case 'float': case 'imaginary': $_SyntaxError(context,'token '+token+' after '+context) } return $transition(context.parent,token,arguments[2]) case 'import': switch(token) { case 'id': if (context.expect==='id'){ new $ImportedModuleCtx(context,arguments[2]) context.expect=',' return context } if (context.expect==='qual'){ context.expect = ',' context.tree[context.tree.length-1].name += '.'+arguments[2] context.tree[context.tree.length-1].alias += '.'+arguments[2] return context } if (context.expect==='alias'){ context.expect = ',' context.tree[context.tree.length-1].alias = arguments[2] return context } break case '.': if (context.expect===','){ context.expect = 'qual' return context } break case ',': if (context.expect===','){ context.expect = 'id' return context } break case 'as': //}else if(token==='as' && if (context.expect===','){ context.expect = 'alias' return context } break case 'eol': if (context.expect===','){ context.bind_names() return $transition(context.parent,token) } break }//switch $_SyntaxError(context,'token '+token+' after '+context) case 'imaginary': case 'int': case 'float': switch(token) { case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case 'not': case 'lamdba': $_SyntaxError(context,'token '+token+' after '+context) } return $transition(context.parent,token,arguments[2]) case 'kwarg': if(token===',') return new $CallArgCtx(context.parent.parent) return $transition(context.parent,token) case 'lambda': if(token===':' && context.args===undefined){ context.args = context.tree context.tree = [] context.body_start = $pos return new $AbstractExprCtx(context,false) } if(context.args!==undefined){ // returning from expression context.body_end = $pos return $transition(context.parent,token) } if(context.args===undefined){ return $transition(new $CallCtx(context),token,arguments[2]) } $_SyntaxError(context,'token '+token+' after '+context) case 'list_or_tuple': if(context.closed){ if(token==='[') return new $SubCtx(context.parent) if(token==='(') return new $CallCtx(context) return $transition(context.parent,token,arguments[2]) }else{ if(context.expect===','){ switch(context.real) { case 'tuple': case 'gen_expr': if (token===')'){ context.closed = true if(context.real==='gen_expr'){context.intervals.push($pos)} return context.parent } break case 'list': case 'list_comp': if (token===']'){ context.closed = true if(context.real==='list_comp'){context.intervals.push($pos)} return context } break case 'dict_or_set_comp': if (token==='}'){ context.intervals.push($pos) return $transition(context.parent,token) } break } switch(token) { case ',': if(context.real==='tuple'){context.has_comma=true} context.expect = 'id' return context case 'for': // comprehension if(context.real==='list'){context.real = 'list_comp'} else{context.real='gen_expr'} // remove names already referenced in list from the function // references context.intervals = [context.start+1] context.expression = context.tree context.tree = [] // reset tree var comp = new $ComprehensionCtx(context) return new $TargetListCtx(new $CompForCtx(comp)) }//switch return $transition(context.parent,token,arguments[2]) }else if(context.expect==='id'){ switch(context.real) { case 'tuple': if (token===')'){ context.closed = true return context.parent } if (token=='eol' && context.implicit===true){ context.closed = true return $transition(context.parent,token) } break case 'gen_expr': if (token===')'){ context.closed = true return $transition(context.parent,token) } break case 'list': if (token===']'){ context.closed = true return context } break }// switch switch(token) { case '=': if (context.real=='tuple' && context.implicit===true){ context.closed = true context.parent.tree.pop() var expr=new $ExprCtx(context.parent,'tuple',false) expr.tree=[context] context.parent=expr return $transition(context.parent,token) } break case ')': break case ']': if(context.real=='tuple' && context.implicit===true){ // Syntax like d[1,]=2 return $transition(context.parent, token, arguments[2]) }else{ break } case ',': $_SyntaxError(context,'unexpected comma inside list') default: context.expect = ',' var expr = new $AbstractExprCtx(context,false) return $transition(expr,token,arguments[2]) }//switch }else{return $transition(context.parent,token,arguments[2])} } case 'list_comp': switch(token) { case ']': return context.parent case 'in': return new $ExprCtx(context,'iterable',true) case 'if': return new $ExprCtx(context,'condition',true) } $_SyntaxError(context,'token '+token+' after '+context) case 'node': switch(token) { case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case 'not': case 'lamdba': case '.': var expr = new $AbstractExprCtx(context,true) return $transition(expr,token,arguments[2]) case 'op': switch(arguments[2]) { case '*': case '+': case '-': case '~': var expr = new $AbstractExprCtx(context,true) return $transition(expr,token,arguments[2]) }// switch break case 'class': return new $ClassCtx(context) case 'continue': return new $ContinueCtx(context) case '__debugger__': return new $DebuggerCtx(context) case 'break': return new $BreakCtx(context) case 'def': return new $DefCtx(context) case 'for': return new $TargetListCtx(new $ForExpr(context)) case 'if': case 'while': return new $AbstractExprCtx(new $ConditionCtx(context,token),false) case 'elif': var previous = $previous(context) if(['condition'].indexOf(previous.type)==-1 || previous.token=='while'){ $_SyntaxError(context, 'elif after '+previous.type) } return new $AbstractExprCtx(new $ConditionCtx(context,token),false) case 'else': var previous = $previous(context) if(['condition', 'except', 'for'].indexOf(previous.type)==-1){ $_SyntaxError(context, 'else after '+previous.type) } return new $SingleKwCtx(context,token) case 'finally': var previous = $previous(context) if(['try', 'except'].indexOf(previous.type)==-1 && (previous.type!='single_kw' || previous.token!='else')){ $_SyntaxError(context, 'finally after '+previous.type) } return new $SingleKwCtx(context,token) case 'try': return new $TryCtx(context) case 'except': var previous = $previous(context) if(['try', 'except'].indexOf(previous.type)==-1){ $_SyntaxError(context, 'except after '+previous.type) } return new $ExceptCtx(context) case 'assert': return new $AbstractExprCtx(new $AssertCtx(context),'assert',true) case 'from': return new $FromCtx(context) case 'import': return new $ImportCtx(context) case 'global': return new $GlobalCtx(context) case 'nonlocal': return new $NonlocalCtx(context) case 'lambda': return new $LambdaCtx(context) case 'pass': return new $PassCtx(context) case 'raise': return new $RaiseCtx(context) case 'return': return new $AbstractExprCtx(new $ReturnCtx(context),true) case 'with': return new $AbstractExprCtx(new $WithCtx(context),false) case 'yield': return new $AbstractExprCtx(new $YieldCtx(context),true) case 'del': return new $AbstractExprCtx(new $DelCtx(context),true) case '@': return new $DecoratorCtx(context) case 'eol': if(context.tree.length===0){ // might be the case after a : context.node.parent.children.pop() return context.node.parent.context } return context } $_SyntaxError(context,'token '+token+' after '+context) case 'not': switch(token) { case 'in': // not is always in an expression : remove it context.parent.parent.tree.pop() // remove 'not' return new $ExprCtx(new $OpCtx(context.parent,'not_in'),'op',false) case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case '.': case 'not': case 'lamdba': var expr = new $AbstractExprCtx(context,false) return $transition(expr,token,arguments[2]) case 'op': var a=arguments[2] if ('+' == a || '-' == a || '~' == a) { var expr = new $AbstractExprCtx(context,false) return $transition(expr,token,arguments[2]) } }//switch return $transition(context.parent,token) case 'op': if(context.op===undefined){ $_SyntaxError(context,['context op undefined '+context]) } if(context.op.substr(0,5)=='unary'){ if(context.parent.type=='assign' || context.parent.type=='return'){ // create and return a tuple whose first element is context context.parent.tree.pop() var t = new $ListOrTupleCtx(context.parent,'tuple') t.tree.push(context) context.parent = t return t } } switch(token) { case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case '.': case 'not': case 'lamdba': return $transition(new $AbstractExprCtx(context,false),token,arguments[2]) case 'op': switch(arguments[2]) { case '+': case '-': case '~': return new $UnaryCtx(context,arguments[2]) }//switch default: if(context.tree[context.tree.length-1].type=='abstract_expr'){ $_SyntaxError(context,'token '+token+' after '+context) } }// switch var t0=context.tree[0], t1=context.tree[1] if(t0.tree && t1.tree){ t0 = t0.tree[0] t1 = t1.tree[0] } return $transition(context.parent,token) case 'packed': if(token==='id'){ new $IdCtx(context,arguments[2]) context.parent.expect = ',' return context.parent } $_SyntaxError(context,'token '+token+' after '+context) case 'pass': if(token==='eol') return context.parent $_SyntaxError(context,'token '+token+' after '+context) case 'raise': switch(token) { case 'id': if (context.tree.length===0){ return new $IdCtx(new $ExprCtx(context,'exc',false),arguments[2]) } break case 'from': if (context.tree.length>0){ return new $AbstractExprCtx(context,false) } break case 'eol': //if(token==='eol') return $transition(context.parent,token) }//switch $_SyntaxError(context,'token '+token+' after '+context) case 'return': var no_args = context.tree[0].type=='abstract_expr' // if 'return' has an agument inside a generator, raise a SyntaxError if(!no_args){ var scope = $get_scope(context) if(scope.ntype=='generator'){ $_SyntaxError(context,["'return' with argument inside generator"]) } // If the function is a generator but no 'yield' has been handled // yet, store the information that function has a return with // arguments, to throw the SyntaxError when the 'yield' is handled scope.has_return_with_arguments = true } return $transition(context.parent,token) case 'single_kw': if(token===':') return $BodyCtx(context) $_SyntaxError(context,'token '+token+' after '+context) case 'star_arg': switch(token) { case 'id': if(context.parent.type=="target_list"){ context.tree.push(arguments[2]) context.parent.expect = ',' console.log('return parent', context.parent) return context.parent } return $transition(new $AbstractExprCtx(context,false),token,arguments[2]) case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case 'not': case 'lamdba': return $transition(new $AbstractExprCtx(context,false),token,arguments[2]) case ',': return $transition(context.parent,token) case ')': return $transition(context.parent,token) case ':': if(context.parent.parent.type==='lambda'){ return $transition(context.parent.parent,token) } } //switch $_SyntaxError(context,'token '+token+' after '+context) case 'str': switch(token) { case '[': return new $AbstractExprCtx(new $SubCtx(context.parent),false) case '(': // Strings are not callable. We replace the string by a call to // an object that will raise the correct exception context.parent.tree[0] = context return new $CallCtx(context.parent) case 'str': context.tree.push(arguments[2]) return context }//switch return $transition(context.parent,token,arguments[2]) case 'sub': // subscription x[a] or slicing x[a:b:c] switch(token) { case 'id': case 'imaginary': case 'int': case 'float': case 'str': case 'bytes': case '[': case '(': case '{': case '.': case 'not': case 'lamdba': var expr = new $AbstractExprCtx(context,false) return $transition(expr,token,arguments[2]) case ']': return context.parent case ':': if(context.tree.length==0){ new $AbstractExprCtx(context,false) } return new $AbstractExprCtx(context,false) } $_SyntaxError(context,'token '+token+' after '+context) case 'target_list': switch(token) { case 'id': if(context.expect==='id'){ context.expect = ',' return new $IdCtx(new $ExprCtx(context, 'target', false),arguments[2]) } case 'op': if(context.expect=='id' && arguments[2]=='*'){ // form "for a, *b in X" return new $PackedCtx(context) } case '(': case '[': if(context.expect==='id'){ context.expect = ',' return new $TargetListCtx(context) } case ')': case ']': if(context.expect===',') return context.parent case ',': if(context.expect==','){ context.expect='id' return context } } //switch if(context.expect===',') { return $transition(context.parent,token,arguments[2]) }else if(token=='in'){ // Support syntax "for x, in ..." return $transition(context.parent,token,arguments[2]) } $_SyntaxError(context,'token '+token+' after '+context) case 'ternary': if(token==='else'){ context.in_else = true return new $AbstractExprCtx(context,false) } return $transition(context.parent,token,arguments[2]) case 'try': if(token===':') return $BodyCtx(context) $_SyntaxError(context,'token '+token+' after '+context) case 'unary': switch(token) { case 'int': case 'float': case 'imaginary': // replace by real value of integer or float // parent of context is a $ExprCtx // grand-parent is a $AbstractExprCtx // we remove the $ExprCtx and trigger a transition // from the $AbstractExpCtx with an integer or float // of the correct value console.log(token,arguments[2],'after',context) var expr = context.parent context.parent.parent.tree.pop() var value = arguments[2] if(context.op==='-'){value="-"+value} else if(context.op==='~'){value=~value} return $transition(context.parent.parent,token,value) case 'id': // replace by x.__neg__(), x.__invert__ or x.__pos__ context.parent.parent.tree.pop() var expr = new $ExprCtx(context.parent.parent,'call',false) var expr1 = new $ExprCtx(expr,'id',false) new $IdCtx(expr1,arguments[2]) // create id if (true){ //context.op !== '+'){ var repl = new $AttrCtx(expr) if(context.op==='+'){repl.name='__pos__'} else if(context.op==='-'){repl.name='__neg__'} else{repl.name='__invert__'} // method is called with no argument var call = new $CallCtx(expr) // new context is the expression above the id return expr1 } return context.parent case 'op': if ('+' == arguments[2] || '-' == arguments[2]) { var op = arguments[2] if(context.op===op){context.op='+'}else{context.op='-'} return context } } //switch return $transition(context.parent,token,arguments[2]) case 'with': switch(token) { case 'id': if(context.expect==='id'){ context.expect = 'as' return $transition(new $AbstractExprCtx(context,false),token,arguments[2]) } if(context.expect==='alias'){ if(context.parenth!==undefined){context.expect = ','} else{context.expect=':'} context.set_alias(arguments[2]) return context } break case 'as': return new $AbstractExprCtx(new $AliasCtx(context)) case ':': switch(context.expect) { case 'id': case 'as': case ':': return $BodyCtx(context) } break case '(': if(context.expect==='id' && context.tree.length===0){ context.parenth = true return context }else if(context.expect=='alias'){ console.log('context', context, 'token', token) context.expect = ':' return new $TargetListCtx(context,false) } break case ')': if (context.expect == ',' || context.expect == 'as') { context.expect = ':' return context } break case ',': if(context.parenth!==undefined && context.has_alias === undefined && (context.expect == ',' || context.expect == 'as')) { context.expect='id' return context }else if(context.expect=='as'){ context.expect = 'id' return context }else if(context.expect==':'){ context.expect = 'id' return context } break }//switch $_SyntaxError(context,'token '+token+' after '+context.expect) case 'yield': if(token=='from'){ // form "yield from <expr>" if(context.tree[0].type!='abstract_expr'){ // 'from' must follow immediately "from" $_SyntaxError(context,"'from' must follow 'yield'") } context.from = true context.tree = [] return new $AbstractExprCtx(context, true) } return $transition(context.parent,token) } // switch(context.type) } $B.forbidden = ['case','catch','constructor','Date','delete', 'default','enum','eval','extends','Error','history','function','location', 'Math','new','null','Number','RegExp','super','this','throw','var', 'toString'] var s_escaped = 'abfnrtvxuU"'+"'"+'\\', is_escaped={} for(var i=0;i<s_escaped.length;i++){is_escaped[s_escaped.charAt(i)]=true} function $tokenize(src,module,locals_id,parent_block_id,line_info){ var delimiters = [["#","\n","comment"],['"""','"""',"triple_string"], ["'","'","string"],['"','"',"string"], ["r'","'","raw_string"],['r"','"',"raw_string"]] var br_open = {"(":0,"[":0,"{":0} var br_close = {")":"(","]":"[","}":"{"} var br_stack = "" var br_pos = [] var kwdict = ["class","return","break", "for","lambda","try","finally","raise","def","from", "nonlocal","while","del","global","with", "as","elif","else","if","yield","assert","import", "except","raise","in", //"not", "pass","with","continue","__debugger__" //"False","None","True","continue", // "and',"or","is" ] var unsupported = [] var $indented = ['class','def','for','condition','single_kw','try','except','with'] // from https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Reserved_Words var punctuation = {',':0,':':0}, int_pattern = new RegExp("^\\d+(j|J)?"), float_pattern1 = new RegExp("^\\d+\\.\\d*([eE][+-]?\\d+)?(j|J)?"), float_pattern2 = new RegExp("^\\d+([eE][+-]?\\d+)(j|J)?"), hex_pattern = new RegExp("^0[xX]([0-9a-fA-F]+)"), octal_pattern = new RegExp("^0[oO]([0-7]+)"), binary_pattern = new RegExp("^0[bB]([01]+)"), id_pattern = new RegExp("[\\$_a-zA-Z]\\w*"), qesc = new RegExp('"',"g"), // escape double quotes sqesc = new RegExp("'","g") // escape single quotes var context = null var root = new $Node('module') root.module = module root.id = locals_id $B.modules[root.id] = root if(locals_id==parent_block_id){ root.parent_block = $B.modules[parent_block_id].parent_block || $B.modules['__builtins__'] }else{ root.parent_block = $B.modules[parent_block_id] || $B.modules['__builtins__'] } root.line_info = line_info root.indent = -1 if(locals_id!==module){$B.bound[locals_id] = {}} var new_node = new $Node(), current = root, name = "", _type = null, pos = 0, indent = null, string_modifier = false var lnum = 1 while(pos<src.length){ var flag = false var car = src.charAt(pos) // build tree structure from indentation if(indent===null){ var indent = 0 while(pos<src.length){ var _s=src.charAt(pos) if(_s==" "){indent++;pos++} else if(_s=="\t"){ // tab : fill until indent is multiple of 8 indent++;pos++ if(indent%8>0) indent+=8-indent%8 }else{break} } // ignore empty lines var _s=src.charAt(pos) if(_s=='\n'){pos++;lnum++;indent=null;continue} else if(_s==='#'){ // comment var offset = src.substr(pos).search(/\n/) if(offset===-1){break} pos+=offset+1;lnum++;indent=null;continue } new_node.indent = indent new_node.line_num = lnum new_node.module = module // attach new node to node with indentation immediately smaller if(indent>current.indent){ // control that parent ended with ':' if(context!==null){ if($indented.indexOf(context.tree[0].type)==-1){ $pos = pos $_SyntaxError(context,'unexpected indent',pos) } } // add a child to current node current.add(new_node) }else if(indent<=current.indent && $indented.indexOf(context.tree[0].type)>-1 && context.tree.length<2){ $pos = pos $_SyntaxError(context,'expected an indented block',pos) }else{ // same or lower level while(indent!==current.indent){ current = current.parent if(current===undefined || indent>current.indent){ $pos = pos $_SyntaxError(context,'unexpected indent',pos) } } current.parent.add(new_node) } current = new_node context = new $NodeCtx(new_node) continue } // comment if(car=="#"){ var end = src.substr(pos+1).search('\n') if(end==-1){end=src.length-1} pos += end+1;continue } // string if(car=='"' || car=="'"){ var raw = context.type == 'str' && context.raw, bytes = false , end = null; if(string_modifier){ switch(string_modifier) { case 'r': // raw string raw = true break case 'u': // in string literals, '\U' and '\u' escapes in raw strings // are not treated specially. break case 'b': bytes = true break case 'rb': case 'br': bytes=true;raw=true break } string_modifier = false } if(src.substr(pos,3)==car+car+car){_type="triple_string";end=pos+3} else{_type="string";end=pos+1} var escaped = false var zone = car var found = false while(end<src.length){ if(escaped){ zone+=src.charAt(end) if(raw && src.charAt(end)=='\\'){zone+='\\'} escaped=false;end+=1 }else if(src.charAt(end)=="\\"){ if(raw){ if(end<src.length-1 && src.charAt(end+1)==car){ zone += '\\\\'+car end += 2 }else{ zone += '\\\\' end++ } escaped = true } else { if(src.charAt(end+1)=='\n'){ // explicit line joining inside strings end += 2 lnum++ } else { if(end < src.length-1 && is_escaped[src.charAt(end+1)]==undefined){ zone += '\\' } zone+='\\' escaped=true;end+=1 } } } else if(src.charAt(end)=='\n' && _type!='triple_string'){ // In a string with single quotes, line feed not following // a backslash raises SyntaxError $pos = end $_SyntaxError(context, ["EOL while scanning string literal"]) } else if(src.charAt(end)==car){ if(_type=="triple_string" && src.substr(end,3)!=car+car+car){ zone += src.charAt(end) end++ } else { found = true // end of string $pos = pos // Escape quotes inside string, except if they are already escaped // In raw mode, always escape var $string = zone.substr(1),string='' for(var i=0;i<$string.length;i++){ var $car = $string.charAt(i) if($car==car && (raw || (i==0 || $string.charAt(i-1)!=='\\'))){ string += '\\' } string += $car } if(bytes){ context = $transition(context,'str','b'+car+string+car) }else{ context = $transition(context,'str',car+string+car) } context.raw = raw; pos = end+1 if(_type=="triple_string"){pos = end+3} break } } else { zone += src.charAt(end) if(src.charAt(end)=='\n'){lnum++} end++ } } if(!found){ if(_type==="triple_string"){ $_SyntaxError(context,"Triple string end not found") }else{ $_SyntaxError(context,"String end not found") } } continue } // identifier ? if(name=="" && car!='$'){ // regexIdentifier is defined in brython_builtins.js. It is a regular // expression that matches all the valid Python identifier names, // including those in non-latin writings (cf issue #358) if($B.regexIdentifier.exec(car)){ name=car // identifier start var p0=pos pos++ while(pos<src.length && $B.regexIdentifier.exec(src.substring(p0, pos+1))){ name+=src.charAt(pos) pos++ } } if(name){ //pos += name.length if(kwdict.indexOf(name)>-1){ $pos = pos-name.length if(unsupported.indexOf(name)>-1){ $_SyntaxError(context,"Unsupported Python keyword '"+name+"'") } context = $transition(context,name) } else if($operators[name]!==undefined && $B.forbidden.indexOf(name)==-1) { // Literal operators : "and", "or", "is", "not" // The additional test is to exclude the name "constructor" if(name=='is'){ // if keyword is "is", see if it is followed by "not" var re = /^\s+not\s+/ var res = re.exec(src.substr(pos)) if(res!==null){ pos += res[0].length $pos = pos-name.length context = $transition(context,'op','is_not') }else{ $pos = pos-name.length context = $transition(context,'op', name) } }else if(name=='not'){ // if keyword is "not", see if it is followed by "in" var re = /^\s+in\s+/ var res = re.exec(src.substr(pos)) if(res!==null){ pos += res[0].length $pos = pos-name.length context = $transition(context,'op','not_in') }else{ $pos = pos-name.length context = $transition(context,name) } }else{ $pos = pos-name.length context = $transition(context,'op',name) } } else if((src.charAt(pos)=='"'||src.charAt(pos)=="'") && ['r','b','u','rb','br'].indexOf(name.toLowerCase())!==-1){ string_modifier = name.toLowerCase() name = "" continue } else { if($B.forbidden.indexOf(name)>-1){name='$$'+name} $pos = pos-name.length context = $transition(context,'id',name) } name="" continue } } switch(car) { case ' ': case '\t': pos++ break case '.': // point, ellipsis (...) if(pos<src.length-1 && /^\d$/.test(src.charAt(pos+1))){ // number starting with . : add a 0 before the point var j = pos+1 while(j<src.length && src.charAt(j).search(/\d|e|E/)>-1){j++} context = $transition(context,'float','0'+src.substr(pos,j-pos)) pos = j break } $pos = pos context = $transition(context,'.') pos++ break case '0': // octal, hexadecimal, binary //if(car==="0"){ var res = hex_pattern.exec(src.substr(pos)) if(res){ context=$transition(context,'int',[16,res[1]]) pos += res[0].length break } var res = octal_pattern.exec(src.substr(pos)) if(res){ context=$transition(context,'int',[8,res[1]]) //parseInt(res[1],8)) pos += res[0].length break } var res = binary_pattern.exec(src.substr(pos)) if(res){ context=$transition(context,'int',[2,res[1]]) //parseInt(res[1],2)) pos += res[0].length break } // literal like "077" is not valid in Python3 if(src.charAt(pos+1).search(/\d/)>-1){ // literal like "000" is valid in Python3 if(parseInt(src.substr(pos)) === 0){ res = int_pattern.exec(src.substr(pos)) $pos = pos context = $transition(context,'int',[10,res[0]]) pos += res[0].length break }else{$_SyntaxError(context,('invalid literal starting with 0'))} } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': // digit var res = float_pattern1.exec(src.substr(pos)) if(res){ $pos = pos if(res[2]!==undefined){ context = $transition(context,'imaginary', res[0].substr(0,res[0].length-1)) }else{context = $transition(context,'float',res[0])} }else{ res = float_pattern2.exec(src.substr(pos)) if(res){ $pos =pos if(res[2]!==undefined){ context = $transition(context,'imaginary', res[0].substr(0,res[0].length-1)) }else{context = $transition(context,'float',res[0])} }else{ res = int_pattern.exec(src.substr(pos)) $pos = pos if(res[1]!==undefined){ context = $transition(context,'imaginary', res[0].substr(0,res[0].length-1)) }else{context = $transition(context,'int',[10,res[0]])} } } pos += res[0].length break case '\n': // line end lnum++ if(br_stack.length>0){ // implicit line joining inside brackets pos++;//continue } else { if(current.context.tree.length>0){ $pos = pos context = $transition(context,'eol') indent=null new_node = new $Node() }else{ new_node.line_num = lnum } pos++ } break case '(': case '[': case '{': br_stack += car br_pos[br_stack.length-1] = [context,pos] $pos = pos context = $transition(context,car) pos++ break case ')': case ']': case '}': if(br_stack==""){ $_SyntaxError(context,"Unexpected closing bracket") } else if(br_close[car]!=br_stack.charAt(br_stack.length-1)){ $_SyntaxError(context,"Unbalanced bracket") } else { br_stack = br_stack.substr(0,br_stack.length-1) $pos = pos context = $transition(context,car) pos++ } break case '=': if(src.charAt(pos+1)!="="){ $pos = pos context = $transition(context,'=') pos++; //continue } else { $pos = pos context = $transition(context,'op','==') pos+=2 } break case ',': case ':': $pos = pos context = $transition(context,car) pos++ break case ';': $transition(context,'eol') // close previous instruction // create a new node, at the same level as current's parent if(current.context.tree.length===0){ // consecutive ; are not allowed $pos=pos $_SyntaxError(context,'invalid syntax') } // if ; ends the line, ignore it var pos1 = pos+1 var ends_line = false while(pos1<src.length){ var _s=src.charAt(pos1) if(_s=='\n' || _s=='#'){ends_line=true;break} else if(_s==' '){pos1++} else{break} } if(ends_line){pos++;break} new_node = new $Node() new_node.indent = $get_node(context).indent new_node.line_num = lnum new_node.module = module $get_node(context).parent.add(new_node) current = new_node context = new $NodeCtx(new_node) pos++ break case '/': case '%': case '&': case '>': case '<': case '-': case '+': case '*': case '/': case '^': case '=': case '|': case '~': case '!': //case 'i': //case 'n': // operators // special case for annotation syntax if(car=='-' && src.charAt(pos+1)=='>'){ context = $transition(context,'annotation') pos += 2 continue } // find longest match var op_match = "" for(var op_sign in $operators){ if(op_sign==src.substr(pos,op_sign.length) && op_sign.length>op_match.length){ op_match=op_sign } } //if(car=='!'){alert('op_match '+op_match)} $pos = pos if(op_match.length>0){ if(op_match in $augmented_assigns){ context = $transition(context,'augm_assign',op_match) }else{ context = $transition(context,'op',op_match) } pos += op_match.length }else{ $_SyntaxError(context,'invalid character: '+car) } break case '\\': if (src.charAt(pos+1)=='\n'){ lnum++ pos+=2 break } case '@': $pos = pos context = $transition(context,car) pos++ break default: $pos=pos;$_SyntaxError(context,'unknown token ['+car+']') } //switch } if(br_stack.length!=0){ var br_err = br_pos[0] $pos = br_err[1] $_SyntaxError(br_err[0],["Unbalanced bracket "+br_stack.charAt(br_stack.length-1)]) } if(context!==null && $indented.indexOf(context.tree[0].type)>-1){ $pos = pos-1 $_SyntaxError(context,'expected an indented block',pos) } return root } $B.py2js = function(src, module, locals_id, parent_block_id, line_info){ // src = Python source (string) // module = module name (string) // locals_id = the id of the block that will be created // parent_block_id = the id of the block where the code is created // line_info = [line_num, parent_block_id] if debug mode is set // create_ns = boolean to create a namespace for locals_id (used in exec) // // Returns a tree structure representing the Python source code var t0 = new Date().getTime() // Normalise line ends and script end src = src.replace(/\r\n/gm,'\n') if(src.charAt(src.length-1)!="\n"){src+='\n'} var locals_is_module = Array.isArray(locals_id) if(locals_is_module){ locals_id = locals_id[0] } var internal = locals_id.charAt(0)=='$' var local_ns = '$locals_'+locals_id.replace(/\./g,'_') var global_ns = '$locals_'+module.replace(/\./g,'_') $B.bound[module] = $B.bound[module] || {} // Internal variables must be defined before tokenising, otherwise // references to these names would generate a NameError $B.bound[module]['__doc__'] = true $B.bound[module]['__name__'] = true $B.bound[module]['__file__'] = true $B.type[module] = $B.type[module] || {} $B.type[locals_id] = $B.type[locals_id] || {} $B.$py_src[locals_id] = $B.$py_src[locals_id] || src var root = $tokenize(src,module,locals_id,parent_block_id,line_info) root.transform() // Create internal variables var js = ['var $B = __BRYTHON__;\n'], pos=1 js[pos++]='eval(__BRYTHON__.InjectBuiltins());\n\n' js[pos] = 'var ' if(locals_is_module){ js[pos] += local_ns+'=$locals_'+module+', ' }else if(!internal){ js[pos] += local_ns+'=$B.imported["'+locals_id+'"] || {}, ' } js[pos]+='$locals='+local_ns+';' var offset = 0 root.insert(0, $NodeJS(js.join(''))) offset++ // module doc string var ds_node = new $Node() new $NodeJSCtx(ds_node, local_ns+'["__doc__"]='+(root.doc_string||'None')+';') root.insert(offset++,ds_node) // name var name_node = new $Node() var lib_module = module new $NodeJSCtx(name_node,local_ns+'["__name__"]='+local_ns+'["__name__"] || "'+locals_id+'";') root.insert(offset++,name_node) // file var file_node = new $Node() new $NodeJSCtx(file_node,local_ns+'["__file__"]="'+$B.$py_module_path[module]+'";None;\n') root.insert(offset++,file_node) var enter_frame_pos = offset root.insert(offset++, $NodeJS('$B.enter_frame(["'+locals_id+'", '+local_ns+','+ '"'+module+'", '+global_ns+']);\n')) // Wrap code in a try/finally to make sure we leave the frame var try_node = new $Node(), children = root.children.slice(enter_frame_pos+1, root.children.length), ctx = new $NodeCtx(try_node) root.insert(enter_frame_pos+1, try_node) new $TryCtx(ctx) // Add module body to the "try" clause if(children.length==0){children=[$NodeJS('')]} // in case the script is empty for(var i=0;i<children.length;i++){ try_node.add(children[i]) } root.children.splice(enter_frame_pos+2, root.children.length) var finally_node = new $Node(), ctx = new $NodeCtx(finally_node) new $SingleKwCtx(ctx, 'finally') finally_node.add($NodeJS('$B.leave_frame("'+locals_id+'")')) root.add(finally_node) if($B.debug>0){$add_line_num(root,null,module)} if($B.debug>=2){ var t1 = new Date().getTime() console.log('module '+module+' translated in '+(t1 - t0)+' ms') } return root } function load_scripts(scripts, run_script, onerror){ // Loads and runs the scripts in the order they are placed in the page // Script can be internal (code inside the <script></script> tag) or // external (<script src="external_script.py"></script>) if (run_script === undefined) { run_script = $B._run_script; } // Callback function when an external script is loaded function callback(ev, script){ var ok = false, skip = false; if (ev !== null) { req = ev.target if(req.readyState==4){ if(req.status==200){ ok = true; script = {name:req.module_name, url:req.responseURL, src:req.responseText}; } } else { // AJAX request with readyState !== 4 => NOP skip = true; } } else { // All data is supplied in script arg ok = true; } if (skip) { return; } if (ok) { try { run_script(script) } catch (e) { if (onerror === undefined) { throw e; } else { onerror(e); } } if(scripts.length>0){ load_scripts(scripts) } }else{ try { throw Error("cannot load script "+ req.module_name+' at '+req.responseURL+ ': error '+req.status) } catch (e) { if (onerror === undefined) { throw e; } else { onerror(e); } } } } var noajax = true // Loop for efficient usage of the calling stack (faster than recursion?) while(scripts.length>0 && noajax){ var script = scripts.shift() if(script['src']===undefined){ // External script : load it by an Ajax call noajax = false; var req = new XMLHttpRequest() req.onreadystatechange = callback req.module_name = script.name req.open('GET', script.url, true) req.send() }else{ // Internal script : execute it callback(null, script) load_scripts(scripts) } } } $B._load_scripts = load_scripts; function run_script(script){ // script has attributes url, src, name $B.$py_module_path[script.name]=script.url try{ // Conversion of Python source code to Javascript var $root = $B.py2js(script.src,script.name,script.name,'__builtins__') var $js = $root.to_js() if($B.debug>1){console.log($js)} // Run resulting Javascript eval($js) $B.imported[script.name] = $locals }catch($err){ if($B.debug>1){ console.log($err) for(var attr in $err){ console.log(attr+' : ', $err[attr]) } } // If the error was not caught by the Python runtime, build an // instance of a Python exception if($err.$py_error===undefined){ console.log('Javascript error', $err) //console.log($js) //for(var attr in $err){console.log(attr+': '+$err[attr])} $err=_b_.RuntimeError($err+'') } // Print the error traceback on the standard error stream var name = $err.__name__ var $trace = _b_.getattr($err,'info')+'\n'+name+': ' if(name=='SyntaxError' || name=='IndentationError'){ $trace += $err.args[0] }else{$trace += $err.args} try{ _b_.getattr($B.stderr,'write')($trace) }catch(print_exc_err){ console.log($trace) } // Throw the error to stop execution throw $err }finally{ $B.clear_ns(script.name) } } $B._run_script = run_script; function brython(options){ var _b_=$B.builtins // meta_path used in py_import.js if ($B.meta_path === undefined) { $B.meta_path = [] } // Options passed to brython(), with default values $B.$options= {} // By default, only set debug level if(options===undefined) options={'debug':0} // If the argument provided to brython() is a number, it is the debug // level if(typeof options==='number') options={'debug':options} if(options.debug === undefined) { options.debug = 0 } $B.debug = options.debug // set built-in variable __debug__ _b_.__debug__ = $B.debug>0 // For imports, default mode is to search modules of the standard library // using a static mapping stored in stdlib_paths.js // This can be disabled by setting option "static_stdlib_import" to false if(options.static_stdlib_import===undefined){options.static_stdlib_import=true} $B.static_stdlib_import = options.static_stdlib_import // If options has an attribute "open", it will be used by the built-in // function open() - see py_builtin_functions.js if (options.open !== undefined) { _b_.open = options.open; console.log("DeprecationWarning: \'open\' option of \'brython\' function will be deprecated in future versions of Brython."); } $B.$options=options // Set $B.meta_path, the list of finders to use for imports // // The original list in $B.meta_path is made of 3 finders defined in // py_import.js : // - finder_VFS : in the Virtual File System : a Javascript object with // source of the standard distribution // - finder_static_stlib : use the script stdlib_path.js to identify the // packages and modules in the standard distribution // - finder_path : search module at different urls var meta_path = [] var path_hooks = [] // $B.use_VFS is set to true if the script py_VFS.js or brython_dist.js // has been loaded in the page. In this case we use the VFS if($B.use_VFS){ meta_path.push($B.$meta_path[0]) path_hooks.push($B.$path_hooks[0]) } if(options.static_stdlib_import!==false){ // Add finder using static paths meta_path.push($B.$meta_path[1]) // Remove /Lib and /libs in sys.path : // if we use the static list and the module // was not find in it, it's no use searching twice in the same place if($B.path.length>3) { $B.path.shift() $B.path.shift() } } // Always use the defaut finder using sys.path meta_path.push($B.$meta_path[2]) $B.meta_path = meta_path path_hooks.push($B.$path_hooks[1]) $B.path_hooks = path_hooks // Option to run code on demand and not all the scripts defined in a page // The following lines are included to allow to run brython scripts in // the IPython/Jupyter notebook using a cell magic. Have a look at // https://github.com/kikocorreoso/brythonmagic for more info. if(options.ipy_id!==undefined){ var $elts = []; for(var $i=0;$i<options.ipy_id.length;$i++){ $elts.push(document.getElementById(options.ipy_id[$i])); } }else{ var scripts=document.getElementsByTagName('script'),$elts=[] // Freeze the list of scripts here ; other scripts can be inserted on // the fly by viruses for(var i=0;i<scripts.length;i++){ var script = scripts[i] if(script.type=="text/python" || script.type=="text/python3"){ $elts.push(script) } } } // URL of the script where function brython() is called var $href = $B.script_path = window.location.href var $href_elts = $href.split('/') $href_elts.pop() // List of URLs where imported modules should be searched // A list can be provided as attribute of options if (options.pythonpath!==undefined) $B.path = options.pythonpath // Allow user to specify the re module they want to use as a default // Valid values are 'pyre' for pythons re module and // 'jsre' for brythons customized re module // Default is for brython to guess which to use by looking at // complexity of the re pattern if (options.re_module !==undefined) { if (options.re_module == 'pyre' || options.re_module=='jsre') { $B.$options.re=options.re } console.log("DeprecationWarning: \'re_module\' option of \'brython\' function will be deprecated in future versions of Brython.") } $B.scripts = [] $B.js = {} // maps script name to JS conversion // Save initial Javascript namespace var kk = Object.keys(window) // Get all links with rel=pythonpath and add them to sys.path var path_links = document.querySelectorAll('head link[rel~=pythonpath]'), _importlib = $B.modules['_importlib']; for (var i=0, e; e = path_links[i]; ++i) { var href = e.href; $B.path.push(href); if (href.slice(-7).toLowerCase() == '.vfs.js' && (' ' + e.rel + ' ').indexOf(' prefetch ') != -1) { // Prefetch VFS file $B.path_importer_cache[href + '/'] = $B.imported['_importlib'].VFSPathFinder(href) } var filetype = e.hreflang; if (filetype) { if (filetype.slice(0,2) == 'x-') filetype = filetype.slice(2); _importlib.optimize_import_for_path(e.href, filetype); } } // Get all scripts with type = text/python or text/python3 and run them var first_script = true, module_name; if(options.ipy_id!==undefined){ module_name='__main__'; var $src = ""; $B.$py_module_path[module_name] = $href; for(var $i=0;$i<$elts.length;$i++){ var $elt = $elts[$i]; $src += ($elt.innerHTML || $elt.textContent); } try{ // Conversion of Python source code to Javascript var $root = $B.py2js($src,module_name,module_name,'__builtins__') //earney var $js = $root.to_js() if($B.debug>1) console.log($js) if ($B.async_enabled) { $js = $B.execution_object.source_conversion($js) //console.log($js) eval($js) } else { // Run resulting Javascript eval($js) } }catch($err){ if($B.debug>1){ console.log($err) for(var attr in $err){ console.log(attr+' : ', $err[attr]) } } // If the error was not caught by the Python runtime, build an // instance of a Python exception if($err.$py_error===undefined){ console.log('Javascript error', $err) //console.log($js) //for(var attr in $err){console.log(attr+': '+$err[attr])} $err=_b_.RuntimeError($err+'') } // Print the error traceback on the standard error stream var $trace = _b_.getattr($err,'info')+'\n'+$err.__name__+ ': ' +$err.args try{ _b_.getattr($B.stderr,'write')($trace) }catch(print_exc_err){ console.log($trace) } // Throw the error to stop execution throw $err } }else{ // Get all explicitely defined ids, to avoid overriding var defined_ids = {} for(var i=0;i<$elts.length;i++){ var elt = $elts[i] if(elt.id){ if(defined_ids[elt.id]){ throw Error("Brython error : Found 2 scripts with the same id '"+ elt.id+"'") }else{ defined_ids[elt.id] = true } } } var scripts = [] for(var $i=0;$i<$elts.length;$i++){ var $elt = $elts[$i] if($elt.type=="text/python"||$elt.type==="text/python3"){ if($elt.id){module_name=$elt.id} else{ if(first_script){module_name='__main__'; first_script=false} else{module_name = '__main__'+$B.UUID()} while(defined_ids[module_name]!==undefined){ module_name = '__main__'+$B.UUID() } } $B.scripts.push(module_name) // Get Python source code var $src = null if($elt.src){ // format <script type="text/python" src="python_script.py"> // get source code by an Ajax call scripts.push({name:module_name, url:$elt.src}) }else{ // Get source code inside the script element var $src = ($elt.innerHTML || $elt.textContent) $B.$py_module_path[module_name] = $href scripts.push({name: module_name, src: $src, url: $href}) } } } } /* load_ext(ext_scripts) for(var i=0;i<inner_scripts.length;i++){ run_script(inner_scripts[i]) } */ if (options.ipy_id === undefined){$B._load_scripts(scripts)} /* Uncomment to check the names added in global Javascript namespace var kk1 = Object.keys(window) for (var i=0; i < kk1.length; i++){ if(kk[i]===undefined){ console.log(kk1[i]) } } */ } $B.$operators = $operators $B.$Node = $Node $B.$NodeJSCtx = $NodeJSCtx // in case the name 'brython' is used in a Javascript library, // we can use $B.brython $B.brython = brython })(__BRYTHON__) var brython = __BRYTHON__.brython
John-Boik/Principled-Societies-Project
leddaApp/static/brython/src/py2js.js
JavaScript
gpl-3.0
289,505
var zoomBox; var navHistory = new OpenLayers.Control.NavigationHistory(); var zoomToContextExtent; var featureInfo; var featureInfo1; var featureInfo2; var featureInfo3; var featureInfo4; var measureControls; //************** New client var zoomBoxIn = new OpenLayers.Control.ZoomBox({out: false}); var zoomBoxOut = new OpenLayers.Control.ZoomBox({out: true}); var queryEventHandler1; // Spectrum var queryEventHandler2; // Spectral ratio var queryEventHandler3; // Cross section var queryEventHandler4; // Elevation Point var loadedProduct = false; // execute maximum zoom function mapZoomMaximum() { map.zoomToExtent(maxextent); // maxextent initialized in planetmap.js } // zoom map in and zoom map out /*function mapZoomInOut(inout) { switch(inout) { case 'in': map.zoomIn(); break; case 'out': map.zoomOut(); break; } }*/ //*************** End - New client function handleMeasurements(event) { //var geometry = event.geometry; var units = event.units; var order = event.order; var measure = event.measure; /*** Commented by swingit *** var element = document.getElementById('mapOutput'); var out = ""; // vincenty constants modified to use mars constants, OpenLayers.js line 242 if(order == 1) { out += "Distance: " + measure.toFixed(3) + " " + units; // distance can be fixed simply by using geodesic: true } else { out += "<span class='mapAreaOutput'>Area: " + measure.toFixed(3) + " " + units + "<sup style='font-size:6px'>2</" + "sup></span>"; // area fix inside OpenLayers.js line 870, replaced earth radius by mars radius } element.innerHTML = out; *** Commented by swingit (end) ***/ // added on 23-09-2013 if(order == 1) { Ext.getCmp('labelShowStatus').setText("Distance: " + measure.toFixed(3) + " " + units); } else { Ext.getCmp('labelShowStatus').update("Area: " + measure.toFixed(3) + " " + units + "<sup>2</sup>"); } } function toggleQueryMode1() { if(featureInfo1.active) { queryEventHandler1.activate(); } else { queryEventHandler1.deactivate(); } } function toggleQueryMode2() { if(featureInfo2.active) { queryEventHandler2.activate(); } else { queryEventHandler2.deactivate(); } } function toggleQueryMode3() { if(featureInfo3.active) { queryEventHandler3.activate(); } else { queryEventHandler3.deactivate(); } } function toggleQueryMode4() { if(featureInfo4.active) { queryEventHandler4.activate(); } else { queryEventHandler4.deactivate(); } } function setLocationHashFromPixel(pixel) { lonlat = map.getLonLatFromPixel(pixel); hashKeys['lat'] = lonlat.lat; hashKeys['lon'] = lonlat.lon; hashKeys['region'] = getRegion(lonlat); hashKeys['productid'] = getProduct(lonlat); } function isZoomEvent() { return (map.getZoom() != hashKeys['zoomlevel']); } function initmapevents() { map.events.register("mousemove", map, function(e) { setLocationHashFromPixel(new OpenLayers.Pixel(e.xy.x,e.xy.y)); setLocationHash(); }); map.events.register("mouseout", map, function(e) { location.hash = ""; }); map.events.register("move", map, function(e) { if (isZoomEvent()) // zoom { hashKeys['zoomlevel'] = map.getZoom(); var productid = hashKeys['productid']; if (productid == "") { loadedProduct = false; setLocationHash(); } else if (!iscodezoomevent && !loadedProduct) { loadmrdr(productid); loadedProduct = true; } } }); map.addControl(zoomBoxIn); map.addControl(zoomBoxOut); zoomBox = new OpenLayers.Control.ZoomBox({ title: "Zoom in box" }); /*navHistory = new OpenLayers.Control.NavigationHistory(); navHistory.previous.title = "View history backward"; navHistory.next.title = "View history forward";*/ map.addControl(navHistory); // build the Select functionality featureInfo = new OpenLayers.Control({ displayClass: "olControlFeatureInfo", title: "Select" }); /* // register events to the featureInfo tool featureInfo.events.register("activate", featureInfo, function() { highlightCtrl.activate(); selectCtrl.activate(); }); featureInfo.events.register("deactivate", featureInfo, function() { highlightCtrl.deactivate(); selectCtrl.deactivate(); }); */ // build the Spectrum functionality featureInfo1 = new OpenLayers.Control({ displayClass: "olControlFeatureInfo1", title: "Spectrum" }); // register events to the spectrum tool featureInfo1.events.register("activate", featureInfo1, function() { toggleQueryMode1(); }); featureInfo1.events.register("deactivate", featureInfo1, function() { toggleQueryMode1(); }); // build the spectral ratio functionality featureInfo2 = new OpenLayers.Control({ displayClass: "olControlFeatureInfo2", title: "Spectral ratio" }); // register events to the Spectral ratio tool featureInfo2.events.register("activate", featureInfo2, function() { toggleQueryMode2(); }); featureInfo2.events.register("deactivate", featureInfo2, function() { toggleQueryMode2(); }); // build the cross functionality featureInfo3 = new OpenLayers.Control({ displayClass: "olControlFeatureInfo3", title: "Cross section" }); // register events to the cross tool featureInfo3.events.register("activate", featureInfo3, function() { toggleQueryMode3(); }); featureInfo3.events.register("deactivate", featureInfo3, function() { toggleQueryMode3(); }); // build the cross functionality featureInfo4 = new OpenLayers.Control({ displayClass: "olControlFeatureInfo4", title: "Elevation point" }); // register events to the cross tool featureInfo4.events.register("activate", featureInfo4, function() { toggleQueryMode4(); }); featureInfo4.events.register("deactivate", featureInfo4, function() { toggleQueryMode4(); }); zoomToContextExtent = new OpenLayers.Control.Button({ title: "Full scale", displayClass: "olControlZoomToMaxExtent", trigger: function(){ map.zoomToExtent(maxextent); } }); // build the measure controls var optionsLine = { handlerOptions: { persist: true }, displayClass: "olControlMeasureDistance", title: "Measure Distance" }; var optionsPolygon = { handlerOptions: { persist: true }, displayClass: "olControlMeasureArea", title: "Measure Area" }; measureControls = { line: new OpenLayers.Control.Measure( OpenLayers.Handler.Path, optionsLine ), polygon: new OpenLayers.Control.Measure( OpenLayers.Handler.Polygon, optionsPolygon ) }; for(var key in measureControls) { control = measureControls[key]; control.geodesic = true; // set true to use geodesic coordinates //control.setImmediate(true); // set true to immediately compute the area/length as soon as the mouse is moved control.events.on({ "measure": handleMeasurements, "measurepartial": handleMeasurements }); } //************** New client map.addControl(measureControls.line); map.addControl(measureControls.polygon); // DragPan control var optionsNavigation = { dragPan: new OpenLayers.Control.DragPan(), }; dragControls = { dragger: new OpenLayers.Control.Navigation(optionsNavigation), }; map.addControl(dragControls.dragger); //************** End - New client // create a new event handler for single click query queryEventHandler1 = new OpenLayers.Handler.Click({ 'map': map }, { 'click': function(e){ fire(e);//Spectrum }}); queryEventHandler2 = new OpenLayers.Handler.Click({ 'map': map }, { 'click': function(e){ fire2(e);//Spectral Ratio }}); queryEventHandler3 = new OpenLayers.Handler.Click({ 'map': map }, { 'click': function(e){ fire3(e);//Cross Section }}); queryEventHandler4 = new OpenLayers.Handler.Click({ 'map': map }, { 'click': function(e){ fire4(e);//Elevation }}); function fire(e) { // draw spectra var lonlat = map.getLonLatFromPixel(e.xy); var lon = lonlat.lon; var lat = lonlat.lat; vector_layer2.destroyFeatures(); // destroy the points from spectral ratio if(addspectrum(lon,lat)) { var origin = {x:lon, y:lat}; var circleout = new OpenLayers.Geometry.Polygon.createRegularPolygon(origin, pointsize, 50); var circle = new OpenLayers.Feature.Vector(circleout, {fcolor: colors[pos]}); vector_layer.addFeatures(circle); pos++; if (pos == nrclicks) { pos = 0; // wrap around } } } function fire2(e) { // ratio var lonlat = map.getLonLatFromPixel(e.xy); var lon = lonlat.lon; var lat = lonlat.lat; vector_layer.destroyFeatures(); // destroy the points from the series if(ratiospectra(lon,lat)) { var origin = {x:lon, y:lat}; var circleout = new OpenLayers.Geometry.Polygon.createRegularPolygon(origin, pointsize, 50); vector_layer2.addFeatures(new OpenLayers.Feature.Vector(circleout)); } } function fire3(e) { // destroy the points from other functions vector_layer.destroyFeatures(); vector_layer2.destroyFeatures(); vector_layer4.destroyFeatures(); var lonlat = map.getLonLatFromPixel(e.xy); var xmin = dtmdataset.xmin; var xmax = dtmdataset.xmax; var ymin = dtmdataset.ymin; var ymax = dtmdataset.ymax; // if you click within the extent of the imagedtm layer: if((lonlat.lon >= xmin) && (lonlat.lon <= xmax) && (lonlat.lat >= ymin) && (lonlat.lat <= ymax)) { var origin = {x:lonlat.lon, y:lonlat.lat}; var circleout = new OpenLayers.Geometry.Polygon.createRegularPolygon(origin, pointsize, 50); vector_layer3.addFeatures(new OpenLayers.Feature.Vector(circleout)); if (crossturn == 1) { // this is our second set of data needed for the cross // add a line joining the two points var points = new Array( new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat), new OpenLayers.Geometry.Point(dtmdataset.templonlat.lon, dtmdataset.templonlat.lat) ); var line = new OpenLayers.Geometry.LineString(points); vector_layer3.addFeatures(new OpenLayers.Feature.Vector(line)); var lon1 = dtmdataset.templonlat.lon; var lat1 = dtmdataset.templonlat.lat; var lon2 = lonlat.lon; var lat2 = lonlat.lat; //New function to show a Cross Section diagram showCrossSectionDiagram(lon1, lat1, lon2, lat2); /*** Commented by swingit *** $('#loader').show(); crosssection(lon1,lat1,lon2,lat2); *** Commented by swingit ***/ crossturn = 0; // reset turn to 0 } else { // crossturn is equal to 0 crossturn++; // increase turn count dtmdataset.templonlat = lonlat; // to keep track of the first set of data } return true; } else { return false; } } function fire4(e) { // destroy the points from other functions //vector_layer.destroyFeatures(); //vector_layer2.destroyFeatures(); //vector_layer3.destroyFeatures(); var lonlat = map.getLonLatFromPixel(e.xy); var xmin = dtmdataset.xmin; var xmax = dtmdataset.xmax; var ymin = dtmdataset.ymin; var ymax = dtmdataset.ymax; // if you click within the extent of the imagedtm layer: if((lonlat.lon >= xmin) && (lonlat.lon <= xmax) && (lonlat.lat >= ymin) && (lonlat.lat <= ymax)) { //var origin = {x:lonlat.lon, y:lonlat.lat}; //var circleout = new OpenLayers.Geometry.Polygon.createRegularPolygon(origin, pointsize, 50); //vector_layer4.addFeatures(new OpenLayers.Feature.Vector(circleout)); //$('#loader').show(); getz(lonlat.lon,lonlat.lat); } } } function inithsmapevents() { OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, { defaultHandlerOptions: { 'single': true, 'double': false, 'pixelTolerance': 0, 'stopSingle': false, 'stopDouble': false }, initialize: function(options) { this.handlerOptions = OpenLayers.Util.extend( {}, this.defaultHandlerOptions ); OpenLayers.Control.prototype.initialize.apply( this, arguments ); }, }); click = new OpenLayers.Control.Click(); map.addControl(click); click.activate(); }
planetserver/webclient-touch
static/js/main/planetmap.events.js
JavaScript
gpl-3.0
13,707
/** * Copyright Intermesh * * This file is part of Group-Office. You should have received a copy of the * Group-Office license along with Group-Office. See the file /LICENSE.TXT * * If you have questions write an e-mail to info@intermesh.nl * * @copyright Copyright Intermesh * @version $Id: EmailTemplateDialog.js 22112 2018-01-12 07:59:41Z mschering $ * @author Merijn Schering <mschering@intermesh.nl> * @author Wilmar van Beusekom <wilmar@intermesh.nl> */ GO.addressbook.EmailTemplateDialog = function(config){ if(!config) { config={}; } this.buildForm(); var focusFirstField = function(){ this.propertiesPanel.items.items[0].focus(); }; config.maximizable=true; config.layout='fit'; config.modal=false; config.resizable=true; config.width=760; config.height=600; config.closeAction='hide'; config.title= t("E-mail template", "addressbook"); config.items= this.formPanel; config.focus= focusFirstField.createDelegate(this); config.buttonAlign='left'; GO.addressbook.EmailTemplateDialog.superclass.constructor.call(this, config); this.addEvents({ 'save' : true }); } Ext.extend(GO.addressbook.EmailTemplateDialog, Ext.Window,{ // // inline_attachments : [], show : function (email_template_id) { if(!this.rendered) { this.render(Ext.getBody()); } this.tabPanel.setActiveTab(0); if(!email_template_id) { email_template_id=0; } this.setEmailTemplateId(email_template_id); if(this.email_template_id>0) { this.formPanel.load({ url: GO.url('addressbook/template/load'), success:function(form, action) { this.readPermissionsTab.setAcl(action.result.data.acl_id); GO.addressbook.EmailTemplateDialog.superclass.show.call(this); }, failure:function(form, action) { GO.errorDialog.show(action.result.feedback) }, scope: this }); }else { this.formPanel.form.reset(); this.htmlEditPanel.reset(); this.readPermissionsTab.setAcl(0); GO.addressbook.EmailTemplateDialog.superclass.show.call(this); } }, setEmailTemplateId : function(email_template_id) { this.formPanel.form.baseParams['id']=email_template_id; this.email_template_id=email_template_id; }, submitForm : function(hide){ //won't toggle if not done twice... // THIS IS ALREADY DONE IN THE EMAILEDITORPANEL // if(this.htmlEditPanel.getHtmlEditor().sourceEditMode){ // this.htmlEditPanel.getHtmlEditor().toggleSourceEdit(false); // this.htmlEditPanel.getHtmlEditor().toggleSourceEdit(false); // } //this.htmlEditPanel.getHtmlEditor().toggleSourceEdit(false); this.formPanel.form.submit( { url: GO.url('addressbook/template/submit'), waitMsg:t("Saving..."), success:function(form, action){ this.fireEvent('save', this); if(hide) { this.hide(); }else { if(action.result.id) { this.setEmailTemplateId(action.result.id); this.readPermissionsTab.setAcl(action.result.acl_id); } } }, failure: function(form, action) { if(action.failureType == 'client') { Ext.MessageBox.alert(t("Error"), t("You have errors in your form. The invalid fields are marked.")); } else { Ext.MessageBox.alert(t("Error"), action.result.feedback); } }, scope: this }); }, buildForm : function () { // var imageInsertPlugin = new GO.plugins.HtmlEditorImageInsert(); // imageInsertPlugin.on('insert', function(plugin, path, url,temp,id) { // // // var ia = { // tmp_file : path, // url : url, // temp:temp // }; // // this.inline_attachments.push(ia); // }, this); var autodata = [ ['{date}',t("Date")], ['{contact:salutation}',t("Salutation")], ['{contact:first_name}',t("First name")], ['{contact:middle_name}',t("Middle name")], ['{contact:last_name}',t("Last name")], ['{contact:initials}',t("Initials")], ['{contact:title}',t("Title")], ['{contact:email}',t("E-mail")], ['{contact:home_phone}',t("Phone")], ['{contact:fax}',t("Fax")], ['{contact:cellular}',t("Mobile")], ['{contact:cellular2}',t("2nd mobile")], ['{contact:address}',t("Address")], ['{contact:address_no}',t("Address 2")], ['{contact:zip}',t("ZIP/Postal")], ['{contact:city}',t("City")], ['{contact:state}',t("State")], ['{contact:country}',t("Country")], ['{contact:company}',t("Company")], ['{contact:department}',t("Department")], ['{contact:function}',t("Function")], ['{contact:work_phone}',t("Phone (work)")], ['{contact:work_fax}',t("Fax (work)")], ['{contact:work_address}',t("Address (work)")], ['{contact:work_address_no}',t("Address 2 (work)")], ['{contact:work_city}',t("City (work)")], ['{contact:work_zip}',t("ZIP/Postal (work)")], ['{contact:work_state}',t("State (work)")], ['{contact:work_country}',t("Country (work)")], ['{contact:work_post_address}',t("Address (post)")], ['{contact:work_post_address_no}',t("Number of house (post)")], ['{contact:work_post_city}',t("City (post)")], ['{contact:work_post_zip}',t("ZIP/Postal (post)")], ['{contact:work_post_state}',t("State (post)")], ['{contact:work_post_country}',t("Country (post)")], ['{contact:homepage}',t("Homepage")], ['{user:name}',t("Name")+' ('+t("User")+')'], ['{user:first_name}',t("First name")+' ('+t("User")+')'], ['{user:middle_name}',t("Middle name")+' ('+t("User")+')'], ['{user:last_name}',t("Last name")+' ('+t("User")+')'], ['{user:initials}',t("Initials")+' ('+t("User")+')'], ['{user:title}',t("Title")+' ('+t("User")+')'], ['{user:email}',t("E-mail")+' ('+t("User")+')'], ['{user:home_phone}',t("Phone")+' ('+t("User")+')'], ['{user:fax}',t("Fax")+' ('+t("User")+')'], ['{user:work_phone}',t("Phone (work)")+' ('+t("User")+')'], ['{user:work_fax}',t("Fax (work)")+' ('+t("User")+')'], ['{user:cellular}',t("Mobile")+' ('+t("User")+')'], ['{user:cellular2}',t("2nd mobile")+' ('+t("User")+')'], ['{user:address}',t("Address")+' ('+t("User")+')'], ['{user:address_no}',t("Address 2")+' ('+t("User")+')'], ['{user:zip}',t("ZIP/Postal")+' ('+t("User")+')'], ['{user:city}',t("City")+' ('+t("User")+')'], ['{user:state}',t("State")+' ('+t("User")+')'], ['{user:country}',t("Country")+' ('+t("User")+')'], ['{usercompany:name}',t("Company")+' ('+t("User")+')'], ['{user:department}',t("Department")+' ('+t("User")+')'], ['{user:function}',t("Function")+' ('+t("User")+')'], ['{usercompany:phone}',t("Phone (work)")+' ('+t("User")+')'], ['{usercompany:fax}',t("Fax (work)")+' ('+t("User")+')'], ['{usercompany:address}',t("Address (work)")+' ('+t("User")+')'], ['{usercompany:address_no}',t("Address 2 (work)")+' ('+t("User")+')'], ['{usercompany:city}',t("City (work)")+' ('+t("User")+')'], ['{usercompany:zip}',t("ZIP/Postal (work)")+' ('+t("User")+')'], ['{usercompany:state}',t("State (work)")+' ('+t("User")+')'], ['{usercompany:country}',t("Country (work)")+' ('+t("User")+')'], ['{user:homepage}',t("Homepage")+' ('+t("User")+')'], ['{unsubscribe_link}',t("Unsubscribe link", "addressbook")], ['%unsubscribe_href%',t("Unsubscribe href", "addressbook")], ['{link}',t("Link")] ]; var items = [new Ext.Panel({ title:t("Autodata", "addressbook") , autoScroll:true, items:new GO.grid.SimpleSelectList({ store: new Ext.data.SimpleStore({ fields: ['value', 'name'], data : autodata }), listeners:{ scope:this, click:function(dataview, index){ this.htmlEditPanel.getHtmlEditor().insertAtCursor(dataview.store.data.items[index].data.value); this.htmlEditPanel.getHtmlEditor().deferFocus(); dataview.clearSelections(); } } }) })]; if(go.Modules.isAvailable("core", "customfields")){ autodata=[]; if(autodata.length){ items.push(new Ext.Panel({ autoScroll:true, title:t("Custom contact fields", "addressbook"), items:new GO.grid.SimpleSelectList({ store: new Ext.data.SimpleStore({ fields: ['value', 'name'], data : autodata }), listeners:{ scope:this, click:function(dataview, index){ this.htmlEditPanel.getHtmlEditor().insertAtCursor(dataview.store.data.items[index].data.value); this.htmlEditPanel.getHtmlEditor().deferFocus(); dataview.clearSelections(); } } }) })); } autodata=[]; if(autodata.length){ items.push(new Ext.Panel({ autoScroll:true, title:t("Custom company fields", "addressbook"), items:new GO.grid.SimpleSelectList({ store: new Ext.data.SimpleStore({ fields: ['value', 'name'], data : autodata }), listeners:{ scope:this, click:function(dataview, index){ this.htmlEditPanel.getHtmlEditor().insertAtCursor(dataview.store.data.items[index].data.value); this.htmlEditPanel.getHtmlEditor().deferFocus(); dataview.clearSelections(); } } }) })); } autodata=[]; if(autodata.length){ items.push(new Ext.Panel({ autoScroll:true, title:t("Custom user fields", "addressbook"), items:new GO.grid.SimpleSelectList({ store: new Ext.data.SimpleStore({ fields: ['value', 'name'], data : autodata }), listeners:{ scope:this, click:function(dataview, index){ this.htmlEditPanel.getHtmlEditor().insertAtCursor(dataview.store.data.items[index].data.value); this.htmlEditPanel.getHtmlEditor().deferFocus(); dataview.clearSelections(); } } }) })); } } this.autoDataPanel = new Ext.Panel({ region:'east', layout:'accordion', border:false, autoScroll:true, width: 180, split:true, resizable:true, items:items }); this.propertiesPanel = new Ext.Panel({ region:'center', border: false, layout:'border', items:[{ region:'north', autoHeight: true, layout:'form', border: false, cls:'go-form-panel', items:[ { xtype: 'textfield', name: 'name', anchor: '100%', allowBlank:false, fieldLabel: t("Name") }, { xtype: 'textfield', name: 'subject', anchor: '100%', allowBlank: true, fieldLabel: t("Subject") } ] }, this.htmlEditPanel = new GO.base.email.EmailEditorPanel({ region:'center' })] }); //{text:'Toggle HTML',handler:function(){this.htmlEditPanel.setContentTypeHtml(this.htmlEditPanel.getContentType()!='html')}, scope:this} var borderLayoutPanel = new Ext.Panel({ layout:'border', title:t("Properties"), items: [this.propertiesPanel, this.autoDataPanel] }); var items = [borderLayoutPanel]; this.readPermissionsTab = new GO.grid.PermissionsPanel({ }); items.push(this.readPermissionsTab); this.tabPanel = new Ext.TabPanel({ activeTab: 0, deferredRender: false, border: false, items: items, anchor: '100% 100%' }) ; this.formPanel = new Ext.form.FormPanel({ border: false, baseParams: { task: 'email_template' }, waitMsgTarget:true, items:this.tabPanel }); this.buttons = [this.htmlEditPanel.getAttachmentsButton(),'->', { text: t("Apply"), handler: function(){ this.submitForm(); }, scope:this },{ text: t("Save"), handler: function(){ this.submitForm(true); }, scope: this }]; } });
deependhulla/powermail-debian9
files/rootdir/usr/local/src/groupoffice-6.3/modules/addressbook/EmailTemplateDialog.js
JavaScript
gpl-3.0
11,486
var app = require('../app'); var assert = require('assert'); var request = require('superagent'); app.listen(app.get('port'), function() { console.log('Express server listening on port ' + app.get('port')); }); describe('Proba', function() { it('should be ok for the first test', function() { assert.equal(true, true); }); it('should be NOT ok for the second test', function() { assert.equal(true, false); }); });
jupy/guess-animal
tests/nodes.js
JavaScript
gpl-3.0
435
m.francais.scrabble.Module = function (e) { // public methods this.buildExercisePresentation = function (div) { }; this.buildExplanation = function (div, currentExercise) { }; this.buildQuestion = function (div, currentExercise, currentModule) { view = new m.francais.scrabble.View(this, div); questionIndex = 1; currentScore = this.getQuestionScore(currentExercise, currentModule); }; this.error = function () { if (currentScore > 0) { --currentScore; } }; this.finishModule = function (currentExercise, currentModule) { return questionIndex == this.getQuestionNumber(currentExercise, currentModule); }; this.getExerciseList = function () { return { title: [ 'Exercice 1' ], subTitle: [ ] }; }; this.getGoodResponseMessage = function () { return 'Bonne réponse !'; }; this.getLevel = function () { return 'm'; }; this.getModuleList = function (currentExercise) { return { title: [ 'Module 1'], subTitle: [ ] }; }; this.getName = function () { return "Le scrabble (mots de 3 à 5 lettres)"; }; this.getNextQuestionButtonText = function () { return 'Suivante'; }; this.getQuestionNumber = function (currentExercise, currentModule) { return 5; }; this.getQuestionScore = function (currentExercise, currentModule) { return 0; // total = 1000 pts }; this.getScore = function () { return currentScore; }; this.getSubject = function () { return 'francais'; }; this.getTopic = function () { return 'scrabble'; }; this.getWrongResponseMessage = function () { return 'Mauvaise réponse'; }; this.initScore = function () { // un exercice à un module return new Score([ [ -1 ] ]); }; this.next = function () { engine.next(); }; this.nextQuestion = function (currentExercise, currentModule) { questionIndex++; if (questionIndex <= this.getQuestionNumber(currentExercise, currentModule)) { currentScore = this.getQuestionScore(currentExercise, currentModule); view.next(); } }; // private methods var init = function (e) { engine = e; }; // private attributes var view; var engine; var questionIndex; var currentScore; init(e); };
pepit-team/pepitmobil-html5
exercises/m/francais/scrabble/js/Module.js
JavaScript
gpl-3.0
2,532
/* ---------------------------------------------------------------------- * js/ca/ca.seteditor.js * ---------------------------------------------------------------------- * CollectiveAccess * Open-source collections management software * ---------------------------------------------------------------------- * * Software by Whirl-i-Gig (http://www.whirl-i-gig.com) * Copyright 2010-2016 Whirl-i-Gig * * For more information visit http://www.CollectiveAccess.org * * This program is free software; you may redistribute it and/or modify it under * the terms of the provided license as published by Whirl-i-Gig * * CollectiveAccess is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * This source code is free and modifiable under the terms of * GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See * the "license.txt" file for details, or visit the CollectiveAccess web site at * http://www.CollectiveAccess.org * * ---------------------------------------------------------------------- */ // // Note: requires jQuery UI.Sortable // var caUI = caUI || {}; (function ($) { caUI.seteditor = function(options) { var that = jQuery.extend({ setID: null, table_num: null, fieldNamePrefix: null, setEditorID: 'setItemEditor', setItemListID: 'setItemList', setNoItemWarningID: 'setNoItemsWarning', setItemAutocompleteID: 'setItemAutocompleter', rowIDListID: 'setRowIDList', displayTemplate: null, lookupURL: null, itemInfoURL: null, editSetItemsURL: null, // url of set item editor (without item_id parameter key or value) editSetItemButton: null, // html to use for edit set item button deleteSetItemButton: null, // html to use for delete set item button initialValues: null, initialValueOrder: null, /* id's to list display list in; required because Google Chrome doesn't iterate over keys in an object in insertion order [doh] */ }, options); // ------------------------------------------------------------------------------------ that.initSetEditor = function() { // setup autocompleter jQuery('#' + that.setItemAutocompleteID).autocomplete( { source: that.lookupURL, minLength: 3, max: 50, html: true, select: function(event, ui) { jQuery.getJSON(that.itemInfoURL, {'set_id': that.setID, 'table_num': that.table_num, 'row_id': ui.item.id, 'displayTemplate': that.displayTemplate} ,  function(data) { if(data.status != 'ok') { alert("Error getting item information"); } else { that.addItemToSet(data.row_id, data, true, true); jQuery('#' + that.setItemAutocompleteID).attr('value', ''); } } ); } } ); // add initial items if (that.initialValues) { jQuery.each(that.initialValueOrder, function(k, v) { that.addItemToSet(that.initialValues[v].row_id, that.initialValues[v], false); }); } that.refresh(); } // ------------------------------------------------------------------------------------ // Adds item to set editor display that.addItemToSet = function(rowID, valueArray, isNew, prepend) { if (isNew) { var id_list = that.getRowIDs(); if(jQuery.inArray(rowID, id_list) != -1) { // don't allow dupes return false; } } var repHTML = valueArray.representation_url || ''; if (repHTML && that.editSetItemsURL) { repHTML = '<div style="margin-left: 25px; background-image: url(\'' + repHTML + '\'); width: ' + valueArray.representation_width + 'px; height: ' + valueArray.representation_height + 'px;"> </div>'; } var itemID = valueArray['item_id']; var rID = rowID + ((itemID > 0) ? "_" + itemID : ""); console.log("item=" + itemID, rowID, rID, repHTML); var editLinkHTML = ''; if ((that.editSetItemButton) && (itemID > 0)) { editLinkHTML = '<div style="float: left;"><a href="' + that.editSetItemsURL + '/item_id/' + valueArray['item_id'] + '" title="' + that.editSetItemToolTip +'" class="setItemEditButton">' + that.editSetItemButton + '</a></div> '; } var itemHTML = "<li class='setItem' id='" + that.fieldNamePrefix + "setItem" + rID +"'><div id='" + that.fieldNamePrefix + "setItemContainer" + rID + "' class='imagecontainer'>"; if (itemID > 0) { itemHTML += "<div class='remove'><a href='#' class='setDeleteButton' id='" + that.fieldNamePrefix + "setItemDelete" + itemID + "'>" + that.deleteSetItemButton + "</a></div>"; } var displayLabel; if(valueArray.displayTemplate) { displayLabel = valueArray.displayTemplate; } else { displayLabel = valueArray.set_item_label + " [<span class='setItemIdentifier'>" + valueArray.idno + "</span>]"; } itemHTML += "<div class='setItemThumbnail'>" + editLinkHTML + repHTML + "</div><div class='setItemCaption'>" + displayLabel + "</div><div class='setItemIdentifierSortable'>" + valueArray.idno_sort + "</div></div><br style='clear: both;'/></li>"; if (prepend) { jQuery('#' + that.fieldNamePrefix + that.setItemListID).prepend(itemHTML); } else { jQuery('#' + that.fieldNamePrefix + that.setItemListID).append(itemHTML); } if (itemID > 0) { that.setDeleteButton(rowID, itemID); } if (isNew) { that.refresh(); caUI.utils.showUnsavedChangesWarning(true); } return true; } // ------------------------------------------------------------------------------------ that.setDeleteButton = function(rowID, itemID) { var rID = rowID + ((itemID > 0) ? "_" + itemID : ""); jQuery('#' + that.fieldNamePrefix + "setItemDelete" + itemID).click( function() { jQuery('#' + that.fieldNamePrefix + "setItem" + rID).fadeOut(250, function() { jQuery('#' + that.fieldNamePrefix + "setItem" + rID).remove(); that.refresh(); }); caUI.utils.showUnsavedChangesWarning(true); return false; } ); } // ------------------------------------------------------------------------------------ // Returns list of item row_ids in user-defined order that.getRowIDs = function() { var id_list = []; jQuery.each(jQuery('#' + that.fieldNamePrefix + that.setItemListID + ' .setItem'), function(k, v) { var id_string = jQuery(v).attr('id'); if (id_string) { id_list.push(id_string.replace(that.fieldNamePrefix + 'setItem', '')); } }); return id_list; } // ------------------------------------------------------------------------------------ that.refresh = function() { jQuery('#' + that.fieldNamePrefix + that.setItemListID).sortable({ opacity: 0.7, revert: true, scroll: true, update: function() { that.refresh(); caUI.utils.showUnsavedChangesWarning(true); } }); // set warning if no items on load jQuery('#' + that.fieldNamePrefix + that.setItemListID + ' li.setItem').length ? jQuery('#' + that.fieldNamePrefix + that.setNoItemWarningID).hide() : jQuery('#' + that.fieldNamePrefix + that.setNoItemWarningID).show(); jQuery('#' + that.rowIDListID).val(that.getRowIDs().join(';')); } // ------------------------------------------------------------------------------------ that.sort = function(key) { var indexedValues = {}; var indexKeyClass = null; switch(key) { case 'name': indexKeyClass = 'setItemCaption'; break; case 'idno': indexKeyClass = 'setItemIdentifierSortable'; break; default: return false; break; } jQuery.each(jQuery('#' + that.fieldNamePrefix + that.setItemListID + ' .setItem'), function(k, v) { var id_string = jQuery(v).attr('id'); if (id_string) { var indexKey = jQuery('#' + id_string + ' .imagecontainer .' + indexKeyClass).text(); indexedValues[indexKey] = v; } jQuery(v).remove(); }); indexedValues = caUI.utils.sortObj(indexedValues, true); jQuery.each(indexedValues, function(k, v) { jQuery('#' + that.fieldNamePrefix + that.setItemListID).append(v); var id_string = jQuery(v).attr('id'); var id = id_string.replace(that.fieldNamePrefix + 'setItem', ''); var rIDBits = id.split(/_/); that.setDeleteButton(rIDBits[0], rIDBits[1]); }); caUI.utils.showUnsavedChangesWarning(true); that.refresh(); } // ------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------ that.initSetEditor(); return that; }; })(jQuery);
bruceklotz/providence-with-Backup
assets/ca/ca.seteditor.js
JavaScript
gpl-3.0
8,638
/** * Este arquivo pertence ao SCE - Sistema de Controle de Estágio -, cuja função * é realizar o controle de estágio para discentes do IFPA. * Copyright (C) 2015 Rafael Campos Nunes * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Script para gerenciar todo tipo de cadastro feito no aplicação. */ // SCE var sceDB = require('./db_api.js') var sceUtils = require('./server_utils.js') var ws = require('./web_socket.js') exports.cadastraEstagiario = function (req, res) { sceUtils.writeLog('Requisição de cadastro de estagiário recebido', '906') // Dados do estagiário a ser enviado ao banco de dados. var estagiario = [] estagiario.push(req.estagiario.matricula) estagiario.push(req.estagiario.nome) estagiario.push(req.estagiario.periodo_inicio) estagiario.push(req.estagiario.periodo_fim) estagiario.push(req.estagiario.empresa) // foto, por enquanto a função não vai ser implementada. estagiario.push('') estagiario.push(req.estagiario.observacao) estagiario.push(req.estagiario.empresa) estagiario.push(req.estagiario.turma) estagiario.push(req.estagiario.orientador) sceDB.insertEstagiario(estagiario, function (data, err) { if (data) { sceUtils.writeLog('Estagiário(a) ' + estagiario[1] + ' inserido(a) no sistema', '903') res.sendFile(sceUtils.getFile('cadastra_estagiario.html')) ws.sendClientMessage('1000', 'Cadastro bem sucedido', '') } else { if (sceUtils.isDebug()) { console.log('Erro ao inserir estagiário: ' + err) } sceUtils.writeLog('[DB_API_ERR] ' + err, '904') res.sendFile(sceUtils.getFile('cadastra_estagiario.html')) ws.sendClientMessage('1004', '[DB_API_ERR]', err) } }) } exports.cadastraEmpresa = function (req, res) { sceUtils.writeLog('Requisição de cadastro de empresa recebido', '906') // dados da empresa var empresa = [] empresa.push(req.empresa.nome) empresa.push(req.empresa.razao_social) empresa.push(req.empresa.cnpj) empresa.push(req.empresa.email) empresa.push(req.empresa.telefone) empresa.push(req.empresa.telefone_2) empresa.push(req.empresa.rua) empresa.push(req.empresa.numero) empresa.push(req.empresa.bairro) empresa.push(req.empresa.cep) sceDB.insertEmpresa(empresa, function (data, err) { if (data) { sceUtils.writeLog('Empresa ' + empresa[0] + ' inserida no sistema', '903') res.sendFile(sceUtils.getFile('empresas.html')) ws.sendClientMessage('1000', 'Cadastro bem sucedido', '') } else { if (sceUtils.isDebug()) { console.log('Erro ao inserir estagiário: ' + err) } sceUtils.writeLog('[DB_API_ERR] ' + err, '904') res.status(400).sendFile(sceUtils.getFile('empresas.html')) ws.sendClientMessage('1004', '[DB_API_ERR]', err) } }) } exports.cadastraOrientador = function (req, res) { sceUtils.writeLog('Requisição de cadastro de orientador recebido', '906') // dados que irão para o banco de dados. var orientador = [] orientador.push(req.orientador.siap) orientador.push(req.orientador.nome) sceDB.insertOrientador(orientador, function (data, err) { if (data) { sceUtils.writeLog('Orientador ' + orientador[1] + ' inserido no sistema', '903') res.sendFile(sceUtils.getFile('orientadores.html')) ws.sendClientMessage('1000', 'Cadastro bem sucedido', '') } else { if (sceUtils.isDebug()) { console.log('Erro ao inserir orientador: ' + err) } sceUtils.writeLog('[DB_API_ERR] ' + err, '904') res.status(400).sendFile(sceUtils.getFile('orientadores.html')) ws.sendClientMessage('1004', '[DB_API_ERR]', err) } }) } exports.cadastraTurma = function (req, res) { sceUtils.writeLog('Requisição de cadastro de turma recebido', '906') // dados que irão para o banco de dados. var turma = [] turma.push(req.turma.id_turma) turma.push(req.turma.turno) turma.push(req.turma.curso) sceDB.insertTurma(turma, function (data, err) { if (data) { sceUtils.writeLog('Turma ' + turma[2] + ' inserida no sistema', '903') res.sendFile(sceUtils.getFile('turmas.html')) ws.sendClientMessage('1000', 'Cadastro bem sucedido', '') } else { if (sceUtils.isDebug()) { console.log('Erro ao inserir turma: ' + err) } sceUtils.writeLog('[DB_API_ERR] ' + err, '904') res.status(400).sendFile(sceUtils.getFile('turmas.html')) ws.sendClientMessage('1004', '[DB_API_ERR]', err) } }) }
tatyanebianchi/SCE
src/server/cadastro.js
JavaScript
gpl-3.0
5,283
var oldConsole = console; var warnFired = false; var errorFired = false; var licenseKey = 'OPEN-SOURCE-GPLV3-LICENSE'; function mockConsole(){ console = {}; console.warn = function(e){ warnFired = true; }; console.error = function(e){ errorFired = true; } } function isWarnFired(){ if(warnFired){ warnFired = false; return true; } return false; } function isErrorFired(){ if(errorFired){ errorFired = false; return true; } return false; } function isUsingExtensionsFile(FP){ return typeof FP.getFullpageData().internals !== 'undefined'; } //loopTop & continuousVertical QUnit.test('Testing warnings for loopTop:false with continuousVertical:true', function(assert) { var id = '#fullpage'; warnFired = false; mockConsole(); var FP = initFullpageNew(id, {loopTop: false, loopBottom: false, continuousVertical:true}); assert.equal(isWarnFired(), false, 'We expect console.warn not to be fired'); }); QUnit.test('Testing warnings for loopTop:true with continuousVertical:true', function(assert) { var id = '#fullpage'; warnFired = false; mockConsole(); var FP = initFullpageNew(id, {loopTop: true, continuousVertical:true}); assert.equal(isWarnFired(), true, 'We expect console.warn to be fired'); }); //loopBottom & continuousVertical QUnit.test('Testing warnings for loopBottom:false with continuousVertical:true', function(assert) { var id = '#fullpage'; warnFired = false; mockConsole(); var FP = initFullpageNew(id, {loopBottom: false, loopBottom: false, continuousVertical:true}); assert.equal(isWarnFired(), false, 'We expect console.warn not to be fired'); }); QUnit.test('Testing warnings for loopBottom:true with continuousVertical:true', function(assert) { var id = '#fullpage'; warnFired = false; mockConsole(); var FP = initFullpageNew(id, {loopBottom: true, continuousVertical:true}); assert.equal(isWarnFired(), true, 'We expect console.warn to be fired'); }); //scrollBar & continuousVertical QUnit.test('Testing warnings for scrollBar:false with continuousVertical:true', function(assert) { var id = '#fullpage'; warnFired = false; mockConsole(); var FP = initFullpageNew(id, {scrollBar: false, autoScrolling:true, continuousVertical:true}); assert.equal(isWarnFired(), false, 'We expect console.warn not to be fired'); }); QUnit.test('Testing warnings for scrollBar:true with continuousVertical:true', function(assert) { var id = '#fullpage'; warnFired = false; mockConsole(); var FP = initFullpageNew(id, {scrollBar: true, autoScrolling:true, continuousVertical:true}); assert.equal(isWarnFired(), true, 'We expect console.warn to be fired'); }); //scrollOverflow && (scrollBar || autoScrolling) QUnit.test('Testing warnings for scrollOverflow:true with scrollBar:true & autoScrolling:true', function(assert) { var id = '#fullpage'; warnFired = false; mockConsole(); var FP = initFullpageNew(id, {scrollBar: true, scrollOverflow:true, scrollOverflowHandler: {init: function(){}, remove: function(){}} }); assert.equal(isWarnFired(), true, 'We expect console.warn to be fired'); }); QUnit.test('Testing warnings for scrollOverflow:true with scrollBar:false & autoScrolling:true', function(assert) { var id = '#fullpage'; warnFired = false; mockConsole(); var FP = initFullpageNew(id, {scrollBar: false, scrollOverflow:true, scrollOverflowHandler: {init: function(){}, remove: function(){}} }); assert.equal(isWarnFired(), false, 'We expect console.warn to be fired'); }); QUnit.test('Testing warnings for scrollOverflow:true with autoScrolling:false', function(assert) { var id = '#fullpage'; warnFired = false; mockConsole(); var FP = initFullpageNew(id, {autoScrolling: false, scrollOverflow:true, scrollOverflowHandler: {init: function(){}, remove: function(){}} }); assert.equal(isWarnFired(), true, 'We expect console.warn to be fired'); }); QUnit.test('Testing warnings for scrollOverflow:true with autoScrolling:true', function(assert) { var id = '#fullpage'; warnFired = false; mockConsole(); var FP = initFullpageNew(id, {autoScrolling: true, scrollOverflow:true, scrollOverflowHandler: {init: function(){}, remove: function(){}} }); assert.equal(isWarnFired(), false, 'We expect console.warn not to be fired'); }); //autoScrolling & continuousVertical QUnit.test('Testing warnings for autoScrolling:true with continuousVertical:true', function(assert) { var id = '#fullpage'; warnFired = false; mockConsole(); var FP = initFullpageNew(id, {autoScrolling: true, continuousVertical:true}); assert.equal(isWarnFired(), false, 'We expect console.warn not to be fired'); }); QUnit.test('Testing warnings for autoScrolling:false with continuousVertical:true', function(assert) { var id = '#fullpage'; warnFired = false; mockConsole(); var FP = initFullpageNew(id, {autoScrolling: false, continuousVertical:true}); assert.equal(isWarnFired(), true, 'We expect console.warn to be fired'); }); //scrollOverflow must exist QUnit.test('Testing warnings for scrollOverflow:true with no vendor file', function(assert) { var id = '#fullpage'; errorFired = false; mockConsole(); var FP = initFullpageNew(id, {scrollOverflow: true, licenseKey: licenseKey, scrollOverflowHandler: null}); assert.equal(isErrorFired(), true, 'We expect console.warn to be fired'); }); //scrollOverflow must exist QUnit.test('Testing warnings for scrollOverflow:true with vendor file', function(assert) { var id = '#fullpage'; errorFired = false; mockConsole(); var FP = initFullpageNew(id, {scrollOverflow: true, licenseKey: licenseKey, scrollOverflowHandler: {init: function(){}, remove: function(){}}}); assert.equal(isWarnFired(), false, 'We expect console.warn not to be fired'); }); //extension file must exist QUnit.test('Testing warnings for parallax:true', function(assert) { var id = '#fullpage'; warnFired = false; mockConsole(); var FP = initFullpageNew(id, {parallax: true}); var expected = isUsingExtensionsFile(FP) ? false : true; assert.equal(isWarnFired(), expected, 'We expect console.warn to be fired'); }); QUnit.test('Testing warnings for scrollOverflowReset:true', function(assert) { var id = '#fullpage'; warnFired = false; mockConsole(); var FP = initFullpageNew(id, {scrollOverflowReset: true}); var expected = isUsingExtensionsFile(FP) ? false : true; assert.equal(isWarnFired(), expected, 'We expect console.warn to be fired'); }); QUnit.test('Testing warnings for dragAndMove:true', function(assert) { var id = '#fullpage'; warnFired = false; mockConsole(); var FP = initFullpageNew(id, {dragAndMove: true}); var expected = isUsingExtensionsFile(FP) ? false : true; assert.equal(isWarnFired(), expected, 'We expect console.warn to be fired'); }); QUnit.test('Testing warnings for offsetSections:true', function(assert) { var id = '#fullpage'; warnFired = false; mockConsole(); var FP = initFullpageNew(id, {offsetSections: true}); var expected = isUsingExtensionsFile(FP) ? false : true; assert.equal(isWarnFired(), expected, 'We expect console.warn to be fired'); }); QUnit.test('Testing warnings for fadingEffect:true', function(assert) { var id = '#fullpage'; warnFired = false; mockConsole(); var FP = initFullpageNew(id, {fadingEffect: true}); var expected = isUsingExtensionsFile(FP) ? false : true; assert.equal(isWarnFired(), expected, 'We expect console.warn to be fired'); }); QUnit.test('Testing warnings for responsiveSlides:true', function(assert) { var id = '#fullpage'; warnFired = false; mockConsole(); var FP = initFullpageNew(id, {responsiveSlides: true}); var expected = isUsingExtensionsFile(FP) ? false : true; assert.equal(isWarnFired(), expected, 'We expect console.warn to be fired'); }); QUnit.test('Testing warnings for continuousHorizontal:true', function(assert) { var id = '#fullpage'; warnFired = false; mockConsole(); var FP = initFullpageNew(id, {continuousHorizontal: true}); var expected = isUsingExtensionsFile(FP) ? false : true; assert.equal(isWarnFired(), expected, 'We expect console.warn to be fired'); }); QUnit.test('Testing warnings for interlockedSlides:true', function(assert) { var id = '#fullpage'; warnFired = false; mockConsole(); var FP = initFullpageNew(id, {interlockedSlides: true}); var expected = isUsingExtensionsFile(FP) ? false : true; assert.equal(isWarnFired(), expected, 'We expect console.warn to be fired'); }); QUnit.test('Testing warnings for scrollHorizontally:true', function(assert) { var id = '#fullpage'; warnFired = false; mockConsole(); var FP = initFullpageNew(id, {scrollHorizontally: true}); var expected = isUsingExtensionsFile(FP) ? false : true; assert.equal(isWarnFired(), expected, 'We expect console.warn to be fired'); }); QUnit.test('Testing warnings for resetSliders:true', function(assert) { var id = '#fullpage'; warnFired = false; mockConsole(); var FP = initFullpageNew(id, {resetSliders: true}); var expected = isUsingExtensionsFile(FP) ? false : true; assert.equal(isWarnFired(), expected, 'We expect console.warn to be fired'); }); //name element? QUnit.test('Testing warnings for name element same as anchor?', function(assert) { var id = '#fullpage-with-name-element'; errorFired = false; mockConsole(); var FP = initFullpageNew(id, {anchors: ['anchor-as-name', 'test2', 'test3', 'test4'], licenseKey: licenseKey}); assert.equal(isErrorFired(), true, 'We expect console.warn to be fired'); }); //id element? QUnit.test('Testing warnings for id element same as anchor?', function(assert) { var id = '#fullpage-with-name-element'; errorFired = false; mockConsole(); var FP = initFullpageNew(id, {anchors: ['anchor-as-id', 'test2', 'test3', 'test4'], licenseKey: licenseKey}); assert.equal(isErrorFired(), true, 'We expect console.warn to be fired'); });
alvarotrigo/fullPage.js
tests/unit/displayWarnings.js
JavaScript
gpl-3.0
10,284
const rules = { isEmail: function(value){ return (/^[^\s@]+@[^\s@]+\.[^\s@]+$/).test((value || "").toString()); }, isNumber: function(value){ return (parseFloat(value) == value); }, isChecked: function(value){ return (!!value) || value === "0"; }, isNotEmpty: function(value){ return (value === 0 || value); } }; export default rules;
webix-hub/tracker
sources/webix/rules.js
JavaScript
gpl-3.0
351
var Newsletter = require('../models/newsletter'); var moment = require('moment'); // New newsletter - method /api/newsletter (POST) exports.addNewsletter = function(req, res){ // Create a new instance of the Newsletter model var newsletter = new Newsletter(); newsletter.title = req.body.title; if(req.body.date) newsletter.date = moment(req.body.date,"DD/MM/YYYY"); if(req.body.preamble) newsletter.preamble = req.body.preamble; if(req.body.spoiler) newsletter.spoiler = req.body.spoiler; if(req.body.html) newsletter.html = req.body.html; if(req.body.campaign_id) newsletter.campaign_id = req.body.campaign_id; newsletter.save(function(err){ if (err) { console.log(err); res.send(err); return; } res.json({ message: 'Newsletter added to the system!', status: 1, data: newsletter }); }); } // Update newsletter - method /api/newsletters/:newsletter_id (PUT) exports.updateNewsletter = function(req, res){ var aNewsletter = new Newsletter(req.body); Newsletter.findByIdAndUpdate(req.params.newsletter_id, {$set : {"title":aNewsletter.title, "preamble":aNewsletter.preamble, "spoiler":aNewsletter.spoiler, "date":moment(req.body.date,"DD/MM/YYYY"), "campaign_id":aNewsletter.campaign_id }}, {upsert:false}, function (err, aNewsletter) { if (err) { console.log(err) return res.send(err); } res.send(aNewsletter); }); } // Get all newsletters - method /api/newsletters (GET) exports.getNewsletters = function(req, res){ Newsletter.find({}). sort({'date':'desc'}). exec( function(err,newsletters){ if(err) return res.send(err); res.send(newsletters); } ); } // Get one newsletter - method /api/newsletters/:newsletter_id (GET) exports.getNewsletter = function(req, res){ Newsletter.findById(req.params.newsletter_id). exec(function(err,aNewsletter){ if(err) return res.send(err); res.json(aNewsletter); } ); } // Remove newsletter - method /api/newsletter/:newsletter_id (DELETE) exports.deleteNewsletter = function(req, res){ Newsletter.findByIdAndRemove(req.params.newsletter_id, function (err, aNewsletter) { if (err) return res.send(err); res.send({message:"Newsletter was removed",data:aNewsletter}); }); }
ACECentre/aacnews
controllers/newsletters.js
JavaScript
gpl-3.0
2,313
import { Meteor } from "meteor/meteor"; import { Mongo, MongoInternals } from "meteor/mongo"; // This code taken from https://github.com/meteorhacks/meteor-aggregate // Add the aggregate function available in tbe raw collection to normal collections Mongo.Collection.prototype.aggregate = function (pipelines, options) { const coll = this._getCollection(); return Meteor.wrapAsync(coll.aggregate.bind(coll))(pipelines, options); }; // this group of methods were taken from https://github.com/meteorhacks/meteor-collection-utils /** * Provides a way to get at the underlying instance of the DB connection * @private * @returns {Object} The underlying Mongo connection */ Mongo.Collection.prototype._getDb = function () { if (typeof this._collection._getDb === "function") { return this._collection._getDb(); } const mongoConn = MongoInternals.defaultRemoteCollectionDriver().mongo; return wrapWithDb(mongoConn); }; /** * Provides a way to get at the underlying instance of the Collection * @private * @returns {Object} The underlying Mongo collection */ Mongo.Collection.prototype._getCollection = function () { const db = this._getDb(); return db.collection(this._name); }; function wrapWithDb(mongoConn) { if (mongoConn.db) { return mongoConn.db; } } /** * @summary Provides a wrapper around the results of a Mongo aggregate query to make it Reactive * @param {Object} pub - The instance of the publication we are creating * @param {Object} collection - The Mongo.Collection instance to query * @param {Array} pipeline - The aggregation pipeline to use * @param {Object} options - Optional options * - `observeSelector` can be given to improve efficiency. This selector is used for observing the collection. // (e.g. `{ authorId: { $exists: 1 } }`) // - `observeOptions` can be given to limit fields, further improving efficiency. Ideally used to limit fields on your query. // If none is given any change to the collection will cause the aggregation to be reevaluated. // (e.g. `{ limit: 10, sort: { createdAt: -1 } }`) // - `clientCollection` defaults to `collection._name` but can be overriden to sent the results // to a different client-side collection. @example // ## Quick Example // // A publication for one of the // [examples](https://docs.mongodb.org/v3.0/reference/operator/aggregation/group/#group-documents-by-author) // in the MongoDB docs would look like this: // // Meteor.publish("booksByAuthor", function () { // ReactiveAggregate(this, Books, [{ // $group: { // _id: "$author", // books: { $push: "$$ROOT" } // } // }]); // }); * @constructor */ export function ReactiveAggregate(pub, collection, pipeline, options) { let allowDiskUse = false; if (process.env.MONGO_ALLOW_DISK_USE) { allowDiskUse = true; } const defaultOptions = { observeSelector: {}, observeOptions: {}, clientCollection: collection._name, allowDiskUse }; const pubOptions = Object.assign({}, defaultOptions, options); let initializing = true; pub._ids = {}; pub._iteration = 1; // run this function every time a record changes function update() { if (initializing) { return; } // add and update documents on the client collection.aggregate(pipeline, { allowDiskUse: pubOptions.allowDiskUse }).forEach((doc) => { if (!pub._ids[doc._id]) { pub.added(pubOptions.clientCollection, doc._id, doc); } else { pub.changed(pubOptions.clientCollection, doc._id, doc); } pub._ids[doc._id] = pub._iteration; }); // remove documents not in the result anymore for (const [key, value] of Object.entries(pub._ids)) { if (value !== pub._iteration) { delete pub._ids[key]; pub.removed(pubOptions.clientCollection, key); } } pub._iteration += 1; } // track any changes on the collection used for the aggregation const query = collection.find(pubOptions.observeSelector, pubOptions.observeOptions); const handle = query.observeChanges({ added: update, changed: update, removed: update, error(error) { throw new Meteor.Error("server-error", `Encountered an error while observing ${collection._name}`, error); } }); // observeChanges() will immediately fire an "added" event for each document in the query // these are skipped using the initializing flag initializing = false; // send an initial result set to the client update(); // mark the subscription as ready pub.ready(); // stop observing the cursor when the client unsubscribes pub.onStop(() => { handle.stop(); }); }
aeyde/reaction
server/publications/collections/reactiveAggregate.js
JavaScript
gpl-3.0
4,656
if (fpcm === undefined) { var fpcm = {}; } fpcm.nkorg_stitemaplinklist = { init: function() { fpcm.ui.setFocus('xmlfilepath'); jQuery('#btnSitemaplinklistCheckPath').click(function() { fpcm.ajax.post('nkorg/sitemaplinklist/checkpath', { data: { path: jQuery('#xmlfilepath').val() }, execDone: function () { ajaxResult = fpcm.ajax.getResult('nkorg/sitemaplinklist/checkpath'); ajaxResult = fpcm.ajax.fromJSON(ajaxResult); fpcm.ui.showLoader(false); fpcm.ui.addMessage(ajaxResult.data, true); if (ajaxResult.code) { setTimeout(window.location.reload, 2500); } } }); return false; }); jQuery('#btnSaveSelectedLinks').click(function () { var selectedLinks = []; jQuery('.fpcm-sitemaplinklist-activelinks:checked').map(function (idx, item) { selectedLinks.push(jQuery(item).val()); }); fpcm.ajax.post('nkorg/sitemaplinklist/savelinks', { data: { selectedLinks: fpcm.ajax.toJSON(selectedLinks) }, execDone: function () { ajaxResult = fpcm.ajax.getResult('nkorg/sitemaplinklist/savelinks'); fpcm.ui.showLoader(false); if (ajaxResult == '0') { fpcmJs.addAjaxMassage('error', 'NKORG_SITEMAPLINKLIST_SAVED_FAILED'); return false; } else { fpcmJs.addAjaxMassage('notice', 'NKORG_SITEMAPLINKLIST_SAVED_OK'); setTimeout(function() { window.location.reload(); }, 2500) } } }); return false; }); } };
sea75300/fanpresscm3
inc/modules/nkorg/sitemaplinklist/js/sitemaplinklist.js
JavaScript
gpl-3.0
2,102
// @tag full-page // @require /var/www/oss/sencha/Lifecoach/app.js
AirDisa/Coach
build/temp/production/Lifecoach/sencha-compiler/app/full-page-master-bundle.js
JavaScript
gpl-3.0
67
/** * Bloginy, Blog Aggregator * Copyright (C) 2012 Riad Benguella - Rizeway * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Objet that handles a tabbed menu */ function BloginyTabs(menu) { var _menu = menu; var activateTab = function(link) { $.each($(_menu).find('a'), function(){ $(this).removeClass('active'); $($(this).attr('href')).hide(); }); $(link).addClass('active'); $($(link).attr('href')).show(); } return { init: function() { activateTab(_menu.find('a:first')); _menu.find('a').click(function(e){ e.preventDefault(); activateTab($(this)); }); } } }
youknowriad/bloginy
web/js/bundles/bloginy/utils/BloginyTabs.js
JavaScript
gpl-3.0
1,395
define( "dojo/cldr/nls/th/hebrew", //begin v1.x content { "field-quarter-short-relative+0": "ไตรมาสนี้", "field-quarter-short-relative+1": "ไตรมาสหน้า", "field-tue-relative+-1": "อังคารที่แล้ว", "field-year": "ปี", "field-wed-relative+0": "พุธนี้", "field-wed-relative+1": "พุธหน้า", "field-minute": "นาที", "field-month-narrow-relative+-1": "เดือนที่แล้ว", "field-tue-narrow-relative+0": "อังคารนี้", "field-tue-narrow-relative+1": "อังคารหน้า", "field-thu-short-relative+0": "พฤหัสนี้", "field-day-short-relative+-1": "เมื่อวาน", "field-thu-short-relative+1": "พฤหัสหน้า", "field-day-relative+0": "วันนี้", "field-day-short-relative+-2": "เมื่อวานซืน", "field-day-relative+1": "พรุ่งนี้", "field-week-narrow-relative+0": "สัปดาห์นี้", "field-day-relative+2": "มะรืนนี้", "field-week-narrow-relative+1": "สัปดาห์หน้า", "field-wed-narrow-relative+-1": "พุธที่แล้ว", "field-year-narrow": "ปี", "field-era-short": "สมัย", "field-year-narrow-relative+0": "ปีนี้", "field-tue-relative+0": "อังคารนี้", "field-year-narrow-relative+1": "ปีหน้า", "field-tue-relative+1": "อังคารหน้า", "field-weekdayOfMonth": "วันของเดือน", "field-second-short": "วิ", "dayPeriods-format-narrow-am": "a", "dateFormatItem-MMMd": "d MMM", "field-weekdayOfMonth-narrow": "วันของเดือน", "dayPeriods-format-abbr-am": "ก่อนเที่ยง", "field-week-relative+0": "สัปดาห์นี้", "field-month-relative+0": "เดือนนี้", "field-week-relative+1": "สัปดาห์หน้า", "field-month-relative+1": "เดือนหน้า", "field-sun-narrow-relative+0": "วันอาทิตย์นี้", "field-mon-short-relative+0": "จันทร์นี้", "field-sun-narrow-relative+1": "วันอาทิตย์หน้า", "field-mon-short-relative+1": "จันทร์หน้า", "field-second-relative+0": "ขณะนี้", "dateFormatItem-yyyyQQQ": "QQQ G y", "months-standAlone-narrow": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13" ], "eraNames": [ "ย.ศ." ], "field-weekOfMonth": "สัปดาห์ของเดือน", "dayPeriods-standAlone-abbr-pm": "หลังเที่ยง", "field-month-short": "เดือน", "dateFormatItem-GyMMMEd": "E d MMM G y", "dateFormatItem-yyyyMd": "d/M/y GGGGG", "field-day": "วัน", "field-dayOfYear-short": "วันของปี", "field-year-relative+-1": "ปีที่แล้ว", "dayPeriods-format-wide-am": "ก่อนเที่ยง", "field-sat-short-relative+-1": "เสาร์ที่แล้ว", "field-hour-relative+0": "ชั่วโมงนี้", "dateFormatItem-yyyyMEd": "E d/M/y GGGGG", "field-wed-relative+-1": "พุธที่แล้ว", "field-sat-narrow-relative+-1": "เสาร์ที่แล้ว", "field-second": "วินาที", "days-standAlone-narrow": [ "อา", "จ", "อ", "พ", "พฤ", "ศ", "ส" ], "dayPeriods-standAlone-wide-pm": "หลังเที่ยง", "dateFormat-long": "d MMMM G y", "dateFormatItem-GyMMMd": "d MMM G y", "field-quarter": "ไตรมาส", "field-week-short": "สัปดาห์", "field-day-narrow-relative+0": "วันนี้", "field-day-narrow-relative+1": "พรุ่งนี้", "field-day-narrow-relative+2": "มะรืนนี้", "quarters-standAlone-wide": [ "ไตรมาส 1", "ไตรมาส 2", "ไตรมาส 3", "ไตรมาส 4" ], "days-format-narrow": [ "อา", "จ", "อ", "พ", "พฤ", "ศ", "ส" ], "field-tue-short-relative+0": "อังคารนี้", "field-tue-short-relative+1": "อังคารหน้า", "field-month-short-relative+-1": "เดือนที่แล้ว", "field-mon-relative+-1": "จันทร์ที่แล้ว", "dateFormatItem-GyMMM": "MMM G y", "field-month": "เดือน", "field-day-narrow": "วัน", "field-dayperiod": "ช่วงวัน", "field-sat-short-relative+0": "เสาร์นี้", "field-sat-short-relative+1": "เสาร์หน้า", "dayPeriods-format-narrow-pm": "p", "dateFormat-medium": "d MMM G y", "dateFormatItem-yyyyMMMM": "MMMM G y", "eraAbbr": [ "ย.ศ." ], "quarters-standAlone-abbr": [ "ไตรมาส 1", "ไตรมาส 2", "ไตรมาส 3", "ไตรมาส 4" ], "dayPeriods-format-abbr-pm": "หลังเที่ยง", "dateFormatItem-yyyyM": "M/y G", "field-second-narrow": "วิ", "field-mon-relative+0": "จันทร์นี้", "field-mon-relative+1": "จันทร์หน้า", "field-day-narrow-relative+-1": "เมื่อวาน", "field-year-short": "ปี", "field-day-narrow-relative+-2": "เมื่อวานซืน", "months-format-narrow": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13" ], "field-quarter-relative+-1": "ไตรมาสที่แล้ว", "dateFormatItem-yyyyMMMd": "d MMM G y", "field-dayperiod-narrow": "ช่วงวัน", "dayPeriods-standAlone-narrow-am": "ก่อนเที่ยง", "field-week-narrow-relative+-1": "สัปดาห์ที่แล้ว", "days-format-short": [ "อา.", "จ.", "อ.", "พ.", "พฤ.", "ศ.", "ส." ], "dayPeriods-format-wide-pm": "หลังเที่ยง", "field-dayOfYear": "วันของปี", "field-sat-relative+-1": "เสาร์ที่แล้ว", "dateFormatItem-Md": "d/M", "field-hour": "ชั่วโมง", "months-format-wide": [ "ทิชรี", "เฮวาน", "กีสเลฟ", "เตเวต", "เชวัต", "อาดาร์ I", "อาดาร์", "นิสซาน", "อิยาร์", "สีวัน", "ตามูซ", "อัฟ", "เอลอุล" ], "dateFormat-full": "EEEEที่ d MMMM G y", "field-month-relative+-1": "เดือนที่แล้ว", "field-quarter-short": "ไตรมาส", "field-sat-narrow-relative+0": "เสาร์นี้", "field-fri-relative+0": "ศุกร์นี้", "field-sat-narrow-relative+1": "เสาร์หน้า", "field-fri-relative+1": "ศุกร์หน้า", "field-month-narrow-relative+0": "เดือนนี้", "field-month-narrow-relative+1": "เดือนหน้า", "field-sun-short-relative+0": "วันอาทิตย์นี้", "field-sun-short-relative+1": "วันอาทิตย์หน้า", "field-week-relative+-1": "สัปดาห์ที่แล้ว", "field-quarter-short-relative+-1": "ไตรมาสที่แล้ว", "months-format-abbr": [ "ทิชรี", "เฮวาน", "กีสเลฟ", "เตเวต", "เชวัต", "อาดาร์ I", "อาดาร์", "นิสซาน", "อิยาร์", "สีวัน", "ตามูซ", "อัฟ", "เอลอุล" ], "field-quarter-relative+0": "ไตรมาสนี้", "field-minute-relative+0": "นาทีนี้", "timeFormat-long": "H นาฬิกา mm นาที ss วินาที z", "field-quarter-relative+1": "ไตรมาสหน้า", "field-wed-short-relative+-1": "พุธที่แล้ว", "dateFormat-short": "d/M/y G", "field-thu-short-relative+-1": "พฤหัสที่แล้ว", "field-year-narrow-relative+-1": "ปีที่แล้ว", "days-standAlone-wide": [ "วันอาทิตย์", "วันจันทร์", "วันอังคาร", "วันพุธ", "วันพฤหัสบดี", "วันศุกร์", "วันเสาร์" ], "dateFormatItem-yyyyMMMEd": "E d MMM G y", "field-mon-narrow-relative+-1": "จันทร์ที่แล้ว", "dateFormatItem-MMMMd": "d MMMM", "field-thu-narrow-relative+-1": "พฤหัสที่แล้ว", "field-tue-narrow-relative+-1": "อังคารที่แล้ว", "field-weekOfMonth-short": "สัปดาห์ของเดือน", "dayPeriods-standAlone-narrow-pm": "หลังเที่ยง", "field-wed-short-relative+0": "พุธนี้", "months-standAlone-wide": [ "ทิชรี", "เฮวาน", "กีสเลฟ", "เตเวต", "เชวัต", "อาดาร์ I", "อาดาร์", "นิสซาน", "อิยาร์", "สีวัน", "ตามูซ", "อัฟ", "เอลอุล" ], "field-wed-short-relative+1": "พุธหน้า", "field-sun-relative+-1": "วันอาทิตย์ที่แล้ว", "days-standAlone-abbr": [ "อา.", "จ.", "อ.", "พ.", "พฤ.", "ศ.", "ส." ], "months-format-abbr-leap": "อาดาร์ II", "field-weekday": "วันของสัปดาห์", "months-standAlone-narrow-leap": "7", "field-day-short-relative+0": "วันนี้", "field-quarter-narrow-relative+0": "ไตรมาสนี้", "field-day-short-relative+1": "พรุ่งนี้", "field-sat-relative+0": "เสาร์นี้", "field-quarter-narrow-relative+1": "ไตรมาสหน้า", "field-day-short-relative+2": "มะรืนนี้", "field-sat-relative+1": "เสาร์หน้า", "field-week-short-relative+0": "สัปดาห์นี้", "field-week-short-relative+1": "สัปดาห์หน้า", "months-standAlone-abbr": [ "ทิชรี", "เฮวาน", "กีสเลฟ", "เตเวต", "เชวัต", "อาดาร์ I", "อาดาร์", "นิสซาน", "อิยาร์", "สีวัน", "ตามูซ", "อัฟ", "เอลอุล" ], "months-format-wide-leap": "อาดาร์ II", "months-format-narrow-leap": "7", "field-dayOfYear-narrow": "วันของปี", "field-month-short-relative+0": "เดือนนี้", "field-month-short-relative+1": "เดือนหน้า", "field-weekdayOfMonth-short": "วันของเดือน", "timeFormat-full": "H นาฬิกา mm นาที ss วินาที zzzz", "dateFormatItem-MEd": "E d/M", "field-zone-narrow": "เขตเวลา", "field-thu-narrow-relative+0": "พฤหัสนี้", "field-thu-narrow-relative+1": "พฤหัสหน้า", "field-sun-narrow-relative+-1": "วันอาทิตย์ที่แล้ว", "field-mon-short-relative+-1": "จันทร์ที่แล้ว", "field-thu-relative+0": "พฤหัสนี้", "field-thu-relative+1": "พฤหัสหน้า", "field-fri-short-relative+-1": "ศุกร์ที่แล้ว", "field-thu-relative+-1": "พฤหัสที่แล้ว", "field-week": "สัปดาห์", "quarters-format-wide": [ "ไตรมาส 1", "ไตรมาส 2", "ไตรมาส 3", "ไตรมาส 4" ], "dateFormatItem-Ed": "E d", "field-wed-narrow-relative+0": "พุธนี้", "field-wed-narrow-relative+1": "พุธหน้า", "field-quarter-narrow-relative+-1": "ไตรมาสที่แล้ว", "field-year-short-relative+0": "ปีนี้", "field-dayperiod-short": "ช่วงวัน", "dateFormatItem-yyyyMMM": "MMM G y", "field-year-short-relative+1": "ปีหน้า", "field-fri-short-relative+0": "ศุกร์นี้", "field-fri-short-relative+1": "ศุกร์หน้า", "days-standAlone-short": [ "อา.", "จ.", "อ.", "พ.", "พฤ.", "ศ.", "ส." ], "field-week-short-relative+-1": "สัปดาห์ที่แล้ว", "months-standAlone-abbr-leap": "อาดาร์ II", "dateFormatItem-yyyyQQQQ": "QQQQ G y", "field-hour-short": "ชม.", "field-zone-short": "โซน", "quarters-format-abbr": [ "ไตรมาส 1", "ไตรมาส 2", "ไตรมาส 3", "ไตรมาส 4" ], "field-month-narrow": "เดือน", "field-hour-narrow": "ชม.", "field-fri-narrow-relative+-1": "ศุกร์ที่แล้ว", "field-year-relative+0": "ปีนี้", "field-year-relative+1": "ปีหน้า", "field-era-narrow": "สมัย", "field-fri-relative+-1": "ศุกร์ที่แล้ว", "eraNarrow": [ "ย.ศ." ], "field-tue-short-relative+-1": "อังคารที่แล้ว", "field-minute-narrow": "นาที", "days-format-wide": [ "วันอาทิตย์", "วันจันทร์", "วันอังคาร", "วันพุธ", "วันพฤหัสบดี", "วันศุกร์", "วันเสาร์" ], "field-mon-narrow-relative+0": "จันทร์นี้", "field-mon-narrow-relative+1": "จันทร์หน้า", "field-year-short-relative+-1": "ปีที่แล้ว", "field-zone": "เขตเวลา", "dateFormatItem-MMMEd": "E d MMM", "field-weekOfMonth-narrow": "สัปดาห์ของเดือน", "field-weekday-narrow": "วันของสัปดาห์", "months-standAlone-wide-leap": "อาดาร์ II", "field-quarter-narrow": "ไตรมาส", "field-sun-short-relative+-1": "วันอาทิตย์ที่แล้ว", "field-day-relative+-1": "เมื่อวาน", "dayPeriods-standAlone-abbr-am": "ก่อนเที่ยง", "field-day-relative+-2": "เมื่อวานซืน", "field-weekday-short": "วันของสัปดาห์", "days-format-abbr": [ "อา.", "จ.", "อ.", "พ.", "พฤ.", "ศ.", "ส." ], "field-sun-relative+0": "วันอาทิตย์นี้", "field-sun-relative+1": "วันอาทิตย์หน้า", "field-day-short": "วัน", "field-week-narrow": "สัปดาห์", "field-era": "สมัย", "field-fri-narrow-relative+0": "ศุกร์นี้", "field-fri-narrow-relative+1": "ศุกร์หน้า", "dayPeriods-standAlone-wide-am": "ก่อนเที่ยง" } //end v1.x content );
ustegrew/ustegrew.github.io
courses/it001/lib/dojo/dojo/cldr/nls/th/hebrew.js.uncompressed.js
JavaScript
gpl-3.0
14,840
/* * Copyright (C) 2010-2016 Structr GmbH * * This file is part of Structr <http://structr.org>. * * Structr 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. * * Structr 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 Structr. If not, see <http://www.gnu.org/licenses/>. */ var animating = false; var timeout = 0; var expanded = {}; var count = 0; $(function() { doLayout(20); s.bind('clickNode', nodeClicked); s.bind('overNode', nodeHovered); s.bind('outNode', function(node) { if (!timeout) { timeout = window.setTimeout(function() { if (timeout) { timeout = 0; $('#graph-info').empty(); } }, 1000); } s.refresh(); }); }); function nodeHovered(node) { var domainOnly = false; if (window.domainOnly && window.domainOnly === true) { domainOnly = true; } if (animating) { return; } window.clearTimeout(timeout); timeout = 0; $('#graph-info').empty(); if (expanded[node.data.node.id] && expanded[node.data.node.id].state === 'expanded') { return; } var hoverMap = {}; $('#graph-info').append('<span>Loading...</span>'); $.ajax({ url: '/structr/rest/' + node.data.node.id + '/out/_graph' + (domainOnly ? '?domainOnly=true' : ''), contentType: 'application/json', method: 'GET', statusCode: { 200: function(data) { $.each(data.result, function(i, result) { if (!s.graph.nodes(result.targetNode.id)) { if (hoverMap[result.targetNode.type]) { hoverMap[result.targetNode.type]++; } else { hoverMap[result.targetNode.type] = 1; } } }); $.ajax({ url: '/structr/rest/' + node.data.node.id + '/in/_graph' + (domainOnly ? '?domainOnly=true' : ''), contentType: 'application/json', method: 'GET', statusCode: { 200: function(data) { $.each(data.result, function(i, result) { if (!s.graph.nodes(result.id)) { if (hoverMap[result.sourceNode.type]) { hoverMap[result.sourceNode.type]++; } else { hoverMap[result.sourceNode.type] = 1; } } }); updateHoverInfo(node, hoverMap); } } }); } } }); } function updateHoverInfo(node, hoverMap) { var graphInfo = $('#graph-info'); var num = Object.keys(hoverMap).length; var i = 0; var size = node.data.node['renderer1:size']; var radius = Math.max(size, 40); var x = Math.floor(node.data.node['renderer1:x']); var y = node.data.node['renderer1:y']; var startAngle = 0; switch (num) { case 2: startAngle = (Math.PI / 8) * 7; break; case 3: startAngle = (Math.PI / 4) * 3; break; case 4: startAngle = (Math.PI / 8) * 5; break; case 5: startAngle = (Math.PI / 8) * 4; break; case 6: startAngle = (Math.PI / 8) * 3; break; case 7: startAngle = (Math.PI / 8) * 7; break; default: startAngle = Math.PI; break; } if (num < 8) { num = 8; } graphInfo.empty(); $.each(hoverMap, function(key, value) { var label = key + ' (' + value + ')'; var angle = startAngle + (Math.PI * 2 / num) * i; var cos = Math.cos(angle); var sin = Math.sin(angle); var dx = (cos * radius) - 15; var dy = (sin * radius) - 15; graphInfo.append('<button class="circle" id="' + key + '-button" style="position: absolute; top: 0px; left: 0px; z-index: 10000;" title="' + label + '">' + value + '</button>'); graphInfo.append('<button class="btn btn-xs" style="margin: 4px; color: #000; background-color: ' + color[key] + '">' + label + '</button>'); var button = $('#' + key + '-button'); button.css('border', 'none'); button.css('background-color', color[key]); button.css('width', '30'); button.css('height', '30'); button.css('color', '#000'); button.css('top', (y + dy + 28) + 'px'); // 28 is the height of the #graph-info div button.css('left', (x + dx) + 'px'); button.on('click', function(e) { node.data.node.size += 5; graphInfo.empty(); expandNode(node, key); s.refresh(); }); i++; }); s.refresh(); } function nodeClicked(node) { var id = node.data.node.id; $('#graph-info').empty(); if (expanded[id] && expanded[id].state === 'expanded') { node.data.node.size -= 5; collapseNode(node); s.refresh(); } else { node.data.node.size += 5; expandNode(node); s.refresh(); } } function expandNode(node, type) { var domainOnly = false; if (window.domainOnly && window.domainOnly === true) { domainOnly = true; } var id = node.data.node.id; var x = node.data.node.x; var y = node.data.node.y; expanded[id] = { state: 'expanded', nodes: expanded[id] ? expanded[id].nodes : [], edges: expanded[id] ? expanded[id].edges : [] }; $.ajax({ url: '/structr/rest/' + node.data.node.id + '/out/_graph' + (domainOnly ? '?domainOnly=true' : ''), contentType: 'application/json', method: 'GET', statusCode: { 200: function(data) { var nodes = {}; var edges = {}; $.each(data.result, function(i, result) { if (!type || result.targetNode.type === type) { addOutNode(nodes, edges, result, x, y); } }); update(id, nodes, edges); } } }); $.ajax({ url: '/structr/rest/' + node.data.node.id + '/in/_graph' + (domainOnly ? '?domainOnly=true' : ''), contentType: 'application/json', method: 'GET', statusCode: { 200: function(data) { var nodes = {}; var edges = {}; $.each(data.result, function(i, result) { if (!type || result.sourceNode.type === type) { addInNode(nodes, edges, result, x, y); } }); update(id, nodes, edges); } } }); } function collapseNode(node) { if (node) { var id = node.data ? node.data.node.id : node.id; if (expanded[id] && expanded[id].state === 'expanded') { var edges = expanded[id].edges; var nodes = expanded[id].nodes; // remove all edges from previous opening $.each(edges, function(i, e) { try { s.graph.dropEdge(e); } catch(x) {} }); // remove all nodes from previous opening $.each(nodes, function(i, n) { collapseNode(s.graph.nodes(n)); try { s.graph.dropNode(n); } catch(x) {} }); expanded[id].state = 'collapsed'; s.refresh(); } } } function addOutNode(nodes, edges, result, x, y) { var sourceNode = result.sourceNode; var targetNode = result.targetNode; var newX = x + (Math.random() * 100) - 50; var newY = y + (Math.random() * 100) - 50; var size = 10; nodes[targetNode.id] = {id: targetNode.id, label: targetNode.name, size: size, x: newX, y: newY, color: color[targetNode.type]}; edges[result.id] = {id: result.id, source: sourceNode.id, target: targetNode.id, label: result.relType, type: 'curvedArrow', color: '#999'}; } function addInNode(nodes, edges, result, x, y) { var sourceNode = result.sourceNode; var targetNode = result.targetNode; var newX = x + (Math.random() * 100) - 50; var newY = y + (Math.random() * 100) - 50; var size = 10; nodes[sourceNode.id] = {id: sourceNode.id, label: sourceNode.name, size: size, x: newX, y: newY, color: color[sourceNode.type]}; edges[result.id] = {id: result.id, source: sourceNode.id, target: targetNode.id, label: result.relType, type: 'curvedArrow', color: '#999'}; } function update(current, nodes, edges) { var added = 0; $.each(nodes, function(i, node) { try { s.graph.addNode(node); // only add expanded node if addNode() is successful => node did not exist before expanded[current].nodes.push(node.id); added++; } catch (e) {} }); $.each(edges, function(i, edge) { try { s.graph.addEdge(edge); // only add expanded edge if addEdge() is successful => edge did not exist before expanded[current].edges.push(edge.id); added++; } catch (e) {} }); if (added) { s.refresh(); doLayout(added); } } function doLayout(num) { running = true; restartLayout(num); } function restartLayout(num) { window.setTimeout(function() { animating = true; sigma.layouts.fruchtermanReingold.start(s, { autoArea: false, area: 1000000000, gravity: 0, speed: 0.1, iterations: 10 }); animating = false; if (count++ < num) { restartLayout(num); } else { count = 0; } }, 20); }
joansmith/structr
structr-ui/src/main/resources/structr/js/graph-browser.js
JavaScript
gpl-3.0
9,207
// Namespace our app var app = app || {}; // The view for all the comics app.allComicsView = Backbone.View.extend({ tagName: "section", class: "comicGallery", initialize : function(){ //This is useful to bind(or delegate) the this keyword inside all the function objects //to the view. Read more here: http://documentcloud.github.com/underscore/#bindAll _.bindAll(this); this.collection.bind('add', this.addItemHandler); }, load : function(){ //here we do the AJAX Request to get our json file, also provide a success and error callbacks this.collection.fetch({ add: true, success: this.loadSuccessHandler, error: this.errorHandler }); }, loadCustomView : function () { this.collection.models.forEach(function(element, index){ this.addItemHandler(element); }, this); this.render(); }, //we arrived here one time per item in our list, so if we received 4 items we //will arrive into this function 4 times addItemHandler : function(model){ //model is an instance of RealWorldItemModel var myItemView = new app.singleComicView({model:model}); myItemView.render(); $(this.el).append(myItemView.el); }, loadSuccessHandler : function(){ this.render(); }, errorHandler : function(){ throw "Error loading comics JSON file"; }, render: function() { $('#contentArea').append($(this.el)); return this; } });
pauloeojeda/webui-comic
js/views/allComicsView.js
JavaScript
gpl-3.0
1,570