text
stringlengths
3
1.05M
:mod:`corpora.lowcorpus` -- Corpus in List-of-Words format =========================================================== .. automodule:: gensim.corpora.lowcorpus :synopsis: Corpus in List-of-Words format :members: :inherited-members:
//======================================================================= // Copyright (c) 2014-2020 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #define ETL_COUNTERS #define ETL_GPU_POOL #include "dll/neural/dense/dense_layer.hpp" #include "dll/neural/lstm/lstm_layer.hpp" #include "dll/neural/recurrent/recurrent_last_layer.hpp" #include "dll/network.hpp" #include "dll/datasets.hpp" int main(int /*argc*/, char* /*argv*/ []) { // Load the dataset auto dataset = dll::make_mnist_dataset_nc(dll::batch_size<200>{}, dll::scale_pre<255>{}); constexpr size_t time_steps = 28; constexpr size_t sequence_length = 28; constexpr size_t hidden_units = 100; // Build the network using network_t = dll::network_desc< dll::network_layers< dll::lstm_layer<time_steps, sequence_length, hidden_units, dll::last_only>, dll::recurrent_last_layer<time_steps, hidden_units>, dll::dense_layer<hidden_units, 10, dll::softmax> > , dll::updater<dll::updater_type::ADAM> // Adam , dll::batch_size<200> // The mini-batch size , dll::no_batch_display // Disable pretty print of each every batch , dll::no_epoch_error // Disable computation of the error at each epoch >::network_t; auto net = std::make_unique<network_t>(); // Display the network and dataset net->display_pretty(); dataset.display_pretty(); // Train the network for performance sake net->train(dataset.train(), 5); // Test the network on test set net->evaluate(dataset.test()); // Show where the time was spent dll::dump_timers_pretty(); // Show ETL performance counters etl::dump_counters_pretty(); return 0; }
package checkpoint import ( "encoding/json" "k8s.io/kubernetes/pkg/kubelet/checkpointmanager" "k8s.io/kubernetes/pkg/kubelet/checkpointmanager/checksum" ) type DeviceManagerCheckpoint interface { checkpointmanager.Checkpoint GetData() ([]PodDevicesEntry, map[string][]string) } type PodDevicesEntry struct { PodUID string ContainerName string ResourceName string DeviceIDs []string AllocResp []byte } // checkpointData struct is used to store pod to device allocation information // in a checkpoint file. // TODO: add version control when we need to change checkpoint format. type checkpointData struct { PodDeviceEntries []PodDevicesEntry RegisteredDevices map[string][]string } type Data struct { Data checkpointData Checksum checksum.Checksum } // NewDeviceManagerCheckpoint returns an instance of Checkpoint func New(devEntries []PodDevicesEntry, devices map[string][]string) DeviceManagerCheckpoint { return &Data{ Data: checkpointData{ PodDeviceEntries: devEntries, RegisteredDevices: devices, }, } } // MarshalCheckpoint returns marshalled data func (cp *Data) MarshalCheckpoint() ([]byte, error) { cp.Checksum = checksum.New(cp.Data) return json.Marshal(*cp) } // UnmarshalCheckpoint returns unmarshalled data func (cp *Data) UnmarshalCheckpoint(blob []byte) error { return json.Unmarshal(blob, cp) } // VerifyChecksum verifies that passed checksum is same as calculated checksum func (cp *Data) VerifyChecksum() error { return cp.Checksum.Verify(cp.Data) } func (cp *Data) GetData() ([]PodDevicesEntry, map[string][]string) { return cp.Data.PodDeviceEntries, cp.Data.RegisteredDevices }
id: maximum-number-of-jsx-root-nodes title: Maximum Number of JSX Root Nodes layout: tips permalink: maximum-number-of-jsx-root-nodes.html prev: self-closing-tag.html next: style-props-value-px.html --- Currently, in a component's `render`, you can only return one node; if you have, say, a list of `div`s to return, you must wrap your components within a `div`, `span` or any other component. Don't forget that JSX compiles into regular JS; returning two functions doesn't really make syntactic sense. Likewise, don't put more than one child in a ternary.
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="ProjectModuleManager"> <modules> <module fileurl="file://$PROJECT_DIR$/android-navigationview-material-design.iml" filepath="$PROJECT_DIR$/android-navigationview-material-design.iml" /> <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" /> </modules> </component> </project>
package org.apache.sling.commons.messaging.mail.internal; import java.util.Collections; import java.util.Map; import javax.annotation.Nonnull; import org.apache.commons.mail.Email; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.SimpleEmail; import org.apache.sling.commons.messaging.mail.MailBuilder; import org.osgi.framework.Constants; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ConfigurationPolicy; import org.osgi.service.component.annotations.Modified; import org.osgi.service.metatype.annotations.Designate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Component( service = MailBuilder.class, property = { Constants.SERVICE_DESCRIPTION + "=Service to build simple mails.", Constants.SERVICE_VENDOR + "=The Apache Software Foundation" }, configurationPolicy = ConfigurationPolicy.REQUIRE ) @Designate( ocd = SimpleMailBuilderConfiguration.class ) public class SimpleMailBuilder implements MailBuilder { // TODO use encryption and support more configuration options private SimpleMailBuilderConfiguration configuration; private static final String SUBJECT_KEY = "mail.subject"; private static final String FROM_KEY = "mail.from"; private static final String CHARSET_KEY = "mail.charset"; private static final String SMTP_HOSTNAME_KEY = "mail.smtp.hostname"; private static final String SMTP_PORT_KEY = "mail.smtp.port"; private static final String SMTP_USERNAME_KEY = "mail.smtp.username"; private static final String SMTP_PASSWORD_KEY = "mail.smtp.password"; private final Logger logger = LoggerFactory.getLogger(SimpleMailBuilder.class); public SimpleMailBuilder() { } @Activate private void activate(final SimpleMailBuilderConfiguration configuration) { logger.debug("activate"); this.configuration = configuration; } @Modified private void modified(final SimpleMailBuilderConfiguration configuration) { logger.debug("modified"); this.configuration = configuration; } @Override public Email build(@Nonnull final String message, @Nonnull final String recipient, @Nonnull final Map data) throws EmailException { final Map configuration = (Map) data.getOrDefault("mail", Collections.EMPTY_MAP); final String subject = (String) configuration.getOrDefault(SUBJECT_KEY, this.configuration.subject()); final String from = (String) configuration.getOrDefault(FROM_KEY, this.configuration.from()); final String charset = (String) configuration.getOrDefault(CHARSET_KEY, this.configuration.charset()); final String smtpHostname = (String) configuration.getOrDefault(SMTP_HOSTNAME_KEY, this.configuration.smtpHostname()); final int smtpPort = (Integer) configuration.getOrDefault(SMTP_PORT_KEY, this.configuration.smtpPort()); final String smtpUsername = (String) configuration.getOrDefault(SMTP_USERNAME_KEY, this.configuration.smtpUsername()); final String smtpPassword = (String) configuration.getOrDefault(SMTP_PASSWORD_KEY, this.configuration.smtpPassword()); final Email email = new SimpleEmail(); email.setCharset(charset); email.setMsg(message); email.addTo(recipient); email.setSubject(subject); email.setFrom(from); email.setHostName(smtpHostname); email.setSmtpPort(smtpPort); email.setAuthentication(smtpUsername, smtpPassword); return email; } }
// Uses AMD or browser globals to create a jQuery plugin. (function (factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else { // Browser globals factory(jQuery); } } (function (jQuery) { var module = { exports: { } }; // Fake component (function() { var Dropzone, Emitter, camelize, contentLoaded, detectVerticalSquash, drawImageIOSFix, noop, without, __slice = [].slice, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; noop = function() {}; Emitter = (function() { function Emitter() {} Emitter.prototype.addEventListener = Emitter.prototype.on; Emitter.prototype.on = function(event, fn) { this._callbacks = this._callbacks || {}; if (!this._callbacks[event]) { this._callbacks[event] = []; } this._callbacks[event].push(fn); return this; }; Emitter.prototype.emit = function() { var args, callback, callbacks, event, _i, _len; event = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; this._callbacks = this._callbacks || {}; callbacks = this._callbacks[event]; if (callbacks) { for (_i = 0, _len = callbacks.length; _i < _len; _i++) { callback = callbacks[_i]; callback.apply(this, args); } } return this; }; Emitter.prototype.removeListener = Emitter.prototype.off; Emitter.prototype.removeAllListeners = Emitter.prototype.off; Emitter.prototype.removeEventListener = Emitter.prototype.off; Emitter.prototype.off = function(event, fn) { var callback, callbacks, i, _i, _len; if (!this._callbacks || arguments.length === 0) { this._callbacks = {}; return this; } callbacks = this._callbacks[event]; if (!callbacks) { return this; } if (arguments.length === 1) { delete this._callbacks[event]; return this; } for (i = _i = 0, _len = callbacks.length; _i < _len; i = ++_i) { callback = callbacks[i]; if (callback === fn) { callbacks.splice(i, 1); break; } } return this; }; return Emitter; })(); Dropzone = (function(_super) { var extend; __extends(Dropzone, _super); Dropzone.prototype.Emitter = Emitter; /* This is a list of all available events you can register on a dropzone object. You can register an event handler like this: dropzone.on("dragEnter", function() { }); */ Dropzone.prototype.events = ["drop", "dragstart", "dragend", "dragenter", "dragover", "dragleave", "addedfile", "removedfile", "thumbnail", "error", "errormultiple", "processing", "processingmultiple", "uploadprogress", "totaluploadprogress", "sending", "sendingmultiple", "success", "successmultiple", "canceled", "canceledmultiple", "complete", "completemultiple", "reset", "maxfilesexceeded", "maxfilesreached"]; Dropzone.prototype.defaultOptions = { url: null, method: "post", withCredentials: false, parallelUploads: 2, uploadMultiple: false, maxFilesize: 256, paramName: "file", createImageThumbnails: true, maxThumbnailFilesize: 10, thumbnailWidth: 100, thumbnailHeight: 100, maxFiles: null, params: {}, clickable: true, ignoreHiddenFiles: true, acceptedFiles: null, acceptedMimeTypes: null, autoProcessQueue: true, autoQueue: true, addRemoveLinks: false, previewsContainer: null, capture: null, dictDefaultMessage: "Drop files here to upload", dictFallbackMessage: "Your browser does not support drag'n'drop file uploads.", dictFallbackText: "Please use the fallback form below to upload your files like in the olden days.", dictFileTooBig: "File is too big ({{filesize}}MiB). Max filesize: {{maxFilesize}}MiB.", dictInvalidFileType: "You can't upload files of this type.", dictResponseError: "Server responded with {{statusCode}} code.", dictCancelUpload: "Cancel upload", dictCancelUploadConfirmation: "Are you sure you want to cancel this upload?", dictRemoveFile: "Remove file", dictRemoveFileConfirmation: null, dictMaxFilesExceeded: "You can not upload any more files.", accept: function(file, done) { return done(); }, init: function() { return noop; }, forceFallback: false, fallback: function() { var child, messageElement, span, _i, _len, _ref; this.element.className = "" + this.element.className + " dz-browser-not-supported"; _ref = this.element.getElementsByTagName("div"); for (_i = 0, _len = _ref.length; _i < _len; _i++) { child = _ref[_i]; if (/(^| )dz-message($| )/.test(child.className)) { messageElement = child; child.className = "dz-message"; continue; } } if (!messageElement) { messageElement = Dropzone.createElement("<div class=\"dz-message\"><span></span></div>"); this.element.appendChild(messageElement); } span = messageElement.getElementsByTagName("span")[0]; if (span) { span.textContent = this.options.dictFallbackMessage; } return this.element.appendChild(this.getFallbackForm()); }, resize: function(file) { var info, srcRatio, trgRatio; info = { srcX: 0, srcY: 0, srcWidth: file.width, srcHeight: file.height }; srcRatio = file.width / file.height; info.optWidth = this.options.thumbnailWidth; info.optHeight = this.options.thumbnailHeight; if ((info.optWidth == null) && (info.optHeight == null)) { info.optWidth = info.srcWidth; info.optHeight = info.srcHeight; } else if (info.optWidth == null) { info.optWidth = srcRatio * info.optHeight; } else if (info.optHeight == null) { info.optHeight = (1 / srcRatio) * info.optWidth; } trgRatio = info.optWidth / info.optHeight; if (file.height < info.optHeight || file.width < info.optWidth) { info.trgHeight = info.srcHeight; info.trgWidth = info.srcWidth; } else { if (srcRatio > trgRatio) { info.srcHeight = file.height; info.srcWidth = info.srcHeight * trgRatio; } else { info.srcWidth = file.width; info.srcHeight = info.srcWidth / trgRatio; } } info.srcX = (file.width - info.srcWidth) / 2; info.srcY = (file.height - info.srcHeight) / 2; return info; }, /* Those functions register themselves to the events on init and handle all the user interface specific stuff. Overwriting them won't break the upload but can break the way it's displayed. You can overwrite them if you don't like the default behavior. If you just want to add an additional event handler, register it on the dropzone object and don't overwrite those options. */ drop: function(e) { return this.element.classList.remove("dz-drag-hover"); }, dragstart: noop, dragend: function(e) { return this.element.classList.remove("dz-drag-hover"); }, dragenter: function(e) { return this.element.classList.add("dz-drag-hover"); }, dragover: function(e) { return this.element.classList.add("dz-drag-hover"); }, dragleave: function(e) { return this.element.classList.remove("dz-drag-hover"); }, paste: noop, reset: function() { return this.element.classList.remove("dz-started"); }, addedfile: function(file) { var node, removeFileEvent, removeLink, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2, _results; if (this.element === this.previewsContainer) { this.element.classList.add("dz-started"); } if (this.previewsContainer) { file.previewElement = Dropzone.createElement(this.options.previewTemplate.trim()); file.previewTemplate = file.previewElement; this.previewsContainer.appendChild(file.previewElement); _ref = file.previewElement.querySelectorAll("[data-dz-name]"); for (_i = 0, _len = _ref.length; _i < _len; _i++) { node = _ref[_i]; node.textContent = file.name; } _ref1 = file.previewElement.querySelectorAll("[data-dz-size]"); for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { node = _ref1[_j]; node.innerHTML = this.filesize(file.size); } if (this.options.addRemoveLinks) { file._removeLink = Dropzone.createElement("<a class=\"dz-remove\" href=\"javascript:undefined;\" data-dz-remove>" + this.options.dictRemoveFile + "</a>"); file.previewElement.appendChild(file._removeLink); } removeFileEvent = (function(_this) { return function(e) { e.preventDefault(); e.stopPropagation(); if (file.status === Dropzone.UPLOADING) { return Dropzone.confirm(_this.options.dictCancelUploadConfirmation, function() { return _this.removeFile(file); }); } else { if (_this.options.dictRemoveFileConfirmation) { return Dropzone.confirm(_this.options.dictRemoveFileConfirmation, function() { return _this.removeFile(file); }); } else { return _this.removeFile(file); } } }; })(this); _ref2 = file.previewElement.querySelectorAll("[data-dz-remove]"); _results = []; for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { removeLink = _ref2[_k]; _results.push(removeLink.addEventListener("click", removeFileEvent)); } return _results; } }, removedfile: function(file) { var _ref; if (file.previewElement) { if ((_ref = file.previewElement) != null) { _ref.parentNode.removeChild(file.previewElement); } } return this._updateMaxFilesReachedClass(); }, thumbnail: function(file, dataUrl) { var thumbnailElement, _i, _len, _ref, _results; if (file.previewElement) { file.previewElement.classList.remove("dz-file-preview"); file.previewElement.classList.add("dz-image-preview"); _ref = file.previewElement.querySelectorAll("[data-dz-thumbnail]"); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { thumbnailElement = _ref[_i]; thumbnailElement.alt = file.name; _results.push(thumbnailElement.src = dataUrl); } return _results; } }, error: function(file, message) { var node, _i, _len, _ref, _results; if (file.previewElement) { file.previewElement.classList.add("dz-error"); if (typeof message !== "String" && message.error) { message = message.error; } _ref = file.previewElement.querySelectorAll("[data-dz-errormessage]"); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { node = _ref[_i]; _results.push(node.textContent = message); } return _results; } }, errormultiple: noop, processing: function(file) { if (file.previewElement) { file.previewElement.classList.add("dz-processing"); if (file._removeLink) { return file._removeLink.textContent = this.options.dictCancelUpload; } } }, processingmultiple: noop, uploadprogress: function(file, progress, bytesSent) { var node, _i, _len, _ref, _results; if (file.previewElement) { _ref = file.previewElement.querySelectorAll("[data-dz-uploadprogress]"); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { node = _ref[_i]; if (node.nodeName === 'PROGRESS') { _results.push(node.value = progress); } else { _results.push(node.style.width = "" + progress + "%"); } } return _results; } }, totaluploadprogress: noop, sending: noop, sendingmultiple: noop, success: function(file) { if (file.previewElement) { return file.previewElement.classList.add("dz-success"); } }, successmultiple: noop, canceled: function(file) { return this.emit("error", file, "Upload canceled."); }, canceledmultiple: noop, complete: function(file) { if (file._removeLink) { return file._removeLink.textContent = this.options.dictRemoveFile; } }, completemultiple: noop, maxfilesexceeded: noop, maxfilesreached: noop, previewTemplate: "<div class=\"dz-preview dz-file-preview\">\n <div class=\"dz-details\">\n <div class=\"dz-filename\"><span data-dz-name></span></div>\n <div class=\"dz-size\" data-dz-size></div>\n <img data-dz-thumbnail />\n </div>\n <div class=\"dz-progress\"><span class=\"dz-upload\" data-dz-uploadprogress></span></div>\n <div class=\"dz-success-mark\"><span>✔</span></div>\n <div class=\"dz-error-mark\"><span>✘</span></div>\n <div class=\"dz-error-message\"><span data-dz-errormessage></span></div>\n</div>" }; extend = function() { var key, object, objects, target, val, _i, _len; target = arguments[0], objects = 2 <= arguments.length ? __slice.call(arguments, 1) : []; for (_i = 0, _len = objects.length; _i < _len; _i++) { object = objects[_i]; for (key in object) { val = object[key]; target[key] = val; } } return target; }; function Dropzone(element, options) { var elementOptions, fallback, _ref; this.element = element; this.version = Dropzone.version; this.defaultOptions.previewTemplate = this.defaultOptions.previewTemplate.replace(/\n*/g, ""); this.clickableElements = []; this.listeners = []; this.files = []; if (typeof this.element === "string") { this.element = document.querySelector(this.element); } if (!(this.element && (this.element.nodeType != null))) { throw new Error("Invalid dropzone element."); } if (this.element.dropzone) { throw new Error("Dropzone already attached."); } Dropzone.instances.push(this); this.element.dropzone = this; elementOptions = (_ref = Dropzone.optionsForElement(this.element)) != null ? _ref : {}; this.options = extend({}, this.defaultOptions, elementOptions, options != null ? options : {}); if (this.options.forceFallback || !Dropzone.isBrowserSupported()) { return this.options.fallback.call(this); } if (this.options.url == null) { this.options.url = this.element.getAttribute("action"); } if (!this.options.url) { throw new Error("No URL provided."); } if (this.options.acceptedFiles && this.options.acceptedMimeTypes) { throw new Error("You can't provide both 'acceptedFiles' and 'acceptedMimeTypes'. 'acceptedMimeTypes' is deprecated."); } if (this.options.acceptedMimeTypes) { this.options.acceptedFiles = this.options.acceptedMimeTypes; delete this.options.acceptedMimeTypes; } this.options.method = this.options.method.toUpperCase(); if ((fallback = this.getExistingFallback()) && fallback.parentNode) { fallback.parentNode.removeChild(fallback); } if (this.options.previewsContainer !== false) { if (this.options.previewsContainer) { this.previewsContainer = Dropzone.getElement(this.options.previewsContainer, "previewsContainer"); } else { this.previewsContainer = this.element; } } if (this.options.clickable) { if (this.options.clickable === true) { this.clickableElements = [this.element]; } else { this.clickableElements = Dropzone.getElements(this.options.clickable, "clickable"); } } this.init(); } Dropzone.prototype.getAcceptedFiles = function() { var file, _i, _len, _ref, _results; _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (file.accepted) { _results.push(file); } } return _results; }; Dropzone.prototype.getRejectedFiles = function() { var file, _i, _len, _ref, _results; _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (!file.accepted) { _results.push(file); } } return _results; }; Dropzone.prototype.getFilesWithStatus = function(status) { var file, _i, _len, _ref, _results; _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (file.status === status) { _results.push(file); } } return _results; }; Dropzone.prototype.getQueuedFiles = function() { return this.getFilesWithStatus(Dropzone.QUEUED); }; Dropzone.prototype.getUploadingFiles = function() { return this.getFilesWithStatus(Dropzone.UPLOADING); }; Dropzone.prototype.getActiveFiles = function() { var file, _i, _len, _ref, _results; _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (file.status === Dropzone.UPLOADING || file.status === Dropzone.QUEUED) { _results.push(file); } } return _results; }; Dropzone.prototype.init = function() { var eventName, noPropagation, setupHiddenFileInput, _i, _len, _ref, _ref1; if (this.element.tagName === "form") { this.element.setAttribute("enctype", "multipart/form-data"); } if (this.element.classList.contains("dropzone") && !this.element.querySelector(".dz-message")) { this.element.appendChild(Dropzone.createElement("<div class=\"dz-default dz-message\"><span>" + this.options.dictDefaultMessage + "</span></div>")); } if (this.clickableElements.length) { setupHiddenFileInput = (function(_this) { return function() { if (_this.hiddenFileInput) { document.body.removeChild(_this.hiddenFileInput); } _this.hiddenFileInput = document.createElement("input"); _this.hiddenFileInput.setAttribute("type", "file"); if ((_this.options.maxFiles == null) || _this.options.maxFiles > 1) { _this.hiddenFileInput.setAttribute("multiple", "multiple"); } _this.hiddenFileInput.className = "dz-hidden-input"; if (_this.options.acceptedFiles != null) { _this.hiddenFileInput.setAttribute("accept", _this.options.acceptedFiles); } if (_this.options.capture != null) { _this.hiddenFileInput.setAttribute("capture", _this.options.capture); } _this.hiddenFileInput.style.visibility = "hidden"; _this.hiddenFileInput.style.position = "absolute"; _this.hiddenFileInput.style.top = "0"; _this.hiddenFileInput.style.left = "0"; _this.hiddenFileInput.style.height = "0"; _this.hiddenFileInput.style.width = "0"; document.body.appendChild(_this.hiddenFileInput); return _this.hiddenFileInput.addEventListener("change", function() { var file, files, _i, _len; files = _this.hiddenFileInput.files; if (files.length) { for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; _this.addFile(file); } } return setupHiddenFileInput(); }); }; })(this); setupHiddenFileInput(); } this.URL = (_ref = window.URL) != null ? _ref : window.webkitURL; _ref1 = this.events; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { eventName = _ref1[_i]; this.on(eventName, this.options[eventName]); } this.on("uploadprogress", (function(_this) { return function() { return _this.updateTotalUploadProgress(); }; })(this)); this.on("removedfile", (function(_this) { return function() { return _this.updateTotalUploadProgress(); }; })(this)); this.on("canceled", (function(_this) { return function(file) { return _this.emit("complete", file); }; })(this)); this.on("complete", (function(_this) { return function(file) { if (_this.getUploadingFiles().length === 0 && _this.getQueuedFiles().length === 0) { return setTimeout((function() { return _this.emit("queuecomplete"); }), 0); } }; })(this)); noPropagation = function(e) { e.stopPropagation(); if (e.preventDefault) { return e.preventDefault(); } else { return e.returnValue = false; } }; this.listeners = [ { element: this.element, events: { "dragstart": (function(_this) { return function(e) { return _this.emit("dragstart", e); }; })(this), "dragenter": (function(_this) { return function(e) { noPropagation(e); return _this.emit("dragenter", e); }; })(this), "dragover": (function(_this) { return function(e) { var efct; try { efct = e.dataTransfer.effectAllowed; } catch (_error) {} e.dataTransfer.dropEffect = 'move' === efct || 'linkMove' === efct ? 'move' : 'copy'; noPropagation(e); return _this.emit("dragover", e); }; })(this), "dragleave": (function(_this) { return function(e) { return _this.emit("dragleave", e); }; })(this), "drop": (function(_this) { return function(e) { noPropagation(e); return _this.drop(e); }; })(this), "dragend": (function(_this) { return function(e) { return _this.emit("dragend", e); }; })(this) } } ]; this.clickableElements.forEach((function(_this) { return function(clickableElement) { return _this.listeners.push({ element: clickableElement, events: { "click": function(evt) { if ((clickableElement !== _this.element) || (evt.target === _this.element || Dropzone.elementInside(evt.target, _this.element.querySelector(".dz-message")))) { return _this.hiddenFileInput.click(); } } } }); }; })(this)); this.enable(); return this.options.init.call(this); }; Dropzone.prototype.destroy = function() { var _ref; this.disable(); this.removeAllFiles(true); if ((_ref = this.hiddenFileInput) != null ? _ref.parentNode : void 0) { this.hiddenFileInput.parentNode.removeChild(this.hiddenFileInput); this.hiddenFileInput = null; } delete this.element.dropzone; return Dropzone.instances.splice(Dropzone.instances.indexOf(this), 1); }; Dropzone.prototype.updateTotalUploadProgress = function() { var activeFiles, file, totalBytes, totalBytesSent, totalUploadProgress, _i, _len, _ref; totalBytesSent = 0; totalBytes = 0; activeFiles = this.getActiveFiles(); if (activeFiles.length) { _ref = this.getActiveFiles(); for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; totalBytesSent += file.upload.bytesSent; totalBytes += file.upload.total; } totalUploadProgress = 100 * totalBytesSent / totalBytes; } else { totalUploadProgress = 100; } return this.emit("totaluploadprogress", totalUploadProgress, totalBytes, totalBytesSent); }; Dropzone.prototype._getParamName = function(n) { if (typeof this.options.paramName === "function") { return this.options.paramName(n); } else { return "" + this.options.paramName + (this.options.uploadMultiple ? "[" + n + "]" : ""); } }; Dropzone.prototype.getFallbackForm = function() { var existingFallback, fields, fieldsString, form; if (existingFallback = this.getExistingFallback()) { return existingFallback; } fieldsString = "<div class=\"dz-fallback\">"; if (this.options.dictFallbackText) { fieldsString += "<p>" + this.options.dictFallbackText + "</p>"; } fieldsString += "<input type=\"file\" name=\"" + (this._getParamName(0)) + "\" " + (this.options.uploadMultiple ? 'multiple="multiple"' : void 0) + " /><input type=\"submit\" value=\"Upload!\"></div>"; fields = Dropzone.createElement(fieldsString); if (this.element.tagName !== "FORM") { form = Dropzone.createElement("<form action=\"" + this.options.url + "\" enctype=\"multipart/form-data\" method=\"" + this.options.method + "\"></form>"); form.appendChild(fields); } else { this.element.setAttribute("enctype", "multipart/form-data"); this.element.setAttribute("method", this.options.method); } return form != null ? form : fields; }; Dropzone.prototype.getExistingFallback = function() { var fallback, getFallback, tagName, _i, _len, _ref; getFallback = function(elements) { var el, _i, _len; for (_i = 0, _len = elements.length; _i < _len; _i++) { el = elements[_i]; if (/(^| )fallback($| )/.test(el.className)) { return el; } } }; _ref = ["div", "form"]; for (_i = 0, _len = _ref.length; _i < _len; _i++) { tagName = _ref[_i]; if (fallback = getFallback(this.element.getElementsByTagName(tagName))) { return fallback; } } }; Dropzone.prototype.setupEventListeners = function() { var elementListeners, event, listener, _i, _len, _ref, _results; _ref = this.listeners; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { elementListeners = _ref[_i]; _results.push((function() { var _ref1, _results1; _ref1 = elementListeners.events; _results1 = []; for (event in _ref1) { listener = _ref1[event]; _results1.push(elementListeners.element.addEventListener(event, listener, false)); } return _results1; })()); } return _results; }; Dropzone.prototype.removeEventListeners = function() { var elementListeners, event, listener, _i, _len, _ref, _results; _ref = this.listeners; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { elementListeners = _ref[_i]; _results.push((function() { var _ref1, _results1; _ref1 = elementListeners.events; _results1 = []; for (event in _ref1) { listener = _ref1[event]; _results1.push(elementListeners.element.removeEventListener(event, listener, false)); } return _results1; })()); } return _results; }; Dropzone.prototype.disable = function() { var file, _i, _len, _ref, _results; this.clickableElements.forEach(function(element) { return element.classList.remove("dz-clickable"); }); this.removeEventListeners(); _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; _results.push(this.cancelUpload(file)); } return _results; }; Dropzone.prototype.enable = function() { this.clickableElements.forEach(function(element) { return element.classList.add("dz-clickable"); }); return this.setupEventListeners(); }; Dropzone.prototype.filesize = function(size) { var string; if (size >= 1024 * 1024 * 1024 * 1024 / 10) { size = size / (1024 * 1024 * 1024 * 1024 / 10); string = "TiB"; } else if (size >= 1024 * 1024 * 1024 / 10) { size = size / (1024 * 1024 * 1024 / 10); string = "GiB"; } else if (size >= 1024 * 1024 / 10) { size = size / (1024 * 1024 / 10); string = "MiB"; } else if (size >= 1024 / 10) { size = size / (1024 / 10); string = "KiB"; } else { size = size * 10; string = "b"; } return "<strong>" + (Math.round(size) / 10) + "</strong> " + string; }; Dropzone.prototype._updateMaxFilesReachedClass = function() { if ((this.options.maxFiles != null) && this.getAcceptedFiles().length >= this.options.maxFiles) { if (this.getAcceptedFiles().length === this.options.maxFiles) { this.emit('maxfilesreached', this.files); } return this.element.classList.add("dz-max-files-reached"); } else { return this.element.classList.remove("dz-max-files-reached"); } }; Dropzone.prototype.drop = function(e) { var files, items; if (!e.dataTransfer) { return; } this.emit("drop", e); files = e.dataTransfer.files; if (files.length) { items = e.dataTransfer.items; if (items && items.length && (items[0].webkitGetAsEntry != null)) { this._addFilesFromItems(items); } else { this.handleFiles(files); } } }; Dropzone.prototype.paste = function(e) { var items, _ref; if ((e != null ? (_ref = e.clipboardData) != null ? _ref.items : void 0 : void 0) == null) { return; } this.emit("paste", e); items = e.clipboardData.items; if (items.length) { return this._addFilesFromItems(items); } }; Dropzone.prototype.handleFiles = function(files) { var file, _i, _len, _results; _results = []; for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; _results.push(this.addFile(file)); } return _results; }; Dropzone.prototype._addFilesFromItems = function(items) { var entry, item, _i, _len, _results; _results = []; for (_i = 0, _len = items.length; _i < _len; _i++) { item = items[_i]; if ((item.webkitGetAsEntry != null) && (entry = item.webkitGetAsEntry())) { if (entry.isFile) { _results.push(this.addFile(item.getAsFile())); } else if (entry.isDirectory) { _results.push(this._addFilesFromDirectory(entry, entry.name)); } else { _results.push(void 0); } } else if (item.getAsFile != null) { if ((item.kind == null) || item.kind === "file") { _results.push(this.addFile(item.getAsFile())); } else { _results.push(void 0); } } else { _results.push(void 0); } } return _results; }; Dropzone.prototype._addFilesFromDirectory = function(directory, path) { var dirReader, entriesReader; dirReader = directory.createReader(); entriesReader = (function(_this) { return function(entries) { var entry, _i, _len; for (_i = 0, _len = entries.length; _i < _len; _i++) { entry = entries[_i]; if (entry.isFile) { entry.file(function(file) { if (_this.options.ignoreHiddenFiles && file.name.substring(0, 1) === '.') { return; } file.fullPath = "" + path + "/" + file.name; return _this.addFile(file); }); } else if (entry.isDirectory) { _this._addFilesFromDirectory(entry, "" + path + "/" + entry.name); } } }; })(this); return dirReader.readEntries(entriesReader, function(error) { return typeof console !== "undefined" && console !== null ? typeof console.log === "function" ? console.log(error) : void 0 : void 0; }); }; Dropzone.prototype.accept = function(file, done) { if (file.size > this.options.maxFilesize * 1024 * 1024) { return done(this.options.dictFileTooBig.replace("{{filesize}}", Math.round(file.size / 1024 / 10.24) / 100).replace("{{maxFilesize}}", this.options.maxFilesize)); } else if (!Dropzone.isValidFile(file, this.options.acceptedFiles)) { return done(this.options.dictInvalidFileType); } else if ((this.options.maxFiles != null) && this.getAcceptedFiles().length >= this.options.maxFiles) { done(this.options.dictMaxFilesExceeded.replace("{{maxFiles}}", this.options.maxFiles)); return this.emit("maxfilesexceeded", file); } else { return this.options.accept.call(this, file, done); } }; Dropzone.prototype.addFile = function(file) { file.upload = { progress: 0, total: file.size, bytesSent: 0 }; this.files.push(file); file.status = Dropzone.ADDED; this.emit("addedfile", file); this._enqueueThumbnail(file); return this.accept(file, (function(_this) { return function(error) { if (error) { file.accepted = false; _this._errorProcessing([file], error); } else { file.accepted = true; if (_this.options.autoQueue) { _this.enqueueFile(file); } } return _this._updateMaxFilesReachedClass(); }; })(this)); }; Dropzone.prototype.enqueueFiles = function(files) { var file, _i, _len; for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; this.enqueueFile(file); } return null; }; Dropzone.prototype.enqueueFile = function(file) { if (file.status === Dropzone.ADDED && file.accepted === true) { file.status = Dropzone.QUEUED; if (this.options.autoProcessQueue) { return setTimeout(((function(_this) { return function() { return _this.processQueue(); }; })(this)), 0); } } else { throw new Error("This file can't be queued because it has already been processed or was rejected."); } }; Dropzone.prototype._thumbnailQueue = []; Dropzone.prototype._processingThumbnail = false; Dropzone.prototype._enqueueThumbnail = function(file) { if (this.options.createImageThumbnails && file.type.match(/image.*/) && file.size <= this.options.maxThumbnailFilesize * 1024 * 1024) { this._thumbnailQueue.push(file); return setTimeout(((function(_this) { return function() { return _this._processThumbnailQueue(); }; })(this)), 0); } }; Dropzone.prototype._processThumbnailQueue = function() { if (this._processingThumbnail || this._thumbnailQueue.length === 0) { return; } this._processingThumbnail = true; return this.createThumbnail(this._thumbnailQueue.shift(), (function(_this) { return function() { _this._processingThumbnail = false; return _this._processThumbnailQueue(); }; })(this)); }; Dropzone.prototype.removeFile = function(file) { if (file.status === Dropzone.UPLOADING) { this.cancelUpload(file); } this.files = without(this.files, file); this.emit("removedfile", file); if (this.files.length === 0) { return this.emit("reset"); } }; Dropzone.prototype.removeAllFiles = function(cancelIfNecessary) { var file, _i, _len, _ref; if (cancelIfNecessary == null) { cancelIfNecessary = false; } _ref = this.files.slice(); for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (file.status !== Dropzone.UPLOADING || cancelIfNecessary) { this.removeFile(file); } } return null; }; Dropzone.prototype.createThumbnail = function(file, callback) { var fileReader; fileReader = new FileReader; fileReader.onload = (function(_this) { return function() { var img; if (file.type === "image/svg+xml") { _this.emit("thumbnail", file, fileReader.result); if (callback != null) { callback(); } return; } img = document.createElement("img"); img.onload = function() { var canvas, ctx, resizeInfo, thumbnail, _ref, _ref1, _ref2, _ref3; file.width = img.width; file.height = img.height; resizeInfo = _this.options.resize.call(_this, file); if (resizeInfo.trgWidth == null) { resizeInfo.trgWidth = resizeInfo.optWidth; } if (resizeInfo.trgHeight == null) { resizeInfo.trgHeight = resizeInfo.optHeight; } canvas = document.createElement("canvas"); ctx = canvas.getContext("2d"); canvas.width = resizeInfo.trgWidth; canvas.height = resizeInfo.trgHeight; drawImageIOSFix(ctx, img, (_ref = resizeInfo.srcX) != null ? _ref : 0, (_ref1 = resizeInfo.srcY) != null ? _ref1 : 0, resizeInfo.srcWidth, resizeInfo.srcHeight, (_ref2 = resizeInfo.trgX) != null ? _ref2 : 0, (_ref3 = resizeInfo.trgY) != null ? _ref3 : 0, resizeInfo.trgWidth, resizeInfo.trgHeight); thumbnail = canvas.toDataURL("image/png"); _this.emit("thumbnail", file, thumbnail); if (callback != null) { return callback(); } }; return img.src = fileReader.result; }; })(this); return fileReader.readAsDataURL(file); }; Dropzone.prototype.processQueue = function() { var i, parallelUploads, processingLength, queuedFiles; parallelUploads = this.options.parallelUploads; processingLength = this.getUploadingFiles().length; i = processingLength; if (processingLength >= parallelUploads) { return; } queuedFiles = this.getQueuedFiles(); if (!(queuedFiles.length > 0)) { return; } if (this.options.uploadMultiple) { return this.processFiles(queuedFiles.slice(0, parallelUploads - processingLength)); } else { while (i < parallelUploads) { if (!queuedFiles.length) { return; } this.processFile(queuedFiles.shift()); i++; } } }; Dropzone.prototype.processFile = function(file) { return this.processFiles([file]); }; Dropzone.prototype.processFiles = function(files) { var file, _i, _len; for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; file.processing = true; file.status = Dropzone.UPLOADING; this.emit("processing", file); } if (this.options.uploadMultiple) { this.emit("processingmultiple", files); } return this.uploadFiles(files); }; Dropzone.prototype._getFilesWithXhr = function(xhr) { var file, files; return files = (function() { var _i, _len, _ref, _results; _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (file.xhr === xhr) { _results.push(file); } } return _results; }).call(this); }; Dropzone.prototype.cancelUpload = function(file) { var groupedFile, groupedFiles, _i, _j, _len, _len1, _ref; if (file.status === Dropzone.UPLOADING) { groupedFiles = this._getFilesWithXhr(file.xhr); for (_i = 0, _len = groupedFiles.length; _i < _len; _i++) { groupedFile = groupedFiles[_i]; groupedFile.status = Dropzone.CANCELED; } file.xhr.abort(); for (_j = 0, _len1 = groupedFiles.length; _j < _len1; _j++) { groupedFile = groupedFiles[_j]; this.emit("canceled", groupedFile); } if (this.options.uploadMultiple) { this.emit("canceledmultiple", groupedFiles); } } else if ((_ref = file.status) === Dropzone.ADDED || _ref === Dropzone.QUEUED) { file.status = Dropzone.CANCELED; this.emit("canceled", file); if (this.options.uploadMultiple) { this.emit("canceledmultiple", [file]); } } if (this.options.autoProcessQueue) { return this.processQueue(); } }; Dropzone.prototype.uploadFile = function(file) { return this.uploadFiles([file]); }; Dropzone.prototype.uploadFiles = function(files) { var file, formData, handleError, headerName, headerValue, headers, i, input, inputName, inputType, key, option, progressObj, response, updateProgress, value, xhr, _i, _j, _k, _l, _len, _len1, _len2, _len3, _m, _ref, _ref1, _ref2, _ref3, _ref4, _ref5; xhr = new XMLHttpRequest(); for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; file.xhr = xhr; } xhr.open(this.options.method, this.options.url, true); xhr.withCredentials = !!this.options.withCredentials; response = null; handleError = (function(_this) { return function() { var _j, _len1, _results; _results = []; for (_j = 0, _len1 = files.length; _j < _len1; _j++) { file = files[_j]; _results.push(_this._errorProcessing(files, response || _this.options.dictResponseError.replace("{{statusCode}}", xhr.status), xhr)); } return _results; }; })(this); updateProgress = (function(_this) { return function(e) { var allFilesFinished, progress, _j, _k, _l, _len1, _len2, _len3, _results; if (e != null) { progress = 100 * e.loaded / e.total; for (_j = 0, _len1 = files.length; _j < _len1; _j++) { file = files[_j]; file.upload = { progress: progress, total: e.total, bytesSent: e.loaded }; } } else { allFilesFinished = true; progress = 100; for (_k = 0, _len2 = files.length; _k < _len2; _k++) { file = files[_k]; if (!(file.upload.progress === 100 && file.upload.bytesSent === file.upload.total)) { allFilesFinished = false; } file.upload.progress = progress; file.upload.bytesSent = file.upload.total; } if (allFilesFinished) { return; } } _results = []; for (_l = 0, _len3 = files.length; _l < _len3; _l++) { file = files[_l]; _results.push(_this.emit("uploadprogress", file, progress, file.upload.bytesSent)); } return _results; }; })(this); xhr.onload = (function(_this) { return function(e) { var _ref; if (files[0].status === Dropzone.CANCELED) { return; } if (xhr.readyState !== 4) { return; } response = xhr.responseText; if (xhr.getResponseHeader("content-type") && ~xhr.getResponseHeader("content-type").indexOf("application/json")) { try { response = JSON.parse(response); } catch (_error) { e = _error; response = "Invalid JSON response from server."; } } updateProgress(); if (!((200 <= (_ref = xhr.status) && _ref < 300))) { return handleError(); } else { return _this._finished(files, response, e); } }; })(this); xhr.onerror = (function(_this) { return function() { if (files[0].status === Dropzone.CANCELED) { return; } return handleError(); }; })(this); progressObj = (_ref = xhr.upload) != null ? _ref : xhr; progressObj.onprogress = updateProgress; headers = { "Accept": "application/json", "Cache-Control": "no-cache", "X-Requested-With": "XMLHttpRequest" }; if (this.options.headers) { extend(headers, this.options.headers); } for (headerName in headers) { headerValue = headers[headerName]; xhr.setRequestHeader(headerName, headerValue); } formData = new FormData(); if (this.options.params) { _ref1 = this.options.params; for (key in _ref1) { value = _ref1[key]; formData.append(key, value); } } for (_j = 0, _len1 = files.length; _j < _len1; _j++) { file = files[_j]; this.emit("sending", file, xhr, formData); } if (this.options.uploadMultiple) { this.emit("sendingmultiple", files, xhr, formData); } if (this.element.tagName === "FORM") { _ref2 = this.element.querySelectorAll("input, textarea, select, button"); for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { input = _ref2[_k]; inputName = input.getAttribute("name"); inputType = input.getAttribute("type"); if (input.tagName === "SELECT" && input.hasAttribute("multiple")) { _ref3 = input.options; for (_l = 0, _len3 = _ref3.length; _l < _len3; _l++) { option = _ref3[_l]; if (option.selected) { formData.append(inputName, option.value); } } } else if (!inputType || ((_ref4 = inputType.toLowerCase()) !== "checkbox" && _ref4 !== "radio") || input.checked) { formData.append(inputName, input.value); } } } for (i = _m = 0, _ref5 = files.length - 1; 0 <= _ref5 ? _m <= _ref5 : _m >= _ref5; i = 0 <= _ref5 ? ++_m : --_m) { formData.append(this._getParamName(i), files[i], files[i].name); } return xhr.send(formData); }; Dropzone.prototype._finished = function(files, responseText, e) { var file, _i, _len; for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; file.status = Dropzone.SUCCESS; this.emit("success", file, responseText, e); this.emit("complete", file); } if (this.options.uploadMultiple) { this.emit("successmultiple", files, responseText, e); this.emit("completemultiple", files); } if (this.options.autoProcessQueue) { return this.processQueue(); } }; Dropzone.prototype._errorProcessing = function(files, message, xhr) { var file, _i, _len; for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; file.status = Dropzone.ERROR; this.emit("error", file, message, xhr); this.emit("complete", file); } if (this.options.uploadMultiple) { this.emit("errormultiple", files, message, xhr); this.emit("completemultiple", files); } if (this.options.autoProcessQueue) { return this.processQueue(); } }; return Dropzone; })(Emitter); Dropzone.version = "3.11.2"; Dropzone.options = {}; Dropzone.optionsForElement = function(element) { if (element.getAttribute("id")) { return Dropzone.options[camelize(element.getAttribute("id"))]; } else { return void 0; } }; Dropzone.instances = []; Dropzone.forElement = function(element) { if (typeof element === "string") { element = document.querySelector(element); } if ((element != null ? element.dropzone : void 0) == null) { throw new Error("No Dropzone found for given element. This is probably because you're trying to access it before Dropzone had the time to initialize. Use the `init` option to setup any additional observers on your Dropzone."); } return element.dropzone; }; Dropzone.autoDiscover = true; Dropzone.discover = function() { var checkElements, dropzone, dropzones, _i, _len, _results; if (document.querySelectorAll) { dropzones = document.querySelectorAll(".dropzone"); } else { dropzones = []; checkElements = function(elements) { var el, _i, _len, _results; _results = []; for (_i = 0, _len = elements.length; _i < _len; _i++) { el = elements[_i]; if (/(^| )dropzone($| )/.test(el.className)) { _results.push(dropzones.push(el)); } else { _results.push(void 0); } } return _results; }; checkElements(document.getElementsByTagName("div")); checkElements(document.getElementsByTagName("form")); } _results = []; for (_i = 0, _len = dropzones.length; _i < _len; _i++) { dropzone = dropzones[_i]; if (Dropzone.optionsForElement(dropzone) !== false) { _results.push(new Dropzone(dropzone)); } else { _results.push(void 0); } } return _results; }; Dropzone.blacklistedBrowsers = [/opera.*Macintosh.*version\/12/i]; Dropzone.isBrowserSupported = function() { var capableBrowser, regex, _i, _len, _ref; capableBrowser = true; if (window.File && window.FileReader && window.FileList && window.Blob && window.FormData && document.querySelector) { if (!("classList" in document.createElement("a"))) { capableBrowser = false; } else { _ref = Dropzone.blacklistedBrowsers; for (_i = 0, _len = _ref.length; _i < _len; _i++) { regex = _ref[_i]; if (regex.test(navigator.userAgent)) { capableBrowser = false; continue; } } } } else { capableBrowser = false; } return capableBrowser; }; without = function(list, rejectedItem) { var item, _i, _len, _results; _results = []; for (_i = 0, _len = list.length; _i < _len; _i++) { item = list[_i]; if (item !== rejectedItem) { _results.push(item); } } return _results; }; camelize = function(str) { return str.replace(/[\-_](\w)/g, function(match) { return match.charAt(1).toUpperCase(); }); }; Dropzone.createElement = function(string) { var div; div = document.createElement("div"); div.innerHTML = string; return div.childNodes[0]; }; Dropzone.elementInside = function(element, container) { if (element === container) { return true; } while (element = element.parentNode) { if (element === container) { return true; } } return false; }; Dropzone.getElement = function(el, name) { var element; if (typeof el === "string") { element = document.querySelector(el); } else if (el.nodeType != null) { element = el; } if (element == null) { throw new Error("Invalid `" + name + "` option provided. Please provide a CSS selector or a plain HTML element."); } return element; }; Dropzone.getElements = function(els, name) { var e, el, elements, _i, _j, _len, _len1, _ref; if (els instanceof Array) { elements = []; try { for (_i = 0, _len = els.length; _i < _len; _i++) { el = els[_i]; elements.push(this.getElement(el, name)); } } catch (_error) { e = _error; elements = null; } } else if (typeof els === "string") { elements = []; _ref = document.querySelectorAll(els); for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) { el = _ref[_j]; elements.push(el); } } else if (els.nodeType != null) { elements = [els]; } if (!((elements != null) && elements.length)) { throw new Error("Invalid `" + name + "` option provided. Please provide a CSS selector, a plain HTML element or a list of those."); } return elements; }; Dropzone.confirm = function(question, accepted, rejected) { if (window.confirm(question)) { return accepted(); } else if (rejected != null) { return rejected(); } }; Dropzone.isValidFile = function(file, acceptedFiles) { var baseMimeType, mimeType, validType, _i, _len; if (!acceptedFiles) { return true; } acceptedFiles = acceptedFiles.split(","); mimeType = file.type; baseMimeType = mimeType.replace(/\/.*$/, ""); for (_i = 0, _len = acceptedFiles.length; _i < _len; _i++) { validType = acceptedFiles[_i]; validType = validType.trim(); if (validType.charAt(0) === ".") { if (file.name.toLowerCase().indexOf(validType.toLowerCase(), file.name.length - validType.length) !== -1) { return true; } } else if (/\/\*$/.test(validType)) { if (baseMimeType === validType.replace(/\/.*$/, "")) { return true; } } else { if (mimeType === validType) { return true; } } } return false; }; if (typeof jQuery !== "undefined" && jQuery !== null) { jQuery.fn.dropzone = function(options) { return this.each(function() { return new Dropzone(this, options); }); }; } if (typeof module !== "undefined" && module !== null) { module.exports = Dropzone; } else { window.Dropzone = Dropzone; } Dropzone.ADDED = "added"; Dropzone.QUEUED = "queued"; Dropzone.ACCEPTED = Dropzone.QUEUED; Dropzone.UPLOADING = "uploading"; Dropzone.PROCESSING = Dropzone.UPLOADING; Dropzone.CANCELED = "canceled"; Dropzone.ERROR = "error"; Dropzone.SUCCESS = "success"; /* Bugfix for iOS 6 and 7 Source: http://stackoverflow.com/questions/11929099/html5-canvas-drawimage-ratio-bug-ios based on the work of https://github.com/stomita/ios-imagefile-megapixel */ detectVerticalSquash = function(img) { var alpha, canvas, ctx, data, ey, ih, iw, py, ratio, sy; iw = img.naturalWidth; ih = img.naturalHeight; canvas = document.createElement("canvas"); canvas.width = 1; canvas.height = ih; ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0); data = ctx.getImageData(0, 0, 1, ih).data; sy = 0; ey = ih; py = ih; while (py > sy) { alpha = data[(py - 1) * 4 + 3]; if (alpha === 0) { ey = py; } else { sy = py; } py = (ey + sy) >> 1; } ratio = py / ih; if (ratio === 0) { return 1; } else { return ratio; } }; drawImageIOSFix = function(ctx, img, sx, sy, sw, sh, dx, dy, dw, dh) { var vertSquashRatio; vertSquashRatio = detectVerticalSquash(img); return ctx.drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh / vertSquashRatio); }; /* * contentloaded.js * * Author: Diego Perini (diego.perini at gmail.com) * Summary: cross-browser wrapper for DOMContentLoaded * Updated: 20101020 * License: MIT * Version: 1.2 * * URL: * http://javascript.nwbox.com/ContentLoaded/ * http://javascript.nwbox.com/ContentLoaded/MIT-LICENSE */ contentLoaded = function(win, fn) { var add, doc, done, init, poll, pre, rem, root, top; done = false; top = true; doc = win.document; root = doc.documentElement; add = (doc.addEventListener ? "addEventListener" : "attachEvent"); rem = (doc.addEventListener ? "removeEventListener" : "detachEvent"); pre = (doc.addEventListener ? "" : "on"); init = function(e) { if (e.type === "readystatechange" && doc.readyState !== "complete") { return; } (e.type === "load" ? win : doc)[rem](pre + e.type, init, false); if (!done && (done = true)) { return fn.call(win, e.type || e); } }; poll = function() { var e; try { root.doScroll("left"); } catch (_error) { e = _error; setTimeout(poll, 50); return; } return init("poll"); }; if (doc.readyState !== "complete") { if (doc.createEventObject && root.doScroll) { try { top = !win.frameElement; } catch (_error) {} if (top) { poll(); } } doc[add](pre + "DOMContentLoaded", init, false); doc[add](pre + "readystatechange", init, false); return win[add](pre + "load", init, false); } }; Dropzone._autoDiscoverFunction = function() { if (Dropzone.autoDiscover) { return Dropzone.discover(); } }; contentLoaded(window, Dropzone._autoDiscoverFunction); }).call(this); return module.exports; }));
package org.apache.hadoop.yarn.server.resourcemanager.volume.csi.event; /** * Volume events. */ public enum VolumeEventType { VALIDATE_VOLUME_EVENT, CREATE_VOLUME_EVENT, CONTROLLER_PUBLISH_VOLUME_EVENT, CONTROLLER_UNPUBLISH_VOLUME_EVENT, DELETE_VOLUME }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="robots" content="index, follow, all" /> <title>Thelia\Files | </title> <link rel="stylesheet" type="text/css" href="../stylesheet.css"> </head> <body id="overview"> <div class="header"> <ul> <li><a href="../classes.html">Classes</a></li> <li><a href="../namespaces.html">Namespaces</a></li> <li><a href="../interfaces.html">Interfaces</a></li> <li><a href="../traits.html">Traits</a></li> <li><a href="../doc-index.html">Index</a></li> </ul> <div id="title"></div> <div class="type">Namespace</div> <h1>Thelia\Files</h1> </div> <div class="content"> <table> <tr> <td><a href="../Thelia/Files/FileManager.html"><abbr title="Thelia\Files\FileManager">FileManager</abbr></a></td> <td class="last">File Manager</td> </tr> </table> <h2>Interfaces</h2> <table> <tr> <td><a href="../Thelia/Files/FileModelInterface.html"><abbr title="Thelia\Files\FileModelInterface">FileModelInterface</abbr></a></td> <td class="last"> </td> </tr> <tr> <td><a href="../Thelia/Files/FileModelParentInterface.html"><abbr title="Thelia\Files\FileModelParentInterface">FileModelParentInterface</abbr></a></td> <td class="last"> </td> </tr> </table> </div> <div id="footer"> Generated by <a href="http://sami.sensiolabs.org/" target="_top">Sami, the API Documentation Generator</a>. </div> </body> </html>
<?php namespace Symfony\Bridge\Doctrine\Tests\Form\Type; use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper; use Symfony\Component\Form\Test\TypeTestCase; use Symfony\Bridge\Doctrine\Tests\Fixtures\GroupableEntity; use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity; use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleStringIdEntity; use Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeIntIdEntity; use Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeStringIdEntity; use Symfony\Bridge\Doctrine\Form\DoctrineOrmExtension; use Doctrine\ORM\Tools\SchemaTool; use Doctrine\Common\Collections\ArrayCollection; use Symfony\Component\Form\Extension\Core\View\ChoiceView; class EntityTypeTest extends TypeTestCase { const ITEM_GROUP_CLASS = 'Symfony\Bridge\Doctrine\Tests\Fixtures\GroupableEntity'; const SINGLE_IDENT_CLASS = 'Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity'; const SINGLE_STRING_IDENT_CLASS = 'Symfony\Bridge\Doctrine\Tests\Fixtures\SingleStringIdEntity'; const COMPOSITE_IDENT_CLASS = 'Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeIntIdEntity'; const COMPOSITE_STRING_IDENT_CLASS = 'Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeStringIdEntity'; /** * @var \Doctrine\ORM\EntityManager */ private $em; /** * @var \PHPUnit_Framework_MockObject_MockObject */ private $emRegistry; protected function setUp() { $this->em = DoctrineTestHelper::createTestEntityManager(); $this->emRegistry = $this->createRegistryMock('default', $this->em); parent::setUp(); $schemaTool = new SchemaTool($this->em); $classes = array( $this->em->getClassMetadata(self::ITEM_GROUP_CLASS), $this->em->getClassMetadata(self::SINGLE_IDENT_CLASS), $this->em->getClassMetadata(self::SINGLE_STRING_IDENT_CLASS), $this->em->getClassMetadata(self::COMPOSITE_IDENT_CLASS), $this->em->getClassMetadata(self::COMPOSITE_STRING_IDENT_CLASS), ); try { $schemaTool->dropSchema($classes); } catch (\Exception $e) { } try { $schemaTool->createSchema($classes); } catch (\Exception $e) { } } protected function tearDown() { parent::tearDown(); $this->em = null; $this->emRegistry = null; } protected function getExtensions() { return array_merge(parent::getExtensions(), array( new DoctrineOrmExtension($this->emRegistry), )); } protected function persist(array $entities) { foreach ($entities as $entity) { $this->em->persist($entity); } $this->em->flush(); // no clear, because entities managed by the choice field must // be managed! } /** * @expectedException \Symfony\Component\OptionsResolver\Exception\MissingOptionsException */ public function testClassOptionIsRequired() { $this->factory->createNamed('name', 'entity'); } public function testSetDataToUninitializedEntityWithNonRequired() { $entity1 = new SingleIntIdEntity(1, 'Foo'); $entity2 = new SingleIntIdEntity(2, 'Bar'); $this->persist(array($entity1, $entity2)); $field = $this->factory->createNamed('name', 'entity', null, array( 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, 'required' => false, 'property' => 'name', )); $this->assertEquals(array(1 => new ChoiceView($entity1, '1', 'Foo'), 2 => new ChoiceView($entity2, '2', 'Bar')), $field->createView()->vars['choices']); } public function testSetDataToUninitializedEntityWithNonRequiredToString() { $entity1 = new SingleIntIdEntity(1, 'Foo'); $entity2 = new SingleIntIdEntity(2, 'Bar'); $this->persist(array($entity1, $entity2)); $field = $this->factory->createNamed('name', 'entity', null, array( 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, 'required' => false, )); $this->assertEquals(array(1 => new ChoiceView($entity1, '1', 'Foo'), 2 => new ChoiceView($entity2, '2', 'Bar')), $field->createView()->vars['choices']); } public function testSetDataToUninitializedEntityWithNonRequiredQueryBuilder() { $entity1 = new SingleIntIdEntity(1, 'Foo'); $entity2 = new SingleIntIdEntity(2, 'Bar'); $this->persist(array($entity1, $entity2)); $qb = $this->em->createQueryBuilder()->select('e')->from(self::SINGLE_IDENT_CLASS, 'e'); $field = $this->factory->createNamed('name', 'entity', null, array( 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, 'required' => false, 'property' => 'name', 'query_builder' => $qb, )); $this->assertEquals(array(1 => new ChoiceView($entity1, '1', 'Foo'), 2 => new ChoiceView($entity2, '2', 'Bar')), $field->createView()->vars['choices']); } /** * @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException */ public function testConfigureQueryBuilderWithNonQueryBuilderAndNonClosure() { $field = $this->factory->createNamed('name', 'entity', null, array( 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, 'query_builder' => new \stdClass(), )); } /** * @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException */ public function testConfigureQueryBuilderWithClosureReturningNonQueryBuilder() { $field = $this->factory->createNamed('name', 'entity', null, array( 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, 'query_builder' => function () { return new \stdClass(); }, )); $field->submit('2'); } public function testSetDataSingleNull() { $field = $this->factory->createNamed('name', 'entity', null, array( 'multiple' => false, 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, )); $field->setData(null); $this->assertNull($field->getData()); $this->assertSame('', $field->getViewData()); } public function testSetDataMultipleExpandedNull() { $field = $this->factory->createNamed('name', 'entity', null, array( 'multiple' => true, 'expanded' => true, 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, )); $field->setData(null); $this->assertNull($field->getData()); $this->assertSame(array(), $field->getViewData()); } public function testSetDataMultipleNonExpandedNull() { $field = $this->factory->createNamed('name', 'entity', null, array( 'multiple' => true, 'expanded' => false, 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, )); $field->setData(null); $this->assertNull($field->getData()); $this->assertSame(array(), $field->getViewData()); } public function testSubmitSingleExpandedNull() { $field = $this->factory->createNamed('name', 'entity', null, array( 'multiple' => false, 'expanded' => true, 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, )); $field->submit(null); $this->assertNull($field->getData()); $this->assertSame(array(), $field->getViewData()); } public function testSubmitSingleNonExpandedNull() { $field = $this->factory->createNamed('name', 'entity', null, array( 'multiple' => false, 'expanded' => false, 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, )); $field->submit(null); $this->assertNull($field->getData()); $this->assertSame('', $field->getViewData()); } public function testSubmitMultipleNull() { $field = $this->factory->createNamed('name', 'entity', null, array( 'multiple' => true, 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, )); $field->submit(null); $this->assertEquals(new ArrayCollection(), $field->getData()); $this->assertSame(array(), $field->getViewData()); } public function testSubmitSingleNonExpandedSingleIdentifier() { $entity1 = new SingleIntIdEntity(1, 'Foo'); $entity2 = new SingleIntIdEntity(2, 'Bar'); $this->persist(array($entity1, $entity2)); $field = $this->factory->createNamed('name', 'entity', null, array( 'multiple' => false, 'expanded' => false, 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, 'property' => 'name', )); $field->submit('2'); $this->assertTrue($field->isSynchronized()); $this->assertSame($entity2, $field->getData()); $this->assertSame('2', $field->getViewData()); } public function testSubmitSingleNonExpandedCompositeIdentifier() { $entity1 = new CompositeIntIdEntity(10, 20, 'Foo'); $entity2 = new CompositeIntIdEntity(30, 40, 'Bar'); $this->persist(array($entity1, $entity2)); $field = $this->factory->createNamed('name', 'entity', null, array( 'multiple' => false, 'expanded' => false, 'em' => 'default', 'class' => self::COMPOSITE_IDENT_CLASS, 'property' => 'name', )); // the collection key is used here $field->submit('1'); $this->assertTrue($field->isSynchronized()); $this->assertSame($entity2, $field->getData()); $this->assertSame('1', $field->getViewData()); } public function testSubmitMultipleNonExpandedSingleIdentifier() { $entity1 = new SingleIntIdEntity(1, 'Foo'); $entity2 = new SingleIntIdEntity(2, 'Bar'); $entity3 = new SingleIntIdEntity(3, 'Baz'); $this->persist(array($entity1, $entity2, $entity3)); $field = $this->factory->createNamed('name', 'entity', null, array( 'multiple' => true, 'expanded' => false, 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, 'property' => 'name', )); $field->submit(array('1', '3')); $expected = new ArrayCollection(array($entity1, $entity3)); $this->assertTrue($field->isSynchronized()); $this->assertEquals($expected, $field->getData()); $this->assertSame(array('1', '3'), $field->getViewData()); } public function testSubmitMultipleNonExpandedSingleIdentifierForExistingData() { $entity1 = new SingleIntIdEntity(1, 'Foo'); $entity2 = new SingleIntIdEntity(2, 'Bar'); $entity3 = new SingleIntIdEntity(3, 'Baz'); $this->persist(array($entity1, $entity2, $entity3)); $field = $this->factory->createNamed('name', 'entity', null, array( 'multiple' => true, 'expanded' => false, 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, 'property' => 'name', )); $existing = new ArrayCollection(array(0 => $entity2)); $field->setData($existing); $field->submit(array('1', '3')); // entry with index 0 ($entity2) was replaced $expected = new ArrayCollection(array(0 => $entity1, 1 => $entity3)); $this->assertTrue($field->isSynchronized()); $this->assertEquals($expected, $field->getData()); // same object still, useful if it is a PersistentCollection $this->assertSame($existing, $field->getData()); $this->assertSame(array('1', '3'), $field->getViewData()); } public function testSubmitMultipleNonExpandedCompositeIdentifier() { $entity1 = new CompositeIntIdEntity(10, 20, 'Foo'); $entity2 = new CompositeIntIdEntity(30, 40, 'Bar'); $entity3 = new CompositeIntIdEntity(50, 60, 'Baz'); $this->persist(array($entity1, $entity2, $entity3)); $field = $this->factory->createNamed('name', 'entity', null, array( 'multiple' => true, 'expanded' => false, 'em' => 'default', 'class' => self::COMPOSITE_IDENT_CLASS, 'property' => 'name', )); // because of the composite key collection keys are used $field->submit(array('0', '2')); $expected = new ArrayCollection(array($entity1, $entity3)); $this->assertTrue($field->isSynchronized()); $this->assertEquals($expected, $field->getData()); $this->assertSame(array('0', '2'), $field->getViewData()); } public function testSubmitMultipleNonExpandedCompositeIdentifierExistingData() { $entity1 = new CompositeIntIdEntity(10, 20, 'Foo'); $entity2 = new CompositeIntIdEntity(30, 40, 'Bar'); $entity3 = new CompositeIntIdEntity(50, 60, 'Baz'); $this->persist(array($entity1, $entity2, $entity3)); $field = $this->factory->createNamed('name', 'entity', null, array( 'multiple' => true, 'expanded' => false, 'em' => 'default', 'class' => self::COMPOSITE_IDENT_CLASS, 'property' => 'name', )); $existing = new ArrayCollection(array(0 => $entity2)); $field->setData($existing); $field->submit(array('0', '2')); // entry with index 0 ($entity2) was replaced $expected = new ArrayCollection(array(0 => $entity1, 1 => $entity3)); $this->assertTrue($field->isSynchronized()); $this->assertEquals($expected, $field->getData()); // same object still, useful if it is a PersistentCollection $this->assertSame($existing, $field->getData()); $this->assertSame(array('0', '2'), $field->getViewData()); } public function testSubmitSingleExpanded() { $entity1 = new SingleIntIdEntity(1, 'Foo'); $entity2 = new SingleIntIdEntity(2, 'Bar'); $this->persist(array($entity1, $entity2)); $field = $this->factory->createNamed('name', 'entity', null, array( 'multiple' => false, 'expanded' => true, 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, 'property' => 'name', )); $field->submit('2'); $this->assertTrue($field->isSynchronized()); $this->assertSame($entity2, $field->getData()); $this->assertFalse($field['1']->getData()); $this->assertTrue($field['2']->getData()); $this->assertNull($field['1']->getViewData()); $this->assertSame('2', $field['2']->getViewData()); } public function testSubmitMultipleExpanded() { $entity1 = new SingleIntIdEntity(1, 'Foo'); $entity2 = new SingleIntIdEntity(2, 'Bar'); $entity3 = new SingleIntIdEntity(3, 'Bar'); $this->persist(array($entity1, $entity2, $entity3)); $field = $this->factory->createNamed('name', 'entity', null, array( 'multiple' => true, 'expanded' => true, 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, 'property' => 'name', )); $field->submit(array('1', '3')); $expected = new ArrayCollection(array($entity1, $entity3)); $this->assertTrue($field->isSynchronized()); $this->assertEquals($expected, $field->getData()); $this->assertTrue($field['1']->getData()); $this->assertFalse($field['2']->getData()); $this->assertTrue($field['3']->getData()); $this->assertSame('1', $field['1']->getViewData()); $this->assertNull($field['2']->getViewData()); $this->assertSame('3', $field['3']->getViewData()); } public function testOverrideChoices() { $entity1 = new SingleIntIdEntity(1, 'Foo'); $entity2 = new SingleIntIdEntity(2, 'Bar'); $entity3 = new SingleIntIdEntity(3, 'Baz'); $this->persist(array($entity1, $entity2, $entity3)); $field = $this->factory->createNamed('name', 'entity', null, array( 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, // not all persisted entities should be displayed 'choices' => array($entity1, $entity2), 'property' => 'name', )); $field->submit('2'); $this->assertEquals(array(1 => new ChoiceView($entity1, '1', 'Foo'), 2 => new ChoiceView($entity2, '2', 'Bar')), $field->createView()->vars['choices']); $this->assertTrue($field->isSynchronized()); $this->assertSame($entity2, $field->getData()); $this->assertSame('2', $field->getViewData()); } public function testGroupByChoices() { $item1 = new GroupableEntity(1, 'Foo', 'Group1'); $item2 = new GroupableEntity(2, 'Bar', 'Group1'); $item3 = new GroupableEntity(3, 'Baz', 'Group2'); $item4 = new GroupableEntity(4, 'Boo!', null); $this->persist(array($item1, $item2, $item3, $item4)); $field = $this->factory->createNamed('name', 'entity', null, array( 'em' => 'default', 'class' => self::ITEM_GROUP_CLASS, 'choices' => array($item1, $item2, $item3, $item4), 'property' => 'name', 'group_by' => 'groupName', )); $field->submit('2'); $this->assertSame('2', $field->getViewData()); $this->assertEquals(array( 'Group1' => array(1 => new ChoiceView($item1, '1', 'Foo'), 2 => new ChoiceView($item2, '2', 'Bar')), 'Group2' => array(3 => new ChoiceView($item3, '3', 'Baz')), '4' => new ChoiceView($item4, '4', 'Boo!'), ), $field->createView()->vars['choices']); } public function testPreferredChoices() { $entity1 = new SingleIntIdEntity(1, 'Foo'); $entity2 = new SingleIntIdEntity(2, 'Bar'); $entity3 = new SingleIntIdEntity(3, 'Baz'); $this->persist(array($entity1, $entity2, $entity3)); $field = $this->factory->createNamed('name', 'entity', null, array( 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, 'preferred_choices' => array($entity3, $entity2), 'property' => 'name', )); $this->assertEquals(array(3 => new ChoiceView($entity3, '3', 'Baz'), 2 => new ChoiceView($entity2, '2', 'Bar')), $field->createView()->vars['preferred_choices']); $this->assertEquals(array(1 => new ChoiceView($entity1, '1', 'Foo')), $field->createView()->vars['choices']); } public function testOverrideChoicesWithPreferredChoices() { $entity1 = new SingleIntIdEntity(1, 'Foo'); $entity2 = new SingleIntIdEntity(2, 'Bar'); $entity3 = new SingleIntIdEntity(3, 'Baz'); $this->persist(array($entity1, $entity2, $entity3)); $field = $this->factory->createNamed('name', 'entity', null, array( 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, 'choices' => array($entity2, $entity3), 'preferred_choices' => array($entity3), 'property' => 'name', )); $this->assertEquals(array(3 => new ChoiceView($entity3, '3', 'Baz')), $field->createView()->vars['preferred_choices']); $this->assertEquals(array(2 => new ChoiceView($entity2, '2', 'Bar')), $field->createView()->vars['choices']); } public function testDisallowChoicesThatAreNotIncludedChoicesSingleIdentifier() { $entity1 = new SingleIntIdEntity(1, 'Foo'); $entity2 = new SingleIntIdEntity(2, 'Bar'); $entity3 = new SingleIntIdEntity(3, 'Baz'); $this->persist(array($entity1, $entity2, $entity3)); $field = $this->factory->createNamed('name', 'entity', null, array( 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, 'choices' => array($entity1, $entity2), 'property' => 'name', )); $field->submit('3'); $this->assertFalse($field->isSynchronized()); $this->assertNull($field->getData()); } public function testDisallowChoicesThatAreNotIncludedChoicesCompositeIdentifier() { $entity1 = new CompositeIntIdEntity(10, 20, 'Foo'); $entity2 = new CompositeIntIdEntity(30, 40, 'Bar'); $entity3 = new CompositeIntIdEntity(50, 60, 'Baz'); $this->persist(array($entity1, $entity2, $entity3)); $field = $this->factory->createNamed('name', 'entity', null, array( 'em' => 'default', 'class' => self::COMPOSITE_IDENT_CLASS, 'choices' => array($entity1, $entity2), 'property' => 'name', )); $field->submit('2'); $this->assertFalse($field->isSynchronized()); $this->assertNull($field->getData()); } public function testDisallowChoicesThatAreNotIncludedQueryBuilderSingleIdentifier() { $entity1 = new SingleIntIdEntity(1, 'Foo'); $entity2 = new SingleIntIdEntity(2, 'Bar'); $entity3 = new SingleIntIdEntity(3, 'Baz'); $this->persist(array($entity1, $entity2, $entity3)); $repository = $this->em->getRepository(self::SINGLE_IDENT_CLASS); $field = $this->factory->createNamed('name', 'entity', null, array( 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, 'query_builder' => $repository->createQueryBuilder('e') ->where('e.id IN (1, 2)'), 'property' => 'name', )); $field->submit('3'); $this->assertFalse($field->isSynchronized()); $this->assertNull($field->getData()); } public function testDisallowChoicesThatAreNotIncludedQueryBuilderAsClosureSingleIdentifier() { $entity1 = new SingleIntIdEntity(1, 'Foo'); $entity2 = new SingleIntIdEntity(2, 'Bar'); $entity3 = new SingleIntIdEntity(3, 'Baz'); $this->persist(array($entity1, $entity2, $entity3)); $field = $this->factory->createNamed('name', 'entity', null, array( 'em' => 'default', 'class' => self::SINGLE_IDENT_CLASS, 'query_builder' => function ($repository) { return $repository->createQueryBuilder('e') ->where('e.id IN (1, 2)'); }, 'property' => 'name', )); $field->submit('3'); $this->assertFalse($field->isSynchronized()); $this->assertNull($field->getData()); } public function testDisallowChoicesThatAreNotIncludedQueryBuilderAsClosureCompositeIdentifier() { $entity1 = new CompositeIntIdEntity(10, 20, 'Foo'); $entity2 = new CompositeIntIdEntity(30, 40, 'Bar'); $entity3 = new CompositeIntIdEntity(50, 60, 'Baz'); $this->persist(array($entity1, $entity2, $entity3)); $field = $this->factory->createNamed('name', 'entity', null, array( 'em' => 'default', 'class' => self::COMPOSITE_IDENT_CLASS, 'query_builder' => function ($repository) { return $repository->createQueryBuilder('e') ->where('e.id1 IN (10, 50)'); }, 'property' => 'name', )); $field->submit('2'); $this->assertFalse($field->isSynchronized()); $this->assertNull($field->getData()); } public function testSubmitSingleStringIdentifier() { $entity1 = new SingleStringIdEntity('foo', 'Foo'); $this->persist(array($entity1)); $field = $this->factory->createNamed('name', 'entity', null, array( 'multiple' => false, 'expanded' => false, 'em' => 'default', 'class' => self::SINGLE_STRING_IDENT_CLASS, 'property' => 'name', )); $field->submit('foo'); $this->assertTrue($field->isSynchronized()); $this->assertSame($entity1, $field->getData()); $this->assertSame('foo', $field->getViewData()); } public function testSubmitCompositeStringIdentifier() { $entity1 = new CompositeStringIdEntity('foo1', 'foo2', 'Foo'); $this->persist(array($entity1)); $field = $this->factory->createNamed('name', 'entity', null, array( 'multiple' => false, 'expanded' => false, 'em' => 'default', 'class' => self::COMPOSITE_STRING_IDENT_CLASS, 'property' => 'name', )); // the collection key is used here $field->submit('0'); $this->assertTrue($field->isSynchronized()); $this->assertSame($entity1, $field->getData()); $this->assertSame('0', $field->getViewData()); } public function testGetManagerForClassIfNoEm() { $this->emRegistry->expects($this->never()) ->method('getManager'); $this->emRegistry->expects($this->once()) ->method('getManagerForClass') ->with(self::SINGLE_IDENT_CLASS) ->will($this->returnValue($this->em)); $this->factory->createNamed('name', 'entity', null, array( 'class' => self::SINGLE_IDENT_CLASS, 'required' => false, 'property' => 'name', )); } protected function createRegistryMock($name, $em) { $registry = $this->getMock('Doctrine\Common\Persistence\ManagerRegistry'); $registry->expects($this->any()) ->method('getManager') ->with($this->equalTo($name)) ->will($this->returnValue($em)); return $registry; } }
import asyncio import collections from typing import Callable class Pool: def __init__(self, factory: Callable, minsize: int = 1, maxsize: int = 10): self.factory = factory self.minsize = minsize self.maxsize = maxsize self._pool = collections.deque(maxlen=maxsize) self._cond = asyncio.Condition(asyncio.Lock()) self._using = set() self._acquiring = 0 self._close_state = asyncio.Event() self._fill_free(override_min=False) def __repr__(self): return f"<{self.__class__.__name__}: size={self.size}>" @property def size(self) -> int: return self.freesize + len(self._using) + self._acquiring @property def freesize(self) -> int: return len(self._pool) async def clear(self) -> None: async with self._cond: while self._pool: client = self._pool.popleft() await client.close() async def _do_close(self) -> None: async with self._cond: assert self._acquiring == 0, self._acquiring while self._pool: client = self._pool.popleft() await client.close() for client in self._using: await client.close() self._using.clear() async def close(self) -> None: if not self._close_state.is_set(): self._close_state.set() await self._do_close() @property def closed(self) -> bool: return self._close_state.is_set() async def acquire(self): async with self._cond: while True: self._fill_free(override_min=True) if self.freesize: client = self._pool.popleft() assert client not in self._using, (client, self._using) self._using.add(client) return client else: await self._cond.wait() async def release(self, client) -> None: assert client in self._using self._using.remove(client) self._pool.append(client) await self._wakeup() async def _wakeup(self) -> None: async with self._cond: self._cond.notify() def _fill_free(self, *, override_min: bool) -> None: while self.size < self.minsize: self._acquiring += 1 try: client = self.factory() self._pool.append(client) finally: self._acquiring -= 1 if self.freesize: return if override_min: while not self._pool and self.size < self.maxsize: self._acquiring += 1 try: client = self.factory() self._pool.append(client) finally: self._acquiring -= 1 async def auto_release(self, client, coro): try: return await coro finally: await self.release(client) def get(self): return AsyncClientContextManager(self) class AsyncClientContextManager: __slots__ = ("_pool", "_client") def __init__(self, pool): self._pool = pool self._client = None async def __aenter__(self): self._client = await self._pool.acquire() return self._client async def __aexit__(self, exc_type, exc_value, tb): try: await self._pool.release(self._client) finally: self._pool = None self._client = None
define("route-recognizer", [], function() { "use strict"; var specials = [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\' ]; var escapeRegex = new RegExp('(\\' + specials.join('|\\') + ')', 'g'); // A Segment represents a segment in the original route description. // Each Segment type provides an `eachChar` and `regex` method. // // The `eachChar` method invokes the callback with one or more character // specifications. A character specification consumes one or more input // characters. // // The `regex` method returns a regex fragment for the segment. If the // segment is a dynamic of star segment, the regex fragment also includes // a capture. // // A character specification contains: // // * `validChars`: a String with a list of all valid characters, or // * `invalidChars`: a String with a list of all invalid characters // * `repeat`: true if the character specification can repeat function StaticSegment(string) { this.string = string; } StaticSegment.prototype = { eachChar: function(callback) { var string = this.string, char; for (var i=0, l=string.length; i<l; i++) { char = string.charAt(i); callback({ validChars: char }); } }, regex: function() { return this.string.replace(escapeRegex, '\\$1'); }, generate: function() { return this.string; } }; function DynamicSegment(name) { this.name = name; } DynamicSegment.prototype = { eachChar: function(callback) { callback({ invalidChars: "/", repeat: true }); }, regex: function() { return "([^/]+)"; }, generate: function(params) { return params[this.name]; } }; function StarSegment(name) { this.name = name; } StarSegment.prototype = { eachChar: function(callback) { callback({ invalidChars: "", repeat: true }); }, regex: function() { return "(.+)"; }, generate: function(params) { return params[this.name]; } }; function EpsilonSegment() {} EpsilonSegment.prototype = { eachChar: function() {}, regex: function() { return ""; }, generate: function() { return ""; } }; function parse(route, names, types) { // normalize route as not starting with a "/". Recognition will // also normalize. if (route.charAt(0) === "/") { route = route.substr(1); } var segments = route.split("/"), results = []; for (var i=0, l=segments.length; i<l; i++) { var segment = segments[i], match; if (match = segment.match(/^:([^\/]+)$/)) { results.push(new DynamicSegment(match[1])); names.push(match[1]); types.dynamics++; } else if (match = segment.match(/^\*([^\/]+)$/)) { results.push(new StarSegment(match[1])); names.push(match[1]); types.stars++; } else if(segment === "") { results.push(new EpsilonSegment()); } else { results.push(new StaticSegment(segment)); types.statics++; } } return results; } // A State has a character specification and (`charSpec`) and a list of possible // subsequent states (`nextStates`). // // If a State is an accepting state, it will also have several additional // properties: // // * `regex`: A regular expression that is used to extract parameters from paths // that reached this accepting state. // * `handlers`: Information on how to convert the list of captures into calls // to registered handlers with the specified parameters // * `types`: How many static, dynamic or star segments in this route. Used to // decide which route to use if multiple registered routes match a path. // // Currently, State is implemented naively by looping over `nextStates` and // comparing a character specification against a character. A more efficient // implementation would use a hash of keys pointing at one or more next states. function State(charSpec) { this.charSpec = charSpec; this.nextStates = []; } State.prototype = { get: function(charSpec) { var nextStates = this.nextStates; for (var i=0, l=nextStates.length; i<l; i++) { var child = nextStates[i]; var isEqual = child.charSpec.validChars === charSpec.validChars; isEqual = isEqual && child.charSpec.invalidChars === charSpec.invalidChars; if (isEqual) { return child; } } }, put: function(charSpec) { var state; // If the character specification already exists in a child of the current // state, just return that state. if (state = this.get(charSpec)) { return state; } // Make a new state for the character spec state = new State(charSpec); // Insert the new state as a child of the current state this.nextStates.push(state); // If this character specification repeats, insert the new state as a child // of itself. Note that this will not trigger an infinite loop because each // transition during recognition consumes a character. if (charSpec.repeat) { state.nextStates.push(state); } // Return the new state return state; }, // Find a list of child states matching the next character match: function(char) { // DEBUG "Processing `" + char + "`:" var nextStates = this.nextStates, child, charSpec, chars; // DEBUG " " + debugState(this) var returned = []; for (var i=0, l=nextStates.length; i<l; i++) { child = nextStates[i]; charSpec = child.charSpec; if (typeof (chars = charSpec.validChars) !== 'undefined') { if (chars.indexOf(char) !== -1) { returned.push(child); } } else if (typeof (chars = charSpec.invalidChars) !== 'undefined') { if (chars.indexOf(char) === -1) { returned.push(child); } } } return returned; } /** IF DEBUG , debug: function() { var charSpec = this.charSpec, debug = "[", chars = charSpec.validChars || charSpec.invalidChars; if (charSpec.invalidChars) { debug += "^"; } debug += chars; debug += "]"; if (charSpec.repeat) { debug += "+"; } return debug; } END IF **/ }; /** IF DEBUG function debug(log) { console.log(log); } function debugState(state) { return state.nextStates.map(function(n) { if (n.nextStates.length === 0) { return "( " + n.debug() + " [accepting] )"; } return "( " + n.debug() + " <then> " + n.nextStates.map(function(s) { return s.debug() }).join(" or ") + " )"; }).join(", ") } END IF **/ // This is a somewhat naive strategy, but should work in a lot of cases // A better strategy would properly resolve /posts/:id/new and /posts/edit/:id function sortSolutions(states) { return states.sort(function(a, b) { if (a.types.stars !== b.types.stars) { return a.types.stars - b.types.stars; } if (a.types.dynamics !== b.types.dynamics) { return a.types.dynamics - b.types.dynamics; } if (a.types.statics !== b.types.statics) { return a.types.statics - b.types.statics; } return 0; }); } function recognizeChar(states, char) { var nextStates = []; for (var i=0, l=states.length; i<l; i++) { var state = states[i]; nextStates = nextStates.concat(state.match(char)); } return nextStates; } function findHandler(state, path) { var handlers = state.handlers, regex = state.regex; var captures = path.match(regex), currentCapture = 1; var result = []; for (var i=0, l=handlers.length; i<l; i++) { var handler = handlers[i], names = handler.names, params = {}; for (var j=0, m=names.length; j<m; j++) { params[names[j]] = captures[currentCapture++]; } result.push({ handler: handler.handler, params: params, isDynamic: !!names.length }); } return result; } function addSegment(currentState, segment) { segment.eachChar(function(char) { var state; currentState = currentState.put(char); }); return currentState; } // The main interface var RouteRecognizer = function() { this.rootState = new State(); this.names = {}; }; RouteRecognizer.prototype = { add: function(routes, options) { var currentState = this.rootState, regex = "^", types = { statics: 0, dynamics: 0, stars: 0 }, handlers = [], allSegments = [], name; var isEmpty = true; for (var i=0, l=routes.length; i<l; i++) { var route = routes[i], names = []; var segments = parse(route.path, names, types); allSegments = allSegments.concat(segments); for (var j=0, m=segments.length; j<m; j++) { var segment = segments[j]; if (segment instanceof EpsilonSegment) { continue; } isEmpty = false; // Add a "/" for the new segment currentState = currentState.put({ validChars: "/" }); regex += "/"; // Add a representation of the segment to the NFA and regex currentState = addSegment(currentState, segment); regex += segment.regex(); } handlers.push({ handler: route.handler, names: names }); } if (isEmpty) { currentState = currentState.put({ validChars: "/" }); regex += "/"; } currentState.handlers = handlers; currentState.regex = new RegExp(regex + "$"); currentState.types = types; if (name = options && options.as) { this.names[name] = { segments: allSegments, handlers: handlers }; } }, handlersFor: function(name) { var route = this.names[name], result = []; if (!route) { throw new Error("There is no route named " + name); } for (var i=0, l=route.handlers.length; i<l; i++) { result.push(route.handlers[i]); } return result; }, hasRoute: function(name) { return !!this.names[name]; }, generate: function(name, params) { var route = this.names[name], output = ""; if (!route) { throw new Error("There is no route named " + name); } var segments = route.segments; for (var i=0, l=segments.length; i<l; i++) { var segment = segments[i]; if (segment instanceof EpsilonSegment) { continue; } output += "/"; output += segment.generate(params); } if (output.charAt(0) !== '/') { output = '/' + output; } return output; }, recognize: function(path) { var states = [ this.rootState ], pathLen, i, l; // DEBUG GROUP path if (path.charAt(0) !== "/") { path = "/" + path; } pathLen = path.length; if (pathLen > 1 && path.charAt(pathLen - 1) === "/") { path = path.substr(0, pathLen - 1); } for (i=0, l=path.length; i<l; i++) { states = recognizeChar(states, path.charAt(i)); if (!states.length) { break; } } // END DEBUG GROUP var solutions = []; for (i=0, l=states.length; i<l; i++) { if (states[i].handlers) { solutions.push(states[i]); } } states = sortSolutions(solutions); var state = solutions[0]; if (state && state.handlers) { return findHandler(state, path); } } }; function Target(path, matcher, delegate) { this.path = path; this.matcher = matcher; this.delegate = delegate; } Target.prototype = { to: function(target, callback) { var delegate = this.delegate; if (delegate && delegate.willAddRoute) { target = delegate.willAddRoute(this.matcher.target, target); } this.matcher.add(this.path, target); if (callback) { if (callback.length === 0) { throw new Error("You must have an argument in the function passed to `to`"); } this.matcher.addChild(this.path, target, callback, this.delegate); } } }; function Matcher(target) { this.routes = {}; this.children = {}; this.target = target; } Matcher.prototype = { add: function(path, handler) { this.routes[path] = handler; }, addChild: function(path, target, callback, delegate) { var matcher = new Matcher(target); this.children[path] = matcher; var match = generateMatch(path, matcher, delegate); if (delegate && delegate.contextEntered) { delegate.contextEntered(target, match); } callback(match); } }; function generateMatch(startingPath, matcher, delegate) { return function(path, nestedCallback) { var fullPath = startingPath + path; if (nestedCallback) { nestedCallback(generateMatch(fullPath, matcher, delegate)); } else { return new Target(startingPath + path, matcher, delegate); } }; } function addRoute(routeArray, path, handler) { var len = 0; for (var i=0, l=routeArray.length; i<l; i++) { len += routeArray[i].path.length; } path = path.substr(len); routeArray.push({ path: path, handler: handler }); } function eachRoute(baseRoute, matcher, callback, binding) { var routes = matcher.routes; for (var path in routes) { if (routes.hasOwnProperty(path)) { var routeArray = baseRoute.slice(); addRoute(routeArray, path, routes[path]); if (matcher.children[path]) { eachRoute(routeArray, matcher.children[path], callback, binding); } else { callback.call(binding, routeArray); } } } } RouteRecognizer.prototype.map = function(callback, addRouteCallback) { var matcher = new Matcher(); callback(generateMatch("", matcher, this.delegate)); eachRoute([], matcher, function(route) { if (addRouteCallback) { addRouteCallback(this, route); } else { this.add(route); } }, this); }; return RouteRecognizer; });
.oo-ui-icon-logoCC { background-image: url('themes/wikimediaui/images/icons/logo-cc.png'); background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/logo-cc.svg'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/logo-cc.svg'); background-image: -o-linear-gradient(transparent, transparent), url('themes/wikimediaui/images/icons/logo-cc.png'); } .oo-ui-image-invert.oo-ui-icon-logoCC { background-image: url('themes/wikimediaui/images/icons/logo-cc-invert.png'); background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/logo-cc-invert.svg'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/logo-cc-invert.svg'); background-image: -o-linear-gradient(transparent, transparent), url('themes/wikimediaui/images/icons/logo-cc-invert.png'); } .oo-ui-image-progressive.oo-ui-icon-logoCC { background-image: url('themes/wikimediaui/images/icons/logo-cc-progressive.png'); background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/logo-cc-progressive.svg'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/logo-cc-progressive.svg'); background-image: -o-linear-gradient(transparent, transparent), url('themes/wikimediaui/images/icons/logo-cc-progressive.png'); } .oo-ui-icon-logoWikimediaCommons { background-image: url('themes/wikimediaui/images/icons/logo-wikimediaCommons.png'); background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/logo-wikimediaCommons.svg'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/logo-wikimediaCommons.svg'); background-image: -o-linear-gradient(transparent, transparent), url('themes/wikimediaui/images/icons/logo-wikimediaCommons.png'); } .oo-ui-image-invert.oo-ui-icon-logoWikimediaCommons { background-image: url('themes/wikimediaui/images/icons/logo-wikimediaCommons-invert.png'); background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/logo-wikimediaCommons-invert.svg'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/logo-wikimediaCommons-invert.svg'); background-image: -o-linear-gradient(transparent, transparent), url('themes/wikimediaui/images/icons/logo-wikimediaCommons-invert.png'); } .oo-ui-image-progressive.oo-ui-icon-logoWikimediaCommons { background-image: url('themes/wikimediaui/images/icons/logo-wikimediaCommons-progressive.png'); background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/logo-wikimediaCommons-progressive.svg'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/logo-wikimediaCommons-progressive.svg'); background-image: -o-linear-gradient(transparent, transparent), url('themes/wikimediaui/images/icons/logo-wikimediaCommons-progressive.png'); } .oo-ui-icon-logoWikimediaDiscovery { background-image: url('themes/wikimediaui/images/icons/logo-wikimediaDiscovery.png'); background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/logo-wikimediaDiscovery.svg'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/logo-wikimediaDiscovery.svg'); background-image: -o-linear-gradient(transparent, transparent), url('themes/wikimediaui/images/icons/logo-wikimediaDiscovery.png'); } .oo-ui-image-invert.oo-ui-icon-logoWikimediaDiscovery { background-image: url('themes/wikimediaui/images/icons/logo-wikimediaDiscovery-invert.png'); background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/logo-wikimediaDiscovery-invert.svg'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/logo-wikimediaDiscovery-invert.svg'); background-image: -o-linear-gradient(transparent, transparent), url('themes/wikimediaui/images/icons/logo-wikimediaDiscovery-invert.png'); } .oo-ui-image-progressive.oo-ui-icon-logoWikimediaDiscovery { background-image: url('themes/wikimediaui/images/icons/logo-wikimediaDiscovery-progressive.png'); background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/logo-wikimediaDiscovery-progressive.svg'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/logo-wikimediaDiscovery-progressive.svg'); background-image: -o-linear-gradient(transparent, transparent), url('themes/wikimediaui/images/icons/logo-wikimediaDiscovery-progressive.png'); } .oo-ui-icon-logoWikipedia { background-image: url('themes/wikimediaui/images/icons/logo-wikipedia.png'); background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/logo-wikipedia.svg'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/logo-wikipedia.svg'); background-image: -o-linear-gradient(transparent, transparent), url('themes/wikimediaui/images/icons/logo-wikipedia.png'); } .oo-ui-image-invert.oo-ui-icon-logoWikipedia { background-image: url('themes/wikimediaui/images/icons/logo-wikipedia-invert.png'); background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/logo-wikipedia-invert.svg'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/logo-wikipedia-invert.svg'); background-image: -o-linear-gradient(transparent, transparent), url('themes/wikimediaui/images/icons/logo-wikipedia-invert.png'); } .oo-ui-image-progressive.oo-ui-icon-logoWikipedia { background-image: url('themes/wikimediaui/images/icons/logo-wikipedia-progressive.png'); background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/logo-wikipedia-progressive.svg'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/logo-wikipedia-progressive.svg'); background-image: -o-linear-gradient(transparent, transparent), url('themes/wikimediaui/images/icons/logo-wikipedia-progressive.png'); }
<?php namespace Detail\Mail\Factory\Message; use Zend\ServiceManager\FactoryInterface; use Zend\ServiceManager\ServiceLocatorInterface; use Detail\Mail\Message\MessageFactory; class MessageFactoryFactory implements FactoryInterface { /** * {@inheritDoc} * @return MessageFactory */ public function createService(ServiceLocatorInterface $serviceLocator) { /** @var \Detail\Mail\Options\ModuleOptions $options */ $options = $serviceLocator->get('Detail\Mail\Options\ModuleOptions'); $factory = new MessageFactory(); $factory->setMessageClass($options->getMessageFactory()->getMessageClass()); return $factory; } }
<html> <head> <script src="resources/cross-frame-access.js"></script> <script> var windowConstructorPropertiesNotAllowed = [ "Attr", "Audio", "CDATASection", "CSSRule", "CSSStyleDeclaration", "CharacterData", "Comment", "DOMException", "DOMImplementation", "DOMParser", "Document", "DocumentFragment", "DocumentType", "Element", "EntityReference", "EvalError", "Event", "HTMLAnchorElement", "HTMLAudioElement", "HTMLAppletElement", "HTMLAreaElement", "HTMLBRElement", "HTMLBaseElement", "HTMLBodyElement", "HTMLButtonElement", "HTMLCanvasElement", "HTMLDListElement", "HTMLDirectoryElement", "HTMLDivElement", "HTMLDocument", "HTMLElement", "HTMLFieldSetElement", "HTMLFontElement", "HTMLFormElement", "HTMLFrameElement", "HTMLFrameSetElement", "HTMLHRElement", "HTMLHeadElement", "HTMLHeadingElement", "HTMLHtmlElement", "HTMLIFrameElement", "HTMLImageElement", "HTMLInputElement", "HTMLIsIndexElement", "HTMLLIElement", "HTMLLabelElement", "HTMLLegendElement", "HTMLLinkElement", "HTMLMapElement", "HTMLMarqueeElement", "HTMLMediaElement", "HTMLMenuElement", "HTMLMetaElement", "HTMLModElement", "HTMLOListElement", "HTMLOptGroupElement", "HTMLOptionElement", "HTMLParagraphElement", "HTMLParamElement", "HTMLPreElement", "HTMLQuoteElement", "HTMLScriptElement", "HTMLSelectElement", "HTMLSourceElement", "HTMLStyleElement", "HTMLTableCaptionElement", "HTMLTableCellElement", "HTMLTableColElement", "HTMLTableElement", "HTMLTableRowElement", "HTMLTableSectionElement", "HTMLTextAreaElement", "HTMLTitleElement", "HTMLUListElement", "HTMLVideoElement", "Image", "MutationEvent", "Node", "NodeFilter", "Option", "ProcessingInstruction", "Range", "RangeError", "ReferenceError", "SyntaxError", "Text", "TypeError", "URIError", "XMLDocument", "XMLHttpRequest", "XMLSerializer", "XPathEvaluator", "XPathResult", "XSLTProcessor" ]; var windowFunctionPropertiesNotAllowed = [ "addEventListener", "alert", "atob", "btoa", "captureEvents", "clearInterval", "clearTimeout", "confirm", "constructor", "find", "getComputedStyle", "getMatchedCSSRules", "getSelection", "moveBy", "moveTo", "open", "print", "prompt", "releaseEvents", "removeEventListener", "resizeBy", "resizeTo", "scroll", "scrollBy", "scrollTo", "setInterval", "setTimeout", "stop" ]; var windowAttributesPropertiesNotAllowed = [ "clientInformation", "console", "crypto", "defaultStatus", "defaultstatus", "devicePixelRatio", "document", "embeds", "eval", "event", "frameElement", "history", "images", "innerHeight", "innerWidth", "locationbar", "menubar", "name", "navigator", "offscreenBuffering", "onabort", "onbeforeunload", "onblur", "onchange", "onclick", "ondblclick", "onerror", "onfocus", "onkeydown", "onkeypress", "onkeyup", "onload", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel", "onreset", "onresize", "onscroll", "onsearch", "onselect", "onsubmit", "onunload", "outerHeight", "outerWidth", "pageXOffset", "pageYOffset", "personalbar", "plugins", "screen", "screenLeft", "screenTop", "screenX", "screenY", "scrollX", "scrollY", "scrollbars", "status", "statusbar", "toolbar" ]; var windowFunctionPropertiesAllowed = [ "blur", "close", "focus" ] var windowAttributesPropertiesAllowed = [ "closed", "frames", "length", "opener", "parent", "self", "top", "window", ]; window.onload = function() { if (window.testRunner) { testRunner.dumpAsText(); testRunner.waitUntilDone(); } window.addEventListener('message', function() { runTest(); if (window.testRunner) testRunner.notifyDone(); }); } runTest = function() { window.targetWindow = frames[0]; log("\n----- tests for getting of allowed properties -----\n"); log("\n----- tests for getting of allowed Functions -----\n"); for (var i = 0; i < windowFunctionPropertiesAllowed.length; i++) { var property = windowFunctionPropertiesAllowed[i]; shouldBeTrue("canGet('targetWindow." + property + "')"); } log("\n----- tests for getting of allowed Attributes -----\n"); for (var i = 0; i < windowAttributesPropertiesAllowed.length; i++) { var property = windowAttributesPropertiesAllowed[i]; shouldBeTrue("canGet('targetWindow." + property + "')"); } log("\n----- tests for getting of not allowed properties -----\n"); log("\n----- tests for getting of not allowed Constructors -----\n"); for (var i = 0; i < windowConstructorPropertiesNotAllowed.length; i++) { var property = windowConstructorPropertiesNotAllowed[i]; shouldBeFalse("canGet('targetWindow." + property + "')"); } log("\n----- tests for getting of not allowed Functions -----\n"); for (var i = 0; i < windowFunctionPropertiesNotAllowed.length; i++) { var property = windowFunctionPropertiesNotAllowed[i]; shouldBeFalse("canGet('targetWindow." + property + "')"); } log("\n----- tests for getting of not allowed Attributes -----\n"); for (var i = 0; i < windowAttributesPropertiesNotAllowed.length; i++) { var property = windowAttributesPropertiesNotAllowed[i]; if (property == "document") log("Firefox allows access to 'document' but throws an exception when you access its properties."); shouldBeFalse("canGet('targetWindow." + property + "')"); } } </script> </head> <body> <p>This test checks cross-frame access security (rdar://problem/5251309).</p> <iframe src="http://localhost:8000/security/resources/cross-frame-iframe-for-get-test.html" style=""></iframe> <pre id="console"></pre> </body> </html>
package watch import ( "fmt" "log" "os" "path/filepath" "time" "github.com/masahide/tail/util" "gopkg.in/fsnotify.v0" "gopkg.in/tomb.v1" ) const ( headerSize = 4 * 1024 logrotateTime = 24*time.Hour - 5*time.Minute ) // InotifyFileWatcher uses inotify to monitor file changes. type InotifyFileWatcher struct { Filename string Size int64 w *fsnotify.Watcher ModTime time.Time } func NewInotifyFileWatcher(filename string, w *fsnotify.Watcher) *InotifyFileWatcher { fw := &InotifyFileWatcher{filename, 0, w, time.Time{}} return fw } func (fw *InotifyFileWatcher) BlockUntilExists(t *tomb.Tomb) error { dirname := filepath.Dir(fw.Filename) // Watch for new files to be created in the parent directory. err := fw.w.WatchFlags(dirname, fsnotify.FSN_CREATE) if err != nil { return err } defer fw.w.RemoveWatch(dirname) // Do a real check now as the file might have been created before // calling `WatchFlags` above. if _, err = os.Stat(fw.Filename); !os.IsNotExist(err) { // file exists, or stat returned an error. return err } for { select { case evt, ok := <-fw.w.Event: if !ok { return fmt.Errorf("inotify watcher has been closed") } evtName, err := filepath.Abs(evt.Name) if err != nil { return err } fwFilename, err := filepath.Abs(fw.Filename) if err != nil { return err } if evtName == fwFilename { return nil } case <-t.Dying(): return tomb.ErrDying } } panic("unreachable") } func (fw *InotifyFileWatcher) ChangeEvents(t *tomb.Tomb, fi os.FileInfo) *FileChanges { changes := NewFileChanges() err := fw.w.Watch(fw.Filename) if err != nil { util.Fatal("Error watching %v: %v", fw.Filename, err) } fw.Size = fi.Size() fw.ModTime = fi.ModTime() go func() { defer fw.w.RemoveWatch(fw.Filename) defer changes.Close() for { prevSize := fw.Size var evt *fsnotify.FileEvent var ok bool select { case evt, ok = <-fw.w.Event: if !ok { return } case <-t.Dying(): return } switch { case evt.IsDelete(): fallthrough case evt.IsRename(): changes.NotifyDeleted() continue //return case evt.IsModify(): fi, err := os.Stat(fw.Filename) if err != nil { if os.IsNotExist(err) { changes.NotifyDeleted() return } // XXX: report this error back to the user util.Fatal("Failed to stat file %v: %v", fw.Filename, err) } fw.Size = fi.Size() if prevSize > 0 && prevSize > fw.Size { log.Printf("prevSize:%d,fw.Size:%d", prevSize, fw.Size) changes.NotifyTruncated() } else if prevSize > 0 && prevSize == fw.Size && fw.Size <= headerSize && fi.ModTime().Sub(fw.ModTime) > logrotateTime { log.Printf("logrotateTime:%s", logrotateTime) // also capture log_header only updates changes.NotifyTruncated() } else { changes.NotifyModified() } prevSize = fw.Size } } }() return changes }
set -e #Initialize gerrit if gerrit site dir is empty. #This is necessary when gerrit site is in a volume. if [ "$1" = '/var/gerrit/gerrit-start.sh' ]; then if [ -z "$(ls -A "$GERRIT_SITE")" ]; then echo "First time initialize gerrit..." java -jar "${GERRIT_WAR}" init --batch --no-auto-start -d "${GERRIT_SITE}" #All git repositories must be removed in order to be recreated at the secondary init below. rm -rf "${GERRIT_SITE}/git" fi #Customize gerrit.config #Section gerrit [ -z "${WEBURL}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" gerrit.canonicalWebUrl "${WEBURL}" #Section database if [ "${DATABASE_TYPE}" = 'postgresql' ]; then git config -f "${GERRIT_SITE}/etc/gerrit.config" database.type "${DATABASE_TYPE}" [ -z "${DB_PORT_5432_TCP_ADDR}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" database.hostname "${DB_PORT_5432_TCP_ADDR}" [ -z "${DB_PORT_5432_TCP_PORT}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" database.port "${DB_PORT_5432_TCP_PORT}" [ -z "${DB_ENV_POSTGRES_DB}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" database.database "${DB_ENV_POSTGRES_DB}" [ -z "${DB_ENV_POSTGRES_USER}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" database.username "${DB_ENV_POSTGRES_USER}" [ -z "${DB_ENV_POSTGRES_PASSWORD}" ] || git config -f "${GERRIT_SITE}/etc/secure.config" database.password "${DB_ENV_POSTGRES_PASSWORD}" fi #Section ldap if [ "${AUTH_TYPE}" = 'LDAP' ]; then git config -f "${GERRIT_SITE}/etc/gerrit.config" auth.type "${AUTH_TYPE}" git config -f "${GERRIT_SITE}/etc/gerrit.config" auth.gitBasicAuth true [ -z "${LDAP_SERVER}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" ldap.server "ldap://${LDAP_SERVER}" [ -z "${LDAP_SSLVERIFY}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" ldap.sslVerify "${LDAP_SSLVERIFY}" [ -z "${LDAP_GROUPSVISIBLETOALL}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" ldap.groupsVisibleToAll "${LDAP_GROUPSVISIBLETOALL}" [ -z "${LDAP_USERNAME}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" ldap.username "${LDAP_USERNAME}" [ -z "${LDAP_PASSWORD}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" ldap.password "${LDAP_PASSWORD}" [ -z "${LDAP_REFERRAL}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" ldap.referral "${LDAP_REFERRAL}" [ -z "${LDAP_READTIMEOUT}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" ldap.readTimeout "${LDAP_READTIMEOUT}" [ -z "${LDAP_ACCOUNTBASE}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" ldap.accountBase "${LDAP_ACCOUNTBASE}" [ -z "${LDAP_ACCOUNTSCOPE}" ] || git config -cd "${GERRIT_SITE}/etc/gerrit.config" ldap.accountScope "${LDAP_ACCOUNTSCOPE}" [ -z "${LDAP_ACCOUNTPATTERN}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" ldap.accountPattern "${LDAP_ACCOUNTPATTERN}" [ -z "${LDAP_ACCOUNTFULLNAME}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" ldap.accountFullName "${LDAP_ACCOUNTFULLNAME}" [ -z "${LDAP_ACCOUNTEMAILADDRESS}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" ldap.accountEmailAddress "${LDAP_ACCOUNTEMAILADDRESS}" [ -z "${LDAP_ACCOUNTSSHUSERNAME}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" ldap.accountSshUserName "${LDAP_ACCOUNTSSHUSERNAME}" [ -z "${LDAP_ACCOUNTMEMBERFIELD}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" ldap.accountMemberField "${LDAP_ACCOUNTMEMBERFIELD}" [ -z "${LDAP_FETCHMEMBEROFEAGERLY}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" ldap.fetchMemberOfEagerly "${LDAP_FETCHMEMBEROFEAGERLY}" [ -z "${LDAP_GROUPBASE}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" ldap.groupBase "${LDAP_GROUPBASE}" [ -z "${LDAP_GROUPSCOPE}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" ldap.groupScope "${LDAP_GROUPSCOPE}" [ -z "${LDAP_GROUPPATTERN}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" ldap.groupPattern "${LDAP_GROUPPATTERN}" [ -z "${LDAP_GROUPMEMBERPATTERN}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" ldap.groupMemberPattern "${LDAP_GROUPMEMBERPATTERN}" [ -z "${LDAP_GROUPNAME}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" ldap.groupName "${LDAP_GROUPNAME}" [ -z "${LDAP_LOCALUSERNAMETOLOWERCASE}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" ldap.localUsernameToLowerCase "${LDAP_LOCALUSERNAMETOLOWERCASE}" [ -z "${LDAP_AUTHENTICATION}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" ldap.authentication "${LDAP_AUTHENTICATION}" [ -z "${LDAP_USECONNECTIONPOOLING}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" ldap.useConnectionPooling "${LDAP_USECONNECTIONPOOLING}" [ -z "${LDAP_CONNECTTIMEOUT}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" ldap.connectTimeout "${LDAP_CONNECTTIMEOUT}" fi #Section http if [ "${AUTH_TYPE}" = 'HTTP' ]; then git config -f "${GERRIT_SITE}/etc/gerrit.config" auth.type "${AUTH_TYPE}" # git config -f "${GERRIT_SITE}/etc/gerrit.config" auth.gitBasicAuth true git config -f "${GERRIT_SITE}/etc/gerrit.config" --unset auth.httpHeader # git config -f "${GERRIT_SITE}/etc/gerrit.config" auth.emailFormat '{0}@17usoft.com' fi # section container [ -z "${JAVA_HEAPLIMIT}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" container.heapLimit "${JAVA_HEAPLIMIT}" [ -z "${JAVA_OPTIONS}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" container.javaOptions "${JAVA_OPTIONS}" [ -z "${JAVA_SLAVE}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" container.slave "${JAVA_SLAVE}" #Section sendemail if [ -z "${SMTP_SERVER}" ]; then git config -f "${GERRIT_SITE}/etc/gerrit.config" sendemail.enable false else git config -f "${GERRIT_SITE}/etc/gerrit.config" sendemail.smtpServer "${SMTP_SERVER}" fi #Section plugins git config -f "${GERRIT_SITE}/etc/gerrit.config" plugins.allowRemoteAdmin true #Section httpd [ -z "${HTTPD_LISTENURL}" ] || git config -f "${GERRIT_SITE}/etc/gerrit.config" httpd.listenUrl "${HTTPD_LISTENURL}" echo "Upgrading gerrit..." java -jar "${GERRIT_WAR}" init --batch -d "${GERRIT_SITE}" if [ $? -eq 0 ]; then echo "Upgrading is OK." else echo "Something wrong..." cat "${GERRIT_SITE}/logs/error_log" fi fi exec "$@"
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Coq bench</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../../..">Unstable</a></li> <li><a href=".">8.5beta1 / contrib:kildall dev</a></li> <li class="active"><a href="">2015-02-03 21:08:42</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="../../../../../about.html">About</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href=".">« Up</a> <h1> contrib:kildall <small> dev <span class="label label-success">42 s</span> </small> </h1> <p><em><script>document.write(moment("2015-02-03 21:08:42 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2015-02-03 21:08:42 UTC)</em><p> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>ruby lint.rb unstable ../unstable/packages/coq:contrib:kildall/coq:contrib:kildall.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --dry-run coq:contrib:kildall.dev coq.8.5beta1</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>2 s</dd> </dl> <p>Dry install without Coq, to test if the problem was incompatibility with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>ulimit -Sv 2000000; timeout 5m opam install -y --deps-only coq:contrib:kildall.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>2 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>ulimit -Sv 2000000; timeout 5m opam install -y --verbose coq:contrib:kildall.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>42 s</dd> </dl> <h2>Installation size</h2> <p>Total: 5,219 K</p> <ul> <li>343 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/fresh_variables.vo</code></li> <li>309 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/fresh_variables.glob</code></li> <li>243 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/inst_shapes.vo</code></li> <li>223 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/machine_shapes.vo</code></li> <li>209 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/inst_types.vo</code></li> <li>197 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/machine.vo</code></li> <li>190 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/machine_types.glob</code></li> <li>187 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/substitutions.vo</code></li> <li>175 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/machine_types.vo</code></li> <li>163 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/machine_shapes.glob</code></li> <li>161 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/inst_types.glob</code></li> <li>161 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/substitutions.glob</code></li> <li>144 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/lists/m_list.vo</code></li> <li>143 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/inst_shapes.glob</code></li> <li>94 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/propa_property.glob</code></li> <li>92 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/propa_property.vo</code></li> <li>86 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/lists/lists.vo</code></li> <li>83 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/machine.glob</code></li> <li>80 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/lists/vector_results.vo</code></li> <li>73 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/instructions.vo</code></li> <li>72 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/itera_property.glob</code></li> <li>69 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/fresh_variables.v</code></li> <li>61 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/lists/pred_list.vo</code></li> <li>60 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/lists/m_list.glob</code></li> <li>59 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/typing.vo</code></li> <li>56 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/propa_property2.glob</code></li> <li>54 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/lists/vector_results.glob</code></li> <li>53 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/itera_property.vo</code></li> <li>52 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/substitutions.v</code></li> <li>51 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/machine_types.v</code></li> <li>49 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/lists/lists.glob</code></li> <li>48 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/lists/pred_list.glob</code></li> <li>45 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/lists/vector.vo</code></li> <li>45 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/machine_shapes.v</code></li> <li>44 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/propa_property2.vo</code></li> <li>43 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/kildall.vo</code></li> <li>41 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/kildall_dfa.glob</code></li> <li>41 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/aux/tree.vo</code></li> <li>40 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/lists/well_founded.vo</code></li> <li>37 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/inst_types.v</code></li> <li>35 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/inst_shapes.v</code></li> <li>35 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/kildall.glob</code></li> <li>31 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/propa.vo</code></li> <li>31 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/kildall_dfa.vo</code></li> <li>30 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/dfa.vo</code></li> <li>30 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/iteraterme.vo</code></li> <li>29 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/lists/nat_bounded_list.vo</code></li> <li>28 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/aux/tree.glob</code></li> <li>26 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/kildall_bv.vo</code></li> <li>26 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/instructions.glob</code></li> <li>25 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/lists/vector.glob</code></li> <li>25 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/aux/product_results.vo</code></li> <li>25 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/itera_eq.vo</code></li> <li>24 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/machine.v</code></li> <li>24 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/aux/semilattices.vo</code></li> <li>22 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/itera.vo</code></li> <li>22 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/aux/aux_arith.vo</code></li> <li>21 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/aux/relations.vo</code></li> <li>20 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/lists/lists.v</code></li> <li>18 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/lists/m_list.v</code></li> <li>17 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/propa.glob</code></li> <li>17 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/kildall_bv.glob</code></li> <li>16 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/itera_eq.glob</code></li> <li>16 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/typing.glob</code></li> <li>16 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/lists/pred_list.v</code></li> <li>15 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/dfa.glob</code></li> <li>15 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/lists/vector_results.v</code></li> <li>14 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/iteraterme.glob</code></li> <li>14 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/propa_property.v</code></li> <li>12 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/lists/well_founded.glob</code></li> <li>10 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/aux/tree.v</code></li> <li>9 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/itera_property.v</code></li> <li>8 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/aux/product_results.glob</code></li> <li>7 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/propa_property2.v</code></li> <li>7 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/itera.glob</code></li> <li>7 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/lists/vector.v</code></li> <li>7 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/instructions.v</code></li> <li>6 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/kildall.v</code></li> <li>6 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/inst/typing.v</code></li> <li>6 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/lists/nat_bounded_list.glob</code></li> <li>5 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/aux/relations.glob</code></li> <li>5 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/aux/semilattices.glob</code></li> <li>5 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/kildall_dfa.v</code></li> <li>4 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/dfa.v</code></li> <li>3 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/kildall_bv.v</code></li> <li>3 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/iteraterme.v</code></li> <li>3 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/lists/well_founded.v</code></li> <li>3 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/propa.v</code></li> <li>3 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/itera_eq.v</code></li> <li>3 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/aux/aux_arith.glob</code></li> <li>3 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/aux/semilattices.v</code></li> <li>2 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/lists/nat_bounded_list.v</code></li> <li>2 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/aux/product_results.v</code></li> <li>1 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/aux/relations.v</code></li> <li>1 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/kildall/itera.v</code></li> <li>1 K <code>/home/bench/.opam/system/lib/coq/user-contrib/Kildall/aux/aux_arith.v</code></li> <li>1 K <code>/home/bench/.opam/system/lib/coq:contrib:kildall/opam.config</code></li> <li>1 K <code>/home/bench/.opam/system/install/coq:contrib:kildall.install</code></li> </ul> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq:contrib:kildall.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>2 s</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
BlueButton.js helps developers parse and generate complex health data formats like C-CDA with ease, so you can empower patients with access to their health records. [Try the demo.](http://www.bluebuttonjs.com/sandbox/) ## Quick Start BlueButton.js supports a few different health data types, like C32 and CCDA. To parse a health document, pass the source data to `BlueButton`: ```JavaScript var myRecord = BlueButton(xml); ``` BlueButton.js will detect the document type and choose the appropriate parser. The returned object has the following properties: ```JavaScript myRecord.type // The document type myRecord.source // The parsed source data with added querying methods myRecord.data // The final parsed document data ``` ## Detailed Documentation See http://www.bluebuttonjs.com/docs/ for an explanation of the data sections, much more detailed sample code, instructions on how to generate a build, etc.
require_lib 'reek/cli/silencer' Reek::CLI::Silencer.silently do require 'parser/ruby22' end require_relative '../spec_helper' require_lib 'reek/tree_dresser' RSpec.describe Reek::TreeDresser do let(:dresser) { described_class.new } let(:sexp) do Parser::Ruby22.parse('class Klazz; def meth(argument); argument.call_me; end; end') end let(:dressed_ast) do # The dressed AST looks like this: # (class # (const nil :Klazz) nil # (def :meth # (args # (arg :argument)) # (send # (lvar :argument) :call_me))) dresser.dress(sexp, {}) end let(:const_node) { dressed_ast.children.first } let(:def_node) { dressed_ast.children.last } let(:args_node) { def_node.children[1] } let(:send_node) { def_node.children[2] } context 'dresses the given sexp' do it 'dresses `const` nodes properly' do expect(const_node).to be_a Reek::AST::SexpExtensions::ConstNode end it 'dresses `def` nodes properly' do expect(def_node).to be_a Reek::AST::SexpExtensions::DefNode expect(def_node).to be_a Reek::AST::SexpExtensions::SingletonMethod expect(def_node).to be_a Reek::AST::SexpExtensions::MethodNodeBase end it 'dresses `args` nodes properly' do expect(args_node).to be_a Reek::AST::SexpExtensions::ArgsNode expect(args_node).to be_a Reek::AST::SexpExtensions::NestedAssignables end it 'dresses `send` nodes properly' do expect(send_node).to be_a Reek::AST::SexpExtensions::SendNode end end end
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Security.Cryptography.Rsa.Tests; using Test.IO.Streams; using Xunit; namespace System.Security.Cryptography.Csp.Tests { public class RSACryptoServiceProviderBackCompat { private static readonly byte[] s_dataToSign = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }; [Theory] [MemberData(nameof(AlgorithmIdentifiers))] public static void AlgorithmLookups(string primaryId, object halg) { using (var rsa = new RSACryptoServiceProvider()) { rsa.ImportParameters(TestData.RSA2048Params); byte[] primary = rsa.SignData(s_dataToSign, primaryId); byte[] lookup = rsa.SignData(s_dataToSign, halg); Assert.Equal(primary, lookup); } } [Fact] public static void ApiInterop_OldToNew() { using (var rsa = new RSACryptoServiceProvider()) { byte[] oldSignature = rsa.SignData(s_dataToSign, "SHA384"); Assert.True(rsa.VerifyData(s_dataToSign, oldSignature, HashAlgorithmName.SHA384, RSASignaturePadding.Pkcs1)); } } [Fact] public static void ApiInterop_OldToNew_Positional() { using (var rsa = new RSACryptoServiceProvider()) { byte[] oldSignature = rsa.SignData(s_dataToSign, 3, 2, "SHA384"); Assert.True(rsa.VerifyData(s_dataToSign, 3, 2, oldSignature, HashAlgorithmName.SHA384, RSASignaturePadding.Pkcs1)); } } [Fact] public static void ApiInterop_OldToNew_Stream() { const int TotalCount = 10; using (var rsa = new RSACryptoServiceProvider()) using (PositionValueStream stream1 = new PositionValueStream(TotalCount)) using (PositionValueStream stream2 = new PositionValueStream(TotalCount)) { byte[] oldSignature = rsa.SignData(stream1, "SHA384"); Assert.True(rsa.VerifyData(stream2, oldSignature, HashAlgorithmName.SHA384, RSASignaturePadding.Pkcs1)); } } [Fact] public static void ApiInterop_NewToOld() { using (var rsa = new RSACryptoServiceProvider()) { byte[] newSignature = rsa.SignData(s_dataToSign, HashAlgorithmName.SHA384, RSASignaturePadding.Pkcs1); Assert.True(rsa.VerifyData(s_dataToSign, "SHA384", newSignature)); } } [Fact] public static void SignHash_NullArray() { using (var rsa = new RSACryptoServiceProvider()) { Assert.Throws<ArgumentNullException>(() => rsa.SignHash(null, "SHA384")); } } [Fact] public static void SignHash_BadAlgorithm() { using (var rsa = new RSACryptoServiceProvider()) { Assert.Throws<CryptographicException>(() => rsa.SignHash(Array.Empty<byte>(), "SHA384-9000")); } } [Fact] public static void SignHash_WrongSizeHash() { using (var rsa = new RSACryptoServiceProvider()) { Assert.ThrowsAny<CryptographicException>(() => rsa.SignHash(Array.Empty<byte>(), "SHA384")); } } [Fact] public static void SignHash_PublicKey() { using (var rsa = new RSACryptoServiceProvider()) { RSAParameters publicParams = new RSAParameters { Modulus = TestData.RSA1024Params.Modulus, Exponent = TestData.RSA1024Params.Exponent, }; rsa.ImportParameters(publicParams); Assert.Throws<CryptographicException>(() => rsa.SignHash(Array.Empty<byte>(), "SHA384")); } } [Theory] [InlineData(true, true)] [InlineData(true, false)] [InlineData(false, true)] // (false, false) is not required, that would be equivalent to the RSA AlgorithmImplementation suite. public static void VerifyLegacySignVerifyHash(bool useLegacySign, bool useLegacyVerify) { byte[] dataHash, signature; using (HashAlgorithm hash = SHA256.Create()) { dataHash = hash.ComputeHash(TestData.HelloBytes); } using (var rsa = new RSACryptoServiceProvider()) { rsa.ImportParameters(TestData.RSA2048Params); signature = useLegacySign ? rsa.SignHash(dataHash, "SHA256") : rsa.SignHash(dataHash, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); } bool verified; using (var rsa = new RSACryptoServiceProvider()) { rsa.ImportParameters( new RSAParameters { Modulus = TestData.RSA2048Params.Modulus, Exponent = TestData.RSA2048Params.Exponent, }); verified = useLegacyVerify ? rsa.VerifyHash(dataHash, "SHA256", signature) : rsa.VerifyHash(dataHash, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); } Assert.True(verified); } public static IEnumerable<object[]> AlgorithmIdentifiers() { return new[] { new object[] { "MD5", MD5.Create() }, new object[] { "MD5", typeof(MD5) }, new object[] { "MD5", "1.2.840.113549.2.5" }, new object[] { "SHA1", SHA1.Create() }, new object[] { "SHA1", typeof(SHA1) }, new object[] { "SHA1", "1.3.14.3.2.26" }, new object[] { "SHA256", SHA256.Create() }, new object[] { "SHA256", typeof(SHA256) }, new object[] { "SHA256", "2.16.840.1.101.3.4.2.1" }, new object[] { "SHA384", SHA384.Create() }, new object[] { "SHA384", typeof(SHA384) }, new object[] { "SHA384", "2.16.840.1.101.3.4.2.2" }, new object[] { "SHA512", SHA512.Create() }, new object[] { "SHA512", typeof(SHA512) }, new object[] { "SHA512", "2.16.840.1.101.3.4.2.3" }, }; } } }
package org.drools.verifier.components; import org.drools.compiler.lang.descr.BaseDescr; public abstract class RuleComponent<D extends BaseDescr> extends PackageComponent<D> implements ChildComponent { private String ruleName; private VerifierComponentType parentType; private String parentPath; private int orderNumber; public RuleComponent(VerifierRule rule) { this((D)rule.getDescr(), rule.getPackageName(), rule.getName() ); } RuleComponent(D descr, String packageName, String ruleName) { super( descr, packageName ); setRuleName( ruleName ); } /** * * @return Rule package name + rule name. */ public String getFullRulePath() { return getPackageName() + "/" + getRuleName(); } public String getRuleName() { return ruleName; } protected void setRuleName(String ruleName) { this.ruleName = ruleName; } public String getRulePath() { return String.format( "%s/rule[@name='%s']", getPackagePath(), getRuleName() ); } @Override public String getPath() { return String.format( "%s/ruleComponent[%s]", getRulePath(), getOrderNumber() ); } public VerifierComponentType getParentType() { return parentType; } public String getParentPath() { return parentPath; } public int getOrderNumber() { return orderNumber; } public void setParentType(VerifierComponentType parentType) { this.parentType = parentType; } public void setParentPath(String parentPath) { this.parentPath = parentPath; } public void setOrderNumber(int orderNumber) { this.orderNumber = orderNumber; } }
using System; using Novell.IceDesktop; namespace Tasque.Backends.IceCore { public class IceCategory : ICategory { private Teamspace team; private TaskFolder folder; private string id; public IceCategory(Teamspace iceTeam, TaskFolder iceFolder) { team = iceTeam; folder = iceFolder; // Construct a unique ID in the format: // <team-id>-<task-folder-id> id = string.Format ("{0}-{1}", team.ID, folder.ID); } public string Name { get { return team.Name; } } public bool ContainsTask(ITask task) { if (task == null) return false; IceCategory iceCategory = task.Category as IceCategory; if (iceCategory == null) return false; if (Id.CompareTo (iceCategory.Id) == 0) return true; return false; } public string Id { get { return id; } } public Teamspace Team { get { return team; } } public TaskFolder Folder { get { return folder; } } } }
function init(){ var bootSimply = new BootSimply("LINKEDIN"); bootSimply.oauthFlow(); document.querySelector('#greeting').innerText = 'chrome-linkedin-oauth sample'; } window.onload = init;
require 'test_helper' class I18nTest < ActiveSupport::TestCase def test_uses_authlogic_as_scope_by_default assert_equal :authlogic, Authlogic::I18n.scope end def test_can_set_scope assert_nothing_raised { Authlogic::I18n.scope = [:a, :b] } assert_equal [:a, :b], Authlogic::I18n.scope Authlogic::I18n.scope = :authlogic end def test_uses_built_in_translator_by_default assert_equal Authlogic::I18n::Translator, Authlogic::I18n.translator.class end def test_can_set_custom_translator old_translator = Authlogic::I18n.translator assert_nothing_raised do Authlogic::I18n.translator = Class.new do def translate(key, options = {}) "Translated: #{key}" end end.new end assert_equal "Translated: x", Authlogic::I18n.translate(:x) Authlogic::I18n.translator = old_translator end end
/* * This code is loosely based on ppmtogif from the PBMPLUS distribution * of Feb. 1991. That file contains the following copyright notice: * Based on GIFENCODE by David Rowley <mgardi@watdscu.waterloo.edu>. * Lempel-Ziv compression based on "compress" by Spencer W. Thomas et al. * Copyright (C) 1989 by Jef Poskanzer. * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose and without fee is hereby granted, provided * that the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation. This software is provided "as is" without express or * implied warranty. * * We are also required to state that * "The Graphics Interchange Format(c) is the Copyright property of * CompuServe Incorporated. GIF(sm) is a Service Mark property of * CompuServe Incorporated." */ #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */ #ifdef GIF_SUPPORTED /* Private version of data destination object */ typedef struct { struct djpeg_dest_struct pub; /* public fields */ j_decompress_ptr cinfo; /* back link saves passing separate parm */ /* State for packing variable-width codes into a bitstream */ int n_bits; /* current number of bits/code */ int maxcode; /* maximum code, given n_bits */ INT32 cur_accum; /* holds bits not yet output */ int cur_bits; /* # of bits in cur_accum */ /* State for GIF code assignment */ int ClearCode; /* clear code (doesn't change) */ int EOFCode; /* EOF code (ditto) */ int code_counter; /* counts output symbols */ /* GIF data packet construction buffer */ int bytesinpkt; /* # of bytes in current packet */ char packetbuf[256]; /* workspace for accumulating packet */ } gif_dest_struct; typedef gif_dest_struct * gif_dest_ptr; /* Largest value that will fit in N bits */ #define MAXCODE(n_bits) ((1 << (n_bits)) - 1) /* * Routines to package finished data bytes into GIF data blocks. * A data block consists of a count byte (1..255) and that many data bytes. */ LOCAL(void) flush_packet (gif_dest_ptr dinfo) /* flush any accumulated data */ { if (dinfo->bytesinpkt > 0) { /* never write zero-length packet */ dinfo->packetbuf[0] = (char) dinfo->bytesinpkt++; if (JFWRITE(dinfo->pub.output_file, dinfo->packetbuf, dinfo->bytesinpkt) != (size_t) dinfo->bytesinpkt) ERREXIT(dinfo->cinfo, JERR_FILE_WRITE); dinfo->bytesinpkt = 0; } } /* Add a character to current packet; flush to disk if necessary */ #define CHAR_OUT(dinfo,c) \ { (dinfo)->packetbuf[++(dinfo)->bytesinpkt] = (char) (c); \ if ((dinfo)->bytesinpkt >= 255) \ flush_packet(dinfo); \ } /* Routine to convert variable-width codes into a byte stream */ LOCAL(void) output (gif_dest_ptr dinfo, int code) /* Emit a code of n_bits bits */ /* Uses cur_accum and cur_bits to reblock into 8-bit bytes */ { dinfo->cur_accum |= ((INT32) code) << dinfo->cur_bits; dinfo->cur_bits += dinfo->n_bits; while (dinfo->cur_bits >= 8) { CHAR_OUT(dinfo, dinfo->cur_accum & 0xFF); dinfo->cur_accum >>= 8; dinfo->cur_bits -= 8; } } /* The pseudo-compression algorithm. * * In this module we simply output each pixel value as a separate symbol; * thus, no compression occurs. In fact, there is expansion of one bit per * pixel, because we use a symbol width one bit wider than the pixel width. * * GIF ordinarily uses variable-width symbols, and the decoder will expect * to ratchet up the symbol width after a fixed number of symbols. * To simplify the logic and keep the expansion penalty down, we emit a * GIF Clear code to reset the decoder just before the width would ratchet up. * Thus, all the symbols in the output file will have the same bit width. * Note that emitting the Clear codes at the right times is a mere matter of * counting output symbols and is in no way dependent on the LZW patent. * * With a small basic pixel width (low color count), Clear codes will be * needed very frequently, causing the file to expand even more. So this * simplistic approach wouldn't work too well on bilevel images, for example. * But for output of JPEG conversions the pixel width will usually be 8 bits * (129 to 256 colors), so the overhead added by Clear symbols is only about * one symbol in every 256. */ LOCAL(void) compress_init (gif_dest_ptr dinfo, int i_bits) /* Initialize pseudo-compressor */ { /* init all the state variables */ dinfo->n_bits = i_bits; dinfo->maxcode = MAXCODE(dinfo->n_bits); dinfo->ClearCode = (1 << (i_bits - 1)); dinfo->EOFCode = dinfo->ClearCode + 1; dinfo->code_counter = dinfo->ClearCode + 2; /* init output buffering vars */ dinfo->bytesinpkt = 0; dinfo->cur_accum = 0; dinfo->cur_bits = 0; /* GIF specifies an initial Clear code */ output(dinfo, dinfo->ClearCode); } LOCAL(void) compress_pixel (gif_dest_ptr dinfo, int c) /* Accept and "compress" one pixel value. * The given value must be less than n_bits wide. */ { /* Output the given pixel value as a symbol. */ output(dinfo, c); /* Issue Clear codes often enough to keep the reader from ratcheting up * its symbol size. */ if (dinfo->code_counter < dinfo->maxcode) { dinfo->code_counter++; } else { output(dinfo, dinfo->ClearCode); dinfo->code_counter = dinfo->ClearCode + 2; /* reset the counter */ } } LOCAL(void) compress_term (gif_dest_ptr dinfo) /* Clean up at end */ { /* Send an EOF code */ output(dinfo, dinfo->EOFCode); /* Flush the bit-packing buffer */ if (dinfo->cur_bits > 0) { CHAR_OUT(dinfo, dinfo->cur_accum & 0xFF); } /* Flush the packet buffer */ flush_packet(dinfo); } /* GIF header construction */ LOCAL(void) put_word (gif_dest_ptr dinfo, unsigned int w) /* Emit a 16-bit word, LSB first */ { putc(w & 0xFF, dinfo->pub.output_file); putc((w >> 8) & 0xFF, dinfo->pub.output_file); } LOCAL(void) put_3bytes (gif_dest_ptr dinfo, int val) /* Emit 3 copies of same byte value --- handy subr for colormap construction */ { putc(val, dinfo->pub.output_file); putc(val, dinfo->pub.output_file); putc(val, dinfo->pub.output_file); } LOCAL(void) emit_header (gif_dest_ptr dinfo, int num_colors, JSAMPARRAY colormap) /* Output the GIF file header, including color map */ /* If colormap==NULL, synthesize a grayscale colormap */ { int BitsPerPixel, ColorMapSize, InitCodeSize, FlagByte; int cshift = dinfo->cinfo->data_precision - 8; int i; if (num_colors > 256) ERREXIT1(dinfo->cinfo, JERR_TOO_MANY_COLORS, num_colors); /* Compute bits/pixel and related values */ BitsPerPixel = 1; while (num_colors > (1 << BitsPerPixel)) BitsPerPixel++; ColorMapSize = 1 << BitsPerPixel; if (BitsPerPixel <= 1) InitCodeSize = 2; else InitCodeSize = BitsPerPixel; /* * Write the GIF header. * Note that we generate a plain GIF87 header for maximum compatibility. */ putc('G', dinfo->pub.output_file); putc('I', dinfo->pub.output_file); putc('F', dinfo->pub.output_file); putc('8', dinfo->pub.output_file); putc('7', dinfo->pub.output_file); putc('a', dinfo->pub.output_file); /* Write the Logical Screen Descriptor */ put_word(dinfo, (unsigned int) dinfo->cinfo->output_width); put_word(dinfo, (unsigned int) dinfo->cinfo->output_height); FlagByte = 0x80; /* Yes, there is a global color table */ FlagByte |= (BitsPerPixel-1) << 4; /* color resolution */ FlagByte |= (BitsPerPixel-1); /* size of global color table */ putc(FlagByte, dinfo->pub.output_file); putc(0, dinfo->pub.output_file); /* Background color index */ putc(0, dinfo->pub.output_file); /* Reserved (aspect ratio in GIF89) */ /* Write the Global Color Map */ /* If the color map is more than 8 bits precision, */ /* we reduce it to 8 bits by shifting */ for (i=0; i < ColorMapSize; i++) { if (i < num_colors) { if (colormap != NULL) { if (dinfo->cinfo->out_color_space == JCS_RGB) { /* Normal case: RGB color map */ putc(GETJSAMPLE(colormap[0][i]) >> cshift, dinfo->pub.output_file); putc(GETJSAMPLE(colormap[1][i]) >> cshift, dinfo->pub.output_file); putc(GETJSAMPLE(colormap[2][i]) >> cshift, dinfo->pub.output_file); } else { /* Grayscale "color map": possible if quantizing grayscale image */ put_3bytes(dinfo, GETJSAMPLE(colormap[0][i]) >> cshift); } } else { /* Create a grayscale map of num_colors values, range 0..255 */ put_3bytes(dinfo, (i * 255 + (num_colors-1)/2) / (num_colors-1)); } } else { /* fill out the map to a power of 2 */ put_3bytes(dinfo, 0); } } /* Write image separator and Image Descriptor */ putc(',', dinfo->pub.output_file); /* separator */ put_word(dinfo, 0); /* left/top offset */ put_word(dinfo, 0); put_word(dinfo, (unsigned int) dinfo->cinfo->output_width); /* image size */ put_word(dinfo, (unsigned int) dinfo->cinfo->output_height); /* flag byte: not interlaced, no local color map */ putc(0x00, dinfo->pub.output_file); /* Write Initial Code Size byte */ putc(InitCodeSize, dinfo->pub.output_file); /* Initialize for "compression" of image data */ compress_init(dinfo, InitCodeSize+1); } /* * Startup: write the file header. */ METHODDEF(void) start_output_gif (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo) { gif_dest_ptr dest = (gif_dest_ptr) dinfo; if (cinfo->quantize_colors) emit_header(dest, cinfo->actual_number_of_colors, cinfo->colormap); else emit_header(dest, 256, (JSAMPARRAY) NULL); } /* * Write some pixel data. * In this module rows_supplied will always be 1. */ METHODDEF(void) put_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo, JDIMENSION rows_supplied) { gif_dest_ptr dest = (gif_dest_ptr) dinfo; register JSAMPROW ptr; register JDIMENSION col; ptr = dest->pub.buffer[0]; for (col = cinfo->output_width; col > 0; col--) { compress_pixel(dest, GETJSAMPLE(*ptr++)); } } /* * Finish up at the end of the file. */ METHODDEF(void) finish_output_gif (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo) { gif_dest_ptr dest = (gif_dest_ptr) dinfo; /* Flush "compression" mechanism */ compress_term(dest); /* Write a zero-length data block to end the series */ putc(0, dest->pub.output_file); /* Write the GIF terminator mark */ putc(';', dest->pub.output_file); /* Make sure we wrote the output file OK */ fflush(dest->pub.output_file); if (ferror(dest->pub.output_file)) ERREXIT(cinfo, JERR_FILE_WRITE); } /* * The module selection routine for GIF format output. */ GLOBAL(djpeg_dest_ptr) jinit_write_gif (j_decompress_ptr cinfo) { gif_dest_ptr dest; /* Create module interface object, fill in method pointers */ dest = (gif_dest_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, sizeof(gif_dest_struct)); dest->cinfo = cinfo; /* make back link for subroutines */ dest->pub.start_output = start_output_gif; dest->pub.put_pixel_rows = put_pixel_rows; dest->pub.finish_output = finish_output_gif; if (cinfo->out_color_space != JCS_GRAYSCALE && cinfo->out_color_space != JCS_RGB) ERREXIT(cinfo, JERR_GIF_COLORSPACE); /* Force quantization if color or if > 8 bits input */ if (cinfo->out_color_space != JCS_GRAYSCALE || cinfo->data_precision > 8) { /* Force quantization to at most 256 colors */ cinfo->quantize_colors = TRUE; if (cinfo->desired_number_of_colors > 256) cinfo->desired_number_of_colors = 256; } /* Calculate output image dimensions so we can allocate space */ jpeg_calc_output_dimensions(cinfo); if (cinfo->output_components != 1) /* safety check: just one component? */ ERREXIT(cinfo, JERR_GIF_BUG); /* Create decompressor output buffer. */ dest->pub.buffer = (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, cinfo->output_width, (JDIMENSION) 1); dest->pub.buffer_height = 1; return (djpeg_dest_ptr) dest; } #endif /* GIF_SUPPORTED */
<div> Veel aspecten van een bouwpoging zijn tijdsafhankelijk. Daarom kan een afwijking van de systeemklok tussen Jenkins en de slaafnodes, eigenaardige problemen veroorzaken. Het valt te overwegen om te zorgen voor een synchronisatie van de systeemklokken via NTP. </div>
using System; using UnityEngine; namespace UnityStandardAssets.Utility { public class TimedObjectDestructor : MonoBehaviour { [SerializeField] private float m_TimeOut = 1.0f; [SerializeField] private bool m_DetachChildren = false; private void Awake() { Invoke("DestroyNow", m_TimeOut); } private void DestroyNow() { if (m_DetachChildren) { transform.DetachChildren(); } DestroyObject(gameObject); } } }
import { HelpMenu } from '@jupyterlab/mainmenu'; import { CommandRegistry } from '@lumino/commands'; describe('@jupyterlab/mainmenu', () => { describe('HelpMenu', () => { let commands: CommandRegistry; let menu: HelpMenu; beforeAll(() => { commands = new CommandRegistry(); }); beforeEach(() => { menu = new HelpMenu({ commands }); }); afterEach(() => { menu.dispose(); }); describe('#constructor()', () => { it('should construct a new help menu', () => { expect(menu).toBeInstanceOf(HelpMenu); // For localization this is now defined when on the mainmenu-extension. expect(menu.title.label).toBe(''); }); }); }); });
package org.elasticsearch.index.query.functionscore; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.SortedNumericDocValues; import org.apache.lucene.index.Term; import org.apache.lucene.search.Explanation; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.RandomApproximationQuery; import org.apache.lucene.search.Scorer; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.Weight; import org.apache.lucene.search.SortField; import org.apache.lucene.store.Directory; import org.apache.lucene.util.Accountable; import org.apache.lucene.util.BytesRef; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.lucene.search.function.CombineFunction; import org.elasticsearch.common.lucene.search.function.FieldValueFactorFunction; import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery; import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery.ScoreMode; import org.elasticsearch.common.lucene.search.function.LeafScoreFunction; import org.elasticsearch.common.lucene.search.function.RandomScoreFunction; import org.elasticsearch.common.lucene.search.function.ScoreFunction; import org.elasticsearch.common.lucene.search.function.WeightFactorFunction; import org.elasticsearch.index.Index; import org.elasticsearch.index.fielddata.AtomicFieldData; import org.elasticsearch.index.fielddata.AtomicNumericFieldData; import org.elasticsearch.index.fielddata.IndexFieldData; import org.elasticsearch.index.fielddata.IndexNumericFieldData; import org.elasticsearch.index.fielddata.ScriptDocValues; import org.elasticsearch.index.fielddata.SortedBinaryDocValues; import org.elasticsearch.index.fielddata.SortedNumericDoubleValues; import org.elasticsearch.search.MultiValueMode; import org.elasticsearch.test.ESTestCase; import org.junit.After; import org.junit.Before; import java.io.IOException; import java.util.Collection; import java.util.concurrent.ExecutionException; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; import static org.elasticsearch.common.lucene.search.function.FunctionScoreQuery.FilterScoreFunction; public class FunctionScoreTests extends ESTestCase { private static final String UNSUPPORTED = "Method not implemented. This is just a stub for testing."; /** * Stub for IndexFieldData. Needed by some score functions. Returns 1 as count always. */ private static class IndexFieldDataStub implements IndexFieldData<AtomicFieldData> { @Override public String getFieldName() { return "test"; } @Override public AtomicFieldData load(LeafReaderContext context) { return new AtomicFieldData() { @Override public ScriptDocValues getScriptValues() { throw new UnsupportedOperationException(UNSUPPORTED); } @Override public SortedBinaryDocValues getBytesValues() { return new SortedBinaryDocValues() { @Override public boolean advanceExact(int docId) { return true; } @Override public int docValueCount() { return 1; } @Override public BytesRef nextValue() { return new BytesRef("0"); } }; } @Override public long ramBytesUsed() { throw new UnsupportedOperationException(UNSUPPORTED); } @Override public Collection<Accountable> getChildResources() { throw new UnsupportedOperationException(UNSUPPORTED); } @Override public void close() { } }; } @Override public AtomicFieldData loadDirect(LeafReaderContext context) throws Exception { throw new UnsupportedOperationException(UNSUPPORTED); } @Override public SortField sortField(@Nullable Object missingValue, MultiValueMode sortMode, XFieldComparatorSource.Nested nested, boolean reverse) { throw new UnsupportedOperationException(UNSUPPORTED); } @Override public void clear() { throw new UnsupportedOperationException(UNSUPPORTED); } @Override public Index index() { throw new UnsupportedOperationException(UNSUPPORTED); } } /** * Stub for IndexNumericFieldData needed by some score functions. Returns 1 as value always. */ private static class IndexNumericFieldDataStub implements IndexNumericFieldData { @Override public NumericType getNumericType() { throw new UnsupportedOperationException(UNSUPPORTED); } @Override public String getFieldName() { return "test"; } @Override public AtomicNumericFieldData load(LeafReaderContext context) { return new AtomicNumericFieldData() { @Override public SortedNumericDocValues getLongValues() { throw new UnsupportedOperationException(UNSUPPORTED); } @Override public SortedNumericDoubleValues getDoubleValues() { return new SortedNumericDoubleValues() { @Override public boolean advanceExact(int docId) { return true; } @Override public int docValueCount() { return 1; } @Override public double nextValue() { return 1d; } }; } @Override public ScriptDocValues getScriptValues() { throw new UnsupportedOperationException(UNSUPPORTED); } @Override public SortedBinaryDocValues getBytesValues() { throw new UnsupportedOperationException(UNSUPPORTED); } @Override public long ramBytesUsed() { throw new UnsupportedOperationException(UNSUPPORTED); } @Override public Collection<Accountable> getChildResources() { throw new UnsupportedOperationException(UNSUPPORTED); } @Override public void close() { } }; } @Override public AtomicNumericFieldData loadDirect(LeafReaderContext context) throws Exception { throw new UnsupportedOperationException(UNSUPPORTED); } @Override public SortField sortField(@Nullable Object missingValue, MultiValueMode sortMode, XFieldComparatorSource.Nested nested, boolean reverse) { throw new UnsupportedOperationException(UNSUPPORTED); } @Override public void clear() { throw new UnsupportedOperationException(UNSUPPORTED); } @Override public Index index() { throw new UnsupportedOperationException(UNSUPPORTED); } } private static final ScoreFunction RANDOM_SCORE_FUNCTION = new RandomScoreFunction(0, 0, new IndexFieldDataStub()); private static final ScoreFunction FIELD_VALUE_FACTOR_FUNCTION = new FieldValueFactorFunction("test", 1, FieldValueFactorFunction.Modifier.LN, 1.0, null); private static final ScoreFunction GAUSS_DECAY_FUNCTION = new DecayFunctionBuilder.NumericFieldDataScoreFunction(0, 1, 0.1, 0, GaussDecayFunctionBuilder.GAUSS_DECAY_FUNCTION, new IndexNumericFieldDataStub(), MultiValueMode.MAX); private static final ScoreFunction EXP_DECAY_FUNCTION = new DecayFunctionBuilder.NumericFieldDataScoreFunction(0, 1, 0.1, 0, ExponentialDecayFunctionBuilder.EXP_DECAY_FUNCTION, new IndexNumericFieldDataStub(), MultiValueMode.MAX); private static final ScoreFunction LIN_DECAY_FUNCTION = new DecayFunctionBuilder.NumericFieldDataScoreFunction(0, 1, 0.1, 0, LinearDecayFunctionBuilder.LINEAR_DECAY_FUNCTION, new IndexNumericFieldDataStub(), MultiValueMode.MAX); private static final ScoreFunction WEIGHT_FACTOR_FUNCTION = new WeightFactorFunction(4); private static final String TEXT = "The way out is through."; private static final String FIELD = "test"; private static final Term TERM = new Term(FIELD, "through"); private Directory dir; private IndexWriter w; private DirectoryReader reader; private IndexSearcher searcher; @Before public void initSearcher() throws IOException { dir = newDirectory(); w = new IndexWriter(dir, newIndexWriterConfig(new StandardAnalyzer())); Document d = new Document(); d.add(new TextField(FIELD, TEXT, Field.Store.YES)); d.add(new TextField("_uid", "1", Field.Store.YES)); w.addDocument(d); w.commit(); reader = DirectoryReader.open(w); searcher = newSearcher(reader); } @After public void closeAllTheReaders() throws IOException { reader.close(); w.close(); dir.close(); } public void testExplainFunctionScoreQuery() throws IOException { Explanation functionExplanation = getFunctionScoreExplanation(searcher, RANDOM_SCORE_FUNCTION); checkFunctionScoreExplanation(functionExplanation, "random score function (seed: 0, field: test)"); assertThat(functionExplanation.getDetails()[0].getDetails().length, equalTo(0)); functionExplanation = getFunctionScoreExplanation(searcher, FIELD_VALUE_FACTOR_FUNCTION); checkFunctionScoreExplanation(functionExplanation, "field value function: ln(doc['test'].value?:1.0 * factor=1.0)"); assertThat(functionExplanation.getDetails()[0].getDetails().length, equalTo(0)); functionExplanation = getFunctionScoreExplanation(searcher, GAUSS_DECAY_FUNCTION); checkFunctionScoreExplanation(functionExplanation, "Function for field test:"); assertThat(functionExplanation.getDetails()[0].getDetails()[0].toString(), equalTo("0.1 = exp(-0.5*pow(MAX[Math.max(Math.abs" + "(1.0(=doc value) - 0.0(=origin))) - 0.0(=offset), 0)],2.0)/0.21714724095162594)\n")); assertThat(functionExplanation.getDetails()[0].getDetails()[0].getDetails().length, equalTo(0)); functionExplanation = getFunctionScoreExplanation(searcher, EXP_DECAY_FUNCTION); checkFunctionScoreExplanation(functionExplanation, "Function for field test:"); assertThat(functionExplanation.getDetails()[0].getDetails()[0].toString(), equalTo("0.1 = exp(- MAX[Math.max(Math.abs(1.0(=doc value) - 0.0(=origin))) - 0.0(=offset), 0)] * 2.3025850929940455)\n")); assertThat(functionExplanation.getDetails()[0].getDetails()[0].getDetails().length, equalTo(0)); functionExplanation = getFunctionScoreExplanation(searcher, LIN_DECAY_FUNCTION); checkFunctionScoreExplanation(functionExplanation, "Function for field test:"); assertThat(functionExplanation.getDetails()[0].getDetails()[0].toString(), equalTo("0.1 = max(0.0, ((1.1111111111111112" + " - MAX[Math.max(Math.abs(1.0(=doc value) - 0.0(=origin))) - 0.0(=offset), 0)])/1.1111111111111112)\n")); assertThat(functionExplanation.getDetails()[0].getDetails()[0].getDetails().length, equalTo(0)); functionExplanation = getFunctionScoreExplanation(searcher, WEIGHT_FACTOR_FUNCTION); checkFunctionScoreExplanation(functionExplanation, "product of:"); assertThat(functionExplanation.getDetails()[0].getDetails()[0].toString(), equalTo("1.0 = constant score 1.0 - no function provided\n")); assertThat(functionExplanation.getDetails()[0].getDetails()[1].toString(), equalTo("4.0 = weight\n")); assertThat(functionExplanation.getDetails()[0].getDetails()[0].getDetails().length, equalTo(0)); assertThat(functionExplanation.getDetails()[0].getDetails()[1].getDetails().length, equalTo(0)); } public Explanation getFunctionScoreExplanation(IndexSearcher searcher, ScoreFunction scoreFunction) throws IOException { FunctionScoreQuery functionScoreQuery = new FunctionScoreQuery(new TermQuery(TERM), scoreFunction, CombineFunction.AVG,0.0f, 100); Weight weight = searcher.createNormalizedWeight(functionScoreQuery, true); Explanation explanation = weight.explain(searcher.getIndexReader().leaves().get(0), 0); return explanation.getDetails()[1]; } public void checkFunctionScoreExplanation(Explanation randomExplanation, String functionExpl) { assertThat(randomExplanation.getDescription(), equalTo("min of:")); assertThat(randomExplanation.getDetails()[0].getDescription(), containsString(functionExpl)); } public void testExplainFiltersFunctionScoreQuery() throws IOException { Explanation functionExplanation = getFiltersFunctionScoreExplanation(searcher, RANDOM_SCORE_FUNCTION); checkFiltersFunctionScoreExplanation(functionExplanation, "random score function (seed: 0, field: test)", 0); assertThat(functionExplanation.getDetails()[0].getDetails()[0].getDetails()[1].getDetails().length, equalTo(0)); functionExplanation = getFiltersFunctionScoreExplanation(searcher, FIELD_VALUE_FACTOR_FUNCTION); checkFiltersFunctionScoreExplanation(functionExplanation, "field value function: ln(doc['test'].value?:1.0 * factor=1.0)", 0); assertThat(functionExplanation.getDetails()[0].getDetails()[0].getDetails()[1].getDetails().length, equalTo(0)); functionExplanation = getFiltersFunctionScoreExplanation(searcher, GAUSS_DECAY_FUNCTION); checkFiltersFunctionScoreExplanation(functionExplanation, "Function for field test:", 0); assertThat(functionExplanation.getDetails()[0].getDetails()[0].getDetails()[1].getDetails()[0].toString(), equalTo("0.1 = " + "exp(-0.5*pow(MAX[Math.max(Math.abs(1.0(=doc value) - 0.0(=origin))) - 0.0(=offset), 0)],2.0)/0.21714724095162594)\n")); assertThat(functionExplanation.getDetails()[0].getDetails()[0].getDetails()[1].getDetails()[0].getDetails().length, equalTo(0)); functionExplanation = getFiltersFunctionScoreExplanation(searcher, EXP_DECAY_FUNCTION); checkFiltersFunctionScoreExplanation(functionExplanation, "Function for field test:", 0); assertThat(functionExplanation.getDetails()[0].getDetails()[0].getDetails()[1].getDetails()[0].toString(), equalTo("0.1 = exp(- MAX[Math.max(Math.abs(1.0(=doc value) - 0.0(=origin))) - 0.0(=offset), 0)] * 2.3025850929940455)\n")); assertThat(functionExplanation.getDetails()[0].getDetails()[0].getDetails()[1].getDetails()[0].getDetails().length, equalTo(0)); functionExplanation = getFiltersFunctionScoreExplanation(searcher, LIN_DECAY_FUNCTION); checkFiltersFunctionScoreExplanation(functionExplanation, "Function for field test:", 0); assertThat(functionExplanation.getDetails()[0].getDetails()[0].getDetails()[1].getDetails()[0].toString(), equalTo("0.1 = max(0.0, ((1.1111111111111112 - MAX[Math.max(Math.abs(1.0(=doc value) - 0.0(=origin)))" + " - 0.0(=offset), 0)])/1.1111111111111112)\n")); assertThat(functionExplanation.getDetails()[0].getDetails()[0].getDetails()[1].getDetails()[0].getDetails().length, equalTo(0)); // now test all together functionExplanation = getFiltersFunctionScoreExplanation(searcher , RANDOM_SCORE_FUNCTION , FIELD_VALUE_FACTOR_FUNCTION , GAUSS_DECAY_FUNCTION , EXP_DECAY_FUNCTION , LIN_DECAY_FUNCTION ); checkFiltersFunctionScoreExplanation(functionExplanation, "random score function (seed: 0, field: test)", 0); assertThat(functionExplanation.getDetails()[0].getDetails()[0].getDetails()[1].getDetails().length, equalTo(0)); checkFiltersFunctionScoreExplanation(functionExplanation, "field value function: ln(doc['test'].value?:1.0 * factor=1.0)", 1); assertThat(functionExplanation.getDetails()[0].getDetails()[1].getDetails()[1].getDetails().length, equalTo(0)); checkFiltersFunctionScoreExplanation(functionExplanation, "Function for field test:", 2); assertThat(functionExplanation.getDetails()[0].getDetails()[2].getDetails()[1].getDetails()[0].toString(), equalTo("0.1 = " + "exp(-0.5*pow(MAX[Math.max(Math.abs(1.0(=doc value) - 0.0(=origin))) - 0.0(=offset), 0)],2.0)/0.21714724095162594)\n")); assertThat(functionExplanation.getDetails()[0].getDetails()[2].getDetails()[1].getDetails()[0].getDetails().length, equalTo(0)); checkFiltersFunctionScoreExplanation(functionExplanation, "Function for field test:", 3); assertThat(functionExplanation.getDetails()[0].getDetails()[3].getDetails()[1].getDetails()[0].toString(), equalTo( "0.1 = exp(- " + "MAX[Math.max(Math.abs(1.0(=doc value) - 0.0(=origin))) - 0.0(=offset), 0)] * 2.3025850929940455)\n")); assertThat(functionExplanation.getDetails()[0].getDetails()[3].getDetails()[1].getDetails()[0].getDetails().length, equalTo(0)); checkFiltersFunctionScoreExplanation(functionExplanation, "Function for field test:", 4); assertThat(functionExplanation.getDetails()[0].getDetails()[4].getDetails()[1].getDetails()[0].toString(), equalTo("0.1 = max(0.0, ((1.1111111111111112 - MAX[Math.max(Math.abs(1.0(=doc value) - 0.0(=origin)))" + " - 0.0(=offset), 0)])/1.1111111111111112)\n")); assertThat(functionExplanation.getDetails()[0].getDetails()[4].getDetails()[1].getDetails()[0].getDetails().length, equalTo(0)); } public Explanation getFiltersFunctionScoreExplanation(IndexSearcher searcher, ScoreFunction... scoreFunctions) throws IOException { FunctionScoreQuery functionScoreQuery = getFiltersFunctionScoreQuery(FunctionScoreQuery.ScoreMode.AVG, CombineFunction.AVG, scoreFunctions); return getExplanation(searcher, functionScoreQuery).getDetails()[1]; } protected Explanation getExplanation(IndexSearcher searcher, FunctionScoreQuery functionScoreQuery) throws IOException { Weight weight = searcher.createNormalizedWeight(functionScoreQuery, true); return weight.explain(searcher.getIndexReader().leaves().get(0), 0); } public FunctionScoreQuery getFiltersFunctionScoreQuery(FunctionScoreQuery.ScoreMode scoreMode, CombineFunction combineFunction, ScoreFunction... scoreFunctions) { ScoreFunction[] filterFunctions = new ScoreFunction[scoreFunctions.length]; for (int i = 0; i < scoreFunctions.length; i++) { filterFunctions[i] = new FunctionScoreQuery.FilterScoreFunction( new TermQuery(TERM), scoreFunctions[i]); } return new FunctionScoreQuery(new TermQuery(TERM), scoreMode, filterFunctions, combineFunction,Float.MAX_VALUE * -1, Float.MAX_VALUE); } public void checkFiltersFunctionScoreExplanation(Explanation randomExplanation, String functionExpl, int whichFunction) { assertThat(randomExplanation.getDescription(), equalTo("min of:")); Explanation explanation = randomExplanation.getDetails()[0]; assertThat(explanation.getDescription(), equalTo("function score, score mode [avg]")); Explanation functionExplanation = randomExplanation.getDetails()[0].getDetails()[whichFunction]; assertThat(functionExplanation.getDescription(), equalTo("function score, product of:")); assertThat(functionExplanation.getDetails()[0].getDescription(), equalTo("match filter: " + FIELD + ":" + TERM.text())); assertThat(functionExplanation.getDetails()[1].getDescription(), equalTo(functionExpl)); } private static float[] randomFloats(int size) { float[] values = new float[size]; for (int i = 0; i < values.length; i++) { values[i] = randomFloat() * (randomBoolean() ? 1.0f : -1.0f) * randomInt(100) + 1.e-5f; } return values; } private static double[] randomDoubles(int size) { double[] values = new double[size]; for (int i = 0; i < values.length; i++) { values[i] = randomDouble() * (randomBoolean() ? 1.0d : -1.0d) * randomInt(100) + 1.e-5d; } return values; } private static class ScoreFunctionStub extends ScoreFunction { private double score; ScoreFunctionStub(double score) { super(CombineFunction.REPLACE); this.score = score; } @Override public LeafScoreFunction getLeafScoreFunction(LeafReaderContext ctx) throws IOException { return new LeafScoreFunction() { @Override public double score(int docId, float subQueryScore) { return score; } @Override public Explanation explainScore(int docId, Explanation subQueryScore) throws IOException { return Explanation.match((float) score, "a random score for testing"); } }; } @Override public boolean needsScores() { return false; } @Override protected boolean doEquals(ScoreFunction other) { return false; } @Override protected int doHashCode() { return 0; } } public void testSimpleWeightedFunction() throws IOException, ExecutionException, InterruptedException { int numFunctions = randomIntBetween(1, 3); float[] weights = randomFloats(numFunctions); double[] scores = randomDoubles(numFunctions); ScoreFunctionStub[] scoreFunctionStubs = new ScoreFunctionStub[numFunctions]; for (int i = 0; i < numFunctions; i++) { scoreFunctionStubs[i] = new ScoreFunctionStub(scores[i]); } WeightFactorFunction[] weightFunctionStubs = new WeightFactorFunction[numFunctions]; for (int i = 0; i < numFunctions; i++) { weightFunctionStubs[i] = new WeightFactorFunction(weights[i], scoreFunctionStubs[i]); } FunctionScoreQuery functionScoreQueryWithWeights = getFiltersFunctionScoreQuery( FunctionScoreQuery.ScoreMode.MULTIPLY , CombineFunction.REPLACE , weightFunctionStubs ); TopDocs topDocsWithWeights = searcher.search(functionScoreQueryWithWeights, 1); float scoreWithWeight = topDocsWithWeights.scoreDocs[0].score; double score = 1; for (int i = 0; i < weights.length; i++) { score *= weights[i] * scores[i]; } assertThat(scoreWithWeight / (float) score, is(1f)); float explainedScore = getExplanation(searcher, functionScoreQueryWithWeights).getValue(); assertThat(explainedScore / scoreWithWeight, is(1f)); functionScoreQueryWithWeights = getFiltersFunctionScoreQuery( FunctionScoreQuery.ScoreMode.SUM , CombineFunction.REPLACE , weightFunctionStubs ); topDocsWithWeights = searcher.search(functionScoreQueryWithWeights, 1); scoreWithWeight = topDocsWithWeights.scoreDocs[0].score; double sum = 0; for (int i = 0; i < weights.length; i++) { sum += weights[i] * scores[i]; } assertThat(scoreWithWeight / (float) sum, is(1f)); explainedScore = getExplanation(searcher, functionScoreQueryWithWeights).getValue(); assertThat(explainedScore / scoreWithWeight, is(1f)); functionScoreQueryWithWeights = getFiltersFunctionScoreQuery( FunctionScoreQuery.ScoreMode.AVG , CombineFunction.REPLACE , weightFunctionStubs ); topDocsWithWeights = searcher.search(functionScoreQueryWithWeights, 1); scoreWithWeight = topDocsWithWeights.scoreDocs[0].score; double norm = 0; sum = 0; for (int i = 0; i < weights.length; i++) { norm += weights[i]; sum += weights[i] * scores[i]; } assertThat(scoreWithWeight / (float) (sum / norm), is(1f)); explainedScore = getExplanation(searcher, functionScoreQueryWithWeights).getValue(); assertThat(explainedScore / scoreWithWeight, is(1f)); functionScoreQueryWithWeights = getFiltersFunctionScoreQuery( FunctionScoreQuery.ScoreMode.MIN , CombineFunction.REPLACE , weightFunctionStubs ); topDocsWithWeights = searcher.search(functionScoreQueryWithWeights, 1); scoreWithWeight = topDocsWithWeights.scoreDocs[0].score; double min = Double.POSITIVE_INFINITY; for (int i = 0; i < weights.length; i++) { min = Math.min(min, weights[i] * scores[i]); } assertThat(scoreWithWeight / (float) min, is(1f)); explainedScore = getExplanation(searcher, functionScoreQueryWithWeights).getValue(); assertThat(explainedScore / scoreWithWeight, is(1f)); functionScoreQueryWithWeights = getFiltersFunctionScoreQuery( FunctionScoreQuery.ScoreMode.MAX , CombineFunction.REPLACE , weightFunctionStubs ); topDocsWithWeights = searcher.search(functionScoreQueryWithWeights, 1); scoreWithWeight = topDocsWithWeights.scoreDocs[0].score; double max = Double.NEGATIVE_INFINITY; for (int i = 0; i < weights.length; i++) { max = Math.max(max, weights[i] * scores[i]); } assertThat(scoreWithWeight / (float) max, is(1f)); explainedScore = getExplanation(searcher, functionScoreQueryWithWeights).getValue(); assertThat(explainedScore / scoreWithWeight, is(1f)); } public void testWeightOnlyCreatesBoostFunction() throws IOException { FunctionScoreQuery filtersFunctionScoreQueryWithWeights = new FunctionScoreQuery(new MatchAllDocsQuery(), new WeightFactorFunction(2), CombineFunction.MULTIPLY,0.0f, 100); TopDocs topDocsWithWeights = searcher.search(filtersFunctionScoreQueryWithWeights, 1); float score = topDocsWithWeights.scoreDocs[0].score; assertThat(score, equalTo(2.0f)); } public void testMinScoreExplain() throws IOException { Query query = new MatchAllDocsQuery(); Explanation queryExpl = searcher.explain(query, 0); FunctionScoreQuery fsq = new FunctionScoreQuery(query,0f, Float.POSITIVE_INFINITY); Explanation fsqExpl = searcher.explain(fsq, 0); assertTrue(fsqExpl.isMatch()); assertEquals(queryExpl.getValue(), fsqExpl.getValue(), 0f); assertEquals(queryExpl.getDescription(), fsqExpl.getDescription()); fsq = new FunctionScoreQuery(query, 10f, Float.POSITIVE_INFINITY); fsqExpl = searcher.explain(fsq, 0); assertFalse(fsqExpl.isMatch()); assertEquals("Score value is too low, expected at least 10.0 but got 1.0", fsqExpl.getDescription()); FunctionScoreQuery ffsq = new FunctionScoreQuery(query, 0f, Float.POSITIVE_INFINITY); Explanation ffsqExpl = searcher.explain(ffsq, 0); assertTrue(ffsqExpl.isMatch()); assertEquals(queryExpl.getValue(), ffsqExpl.getValue(), 0f); assertEquals(queryExpl.getDescription(), ffsqExpl.getDescription()); ffsq = new FunctionScoreQuery(query, 10f, Float.POSITIVE_INFINITY); ffsqExpl = searcher.explain(ffsq, 0); assertFalse(ffsqExpl.isMatch()); assertEquals("Score value is too low, expected at least 10.0 but got 1.0", ffsqExpl.getDescription()); } public void testPropagatesApproximations() throws IOException { Query query = new RandomApproximationQuery(new MatchAllDocsQuery(), random()); IndexSearcher searcher = newSearcher(reader); searcher.setQueryCache(null); // otherwise we could get a cached entry that does not have approximations FunctionScoreQuery fsq = new FunctionScoreQuery(query, null, Float.POSITIVE_INFINITY); for (boolean needsScores : new boolean[] {true, false}) { Weight weight = searcher.createWeight(fsq, needsScores, 1f); Scorer scorer = weight.scorer(reader.leaves().get(0)); assertNotNull(scorer.twoPhaseIterator()); } } public void testFunctionScoreHashCodeAndEquals() { Float minScore = randomBoolean() ? null : 1.0f; CombineFunction combineFunction = randomFrom(CombineFunction.values()); float maxBoost = randomBoolean() ? Float.POSITIVE_INFINITY : randomFloat(); ScoreFunction function = new DummyScoreFunction(combineFunction); FunctionScoreQuery q = new FunctionScoreQuery(new TermQuery(new Term("foo", "bar")), function, combineFunction, minScore, maxBoost); FunctionScoreQuery q1 = new FunctionScoreQuery(new TermQuery(new Term("foo", "bar")), function, combineFunction, minScore, maxBoost); assertEquals(q, q); assertEquals(q.hashCode(), q.hashCode()); assertEquals(q, q1); assertEquals(q.hashCode(), q1.hashCode()); FunctionScoreQuery diffQuery = new FunctionScoreQuery(new TermQuery(new Term("foo", "baz")), function, combineFunction, minScore, maxBoost); FunctionScoreQuery diffMinScore = new FunctionScoreQuery(q.getSubQuery(), function, combineFunction, minScore == null ? 1.0f : null, maxBoost); ScoreFunction otherFunction = new DummyScoreFunction(combineFunction); FunctionScoreQuery diffFunction = new FunctionScoreQuery(q.getSubQuery(), otherFunction, combineFunction, minScore, maxBoost); FunctionScoreQuery diffMaxBoost = new FunctionScoreQuery(new TermQuery(new Term("foo", "bar")), function, combineFunction, minScore, maxBoost == 1.0f ? 0.9f : 1.0f); FunctionScoreQuery[] queries = new FunctionScoreQuery[] { diffFunction, diffMinScore, diffQuery, q, diffMaxBoost }; final int numIters = randomIntBetween(20, 100); for (int i = 0; i < numIters; i++) { FunctionScoreQuery left = randomFrom(queries); FunctionScoreQuery right = randomFrom(queries); if (left == right) { assertEquals(left, right); assertEquals(left.hashCode(), right.hashCode()); } else { assertNotEquals(left + " == " + right, left, right); } } } public void testFilterFunctionScoreHashCodeAndEquals() { CombineFunction combineFunction = randomFrom(CombineFunction.values()); ScoreFunction scoreFunction = new DummyScoreFunction(combineFunction); Float minScore = randomBoolean() ? null : 1.0f; Float maxBoost = randomBoolean() ? Float.POSITIVE_INFINITY : randomFloat(); FilterScoreFunction function = new FilterScoreFunction(new TermQuery(new Term("filter", "query")), scoreFunction); FunctionScoreQuery q = new FunctionScoreQuery(new TermQuery(new Term("foo", "bar")), function, combineFunction, minScore, maxBoost); FunctionScoreQuery q1 = new FunctionScoreQuery(new TermQuery(new Term("foo", "bar")), function, combineFunction, minScore, maxBoost); assertEquals(q, q); assertEquals(q.hashCode(), q.hashCode()); assertEquals(q, q1); assertEquals(q.hashCode(), q1.hashCode()); FunctionScoreQuery diffCombineFunc = new FunctionScoreQuery(new TermQuery(new Term("foo", "bar")), function, combineFunction == CombineFunction.AVG ? CombineFunction.MAX : CombineFunction.AVG, minScore, maxBoost); FunctionScoreQuery diffQuery = new FunctionScoreQuery(new TermQuery(new Term("foo", "baz")), function, combineFunction, minScore, maxBoost); FunctionScoreQuery diffMaxBoost = new FunctionScoreQuery(new TermQuery(new Term("foo", "bar")), function, combineFunction, minScore, maxBoost == 1.0f ? 0.9f : 1.0f); FunctionScoreQuery diffMinScore = new FunctionScoreQuery(new TermQuery(new Term("foo", "bar")), function, combineFunction, minScore == null ? 0.9f : null, maxBoost); FilterScoreFunction otherFunc = new FilterScoreFunction(new TermQuery(new Term("filter", "other_query")), scoreFunction); FunctionScoreQuery diffFunc = new FunctionScoreQuery(new TermQuery(new Term("foo", "bar")), randomFrom(ScoreMode.values()), randomBoolean() ? new ScoreFunction[] { function, otherFunc } : new ScoreFunction[] { otherFunc }, combineFunction, minScore, maxBoost); FunctionScoreQuery[] queries = new FunctionScoreQuery[] { diffQuery, diffMaxBoost, diffMinScore, diffFunc, q, diffCombineFunc }; final int numIters = randomIntBetween(20, 100); for (int i = 0; i < numIters; i++) { FunctionScoreQuery left = randomFrom(queries); FunctionScoreQuery right = randomFrom(queries); if (left == right) { assertEquals(left, right); assertEquals(left.hashCode(), right.hashCode()); } else { assertNotEquals(left + " == " + right, left, right); } } } public void testExplanationAndScoreEqualsEvenIfNoFunctionMatches() throws IOException { IndexSearcher localSearcher = newSearcher(reader); ScoreMode scoreMode = randomFrom(new ScoreMode[]{ScoreMode.SUM, ScoreMode.AVG, ScoreMode.FIRST, ScoreMode.MIN, ScoreMode.MAX, ScoreMode.MULTIPLY}); CombineFunction combineFunction = randomFrom(new CombineFunction[]{CombineFunction.SUM, CombineFunction.AVG, CombineFunction.MIN, CombineFunction.MAX, CombineFunction.MULTIPLY, CombineFunction.REPLACE}); // check for document that has no macthing function FunctionScoreQuery query = new FunctionScoreQuery(new TermQuery(new Term(FIELD, "out")), new FilterScoreFunction(new TermQuery(new Term("_uid", "2")), new WeightFactorFunction(10)), combineFunction, Float.NEGATIVE_INFINITY, Float.MAX_VALUE); TopDocs searchResult = localSearcher.search(query, 1); Explanation explanation = localSearcher.explain(query, searchResult.scoreDocs[0].doc); assertThat(searchResult.scoreDocs[0].score, equalTo(explanation.getValue())); // check for document that has a matching function query = new FunctionScoreQuery(new TermQuery(new Term(FIELD, "out")), new FilterScoreFunction(new TermQuery(new Term("_uid", "1")), new WeightFactorFunction(10)), combineFunction, Float.NEGATIVE_INFINITY, Float.MAX_VALUE); searchResult = localSearcher.search(query, 1); explanation = localSearcher.explain(query, searchResult.scoreDocs[0].doc); assertThat(searchResult.scoreDocs[0].score, equalTo(explanation.getValue())); } public void testWeightFactorNeedsScore() { for (boolean needsScore : new boolean[] {true, false}) { WeightFactorFunction function = new WeightFactorFunction(10.0f, new ScoreFunction(CombineFunction.REPLACE) { @Override public LeafScoreFunction getLeafScoreFunction(LeafReaderContext ctx) throws IOException { return null; } @Override public boolean needsScores() { return needsScore; } @Override protected boolean doEquals(ScoreFunction other) { return false; } @Override protected int doHashCode() { return 0; } }); assertEquals(needsScore, function.needsScores()); } } private static class ConstantScoreFunction extends ScoreFunction { final double value; protected ConstantScoreFunction(double value) { super(CombineFunction.REPLACE); this.value = value; } @Override public LeafScoreFunction getLeafScoreFunction(LeafReaderContext ctx) throws IOException { return new LeafScoreFunction() { @Override public double score(int docId, float subQueryScore) throws IOException { return value; } @Override public Explanation explainScore(int docId, Explanation subQueryScore) throws IOException { return null; } }; } @Override public boolean needsScores() { return false; } @Override protected boolean doEquals(ScoreFunction other) { return false; } @Override protected int doHashCode() { return 0; } } public void testWithInvalidScores() { IndexSearcher localSearcher = new IndexSearcher(reader); FunctionScoreQuery query1 = new FunctionScoreQuery(new TermQuery(new Term(FIELD, "out")), new ConstantScoreFunction(Float.NaN), CombineFunction.REPLACE, null, Float.POSITIVE_INFINITY); ElasticsearchException exc = expectThrows(ElasticsearchException.class, () -> localSearcher.search(query1, 1)); assertThat(exc.getMessage(), containsString("function score query returned an invalid score: " + Float.NaN)); FunctionScoreQuery query2 = new FunctionScoreQuery(new TermQuery(new Term(FIELD, "out")), new ConstantScoreFunction(Float.NEGATIVE_INFINITY), CombineFunction.REPLACE, null, Float.POSITIVE_INFINITY); exc = expectThrows(ElasticsearchException.class, () -> localSearcher.search(query2, 1)); assertThat(exc.getMessage(), containsString("function score query returned an invalid score: " + Float.NEGATIVE_INFINITY)); } public void testWarningOnNegativeScores() throws IOException { IndexSearcher localSearcher = new IndexSearcher(reader); TermQuery termQuery = new TermQuery(new Term(FIELD, "out")); // test that field_value_factor function issues a warning on negative scores FieldValueFactorFunction.Modifier modifier = FieldValueFactorFunction.Modifier.NONE; final ScoreFunction fvfFunction = new FieldValueFactorFunction(FIELD, -10, modifier, 1.0, new IndexNumericFieldDataStub()); FunctionScoreQuery fsQuery = new FunctionScoreQuery(termQuery, fvfFunction, CombineFunction.REPLACE, null, Float.POSITIVE_INFINITY); localSearcher.search(fsQuery, 1); assertWarnings("Negative scores for field value function are deprecated," + " and will throw an error in the next major version. Got: [-10.0] for field value: [1.0]"); } private static class DummyScoreFunction extends ScoreFunction { protected DummyScoreFunction(CombineFunction scoreCombiner) { super(scoreCombiner); } @Override public LeafScoreFunction getLeafScoreFunction(LeafReaderContext ctx) throws IOException { return null; } @Override public boolean needsScores() { return false; } @Override protected boolean doEquals(ScoreFunction other) { return other == this; } @Override protected int doHashCode() { return 0; }; } }
package org.lwjgl.util.generator; /** * Use this annotation on extensions with deprecated functionality. * Functions in such extensions marked with this annotation will not be loaded in a forward compatible context. * * @author spasi <spasi@users.sourceforge.net> */ import java.lang.annotation.ElementType; import java.lang.annotation.Target; @Target({ ElementType.TYPE, ElementType.METHOD }) public @interface DeprecatedGL { }
"""Tests for the ipdoctest machinery itself. Note: in a file named test_X, functions whose only test is their docstring (as a doctest) and which have no test functionality of their own, should be called 'doctest_foo' instead of 'test_foo', otherwise they get double-counted (the empty function call is counted as a test, which just inflates tests numbers artificially). """ def doctest_simple(): """ipdoctest must handle simple inputs In [1]: 1 Out[1]: 1 In [2]: print 1 1 """ def doctest_run_builtins(): """Check that %run doesn't damage __builtins__ via a doctest. This is similar to the test_run_builtins, but I want *both* forms of the test to catch any possible glitches in our testing machinery, since that modifies %run somewhat. So for this, we have both a normal test (below) and a doctest (this one). In [1]: import tempfile In [3]: f = tempfile.NamedTemporaryFile() In [4]: f.write('pass\\n') In [5]: f.flush() In [7]: %run $f.name """ def doctest_multiline1(): """The ipdoctest machinery must handle multiline examples gracefully. In [2]: for i in range(10): ...: print i, ...: 0 1 2 3 4 5 6 7 8 9 """ def doctest_multiline2(): """Multiline examples that define functions and print output. In [7]: def f(x): ...: return x+1 ...: In [8]: f(1) Out[8]: 2 In [9]: def g(x): ...: print 'x is:',x ...: In [10]: g(1) x is: 1 In [11]: g('hello') x is: hello """ def doctest_multiline3(): """Multiline examples with blank lines. In [12]: def h(x): ....: if x>1: ....: return x**2 ....: # To leave a blank line in the input, you must mark it ....: # with a comment character: ....: # ....: # otherwise the doctest parser gets confused. ....: else: ....: return -1 ....: In [13]: h(5) Out[13]: 25 In [14]: h(1) Out[14]: -1 In [15]: h(0) Out[15]: -1 """
using System; using System.Security.Cryptography.X509Certificates; namespace Internal.Cryptography.Pal { internal interface IStorePal : IDisposable { byte[] Export(X509ContentType contentType, string password); void CopyTo(X509Certificate2Collection collection); void Add(ICertificatePal cert); void Remove(ICertificatePal cert); } }
 // This file contains style definitions that can be used by CKEditor plugins. // // The most common use for it is the "stylescombo" plugin, which shows a combo // in the editor toolbar, containing all styles. Other plugins instead, like // the div plugin, use a subset of the styles on their feature. // // If you don't have plugins that depend on this file, you can simply ignore it. // Otherwise it is strongly recommended to customize this file to match your // website requirements and design properly. CKEDITOR.stylesSet.add( 'default', [ /* Block Styles */ // These styles are already available in the "Format" combo ("format" plugin), // so they are not needed here by default. You may enable them to avoid // placing the "Format" combo in the toolbar, maintaining the same features. /* { name: 'Paragraph', element: 'p' }, { name: 'Heading 1', element: 'h1' }, { name: 'Heading 2', element: 'h2' }, { name: 'Heading 3', element: 'h3' }, { name: 'Heading 4', element: 'h4' }, { name: 'Heading 5', element: 'h5' }, { name: 'Heading 6', element: 'h6' }, { name: 'Preformatted Text',element: 'pre' }, { name: 'Address', element: 'address' }, */ { name: 'Italic Title', element: 'h2', styles: { 'font-style': 'italic' } }, { name: 'Subtitle', element: 'h3', styles: { 'color': '#aaa', 'font-style': 'italic' } }, { name: 'Special Container', element: 'div', styles: { padding: '5px 10px', background: '#eee', border: '1px solid #ccc' } }, /* Inline Styles */ // These are core styles available as toolbar buttons. You may opt enabling // some of them in the Styles combo, removing them from the toolbar. // (This requires the "stylescombo" plugin) /* { name: 'Strong', element: 'strong', overrides: 'b' }, { name: 'Emphasis', element: 'em' , overrides: 'i' }, { name: 'Underline', element: 'u' }, { name: 'Strikethrough', element: 'strike' }, { name: 'Subscript', element: 'sub' }, { name: 'Superscript', element: 'sup' }, */ { name: 'Marker: Yellow', element: 'span', styles: { 'background-color': 'Yellow' } }, { name: 'Marker: Green', element: 'span', styles: { 'background-color': 'Lime' } }, { name: 'Big', element: 'big' }, { name: 'Small', element: 'small' }, { name: 'Typewriter', element: 'tt' }, { name: 'Computer Code', element: 'code' }, { name: 'Keyboard Phrase', element: 'kbd' }, { name: 'Sample Text', element: 'samp' }, { name: 'Variable', element: 'var' }, { name: 'Deleted Text', element: 'del' }, { name: 'Inserted Text', element: 'ins' }, { name: 'Cited Work', element: 'cite' }, { name: 'Inline Quotation', element: 'q' }, { name: 'Language: RTL', element: 'span', attributes: { 'dir': 'rtl' } }, { name: 'Language: LTR', element: 'span', attributes: { 'dir': 'ltr' } }, /* Object Styles */ { name: 'Styled image (left)', element: 'img', attributes: { 'class': 'left' } }, { name: 'Styled image (right)', element: 'img', attributes: { 'class': 'right' } }, { name: 'Compact table', element: 'table', attributes: { cellpadding: '5', cellspacing: '0', border: '1', bordercolor: '#ccc' }, styles: { 'border-collapse': 'collapse' } }, { name: 'Borderless Table', element: 'table', styles: { 'border-style': 'hidden', 'background-color': '#E6E6FA' } }, { name: 'Square Bulleted List', element: 'ul', styles: { 'list-style-type': 'square' } } ]);
<?php require_once dirname(__FILE__) . '/../../../bootstrap.php'; class Elastica_Query_BoolTest extends PHPUnit_Framework_TestCase { public function testToArray() { $query = new Elastica_Query_Bool(); $idsQuery1 = new Elastica_Query_Ids(); $idsQuery1->setIds(1); $idsQuery2 = new Elastica_Query_Ids(); $idsQuery2->setIds(2); $idsQuery3 = new Elastica_Query_Ids(); $idsQuery3->setIds(3); $boost = 1.2; $minMatch = 2; $query->setBoost($boost); $query->setMinimumNumberShouldMatch($minMatch); $query->addMust($idsQuery1); $query->addMustNot($idsQuery2); $query->addShould($idsQuery3->toArray()); $expectedArray = array( 'bool' => array( 'must' => array($idsQuery1->toArray()), 'should' => array($idsQuery3->toArray()), 'minimum_number_should_match' => $minMatch, 'must_not' => array($idsQuery2->toArray()), 'boost' => $boost, ) ); $this->assertEquals($expectedArray, $query->toArray()); } /** * Test to resolve the following issue * * https://groups.google.com/forum/?fromgroups#!topic/elastica-php-client/zK_W_hClfvU */ public function testToArrayStructure() { $boolQuery = new Elastica_Query_Bool(); $term1 = new Elastica_Query_Term(); $term1->setParam('interests', 84); $term2 = new Elastica_Query_Term(); $term2->setParam('interests', 92); $boolQuery->addShould($term1)->addShould($term2); $jsonString = '{"bool":{"should":[{"term":{"interests":84}},{"term":{"interests":92}}]}}'; $this->assertEquals($jsonString, json_encode($boolQuery->toArray())); } public function testSearch() { $client = new Elastica_Client(); $index = new Elastica_Index($client, 'test'); $index->create(array(), true); $type = new Elastica_Type($index, 'helloworld'); $doc = new Elastica_Document(1, array('id' => 1, 'email' => 'hans@test.com', 'username' => 'hans', 'test' => array('2', '3', '5'))); $type->addDocument($doc); $doc = new Elastica_Document(2, array('id' => 2, 'email' => 'emil@test.com', 'username' => 'emil', 'test' => array('1', '3', '6'))); $type->addDocument($doc); $doc = new Elastica_Document(3, array('id' => 3, 'email' => 'ruth@test.com', 'username' => 'ruth', 'test' => array('2', '3', '7'))); $type->addDocument($doc); // Refresh index $index->refresh(); $boolQuery = new Elastica_Query_Bool(); $termQuery1 = new Elastica_Query_Term(array('test' => '2')); $boolQuery->addMust($termQuery1); $resultSet = $type->search($boolQuery); $this->assertEquals(2, $resultSet->count()); $termQuery2 = new Elastica_Query_Term(array('test' => '5')); $boolQuery->addMust($termQuery2); $resultSet = $type->search($boolQuery); $this->assertEquals(1, $resultSet->count()); $termQuery3 = new Elastica_Query_Term(array('username' => 'hans')); $boolQuery->addMust($termQuery3); $resultSet = $type->search($boolQuery); $this->assertEquals(1, $resultSet->count()); $termQuery4 = new Elastica_Query_Term(array('username' => 'emil')); $boolQuery->addMust($termQuery4); $resultSet = $type->search($boolQuery); $this->assertEquals(0, $resultSet->count()); } }
<?php /** * Import WordPress Administration Screen * * @package WordPress * @subpackage Administration */ define('WP_LOAD_IMPORTERS', true); /** Load WordPress Bootstrap */ require_once( dirname( __FILE__ ) . '/admin.php' ); if ( !current_user_can('import') ) wp_die(__('You do not have sufficient permissions to import content in this site.')); $title = __('Import'); get_current_screen()->add_help_tab( array( 'id' => 'overview', 'title' => __('Overview'), 'content' => '<p>' . __('This screen lists links to plugins to import data from blogging/content management platforms. Choose the platform you want to import from, and click Install Now when you are prompted in the popup window. If your platform is not listed, click the link to search the plugin directory for other importer plugins to see if there is one for your platform.') . '</p>' . '<p>' . __('In previous versions of WordPress, all importers were built-in. They have been turned into plugins since most people only use them once or infrequently.') . '</p>', ) ); get_current_screen()->set_help_sidebar( '<p><strong>' . __('For more information:') . '</strong></p>' . '<p>' . __('<a href="https://codex.wordpress.org/Tools_Import_Screen" target="_blank">Documentation on Import</a>') . '</p>' . '<p>' . __('<a href="https://wordpress.org/support/" target="_blank">Support Forums</a>') . '</p>' ); if ( current_user_can( 'install_plugins' ) ) $popular_importers = wp_get_popular_importers(); else $popular_importers = array(); // Detect and redirect invalid importers like 'movabletype', which is registered as 'mt' if ( ! empty( $_GET['invalid'] ) && isset( $popular_importers[ $_GET['invalid'] ] ) ) { $importer_id = $popular_importers[ $_GET['invalid'] ]['importer-id']; if ( $importer_id != $_GET['invalid'] ) { // Prevent redirect loops. wp_redirect( admin_url( 'admin.php?import=' . $importer_id ) ); exit; } unset( $importer_id ); } add_thickbox(); wp_enqueue_script( 'plugin-install' ); require_once( ABSPATH . 'wp-admin/admin-header.php' ); $parent_file = 'tools.php'; ?> <div class="wrap"> <h1><?php echo esc_html( $title ); ?></h1> <?php if ( ! empty( $_GET['invalid'] ) ) : ?> <div class="error"><p><strong><?php _e('ERROR:')?></strong> <?php printf( __('The <strong>%s</strong> importer is invalid or is not installed.'), esc_html( $_GET['invalid'] ) ); ?></p></div> <?php endif; ?> <p><?php _e('If you have posts or comments in another system, WordPress can import those into this site. To get started, choose a system to import from below:'); ?></p> <?php $importers = get_importers(); // If a popular importer is not registered, create a dummy registration that links to the plugin installer. foreach ( $popular_importers as $pop_importer => $pop_data ) { if ( isset( $importers[ $pop_importer ] ) ) continue; if ( isset( $importers[ $pop_data['importer-id'] ] ) ) continue; $importers[ $pop_data['importer-id'] ] = array( $pop_data['name'], $pop_data['description'], 'install' => $pop_data['plugin-slug'] ); } if ( empty( $importers ) ) { echo '<p>' . __('No importers are available.') . '</p>'; // TODO: make more helpful } else { uasort( $importers, '_usort_by_first_member' ); ?> <table class="widefat importers striped"> <?php foreach ($importers as $importer_id => $data) { $action = ''; if ( isset( $data['install'] ) ) { $plugin_slug = $data['install']; if ( file_exists( WP_PLUGIN_DIR . '/' . $plugin_slug ) ) { // Looks like Importer is installed, But not active $plugins = get_plugins( '/' . $plugin_slug ); if ( !empty($plugins) ) { $keys = array_keys($plugins); $plugin_file = $plugin_slug . '/' . $keys[0]; $action = '<a href="' . esc_url(wp_nonce_url(admin_url('plugins.php?action=activate&plugin=' . $plugin_file . '&from=import'), 'activate-plugin_' . $plugin_file)) . '"title="' . esc_attr__('Activate importer') . '"">' . $data[0] . '</a>'; } } if ( empty($action) ) { if ( is_main_site() ) { $action = '<a href="' . esc_url( network_admin_url( 'plugin-install.php?tab=plugin-information&plugin=' . $plugin_slug . '&from=import&TB_iframe=true&width=600&height=550' ) ) . '" class="thickbox" title="' . esc_attr__('Install importer') . '">' . $data[0] . '</a>'; } else { $action = $data[0]; $data[1] = sprintf( __( 'This importer is not installed. Please install importers from <a href="%s">the main site</a>.' ), get_admin_url( $current_site->blog_id, 'import.php' ) ); } } } else { $action = "<a href='" . esc_url( "admin.php?import=$importer_id" ) . "' title='" . esc_attr( wptexturize( strip_tags( $data[1] ) ) ) ."'>{$data[0]}</a>"; } echo " <tr> <td class='import-system row-title'>$action</td> <td class='desc'>{$data[1]}</td> </tr>"; } ?> </table> <?php } if ( current_user_can('install_plugins') ) echo '<p>' . sprintf( __('If the importer you need is not listed, <a href="%s">search the plugin directory</a> to see if an importer is available.'), esc_url( network_admin_url( 'plugin-install.php?tab=search&type=tag&s=importer' ) ) ) . '</p>'; ?> </div> <?php include( ABSPATH . 'wp-admin/admin-footer.php' );
import { tryInvoke } from 'ember-metal/utils'; var obj; QUnit.module("Ember.tryInvoke", { setup: function() { obj = { aMethodThatExists: function() { return true; }, aMethodThatTakesArguments: function(arg1, arg2) { return arg1 === arg2; } }; }, teardown: function() { obj = undefined; } }); test("should return undefined when the object doesn't exist", function() { equal(tryInvoke(undefined, 'aMethodThatDoesNotExist'), undefined); }); test("should return undefined when asked to perform a method that doesn't exist on the object", function() { equal(tryInvoke(obj, 'aMethodThatDoesNotExist'), undefined); }); test("should return what the method returns when asked to perform a method that exists on the object", function() { equal(tryInvoke(obj, 'aMethodThatExists'), true); }); test("should return what the method returns when asked to perform a method that takes arguments and exists on the object", function() { equal(tryInvoke(obj, 'aMethodThatTakesArguments', [true, true]), true); });
package org.pentaho.di.trans.steps.csvinput; import java.nio.charset.StandardCharsets; import org.junit.AfterClass; import org.junit.Assert; import org.junit.ClassRule; import org.mockito.Matchers; import org.mockito.Mockito; import org.junit.BeforeClass; import org.junit.Test; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.logging.LoggingObjectInterface; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.junit.rules.RestorePDIEngineEnvironment; import org.pentaho.di.trans.step.RowAdapter; import org.pentaho.di.trans.steps.mock.StepMockHelper; import org.pentaho.di.trans.steps.textfileinput.TextFileInputField; /** * Tests for unicode support in CsvInput step * * @author Pavel Sakun * @see CsvInput */ public class CsvInputUnicodeTest extends CsvInputUnitTestBase { @ClassRule public static RestorePDIEngineEnvironment env = new RestorePDIEngineEnvironment(); private static final String UTF8 = "UTF-8"; private static final String UTF16LE = "UTF-16LE"; private static final String UTF16LEBOM = "x-UTF-16LE-BOM"; private static final String UTF16BE = "UTF-16BE"; private static final String ONE_CHAR_DELIM = "\t"; private static final String MULTI_CHAR_DELIM = "|||"; private static final String TEXT = "Header1%1$sHeader2\nValue%1$sValue\nValue%1$sValue\n"; private static final String TEXTHEADER = "Header1%1$sHeader2\n"; private static final String TEXTBODY = "Value%1$sValue\nValue%1$sValue\n"; private static final String TEXT_WITH_ENCLOSURES = "Header1%1$sHeader2\n\"Value\"%1$s\"Value\"\n\"Value\"%1$s\"Value\"\n"; private static final String TEST_DATA = String.format( TEXT, ONE_CHAR_DELIM ); private static final String TEST_DATA1 = String.format( TEXT, MULTI_CHAR_DELIM ); private static final String TEST_DATA2 = String.format( TEXT_WITH_ENCLOSURES, ONE_CHAR_DELIM ); private static final String TEST_DATA3 = String.format( TEXT_WITH_ENCLOSURES, MULTI_CHAR_DELIM ); private static final byte[] UTF8_BOM = { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF }; private static final String TEST_DATA_UTF8_BOM = String.format( new String( UTF8_BOM, StandardCharsets.UTF_8 ) + TEXT, ONE_CHAR_DELIM ); private static final String TEST_DATA_NOHEADER_UTF8_BOM = String.format( new String( UTF8_BOM, StandardCharsets.UTF_8 ) + TEXTBODY, ONE_CHAR_DELIM ); private static final byte[] UTF16LE_BOM = { (byte) 0xFF, (byte) 0xFE }; private static final String TEST_DATA_UTF16LE_BOM = String.format( new String( UTF16LE_BOM, StandardCharsets.UTF_16LE ) + TEST_DATA2, ONE_CHAR_DELIM ); private static final byte[] UTF16BE_BOM = { (byte) 0xFE, (byte) 0xFF }; private static final String TEST_DATA_UTF16BE_BOM = String.format( new String( UTF16BE_BOM, StandardCharsets.UTF_16BE ) + TEST_DATA2, ONE_CHAR_DELIM ); private static StepMockHelper<?, ?> stepMockHelper; @BeforeClass public static void setUp() throws KettleException { stepMockHelper = new StepMockHelper<CsvInputMeta, CsvInputData>( "CsvInputTest", CsvInputMeta.class, CsvInputData.class ); Mockito.when( stepMockHelper.logChannelInterfaceFactory.create( Matchers.any(), Matchers.any( LoggingObjectInterface.class ) ) ) .thenReturn( stepMockHelper.logChannelInterface ); Mockito.when( stepMockHelper.trans.isRunning() ).thenReturn( true ); } @AfterClass public static void cleanUp() { stepMockHelper.cleanUp(); } @Test public void testUTF16LE() throws Exception { doTest( UTF16LE, UTF16LE, TEST_DATA, ONE_CHAR_DELIM, true ); } @Test public void testUTF16BE() throws Exception { doTest( UTF16BE, UTF16BE, TEST_DATA, ONE_CHAR_DELIM, true ); } @Test public void testUTF16BE_multiDelim() throws Exception { doTest( UTF16BE, UTF16BE, TEST_DATA1, MULTI_CHAR_DELIM, true ); } @Test public void testUTF16LEBOM() throws Exception { doTest( UTF16LEBOM, UTF16LE, TEST_DATA, ONE_CHAR_DELIM, true ); } @Test public void testUTF8() throws Exception { doTest( UTF8, UTF8, TEST_DATA, ONE_CHAR_DELIM, true ); } @Test public void testUTF8_multiDelim() throws Exception { doTest( UTF8, UTF8, TEST_DATA1, MULTI_CHAR_DELIM, true ); } @Test public void testUTF8_headerWithBOM() throws Exception { doTest( UTF8, UTF8, TEST_DATA_UTF8_BOM, ONE_CHAR_DELIM, true ); } @Test public void testUTF8_withoutHeaderWithBOM() throws Exception { doTest( UTF8, UTF8, TEST_DATA_NOHEADER_UTF8_BOM, ONE_CHAR_DELIM, false ); } @Test public void testUTF16LEDataWithEnclosures() throws Exception { doTest( UTF16LE, UTF16LE, TEST_DATA2, ONE_CHAR_DELIM, true ); } @Test public void testUTF16LE_headerWithBOM() throws Exception { doTest( UTF16LE, UTF16LE, TEST_DATA_UTF16LE_BOM, ONE_CHAR_DELIM, true ); } @Test public void testUTF16BEDataWithEnclosures() throws Exception { doTest( UTF16BE, UTF16BE, TEST_DATA2, ONE_CHAR_DELIM, true ); } @Test public void testUTF16BE_headerWithBOM() throws Exception { doTest( UTF16BE, UTF16BE, TEST_DATA_UTF16BE_BOM, ONE_CHAR_DELIM, true ); } @Test public void testUTF16LEBOMDataWithEnclosures() throws Exception { doTest( UTF16LEBOM, UTF16LE, TEST_DATA2, ONE_CHAR_DELIM, true ); } @Test public void testUTF16BE_multiDelim_DataWithEnclosures() throws Exception { doTest( UTF16BE, UTF16BE, TEST_DATA3, MULTI_CHAR_DELIM, true ); } @Test public void testUTF16LE_multiDelim_DataWithEnclosures() throws Exception { doTest( UTF16LE, UTF16LE, TEST_DATA3, MULTI_CHAR_DELIM, true ); } @Test public void testUTF8_multiDelim_DataWithEnclosures() throws Exception { doTest( UTF8, UTF8, TEST_DATA3, MULTI_CHAR_DELIM, true ); } private void doTest( final String fileEncoding, final String stepEncoding, final String testData, final String delimiter, final boolean useHeader ) throws Exception { String testFilePath = createTestFile( fileEncoding, testData ).getAbsolutePath(); CsvInputMeta meta = createStepMeta( testFilePath, stepEncoding, delimiter, useHeader ); CsvInputData data = new CsvInputData(); CsvInput csvInput = new CsvInput( stepMockHelper.stepMeta, stepMockHelper.stepDataInterface, 0, stepMockHelper.transMeta, stepMockHelper.trans ); csvInput.init( meta, data ); csvInput.addRowListener( new RowAdapter() { @Override public void rowWrittenEvent( RowMetaInterface rowMeta, Object[] row ) throws KettleStepException { for ( int i = 0; i < rowMeta.size(); i++ ) { Assert.assertEquals( "Value", row[ i ] ); } } } ); boolean haveRowsToRead; do { haveRowsToRead = !csvInput.processRow( meta, data ); } while ( !haveRowsToRead ); csvInput.dispose( meta, data ); Assert.assertEquals( 2, csvInput.getLinesWritten() ); } private CsvInputMeta createStepMeta( final String testFilePath, final String encoding, final String delimiter, final boolean useHeader ) { final CsvInputMeta meta = new CsvInputMeta(); meta.setFilename( testFilePath ); meta.setDelimiter( delimiter ); meta.setEncoding( encoding ); meta.setEnclosure( "\"" ); meta.setBufferSize( "50000" ); meta.setInputFields( getInputFileFields() ); meta.setHeaderPresent( useHeader ); return meta; } private TextFileInputField[] getInputFileFields() { return createInputFileFields( "Header1", "Header2" ); } }
package ammonite.shell import ammonite.ops._ /** * Convenience entry-point useful to kick off a shell with */ object TestMain { val examplePredef = "shell/src/main/resources/ammonite/shell/example-predef-bare.sc" def main(args: Array[String]): Unit = { System.setProperty("ammonite-sbt-build", "true") ammonite.Main.main(args ++ Array( "--home", "target/tempAmmoniteHome", "--predef-file", examplePredef )) } }
public class ATest extends LightCodeInsightFixtureTestCase { public void testFixtureConfigureByFile() throws Exception { doFileTest("before", "after"); } private void doFileTest(@com.intellij.testFramework.TestDataFile String before, @com.intellij.testFramework.TestDataFile String after) { } }
using System.Linq; using System.Runtime.Versioning; namespace DotNetApis.Nuget { /// <summary> /// A normalized form of <see cref="FrameworkName"/>. /// </summary> public sealed class PlatformTarget { private readonly string _shortName; public PlatformTarget(FrameworkName framework) { // Do standard Nuget normalization. FrameworkName = framework.NormalizeFrameworkName(); // Further normalize PCL platforms by ordering their child platforms. if (FrameworkName.IsFrameworkPortable()) { var profile = string.Join("+", FrameworkName.Profile.Split('+').OrderBy(x => x)); if (FrameworkName.Profile != profile) FrameworkName = new FrameworkName(FrameworkName.Identifier, FrameworkName.Version, profile); } _shortName = FrameworkName.ShortFrameworkName().ToLowerInvariant(); } /// <summary> /// Gets the normalized framework name. /// </summary> public FrameworkName FrameworkName { get; } /// <summary> /// Returns the standard NuGet name for this target framework, lowercased. /// </summary> public override string ToString() => _shortName; /// <summary> /// Attempts to parse a string as a platform target. Returns <c>null</c> if the parsing fails. /// </summary> /// <param name="targetFramework">The string.</param> public static PlatformTarget TryParse(string targetFramework) { var result = NugetUtility.TryParseFrameworkName(targetFramework); return result == null ? null : new PlatformTarget(result); } } }
/** * @private */ Ext.define('Ext.device.device.Sencha', { extend: 'Ext.device.device.Abstract', constructor: function() { this.name = device.name; this.uuid = device.uuid; this.platform = device.platformName || Ext.os.name; this.scheme = Ext.device.Communicator.send({ command: 'OpenURL#getScheme', sync: true }) || false; Ext.device.Communicator.send({ command: 'OpenURL#watch', callbacks: { callback: function(scheme) { this.scheme = scheme || false; this.fireEvent('schemeupdate', this, this.scheme); } }, scope: this }); }, openURL: function(url) { Ext.device.Communicator.send({ command: 'OpenURL#open', url: url }); } });
/** * @file * Network buffer management * */ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels <adam@sics.se> * */ #include "lwip/opt.h" #if LWIP_NETCONN /* don't build if not configured for use in lwipopts.h */ #include "lwip/netbuf.h" #include "lwip/memp.h" #include <string.h> /** * Create (allocate) and initialize a new netbuf. * The netbuf doesn't yet contain a packet buffer! * * @return a pointer to a new netbuf * NULL on lack of memory */ struct netbuf *netbuf_new(void) { struct netbuf *buf; buf = (struct netbuf *)memp_malloc(MEMP_NETBUF); if (buf != NULL) { buf->p = NULL; buf->ptr = NULL; ip_addr_set_any(&buf->addr); buf->port = 0; #if LWIP_NETBUF_RECVINFO || LWIP_CHECKSUM_ON_COPY #if LWIP_CHECKSUM_ON_COPY buf->flags = 0; #endif /* LWIP_CHECKSUM_ON_COPY */ buf->toport_chksum = 0; #if LWIP_NETBUF_RECVINFO ip_addr_set_any(&buf->toaddr); #endif /* LWIP_NETBUF_RECVINFO */ #endif /* LWIP_NETBUF_RECVINFO || LWIP_CHECKSUM_ON_COPY */ return buf; } else { return NULL; } } /** * Deallocate a netbuf allocated by netbuf_new(). * * @param buf pointer to a netbuf allocated by netbuf_new() */ void netbuf_delete(struct netbuf *buf) { if (buf != NULL) { if (buf->p != NULL) { pbuf_free(buf->p); buf->p = buf->ptr = NULL; } memp_free(MEMP_NETBUF, buf); } } /** * Allocate memory for a packet buffer for a given netbuf. * * @param buf the netbuf for which to allocate a packet buffer * @param size the size of the packet buffer to allocate * @return pointer to the allocated memory * NULL if no memory could be allocated */ void * netbuf_alloc(struct netbuf *buf, u16_t size) { LWIP_ERROR("netbuf_alloc: invalid buf", (buf != NULL), return NULL;); /* Deallocate any previously allocated memory. */ if (buf->p != NULL) { pbuf_free(buf->p); } buf->p = pbuf_alloc(PBUF_TRANSPORT, size, PBUF_RAM); if (buf->p == NULL) { return NULL; } LWIP_ASSERT("check that first pbuf can hold size", (buf->p->len >= size)); buf->ptr = buf->p; return buf->p->payload; } /** * Free the packet buffer included in a netbuf * * @param buf pointer to the netbuf which contains the packet buffer to free */ void netbuf_free(struct netbuf *buf) { LWIP_ERROR("netbuf_free: invalid buf", (buf != NULL), return;); if (buf->p != NULL) { pbuf_free(buf->p); } buf->p = buf->ptr = NULL; } /** * Let a netbuf reference existing (non-volatile) data. * * @param buf netbuf which should reference the data * @param dataptr pointer to the data to reference * @param size size of the data * @return ERR_OK if data is referenced * ERR_MEM if data couldn't be referenced due to lack of memory */ err_t netbuf_ref(struct netbuf *buf, const void *dataptr, u16_t size) { LWIP_ERROR("netbuf_ref: invalid buf", (buf != NULL), return ERR_ARG;); if (buf->p != NULL) { pbuf_free(buf->p); } buf->p = pbuf_alloc(PBUF_TRANSPORT, 0, PBUF_REF); if (buf->p == NULL) { buf->ptr = NULL; return ERR_MEM; } buf->p->payload = (void*)dataptr; buf->p->len = buf->p->tot_len = size; buf->ptr = buf->p; return ERR_OK; } /** * Chain one netbuf to another (@see pbuf_chain) * * @param head the first netbuf * @param tail netbuf to chain after head, freed by this function, may not be reference after returning */ void netbuf_chain(struct netbuf *head, struct netbuf *tail) { LWIP_ERROR("netbuf_ref: invalid head", (head != NULL), return;); LWIP_ERROR("netbuf_chain: invalid tail", (tail != NULL), return;); pbuf_cat(head->p, tail->p); head->ptr = head->p; memp_free(MEMP_NETBUF, tail); } /** * Get the data pointer and length of the data inside a netbuf. * * @param buf netbuf to get the data from * @param dataptr pointer to a void pointer where to store the data pointer * @param len pointer to an u16_t where the length of the data is stored * @return ERR_OK if the information was retreived, * ERR_BUF on error. */ err_t netbuf_data(struct netbuf *buf, void **dataptr, u16_t *len) { LWIP_ERROR("netbuf_data: invalid buf", (buf != NULL), return ERR_ARG;); LWIP_ERROR("netbuf_data: invalid dataptr", (dataptr != NULL), return ERR_ARG;); LWIP_ERROR("netbuf_data: invalid len", (len != NULL), return ERR_ARG;); if (buf->ptr == NULL) { return ERR_BUF; } *dataptr = buf->ptr->payload; *len = buf->ptr->len; return ERR_OK; } /** * Move the current data pointer of a packet buffer contained in a netbuf * to the next part. * The packet buffer itself is not modified. * * @param buf the netbuf to modify * @return -1 if there is no next part * 1 if moved to the next part but now there is no next part * 0 if moved to the next part and there are still more parts */ s8_t netbuf_next(struct netbuf *buf) { LWIP_ERROR("netbuf_free: invalid buf", (buf != NULL), return -1;); if (buf->ptr->next == NULL) { return -1; } buf->ptr = buf->ptr->next; if (buf->ptr->next == NULL) { return 1; } return 0; } /** * Move the current data pointer of a packet buffer contained in a netbuf * to the beginning of the packet. * The packet buffer itself is not modified. * * @param buf the netbuf to modify */ void netbuf_first(struct netbuf *buf) { LWIP_ERROR("netbuf_free: invalid buf", (buf != NULL), return;); buf->ptr = buf->p; } #endif /* LWIP_NETCONN */
<h1>External Content</h1> <p> The <a href="app_architecture.html#security">Chrome Apps security model</a> disallows external content in iframes and the use of inline scripting and <code>eval()</code>. You can override these restrictions, but your external content must be isolated from the app. </p> <p> Isolated content cannot directly access the app's data or any of the APIs. Use cross-origin XMLHttpRequests and post-messaging to communicate between the event page and sandboxed content and indirectly access the APIs. </p> <p class="note"> <b>API Sample: </b> Want to play with the code? Check out the <a href="https://github.com/GoogleChrome/chrome-app-samples/tree/master/sandbox">sandbox</a> sample. </p> <h2 id="external">Referencing external resources</h2> <p> The <a href="contentSecurityPolicy.html">Content Security Policy</a> used by apps disallows the use of many kinds of remote URLs, so you can't directly reference external images, stylesheets, or fonts from an app page. Instead, you can use use cross-origin XMLHttpRequests to fetch these resources, and then serve them via <code>blob:</code> URLs. </p> <h3 id="manifest">Manifest requirement</h3> <p> To be able to do cross-origin XMLHttpRequests, you'll need to add a permission for the remote URL's host: </p> <pre data-filename="manifest.json"> "permissions": [ "...", "https://supersweetdomainbutnotcspfriendly.com/" ] </pre> <h3 id="cross-origin">Cross-origin XMLHttpRequest</h3> <p> Fetch the remote URL into the app and serve its contents as a <code>blob:</code> URL: </p> <pre> var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://supersweetdomainbutnotcspfriendly.com/image.png', true); xhr.responseType = 'blob'; xhr.onload = function(e) { var img = document.createElement('img'); img.src = window.webkitURL.createObjectURL(this.response); document.body.appendChild(img); }; xhr.send(); </pre> <p>You may want to <a href="offline_apps.html#saving-locally">save</a> these resources locally, so that they are available offline.</p> <h2 id="webview">Embed external web pages</h2> <p class="note"> <b>API Sample: </b> Want to play with the code? Check out the <a href="https://github.com/GoogleChrome/chrome-app-samples/tree/master/browser">browser</a> sample. </p> <p> The <code>webview</code> tag allows you to embed external web content in your app, for example, a web page. It replaces iframes that point to remote URLs, which are disabled inside Chrome Apps. Unlike iframes, the <code>webview</code> tag runs in a separate process. This means that an exploit inside of it will still be isolated and won't be able to gain elevated privileges. Further, since its storage (cookies, etc.) is isolated from the app, there is no way for the web content to access any of the app's data. </p> <h3 id="webview_element">Add webview element</h3> <p> Your <code>webview</code> element must include the URL to the source content and specify its dimensions. </p> <pre data-filename="browser.html"> &lt;webview src="http://news.google.com/" width="640" height="480">&lt;/webview> </pre> <h3 id="properties">Update properties</h3> <p> To dynamically change the <code>src</code>, <code>width</code> and <code>height</code> properties of a <code>webview</code> tag, you can either set those properties directly on the JavaScript object, or use the <code>setAttribute</code> DOM function. </p> <pre data-filename="browser.js"> document.querySelector('#mywebview').src = 'http://blog.chromium.org/'; // or document.querySelector('#mywebview').setAttribute( 'src', 'http://blog.chromium.org/'); </pre> <h2 id="sandboxing">Sandbox local content</h2> <p> Sandboxing allows specified pages to be served in a sandboxed, unique origin. These pages are then exempt from their Content Security Policy. Sandboxed pages can use iframes, inline scripting, and <code>eval()</code>. Check out the manifest field description for <a href="manifest/sandbox.html">sandbox</a>. </p> <p> It's a trade-off though: sandboxed pages can't use the chrome.* APIs. If you need to do things like <code>eval()</code>, go this route to be exempt from CSP, but you won't be able to use the cool new stuff. </p> <h3 id="inline_scripts">Use inline scripts in sandbox</h3> <p> Here's a sample sandboxed page which uses an inline script and <code>eval()</code>: </p> <pre data-filename="sandboxed.html"> &lt;html> &lt;body> &lt;h1>Woot&lt;/h1> &lt;script> document.write('I am an inline script.&lt;br>'); eval('document.write(\'I am an eval-ed inline script.\');'); &lt;/script> &lt;/body> &lt;/html> </pre> <h3 id="include_sandbox">Include sandbox in manifest</h3> <p> You need to include the <code>sandbox</code> field in the manifest and list the app pages to be served in a sandbox: </p> <pre data-filename="manifest.json"> "sandbox": { "pages": ["sandboxed.html"] } </pre> <h3 id="opening_sandbox">Opening a sandboxed page in a window</h3> <p> Just like any other app pages, you can create a window that the sandboxed page opens in. Here's a sample that creates two windows, one for the main app window that isn't sandboxed, and one for the sandboxed page: </p> <p class="warning"> NOTE: <a href="https://code.google.com/p/chromium/issues/detail?id=154662">issue 154662</a> is a bug when using sandbox pages to create windows. The effect is that an error "Uncaught TypeError: Cannot call method 'initializeAppWindow' of undefined" is output to the developer console and that the app.window.create call does not call the callback function with a window object. However, the sandbox page is created as a new window. </p> <pre data-filename="background.js"> chrome.app.runtime.onLaunched.addListener(function() { chrome.app.window.create('window.html', { 'bounds': { 'width': 400, 'height': 400, 'left': 0, 'top': 0 } }); chrome.app.window.create('sandboxed.html', { 'bounds': { 'width': 400, 'height': 400, 'left': 400, 'top': 0 } }); }); </pre> <h3 id="embedding_sandbox">Embedding a sandboxed page in an app page</h3> <p>Sandboxed pages can also be embedded within another app page using an <code>iframe</code>:</p> <pre data-filename="window.html"> &lt;!DOCTYPE html> &lt;html> &lt;head> &lt;/head> &lt;body> &lt;p>I am normal app window.&lt;/p> &lt;iframe src="sandboxed.html" width="300" height="200">&lt;/iframe> &lt;/body> &lt;/html> </pre> <h2 id="postMessage">Sending messages to sandboxed pages</h2> <p> There are two parts to sending a message: you need to post a message from the sender page/window, and listen for messages on the receiving page/window. </p> <h3 id="post_message">Post message</h3> <p> You can use <code>postMessage</code> to communicate between your app and sandboxed content. Here's a sample background script that posts a message to the sandboxed page it opens: </p> <pre data-filename="background.js"> var myWin = null; chrome.app.runtime.onLaunched.addListener(function() { chrome.app.window.create('sandboxed.html', { 'bounds': { 'width': 400, 'height': 400 } }, function(win) { myWin = win; myWin.contentWindow.postMessage('Just wanted to say hey.', '*'); }); }); </pre> <p> Generally speaking on the web, you want to specify the exact origin from where the message is sent. Chrome Apps have no access to the unique origin of sandboxed content, so you can only whitelist all origins as acceptable origins ('*'). On the receiving end, you generally want to check the origin; but since Chrome Apps content is contained, it isn't necessary. To find out more, see <a href="https://developer.mozilla.org/en/DOM/window.postMessage">window.postMessage</a>. </p> <h3 id="listen_message">Listen for message</h3> <p> Here's a sample message receiver that gets added to your sandboxed page: </p> <pre data-filename="sandboxed.html"> var messageHandler = function(e) { console.log('Background script says hello.', e.data); }; window.addEventListener('message', messageHandler); </pre> <p class="backtotop"><a href="#top">Back to top</a></p>
<?php class Twig_Node_Expression_Binary_FloorDiv extends Twig_Node_Expression_Binary { /** * Compiles the node to PHP. * * @param Twig_Compiler $compiler A Twig_Compiler instance */ public function compile(Twig_Compiler $compiler) { $compiler->raw('intval(floor('); parent::compile($compiler); $compiler->raw('))'); } public function operator(Twig_Compiler $compiler) { return $compiler->raw('/'); } }
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v12.0.2 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var component_1 = require("../../widgets/component"); var svgFactory_1 = require("../../svgFactory"); var utils_1 = require("../../utils"); var columnController_1 = require("../../columnController/columnController"); var gridOptionsWrapper_1 = require("../../gridOptionsWrapper"); var context_1 = require("../../context/context"); var touchListener_1 = require("../../widgets/touchListener"); var componentAnnotations_1 = require("../../widgets/componentAnnotations"); var originalColumnGroup_1 = require("../../entities/originalColumnGroup"); var svgFactory = svgFactory_1.SvgFactory.getInstance(); var HeaderGroupComp = (function (_super) { __extends(HeaderGroupComp, _super); function HeaderGroupComp() { return _super.call(this, HeaderGroupComp.TEMPLATE) || this; } HeaderGroupComp.prototype.init = function (params) { this.params = params; this.setupLabel(); this.addGroupExpandIcon(); if (this.params.columnGroup.isExpandable()) { this.setupExpandIcons(); } else { this.removeExpandIcons(); } }; HeaderGroupComp.prototype.setupExpandIcons = function () { this.addInIcon('columnGroupOpened', 'agOpened', svgFactory.createGroupExpandedIcon); this.addInIcon('columnGroupClosed', 'agClosed', svgFactory.createGroupContractedIcon); this.addTouchAndClickListeners(this.eCloseIcon); this.addTouchAndClickListeners(this.eOpenIcon); this.updateIconVisibilty(); this.addDestroyableEventListener(this.params.columnGroup.getOriginalColumnGroup(), originalColumnGroup_1.OriginalColumnGroup.EVENT_EXPANDED_CHANGED, this.updateIconVisibilty.bind(this)); }; HeaderGroupComp.prototype.addTouchAndClickListeners = function (eElement) { var _this = this; var expandAction = function () { var newExpandedValue = !_this.params.columnGroup.isExpanded(); _this.columnController.setColumnGroupOpened(_this.params.columnGroup, newExpandedValue); }; var touchListener = new touchListener_1.TouchListener(this.eCloseIcon); this.addDestroyableEventListener(touchListener, touchListener_1.TouchListener.EVENT_TAP, expandAction); this.addDestroyFunc(function () { return touchListener.destroy(); }); this.addDestroyableEventListener(eElement, 'click', expandAction); }; HeaderGroupComp.prototype.updateIconVisibilty = function () { var expanded = this.params.columnGroup.isExpanded(); utils_1.Utils.setVisible(this.eOpenIcon, !expanded); utils_1.Utils.setVisible(this.eCloseIcon, expanded); }; HeaderGroupComp.prototype.removeExpandIcons = function () { utils_1.Utils.setVisible(this.eOpenIcon, false); utils_1.Utils.setVisible(this.eCloseIcon, false); }; HeaderGroupComp.prototype.addInIcon = function (iconName, refName, defaultIconFactory) { var eIcon = utils_1.Utils.createIconNoSpan(iconName, this.gridOptionsWrapper, null, defaultIconFactory); this.getRefElement(refName).appendChild(eIcon); }; HeaderGroupComp.prototype.addGroupExpandIcon = function () { if (!this.params.columnGroup.isExpandable()) { utils_1.Utils.setVisible(this.eOpenIcon, false); utils_1.Utils.setVisible(this.eCloseIcon, false); return; } }; HeaderGroupComp.prototype.setupLabel = function () { // no renderer, default text render if (this.params.displayName && this.params.displayName !== '') { if (utils_1.Utils.isBrowserSafari()) { this.getGui().style.display = 'table-cell'; } var eInnerText = this.getRefElement('agLabel'); eInnerText.innerHTML = this.params.displayName; } }; HeaderGroupComp.TEMPLATE = "<div class=\"ag-header-group-cell-label\">" + "<span ref=\"agLabel\" class=\"ag-header-group-text\"></span>" + "<span ref=\"agOpened\" class=\"ag-header-icon ag-header-expand-icon ag-header-expand-icon-expanded\"></span>" + "<span ref=\"agClosed\" class=\"ag-header-icon ag-header-expand-icon ag-header-expand-icon-collapsed\"></span>" + "</div>"; __decorate([ context_1.Autowired('columnController'), __metadata("design:type", columnController_1.ColumnController) ], HeaderGroupComp.prototype, "columnController", void 0); __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper) ], HeaderGroupComp.prototype, "gridOptionsWrapper", void 0); __decorate([ componentAnnotations_1.RefSelector('agOpened'), __metadata("design:type", HTMLElement) ], HeaderGroupComp.prototype, "eOpenIcon", void 0); __decorate([ componentAnnotations_1.RefSelector('agClosed'), __metadata("design:type", HTMLElement) ], HeaderGroupComp.prototype, "eCloseIcon", void 0); return HeaderGroupComp; }(component_1.Component)); exports.HeaderGroupComp = HeaderGroupComp;
from boto.exception import BotoServerError class InvalidDeploymentIdException(BotoServerError): pass class InvalidDeploymentGroupNameException(BotoServerError): pass class DeploymentConfigAlreadyExistsException(BotoServerError): pass class InvalidRoleException(BotoServerError): pass class RoleRequiredException(BotoServerError): pass class DeploymentGroupAlreadyExistsException(BotoServerError): pass class DeploymentConfigLimitExceededException(BotoServerError): pass class InvalidNextTokenException(BotoServerError): pass class InvalidDeploymentConfigNameException(BotoServerError): pass class InvalidSortByException(BotoServerError): pass class InstanceDoesNotExistException(BotoServerError): pass class InvalidMinimumHealthyHostValueException(BotoServerError): pass class ApplicationLimitExceededException(BotoServerError): pass class ApplicationNameRequiredException(BotoServerError): pass class InvalidEC2TagException(BotoServerError): pass class DeploymentDoesNotExistException(BotoServerError): pass class DeploymentLimitExceededException(BotoServerError): pass class InvalidInstanceStatusException(BotoServerError): pass class RevisionRequiredException(BotoServerError): pass class InvalidBucketNameFilterException(BotoServerError): pass class DeploymentGroupLimitExceededException(BotoServerError): pass class DeploymentGroupDoesNotExistException(BotoServerError): pass class DeploymentConfigNameRequiredException(BotoServerError): pass class DeploymentAlreadyCompletedException(BotoServerError): pass class RevisionDoesNotExistException(BotoServerError): pass class DeploymentGroupNameRequiredException(BotoServerError): pass class DeploymentIdRequiredException(BotoServerError): pass class DeploymentConfigDoesNotExistException(BotoServerError): pass class BucketNameFilterRequiredException(BotoServerError): pass class InvalidTimeRangeException(BotoServerError): pass class ApplicationDoesNotExistException(BotoServerError): pass class InvalidRevisionException(BotoServerError): pass class InvalidSortOrderException(BotoServerError): pass class InvalidOperationException(BotoServerError): pass class InvalidAutoScalingGroupException(BotoServerError): pass class InvalidApplicationNameException(BotoServerError): pass class DescriptionTooLongException(BotoServerError): pass class ApplicationAlreadyExistsException(BotoServerError): pass class InvalidDeployedStateFilterException(BotoServerError): pass class DeploymentNotStartedException(BotoServerError): pass class DeploymentConfigInUseException(BotoServerError): pass class InstanceIdRequiredException(BotoServerError): pass class InvalidKeyPrefixFilterException(BotoServerError): pass class InvalidDeploymentStatusException(BotoServerError): pass
const test = require('tape'); const TheAwesomeBot = require('../TheAwesomeBot'); const token = process.env.DISCORD_TOKEN || require('../tokens.json').discord; // eslint-disable-line global-require test('connect & disconnect', (t) => { t.timeoutAfter(15000); t.ok(token, 'discord token should be set'); const bot = new TheAwesomeBot(token); t.false(bot.isReady, 'bot should not be ready'); bot.init(); // wait for it to be ready const si = setInterval(() => { if (bot.isReady) { bot.deinit().then(() => { clearInterval(si); t.end(); }); } }, 5000); });
#ifndef ERL_ASYNC_H__ #define ERL_ASYNC_H__ #define ERTS_MAX_NO_OF_ASYNC_THREADS 1024 extern int erts_async_max_threads; #define ERTS_ASYNC_THREAD_MIN_STACK_SIZE 16 /* Kilo words */ #define ERTS_ASYNC_THREAD_MAX_STACK_SIZE 8192 /* Kilo words */ extern int erts_async_thread_suggested_stack_size; #ifdef USE_THREADS #ifdef ERTS_SMP /* * With smp support we can choose to have, or not to * have an async ready queue. */ #define ERTS_USE_ASYNC_READY_Q 1 #endif #ifndef ERTS_SMP /* In non-smp case we *need* the async ready queue */ # undef ERTS_USE_ASYNC_READY_Q # define ERTS_USE_ASYNC_READY_Q 1 #endif #ifndef ERTS_USE_ASYNC_READY_Q # define ERTS_USE_ASYNC_READY_Q 0 #endif #if ERTS_USE_ASYNC_READY_Q int erts_check_async_ready(void *); int erts_async_ready_clean(void *, void *); void *erts_get_async_ready_queue(Uint sched_id); #define ERTS_ASYNC_READY_CLEAN 0 #define ERTS_ASYNC_READY_DIRTY 1 #ifdef ERTS_SMP #define ERTS_ASYNC_READY_NEED_THR_PRGR 2 #endif #endif /* ERTS_USE_ASYNC_READY_Q */ #endif /* USE_THREADS */ void erts_init_async(void); void erts_exit_flush_async(void); #endif /* ERL_ASYNC_H__ */
namespace base { // A simple thread abstraction that establishes a MessageLoop on a new thread. // The consumer uses the MessageLoop of the thread to cause code to execute on // the thread. When this object is destroyed the thread is terminated. All // pending tasks queued on the thread's message loop will run to completion // before the thread is terminated. // // WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread(). // // After the thread is stopped, the destruction sequence is: // // (1) Thread::CleanUp() // (2) MessageLoop::~MessageLoop // (3.b) MessageLoop::DestructionObserver::WillDestroyCurrentMessageLoop class BASE_EXPORT Thread : PlatformThread::Delegate { public: struct Options { Options() : message_loop_type(MessageLoop::TYPE_DEFAULT), stack_size(0) {} Options(MessageLoop::Type type, size_t size) : message_loop_type(type), stack_size(size) {} // Specifies the type of message loop that will be allocated on the thread. MessageLoop::Type message_loop_type; // Specifies the maximum stack size that the thread is allowed to use. // This does not necessarily correspond to the thread's initial stack size. // A value of 0 indicates that the default maximum should be used. size_t stack_size; }; // Constructor. // name is a display string to identify the thread. explicit Thread(const char* name); // Destroys the thread, stopping it if necessary. // // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or // guarantee Stop() is explicitly called before the subclass is destroyed). // This is required to avoid a data race between the destructor modifying the // vtable, and the thread's ThreadMain calling the virtual method Run(). It // also ensures that the CleanUp() virtual method is called on the subclass // before it is destructed. virtual ~Thread(); #if defined(OS_WIN) // Causes the thread to initialize COM. This must be called before calling // Start() or StartWithOptions(). If |use_mta| is false, the thread is also // started with a TYPE_UI message loop. It is an error to call // init_com_with_mta(false) and then StartWithOptions() with any message loop // type other than TYPE_UI. void init_com_with_mta(bool use_mta) { DCHECK(!started_); com_status_ = use_mta ? MTA : STA; } #endif // Starts the thread. Returns true if the thread was successfully started; // otherwise, returns false. Upon successful return, the message_loop() // getter will return non-null. // // Note: This function can't be called on Windows with the loader lock held; // i.e. during a DllMain, global object construction or destruction, atexit() // callback. bool Start(); // Starts the thread. Behaves exactly like Start in addition to allow to // override the default options. // // Note: This function can't be called on Windows with the loader lock held; // i.e. during a DllMain, global object construction or destruction, atexit() // callback. bool StartWithOptions(const Options& options); // Signals the thread to exit and returns once the thread has exited. After // this method returns, the Thread object is completely reset and may be used // as if it were newly constructed (i.e., Start may be called again). // // Stop may be called multiple times and is simply ignored if the thread is // already stopped. // // NOTE: If you are a consumer of Thread, it is not necessary to call this // before deleting your Thread objects, as the destructor will do it. // IF YOU ARE A SUBCLASS OF Thread, YOU MUST CALL THIS IN YOUR DESTRUCTOR. void Stop(); // Signals the thread to exit in the near future. // // WARNING: This function is not meant to be commonly used. Use at your own // risk. Calling this function will cause message_loop() to become invalid in // the near future. This function was created to workaround a specific // deadlock on Windows with printer worker thread. In any other case, Stop() // should be used. // // StopSoon should not be called multiple times as it is risky to do so. It // could cause a timing issue in message_loop() access. Call Stop() to reset // the thread object once it is known that the thread has quit. void StopSoon(); // Returns the message loop for this thread. Use the MessageLoop's // PostTask methods to execute code on the thread. This only returns // non-null after a successful call to Start. After Stop has been called, // this will return NULL. // // NOTE: You must not call this MessageLoop's Quit method directly. Use // the Thread's Stop method instead. // MessageLoop* message_loop() const { return message_loop_; } // Returns a MessageLoopProxy for this thread. Use the MessageLoopProxy's // PostTask methods to execute code on the thread. This only returns // non-NULL after a successful call to Start. After Stop has been called, // this will return NULL. Callers can hold on to this even after the thread // is gone. scoped_refptr<MessageLoopProxy> message_loop_proxy() const { return message_loop_ ? message_loop_->message_loop_proxy() : NULL; } // Returns the name of this thread (for display in debugger too). const std::string& thread_name() const { return name_; } // The native thread handle. PlatformThreadHandle thread_handle() { return thread_; } // The thread ID. PlatformThreadId thread_id() const { return thread_id_; } // Returns true if the thread has been started, and not yet stopped. bool IsRunning() const; // Sets the thread priority. The thread must already be started. void SetPriority(ThreadPriority priority); protected: // Called just prior to starting the message loop virtual void Init() {} // Called to start the message loop virtual void Run(MessageLoop* message_loop); // Called just after the message loop ends virtual void CleanUp() {} static void SetThreadWasQuitProperly(bool flag); static bool GetThreadWasQuitProperly(); void set_message_loop(MessageLoop* message_loop) { message_loop_ = message_loop; } private: #if defined(OS_WIN) enum ComStatus { NONE, STA, MTA, }; #endif // PlatformThread::Delegate methods: virtual void ThreadMain() OVERRIDE; #if defined(OS_WIN) // Whether this thread needs to initialize COM, and if so, in what mode. ComStatus com_status_; #endif // Whether we successfully started the thread. bool started_; // If true, we're in the middle of stopping, and shouldn't access // |message_loop_|. It may non-NULL and invalid. bool stopping_; // True while inside of Run(). bool running_; // Used to pass data to ThreadMain. struct StartupData; StartupData* startup_data_; // The thread's handle. PlatformThreadHandle thread_; // The thread's message loop. Valid only while the thread is alive. Set // by the created thread. MessageLoop* message_loop_; // Our thread's ID. PlatformThreadId thread_id_; // The name of the thread. Used for debugging purposes. std::string name_; friend void ThreadQuitHelper(); DISALLOW_COPY_AND_ASSIGN(Thread); }; } // namespace base #endif // BASE_THREADING_THREAD_H_
import smartbot.storage class Storage(smartbot.storage.Storage): def __init__(self): self.data = {} def get(self, key, default=None): return self.data.get(key, default) def setdefault(self, key, default=None): if key not in self.data: self[key] = default return self[key] def __getitem__(self, key): return self.data[key] def __setitem__(self, key, value): self.data[key] = value def __delitem__(self, key): del self.data[key]
 #include <aws/ecs/model/ListAttributesResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::ECS::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; ListAttributesResult::ListAttributesResult() { } ListAttributesResult::ListAttributesResult(const AmazonWebServiceResult<JsonValue>& result) { *this = result; } ListAttributesResult& ListAttributesResult::operator =(const AmazonWebServiceResult<JsonValue>& result) { const JsonValue& jsonValue = result.GetPayload(); if(jsonValue.ValueExists("attributes")) { Array<JsonValue> attributesJsonList = jsonValue.GetArray("attributes"); for(unsigned attributesIndex = 0; attributesIndex < attributesJsonList.GetLength(); ++attributesIndex) { m_attributes.push_back(attributesJsonList[attributesIndex].AsObject()); } } if(jsonValue.ValueExists("nextToken")) { m_nextToken = jsonValue.GetString("nextToken"); } return *this; }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace OpenSim.Region.Physics.Manager.Vehicle { /// <summary> /// Enum containing all the lsl vehicle rotation parameters ( http://wiki.secondlife.com/wiki/LlSetVehicleType ) /// /// Please note if you update this enum you should also update the validator below to include the new range(s) /// </summary> public enum RotationParams { VehicleReferenceFrame = 44, } /// <summary> /// This is kind of verbose for checking the validity of the enum, but it will be fast at runtime /// unlike Enum.IsDefined() ( see: http://stackoverflow.com/questions/13615/validate-enum-values ) /// </summary> public class RotationParamsValidator { public const int ROTATION_PARAMS_MIN = (int)RotationParams.VehicleReferenceFrame; public const int ROTATION_PARAMS_MAX = (int)RotationParams.VehicleReferenceFrame; public static bool IsValid(int value) { if (value < ROTATION_PARAMS_MIN) return false; if (value > ROTATION_PARAMS_MAX) return false; return true; } } }
Setting Up the Browser ======================= Protractor works with [Selenium WebDriver](http://docs.seleniumhq.org/docs/03_webdriver.jsp), a browser automation framework. Selenium WebDriver supports several browser implementations or [drivers](http://docs.seleniumhq.org/docs/03_webdriver.jsp#selenium-webdriver-s-drivers) which are discussed below. Browser Support --------------- Protractor support for a particular browser is tied to the capabilities available in the driver for that browser. Notably, Protractor requires the driver to implement asynchronous script execution. Protractor supports the two latest major versions of Chrome, Firefox, Safari, and IE. | Driver | Support | Known Issues | |------------------------|--------------|-----------------| |ChromeDriver |Yes | | |FirefoxDriver |Yes |[#480](https://github.com/angular/protractor/issues/480) clicking options doesn't update the model| |SafariDriver |Yes |[#481](https://github.com/angular/protractor/issues/481) minus key doesn't work, SafariDriver does not support modals, [#1051](https://github.com/angular/protractor/issues/1051) We see occasional page loading timeouts| |IEDriver |Yes |[#778](https://github.com/angular/protractor/issues/778), can be slow, [#1052](https://github.com/angular/protractor/issues/1052) often times out waiting for page load| |OperaDriver |No | | |ios-Driver |No | | |Appium - iOS/Safari |Yes* | drag and drop not supported (session/:sessionid/buttondown unimplemented) | |Appium - Android/Chrome |Yes* | | |Selendroid |Yes* | | * These drivers are not yet in the Protractor smoke tests. Configuring Browsers -------------------- In your Protractor config file (see [referenceConf.js](/docs/referenceConf.js)), all browser setup is done within the `capabilities` object. This object is passed directly to the WebDriver builder ([builder.js](https://code.google.com/p/selenium/source/browse/javascript/webdriver/builder.js)). See [DesiredCapabilities](https://code.google.com/p/selenium/wiki/DesiredCapabilities) for full information on which properties are available. Using Browsers Other Than Chrome -------------------------------- To use a browser other than Chrome, simply set a different browser name in the capabilities object. ```javascript capabilities: { 'browserName': 'firefox' } ``` You may need to install a separate binary to run another browser, such as IE or Android. For more information, see [SeleniumHQ Downloads](http://docs.seleniumhq.org/download/). Adding Chrome-Specific Options ------------------------------ Chrome options are nested in the `chromeOptions` object. A full list of options is at the [ChromeDriver](https://sites.google.com/a/chromium.org/chromedriver/capabilities) site. For example, to show an FPS counter in the upper right, your configuration would look like this: ```javascript capabilities: { 'browserName': 'chrome', 'chromeOptions': { 'args': ['show-fps-counter=true'] } }, ``` Testing Against Multiple Browsers --------------------------------- If you would like to test against multiple browsers, use the `multiCapabilities` configuration option. ```javascript multiCapabilities: [{ 'browserName': 'firefox' }, { 'browserName': 'chrome' }] ``` Protractor will run tests in parallel against each set of capabilities. Please note that if `multiCapabilities` is defined, the runner will ignore the `capabilities` configuration. Setting Up Protractor with Appium - Android/Chrome ------------------------------------- ###### Setup * Install Java SDK (>1.6) and configure JAVA_HOME (Important: make sure it's not pointing to JRE). * Follow http://spring.io/guides/gs/android/ to install and set up Android developer environment. Do not set up Android Virtual Device as instructed here. * From commandline, ```android avd``` and then install an AVD, taking note of the following: * Start with an ARM ABI * Enable hardware keyboard: ```hw.keyboard=yes``` * Enable hardware battery: ```hw.battery=yes``` * Use the Host GPU * Here's an example: Phone: ```shell > android list avd Available Android Virtual Devices: Name: LatestAndroid Device: Nexus 5 (Google) Path: /Users/hankduan/.android/avd/LatestAndroid.avd Target: Android 4.4.2 (API level 19) Tag/ABI: default/armeabi-v7a Skin: HVGA ``` Tablet: ```shell > android list avd Available Android Virtual Devices: Name: LatestTablet Device: Nexus 10 (Google) Path: /Users/hankduan/.android/avd/LatestTablet.avd Target: Android 4.4.2 (API level 19) Tag/ABI: default/armeabi-v7a Skin: WXGA800-7in ``` * Follow http://ant.apache.org/manual/index.html to install ant and set up the environment. * Follow http://maven.apache.org/download.cgi to install mvn (Maven) and set up the environment. * NOTE: Appium suggests installing Maven 3.0.5 (I haven't tried later versions, but 3.0.5 works for sure). * Install Appium using node ```npm install -g appium```. Make sure you don't install as sudo or else Appium will complain. * You can do this either if you installed node without sudo, or you can chown the global node_modules lib and bin directories. * Start emulator manually (at least the first time) and unlock screen. ```shell > emulator -avd LatestAndroid ``` * Your devices should show up under adb now: ```shell > adb devices List of devices attached emulator-5554 device ``` * If the AVD does not have chrome (and it probably won't if it just created), you need to install it: * You can get v34.0.1847.114 from http://www.apk4fun.com/apk/1192/ * Once you download the apk, install to your AVD as such: ```shell > adb install ~/Desktop/chrome-browser-google-34.0.1847.114-www.apk4fun.com.apk 2323 KB/s (30024100 bytes in 12.617s) Success ``` * If you check your AVD now, it should have Chrome. ###### Running Tests * Ensure app is running if testing local app (Skip if testing public website): ```shell > ./scripts/web-server.js Starting express web server in /workspace/protractor/testapp on port 8000 ``` * If your AVD isn't already started from the setup, start it now: ```shell > emulator -avd LatestAndroid ``` * Start Appium: ```shell > appium info: Welcome to Appium v1.0.0-beta.1 (REV 6fcf54391fb06bb5fb03dfcf1582c84a1d9838b6) info: Appium REST http interface listener started on 0.0.0.0:4723 info: socket.io started ``` *Note Appium listens to port 4723 instead of 4444* * Configure protractor: ```javascript exports.config = { seleniumAddress: 'http://localhost:4723/wd/hub', specs: ['basic/*_spec.js'], // Reference: https://github.com/appium/sample-code/blob/master/sample-code/examples/node/helpers/caps.js capabilities: { browserName: 'chrome', 'appium-version': '1.0', platformName: 'Android', platformVersion: '4.4.2', deviceName: 'Android Emulator', }, baseUrl: 'http://10.0.2.2:8000', // configuring wd in onPrepare // wdBridge helps to bridge wd driver with other selenium clients // See https://github.com/sebv/wd-bridge/blob/master/README.md onPrepare: function () { var wd = require('wd'), protractor = require('protractor'), wdBridge = require('wd-bridge')(protractor, wd); wdBridge.initFromProtractor(exports.config); } }; ``` *Note the following:* - baseUrl is 10.0.2.2 instead of localhost because it is used to access the localhost of the host machine in the android emulator - selenium address is using port 4723 Setting Up Protractor with Appium - iOS/Safari ------------------------------------- ###### Setup * Install Java SDK (>1.6) and configure JAVA_HOME (Important: make sure it's not pointing to JRE). * Follow http://ant.apache.org/manual/index.html to install ant and set up the environment. * Follow http://maven.apache.org/download.cgi to install mvn (Maven) and set up the environment. * NOTE: Appium suggests installing Maven 3.0.5 (I haven't tried later versions, but 3.0.5 works for sure). * Install Appium using node ```npm install -g appium```. Make sure you don't install as sudo or else Appium will complain. * You can do this either if you installed node without sudo, or you can chown the global node_modules lib and bin directories. * Run the following: `appium-doctor` and `authorize_ios` (sudo if necessary) * You need XCode >= 4.6.3, 5.1.1 recommended. Note, iOS8 (XCode 6) does not work off the shelf (see https://github.com/appium/appium/pull/3517) ###### Running Tests * Ensure app is running if testing local app (Skip if testing public website): ```shell > ./scripts/web-server.js Starting express web server in /workspace/protractor/testapp on port 8000 ``` * Start Appium: ```shell > appium info: Welcome to Appium v1.0.0-beta.1 (REV 6fcf54391fb06bb5fb03dfcf1582c84a1d9838b6) info: Appium REST http interface listener started on 0.0.0.0:4723 info: socket.io started ``` *Note: Appium listens to port 4723 instead of 4444.* * Configure protractor: iPhone: ```javascript exports.config = { seleniumAddress: 'http://localhost:4723/wd/hub', specs: [ 'basic/*_spec.js' ], // Reference: https://github.com/appium/sample-code/blob/master/sample-code/examples/node/helpers/caps.js capabilities: { browserName: 'safari', 'appium-version': '1.0', platformName: 'iOS', platformVersion: '7.1', deviceName: 'iPhone Simulator', }, baseUrl: 'http://localhost:8000', // configuring wd in onPrepare // wdBridge helps to bridge wd driver with other selenium clients // See https://github.com/sebv/wd-bridge/blob/master/README.md onPrepare: function () { var wd = require('wd'), protractor = require('protractor'), wdBridge = require('wd-bridge')(protractor, wd); wdBridge.initFromProtractor(exports.config); } }; ``` iPad: ```javascript exports.config = { seleniumAddress: 'http://localhost:4723/wd/hub', specs: [ 'basic/*_spec.js' ], // Reference: https://github.com/appium/sample-code/blob/master/sample-code/examples/node/helpers/caps.js capabilities: { browserName: 'safari', 'appium-version': '1.0', platformName: 'iOS', platformVersion: '7.1', deviceName: 'IPad Simulator', }, baseUrl: 'http://localhost:8000', // configuring wd in onPrepare // wdBridge helps to bridge wd driver with other selenium clients // See https://github.com/sebv/wd-bridge/blob/master/README.md onPrepare: function () { var wd = require('wd'), protractor = require('protractor'), wdBridge = require('wd-bridge')(protractor, wd); wdBridge.initFromProtractor(exports.config); } }; ``` *Note the following:* - note capabilities - baseUrl is localhost (not 10.0.2.2) - selenium address is using port 4723 Setting Up Protractor with Selendroid ------------------------------------- ###### Setup * Install Java SDK (>1.6) and configure JAVA_HOME (Important: make sure it's not pointing to JRE). * Follow http://spring.io/guides/gs/android/ to install and set up Android developer environment. Do not set up Android Virtual Device as instructed here. * From commandline, 'android avd' and then follow Selendroid's recommendation (http://selendroid.io/setup.html#androidDevices). Take note of the emulator accelerator. Here's an example: ```shell > android list avd Available Android Virtual Devices: Name: myAvd Device: Nexus 5 (Google) Path: /Users/hankduan/.android/avd/Hank.avd Target: Android 4.4.2 (API level 19) Tag/ABI: default/x86 Skin: WVGA800 ``` ###### Running Tests * Ensure app is running if testing local app (Skip if testing public website): ```shell > ./scripts/web-server.js Starting express web server in /workspace/protractor/testapp on port 8000 ``` * Start emulator manually (at least the first time): ```shell > emulator -avd myAvd HAX is working and emulator runs in fast virt mode ``` *Note: The last line that tells you the emulator accelerator is running.* * Start selendroid: ```shell > java -jar selendroid-standalone-0.9.0-with-dependencies.jar ... ``` * Once selendroid is started, you should be able to go to "http://localhost:4444/wd/hub/status" and see your device there: ```javascript {"value":{"os":{"name":"Mac OS X","arch":"x86_64","version":"10.9.2"},"build":{"browserName":"selendroid","version":"0.9.0"},"supportedDevices":[{"emulator":true,"screenSize":"WVGA800","avdName":"Hank","androidTarget":"ANDROID19"}],"supportedApps":[{"mainActivity":"io.selendroid.androiddriver.WebViewActivity","appId":"io.selendroid.androiddriver:0.9.0","basePackage":"io.selendroid.androiddriver"}]},"status":0} ``` * Configure protractor: ```javascript exports.config = { seleniumAddress: 'http://localhost:4444/wd/hub', specs: [ 'basic/*_spec.js' ], capabilities: { 'browserName': 'android' }, baseUrl: 'http://10.0.2.2:8000' }; ``` *Note the following:* - browserName is 'android' - baseUrl is 10.0.2.2 instead of localhost because it is used to access the localhost of the host machine in the android emulator Setting up PhantomJS -------------------- _Note: We recommend against using PhantomJS for tests with Protractor. There are many reported issues with PhantomJS crashing and behaving differently from real browsers._ In order to test locally with [PhantomJS](http://phantomjs.org/), you'll need to either have it installed globally, or relative to your project. For global install see the [PhantomJS download page](http://phantomjs.org/download.html). For local install run: `npm install phantomjs`. Add phantomjs to the driver capabilities, and include a path to the binary if using local installation: ```javascript capabilities: { 'browserName': 'phantomjs', /* * Can be used to specify the phantomjs binary path. * This can generally be ommitted if you installed phantomjs globally. */ 'phantomjs.binary.path': require('phantomjs').path, /* * Command line args to pass to ghostdriver, phantomjs's browser driver. * See https://github.com/detro/ghostdriver#faq */ 'phantomjs.ghostdriver.cli.args': ['--loglevel=DEBUG'] } ```
package org.apache.reef.io.network.impl; import org.apache.reef.io.network.Message; import org.apache.reef.wake.Identifier; import java.net.SocketAddress; import java.util.List; /** * NetworkConnectionServiceMessage implementation. * This is a wrapper message of message type <T>. */ final class NetworkConnectionServiceMessage<T> implements Message<T> { private final List<T> messages; private SocketAddress remoteAddr; private final String connFactoryId; private final Identifier srcId; private final Identifier destId; /** * Constructs a network connection service message. * * @param connFactoryId the connection factory identifier * @param srcId the source identifier of NetworkConnectionService * @param destId the destination identifier of NetworkConnectionService * @param messages the list of messages */ NetworkConnectionServiceMessage( final String connFactoryId, final Identifier srcId, final Identifier destId, final List<T> messages) { this.connFactoryId = connFactoryId; this.srcId = srcId; this.destId = destId; this.messages = messages; } void setRemoteAddress(final SocketAddress remoteAddress) { this.remoteAddr = remoteAddress; } /** * Gets a destination identifier. * * @return a remote id */ @Override public Identifier getDestId() { return destId; } /** * Gets a connection factory identifier. * * @return a connection factory id */ public String getConnectionFactoryId() { return connFactoryId; } /** * Gets a source identifier of NetworkConnectionService. * * @return a source id */ @Override public Identifier getSrcId() { return srcId; } @Override public List<T> getData() { return messages; } /** * Returns a string representation of this object. * * @return a string representation of this object */ public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("NSMessage"); builder.append(" remoteID="); builder.append(destId); builder.append(" message=[| "); for (final T message : messages) { builder.append(message + " |"); } builder.append("]"); return builder.toString(); } }
declare class AppRate { static locales:Locales; static preferences:AppRatePreferences; static init():AppRate; static promptForRating(immediately?:boolean):AppRate; static navigateToAppStore():AppRate; } declare class AppRatePreferences { useLanguage:string; displayAppName:string; promptAgainForEachNewVersion:boolean; usesUntilPrompt:number; openStoreInApp:boolean; useCustomRateDialog:boolean; callbacks:CallbackPreferences; storeAppURL:StoreAppURLPreferences; customLocale:CustomLocale; } declare class StoreAppURLPreferences { ios:string; android:string; blackberry:string; windows8:string; } declare class CallbackPreferences { onButtonClicked:(buttonIndex:number) => void; onRateDialogShow:(rateCallback:(buttonIndex:number) => void) => void; } declare class CustomLocale { title:string; message:string; cancelButtonLabel:string; laterButtonLabel:string; rateButtonLabel:string; } declare class Locales { addLocale(localeObject:Locale):Locale; getLocale(language:string, applicationTitle?:string):Locale; getLocalesNames():Array<string>; } declare class Locale { constructor(localeOptions:LocaleOptions); } declare class LocaleOptions { language:string title:string; message:string; cancelButtonLabel:string; laterButtonLabel:string; rateButtonLabel:string; }
/* Includes ------------------------------------------------------------------*/ #if !defined(STM32L011xx) && !defined(STM32L021xx) && !defined (STM32L031xx) && !defined (STM32L041xx) && !defined (STM32L051xx) && !defined (STM32L061xx) && !defined (STM32L071xx) && !defined (STM32L081xx) #include "stm32l0xx_hal.h" #ifdef HAL_TSC_MODULE_ENABLED /** @addtogroup STM32L0xx_HAL_Driver * @{ */ /** @addtogroup TSC * @brief HAL TSC module driver * @{ */ /** @addtogroup TSC_Private TSC Private * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ static uint32_t TSC_extract_groups(uint32_t iomask); /* Private functions ---------------------------------------------------------*/ /** * @} */ /** @addtogroup TSC_Exported_Functions TSC Exported Functions * @{ */ /** @addtogroup HAL_TSC_Exported_Functions_Group1 * @brief Initialization and Configuration functions * @verbatim =============================================================================== ##### Initialization and de-initialization functions ##### =============================================================================== [..] This section provides functions allowing to: (+) Initialize and configure the TSC. (+) De-initialize the TSC. @endverbatim * @{ */ /** * @brief Initializes the TSC peripheral according to the specified parameters * in the TSC_InitTypeDef structure. * @param htsc: TSC handle * @retval HAL status */ HAL_StatusTypeDef HAL_TSC_Init(TSC_HandleTypeDef* htsc) { /* Check TSC handle allocation */ if (htsc == NULL) { return HAL_ERROR; } /* Check the parameters */ assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); assert_param(IS_TSC_CTPH(htsc->Init.CTPulseHighLength)); assert_param(IS_TSC_CTPL(htsc->Init.CTPulseLowLength)); assert_param(IS_TSC_SS(htsc->Init.SpreadSpectrum)); assert_param(IS_TSC_SSD(htsc->Init.SpreadSpectrumDeviation)); assert_param(IS_TSC_SS_PRESC(htsc->Init.SpreadSpectrumPrescaler)); assert_param(IS_TSC_PG_PRESC(htsc->Init.PulseGeneratorPrescaler)); assert_param(IS_TSC_MCV(htsc->Init.MaxCountValue)); assert_param(IS_TSC_IODEF(htsc->Init.IODefaultMode)); assert_param(IS_TSC_SYNC_POL(htsc->Init.SynchroPinPolarity)); assert_param(IS_TSC_ACQ_MODE(htsc->Init.AcquisitionMode)); assert_param(IS_TSC_MCE_IT(htsc->Init.MaxCountInterrupt)); if(htsc->State == HAL_TSC_STATE_RESET) { /* Allocate lock resource and initialize it */ htsc->Lock = HAL_UNLOCKED; } /* Initialize the TSC state */ htsc->State = HAL_TSC_STATE_BUSY; /* Init the low level hardware : GPIO, CLOCK, CORTEX */ HAL_TSC_MspInit(htsc); /*--------------------------------------------------------------------------*/ /* Set TSC parameters */ /* Enable TSC */ htsc->Instance->CR = TSC_CR_TSCE; /* Set all functions */ htsc->Instance->CR |= (htsc->Init.CTPulseHighLength | htsc->Init.CTPulseLowLength | (uint32_t)(htsc->Init.SpreadSpectrumDeviation << 17) | htsc->Init.SpreadSpectrumPrescaler | htsc->Init.PulseGeneratorPrescaler | htsc->Init.MaxCountValue | htsc->Init.SynchroPinPolarity | htsc->Init.AcquisitionMode); /* Spread spectrum */ if (htsc->Init.SpreadSpectrum == ENABLE) { htsc->Instance->CR |= TSC_CR_SSE; } /* Disable Schmitt trigger hysteresis on all used TSC IOs */ htsc->Instance->IOHCR = (uint32_t)(~(htsc->Init.ChannelIOs | htsc->Init.ShieldIOs | htsc->Init.SamplingIOs)); /* Set channel and shield IOs */ htsc->Instance->IOCCR = (htsc->Init.ChannelIOs | htsc->Init.ShieldIOs); /* Set sampling IOs */ htsc->Instance->IOSCR = htsc->Init.SamplingIOs; /* Set the groups to be acquired */ htsc->Instance->IOGCSR = TSC_extract_groups(htsc->Init.ChannelIOs); /* Clear interrupts */ htsc->Instance->IER &= (uint32_t)(~(TSC_IT_EOA | TSC_IT_MCE)); /* Clear flags */ htsc->Instance->ICR = (TSC_FLAG_EOA | TSC_FLAG_MCE); /*--------------------------------------------------------------------------*/ /* Initialize the TSC state */ htsc->State = HAL_TSC_STATE_READY; /* Return function status */ return HAL_OK; } /** * @brief Deinitializes the TSC peripheral registers to their default reset values. * @param htsc: TSC handle * @retval HAL status */ HAL_StatusTypeDef HAL_TSC_DeInit(TSC_HandleTypeDef* htsc) { /* Check TSC handle allocation */ if (htsc == NULL) { return HAL_ERROR; } /* Check the parameters */ assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); /* Change TSC state */ htsc->State = HAL_TSC_STATE_BUSY; /* DeInit the low level hardware */ HAL_TSC_MspDeInit(htsc); /* Change TSC state */ htsc->State = HAL_TSC_STATE_RESET; /* Process unlocked */ __HAL_UNLOCK(htsc); /* Return function status */ return HAL_OK; } /** * @brief Initializes the TSC MSP. * @param htsc: pointer to a TSC_HandleTypeDef structure that contains * the configuration information for the specified TSC. * @retval None */ __weak void HAL_TSC_MspInit(TSC_HandleTypeDef* htsc) { /* Prevent unused argument(s) compilation warning */ UNUSED(htsc); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TSC_MspInit could be implemented in the user file. */ } /** * @brief DeInitializes the TSC MSP. * @param htsc: pointer to a TSC_HandleTypeDef structure that contains * the configuration information for the specified TSC. * @retval None */ __weak void HAL_TSC_MspDeInit(TSC_HandleTypeDef* htsc) { /* Prevent unused argument(s) compilation warning */ UNUSED(htsc); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TSC_MspDeInit could be implemented in the user file. */ } /** * @} */ /** @addtogroup HAL_TSC_Exported_Functions_Group2 * @brief IO operation functions * @verbatim =============================================================================== ##### IO Operation functions ##### =============================================================================== [..] This section provides functions allowing to: (+) Start acquisition in polling mode. (+) Start acquisition in interrupt mode. (+) Stop conversion in polling mode. (+) Stop conversion in interrupt mode. (+) Get group acquisition status. (+) Get group acquisition value. @endverbatim * @{ */ /** * @brief Starts the acquisition. * @param htsc: pointer to a TSC_HandleTypeDef structure that contains * the configuration information for the specified TSC. * @retval HAL status */ HAL_StatusTypeDef HAL_TSC_Start(TSC_HandleTypeDef* htsc) { /* Check the parameters */ assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); /* Process locked */ __HAL_LOCK(htsc); /* Change TSC state */ htsc->State = HAL_TSC_STATE_BUSY; /* Clear interrupts */ __HAL_TSC_DISABLE_IT(htsc, (TSC_IT_EOA | TSC_IT_MCE)); /* Clear flags */ __HAL_TSC_CLEAR_FLAG(htsc, (TSC_FLAG_EOA | TSC_FLAG_MCE)); /* Set touch sensing IOs not acquired to the specified IODefaultMode */ if (htsc->Init.IODefaultMode == TSC_IODEF_OUT_PP_LOW) { __HAL_TSC_SET_IODEF_OUTPPLOW(htsc); } else { __HAL_TSC_SET_IODEF_INFLOAT(htsc); } /* Launch the acquisition */ __HAL_TSC_START_ACQ(htsc); /* Process unlocked */ __HAL_UNLOCK(htsc); /* Return function status */ return HAL_OK; } /** * @brief Enables the interrupt and starts the acquisition * @param htsc: pointer to a TSC_HandleTypeDef structure that contains * the configuration information for the specified TSC. * @retval HAL status. */ HAL_StatusTypeDef HAL_TSC_Start_IT(TSC_HandleTypeDef* htsc) { /* Check the parameters */ assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); assert_param(IS_TSC_MCE_IT(htsc->Init.MaxCountInterrupt)); /* Process locked */ __HAL_LOCK(htsc); /* Change TSC state */ htsc->State = HAL_TSC_STATE_BUSY; /* Enable end of acquisition interrupt */ __HAL_TSC_ENABLE_IT(htsc, TSC_IT_EOA); /* Enable max count error interrupt (optional) */ if (htsc->Init.MaxCountInterrupt == ENABLE) { __HAL_TSC_ENABLE_IT(htsc, TSC_IT_MCE); } else { __HAL_TSC_DISABLE_IT(htsc, TSC_IT_MCE); } /* Clear flags */ __HAL_TSC_CLEAR_FLAG(htsc, (TSC_FLAG_EOA | TSC_FLAG_MCE)); /* Set touch sensing IOs not acquired to the specified IODefaultMode */ if (htsc->Init.IODefaultMode == TSC_IODEF_OUT_PP_LOW) { __HAL_TSC_SET_IODEF_OUTPPLOW(htsc); } else { __HAL_TSC_SET_IODEF_INFLOAT(htsc); } /* Launch the acquisition */ __HAL_TSC_START_ACQ(htsc); /* Process unlocked */ __HAL_UNLOCK(htsc); /* Return function status */ return HAL_OK; } /** * @brief Stops the acquisition previously launched in polling mode * @param htsc: pointer to a TSC_HandleTypeDef structure that contains * the configuration information for the specified TSC. * @retval HAL status */ HAL_StatusTypeDef HAL_TSC_Stop(TSC_HandleTypeDef* htsc) { /* Check the parameters */ assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); /* Process locked */ __HAL_LOCK(htsc); /* Stop the acquisition */ __HAL_TSC_STOP_ACQ(htsc); /* Set touch sensing IOs in low power mode (output push-pull) */ __HAL_TSC_SET_IODEF_OUTPPLOW(htsc); /* Clear flags */ __HAL_TSC_CLEAR_FLAG(htsc, (TSC_FLAG_EOA | TSC_FLAG_MCE)); /* Change TSC state */ htsc->State = HAL_TSC_STATE_READY; /* Process unlocked */ __HAL_UNLOCK(htsc); /* Return function status */ return HAL_OK; } /** * @brief Stops the acquisition previously launched in interrupt mode * @param htsc: pointer to a TSC_HandleTypeDef structure that contains * the configuration information for the specified TSC. * @retval HAL status */ HAL_StatusTypeDef HAL_TSC_Stop_IT(TSC_HandleTypeDef* htsc) { /* Check the parameters */ assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); /* Process locked */ __HAL_LOCK(htsc); /* Stop the acquisition */ __HAL_TSC_STOP_ACQ(htsc); /* Set touch sensing IOs in low power mode (output push-pull) */ __HAL_TSC_SET_IODEF_OUTPPLOW(htsc); /* Disable interrupts */ __HAL_TSC_DISABLE_IT(htsc, (TSC_IT_EOA | TSC_IT_MCE)); /* Clear flags */ __HAL_TSC_CLEAR_FLAG(htsc, (TSC_FLAG_EOA | TSC_FLAG_MCE)); /* Change TSC state */ htsc->State = HAL_TSC_STATE_READY; /* Process unlocked */ __HAL_UNLOCK(htsc); /* Return function status */ return HAL_OK; } /** * @brief Gets the acquisition status for a group * @param htsc: pointer to a TSC_HandleTypeDef structure that contains * the configuration information for the specified TSC. * @param gx_index: Index of the group * @retval Group status */ TSC_GroupStatusTypeDef HAL_TSC_GroupGetStatus(TSC_HandleTypeDef* htsc, uint32_t gx_index) { /* Check the parameters */ assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); assert_param(IS_TSC_GROUP_INDEX(gx_index)); /* Return the group status */ return(__HAL_TSC_GET_GROUP_STATUS(htsc, gx_index)); } /** * @brief Gets the acquisition measure for a group * @param htsc: pointer to a TSC_HandleTypeDef structure that contains * the configuration information for the specified TSC. * @param gx_index: Index of the group * @retval Acquisition measure */ uint32_t HAL_TSC_GroupGetValue(TSC_HandleTypeDef* htsc, uint32_t gx_index) { /* Check the parameters */ assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); assert_param(IS_TSC_GROUP_INDEX(gx_index)); /* Return the group acquisition counter */ return htsc->Instance->IOGXCR[gx_index]; } /** * @} */ /** @addtogroup HAL_TSC_Exported_Functions_Group3 * @brief Peripheral Control functions * @verbatim =============================================================================== ##### Peripheral Control functions ##### =============================================================================== [..] This section provides functions allowing to: (+) Configure TSC IOs (+) Discharge TSC IOs @endverbatim * @{ */ /** * @brief Configures TSC IOs * @param htsc: pointer to a TSC_HandleTypeDef structure that contains * the configuration information for the specified TSC. * @param config: pointer to the configuration structure. * @retval HAL status */ HAL_StatusTypeDef HAL_TSC_IOConfig(TSC_HandleTypeDef* htsc, TSC_IOConfigTypeDef* config) { /* Check the parameters */ assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); /* Process locked */ __HAL_LOCK(htsc); /* Stop acquisition */ __HAL_TSC_STOP_ACQ(htsc); /* Disable Schmitt trigger hysteresis on all used TSC IOs */ htsc->Instance->IOHCR = (uint32_t)(~(config->ChannelIOs | config->ShieldIOs | config->SamplingIOs)); /* Set channel and shield IOs */ htsc->Instance->IOCCR = (config->ChannelIOs | config->ShieldIOs); /* Set sampling IOs */ htsc->Instance->IOSCR = config->SamplingIOs; /* Set groups to be acquired */ htsc->Instance->IOGCSR = TSC_extract_groups(config->ChannelIOs); /* Process unlocked */ __HAL_UNLOCK(htsc); /* Return function status */ return HAL_OK; } /** * @brief Discharge TSC IOs * @param htsc: pointer to a TSC_HandleTypeDef structure that contains * the configuration information for the specified TSC. * @param choice: enable or disable * @retval HAL status */ HAL_StatusTypeDef HAL_TSC_IODischarge(TSC_HandleTypeDef* htsc, uint32_t choice) { /* Check the parameters */ assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); /* Process locked */ __HAL_LOCK(htsc); if (choice == ENABLE) { __HAL_TSC_SET_IODEF_OUTPPLOW(htsc); } else { __HAL_TSC_SET_IODEF_INFLOAT(htsc); } /* Process unlocked */ __HAL_UNLOCK(htsc); /* Return the group acquisition counter */ return HAL_OK; } /** * @} */ /** @addtogroup HAL_TSC_Exported_Functions_Group4 * @brief State functions * @verbatim =============================================================================== ##### State functions ##### =============================================================================== [..] This subsection provides functions allowing to (+) Get TSC state. (+) Poll for acquisition completed. (+) Handles TSC interrupt request. @endverbatim * @{ */ /** * @brief Return the TSC state * @param htsc: pointer to a TSC_HandleTypeDef structure that contains * the configuration information for the specified TSC. * @retval HAL state */ HAL_TSC_StateTypeDef HAL_TSC_GetState(TSC_HandleTypeDef* htsc) { /* Check the parameters */ assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); if (htsc->State == HAL_TSC_STATE_BUSY) { /* Check end of acquisition flag */ if (__HAL_TSC_GET_FLAG(htsc, TSC_FLAG_EOA) != RESET) { /* Check max count error flag */ if (__HAL_TSC_GET_FLAG(htsc, TSC_FLAG_MCE) != RESET) { /* Change TSC state */ htsc->State = HAL_TSC_STATE_ERROR; } else { /* Change TSC state */ htsc->State = HAL_TSC_STATE_READY; } } } /* Return TSC state */ return htsc->State; } /** * @brief Start acquisition and wait until completion * @note There is no need of a timeout parameter as the max count error is already * managed by the TSC peripheral. * @param htsc: pointer to a TSC_HandleTypeDef structure that contains * the configuration information for the specified TSC. * @retval HAL state */ HAL_StatusTypeDef HAL_TSC_PollForAcquisition(TSC_HandleTypeDef* htsc) { /* Check the parameters */ assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); /* Process locked */ __HAL_LOCK(htsc); /* Check end of acquisition */ while (HAL_TSC_GetState(htsc) == HAL_TSC_STATE_BUSY) { /* The timeout (max count error) is managed by the TSC peripheral itself. */ } /* Process unlocked */ __HAL_UNLOCK(htsc); return HAL_OK; } /** * @brief Handles TSC interrupt request * @param htsc: pointer to a TSC_HandleTypeDef structure that contains * the configuration information for the specified TSC. * @retval None */ void HAL_TSC_IRQHandler(TSC_HandleTypeDef* htsc) { /* Check the parameters */ assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); /* Check if the end of acquisition occured */ if (__HAL_TSC_GET_FLAG(htsc, TSC_FLAG_EOA) != RESET) { /* Clear EOA flag */ __HAL_TSC_CLEAR_FLAG(htsc, TSC_FLAG_EOA); } /* Check if max count error occured */ if (__HAL_TSC_GET_FLAG(htsc, TSC_FLAG_MCE) != RESET) { /* Clear MCE flag */ __HAL_TSC_CLEAR_FLAG(htsc, TSC_FLAG_MCE); /* Change TSC state */ htsc->State = HAL_TSC_STATE_ERROR; /* Conversion completed callback */ HAL_TSC_ErrorCallback(htsc); } else { /* Change TSC state */ htsc->State = HAL_TSC_STATE_READY; /* Conversion completed callback */ HAL_TSC_ConvCpltCallback(htsc); } } /** * @brief Acquisition completed callback in non blocking mode * @param htsc: pointer to a TSC_HandleTypeDef structure that contains * the configuration information for the specified TSC. * @retval None */ __weak void HAL_TSC_ConvCpltCallback(TSC_HandleTypeDef* htsc) { /* Prevent unused argument(s) compilation warning */ UNUSED(htsc); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TSC_ConvCpltCallback could be implemented in the user file. */ } /** * @brief Error callback in non blocking mode * @param htsc: pointer to a TSC_HandleTypeDef structure that contains * the configuration information for the specified TSC. * @retval None */ __weak void HAL_TSC_ErrorCallback(TSC_HandleTypeDef* htsc) { /* Prevent unused argument(s) compilation warning */ UNUSED(htsc); /* NOTE : This function should not be modified, when the callback is needed, the HAL_TSC_ErrorCallback could be implemented in the user file. */ } /** * @} */ /** * @} */ /** @addtogroup TSC_Private * @{ */ /** * @brief Utility function used to set the acquired groups mask * @param iomask: Channels IOs mask * @retval Acquired groups mask */ static uint32_t TSC_extract_groups(uint32_t iomask) { uint32_t groups = 0; uint32_t idx; for (idx = 0; idx < TSC_NB_OF_GROUPS; idx++) { if ((iomask & ((uint32_t)0x0F << (idx * 4))) != RESET) { groups |= ((uint32_t)1 << idx); } } return groups; } /** * @} */ /** * @} */ /** * @} */ #endif /* HAL_TSC_MODULE_ENABLED */ #endif /* #if !defined(STM32L011xx) && !defined(STM32L021xx) && !defined (STM32L031xx) && !defined (STM32L041xx) && !defined (STM32L051xx) && !defined (STM32L061xx) && !defined (STM32L071xx) && !defined (STM32L081xx) */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
if(NOT WITH_PYTHON) add_definitions(-DPADDLE_NO_PYTHON) endif(NOT WITH_PYTHON) if(WITH_DSO) add_definitions(-DPADDLE_USE_DSO) endif(WITH_DSO) if(WITH_TESTING) add_definitions(-DPADDLE_WITH_TESTING) endif(WITH_TESTING) if(NOT WITH_PROFILER) add_definitions(-DPADDLE_DISABLE_PROFILER) endif(NOT WITH_PROFILER) if(WITH_AVX AND AVX_FOUND) set(SIMD_FLAG ${AVX_FLAG}) elseif(SSE3_FOUND) set(SIMD_FLAG ${SSE3_FLAG}) endif() if(WIN32) # windows header option for all targets. add_definitions(-D_XKEYCHECK_H) # Use symbols instead of absolute path, reduce the cmake link command length. SET(CMAKE_C_USE_RESPONSE_FILE_FOR_LIBRARIES 1) SET(CMAKE_CXX_USE_RESPONSE_FILE_FOR_LIBRARIES 1) SET(CMAKE_C_USE_RESPONSE_FILE_FOR_OBJECTS 1) SET(CMAKE_CXX_USE_RESPONSE_FILE_FOR_OBJECTS 1) SET(CMAKE_C_USE_RESPONSE_FILE_FOR_INCLUDES 1) SET(CMAKE_CXX_USE_RESPONSE_FILE_FOR_INCLUDES 1) SET(CMAKE_C_RESPONSE_FILE_LINK_FLAG "@") SET(CMAKE_CXX_RESPONSE_FILE_LINK_FLAG "@") # Specify the program to use when building static libraries SET(CMAKE_C_CREATE_STATIC_LIBRARY "<CMAKE_AR> lib <TARGET> <LINK_FLAGS> <OBJECTS>") SET(CMAKE_CXX_CREATE_STATIC_LIBRARY "<CMAKE_AR> lib <TARGET> <LINK_FLAGS> <OBJECTS>") # set defination for the dll export if (NOT MSVC) message(FATAL "Windows build only support msvc. Which was binded by the nvcc compiler of NVIDIA.") endif(NOT MSVC) endif(WIN32) if(WITH_PSLIB) add_definitions(-DPADDLE_WITH_PSLIB) endif() if(WITH_GPU) add_definitions(-DPADDLE_WITH_CUDA) add_definitions(-DEIGEN_USE_GPU) FIND_PACKAGE(CUDA REQUIRED) if(${CUDA_VERSION_MAJOR} VERSION_LESS 7) message(FATAL_ERROR "Paddle needs CUDA >= 7.0 to compile") endif() if(NOT CUDNN_FOUND) message(FATAL_ERROR "Paddle needs cudnn to compile") endif() if(CUPTI_FOUND) include_directories(${CUPTI_INCLUDE_DIR}) add_definitions(-DPADDLE_WITH_CUPTI) else() message(STATUS "Cannot find CUPTI, GPU Profiling is incorrect.") endif() set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS} "-Xcompiler ${SIMD_FLAG}") # Include cuda and cudnn include_directories(${CUDNN_INCLUDE_DIR}) include_directories(${CUDA_TOOLKIT_INCLUDE}) if(TENSORRT_FOUND) if(${CUDA_VERSION_MAJOR} VERSION_LESS 8) message(FATAL_ERROR "TensorRT needs CUDA >= 8.0 to compile") endif() if(${CUDNN_MAJOR_VERSION} VERSION_LESS 7) message(FATAL_ERROR "TensorRT needs CUDNN >= 7.0 to compile") endif() if(${TENSORRT_MAJOR_VERSION} VERSION_LESS 4) message(FATAL_ERROR "Paddle needs TensorRT >= 4.0 to compile") endif() include_directories(${TENSORRT_INCLUDE_DIR}) endif() if(WITH_ANAKIN) if(${CUDA_VERSION_MAJOR} VERSION_LESS 8) message(WARNING "Anakin needs CUDA >= 8.0 to compile. Force WITH_ANAKIN=OFF") set(WITH_ANAKIN OFF CACHE STRING "Anakin is valid only when CUDA >= 8.0." FORCE) endif() if(${CUDNN_MAJOR_VERSION} VERSION_LESS 7) message(WARNING "Anakin needs CUDNN >= 7.0 to compile. Force WITH_ANAKIN=OFF") set(WITH_ANAKIN OFF CACHE STRING "Anakin is valid only when CUDNN >= 7.0." FORCE) endif() add_definitions(-DWITH_ANAKIN) endif() if(WITH_ANAKIN) # NOTICE(minqiyang): the end slash is important because $CUDNN_INCLUDE_DIR # is a softlink to real cudnn.h directory set(ENV{CUDNN_INCLUDE_DIR} "${CUDNN_INCLUDE_DIR}/") get_filename_component(CUDNN_LIBRARY_DIR ${CUDNN_LIBRARY} DIRECTORY) set(ENV{CUDNN_LIBRARY} ${CUDNN_LIBRARY_DIR}) endif() elseif(WITH_AMD_GPU) add_definitions(-DPADDLE_WITH_HIP) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -D__HIP_PLATFORM_HCC__") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D__HIP_PLATFORM_HCC__") else() add_definitions(-DHPPL_STUB_FUNC) list(APPEND CMAKE_CXX_SOURCE_FILE_EXTENSIONS cu) endif() if (WITH_MKLML AND MKLML_IOMP_LIB) message(STATUS "Enable Intel OpenMP with ${MKLML_IOMP_LIB}") if(WIN32) # openmp not support well for now on windows set(OPENMP_FLAGS "") else(WIN32) set(OPENMP_FLAGS "-fopenmp") endif(WIN32) set(CMAKE_C_CREATE_SHARED_LIBRARY_FORBIDDEN_FLAGS ${OPENMP_FLAGS}) set(CMAKE_CXX_CREATE_SHARED_LIBRARY_FORBIDDEN_FLAGS ${OPENMP_FLAGS}) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OPENMP_FLAGS}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OPENMP_FLAGS}") endif() set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${SIMD_FLAG}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${SIMD_FLAG}") if(WITH_DISTRIBUTE) add_definitions(-DPADDLE_WITH_DISTRIBUTE) endif() if(WITH_GRPC) add_definitions(-DPADDLE_WITH_GRPC) endif(WITH_GRPC) if(WITH_BRPC_RDMA) add_definitions(-DPADDLE_WITH_BRPC_RDMA) endif(WITH_BRPC_RDMA) if(ON_INFER) add_definitions(-DPADDLE_ON_INFERENCE) endif(ON_INFER)
\documentclass[aspectratio=169]{beamer} % because we need to claim weird things \newtheorem{claim}{Claim} \newtheorem{defn}{Definition} %\newtheorem{lemma}{Lemma} \newtheorem{thm}{Theorem} \newtheorem{vita}{Vit\ae} \newtheorem{qotd}{Quote of the Day} \usepackage{algorithm} \usepackage{algpseudocode} \usepackage{listings} \usepackage{color} \usepackage{graphics} \usepackage{ulem} \bibliographystyle{unsrt} % background image \usebackgroundtemplate% {% \includegraphics[width=\paperwidth,height=\paperheight]{../artifacts/stemulus.pdf}% } \setbeamertemplate{caption}[numbered] \lstset{% breaklines=true, captionpos=b, frame=single, keepspaces=true } % page numbers \addtobeamertemplate{navigation symbols}{}{% \usebeamerfont{footline}% \usebeamercolor[fg]{footline}% \hspace{1em}% \insertframenumber/\inserttotalframenumber } % presentation header \usetheme{Warsaw} \title{Introduction to JavaScript} \author{Dylan Lane McDonald} \institute{CNM STEMulus Center\\Web Development with PHP} \date{\today} \begin{document} \lstset{language=HTML} \begin{frame} \titlepage \end{frame} \begin{frame} \frametitle{Outline} \tableofcontents \end{frame} \section{About JavaScript} \subsection{History of JavaScript} \begin{frame} \frametitle{History of JavaScript} JavaScript began its life at Netscape in 1995. Originally slated for Netscape 2.0, the language was originally called \textit{LiveScript} and subsequently renamed to \textit{JavaScript} shortly before Netscape 2.0's release. This begs the question: is JavaScript similar to Java? \mbox{}\\ \pause \textbf{ABSOLUTELY NOT!!!!} \mbox{}\\ \pause JavaScript's similarities to Java are purely superficial. The syntax is derived from a common ancestor, C, and both use C-like syntax. The similarities stop there. \end{frame} \subsection{Features of JavaScript} \begin{frame} \frametitle{Features of JavaScript} JavaScript is an \textbf{interpreted} language run by a JavaScript engine, normally a component of the end user's web browser. Some of the key features of JavaScript are: \begin{itemize} \item \textbf{Imperative}: Functions can be written to perform specific tasks \item \textbf{Object Oriented}: Objects can be modeled around what the system is \item \textbf{Dynamically Typed}: The variable type (e.g., String, Integer, \dots) are decided at run time \end{itemize} JavaScript is enabled on most end user's web browsers and is used in creating responsive, dynamic, and fun sites. \end{frame} \section{Events \& Closures} \subsection{Events} \begin{frame} \frametitle{Javascript Events} An event can roughly be categorized into one or both of the following categories: \begin{itemize} \item Something the browser does \item Something the user does \end{itemize} \pause \mbox{}\\ Events are the centerpiece of creating interactive web sites. Whether flat JavaScript or a framework such as Angular or jQuery are used, reacting to events is the key to creating dynamic and interactive web sites. \pause \mbox{}\\ Events map everything from user interaction such as key presses, mouse movements, and scrolls to network events such as loads and going offline. \end{frame} \begin{frame} \frametitle{Example Events} Events are a reaction to a user's action on a web site. Table \ref{tbl:events} lists a very small subset of possible JavaScript events. \begin{table} \begin{tabular}{|l|l|} \hline \textbf{Event} & \textbf{Comment}\\ \hline click & when a user clicks on an element\\ \hline change & when a user changes an input field\\ \hline drag & when a user drags an element\\ \hline drop & when a user drops an element onto another\\ \hline scroll & when a user scrolls (desktop) or swipes (mobile)\\ \hline \end{tabular} \caption{Common JavaScript Events} \label{tbl:events} \end{table} As always, a more exhaustive list of all the possible events are available at the Mozilla Developer Network. \cite{mdn} \end{frame} \subsection{Closures} \begin{frame} \frametitle{Closures} \begin{defn} A \textbf{closure} is a JavaScript function that generates another function. The advantage of a closure is to generalize functionality for use cases that only vary slightly. \end{defn} \pause An example use case of a closure is to greet the user in many different languages. Here, we have a constant and a variable: \begin{itemize} \item \textbf{Constant:} the user's name \item \textbf{Variable:} the exact words in the user's native language \end{itemize} \pause Using a closure, one can boilerplate the words in the particular language and concentrate on the only variable: the user's name. The use of closures is vast in JavaScript frameworks such as Angular and jQuery, where closures are applied to multiple elements at once using class selectors. \end{frame} \begin{frame} \frametitle{Works Cited} \bibliography{javascript} \end{frame} \end{document}
describe Fastlane do describe Fastlane::FastFile do before do allow(FastlaneCore::FastlaneFolder).to receive(:path).and_return(nil) @path = "./fastlane/spec/fixtures/actions/archive.rb" @output_path_with_zip = "./fastlane/spec/fixtures/actions/archive_file.zip" @output_path_without_zip = "./fastlane/spec/fixtures/actions/archive_file" end describe "zip" do it "generates a valid zip command" do expect(Fastlane::Actions).to receive(:sh).with("zip -r #{File.expand_path(@path)}.zip archive.rb") result = Fastlane::FastFile.new.parse("lane :test do zip(path: '#{@path}') end").runner.execute(:test) end it "generates a valid zip command without verbose output" do expect(Fastlane::Actions).to receive(:sh).with("zip -rq #{File.expand_path(@path)}.zip archive.rb") result = Fastlane::FastFile.new.parse("lane :test do zip(path: '#{@path}', verbose: 'false') end").runner.execute(:test) end it "generates an output path given no output path" do result = Fastlane::FastFile.new.parse("lane :test do zip(path: '#{@path}', output_path: '#{@path}') end").runner.execute(:test) expect(result).to eq(File.absolute_path("#{@path}.zip")) end it "generates an output path with zip extension (given zip extension)" do result = Fastlane::FastFile.new.parse("lane :test do zip(path: '#{@path}', output_path: '#{@output_path_with_zip}') end").runner.execute(:test) expect(result).to eq(File.absolute_path(@output_path_with_zip)) end it "generates an output path with zip extension (not given zip extension)" do result = Fastlane::FastFile.new.parse("lane :test do zip(path: '#{@path}', output_path: '#{@output_path_without_zip}') end").runner.execute(:test) expect(result).to eq(File.absolute_path(@output_path_with_zip)) end end end end
using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using WebsitePanel.Providers.Virtualization; using WebsitePanel.WebPortal; using WebsitePanel.EnterpriseServer; using System.Text; namespace WebsitePanel.Portal.VPS2012 { public partial class VdcPrivateNetwork : WebsitePanelModuleBase { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { searchBox.AddCriteria("IPAddress", GetLocalizedString("SearchField.IPAddress")); searchBox.AddCriteria("ItemName", GetLocalizedString("SearchField.ItemName")); } searchBox.AjaxData = this.GetSearchBoxAjaxData(); } public string GetServerEditUrl(string itemID) { return EditUrl("SpaceID", PanelSecurity.PackageId.ToString(), "vps_general", "ItemID=" + itemID); } protected void odsPrivateAddressesPaged_Selected(object sender, ObjectDataSourceStatusEventArgs e) { if (e.Exception != null) { messageBox.ShowErrorMessage("EXCHANGE_GET_MAILBOXES", e.Exception); e.ExceptionHandled = true; } } public string GetSearchBoxAjaxData() { StringBuilder res = new StringBuilder(); res.Append("PagedStored: 'PackagePrivateIPAddresses'"); res.Append(", RedirectUrl: '" + GetServerEditUrl("{0}").Substring(2) + "'"); res.Append(", PackageID: " + (String.IsNullOrEmpty(Request["SpaceID"]) ? "0" : Request["SpaceID"])); res.Append(", VPSTypeID: 'VPS2012'"); return res.ToString(); } } }
/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Copyright (c) 1997-2012 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ----------------------------------------------------------------------------- */ /* Generate code with 16 bit character support. */ #define COMPILE_PCRE16 #include "pcre_version.c" /* End of pcre16_version.c */
using System; using System.Timers; using Sensus.Context; using Xamarin.Forms; namespace Sensus.UI { public class ParticipationReportPage : ContentPage { public ParticipationReportPage(Protocol protocol, ParticipationRewardDatum participationRewardDatum, bool displayDatumQrCode) { Title = protocol.Name; #if __IOS__ string howToIncreaseScore = "You can increase your score by opening Sensus more often and responding to questions that Sensus asks you."; #elif __ANDROID__ string howToIncreaseScore = "You can increase your score by allowing Sensus to run continuously and responding to questions that Sensus asks you."; #elif LOCAL_TESTS string howToIncreaseScore = null; #else #warning "Unrecognized platform." string howToIncreaseScore = "You can increase your score by opening Sensus more often and responding to questions that Sensus asks you."; #endif StackLayout contentLayout = new StackLayout { Orientation = StackOrientation.Vertical, VerticalOptions = LayoutOptions.FillAndExpand, Padding = new Thickness(0, 25, 0, 0), Children = { new Label { Text = "Participation Level", FontSize = 20, HorizontalOptions = LayoutOptions.CenterAndExpand }, new Label { Text = Math.Round(participationRewardDatum.Participation * 100, 0) + "%", FontSize = 50, HorizontalOptions = LayoutOptions.CenterAndExpand }, new Label { Text = "This score reflects your participation level over the past " + (protocol.ParticipationHorizonDays == 1 ? "day" : protocol.ParticipationHorizonDays + " days") + "." + (displayDatumQrCode ? " Anyone can verify your participation by tapping \"Scan Participation Barcode\" on their device and scanning the following barcode:" : ""), FontSize = 20, HorizontalOptions = LayoutOptions.CenterAndExpand } } }; if (displayDatumQrCode) { Label expirationLabel = new Label { FontSize = 15, HorizontalOptions = LayoutOptions.CenterAndExpand }; contentLayout.Children.Add(expirationLabel); Timer timer = new Timer(1000); timer.Elapsed += (o, e) => { SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(() => { int secondsLeftBeforeBarcodeExpiration = (int)(SensusServiceHelper.PARTICIPATION_VERIFICATION_TIMEOUT_SECONDS - (DateTimeOffset.UtcNow - participationRewardDatum.Timestamp).TotalSeconds); if (secondsLeftBeforeBarcodeExpiration <= 0) { expirationLabel.TextColor = Color.Red; expirationLabel.Text = "Barcode has expired. Please reopen this page to renew it."; timer.Stop(); } else { --secondsLeftBeforeBarcodeExpiration; expirationLabel.Text = "Barcode will expire in " + secondsLeftBeforeBarcodeExpiration + " second" + (secondsLeftBeforeBarcodeExpiration == 1 ? "" : "s") + "."; } }); }; timer.Start(); Disappearing += (o, e) => { timer.Stop(); }; contentLayout.Children.Add(new Image { Source = SensusServiceHelper.Get().GetQrCodeImageSource(protocol.RemoteDataStore.GetDatumKey(participationRewardDatum)), HorizontalOptions = LayoutOptions.CenterAndExpand }); } contentLayout.Children.Add(new Label { Text = howToIncreaseScore, FontSize = 20, HorizontalOptions = LayoutOptions.CenterAndExpand }); if (!string.IsNullOrWhiteSpace(protocol.ContactEmail)) { Button emailStudyManagerButton = new Button { Text = "Email Study Manager for Help", FontSize = 20 }; emailStudyManagerButton.Clicked += async (o, e) => { await SensusServiceHelper.Get().SendEmailAsync(protocol.ContactEmail, "Help with Sensus study: " + protocol.Name, "Hello - " + Environment.NewLine + Environment.NewLine + "I am having trouble with a Sensus study. The name of the study is \"" + protocol.Name + "\"." + Environment.NewLine + Environment.NewLine + "Here is why I am sending this email: "); }; contentLayout.Children.Add(emailStudyManagerButton); } Button viewParticipationDetailsButton = new Button { Text = "View Participation Details", FontSize = 20 }; viewParticipationDetailsButton.Clicked += async (o, e) => { await Navigation.PushAsync(new ParticipationReportDetailsPage(protocol)); }; contentLayout.Children.Add(viewParticipationDetailsButton); Content = new ScrollView { Content = contentLayout }; } } }
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ Licensed to the Apache Software Foundation (ASF) under one ~ or more contributor license agreements. See the NOTICE file ~ distributed with this work for additional information ~ regarding copyright ownership. The ASF licenses this file ~ to you under the Apache License, Version 2.0 (the ~ "License"); you may not use this file except in compliance ~ with the License. You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, ~ software distributed under the License is distributed on an ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ~ KIND, either express or implied. See the License for the ~ specific language governing permissions and limitations ~ under the License. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.apache.archiva</groupId> <artifactId>archiva-rest</artifactId> <version>3.0.0-SNAPSHOT</version> </parent> <artifactId>archiva-rest-services</artifactId> <name>Archiva Web :: REST support :: Services</name> <properties> <archiva.baseRestUrl /> <rest.admin.pwd /> <!-- <redbackTestJdbcUrl>jdbc:derby:memory:users-test;create=true</redbackTestJdbcUrl> <redbackTestJdbcDriver>org.apache.derby.jdbc.EmbeddedDriver</redbackTestJdbcDriver> --> <redbackTestJdbcUrl>jdbc:hsqldb:mem:redback-test</redbackTestJdbcUrl> <redbackTestJdbcDriver>org.hsqldb.jdbcDriver</redbackTestJdbcDriver> <site.staging.base>${project.parent.parent.parent.basedir}</site.staging.base> </properties> <dependencies> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>archiva-security</artifactId> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>archiva-storage-api</artifactId> </dependency> <dependency> <groupId>org.apache.archiva.event</groupId> <artifactId>archiva-event-api</artifactId> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>archiva-repository-admin-api</artifactId> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>metadata-model</artifactId> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>archiva-filelock</artifactId> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>archiva-scheduler-indexing</artifactId> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging-api</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.archiva.maven</groupId> <artifactId>archiva-maven-scheduler</artifactId> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>generic-metadata-support</artifactId> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>archiva-repository-layer</artifactId> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>archiva-repository-scanner</artifactId> </dependency> <dependency> <groupId>org.apache.archiva.maven</groupId> <artifactId>archiva-maven-model</artifactId> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>archiva-model</artifactId> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>archiva-policies</artifactId> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>archiva-proxy-api</artifactId> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>archiva-consumer-api</artifactId> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>archiva-scheduler-repository-api</artifactId> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>archiva-common</artifactId> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>archiva-checksum</artifactId> </dependency> <dependency> <groupId>org.apache.archiva.maven</groupId> <artifactId>archiva-maven-common</artifactId> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>archiva-storage-fs</artifactId> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>archiva-security-common</artifactId> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>archiva-scheduler-api</artifactId> </dependency> <dependency> <groupId>org.apache.archiva.maven</groupId> <artifactId>archiva-maven-metadata</artifactId> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>metadata-statistics-api</artifactId> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>metadata-repository-api</artifactId> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>archiva-repository-api</artifactId> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>archiva-rest-api</artifactId> </dependency> <dependency> <groupId>org.apache.archiva.maven</groupId> <artifactId>archiva-maven-repository</artifactId> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>stage-repository-merge</artifactId> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>audit</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>archiva-scheduler-repository</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.apache.archiva.maven</groupId> <artifactId>archiva-maven-indexer</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.apache.archiva.maven</groupId> <artifactId>archiva-maven-proxy</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.apache.archiva.redback</groupId> <artifactId>redback-common-ldap</artifactId> </dependency> <dependency> <groupId>org.apache.archiva.redback</groupId> <artifactId>redback-configuration</artifactId> </dependency> <dependency> <groupId>org.apache.archiva.redback</groupId> <artifactId>redback-rbac-role-manager</artifactId> </dependency> <dependency> <groupId>org.apache.archiva.redback</groupId> <artifactId>redback-rbac-model</artifactId> </dependency> <dependency> <groupId>org.apache.archiva.redback</groupId> <artifactId>redback-system</artifactId> </dependency> <dependency> <groupId>org.apache.archiva.redback</groupId> <artifactId>redback-policy</artifactId> </dependency> <dependency> <groupId>org.apache.archiva.redback</groupId> <artifactId>redback-users-api</artifactId> </dependency> <dependency> <groupId>org.apache.archiva.redback</groupId> <artifactId>redback-authorization-api</artifactId> </dependency> <dependency> <groupId>org.apache.archiva.redback</groupId> <artifactId>redback-authentication-api</artifactId> </dependency> <dependency> <groupId>org.apache.archiva.redback</groupId> <artifactId>redback-rest-services</artifactId> </dependency> <dependency> <groupId>org.apache.archiva.redback</groupId> <artifactId>redback-rest-api</artifactId> </dependency> <dependency> <groupId>org.apache.archiva.components</groupId> <artifactId>archiva-components-spring-quartz</artifactId> </dependency> <dependency> <groupId>org.apache.archiva.components.cache</groupId> <artifactId>archiva-components-spring-cache-api</artifactId> </dependency> <dependency> <groupId>org.apache.archiva.components</groupId> <artifactId>archiva-components-spring-taskqueue</artifactId> </dependency> <dependency> <groupId>jakarta.inject</groupId> <artifactId>jakarta.inject-api</artifactId> </dependency> <dependency> <groupId>jakarta.annotation</groupId> <artifactId>jakarta.annotation-api</artifactId> </dependency> <dependency> <groupId>jakarta.xml.bind</groupId> <artifactId>jakarta.xml.bind-api</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> </dependency> <dependency> <groupId>org.apache.maven.wagon</groupId> <artifactId>wagon-http</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.maven.wagon</groupId> <artifactId>wagon-provider-api</artifactId> </dependency> <dependency> <groupId>org.apache.maven.wagon</groupId> <artifactId>wagon-http-shared</artifactId> </dependency> <dependency> <groupId>jakarta.ws.rs</groupId> <artifactId>jakarta.ws.rs-api</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.jaxrs</groupId> <artifactId>jackson-jaxrs-json-provider</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.jaxrs</groupId> <artifactId>jackson-jaxrs-xml-provider</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.jaxrs</groupId> <artifactId>jackson-jaxrs-base</artifactId> </dependency> <dependency> <groupId>org.modelmapper</groupId> <artifactId>modelmapper</artifactId> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-core</artifactId> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http</artifactId> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxrs</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-rs-client</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-features-logging</artifactId> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-rs-extension-providers</artifactId> <scope>runtime</scope> </dependency> <!-- TEST Scope --> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.hsqldb</groupId> <artifactId>hsqldb</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>jakarta.persistence</groupId> <artifactId>jakarta.persistence-api</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>jakarta.transaction</groupId> <artifactId>jakarta.transaction-api</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.archiva.redback</groupId> <artifactId>redback-rbac-ldap</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.archiva.redback</groupId> <artifactId>redback-rbac-jpa</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.archiva.redback</groupId> <artifactId>redback-rest-services</artifactId> <classifier>tests</classifier> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.archiva.redback</groupId> <artifactId>redback-keys-jpa</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>archiva-test-utils</artifactId> <version>${project.version}</version> <scope>test</scope> <exclusions> <exclusion> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>jakarta.mail</groupId> <artifactId>jakarta.mail-api</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>metadata-store-jcr</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>archiva-repository-admin-default</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.maven.wagon</groupId> <artifactId>wagon-http-lightweight</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>archiva-test-mocks</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.archiva</groupId> <artifactId>archiva-metadata-consumer</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>jakarta.servlet</groupId> <artifactId>jakarta.servlet-api</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>jakarta.validation</groupId> <artifactId>jakarta.validation-api</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-server</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-servlet</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <scope>test</scope> </dependency> <!-- Needed for JDK >= 9 --> <dependency> <groupId>org.glassfish.jaxb</groupId> <artifactId>jaxb-runtime</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>jakarta.annotation</groupId> <artifactId>jakarta.annotation-api</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>jakarta.xml.bind</groupId> <artifactId>jakarta.xml.bind-api</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.rat</groupId> <artifactId>apache-rat-plugin</artifactId> <configuration> <excludes> <exclude>src/test/repo-with-osgi/**</exclude> <exclude>src/test/repo-with-osgi-stage/**</exclude> <exclude>src/test/repo-with-classifier-only/**</exclude> <exclude>src/test/repo-with-snapshots/**</exclude> <exclude>src/main/resources/META-INF/cxf/org.apache.cxf.Logger</exclude> </excludes> </configuration> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <forkCount>2</forkCount> <reuseForks>false</reuseForks> <includes> <include>**/*Tests.java</include> <include>**/*Test.java</include> </includes> <workingDirectory>${project.build.directory}/WDIR-${surefire.forkNumber}</workingDirectory> <trimStackTrace>false</trimStackTrace> <!-- The property jdk.net.URLClassPath.disableClassPathURLCheck is a workaround for a regression with surefire and OpenJDK 8 181b13 on Debian/Ubuntu, @see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=911925 --> <argLine>-Xms2048m -Xmx2048m -server -Djdk.net.URLClassPath.disableClassPathURLCheck=true</argLine> <systemPropertyVariables> <mvn.project.base.dir>${project.basedir}</mvn.project.base.dir> <appserver.base>${project.build.directory}/appserver-base-${surefire.forkNumber}</appserver.base> <plexus.home>${project.build.directory}/appserver-base-${surefire.forkNumber}</plexus.home> <derby.system.home>${project.build.directory}/appserver-base-${surefire.forkNumber}</derby.system.home> <archiva.baseRestUrl>${archiva.baseRestUrl}</archiva.baseRestUrl> <rest.admin.pwd>${rest.admin.pwd}</rest.admin.pwd> <redback.jdbc.url>${redbackTestJdbcUrl}</redback.jdbc.url> <redback.jdbc.driver.name>${redbackTestJdbcDriver}</redback.jdbc.driver.name> <basedir>${basedir}</basedir> <builddir>${project.build.directory}</builddir> <org.apache.jackrabbit.maxCacheMemory>1</org.apache.jackrabbit.maxCacheMemory> <org.apache.jackrabbit.maxMemoryPerCache>1</org.apache.jackrabbit.maxMemoryPerCache> <!--org.apache.jackrabbit.minMemoryPerCache>1</org.apache.jackrabbit.minMemoryPerCache--> <archiva.repositorySessionFactory.id>jcr</archiva.repositorySessionFactory.id> <openjpa.Log>${openjpa.Log}</openjpa.Log> <org.apache.jackrabbit.core.state.validatehierarchy>true</org.apache.jackrabbit.core.state.validatehierarchy> </systemPropertyVariables> </configuration> </plugin> </plugins> </build> </project>
/*! * Qoopido.js library v3.6.6, 2015-7-7 * https://github.com/dlueth/qoopido.js * (c) 2015 Dirk Lueth * Dual licensed under MIT and GPL */ !function(o){window.qoopido.register("support/css/boxshadow",o,["../../support"])}(function(o){"use strict";return o.support.addTest("/css/boxshadow",function(s){o.support.supportsCssProperty("box-shadow")?s.resolve(o.support.getCssProperty("box-shadow")):s.reject()})});
// Copyright (C) 2002-2012 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #ifndef __I_SCENE_NODE_ANIMATOR_CAMERA_FPS_H_INCLUDED__ #define __I_SCENE_NODE_ANIMATOR_CAMERA_FPS_H_INCLUDED__ #include "ISceneNodeAnimator.h" #include "IEventReceiver.h" #include "irrArray.h" namespace ue { struct SKeyMap; namespace scene { //! Special scene node animator for FPS cameras /** This scene node animator can be attached to a camera to make it act like a first person shooter */ class ISceneNodeAnimatorCameraFPS : public ISceneNodeAnimator { public: //! Returns the speed of movement in units per millisecond virtual f32 getMoveSpeed() const = 0; //! Sets the speed of movement in units per millisecond virtual void setMoveSpeed(f32 moveSpeed) = 0; //! Returns the rotation speed in degrees /** The degrees are equivalent to a half screen movement of the mouse, i.e. if the mouse cursor had been moved to the border of the screen since the last animation. */ virtual f32 getRotateSpeed() const = 0; //! Set the rotation speed in degrees virtual void setRotateSpeed(f32 rotateSpeed) = 0; //! Sets the keyboard mapping for this animator (old style) /** \param map Array of keyboard mappings, see ue::SKeyMap \param count Size of the keyboard map array. */ virtual void setKeyMap(SKeyMap *map, u32 count) = 0; //! Sets the keyboard mapping for this animator //! \param keymap The new keymap array virtual void setKeyMap(const core::array<SKeyMap>& keymap) = 0; //! Gets the keyboard mapping for this animator virtual const core::array<SKeyMap>& getKeyMap() const = 0; //! Sets whether vertical movement should be allowed. /** If vertical movement is enabled then the camera may fight with gravity causing camera shake. Disable this if the camera has a collision animator with gravity enabled. */ virtual void setVerticalMovement(bool allow) = 0; //! Sets whether the Y axis of the mouse should be inverted. /** If enabled then moving the mouse down will cause the camera to look up. It is disabled by default. */ virtual void setInvertMouse(bool invert) = 0; }; } // end namespace scene } // end namespace ue #endif
using System; using System.Threading; namespace SupaCharge.Core.ThreadingAbstractions { public class ResultFuture<T> : IDisposable { public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public void Set(T value) { lock (mLock) { mValue = value; mEvent.Set(); } } public void Failed(Exception exception) { lock (mLock) { mException = exception; mEvent.Set(); } } public T Wait() { return Wait(Timeout.Infinite); } public T Wait(int millisecondsTimeout) { if (mEvent.WaitOne(millisecondsTimeout)) return GetValueOrThrow(); throw new TimeoutException("Timeout waiting for future to resolve"); } protected virtual void Dispose(bool disposing) { if (mEvent == null || !disposing) return; mEvent.Close(); mEvent = null; } private T GetValueOrThrow() { lock (mLock) { if (mException != null) ThrowException(); return mValue; } } private void ThrowException() { throw new FutureException("Error Resolving Future", mException); } private readonly object mLock = new Object(); private ManualResetEvent mEvent = new ManualResetEvent(false); private Exception mException; private T mValue; } }
namespace KelpNet { public class LinearShift : Scheduler { private Real[] ValueRange; private int[] TimeRange; private int t = 0; LinearShift(Real[] valueRange, int[] timeRange, int lastEpoch = 0) : base(lastEpoch) { ValueRange = valueRange; TimeRange = timeRange; } //LinearShiftでは元のパラメータを考慮しない public override Real[] StepFunc(Real[] Params) { t++; Real result; if (t <= TimeRange[0]) { result = ValueRange[0]; } else if (t >= TimeRange[1]) { result = ValueRange[1]; } else { Real rate = (t - TimeRange[0]) / (TimeRange[1] - TimeRange[0]); result = ValueRange[0] + rate * (ValueRange[1] - ValueRange[0]); } Real[] realts = new Real[Params.Length]; for (int i = 0; i < realts.Length; i++) { realts[i] = result; } return realts; } } }
<?php namespace Monolog\Formatter; class ScalarFormatterTest extends \PHPUnit_Framework_TestCase { public function setUp() { $this->formatter = new ScalarFormatter(); } public function buildTrace(\Exception $e) { $data = array(); $trace = $e->getTrace(); foreach ($trace as $frame) { if (isset($frame['file'])) { $data[] = $frame['file'].':'.$frame['line']; } else { $data[] = json_encode($frame); } } return $data; } public function encodeJson($data) { if (version_compare(PHP_VERSION, '5.4.0', '>=')) { return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); } return json_encode($data); } public function testFormat() { $exception = new \Exception('foo'); $formatted = $this->formatter->format(array( 'foo' => 'string', 'bar' => 1, 'baz' => false, 'bam' => array(1, 2, 3), 'bat' => array('foo' => 'bar'), 'bap' => \DateTime::createFromFormat(\DateTime::ISO8601, '1970-01-01T00:00:00+0000'), 'ban' => $exception )); $this->assertSame(array( 'foo' => 'string', 'bar' => 1, 'baz' => false, 'bam' => $this->encodeJson(array(1, 2, 3)), 'bat' => $this->encodeJson(array('foo' => 'bar')), 'bap' => '1970-01-01 00:00:00', 'ban' => $this->encodeJson(array( 'class' => get_class($exception), 'message' => $exception->getMessage(), 'code' => $exception->getCode(), 'file' => $exception->getFile() . ':' . $exception->getLine(), 'trace' => $this->buildTrace($exception) )) ), $formatted); } public function testFormatWithErrorContext() { $context = array('file' => 'foo', 'line' => 1); $formatted = $this->formatter->format(array( 'context' => $context )); $this->assertSame(array( 'context' => $this->encodeJson($context) ), $formatted); } public function testFormatWithExceptionContext() { $exception = new \Exception('foo'); $formatted = $this->formatter->format(array( 'context' => array( 'exception' => $exception ) )); $this->assertSame(array( 'context' => $this->encodeJson(array( 'exception' => array( 'class' => get_class($exception), 'message' => $exception->getMessage(), 'code' => $exception->getCode(), 'file' => $exception->getFile() . ':' . $exception->getLine(), 'trace' => $this->buildTrace($exception) ) )) ), $formatted); } }
var wysihtml5 = { version: "0.3.0", // namespaces commands: {}, dom: {}, quirks: {}, toolbar: {}, lang: {}, selection: {}, views: {}, INVISIBLE_SPACE: "\uFEFF", EMPTY_FUNCTION: function() {}, ELEMENT_NODE: 1, TEXT_NODE: 3, BACKSPACE_KEY: 8, ENTER_KEY: 13, ESCAPE_KEY: 27, SPACE_KEY: 32, DELETE_KEY: 46 };/** * @license Rangy, a cross-browser JavaScript range and selection library * http://code.google.com/p/rangy/ * * Copyright 2011, Tim Down * Licensed under the MIT license. * Version: 1.2.2 * Build date: 13 November 2011 */ window['rangy'] = (function() { var OBJECT = "object", FUNCTION = "function", UNDEFINED = "undefined"; var domRangeProperties = ["startContainer", "startOffset", "endContainer", "endOffset", "collapsed", "commonAncestorContainer", "START_TO_START", "START_TO_END", "END_TO_START", "END_TO_END"]; var domRangeMethods = ["setStart", "setStartBefore", "setStartAfter", "setEnd", "setEndBefore", "setEndAfter", "collapse", "selectNode", "selectNodeContents", "compareBoundaryPoints", "deleteContents", "extractContents", "cloneContents", "insertNode", "surroundContents", "cloneRange", "toString", "detach"]; var textRangeProperties = ["boundingHeight", "boundingLeft", "boundingTop", "boundingWidth", "htmlText", "text"]; // Subset of TextRange's full set of methods that we're interested in var textRangeMethods = ["collapse", "compareEndPoints", "duplicate", "getBookmark", "moveToBookmark", "moveToElementText", "parentElement", "pasteHTML", "select", "setEndPoint", "getBoundingClientRect"]; /*----------------------------------------------------------------------------------------------------------------*/ // Trio of functions taken from Peter Michaux's article: // http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting function isHostMethod(o, p) { var t = typeof o[p]; return t == FUNCTION || (!!(t == OBJECT && o[p])) || t == "unknown"; } function isHostObject(o, p) { return !!(typeof o[p] == OBJECT && o[p]); } function isHostProperty(o, p) { return typeof o[p] != UNDEFINED; } // Creates a convenience function to save verbose repeated calls to tests functions function createMultiplePropertyTest(testFunc) { return function(o, props) { var i = props.length; while (i--) { if (!testFunc(o, props[i])) { return false; } } return true; }; } // Next trio of functions are a convenience to save verbose repeated calls to previous two functions var areHostMethods = createMultiplePropertyTest(isHostMethod); var areHostObjects = createMultiplePropertyTest(isHostObject); var areHostProperties = createMultiplePropertyTest(isHostProperty); function isTextRange(range) { return range && areHostMethods(range, textRangeMethods) && areHostProperties(range, textRangeProperties); } var api = { version: "1.2.2", initialized: false, supported: true, util: { isHostMethod: isHostMethod, isHostObject: isHostObject, isHostProperty: isHostProperty, areHostMethods: areHostMethods, areHostObjects: areHostObjects, areHostProperties: areHostProperties, isTextRange: isTextRange }, features: {}, modules: {}, config: { alertOnWarn: false, preferTextRange: false } }; function fail(reason) { window.alert("Rangy not supported in your browser. Reason: " + reason); api.initialized = true; api.supported = false; } api.fail = fail; function warn(msg) { var warningMessage = "Rangy warning: " + msg; if (api.config.alertOnWarn) { window.alert(warningMessage); } else if (typeof window.console != UNDEFINED && typeof window.console.log != UNDEFINED) { window.console.log(warningMessage); } } api.warn = warn; if ({}.hasOwnProperty) { api.util.extend = function(o, props) { for (var i in props) { if (props.hasOwnProperty(i)) { o[i] = props[i]; } } }; } else { fail("hasOwnProperty not supported"); } var initListeners = []; var moduleInitializers = []; // Initialization function init() { if (api.initialized) { return; } var testRange; var implementsDomRange = false, implementsTextRange = false; // First, perform basic feature tests if (isHostMethod(document, "createRange")) { testRange = document.createRange(); if (areHostMethods(testRange, domRangeMethods) && areHostProperties(testRange, domRangeProperties)) { implementsDomRange = true; } testRange.detach(); } var body = isHostObject(document, "body") ? document.body : document.getElementsByTagName("body")[0]; if (body && isHostMethod(body, "createTextRange")) { testRange = body.createTextRange(); if (isTextRange(testRange)) { implementsTextRange = true; } } if (!implementsDomRange && !implementsTextRange) { fail("Neither Range nor TextRange are implemented"); } api.initialized = true; api.features = { implementsDomRange: implementsDomRange, implementsTextRange: implementsTextRange }; // Initialize modules and call init listeners var allListeners = moduleInitializers.concat(initListeners); for (var i = 0, len = allListeners.length; i < len; ++i) { try { allListeners[i](api); } catch (ex) { if (isHostObject(window, "console") && isHostMethod(window.console, "log")) { window.console.log("Init listener threw an exception. Continuing.", ex); } } } } // Allow external scripts to initialize this library in case it's loaded after the document has loaded api.init = init; // Execute listener immediately if already initialized api.addInitListener = function(listener) { if (api.initialized) { listener(api); } else { initListeners.push(listener); } }; var createMissingNativeApiListeners = []; api.addCreateMissingNativeApiListener = function(listener) { createMissingNativeApiListeners.push(listener); }; function createMissingNativeApi(win) { win = win || window; init(); // Notify listeners for (var i = 0, len = createMissingNativeApiListeners.length; i < len; ++i) { createMissingNativeApiListeners[i](win); } } api.createMissingNativeApi = createMissingNativeApi; /** * @constructor */ function Module(name) { this.name = name; this.initialized = false; this.supported = false; } Module.prototype.fail = function(reason) { this.initialized = true; this.supported = false; throw new Error("Module '" + this.name + "' failed to load: " + reason); }; Module.prototype.warn = function(msg) { api.warn("Module " + this.name + ": " + msg); }; Module.prototype.createError = function(msg) { return new Error("Error in Rangy " + this.name + " module: " + msg); }; api.createModule = function(name, initFunc) { var module = new Module(name); api.modules[name] = module; moduleInitializers.push(function(api) { initFunc(api, module); module.initialized = true; module.supported = true; }); }; api.requireModules = function(modules) { for (var i = 0, len = modules.length, module, moduleName; i < len; ++i) { moduleName = modules[i]; module = api.modules[moduleName]; if (!module || !(module instanceof Module)) { throw new Error("Module '" + moduleName + "' not found"); } if (!module.supported) { throw new Error("Module '" + moduleName + "' not supported"); } } }; /*----------------------------------------------------------------------------------------------------------------*/ // Wait for document to load before running tests var docReady = false; var loadHandler = function(e) { if (!docReady) { docReady = true; if (!api.initialized) { init(); } } }; // Test whether we have window and document objects that we will need if (typeof window == UNDEFINED) { fail("No window found"); return; } if (typeof document == UNDEFINED) { fail("No document found"); return; } if (isHostMethod(document, "addEventListener")) { document.addEventListener("DOMContentLoaded", loadHandler, false); } // Add a fallback in case the DOMContentLoaded event isn't supported if (isHostMethod(window, "addEventListener")) { window.addEventListener("load", loadHandler, false); } else if (isHostMethod(window, "attachEvent")) { window.attachEvent("onload", loadHandler); } else { fail("Window does not have required addEventListener or attachEvent method"); } return api; })(); rangy.createModule("DomUtil", function(api, module) { var UNDEF = "undefined"; var util = api.util; // Perform feature tests if (!util.areHostMethods(document, ["createDocumentFragment", "createElement", "createTextNode"])) { module.fail("document missing a Node creation method"); } if (!util.isHostMethod(document, "getElementsByTagName")) { module.fail("document missing getElementsByTagName method"); } var el = document.createElement("div"); if (!util.areHostMethods(el, ["insertBefore", "appendChild", "cloneNode"] || !util.areHostObjects(el, ["previousSibling", "nextSibling", "childNodes", "parentNode"]))) { module.fail("Incomplete Element implementation"); } // innerHTML is required for Range's createContextualFragment method if (!util.isHostProperty(el, "innerHTML")) { module.fail("Element is missing innerHTML property"); } var textNode = document.createTextNode("test"); if (!util.areHostMethods(textNode, ["splitText", "deleteData", "insertData", "appendData", "cloneNode"] || !util.areHostObjects(el, ["previousSibling", "nextSibling", "childNodes", "parentNode"]) || !util.areHostProperties(textNode, ["data"]))) { module.fail("Incomplete Text Node implementation"); } /*----------------------------------------------------------------------------------------------------------------*/ // Removed use of indexOf because of a bizarre bug in Opera that is thrown in one of the Acid3 tests. I haven't been // able to replicate it outside of the test. The bug is that indexOf returns -1 when called on an Array that // contains just the document as a single element and the value searched for is the document. var arrayContains = /*Array.prototype.indexOf ? function(arr, val) { return arr.indexOf(val) > -1; }:*/ function(arr, val) { var i = arr.length; while (i--) { if (arr[i] === val) { return true; } } return false; }; // Opera 11 puts HTML elements in the null namespace, it seems, and IE 7 has undefined namespaceURI function isHtmlNamespace(node) { var ns; return typeof node.namespaceURI == UNDEF || ((ns = node.namespaceURI) === null || ns == "http://www.w3.org/1999/xhtml"); } function parentElement(node) { var parent = node.parentNode; return (parent.nodeType == 1) ? parent : null; } function getNodeIndex(node) { var i = 0; while( (node = node.previousSibling) ) { i++; } return i; } function getNodeLength(node) { var childNodes; return isCharacterDataNode(node) ? node.length : ((childNodes = node.childNodes) ? childNodes.length : 0); } function getCommonAncestor(node1, node2) { var ancestors = [], n; for (n = node1; n; n = n.parentNode) { ancestors.push(n); } for (n = node2; n; n = n.parentNode) { if (arrayContains(ancestors, n)) { return n; } } return null; } function isAncestorOf(ancestor, descendant, selfIsAncestor) { var n = selfIsAncestor ? descendant : descendant.parentNode; while (n) { if (n === ancestor) { return true; } else { n = n.parentNode; } } return false; } function getClosestAncestorIn(node, ancestor, selfIsAncestor) { var p, n = selfIsAncestor ? node : node.parentNode; while (n) { p = n.parentNode; if (p === ancestor) { return n; } n = p; } return null; } function isCharacterDataNode(node) { var t = node.nodeType; return t == 3 || t == 4 || t == 8 ; // Text, CDataSection or Comment } function insertAfter(node, precedingNode) { var nextNode = precedingNode.nextSibling, parent = precedingNode.parentNode; if (nextNode) { parent.insertBefore(node, nextNode); } else { parent.appendChild(node); } return node; } // Note that we cannot use splitText() because it is bugridden in IE 9. function splitDataNode(node, index) { var newNode = node.cloneNode(false); newNode.deleteData(0, index); node.deleteData(index, node.length - index); insertAfter(newNode, node); return newNode; } function getDocument(node) { if (node.nodeType == 9) { return node; } else if (typeof node.ownerDocument != UNDEF) { return node.ownerDocument; } else if (typeof node.document != UNDEF) { return node.document; } else if (node.parentNode) { return getDocument(node.parentNode); } else { throw new Error("getDocument: no document found for node"); } } function getWindow(node) { var doc = getDocument(node); if (typeof doc.defaultView != UNDEF) { return doc.defaultView; } else if (typeof doc.parentWindow != UNDEF) { return doc.parentWindow; } else { throw new Error("Cannot get a window object for node"); } } function getIframeDocument(iframeEl) { if (typeof iframeEl.contentDocument != UNDEF) { return iframeEl.contentDocument; } else if (typeof iframeEl.contentWindow != UNDEF) { return iframeEl.contentWindow.document; } else { throw new Error("getIframeWindow: No Document object found for iframe element"); } } function getIframeWindow(iframeEl) { if (typeof iframeEl.contentWindow != UNDEF) { return iframeEl.contentWindow; } else if (typeof iframeEl.contentDocument != UNDEF) { return iframeEl.contentDocument.defaultView; } else { throw new Error("getIframeWindow: No Window object found for iframe element"); } } function getBody(doc) { return util.isHostObject(doc, "body") ? doc.body : doc.getElementsByTagName("body")[0]; } function getRootContainer(node) { var parent; while ( (parent = node.parentNode) ) { node = parent; } return node; } function comparePoints(nodeA, offsetA, nodeB, offsetB) { // See http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Comparing var nodeC, root, childA, childB, n; if (nodeA == nodeB) { // Case 1: nodes are the same return offsetA === offsetB ? 0 : (offsetA < offsetB) ? -1 : 1; } else if ( (nodeC = getClosestAncestorIn(nodeB, nodeA, true)) ) { // Case 2: node C (container B or an ancestor) is a child node of A return offsetA <= getNodeIndex(nodeC) ? -1 : 1; } else if ( (nodeC = getClosestAncestorIn(nodeA, nodeB, true)) ) { // Case 3: node C (container A or an ancestor) is a child node of B return getNodeIndex(nodeC) < offsetB ? -1 : 1; } else { // Case 4: containers are siblings or descendants of siblings root = getCommonAncestor(nodeA, nodeB); childA = (nodeA === root) ? root : getClosestAncestorIn(nodeA, root, true); childB = (nodeB === root) ? root : getClosestAncestorIn(nodeB, root, true); if (childA === childB) { // This shouldn't be possible throw new Error("comparePoints got to case 4 and childA and childB are the same!"); } else { n = root.firstChild; while (n) { if (n === childA) { return -1; } else if (n === childB) { return 1; } n = n.nextSibling; } throw new Error("Should not be here!"); } } } function fragmentFromNodeChildren(node) { var fragment = getDocument(node).createDocumentFragment(), child; while ( (child = node.firstChild) ) { fragment.appendChild(child); } return fragment; } function inspectNode(node) { if (!node) { return "[No node]"; } if (isCharacterDataNode(node)) { return '"' + node.data + '"'; } else if (node.nodeType == 1) { var idAttr = node.id ? ' id="' + node.id + '"' : ""; return "<" + node.nodeName + idAttr + ">[" + node.childNodes.length + "]"; } else { return node.nodeName; } } /** * @constructor */ function NodeIterator(root) { this.root = root; this._next = root; } NodeIterator.prototype = { _current: null, hasNext: function() { return !!this._next; }, next: function() { var n = this._current = this._next; var child, next; if (this._current) { child = n.firstChild; if (child) { this._next = child; } else { next = null; while ((n !== this.root) && !(next = n.nextSibling)) { n = n.parentNode; } this._next = next; } } return this._current; }, detach: function() { this._current = this._next = this.root = null; } }; function createIterator(root) { return new NodeIterator(root); } /** * @constructor */ function DomPosition(node, offset) { this.node = node; this.offset = offset; } DomPosition.prototype = { equals: function(pos) { return this.node === pos.node & this.offset == pos.offset; }, inspect: function() { return "[DomPosition(" + inspectNode(this.node) + ":" + this.offset + ")]"; } }; /** * @constructor */ function DOMException(codeName) { this.code = this[codeName]; this.codeName = codeName; this.message = "DOMException: " + this.codeName; } DOMException.prototype = { INDEX_SIZE_ERR: 1, HIERARCHY_REQUEST_ERR: 3, WRONG_DOCUMENT_ERR: 4, NO_MODIFICATION_ALLOWED_ERR: 7, NOT_FOUND_ERR: 8, NOT_SUPPORTED_ERR: 9, INVALID_STATE_ERR: 11 }; DOMException.prototype.toString = function() { return this.message; }; api.dom = { arrayContains: arrayContains, isHtmlNamespace: isHtmlNamespace, parentElement: parentElement, getNodeIndex: getNodeIndex, getNodeLength: getNodeLength, getCommonAncestor: getCommonAncestor, isAncestorOf: isAncestorOf, getClosestAncestorIn: getClosestAncestorIn, isCharacterDataNode: isCharacterDataNode, insertAfter: insertAfter, splitDataNode: splitDataNode, getDocument: getDocument, getWindow: getWindow, getIframeWindow: getIframeWindow, getIframeDocument: getIframeDocument, getBody: getBody, getRootContainer: getRootContainer, comparePoints: comparePoints, inspectNode: inspectNode, fragmentFromNodeChildren: fragmentFromNodeChildren, createIterator: createIterator, DomPosition: DomPosition }; api.DOMException = DOMException; });rangy.createModule("DomRange", function(api, module) { api.requireModules( ["DomUtil"] ); var dom = api.dom; var DomPosition = dom.DomPosition; var DOMException = api.DOMException; /*----------------------------------------------------------------------------------------------------------------*/ // Utility functions function isNonTextPartiallySelected(node, range) { return (node.nodeType != 3) && (dom.isAncestorOf(node, range.startContainer, true) || dom.isAncestorOf(node, range.endContainer, true)); } function getRangeDocument(range) { return dom.getDocument(range.startContainer); } function dispatchEvent(range, type, args) { var listeners = range._listeners[type]; if (listeners) { for (var i = 0, len = listeners.length; i < len; ++i) { listeners[i].call(range, {target: range, args: args}); } } } function getBoundaryBeforeNode(node) { return new DomPosition(node.parentNode, dom.getNodeIndex(node)); } function getBoundaryAfterNode(node) { return new DomPosition(node.parentNode, dom.getNodeIndex(node) + 1); } function insertNodeAtPosition(node, n, o) { var firstNodeInserted = node.nodeType == 11 ? node.firstChild : node; if (dom.isCharacterDataNode(n)) { if (o == n.length) { dom.insertAfter(node, n); } else { n.parentNode.insertBefore(node, o == 0 ? n : dom.splitDataNode(n, o)); } } else if (o >= n.childNodes.length) { n.appendChild(node); } else { n.insertBefore(node, n.childNodes[o]); } return firstNodeInserted; } function cloneSubtree(iterator) { var partiallySelected; for (var node, frag = getRangeDocument(iterator.range).createDocumentFragment(), subIterator; node = iterator.next(); ) { partiallySelected = iterator.isPartiallySelectedSubtree(); node = node.cloneNode(!partiallySelected); if (partiallySelected) { subIterator = iterator.getSubtreeIterator(); node.appendChild(cloneSubtree(subIterator)); subIterator.detach(true); } if (node.nodeType == 10) { // DocumentType throw new DOMException("HIERARCHY_REQUEST_ERR"); } frag.appendChild(node); } return frag; } function iterateSubtree(rangeIterator, func, iteratorState) { var it, n; iteratorState = iteratorState || { stop: false }; for (var node, subRangeIterator; node = rangeIterator.next(); ) { //log.debug("iterateSubtree, partially selected: " + rangeIterator.isPartiallySelectedSubtree(), nodeToString(node)); if (rangeIterator.isPartiallySelectedSubtree()) { // The node is partially selected by the Range, so we can use a new RangeIterator on the portion of the // node selected by the Range. if (func(node) === false) { iteratorState.stop = true; return; } else { subRangeIterator = rangeIterator.getSubtreeIterator(); iterateSubtree(subRangeIterator, func, iteratorState); subRangeIterator.detach(true); if (iteratorState.stop) { return; } } } else { // The whole node is selected, so we can use efficient DOM iteration to iterate over the node and its // descendant it = dom.createIterator(node); while ( (n = it.next()) ) { if (func(n) === false) { iteratorState.stop = true; return; } } } } } function deleteSubtree(iterator) { var subIterator; while (iterator.next()) { if (iterator.isPartiallySelectedSubtree()) { subIterator = iterator.getSubtreeIterator(); deleteSubtree(subIterator); subIterator.detach(true); } else { iterator.remove(); } } } function extractSubtree(iterator) { for (var node, frag = getRangeDocument(iterator.range).createDocumentFragment(), subIterator; node = iterator.next(); ) { if (iterator.isPartiallySelectedSubtree()) { node = node.cloneNode(false); subIterator = iterator.getSubtreeIterator(); node.appendChild(extractSubtree(subIterator)); subIterator.detach(true); } else { iterator.remove(); } if (node.nodeType == 10) { // DocumentType throw new DOMException("HIERARCHY_REQUEST_ERR"); } frag.appendChild(node); } return frag; } function getNodesInRange(range, nodeTypes, filter) { //log.info("getNodesInRange, " + nodeTypes.join(",")); var filterNodeTypes = !!(nodeTypes && nodeTypes.length), regex; var filterExists = !!filter; if (filterNodeTypes) { regex = new RegExp("^(" + nodeTypes.join("|") + ")$"); } var nodes = []; iterateSubtree(new RangeIterator(range, false), function(node) { if ((!filterNodeTypes || regex.test(node.nodeType)) && (!filterExists || filter(node))) { nodes.push(node); } }); return nodes; } function inspect(range) { var name = (typeof range.getName == "undefined") ? "Range" : range.getName(); return "[" + name + "(" + dom.inspectNode(range.startContainer) + ":" + range.startOffset + ", " + dom.inspectNode(range.endContainer) + ":" + range.endOffset + ")]"; } /*----------------------------------------------------------------------------------------------------------------*/ // RangeIterator code partially borrows from IERange by Tim Ryan (http://github.com/timcameronryan/IERange) /** * @constructor */ function RangeIterator(range, clonePartiallySelectedTextNodes) { this.range = range; this.clonePartiallySelectedTextNodes = clonePartiallySelectedTextNodes; if (!range.collapsed) { this.sc = range.startContainer; this.so = range.startOffset; this.ec = range.endContainer; this.eo = range.endOffset; var root = range.commonAncestorContainer; if (this.sc === this.ec && dom.isCharacterDataNode(this.sc)) { this.isSingleCharacterDataNode = true; this._first = this._last = this._next = this.sc; } else { this._first = this._next = (this.sc === root && !dom.isCharacterDataNode(this.sc)) ? this.sc.childNodes[this.so] : dom.getClosestAncestorIn(this.sc, root, true); this._last = (this.ec === root && !dom.isCharacterDataNode(this.ec)) ? this.ec.childNodes[this.eo - 1] : dom.getClosestAncestorIn(this.ec, root, true); } } } RangeIterator.prototype = { _current: null, _next: null, _first: null, _last: null, isSingleCharacterDataNode: false, reset: function() { this._current = null; this._next = this._first; }, hasNext: function() { return !!this._next; }, next: function() { // Move to next node var current = this._current = this._next; if (current) { this._next = (current !== this._last) ? current.nextSibling : null; // Check for partially selected text nodes if (dom.isCharacterDataNode(current) && this.clonePartiallySelectedTextNodes) { if (current === this.ec) { (current = current.cloneNode(true)).deleteData(this.eo, current.length - this.eo); } if (this._current === this.sc) { (current = current.cloneNode(true)).deleteData(0, this.so); } } } return current; }, remove: function() { var current = this._current, start, end; if (dom.isCharacterDataNode(current) && (current === this.sc || current === this.ec)) { start = (current === this.sc) ? this.so : 0; end = (current === this.ec) ? this.eo : current.length; if (start != end) { current.deleteData(start, end - start); } } else { if (current.parentNode) { current.parentNode.removeChild(current); } else { } } }, // Checks if the current node is partially selected isPartiallySelectedSubtree: function() { var current = this._current; return isNonTextPartiallySelected(current, this.range); }, getSubtreeIterator: function() { var subRange; if (this.isSingleCharacterDataNode) { subRange = this.range.cloneRange(); subRange.collapse(); } else { subRange = new Range(getRangeDocument(this.range)); var current = this._current; var startContainer = current, startOffset = 0, endContainer = current, endOffset = dom.getNodeLength(current); if (dom.isAncestorOf(current, this.sc, true)) { startContainer = this.sc; startOffset = this.so; } if (dom.isAncestorOf(current, this.ec, true)) { endContainer = this.ec; endOffset = this.eo; } updateBoundaries(subRange, startContainer, startOffset, endContainer, endOffset); } return new RangeIterator(subRange, this.clonePartiallySelectedTextNodes); }, detach: function(detachRange) { if (detachRange) { this.range.detach(); } this.range = this._current = this._next = this._first = this._last = this.sc = this.so = this.ec = this.eo = null; } }; /*----------------------------------------------------------------------------------------------------------------*/ // Exceptions /** * @constructor */ function RangeException(codeName) { this.code = this[codeName]; this.codeName = codeName; this.message = "RangeException: " + this.codeName; } RangeException.prototype = { BAD_BOUNDARYPOINTS_ERR: 1, INVALID_NODE_TYPE_ERR: 2 }; RangeException.prototype.toString = function() { return this.message; }; /*----------------------------------------------------------------------------------------------------------------*/ /** * Currently iterates through all nodes in the range on creation until I think of a decent way to do it * TODO: Look into making this a proper iterator, not requiring preloading everything first * @constructor */ function RangeNodeIterator(range, nodeTypes, filter) { this.nodes = getNodesInRange(range, nodeTypes, filter); this._next = this.nodes[0]; this._position = 0; } RangeNodeIterator.prototype = { _current: null, hasNext: function() { return !!this._next; }, next: function() { this._current = this._next; this._next = this.nodes[ ++this._position ]; return this._current; }, detach: function() { this._current = this._next = this.nodes = null; } }; var beforeAfterNodeTypes = [1, 3, 4, 5, 7, 8, 10]; var rootContainerNodeTypes = [2, 9, 11]; var readonlyNodeTypes = [5, 6, 10, 12]; var insertableNodeTypes = [1, 3, 4, 5, 7, 8, 10, 11]; var surroundNodeTypes = [1, 3, 4, 5, 7, 8]; function createAncestorFinder(nodeTypes) { return function(node, selfIsAncestor) { var t, n = selfIsAncestor ? node : node.parentNode; while (n) { t = n.nodeType; if (dom.arrayContains(nodeTypes, t)) { return n; } n = n.parentNode; } return null; }; } var getRootContainer = dom.getRootContainer; var getDocumentOrFragmentContainer = createAncestorFinder( [9, 11] ); var getReadonlyAncestor = createAncestorFinder(readonlyNodeTypes); var getDocTypeNotationEntityAncestor = createAncestorFinder( [6, 10, 12] ); function assertNoDocTypeNotationEntityAncestor(node, allowSelf) { if (getDocTypeNotationEntityAncestor(node, allowSelf)) { throw new RangeException("INVALID_NODE_TYPE_ERR"); } } function assertNotDetached(range) { if (!range.startContainer) { throw new DOMException("INVALID_STATE_ERR"); } } function assertValidNodeType(node, invalidTypes) { if (!dom.arrayContains(invalidTypes, node.nodeType)) { throw new RangeException("INVALID_NODE_TYPE_ERR"); } } function assertValidOffset(node, offset) { if (offset < 0 || offset > (dom.isCharacterDataNode(node) ? node.length : node.childNodes.length)) { throw new DOMException("INDEX_SIZE_ERR"); } } function assertSameDocumentOrFragment(node1, node2) { if (getDocumentOrFragmentContainer(node1, true) !== getDocumentOrFragmentContainer(node2, true)) { throw new DOMException("WRONG_DOCUMENT_ERR"); } } function assertNodeNotReadOnly(node) { if (getReadonlyAncestor(node, true)) { throw new DOMException("NO_MODIFICATION_ALLOWED_ERR"); } } function assertNode(node, codeName) { if (!node) { throw new DOMException(codeName); } } function isOrphan(node) { return !dom.arrayContains(rootContainerNodeTypes, node.nodeType) && !getDocumentOrFragmentContainer(node, true); } function isValidOffset(node, offset) { return offset <= (dom.isCharacterDataNode(node) ? node.length : node.childNodes.length); } function assertRangeValid(range) { assertNotDetached(range); if (isOrphan(range.startContainer) || isOrphan(range.endContainer) || !isValidOffset(range.startContainer, range.startOffset) || !isValidOffset(range.endContainer, range.endOffset)) { throw new Error("Range error: Range is no longer valid after DOM mutation (" + range.inspect() + ")"); } } /*----------------------------------------------------------------------------------------------------------------*/ // Test the browser's innerHTML support to decide how to implement createContextualFragment var styleEl = document.createElement("style"); var htmlParsingConforms = false; try { styleEl.innerHTML = "<b>x</b>"; htmlParsingConforms = (styleEl.firstChild.nodeType == 3); // Opera incorrectly creates an element node } catch (e) { // IE 6 and 7 throw } api.features.htmlParsingConforms = htmlParsingConforms; var createContextualFragment = htmlParsingConforms ? // Implementation as per HTML parsing spec, trusting in the browser's implementation of innerHTML. See // discussion and base code for this implementation at issue 67. // Spec: http://html5.org/specs/dom-parsing.html#extensions-to-the-range-interface // Thanks to Aleks Williams. function(fragmentStr) { // "Let node the context object's start's node." var node = this.startContainer; var doc = dom.getDocument(node); // "If the context object's start's node is null, raise an INVALID_STATE_ERR // exception and abort these steps." if (!node) { throw new DOMException("INVALID_STATE_ERR"); } // "Let element be as follows, depending on node's interface:" // Document, Document Fragment: null var el = null; // "Element: node" if (node.nodeType == 1) { el = node; // "Text, Comment: node's parentElement" } else if (dom.isCharacterDataNode(node)) { el = dom.parentElement(node); } // "If either element is null or element's ownerDocument is an HTML document // and element's local name is "html" and element's namespace is the HTML // namespace" if (el === null || ( el.nodeName == "HTML" && dom.isHtmlNamespace(dom.getDocument(el).documentElement) && dom.isHtmlNamespace(el) )) { // "let element be a new Element with "body" as its local name and the HTML // namespace as its namespace."" el = doc.createElement("body"); } else { el = el.cloneNode(false); } // "If the node's document is an HTML document: Invoke the HTML fragment parsing algorithm." // "If the node's document is an XML document: Invoke the XML fragment parsing algorithm." // "In either case, the algorithm must be invoked with fragment as the input // and element as the context element." el.innerHTML = fragmentStr; // "If this raises an exception, then abort these steps. Otherwise, let new // children be the nodes returned." // "Let fragment be a new DocumentFragment." // "Append all new children to fragment." // "Return fragment." return dom.fragmentFromNodeChildren(el); } : // In this case, innerHTML cannot be trusted, so fall back to a simpler, non-conformant implementation that // previous versions of Rangy used (with the exception of using a body element rather than a div) function(fragmentStr) { assertNotDetached(this); var doc = getRangeDocument(this); var el = doc.createElement("body"); el.innerHTML = fragmentStr; return dom.fragmentFromNodeChildren(el); }; /*----------------------------------------------------------------------------------------------------------------*/ var rangeProperties = ["startContainer", "startOffset", "endContainer", "endOffset", "collapsed", "commonAncestorContainer"]; var s2s = 0, s2e = 1, e2e = 2, e2s = 3; var n_b = 0, n_a = 1, n_b_a = 2, n_i = 3; function RangePrototype() {} RangePrototype.prototype = { attachListener: function(type, listener) { this._listeners[type].push(listener); }, compareBoundaryPoints: function(how, range) { assertRangeValid(this); assertSameDocumentOrFragment(this.startContainer, range.startContainer); var nodeA, offsetA, nodeB, offsetB; var prefixA = (how == e2s || how == s2s) ? "start" : "end"; var prefixB = (how == s2e || how == s2s) ? "start" : "end"; nodeA = this[prefixA + "Container"]; offsetA = this[prefixA + "Offset"]; nodeB = range[prefixB + "Container"]; offsetB = range[prefixB + "Offset"]; return dom.comparePoints(nodeA, offsetA, nodeB, offsetB); }, insertNode: function(node) { assertRangeValid(this); assertValidNodeType(node, insertableNodeTypes); assertNodeNotReadOnly(this.startContainer); if (dom.isAncestorOf(node, this.startContainer, true)) { throw new DOMException("HIERARCHY_REQUEST_ERR"); } // No check for whether the container of the start of the Range is of a type that does not allow // children of the type of node: the browser's DOM implementation should do this for us when we attempt // to add the node var firstNodeInserted = insertNodeAtPosition(node, this.startContainer, this.startOffset); this.setStartBefore(firstNodeInserted); }, cloneContents: function() { assertRangeValid(this); var clone, frag; if (this.collapsed) { return getRangeDocument(this).createDocumentFragment(); } else { if (this.startContainer === this.endContainer && dom.isCharacterDataNode(this.startContainer)) { clone = this.startContainer.cloneNode(true); clone.data = clone.data.slice(this.startOffset, this.endOffset); frag = getRangeDocument(this).createDocumentFragment(); frag.appendChild(clone); return frag; } else { var iterator = new RangeIterator(this, true); clone = cloneSubtree(iterator); iterator.detach(); } return clone; } }, canSurroundContents: function() { assertRangeValid(this); assertNodeNotReadOnly(this.startContainer); assertNodeNotReadOnly(this.endContainer); // Check if the contents can be surrounded. Specifically, this means whether the range partially selects // no non-text nodes. var iterator = new RangeIterator(this, true); var boundariesInvalid = (iterator._first && (isNonTextPartiallySelected(iterator._first, this)) || (iterator._last && isNonTextPartiallySelected(iterator._last, this))); iterator.detach(); return !boundariesInvalid; }, surroundContents: function(node) { assertValidNodeType(node, surroundNodeTypes); if (!this.canSurroundContents()) { throw new RangeException("BAD_BOUNDARYPOINTS_ERR"); } // Extract the contents var content = this.extractContents(); // Clear the children of the node if (node.hasChildNodes()) { while (node.lastChild) { node.removeChild(node.lastChild); } } // Insert the new node and add the extracted contents insertNodeAtPosition(node, this.startContainer, this.startOffset); node.appendChild(content); this.selectNode(node); }, cloneRange: function() { assertRangeValid(this); var range = new Range(getRangeDocument(this)); var i = rangeProperties.length, prop; while (i--) { prop = rangeProperties[i]; range[prop] = this[prop]; } return range; }, toString: function() { assertRangeValid(this); var sc = this.startContainer; if (sc === this.endContainer && dom.isCharacterDataNode(sc)) { return (sc.nodeType == 3 || sc.nodeType == 4) ? sc.data.slice(this.startOffset, this.endOffset) : ""; } else { var textBits = [], iterator = new RangeIterator(this, true); iterateSubtree(iterator, function(node) { // Accept only text or CDATA nodes, not comments if (node.nodeType == 3 || node.nodeType == 4) { textBits.push(node.data); } }); iterator.detach(); return textBits.join(""); } }, // The methods below are all non-standard. The following batch were introduced by Mozilla but have since // been removed from Mozilla. compareNode: function(node) { assertRangeValid(this); var parent = node.parentNode; var nodeIndex = dom.getNodeIndex(node); if (!parent) { throw new DOMException("NOT_FOUND_ERR"); } var startComparison = this.comparePoint(parent, nodeIndex), endComparison = this.comparePoint(parent, nodeIndex + 1); if (startComparison < 0) { // Node starts before return (endComparison > 0) ? n_b_a : n_b; } else { return (endComparison > 0) ? n_a : n_i; } }, comparePoint: function(node, offset) { assertRangeValid(this); assertNode(node, "HIERARCHY_REQUEST_ERR"); assertSameDocumentOrFragment(node, this.startContainer); if (dom.comparePoints(node, offset, this.startContainer, this.startOffset) < 0) { return -1; } else if (dom.comparePoints(node, offset, this.endContainer, this.endOffset) > 0) { return 1; } return 0; }, createContextualFragment: createContextualFragment, toHtml: function() { assertRangeValid(this); var container = getRangeDocument(this).createElement("div"); container.appendChild(this.cloneContents()); return container.innerHTML; }, // touchingIsIntersecting determines whether this method considers a node that borders a range intersects // with it (as in WebKit) or not (as in Gecko pre-1.9, and the default) intersectsNode: function(node, touchingIsIntersecting) { assertRangeValid(this); assertNode(node, "NOT_FOUND_ERR"); if (dom.getDocument(node) !== getRangeDocument(this)) { return false; } var parent = node.parentNode, offset = dom.getNodeIndex(node); assertNode(parent, "NOT_FOUND_ERR"); var startComparison = dom.comparePoints(parent, offset, this.endContainer, this.endOffset), endComparison = dom.comparePoints(parent, offset + 1, this.startContainer, this.startOffset); return touchingIsIntersecting ? startComparison <= 0 && endComparison >= 0 : startComparison < 0 && endComparison > 0; }, isPointInRange: function(node, offset) { assertRangeValid(this); assertNode(node, "HIERARCHY_REQUEST_ERR"); assertSameDocumentOrFragment(node, this.startContainer); return (dom.comparePoints(node, offset, this.startContainer, this.startOffset) >= 0) && (dom.comparePoints(node, offset, this.endContainer, this.endOffset) <= 0); }, // The methods below are non-standard and invented by me. // Sharing a boundary start-to-end or end-to-start does not count as intersection. intersectsRange: function(range, touchingIsIntersecting) { assertRangeValid(this); if (getRangeDocument(range) != getRangeDocument(this)) { throw new DOMException("WRONG_DOCUMENT_ERR"); } var startComparison = dom.comparePoints(this.startContainer, this.startOffset, range.endContainer, range.endOffset), endComparison = dom.comparePoints(this.endContainer, this.endOffset, range.startContainer, range.startOffset); return touchingIsIntersecting ? startComparison <= 0 && endComparison >= 0 : startComparison < 0 && endComparison > 0; }, intersection: function(range) { if (this.intersectsRange(range)) { var startComparison = dom.comparePoints(this.startContainer, this.startOffset, range.startContainer, range.startOffset), endComparison = dom.comparePoints(this.endContainer, this.endOffset, range.endContainer, range.endOffset); var intersectionRange = this.cloneRange(); if (startComparison == -1) { intersectionRange.setStart(range.startContainer, range.startOffset); } if (endComparison == 1) { intersectionRange.setEnd(range.endContainer, range.endOffset); } return intersectionRange; } return null; }, union: function(range) { if (this.intersectsRange(range, true)) { var unionRange = this.cloneRange(); if (dom.comparePoints(range.startContainer, range.startOffset, this.startContainer, this.startOffset) == -1) { unionRange.setStart(range.startContainer, range.startOffset); } if (dom.comparePoints(range.endContainer, range.endOffset, this.endContainer, this.endOffset) == 1) { unionRange.setEnd(range.endContainer, range.endOffset); } return unionRange; } else { throw new RangeException("Ranges do not intersect"); } }, containsNode: function(node, allowPartial) { if (allowPartial) { return this.intersectsNode(node, false); } else { return this.compareNode(node) == n_i; } }, containsNodeContents: function(node) { return this.comparePoint(node, 0) >= 0 && this.comparePoint(node, dom.getNodeLength(node)) <= 0; }, containsRange: function(range) { return this.intersection(range).equals(range); }, containsNodeText: function(node) { var nodeRange = this.cloneRange(); nodeRange.selectNode(node); var textNodes = nodeRange.getNodes([3]); if (textNodes.length > 0) { nodeRange.setStart(textNodes[0], 0); var lastTextNode = textNodes.pop(); nodeRange.setEnd(lastTextNode, lastTextNode.length); var contains = this.containsRange(nodeRange); nodeRange.detach(); return contains; } else { return this.containsNodeContents(node); } }, createNodeIterator: function(nodeTypes, filter) { assertRangeValid(this); return new RangeNodeIterator(this, nodeTypes, filter); }, getNodes: function(nodeTypes, filter) { assertRangeValid(this); return getNodesInRange(this, nodeTypes, filter); }, getDocument: function() { return getRangeDocument(this); }, collapseBefore: function(node) { assertNotDetached(this); this.setEndBefore(node); this.collapse(false); }, collapseAfter: function(node) { assertNotDetached(this); this.setStartAfter(node); this.collapse(true); }, getName: function() { return "DomRange"; }, equals: function(range) { return Range.rangesEqual(this, range); }, inspect: function() { return inspect(this); } }; function copyComparisonConstantsToObject(obj) { obj.START_TO_START = s2s; obj.START_TO_END = s2e; obj.END_TO_END = e2e; obj.END_TO_START = e2s; obj.NODE_BEFORE = n_b; obj.NODE_AFTER = n_a; obj.NODE_BEFORE_AND_AFTER = n_b_a; obj.NODE_INSIDE = n_i; } function copyComparisonConstants(constructor) { copyComparisonConstantsToObject(constructor); copyComparisonConstantsToObject(constructor.prototype); } function createRangeContentRemover(remover, boundaryUpdater) { return function() { assertRangeValid(this); var sc = this.startContainer, so = this.startOffset, root = this.commonAncestorContainer; var iterator = new RangeIterator(this, true); // Work out where to position the range after content removal var node, boundary; if (sc !== root) { node = dom.getClosestAncestorIn(sc, root, true); boundary = getBoundaryAfterNode(node); sc = boundary.node; so = boundary.offset; } // Check none of the range is read-only iterateSubtree(iterator, assertNodeNotReadOnly); iterator.reset(); // Remove the content var returnValue = remover(iterator); iterator.detach(); // Move to the new position boundaryUpdater(this, sc, so, sc, so); return returnValue; }; } function createPrototypeRange(constructor, boundaryUpdater, detacher) { function createBeforeAfterNodeSetter(isBefore, isStart) { return function(node) { assertNotDetached(this); assertValidNodeType(node, beforeAfterNodeTypes); assertValidNodeType(getRootContainer(node), rootContainerNodeTypes); var boundary = (isBefore ? getBoundaryBeforeNode : getBoundaryAfterNode)(node); (isStart ? setRangeStart : setRangeEnd)(this, boundary.node, boundary.offset); }; } function setRangeStart(range, node, offset) { var ec = range.endContainer, eo = range.endOffset; if (node !== range.startContainer || offset !== range.startOffset) { // Check the root containers of the range and the new boundary, and also check whether the new boundary // is after the current end. In either case, collapse the range to the new position if (getRootContainer(node) != getRootContainer(ec) || dom.comparePoints(node, offset, ec, eo) == 1) { ec = node; eo = offset; } boundaryUpdater(range, node, offset, ec, eo); } } function setRangeEnd(range, node, offset) { var sc = range.startContainer, so = range.startOffset; if (node !== range.endContainer || offset !== range.endOffset) { // Check the root containers of the range and the new boundary, and also check whether the new boundary // is after the current end. In either case, collapse the range to the new position if (getRootContainer(node) != getRootContainer(sc) || dom.comparePoints(node, offset, sc, so) == -1) { sc = node; so = offset; } boundaryUpdater(range, sc, so, node, offset); } } function setRangeStartAndEnd(range, node, offset) { if (node !== range.startContainer || offset !== range.startOffset || node !== range.endContainer || offset !== range.endOffset) { boundaryUpdater(range, node, offset, node, offset); } } constructor.prototype = new RangePrototype(); api.util.extend(constructor.prototype, { setStart: function(node, offset) { assertNotDetached(this); assertNoDocTypeNotationEntityAncestor(node, true); assertValidOffset(node, offset); setRangeStart(this, node, offset); }, setEnd: function(node, offset) { assertNotDetached(this); assertNoDocTypeNotationEntityAncestor(node, true); assertValidOffset(node, offset); setRangeEnd(this, node, offset); }, setStartBefore: createBeforeAfterNodeSetter(true, true), setStartAfter: createBeforeAfterNodeSetter(false, true), setEndBefore: createBeforeAfterNodeSetter(true, false), setEndAfter: createBeforeAfterNodeSetter(false, false), collapse: function(isStart) { assertRangeValid(this); if (isStart) { boundaryUpdater(this, this.startContainer, this.startOffset, this.startContainer, this.startOffset); } else { boundaryUpdater(this, this.endContainer, this.endOffset, this.endContainer, this.endOffset); } }, selectNodeContents: function(node) { // This doesn't seem well specified: the spec talks only about selecting the node's contents, which // could be taken to mean only its children. However, browsers implement this the same as selectNode for // text nodes, so I shall do likewise assertNotDetached(this); assertNoDocTypeNotationEntityAncestor(node, true); boundaryUpdater(this, node, 0, node, dom.getNodeLength(node)); }, selectNode: function(node) { assertNotDetached(this); assertNoDocTypeNotationEntityAncestor(node, false); assertValidNodeType(node, beforeAfterNodeTypes); var start = getBoundaryBeforeNode(node), end = getBoundaryAfterNode(node); boundaryUpdater(this, start.node, start.offset, end.node, end.offset); }, extractContents: createRangeContentRemover(extractSubtree, boundaryUpdater), deleteContents: createRangeContentRemover(deleteSubtree, boundaryUpdater), canSurroundContents: function() { assertRangeValid(this); assertNodeNotReadOnly(this.startContainer); assertNodeNotReadOnly(this.endContainer); // Check if the contents can be surrounded. Specifically, this means whether the range partially selects // no non-text nodes. var iterator = new RangeIterator(this, true); var boundariesInvalid = (iterator._first && (isNonTextPartiallySelected(iterator._first, this)) || (iterator._last && isNonTextPartiallySelected(iterator._last, this))); iterator.detach(); return !boundariesInvalid; }, detach: function() { detacher(this); }, splitBoundaries: function() { assertRangeValid(this); var sc = this.startContainer, so = this.startOffset, ec = this.endContainer, eo = this.endOffset; var startEndSame = (sc === ec); if (dom.isCharacterDataNode(ec) && eo > 0 && eo < ec.length) { dom.splitDataNode(ec, eo); } if (dom.isCharacterDataNode(sc) && so > 0 && so < sc.length) { sc = dom.splitDataNode(sc, so); if (startEndSame) { eo -= so; ec = sc; } else if (ec == sc.parentNode && eo >= dom.getNodeIndex(sc)) { eo++; } so = 0; } boundaryUpdater(this, sc, so, ec, eo); }, normalizeBoundaries: function() { assertRangeValid(this); var sc = this.startContainer, so = this.startOffset, ec = this.endContainer, eo = this.endOffset; var mergeForward = function(node) { var sibling = node.nextSibling; if (sibling && sibling.nodeType == node.nodeType) { ec = node; eo = node.length; node.appendData(sibling.data); sibling.parentNode.removeChild(sibling); } }; var mergeBackward = function(node) { var sibling = node.previousSibling; if (sibling && sibling.nodeType == node.nodeType) { sc = node; var nodeLength = node.length; so = sibling.length; node.insertData(0, sibling.data); sibling.parentNode.removeChild(sibling); if (sc == ec) { eo += so; ec = sc; } else if (ec == node.parentNode) { var nodeIndex = dom.getNodeIndex(node); if (eo == nodeIndex) { ec = node; eo = nodeLength; } else if (eo > nodeIndex) { eo--; } } } }; var normalizeStart = true; if (dom.isCharacterDataNode(ec)) { if (ec.length == eo) { mergeForward(ec); } } else { if (eo > 0) { var endNode = ec.childNodes[eo - 1]; if (endNode && dom.isCharacterDataNode(endNode)) { mergeForward(endNode); } } normalizeStart = !this.collapsed; } if (normalizeStart) { if (dom.isCharacterDataNode(sc)) { if (so == 0) { mergeBackward(sc); } } else { if (so < sc.childNodes.length) { var startNode = sc.childNodes[so]; if (startNode && dom.isCharacterDataNode(startNode)) { mergeBackward(startNode); } } } } else { sc = ec; so = eo; } boundaryUpdater(this, sc, so, ec, eo); }, collapseToPoint: function(node, offset) { assertNotDetached(this); assertNoDocTypeNotationEntityAncestor(node, true); assertValidOffset(node, offset); setRangeStartAndEnd(this, node, offset); } }); copyComparisonConstants(constructor); } /*----------------------------------------------------------------------------------------------------------------*/ // Updates commonAncestorContainer and collapsed after boundary change function updateCollapsedAndCommonAncestor(range) { range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset); range.commonAncestorContainer = range.collapsed ? range.startContainer : dom.getCommonAncestor(range.startContainer, range.endContainer); } function updateBoundaries(range, startContainer, startOffset, endContainer, endOffset) { var startMoved = (range.startContainer !== startContainer || range.startOffset !== startOffset); var endMoved = (range.endContainer !== endContainer || range.endOffset !== endOffset); range.startContainer = startContainer; range.startOffset = startOffset; range.endContainer = endContainer; range.endOffset = endOffset; updateCollapsedAndCommonAncestor(range); dispatchEvent(range, "boundarychange", {startMoved: startMoved, endMoved: endMoved}); } function detach(range) { assertNotDetached(range); range.startContainer = range.startOffset = range.endContainer = range.endOffset = null; range.collapsed = range.commonAncestorContainer = null; dispatchEvent(range, "detach", null); range._listeners = null; } /** * @constructor */ function Range(doc) { this.startContainer = doc; this.startOffset = 0; this.endContainer = doc; this.endOffset = 0; this._listeners = { boundarychange: [], detach: [] }; updateCollapsedAndCommonAncestor(this); } createPrototypeRange(Range, updateBoundaries, detach); api.rangePrototype = RangePrototype.prototype; Range.rangeProperties = rangeProperties; Range.RangeIterator = RangeIterator; Range.copyComparisonConstants = copyComparisonConstants; Range.createPrototypeRange = createPrototypeRange; Range.inspect = inspect; Range.getRangeDocument = getRangeDocument; Range.rangesEqual = function(r1, r2) { return r1.startContainer === r2.startContainer && r1.startOffset === r2.startOffset && r1.endContainer === r2.endContainer && r1.endOffset === r2.endOffset; }; api.DomRange = Range; api.RangeException = RangeException; });rangy.createModule("WrappedRange", function(api, module) { api.requireModules( ["DomUtil", "DomRange"] ); /** * @constructor */ var WrappedRange; var dom = api.dom; var DomPosition = dom.DomPosition; var DomRange = api.DomRange; /*----------------------------------------------------------------------------------------------------------------*/ /* This is a workaround for a bug where IE returns the wrong container element from the TextRange's parentElement() method. For example, in the following (where pipes denote the selection boundaries): <ul id="ul"><li id="a">| a </li><li id="b"> b |</li></ul> var range = document.selection.createRange(); alert(range.parentElement().id); // Should alert "ul" but alerts "b" This method returns the common ancestor node of the following: - the parentElement() of the textRange - the parentElement() of the textRange after calling collapse(true) - the parentElement() of the textRange after calling collapse(false) */ function getTextRangeContainerElement(textRange) { var parentEl = textRange.parentElement(); var range = textRange.duplicate(); range.collapse(true); var startEl = range.parentElement(); range = textRange.duplicate(); range.collapse(false); var endEl = range.parentElement(); var startEndContainer = (startEl == endEl) ? startEl : dom.getCommonAncestor(startEl, endEl); return startEndContainer == parentEl ? startEndContainer : dom.getCommonAncestor(parentEl, startEndContainer); } function textRangeIsCollapsed(textRange) { return textRange.compareEndPoints("StartToEnd", textRange) == 0; } // Gets the boundary of a TextRange expressed as a node and an offset within that node. This function started out as // an improved version of code found in Tim Cameron Ryan's IERange (http://code.google.com/p/ierange/) but has // grown, fixing problems with line breaks in preformatted text, adding workaround for IE TextRange bugs, handling // for inputs and images, plus optimizations. function getTextRangeBoundaryPosition(textRange, wholeRangeContainerElement, isStart, isCollapsed) { var workingRange = textRange.duplicate(); workingRange.collapse(isStart); var containerElement = workingRange.parentElement(); // Sometimes collapsing a TextRange that's at the start of a text node can move it into the previous node, so // check for that // TODO: Find out when. Workaround for wholeRangeContainerElement may break this if (!dom.isAncestorOf(wholeRangeContainerElement, containerElement, true)) { containerElement = wholeRangeContainerElement; } // Deal with nodes that cannot "contain rich HTML markup". In practice, this means form inputs, images and // similar. See http://msdn.microsoft.com/en-us/library/aa703950%28VS.85%29.aspx if (!containerElement.canHaveHTML) { return new DomPosition(containerElement.parentNode, dom.getNodeIndex(containerElement)); } var workingNode = dom.getDocument(containerElement).createElement("span"); var comparison, workingComparisonType = isStart ? "StartToStart" : "StartToEnd"; var previousNode, nextNode, boundaryPosition, boundaryNode; // Move the working range through the container's children, starting at the end and working backwards, until the // working range reaches or goes past the boundary we're interested in do { containerElement.insertBefore(workingNode, workingNode.previousSibling); workingRange.moveToElementText(workingNode); } while ( (comparison = workingRange.compareEndPoints(workingComparisonType, textRange)) > 0 && workingNode.previousSibling); // We've now reached or gone past the boundary of the text range we're interested in // so have identified the node we want boundaryNode = workingNode.nextSibling; if (comparison == -1 && boundaryNode && dom.isCharacterDataNode(boundaryNode)) { // This is a character data node (text, comment, cdata). The working range is collapsed at the start of the // node containing the text range's boundary, so we move the end of the working range to the boundary point // and measure the length of its text to get the boundary's offset within the node. workingRange.setEndPoint(isStart ? "EndToStart" : "EndToEnd", textRange); var offset; if (/[\r\n]/.test(boundaryNode.data)) { /* For the particular case of a boundary within a text node containing line breaks (within a <pre> element, for example), we need a slightly complicated approach to get the boundary's offset in IE. The facts: - Each line break is represented as \r in the text node's data/nodeValue properties - Each line break is represented as \r\n in the TextRange's 'text' property - The 'text' property of the TextRange does not contain trailing line breaks To get round the problem presented by the final fact above, we can use the fact that TextRange's moveStart() and moveEnd() methods return the actual number of characters moved, which is not necessarily the same as the number of characters it was instructed to move. The simplest approach is to use this to store the characters moved when moving both the start and end of the range to the start of the document body and subtracting the start offset from the end offset (the "move-negative-gazillion" method). However, this is extremely slow when the document is large and the range is near the end of it. Clearly doing the mirror image (i.e. moving the range boundaries to the end of the document) has the same problem. Another approach that works is to use moveStart() to move the start boundary of the range up to the end boundary one character at a time and incrementing a counter with the value returned by the moveStart() call. However, the check for whether the start boundary has reached the end boundary is expensive, so this method is slow (although unlike "move-negative-gazillion" is largely unaffected by the location of the range within the document). The method below is a hybrid of the two methods above. It uses the fact that a string containing the TextRange's 'text' property with each \r\n converted to a single \r character cannot be longer than the text of the TextRange, so the start of the range is moved that length initially and then a character at a time to make up for any trailing line breaks not contained in the 'text' property. This has good performance in most situations compared to the previous two methods. */ var tempRange = workingRange.duplicate(); var rangeLength = tempRange.text.replace(/\r\n/g, "\r").length; offset = tempRange.moveStart("character", rangeLength); while ( (comparison = tempRange.compareEndPoints("StartToEnd", tempRange)) == -1) { offset++; tempRange.moveStart("character", 1); } } else { offset = workingRange.text.length; } boundaryPosition = new DomPosition(boundaryNode, offset); } else { // If the boundary immediately follows a character data node and this is the end boundary, we should favour // a position within that, and likewise for a start boundary preceding a character data node previousNode = (isCollapsed || !isStart) && workingNode.previousSibling; nextNode = (isCollapsed || isStart) && workingNode.nextSibling; if (nextNode && dom.isCharacterDataNode(nextNode)) { boundaryPosition = new DomPosition(nextNode, 0); } else if (previousNode && dom.isCharacterDataNode(previousNode)) { boundaryPosition = new DomPosition(previousNode, previousNode.length); } else { boundaryPosition = new DomPosition(containerElement, dom.getNodeIndex(workingNode)); } } // Clean up workingNode.parentNode.removeChild(workingNode); return boundaryPosition; } // Returns a TextRange representing the boundary of a TextRange expressed as a node and an offset within that node. // This function started out as an optimized version of code found in Tim Cameron Ryan's IERange // (http://code.google.com/p/ierange/) function createBoundaryTextRange(boundaryPosition, isStart) { var boundaryNode, boundaryParent, boundaryOffset = boundaryPosition.offset; var doc = dom.getDocument(boundaryPosition.node); var workingNode, childNodes, workingRange = doc.body.createTextRange(); var nodeIsDataNode = dom.isCharacterDataNode(boundaryPosition.node); if (nodeIsDataNode) { boundaryNode = boundaryPosition.node; boundaryParent = boundaryNode.parentNode; } else { childNodes = boundaryPosition.node.childNodes; boundaryNode = (boundaryOffset < childNodes.length) ? childNodes[boundaryOffset] : null; boundaryParent = boundaryPosition.node; } // Position the range immediately before the node containing the boundary workingNode = doc.createElement("span"); // Making the working element non-empty element persuades IE to consider the TextRange boundary to be within the // element rather than immediately before or after it, which is what we want workingNode.innerHTML = "&#feff;"; // insertBefore is supposed to work like appendChild if the second parameter is null. However, a bug report // for IERange suggests that it can crash the browser: http://code.google.com/p/ierange/issues/detail?id=12 if (boundaryNode) { boundaryParent.insertBefore(workingNode, boundaryNode); } else { boundaryParent.appendChild(workingNode); } workingRange.moveToElementText(workingNode); workingRange.collapse(!isStart); // Clean up boundaryParent.removeChild(workingNode); // Move the working range to the text offset, if required if (nodeIsDataNode) { workingRange[isStart ? "moveStart" : "moveEnd"]("character", boundaryOffset); } return workingRange; } /*----------------------------------------------------------------------------------------------------------------*/ if (api.features.implementsDomRange && (!api.features.implementsTextRange || !api.config.preferTextRange)) { // This is a wrapper around the browser's native DOM Range. It has two aims: // - Provide workarounds for specific browser bugs // - provide convenient extensions, which are inherited from Rangy's DomRange (function() { var rangeProto; var rangeProperties = DomRange.rangeProperties; var canSetRangeStartAfterEnd; function updateRangeProperties(range) { var i = rangeProperties.length, prop; while (i--) { prop = rangeProperties[i]; range[prop] = range.nativeRange[prop]; } } function updateNativeRange(range, startContainer, startOffset, endContainer,endOffset) { var startMoved = (range.startContainer !== startContainer || range.startOffset != startOffset); var endMoved = (range.endContainer !== endContainer || range.endOffset != endOffset); // Always set both boundaries for the benefit of IE9 (see issue 35) if (startMoved || endMoved) { range.setEnd(endContainer, endOffset); range.setStart(startContainer, startOffset); } } function detach(range) { range.nativeRange.detach(); range.detached = true; var i = rangeProperties.length, prop; while (i--) { prop = rangeProperties[i]; range[prop] = null; } } var createBeforeAfterNodeSetter; WrappedRange = function(range) { if (!range) { throw new Error("Range must be specified"); } this.nativeRange = range; updateRangeProperties(this); }; DomRange.createPrototypeRange(WrappedRange, updateNativeRange, detach); rangeProto = WrappedRange.prototype; rangeProto.selectNode = function(node) { this.nativeRange.selectNode(node); updateRangeProperties(this); }; rangeProto.deleteContents = function() { this.nativeRange.deleteContents(); updateRangeProperties(this); }; rangeProto.extractContents = function() { var frag = this.nativeRange.extractContents(); updateRangeProperties(this); return frag; }; rangeProto.cloneContents = function() { return this.nativeRange.cloneContents(); }; // TODO: Until I can find a way to programmatically trigger the Firefox bug (apparently long-standing, still // present in 3.6.8) that throws "Index or size is negative or greater than the allowed amount" for // insertNode in some circumstances, all browsers will have to use the Rangy's own implementation of // insertNode, which works but is almost certainly slower than the native implementation. /* rangeProto.insertNode = function(node) { this.nativeRange.insertNode(node); updateRangeProperties(this); }; */ rangeProto.surroundContents = function(node) { this.nativeRange.surroundContents(node); updateRangeProperties(this); }; rangeProto.collapse = function(isStart) { this.nativeRange.collapse(isStart); updateRangeProperties(this); }; rangeProto.cloneRange = function() { return new WrappedRange(this.nativeRange.cloneRange()); }; rangeProto.refresh = function() { updateRangeProperties(this); }; rangeProto.toString = function() { return this.nativeRange.toString(); }; // Create test range and node for feature detection var testTextNode = document.createTextNode("test"); dom.getBody(document).appendChild(testTextNode); var range = document.createRange(); /*--------------------------------------------------------------------------------------------------------*/ // Test for Firefox 2 bug that prevents moving the start of a Range to a point after its current end and // correct for it range.setStart(testTextNode, 0); range.setEnd(testTextNode, 0); try { range.setStart(testTextNode, 1); canSetRangeStartAfterEnd = true; rangeProto.setStart = function(node, offset) { this.nativeRange.setStart(node, offset); updateRangeProperties(this); }; rangeProto.setEnd = function(node, offset) { this.nativeRange.setEnd(node, offset); updateRangeProperties(this); }; createBeforeAfterNodeSetter = function(name) { return function(node) { this.nativeRange[name](node); updateRangeProperties(this); }; }; } catch(ex) { canSetRangeStartAfterEnd = false; rangeProto.setStart = function(node, offset) { try { this.nativeRange.setStart(node, offset); } catch (ex) { this.nativeRange.setEnd(node, offset); this.nativeRange.setStart(node, offset); } updateRangeProperties(this); }; rangeProto.setEnd = function(node, offset) { try { this.nativeRange.setEnd(node, offset); } catch (ex) { this.nativeRange.setStart(node, offset); this.nativeRange.setEnd(node, offset); } updateRangeProperties(this); }; createBeforeAfterNodeSetter = function(name, oppositeName) { return function(node) { try { this.nativeRange[name](node); } catch (ex) { this.nativeRange[oppositeName](node); this.nativeRange[name](node); } updateRangeProperties(this); }; }; } rangeProto.setStartBefore = createBeforeAfterNodeSetter("setStartBefore", "setEndBefore"); rangeProto.setStartAfter = createBeforeAfterNodeSetter("setStartAfter", "setEndAfter"); rangeProto.setEndBefore = createBeforeAfterNodeSetter("setEndBefore", "setStartBefore"); rangeProto.setEndAfter = createBeforeAfterNodeSetter("setEndAfter", "setStartAfter"); /*--------------------------------------------------------------------------------------------------------*/ // Test for and correct Firefox 2 behaviour with selectNodeContents on text nodes: it collapses the range to // the 0th character of the text node range.selectNodeContents(testTextNode); if (range.startContainer == testTextNode && range.endContainer == testTextNode && range.startOffset == 0 && range.endOffset == testTextNode.length) { rangeProto.selectNodeContents = function(node) { this.nativeRange.selectNodeContents(node); updateRangeProperties(this); }; } else { rangeProto.selectNodeContents = function(node) { this.setStart(node, 0); this.setEnd(node, DomRange.getEndOffset(node)); }; } /*--------------------------------------------------------------------------------------------------------*/ // Test for WebKit bug that has the beahviour of compareBoundaryPoints round the wrong way for constants // START_TO_END and END_TO_START: https://bugs.webkit.org/show_bug.cgi?id=20738 range.selectNodeContents(testTextNode); range.setEnd(testTextNode, 3); var range2 = document.createRange(); range2.selectNodeContents(testTextNode); range2.setEnd(testTextNode, 4); range2.setStart(testTextNode, 2); if (range.compareBoundaryPoints(range.START_TO_END, range2) == -1 & range.compareBoundaryPoints(range.END_TO_START, range2) == 1) { // This is the wrong way round, so correct for it rangeProto.compareBoundaryPoints = function(type, range) { range = range.nativeRange || range; if (type == range.START_TO_END) { type = range.END_TO_START; } else if (type == range.END_TO_START) { type = range.START_TO_END; } return this.nativeRange.compareBoundaryPoints(type, range); }; } else { rangeProto.compareBoundaryPoints = function(type, range) { return this.nativeRange.compareBoundaryPoints(type, range.nativeRange || range); }; } /*--------------------------------------------------------------------------------------------------------*/ // Test for existence of createContextualFragment and delegate to it if it exists if (api.util.isHostMethod(range, "createContextualFragment")) { rangeProto.createContextualFragment = function(fragmentStr) { return this.nativeRange.createContextualFragment(fragmentStr); }; } /*--------------------------------------------------------------------------------------------------------*/ // Clean up dom.getBody(document).removeChild(testTextNode); range.detach(); range2.detach(); })(); api.createNativeRange = function(doc) { doc = doc || document; return doc.createRange(); }; } else if (api.features.implementsTextRange) { // This is a wrapper around a TextRange, providing full DOM Range functionality using rangy's DomRange as a // prototype WrappedRange = function(textRange) { this.textRange = textRange; this.refresh(); }; WrappedRange.prototype = new DomRange(document); WrappedRange.prototype.refresh = function() { var start, end; // TextRange's parentElement() method cannot be trusted. getTextRangeContainerElement() works around that. var rangeContainerElement = getTextRangeContainerElement(this.textRange); if (textRangeIsCollapsed(this.textRange)) { end = start = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, true, true); } else { start = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, true, false); end = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, false, false); } this.setStart(start.node, start.offset); this.setEnd(end.node, end.offset); }; DomRange.copyComparisonConstants(WrappedRange); // Add WrappedRange as the Range property of the global object to allow expression like Range.END_TO_END to work var globalObj = (function() { return this; })(); if (typeof globalObj.Range == "undefined") { globalObj.Range = WrappedRange; } api.createNativeRange = function(doc) { doc = doc || document; return doc.body.createTextRange(); }; } if (api.features.implementsTextRange) { WrappedRange.rangeToTextRange = function(range) { if (range.collapsed) { var tr = createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true); return tr; //return createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true); } else { var startRange = createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true); var endRange = createBoundaryTextRange(new DomPosition(range.endContainer, range.endOffset), false); var textRange = dom.getDocument(range.startContainer).body.createTextRange(); textRange.setEndPoint("StartToStart", startRange); textRange.setEndPoint("EndToEnd", endRange); return textRange; } }; } WrappedRange.prototype.getName = function() { return "WrappedRange"; }; api.WrappedRange = WrappedRange; api.createRange = function(doc) { doc = doc || document; return new WrappedRange(api.createNativeRange(doc)); }; api.createRangyRange = function(doc) { doc = doc || document; return new DomRange(doc); }; api.createIframeRange = function(iframeEl) { return api.createRange(dom.getIframeDocument(iframeEl)); }; api.createIframeRangyRange = function(iframeEl) { return api.createRangyRange(dom.getIframeDocument(iframeEl)); }; api.addCreateMissingNativeApiListener(function(win) { var doc = win.document; if (typeof doc.createRange == "undefined") { doc.createRange = function() { return api.createRange(this); }; } doc = win = null; }); });rangy.createModule("WrappedSelection", function(api, module) { // This will create a selection object wrapper that follows the Selection object found in the WHATWG draft DOM Range // spec (http://html5.org/specs/dom-range.html) api.requireModules( ["DomUtil", "DomRange", "WrappedRange"] ); api.config.checkSelectionRanges = true; var BOOLEAN = "boolean", windowPropertyName = "_rangySelection", dom = api.dom, util = api.util, DomRange = api.DomRange, WrappedRange = api.WrappedRange, DOMException = api.DOMException, DomPosition = dom.DomPosition, getSelection, selectionIsCollapsed, CONTROL = "Control"; function getWinSelection(winParam) { return (winParam || window).getSelection(); } function getDocSelection(winParam) { return (winParam || window).document.selection; } // Test for the Range/TextRange and Selection features required // Test for ability to retrieve selection var implementsWinGetSelection = api.util.isHostMethod(window, "getSelection"), implementsDocSelection = api.util.isHostObject(document, "selection"); var useDocumentSelection = implementsDocSelection && (!implementsWinGetSelection || api.config.preferTextRange); if (useDocumentSelection) { getSelection = getDocSelection; api.isSelectionValid = function(winParam) { var doc = (winParam || window).document, nativeSel = doc.selection; // Check whether the selection TextRange is actually contained within the correct document return (nativeSel.type != "None" || dom.getDocument(nativeSel.createRange().parentElement()) == doc); }; } else if (implementsWinGetSelection) { getSelection = getWinSelection; api.isSelectionValid = function() { return true; }; } else { module.fail("Neither document.selection or window.getSelection() detected."); } api.getNativeSelection = getSelection; var testSelection = getSelection(); var testRange = api.createNativeRange(document); var body = dom.getBody(document); // Obtaining a range from a selection var selectionHasAnchorAndFocus = util.areHostObjects(testSelection, ["anchorNode", "focusNode"] && util.areHostProperties(testSelection, ["anchorOffset", "focusOffset"])); api.features.selectionHasAnchorAndFocus = selectionHasAnchorAndFocus; // Test for existence of native selection extend() method var selectionHasExtend = util.isHostMethod(testSelection, "extend"); api.features.selectionHasExtend = selectionHasExtend; // Test if rangeCount exists var selectionHasRangeCount = (typeof testSelection.rangeCount == "number"); api.features.selectionHasRangeCount = selectionHasRangeCount; var selectionSupportsMultipleRanges = false; var collapsedNonEditableSelectionsSupported = true; if (util.areHostMethods(testSelection, ["addRange", "getRangeAt", "removeAllRanges"]) && typeof testSelection.rangeCount == "number" && api.features.implementsDomRange) { (function() { var iframe = document.createElement("iframe"); body.appendChild(iframe); var iframeDoc = dom.getIframeDocument(iframe); iframeDoc.open(); iframeDoc.write("<html><head></head><body>12</body></html>"); iframeDoc.close(); var sel = dom.getIframeWindow(iframe).getSelection(); var docEl = iframeDoc.documentElement; var iframeBody = docEl.lastChild, textNode = iframeBody.firstChild; // Test whether the native selection will allow a collapsed selection within a non-editable element var r1 = iframeDoc.createRange(); r1.setStart(textNode, 1); r1.collapse(true); sel.addRange(r1); collapsedNonEditableSelectionsSupported = (sel.rangeCount == 1); sel.removeAllRanges(); // Test whether the native selection is capable of supporting multiple ranges var r2 = r1.cloneRange(); r1.setStart(textNode, 0); r2.setEnd(textNode, 2); sel.addRange(r1); sel.addRange(r2); selectionSupportsMultipleRanges = (sel.rangeCount == 2); // Clean up r1.detach(); r2.detach(); body.removeChild(iframe); })(); } api.features.selectionSupportsMultipleRanges = selectionSupportsMultipleRanges; api.features.collapsedNonEditableSelectionsSupported = collapsedNonEditableSelectionsSupported; // ControlRanges var implementsControlRange = false, testControlRange; if (body && util.isHostMethod(body, "createControlRange")) { testControlRange = body.createControlRange(); if (util.areHostProperties(testControlRange, ["item", "add"])) { implementsControlRange = true; } } api.features.implementsControlRange = implementsControlRange; // Selection collapsedness if (selectionHasAnchorAndFocus) { selectionIsCollapsed = function(sel) { return sel.anchorNode === sel.focusNode && sel.anchorOffset === sel.focusOffset; }; } else { selectionIsCollapsed = function(sel) { return sel.rangeCount ? sel.getRangeAt(sel.rangeCount - 1).collapsed : false; }; } function updateAnchorAndFocusFromRange(sel, range, backwards) { var anchorPrefix = backwards ? "end" : "start", focusPrefix = backwards ? "start" : "end"; sel.anchorNode = range[anchorPrefix + "Container"]; sel.anchorOffset = range[anchorPrefix + "Offset"]; sel.focusNode = range[focusPrefix + "Container"]; sel.focusOffset = range[focusPrefix + "Offset"]; } function updateAnchorAndFocusFromNativeSelection(sel) { var nativeSel = sel.nativeSelection; sel.anchorNode = nativeSel.anchorNode; sel.anchorOffset = nativeSel.anchorOffset; sel.focusNode = nativeSel.focusNode; sel.focusOffset = nativeSel.focusOffset; } function updateEmptySelection(sel) { sel.anchorNode = sel.focusNode = null; sel.anchorOffset = sel.focusOffset = 0; sel.rangeCount = 0; sel.isCollapsed = true; sel._ranges.length = 0; } function getNativeRange(range) { var nativeRange; if (range instanceof DomRange) { nativeRange = range._selectionNativeRange; if (!nativeRange) { nativeRange = api.createNativeRange(dom.getDocument(range.startContainer)); nativeRange.setEnd(range.endContainer, range.endOffset); nativeRange.setStart(range.startContainer, range.startOffset); range._selectionNativeRange = nativeRange; range.attachListener("detach", function() { this._selectionNativeRange = null; }); } } else if (range instanceof WrappedRange) { nativeRange = range.nativeRange; } else if (api.features.implementsDomRange && (range instanceof dom.getWindow(range.startContainer).Range)) { nativeRange = range; } return nativeRange; } function rangeContainsSingleElement(rangeNodes) { if (!rangeNodes.length || rangeNodes[0].nodeType != 1) { return false; } for (var i = 1, len = rangeNodes.length; i < len; ++i) { if (!dom.isAncestorOf(rangeNodes[0], rangeNodes[i])) { return false; } } return true; } function getSingleElementFromRange(range) { var nodes = range.getNodes(); if (!rangeContainsSingleElement(nodes)) { throw new Error("getSingleElementFromRange: range " + range.inspect() + " did not consist of a single element"); } return nodes[0]; } function isTextRange(range) { return !!range && typeof range.text != "undefined"; } function updateFromTextRange(sel, range) { // Create a Range from the selected TextRange var wrappedRange = new WrappedRange(range); sel._ranges = [wrappedRange]; updateAnchorAndFocusFromRange(sel, wrappedRange, false); sel.rangeCount = 1; sel.isCollapsed = wrappedRange.collapsed; } function updateControlSelection(sel) { // Update the wrapped selection based on what's now in the native selection sel._ranges.length = 0; if (sel.docSelection.type == "None") { updateEmptySelection(sel); } else { var controlRange = sel.docSelection.createRange(); if (isTextRange(controlRange)) { // This case (where the selection type is "Control" and calling createRange() on the selection returns // a TextRange) can happen in IE 9. It happens, for example, when all elements in the selected // ControlRange have been removed from the ControlRange and removed from the document. updateFromTextRange(sel, controlRange); } else { sel.rangeCount = controlRange.length; var range, doc = dom.getDocument(controlRange.item(0)); for (var i = 0; i < sel.rangeCount; ++i) { range = api.createRange(doc); range.selectNode(controlRange.item(i)); sel._ranges.push(range); } sel.isCollapsed = sel.rangeCount == 1 && sel._ranges[0].collapsed; updateAnchorAndFocusFromRange(sel, sel._ranges[sel.rangeCount - 1], false); } } } function addRangeToControlSelection(sel, range) { var controlRange = sel.docSelection.createRange(); var rangeElement = getSingleElementFromRange(range); // Create a new ControlRange containing all the elements in the selected ControlRange plus the element // contained by the supplied range var doc = dom.getDocument(controlRange.item(0)); var newControlRange = dom.getBody(doc).createControlRange(); for (var i = 0, len = controlRange.length; i < len; ++i) { newControlRange.add(controlRange.item(i)); } try { newControlRange.add(rangeElement); } catch (ex) { throw new Error("addRange(): Element within the specified Range could not be added to control selection (does it have layout?)"); } newControlRange.select(); // Update the wrapped selection based on what's now in the native selection updateControlSelection(sel); } var getSelectionRangeAt; if (util.isHostMethod(testSelection, "getRangeAt")) { getSelectionRangeAt = function(sel, index) { try { return sel.getRangeAt(index); } catch(ex) { return null; } }; } else if (selectionHasAnchorAndFocus) { getSelectionRangeAt = function(sel) { var doc = dom.getDocument(sel.anchorNode); var range = api.createRange(doc); range.setStart(sel.anchorNode, sel.anchorOffset); range.setEnd(sel.focusNode, sel.focusOffset); // Handle the case when the selection was selected backwards (from the end to the start in the // document) if (range.collapsed !== this.isCollapsed) { range.setStart(sel.focusNode, sel.focusOffset); range.setEnd(sel.anchorNode, sel.anchorOffset); } return range; }; } /** * @constructor */ function WrappedSelection(selection, docSelection, win) { this.nativeSelection = selection; this.docSelection = docSelection; this._ranges = []; this.win = win; this.refresh(); } api.getSelection = function(win) { win = win || window; var sel = win[windowPropertyName]; var nativeSel = getSelection(win), docSel = implementsDocSelection ? getDocSelection(win) : null; if (sel) { sel.nativeSelection = nativeSel; sel.docSelection = docSel; sel.refresh(win); } else { sel = new WrappedSelection(nativeSel, docSel, win); win[windowPropertyName] = sel; } return sel; }; api.getIframeSelection = function(iframeEl) { return api.getSelection(dom.getIframeWindow(iframeEl)); }; var selProto = WrappedSelection.prototype; function createControlSelection(sel, ranges) { // Ensure that the selection becomes of type "Control" var doc = dom.getDocument(ranges[0].startContainer); var controlRange = dom.getBody(doc).createControlRange(); for (var i = 0, el; i < rangeCount; ++i) { el = getSingleElementFromRange(ranges[i]); try { controlRange.add(el); } catch (ex) { throw new Error("setRanges(): Element within the one of the specified Ranges could not be added to control selection (does it have layout?)"); } } controlRange.select(); // Update the wrapped selection based on what's now in the native selection updateControlSelection(sel); } // Selecting a range if (!useDocumentSelection && selectionHasAnchorAndFocus && util.areHostMethods(testSelection, ["removeAllRanges", "addRange"])) { selProto.removeAllRanges = function() { this.nativeSelection.removeAllRanges(); updateEmptySelection(this); }; var addRangeBackwards = function(sel, range) { var doc = DomRange.getRangeDocument(range); var endRange = api.createRange(doc); endRange.collapseToPoint(range.endContainer, range.endOffset); sel.nativeSelection.addRange(getNativeRange(endRange)); sel.nativeSelection.extend(range.startContainer, range.startOffset); sel.refresh(); }; if (selectionHasRangeCount) { selProto.addRange = function(range, backwards) { if (implementsControlRange && implementsDocSelection && this.docSelection.type == CONTROL) { addRangeToControlSelection(this, range); } else { if (backwards && selectionHasExtend) { addRangeBackwards(this, range); } else { var previousRangeCount; if (selectionSupportsMultipleRanges) { previousRangeCount = this.rangeCount; } else { this.removeAllRanges(); previousRangeCount = 0; } this.nativeSelection.addRange(getNativeRange(range)); // Check whether adding the range was successful this.rangeCount = this.nativeSelection.rangeCount; if (this.rangeCount == previousRangeCount + 1) { // The range was added successfully // Check whether the range that we added to the selection is reflected in the last range extracted from // the selection if (api.config.checkSelectionRanges) { var nativeRange = getSelectionRangeAt(this.nativeSelection, this.rangeCount - 1); if (nativeRange && !DomRange.rangesEqual(nativeRange, range)) { // Happens in WebKit with, for example, a selection placed at the start of a text node range = new WrappedRange(nativeRange); } } this._ranges[this.rangeCount - 1] = range; updateAnchorAndFocusFromRange(this, range, selectionIsBackwards(this.nativeSelection)); this.isCollapsed = selectionIsCollapsed(this); } else { // The range was not added successfully. The simplest thing is to refresh this.refresh(); } } } }; } else { selProto.addRange = function(range, backwards) { if (backwards && selectionHasExtend) { addRangeBackwards(this, range); } else { this.nativeSelection.addRange(getNativeRange(range)); this.refresh(); } }; } selProto.setRanges = function(ranges) { if (implementsControlRange && ranges.length > 1) { createControlSelection(this, ranges); } else { this.removeAllRanges(); for (var i = 0, len = ranges.length; i < len; ++i) { this.addRange(ranges[i]); } } }; } else if (util.isHostMethod(testSelection, "empty") && util.isHostMethod(testRange, "select") && implementsControlRange && useDocumentSelection) { selProto.removeAllRanges = function() { // Added try/catch as fix for issue #21 try { this.docSelection.empty(); // Check for empty() not working (issue #24) if (this.docSelection.type != "None") { // Work around failure to empty a control selection by instead selecting a TextRange and then // calling empty() var doc; if (this.anchorNode) { doc = dom.getDocument(this.anchorNode); } else if (this.docSelection.type == CONTROL) { var controlRange = this.docSelection.createRange(); if (controlRange.length) { doc = dom.getDocument(controlRange.item(0)).body.createTextRange(); } } if (doc) { var textRange = doc.body.createTextRange(); textRange.select(); this.docSelection.empty(); } } } catch(ex) {} updateEmptySelection(this); }; selProto.addRange = function(range) { if (this.docSelection.type == CONTROL) { addRangeToControlSelection(this, range); } else { WrappedRange.rangeToTextRange(range).select(); this._ranges[0] = range; this.rangeCount = 1; this.isCollapsed = this._ranges[0].collapsed; updateAnchorAndFocusFromRange(this, range, false); } }; selProto.setRanges = function(ranges) { this.removeAllRanges(); var rangeCount = ranges.length; if (rangeCount > 1) { createControlSelection(this, ranges); } else if (rangeCount) { this.addRange(ranges[0]); } }; } else { module.fail("No means of selecting a Range or TextRange was found"); return false; } selProto.getRangeAt = function(index) { if (index < 0 || index >= this.rangeCount) { throw new DOMException("INDEX_SIZE_ERR"); } else { return this._ranges[index]; } }; var refreshSelection; if (useDocumentSelection) { refreshSelection = function(sel) { var range; if (api.isSelectionValid(sel.win)) { range = sel.docSelection.createRange(); } else { range = dom.getBody(sel.win.document).createTextRange(); range.collapse(true); } if (sel.docSelection.type == CONTROL) { updateControlSelection(sel); } else if (isTextRange(range)) { updateFromTextRange(sel, range); } else { updateEmptySelection(sel); } }; } else if (util.isHostMethod(testSelection, "getRangeAt") && typeof testSelection.rangeCount == "number") { refreshSelection = function(sel) { if (implementsControlRange && implementsDocSelection && sel.docSelection.type == CONTROL) { updateControlSelection(sel); } else { sel._ranges.length = sel.rangeCount = sel.nativeSelection.rangeCount; if (sel.rangeCount) { for (var i = 0, len = sel.rangeCount; i < len; ++i) { sel._ranges[i] = new api.WrappedRange(sel.nativeSelection.getRangeAt(i)); } updateAnchorAndFocusFromRange(sel, sel._ranges[sel.rangeCount - 1], selectionIsBackwards(sel.nativeSelection)); sel.isCollapsed = selectionIsCollapsed(sel); } else { updateEmptySelection(sel); } } }; } else if (selectionHasAnchorAndFocus && typeof testSelection.isCollapsed == BOOLEAN && typeof testRange.collapsed == BOOLEAN && api.features.implementsDomRange) { refreshSelection = function(sel) { var range, nativeSel = sel.nativeSelection; if (nativeSel.anchorNode) { range = getSelectionRangeAt(nativeSel, 0); sel._ranges = [range]; sel.rangeCount = 1; updateAnchorAndFocusFromNativeSelection(sel); sel.isCollapsed = selectionIsCollapsed(sel); } else { updateEmptySelection(sel); } }; } else { module.fail("No means of obtaining a Range or TextRange from the user's selection was found"); return false; } selProto.refresh = function(checkForChanges) { var oldRanges = checkForChanges ? this._ranges.slice(0) : null; refreshSelection(this); if (checkForChanges) { var i = oldRanges.length; if (i != this._ranges.length) { return false; } while (i--) { if (!DomRange.rangesEqual(oldRanges[i], this._ranges[i])) { return false; } } return true; } }; // Removal of a single range var removeRangeManually = function(sel, range) { var ranges = sel.getAllRanges(), removed = false; sel.removeAllRanges(); for (var i = 0, len = ranges.length; i < len; ++i) { if (removed || range !== ranges[i]) { sel.addRange(ranges[i]); } else { // According to the draft WHATWG Range spec, the same range may be added to the selection multiple // times. removeRange should only remove the first instance, so the following ensures only the first // instance is removed removed = true; } } if (!sel.rangeCount) { updateEmptySelection(sel); } }; if (implementsControlRange) { selProto.removeRange = function(range) { if (this.docSelection.type == CONTROL) { var controlRange = this.docSelection.createRange(); var rangeElement = getSingleElementFromRange(range); // Create a new ControlRange containing all the elements in the selected ControlRange minus the // element contained by the supplied range var doc = dom.getDocument(controlRange.item(0)); var newControlRange = dom.getBody(doc).createControlRange(); var el, removed = false; for (var i = 0, len = controlRange.length; i < len; ++i) { el = controlRange.item(i); if (el !== rangeElement || removed) { newControlRange.add(controlRange.item(i)); } else { removed = true; } } newControlRange.select(); // Update the wrapped selection based on what's now in the native selection updateControlSelection(this); } else { removeRangeManually(this, range); } }; } else { selProto.removeRange = function(range) { removeRangeManually(this, range); }; } // Detecting if a selection is backwards var selectionIsBackwards; if (!useDocumentSelection && selectionHasAnchorAndFocus && api.features.implementsDomRange) { selectionIsBackwards = function(sel) { var backwards = false; if (sel.anchorNode) { backwards = (dom.comparePoints(sel.anchorNode, sel.anchorOffset, sel.focusNode, sel.focusOffset) == 1); } return backwards; }; selProto.isBackwards = function() { return selectionIsBackwards(this); }; } else { selectionIsBackwards = selProto.isBackwards = function() { return false; }; } // Selection text // This is conformant to the new WHATWG DOM Range draft spec but differs from WebKit and Mozilla's implementation selProto.toString = function() { var rangeTexts = []; for (var i = 0, len = this.rangeCount; i < len; ++i) { rangeTexts[i] = "" + this._ranges[i]; } return rangeTexts.join(""); }; function assertNodeInSameDocument(sel, node) { if (sel.anchorNode && (dom.getDocument(sel.anchorNode) !== dom.getDocument(node))) { throw new DOMException("WRONG_DOCUMENT_ERR"); } } // No current browsers conform fully to the HTML 5 draft spec for this method, so Rangy's own method is always used selProto.collapse = function(node, offset) { assertNodeInSameDocument(this, node); var range = api.createRange(dom.getDocument(node)); range.collapseToPoint(node, offset); this.removeAllRanges(); this.addRange(range); this.isCollapsed = true; }; selProto.collapseToStart = function() { if (this.rangeCount) { var range = this._ranges[0]; this.collapse(range.startContainer, range.startOffset); } else { throw new DOMException("INVALID_STATE_ERR"); } }; selProto.collapseToEnd = function() { if (this.rangeCount) { var range = this._ranges[this.rangeCount - 1]; this.collapse(range.endContainer, range.endOffset); } else { throw new DOMException("INVALID_STATE_ERR"); } }; // The HTML 5 spec is very specific on how selectAllChildren should be implemented so the native implementation is // never used by Rangy. selProto.selectAllChildren = function(node) { assertNodeInSameDocument(this, node); var range = api.createRange(dom.getDocument(node)); range.selectNodeContents(node); this.removeAllRanges(); this.addRange(range); }; selProto.deleteFromDocument = function() { // Sepcial behaviour required for Control selections if (implementsControlRange && implementsDocSelection && this.docSelection.type == CONTROL) { var controlRange = this.docSelection.createRange(); var element; while (controlRange.length) { element = controlRange.item(0); controlRange.remove(element); element.parentNode.removeChild(element); } this.refresh(); } else if (this.rangeCount) { var ranges = this.getAllRanges(); this.removeAllRanges(); for (var i = 0, len = ranges.length; i < len; ++i) { ranges[i].deleteContents(); } // The HTML5 spec says nothing about what the selection should contain after calling deleteContents on each // range. Firefox moves the selection to where the final selected range was, so we emulate that this.addRange(ranges[len - 1]); } }; // The following are non-standard extensions selProto.getAllRanges = function() { return this._ranges.slice(0); }; selProto.setSingleRange = function(range) { this.setRanges( [range] ); }; selProto.containsNode = function(node, allowPartial) { for (var i = 0, len = this._ranges.length; i < len; ++i) { if (this._ranges[i].containsNode(node, allowPartial)) { return true; } } return false; }; selProto.toHtml = function() { var html = ""; if (this.rangeCount) { var container = DomRange.getRangeDocument(this._ranges[0]).createElement("div"); for (var i = 0, len = this._ranges.length; i < len; ++i) { container.appendChild(this._ranges[i].cloneContents()); } html = container.innerHTML; } return html; }; function inspect(sel) { var rangeInspects = []; var anchor = new DomPosition(sel.anchorNode, sel.anchorOffset); var focus = new DomPosition(sel.focusNode, sel.focusOffset); var name = (typeof sel.getName == "function") ? sel.getName() : "Selection"; if (typeof sel.rangeCount != "undefined") { for (var i = 0, len = sel.rangeCount; i < len; ++i) { rangeInspects[i] = DomRange.inspect(sel.getRangeAt(i)); } } return "[" + name + "(Ranges: " + rangeInspects.join(", ") + ")(anchor: " + anchor.inspect() + ", focus: " + focus.inspect() + "]"; } selProto.getName = function() { return "WrappedSelection"; }; selProto.inspect = function() { return inspect(this); }; selProto.detach = function() { this.win[windowPropertyName] = null; this.win = this.anchorNode = this.focusNode = null; }; WrappedSelection.inspect = inspect; api.Selection = WrappedSelection; api.selectionPrototype = selProto; api.addCreateMissingNativeApiListener(function(win) { if (typeof win.getSelection == "undefined") { win.getSelection = function() { return api.getSelection(this); }; } win = null; }); }); /* Base.js, version 1.1a Copyright 2006-2010, Dean Edwards License: http://www.opensource.org/licenses/mit-license.php */ var Base = function() { // dummy }; Base.extend = function(_instance, _static) { // subclass var extend = Base.prototype.extend; // build the prototype Base._prototyping = true; var proto = new this; extend.call(proto, _instance); proto.base = function() { // call this method from any other method to invoke that method's ancestor }; delete Base._prototyping; // create the wrapper for the constructor function //var constructor = proto.constructor.valueOf(); //-dean var constructor = proto.constructor; var klass = proto.constructor = function() { if (!Base._prototyping) { if (this._constructing || this.constructor == klass) { // instantiation this._constructing = true; constructor.apply(this, arguments); delete this._constructing; } else if (arguments[0] != null) { // casting return (arguments[0].extend || extend).call(arguments[0], proto); } } }; // build the class interface klass.ancestor = this; klass.extend = this.extend; klass.forEach = this.forEach; klass.implement = this.implement; klass.prototype = proto; klass.toString = this.toString; klass.valueOf = function(type) { //return (type == "object") ? klass : constructor; //-dean return (type == "object") ? klass : constructor.valueOf(); }; extend.call(klass, _static); // class initialisation if (typeof klass.init == "function") klass.init(); return klass; }; Base.prototype = { extend: function(source, value) { if (arguments.length > 1) { // extending with a name/value pair var ancestor = this[source]; if (ancestor && (typeof value == "function") && // overriding a method? // the valueOf() comparison is to avoid circular references (!ancestor.valueOf || ancestor.valueOf() != value.valueOf()) && /\bbase\b/.test(value)) { // get the underlying method var method = value.valueOf(); // override value = function() { var previous = this.base || Base.prototype.base; this.base = ancestor; var returnValue = method.apply(this, arguments); this.base = previous; return returnValue; }; // point to the underlying method value.valueOf = function(type) { return (type == "object") ? value : method; }; value.toString = Base.toString; } this[source] = value; } else if (source) { // extending with an object literal var extend = Base.prototype.extend; // if this object has a customised extend method then use it if (!Base._prototyping && typeof this != "function") { extend = this.extend || extend; } var proto = {toSource: null}; // do the "toString" and other methods manually var hidden = ["constructor", "toString", "valueOf"]; // if we are prototyping then include the constructor var i = Base._prototyping ? 0 : 1; while (key = hidden[i++]) { if (source[key] != proto[key]) { extend.call(this, key, source[key]); } } // copy each of the source object's properties to this object for (var key in source) { if (!proto[key]) extend.call(this, key, source[key]); } } return this; } }; // initialise Base = Base.extend({ constructor: function() { this.extend(arguments[0]); } }, { ancestor: Object, version: "1.1", forEach: function(object, block, context) { for (var key in object) { if (this.prototype[key] === undefined) { block.call(context, object[key], key, object); } } }, implement: function() { for (var i = 0; i < arguments.length; i++) { if (typeof arguments[i] == "function") { // if it's a function, call it arguments[i](this.prototype); } else { // add the interface using the extend method this.prototype.extend(arguments[i]); } } return this; }, toString: function() { return String(this.valueOf()); } });/** * Detect browser support for specific features */ wysihtml5.browser = (function() { var userAgent = navigator.userAgent, testElement = document.createElement("div"), // Browser sniffing is unfortunately needed since some behaviors are impossible to feature detect isIE = userAgent.indexOf("MSIE") !== -1 && userAgent.indexOf("Opera") === -1, isGecko = userAgent.indexOf("Gecko") !== -1 && userAgent.indexOf("KHTML") === -1, isWebKit = userAgent.indexOf("AppleWebKit/") !== -1, isChrome = userAgent.indexOf("Chrome/") !== -1, isOpera = userAgent.indexOf("Opera/") !== -1; function iosVersion(userAgent) { return ((/ipad|iphone|ipod/.test(userAgent) && userAgent.match(/ os (\d+).+? like mac os x/)) || [, 0])[1]; } return { // Static variable needed, publicly accessible, to be able override it in unit tests USER_AGENT: userAgent, /** * Exclude browsers that are not capable of displaying and handling * contentEditable as desired: * - iPhone, iPad (tested iOS 4.2.2) and Android (tested 2.2) refuse to make contentEditables focusable * - IE < 8 create invalid markup and crash randomly from time to time * * @return {Boolean} */ supported: function() { var userAgent = this.USER_AGENT.toLowerCase(), // Essential for making html elements editable hasContentEditableSupport = "contentEditable" in testElement, // Following methods are needed in order to interact with the contentEditable area hasEditingApiSupport = document.execCommand && document.queryCommandSupported && document.queryCommandState, // document selector apis are only supported by IE 8+, Safari 4+, Chrome and Firefox 3.5+ hasQuerySelectorSupport = document.querySelector && document.querySelectorAll, // contentEditable is unusable in mobile browsers (tested iOS 4.2.2, Android 2.2, Opera Mobile, WebOS 3.05) isIncompatibleMobileBrowser = (this.isIos() && iosVersion(userAgent) < 5) || userAgent.indexOf("opera mobi") !== -1 || userAgent.indexOf("hpwos/") !== -1; return hasContentEditableSupport && hasEditingApiSupport && hasQuerySelectorSupport && !isIncompatibleMobileBrowser; }, isTouchDevice: function() { return this.supportsEvent("touchmove"); }, isIos: function() { var userAgent = this.USER_AGENT.toLowerCase(); return userAgent.indexOf("webkit") !== -1 && userAgent.indexOf("mobile") !== -1; }, /** * Whether the browser supports sandboxed iframes * Currently only IE 6+ offers such feature <iframe security="restricted"> * * http://msdn.microsoft.com/en-us/library/ms534622(v=vs.85).aspx * http://blogs.msdn.com/b/ie/archive/2008/01/18/using-frames-more-securely.aspx * * HTML5 sandboxed iframes are still buggy and their DOM is not reachable from the outside (except when using postMessage) */ supportsSandboxedIframes: function() { return isIE; }, /** * IE6+7 throw a mixed content warning when the src of an iframe * is empty/unset or about:blank * window.querySelector is implemented as of IE8 */ throwsMixedContentWarningWhenIframeSrcIsEmpty: function() { return !("querySelector" in document); }, /** * Whether the caret is correctly displayed in contentEditable elements * Firefox sometimes shows a huge caret in the beginning after focusing */ displaysCaretInEmptyContentEditableCorrectly: function() { return !isGecko; }, /** * Opera and IE are the only browsers who offer the css value * in the original unit, thx to the currentStyle object * All other browsers provide the computed style in px via window.getComputedStyle */ hasCurrentStyleProperty: function() { return "currentStyle" in testElement; }, /** * Whether the browser inserts a <br> when pressing enter in a contentEditable element */ insertsLineBreaksOnReturn: function() { return isGecko; }, supportsPlaceholderAttributeOn: function(element) { return "placeholder" in element; }, supportsEvent: function(eventName) { return "on" + eventName in testElement || (function() { testElement.setAttribute("on" + eventName, "return;"); return typeof(testElement["on" + eventName]) === "function"; })(); }, /** * Opera doesn't correctly fire focus/blur events when clicking in- and outside of iframe */ supportsEventsInIframeCorrectly: function() { return !isOpera; }, /** * Chrome & Safari only fire the ondrop/ondragend/... events when the ondragover event is cancelled * with event.preventDefault * Firefox 3.6 fires those events anyway, but the mozilla doc says that the dragover/dragenter event needs * to be cancelled */ firesOnDropOnlyWhenOnDragOverIsCancelled: function() { return isWebKit || isGecko; }, /** * Whether the browser supports the event.dataTransfer property in a proper way */ supportsDataTransfer: function() { try { // Firefox doesn't support dataTransfer in a safe way, it doesn't strip script code in the html payload (like Chrome does) return isWebKit && (window.Clipboard || window.DataTransfer).prototype.getData; } catch(e) { return false; } }, /** * Everything below IE9 doesn't know how to treat HTML5 tags * * @param {Object} context The document object on which to check HTML5 support * * @example * wysihtml5.browser.supportsHTML5Tags(document); */ supportsHTML5Tags: function(context) { var element = context.createElement("div"), html5 = "<article>foo</article>"; element.innerHTML = html5; return element.innerHTML.toLowerCase() === html5; }, /** * Checks whether a document supports a certain queryCommand * In particular, Opera needs a reference to a document that has a contentEditable in it's dom tree * in oder to report correct results * * @param {Object} doc Document object on which to check for a query command * @param {String} command The query command to check for * @return {Boolean} * * @example * wysihtml5.browser.supportsCommand(document, "bold"); */ supportsCommand: (function() { // Following commands are supported but contain bugs in some browsers var buggyCommands = { // formatBlock fails with some tags (eg. <blockquote>) "formatBlock": isIE, // When inserting unordered or ordered lists in Firefox, Chrome or Safari, the current selection or line gets // converted into a list (<ul><li>...</li></ul>, <ol><li>...</li></ol>) // IE and Opera act a bit different here as they convert the entire content of the current block element into a list "insertUnorderedList": isIE || isOpera || isWebKit, "insertOrderedList": isIE || isOpera || isWebKit }; // Firefox throws errors for queryCommandSupported, so we have to build up our own object of supported commands var supported = { "insertHTML": isGecko }; return function(doc, command) { var isBuggy = buggyCommands[command]; if (!isBuggy) { // Firefox throws errors when invoking queryCommandSupported or queryCommandEnabled try { return doc.queryCommandSupported(command); } catch(e1) {} try { return doc.queryCommandEnabled(command); } catch(e2) { return !!supported[command]; } } return false; }; })(), /** * IE: URLs starting with: * www., http://, https://, ftp://, gopher://, mailto:, new:, snews:, telnet:, wasis:, file://, * nntp://, newsrc:, ldap://, ldaps://, outlook:, mic:// and url: * will automatically be auto-linked when either the user inserts them via copy&paste or presses the * space bar when the caret is directly after such an url. * This behavior cannot easily be avoided in IE < 9 since the logic is hardcoded in the mshtml.dll * (related blog post on msdn * http://blogs.msdn.com/b/ieinternals/archive/2009/09/17/prevent-automatic-hyperlinking-in-contenteditable-html.aspx). */ doesAutoLinkingInContentEditable: function() { return isIE; }, /** * As stated above, IE auto links urls typed into contentEditable elements * Since IE9 it's possible to prevent this behavior */ canDisableAutoLinking: function() { return this.supportsCommand(document, "AutoUrlDetect"); }, /** * IE leaves an empty paragraph in the contentEditable element after clearing it * Chrome/Safari sometimes an empty <div> */ clearsContentEditableCorrectly: function() { return isGecko || isOpera || isWebKit; }, /** * IE gives wrong results for getAttribute */ supportsGetAttributeCorrectly: function() { var td = document.createElement("td"); return td.getAttribute("rowspan") != "1"; }, /** * When clicking on images in IE, Opera and Firefox, they are selected, which makes it easy to interact with them. * Chrome and Safari both don't support this */ canSelectImagesInContentEditable: function() { return isGecko || isIE || isOpera; }, /** * When the caret is in an empty list (<ul><li>|</li></ul>) which is the first child in an contentEditable container * pressing backspace doesn't remove the entire list as done in other browsers */ clearsListsInContentEditableCorrectly: function() { return isGecko || isIE || isWebKit; }, /** * All browsers except Safari and Chrome automatically scroll the range/caret position into view */ autoScrollsToCaret: function() { return !isWebKit; }, /** * Check whether the browser automatically closes tags that don't need to be opened */ autoClosesUnclosedTags: function() { var clonedTestElement = testElement.cloneNode(false), returnValue, innerHTML; clonedTestElement.innerHTML = "<p><div></div>"; innerHTML = clonedTestElement.innerHTML.toLowerCase(); returnValue = innerHTML === "<p></p><div></div>" || innerHTML === "<p><div></div></p>"; // Cache result by overwriting current function this.autoClosesUnclosedTags = function() { return returnValue; }; return returnValue; }, /** * Whether the browser supports the native document.getElementsByClassName which returns live NodeLists */ supportsNativeGetElementsByClassName: function() { return String(document.getElementsByClassName).indexOf("[native code]") !== -1; }, /** * As of now (19.04.2011) only supported by Firefox 4 and Chrome * See https://developer.mozilla.org/en/DOM/Selection/modify */ supportsSelectionModify: function() { return "getSelection" in window && "modify" in window.getSelection(); }, /** * Whether the browser supports the classList object for fast className manipulation * See https://developer.mozilla.org/en/DOM/element.classList */ supportsClassList: function() { return "classList" in testElement; }, /** * Opera needs a white space after a <br> in order to position the caret correctly */ needsSpaceAfterLineBreak: function() { return isOpera; }, /** * Whether the browser supports the speech api on the given element * See http://mikepultz.com/2011/03/accessing-google-speech-api-chrome-11/ * * @example * var input = document.createElement("input"); * if (wysihtml5.browser.supportsSpeechApiOn(input)) { * // ... * } */ supportsSpeechApiOn: function(input) { var chromeVersion = userAgent.match(/Chrome\/(\d+)/) || [, 0]; return chromeVersion[1] >= 11 && ("onwebkitspeechchange" in input || "speech" in input); }, /** * IE9 crashes when setting a getter via Object.defineProperty on XMLHttpRequest or XDomainRequest * See https://connect.microsoft.com/ie/feedback/details/650112 * or try the POC http://tifftiff.de/ie9_crash/ */ crashesWhenDefineProperty: function(property) { return isIE && (property === "XMLHttpRequest" || property === "XDomainRequest"); }, /** * IE is the only browser who fires the "focus" event not immediately when .focus() is called on an element */ doesAsyncFocus: function() { return isIE; }, /** * In IE it's impssible for the user and for the selection library to set the caret after an <img> when it's the lastChild in the document */ hasProblemsSettingCaretAfterImg: function() { return isIE; }, hasUndoInContextMenu: function() { return isGecko || isChrome || isOpera; } }; })();wysihtml5.lang.array = function(arr) { return { /** * Check whether a given object exists in an array * * @example * wysihtml5.lang.array([1, 2]).contains(1); * // => true */ contains: function(needle) { if (arr.indexOf) { return arr.indexOf(needle) !== -1; } else { for (var i=0, length=arr.length; i<length; i++) { if (arr[i] === needle) { return true; } } return false; } }, /** * Substract one array from another * * @example * wysihtml5.lang.array([1, 2, 3, 4]).without([3, 4]); * // => [1, 2] */ without: function(arrayToSubstract) { arrayToSubstract = wysihtml5.lang.array(arrayToSubstract); var newArr = [], i = 0, length = arr.length; for (; i<length; i++) { if (!arrayToSubstract.contains(arr[i])) { newArr.push(arr[i]); } } return newArr; }, /** * Return a clean native array * * Following will convert a Live NodeList to a proper Array * @example * var childNodes = wysihtml5.lang.array(document.body.childNodes).get(); */ get: function() { var i = 0, length = arr.length, newArray = []; for (; i<length; i++) { newArray.push(arr[i]); } return newArray; } }; };wysihtml5.lang.Dispatcher = Base.extend( /** @scope wysihtml5.lang.Dialog.prototype */ { observe: function(eventName, handler) { this.events = this.events || {}; this.events[eventName] = this.events[eventName] || []; this.events[eventName].push(handler); return this; }, on: function() { return this.observe.apply(this, wysihtml5.lang.array(arguments).get()); }, fire: function(eventName, payload) { this.events = this.events || {}; var handlers = this.events[eventName] || [], i = 0; for (; i<handlers.length; i++) { handlers[i].call(this, payload); } return this; }, stopObserving: function(eventName, handler) { this.events = this.events || {}; var i = 0, handlers, newHandlers; if (eventName) { handlers = this.events[eventName] || [], newHandlers = []; for (; i<handlers.length; i++) { if (handlers[i] !== handler && handler) { newHandlers.push(handlers[i]); } } this.events[eventName] = newHandlers; } else { // Clean up all events this.events = {}; } return this; } });wysihtml5.lang.object = function(obj) { return { /** * @example * wysihtml5.lang.object({ foo: 1, bar: 1 }).merge({ bar: 2, baz: 3 }).get(); * // => { foo: 1, bar: 2, baz: 3 } */ merge: function(otherObj) { for (var i in otherObj) { obj[i] = otherObj[i]; } return this; }, get: function() { return obj; }, /** * @example * wysihtml5.lang.object({ foo: 1 }).clone(); * // => { foo: 1 } */ clone: function() { var newObj = {}, i; for (i in obj) { newObj[i] = obj[i]; } return newObj; }, /** * @example * wysihtml5.lang.object([]).isArray(); * // => true */ isArray: function() { return Object.prototype.toString.call(obj) === "[object Array]"; } }; };(function() { var WHITE_SPACE_START = /^\s+/, WHITE_SPACE_END = /\s+$/; wysihtml5.lang.string = function(str) { str = String(str); return { /** * @example * wysihtml5.lang.string(" foo ").trim(); * // => "foo" */ trim: function() { return str.replace(WHITE_SPACE_START, "").replace(WHITE_SPACE_END, ""); }, /** * @example * wysihtml5.lang.string("Hello #{name}").interpolate({ name: "Christopher" }); * // => "Hello Christopher" */ interpolate: function(vars) { for (var i in vars) { str = this.replace("#{" + i + "}").by(vars[i]); } return str; }, /** * @example * wysihtml5.lang.string("Hello Tom").replace("Tom").with("Hans"); * // => "Hello Hans" */ replace: function(search) { return { by: function(replace) { return str.split(search).join(replace); } } } }; }; })();/** * Find urls in descendant text nodes of an element and auto-links them * Inspired by http://james.padolsey.com/javascript/find-and-replace-text-with-javascript/ * * @param {Element} element Container element in which to search for urls * * @example * <div id="text-container">Please click here: www.google.com</div> * <script>wysihtml5.dom.autoLink(document.getElementById("text-container"));</script> */ (function(wysihtml5) { var /** * Don't auto-link urls that are contained in the following elements: */ IGNORE_URLS_IN = wysihtml5.lang.array(["CODE", "PRE", "A", "SCRIPT", "HEAD", "TITLE", "STYLE"]), /** * revision 1: * /(\S+\.{1}[^\s\,\.\!]+)/g * * revision 2: * /(\b(((https?|ftp):\/\/)|(www\.))[-A-Z0-9+&@#\/%?=~_|!:,.;\[\]]*[-A-Z0-9+&@#\/%=~_|])/gim * * put this in the beginning if you don't wan't to match within a word * (^|[\>\(\{\[\s\>]) */ URL_REG_EXP = /((https?:\/\/|www\.)[^\s<]{3,})/gi, TRAILING_CHAR_REG_EXP = /([^\w\/\-](,?))$/i, MAX_DISPLAY_LENGTH = 100, BRACKETS = { ")": "(", "]": "[", "}": "{" }; function autoLink(element) { if (_hasParentThatShouldBeIgnored(element)) { return element; } if (element === element.ownerDocument.documentElement) { element = element.ownerDocument.body; } return _parseNode(element); } /** * This is basically a rebuild of * the rails auto_link_urls text helper */ function _convertUrlsToLinks(str) { return str.replace(URL_REG_EXP, function(match, url) { var punctuation = (url.match(TRAILING_CHAR_REG_EXP) || [])[1] || "", opening = BRACKETS[punctuation]; url = url.replace(TRAILING_CHAR_REG_EXP, ""); if (url.split(opening).length > url.split(punctuation).length) { url = url + punctuation; punctuation = ""; } var realUrl = url, displayUrl = url; if (url.length > MAX_DISPLAY_LENGTH) { displayUrl = displayUrl.substr(0, MAX_DISPLAY_LENGTH) + "..."; } // Add http prefix if necessary if (realUrl.substr(0, 4) === "www.") { realUrl = "http://" + realUrl; } return '<a href="' + realUrl + '">' + displayUrl + '</a>' + punctuation; }); } /** * Creates or (if already cached) returns a temp element * for the given document object */ function _getTempElement(context) { var tempElement = context._wysihtml5_tempElement; if (!tempElement) { tempElement = context._wysihtml5_tempElement = context.createElement("div"); } return tempElement; } /** * Replaces the original text nodes with the newly auto-linked dom tree */ function _wrapMatchesInNode(textNode) { var parentNode = textNode.parentNode, tempElement = _getTempElement(parentNode.ownerDocument); // We need to insert an empty/temporary <span /> to fix IE quirks // Elsewise IE would strip white space in the beginning tempElement.innerHTML = "<span></span>" + _convertUrlsToLinks(textNode.data); tempElement.removeChild(tempElement.firstChild); while (tempElement.firstChild) { // inserts tempElement.firstChild before textNode parentNode.insertBefore(tempElement.firstChild, textNode); } parentNode.removeChild(textNode); } function _hasParentThatShouldBeIgnored(node) { var nodeName; while (node.parentNode) { node = node.parentNode; nodeName = node.nodeName; if (IGNORE_URLS_IN.contains(nodeName)) { return true; } else if (nodeName === "body") { return false; } } return false; } function _parseNode(element) { if (IGNORE_URLS_IN.contains(element.nodeName)) { return; } if (element.nodeType === wysihtml5.TEXT_NODE && element.data.match(URL_REG_EXP)) { _wrapMatchesInNode(element); return; } var childNodes = wysihtml5.lang.array(element.childNodes).get(), childNodesLength = childNodes.length, i = 0; for (; i<childNodesLength; i++) { _parseNode(childNodes[i]); } return element; } wysihtml5.dom.autoLink = autoLink; // Reveal url reg exp to the outside wysihtml5.dom.autoLink.URL_REG_EXP = URL_REG_EXP; })(wysihtml5);(function(wysihtml5) { var supportsClassList = wysihtml5.browser.supportsClassList(), api = wysihtml5.dom; api.addClass = function(element, className) { if (supportsClassList) { return element.classList.add(className); } if (api.hasClass(element, className)) { return; } element.className += " " + className; }; api.removeClass = function(element, className) { if (supportsClassList) { return element.classList.remove(className); } element.className = element.className.replace(new RegExp("(^|\\s+)" + className + "(\\s+|$)"), " "); }; api.hasClass = function(element, className) { if (supportsClassList) { return element.classList.contains(className); } var elementClassName = element.className; return (elementClassName.length > 0 && (elementClassName == className || new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName))); }; })(wysihtml5); wysihtml5.dom.contains = (function() { var documentElement = document.documentElement; if (documentElement.contains) { return function(container, element) { if (element.nodeType !== wysihtml5.ELEMENT_NODE) { element = element.parentNode; } return container !== element && container.contains(element); }; } else if (documentElement.compareDocumentPosition) { return function(container, element) { // https://developer.mozilla.org/en/DOM/Node.compareDocumentPosition return !!(container.compareDocumentPosition(element) & 16); }; } })();/** * Converts an HTML fragment/element into a unordered/ordered list * * @param {Element} element The element which should be turned into a list * @param {String} listType The list type in which to convert the tree (either "ul" or "ol") * @return {Element} The created list * * @example * <!-- Assume the following dom: --> * <span id="pseudo-list"> * eminem<br> * dr. dre * <div>50 Cent</div> * </span> * * <script> * wysihtml5.dom.convertToList(document.getElementById("pseudo-list"), "ul"); * </script> * * <!-- Will result in: --> * <ul> * <li>eminem</li> * <li>dr. dre</li> * <li>50 Cent</li> * </ul> */ wysihtml5.dom.convertToList = (function() { function _createListItem(doc, list) { var listItem = doc.createElement("li"); list.appendChild(listItem); return listItem; } function _createList(doc, type) { return doc.createElement(type); } function convertToList(element, listType) { if (element.nodeName === "UL" || element.nodeName === "OL" || element.nodeName === "MENU") { // Already a list return element; } var doc = element.ownerDocument, list = _createList(doc, listType), lineBreaks = element.querySelectorAll("br"), lineBreaksLength = lineBreaks.length, childNodes, childNodesLength, childNode, lineBreak, parentNode, isBlockElement, isLineBreak, currentListItem, i; // First find <br> at the end of inline elements and move them behind them for (i=0; i<lineBreaksLength; i++) { lineBreak = lineBreaks[i]; while ((parentNode = lineBreak.parentNode) && parentNode !== element && parentNode.lastChild === lineBreak) { if (wysihtml5.dom.getStyle("display").from(parentNode) === "block") { parentNode.removeChild(lineBreak); break; } wysihtml5.dom.insert(lineBreak).after(lineBreak.parentNode); } } childNodes = wysihtml5.lang.array(element.childNodes).get(); childNodesLength = childNodes.length; for (i=0; i<childNodesLength; i++) { currentListItem = currentListItem || _createListItem(doc, list); childNode = childNodes[i]; isBlockElement = wysihtml5.dom.getStyle("display").from(childNode) === "block"; isLineBreak = childNode.nodeName === "BR"; if (isBlockElement) { // Append blockElement to current <li> if empty, otherwise create a new one currentListItem = currentListItem.firstChild ? _createListItem(doc, list) : currentListItem; currentListItem.appendChild(childNode); currentListItem = null; continue; } if (isLineBreak) { // Only create a new list item in the next iteration when the current one has already content currentListItem = currentListItem.firstChild ? null : currentListItem; continue; } currentListItem.appendChild(childNode); } element.parentNode.replaceChild(list, element); return list; } return convertToList; })();/** * Copy a set of attributes from one element to another * * @param {Array} attributesToCopy List of attributes which should be copied * @return {Object} Returns an object which offers the "from" method which can be invoked with the element where to * copy the attributes from., this again returns an object which provides a method named "to" which can be invoked * with the element where to copy the attributes to (see example) * * @example * var textarea = document.querySelector("textarea"), * div = document.querySelector("div[contenteditable=true]"), * anotherDiv = document.querySelector("div.preview"); * wysihtml5.dom.copyAttributes(["spellcheck", "value", "placeholder"]).from(textarea).to(div).andTo(anotherDiv); * */ wysihtml5.dom.copyAttributes = function(attributesToCopy) { return { from: function(elementToCopyFrom) { return { to: function(elementToCopyTo) { var attribute, i = 0, length = attributesToCopy.length; for (; i<length; i++) { attribute = attributesToCopy[i]; if (typeof(elementToCopyFrom[attribute]) !== "undefined" && elementToCopyFrom[attribute] !== "") { elementToCopyTo[attribute] = elementToCopyFrom[attribute]; } } return { andTo: arguments.callee }; } }; } }; };/** * Copy a set of styles from one element to another * Please note that this only works properly across browsers when the element from which to copy the styles * is in the dom * * Interesting article on how to copy styles * * @param {Array} stylesToCopy List of styles which should be copied * @return {Object} Returns an object which offers the "from" method which can be invoked with the element where to * copy the styles from., this again returns an object which provides a method named "to" which can be invoked * with the element where to copy the styles to (see example) * * @example * var textarea = document.querySelector("textarea"), * div = document.querySelector("div[contenteditable=true]"), * anotherDiv = document.querySelector("div.preview"); * wysihtml5.dom.copyStyles(["overflow-y", "width", "height"]).from(textarea).to(div).andTo(anotherDiv); * */ (function(dom) { /** * Mozilla, WebKit and Opera recalculate the computed width when box-sizing: boder-box; is set * So if an element has "width: 200px; -moz-box-sizing: border-box; border: 1px;" then * its computed css width will be 198px */ var BOX_SIZING_PROPERTIES = ["-webkit-box-sizing", "-moz-box-sizing", "-ms-box-sizing", "box-sizing"]; var shouldIgnoreBoxSizingBorderBox = function(element) { if (hasBoxSizingBorderBox(element)) { return parseInt(dom.getStyle("width").from(element), 10) < element.offsetWidth; } return false; }; var hasBoxSizingBorderBox = function(element) { var i = 0, length = BOX_SIZING_PROPERTIES.length; for (; i<length; i++) { if (dom.getStyle(BOX_SIZING_PROPERTIES[i]).from(element) === "border-box") { return BOX_SIZING_PROPERTIES[i]; } } }; dom.copyStyles = function(stylesToCopy) { return { from: function(element) { if (shouldIgnoreBoxSizingBorderBox(element)) { stylesToCopy = wysihtml5.lang.array(stylesToCopy).without(BOX_SIZING_PROPERTIES); } var cssText = "", length = stylesToCopy.length, i = 0, property; for (; i<length; i++) { property = stylesToCopy[i]; cssText += property + ":" + dom.getStyle(property).from(element) + ";"; } return { to: function(element) { dom.setStyles(cssText).on(element); return { andTo: arguments.callee }; } }; } }; }; })(wysihtml5.dom);/** * Event Delegation * * @example * wysihtml5.dom.delegate(document.body, "a", "click", function() { * // foo * }); */ (function(wysihtml5) { wysihtml5.dom.delegate = function(container, selector, eventName, handler) { return wysihtml5.dom.observe(container, eventName, function(event) { var target = event.target, match = wysihtml5.lang.array(container.querySelectorAll(selector)); while (target && target !== container) { if (match.contains(target)) { handler.call(target, event); break; } target = target.parentNode; } }); }; })(wysihtml5);/** * Returns the given html wrapped in a div element * * Fixing IE's inability to treat unknown elements (HTML5 section, article, ...) correctly * when inserted via innerHTML * * @param {String} html The html which should be wrapped in a dom element * @param {Obejct} [context] Document object of the context the html belongs to * * @example * wysihtml5.dom.getAsDom("<article>foo</article>"); */ wysihtml5.dom.getAsDom = (function() { var _innerHTMLShiv = function(html, context) { var tempElement = context.createElement("div"); tempElement.style.display = "none"; context.body.appendChild(tempElement); // IE throws an exception when trying to insert <frameset></frameset> via innerHTML try { tempElement.innerHTML = html; } catch(e) {} context.body.removeChild(tempElement); return tempElement; }; /** * Make sure IE supports HTML5 tags, which is accomplished by simply creating one instance of each element */ var _ensureHTML5Compatibility = function(context) { if (context._wysihtml5_supportsHTML5Tags) { return; } for (var i=0, length=HTML5_ELEMENTS.length; i<length; i++) { context.createElement(HTML5_ELEMENTS[i]); } context._wysihtml5_supportsHTML5Tags = true; }; /** * List of html5 tags * taken from http://simon.html5.org/html5-elements */ var HTML5_ELEMENTS = [ "abbr", "article", "aside", "audio", "bdi", "canvas", "command", "datalist", "details", "figcaption", "figure", "footer", "header", "hgroup", "keygen", "mark", "meter", "nav", "output", "progress", "rp", "rt", "ruby", "svg", "section", "source", "summary", "time", "track", "video", "wbr" ]; return function(html, context) { context = context || document; var tempElement; if (typeof(html) === "object" && html.nodeType) { tempElement = context.createElement("div"); tempElement.appendChild(html); } else if (wysihtml5.browser.supportsHTML5Tags(context)) { tempElement = context.createElement("div"); tempElement.innerHTML = html; } else { _ensureHTML5Compatibility(context); tempElement = _innerHTMLShiv(html, context); } return tempElement; }; })();/** * Walks the dom tree from the given node up until it finds a match * Designed for optimal performance. * * @param {Element} node The from which to check the parent nodes * @param {Object} matchingSet Object to match against (possible properties: nodeName, className, classRegExp) * @param {Number} [levels] How many parents should the function check up from the current node (defaults to 50) * @return {null|Element} Returns the first element that matched the desiredNodeName(s) * @example * var listElement = wysihtml5.dom.getParentElement(document.querySelector("li"), { nodeName: ["MENU", "UL", "OL"] }); * // ... or ... * var unorderedListElement = wysihtml5.dom.getParentElement(document.querySelector("li"), { nodeName: "UL" }); * // ... or ... * var coloredElement = wysihtml5.dom.getParentElement(myTextNode, { nodeName: "SPAN", className: "wysiwyg-color-red", classRegExp: /wysiwyg-color-[a-z]/g }); */ wysihtml5.dom.getParentElement = (function() { function _isSameNodeName(nodeName, desiredNodeNames) { if (!desiredNodeNames || !desiredNodeNames.length) { return true; } if (typeof(desiredNodeNames) === "string") { return nodeName === desiredNodeNames; } else { return wysihtml5.lang.array(desiredNodeNames).contains(nodeName); } } function _isElement(node) { return node.nodeType === wysihtml5.ELEMENT_NODE; } function _hasClassName(element, className, classRegExp) { var classNames = (element.className || "").match(classRegExp) || []; if (!className) { return !!classNames.length; } return classNames[classNames.length - 1] === className; } function _getParentElementWithNodeName(node, nodeName, levels) { while (levels-- && node && node.nodeName !== "BODY") { if (_isSameNodeName(node.nodeName, nodeName)) { return node; } node = node.parentNode; } return null; } function _getParentElementWithNodeNameAndClassName(node, nodeName, className, classRegExp, levels) { while (levels-- && node && node.nodeName !== "BODY") { if (_isElement(node) && _isSameNodeName(node.nodeName, nodeName) && _hasClassName(node, className, classRegExp)) { return node; } node = node.parentNode; } return null; } return function(node, matchingSet, levels) { levels = levels || 50; // Go max 50 nodes upwards from current node if (matchingSet.className || matchingSet.classRegExp) { return _getParentElementWithNodeNameAndClassName( node, matchingSet.nodeName, matchingSet.className, matchingSet.classRegExp, levels ); } else { return _getParentElementWithNodeName( node, matchingSet.nodeName, levels ); } }; })(); /** * Get element's style for a specific css property * * @param {Element} element The element on which to retrieve the style * @param {String} property The CSS property to retrieve ("float", "display", "text-align", ...) * * @example * wysihtml5.dom.getStyle("display").from(document.body); * // => "block" */ wysihtml5.dom.getStyle = (function() { var stylePropertyMapping = { "float": ("styleFloat" in document.createElement("div").style) ? "styleFloat" : "cssFloat" }, REG_EXP_CAMELIZE = /\-[a-z]/g; function camelize(str) { return str.replace(REG_EXP_CAMELIZE, function(match) { return match.charAt(1).toUpperCase(); }); } return function(property) { return { from: function(element) { if (element.nodeType !== wysihtml5.ELEMENT_NODE) { return; } var doc = element.ownerDocument, camelizedProperty = stylePropertyMapping[property] || camelize(property), style = element.style, currentStyle = element.currentStyle, styleValue = style[camelizedProperty]; if (styleValue) { return styleValue; } // currentStyle is no standard and only supported by Opera and IE but it has one important advantage over the standard-compliant // window.getComputedStyle, since it returns css property values in their original unit: // If you set an elements width to "50%", window.getComputedStyle will give you it's current width in px while currentStyle // gives you the original "50%". // Opera supports both, currentStyle and window.getComputedStyle, that's why checking for currentStyle should have higher prio if (currentStyle) { try { return currentStyle[camelizedProperty]; } catch(e) { //ie will occasionally fail for unknown reasons. swallowing exception } } var win = doc.defaultView || doc.parentWindow, needsOverflowReset = (property === "height" || property === "width") && element.nodeName === "TEXTAREA", originalOverflow, returnValue; if (win.getComputedStyle) { // Chrome and Safari both calculate a wrong width and height for textareas when they have scroll bars // therfore we remove and restore the scrollbar and calculate the value in between if (needsOverflowReset) { originalOverflow = style.overflow; style.overflow = "hidden"; } returnValue = win.getComputedStyle(element, null).getPropertyValue(property); if (needsOverflowReset) { style.overflow = originalOverflow || ""; } return returnValue; } } }; }; })();/** * High performant way to check whether an element with a specific tag name is in the given document * Optimized for being heavily executed * Unleashes the power of live node lists * * @param {Object} doc The document object of the context where to check * @param {String} tagName Upper cased tag name * @example * wysihtml5.dom.hasElementWithTagName(document, "IMG"); */ wysihtml5.dom.hasElementWithTagName = (function() { var LIVE_CACHE = {}, DOCUMENT_IDENTIFIER = 1; function _getDocumentIdentifier(doc) { return doc._wysihtml5_identifier || (doc._wysihtml5_identifier = DOCUMENT_IDENTIFIER++); } return function(doc, tagName) { var key = _getDocumentIdentifier(doc) + ":" + tagName, cacheEntry = LIVE_CACHE[key]; if (!cacheEntry) { cacheEntry = LIVE_CACHE[key] = doc.getElementsByTagName(tagName); } return cacheEntry.length > 0; }; })();/** * High performant way to check whether an element with a specific class name is in the given document * Optimized for being heavily executed * Unleashes the power of live node lists * * @param {Object} doc The document object of the context where to check * @param {String} tagName Upper cased tag name * @example * wysihtml5.dom.hasElementWithClassName(document, "foobar"); */ (function(wysihtml5) { var LIVE_CACHE = {}, DOCUMENT_IDENTIFIER = 1; function _getDocumentIdentifier(doc) { return doc._wysihtml5_identifier || (doc._wysihtml5_identifier = DOCUMENT_IDENTIFIER++); } wysihtml5.dom.hasElementWithClassName = function(doc, className) { // getElementsByClassName is not supported by IE<9 // but is sometimes mocked via library code (which then doesn't return live node lists) if (!wysihtml5.browser.supportsNativeGetElementsByClassName()) { return !!doc.querySelector("." + className); } var key = _getDocumentIdentifier(doc) + ":" + className, cacheEntry = LIVE_CACHE[key]; if (!cacheEntry) { cacheEntry = LIVE_CACHE[key] = doc.getElementsByClassName(className); } return cacheEntry.length > 0; }; })(wysihtml5); wysihtml5.dom.insert = function(elementToInsert) { return { after: function(element) { element.parentNode.insertBefore(elementToInsert, element.nextSibling); }, before: function(element) { element.parentNode.insertBefore(elementToInsert, element); }, into: function(element) { element.appendChild(elementToInsert); } }; };wysihtml5.dom.insertCSS = function(rules) { rules = rules.join("\n"); return { into: function(doc) { var head = doc.head || doc.getElementsByTagName("head")[0], styleElement = doc.createElement("style"); styleElement.type = "text/css"; if (styleElement.styleSheet) { styleElement.styleSheet.cssText = rules; } else { styleElement.appendChild(doc.createTextNode(rules)); } if (head) { head.appendChild(styleElement); } } }; };/** * Method to set dom events * * @example * wysihtml5.dom.observe(iframe.contentWindow.document.body, ["focus", "blur"], function() { ... }); */ wysihtml5.dom.observe = function(element, eventNames, handler) { eventNames = typeof(eventNames) === "string" ? [eventNames] : eventNames; var handlerWrapper, eventName, i = 0, length = eventNames.length; for (; i<length; i++) { eventName = eventNames[i]; if (element.addEventListener) { element.addEventListener(eventName, handler, false); } else { handlerWrapper = function(event) { if (!("target" in event)) { event.target = event.srcElement; } event.preventDefault = event.preventDefault || function() { this.returnValue = false; }; event.stopPropagation = event.stopPropagation || function() { this.cancelBubble = true; }; handler.call(element, event); }; element.attachEvent("on" + eventName, handlerWrapper); } } return { stop: function() { var eventName, i = 0, length = eventNames.length; for (; i<length; i++) { eventName = eventNames[i]; if (element.removeEventListener) { element.removeEventListener(eventName, handler, false); } else { element.detachEvent("on" + eventName, handlerWrapper); } } } }; }; /** * HTML Sanitizer * Rewrites the HTML based on given rules * * @param {Element|String} elementOrHtml HTML String to be sanitized OR element whose content should be sanitized * @param {Object} [rules] List of rules for rewriting the HTML, if there's no rule for an element it will * be converted to a "span". Each rule is a key/value pair where key is the tag to convert, and value the * desired substitution. * @param {Object} context Document object in which to parse the html, needed to sandbox the parsing * * @return {Element|String} Depends on the elementOrHtml parameter. When html then the sanitized html as string elsewise the element. * * @example * var userHTML = '<div id="foo" onclick="alert(1);"><p><font color="red">foo</font><script>alert(1);</script></p></div>'; * wysihtml5.dom.parse(userHTML, { * tags { * p: "div", // Rename p tags to div tags * font: "span" // Rename font tags to span tags * div: true, // Keep them, also possible (same result when passing: "div" or true) * script: undefined // Remove script elements * } * }); * // => <div><div><span>foo bar</span></div></div> * * var userHTML = '<table><tbody><tr><td>I'm a table!</td></tr></tbody></table>'; * wysihtml5.dom.parse(userHTML); * // => '<span><span><span><span>I'm a table!</span></span></span></span>' * * var userHTML = '<div>foobar<br>foobar</div>'; * wysihtml5.dom.parse(userHTML, { * tags: { * div: undefined, * br: true * } * }); * // => '' * * var userHTML = '<div class="red">foo</div><div class="pink">bar</div>'; * wysihtml5.dom.parse(userHTML, { * classes: { * red: 1, * green: 1 * }, * tags: { * div: { * rename_tag: "p" * } * } * }); * // => '<p class="red">foo</p><p>bar</p>' */ wysihtml5.dom.parse = (function() { /** * It's not possible to use a XMLParser/DOMParser as HTML5 is not always well-formed XML * new DOMParser().parseFromString('<img src="foo.gif">') will cause a parseError since the * node isn't closed * * Therefore we've to use the browser's ordinary HTML parser invoked by setting innerHTML. */ var NODE_TYPE_MAPPING = { "1": _handleElement, "3": _handleText }, // Rename unknown tags to this DEFAULT_NODE_NAME = "span", WHITE_SPACE_REG_EXP = /\s+/, defaultRules = { tags: {}, classes: {} }, currentRules = {}; /** * Iterates over all childs of the element, recreates them, appends them into a document fragment * which later replaces the entire body content */ function parse(elementOrHtml, rules, context, cleanUp) { wysihtml5.lang.object(currentRules).merge(defaultRules).merge(rules).get(); context = context || elementOrHtml.ownerDocument || document; var fragment = context.createDocumentFragment(), isString = typeof(elementOrHtml) === "string", element, newNode, firstChild; if (isString) { element = wysihtml5.dom.getAsDom(elementOrHtml, context); } else { element = elementOrHtml; } while (element.firstChild) { firstChild = element.firstChild; element.removeChild(firstChild); newNode = _convert(firstChild, cleanUp); if (newNode) { fragment.appendChild(newNode); } } // Clear element contents element.innerHTML = ""; // Insert new DOM tree element.appendChild(fragment); return isString ? wysihtml5.quirks.getCorrectInnerHTML(element) : element; } function _convert(oldNode, cleanUp) { var oldNodeType = oldNode.nodeType, oldChilds = oldNode.childNodes, oldChildsLength = oldChilds.length, newNode, method = NODE_TYPE_MAPPING[oldNodeType], i = 0; newNode = method && method(oldNode); if (!newNode) { return null; } for (i=0; i<oldChildsLength; i++) { newChild = _convert(oldChilds[i], cleanUp); if (newChild) { newNode.appendChild(newChild); } } // Cleanup senseless <span> elements if (cleanUp && newNode.childNodes.length <= 1 && newNode.nodeName.toLowerCase() === DEFAULT_NODE_NAME && !newNode.attributes.length) { return newNode.firstChild; } return newNode; } function _handleElement(oldNode) { var rule, newNode, endTag, tagRules = currentRules.tags, nodeName = oldNode.nodeName.toLowerCase(), scopeName = oldNode.scopeName; /** * We already parsed that element * ignore it! (yes, this sometimes happens in IE8 when the html is invalid) */ if (oldNode._wysihtml5) { return null; } oldNode._wysihtml5 = 1; if (oldNode.className === "wysihtml5-temp") { return null; } /** * IE is the only browser who doesn't include the namespace in the * nodeName, that's why we have to prepend it by ourselves * scopeName is a proprietary IE feature * read more here http://msdn.microsoft.com/en-us/library/ms534388(v=vs.85).aspx */ if (scopeName && scopeName != "HTML") { nodeName = scopeName + ":" + nodeName; } /** * Repair node * IE is a bit bitchy when it comes to invalid nested markup which includes unclosed tags * A <p> doesn't need to be closed according HTML4-5 spec, we simply replace it with a <div> to preserve its content and layout */ if ("outerHTML" in oldNode) { if (!wysihtml5.browser.autoClosesUnclosedTags() && oldNode.nodeName === "P" && oldNode.outerHTML.slice(-4).toLowerCase() !== "</p>") { nodeName = "div"; } } if (nodeName in tagRules) { rule = tagRules[nodeName]; if (!rule || rule.remove) { return null; } rule = typeof(rule) === "string" ? { rename_tag: rule } : rule; } else if (oldNode.firstChild) { rule = { rename_tag: DEFAULT_NODE_NAME }; } else { // Remove empty unknown elements return null; } newNode = oldNode.ownerDocument.createElement(rule.rename_tag || nodeName); _handleAttributes(oldNode, newNode, rule); oldNode = null; return newNode; } function _handleAttributes(oldNode, newNode, rule) { var attributes = {}, // fresh new set of attributes to set on newNode setClass = rule.set_class, // classes to set addClass = rule.add_class, // add classes based on existing attributes setAttributes = rule.set_attributes, // attributes to set on the current node checkAttributes = rule.check_attributes, // check/convert values of attributes allowedClasses = currentRules.classes, i = 0, classes = [], newClasses = [], newUniqueClasses = [], oldClasses = [], classesLength, newClassesLength, currentClass, newClass, attributeName, newAttributeValue, method; if (setAttributes) { attributes = wysihtml5.lang.object(setAttributes).clone(); } if (checkAttributes) { for (attributeName in checkAttributes) { method = attributeCheckMethods[checkAttributes[attributeName]]; if (!method) { continue; } newAttributeValue = method(_getAttribute(oldNode, attributeName)); if (typeof(newAttributeValue) === "string") { attributes[attributeName] = newAttributeValue; } } } if (setClass) { classes.push(setClass); } if (addClass) { for (attributeName in addClass) { method = addClassMethods[addClass[attributeName]]; if (!method) { continue; } newClass = method(_getAttribute(oldNode, attributeName)); if (typeof(newClass) === "string") { classes.push(newClass); } } } // make sure that wysihtml5 temp class doesn't get stripped out allowedClasses["_wysihtml5-temp-placeholder"] = 1; // add old classes last oldClasses = oldNode.getAttribute("class"); if (oldClasses) { classes = classes.concat(oldClasses.split(WHITE_SPACE_REG_EXP)); } classesLength = classes.length; for (; i<classesLength; i++) { currentClass = classes[i]; if (allowedClasses[currentClass]) { newClasses.push(currentClass); } } // remove duplicate entries and preserve class specificity newClassesLength = newClasses.length; while (newClassesLength--) { currentClass = newClasses[newClassesLength]; if (!wysihtml5.lang.array(newUniqueClasses).contains(currentClass)) { newUniqueClasses.unshift(currentClass); } } if (newUniqueClasses.length) { attributes["class"] = newUniqueClasses.join(" "); } // set attributes on newNode for (attributeName in attributes) { // Setting attributes can cause a js error in IE under certain circumstances // eg. on a <img> under https when it's new attribute value is non-https // TODO: Investigate this further and check for smarter handling try { newNode.setAttribute(attributeName, attributes[attributeName]); } catch(e) {} } // IE8 sometimes loses the width/height attributes when those are set before the "src" // so we make sure to set them again if (attributes.src) { if (typeof(attributes.width) !== "undefined") { newNode.setAttribute("width", attributes.width); } if (typeof(attributes.height) !== "undefined") { newNode.setAttribute("height", attributes.height); } } } /** * IE gives wrong results for hasAttribute/getAttribute, for example: * var td = document.createElement("td"); * td.getAttribute("rowspan"); // => "1" in IE * * Therefore we have to check the element's outerHTML for the attribute */ var HAS_GET_ATTRIBUTE_BUG = !wysihtml5.browser.supportsGetAttributeCorrectly(); function _getAttribute(node, attributeName) { attributeName = attributeName.toLowerCase(); var nodeName = node.nodeName; if (nodeName == "IMG" && attributeName == "src" && _isLoadedImage(node) === true) { // Get 'src' attribute value via object property since this will always contain the // full absolute url (http://...) // this fixes a very annoying bug in firefox (ver 3.6 & 4) and IE 8 where images copied from the same host // will have relative paths, which the sanitizer strips out (see attributeCheckMethods.url) return node.src; } else if (HAS_GET_ATTRIBUTE_BUG && "outerHTML" in node) { // Don't trust getAttribute/hasAttribute in IE 6-8, instead check the element's outerHTML var outerHTML = node.outerHTML.toLowerCase(), // TODO: This might not work for attributes without value: <input disabled> hasAttribute = outerHTML.indexOf(" " + attributeName + "=") != -1; return hasAttribute ? node.getAttribute(attributeName) : null; } else{ return node.getAttribute(attributeName); } } /** * Check whether the given node is a proper loaded image * FIXME: Returns undefined when unknown (Chrome, Safari) */ function _isLoadedImage(node) { try { return node.complete && !node.mozMatchesSelector(":-moz-broken"); } catch(e) { if (node.complete && node.readyState === "complete") { return true; } } } function _handleText(oldNode) { return oldNode.ownerDocument.createTextNode(oldNode.data); } // ------------ attribute checks ------------ \\ var attributeCheckMethods = { url: (function() { var REG_EXP = /^https?:\/\//i; return function(attributeValue) { if (!attributeValue || !attributeValue.match(REG_EXP)) { return null; } return attributeValue.replace(REG_EXP, function(match) { return match.toLowerCase(); }); }; })(), alt: (function() { var REG_EXP = /[^ a-z0-9_\-]/gi; return function(attributeValue) { if (!attributeValue) { return ""; } return attributeValue.replace(REG_EXP, ""); }; })(), numbers: (function() { var REG_EXP = /\D/g; return function(attributeValue) { attributeValue = (attributeValue || "").replace(REG_EXP, ""); return attributeValue || null; }; })() }; // ------------ class converter (converts an html attribute to a class name) ------------ \\ var addClassMethods = { align_img: (function() { var mapping = { left: "wysiwyg-float-left", right: "wysiwyg-float-right" }; return function(attributeValue) { return mapping[String(attributeValue).toLowerCase()]; }; })(), align_text: (function() { var mapping = { left: "wysiwyg-text-align-left", right: "wysiwyg-text-align-right", center: "wysiwyg-text-align-center", justify: "wysiwyg-text-align-justify" }; return function(attributeValue) { return mapping[String(attributeValue).toLowerCase()]; }; })(), clear_br: (function() { var mapping = { left: "wysiwyg-clear-left", right: "wysiwyg-clear-right", both: "wysiwyg-clear-both", all: "wysiwyg-clear-both" }; return function(attributeValue) { return mapping[String(attributeValue).toLowerCase()]; }; })(), size_font: (function() { var mapping = { "1": "wysiwyg-font-size-xx-small", "2": "wysiwyg-font-size-small", "3": "wysiwyg-font-size-medium", "4": "wysiwyg-font-size-large", "5": "wysiwyg-font-size-x-large", "6": "wysiwyg-font-size-xx-large", "7": "wysiwyg-font-size-xx-large", "-": "wysiwyg-font-size-smaller", "+": "wysiwyg-font-size-larger" }; return function(attributeValue) { return mapping[String(attributeValue).charAt(0)]; }; })() }; return parse; })();/** * Checks for empty text node childs and removes them * * @param {Element} node The element in which to cleanup * @example * wysihtml5.dom.removeEmptyTextNodes(element); */ wysihtml5.dom.removeEmptyTextNodes = function(node) { var childNode, childNodes = wysihtml5.lang.array(node.childNodes).get(), childNodesLength = childNodes.length, i = 0; for (; i<childNodesLength; i++) { childNode = childNodes[i]; if (childNode.nodeType === wysihtml5.TEXT_NODE && childNode.data === "") { childNode.parentNode.removeChild(childNode); } } }; /** * Renames an element (eg. a <div> to a <p>) and keeps its childs * * @param {Element} element The list element which should be renamed * @param {Element} newNodeName The desired tag name * * @example * <!-- Assume the following dom: --> * <ul id="list"> * <li>eminem</li> * <li>dr. dre</li> * <li>50 Cent</li> * </ul> * * <script> * wysihtml5.dom.renameElement(document.getElementById("list"), "ol"); * </script> * * <!-- Will result in: --> * <ol> * <li>eminem</li> * <li>dr. dre</li> * <li>50 Cent</li> * </ol> */ wysihtml5.dom.renameElement = function(element, newNodeName) { var newElement = element.ownerDocument.createElement(newNodeName), firstChild; while (firstChild = element.firstChild) { newElement.appendChild(firstChild); } wysihtml5.dom.copyAttributes(["align", "className"]).from(element).to(newElement); element.parentNode.replaceChild(newElement, element); return newElement; };/** * Takes an element, removes it and replaces it with it's childs * * @param {Object} node The node which to replace with it's child nodes * @example * <div id="foo"> * <span>hello</span> * </div> * <script> * // Remove #foo and replace with it's children * wysihtml5.dom.replaceWithChildNodes(document.getElementById("foo")); * </script> */ wysihtml5.dom.replaceWithChildNodes = function(node) { if (!node.parentNode) { return; } if (!node.firstChild) { node.parentNode.removeChild(node); return; } var fragment = node.ownerDocument.createDocumentFragment(); while (node.firstChild) { fragment.appendChild(node.firstChild); } node.parentNode.replaceChild(fragment, node); node = fragment = null; }; /** * Unwraps an unordered/ordered list * * @param {Element} element The list element which should be unwrapped * * @example * <!-- Assume the following dom: --> * <ul id="list"> * <li>eminem</li> * <li>dr. dre</li> * <li>50 Cent</li> * </ul> * * <script> * wysihtml5.dom.resolveList(document.getElementById("list")); * </script> * * <!-- Will result in: --> * eminem<br> * dr. dre<br> * 50 Cent<br> */ (function(dom) { function _isBlockElement(node) { return dom.getStyle("display").from(node) === "block"; } function _isLineBreak(node) { return node.nodeName === "BR"; } function _appendLineBreak(element) { var lineBreak = element.ownerDocument.createElement("br"); element.appendChild(lineBreak); } function resolveList(list) { if (list.nodeName !== "MENU" && list.nodeName !== "UL" && list.nodeName !== "OL") { return; } var doc = list.ownerDocument, fragment = doc.createDocumentFragment(), previousSibling = list.previousElementSibling || list.previousSibling, firstChild, lastChild, isLastChild, shouldAppendLineBreak, listItem; if (previousSibling && !_isBlockElement(previousSibling)) { _appendLineBreak(fragment); } while (listItem = list.firstChild) { lastChild = listItem.lastChild; while (firstChild = listItem.firstChild) { isLastChild = firstChild === lastChild; // This needs to be done before appending it to the fragment, as it otherwise will loose style information shouldAppendLineBreak = isLastChild && !_isBlockElement(firstChild) && !_isLineBreak(firstChild); fragment.appendChild(firstChild); if (shouldAppendLineBreak) { _appendLineBreak(fragment); } } listItem.parentNode.removeChild(listItem); } list.parentNode.replaceChild(fragment, list); } dom.resolveList = resolveList; })(wysihtml5.dom);/** * Sandbox for executing javascript, parsing css styles and doing dom operations in a secure way * * Browser Compatibility: * - Secure in MSIE 6+, but only when the user hasn't made changes to his security level "restricted" * - Partially secure in other browsers (Firefox, Opera, Safari, Chrome, ...) * * Please note that this class can't benefit from the HTML5 sandbox attribute for the following reasons: * - sandboxing doesn't work correctly with inlined content (src="javascript:'<html>...</html>'") * - sandboxing of physical documents causes that the dom isn't accessible anymore from the outside (iframe.contentWindow, ...) * - setting the "allow-same-origin" flag would fix that, but then still javascript and dom events refuse to fire * - therefore the "allow-scripts" flag is needed, which then would deactivate any security, as the js executed inside the iframe * can do anything as if the sandbox attribute wasn't set * * @param {Function} [readyCallback] Method that gets invoked when the sandbox is ready * @param {Object} [config] Optional parameters * * @example * new wysihtml5.dom.Sandbox(function(sandbox) { * sandbox.getWindow().document.body.innerHTML = '<img src=foo.gif onerror="alert(document.cookie)">'; * }); */ (function(wysihtml5) { var /** * Default configuration */ doc = document, /** * Properties to unset/protect on the window object */ windowProperties = [ "parent", "top", "opener", "frameElement", "frames", "localStorage", "globalStorage", "sessionStorage", "indexedDB" ], /** * Properties on the window object which are set to an empty function */ windowProperties2 = [ "open", "close", "openDialog", "showModalDialog", "alert", "confirm", "prompt", "openDatabase", "postMessage", "XMLHttpRequest", "XDomainRequest" ], /** * Properties to unset/protect on the document object */ documentProperties = [ "referrer", "write", "open", "close" ]; wysihtml5.dom.Sandbox = Base.extend( /** @scope wysihtml5.dom.Sandbox.prototype */ { constructor: function(readyCallback, config) { this.callback = readyCallback || wysihtml5.EMPTY_FUNCTION; this.config = wysihtml5.lang.object({}).merge(config).get(); this.iframe = this._createIframe(); }, insertInto: function(element) { if (typeof(element) === "string") { element = doc.getElementById(element); } element.appendChild(this.iframe); }, getIframe: function() { return this.iframe; }, getWindow: function() { this._readyError(); }, getDocument: function() { this._readyError(); }, destroy: function() { var iframe = this.getIframe(); iframe.parentNode.removeChild(iframe); }, _readyError: function() { throw new Error("wysihtml5.Sandbox: Sandbox iframe isn't loaded yet"); }, /** * Creates the sandbox iframe * * Some important notes: * - We can't use HTML5 sandbox for now: * setting it causes that the iframe's dom can't be accessed from the outside * Therefore we need to set the "allow-same-origin" flag which enables accessing the iframe's dom * But then there's another problem, DOM events (focus, blur, change, keypress, ...) aren't fired. * In order to make this happen we need to set the "allow-scripts" flag. * A combination of allow-scripts and allow-same-origin is almost the same as setting no sandbox attribute at all. * - Chrome & Safari, doesn't seem to support sandboxing correctly when the iframe's html is inlined (no physical document) * - IE needs to have the security="restricted" attribute set before the iframe is * inserted into the dom tree * - Believe it or not but in IE "security" in document.createElement("iframe") is false, even * though it supports it * - When an iframe has security="restricted", in IE eval() & execScript() don't work anymore * - IE doesn't fire the onload event when the content is inlined in the src attribute, therefore we rely * on the onreadystatechange event */ _createIframe: function() { var that = this, iframe = doc.createElement("iframe"); iframe.className = "wysihtml5-sandbox"; wysihtml5.dom.setAttributes({ "security": "restricted", "allowtransparency": "true", "frameborder": 0, "width": 0, "height": 0, "marginwidth": 0, "marginheight": 0 }).on(iframe); // Setting the src like this prevents ssl warnings in IE6 if (wysihtml5.browser.throwsMixedContentWarningWhenIframeSrcIsEmpty()) { iframe.src = "javascript:'<html></html>'"; } iframe.onload = function() { iframe.onreadystatechange = iframe.onload = null; that._onLoadIframe(iframe); }; iframe.onreadystatechange = function() { if (/loaded|complete/.test(iframe.readyState)) { iframe.onreadystatechange = iframe.onload = null; that._onLoadIframe(iframe); } }; return iframe; }, /** * Callback for when the iframe has finished loading */ _onLoadIframe: function(iframe) { // don't resume when the iframe got unloaded (eg. by removing it from the dom) if (!wysihtml5.dom.contains(doc.documentElement, iframe)) { return; } var that = this, iframeWindow = iframe.contentWindow, iframeDocument = iframe.contentWindow.document, charset = doc.characterSet || doc.charset || "utf-8", sandboxHtml = this._getHtml({ charset: charset, stylesheets: this.config.stylesheets }); // Create the basic dom tree including proper DOCTYPE and charset iframeDocument.open("text/html", "replace"); iframeDocument.write(sandboxHtml); iframeDocument.close(); this.getWindow = function() { return iframe.contentWindow; }; this.getDocument = function() { return iframe.contentWindow.document; }; // Catch js errors and pass them to the parent's onerror event // addEventListener("error") doesn't work properly in some browsers // TODO: apparently this doesn't work in IE9! iframeWindow.onerror = function(errorMessage, fileName, lineNumber) { throw new Error("wysihtml5.Sandbox: " + errorMessage, fileName, lineNumber); }; if (!wysihtml5.browser.supportsSandboxedIframes()) { // Unset a bunch of sensitive variables // Please note: This isn't hack safe! // It more or less just takes care of basic attacks and prevents accidental theft of sensitive information // IE is secure though, which is the most important thing, since IE is the only browser, who // takes over scripts & styles into contentEditable elements when copied from external websites // or applications (Microsoft Word, ...) var i, length; for (i=0, length=windowProperties.length; i<length; i++) { this._unset(iframeWindow, windowProperties[i]); } for (i=0, length=windowProperties2.length; i<length; i++) { this._unset(iframeWindow, windowProperties2[i], wysihtml5.EMPTY_FUNCTION); } for (i=0, length=documentProperties.length; i<length; i++) { this._unset(iframeDocument, documentProperties[i]); } // This doesn't work in Safari 5 // See http://stackoverflow.com/questions/992461/is-it-possible-to-override-document-cookie-in-webkit this._unset(iframeDocument, "cookie", "", true); } this.loaded = true; // Trigger the callback setTimeout(function() { that.callback(that); }, 0); }, _getHtml: function(templateVars) { var stylesheets = templateVars.stylesheets, html = "", i = 0, length; stylesheets = typeof(stylesheets) === "string" ? [stylesheets] : stylesheets; if (stylesheets) { length = stylesheets.length; for (; i<length; i++) { html += '<link rel="stylesheet" href="' + stylesheets[i] + '">'; } } templateVars.stylesheets = html; return wysihtml5.lang.string( '<!DOCTYPE html><html><head>' + '<meta charset="#{charset}">#{stylesheets}</head>' + '<body></body></html>' ).interpolate(templateVars); }, /** * Method to unset/override existing variables * @example * // Make cookie unreadable and unwritable * this._unset(document, "cookie", "", true); */ _unset: function(object, property, value, setter) { try { object[property] = value; } catch(e) {} try { object.__defineGetter__(property, function() { return value; }); } catch(e) {} if (setter) { try { object.__defineSetter__(property, function() {}); } catch(e) {} } if (!wysihtml5.browser.crashesWhenDefineProperty(property)) { try { var config = { get: function() { return value; } }; if (setter) { config.set = function() {}; } Object.defineProperty(object, property, config); } catch(e) {} } } }); })(wysihtml5); (function() { var mapping = { "className": "class" }; wysihtml5.dom.setAttributes = function(attributes) { return { on: function(element) { for (var i in attributes) { element.setAttribute(mapping[i] || i, attributes[i]); } } } }; })();wysihtml5.dom.setStyles = function(styles) { return { on: function(element) { var style = element.style; if (typeof(styles) === "string") { style.cssText += ";" + styles; return; } for (var i in styles) { if (i === "float") { style.cssFloat = styles[i]; style.styleFloat = styles[i]; } else { style[i] = styles[i]; } } } }; };/** * Simulate HTML5 placeholder attribute * * Needed since * - div[contentEditable] elements don't support it * - older browsers (such as IE8 and Firefox 3.6) don't support it at all * * @param {Object} parent Instance of main wysihtml5.Editor class * @param {Element} view Instance of wysihtml5.views.* class * @param {String} placeholderText * * @example * wysihtml.dom.simulatePlaceholder(this, composer, "Foobar"); */ (function(dom) { dom.simulatePlaceholder = function(editor, view, placeholderText) { var CLASS_NAME = "placeholder", unset = function() { if (view.hasPlaceholderSet()) { view.clear(); } dom.removeClass(view.element, CLASS_NAME); }, set = function() { if (view.isEmpty()) { view.setValue(placeholderText); dom.addClass(view.element, CLASS_NAME); } }; editor .observe("set_placeholder", set) .observe("unset_placeholder", unset) .observe("focus:composer", unset) .observe("paste:composer", unset) .observe("blur:composer", set); set(); }; })(wysihtml5.dom); (function(dom) { var documentElement = document.documentElement; if ("textContent" in documentElement) { dom.setTextContent = function(element, text) { element.textContent = text; }; dom.getTextContent = function(element) { return element.textContent; }; } else if ("innerText" in documentElement) { dom.setTextContent = function(element, text) { element.innerText = text; }; dom.getTextContent = function(element) { return element.innerText; }; } else { dom.setTextContent = function(element, text) { element.nodeValue = text; }; dom.getTextContent = function(element) { return element.nodeValue; }; } })(wysihtml5.dom); /** * Fix most common html formatting misbehaviors of browsers implementation when inserting * content via copy & paste contentEditable * * @author Christopher Blum */ wysihtml5.quirks.cleanPastedHTML = (function() { // TODO: We probably need more rules here var defaultRules = { // When pasting underlined links <a> into a contentEditable, IE thinks, it has to insert <u> to keep the styling "a u": wysihtml5.dom.replaceWithChildNodes }; function cleanPastedHTML(elementOrHtml, rules, context) { rules = rules || defaultRules; context = context || elementOrHtml.ownerDocument || document; var element, isString = typeof(elementOrHtml) === "string", method, matches, matchesLength, i, j = 0; if (isString) { element = wysihtml5.dom.getAsDom(elementOrHtml, context); } else { element = elementOrHtml; } for (i in rules) { matches = element.querySelectorAll(i); method = rules[i]; matchesLength = matches.length; for (; j<matchesLength; j++) { method(matches[j]); } } matches = elementOrHtml = rules = null; return isString ? element.innerHTML : element; } return cleanPastedHTML; })();/** * IE and Opera leave an empty paragraph in the contentEditable element after clearing it * * @param {Object} contentEditableElement The contentEditable element to observe for clearing events * @exaple * wysihtml5.quirks.ensureProperClearing(myContentEditableElement); */ (function(wysihtml5) { var dom = wysihtml5.dom; wysihtml5.quirks.ensureProperClearing = (function() { var clearIfNecessary = function(event) { var element = this; setTimeout(function() { var innerHTML = element.innerHTML.toLowerCase(); if (innerHTML == "<p>&nbsp;</p>" || innerHTML == "<p>&nbsp;</p><p>&nbsp;</p>") { element.innerHTML = ""; } }, 0); }; return function(composer) { dom.observe(composer.element, ["cut", "keydown"], clearIfNecessary); }; })(); /** * In Opera when the caret is in the first and only item of a list (<ul><li>|</li></ul>) and the list is the first child of the contentEditable element, it's impossible to delete the list by hitting backspace * * @param {Object} contentEditableElement The contentEditable element to observe for clearing events * @exaple * wysihtml5.quirks.ensureProperClearing(myContentEditableElement); */ wysihtml5.quirks.ensureProperClearingOfLists = (function() { var ELEMENTS_THAT_CONTAIN_LI = ["OL", "UL", "MENU"]; var clearIfNecessary = function(element, contentEditableElement) { if (!contentEditableElement.firstChild || !wysihtml5.lang.array(ELEMENTS_THAT_CONTAIN_LI).contains(contentEditableElement.firstChild.nodeName)) { return; } var list = dom.getParentElement(element, { nodeName: ELEMENTS_THAT_CONTAIN_LI }); if (!list) { return; } var listIsFirstChildOfContentEditable = list == contentEditableElement.firstChild; if (!listIsFirstChildOfContentEditable) { return; } var hasOnlyOneListItem = list.childNodes.length <= 1; if (!hasOnlyOneListItem) { return; } var onlyListItemIsEmpty = list.firstChild ? list.firstChild.innerHTML === "" : true; if (!onlyListItemIsEmpty) { return; } list.parentNode.removeChild(list); }; return function(composer) { dom.observe(composer.element, "keydown", function(event) { if (event.keyCode !== wysihtml5.BACKSPACE_KEY) { return; } var element = composer.selection.getSelectedNode(); clearIfNecessary(element, composer.element); }); }; })(); })(wysihtml5); // See https://bugzilla.mozilla.org/show_bug.cgi?id=664398 // // In Firefox this: // var d = document.createElement("div"); // d.innerHTML ='<a href="~"></a>'; // d.innerHTML; // will result in: // <a href="%7E"></a> // which is wrong (function(wysihtml5) { var TILDE_ESCAPED = "%7E"; wysihtml5.quirks.getCorrectInnerHTML = function(element) { var innerHTML = element.innerHTML; if (innerHTML.indexOf(TILDE_ESCAPED) === -1) { return innerHTML; } var elementsWithTilde = element.querySelectorAll("[href*='~'], [src*='~']"), url, urlToSearch, length, i; for (i=0, length=elementsWithTilde.length; i<length; i++) { url = elementsWithTilde[i].href || elementsWithTilde[i].src; urlToSearch = wysihtml5.lang.string(url).replace("~").by(TILDE_ESCAPED); innerHTML = wysihtml5.lang.string(innerHTML).replace(urlToSearch).by(url); } return innerHTML; }; })(wysihtml5);/** * Some browsers don't insert line breaks when hitting return in a contentEditable element * - Opera & IE insert new <p> on return * - Chrome & Safari insert new <div> on return * - Firefox inserts <br> on return (yippie!) * * @param {Element} element * * @example * wysihtml5.quirks.insertLineBreakOnReturn(element); */ (function(wysihtml5) { var dom = wysihtml5.dom, USE_NATIVE_LINE_BREAK_WHEN_CARET_INSIDE_TAGS = ["LI", "P", "H1", "H2", "H3", "H4", "H5", "H6"], LIST_TAGS = ["UL", "OL", "MENU"]; wysihtml5.quirks.insertLineBreakOnReturn = function(composer) { function unwrap(selectedNode) { var parentElement = dom.getParentElement(selectedNode, { nodeName: ["P", "DIV"] }, 2); if (!parentElement) { return; } var invisibleSpace = document.createTextNode(wysihtml5.INVISIBLE_SPACE); dom.insert(invisibleSpace).before(parentElement); dom.replaceWithChildNodes(parentElement); composer.selection.selectNode(invisibleSpace); } function keyDown(event) { var keyCode = event.keyCode; if (event.shiftKey || (keyCode !== wysihtml5.ENTER_KEY && keyCode !== wysihtml5.BACKSPACE_KEY)) { return; } var element = event.target, selectedNode = composer.selection.getSelectedNode(), blockElement = dom.getParentElement(selectedNode, { nodeName: USE_NATIVE_LINE_BREAK_WHEN_CARET_INSIDE_TAGS }, 4); if (blockElement) { // Some browsers create <p> elements after leaving a list // check after keydown of backspace and return whether a <p> got inserted and unwrap it if (blockElement.nodeName === "LI" && (keyCode === wysihtml5.ENTER_KEY || keyCode === wysihtml5.BACKSPACE_KEY)) { setTimeout(function() { var selectedNode = composer.selection.getSelectedNode(), list, div; if (!selectedNode) { return; } list = dom.getParentElement(selectedNode, { nodeName: LIST_TAGS }, 2); if (list) { return; } unwrap(selectedNode); }, 0); } else if (blockElement.nodeName.match(/H[1-6]/) && keyCode === wysihtml5.ENTER_KEY) { setTimeout(function() { unwrap(composer.selection.getSelectedNode()); }, 0); } return; } if (keyCode === wysihtml5.ENTER_KEY && !wysihtml5.browser.insertsLineBreaksOnReturn()) { composer.commands.exec("insertLineBreak"); event.preventDefault(); } } // keypress doesn't fire when you hit backspace dom.observe(composer.element.ownerDocument, "keydown", keyDown); }; })(wysihtml5);/** * Force rerendering of a given element * Needed to fix display misbehaviors of IE * * @param {Element} element The element object which needs to be rerendered * @example * wysihtml5.quirks.redraw(document.body); */ (function(wysihtml5) { var CLASS_NAME = "wysihtml5-quirks-redraw"; wysihtml5.quirks.redraw = function(element) { wysihtml5.dom.addClass(element, CLASS_NAME); wysihtml5.dom.removeClass(element, CLASS_NAME); // Following hack is needed for firefox to make sure that image resize handles are properly removed try { var doc = element.ownerDocument; doc.execCommand("italic", false, null); doc.execCommand("italic", false, null); } catch(e) {} }; })(wysihtml5);/** * Selection API * * @example * var selection = new wysihtml5.Selection(editor); */ (function(wysihtml5) { var dom = wysihtml5.dom; function _getCumulativeOffsetTop(element) { var top = 0; if (element.parentNode) { do { top += element.offsetTop || 0; element = element.offsetParent; } while (element); } return top; } wysihtml5.Selection = Base.extend( /** @scope wysihtml5.Selection.prototype */ { constructor: function(editor) { // Make sure that our external range library is initialized window.rangy.init(); this.editor = editor; this.composer = editor.composer; this.doc = this.composer.doc; }, /** * Get the current selection as a bookmark to be able to later restore it * * @return {Object} An object that represents the current selection */ getBookmark: function() { var range = this.getRange(); return range && range.cloneRange(); }, /** * Restore a selection retrieved via wysihtml5.Selection.prototype.getBookmark * * @param {Object} bookmark An object that represents the current selection */ setBookmark: function(bookmark) { if (!bookmark) { return; } this.setSelection(bookmark); }, /** * Set the caret in front of the given node * * @param {Object} node The element or text node where to position the caret in front of * @example * selection.setBefore(myElement); */ setBefore: function(node) { var range = rangy.createRange(this.doc); range.setStartBefore(node); range.setEndBefore(node); return this.setSelection(range); }, /** * Set the caret after the given node * * @param {Object} node The element or text node where to position the caret in front of * @example * selection.setBefore(myElement); */ setAfter: function(node) { var range = rangy.createRange(this.doc); range.setStartAfter(node); range.setEndAfter(node); return this.setSelection(range); }, /** * Ability to select/mark nodes * * @param {Element} node The node/element to select * @example * selection.selectNode(document.getElementById("my-image")); */ selectNode: function(node) { var range = rangy.createRange(this.doc), isElement = node.nodeType === wysihtml5.ELEMENT_NODE, canHaveHTML = "canHaveHTML" in node ? node.canHaveHTML : (node.nodeName !== "IMG"), content = isElement ? node.innerHTML : node.data, isEmpty = (content === "" || content === wysihtml5.INVISIBLE_SPACE), displayStyle = dom.getStyle("display").from(node), isBlockElement = (displayStyle === "block" || displayStyle === "list-item"); if (isEmpty && isElement && canHaveHTML) { // Make sure that caret is visible in node by inserting a zero width no breaking space try { node.innerHTML = wysihtml5.INVISIBLE_SPACE; } catch(e) {} } if (canHaveHTML) { range.selectNodeContents(node); } else { range.selectNode(node); } if (canHaveHTML && isEmpty && isElement) { range.collapse(isBlockElement); } else if (canHaveHTML && isEmpty) { range.setStartAfter(node); range.setEndAfter(node); } this.setSelection(range); }, /** * Get the node which contains the selection * * @param {Boolean} [controlRange] (only IE) Whether it should return the selected ControlRange element when the selection type is a "ControlRange" * @return {Object} The node that contains the caret * @example * var nodeThatContainsCaret = selection.getSelectedNode(); */ getSelectedNode: function(controlRange) { var selection, range; if (controlRange && this.doc.selection && this.doc.selection.type === "Control") { range = this.doc.selection.createRange(); if (range && range.length) { return range.item(0); } } selection = this.getSelection(this.doc); if (selection.focusNode === selection.anchorNode) { return selection.focusNode; } else { range = this.getRange(this.doc); return range ? range.commonAncestorContainer : this.doc.body; } }, executeAndRestore: function(method, restoreScrollPosition) { var body = this.doc.body, oldScrollTop = restoreScrollPosition && body.scrollTop, oldScrollLeft = restoreScrollPosition && body.scrollLeft, className = "_wysihtml5-temp-placeholder", placeholderHTML = '<span class="' + className + '">' + wysihtml5.INVISIBLE_SPACE + '</span>', range = this.getRange(this.doc), newRange; // Nothing selected, execute and say goodbye if (!range) { method(body, body); return; } var node = range.createContextualFragment(placeholderHTML); range.insertNode(node); // Make sure that a potential error doesn't cause our placeholder element to be left as a placeholder try { method(range.startContainer, range.endContainer); } catch(e3) { setTimeout(function() { throw e3; }, 0); } caretPlaceholder = this.doc.querySelector("." + className); if (caretPlaceholder) { newRange = rangy.createRange(this.doc); newRange.selectNode(caretPlaceholder); newRange.deleteContents(); this.setSelection(newRange); } else { // fallback for when all hell breaks loose body.focus(); } if (restoreScrollPosition) { body.scrollTop = oldScrollTop; body.scrollLeft = oldScrollLeft; } // Remove it again, just to make sure that the placeholder is definitely out of the dom tree try { caretPlaceholder.parentNode.removeChild(caretPlaceholder); } catch(e4) {} }, /** * Different approach of preserving the selection (doesn't modify the dom) * Takes all text nodes in the selection and saves the selection position in the first and last one */ executeAndRestoreSimple: function(method) { var range = this.getRange(), body = this.doc.body, newRange, firstNode, lastNode, textNodes, rangeBackup; // Nothing selected, execute and say goodbye if (!range) { method(body, body); return; } textNodes = range.getNodes([3]); firstNode = textNodes[0] || range.startContainer; lastNode = textNodes[textNodes.length - 1] || range.endContainer; rangeBackup = { collapsed: range.collapsed, startContainer: firstNode, startOffset: firstNode === range.startContainer ? range.startOffset : 0, endContainer: lastNode, endOffset: lastNode === range.endContainer ? range.endOffset : lastNode.length }; try { method(range.startContainer, range.endContainer); } catch(e) { setTimeout(function() { throw e; }, 0); } newRange = rangy.createRange(this.doc); try { newRange.setStart(rangeBackup.startContainer, rangeBackup.startOffset); } catch(e1) {} try { newRange.setEnd(rangeBackup.endContainer, rangeBackup.endOffset); } catch(e2) {} try { this.setSelection(newRange); } catch(e3) {} }, /** * Insert html at the caret position and move the cursor after the inserted html * * @param {String} html HTML string to insert * @example * selection.insertHTML("<p>foobar</p>"); */ insertHTML: function(html) { var range = rangy.createRange(this.doc), node = range.createContextualFragment(html), lastChild = node.lastChild; this.insertNode(node); if (lastChild) { this.setAfter(lastChild); } }, /** * Insert a node at the caret position and move the cursor behind it * * @param {Object} node HTML string to insert * @example * selection.insertNode(document.createTextNode("foobar")); */ insertNode: function(node) { var range = this.getRange(); if (range) { range.insertNode(node); } }, /** * Wraps current selection with the given node * * @param {Object} node The node to surround the selected elements with */ surround: function(node) { var range = this.getRange(); if (!range) { return; } try { // This only works when the range boundaries are not overlapping other elements range.surroundContents(node); this.selectNode(node); } catch(e) { // fallback node.appendChild(range.extractContents()); range.insertNode(node); } }, /** * Scroll the current caret position into the view * FIXME: This is a bit hacky, there might be a smarter way of doing this * * @example * selection.scrollIntoView(); */ scrollIntoView: function() { var doc = this.doc, hasScrollBars = doc.documentElement.scrollHeight > doc.documentElement.offsetHeight, tempElement = doc._wysihtml5ScrollIntoViewElement = doc._wysihtml5ScrollIntoViewElement || (function() { var element = doc.createElement("span"); // The element needs content in order to be able to calculate it's position properly element.innerHTML = wysihtml5.INVISIBLE_SPACE; return element; })(), offsetTop; if (hasScrollBars) { this.insertNode(tempElement); offsetTop = _getCumulativeOffsetTop(tempElement); tempElement.parentNode.removeChild(tempElement); if (offsetTop > doc.body.scrollTop) { doc.body.scrollTop = offsetTop; } } }, /** * Select line where the caret is in */ selectLine: function() { if (wysihtml5.browser.supportsSelectionModify()) { this._selectLine_W3C(); } else if (this.doc.selection) { this._selectLine_MSIE(); } }, /** * See https://developer.mozilla.org/en/DOM/Selection/modify */ _selectLine_W3C: function() { var win = this.doc.defaultView, selection = win.getSelection(); selection.modify("extend", "left", "lineboundary"); selection.modify("extend", "right", "lineboundary"); }, _selectLine_MSIE: function() { var range = this.doc.selection.createRange(), rangeTop = range.boundingTop, rangeHeight = range.boundingHeight, scrollWidth = this.doc.body.scrollWidth, rangeBottom, rangeEnd, measureNode, i, j; if (!range.moveToPoint) { return; } if (rangeTop === 0) { // Don't know why, but when the selection ends at the end of a line // range.boundingTop is 0 measureNode = this.doc.createElement("span"); this.insertNode(measureNode); rangeTop = measureNode.offsetTop; measureNode.parentNode.removeChild(measureNode); } rangeTop += 1; for (i=-10; i<scrollWidth; i+=2) { try { range.moveToPoint(i, rangeTop); break; } catch(e1) {} } // Investigate the following in order to handle multi line selections // rangeBottom = rangeTop + (rangeHeight ? (rangeHeight - 1) : 0); rangeBottom = rangeTop; rangeEnd = this.doc.selection.createRange(); for (j=scrollWidth; j>=0; j--) { try { rangeEnd.moveToPoint(j, rangeBottom); break; } catch(e2) {} } range.setEndPoint("EndToEnd", rangeEnd); range.select(); }, getText: function() { var selection = this.getSelection(); return selection ? selection.toString() : ""; }, getNodes: function(nodeType, filter) { var range = this.getRange(); if (range) { return range.getNodes([nodeType], filter); } else { return []; } }, getRange: function() { var selection = this.getSelection(); return selection && selection.rangeCount && selection.getRangeAt(0); }, getSelection: function() { return rangy.getSelection(this.doc.defaultView || this.doc.parentWindow); }, setSelection: function(range) { var win = this.doc.defaultView || this.doc.parentWindow, selection = rangy.getSelection(win); return selection.setSingleRange(range); } }); })(wysihtml5); /** * Inspired by the rangy CSS Applier module written by Tim Down and licensed under the MIT license. * http://code.google.com/p/rangy/ * * changed in order to be able ... * - to use custom tags * - to detect and replace similar css classes via reg exp */ (function(wysihtml5, rangy) { var defaultTagName = "span"; var REG_EXP_WHITE_SPACE = /\s+/g; function hasClass(el, cssClass, regExp) { if (!el.className) { return false; } var matchingClassNames = el.className.match(regExp) || []; return matchingClassNames[matchingClassNames.length - 1] === cssClass; } function addClass(el, cssClass, regExp) { if (el.className) { removeClass(el, regExp); el.className += " " + cssClass; } else { el.className = cssClass; } } function removeClass(el, regExp) { if (el.className) { el.className = el.className.replace(regExp, ""); } } function hasSameClasses(el1, el2) { return el1.className.replace(REG_EXP_WHITE_SPACE, " ") == el2.className.replace(REG_EXP_WHITE_SPACE, " "); } function replaceWithOwnChildren(el) { var parent = el.parentNode; while (el.firstChild) { parent.insertBefore(el.firstChild, el); } parent.removeChild(el); } function elementsHaveSameNonClassAttributes(el1, el2) { if (el1.attributes.length != el2.attributes.length) { return false; } for (var i = 0, len = el1.attributes.length, attr1, attr2, name; i < len; ++i) { attr1 = el1.attributes[i]; name = attr1.name; if (name != "class") { attr2 = el2.attributes.getNamedItem(name); if (attr1.specified != attr2.specified) { return false; } if (attr1.specified && attr1.nodeValue !== attr2.nodeValue) { return false; } } } return true; } function isSplitPoint(node, offset) { if (rangy.dom.isCharacterDataNode(node)) { if (offset == 0) { return !!node.previousSibling; } else if (offset == node.length) { return !!node.nextSibling; } else { return true; } } return offset > 0 && offset < node.childNodes.length; } function splitNodeAt(node, descendantNode, descendantOffset) { var newNode; if (rangy.dom.isCharacterDataNode(descendantNode)) { if (descendantOffset == 0) { descendantOffset = rangy.dom.getNodeIndex(descendantNode); descendantNode = descendantNode.parentNode; } else if (descendantOffset == descendantNode.length) { descendantOffset = rangy.dom.getNodeIndex(descendantNode) + 1; descendantNode = descendantNode.parentNode; } else { newNode = rangy.dom.splitDataNode(descendantNode, descendantOffset); } } if (!newNode) { newNode = descendantNode.cloneNode(false); if (newNode.id) { newNode.removeAttribute("id"); } var child; while ((child = descendantNode.childNodes[descendantOffset])) { newNode.appendChild(child); } rangy.dom.insertAfter(newNode, descendantNode); } return (descendantNode == node) ? newNode : splitNodeAt(node, newNode.parentNode, rangy.dom.getNodeIndex(newNode)); } function Merge(firstNode) { this.isElementMerge = (firstNode.nodeType == wysihtml5.ELEMENT_NODE); this.firstTextNode = this.isElementMerge ? firstNode.lastChild : firstNode; this.textNodes = [this.firstTextNode]; } Merge.prototype = { doMerge: function() { var textBits = [], textNode, parent, text; for (var i = 0, len = this.textNodes.length; i < len; ++i) { textNode = this.textNodes[i]; parent = textNode.parentNode; textBits[i] = textNode.data; if (i) { parent.removeChild(textNode); if (!parent.hasChildNodes()) { parent.parentNode.removeChild(parent); } } } this.firstTextNode.data = text = textBits.join(""); return text; }, getLength: function() { var i = this.textNodes.length, len = 0; while (i--) { len += this.textNodes[i].length; } return len; }, toString: function() { var textBits = []; for (var i = 0, len = this.textNodes.length; i < len; ++i) { textBits[i] = "'" + this.textNodes[i].data + "'"; } return "[Merge(" + textBits.join(",") + ")]"; } }; function HTMLApplier(tagNames, cssClass, similarClassRegExp, normalize) { this.tagNames = tagNames || [defaultTagName]; this.cssClass = cssClass || ""; this.similarClassRegExp = similarClassRegExp; this.normalize = normalize; this.applyToAnyTagName = false; } HTMLApplier.prototype = { getAncestorWithClass: function(node) { var cssClassMatch; while (node) { cssClassMatch = this.cssClass ? hasClass(node, this.cssClass, this.similarClassRegExp) : true; if (node.nodeType == wysihtml5.ELEMENT_NODE && rangy.dom.arrayContains(this.tagNames, node.tagName.toLowerCase()) && cssClassMatch) { return node; } node = node.parentNode; } return false; }, // Normalizes nodes after applying a CSS class to a Range. postApply: function(textNodes, range) { var firstNode = textNodes[0], lastNode = textNodes[textNodes.length - 1]; var merges = [], currentMerge; var rangeStartNode = firstNode, rangeEndNode = lastNode; var rangeStartOffset = 0, rangeEndOffset = lastNode.length; var textNode, precedingTextNode; for (var i = 0, len = textNodes.length; i < len; ++i) { textNode = textNodes[i]; precedingTextNode = this.getAdjacentMergeableTextNode(textNode.parentNode, false); if (precedingTextNode) { if (!currentMerge) { currentMerge = new Merge(precedingTextNode); merges.push(currentMerge); } currentMerge.textNodes.push(textNode); if (textNode === firstNode) { rangeStartNode = currentMerge.firstTextNode; rangeStartOffset = rangeStartNode.length; } if (textNode === lastNode) { rangeEndNode = currentMerge.firstTextNode; rangeEndOffset = currentMerge.getLength(); } } else { currentMerge = null; } } // Test whether the first node after the range needs merging var nextTextNode = this.getAdjacentMergeableTextNode(lastNode.parentNode, true); if (nextTextNode) { if (!currentMerge) { currentMerge = new Merge(lastNode); merges.push(currentMerge); } currentMerge.textNodes.push(nextTextNode); } // Do the merges if (merges.length) { for (i = 0, len = merges.length; i < len; ++i) { merges[i].doMerge(); } // Set the range boundaries range.setStart(rangeStartNode, rangeStartOffset); range.setEnd(rangeEndNode, rangeEndOffset); } }, getAdjacentMergeableTextNode: function(node, forward) { var isTextNode = (node.nodeType == wysihtml5.TEXT_NODE); var el = isTextNode ? node.parentNode : node; var adjacentNode; var propName = forward ? "nextSibling" : "previousSibling"; if (isTextNode) { // Can merge if the node's previous/next sibling is a text node adjacentNode = node[propName]; if (adjacentNode && adjacentNode.nodeType == wysihtml5.TEXT_NODE) { return adjacentNode; } } else { // Compare element with its sibling adjacentNode = el[propName]; if (adjacentNode && this.areElementsMergeable(node, adjacentNode)) { return adjacentNode[forward ? "firstChild" : "lastChild"]; } } return null; }, areElementsMergeable: function(el1, el2) { return rangy.dom.arrayContains(this.tagNames, (el1.tagName || "").toLowerCase()) && rangy.dom.arrayContains(this.tagNames, (el2.tagName || "").toLowerCase()) && hasSameClasses(el1, el2) && elementsHaveSameNonClassAttributes(el1, el2); }, createContainer: function(doc) { var el = doc.createElement(this.tagNames[0]); if (this.cssClass) { el.className = this.cssClass; } return el; }, applyToTextNode: function(textNode) { var parent = textNode.parentNode; if (parent.childNodes.length == 1 && rangy.dom.arrayContains(this.tagNames, parent.tagName.toLowerCase())) { if (this.cssClass) { addClass(parent, this.cssClass, this.similarClassRegExp); } } else { var el = this.createContainer(rangy.dom.getDocument(textNode)); textNode.parentNode.insertBefore(el, textNode); el.appendChild(textNode); } }, isRemovable: function(el) { return rangy.dom.arrayContains(this.tagNames, el.tagName.toLowerCase()) && wysihtml5.lang.string(el.className).trim() == this.cssClass; }, undoToTextNode: function(textNode, range, ancestorWithClass) { if (!range.containsNode(ancestorWithClass)) { // Split out the portion of the ancestor from which we can remove the CSS class var ancestorRange = range.cloneRange(); ancestorRange.selectNode(ancestorWithClass); if (ancestorRange.isPointInRange(range.endContainer, range.endOffset) && isSplitPoint(range.endContainer, range.endOffset)) { splitNodeAt(ancestorWithClass, range.endContainer, range.endOffset); range.setEndAfter(ancestorWithClass); } if (ancestorRange.isPointInRange(range.startContainer, range.startOffset) && isSplitPoint(range.startContainer, range.startOffset)) { ancestorWithClass = splitNodeAt(ancestorWithClass, range.startContainer, range.startOffset); } } if (this.similarClassRegExp) { removeClass(ancestorWithClass, this.similarClassRegExp); } if (this.isRemovable(ancestorWithClass)) { replaceWithOwnChildren(ancestorWithClass); } }, applyToRange: function(range) { var textNodes = range.getNodes([wysihtml5.TEXT_NODE]); if (!textNodes.length) { try { var node = this.createContainer(range.endContainer.ownerDocument); range.surroundContents(node); this.selectNode(range, node); return; } catch(e) {} } range.splitBoundaries(); textNodes = range.getNodes([wysihtml5.TEXT_NODE]); if (textNodes.length) { var textNode; for (var i = 0, len = textNodes.length; i < len; ++i) { textNode = textNodes[i]; if (!this.getAncestorWithClass(textNode)) { this.applyToTextNode(textNode); } } range.setStart(textNodes[0], 0); textNode = textNodes[textNodes.length - 1]; range.setEnd(textNode, textNode.length); if (this.normalize) { this.postApply(textNodes, range); } } }, undoToRange: function(range) { var textNodes = range.getNodes([wysihtml5.TEXT_NODE]), textNode, ancestorWithClass; if (textNodes.length) { range.splitBoundaries(); textNodes = range.getNodes([wysihtml5.TEXT_NODE]); } else { var doc = range.endContainer.ownerDocument, node = doc.createTextNode(wysihtml5.INVISIBLE_SPACE); range.insertNode(node); range.selectNode(node); textNodes = [node]; } for (var i = 0, len = textNodes.length; i < len; ++i) { textNode = textNodes[i]; ancestorWithClass = this.getAncestorWithClass(textNode); if (ancestorWithClass) { this.undoToTextNode(textNode, range, ancestorWithClass); } } if (len == 1) { this.selectNode(range, textNodes[0]); } else { range.setStart(textNodes[0], 0); textNode = textNodes[textNodes.length - 1]; range.setEnd(textNode, textNode.length); if (this.normalize) { this.postApply(textNodes, range); } } }, selectNode: function(range, node) { var isElement = node.nodeType === wysihtml5.ELEMENT_NODE, canHaveHTML = "canHaveHTML" in node ? node.canHaveHTML : true, content = isElement ? node.innerHTML : node.data, isEmpty = (content === "" || content === wysihtml5.INVISIBLE_SPACE); if (isEmpty && isElement && canHaveHTML) { // Make sure that caret is visible in node by inserting a zero width no breaking space try { node.innerHTML = wysihtml5.INVISIBLE_SPACE; } catch(e) {} } range.selectNodeContents(node); if (isEmpty && isElement) { range.collapse(false); } else if (isEmpty) { range.setStartAfter(node); range.setEndAfter(node); } }, getTextSelectedByRange: function(textNode, range) { var textRange = range.cloneRange(); textRange.selectNodeContents(textNode); var intersectionRange = textRange.intersection(range); var text = intersectionRange ? intersectionRange.toString() : ""; textRange.detach(); return text; }, isAppliedToRange: function(range) { var ancestors = [], ancestor, textNodes = range.getNodes([wysihtml5.TEXT_NODE]); if (!textNodes.length) { ancestor = this.getAncestorWithClass(range.startContainer); return ancestor ? [ancestor] : false; } for (var i = 0, len = textNodes.length, selectedText; i < len; ++i) { selectedText = this.getTextSelectedByRange(textNodes[i], range); ancestor = this.getAncestorWithClass(textNodes[i]); if (selectedText != "" && !ancestor) { return false; } else { ancestors.push(ancestor); } } return ancestors; }, toggleRange: function(range) { if (this.isAppliedToRange(range)) { this.undoToRange(range); } else { this.applyToRange(range); } } }; wysihtml5.selection.HTMLApplier = HTMLApplier; })(wysihtml5, rangy);/** * Rich Text Query/Formatting Commands * * @example * var commands = new wysihtml5.Commands(editor); */ wysihtml5.Commands = Base.extend( /** @scope wysihtml5.Commands.prototype */ { constructor: function(editor) { this.editor = editor; this.composer = editor.composer; this.doc = this.composer.doc; }, /** * Check whether the browser supports the given command * * @param {String} command The command string which to check (eg. "bold", "italic", "insertUnorderedList") * @example * commands.supports("createLink"); */ support: function(command) { return wysihtml5.browser.supportsCommand(this.doc, command); }, /** * Check whether the browser supports the given command * * @param {String} command The command string which to execute (eg. "bold", "italic", "insertUnorderedList") * @param {String} [value] The command value parameter, needed for some commands ("createLink", "insertImage", ...), optional for commands that don't require one ("bold", "underline", ...) * @example * commands.exec("insertImage", "http://a1.twimg.com/profile_images/113868655/schrei_twitter_reasonably_small.jpg"); */ exec: function(command, value) { var obj = wysihtml5.commands[command], args = wysihtml5.lang.array(arguments).get(), method = obj && obj.exec, result = null; this.editor.fire("beforecommand:composer"); if (method) { args.unshift(this.composer); result = method.apply(obj, args); } else { try { // try/catch for buggy firefox result = this.doc.execCommand(command, false, value); } catch(e) {} } this.editor.fire("aftercommand:composer"); return result; }, /** * Check whether the current command is active * If the caret is within a bold text, then calling this with command "bold" should return true * * @param {String} command The command string which to check (eg. "bold", "italic", "insertUnorderedList") * @param {String} [commandValue] The command value parameter (eg. for "insertImage" the image src) * @return {Boolean} Whether the command is active * @example * var isCurrentSelectionBold = commands.state("bold"); */ state: function(command, commandValue) { var obj = wysihtml5.commands[command], args = wysihtml5.lang.array(arguments).get(), method = obj && obj.state; if (method) { args.unshift(this.composer); return method.apply(obj, args); } else { try { // try/catch for buggy firefox return this.doc.queryCommandState(command); } catch(e) { return false; } } }, /** * Get the current command's value * * @param {String} command The command string which to check (eg. "formatBlock") * @return {String} The command value * @example * var currentBlockElement = commands.value("formatBlock"); */ value: function(command) { var obj = wysihtml5.commands[command], method = obj && obj.value; if (method) { return method.call(obj, this.composer, command); } else { try { // try/catch for buggy firefox return this.doc.queryCommandValue(command); } catch(e) { return null; } } } }); (function(wysihtml5) { var undef; wysihtml5.commands.bold = { exec: function(composer, command) { return wysihtml5.commands.formatInline.exec(composer, command, "b"); }, state: function(composer, command, color) { // element.ownerDocument.queryCommandState("bold") results: // firefox: only <b> // chrome: <b>, <strong>, <h1>, <h2>, ... // ie: <b>, <strong> // opera: <b>, <strong> return wysihtml5.commands.formatInline.state(composer, command, "b"); }, value: function() { return undef; } }; })(wysihtml5); (function(wysihtml5) { var undef, NODE_NAME = "A", dom = wysihtml5.dom; function _removeFormat(composer, anchors) { var length = anchors.length, i = 0, anchor, codeElement, textContent; for (; i<length; i++) { anchor = anchors[i]; codeElement = dom.getParentElement(anchor, { nodeName: "code" }); textContent = dom.getTextContent(anchor); // if <a> contains url-like text content, rename it to <code> to prevent re-autolinking // else replace <a> with its childNodes if (textContent.match(dom.autoLink.URL_REG_EXP) && !codeElement) { // <code> element is used to prevent later auto-linking of the content codeElement = dom.renameElement(anchor, "code"); } else { dom.replaceWithChildNodes(anchor); } } } function _format(composer, attributes) { var doc = composer.doc, tempClass = "_wysihtml5-temp-" + (+new Date()), tempClassRegExp = /non-matching-class/g, i = 0, length, anchors, anchor, hasElementChild, isEmpty, elementToSetCaretAfter, textContent, whiteSpace, j; wysihtml5.commands.formatInline.exec(composer, undef, NODE_NAME, tempClass, tempClassRegExp); anchors = doc.querySelectorAll(NODE_NAME + "." + tempClass); length = anchors.length; for (; i<length; i++) { anchor = anchors[i]; anchor.removeAttribute("class"); for (j in attributes) { anchor.setAttribute(j, attributes[j]); } } elementToSetCaretAfter = anchor; if (length === 1) { textContent = dom.getTextContent(anchor); hasElementChild = !!anchor.querySelector("*"); isEmpty = textContent === "" || textContent === wysihtml5.INVISIBLE_SPACE; if (!hasElementChild && isEmpty) { dom.setTextContent(anchor, attributes.text || anchor.href); whiteSpace = doc.createTextNode(" "); composer.selection.setAfter(anchor); composer.selection.insertNode(whiteSpace); elementToSetCaretAfter = whiteSpace; } } composer.selection.setAfter(elementToSetCaretAfter); } wysihtml5.commands.createLink = { /** * TODO: Use HTMLApplier or formatInline here * * Turns selection into a link * If selection is already a link, it removes the link and wraps it with a <code> element * The <code> element is needed to avoid auto linking * * @example * // either ... * wysihtml5.commands.createLink.exec(composer, "createLink", "http://www.google.de"); * // ... or ... * wysihtml5.commands.createLink.exec(composer, "createLink", { href: "http://www.google.de", target: "_blank" }); */ exec: function(composer, command, value) { var anchors = this.state(composer, command); if (anchors) { // Selection contains links composer.selection.executeAndRestore(function() { _removeFormat(composer, anchors); }); } else { // Create links value = typeof(value) === "object" ? value : { href: value }; _format(composer, value); } }, state: function(composer, command) { return wysihtml5.commands.formatInline.state(composer, command, "A"); }, value: function() { return undef; } }; })(wysihtml5);/** * document.execCommand("fontSize") will create either inline styles (firefox, chrome) or use font tags * which we don't want * Instead we set a css class */ (function(wysihtml5) { var undef, REG_EXP = /wysiwyg-font-size-[a-z\-]+/g; wysihtml5.commands.fontSize = { exec: function(composer, command, size) { return wysihtml5.commands.formatInline.exec(composer, command, "span", "wysiwyg-font-size-" + size, REG_EXP); }, state: function(composer, command, size) { return wysihtml5.commands.formatInline.state(composer, command, "span", "wysiwyg-font-size-" + size, REG_EXP); }, value: function() { return undef; } }; })(wysihtml5); /** * document.execCommand("foreColor") will create either inline styles (firefox, chrome) or use font tags * which we don't want * Instead we set a css class */ (function(wysihtml5) { var undef, REG_EXP = /wysiwyg-color-[a-z]+/g; wysihtml5.commands.foreColor = { exec: function(composer, command, color) { return wysihtml5.commands.formatInline.exec(composer, command, "span", "wysiwyg-color-" + color, REG_EXP); }, state: function(composer, command, color) { return wysihtml5.commands.formatInline.state(composer, command, "span", "wysiwyg-color-" + color, REG_EXP); }, value: function() { return undef; } }; })(wysihtml5);(function(wysihtml5) { var undef, dom = wysihtml5.dom, DEFAULT_NODE_NAME = "DIV", // Following elements are grouped // when the caret is within a H1 and the H4 is invoked, the H1 should turn into H4 // instead of creating a H4 within a H1 which would result in semantically invalid html BLOCK_ELEMENTS_GROUP = ["H1", "H2", "H3", "H4", "H5", "H6", "P", "BLOCKQUOTE", DEFAULT_NODE_NAME]; /** * Remove similiar classes (based on classRegExp) * and add the desired class name */ function _addClass(element, className, classRegExp) { if (element.className) { _removeClass(element, classRegExp); element.className += " " + className; } else { element.className = className; } } function _removeClass(element, classRegExp) { element.className = element.className.replace(classRegExp, ""); } /** * Check whether given node is a text node and whether it's empty */ function _isBlankTextNode(node) { return node.nodeType === wysihtml5.TEXT_NODE && !wysihtml5.lang.string(node.data).trim(); } /** * Returns previous sibling node that is not a blank text node */ function _getPreviousSiblingThatIsNotBlank(node) { var previousSibling = node.previousSibling; while (previousSibling && _isBlankTextNode(previousSibling)) { previousSibling = previousSibling.previousSibling; } return previousSibling; } /** * Returns next sibling node that is not a blank text node */ function _getNextSiblingThatIsNotBlank(node) { var nextSibling = node.nextSibling; while (nextSibling && _isBlankTextNode(nextSibling)) { nextSibling = nextSibling.nextSibling; } return nextSibling; } /** * Adds line breaks before and after the given node if the previous and next siblings * aren't already causing a visual line break (block element or <br>) */ function _addLineBreakBeforeAndAfter(node) { var doc = node.ownerDocument, nextSibling = _getNextSiblingThatIsNotBlank(node), previousSibling = _getPreviousSiblingThatIsNotBlank(node); if (nextSibling && !_isLineBreakOrBlockElement(nextSibling)) { node.parentNode.insertBefore(doc.createElement("br"), nextSibling); } if (previousSibling && !_isLineBreakOrBlockElement(previousSibling)) { node.parentNode.insertBefore(doc.createElement("br"), node); } } /** * Removes line breaks before and after the given node */ function _removeLineBreakBeforeAndAfter(node) { var nextSibling = _getNextSiblingThatIsNotBlank(node), previousSibling = _getPreviousSiblingThatIsNotBlank(node); if (nextSibling && _isLineBreak(nextSibling)) { nextSibling.parentNode.removeChild(nextSibling); } if (previousSibling && _isLineBreak(previousSibling)) { previousSibling.parentNode.removeChild(previousSibling); } } function _removeLastChildIfLineBreak(node) { var lastChild = node.lastChild; if (lastChild && _isLineBreak(lastChild)) { lastChild.parentNode.removeChild(lastChild); } } function _isLineBreak(node) { return node.nodeName === "BR"; } /** * Checks whether the elment causes a visual line break * (<br> or block elements) */ function _isLineBreakOrBlockElement(element) { if (_isLineBreak(element)) { return true; } if (dom.getStyle("display").from(element) === "block") { return true; } return false; } /** * Execute native query command * and if necessary modify the inserted node's className */ function _execCommand(doc, command, nodeName, className) { if (className) { var eventListener = dom.observe(doc, "DOMNodeInserted", function(event) { var target = event.target, displayStyle; if (target.nodeType !== wysihtml5.ELEMENT_NODE) { return; } displayStyle = dom.getStyle("display").from(target); if (displayStyle.substr(0, 6) !== "inline") { // Make sure that only block elements receive the given class target.className += " " + className; } }); } doc.execCommand(command, false, nodeName); if (eventListener) { eventListener.stop(); } } function _selectLineAndWrap(composer, element) { composer.selection.selectLine(); composer.selection.surround(element); _removeLineBreakBeforeAndAfter(element); _removeLastChildIfLineBreak(element); composer.selection.selectNode(element); } function _hasClasses(element) { return !!wysihtml5.lang.string(element.className).trim(); } wysihtml5.commands.formatBlock = { exec: function(composer, command, nodeName, className, classRegExp) { var doc = composer.doc, blockElement = this.state(composer, command, nodeName, className, classRegExp), selectedNode; nodeName = typeof(nodeName) === "string" ? nodeName.toUpperCase() : nodeName; if (blockElement) { composer.selection.executeAndRestoreSimple(function() { if (classRegExp) { _removeClass(blockElement, classRegExp); } var hasClasses = _hasClasses(blockElement); if (!hasClasses && blockElement.nodeName === (nodeName || DEFAULT_NODE_NAME)) { // Insert a line break afterwards and beforewards when there are siblings // that are not of type line break or block element _addLineBreakBeforeAndAfter(blockElement); dom.replaceWithChildNodes(blockElement); } else if (hasClasses) { // Make sure that styling is kept by renaming the element to <div> and copying over the class name dom.renameElement(blockElement, DEFAULT_NODE_NAME); } }); return; } // Find similiar block element and rename it (<h2 class="foo"></h2> => <h1 class="foo"></h1>) if (nodeName === null || wysihtml5.lang.array(BLOCK_ELEMENTS_GROUP).contains(nodeName)) { selectedNode = composer.selection.getSelectedNode(); blockElement = dom.getParentElement(selectedNode, { nodeName: BLOCK_ELEMENTS_GROUP }); if (blockElement) { composer.selection.executeAndRestoreSimple(function() { // Rename current block element to new block element and add class if (nodeName) { blockElement = dom.renameElement(blockElement, nodeName); } if (className) { _addClass(blockElement, className, classRegExp); } }); return; } } if (composer.commands.support(command)) { _execCommand(doc, command, nodeName || DEFAULT_NODE_NAME, className); return; } blockElement = doc.createElement(nodeName || DEFAULT_NODE_NAME); if (className) { blockElement.className = className; } _selectLineAndWrap(composer, blockElement); }, state: function(composer, command, nodeName, className, classRegExp) { nodeName = typeof(nodeName) === "string" ? nodeName.toUpperCase() : nodeName; var selectedNode = composer.selection.getSelectedNode(); return dom.getParentElement(selectedNode, { nodeName: nodeName, className: className, classRegExp: classRegExp }); }, value: function() { return undef; } }; })(wysihtml5);/** * formatInline scenarios for tag "B" (| = caret, |foo| = selected text) * * #1 caret in unformatted text: * abcdefg| * output: * abcdefg<b>|</b> * * #2 unformatted text selected: * abc|deg|h * output: * abc<b>|deg|</b>h * * #3 unformatted text selected across boundaries: * ab|c <span>defg|h</span> * output: * ab<b>|c </b><span><b>defg</b>|h</span> * * #4 formatted text entirely selected * <b>|abc|</b> * output: * |abc| * * #5 formatted text partially selected * <b>ab|c|</b> * output: * <b>ab</b>|c| * * #6 formatted text selected across boundaries * <span>ab|c</span> <b>de|fgh</b> * output: * <span>ab|c</span> de|<b>fgh</b> */ (function(wysihtml5) { var undef, // Treat <b> as <strong> and vice versa ALIAS_MAPPING = { "strong": "b", "em": "i", "b": "strong", "i": "em" }, htmlApplier = {}; function _getTagNames(tagName) { var alias = ALIAS_MAPPING[tagName]; return alias ? [tagName.toLowerCase(), alias.toLowerCase()] : [tagName.toLowerCase()]; } function _getApplier(tagName, className, classRegExp) { var identifier = tagName + ":" + className; if (!htmlApplier[identifier]) { htmlApplier[identifier] = new wysihtml5.selection.HTMLApplier(_getTagNames(tagName), className, classRegExp, true); } return htmlApplier[identifier]; } wysihtml5.commands.formatInline = { exec: function(composer, command, tagName, className, classRegExp) { var range = composer.selection.getRange(); if (!range) { return false; } _getApplier(tagName, className, classRegExp).toggleRange(range); composer.selection.setSelection(range); }, state: function(composer, command, tagName, className, classRegExp) { var doc = composer.doc, aliasTagName = ALIAS_MAPPING[tagName] || tagName, range; // Check whether the document contains a node with the desired tagName if (!wysihtml5.dom.hasElementWithTagName(doc, tagName) && !wysihtml5.dom.hasElementWithTagName(doc, aliasTagName)) { return false; } // Check whether the document contains a node with the desired className if (className && !wysihtml5.dom.hasElementWithClassName(doc, className)) { return false; } range = composer.selection.getRange(); if (!range) { return false; } return _getApplier(tagName, className, classRegExp).isAppliedToRange(range); }, value: function() { return undef; } }; })(wysihtml5);(function(wysihtml5) { var undef; wysihtml5.commands.insertHTML = { exec: function(composer, command, html) { if (composer.commands.support(command)) { composer.doc.execCommand(command, false, html); } else { composer.selection.insertHTML(html); } }, state: function() { return false; }, value: function() { return undef; } }; })(wysihtml5);(function(wysihtml5) { var NODE_NAME = "IMG"; wysihtml5.commands.insertImage = { /** * Inserts an <img> * If selection is already an image link, it removes it * * @example * // either ... * wysihtml5.commands.insertImage.exec(composer, "insertImage", "http://www.google.de/logo.jpg"); * // ... or ... * wysihtml5.commands.insertImage.exec(composer, "insertImage", { src: "http://www.google.de/logo.jpg", title: "foo" }); */ exec: function(composer, command, value) { value = typeof(value) === "object" ? value : { src: value }; var doc = composer.doc, image = this.state(composer), textNode, i, parent; if (image) { // Image already selected, set the caret before it and delete it composer.selection.setBefore(image); parent = image.parentNode; parent.removeChild(image); // and it's parent <a> too if it hasn't got any other relevant child nodes wysihtml5.dom.removeEmptyTextNodes(parent); if (parent.nodeName === "A" && !parent.firstChild) { composer.selection.setAfter(parent); parent.parentNode.removeChild(parent); } // firefox and ie sometimes don't remove the image handles, even though the image got removed wysihtml5.quirks.redraw(composer.element); return; } image = doc.createElement(NODE_NAME); for (i in value) { image[i] = value[i]; } composer.selection.insertNode(image); if (wysihtml5.browser.hasProblemsSettingCaretAfterImg()) { textNode = doc.createTextNode(wysihtml5.INVISIBLE_SPACE); composer.selection.insertNode(textNode); composer.selection.setAfter(textNode); } else { composer.selection.setAfter(image); } }, state: function(composer) { var doc = composer.doc, selectedNode, text, imagesInSelection; if (!wysihtml5.dom.hasElementWithTagName(doc, NODE_NAME)) { return false; } selectedNode = composer.selection.getSelectedNode(); if (!selectedNode) { return false; } if (selectedNode.nodeName === NODE_NAME) { // This works perfectly in IE return selectedNode; } if (selectedNode.nodeType !== wysihtml5.ELEMENT_NODE) { return false; } text = composer.selection.getText(); text = wysihtml5.lang.string(text).trim(); if (text) { return false; } imagesInSelection = composer.selection.getNodes(wysihtml5.ELEMENT_NODE, function(node) { return node.nodeName === "IMG"; }); if (imagesInSelection.length !== 1) { return false; } return imagesInSelection[0]; }, value: function(composer) { var image = this.state(composer); return image && image.src; } }; })(wysihtml5);(function(wysihtml5) { var undef, LINE_BREAK = "<br>" + (wysihtml5.browser.needsSpaceAfterLineBreak() ? " " : ""); wysihtml5.commands.insertLineBreak = { exec: function(composer, command) { if (composer.commands.support(command)) { composer.doc.execCommand(command, false, null); if (!wysihtml5.browser.autoScrollsToCaret()) { composer.selection.scrollIntoView(); } } else { composer.commands.exec("insertHTML", LINE_BREAK); } }, state: function() { return false; }, value: function() { return undef; } }; })(wysihtml5);(function(wysihtml5) { var undef; wysihtml5.commands.insertOrderedList = { exec: function(composer, command) { var doc = composer.doc, selectedNode = composer.selection.getSelectedNode(), list = wysihtml5.dom.getParentElement(selectedNode, { nodeName: "OL" }), otherList = wysihtml5.dom.getParentElement(selectedNode, { nodeName: "UL" }), tempClassName = "_wysihtml5-temp-" + new Date().getTime(), isEmpty, tempElement; if (composer.commands.support(command)) { doc.execCommand(command, false, null); return; } if (list) { // Unwrap list // <ol><li>foo</li><li>bar</li></ol> // becomes: // foo<br>bar<br> composer.selection.executeAndRestoreSimple(function() { wysihtml5.dom.resolveList(list); }); } else if (otherList) { // Turn an unordered list into an ordered list // <ul><li>foo</li><li>bar</li></ul> // becomes: // <ol><li>foo</li><li>bar</li></ol> composer.selection.executeAndRestoreSimple(function() { wysihtml5.dom.renameElement(otherList, "ol"); }); } else { // Create list composer.commands.exec("formatBlock", "div", tempClassName); tempElement = doc.querySelector("." + tempClassName); isEmpty = tempElement.innerHTML === "" || tempElement.innerHTML === wysihtml5.INVISIBLE_SPACE; composer.selection.executeAndRestoreSimple(function() { list = wysihtml5.dom.convertToList(tempElement, "ol"); }); if (isEmpty) { composer.selection.selectNode(list.querySelector("li")); } } }, state: function(composer) { var selectedNode = composer.selection.getSelectedNode(); return wysihtml5.dom.getParentElement(selectedNode, { nodeName: "OL" }); }, value: function() { return undef; } }; })(wysihtml5);(function(wysihtml5) { var undef; wysihtml5.commands.insertUnorderedList = { exec: function(composer, command) { var doc = composer.doc, selectedNode = composer.selection.getSelectedNode(), list = wysihtml5.dom.getParentElement(selectedNode, { nodeName: "UL" }), otherList = wysihtml5.dom.getParentElement(selectedNode, { nodeName: "OL" }), tempClassName = "_wysihtml5-temp-" + new Date().getTime(), isEmpty, tempElement; if (composer.commands.support(command)) { doc.execCommand(command, false, null); return; } if (list) { // Unwrap list // <ul><li>foo</li><li>bar</li></ul> // becomes: // foo<br>bar<br> composer.selection.executeAndRestoreSimple(function() { wysihtml5.dom.resolveList(list); }); } else if (otherList) { // Turn an ordered list into an unordered list // <ol><li>foo</li><li>bar</li></ol> // becomes: // <ul><li>foo</li><li>bar</li></ul> composer.selection.executeAndRestoreSimple(function() { wysihtml5.dom.renameElement(otherList, "ul"); }); } else { // Create list composer.commands.exec("formatBlock", "div", tempClassName); tempElement = doc.querySelector("." + tempClassName); isEmpty = tempElement.innerHTML === "" || tempElement.innerHTML === wysihtml5.INVISIBLE_SPACE; composer.selection.executeAndRestoreSimple(function() { list = wysihtml5.dom.convertToList(tempElement, "ul"); }); if (isEmpty) { composer.selection.selectNode(list.querySelector("li")); } } }, state: function(composer) { var selectedNode = composer.selection.getSelectedNode(); return wysihtml5.dom.getParentElement(selectedNode, { nodeName: "UL" }); }, value: function() { return undef; } }; })(wysihtml5);(function(wysihtml5) { var undef; wysihtml5.commands.italic = { exec: function(composer, command) { return wysihtml5.commands.formatInline.exec(composer, command, "i"); }, state: function(composer, command, color) { // element.ownerDocument.queryCommandState("italic") results: // firefox: only <i> // chrome: <i>, <em>, <blockquote>, ... // ie: <i>, <em> // opera: only <i> return wysihtml5.commands.formatInline.state(composer, command, "i"); }, value: function() { return undef; } }; })(wysihtml5);(function(wysihtml5) { var undef, CLASS_NAME = "wysiwyg-text-align-center", REG_EXP = /wysiwyg-text-align-[a-z]+/g; wysihtml5.commands.justifyCenter = { exec: function(composer, command) { return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", null, CLASS_NAME, REG_EXP); }, state: function(composer, command) { return wysihtml5.commands.formatBlock.state(composer, "formatBlock", null, CLASS_NAME, REG_EXP); }, value: function() { return undef; } }; })(wysihtml5);(function(wysihtml5) { var undef, CLASS_NAME = "wysiwyg-text-align-left", REG_EXP = /wysiwyg-text-align-[a-z]+/g; wysihtml5.commands.justifyLeft = { exec: function(composer, command) { return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", null, CLASS_NAME, REG_EXP); }, state: function(composer, command) { return wysihtml5.commands.formatBlock.state(composer, "formatBlock", null, CLASS_NAME, REG_EXP); }, value: function() { return undef; } }; })(wysihtml5);(function(wysihtml5) { var undef, CLASS_NAME = "wysiwyg-text-align-right", REG_EXP = /wysiwyg-text-align-[a-z]+/g; wysihtml5.commands.justifyRight = { exec: function(composer, command) { return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", null, CLASS_NAME, REG_EXP); }, state: function(composer, command) { return wysihtml5.commands.formatBlock.state(composer, "formatBlock", null, CLASS_NAME, REG_EXP); }, value: function() { return undef; } }; })(wysihtml5);(function(wysihtml5) { var undef; wysihtml5.commands.underline = { exec: function(composer, command) { return wysihtml5.commands.formatInline.exec(composer, command, "u"); }, state: function(composer, command) { return wysihtml5.commands.formatInline.state(composer, command, "u"); }, value: function() { return undef; } }; })(wysihtml5);/** * Undo Manager for wysihtml5 * slightly inspired by http://rniwa.com/editing/undomanager.html#the-undomanager-interface */ (function(wysihtml5) { var Z_KEY = 90, Y_KEY = 89, BACKSPACE_KEY = 8, DELETE_KEY = 46, MAX_HISTORY_ENTRIES = 40, UNDO_HTML = '<span id="_wysihtml5-undo" class="_wysihtml5-temp">' + wysihtml5.INVISIBLE_SPACE + '</span>', REDO_HTML = '<span id="_wysihtml5-redo" class="_wysihtml5-temp">' + wysihtml5.INVISIBLE_SPACE + '</span>', dom = wysihtml5.dom; function cleanTempElements(doc) { var tempElement; while (tempElement = doc.querySelector("._wysihtml5-temp")) { tempElement.parentNode.removeChild(tempElement); } } wysihtml5.UndoManager = wysihtml5.lang.Dispatcher.extend( /** @scope wysihtml5.UndoManager.prototype */ { constructor: function(editor) { this.editor = editor; this.composer = editor.composer; this.element = this.composer.element; this.history = [this.composer.getValue()]; this.position = 1; // Undo manager currently only supported in browsers who have the insertHTML command (not IE) if (this.composer.commands.support("insertHTML")) { this._observe(); } }, _observe: function() { var that = this, doc = this.composer.sandbox.getDocument(), lastKey; // Catch CTRL+Z and CTRL+Y dom.observe(this.element, "keydown", function(event) { if (event.altKey || (!event.ctrlKey && !event.metaKey)) { return; } var keyCode = event.keyCode, isUndo = keyCode === Z_KEY && !event.shiftKey, isRedo = (keyCode === Z_KEY && event.shiftKey) || (keyCode === Y_KEY); if (isUndo) { that.undo(); event.preventDefault(); } else if (isRedo) { that.redo(); event.preventDefault(); } }); // Catch delete and backspace dom.observe(this.element, "keydown", function(event) { var keyCode = event.keyCode; if (keyCode === lastKey) { return; } lastKey = keyCode; if (keyCode === BACKSPACE_KEY || keyCode === DELETE_KEY) { that.transact(); } }); // Now this is very hacky: // These days browsers don't offer a undo/redo event which we could hook into // to be notified when the user hits undo/redo in the contextmenu. // Therefore we simply insert two elements as soon as the contextmenu gets opened. // The last element being inserted will be immediately be removed again by a exexCommand("undo") // => When the second element appears in the dom tree then we know the user clicked "redo" in the context menu // => When the first element disappears from the dom tree then we know the user clicked "undo" in the context menu if (wysihtml5.browser.hasUndoInContextMenu()) { var interval, observed, cleanUp = function() { cleanTempElements(doc); clearInterval(interval); }; dom.observe(this.element, "contextmenu", function() { cleanUp(); that.composer.selection.executeAndRestoreSimple(function() { if (that.element.lastChild) { that.composer.selection.setAfter(that.element.lastChild); } // enable undo button in context menu doc.execCommand("insertHTML", false, UNDO_HTML); // enable redo button in context menu doc.execCommand("insertHTML", false, REDO_HTML); doc.execCommand("undo", false, null); }); interval = setInterval(function() { if (doc.getElementById("_wysihtml5-redo")) { cleanUp(); that.redo(); } else if (!doc.getElementById("_wysihtml5-undo")) { cleanUp(); that.undo(); } }, 400); if (!observed) { observed = true; dom.observe(document, "mousedown", cleanUp); dom.observe(doc, ["mousedown", "paste", "cut", "copy"], cleanUp); } }); } this.editor .observe("newword:composer", function() { that.transact(); }) .observe("beforecommand:composer", function() { that.transact(); }); }, transact: function() { var previousHtml = this.history[this.position - 1], currentHtml = this.composer.getValue(); if (currentHtml == previousHtml) { return; } var length = this.history.length = this.position; if (length > MAX_HISTORY_ENTRIES) { this.history.shift(); this.position--; } this.position++; this.history.push(currentHtml); }, undo: function() { this.transact(); if (this.position <= 1) { return; } this.set(this.history[--this.position - 1]); this.editor.fire("undo:composer"); }, redo: function() { if (this.position >= this.history.length) { return; } this.set(this.history[++this.position - 1]); this.editor.fire("redo:composer"); }, set: function(html) { this.composer.setValue(html); this.editor.focus(true); } }); })(wysihtml5); /** * TODO: the following methods still need unit test coverage */ wysihtml5.views.View = Base.extend( /** @scope wysihtml5.views.View.prototype */ { constructor: function(parent, textareaElement, config) { this.parent = parent; this.element = textareaElement; this.config = config; this._observeViewChange(); }, _observeViewChange: function() { var that = this; this.parent.observe("beforeload", function() { that.parent.observe("change_view", function(view) { if (view === that.name) { that.parent.currentView = that; that.show(); // Using tiny delay here to make sure that the placeholder is set before focusing setTimeout(function() { that.focus(); }, 0); } else { that.hide(); } }); }); }, focus: function() { if (this.element.ownerDocument.querySelector(":focus") === this.element) { return; } try { this.element.focus(); } catch(e) {} }, hide: function() { this.element.style.display = "none"; }, show: function() { this.element.style.display = ""; }, disable: function() { this.element.setAttribute("disabled", "disabled"); }, enable: function() { this.element.removeAttribute("disabled"); } });(function(wysihtml5) { var dom = wysihtml5.dom, browser = wysihtml5.browser; wysihtml5.views.Composer = wysihtml5.views.View.extend( /** @scope wysihtml5.views.Composer.prototype */ { name: "composer", // Needed for firefox in order to display a proper caret in an empty contentEditable CARET_HACK: "<br>", constructor: function(parent, textareaElement, config) { this.base(parent, textareaElement, config); this.textarea = this.parent.textarea; this._initSandbox(); }, clear: function() { this.element.innerHTML = browser.displaysCaretInEmptyContentEditableCorrectly() ? "" : this.CARET_HACK; }, getValue: function(parse) { var value = this.isEmpty() ? "" : wysihtml5.quirks.getCorrectInnerHTML(this.element); if (parse) { value = this.parent.parse(value); } // Replace all "zero width no breaking space" chars // which are used as hacks to enable some functionalities // Also remove all CARET hacks that somehow got left value = wysihtml5.lang.string(value).replace(wysihtml5.INVISIBLE_SPACE).by(""); return value; }, setValue: function(html, parse) { if (parse) { html = this.parent.parse(html); } this.element.innerHTML = html; }, show: function() { this.iframe.style.display = this._displayStyle || ""; // Firefox needs this, otherwise contentEditable becomes uneditable this.disable(); this.enable(); }, hide: function() { this._displayStyle = dom.getStyle("display").from(this.iframe); if (this._displayStyle === "none") { this._displayStyle = null; } this.iframe.style.display = "none"; }, disable: function() { this.element.removeAttribute("contentEditable"); this.base(); }, enable: function() { this.element.setAttribute("contentEditable", "true"); this.base(); }, focus: function(setToEnd) { // IE 8 fires the focus event after .focus() // This is needed by our simulate_placeholder.js to work // therefore we clear it ourselves this time if (wysihtml5.browser.doesAsyncFocus() && this.hasPlaceholderSet()) { this.clear(); } this.base(); var lastChild = this.element.lastChild; if (setToEnd && lastChild) { if (lastChild.nodeName === "BR") { this.selection.setBefore(this.element.lastChild); } else { this.selection.setAfter(this.element.lastChild); } } }, getTextContent: function() { return dom.getTextContent(this.element); }, hasPlaceholderSet: function() { return this.getTextContent() == this.textarea.element.getAttribute("placeholder"); }, isEmpty: function() { var innerHTML = this.element.innerHTML, elementsWithVisualValue = "blockquote, ul, ol, img, embed, object, table, iframe, svg, video, audio, button, input, select, textarea"; return innerHTML === "" || innerHTML === this.CARET_HACK || this.hasPlaceholderSet() || (this.getTextContent() === "" && !this.element.querySelector(elementsWithVisualValue)); }, _initSandbox: function() { var that = this; this.sandbox = new dom.Sandbox(function() { that._create(); }, { stylesheets: this.config.stylesheets }); this.iframe = this.sandbox.getIframe(); // Create hidden field which tells the server after submit, that the user used an wysiwyg editor var hiddenField = document.createElement("input"); hiddenField.type = "hidden"; hiddenField.name = "_wysihtml5_mode"; hiddenField.value = 1; // Store reference to current wysihtml5 instance on the textarea element var textareaElement = this.textarea.element; dom.insert(this.iframe).after(textareaElement); dom.insert(hiddenField).after(textareaElement); }, _create: function() { var that = this; this.doc = this.sandbox.getDocument(); this.element = this.doc.body; this.textarea = this.parent.textarea; this.element.innerHTML = this.textarea.getValue(true); this.enable(); // Make sure our selection handler is ready this.selection = new wysihtml5.Selection(this.parent); // Make sure commands dispatcher is ready this.commands = new wysihtml5.Commands(this.parent); dom.copyAttributes([ "className", "spellcheck", "title", "lang", "dir", "accessKey" ]).from(this.textarea.element).to(this.element); dom.addClass(this.element, this.config.composerClassName); // Make the editor look like the original textarea, by syncing styles if (this.config.style) { this.style(); } this.observe(); var name = this.config.name; if (name) { dom.addClass(this.element, name); dom.addClass(this.iframe, name); } // Simulate html5 placeholder attribute on contentEditable element var placeholderText = typeof(this.config.placeholder) === "string" ? this.config.placeholder : this.textarea.element.getAttribute("placeholder"); if (placeholderText) { dom.simulatePlaceholder(this.parent, this, placeholderText); } // Make sure that the browser avoids using inline styles whenever possible this.commands.exec("styleWithCSS", false); this._initAutoLinking(); this._initObjectResizing(); this._initUndoManager(); // Simulate html5 autofocus on contentEditable element if (this.textarea.element.hasAttribute("autofocus") || document.querySelector(":focus") == this.textarea.element) { setTimeout(function() { that.focus(); }, 100); } wysihtml5.quirks.insertLineBreakOnReturn(this); // IE sometimes leaves a single paragraph, which can't be removed by the user if (!browser.clearsContentEditableCorrectly()) { wysihtml5.quirks.ensureProperClearing(this); } if (!browser.clearsListsInContentEditableCorrectly()) { wysihtml5.quirks.ensureProperClearingOfLists(this); } // Set up a sync that makes sure that textarea and editor have the same content if (this.initSync && this.config.sync) { this.initSync(); } // Okay hide the textarea, we are ready to go this.textarea.hide(); // Fire global (before-)load event this.parent.fire("beforeload").fire("load"); }, _initAutoLinking: function() { var that = this, supportsDisablingOfAutoLinking = browser.canDisableAutoLinking(), supportsAutoLinking = browser.doesAutoLinkingInContentEditable(); if (supportsDisablingOfAutoLinking) { this.commands.exec("autoUrlDetect", false); } if (!this.config.autoLink) { return; } // Only do the auto linking by ourselves when the browser doesn't support auto linking // OR when he supports auto linking but we were able to turn it off (IE9+) if (!supportsAutoLinking || (supportsAutoLinking && supportsDisablingOfAutoLinking)) { this.parent.observe("newword:composer", function() { that.selection.executeAndRestore(function(startContainer, endContainer) { dom.autoLink(endContainer.parentNode); }); }); } // Assuming we have the following: // <a href="http://www.google.de">http://www.google.de</a> // If a user now changes the url in the innerHTML we want to make sure that // it's synchronized with the href attribute (as long as the innerHTML is still a url) var // Use a live NodeList to check whether there are any links in the document links = this.sandbox.getDocument().getElementsByTagName("a"), // The autoLink helper method reveals a reg exp to detect correct urls urlRegExp = dom.autoLink.URL_REG_EXP, getTextContent = function(element) { var textContent = wysihtml5.lang.string(dom.getTextContent(element)).trim(); if (textContent.substr(0, 4) === "www.") { textContent = "http://" + textContent; } return textContent; }; dom.observe(this.element, "keydown", function(event) { if (!links.length) { return; } var selectedNode = that.selection.getSelectedNode(event.target.ownerDocument), link = dom.getParentElement(selectedNode, { nodeName: "A" }, 4), textContent; if (!link) { return; } textContent = getTextContent(link); // keydown is fired before the actual content is changed // therefore we set a timeout to change the href setTimeout(function() { var newTextContent = getTextContent(link); if (newTextContent === textContent) { return; } // Only set href when new href looks like a valid url if (newTextContent.match(urlRegExp)) { link.setAttribute("href", newTextContent); } }, 0); }); }, _initObjectResizing: function() { var properties = ["width", "height"], propertiesLength = properties.length, element = this.element; this.commands.exec("enableObjectResizing", this.config.allowObjectResizing); if (this.config.allowObjectResizing) { // IE sets inline styles after resizing objects // The following lines make sure that the width/height css properties // are copied over to the width/height attributes if (browser.supportsEvent("resizeend")) { dom.observe(element, "resizeend", function(event) { var target = event.target || event.srcElement, style = target.style, i = 0, property; for(; i<propertiesLength; i++) { property = properties[i]; if (style[property]) { target.setAttribute(property, parseInt(style[property], 10)); style[property] = ""; } } // After resizing IE sometimes forgets to remove the old resize handles wysihtml5.quirks.redraw(element); }); } } else { if (browser.supportsEvent("resizestart")) { dom.observe(element, "resizestart", function(event) { event.preventDefault(); }); } } }, _initUndoManager: function() { new wysihtml5.UndoManager(this.parent); } }); })(wysihtml5);(function(wysihtml5) { var dom = wysihtml5.dom, doc = document, win = window, HOST_TEMPLATE = doc.createElement("div"), /** * Styles to copy from textarea to the composer element */ TEXT_FORMATTING = [ "background-color", "color", "cursor", "font-family", "font-size", "font-style", "font-variant", "font-weight", "line-height", "letter-spacing", "text-align", "text-decoration", "text-indent", "text-rendering", "word-break", "word-wrap", "word-spacing" ], /** * Styles to copy from textarea to the iframe */ BOX_FORMATTING = [ "background-color", "border-collapse", "border-bottom-color", "border-bottom-style", "border-bottom-width", "border-left-color", "border-left-style", "border-left-width", "border-right-color", "border-right-style", "border-right-width", "border-top-color", "border-top-style", "border-top-width", "clear", "display", "float", "margin-bottom", "margin-left", "margin-right", "margin-top", "outline-color", "outline-offset", "outline-width", "outline-style", "padding-left", "padding-right", "padding-top", "padding-bottom", "position", "top", "left", "right", "bottom", "z-index", "vertical-align", "text-align", "-webkit-box-sizing", "-moz-box-sizing", "-ms-box-sizing", "box-sizing", "-webkit-box-shadow", "-moz-box-shadow", "-ms-box-shadow","box-shadow", "-webkit-border-top-right-radius", "-moz-border-radius-topright", "border-top-right-radius", "-webkit-border-bottom-right-radius", "-moz-border-radius-bottomright", "border-bottom-right-radius", "-webkit-border-bottom-left-radius", "-moz-border-radius-bottomleft", "border-bottom-left-radius", "-webkit-border-top-left-radius", "-moz-border-radius-topleft", "border-top-left-radius", "width", "height" ], /** * Styles to sync while the window gets resized */ RESIZE_STYLE = [ "width", "height", "top", "left", "right", "bottom" ], ADDITIONAL_CSS_RULES = [ "html { height: 100%; }", "body { min-height: 100%; padding: 0; margin: 0; margin-top: -1px; padding-top: 1px; }", "._wysihtml5-temp { display: none; }", wysihtml5.browser.isGecko ? "body.placeholder { color: graytext !important; }" : "body.placeholder { color: #a9a9a9 !important; }", "body[disabled] { background-color: #eee !important; color: #999 !important; cursor: default !important; }", // Ensure that user see's broken images and can delete them "img:-moz-broken { -moz-force-broken-image-icon: 1; height: 24px; width: 24px; }" ]; /** * With "setActive" IE offers a smart way of focusing elements without scrolling them into view: * http://msdn.microsoft.com/en-us/library/ms536738(v=vs.85).aspx * * Other browsers need a more hacky way: (pssst don't tell my mama) * In order to prevent the element being scrolled into view when focusing it, we simply * move it out of the scrollable area, focus it, and reset it's position */ var focusWithoutScrolling = function(element) { if (element.setActive) { // Following line could cause a js error when the textarea is invisible // See https://github.com/xing/wysihtml5/issues/9 try { element.setActive(); } catch(e) {} } else { var elementStyle = element.style, originalScrollTop = doc.documentElement.scrollTop || doc.body.scrollTop, originalScrollLeft = doc.documentElement.scrollLeft || doc.body.scrollLeft, originalStyles = { position: elementStyle.position, top: elementStyle.top, left: elementStyle.left, WebkitUserSelect: elementStyle.WebkitUserSelect }; dom.setStyles({ position: "absolute", top: "-99999px", left: "-99999px", // Don't ask why but temporarily setting -webkit-user-select to none makes the whole thing performing smoother WebkitUserSelect: "none" }).on(element); element.focus(); dom.setStyles(originalStyles).on(element); if (win.scrollTo) { // Some browser extensions unset this method to prevent annoyances // "Better PopUp Blocker" for Chrome http://code.google.com/p/betterpopupblocker/source/browse/trunk/blockStart.js#100 // Issue: http://code.google.com/p/betterpopupblocker/issues/detail?id=1 win.scrollTo(originalScrollLeft, originalScrollTop); } } }; wysihtml5.views.Composer.prototype.style = function() { var that = this, originalActiveElement = doc.querySelector(":focus"), textareaElement = this.textarea.element, hasPlaceholder = textareaElement.hasAttribute("placeholder"), originalPlaceholder = hasPlaceholder && textareaElement.getAttribute("placeholder"); this.focusStylesHost = this.focusStylesHost || HOST_TEMPLATE.cloneNode(false); this.blurStylesHost = this.blurStylesHost || HOST_TEMPLATE.cloneNode(false); // Remove placeholder before copying (as the placeholder has an affect on the computed style) if (hasPlaceholder) { textareaElement.removeAttribute("placeholder"); } if (textareaElement === originalActiveElement) { textareaElement.blur(); } // --------- iframe styles (has to be set before editor styles, otherwise IE9 sets wrong fontFamily on blurStylesHost) --------- dom.copyStyles(BOX_FORMATTING).from(textareaElement).to(this.iframe).andTo(this.blurStylesHost); // --------- editor styles --------- dom.copyStyles(TEXT_FORMATTING).from(textareaElement).to(this.element).andTo(this.blurStylesHost); // --------- apply standard rules --------- dom.insertCSS(ADDITIONAL_CSS_RULES).into(this.element.ownerDocument); // --------- :focus styles --------- focusWithoutScrolling(textareaElement); dom.copyStyles(BOX_FORMATTING).from(textareaElement).to(this.focusStylesHost); dom.copyStyles(TEXT_FORMATTING).from(textareaElement).to(this.focusStylesHost); // Make sure that we don't change the display style of the iframe when copying styles oblur/onfocus // this is needed for when the change_view event is fired where the iframe is hidden and then // the blur event fires and re-displays it var boxFormattingStyles = wysihtml5.lang.array(BOX_FORMATTING).without(["display"]); // --------- restore focus --------- if (originalActiveElement) { originalActiveElement.focus(); } else { textareaElement.blur(); } // --------- restore placeholder --------- if (hasPlaceholder) { textareaElement.setAttribute("placeholder", originalPlaceholder); } // When copying styles, we only get the computed style which is never returned in percent unit // Therefore we've to recalculate style onresize if (!wysihtml5.browser.hasCurrentStyleProperty()) { var winObserver = dom.observe(win, "resize", function() { // Remove event listener if composer doesn't exist anymore if (!dom.contains(document.documentElement, that.iframe)) { winObserver.stop(); return; } var originalTextareaDisplayStyle = dom.getStyle("display").from(textareaElement), originalComposerDisplayStyle = dom.getStyle("display").from(that.iframe); textareaElement.style.display = ""; that.iframe.style.display = "none"; dom.copyStyles(RESIZE_STYLE) .from(textareaElement) .to(that.iframe) .andTo(that.focusStylesHost) .andTo(that.blurStylesHost); that.iframe.style.display = originalComposerDisplayStyle; textareaElement.style.display = originalTextareaDisplayStyle; }); } // --------- Sync focus/blur styles --------- this.parent.observe("focus:composer", function() { dom.copyStyles(boxFormattingStyles) .from(that.focusStylesHost).to(that.iframe); dom.copyStyles(TEXT_FORMATTING) .from(that.focusStylesHost).to(that.element); }); this.parent.observe("blur:composer", function() { dom.copyStyles(boxFormattingStyles) .from(that.blurStylesHost).to(that.iframe); dom.copyStyles(TEXT_FORMATTING) .from(that.blurStylesHost).to(that.element); }); return this; }; })(wysihtml5);/** * Taking care of events * - Simulating 'change' event on contentEditable element * - Handling drag & drop logic * - Catch paste events * - Dispatch proprietary newword:composer event * - Keyboard shortcuts */ (function(wysihtml5) { var dom = wysihtml5.dom, browser = wysihtml5.browser, /** * Map keyCodes to query commands */ shortcuts = { "66": "bold", // B "73": "italic", // I "85": "underline" // U }; wysihtml5.views.Composer.prototype.observe = function() { var that = this, state = this.getValue(), iframe = this.sandbox.getIframe(), element = this.element, focusBlurElement = browser.supportsEventsInIframeCorrectly() ? element : this.sandbox.getWindow(), // Firefox < 3.5 doesn't support the drop event, instead it supports a so called "dragdrop" event which behaves almost the same pasteEvents = browser.supportsEvent("drop") ? ["drop", "paste"] : ["dragdrop", "paste"]; // --------- destroy:composer event --------- dom.observe(iframe, "DOMNodeRemoved", function() { clearInterval(domNodeRemovedInterval); that.parent.fire("destroy:composer"); }); // DOMNodeRemoved event is not supported in IE 8 var domNodeRemovedInterval = setInterval(function() { if (!dom.contains(document.documentElement, iframe)) { clearInterval(domNodeRemovedInterval); that.parent.fire("destroy:composer"); } }, 250); // --------- Focus & blur logic --------- dom.observe(focusBlurElement, "focus", function() { that.parent.fire("focus").fire("focus:composer"); // Delay storing of state until all focus handler are fired // especially the one which resets the placeholder setTimeout(function() { state = that.getValue(); }, 0); }); dom.observe(focusBlurElement, "blur", function() { if (state !== that.getValue()) { that.parent.fire("change").fire("change:composer"); } that.parent.fire("blur").fire("blur:composer"); }); if (wysihtml5.browser.isIos()) { // When on iPad/iPhone/IPod after clicking outside of editor, the editor loses focus // but the UI still acts as if the editor has focus (blinking caret and onscreen keyboard visible) // We prevent that by focusing a temporary input element which immediately loses focus dom.observe(element, "blur", function() { var input = element.ownerDocument.createElement("input"), originalScrollTop = document.documentElement.scrollTop || document.body.scrollTop, originalScrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft; try { that.selection.insertNode(input); } catch(e) { element.appendChild(input); } input.focus(); input.parentNode.removeChild(input); window.scrollTo(originalScrollLeft, originalScrollTop); }); } // --------- Drag & Drop logic --------- dom.observe(element, "dragenter", function() { that.parent.fire("unset_placeholder"); }); if (browser.firesOnDropOnlyWhenOnDragOverIsCancelled()) { dom.observe(element, ["dragover", "dragenter"], function(event) { event.preventDefault(); }); } dom.observe(element, pasteEvents, function(event) { var dataTransfer = event.dataTransfer, data; if (dataTransfer && browser.supportsDataTransfer()) { data = dataTransfer.getData("text/html") || dataTransfer.getData("text/plain"); } if (data) { element.focus(); that.commands.exec("insertHTML", data); that.parent.fire("paste").fire("paste:composer"); event.stopPropagation(); event.preventDefault(); } else { setTimeout(function() { that.parent.fire("paste").fire("paste:composer"); }, 0); } }); // --------- neword event --------- dom.observe(element, "keyup", function(event) { var keyCode = event.keyCode; if (keyCode === wysihtml5.SPACE_KEY || keyCode === wysihtml5.ENTER_KEY) { that.parent.fire("newword:composer"); } }); this.parent.observe("paste:composer", function() { setTimeout(function() { that.parent.fire("newword:composer"); }, 0); }); // --------- Make sure that images are selected when clicking on them --------- if (!browser.canSelectImagesInContentEditable()) { dom.observe(element, "mousedown", function(event) { var target = event.target; if (target.nodeName === "IMG") { that.selection.selectNode(target); event.preventDefault(); } }); } // --------- Shortcut logic --------- dom.observe(element, "keydown", function(event) { var keyCode = event.keyCode, command = shortcuts[keyCode]; if ((event.ctrlKey || event.metaKey) && !event.altKey && command) { that.commands.exec(command); event.preventDefault(); } }); // --------- Make sure that when pressing backspace/delete on selected images deletes the image and it's anchor --------- dom.observe(element, "keydown", function(event) { var target = that.selection.getSelectedNode(true), keyCode = event.keyCode, parent; if (target && target.nodeName === "IMG" && (keyCode === wysihtml5.BACKSPACE_KEY || keyCode === wysihtml5.DELETE_KEY)) { // 8 => backspace, 46 => delete parent = target.parentNode; // delete the <img> parent.removeChild(target); // and it's parent <a> too if it hasn't got any other child nodes if (parent.nodeName === "A" && !parent.firstChild) { parent.parentNode.removeChild(parent); } setTimeout(function() { wysihtml5.quirks.redraw(element); }, 0); event.preventDefault(); } }); // --------- Show url in tooltip when hovering links or images --------- var titlePrefixes = { IMG: "Image: ", A: "Link: " }; dom.observe(element, "mouseover", function(event) { var target = event.target, nodeName = target.nodeName, title; if (nodeName !== "A" && nodeName !== "IMG") { return; } var hasTitle = target.hasAttribute("title"); if(!hasTitle){ title = titlePrefixes[nodeName] + (target.getAttribute("href") || target.getAttribute("src")); target.setAttribute("title", title); } }); }; })(wysihtml5);/** * Class that takes care that the value of the composer and the textarea is always in sync */ (function(wysihtml5) { var INTERVAL = 400; wysihtml5.views.Synchronizer = Base.extend( /** @scope wysihtml5.views.Synchronizer.prototype */ { constructor: function(editor, textarea, composer) { this.editor = editor; this.textarea = textarea; this.composer = composer; this._observe(); }, /** * Sync html from composer to textarea * Takes care of placeholders * @param {Boolean} shouldParseHtml Whether the html should be sanitized before inserting it into the textarea */ fromComposerToTextarea: function(shouldParseHtml) { this.textarea.setValue(wysihtml5.lang.string(this.composer.getValue()).trim(), shouldParseHtml); }, /** * Sync value of textarea to composer * Takes care of placeholders * @param {Boolean} shouldParseHtml Whether the html should be sanitized before inserting it into the composer */ fromTextareaToComposer: function(shouldParseHtml) { var textareaValue = this.textarea.getValue(); if (textareaValue) { this.composer.setValue(textareaValue, shouldParseHtml); } else { this.composer.clear(); this.editor.fire("set_placeholder"); } }, /** * Invoke syncing based on view state * @param {Boolean} shouldParseHtml Whether the html should be sanitized before inserting it into the composer/textarea */ sync: function(shouldParseHtml) { if (this.editor.currentView.name === "textarea") { this.fromTextareaToComposer(shouldParseHtml); } else { this.fromComposerToTextarea(shouldParseHtml); } }, /** * Initializes interval-based syncing * also makes sure that on-submit the composer's content is synced with the textarea * immediately when the form gets submitted */ _observe: function() { var interval, that = this, form = this.textarea.element.form, startInterval = function() { interval = setInterval(function() { that.fromComposerToTextarea(); }, INTERVAL); }, stopInterval = function() { clearInterval(interval); interval = null; }; startInterval(); if (form) { // If the textarea is in a form make sure that after onreset and onsubmit the composer // has the correct state wysihtml5.dom.observe(form, "submit", function() { that.sync(true); }); wysihtml5.dom.observe(form, "reset", function() { setTimeout(function() { that.fromTextareaToComposer(); }, 0); }); } this.editor.observe("change_view", function(view) { if (view === "composer" && !interval) { that.fromTextareaToComposer(true); startInterval(); } else if (view === "textarea") { that.fromComposerToTextarea(true); stopInterval(); } }); this.editor.observe("destroy:composer", stopInterval); } }); })(wysihtml5); wysihtml5.views.Textarea = wysihtml5.views.View.extend( /** @scope wysihtml5.views.Textarea.prototype */ { name: "textarea", constructor: function(parent, textareaElement, config) { this.base(parent, textareaElement, config); this._observe(); }, clear: function() { this.element.value = ""; }, getValue: function(parse) { var value = this.isEmpty() ? "" : this.element.value; if (parse) { value = this.parent.parse(value); } return value; }, setValue: function(html, parse) { if (parse) { html = this.parent.parse(html); } this.element.value = html; }, hasPlaceholderSet: function() { var supportsPlaceholder = wysihtml5.browser.supportsPlaceholderAttributeOn(this.element), placeholderText = this.element.getAttribute("placeholder") || null, value = this.element.value, isEmpty = !value; return (supportsPlaceholder && isEmpty) || (value === placeholderText); }, isEmpty: function() { return !wysihtml5.lang.string(this.element.value).trim() || this.hasPlaceholderSet(); }, _observe: function() { var element = this.element, parent = this.parent, eventMapping = { focusin: "focus", focusout: "blur" }, /** * Calling focus() or blur() on an element doesn't synchronously trigger the attached focus/blur events * This is the case for focusin and focusout, so let's use them whenever possible, kkthxbai */ events = wysihtml5.browser.supportsEvent("focusin") ? ["focusin", "focusout", "change"] : ["focus", "blur", "change"]; parent.observe("beforeload", function() { wysihtml5.dom.observe(element, events, function(event) { var eventName = eventMapping[event.type] || event.type; parent.fire(eventName).fire(eventName + ":textarea"); }); wysihtml5.dom.observe(element, ["paste", "drop"], function() { setTimeout(function() { parent.fire("paste").fire("paste:textarea"); }, 0); }); }); } });/** * Toolbar Dialog * * @param {Element} link The toolbar link which causes the dialog to show up * @param {Element} container The dialog container * * @example * <!-- Toolbar link --> * <a data-wysihtml5-command="insertImage">insert an image</a> * * <!-- Dialog --> * <div data-wysihtml5-dialog="insertImage" style="display: none;"> * <label> * URL: <input data-wysihtml5-dialog-field="src" value="http://"> * </label> * <label> * Alternative text: <input data-wysihtml5-dialog-field="alt" value=""> * </label> * </div> * * <script> * var dialog = new wysihtml5.toolbar.Dialog( * document.querySelector("[data-wysihtml5-command='insertImage']"), * document.querySelector("[data-wysihtml5-dialog='insertImage']") * ); * dialog.observe("save", function(attributes) { * // do something * }); * </script> */ (function(wysihtml5) { var dom = wysihtml5.dom, CLASS_NAME_OPENED = "wysihtml5-command-dialog-opened", SELECTOR_FORM_ELEMENTS = "input, select, textarea", SELECTOR_FIELDS = "[data-wysihtml5-dialog-field]", ATTRIBUTE_FIELDS = "data-wysihtml5-dialog-field"; wysihtml5.toolbar.Dialog = wysihtml5.lang.Dispatcher.extend( /** @scope wysihtml5.toolbar.Dialog.prototype */ { constructor: function(link, container) { this.link = link; this.container = container; }, _observe: function() { if (this._observed) { return; } var that = this, callbackWrapper = function(event) { var attributes = that._serialize(); if (attributes == that.elementToChange) { that.fire("edit", attributes); } else { that.fire("save", attributes); } that.hide(); event.preventDefault(); event.stopPropagation(); }; dom.observe(that.link, "click", function(event) { if (dom.hasClass(that.link, CLASS_NAME_OPENED)) { setTimeout(function() { that.hide(); }, 0); } }); dom.observe(this.container, "keydown", function(event) { var keyCode = event.keyCode; if (keyCode === wysihtml5.ENTER_KEY) { callbackWrapper(event); } if (keyCode === wysihtml5.ESCAPE_KEY) { that.hide(); } }); dom.delegate(this.container, "[data-wysihtml5-dialog-action=save]", "click", callbackWrapper); dom.delegate(this.container, "[data-wysihtml5-dialog-action=cancel]", "click", function(event) { that.fire("cancel"); that.hide(); event.preventDefault(); event.stopPropagation(); }); var formElements = this.container.querySelectorAll(SELECTOR_FORM_ELEMENTS), i = 0, length = formElements.length, _clearInterval = function() { clearInterval(that.interval); }; for (; i<length; i++) { dom.observe(formElements[i], "change", _clearInterval); } this._observed = true; }, /** * Grabs all fields in the dialog and puts them in key=>value style in an object which * then gets returned */ _serialize: function() { var data = this.elementToChange || {}, fields = this.container.querySelectorAll(SELECTOR_FIELDS), length = fields.length, i = 0; for (; i<length; i++) { data[fields[i].getAttribute(ATTRIBUTE_FIELDS)] = fields[i].value; } return data; }, /** * Takes the attributes of the "elementToChange" * and inserts them in their corresponding dialog input fields * * Assume the "elementToChange" looks like this: * <a href="http://www.google.com" target="_blank">foo</a> * * and we have the following dialog: * <input type="text" data-wysihtml5-dialog-field="href" value=""> * <input type="text" data-wysihtml5-dialog-field="target" value=""> * * after calling _interpolate() the dialog will look like this * <input type="text" data-wysihtml5-dialog-field="href" value="http://www.google.com"> * <input type="text" data-wysihtml5-dialog-field="target" value="_blank"> * * Basically it adopted the attribute values into the corresponding input fields * */ _interpolate: function(avoidHiddenFields) { var field, fieldName, newValue, focusedElement = document.querySelector(":focus"), fields = this.container.querySelectorAll(SELECTOR_FIELDS), length = fields.length, i = 0; for (; i<length; i++) { field = fields[i]; // Never change elements where the user is currently typing in if (field === focusedElement) { continue; } // Don't update hidden fields // See https://github.com/xing/wysihtml5/pull/14 if (avoidHiddenFields && field.type === "hidden") { continue; } fieldName = field.getAttribute(ATTRIBUTE_FIELDS); newValue = this.elementToChange ? (this.elementToChange[fieldName] || "") : field.defaultValue; field.value = newValue; } }, /** * Show the dialog element */ show: function(elementToChange) { var that = this, firstField = this.container.querySelector(SELECTOR_FORM_ELEMENTS); this.elementToChange = elementToChange; this._observe(); this._interpolate(); if (elementToChange) { this.interval = setInterval(function() { that._interpolate(true); }, 500); } dom.addClass(this.link, CLASS_NAME_OPENED); this.container.style.display = ""; this.fire("show"); if (firstField && !elementToChange) { try { firstField.focus(); } catch(e) {} } }, /** * Hide the dialog element */ hide: function() { clearInterval(this.interval); this.elementToChange = null; dom.removeClass(this.link, CLASS_NAME_OPENED); this.container.style.display = "none"; this.fire("hide"); } }); })(wysihtml5); /** * Converts speech-to-text and inserts this into the editor * As of now (2011/03/25) this only is supported in Chrome >= 11 * * Note that it sends the recorded audio to the google speech recognition api: * http://stackoverflow.com/questions/4361826/does-chrome-have-buil-in-speech-recognition-for-input-type-text-x-webkit-speec * * Current HTML5 draft can be found here * http://lists.w3.org/Archives/Public/public-xg-htmlspeech/2011Feb/att-0020/api-draft.html * * "Accessing Google Speech API Chrome 11" * http://mikepultz.com/2011/03/accessing-google-speech-api-chrome-11/ */ (function(wysihtml5) { var dom = wysihtml5.dom; var linkStyles = { position: "relative" }; var wrapperStyles = { left: 0, margin: 0, opacity: 0, overflow: "hidden", padding: 0, position: "absolute", top: 0, zIndex: 1 }; var inputStyles = { cursor: "inherit", fontSize: "50px", height: "50px", marginTop: "-25px", outline: 0, padding: 0, position: "absolute", right: "-4px", top: "50%" }; var inputAttributes = { "x-webkit-speech": "", "speech": "" }; wysihtml5.toolbar.Speech = function(parent, link) { var input = document.createElement("input"); if (!wysihtml5.browser.supportsSpeechApiOn(input)) { link.style.display = "none"; return; } var wrapper = document.createElement("div"); wysihtml5.lang.object(wrapperStyles).merge({ width: link.offsetWidth + "px", height: link.offsetHeight + "px" }); dom.insert(input).into(wrapper); dom.insert(wrapper).into(link); dom.setStyles(inputStyles).on(input); dom.setAttributes(inputAttributes).on(input) dom.setStyles(wrapperStyles).on(wrapper); dom.setStyles(linkStyles).on(link); var eventName = "onwebkitspeechchange" in input ? "webkitspeechchange" : "speechchange"; dom.observe(input, eventName, function() { parent.execCommand("insertText", input.value); input.value = ""; }); dom.observe(input, "click", function(event) { if (dom.hasClass(link, "wysihtml5-command-disabled")) { event.preventDefault(); } event.stopPropagation(); }); }; })(wysihtml5);/** * Toolbar * * @param {Object} parent Reference to instance of Editor instance * @param {Element} container Reference to the toolbar container element * * @example * <div id="toolbar"> * <a data-wysihtml5-command="createLink">insert link</a> * <a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h1">insert h1</a> * </div> * * <script> * var toolbar = new wysihtml5.toolbar.Toolbar(editor, document.getElementById("toolbar")); * </script> */ (function(wysihtml5) { var CLASS_NAME_COMMAND_DISABLED = "wysihtml5-command-disabled", CLASS_NAME_COMMANDS_DISABLED = "wysihtml5-commands-disabled", CLASS_NAME_COMMAND_ACTIVE = "wysihtml5-command-active", CLASS_NAME_ACTION_ACTIVE = "wysihtml5-action-active", dom = wysihtml5.dom; wysihtml5.toolbar.Toolbar = Base.extend( /** @scope wysihtml5.toolbar.Toolbar.prototype */ { constructor: function(editor, container) { this.editor = editor; this.container = typeof(container) === "string" ? document.getElementById(container) : container; this.composer = editor.composer; this._getLinks("command"); this._getLinks("action"); this._observe(); this.show(); var speechInputLinks = this.container.querySelectorAll("[data-wysihtml5-command=insertSpeech]"), length = speechInputLinks.length, i = 0; for (; i<length; i++) { new wysihtml5.toolbar.Speech(this, speechInputLinks[i]); } }, _getLinks: function(type) { var links = this[type + "Links"] = wysihtml5.lang.array(this.container.querySelectorAll("[data-wysihtml5-" + type + "]")).get(), length = links.length, i = 0, mapping = this[type + "Mapping"] = {}, link, group, name, value, dialog; for (; i<length; i++) { link = links[i]; name = link.getAttribute("data-wysihtml5-" + type); value = link.getAttribute("data-wysihtml5-" + type + "-value"); group = this.container.querySelector("[data-wysihtml5-" + type + "-group='" + name + "']"); dialog = this._getDialog(link, name); mapping[name + ":" + value] = { link: link, group: group, name: name, value: value, dialog: dialog, state: false }; } }, _getDialog: function(link, command) { var that = this, dialogElement = this.container.querySelector("[data-wysihtml5-dialog='" + command + "']"), dialog, caretBookmark; if (dialogElement) { dialog = new wysihtml5.toolbar.Dialog(link, dialogElement); dialog.observe("show", function() { caretBookmark = that.composer.selection.getBookmark(); that.editor.fire("show:dialog", { command: command, dialogContainer: dialogElement, commandLink: link }); }); dialog.observe("save", function(attributes) { if (caretBookmark) { that.composer.selection.setBookmark(caretBookmark); } that._execCommand(command, attributes); that.editor.fire("save:dialog", { command: command, dialogContainer: dialogElement, commandLink: link }); }); dialog.observe("cancel", function() { that.editor.focus(false); that.editor.fire("cancel:dialog", { command: command, dialogContainer: dialogElement, commandLink: link }); }); } return dialog; }, /** * @example * var toolbar = new wysihtml5.Toolbar(); * // Insert a <blockquote> element or wrap current selection in <blockquote> * toolbar.execCommand("formatBlock", "blockquote"); */ execCommand: function(command, commandValue) { if (this.commandsDisabled) { return; } var commandObj = this.commandMapping[command + ":" + commandValue]; // Show dialog when available if (commandObj && commandObj.dialog && !commandObj.state) { commandObj.dialog.show(); } else { this._execCommand(command, commandValue); } }, _execCommand: function(command, commandValue) { // Make sure that composer is focussed (false => don't move caret to the end) this.editor.focus(false); this.composer.commands.exec(command, commandValue); this._updateLinkStates(); }, execAction: function(action) { var editor = this.editor; switch(action) { case "change_view": if (editor.currentView === editor.textarea) { editor.fire("change_view", "composer"); } else { editor.fire("change_view", "textarea"); } break; } }, _observe: function() { var that = this, editor = this.editor, container = this.container, links = this.commandLinks.concat(this.actionLinks), length = links.length, i = 0; for (; i<length; i++) { // 'javascript:;' and unselectable=on Needed for IE, but done in all browsers to make sure that all get the same css applied // (you know, a:link { ... } doesn't match anchors with missing href attribute) dom.setAttributes({ href: "javascript:;", unselectable: "on" }).on(links[i]); } // Needed for opera dom.delegate(container, "[data-wysihtml5-command]", "mousedown", function(event) { event.preventDefault(); }); dom.delegate(container, "[data-wysihtml5-command]", "click", function(event) { var link = this, command = link.getAttribute("data-wysihtml5-command"), commandValue = link.getAttribute("data-wysihtml5-command-value"); that.execCommand(command, commandValue); event.preventDefault(); }); dom.delegate(container, "[data-wysihtml5-action]", "click", function(event) { var action = this.getAttribute("data-wysihtml5-action"); that.execAction(action); event.preventDefault(); }); editor.observe("focus:composer", function() { that.bookmark = null; clearInterval(that.interval); that.interval = setInterval(function() { that._updateLinkStates(); }, 500); }); editor.observe("blur:composer", function() { clearInterval(that.interval); }); editor.observe("destroy:composer", function() { clearInterval(that.interval); }); editor.observe("change_view", function(currentView) { // Set timeout needed in order to let the blur event fire first setTimeout(function() { that.commandsDisabled = (currentView !== "composer"); that._updateLinkStates(); if (that.commandsDisabled) { dom.addClass(container, CLASS_NAME_COMMANDS_DISABLED); } else { dom.removeClass(container, CLASS_NAME_COMMANDS_DISABLED); } }, 0); }); }, _updateLinkStates: function() { var element = this.composer.element, commandMapping = this.commandMapping, actionMapping = this.actionMapping, i, state, action, command; // every millisecond counts... this is executed quite often for (i in commandMapping) { command = commandMapping[i]; if (this.commandsDisabled) { state = false; dom.removeClass(command.link, CLASS_NAME_COMMAND_ACTIVE); if (command.group) { dom.removeClass(command.group, CLASS_NAME_COMMAND_ACTIVE); } if (command.dialog) { command.dialog.hide(); } } else { state = this.composer.commands.state(command.name, command.value); if (wysihtml5.lang.object(state).isArray()) { // Grab first and only object/element in state array, otherwise convert state into boolean // to avoid showing a dialog for multiple selected elements which may have different attributes // eg. when two links with different href are selected, the state will be an array consisting of both link elements // but the dialog interface can only update one state = state.length === 1 ? state[0] : true; } dom.removeClass(command.link, CLASS_NAME_COMMAND_DISABLED); if (command.group) { dom.removeClass(command.group, CLASS_NAME_COMMAND_DISABLED); } } if (command.state === state) { continue; } command.state = state; if (state) { dom.addClass(command.link, CLASS_NAME_COMMAND_ACTIVE); if (command.group) { dom.addClass(command.group, CLASS_NAME_COMMAND_ACTIVE); } if (command.dialog) { if (typeof(state) === "object") { command.dialog.show(state); } else { command.dialog.hide(); } } } else { dom.removeClass(command.link, CLASS_NAME_COMMAND_ACTIVE); if (command.group) { dom.removeClass(command.group, CLASS_NAME_COMMAND_ACTIVE); } if (command.dialog) { command.dialog.hide(); } } } for (i in actionMapping) { action = actionMapping[i]; if (action.name === "change_view") { action.state = this.editor.currentView === this.editor.textarea; if (action.state) { dom.addClass(action.link, CLASS_NAME_ACTION_ACTIVE); } else { dom.removeClass(action.link, CLASS_NAME_ACTION_ACTIVE); } } } }, show: function() { this.container.style.display = ""; }, hide: function() { this.container.style.display = "none"; } }); })(wysihtml5); /** * WYSIHTML5 Editor * * @param {Element} textareaElement Reference to the textarea which should be turned into a rich text interface * @param {Object} [config] See defaultConfig object below for explanation of each individual config option * * @events * load * beforeload (for internal use only) * focus * focus:composer * focus:textarea * blur * blur:composer * blur:textarea * change * change:composer * change:textarea * paste * paste:composer * paste:textarea * newword:composer * destroy:composer * undo:composer * redo:composer * beforecommand:composer * aftercommand:composer * change_view */ (function(wysihtml5) { var undef; var defaultConfig = { // Give the editor a name, the name will also be set as class name on the iframe and on the iframe's body name: undef, // Whether the editor should look like the textarea (by adopting styles) style: true, // Id of the toolbar element, pass falsey value if you don't want any toolbar logic toolbar: undef, // Whether urls, entered by the user should automatically become clickable-links autoLink: true, // Object which includes parser rules to apply when html gets inserted via copy & paste // See parser_rules/*.js for examples parserRules: { tags: { br: {}, span: {}, div: {}, p: {} }, classes: {} }, // Parser method to use when the user inserts content via copy & paste parser: wysihtml5.dom.parse, // Class name which should be set on the contentEditable element in the created sandbox iframe, can be styled via the 'stylesheets' option composerClassName: "wysihtml5-editor", // Class name to add to the body when the wysihtml5 editor is supported bodyClassName: "wysihtml5-supported", // Array (or single string) of stylesheet urls to be loaded in the editor's iframe stylesheets: [], // Placeholder text to use, defaults to the placeholder attribute on the textarea element placeholderText: undef, // Whether the composer should allow the user to manually resize images, tables etc. allowObjectResizing: true, // Whether the rich text editor should be rendered on touch devices (wysihtml5 >= 0.3.0 comes with basic support for iOS 5) supportTouchDevices: true }; wysihtml5.Editor = wysihtml5.lang.Dispatcher.extend( /** @scope wysihtml5.Editor.prototype */ { constructor: function(textareaElement, config) { this.textareaElement = typeof(textareaElement) === "string" ? document.getElementById(textareaElement) : textareaElement; this.config = wysihtml5.lang.object({}).merge(defaultConfig).merge(config).get(); this.textarea = new wysihtml5.views.Textarea(this, this.textareaElement, this.config); this.currentView = this.textarea; this._isCompatible = wysihtml5.browser.supported(); // Sort out unsupported/unwanted browsers here if (!this._isCompatible || (!this.config.supportTouchDevices && wysihtml5.browser.isTouchDevice())) { var that = this; setTimeout(function() { that.fire("beforeload").fire("load"); }, 0); return; } // Add class name to body, to indicate that the editor is supported wysihtml5.dom.addClass(document.body, this.config.bodyClassName); this.composer = new wysihtml5.views.Composer(this, this.textareaElement, this.config); this.currentView = this.composer; if (typeof(this.config.parser) === "function") { this._initParser(); } this.observe("beforeload", function() { this.synchronizer = new wysihtml5.views.Synchronizer(this, this.textarea, this.composer); if (this.config.toolbar) { this.toolbar = new wysihtml5.toolbar.Toolbar(this, this.config.toolbar); } }); try { console.log("Heya! This page is using wysihtml5 for rich text editing. Check out https://github.com/xing/wysihtml5"); } catch(e) {} }, isCompatible: function() { return this._isCompatible; }, clear: function() { this.currentView.clear(); return this; }, getValue: function(parse) { return this.currentView.getValue(parse); }, setValue: function(html, parse) { if (!html) { return this.clear(); } this.currentView.setValue(html, parse); return this; }, focus: function(setToEnd) { this.currentView.focus(setToEnd); return this; }, /** * Deactivate editor (make it readonly) */ disable: function() { this.currentView.disable(); return this; }, /** * Activate editor */ enable: function() { this.currentView.enable(); return this; }, isEmpty: function() { return this.currentView.isEmpty(); }, hasPlaceholderSet: function() { return this.currentView.hasPlaceholderSet(); }, parse: function(htmlOrElement) { var returnValue = this.config.parser(htmlOrElement, this.config.parserRules, this.composer.sandbox.getDocument(), true); if (typeof(htmlOrElement) === "object") { wysihtml5.quirks.redraw(htmlOrElement); } return returnValue; }, /** * Prepare html parser logic * - Observes for paste and drop */ _initParser: function() { this.observe("paste:composer", function() { var keepScrollPosition = true, that = this; that.composer.selection.executeAndRestore(function() { wysihtml5.quirks.cleanPastedHTML(that.composer.element); that.parse(that.composer.element); }, keepScrollPosition); }); this.observe("paste:textarea", function() { var value = this.textarea.getValue(), newValue; newValue = this.parse(value); this.textarea.setValue(newValue); }); } }); })(wysihtml5);
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.deeplearning4j</groupId> <artifactId>dl4j-streaming_2.11</artifactId> <packaging>jar</packaging> <version>0.8.1_spark_1-SNAPSHOT</version> <parent> <artifactId>deeplearning4j-scaleout</artifactId> <groupId>org.deeplearning4j</groupId> <version>0.8.1-SNAPSHOT</version> </parent> <properties> <kafka.scala.exclusion.version>2.11</kafka.scala.exclusion.version> <!-- These Spark version properties have to defined be here, and NOT in the deeplearning4j-parent pom or in deeplearning4j-scaleout. Otherwise, the properties will be resolved to their defaults (and not the values present during the build). Whereas when defined here (the version is spark 1 vs. 2 specific) we can have different version properties simultaneously (in different pom files) instead of a single global property. --> <spark.version>1.6.2</spark.version> <spark.major.version>1</spark.major.version> <datavec.spark.version>0.8.1_spark_1-SNAPSHOT</datavec.spark.version> </properties> <name>Dl4j Streaming</name> <url>http://www.deeplearning4j.org</url> <dependencies> <dependency> <groupId>org.datavec</groupId> <artifactId>datavec-camel</artifactId> <version>${project.parent.version}</version> </dependency> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-csv</artifactId> <version>${camel.version}</version> </dependency> <dependency> <groupId>org.deeplearning4j</groupId> <artifactId>dl4j-spark_2.11</artifactId> <version>${project.version}</version> <exclusions> <exclusion> <groupId>org.apache.spark</groupId> <artifactId>spark-core_2.11</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.nd4j</groupId> <artifactId>nd4j-base64</artifactId> <version>${nd4j.version}</version> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-streaming_2.11</artifactId> <version>${spark.version}</version> </dependency> <dependency> <groupId>org.datavec</groupId> <artifactId>datavec-spark_2.11</artifactId> <version>${datavec.spark.version}</version> </dependency> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>${zookeeper.version}</version> </dependency> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-kafka</artifactId> <version>${camel.version}</version> </dependency> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-core</artifactId> <version>${camel.version}</version> </dependency> <dependency> <groupId>org.apache.kafka</groupId> <artifactId>kafka_2.11</artifactId> <version>${kafka.version}</version> <scope>test</scope> <exclusions> <exclusion> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> </exclusion> <exclusion> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> </exclusion> <exclusion> <groupId>log4j</groupId> <artifactId>log4j</artifactId> </exclusion> </exclusions> </dependency> <!-- testing --> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-test</artifactId> <version>${camel.version}</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <!-- added source folder containing the code specific to the spark version --> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>${maven-build-helper-plugin.version}</version> <executions> <execution> <id>add-source</id> <phase>generate-sources</phase> <goals><goal>add-source</goal></goals> <configuration> <sources> <source>src/main/spark-${spark.major.version}</source> </sources> </configuration> </execution> </executions> </plugin> </plugins> </build> <profiles> <profile> <id>test-nd4j-native</id> </profile> <profile> <id>test-nd4j-cuda-8.0</id> </profile> </profiles> </project>
package test type typeForTest struct { F map[string]string }
"""Tests for Vizio config flow.""" import dataclasses import pytest import voluptuous as vol from homeassistant import data_entry_flow from homeassistant.components.media_player import MediaPlayerDeviceClass from homeassistant.components.vizio.config_flow import _get_config_schema from homeassistant.components.vizio.const import ( CONF_APPS, CONF_APPS_TO_INCLUDE_OR_EXCLUDE, CONF_INCLUDE, CONF_VOLUME_STEP, DEFAULT_NAME, DEFAULT_VOLUME_STEP, DOMAIN, VIZIO_SCHEMA, ) from homeassistant.config_entries import ( SOURCE_IGNORE, SOURCE_IMPORT, SOURCE_USER, SOURCE_ZEROCONF, ) from homeassistant.const import ( CONF_ACCESS_TOKEN, CONF_DEVICE_CLASS, CONF_HOST, CONF_NAME, CONF_PIN, ) from homeassistant.core import HomeAssistant from .const import ( ACCESS_TOKEN, CURRENT_APP, HOST, HOST2, MOCK_IMPORT_VALID_TV_CONFIG, MOCK_INCLUDE_APPS, MOCK_INCLUDE_NO_APPS, MOCK_PIN_CONFIG, MOCK_SPEAKER_CONFIG, MOCK_TV_CONFIG_NO_TOKEN, MOCK_TV_WITH_ADDITIONAL_APPS_CONFIG, MOCK_TV_WITH_EXCLUDE_CONFIG, MOCK_USER_VALID_TV_CONFIG, MOCK_ZEROCONF_SERVICE_INFO, NAME, NAME2, UNIQUE_ID, VOLUME_STEP, ) from tests.common import MockConfigEntry async def test_user_flow_minimum_fields( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_setup: pytest.fixture, ) -> None: """Test user config flow with minimum fields.""" # test form shows result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] == data_entry_flow.FlowResultType.FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_SPEAKER_CONFIG ) assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY assert result["title"] == NAME assert result["data"][CONF_NAME] == NAME assert result["data"][CONF_HOST] == HOST assert result["data"][CONF_DEVICE_CLASS] == MediaPlayerDeviceClass.SPEAKER async def test_user_flow_all_fields( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_setup: pytest.fixture, ) -> None: """Test user config flow with all fields.""" # test form shows result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] == data_entry_flow.FlowResultType.FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_USER_VALID_TV_CONFIG ) assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY assert result["title"] == NAME assert result["data"][CONF_NAME] == NAME assert result["data"][CONF_HOST] == HOST assert result["data"][CONF_DEVICE_CLASS] == MediaPlayerDeviceClass.TV assert result["data"][CONF_ACCESS_TOKEN] == ACCESS_TOKEN assert CONF_APPS not in result["data"] async def test_speaker_options_flow( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_update: pytest.fixture, ) -> None: """Test options config flow for speaker.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=MOCK_SPEAKER_CONFIG ) await hass.async_block_till_done() assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY entry = result["result"] result = await hass.config_entries.options.async_init(entry.entry_id, data=None) assert result["type"] == data_entry_flow.FlowResultType.FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_VOLUME_STEP: VOLUME_STEP} ) assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY assert result["title"] == "" assert result["data"][CONF_VOLUME_STEP] == VOLUME_STEP assert CONF_APPS not in result["data"] async def test_tv_options_flow_no_apps( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_update: pytest.fixture, ) -> None: """Test options config flow for TV without providing apps option.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=MOCK_USER_VALID_TV_CONFIG ) await hass.async_block_till_done() assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY entry = result["result"] result = await hass.config_entries.options.async_init(entry.entry_id, data=None) assert result["type"] == data_entry_flow.FlowResultType.FORM assert result["step_id"] == "init" options = {CONF_VOLUME_STEP: VOLUME_STEP} options.update(MOCK_INCLUDE_NO_APPS) result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=options ) assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY assert result["title"] == "" assert result["data"][CONF_VOLUME_STEP] == VOLUME_STEP assert CONF_APPS not in result["data"] async def test_tv_options_flow_with_apps( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_update: pytest.fixture, ) -> None: """Test options config flow for TV with providing apps option.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=MOCK_USER_VALID_TV_CONFIG ) await hass.async_block_till_done() assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY entry = result["result"] result = await hass.config_entries.options.async_init(entry.entry_id, data=None) assert result["type"] == data_entry_flow.FlowResultType.FORM assert result["step_id"] == "init" options = {CONF_VOLUME_STEP: VOLUME_STEP} options.update(MOCK_INCLUDE_APPS) result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=options ) assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY assert result["title"] == "" assert result["data"][CONF_VOLUME_STEP] == VOLUME_STEP assert CONF_APPS in result["data"] assert result["data"][CONF_APPS] == {CONF_INCLUDE: [CURRENT_APP]} async def test_tv_options_flow_start_with_volume( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_update: pytest.fixture, ) -> None: """Test options config flow for TV with providing apps option after providing volume step in initial config.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=MOCK_USER_VALID_TV_CONFIG ) await hass.async_block_till_done() assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY entry = result["result"] result = await hass.config_entries.options.async_init( entry.entry_id, data={CONF_VOLUME_STEP: VOLUME_STEP} ) assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY assert entry.options assert entry.options == {CONF_VOLUME_STEP: VOLUME_STEP} assert CONF_APPS not in entry.options assert CONF_APPS_TO_INCLUDE_OR_EXCLUDE not in entry.options result = await hass.config_entries.options.async_init(entry.entry_id, data=None) assert result["type"] == data_entry_flow.FlowResultType.FORM assert result["step_id"] == "init" options = {CONF_VOLUME_STEP: VOLUME_STEP} options.update(MOCK_INCLUDE_APPS) result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=options ) assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY assert result["title"] == "" assert result["data"][CONF_VOLUME_STEP] == VOLUME_STEP assert CONF_APPS in result["data"] assert result["data"][CONF_APPS] == {CONF_INCLUDE: [CURRENT_APP]} async def test_user_host_already_configured( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_setup: pytest.fixture, ) -> None: """Test host is already configured during user setup.""" entry = MockConfigEntry( domain=DOMAIN, data=MOCK_SPEAKER_CONFIG, options={CONF_VOLUME_STEP: VOLUME_STEP}, unique_id=UNIQUE_ID, ) entry.add_to_hass(hass) fail_entry = MOCK_SPEAKER_CONFIG.copy() fail_entry[CONF_NAME] = "newtestname" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=fail_entry ) assert result["type"] == data_entry_flow.FlowResultType.FORM assert result["errors"] == {CONF_HOST: "existing_config_entry_found"} async def test_user_serial_number_already_exists( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_setup: pytest.fixture, ) -> None: """Test serial_number is already configured with different host and name during user setup.""" # Set up new entry MockConfigEntry( domain=DOMAIN, data=MOCK_SPEAKER_CONFIG, unique_id=UNIQUE_ID ).add_to_hass(hass) # Set up new entry with same unique_id but different host and name fail_entry = MOCK_SPEAKER_CONFIG.copy() fail_entry[CONF_HOST] = HOST2 fail_entry[CONF_NAME] = NAME2 result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=fail_entry ) assert result["type"] == data_entry_flow.FlowResultType.FORM assert result["errors"] == {CONF_HOST: "existing_config_entry_found"} async def test_user_error_on_could_not_connect( hass: HomeAssistant, vizio_no_unique_id: pytest.fixture ) -> None: """Test with could_not_connect during user setup due to no connectivity.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=MOCK_USER_VALID_TV_CONFIG ) assert result["type"] == data_entry_flow.FlowResultType.FORM assert result["errors"] == {CONF_HOST: "cannot_connect"} async def test_user_error_on_could_not_connect_invalid_token( hass: HomeAssistant, vizio_cant_connect: pytest.fixture ) -> None: """Test with could_not_connect during user setup due to invalid token.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=MOCK_USER_VALID_TV_CONFIG ) assert result["type"] == data_entry_flow.FlowResultType.FORM assert result["errors"] == {"base": "cannot_connect"} async def test_user_tv_pairing_no_apps( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_setup: pytest.fixture, vizio_complete_pairing: pytest.fixture, ) -> None: """Test pairing config flow when access token not provided for tv during user entry and no apps configured.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=MOCK_TV_CONFIG_NO_TOKEN ) assert result["type"] == data_entry_flow.FlowResultType.FORM assert result["step_id"] == "pair_tv" result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_PIN_CONFIG ) assert result["type"] == data_entry_flow.FlowResultType.FORM assert result["step_id"] == "pairing_complete" result = await hass.config_entries.flow.async_configure(result["flow_id"]) assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY assert result["title"] == NAME assert result["data"][CONF_NAME] == NAME assert result["data"][CONF_HOST] == HOST assert result["data"][CONF_DEVICE_CLASS] == MediaPlayerDeviceClass.TV assert CONF_APPS not in result["data"] async def test_user_start_pairing_failure( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_setup: pytest.fixture, vizio_start_pairing_failure: pytest.fixture, ) -> None: """Test failure to start pairing from user config flow.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=MOCK_TV_CONFIG_NO_TOKEN ) assert result["type"] == data_entry_flow.FlowResultType.FORM assert result["step_id"] == "user" assert result["errors"] == {"base": "cannot_connect"} async def test_user_invalid_pin( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_setup: pytest.fixture, vizio_invalid_pin_failure: pytest.fixture, ) -> None: """Test failure to complete pairing from user config flow.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=MOCK_TV_CONFIG_NO_TOKEN ) assert result["type"] == data_entry_flow.FlowResultType.FORM assert result["step_id"] == "pair_tv" result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_PIN_CONFIG ) assert result["type"] == data_entry_flow.FlowResultType.FORM assert result["step_id"] == "pair_tv" assert result["errors"] == {CONF_PIN: "complete_pairing_failed"} async def test_user_ignore( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_setup: pytest.fixture, ) -> None: """Test user config flow doesn't throw an error when there's an existing ignored source.""" entry = MockConfigEntry( domain=DOMAIN, data=MOCK_SPEAKER_CONFIG, options={CONF_VOLUME_STEP: VOLUME_STEP}, source=SOURCE_IGNORE, ) entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=MOCK_SPEAKER_CONFIG ) assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY async def test_import_flow_minimum_fields( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_setup: pytest.fixture, ) -> None: """Test import config flow with minimum fields.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=vol.Schema(VIZIO_SCHEMA)( {CONF_HOST: HOST, CONF_DEVICE_CLASS: MediaPlayerDeviceClass.SPEAKER} ), ) assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY assert result["title"] == DEFAULT_NAME assert result["data"][CONF_NAME] == DEFAULT_NAME assert result["data"][CONF_HOST] == HOST assert result["data"][CONF_DEVICE_CLASS] == MediaPlayerDeviceClass.SPEAKER assert result["data"][CONF_VOLUME_STEP] == DEFAULT_VOLUME_STEP async def test_import_flow_all_fields( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_setup: pytest.fixture, ) -> None: """Test import config flow with all fields.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=vol.Schema(VIZIO_SCHEMA)(MOCK_IMPORT_VALID_TV_CONFIG), ) assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY assert result["title"] == NAME assert result["data"][CONF_NAME] == NAME assert result["data"][CONF_HOST] == HOST assert result["data"][CONF_DEVICE_CLASS] == MediaPlayerDeviceClass.TV assert result["data"][CONF_ACCESS_TOKEN] == ACCESS_TOKEN assert result["data"][CONF_VOLUME_STEP] == VOLUME_STEP async def test_import_entity_already_configured( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_setup: pytest.fixture, ) -> None: """Test entity is already configured during import setup.""" entry = MockConfigEntry( domain=DOMAIN, data=vol.Schema(VIZIO_SCHEMA)(MOCK_SPEAKER_CONFIG), options={CONF_VOLUME_STEP: VOLUME_STEP}, ) entry.add_to_hass(hass) fail_entry = vol.Schema(VIZIO_SCHEMA)(MOCK_SPEAKER_CONFIG.copy()) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=fail_entry ) assert result["type"] == data_entry_flow.FlowResultType.ABORT assert result["reason"] == "already_configured_device" async def test_import_flow_update_options( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_update: pytest.fixture, ) -> None: """Test import config flow with updated options.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=vol.Schema(VIZIO_SCHEMA)(MOCK_SPEAKER_CONFIG), ) await hass.async_block_till_done() assert result["result"].options == {CONF_VOLUME_STEP: DEFAULT_VOLUME_STEP} assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY entry_id = result["result"].entry_id updated_config = MOCK_SPEAKER_CONFIG.copy() updated_config[CONF_VOLUME_STEP] = VOLUME_STEP + 1 result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=vol.Schema(VIZIO_SCHEMA)(updated_config), ) assert result["type"] == data_entry_flow.FlowResultType.ABORT assert result["reason"] == "updated_entry" config_entry = hass.config_entries.async_get_entry(entry_id) assert config_entry.options[CONF_VOLUME_STEP] == VOLUME_STEP + 1 async def test_import_flow_update_name_and_apps( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_update: pytest.fixture, ) -> None: """Test import config flow with updated name and apps.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=vol.Schema(VIZIO_SCHEMA)(MOCK_IMPORT_VALID_TV_CONFIG), ) await hass.async_block_till_done() assert result["result"].data[CONF_NAME] == NAME assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY entry_id = result["result"].entry_id updated_config = MOCK_IMPORT_VALID_TV_CONFIG.copy() updated_config[CONF_NAME] = NAME2 updated_config[CONF_APPS] = {CONF_INCLUDE: [CURRENT_APP]} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=vol.Schema(VIZIO_SCHEMA)(updated_config), ) assert result["type"] == data_entry_flow.FlowResultType.ABORT assert result["reason"] == "updated_entry" config_entry = hass.config_entries.async_get_entry(entry_id) assert config_entry.data[CONF_NAME] == NAME2 assert config_entry.data[CONF_APPS] == {CONF_INCLUDE: [CURRENT_APP]} assert config_entry.options[CONF_APPS] == {CONF_INCLUDE: [CURRENT_APP]} async def test_import_flow_update_remove_apps( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_update: pytest.fixture, ) -> None: """Test import config flow with removed apps.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=vol.Schema(VIZIO_SCHEMA)(MOCK_TV_WITH_EXCLUDE_CONFIG), ) await hass.async_block_till_done() assert result["result"].data[CONF_NAME] == NAME assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY config_entry = hass.config_entries.async_get_entry(result["result"].entry_id) assert CONF_APPS in config_entry.data assert CONF_APPS in config_entry.options updated_config = MOCK_TV_WITH_EXCLUDE_CONFIG.copy() updated_config.pop(CONF_APPS) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=vol.Schema(VIZIO_SCHEMA)(updated_config), ) assert result["type"] == data_entry_flow.FlowResultType.ABORT assert result["reason"] == "updated_entry" assert CONF_APPS not in config_entry.data assert CONF_APPS not in config_entry.options async def test_import_needs_pairing( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_setup: pytest.fixture, vizio_complete_pairing: pytest.fixture, ) -> None: """Test pairing config flow when access token not provided for tv during import.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=MOCK_TV_CONFIG_NO_TOKEN ) assert result["type"] == data_entry_flow.FlowResultType.FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_TV_CONFIG_NO_TOKEN ) assert result["type"] == data_entry_flow.FlowResultType.FORM assert result["step_id"] == "pair_tv" result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_PIN_CONFIG ) assert result["type"] == data_entry_flow.FlowResultType.FORM assert result["step_id"] == "pairing_complete_import" result = await hass.config_entries.flow.async_configure(result["flow_id"]) assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY assert result["title"] == NAME assert result["data"][CONF_NAME] == NAME assert result["data"][CONF_HOST] == HOST assert result["data"][CONF_DEVICE_CLASS] == MediaPlayerDeviceClass.TV async def test_import_with_apps_needs_pairing( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_setup: pytest.fixture, vizio_complete_pairing: pytest.fixture, ) -> None: """Test pairing config flow when access token not provided for tv but apps are included during import.""" import_config = MOCK_TV_CONFIG_NO_TOKEN.copy() import_config[CONF_APPS] = {CONF_INCLUDE: [CURRENT_APP]} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=import_config ) assert result["type"] == data_entry_flow.FlowResultType.FORM assert result["step_id"] == "user" # Mock inputting info without apps to make sure apps get stored result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=_get_config_schema(MOCK_TV_CONFIG_NO_TOKEN)(MOCK_TV_CONFIG_NO_TOKEN), ) assert result["type"] == data_entry_flow.FlowResultType.FORM assert result["step_id"] == "pair_tv" result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_PIN_CONFIG ) assert result["type"] == data_entry_flow.FlowResultType.FORM assert result["step_id"] == "pairing_complete_import" result = await hass.config_entries.flow.async_configure(result["flow_id"]) assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY assert result["title"] == NAME assert result["data"][CONF_NAME] == NAME assert result["data"][CONF_HOST] == HOST assert result["data"][CONF_DEVICE_CLASS] == MediaPlayerDeviceClass.TV assert result["data"][CONF_APPS][CONF_INCLUDE] == [CURRENT_APP] async def test_import_flow_additional_configs( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_update: pytest.fixture, ) -> None: """Test import config flow with additional configs defined in CONF_APPS.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=vol.Schema(VIZIO_SCHEMA)(MOCK_TV_WITH_ADDITIONAL_APPS_CONFIG), ) await hass.async_block_till_done() assert result["result"].data[CONF_NAME] == NAME assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY config_entry = hass.config_entries.async_get_entry(result["result"].entry_id) assert CONF_APPS in config_entry.data assert CONF_APPS not in config_entry.options async def test_import_error( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_setup: pytest.fixture, caplog: pytest.fixture, ) -> None: """Test that error is logged when import config has an error.""" entry = MockConfigEntry( domain=DOMAIN, data=vol.Schema(VIZIO_SCHEMA)(MOCK_SPEAKER_CONFIG), options={CONF_VOLUME_STEP: VOLUME_STEP}, unique_id=UNIQUE_ID, ) entry.add_to_hass(hass) fail_entry = MOCK_SPEAKER_CONFIG.copy() fail_entry[CONF_HOST] = "0.0.0.0" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=vol.Schema(VIZIO_SCHEMA)(fail_entry), ) assert result["type"] == data_entry_flow.FlowResultType.FORM # Ensure error gets logged vizio_log_list = [ log for log in caplog.records if log.name == "homeassistant.components.vizio.config_flow" ] assert len(vizio_log_list) == 1 async def test_import_ignore( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_setup: pytest.fixture, ) -> None: """Test import config flow doesn't throw an error when there's an existing ignored source.""" entry = MockConfigEntry( domain=DOMAIN, data=MOCK_SPEAKER_CONFIG, options={CONF_VOLUME_STEP: VOLUME_STEP}, source=SOURCE_IGNORE, ) entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=vol.Schema(VIZIO_SCHEMA)(MOCK_SPEAKER_CONFIG), ) assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY async def test_zeroconf_flow( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_setup: pytest.fixture, vizio_guess_device_type: pytest.fixture, ) -> None: """Test zeroconf config flow.""" discovery_info = dataclasses.replace(MOCK_ZEROCONF_SERVICE_INFO) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_ZEROCONF}, data=discovery_info ) # Form should always show even if all required properties are discovered assert result["type"] == data_entry_flow.FlowResultType.FORM assert result["step_id"] == "user" # Apply discovery updates to entry to mimic when user hits submit without changing # defaults which were set from discovery parameters user_input = result["data_schema"]( { CONF_HOST: f"{discovery_info.host}:{discovery_info.port}", CONF_NAME: discovery_info.name[: -(len(discovery_info.type) + 1)], CONF_DEVICE_CLASS: "speaker", } ) result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=user_input ) assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY assert result["title"] == NAME assert result["data"][CONF_HOST] == HOST assert result["data"][CONF_NAME] == NAME assert result["data"][CONF_DEVICE_CLASS] == MediaPlayerDeviceClass.SPEAKER async def test_zeroconf_flow_already_configured( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_setup: pytest.fixture, vizio_guess_device_type: pytest.fixture, ) -> None: """Test entity is already configured during zeroconf setup.""" entry = MockConfigEntry( domain=DOMAIN, data=MOCK_SPEAKER_CONFIG, options={CONF_VOLUME_STEP: VOLUME_STEP}, unique_id=UNIQUE_ID, ) entry.add_to_hass(hass) # Try rediscovering same device discovery_info = dataclasses.replace(MOCK_ZEROCONF_SERVICE_INFO) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_ZEROCONF}, data=discovery_info ) # Flow should abort because device is already setup assert result["type"] == data_entry_flow.FlowResultType.ABORT assert result["reason"] == "already_configured" async def test_zeroconf_flow_with_port_in_host( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_setup: pytest.fixture, vizio_guess_device_type: pytest.fixture, ) -> None: """Test entity is already configured during zeroconf setup when port is in host.""" entry = MockConfigEntry( domain=DOMAIN, data=MOCK_SPEAKER_CONFIG, options={CONF_VOLUME_STEP: VOLUME_STEP}, unique_id=UNIQUE_ID, ) entry.add_to_hass(hass) # Try rediscovering same device, this time with port already in host discovery_info = dataclasses.replace(MOCK_ZEROCONF_SERVICE_INFO) discovery_info.host = f"{discovery_info.host}:{discovery_info.port}" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_ZEROCONF}, data=discovery_info ) # Flow should abort because device is already setup assert result["type"] == data_entry_flow.FlowResultType.ABORT assert result["reason"] == "already_configured" async def test_zeroconf_dupe_fail( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_setup: pytest.fixture, vizio_guess_device_type: pytest.fixture, ) -> None: """Test zeroconf config flow when device gets discovered multiple times.""" discovery_info = dataclasses.replace(MOCK_ZEROCONF_SERVICE_INFO) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_ZEROCONF}, data=discovery_info ) # Form should always show even if all required properties are discovered assert result["type"] == data_entry_flow.FlowResultType.FORM assert result["step_id"] == "user" discovery_info = dataclasses.replace(MOCK_ZEROCONF_SERVICE_INFO) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_ZEROCONF}, data=discovery_info ) # Flow should abort because device is already setup assert result["type"] == data_entry_flow.FlowResultType.ABORT assert result["reason"] == "already_in_progress" async def test_zeroconf_ignore( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_setup: pytest.fixture, vizio_guess_device_type: pytest.fixture, ) -> None: """Test zeroconf discovery doesn't throw an error when there's an existing ignored source.""" entry = MockConfigEntry( domain=DOMAIN, data=MOCK_SPEAKER_CONFIG, options={CONF_VOLUME_STEP: VOLUME_STEP}, source=SOURCE_IGNORE, ) entry.add_to_hass(hass) discovery_info = dataclasses.replace(MOCK_ZEROCONF_SERVICE_INFO) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_ZEROCONF}, data=discovery_info ) assert result["type"] == data_entry_flow.FlowResultType.FORM async def test_zeroconf_no_unique_id( hass: HomeAssistant, vizio_guess_device_type: pytest.fixture, vizio_no_unique_id: pytest.fixture, ) -> None: """Test zeroconf discovery aborts when unique_id is None.""" discovery_info = dataclasses.replace(MOCK_ZEROCONF_SERVICE_INFO) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_ZEROCONF}, data=discovery_info ) assert result["type"] == data_entry_flow.FlowResultType.ABORT assert result["reason"] == "cannot_connect" async def test_zeroconf_abort_when_ignored( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_setup: pytest.fixture, vizio_guess_device_type: pytest.fixture, ) -> None: """Test zeroconf discovery aborts when the same host has been ignored.""" entry = MockConfigEntry( domain=DOMAIN, data=MOCK_SPEAKER_CONFIG, options={CONF_VOLUME_STEP: VOLUME_STEP}, source=SOURCE_IGNORE, unique_id=UNIQUE_ID, ) entry.add_to_hass(hass) discovery_info = dataclasses.replace(MOCK_ZEROCONF_SERVICE_INFO) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_ZEROCONF}, data=discovery_info ) assert result["type"] == data_entry_flow.FlowResultType.ABORT assert result["reason"] == "already_configured" async def test_zeroconf_flow_already_configured_hostname( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_setup: pytest.fixture, vizio_hostname_check: pytest.fixture, vizio_guess_device_type: pytest.fixture, ) -> None: """Test entity is already configured during zeroconf setup when existing entry uses hostname.""" config = MOCK_SPEAKER_CONFIG.copy() config[CONF_HOST] = "hostname" entry = MockConfigEntry( domain=DOMAIN, data=config, options={CONF_VOLUME_STEP: VOLUME_STEP}, unique_id=UNIQUE_ID, ) entry.add_to_hass(hass) # Try rediscovering same device discovery_info = dataclasses.replace(MOCK_ZEROCONF_SERVICE_INFO) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_ZEROCONF}, data=discovery_info ) # Flow should abort because device is already setup assert result["type"] == data_entry_flow.FlowResultType.ABORT assert result["reason"] == "already_configured" async def test_import_flow_already_configured_hostname( hass: HomeAssistant, vizio_connect: pytest.fixture, vizio_bypass_setup: pytest.fixture, vizio_hostname_check: pytest.fixture, ) -> None: """Test entity is already configured during import setup when existing entry uses hostname.""" config = MOCK_SPEAKER_CONFIG.copy() config[CONF_HOST] = "hostname" entry = MockConfigEntry( domain=DOMAIN, data=config, options={CONF_VOLUME_STEP: VOLUME_STEP} ) entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=vol.Schema(VIZIO_SCHEMA)(MOCK_SPEAKER_CONFIG), ) # Flow should abort because device was updated assert result["type"] == data_entry_flow.FlowResultType.ABORT assert result["reason"] == "updated_entry" assert entry.data[CONF_HOST] == HOST
/* Include margin and padding in the width calculation of input and textarea. */ input, textarea { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } input[type="text"], input[type="password"], input[type="checkbox"], input[type="color"], input[type="date"], input[type="datetime"], input[type="datetime-local"], input[type="email"], input[type="month"], input[type="number"], input[type="search"], input[type="radio"], input[type="tel"], input[type="text"], input[type="time"], input[type="url"], input[type="week"], select, textarea { border: 1px solid #ddd; -webkit-box-shadow: inset 0 1px 2px rgba( 0, 0, 0, 0.07 ); box-shadow: inset 0 1px 2px rgba( 0, 0, 0, 0.07 ); background-color: #fff; color: #32373c; outline: none; -webkit-transition: 0.05s border-color ease-in-out; transition: 0.05s border-color ease-in-out; } input[type="text"]:focus, input[type="password"]:focus, input[type="color"]:focus, input[type="date"]:focus, input[type="datetime"]:focus, input[type="datetime-local"]:focus, input[type="email"]:focus, input[type="month"]:focus, input[type="number"]:focus, input[type="search"]:focus, input[type="tel"]:focus, input[type="text"]:focus, input[type="time"]:focus, input[type="url"]:focus, input[type="week"]:focus, input[type="checkbox"]:focus, input[type="radio"]:focus, select:focus, textarea:focus { border-color: #5b9dd9; -webkit-box-shadow: 0 0 2px rgba( 30, 140, 190, 0.8 ); box-shadow: 0 0 2px rgba( 30, 140, 190, 0.8 ); } /* rtl:ignore */ input[type="email"], input[type="url"] { direction: ltr; } /* Vertically align the number selector with the input. */ input[type="number"] { height: 28px; line-height: 1; } input[type="checkbox"], input[type="radio"] { border: 1px solid #b4b9be; background: #fff; color: #555; clear: none; cursor: pointer; display: inline-block; line-height: 0; height: 16px; margin: -4px 0 0 4px; outline: 0; padding: 0 !important; text-align: center; vertical-align: middle; width: 16px; min-width: 16px; -webkit-appearance: none; -webkit-box-shadow: inset 0 1px 2px rgba( 0, 0, 0, 0.1 ); box-shadow: inset 0 1px 2px rgba( 0, 0, 0, 0.1 ); -webkit-transition: .05s border-color ease-in-out; transition: .05s border-color ease-in-out; } input[type="radio"]:checked + label:before { color: #82878c; } .wp-core-ui input[type="reset"]:hover, .wp-core-ui input[type="reset"]:active { color: #00a0d2; } td > input[type="checkbox"], .wp-admin p input[type="checkbox"], .wp-admin p input[type="radio"] { margin-top: 0; } .wp-admin p label input[type="checkbox"] { margin-top: -4px; } .wp-admin p label input[type="radio"] { margin-top: -2px; } input[type="radio"] { -webkit-border-radius: 50%; border-radius: 50%; margin-left: 4px; line-height: 10px; } input[type="checkbox"]:checked:before, input[type="radio"]:checked:before { float: right; display: inline-block; vertical-align: middle; width: 16px; font: normal 21px/1 dashicons; speak: none; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } input[type="checkbox"]:checked:before { content: "\f147"; margin: -3px -4px 0 0; color: #1e8cbe; } input[type="radio"]:checked:before { content: "\2022"; text-indent: -9999px; -webkit-border-radius: 50px; border-radius: 50px; font-size: 24px; width: 6px; height: 6px; margin: 4px; line-height: 16px; background-color: #1e8cbe; } @-moz-document url-prefix() { input[type="checkbox"], input[type="radio"], .form-table input.tog { margin-bottom: -1px; } } /* Search */ input[type="search"] { -webkit-appearance: textfield; } input[type="search"]::-webkit-search-decoration { display: none; } .ie8 input[type="password"] { font-family: sans-serif; } textarea, input, select, button { font-family: inherit; font-size: inherit; font-weight: inherit; } textarea, input, select { font-size: 14px; padding: 3px 5px; -webkit-border-radius: 0; border-radius: 0; /* Reset mobile webkit's default element styling */ } textarea { overflow: auto; padding: 2px 6px; line-height: 1.4; resize: vertical; } .wp-admin input[type="file"] { padding: 3px 0; cursor: pointer; } label { cursor: pointer; } input, select { margin: 1px; padding: 3px 5px; } input.code { padding-top: 6px; } textarea.code { line-height: 1.4; padding: 4px 6px 1px 6px; } input.readonly, input[readonly], textarea.readonly, textarea[readonly] { background-color: #eee; } ::-webkit-input-placeholder { color: #72777c; } ::-moz-placeholder { color: #72777c; opacity: 1; } :-ms-input-placeholder { color: #72777c; } .form-invalid input, .form-invalid input:focus, .form-invalid select, .form-invalid select:focus { border-color: #dc3232 !important; -webkit-box-shadow: 0 0 2px rgba( 204, 0, 0, 0.8 ); box-shadow: 0 0 2px rgba( 204, 0, 0, 0.8 ); } .form-table .form-required.form-invalid td:after { content: "\f534"; font: normal 20px/1 dashicons; color: #dc3232; margin-right: -25px; vertical-align: middle; } /* Adjust error indicator for password layout */ .form-table .form-required.user-pass1-wrap.form-invalid td:after { content: ''; } .form-table .form-required.user-pass1-wrap.form-invalid .password-input-wrapper:after { content: '\f534'; font: normal 20px/1 dashicons; color: #dc3232; margin: 0 -29px 0 6px; vertical-align: middle; } .form-input-tip { color: #666; } input:disabled, input.disabled, select:disabled, select.disabled, textarea:disabled, textarea.disabled { background: rgba( 255, 255, 255, 0.5 ); border-color: rgba( 222, 222, 222, 0.75 ); -webkit-box-shadow: inset 0 1px 2px rgba( 0, 0, 0, 0.04 ); box-shadow: inset 0 1px 2px rgba( 0, 0, 0, 0.04 ); color: rgba( 51, 51, 51, 0.5 ); } input[type="file"]:disabled, input[type="file"].disabled, input[type="range"]:disabled, input[type="range"].disabled { background: none; -webkit-box-shadow: none; box-shadow: none; cursor: default; } input[type="checkbox"]:disabled, input[type="checkbox"].disabled, input[type="radio"]:disabled, input[type="radio"].disabled, input[type="checkbox"]:disabled:checked:before, input[type="checkbox"].disabled:checked:before, input[type="radio"]:disabled:checked:before, input[type="radio"].disabled:checked:before { opacity: 0.7; } /*------------------------------------------------------------------------------ 2.0 - Forms ------------------------------------------------------------------------------*/ .wp-admin select { padding: 2px; line-height: 28px; height: 28px; vertical-align: middle; } .wp-admin .button-cancel { padding: 0 5px; line-height: 2; } .meta-box-sortables select { max-width: 100%; } .wp-admin select[multiple] { height: auto; } .submit { padding: 1.5em 0; margin: 5px 0; -webkit-border-bottom-right-radius: 3px; border-bottom-right-radius: 3px; -webkit-border-bottom-left-radius: 3px; border-bottom-left-radius: 3px; border: none; } form p.submit a.cancel:hover { text-decoration: none; } p.submit { text-align: right; max-width: 100%; margin-top: 20px; padding-top: 10px; } .textright p.submit { border: none; text-align: left; } table.form-table + p.submit, table.form-table + input + p.submit, table.form-table + input + input + p.submit { border-top: none; padding-top: 0; } #minor-publishing-actions input, #major-publishing-actions input, #minor-publishing-actions .preview { text-align: center; } textarea.all-options, input.all-options { width: 250px; } input.large-text, textarea.large-text { width: 99%; } .regular-text { width: 25em; } input.small-text { width: 50px; padding: 1px 6px; } input[type="number"].small-text { width: 65px; } input.tiny-text { width: 35px; } input[type="number"].tiny-text { width: 45px; } #doaction, #doaction2, #post-query-submit { margin: 1px 0 0 8px; } .tablenav #changeit, .tablenav #delete_all, .tablenav #clear-recent-list, .wp-filter #delete_all { margin-top: 1px; } .tablenav .actions select { float: right; margin-left: 6px; max-width: 200px; } .ie8 .tablenav .actions select { width: 155px; } .ie8 .tablenav .actions select#cat { width: 200px; } #timezone_string option { margin-right: 1em; } button.wp-hide-pw > .dashicons { position: relative; top: 3px; } label, #your-profile label + a { vertical-align: middle; } fieldset label, #your-profile label + a { vertical-align: middle; } .options-media-php label[for*="_size_"], #misc-publishing-actions label { vertical-align: baseline; } #pass-strength-result { background-color: #eee; border: 1px solid #ddd; color: #23282d; margin: -2px 1px 5px 5px; padding: 3px 5px; text-align: center; width: 25em; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; opacity: 0; } #pass-strength-result.short { background-color: #f1adad; border-color: #e35b5b; opacity: 1; } #pass-strength-result.bad { background-color: #fbc5a9; border-color: #f78b53; opacity: 1; } #pass-strength-result.good { background-color: #ffe399; border-color: #ffc733; opacity: 1; } #pass-strength-result.strong { background-color: #c1e1b9; border-color: #83c373; opacity: 1; } #pass1.short, #pass1-text.short { border-color: #e35b5b; } #pass1.bad, #pass1-text.bad { border-color: #f78b53; } #pass1.good, #pass1-text.good { border-color: #ffc733; } #pass1.strong, #pass1-text.strong { border-color: #83c373; } .pw-weak { display:none; } .indicator-hint { padding-top: 8px; } #pass1-text, .show-password #pass1 { display: none; } .show-password #pass1-text { display: inline-block; } .form-table span.description.important { font-size: 12px; } p.search-box { float: left; margin: 0; } .network-admin.themes-php p.search-box { clear: right; } .search-box input[name="s"], .tablenav .search-plugins input[name="s"], .tagsdiv .newtag { float: right; height: 28px; margin: 0 0 0 4px; } .js.plugins-php .search-box .wp-filter-search { margin: 0; width: 280px; font-size: 16px; font-weight: 300; line-height: 1.5; padding: 3px 5px; height: 32px; } input[type="text"].ui-autocomplete-loading, input[type="email"].ui-autocomplete-loading { background-image: url(../images/loading.gif); background-repeat: no-repeat; background-position: left center; visibility: visible; } input.ui-autocomplete-input.open { border-bottom-color: transparent; } ul#add-to-blog-users { margin: 0 14px 0 0; } .ui-autocomplete { padding: 0; margin: 0; list-style: none; position: absolute; z-index: 10000; border: 1px solid #5b9dd9; -webkit-box-shadow: 0 1px 2px rgba( 30, 140, 190, 0.8 ); box-shadow: 0 1px 2px rgba( 30, 140, 190, 0.8 ); background-color: #fff; } .ui-autocomplete li { margin-bottom: 0; padding: 4px 10px; white-space: nowrap; text-align: right; cursor: pointer; } /* Colors for the wplink toolbar autocomplete. */ .ui-autocomplete .ui-state-focus { background-color: #ddd; } /* Colors for the tags autocomplete. */ .wp-tags-autocomplete .ui-state-focus { background-color: #0073aa; color: #fff; } /*------------------------------------------------------------------------------ 15.0 - Comments Screen ------------------------------------------------------------------------------*/ .form-table { border-collapse: collapse; margin-top: 0.5em; width: 100%; clear: both; } .form-table, .form-table td, .form-table th, .form-table td p { font-size: 14px; } .form-table td { margin-bottom: 9px; padding: 15px 10px; line-height: 1.3; vertical-align: middle; } .form-table th, .form-wrap label { color: #23282d; font-weight: 400; text-shadow: none; vertical-align: baseline; } .form-table th { vertical-align: top; text-align: right; padding: 20px 0 20px 10px; width: 200px; line-height: 1.3; font-weight: 600; } .form-table th.th-full { width: auto; font-weight: 400; } .form-table td p { margin-top: 4px; margin-bottom: 0; } .form-table .date-time-doc { margin-top: 1em; } .form-table p.timezone-info { margin: 1em 0; } .form-table td fieldset label { margin: 0.25em 0 0.5em !important; display: inline-block; } .form-table td fieldset label, .form-table td fieldset p, .form-table td fieldset li { line-height: 1.4em; } .form-table input.tog, .form-table input[type="radio"] { margin-top: -4px; margin-left: 4px; float: none; } .form-table .pre { padding: 8px; margin: 0; } table.form-table td .updated { font-size: 13px; } table.form-table td .updated p { font-size: 13px; margin: 0.3em 0; } /*------------------------------------------------------------------------------ 18.0 - Users ------------------------------------------------------------------------------*/ #profile-page .form-table textarea { width: 500px; margin-bottom: 6px; } #profile-page .form-table #rich_editing { margin-left: 5px } #your-profile legend { font-size: 22px; } #display_name { width: 15em; } #adduser .form-field input, #createuser .form-field input { width: 25em; } .color-option { display: inline-block; width: 24%; padding: 5px 15px 15px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; margin-bottom: 3px; } .color-option:hover, .color-option.selected { background: #ddd; } .color-palette { width: 100%; border-spacing: 0; border-collapse: collapse; } .color-palette td { height: 20px; padding: 0; border: none; } .color-option { cursor: pointer; } /*------------------------------------------------------------------------------ 19.0 - Tools ------------------------------------------------------------------------------*/ .tool-box .title { margin: 8px 0; font-size: 18px; font-weight: 400; line-height: 24px; } .label-responsive { vertical-align: middle; } #export-filters p { margin: 0 0 1em; } #export-filters p.submit { margin: 7px 0 5px; } /* Card styles */ .card { position: relative; margin-top: 20px; padding: 0.7em 2em 1em; min-width: 255px; max-width: 520px; border: 1px solid #e5e5e5; -webkit-box-shadow: 0 1px 1px rgba(0,0,0,0.04); box-shadow: 0 1px 1px rgba(0,0,0,0.04); background: #fff; } /* Press this styles */ .pressthis h4 { margin: 2em 0 1em; } .pressthis textarea { width: 100%; font-size: 1em; } #pressthis-code-wrap { overflow: auto; } .pressthis-bookmarklet-wrapper { margin: 20px 0 8px; vertical-align: top; position: relative; z-index: 1; } .pressthis-bookmarklet, .pressthis-bookmarklet:hover, .pressthis-bookmarklet:focus, .pressthis-bookmarklet:active { display: inline-block; position: relative; cursor: move; color: #32373c; background: #e5e5e5; -webkit-border-radius: 5px; border-radius: 5px; border: 1px solid #b4b9be; font-style: normal; line-height: 16px; font-size: 14px; text-decoration: none; } .pressthis-bookmarklet:active { outline: none; } .pressthis-bookmarklet:after { content: ""; width: 70%; height: 55%; z-index: -1; position: absolute; left: 10px; bottom: 9px; background: transparent; -webkit-transform: skew(-20deg) rotate(-6deg); -ms-transform: skew(-20deg) rotate(-6deg); transform: skew(-20deg) rotate(-6deg); -webkit-box-shadow: 0 10px 8px rgba(0, 0, 0, 0.6); box-shadow: 0 10px 8px rgba(0, 0, 0, 0.6); } .pressthis-bookmarklet:hover:after { -webkit-transform: skew(-20deg) rotate(-9deg); -ms-transform: skew(-20deg) rotate(-9deg); transform: skew(-20deg) rotate(-9deg); -webkit-box-shadow: 0 10px 8px rgba(0, 0, 0, 0.7); box-shadow: 0 10px 8px rgba(0, 0, 0, 0.7); } .pressthis-bookmarklet span { display: inline-block; margin: 0px 0 0; padding: 0px 9px 8px 12px; } .pressthis-bookmarklet span:before { color: #72777c; font: normal 20px/1 dashicons; content: "\f157"; position: relative; display: inline-block; top: 4px; margin-left: 4px; } .pressthis-js-toggle { margin-right: 10px; padding: 0; height: auto; vertical-align: top; } /* to override the button class being applied */ .pressthis-js-toggle.button.button { margin-right: 10px; padding: 0; height: auto; vertical-align: top; } .pressthis-js-toggle .dashicons { margin: 5px 7px 6px 8px; color: #555d66; } /*------------------------------------------------------------------------------ 20.0 - Settings ------------------------------------------------------------------------------*/ .timezone-info code { white-space: nowrap; } .defaultavatarpicker .avatar { margin: 2px 0; vertical-align: middle; } .options-general-php .date-time-text { display: inline-block; min-width: 10em; } .options-general-php input.small-text { width: 56px; } .options-general-php .spinner { float: none; margin: 0 3px; } .settings-php .language-install-spinner, .options-general-php .language-install-spinner { display: inline-block; float: none; margin: -3px 5px 0; vertical-align: middle; } /*------------------------------------------------------------------------------ 21.0 - Network Admin ------------------------------------------------------------------------------*/ .setup-php textarea { max-width: 100%; } .form-field #site-address { max-width: 25em; } .form-field #domain { max-width: 22em; } .form-field #site-title, .form-field #admin-email, .form-field #path, .form-field #blog_registered, .form-field #blog_last_updated { max-width: 25em; } .form-field #path { margin-bottom: 5px; } #search-users, #search-sites { max-width: 100%; } /*------------------------------------------------------------------------------ Credentials check dialog for Install and Updates ------------------------------------------------------------------------------*/ .request-filesystem-credentials-dialog { display: none; } .request-filesystem-credentials-dialog .notification-dialog { top: 10%; max-height: 85%; } .request-filesystem-credentials-dialog-content { margin: 25px; } #request-filesystem-credentials-title { font-size: 1.3em; margin: 1em 0; } .request-filesystem-credentials-form legend { font-size: 1em; padding: 1.33em 0; font-weight: 600; } .request-filesystem-credentials-form input[type="text"], .request-filesystem-credentials-form input[type="password"] { display: block; } .request-filesystem-credentials-dialog input[type="text"], .request-filesystem-credentials-dialog input[type="password"] { width: 100%; } .request-filesystem-credentials-form .field-title { font-weight: 600; } .request-filesystem-credentials-dialog label[for="hostname"], .request-filesystem-credentials-dialog label[for="public_key"], .request-filesystem-credentials-dialog label[for="private_key"] { display: block; margin-bottom: 1em; } .request-filesystem-credentials-dialog .ftp-username, .request-filesystem-credentials-dialog .ftp-password { float: right; width: 48%; } .request-filesystem-credentials-dialog .ftp-password { margin-right: 4%; } .request-filesystem-credentials-dialog .request-filesystem-credentials-action-buttons { text-align: left; } .request-filesystem-credentials-dialog label[for="ftp"] { margin-left: 10px; } .request-filesystem-credentials-dialog #auth-keys-desc { margin-bottom: 0; } #request-filesystem-credentials-dialog .button:not(:last-child) { margin-left: 10px; } #request-filesystem-credentials-form .cancel-button { display: none; } #request-filesystem-credentials-dialog .cancel-button { display: inline; } .request-filesystem-credentials-dialog .ftp-username, .request-filesystem-credentials-dialog .ftp-password { float: none; width: auto; } .request-filesystem-credentials-dialog .ftp-username { margin-bottom: 1em; } .request-filesystem-credentials-dialog .ftp-password { margin: 0; } .request-filesystem-credentials-dialog .ftp-password em { color: #888; } .request-filesystem-credentials-dialog label { display: block; line-height: 1.5; margin-bottom: 1em; } .request-filesystem-credentials-form legend { padding-bottom: 0; } .request-filesystem-credentials-form #ssh-keys legend { font-size: 1.3em; } .request-filesystem-credentials-form .notice { margin: 0 0 20px 0; clear: both; } /* =Media Queries -------------------------------------------------------------- */ @media screen and ( max-width: 782px ) { /* Input Elements */ textarea { -webkit-appearance: none; } input[type="text"], input[type="email"], input[type="search"], input[type="password"], input[type="number"] { -webkit-appearance: none; padding: 6px 10px; } input[type="number"] { height: 40px; } input.code { padding-bottom: 5px; padding-top: 10px; } input[type="checkbox"], .widefat th input[type="checkbox"], .widefat thead td input[type="checkbox"], .widefat tfoot td input[type="checkbox"] { -webkit-appearance: none; padding: 10px; } .widefat th input[type="checkbox"], .widefat thead td input[type="checkbox"], .widefat tfoot td input[type="checkbox"] { margin-bottom: 8px; } input[type="checkbox"]:checked:before, .widefat th input[type="checkbox"]:before, .widefat thead td input[type="checkbox"]:before, .widefat tfoot td input[type="checkbox"]:before { font: normal 30px/1 dashicons; margin: -3px -5px; } input[type="radio"], input[type="checkbox"] { height: 25px; width: 25px; } .wp-admin p input[type="checkbox"], .wp-admin p input[type="radio"] { margin-top: -3px; } input[type="radio"]:checked:before { vertical-align: middle; width: 9px; height: 9px; margin: 7px; line-height: 16px; } .wp-upload-form input[type="submit"] { margin-top: 10px; } #wpbody select { height: 36px; font-size: 16px; } .wp-admin .button-cancel { padding: 0; font-size: 14px; } #adduser .form-field input, #createuser .form-field input { width: 100%; } .form-table { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .form-table th, .form-table td, .label-responsive { display: block; width: auto; vertical-align: middle; } .label-responsive { margin: 0.5em 0; } .export-filters li { margin-bottom: 0; } .form-table .color-palette td { display: table-cell; width: 15px; } .form-table table.color-palette { margin-left: 10px; } textarea, input { font-size: 16px; } .form-table td input[type="text"], .form-table td input[type="email"], .form-table td input[type="password"], .form-table td select, .form-table td textarea, .form-table span.description, #profile-page .form-table textarea { width: 100%; font-size: 16px; line-height: 1.5; padding: 7px 10px; display: block; max-width: none; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .form-table .form-required.form-invalid td:after { float: left; margin: -30px 0 0 3px; } #wpbody .form-table td select { height: 40px; } input[type="text"].small-text, input[type="search"].small-text, input[type="password"].small-text, input[type="number"].small-text, input[type="number"].small-text, .form-table input[type="text"].small-text { width: auto; max-width: 55px; display: inline; padding: 3px 6px; margin: 0 3px; } #pass-strength-result { width: 100%; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; padding: 8px; } p.search-box { float: none; position: absolute; bottom: 0; width: 98%; height: 90px; margin-bottom: 20px; } p.search-box input[name="s"] { height: auto; float: none; width: 100%; margin-bottom: 10px; vertical-align: middle; -webkit-appearance: none; } p.search-box input[type="submit"] { margin-bottom: 10px; } .form-table span.description { display: inline; padding: 4px 0 0; line-height: 1.4em; font-size: 14px; } .form-table th { padding-top: 10px; padding-bottom: 0; border-bottom: 0; } .form-table td { margin-bottom: 0; padding-bottom: 6px; padding-top: 4px; padding-right: 0; } .form-table.permalink-structure td code { margin-right: 32px; } .form-table.permalink-structure td input[type="text"] { margin-right: 32px; margin-top: 4px; width: 96%; } .form-table input.regular-text { width: 100%; } .form-table label { font-size: 14px; } .form-table fieldset label { display: block; } #utc-time, #local-time { display: block; float: none; margin-top: 0.5em; } .form-field #domain { max-width: none; } /* New Password */ .wp-pwd { position: relative; } .wp-pwd [type="text"], .wp-pwd [type="password"] { padding-left: 40px; } .wp-pwd button.button { background: transparent; border: none; -webkit-box-shadow: none; box-shadow: none; line-height: 2; margin: 0; padding: 5px 10px; position: absolute; left: 0; top: 0; } .wp-pwd button.button:hover, .wp-pwd button.button:focus, .wp-pwd button.button:active { background: transparent; } .wp-pwd .button .text { display: none; } .options-general-php input[type="text"].small-text { max-width: 60px; margin: 0; } } @media only screen and (max-width: 768px) { .form-field input[type="text"], .form-field input[type="email"], .form-field input[type="password"], .form-field select, .form-field textarea { width: 99%; } .form-wrap .form-field { padding:0; } /* users */ #profile-page .form-table textarea { max-width: 400px; width: auto; } } @media only screen and (max-height: 480px) { /* Request Credentials */ .request-filesystem-credentials-dialog .notification-dialog{ width: 100%; height: 100%; max-height: 100%; position: fixed; top: 0; margin: 0; right: 0; } } /* Smartphone */ @media screen and (max-width: 600px) { /* Color Picker Options */ .color-option { width: 49%; } } @media only screen and (max-width: 320px) { .options-general-php .date-time-text.date-time-custom-text { min-width: 0; margin-left: 0.5em; } }
class ProjectsController < ApplicationController prepend_before_filter :render_go_import, only: [:show] skip_before_action :authenticate_user!, only: [:show] before_action :project, except: [:new, :create] before_action :repository, except: [:new, :create] # Authorize before_action :authorize_admin_project!, only: [:edit, :update, :destroy, :transfer, :archive, :unarchive] before_action :event_filter, only: [:show, :activity] layout :determine_layout def new @project = Project.new end def edit render 'edit' end def create @project = ::Projects::CreateService.new(current_user, project_params).execute if @project.saved? redirect_to( project_path(@project), notice: 'Project was successfully created.' ) else render 'new' end end def update status = ::Projects::UpdateService.new(@project, current_user, project_params).execute respond_to do |format| if status flash[:notice] = 'Project was successfully updated.' format.html do redirect_to( edit_project_path(@project), notice: 'Project was successfully updated.' ) end format.js else format.html { render 'edit' } format.js end end end def transfer namespace = Namespace.find_by(id: params[:new_namespace_id]) ::Projects::TransferService.new(project, current_user).execute(namespace) if @project.errors[:new_namespace].present? flash[:alert] = @project.errors[:new_namespace].first end end def activity respond_to do |format| format.html format.json do load_events pager_json('events/_events', @events.count) end end end def show if @project.import_in_progress? redirect_to namespace_project_import_path(@project.namespace, @project) return end respond_to do |format| format.html do if @project.repository_exists? if @project.empty_repo? render 'projects/empty' else render :show end else render 'projects/no_repo' end end format.atom do load_events render layout: false end end end def destroy return access_denied! unless can?(current_user, :remove_project, @project) ::Projects::DestroyService.new(@project, current_user, {}).execute flash[:alert] = 'Project deleted.' if request.referer.include?('/admin') redirect_to admin_namespaces_projects_path else redirect_to dashboard_path end rescue Projects::DestroyService::DestroyError => ex redirect_to edit_project_path(@project), alert: ex.message end def autocomplete_sources note_type = params['type'] note_id = params['type_id'] autocomplete = ::Projects::AutocompleteService.new(@project) participants = ::Projects::ParticipantsService.new(@project, current_user).execute(note_type, note_id) @suggestions = { emojis: autocomplete_emojis, issues: autocomplete.issues, mergerequests: autocomplete.merge_requests, members: participants } respond_to do |format| format.json { render json: @suggestions } end end def archive return access_denied! unless can?(current_user, :archive_project, @project) @project.archive! respond_to do |format| format.html { redirect_to project_path(@project) } end end def unarchive return access_denied! unless can?(current_user, :archive_project, @project) @project.unarchive! respond_to do |format| format.html { redirect_to project_path(@project) } end end def toggle_star current_user.toggle_star(@project) @project.reload render json: { html: view_to_html_string("projects/buttons/_star") } end def markdown_preview text = params[:text] ext = Gitlab::ReferenceExtractor.new(@project, current_user) ext.analyze(text) render json: { body: view_context.markdown(text), references: { users: ext.users.map(&:username) } } end private def determine_layout if [:new, :create].include?(action_name.to_sym) 'application' elsif [:edit, :update].include?(action_name.to_sym) 'project_settings' else 'project' end end def load_events @events = @project.events.recent @events = event_filter.apply_filter(@events).with_associations limit = (params[:limit] || 20).to_i @events = @events.limit(limit).offset(params[:offset] || 0) end def project_params params.require(:project).permit( :name, :path, :description, :issues_tracker, :tag_list, :issues_enabled, :merge_requests_enabled, :snippets_enabled, :issues_tracker_id, :default_branch, :wiki_enabled, :visibility_level, :import_url, :last_activity_at, :namespace_id, :avatar ) end def autocomplete_emojis Rails.cache.fetch("autocomplete-emoji-#{Gemojione::VERSION}") do Emoji.emojis.map do |name, emoji| { name: name, path: view_context.image_url("emoji/#{emoji["unicode"]}.png") } end end end def render_go_import return unless params["go-get"] == "1" @namespace = params[:namespace_id] @id = params[:project_id] || params[:id] @id = @id.gsub(/\.git\Z/, "") render "go_import", layout: false end end
module Azure::Network::Mgmt::V2016_12_01 module Models # # Parameters that define the VM to check security groups for. # class SecurityGroupViewParameters include MsRestAzure # @return [String] ID of the target VM. attr_accessor :target_resource_id # # Mapper for SecurityGroupViewParameters class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'SecurityGroupViewParameters', type: { name: 'Composite', class_name: 'SecurityGroupViewParameters', model_properties: { target_resource_id: { client_side_validation: true, required: true, serialized_name: 'targetResourceId', type: { name: 'String' } } } } } end end end end
<?php namespace Steppie\Bundle\AppBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class SteppieAppBundle extends Bundle { }
var createWrapper = require('../internals/createWrapper'), slice = require('../internals/slice'); /** * Creates a function that, when called, invokes `func` with any additional * `partial` arguments prepended to those provided to the new function. This * method is similar to `_.bind` except it does **not** alter the `this` binding. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to partially apply arguments to. * @param {...*} [arg] Arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * var greet = function(greeting, name) { return greeting + ' ' + name; }; * var hi = _.partial(greet, 'hi'); * hi('fred'); * // => 'hi fred' */ function partial(func) { return createWrapper(func, 16, slice(arguments, 1)); } module.exports = partial;
// Conformance for emitting ES6 // @target: es6 // A parameter declaration may specify either an identifier or a binding pattern. // The identifiers specified in parameter declarations and binding patterns // in a parameter list must be unique within that parameter list. // If the declaration includes a type annotation, the parameter is of that type function a1([a, b, [[c]]]: [number, number, string[][]]) { } function a2(o: { x: number, a: number }) { } function a3({j, k, l: {m, n}, q: [a, b, c]}: { j: number, k: string, l: { m: boolean, n: number }, q: (number|string)[] }) { }; function a4({x, a}: { x: number, a: number }) { } a1([1, 2, [["world"]]]); a1([1, 2, [["world"]], 3]); // If the declaration includes an initializer expression (which is permitted only // when the parameter list occurs in conjunction with a function body), // the parameter type is the widened form (section 3.11) of the type of the initializer expression. function b1(z = [undefined, null]) { }; function b2(z = null, o = { x: 0, y: undefined }) { } function b3({z: {x, y: {j}}} = { z: { x: "hi", y: { j: 1 } } }) { } interface F1 { b5(z, y, [, a, b], {p, m: { q, r}}); } function b6([a, z, y] = [undefined, null, undefined]) { } function b7([[a], b, [[c, d]]] = [[undefined], undefined, [[undefined, undefined]]]) { } b1([1, 2, 3]); // z is widen to the type any[] b2("string", { x: 200, y: "string" }); b2("string", { x: 200, y: true }); // If the declaration specifies a binding pattern, the parameter type is the implied type of that binding pattern (section 5.1.3) enum Foo { a } function c0({z: {x, y: {j}}}) { } function c1({z} = { z: 10 }) { } function c2({z = 10}) { } function c3({b}: { b: number|string} = { b: "hello" }) { } function c5([a, b, [[c]]]) { } function c6([a, b, [[c=1]]]) { } c0({z : { x: 1, y: { j: "world" } }}); // Implied type is { z: {x: any, y: {j: any}} } c0({z : { x: "string", y: { j: true } }}); // Implied type is { z: {x: any, y: {j: any}} } c1(); // Implied type is {z:number}? c1({ z: 1 }) // Implied type is {z:number}? c2({}); // Implied type is {z?: number} c2({z:1}); // Implied type is {z?: number} c3({ b: 1 }); // Implied type is { b: number|string }. c5([1, 2, [["string"]]]); // Implied type is is [any, any, [[any]]] c5([1, 2, [["string"]], false, true]); // Implied type is is [any, any, [[any]]] // A parameter can be marked optional by following its name or binding pattern with a question mark (?) // or by including an initializer. interface F2 { d3([a, b, c]?); d4({x, y, z}?); e0([a, b, c]); } class C2 implements F2 { constructor() { } d3() { } d4() { } e0([a, b, c]) { } } class C3 implements F2 { d3([a, b, c]) { } d4({x, y, z}) { } e0([a, b, c]) { } } function d5({x, y} = { x: 1, y: 2 }) { } d5(); // Parameter is optional as its declaration included an initializer // Destructuring parameter declarations do not permit type annotations on the individual binding patterns, // as such annotations would conflict with the already established meaning of colons in object literals. // Type annotations must instead be written on the top- level parameter declaration function e1({x: number}) { } // x has type any NOT number function e2({x}: { x: number }) { } // x is type number function e3({x}: { x?: number }) { } // x is an optional with type number function e4({x: [number,string,any] }) { } // x has type [any, any, any] function e5({x: [a, b, c]}: { x: [number, number, number] }) { } // x has type [any, any, any] function e6({x: [number, number, number]}) { } // error, duplicate identifier;
module RuboCop module Cop module Style # This cop checks for the presence of `method_missing` without also # defining `respond_to_missing?` and falling back on `super`. # # @example # #bad # def method_missing(...) # ... # end # # #good # def respond_to_missing?(...) # ... # end # # def method_missing(...) # ... # super # end class MethodMissing < Cop include OnMethodDef MSG = 'When using `method_missing`, %s.'.freeze def on_method_def(node, method_name, _args, _body) return unless method_name == :method_missing check(node) end private def check(node) return if calls_super?(node) && implements_respond_to_missing?(node) add_offense(node, :expression) end def message(node) instructions = [] unless implements_respond_to_missing?(node) instructions << 'define `respond_to_missing?`'.freeze end unless calls_super?(node) instructions << 'fall back on `super`'.freeze end format(MSG, instructions.join(' and ')) end def calls_super?(node) node.descendants.any?(&:zsuper_type?) end def implements_respond_to_missing?(node) node.parent.each_child_node(node.type).any? do |sibling| if node.def_type? respond_to_missing_def?(sibling) elsif node.defs_type? respond_to_missing_defs?(sibling) end end end def_node_matcher :respond_to_missing_def?, <<-PATTERN (def :respond_to_missing? (...) ...) PATTERN def_node_matcher :respond_to_missing_defs?, <<-PATTERN (defs (self) :respond_to_missing? (...) ...) PATTERN end end end end
var jsdoc = require('../../jsdoc'); module.exports = validateTypesInTags; module.exports.scopes = ['file']; module.exports.options = { checkTypes: {allowedValues: [true, 'strictNativeCase', 'capitalizedNativeCase']} }; var allowedTags = { // common typedef: true, type: true, param: true, 'return': true, returns: true, 'enum': true, // jsdoc 'var': true, prop: true, property: true, arg: true, argument: true, // jsduck cfg: true, // closure lends: true, extends: true, implements: true, define: true }; var strictNatives = { // lowercased boolean: 'boolean', number: 'number', string: 'string', // titlecased array: 'Array', object: 'Object', regexp: 'RegExp', date: 'Date', 'function': 'Function' }; /** * Validator for types in tags * * @param {JSCS.JSFile} file * @param {JSCS.Errors} errors */ function validateTypesInTags(file, errors) { var strictNativeCase = this._options.checkTypes === 'strictNativeCase'; var capitalizedNativeCase = this._options.checkTypes === 'capitalizedNativeCase'; var comments = file.getComments(); comments.forEach(function(commentNode) { if (commentNode.type !== 'CommentBlock' || commentNode.value[0] !== '*') { return; } // trying to create DocComment object var node = jsdoc.createDocCommentByCommentNode(commentNode); if (!node.valid) { return; } node.iterateByType(Object.keys(allowedTags), /** * @param {DocType} tag */ function(tag) { if (!tag.type) { // skip untyped params return; } if (!tag.type.valid) { // throw an error if not valid errors.add('Expects valid type instead of ' + tag.type.value, commentNode, tag.type.loc.offset); } if (strictNativeCase || capitalizedNativeCase) { tag.type.iterate(function(node) { // it shouldn't be! if (!node.typeName) { // skip untyped unknown things return; } // is native? var type = node.typeName; var lowerType = type.toLowerCase(); if (!strictNatives.hasOwnProperty(lowerType)) { return; } var normType = strictNatives[lowerType]; if (strictNativeCase && type !== normType || capitalizedNativeCase && type !== (normType[0].toUpperCase() + normType.substr(1))) { errors.add('Invalid case of type `' + type + '`', commentNode, tag.type.loc.offset); } }); } }); }); }
package alex.mojaki.boxes.test; import alex.mojaki.boxes.BoxFamily; import alex.mojaki.boxes.CommonBox; public class ExposedCommonBox<T> extends CommonBox<T> { public ExposedCommonBox(BoxFamily family) { super(family); } public ExposedCommonBox(Class<?> clazz, String name) { super(clazz, name); } @Override public void rawSet(T value) { super.rawSet(value); } @Override protected T rawGet() { return super.rawGet(); } }
#include <QMdiArea> #include <QScrollBar> #include <QLayout> #include <QPainter> #include <QGraphicsView> #include <QGraphicsScene> #include <QGraphicsRectItem> #include <QTime> #include <ossim/imaging/ossimScalarRemapper.h> #include <ossim/imaging/ossimCacheTileSource.h> #include <ossimGui/ImageWidget.h> #include <ossimGui/Image.h> #include <ossimGui/DisplayTimerJobQueue.h> #include <ossimGui/GatherImageViewProjTransVisitor.h> #include <ossimGui/RegistrationOverlay.h> ossimGui::ImageWidgetJob::ImageWidgetJob() { m_maxProcessingTime = 20; } void ossimGui::ImageWidgetJob::run() { if(m_inputSource.valid()) { std::lock_guard<std::mutex> lock(m_imageWidgetJobMutex); QTime start = QTime::currentTime(); ossimDrect cacheRect(m_tileCache->getRect()); // ossimDpt ulCachePt = cacheRect.ul(); ossimIrect rect; ossimDpt ul; // Because the cache rect is a sub rect of the scroll we need the upper left which starts at offset 0,0 in scroll space m_cacheToView.map(0.0, 0.0, &ul.x, &ul.y); while(m_tileCache->nextInvalidTile(rect) && (!isCanceled())) { // shift to zero based rectangle and then set back for opying purposes. ossimRefPtr<ossimImageData> data =m_inputSource->getTile(rect+ul); data->setImageRectangle(rect); ossimGui::Image img(data.get()); if(data.valid()) { m_tileCache->addTile(ossimGui::Image(data.get(), true)); } else { img = QImage(rect.width(), rect.height(), QImage::Format_RGB32); img.fill(0); img.setOffset(QPoint(rect.ul().x, rect.ul().y)); m_tileCache->addTile(img); } QTime end = QTime::currentTime(); if(start.msecsTo(end) >= m_maxProcessingTime) { break; } } } } ossimGui::ImageScrollWidget::ImageScrollWidget(QWidget* parent) :QScrollArea(parent), m_listener(new ConnectionListener(this)), m_jobQueue(std::make_shared<DisplayTimerJobQueue>()) { m_trackPoint.makeNan(); m_oldTrackPoint.makeNan(); m_trackingFlag = true; m_mouseInsideFlag = false; m_layers = new Layers(); //m_connector->addListener(m_listener); m_widget = new ImageWidget(this, viewport()); //m_widget->setAttribute(Qt::WA_StaticContents); m_widget->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); // setWidget(m_widget); setWidgetResizable(false); m_widget->show(); m_trackingFlag = true; m_scrollOrigin = ossimDpt(0.0,0.0); m_tileSize = ossimIpt(64,64); //m_widget->setTileCache(new StaticTileImageCache(m_tileSize)); m_timerId = -1; viewport()->setCursor(Qt::CrossCursor); m_imageWidgetJob = std::make_shared<ImageWidgetJob>();//this); m_imageWidgetJob->setCallback(std::make_shared<Callback>(this)); // m_multiLayerAlgorithm = HORIZONTAL_SWIPE_ALGORITHM; // m_multiLayerAlgorithm = VERTICAL_SWIPE_ALGORITHM; // m_multiLayerAlgorithm = BOX_SWIPE_ALGORITHM; m_multiLayerAlgorithm = CIRCLE_SWIPE_ALGORITHM; // Initialize drawing control m_drawPts = false; // m_regOverlay = new RegistrationOverlay(); ///???????????? // m_scene = new QGraphicsScene(0,0,500,400,this); // m_view = new QGraphicsView(this); // m_view->setScene(m_scene); // m_view->setStyleSheet("background: transparent"); // QGraphicsRectItem* rect = m_scene->addRect(50,40,100,200); // rect->setFlags(QGraphicsItem::ItemIsMovable); // rect->setBrush(QBrush(Qt::blue)); // rect->setOpacity(0.3); // QGraphicsItem* item = m_scene->addText("QGraphicsTextItem"); // item->setFlags(QGraphicsItem::ItemIsMovable); // m_view->show(); } ossimGui::ImageScrollWidget::~ImageScrollWidget() { m_imageWidgetJob->cancel(); if(m_connectableObject.get()&&m_listener) { if(m_listener) { m_connectableObject->removeListener(m_listener); } m_connectableObject->disconnect(); } if(m_listener) { delete m_listener; m_listener = 0; } m_connectableObject = 0; m_layers = 0; } ossimGui::ConnectableImageObject* ossimGui::ImageScrollWidget::connectableObject() { return m_connectableObject.get(); } void ossimGui::ImageScrollWidget::setConnectableObject(ConnectableImageObject* c) { if(m_connectableObject.valid()) { m_connectableObject->removeListener(m_listener); } m_connectableObject = c; if(m_connectableObject.valid()) { m_connectableObject->addListener(m_listener); } if(m_connectableObject.valid()) inputConnected(); } void ossimGui::ImageScrollWidget::inputConnected(ossim_int32 /* idx */) { m_layers->adjustLayers(m_connectableObject.get()); // m_scalarRemapperChain->connectMyInputTo(0, m_connectableObject->getInput()); m_inputBounds = m_connectableObject->getBounds(); // setCacheRect(); if(!m_inputBounds.hasNans()) { updateScrollBars(); } updateTransforms(); setCacheRect(); // QPoint localPt(50,50); // QPoint viewPoint = m_localToView.map(localPt); if(m_jobQueue) { if(!m_imageWidgetJob->isRunning()) m_imageWidgetJob->ready(); m_jobQueue->add(m_imageWidgetJob); } } void ossimGui::ImageScrollWidget::inputDisconnected(ossim_int32 /* idx */) { m_layers->adjustLayers(m_connectableObject.get()); m_inputBounds = m_connectableObject->getBounds(); // setCacheRect(); if(!m_inputBounds.hasNans()) { updateScrollBars(); } updateTransforms(); setCacheRect(); if(m_jobQueue) { if(!m_imageWidgetJob->isRunning()) m_imageWidgetJob->ready(); m_jobQueue->add(m_imageWidgetJob); } } ossimDrect ossimGui::ImageScrollWidget::viewportBoundsInViewSpace()const { QSize size = viewport()->size(); QRectF out = m_localToView.mapRect(QRectF(0,0,size.width(), size.height())); return ossimDrect(out.x(), out.y(),out.x()+(out.width()-1), out.y() + (out.height()-1)); } void ossimGui::ImageScrollWidget::setJobQueue(std::shared_ptr<ossimJobQueue> jobQueue) { m_jobQueue = jobQueue; } void ossimGui::ImageScrollWidget::refreshDisplay() { m_layers->flushDisplayCaches(); m_inputBounds = m_connectableObject->getBounds(); // setCacheRect(); if(!m_inputBounds.hasNans()) { updateScrollBars(); } updateTransforms(); setCacheRect(); if(m_jobQueue) { if(!m_imageWidgetJob->isRunning()) m_imageWidgetJob->ready(); m_jobQueue->add(m_imageWidgetJob); } } void ossimGui::ImageScrollWidget::updateTransforms() { if(!m_inputBounds.hasNans()) { m_viewToScroll = QTransform(1.0, 0.0, 0.0, 1.0, -m_inputBounds.ul().x, -m_inputBounds.ul().y); m_scrollToView = m_viewToScroll.inverted(); m_scrollToLocal = QTransform(1.0,0.0,0.0,1.0, - m_scrollOrigin.x, -m_scrollOrigin.y); m_localToScroll = m_scrollToLocal.inverted(); m_viewToLocal = m_scrollToLocal*m_viewToScroll; m_localToView = m_viewToLocal.inverted(); } else { m_viewToScroll = m_scrollToView = m_scrollToLocal = m_localToScroll = m_viewToLocal = m_localToView =QTransform(); } //m_imageWidgetJob->setCacheToViewTransform(scrollToView()); //m_imageWidgetJob->setViewToCacheTransform(viewToScroll()); } void ossimGui::ImageScrollWidget::resizeEvent(QResizeEvent* event) { QAbstractScrollArea::resizeEvent(event); m_widget->resize(size()); updateScrollBars(); m_scrollOrigin.x = horizontalScrollBar()->value(); m_scrollOrigin.y = verticalScrollBar()->value(); updateTransforms(); setCacheRect(); if(m_layers->findFirstDirtyLayer()) { if(m_jobQueue) { if(!m_imageWidgetJob->isRunning()) m_imageWidgetJob->ready(); m_jobQueue->add(m_imageWidgetJob); } } // This would be useful only for HUD?? //m_regOverlay->resize(event->size()); // event->accept(); //??? } void ossimGui::ImageScrollWidget::scrollContentsBy( int dx, int dy ) { QScrollArea::scrollContentsBy( dx,dy ); m_scrollOrigin.x = horizontalScrollBar()->value(); m_scrollOrigin.y = verticalScrollBar()->value(); updateTransforms(); setCacheRect(); m_widget->update(); if(m_layers->findFirstDirtyLayer()) { if(m_jobQueue) { if(!m_imageWidgetJob->isRunning()) m_imageWidgetJob->ready(); m_jobQueue->add(m_imageWidgetJob); } } } void ossimGui::ImageScrollWidget::setCacheRect() { /* ossimIpt ul(m_scrollOrigin); ossimIpt lr(m_scrollOrigin.x + size().width()-1, m_scrollOrigin.y + size().height()-1); ossimIrect rect(ul.x, ul.y, lr.x, lr.y); m_layers->setCacheRect(rect); */ QRectF rect = m_localToScroll.mapRect(QRectF(0,0,size().width(), size().height())); m_layers->setCacheRect(ossimDrect(rect.x(), rect.y(), rect.x() + rect.width()-1, rect.y() + rect.height()-1)); } void ossimGui::ImageScrollWidget::updateScrollBars() { if(!m_inputBounds.hasNans()) { if(m_inputBounds.width() > viewport()->size().width()) { horizontalScrollBar()->setRange(0,m_inputBounds.width()-viewport()->size().width()); horizontalScrollBar()->show(); } else { horizontalScrollBar()->setRange(0,0);//,viewport()->size().width()); horizontalScrollBar()->setVisible(false); horizontalScrollBar()->setValue(0); } if(m_inputBounds.height() > viewport()->size().height()) { verticalScrollBar()->setRange(0,m_inputBounds.height()-viewport()->size().height()); verticalScrollBar()->show(); } else { verticalScrollBar()->setRange(0,0);//viewport()->size().height()); verticalScrollBar()->setVisible(false); verticalScrollBar()->setValue(0); } m_scrollOrigin = ossimIpt(horizontalScrollBar()->value(), verticalScrollBar()->value()); } } void ossimGui::ImageScrollWidget::setPositionGivenView(const ossimDpt& position) { QSize size = viewport()->size(); ossimDpt adjusted = (position - m_inputBounds.ul()) - ossimDpt(size.width()*.5, size.height()*.5); setPositionGivenLocal(adjusted); } void ossimGui::ImageScrollWidget::setPositionGivenLocal(const ossimDpt& position) { QSize size = viewport()->size(); ossimIpt scrollPosition(position); if(scrollPosition.x < 0) scrollPosition.x = 0; if(scrollPosition.y < 0) scrollPosition.y = 0; if(size.width() > m_inputBounds.width()) scrollPosition.x = 0; if(size.height() > m_inputBounds.height()) scrollPosition.y = 0; if(scrollPosition.x > m_inputBounds.width()) scrollPosition.x = m_inputBounds.width()-1; if(scrollPosition.y > m_inputBounds.height()) scrollPosition.y = m_inputBounds.height()-1; if(horizontalScrollBar()->value() != scrollPosition.x) { horizontalScrollBar()->setValue(scrollPosition.x); } if(verticalScrollBar()->value() != scrollPosition.y) { verticalScrollBar()->setValue(scrollPosition.y); } } void ossimGui::ImageScrollWidget::mouseDoubleClickEvent ( QMouseEvent * e ) { QScrollArea::mouseDoubleClickEvent(e); if(!m_inputBounds.hasNans()) { ossimIpt origin = m_inputBounds.ul(); ossimIpt localPoint(m_scrollOrigin.x +e->x(), m_scrollOrigin.y+e->y()); ossimIpt viewPoint(localPoint.x+origin.x, localPoint.y+origin.y); ossimDrect rect = viewportBoundsInViewSpace(); emit mouseDoubleClick(e, rect, viewPoint);//viewportPoint, localPoint, viewPoint); } } void ossimGui::ImageScrollWidget::mouseMoveEvent ( QMouseEvent * e ) { QScrollArea::mouseMoveEvent(e); if(e->buttons() & Qt::LeftButton) { m_activePointEnd = e->pos(); if(m_layers->numberOfLayers() > 1) { m_widget->update(); } } if(!m_inputBounds.hasNans()) { ossimIpt origin = m_inputBounds.ul(); ossimIpt localPoint(m_scrollOrigin.x +e->x(), m_scrollOrigin.y+e->y()); ossimIpt viewPoint(localPoint.x+origin.x, localPoint.y+origin.y); ossimDrect rect = viewportBoundsInViewSpace(); emit mouseMove(e, rect, viewPoint);//viewportPoint, localPoint, viewPoint); } } void ossimGui::ImageScrollWidget::mousePressEvent ( QMouseEvent * e ) { QScrollArea::mousePressEvent(e); m_activePointStart = e->pos(); m_activePointEnd = e->pos(); if(!m_inputBounds.hasNans()) { ossimIpt origin = m_inputBounds.ul(); ossimIpt localPoint(m_scrollOrigin.x +e->x(), m_scrollOrigin.y+e->y()); ossimIpt viewPoint(localPoint.x+origin.x, localPoint.y+origin.y); ossimDrect rect = viewportBoundsInViewSpace(); // Save the measured point position // (viewPoint = view<-scroll<-local) ossim_uint32 idxLayer = 0; ossimImageSource* src = m_layers->layer(idxLayer)->chain(); ossimGui::GatherImageViewProjTransVisitor visitor; src->accept(visitor); if (visitor.getTransformList().size() == 1) { // Transform to true image coordinates and save ossimRefPtr<IvtGeomTransform> ivtg = visitor.getTransformList()[0].get(); if (ivtg.valid()) { ivtg->viewToImage(viewPoint, m_measImgPoint); } } m_measPoint = viewPoint; m_drawPts = true; update(); // m_regOverlay->setMeasPoint(m_measPoint); // cout << "\n ImageScrollWidget::mousePressEvent (" // << viewPoint.x << ", "<< viewPoint.y << ") (" // << m_measImgPoint.x << ", "<< m_measImgPoint.y << ")" // << endl; emit mousePress(e, rect, viewPoint);//viewportPoint, localPoint, viewPoint); } } void ossimGui::ImageScrollWidget::mouseReleaseEvent ( QMouseEvent * e ) { QScrollArea::mouseReleaseEvent(e); m_activePointEnd = e->pos(); if(!m_inputBounds.hasNans()) { ossimIpt origin = m_inputBounds.ul(); ossimIpt localPoint(m_scrollOrigin.x +e->x(), m_scrollOrigin.y+e->y()); ossimIpt viewPoint(localPoint.x+origin.x, localPoint.y+origin.y); ossimDrect rect = viewportBoundsInViewSpace(); emit mouseRelease(e, rect, viewPoint);//viewportPoint, localPoint, viewPoint); } } void ossimGui::ImageScrollWidget::wheelEvent ( QWheelEvent * e ) { //QScrollArea::wheelEvent(e); if(!m_inputBounds.hasNans()) { ossimIpt origin = m_inputBounds.ul(); ossimIpt localPoint(m_scrollOrigin.x +e->x(), m_scrollOrigin.y+e->y()); ossimIpt viewPoint(localPoint.x+origin.x, localPoint.y+origin.y); ossimDrect rect = viewportBoundsInViewSpace(); emit wheel(e, rect, viewPoint);//viewportPoint, localPoint, viewPoint); } } void ossimGui::ImageScrollWidget::enterEvent ( QEvent * ) { m_mouseInsideFlag = true; m_widget->update(); } void ossimGui::ImageScrollWidget::leaveEvent ( QEvent * ) { m_mouseInsideFlag = false; m_widget->update(); } ossimImageGeometry* ossimGui::ImageScrollWidget::getGeometry() { ossimImageSource* is = dynamic_cast<ossimImageSource*>(m_connectableObject->getInput()); if(is) { return is->getImageGeometry().get(); } return 0; } void ossimGui::ImageScrollWidget::setTrackPoint(const ossimDpt& position) { if(position.hasNans()) { m_trackPoint.makeNan(); } else { ossimDpt pt; m_viewToScroll.map(position.x, position.y, &pt.x, &pt.y); m_scrollToLocal.map(pt.x, pt.y, &m_trackPoint.x, &m_trackPoint.y); m_widget->update(); } } ossimGui::ImageScrollWidget::Layer::Layer(ossimConnectableObject* obj) { m_inputObject = obj; m_tileCache = new StaticTileImageCache(); m_scalarRemapperChain = new ossimImageChain(); m_scalarRemapperChain->addFirst(new ossimScalarRemapper()); m_scalarRemapperChain->addFirst(new ossimCacheTileSource()); if(obj) m_scalarRemapperChain->connectMyInputTo(0, obj); } ossimGui::ImageScrollWidget::Layer::~Layer() { clear(); } ossimGui::ImageScrollWidget::Layers::Layers() { } ossimGui::ImageScrollWidget::Layers::~Layers() { ossim_uint32 idx = 0; for(idx = 0; idx < m_layers.size(); ++idx) { m_layers[idx]->clear(); m_layers[idx] = 0; } m_layers.clear(); } ossimGui::ImageScrollWidget::Layer* ossimGui::ImageScrollWidget::Layers::layer(ossim_uint32 idx) { std::lock_guard<std::mutex> lock(m_mutex); return layerNoMutex(idx); } ossimGui::ImageScrollWidget::Layer* ossimGui::ImageScrollWidget::Layers::layer(ossimConnectableObject* input) { std::lock_guard<std::mutex> lock(m_mutex); return layerNoMutex(input); } void ossimGui::ImageScrollWidget::Layers::setCacheRect(const ossimDrect& rect) { std::lock_guard<std::mutex> lock(m_mutex); ossim_uint32 idx = 0; for(idx = 0; idx < m_layers.size(); ++idx) { m_layers[idx]->tileCache()->setRect(rect); } } ossimGui::ImageScrollWidget::Layer* ossimGui::ImageScrollWidget::Layers::layerNoMutex(ossim_uint32 idx) { Layer* result = 0; if(idx < m_layers.size()) { return m_layers[idx].get(); } return result; } ossimGui::ImageScrollWidget::Layer* ossimGui::ImageScrollWidget::Layers::layerNoMutex(ossimConnectableObject* input) { Layer* result = 0; LayerListType::iterator iter = std::find_if(m_layers.begin(), m_layers.end(), FindConnectable(input)); if(iter != m_layers.end()) { result = (*iter).get(); } return result; } ossimGui::ImageScrollWidget::Layer* ossimGui::ImageScrollWidget::Layers::findFirstDirtyLayer() { std::lock_guard<std::mutex> lock(m_mutex); ossim_uint32 idx = 0; for(idx = 0; idx < m_layers.size();++idx) { if(m_layers[idx]->tileCache()->hasInvalidTiles()) { return m_layers[idx].get(); } } return 0; } bool ossimGui::ImageScrollWidget::Layers::isEmpty()const { std::lock_guard<std::mutex> lock(m_mutex); return m_layers.empty(); } void ossimGui::ImageScrollWidget::Layers::adjustLayers(ossimConnectableObject* connectable) { { std::lock_guard<std::mutex> lock(m_mutex); LayerListType layers; ossim_uint32 nInputs = connectable->getNumberOfInputs(); for(ossim_uint32 inputIdx = 0; inputIdx<nInputs;++inputIdx) { ossimRefPtr<ossimConnectableObject> inputObj = connectable->getInput(inputIdx); ossimRefPtr<Layer> tempLayer = layerNoMutex(inputObj.get()); if(tempLayer.valid()) { layers.push_back(tempLayer.get()); } else // allocate a new display layer { tempLayer = new Layer(inputObj.get()); layers.push_back(tempLayer.get()); } } // Now any old layers that were removed lets fully remove // LayerListType::iterator iter = m_layers.begin(); while(iter!=m_layers.end()) { if(std::find(layers.begin(), layers.end(), (*iter).get())==layers.end()) { (*iter)->clear(); } ++iter; } m_layers = layers; // ossim_uint32 idx = 0; } } void ossimGui::ImageScrollWidget::Layers::flushDisplayCaches() { std::lock_guard<std::mutex> lock(m_mutex); ossim_uint32 idx = 0; for(idx = 0; idx < m_layers.size(); ++idx) { if(m_layers[idx]->tileCache()) m_layers[idx]->tileCache()->flush(); } } void ossimGui::ImageScrollWidget::paintWidget(QPainter& painter) { if((m_layers->numberOfLayers() > 1)&&(m_multiLayerAlgorithm!=NO_ALGORITHM)) { paintMultiLayer(painter); } else { ossimRefPtr<Layer> topLayer = m_layers->layer((ossim_uint32)0); if(topLayer.valid()) { ossimRefPtr<StaticTileImageCache> topTileCache = topLayer->tileCache(); if(topTileCache.valid()) { ossimIrect rect = topTileCache->getRect(); QRectF rectF = m_scrollToLocal.mapRect(QRectF(rect.ul().x, rect.ul().y, rect.width(), rect.height())); ossimIpt topOriginOffset = ossimDpt(rectF.x(), rectF.y()); painter.drawImage(topOriginOffset.x, topOriginOffset.y, topTileCache->getCache()); } } } if(!m_trackPoint.hasNans()&&m_trackingFlag&&!m_mouseInsideFlag) { drawCursor(painter); } // Temporary marker control // if (m_drawPts == true) // { // m_regOverlay->drawMeas(painter, m_viewToLocal); // } // m_regOverlay->drawProj(painter, m_viewToLocal); } void ossimGui::ImageScrollWidget::paintMultiLayer(QPainter& painter) { if(m_multiLayerAlgorithm != ANIMATION_ALGORITHM) { ossimRefPtr<Layer> topLayer = m_layers->layer((ossim_uint32)0); ossimRefPtr<Layer> bottomLayer = m_layers->layer((ossim_uint32)1); if(topLayer.valid()&&bottomLayer.valid()) { ossimRefPtr<StaticTileImageCache> topTileCache = topLayer->tileCache(); ossimRefPtr<StaticTileImageCache> bottomTileCache = bottomLayer->tileCache(); if(topTileCache.valid()&&bottomTileCache.valid()) { ossimIrect rect = topTileCache->getRect(); QRectF rectF = m_scrollToLocal.mapRect(QRectF(rect.ul().x, rect.ul().y, rect.width(), rect.height())); ossimIpt topOriginOffset = ossimDpt(rectF.x(), rectF.y()); // for scrolling we need to offset from the tile location to the actual rect indicated by the viewport. // ossim_uint32 w = rect.width(); ossim_uint32 h = rect.height(); switch(m_multiLayerAlgorithm) { case HORIZONTAL_SWIPE_ALGORITHM: { ossim_int64 topLayerx = topOriginOffset.x; ossim_int64 bottomLayerx = m_activePointEnd.x(); ossim_int64 topLayerWidth = bottomLayerx - topLayerx; painter.drawImage(topLayerx, topOriginOffset.y, topTileCache->getCache(), 0,0,topLayerWidth,h); painter.drawImage(topLayerx+topLayerWidth, topOriginOffset.y, bottomTileCache->getCache(), topLayerWidth, 0); break; } case VERTICAL_SWIPE_ALGORITHM: { ossim_int64 topLayery = topOriginOffset.y; ossim_int64 bottomLayery = m_activePointEnd.y(); ossim_int64 topLayerHeight = bottomLayery - topLayery; painter.drawImage(topOriginOffset.x, topLayery, topTileCache->getCache(), 0, 0, w, topLayerHeight); painter.drawImage(topOriginOffset.x, topLayery+topLayerHeight, bottomTileCache->getCache(), 0, topLayerHeight); break; } case BOX_SWIPE_ALGORITHM: { painter.drawImage(topOriginOffset.x, topOriginOffset.y, topTileCache->getCache()); ossim_int64 minx = ossim::min(m_activePointStart.x(), m_activePointEnd.x()); ossim_int64 maxx = ossim::max(m_activePointStart.x(), m_activePointEnd.x()); ossim_int64 miny = ossim::min(m_activePointStart.y(), m_activePointEnd.y()); ossim_int64 maxy = ossim::max(m_activePointStart.y(), m_activePointEnd.y()); ossim_int64 w = maxx-minx; ossim_int64 h = maxy-miny; ossim_int64 x = minx; ossim_int64 y = miny; QPointF scrollPoint = m_localToScroll.map(QPointF(x,y)); ossimDrect cacheRect = bottomTileCache->getRect(); ossimDpt delta = ossimDpt(scrollPoint.x(), scrollPoint.y()) - cacheRect.ul(); painter.drawImage(x, y, bottomTileCache->getCache(), delta.x, delta.y, w, h); break; } case CIRCLE_SWIPE_ALGORITHM: { // QImage& cahceImage = topTileCache->getCache(); // draw top and then overlay the bottom ossim_int64 minx = ossim::min(m_activePointStart.x(), m_activePointEnd.x()); ossim_int64 maxx = ossim::max(m_activePointStart.x(), m_activePointEnd.x()); ossim_int64 miny = ossim::min(m_activePointStart.y(), m_activePointEnd.y()); ossim_int64 maxy = ossim::max(m_activePointStart.y(), m_activePointEnd.y()); ossim_int64 w = maxx-minx; ossim_int64 h = maxy-miny; ossim_int64 x = minx; ossim_int64 y = miny; // QPointF scrollPoint = m_localToScroll.map(QPointF(x,y)); // ossimDpt cachePt = ossimDpt(scrollPoint.x(), scrollPoint.y()) - topTileCache->getRect().ul(); painter.save(); painter.drawImage(topOriginOffset.x, topOriginOffset.y, topTileCache->getCache()); painter.setBrush(QBrush(bottomTileCache->getCache())); painter.setPen(Qt::NoPen); // this part is a little tricky but for the texturing to be placed in the ellipse properly // I had to add a translation for the painter because the cache might extend past the current scroll region because it // is on tile boundaries // // Because we shift for texturing with the QBrush we must undo the shift when drawing the ellipse so it lines up with // the mouse draws. The topOriginOffset holds the shift. // painter.translate(topOriginOffset.x, topOriginOffset.y); painter.drawEllipse(x-topOriginOffset.x,y-topOriginOffset.y,w,h); painter.restore(); break; } default: { break; } } } } } else { } } void ossimGui::ImageScrollWidget::drawCursor(QPainter& painter) { if(!m_trackPoint.hasNans()) { ossimIpt roundedPoint(m_trackPoint); bool hasClipping = painter.hasClipping(); painter.setClipping(false); painter.setPen(QColor(255, 255, 255)); ossimIrect rect(0,0,size().width()-1, size().height()-1); // ossimIpt ul = rect.ul(); // ossimIpt lr = rect.lr(); int left = rect.ul().x; int right = rect.lr().x; int top = rect.ul().y; int bottom = rect.lr().y; if(rect.pointWithin(roundedPoint)) { // draw horizontal // int x1 = left; int x2 = right; int y1 = roundedPoint.y; int y2 = y1; painter.drawLine(x1, y1, x2, y2); // draw vertical x1 = roundedPoint.x; x2 = x1; y1 = top; y2 = bottom; painter.drawLine(x1, y1, x2, y2); } painter.setClipping(hasClipping); } m_oldTrackPoint = m_trackPoint; } void ossimGui::ImageScrollWidget::updateAnnotation() { ossim_uint32 idxLayer = 0; ossimImageSource* src = m_layers->layer(idxLayer)->chain(); ossimGui::GatherImageViewProjTransVisitor visitor; src->accept(visitor); if (visitor.getTransformList().size() == 1) { ossimRefPtr<IvtGeomTransform> ivtg = visitor.getTransformList()[0].get(); if (ivtg.valid()) { ivtg->imageToView(m_measImgPoint, m_measPoint); ivtg->imageToView(m_markImgPoint, m_markPoint); // m_regOverlay->setMeasPoint(m_measPoint); // m_regOverlay->setProjPoint(m_markPoint); } } update(); } void ossimGui::ImageScrollWidget::setMarkPointPosition(const ossimDpt& setViewPoint, const ossimDpt& setImagePoint) { m_markPoint = setViewPoint; m_markImgPoint = setImagePoint; // m_regOverlay->setProjPoint(m_markPoint); } void ossimGui::ImageScrollWidget::storeCurrentPosition(const ossimString& /* id */) { // m_regOverlay->addPoint(id, m_measImgPoint); } bool ossimGui::ImageScrollWidget::getPoint(const ossimString& /* id */, ossimDpt& imgPt) { // bool foundPt = m_regOverlay->getPoint(id, imgPt); // return foundPt; return true; } ossimGui::ImageScrollWidget::ImageWidget::ImageWidget(ImageScrollWidget* scrollWidget, QWidget* parent) :QFrame(parent), m_scrollWidget(scrollWidget) { // m_scene = new QGraphicsScene(0,0,500,400,this); // m_view = new QGraphicsView(this); // m_view->setScene(m_scene); // m_view->setStyleSheet("background: transparent"); // QGraphicsRectItem* rect = m_scene->addRect(50,40,100,200); // rect->setFlags(QGraphicsItem::ItemIsMovable); // rect->setBrush(QBrush(Qt::blue)); // rect->setOpacity(0.3); // QGraphicsItem* item = m_scene->addText("QGraphicsTextItem"); // item->setFlags(QGraphicsItem::ItemIsMovable); // m_view->show(); } void ossimGui::ImageScrollWidget::ImageWidget::paintEvent(QPaintEvent* /* event */ ) { QPainter painter(this); m_scrollWidget->paintWidget(painter); #if 0 // for scrolling we need to offset from the tile location to the actual rect indicated by the viewport. // ossimIpt originOffset = m_tileCache->getRect().ul() - m_tileCache->getActualRect().ul(); painter.drawImage(originOffset.x, originOffset.y, m_tileCache->getCache()); //eraseCursor(painter); if(!m_trackPoint.hasNans()&&m_trackingFlag&&!m_mouseInsideFlag) { drawCursor(painter); } #endif } #if 0 void ossimGui::ImageWidget::eraseCursor(QPainter& painter) { if(!m_oldTrackPoint.hasNans()) { ossimIpt originOffset = m_tileCache->getActualRect().ul(); ossimIpt roundedPoint(m_oldTrackPoint); QImage& cacheImage = m_tileCache->getCache(); ossimIrect rect(0,0,size().width()-1, size().height()-1); if(rect.pointWithin(roundedPoint)) { // erase horizontal line painter.drawImage(0, roundedPoint.y, cacheImage, originOffset.x+rect.ul().x, originOffset.y+roundedPoint.y, (int)rect.width(), (int)1); // erase vertical line painter.drawImage(roundedPoint.x, 0, cacheImage, originOffset.x + roundedPoint.x, originOffset.y + rect.ul().y , (int)1, (int)rect.height()); } m_oldTrackPoint.makeNan(); } } void ossimGui::ImageWidget::setTrackPoint(const ossimDpt& position) { m_trackPoint = position; } //void ossimGui::ImageWidget::setTrackingFlag(bool flag) //{ // m_trackingFlag = flag; //} void ossimGui::ImageWidget::setMouseInsideFlag(bool flag) { m_mouseInsideFlag = flag; } #endif
package demo.org.powermock.examples.tutorial.hellopower; import org.junit.Test; /** * The purpose of this test is to get 100% coverage of the {@link HelloWorld} * class without any code changes to that class. To achieve this you need learn * how to mock static methods. * <p> * While doing this tutorial please refer to the documentation on how to mock * static methods at the PowerMock web site. */ // TODO Specify the PowerMock runner // TODO Specify which classes that must be prepared for test public class HelloWorldTest_Tutorial { @Test public void testGreeting() { // TODO: mock the static methods of SimpleConfig // TODO: Replay the behavior // TODO: Perform the test of the greet method and assert that it returns the expected behavior // TODO: Verify the behavior } }
<?xml version="1.0"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <artifactId>message</artifactId> <groupId>org.sakaiproject.message</groupId> <version>11-SNAPSHOT</version> <relativePath>../../pom.xml</relativePath> </parent> <name>sakai-message-api</name> <groupId>org.sakaiproject.message</groupId> <artifactId>sakai-message-api</artifactId> <organization> <name>The Sakai Foundation</name> <url>http://sakaiproject.org/</url> </organization> <inceptionYear>2003</inceptionYear> <packaging>jar</packaging> <properties> <deploy.target>shared</deploy.target> </properties> <dependencies> <dependency> <groupId>org.sakaiproject.kernel</groupId> <artifactId>sakai-kernel-api</artifactId> </dependency> <dependency> <groupId>org.sakaiproject.kernel</groupId> <artifactId>sakai-component-manager</artifactId> </dependency> </dependencies> </project>
<?php $html = ' <h1>mPDF</h1> <h2>Justification</h2> <h4>Tables</h4> <p>Text can be justified in table cells using in-line or stylesheet CSS. (Note that &lt;p&gt; tags are removed within cells along with any style definition or attributes.)</p> <table class="bpmTopnTailC"><thead> <tr class="headerrow"><th>Col/Row Header</th> <td> <p>Second column header p</p> </td> <td>Third column header</td> </tr> </thead><tbody> <tr class="oddrow"><th>Row header 1</th> <td>This is data</td> <td>This is data</td> </tr> <tr class="evenrow"><th>Row header 2</th> <td> <p>This is data p</p> </td> <td> <p>This is data</p> </td> </tr> <tr class="oddrow"><th> <p>Row header 3</p> </th> <td> <p>This is long data</p> </td> <td>This is data</td> </tr> <tr class="evenrow"><th> <p>Row header 4</p> <p>&lt;th&gt; cell acting as header</p> </th> <td style="text-align:justify;"><p>Proin aliquet lorem id felis. Curabitur vel libero at mauris nonummy tincidunt. Donec imperdiet. Vestibulum sem sem, lacinia vel, molestie et, laoreet eget, urna. Curabitur viverra faucibus pede. Morbi lobortis. Donec dapibus. Donec tempus. Ut arcu enim, rhoncus ac, venenatis eu, porttitor mollis, dui. Sed vitae risus. In elementum sem placerat dui. Nam tristique eros in nisl. Nulla cursus sapien non quam porta porttitor. Quisque dictum ipsum ornare tortor. Fusce ornare tempus enim. </p></td> <td> <p>This is data</p> </td> </tr> <tr class="oddrow"><th>Row header 5</th> <td>Also data</td> <td>Also data</td> </tr> <tr class="evenrow"><th>Row header 6</th> <td>Also data</td> <td>Also data</td> </tr> <tr class="oddrow"><th>Row header 7</th> <td>Also data</td> <td>Also data</td> </tr> <tr class="evenrow"><th>Row header 8</th> <td>Also data</td> <td>Also data</td> </tr> </tbody></table> <p>&nbsp;</p> <h4>Testing Justification with Long Words</h4> <p><a href="http://www-950.ibm.com/software/globalization/icu/demo/converters?s=ALL&amp;snd=4356&amp;dnd=4356">http://www-950.ibm.com/software/globalization/icu/demo/converters?s=ALL&amp;snd=4356&amp;dnd=4356</a></p> <h5>Should not split</h5> <p>Maecenas feugiat pede vel risus. Nulla et lectus eleifend <i>verylongwordthatwontsplit</i> neque sit amet erat</p> <p>Maecenas feugiat pede vel risus. Nulla et lectus eleifend et <i>verylongwordthatwontsplit</i> neque sit amet erat</p> <h5>Non-breaking Space &amp;nbsp;</h5><p>The next example has a non-breaking space between <i>eleifend</i> and the very long word.</p><p>Maecenas feugiat pede vel risus. Nulla et lectus eleifend&nbsp;verylongwordthatwontsplitanywhere neque sit amet erat</p><p>Nbsp will only work in fonts that have a glyph to represent the character i.e. not in the CJK languages nor some Unicode fonts.</p> <h4>Testing Justification with mixed Styles</h4> <p>This is <s>strikethrough</s> in <b><s>block</s></b> and <small>small <s>strikethrough</s> in <i>small span</i></small> and <big>big <s>strikethrough</s> in big span</big> and then <u>underline</u> but out of span again but <font color="#000088">blue</font> font and <acronym>ACRONYM</acronym> text</p> <p>This is a <font color="#008800">green reference<sup>32-47</sup></font> and <u>underlined reference<sup>32-47</sup></u> then reference<sub>32-47</sub> and <u>underlined reference<sub>32-47</sub></u> then <s>Strikethrough reference<sup>32-47</sup></s> and <s>strikethrough reference<sub>32-47</sub></s> and then more text. </p> <p><big>Repeated in <u>BIG</u>: This is reference<sup>32-47</sup> and <u>underlined reference<sup>32-47</sup></u> then reference<sub>32-47</sub> and <u>underlined reference<sub>32-47</sub></u> but out of span again but <font color="#000088">blue</font> font and <acronym>ACRONYM</acronym> text</big> </p> <p><small>Repeated in small: This is reference<sup>32-47</sup> and <u>underlined reference<sup>32-47</sup></u> then reference<sub>32-47</sub> and <u>underlined reference<sub>32-47</sub></u> but out of span again but <font color="#000088">blue</font> font and <acronym>ACRONYM</acronym> text</small> </p> <p style="font-size:7pt;">This is <s>strikethrough</s> in block and <big>big <s>strikethrough</s> in big span</big> and then <u>underline</u> but out of span again but <font color="#000088">blue</font> font and <acronym>ACRONYM</acronym> text</p> <p style="font-size:7pt;">This is reference<sup>32-47</sup> and <u>underlined reference<sup>32-47</sup></u> then reference<sub>32-47</sub> and <u>underlined reference<sub>32-47</sub></u> then <s>Strikethrough reference<sup>32-47</sup></s> and <s>strikethrough reference<sub>32-47</sub></s> then more text. </p> <p></p> <p style="font-size:7pt;"> <big>Repeated in BIG: This is reference<sup>32-47</sup> and <u>underlined reference<sup>32-47</sup></u> then reference<sub>32-47</sub> and <u>underlined reference<sub>32-47</sub></u> but out of span again but <font color="#000088">blue</font> font and <acronym>ACRONYM</acronym> text</big> </p> '; //============================================================== //============================================================== //============================================================== include("../mpdf.php"); $mpdf=new mPDF('c','A4','','',32,25,27,25,16,13); $mpdf->SetDisplayMode('fullpage'); // LOAD a stylesheet $stylesheet = file_get_contents('mpdfstyletables.css'); $mpdf->WriteHTML($stylesheet,1); // The parameter 1 tells that this is css/style only and no body/html/text $mpdf->WriteHTML($html); // SPACING $mpdf->WriteHTML("<h4>Spacing</h4><p>mPDF uses both letter- and word-spacing for text justification. The default is a mixture of both, set by the configurable values jSWord and jSmaxChar. (Only word spacing is used when cursive languages such as Arabic or Indic are detected.) </p>"); $mpdf->jSWord = 0; // Proportion (/1) of space (when justifying margins) to allocate to Word vs. Character $mpdf->jSmaxChar = 0; // Maximum spacing to allocate to character spacing. (0 = no maximum) $mpdf->WriteHTML("<h5>Character spacing</h5><p>Maecenas feugiat pede vel risus. Nulla et lectus eleifend <i>verylongwordthatwontsplitanywhere</i> neque sit amet erat</p>"); // Back to default settings $mpdf->jSWord = 0.4; $mpdf->jSmaxChar = 2; $mpdf->WriteHTML("<h5>Word spacing</h5><p style=\"letter-spacing:0\">Maecenas feugiat pede vel risus. Nulla et lectus eleifend <i>verylongwordthatwontsplitanywhere</i> neque sit amet erat</p>"); $mpdf->WriteHTML("<h5>Mixed Character and Word spacing</h5><p>Maecenas feugiat pede vel risus. Nulla et lectus eleifend <i>verylongwordthatwontsplitanywhere</i> neque sit amet erat</p>"); $mpdf->Output(); exit; ?>
using System; using System.Configuration; using System.Dynamic; using System.Linq; using System.Threading; using System.Threading.Tasks; using NUnit.Framework; using Salesforce.Common; using Salesforce.Common.Models; using Salesforce.Force.FunctionalTests.Models; using WadeWegner.Salesforce.SOAPHelpers; namespace Salesforce.Force.FunctionalTests { [TestFixture] public class ForceClientTests { private static readonly string SecurityToken = ConfigurationManager.AppSettings["SecurityToken"]; private static readonly string ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"]; private static readonly string ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"]; private static readonly string Username = ConfigurationManager.AppSettings["Username"]; private static readonly string Password = ConfigurationManager.AppSettings["Password"] + SecurityToken; private static readonly string OrganizationId = ConfigurationManager.AppSettings["OrganizationId"]; private AuthenticationClient _auth; private ForceClient _client; [TestFixtureSetUp] public void Init() { _auth = new AuthenticationClient(); _auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password).Wait(); _client = new ForceClient(_auth.InstanceUrl, _auth.AccessToken, _auth.ApiVersion); } [Test] public async void AsyncTaskCompletion_ExpandoObject() { dynamic account = new ExpandoObject(); account.Name = "ExpandoName" + DateTime.Now.Ticks; account.Description = "ExpandoDescription" + DateTime.Now.Ticks; var result = await _client.CreateAsync("Account", account); Assert.IsNotNull(result); } [Test] public async void UserInfo_IsNotNull() { var userInfo = await _client.UserInfo<UserInfo>(_auth.Id); Assert.IsNotNull(userInfo); } [Test] public async void Query_Accounts_Continuation() { var accounts = await _client.QueryAsync<Account>("SELECT count() FROM Account"); if (accounts.totalSize < 1000) { await CreateLotsOfAccounts(_client); } var contacts = await _client.QueryAsync<dynamic>("SELECT Id, Name, Description FROM Account"); var nextRecordsUrl = contacts.nextRecordsUrl; var nextContacts = await _client.QueryContinuationAsync<dynamic>(nextRecordsUrl); Assert.IsNotNull(nextContacts); Assert.AreNotEqual(contacts, nextContacts); } public async Task CreateLotsOfAccounts(ForceClient forceClient) { var account = new Account { Name = "Test Account", Description = "New Account Description" }; for (var i = 0; i < 1000; i++) { account.Name = "Test Account (" + i + ")"; await forceClient.CreateAsync("Account", account); } } [Test] public async void Query_Count() { var accounts = await _client.QueryAsync<Account>("SELECT count() FROM Account"); Assert.IsNotNull(accounts); } [Test] public async void Query_Accounts_IsNotEmpty() { var accounts = await _client.QueryAsync<Account>("SELECT id, name, description FROM Account"); Assert.IsNotNull(accounts); } [Test] public async void Query_Accounts_BadObject() { try { await _client.QueryAsync<Account>("SELECT id, name, description FROM BadObject"); } catch (ForceException ex) { Assert.IsNotNull(ex); Assert.IsNotNull(ex.Message); Assert.IsNotNull(ex.Error); } } [Test] public async void Create_Account_Typed() { var account = new Account { Name = "New Account", Description = "New Account Description" }; var id = await _client.CreateAsync("Account", account); Assert.IsNotNullOrEmpty(id); } [Test] public async void QueryAll_Accounts_IsNotEmpty() { var accounts = await _client.QueryAllAsync<Account>("SELECT id, name, description FROM Account"); Assert.IsNotNull(accounts); } [Test] public async void QueryAll_Accounts_Continuation() { var accounts = await _client.QueryAllAsync<Account>("SELECT count() FROM Account"); if (accounts.totalSize < 1000) { await CreateLotsOfAccounts(_client); } var contacts = await _client.QueryAllAsync<dynamic>("SELECT Id, Name, Description FROM Account"); var nextRecordsUrl = contacts.nextRecordsUrl; var nextContacts = await _client.QueryContinuationAsync<dynamic>(nextRecordsUrl); Assert.IsNotNull(nextContacts); Assert.AreNotEqual(contacts, nextContacts); } [Test] public async void Create_Contact_Typed_Annotations() { var contact = new Contact { Id = "Id", IsDeleted = false, AccountId = "AccountId", Name = "Name", FirstName = "FirstName", LastName = "LastName", Description = "Description" }; var id = await _client.CreateAsync("Contact", contact); Assert.IsNotNullOrEmpty(id); } [Test] public async void Create_Account_Untyped() { var account = new { Name = "New Account", Description = "New Account Description" }; var id = await _client.CreateAsync("Account", account); Assert.IsNotNullOrEmpty(id); } [Test] public async void Create_Account_Untyped_BadObject() { try { var account = new { Name = "New Account", Description = "New Account Description" }; await _client.CreateAsync("BadAccount", account); } catch (ForceException ex) { Assert.IsNotNull(ex); Assert.IsNotNull(ex.Message); Assert.IsNotNull(ex.Error); } } [Test] public async void Create_Account_Untyped_BadFields() { try { var account = new { BadName = "New Account", BadDescription = "New Account Description" }; await _client.CreateAsync("Account", account); } catch (ForceException ex) { Assert.IsNotNull(ex); Assert.IsNotNull(ex.Message); Assert.IsNotNull(ex.Error); } } [Test] public async void Update_Account_IsSuccess() { const string originalName = "New Account"; const string newName = "New Account 2"; var account = new Account { Name = originalName, Description = "New Account Description" }; var id = await _client.CreateAsync("Account", account); account.Name = newName; var success = await _client.UpdateAsync("Account", id, account); Assert.IsNotNull(success); } [Test] public async void Update_Account_BadObject() { try { const string originalName = "New Account"; const string newName = "New Account 2"; var account = new Account { Name = originalName, Description = "New Account Description" }; var id = await _client.CreateAsync("Account", account); account.Name = newName; await _client.UpdateAsync("BadAccount", id, account); } catch (ForceException ex) { Assert.IsNotNull(ex); Assert.IsNotNull(ex.Message); Assert.IsNotNull(ex.Error); } } [Test] public async void Update_Account_BadField() { try { const string originalName = "New Account"; const string newName = "New Account 2"; var account = new { Name = originalName, Description = "New Account Description" }; var id = await _client.CreateAsync("Account", account); var updatedAccount = new { BadName = newName, Description = "New Account Description" }; await _client.UpdateAsync("Account", id, updatedAccount); } catch (ForceException ex) { Assert.IsNotNull(ex); Assert.IsNotNull(ex.Message); Assert.IsNotNull(ex.Error); } } [Test] public async void Update_Account_NameChanged() { const string originalName = "New Account"; const string newName = "New Account 2"; var account = new Account { Name = originalName, Description = "New Account Description" }; var id = await _client.CreateAsync("Account", account); account.Name = newName; await _client.UpdateAsync("Account", id, account); var result = await _client.QueryByIdAsync<Account>("Account", id); Assert.True(result.Name == newName); } [Test] public async void Delete_Account_IsSuccess() { var account = new Account { Name = "New Account", Description = "New Account Description" }; var id = await _client.CreateAsync("Account", account); var success = await _client.DeleteAsync("Account", id); Assert.IsTrue(success); } [Test] public async void Delete_Account_ObjectDoesNotExist() { try { var account = new Account { Name = "New Account", Description = "New Account Description" }; var id = await _client.CreateAsync("Account", account); var success = await _client.DeleteAsync("BadAccount", id); Assert.IsTrue(success); } catch (ForceException ex) { Assert.IsNotNull(ex); Assert.IsNotNull(ex.Message); Assert.IsNotNull(ex.Error); } } [Test] public async void Delete_Account_IdDoesNotExist() { try { const string id = "asdfasdfasdf"; await _client.DeleteAsync("Account", id); } catch (ForceException ex) { Assert.IsNotNull(ex); Assert.IsNotNull(ex.Message); Assert.IsNotNull(ex.Error); } } [Test] public async void Delete_Account_ValidateIsGone() { var account = new Account { Name = "New Account", Description = "New Account Description" }; var id = await _client.CreateAsync("Account", account); await _client.DeleteAsync("Account", id); var result = await _client.QueryByIdAsync<Account>("Account", id); Assert.IsNull(result); } [Test] public async void Objects_GetAllObjects_IsNotNull() { var objects = await _client.GetObjectsAsync<object>(); Assert.IsNotNull(objects); } [Test] public async void Object_BasicInformation_IsNotNull() { var accounts = await _client.BasicInformationAsync<object>("Account"); Assert.IsNotNull(accounts); } [Test] public async void Object_Describe_IsNotNull() { var accounts = await _client.DescribeAsync<object>("Account"); Assert.IsNotNull(accounts); } [Test] public async void Object_GetDeleted_IsNotNull() { var account = new Account { Name = "New Account to Delete", Description = "New Account Description" }; var id = await _client.CreateAsync("Account", account); await _client.DeleteAsync("Account", id); var dateTime = DateTime.Now; await Task.Run(() => Thread.Sleep(5000)); var sdt = dateTime.Subtract(new TimeSpan(0, 0, 2, 0)); var edt = dateTime.Add(new TimeSpan(0, 0, 2, 0)); var deleted = await _client.GetDeleted<DeletedRecordRootObject>("Account", sdt, edt); Assert.IsNotNull(deleted); Assert.IsNotNull(deleted.deletedRecords); Assert.IsTrue(deleted.deletedRecords.Count > 0); } [Test] public async void Object_GetUpdated_IsNotNull() { const string originalName = "New Account"; const string newName = "New Account 2"; var account = new Account { Name = originalName, Description = "New Account Description" }; var id = await _client.CreateAsync("Account", account); account.Name = newName; var dateTime = DateTime.Now; await _client.UpdateAsync("Account", id, account); await Task.Run(() => Thread.Sleep(5000)); var sdt = dateTime.Subtract(new TimeSpan(0, 0, 2, 0)); var edt = dateTime.Add(new TimeSpan(0, 0, 2, 0)); var updated = await _client.GetUpdated<UpdatedRecordRootObject>("Account", sdt, edt); Assert.IsNotNull(updated); Assert.IsTrue(updated.ids.Count > 0); } [Test] public async void Object_DescribeLayout_IsNotNull() { var accountsLayout = await _client.DescribeLayoutAsync<dynamic>("Account"); Assert.IsNotNull(accountsLayout); string recordTypeId = accountsLayout.recordTypeMappings[0].recordTypeId; Assert.IsNotNull(recordTypeId); var accountsLayoutForRecordTypeId = await _client.DescribeLayoutAsync<dynamic>("Account", recordTypeId); Assert.IsNotNull(accountsLayoutForRecordTypeId); } [Test] public async void Recent_IsNotNull() { var recent = await _client.RecentAsync<object>(5); Assert.IsNotNull(recent); } [Test] public async void Upsert_Account_Update_IsSuccess() { const string objectName = "Account"; const string fieldName = "ExternalId__c"; await CreateExternalIdField(objectName, fieldName); var account = new Account { Name = "Upserted Account", Description = "Upserted Account Description" }; var success = await _client.UpsertExternalAsync(objectName, fieldName, "123", account); Assert.IsNotNull(success); Assert.IsEmpty(success.id); } [Test] public async void Upsert_Account_Insert_IsSuccess() { const string objectName = "Account"; const string fieldName = "ExternalId__c"; await CreateExternalIdField(objectName, fieldName); var account = new Account { Name = "Upserted Account" + DateTime.Now.Ticks, Description = "New Upserted Account Description" + DateTime.Now.Ticks }; var success = await _client.UpsertExternalAsync(objectName, fieldName, "123" + DateTime.Now.Ticks, account); Assert.IsNotNull(success); Assert.IsNotNull(success.id); Assert.IsNotNullOrEmpty(success.id); } [Test] public async void Upsert_Account_BadObject() { try { var account = new Account { Name = "New Account ExternalID", Description = "New Account Description" }; await _client.UpsertExternalAsync("BadAccount", "ExternalID__c", "2", account); } catch (ForceException ex) { Assert.IsNotNull(ex); Assert.IsNotNull(ex.Message); Assert.IsNotNull(ex.Error); } } [Test] public async void Upsert_Account_BadField() { try { var accountBadName = new { BadName = "New Account", Description = "New Account Description" }; await _client.UpsertExternalAsync("Account", "ExternalID__c", "3", accountBadName); } catch (ForceException ex) { Assert.IsNotNull(ex); Assert.IsNotNull(ex.Message); Assert.IsNotNull(ex.Error); } } [Test] public async void Upsert_Account_NameChanged() { const string fieldName = "ExternalId__c"; await CreateExternalIdField("Account", fieldName); const string originalName = "New Account External Upsert"; const string newName = "New Account External Upsert 2"; var account = new Account { Name = originalName, Description = "New Account Description" }; await _client.UpsertExternalAsync("Account", fieldName, "4", account); account.Name = newName; await _client.UpsertExternalAsync("Account", fieldName, "4", account); var accountResult = await _client.QueryAsync<Account>(string.Format("SELECT Name FROM Account WHERE {0} = '4'", fieldName)); var firstOrDefault = accountResult.records.FirstOrDefault(); Assert.True(firstOrDefault != null && firstOrDefault.Name == newName); } private static async Task CreateExternalIdField(string objectName, string fieldName) { var salesforceClient = new SalesforceClient(); var loginResult = await salesforceClient.Login(Username, Password, OrganizationId); await salesforceClient.CreateCustomField(objectName, fieldName, loginResult.SessionId, loginResult.MetadataServerUrl, true); } } }
package org.wso2.carbon.apimgt.impl.utils; import org.apache.axis2.clustering.ClusteringCommand; import org.apache.axis2.clustering.ClusteringFault; import org.apache.axis2.clustering.ClusteringMessage; import org.apache.axis2.context.ConfigurationContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.apimgt.impl.APIManagerAnalyticsConfiguration; /** * This class provides the definition of the cluster message which is initiated from the * web service call from publisher node */ public class StatUpdateClusterMessage extends ClusteringMessage { private static final Log log = LogFactory.getLog(StatUpdateClusterMessage.class); private Boolean statUpdateStatus; private String receiverUrl; private String user; private String password; public StatUpdateClusterMessage(Boolean statUpdateStatus, String receiverUrl, String user, String password) { this.statUpdateStatus = statUpdateStatus; this.receiverUrl = receiverUrl; this.user = user; this.password = password; } @Override public ClusteringCommand getResponse() { return null; } @Override public void execute(ConfigurationContext configurationContext) throws ClusteringFault { //update the service variable, a boolean variable representing the stat data publishing in the node APIManagerAnalyticsConfiguration instanceOfAPIAnalytics = APIManagerAnalyticsConfiguration.getInstance(); instanceOfAPIAnalytics.setAnalyticsEnabled(statUpdateStatus); // Only change Data publishing information only if they are set if (receiverUrl != null && !receiverUrl.isEmpty() && user != null && !user.isEmpty() && password != null && !password.isEmpty()) { instanceOfAPIAnalytics.setDasReceiverUrlGroups(receiverUrl); instanceOfAPIAnalytics.setDasReceiverServerUser(user); instanceOfAPIAnalytics.setDasReceiverServerPassword(password); } if (log.isDebugEnabled()) { log.debug("Updated Stat publishing status to : " + statUpdateStatus); } } }
FOUNDATION_EXPORT const NSString *kSBStagingResolverURL; @interface SBTestCase : XCTestCase @end
/** * helper function to output debugging data to the console * * @param {String} msg text to output */ function logit(msg) { if (typeof (console) !== 'undefined') { console.log((new Date()).getTime() + '-' + msg); } } /** * helper function to output test data to reporting window * * @param {String} msg text to output * @param {String} CSS div id of reporting window */ function showit(msg, divId, first) { var oDiv = document.getElementById(divId); if (first) { oDiv.innerHTML = msg; } else { oDiv.innerHTML = oDiv.innerHTML + '<br/><br/>' + msg; } } var ORMMAReadyStatus = { NOT_FOUND: -1, FOUND: 1 }; window.ormmaStatus = undefined; /** * called by open, calls the ormma.open method * * @see open * @requires ormma * @returns {Boolean} false - so click event can stop propogating */ function ormmaOpen(url) { if (!window.ormmaAvail) { return (true); } ormma.open(url); return (false); } /** * called by expand, calls the ormma.expand method * * @see expand * @requires ormma * @returns {Boolean} false - so click event can stop propogating */ function ormmaExpand() { if (!window.ormmaAvail) { return (false); } var props = {}, pos = ormma.getDefaultPosition(); document.getElementById('propName').disabled = 'disabled'; document.getElementById('propValue').disabled = 'disabled'; var propName = document.getElementById('propName').value; var propValue = document.getElementById('propValue').value; if (propName && propValue) { props[propName] = propValue; } /* if (!props['useBackground']) { props['useBackground'] = true; } if (!props['backgroundColor']) { props['backgroundColor'] = '#000000'; } if (!props['backgroundOpacity']) { props['backgroundOpacity'] = 1; } if (!props['lockOrientation']) { props['lockOrientation'] = true; } */ ormma.setExpandProperties(props); ormma.addEventListener('stateChange', function () { logit('ad is expanded'); ormma.removeEventListener('stateChange'); }); ormma.expand({'x' : pos.x, 'y' : pos.y, 'width' : 300, 'height' : 300}, null); return (false); } /** * called by collapse, calls the ormma.close method * * @see collapse * @requires ormma * @returns {Boolean} false - so click event can stop propogating */ function ormmaClose() { if (!window.ormmaAvail) { return false; } ormma.addEventListener('stateChange', function () { logit('ad is no longer expanded'); ormma.removeEventListener('stateChange'); }); document.getElementById('propName').disabled = ''; document.getElementById('propValue').disabled = ''; ormma.close(); return false; } /** * triggered by user interaction, expands banner ad to panel * attempts to call ormma.expand * * @returns {Boolean} false - so click event can stop propogating */ function expand() { var oEl = document.getElementById('panel'); oEl.style.display = 'block'; oEl = document.getElementById('close'); oEl.style.display = 'block'; oEl = document.getElementById('banner'); oEl.style.display = 'none'; return ormmaExpand(); } /** * triggered by user interaction to close panel ad back to banner * attempts to call ormma.close * * @returns {Boolean} false - so click event can stop propogating */ function collapse() { var oEl = document.getElementById('panel'); oEl.style.display = 'none'; oEl = document.getElementById('close'); oEl.style.display = 'none'; oEl = document.getElementById('banner'); oEl.style.display = 'block'; return ormmaClose(); } /** * ORMMAReady called by the SDK * Sets global 'ormmaAvail' to true * * @requires ormma * */ function ORMMAReady(evt) { var msg; window.ormmaAvail = window.ormmaAvail || ORMMAReadyStatus.FOUND; if (window.ormmaAvail !== ORMMAReadyStatus.NOT_FOUND) { //clear any timers that have been waiting for ORMMA window.clearTimeout(window.ormmaWaitId); logit('ORMMA found'); if (typeof ormma === 'undefined') { showit('ormma object not found - failed.', 'result', true); return; } //check that all expected Level1 methods are available var ormmaMethods = ['expand', 'close', 'getExpandProperties', 'setExpandProperties']; var hasOrmmaMethods; var hasError = false; for (var i = 0; i < ormmaMethods.length; i++) { ormmaMethod = ormmaMethods[i]; hasOrmmaMethods = (typeof(ormma[ormmaMethod]) === 'function'); if (!hasOrmmaMethods) { showit(ormmaMethod + ' method not found - failed.', 'result', true); logit ('method ' + ormmaMethod + ' not found'); } } document.getElementById('propName').onchange = function(evt) { document.getElementById('propValue').value = ''; }; if (!hasError) { var msg = ['expand/close methods found - passed.<br/>', 'Visual confirmation needed...<ul>', '<li>Panel expanded in-app?</li>', '<li>Panel close returned to banner?</li></ul>'].join(''); showit(msg, 'result', true) } } } /** * stub function to highlight when ORMMA is not found */ function ORMMANotFound() { window.ormmaAvail = window.ormmaAvail || ORMMAReadyStatus.NOT_FOUND; if (window.ormmaAvail !== ORMMAReadyStatus.FOUND) { window.ormmaAvail = false; logit('ORMMA not found'); } } window.ormmaWaitId = window.setTimeout(ORMMANotFound, 2000);
The actions folder contains action scripts and metadata files. See [Actions](http://docs.stackstorm.com/actions.html) and [Workflows](http://docs.stackstorm.com/workflows.html) for specifics on writing actions. Note that the lib sub-folder is always available for access for an action script.
import { ISpecification, IConcreteEntity } from "@poseidon/core-models"; export abstract class Specification<T extends IConcreteEntity = IConcreteEntity> implements ISpecification<T> { abstract async eval(fact: T): Promise<boolean>; constructor( public discriminator: string, public description: string) { } }
using Cake.Core; using Cake.Core.Diagnostics; using Cake.Core.Scripting; namespace Cake.Scripting { /// <summary> /// The script host used to execute Cake scripts. /// </summary> public sealed class BuildScriptHost : ScriptHost { private readonly ICakeReportPrinter _reportPrinter; private readonly ICakeLog _log; /// <summary> /// Initializes a new instance of the <see cref="BuildScriptHost"/> class. /// </summary> /// <param name="engine">The engine.</param> /// <param name="context">The context.</param> /// <param name="reportPrinter">The report printer.</param> /// <param name="log">The log.</param> public BuildScriptHost( ICakeEngine engine, ICakeContext context, ICakeReportPrinter reportPrinter, ICakeLog log) : base(engine, context) { _reportPrinter = reportPrinter; _log = log; } /// <summary> /// Runs the specified target. /// </summary> /// <param name="target">The target to run.</param> /// <returns>The resulting report.</returns> public override CakeReport RunTarget(string target) { var strategy = new DefaultExecutionStrategy(_log); var report = Engine.RunTarget(Context, strategy, target); if (report != null && !report.IsEmpty) { _reportPrinter.Write(report); } return report; } } }
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "transactiontablemodel.h" #include "guiutil.h" #include "transactionrecord.h" #include "guiconstants.h" #include "transactiondesc.h" #include "walletmodel.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include "bitcoinunits.h" #include "wallet.h" #include "ui_interface.h" #include <QList> #include <QColor> #include <QTimer> #include <QIcon> #include <QDateTime> // Amount column is right-aligned it contains numbers static int column_alignments[] = { Qt::AlignLeft|Qt::AlignVCenter, Qt::AlignLeft|Qt::AlignVCenter, Qt::AlignLeft|Qt::AlignVCenter, Qt::AlignLeft|Qt::AlignVCenter, Qt::AlignRight|Qt::AlignVCenter }; // Comparison operator for sort/binary search of model tx list struct TxLessThan { bool operator()(const TransactionRecord &a, const TransactionRecord &b) const { return a.hash < b.hash; } bool operator()(const TransactionRecord &a, const uint256 &b) const { return a.hash < b; } bool operator()(const uint256 &a, const TransactionRecord &b) const { return a < b.hash; } }; // Private implementation class TransactionTablePriv { public: TransactionTablePriv(CWallet *wallet, TransactionTableModel *parent): wallet(wallet), parent(parent) { } CWallet *wallet; TransactionTableModel *parent; /* Local cache of wallet. * As it is in the same order as the CWallet, by definition * this is sorted by sha256. */ QList<TransactionRecord> cachedWallet; /* Query entire wallet anew from core. */ void refreshWallet() { OutputDebugStringF("refreshWallet\n"); cachedWallet.clear(); { LOCK(wallet->cs_wallet); for(std::map<uint256, CWalletTx>::iterator it = wallet->mapWallet.begin(); it != wallet->mapWallet.end(); ++it) { if(TransactionRecord::showTransaction(it->second)) cachedWallet.append(TransactionRecord::decomposeTransaction(wallet, it->second)); } } } /* Update our model of the wallet incrementally, to synchronize our model of the wallet with that of the core. Call with transaction that was added, removed or changed. */ void updateWallet(const uint256 &hash, int status) { OutputDebugStringF("updateWallet %s %i\n", hash.ToString().c_str(), status); { LOCK(wallet->cs_wallet); // Find transaction in wallet std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash); bool inWallet = mi != wallet->mapWallet.end(); // Find bounds of this transaction in model QList<TransactionRecord>::iterator lower = qLowerBound( cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan()); QList<TransactionRecord>::iterator upper = qUpperBound( cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan()); int lowerIndex = (lower - cachedWallet.begin()); int upperIndex = (upper - cachedWallet.begin()); bool inModel = (lower != upper); // Determine whether to show transaction or not bool showTransaction = (inWallet && TransactionRecord::showTransaction(mi->second)); if(status == CT_UPDATED) { if(showTransaction && !inModel) status = CT_NEW; /* Not in model, but want to show, treat as new */ if(!showTransaction && inModel) status = CT_DELETED; /* In model, but want to hide, treat as deleted */ } OutputDebugStringF(" inWallet=%i inModel=%i Index=%i-%i showTransaction=%i derivedStatus=%i\n", inWallet, inModel, lowerIndex, upperIndex, showTransaction, status); switch(status) { case CT_NEW: if(inModel) { OutputDebugStringF("Warning: updateWallet: Got CT_NEW, but transaction is already in model\n"); break; } if(!inWallet) { OutputDebugStringF("Warning: updateWallet: Got CT_NEW, but transaction is not in wallet\n"); break; } if(showTransaction) { // Added -- insert at the right position QList<TransactionRecord> toInsert = TransactionRecord::decomposeTransaction(wallet, mi->second); if(!toInsert.isEmpty()) /* only if something to insert */ { parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex+toInsert.size()-1); int insert_idx = lowerIndex; foreach(const TransactionRecord &rec, toInsert) { cachedWallet.insert(insert_idx, rec); insert_idx += 1; } parent->endInsertRows(); } } break; case CT_DELETED: if(!inModel) { OutputDebugStringF("Warning: updateWallet: Got CT_DELETED, but transaction is not in model\n"); break; } // Removed -- remove entire transaction from table parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1); cachedWallet.erase(lower, upper); parent->endRemoveRows(); break; case CT_UPDATED: // Miscellaneous updates -- nothing to do, status update will take care of this, and is only computed for // visible transactions. break; } } } int size() { return cachedWallet.size(); } TransactionRecord *index(int idx) { if(idx >= 0 && idx < cachedWallet.size()) { TransactionRecord *rec = &cachedWallet[idx]; // If a status update is needed (blocks came in since last check), // update the status of this transaction from the wallet. Otherwise, // simply re-use the cached status. if(rec->statusUpdateNeeded()) { { LOCK(wallet->cs_wallet); std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash); if(mi != wallet->mapWallet.end()) { rec->updateStatus(mi->second); } } } return rec; } else { return 0; } } QString describe(TransactionRecord *rec) { { LOCK(wallet->cs_wallet); std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash); if(mi != wallet->mapWallet.end()) { return TransactionDesc::toHTML(wallet, mi->second); } } return QString(""); } }; TransactionTableModel::TransactionTableModel(CWallet* wallet, WalletModel *parent): QAbstractTableModel(parent), wallet(wallet), walletModel(parent), priv(new TransactionTablePriv(wallet, this)), cachedNumBlocks(0) { columns << QString() << tr("Date") << tr("Type") << tr("Address") << tr("Amount"); priv->refreshWallet(); QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(updateConfirmations())); timer->start(MODEL_UPDATE_DELAY); connect(walletModel->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); } TransactionTableModel::~TransactionTableModel() { delete priv; } void TransactionTableModel::updateTransaction(const QString &hash, int status) { uint256 updated; updated.SetHex(hash.toStdString()); priv->updateWallet(updated, status); } void TransactionTableModel::updateConfirmations() { if(nBestHeight != cachedNumBlocks) { cachedNumBlocks = nBestHeight; // Blocks came in since last poll. // Invalidate status (number of confirmations) and (possibly) description // for all rows. Qt is smart enough to only actually request the data for the // visible rows. emit dataChanged(index(0, Status), index(priv->size()-1, Status)); emit dataChanged(index(0, ToAddress), index(priv->size()-1, ToAddress)); } } int TransactionTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return priv->size(); } int TransactionTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } QString TransactionTableModel::formatTxStatus(const TransactionRecord *wtx) const { QString status; switch(wtx->status.status) { case TransactionStatus::OpenUntilBlock: status = tr("Open for %n more block(s)","",wtx->status.open_for); break; case TransactionStatus::OpenUntilDate: status = tr("Open until %1").arg(GUIUtil::dateTimeStr(wtx->status.open_for)); break; case TransactionStatus::Offline: status = tr("Offline (%1 confirmations)").arg(wtx->status.depth); break; case TransactionStatus::Unconfirmed: status = tr("Unconfirmed (%1 of %2 confirmations)").arg(wtx->status.depth).arg(TransactionRecord::NumConfirmations); break; case TransactionStatus::HaveConfirmations: status = tr("Confirmed (%1 confirmations)").arg(wtx->status.depth); break; } if(wtx->type == TransactionRecord::Generated) { switch(wtx->status.maturity) { case TransactionStatus::Immature: status += "\n" + tr("Mined balance will be available when it matures in %n more block(s)", "", wtx->status.matures_in); break; case TransactionStatus::Mature: break; case TransactionStatus::MaturesWarning: status += "\n" + tr("This block was not received by any other nodes and will probably not be accepted!"); break; case TransactionStatus::NotAccepted: status += "\n" + tr("Generated but not accepted"); break; } } return status; } QString TransactionTableModel::formatTxDate(const TransactionRecord *wtx) const { if(wtx->time) { return GUIUtil::dateTimeStr(wtx->time); } else { return QString(); } } /* Look up address in address book, if found return label (address) otherwise just return (address) */ QString TransactionTableModel::lookupAddress(const std::string &address, bool tooltip) const { QString label = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(address)); QString description; if(!label.isEmpty()) { description += label + QString(" "); } if(label.isEmpty() || walletModel->getOptionsModel()->getDisplayAddresses() || tooltip) { description += QString("(") + QString::fromStdString(address) + QString(")"); } return description; } QString TransactionTableModel::formatTxType(const TransactionRecord *wtx) const { switch(wtx->type) { case TransactionRecord::RecvWithAddress: return tr("Received with"); case TransactionRecord::RecvFromOther: return tr("Received from"); case TransactionRecord::SendToAddress: case TransactionRecord::SendToOther: return tr("Sent to"); case TransactionRecord::SendToSelf: return tr("Payment to yourself"); case TransactionRecord::Generated: return tr("Mined"); default: return QString(); } } QVariant TransactionTableModel::txAddressDecoration(const TransactionRecord *wtx) const { switch(wtx->type) { case TransactionRecord::Generated: return QIcon(":/icons/tx_mined"); case TransactionRecord::RecvWithAddress: case TransactionRecord::RecvFromOther: return QIcon(":/icons/tx_input"); case TransactionRecord::SendToAddress: case TransactionRecord::SendToOther: return QIcon(":/icons/tx_output"); default: return QIcon(":/icons/tx_inout"); } return QVariant(); } QString TransactionTableModel::formatTxToAddress(const TransactionRecord *wtx, bool tooltip) const { switch(wtx->type) { case TransactionRecord::RecvFromOther: return QString::fromStdString(wtx->address); case TransactionRecord::RecvWithAddress: case TransactionRecord::SendToAddress: case TransactionRecord::Generated: return lookupAddress(wtx->address, tooltip); case TransactionRecord::SendToOther: return QString::fromStdString(wtx->address); case TransactionRecord::SendToSelf: default: return tr("(n/a)"); } } QVariant TransactionTableModel::addressColor(const TransactionRecord *wtx) const { // Show addresses without label in a less visible color switch(wtx->type) { case TransactionRecord::RecvWithAddress: case TransactionRecord::SendToAddress: case TransactionRecord::Generated: { QString label = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(wtx->address)); if(label.isEmpty()) return COLOR_BAREADDRESS; } break; case TransactionRecord::SendToSelf: return COLOR_BAREADDRESS; default: break; } return QVariant(); } QString TransactionTableModel::formatTxAmount(const TransactionRecord *wtx, bool showUnconfirmed) const { QString str = BitcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), wtx->credit + wtx->debit); if(showUnconfirmed) { if(!wtx->status.confirmed || wtx->status.maturity != TransactionStatus::Mature) { str = QString("[") + str + QString("]"); } } return QString(str); } QVariant TransactionTableModel::txStatusDecoration(const TransactionRecord *wtx) const { if(wtx->type == TransactionRecord::Generated) { switch(wtx->status.maturity) { case TransactionStatus::Immature: { int total = wtx->status.depth + wtx->status.matures_in; int part = (wtx->status.depth * 4 / total) + 1; return QIcon(QString(":/icons/transaction_%1").arg(part)); } case TransactionStatus::Mature: return QIcon(":/icons/transaction_confirmed"); case TransactionStatus::MaturesWarning: case TransactionStatus::NotAccepted: return QIcon(":/icons/transaction_0"); } } else { switch(wtx->status.status) { case TransactionStatus::OpenUntilBlock: case TransactionStatus::OpenUntilDate: return QColor(64,64,255); break; case TransactionStatus::Offline: return QColor(192,192,192); case TransactionStatus::Unconfirmed: switch(wtx->status.depth) { case 0: return QIcon(":/icons/transaction_0"); case 1: return QIcon(":/icons/transaction_1"); case 2: return QIcon(":/icons/transaction_2"); case 3: return QIcon(":/icons/transaction_3"); case 4: return QIcon(":/icons/transaction_4"); default: return QIcon(":/icons/transaction_5"); }; case TransactionStatus::HaveConfirmations: return QIcon(":/icons/transaction_confirmed"); } } return QColor(0,0,0); } QString TransactionTableModel::formatTooltip(const TransactionRecord *rec) const { QString tooltip = formatTxStatus(rec) + QString("\n") + formatTxType(rec); if(rec->type==TransactionRecord::RecvFromOther || rec->type==TransactionRecord::SendToOther || rec->type==TransactionRecord::SendToAddress || rec->type==TransactionRecord::RecvWithAddress) { tooltip += QString(" ") + formatTxToAddress(rec, true); } return tooltip; } QVariant TransactionTableModel::data(const QModelIndex &index, int role) const { if(!index.isValid()) return QVariant(); TransactionRecord *rec = static_cast<TransactionRecord*>(index.internalPointer()); switch(role) { case Qt::DecorationRole: switch(index.column()) { case Status: return txStatusDecoration(rec); case ToAddress: return txAddressDecoration(rec); } break; case Qt::DisplayRole: switch(index.column()) { case Date: return formatTxDate(rec); case Type: return formatTxType(rec); case ToAddress: return formatTxToAddress(rec, false); case Amount: return formatTxAmount(rec); } break; case Qt::EditRole: // Edit role is used for sorting, so return the unformatted values switch(index.column()) { case Status: return QString::fromStdString(rec->status.sortKey); case Date: return rec->time; case Type: return formatTxType(rec); case ToAddress: return formatTxToAddress(rec, true); case Amount: return rec->credit + rec->debit; } break; case Qt::ToolTipRole: return formatTooltip(rec); case Qt::TextAlignmentRole: return column_alignments[index.column()]; case Qt::ForegroundRole: // Non-confirmed transactions are grey if(!rec->status.confirmed) { return COLOR_UNCONFIRMED; } if(index.column() == Amount && (rec->credit+rec->debit) < 0) { return COLOR_NEGATIVE; } if(index.column() == ToAddress) { return addressColor(rec); } break; case TypeRole: return rec->type; case DateRole: return QDateTime::fromTime_t(static_cast<uint>(rec->time)); case LongDescriptionRole: return priv->describe(rec); case AddressRole: return QString::fromStdString(rec->address); case LabelRole: return walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(rec->address)); case AmountRole: return rec->credit + rec->debit; case TxIDRole: return QString::fromStdString(rec->getTxID()); case ConfirmedRole: // Return True if transaction counts for balance return rec->status.confirmed && !(rec->type == TransactionRecord::Generated && rec->status.maturity != TransactionStatus::Mature); case FormattedAmountRole: return formatTxAmount(rec, false); } return QVariant(); } QVariant TransactionTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole) { return columns[section]; } else if (role == Qt::TextAlignmentRole) { return column_alignments[section]; } else if (role == Qt::ToolTipRole) { switch(section) { case Status: return tr("Transaction status. Hover over this field to show number of confirmations."); case Date: return tr("Date and time that the transaction was received."); case Type: return tr("Type of transaction."); case ToAddress: return tr("Destination address of transaction."); case Amount: return tr("Amount removed from or added to balance."); } } } return QVariant(); } QModelIndex TransactionTableModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); TransactionRecord *data = priv->index(row); if(data) { return createIndex(row, column, priv->index(row)); } else { return QModelIndex(); } } void TransactionTableModel::updateDisplayUnit() { // emit dataChanged to update Amount column with the current unit emit dataChanged(index(0, Amount), index(priv->size()-1, Amount)); }
var events = require("events"); var request = require("request"); var mocha = require("mocha"); var should = require("should"); var Trello = require("../index"); var Stream = require("stream"); var behavesLike = require("./trello-behaviors"); describe("Trello", function () { describe("#constructor()", function () { it("should throw an Error if no API key is supplied", function () { (function () { new Trello(); }).should.throw("Application API key is required"); }); it("should not require a user's token", function () { new Trello("APIKEY").should.be.ok; }); it("should set key and token properties", function () { var trello = new Trello("APIKEY", "USERTOKEN"); trello.key.should.equal("APIKEY"); trello.token.should.equal("USERTOKEN"); }); }); describe("Requests", function () { beforeEach(function () { request.get = function (options) { this.request = { options: options }; return new events.EventEmitter(); }.bind(this); request.post = function (options) { this.request = { options: options }; return new events.EventEmitter(); }.bind(this); request.put = function (options) { this.request = { options: options }; return new events.EventEmitter(); }.bind(this); request.del = function (options) { this.request = { options: options }; return new events.EventEmitter(); }.bind(this); request.verb = function (options) { this.request = { options: options }; return new events.EventEmitter(); }.bind(this); this.trello = new Trello("APIKEY", "USERTOKEN"); }); describe("#get()", function () { beforeEach(function () { this.trello.get("/test", { type: "any" }, function () {}); }); behavesLike.aRequest(); it("should not require json arguments", function () { this.trello.get("/test", function () {}); this.request.options.json.should.be.ok; }); it("should make a GET request", function () { this.request.options.method.should.equal("GET"); }); }); describe("#post()", function () { beforeEach(function () { this.trello.post("/test", { type: "any" }, function () {}); }); behavesLike.aRequest(); it("should not require json arguments", function () { this.trello.post("/test", function () {}); this.request.options.json.should.be.ok; }); it("should make a POST request", function () { this.request.options.method.should.equal("POST"); }); it("should not have query parameters", function () { this.request.options.url.should.not.containEql("?"); }); }); describe("#post() - image stream upload", function () { beforeEach(function () { this.trello.post("/test", { attachment: new Stream.Readable() }, function () {}); }); behavesLike.aPostBodyRequest(); it("should have an formData.file property", function () { this.request.options.formData.should.have.property("file"); }); // Check if a readable stream // http://stackoverflow.com/a/28564000 it("should have a readable stream as formData.file property", function () { this.request.options.formData.file.should.be.an.instanceOf(Stream.Stream); this.request.options.formData.file._read.should.be.a.Function; this.request.options.formData.file._readableState.should.be.an.Object; }); }); describe("#post() - image url upload", function () { beforeEach(function () { this.trello.post("/test", { attachment: 'image.png' }, function () {}); }); behavesLike.aPostBodyRequest(); it("should have an formData.url property", function () { this.request.options.formData.should.have.property("url"); }); it("should have a string as formData.url property", function () { this.request.options.formData.url.should.be.a.String; }); }); describe("#put()", function () { beforeEach(function () { this.trello.put("/test", { type: "any" }, function () {}); }); behavesLike.aRequest(); it("should not require json arguments", function () { this.trello.put("/test", function () {}); this.request.options.json.should.be.ok; }); it("should make a PUT request", function () { this.request.options.method.should.equal("PUT"); }); }); describe("#del()", function () { beforeEach(function () { this.trello.del("/test", { type: "any" }, function () {}); }); behavesLike.aRequest(); it("should not require json arguments", function () { this.trello.del("/test", function () {}); this.request.options.json.should.be.ok; }); it("should make a DELETE request", function () { this.request.options.method.should.equal("DELETE"); }); }); describe("#request()", function () { beforeEach(function () { this.trello.request("VERB", "/test", { type: "any" }, function () {}); }); behavesLike.aRequest(); it("should not require json arguments", function () { this.trello.request("VERB", "/test", function () {}); this.request.options.json.should.be.ok; }); it("should make a request with any method specified", function () { this.request.options.method.should.equal("VERB"); }); it("should allow uris with a leading slash", function () { this.trello.request("VERB", "/test", function () {}); this.request.options.url.should.containEql("https://api.trello.com/test"); }); it("should allow uris without a leading slash", function () { this.trello.request("VERB", "test", function () {}); this.request.options.url.should.containEql("https://api.trello.com/test"); }); it("should parse jsonstring parameters from the uri", function () { this.trello.request("VERB", "/test?name=values", function () {}); this.request.options.json.should.have.property("name"); this.request.options.json.name.should.equal("values"); }); it("should pass through any errors without response bodies", function () { var method = request.get; request.get = function (options, callback) { callback(new Error("Something bad happened.")); }; this.trello.request("GET", "/test", function (err, response) { err.message.should.equal("Something bad happened."); }); request.get = method; }); }); }); });
/* Angular File Upload v0.3.3.1 https://github.com/nervgh/angular-file-upload */ (function(angular, factory) { if (typeof define === 'function' && define.amd) { define('angular-file-upload', ['angular'], function(angular) { return factory(angular); }); } else { return factory(angular); } }(angular || null, function(angular) { var app = angular.module('angularFileUpload', []); // It is attached to an element that catches the event drop file app.directive('ngFileDrop', [ '$fileUploader', function ($fileUploader) { 'use strict'; return { // don't use drag-n-drop files in IE9, because not File API support link: !$fileUploader.isHTML5 ? angular.noop : function (scope, element, attributes) { element .bind('drop', function (event) { var dataTransfer = event.dataTransfer ? event.dataTransfer : event.originalEvent.dataTransfer; // jQuery fix; if (!dataTransfer) return; event.preventDefault(); event.stopPropagation(); scope.$broadcast('file:removeoverclass'); scope.$emit('file:add', dataTransfer.files, scope.$eval(attributes.ngFileDrop)); }) .bind('dragover', function (event) { var dataTransfer = event.dataTransfer ? event.dataTransfer : event.originalEvent.dataTransfer; // jQuery fix; event.preventDefault(); event.stopPropagation(); dataTransfer.dropEffect = 'copy'; scope.$broadcast('file:addoverclass'); }) .bind('dragleave', function () { scope.$broadcast('file:removeoverclass'); }); } }; }]) // It is attached to an element which will be assigned to a class "ng-file-over" or ng-file-over="className" app.directive('ngFileOver', function () { 'use strict'; return { link: function (scope, element, attributes) { scope.$on('file:addoverclass', function () { element.addClass(attributes.ngFileOver || 'ng-file-over'); }); scope.$on('file:removeoverclass', function () { element.removeClass(attributes.ngFileOver || 'ng-file-over'); }); } }; }); // It is attached to <input type="file"> element like <ng-file-select="options"> app.directive('ngFileSelect', [ '$fileUploader', function ($fileUploader) { 'use strict'; return { link: function (scope, element, attributes) { $fileUploader.isHTML5 || element.removeAttr('multiple'); element.bind('change', function () { scope.$emit('file:add', $fileUploader.isHTML5 ? this.files : this, scope.$eval(attributes.ngFileSelect)); ($fileUploader.isHTML5 && element.attr('multiple')) && element.prop('value', null); }); element.prop('value', null); // FF fix } }; }]); app.factory('$fileUploader', [ '$compile', '$rootScope', '$http', '$window', function ($compile, $rootScope, $http, $window) { 'use strict'; /** * Creates a uploader * @param {Object} params * @constructor */ function Uploader(params) { angular.extend(this, { scope: $rootScope, url: '/', alias: 'file', queue: [], headers: {}, progress: null, autoUpload: false, removeAfterUpload: false, method: 'POST', filters: [], formData: [], isUploading: false, _nextIndex: 0, _timestamp: Date.now() }, params); // add the base filter this.filters.unshift(this._filter); this.scope.$on('file:add', function (event, items, options) { event.stopPropagation(); this.addToQueue(items, options); }.bind(this)); this.bind('beforeupload', Item.prototype._beforeupload); this.bind('in:progress', Item.prototype._progress); this.bind('in:success', Item.prototype._success); this.bind('in:cancel', Item.prototype._cancel); this.bind('in:error', Item.prototype._error); this.bind('in:complete', Item.prototype._complete); this.bind('in:progress', this._progress); this.bind('in:complete', this._complete); } Uploader.prototype = { /** * Link to the constructor */ constructor: Uploader, /** * The base filter. If returns "true" an item will be added to the queue * @param {File|Input} item * @returns {boolean} * @private */ _filter: function (item) { return angular.isElement(item) ? true : !!item.size; }, /** * Registers a event handler * @param {String} event * @param {Function} handler * @return {Function} unsubscribe function */ bind: function (event, handler) { return this.scope.$on(this._timestamp + ':' + event, handler.bind(this)); }, /** * Triggers events * @param {String} event * @param {...*} [some] */ trigger: function (event, some) { arguments[ 0 ] = this._timestamp + ':' + event; this.scope.$broadcast.apply(this.scope, arguments); }, /** * Checks a support the html5 uploader * @returns {Boolean} * @readonly */ isHTML5: !!($window.File && $window.FormData), /** * Adds items to the queue * @param {FileList|File|HTMLInputElement} items * @param {Object} [options] */ addToQueue: function (items, options) { var length = this.queue.length; var list = 'length' in items ? items : [items]; angular.forEach(list, function (file) { // check a [File|HTMLInputElement] var isValid = !this.filters.length ? true : this.filters.every(function (filter) { return filter.call(this, file); }, this); // create new item var item = new Item(angular.extend({ url: this.url, alias: this.alias, headers: angular.copy(this.headers), formData: angular.copy(this.formData), removeAfterUpload: this.removeAfterUpload, method: this.method, uploader: this, file: file }, options)); if (isValid) { this.queue.push(item); this.trigger('afteraddingfile', item); } else { this.trigger('whenaddingfilefailed', item); } }, this); if (this.queue.length !== length) { this.trigger('afteraddingall', this.queue); this.progress = this._getTotalProgress(); } this._render(); this.autoUpload && this.uploadAll(); }, /** * Remove items from the queue. Remove last: index = -1 * @param {Item|Number} value */ removeFromQueue: function (value) { var index = this.getIndexOfItem(value); var item = this.queue[ index ]; item.isUploading && item.cancel(); this.queue.splice(index, 1); item._destroy(); this.progress = this._getTotalProgress(); }, /** * Clears the queue */ clearQueue: function () { this.queue.forEach(function (item) { item.isUploading && item.cancel(); item._destroy(); }, this); this.queue.length = 0; this.progress = 0; }, /** * Returns a index of item from the queue * @param {Item|Number} value * @returns {Number} */ getIndexOfItem: function (value) { return angular.isObject(value) ? this.queue.indexOf(value) : value; }, /** * Returns not uploaded items * @returns {Array} */ getNotUploadedItems: function () { return this.queue.filter(function (item) { return !item.isUploaded; }); }, /** * Returns items ready for upload * @returns {Array} */ getReadyItems: function() { return this.queue .filter(function(item) { return item.isReady && !item.isUploading; }) .sort(function(item1, item2) { return item1.index - item2.index; }); }, /** * Uploads a item from the queue * @param {Item|Number} value */ uploadItem: function (value) { var index = this.getIndexOfItem(value); var item = this.queue[ index ]; var transport = this.isHTML5 ? '_xhrTransport' : '_iframeTransport'; item.index = item.index || this._nextIndex++; item.isReady = true; if (this.isUploading) { return; } this.isUploading = true; this[ transport ](item); }, /** * Cancels uploading of item from the queue * @param {Item|Number} value */ cancelItem: function(value) { var index = this.getIndexOfItem(value); var item = this.queue[ index ]; var prop = this.isHTML5 ? '_xhr' : '_form'; item[prop] && item[prop].abort(); }, /** * Uploads all not uploaded items of queue */ uploadAll: function () { var items = this.getNotUploadedItems().filter(function(item) { return !item.isUploading; }); items.forEach(function(item) { item.index = item.index || this._nextIndex++; item.isReady = true; }, this); items.length && this.uploadItem(items[ 0 ]); }, /** * Cancels all uploads */ cancelAll: function() { this.getNotUploadedItems().forEach(function(item) { this.cancelItem(item); }, this); }, /** * Updates angular scope * @private */ _render: function() { this.scope.$$phase || this.scope.$digest(); }, /** * Returns the total progress * @param {Number} [value] * @returns {Number} * @private */ _getTotalProgress: function (value) { if (this.removeAfterUpload) { return value || 0; } var notUploaded = this.getNotUploadedItems().length; var uploaded = notUploaded ? this.queue.length - notUploaded : this.queue.length; var ratio = 100 / this.queue.length; var current = (value || 0) * ratio / 100; return Math.round(uploaded * ratio + current); }, /** * The 'in:progress' handler * @private */ _progress: function (event, item, progress) { var result = this._getTotalProgress(progress); this.trigger('progressall', result); this.progress = result; this._render(); }, /** * The 'in:complete' handler * @private */ _complete: function () { var item = this.getReadyItems()[ 0 ]; this.isUploading = false; if (angular.isDefined(item)) { this.uploadItem(item); return; } this.trigger('completeall', this.queue); this.progress = this._getTotalProgress(); this._render(); }, /** * The XMLHttpRequest transport * @private */ _xhrTransport: function (item) { var xhr = item._xhr = new XMLHttpRequest(); var form = new FormData(); var that = this; this.trigger('beforeupload', item); item.formData.forEach(function(obj) { angular.forEach(obj, function(value, key) { form.append(key, value); }); }); form.append(item.alias, item.file); xhr.upload.onprogress = function (event) { var progress = event.lengthComputable ? event.loaded * 100 / event.total : 0; that.trigger('in:progress', item, Math.round(progress)); }; xhr.onload = function () { var response = that._transformResponse(xhr.response); var event = that._isSuccessCode(xhr.status) ? 'success' : 'error'; that.trigger('in:' + event, xhr, item, response); that.trigger('in:complete', xhr, item, response); }; xhr.onerror = function () { that.trigger('in:error', xhr, item); that.trigger('in:complete', xhr, item); }; xhr.onabort = function () { that.trigger('in:cancel', xhr, item); that.trigger('in:complete', xhr, item); }; xhr.open(item.method, item.url, true); angular.forEach(item.headers, function (value, name) { xhr.setRequestHeader(name, value); }); xhr.send(form); }, /** * The IFrame transport * @private */ _iframeTransport: function (item) { var form = angular.element('<form style="display: none;" />'); var iframe = angular.element('<iframe name="iframeTransport' + Date.now() + '">'); var input = item._input; var that = this; item._form && item._form.replaceWith(input); // remove old form item._form = form; // save link to new form this.trigger('beforeupload', item); input.prop('name', item.alias); item.formData.forEach(function(obj) { angular.forEach(obj, function(value, key) { form.append(angular.element('<input type="hidden" name="' + key + '" value="' + value + '" />')); }); }); form.prop({ action: item.url, method: item.method, target: iframe.prop('name'), enctype: 'multipart/form-data', encoding: 'multipart/form-data' // old IE }); iframe.bind('load', function () { // fixed angular.contents() for iframes var html = iframe[0].contentDocument.body.innerHTML; var xhr = { response: html, status: 200, dummy: true }; var response = that._transformResponse(xhr.response); that.trigger('in:success', xhr, item, response); that.trigger('in:complete', xhr, item, response); }); form.abort = function() { var xhr = { status: 0, dummy: true }; iframe.unbind('load').prop('src', 'javascript:false;'); form.replaceWith(input); that.trigger('in:cancel', xhr, item); that.trigger('in:complete', xhr, item); }; input.after(form); form.append(input).append(iframe); form[ 0 ].submit(); }, /** * Checks whether upload successful * @param {Number} status * @returns {Boolean} * @private */ _isSuccessCode: function(status) { return (status >= 200 && status < 300) || status === 304; }, /** * Transforms the server response * @param {*} response * @returns {*} * @private */ _transformResponse: function (response) { $http.defaults.transformResponse.forEach(function (transformFn) { response = transformFn(response); }); return response; } }; /** * Create a item * @param {Object} params * @constructor */ function Item(params) { // fix for old browsers if (!Uploader.prototype.isHTML5) { var input = angular.element(params.file); var clone = $compile(input.clone())(params.uploader.scope); var value = input.val(); params.file = { lastModifiedDate: null, size: null, type: 'like/' + value.slice(value.lastIndexOf('.') + 1).toLowerCase(), name: value.slice(value.lastIndexOf('/') + value.lastIndexOf('\\') + 2) }; params._input = input; clone.prop('value', null); // FF fix input.css('display', 'none').after(clone); // remove jquery dependency } angular.extend(this, { isReady: false, isUploading: false, isUploaded: false, isSuccess: false, isCancel: false, isError: false, progress: null, index: null }, params); } Item.prototype = { /** * Link to the constructor */ constructor: Item, /** * Removes a item */ remove: function () { this.uploader.removeFromQueue(this); }, /** * Uploads a item */ upload: function () { this.uploader.uploadItem(this); }, /** * Cancels uploading */ cancel: function() { this.uploader.cancelItem(this); }, /** * Destroys form and input * @private */ _destroy: function() { this._form && this._form.remove(); this._input && this._input.remove(); delete this._form; delete this._input; }, /** * The 'beforeupload' handler * @param {Object} event * @param {Item} item * @private */ _beforeupload: function (event, item) { item.isReady = true; item.isUploading = true; item.isUploaded = false; item.isSuccess = false; item.isCancel = false; item.isError = false; item.progress = 0; }, /** * The 'in:progress' handler * @param {Object} event * @param {Item} item * @param {Number} progress * @private */ _progress: function (event, item, progress) { item.progress = progress; item.uploader.trigger('progress', item, progress); }, /** * The 'in:success' handler * @param {Object} event * @param {XMLHttpRequest} xhr * @param {Item} item * @param {*} response * @private */ _success: function (event, xhr, item, response) { item.isReady = false; item.isUploading = false; item.isUploaded = true; item.isSuccess = true; item.isCancel = false; item.isError = false; item.progress = 100; item.index = null; item.uploader.trigger('success', xhr, item, response); }, /** * The 'in:cancel' handler * @param {Object} event * @param {XMLHttpRequest} xhr * @param {Item} item * @private */ _cancel: function(event, xhr, item) { item.isReady = false; item.isUploading = false; item.isUploaded = false; item.isSuccess = false; item.isCancel = true; item.isError = false; item.progress = 0; item.index = null; item.uploader.trigger('cancel', xhr, item); }, /** * The 'in:error' handler * @param {Object} event * @param {XMLHttpRequest} xhr * @param {Item} item * @param {*} response * @private */ _error: function (event, xhr, item, response) { item.isReady = false; item.isUploading = false; item.isUploaded = true; item.isSuccess = false; item.isCancel = false; item.isError = true; item.progress = 100; item.index = null; item.uploader.trigger('error', xhr, item, response); }, /** * The 'in:complete' handler * @param {Object} event * @param {XMLHttpRequest} xhr * @param {Item} item * @param {*} response * @private */ _complete: function (event, xhr, item, response) { item.uploader.trigger('complete', xhr, item, response); item.removeAfterUpload && item.remove(); } }; return { create: function (params) { return new Uploader(params); }, isHTML5: Uploader.prototype.isHTML5 }; }]) return app; }));
from django.template.defaultfilters import truncatechars_html from django.test import SimpleTestCase class FunctionTests(SimpleTestCase): def test_truncate_zero(self): self.assertEqual(truncatechars_html('<p>one <a href="#">two - three <br>four</a> five</p>', 0), '...') def test_truncate(self): self.assertEqual( truncatechars_html('<p>one <a href="#">two - three <br>four</a> five</p>', 6), '<p>one...</p>', ) def test_truncate2(self): self.assertEqual( truncatechars_html('<p>one <a href="#">two - three <br>four</a> five</p>', 11), '<p>one <a href="#">two ...</a></p>', ) def test_truncate3(self): self.assertEqual( truncatechars_html('<p>one <a href="#">two - three <br>four</a> five</p>', 100), '<p>one <a href="#">two - three <br>four</a> five</p>', ) def test_truncate_unicode(self): self.assertEqual(truncatechars_html('<b>\xc5ngstr\xf6m</b> was here', 5), '<b>\xc5n...</b>') def test_truncate_something(self): self.assertEqual(truncatechars_html('a<b>b</b>c', 3), 'a<b>b</b>c')
// mxj - A collection of map[string]interface{} and associated XML and JSON utilities. // Copyright 2012-2014 Charles Banning. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file /* Marshal/Unmarshal XML to/from JSON and map[string]interface{} values, and extract/modify values from maps by key or key-path, including wildcards. mxj supplants the legacy x2j and j2x packages. If you want the old syntax, use mxj/x2j or mxj/j2x packages. Note: this library was designed for processing ad hoc anonymous messages. Bulk processing large data sets may be much more efficiently performed using the encoding/xml or encoding/json packages from Go's standard library directly. Note: 2014-08-02: AnyXml() and AnyXmlIndent() will try to marshal arbitrary values to XML. SUMMARY type Map map[string]interface{} Create a Map value, 'm', from any map[string]interface{} value, 'v': m := Map(v) Unmarshal / marshal XML as a Map value, 'm': m, err := NewMapXml(xmlValue) // unmarshal xmlValue, err := m.Xml() // marshal Unmarshal XML from an io.Reader as a Map value, 'm': m, err := NewMapReader(xmlReader) // repeated calls, as with an os.File Reader, will process stream m, raw, err := NewMapReaderRaw(xmlReader) // 'raw' is the raw XML that was decoded Marshal Map value, 'm', to an XML Writer (io.Writer): err := m.XmlWriter(xmlWriter) raw, err := m.XmlWriterRaw(xmlWriter) // 'raw' is the raw XML that was written on xmlWriter Also, for prettified output: xmlValue, err := m.XmlIndent(prefix, indent, ...) err := m.XmlIndentWriter(xmlWriter, prefix, indent, ...) raw, err := m.XmlIndentWriterRaw(xmlWriter, prefix, indent, ...) Bulk process XML with error handling (note: handlers must return a boolean value): err := HandleXmlReader(xmlReader, mapHandler(Map), errHandler(error)) err := HandleXmlReaderRaw(xmlReader, mapHandler(Map, []byte), errHandler(error, []byte)) Converting XML to JSON: see Examples for NewMapXml and HandleXmlReader. There are comparable functions and methods for JSON processing. Arbitrary structure values can be decoded to / encoded from Map values: m, err := NewMapStruct(structVal) err := m.Struct(structPointer) To work with XML tag values, JSON or Map key values or structure field values, decode the XML, JSON or structure to a Map value, 'm', or cast a map[string]interface{} value to a Map value, 'm', then: paths := m.PathsForKey(key) path := m.PathForKeyShortest(key) values, err := m.ValuesForKey(key, subkeys) values, err := m.ValuesForPath(path, subkeys) // 'path' can be dot-notation with wildcards and indexed arrays. count, err := m.UpdateValuesForPath(newVal, path, subkeys) Get everything at once, irrespective of path depth: leafnodes := m.LeafNodes() leafvalues := m.LeafValues() A new Map with whatever keys are desired can be created from the current Map and then encoded in XML or JSON. (Note: keys can use dot-notation. 'oldKey' can also use wildcards and indexed arrays.) newMap := m.NewMap("oldKey_1:newKey_1", "oldKey_2:newKey_2", ..., "oldKey_N:newKey_N") newXml := newMap.Xml() // for example newJson := newMap.Json() // ditto XML PARSING CONVENTIONS - Attributes are parsed to map[string]interface{} values by prefixing a hyphen, '-', to the attribute label. (PrependAttrWithHyphen(false) will override this.) - If the element is a simple element and has attributes, the element value is given the key '#text' for its map[string]interface{} representation. XML ENCODING CONVENTIONS - 'nil' Map values, which may represent 'null' JSON values, are encoded as "<tag/>". NOTE: the operation is not symmetric as "<tag/>" elements are decoded as 'tag:""' Map values, which, then, encode in JSON as '"tag":""' values.. */ package mxj
<?php /* CAT:Labels */ /* pChart library inclusions */ include("../class/pData.class.php"); include("../class/pDraw.class.php"); include("../class/pImage.class.php"); include("../class/pBubble.class.php"); /* Create and populate the pData object */ $MyData = new pData(); $MyData->loadPalette("../palettes/blind.color",TRUE); $MyData->addPoints(array(34,55,15,62,38,42),"Probe1"); $MyData->addPoints(array(5,10,8,9,15,10),"Probe1Weight"); $MyData->addPoints(array(5,10,-5,-1,0,-10),"Probe2"); $MyData->addPoints(array(6,10,14,10,14,6),"Probe2Weight"); $MyData->setSerieDescription("Probe1","This year"); $MyData->setSerieDescription("Probe2","Last year"); $MyData->setAxisName(0,"Current stock"); $MyData->addPoints(array("Apple","Banana","Orange","Lemon","Peach","Strawberry"),"Product"); $MyData->setAbscissa("Product"); /* Create the pChart object */ $myPicture = new pImage(700,230,$MyData); /* Draw the background */ $Settings = array("R"=>170, "G"=>183, "B"=>87, "Dash"=>1, "DashR"=>190, "DashG"=>203, "DashB"=>107); $myPicture->drawFilledRectangle(0,0,700,230,$Settings); /* Overlay with a gradient */ $Settings = array("StartR"=>219, "StartG"=>231, "StartB"=>139, "EndR"=>1, "EndG"=>138, "EndB"=>68, "Alpha"=>50); $myPicture->drawGradientArea(0,0,700,230,DIRECTION_VERTICAL,$Settings); $myPicture->drawGradientArea(0,0,700,20,DIRECTION_VERTICAL,array("StartR"=>0,"StartG"=>0,"StartB"=>0,"EndR"=>50,"EndG"=>50,"EndB"=>50,"Alpha"=>80)); /* Add a border to the picture */ $myPicture->drawRectangle(0,0,699,229,array("R"=>0,"G"=>0,"B"=>0)); /* Write the picture title */ $myPicture->setFontProperties(array("FontName"=>"../fonts/Silkscreen.ttf","FontSize"=>6)); $myPicture->drawText(10,13,"drawBubbleChart() - draw a linear bubble chart",array("R"=>255,"G"=>255,"B"=>255)); /* Write the title */ $myPicture->setFontProperties(array("FontName"=>"../fonts/Forgotte.ttf","FontSize"=>11)); $myPicture->drawText(40,55,"Current Stock / Needs chart",array("FontSize"=>14,"Align"=>TEXT_ALIGN_BOTTOMLEFT)); /* Change the default font */ $myPicture->setFontProperties(array("FontName"=>"../fonts/pf_arma_five.ttf","FontSize"=>6)); /* Create the Bubble chart object and scale up */ $myBubbleChart = new pBubble($myPicture,$MyData); /* Scale up for the bubble chart */ $bubbleDataSeries = array("Probe1","Probe2"); $bubbleWeightSeries = array("Probe1Weight","Probe2Weight"); $myBubbleChart->bubbleScale($bubbleDataSeries,$bubbleWeightSeries); /* Draw the 1st chart */ $myPicture->setGraphArea(40,60,430,190); $myPicture->drawFilledRectangle(40,60,430,190,array("R"=>255,"G"=>255,"B"=>255,"Surrounding"=>-50,"Alpha"=>10)); $myPicture->drawScale(array("DrawSubTicks"=>TRUE,"CycleBackground"=>TRUE)); $myPicture->setShadow(TRUE,array("X"=>1,"Y"=>1,"R"=>0,"G"=>0,"B"=>0,"Alpha"=>30)); $myBubbleChart->drawBubbleChart($bubbleDataSeries,$bubbleWeightSeries); /* Write a label over the chart */ $LabelSettings = array("TitleMode"=>LABEL_TITLE_BACKGROUND,"VerticalMargin"=>4,"HorizontalMargin"=>6,"DrawSerieColor"=>FALSE,"TitleR"=>255,"TitleG"=>255,"TitleB"=>255); $myBubbleChart->writeBubbleLabel("Probe1","Probe1Weight",3,$LabelSettings); $myBubbleChart->writeBubbleLabel("Probe2","Probe2Weight",4,$LabelSettings); /* Draw the 2nd scale */ $myPicture->setShadow(FALSE); $myPicture->setGraphArea(500,60,670,190); $myPicture->drawFilledRectangle(500,60,670,190,array("R"=>255,"G"=>255,"B"=>255,"Surrounding"=>-200,"Alpha"=>10)); $myPicture->drawScale(array("Pos"=>SCALE_POS_TOPBOTTOM,"DrawSubTicks"=>TRUE)); /* Draw the 2nd bubble chart */ $myPicture->setShadow(TRUE,array("X"=>1,"Y"=>1,"R"=>0,"G"=>0,"B"=>0,"Alpha"=>30)); $myBubbleChart->drawbubbleChart($bubbleDataSeries,$bubbleWeightSeries,array("DrawBorder"=>TRUE,"Surrounding"=>60,"BorderAlpha"=>100)); /* Write a label over the chart */ $myBubbleChart->writeBubbleLabel("Probe1","Probe1Weight",4,$LabelSettings); /* Write the chart legend */ $myPicture->drawLegend(550,215,array("Style"=>LEGEND_NOBORDER,"Mode"=>LEGEND_HORIZONTAL)); /* Render the picture (choose the best way) */ $myPicture->autoOutput("pictures/example.drawLabel.bubble.png"); ?>
#include "config.h" #include "WKNetworkInfoManager.h" #include "WKAPICast.h" #include "WebNetworkInfoManagerProxy.h" using namespace WebKit; WKTypeID WKNetworkInfoManagerGetTypeID() { #if ENABLE(NETWORK_INFO) return toAPI(WebNetworkInfoManagerProxy::APIType); #else return 0; #endif } void WKNetworkInfoManagerSetProvider(WKNetworkInfoManagerRef networkInfoManager, const WKNetworkInfoProvider* provider) { #if ENABLE(NETWORK_INFO) toImpl(networkInfoManager)->initializeProvider(provider); #endif } void WKNetworkInfoManagerProviderDidChangeNetworkInformation(WKNetworkInfoManagerRef networkInfoManager, WKStringRef eventType, WKNetworkInfoRef networkInfo) { #if ENABLE(NETWORK_INFO) toImpl(networkInfoManager)->providerDidChangeNetworkInformation(AtomicString(toImpl(eventType)->string()), toImpl(networkInfo)); #endif }