code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
// 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.IO; namespace System.Net { /// <summary> /// <para>The FtpWebResponse class contains the result of the FTP request. /// </summary> public class FtpWebResponse : WebResponse, IDisposable { internal Stream _responseStream; private long _contentLength; private Uri _responseUri; private FtpStatusCode _statusCode; private string _statusLine; private WebHeaderCollection _ftpRequestHeaders; private DateTime _lastModified; private string _bannerMessage; private string _welcomeMessage; private string _exitMessage; internal FtpWebResponse(Stream responseStream, long contentLength, Uri responseUri, FtpStatusCode statusCode, string statusLine, DateTime lastModified, string bannerMessage, string welcomeMessage, string exitMessage) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, contentLength, statusLine); _responseStream = responseStream; if (responseStream == null && contentLength < 0) { contentLength = 0; } _contentLength = contentLength; _responseUri = responseUri; _statusCode = statusCode; _statusLine = statusLine; _lastModified = lastModified; _bannerMessage = bannerMessage; _welcomeMessage = welcomeMessage; _exitMessage = exitMessage; } internal void UpdateStatus(FtpStatusCode statusCode, string statusLine, string exitMessage) { _statusCode = statusCode; _statusLine = statusLine; _exitMessage = exitMessage; } public override Stream GetResponseStream() { Stream responseStream = null; if (_responseStream != null) { responseStream = _responseStream; } else { responseStream = _responseStream = new EmptyStream(); } return responseStream; } internal sealed class EmptyStream : MemoryStream { internal EmptyStream() : base(Array.Empty<byte>(), false) { } } internal void SetResponseStream(Stream stream) { if (stream == null || stream == Stream.Null || stream is EmptyStream) return; _responseStream = stream; } /// <summary> /// <para>Closes the underlying FTP response stream, but does not close control connection</para> /// </summary> public override void Close() { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); _responseStream?.Close(); if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } /// <summary> /// <para>Queries the length of the response</para> /// </summary> public override long ContentLength { get { return _contentLength; } } internal void SetContentLength(long value) { _contentLength = value; } public override WebHeaderCollection Headers { get { if (_ftpRequestHeaders == null) { lock (this) { if (_ftpRequestHeaders == null) { _ftpRequestHeaders = new WebHeaderCollection(); } } } return _ftpRequestHeaders; } } public override bool SupportsHeaders { get { return true; } } /// <summary> /// <para>Shows the final Uri that the FTP request ended up on</para> /// </summary> public override Uri ResponseUri { get { return _responseUri; } } /// <summary> /// <para>Last status code retrived</para> /// </summary> public FtpStatusCode StatusCode { get { return _statusCode; } } /// <summary> /// <para>Last status line retrived</para> /// </summary> public string StatusDescription { get { return _statusLine; } } /// <summary> /// <para>Returns last modified date time for given file (null if not relavant/avail)</para> /// </summary> public DateTime LastModified { get { return _lastModified; } } /// <summary> /// <para>Returns the server message sent before user credentials are sent</para> /// </summary> public string BannerMessage { get { return _bannerMessage; } } /// <summary> /// <para>Returns the server message sent after user credentials are sent</para> /// </summary> public string WelcomeMessage { get { return _welcomeMessage; } } /// <summary> /// <para>Returns the exit sent message on shutdown</para> /// </summary> public string ExitMessage { get { return _exitMessage; } } } }
krk/corefx
src/System.Net.Requests/src/System/Net/FtpWebResponse.cs
C#
mit
5,923
WebMock.disable_net_connect!(allow: 'coveralls.io') # iTunes Lookup API RSpec.configure do |config| config.before(:each) do # iTunes Lookup API by Apple ID ["invalid", "", 0, '284882215', ['338986109', 'FR']].each do |current| if current.kind_of? Array id = current[0] country = current[1] url = "https://itunes.apple.com/lookup?id=#{id}&country=#{country}" body_file = "spec/responses/itunesLookup-#{id}_#{country}.json" else id = current url = "https://itunes.apple.com/lookup?id=#{id}" body_file = "spec/responses/itunesLookup-#{id}.json" end stub_request(:get, url). with(headers: { 'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent' => 'Ruby' }). to_return(status: 200, body: File.read(body_file), headers: {}) end # iTunes Lookup API by App Identifier stub_request(:get, "https://itunes.apple.com/lookup?bundleId=com.facebook.Facebook"). with(headers: { 'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent' => 'Ruby' }). to_return(status: 200, body: File.read("spec/responses/itunesLookup-com.facebook.Facebook.json"), headers: {}) stub_request(:get, "https://itunes.apple.com/lookup?bundleId=net.sunapps.invalid"). with(headers: { 'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent' => 'Ruby' }). to_return(status: 200, body: File.read("spec/responses/itunesLookup-net.sunapps.invalid.json"), headers: {}) end end describe FastlaneCore do describe FastlaneCore::ItunesSearchApi do it "returns nil when it could not be found" do expect(FastlaneCore::ItunesSearchApi.fetch("invalid")).to eq(nil) expect(FastlaneCore::ItunesSearchApi.fetch("")).to eq(nil) expect(FastlaneCore::ItunesSearchApi.fetch(0)).to eq(nil) end it "returns the actual object if it could be found" do response = FastlaneCore::ItunesSearchApi.fetch("284882215") expect(response['kind']).to eq('software') expect(response['supportedDevices'].count).to be > 8 expect(FastlaneCore::ItunesSearchApi.fetch_bundle_identifier("284882215")).to eq('com.facebook.Facebook') end it "returns the actual object if it could be found" do response = FastlaneCore::ItunesSearchApi.fetch_by_identifier("com.facebook.Facebook") expect(response['kind']).to eq('software') expect(response['supportedDevices'].count).to be > 8 expect(response['trackId']).to eq(284_882_215) end it "can find country specific object" do response = FastlaneCore::ItunesSearchApi.fetch(338_986_109, 'FR') expect(response['kind']).to eq('software') expect(response['supportedDevices'].count).to be > 8 expect(response['trackId']).to eq(338_986_109) end end end
mathiasAichinger/fastlane_core
spec/itunes_search_api_spec.rb
Ruby
mit
2,907
var baz = "baz"; export default baz;
EliteScientist/webpack
test/statsCases/import-context-filter/templates/baz.noimport.js
JavaScript
mit
38
define( [ "js/views/baseview", "underscore", "js/models/metadata", "js/views/abstract_editor", "js/models/uploads", "js/views/uploads", "js/models/license", "js/views/license", "js/views/video/transcripts/metadata_videolist", "js/views/video/translations_editor" ], function(BaseView, _, MetadataModel, AbstractEditor, FileUpload, UploadDialog, LicenseModel, LicenseView, VideoList, VideoTranslations) { var Metadata = {}; Metadata.Editor = BaseView.extend({ // Model is CMS.Models.MetadataCollection, initialize : function() { var self = this, counter = 0, locator = self.$el.closest('[data-locator]').data('locator'), courseKey = self.$el.closest('[data-course-key]').data('course-key'); this.template = this.loadTemplate('metadata-editor'); this.$el.html(this.template({numEntries: this.collection.length})); this.collection.each( function (model) { var data = { el: self.$el.find('.metadata_entry')[counter++], courseKey: courseKey, locator: locator, model: model }, conversions = { 'Select': 'Option', 'Float': 'Number', 'Integer': 'Number' }, type = model.getType(); if (conversions[type]) { type = conversions[type]; } if (_.isFunction(Metadata[type])) { new Metadata[type](data); } else { // Everything else is treated as GENERIC_TYPE, which uses String editor. new Metadata.String(data); } }); }, /** * Returns just the modified metadata values, in the format used to persist to the server. */ getModifiedMetadataValues: function () { var modified_values = {}; this.collection.each( function (model) { if (model.isModified()) { modified_values[model.getFieldName()] = model.getValue(); } } ); return modified_values; }, /** * Returns a display name for the component related to this metadata. This method looks to see * if there is a metadata entry called 'display_name', and if so, it returns its value. If there * is no such entry, or if display_name does not have a value set, it returns an empty string. */ getDisplayName: function () { var displayName = ''; this.collection.each( function (model) { if (model.get('field_name') === 'display_name') { var displayNameValue = model.get('value'); // It is possible that there is no display name value set. In that case, return empty string. displayName = displayNameValue ? displayNameValue : ''; } } ); return displayName; } }); Metadata.VideoList = VideoList; Metadata.VideoTranslations = VideoTranslations; Metadata.String = AbstractEditor.extend({ events : { "change input" : "updateModel", "keypress .setting-input" : "showClearButton", "click .setting-clear" : "clear" }, templateName: "metadata-string-entry", render: function () { AbstractEditor.prototype.render.apply(this); // If the model has property `non editable` equals `true`, // the field is disabled, but user is able to clear it. if (this.model.get('non_editable')) { this.$el.find('#' + this.uniqueId) .prop('readonly', true) .addClass('is-disabled') .attr('aria-disabled', true); } }, getValueFromEditor : function () { return this.$el.find('#' + this.uniqueId).val(); }, setValueInEditor : function (value) { this.$el.find('input').val(value); } }); Metadata.Number = AbstractEditor.extend({ events : { "change input" : "updateModel", "keypress .setting-input" : "keyPressed", "change .setting-input" : "changed", "click .setting-clear" : "clear" }, render: function () { AbstractEditor.prototype.render.apply(this); if (!this.initialized) { var numToString = function (val) { return val.toFixed(4); }; var min = "min"; var max = "max"; var step = "step"; var options = this.model.getOptions(); if (options.hasOwnProperty(min)) { this.min = Number(options[min]); this.$el.find('input').attr(min, numToString(this.min)); } if (options.hasOwnProperty(max)) { this.max = Number(options[max]); this.$el.find('input').attr(max, numToString(this.max)); } var stepValue = undefined; if (options.hasOwnProperty(step)) { // Parse step and convert to String. Polyfill doesn't like float values like ".1" (expects "0.1"). stepValue = numToString(Number(options[step])); } else if (this.isIntegerField()) { stepValue = "1"; } if (stepValue !== undefined) { this.$el.find('input').attr(step, stepValue); } // Manually runs polyfill for input number types to correct for Firefox non-support. // inputNumber will be undefined when unit test is running. if ($.fn.inputNumber) { this.$el.find('.setting-input-number').inputNumber(); } this.initialized = true; } return this; }, templateName: "metadata-number-entry", getValueFromEditor : function () { return this.$el.find('#' + this.uniqueId).val(); }, setValueInEditor : function (value) { this.$el.find('input').val(value); }, /** * Returns true if this view is restricted to integers, as opposed to floating points values. */ isIntegerField : function () { return this.model.getType() === 'Integer'; }, keyPressed: function (e) { this.showClearButton(); // This first filtering if statement is take from polyfill to prevent // non-numeric input (for browsers that don't use polyfill because they DO have a number input type). var _ref, _ref1; if (((_ref = e.keyCode) !== 8 && _ref !== 9 && _ref !== 35 && _ref !== 36 && _ref !== 37 && _ref !== 39) && ((_ref1 = e.which) !== 45 && _ref1 !== 46 && _ref1 !== 48 && _ref1 !== 49 && _ref1 !== 50 && _ref1 !== 51 && _ref1 !== 52 && _ref1 !== 53 && _ref1 !== 54 && _ref1 !== 55 && _ref1 !== 56 && _ref1 !== 57)) { e.preventDefault(); } // For integers, prevent decimal points. if (this.isIntegerField() && e.keyCode === 46) { e.preventDefault(); } }, changed: function () { // Limit value to the range specified by min and max (necessary for browsers that aren't using polyfill). // Prevent integer/float fields value to be empty (set them to their defaults) var value = this.getValueFromEditor(); if (value) { if ((this.max !== undefined) && value > this.max) { value = this.max; } else if ((this.min != undefined) && value < this.min) { value = this.min; } this.setValueInEditor(value); this.updateModel(); } else { this.clear(); } } }); Metadata.Option = AbstractEditor.extend({ events : { "change select" : "updateModel", "click .setting-clear" : "clear" }, templateName: "metadata-option-entry", getValueFromEditor : function () { var selectedText = this.$el.find('#' + this.uniqueId).find(":selected").text(); var selectedValue; _.each(this.model.getOptions(), function (modelValue) { if (modelValue === selectedText) { selectedValue = modelValue; } else if (modelValue['display_name'] === selectedText) { selectedValue = modelValue['value']; } }); return selectedValue; }, setValueInEditor : function (value) { // Value here is the json value as used by the field. The choice may instead be showing display names. // Find the display name matching the value passed in. _.each(this.model.getOptions(), function (modelValue) { if (modelValue['value'] === value) { value = modelValue['display_name']; } }); this.$el.find('#' + this.uniqueId + " option").filter(function() { return $(this).text() === value; }).prop('selected', true); } }); Metadata.List = AbstractEditor.extend({ events : { "click .setting-clear" : "clear", "keypress .setting-input" : "showClearButton", "change input" : "updateModel", "input input" : "enableAdd", "click .create-setting" : "addEntry", "click .remove-setting" : "removeEntry" }, templateName: "metadata-list-entry", getValueFromEditor: function () { return _.map( this.$el.find('li input'), function (ele) { return ele.value.trim(); } ).filter(_.identity); }, setValueInEditor: function (value) { var list = this.$el.find('ol'); list.empty(); _.each(value, function(ele, index) { var template = _.template( '<li class="list-settings-item">' + '<input type="text" class="input" value="<%= ele %>">' + '<a href="#" class="remove-action remove-setting" data-index="<%= index %>"><i class="icon fa fa-times-circle" aria-hidden="true"></i><span class="sr">Remove</span></a>' + '</li>' ); list.append($(template({'ele': ele, 'index': index}))); }); }, addEntry: function(event) { event.preventDefault(); // We don't call updateModel here since it's bound to the // change event var list = this.model.get('value') || []; this.setValueInEditor(list.concat([''])); this.$el.find('.create-setting').addClass('is-disabled').attr('aria-disabled', true); }, removeEntry: function(event) { event.preventDefault(); var entry = $(event.currentTarget).siblings().val(); this.setValueInEditor(_.without(this.model.get('value'), entry)); this.updateModel(); this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false); }, enableAdd: function() { this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false); }, clear: function() { AbstractEditor.prototype.clear.apply(this, arguments); if (_.isNull(this.model.getValue())) { this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false); } } }); Metadata.RelativeTime = AbstractEditor.extend({ defaultValue: '00:00:00', // By default max value of RelativeTime field on Backend is 23:59:59, // that is 86399 seconds. maxTimeInSeconds: 86399, events: { "focus input" : "addSelection", "mouseup input" : "mouseUpHandler", "change input" : "updateModel", "keypress .setting-input" : "showClearButton" , "click .setting-clear" : "clear" }, templateName: "metadata-string-entry", getValueFromEditor: function () { var $input = this.$el.find('#' + this.uniqueId); return $input.val(); }, updateModel: function () { var value = this.getValueFromEditor(), time = this.parseRelativeTime(value); this.model.setValue(time); // Sometimes, `parseRelativeTime` method returns the same value for // the different inputs. In this case, model will not be // updated (it already has the same value) and we should // call `render` method manually. // Examples: // value => 23:59:59; parseRelativeTime => 23:59:59 // value => 44:59:59; parseRelativeTime => 23:59:59 if (value !== time && !this.model.hasChanged('value')) { this.render(); } }, parseRelativeTime: function (value) { // This function ensure you have two-digits var pad = function (number) { return (number < 10) ? "0" + number : number; }, // Removes all white-spaces and splits by `:`. list = value.replace(/\s+/g, '').split(':'), seconds, date; list = _.map(list, function(num) { return Math.max(0, parseInt(num, 10) || 0); }).reverse(); seconds = _.reduce(list, function(memo, num, index) { return memo + num * Math.pow(60, index); }, 0); // multiply by 1000 because Date() requires milliseconds date = new Date(Math.min(seconds, this.maxTimeInSeconds) * 1000); return [ pad(date.getUTCHours()), pad(date.getUTCMinutes()), pad(date.getUTCSeconds()) ].join(':'); }, setValueInEditor: function (value) { if (!value) { value = this.defaultValue; } this.$el.find('input').val(value); }, addSelection: function (event) { $(event.currentTarget).select(); }, mouseUpHandler: function (event) { // Prevents default behavior to make works selection in WebKit // browsers event.preventDefault(); } }); Metadata.Dict = AbstractEditor.extend({ events: { "click .setting-clear" : "clear", "keypress .setting-input" : "showClearButton", "change input" : "updateModel", "input input" : "enableAdd", "click .create-setting" : "addEntry", "click .remove-setting" : "removeEntry" }, templateName: "metadata-dict-entry", getValueFromEditor: function () { var dict = {}; _.each(this.$el.find('li'), function(li, index) { var key = $(li).find('.input-key').val().trim(), value = $(li).find('.input-value').val().trim(); // Keys should be unique, so if our keys are duplicated and // second key is empty or key and value are empty just do // nothing. Otherwise, it'll be overwritten by the new value. if (value === '') { if (key === '' || key in dict) { return false; } } dict[key] = value; }); return dict; }, setValueInEditor: function (value) { var list = this.$el.find('ol'), frag = document.createDocumentFragment(); _.each(value, function(value, key) { var template = _.template( '<li class="list-settings-item">' + '<input type="text" class="input input-key" value="<%= key %>">' + '<input type="text" class="input input-value" value="<%= value %>">' + '<a href="#" class="remove-action remove-setting" data-value="<%= value %>"><i class="icon fa fa-times-circle" aria-hidden="true"></i><span class="sr">Remove</span></a>' + '</li>' ); frag.appendChild($(template({'key': key, 'value': value}))[0]); }); list.html([frag]); }, addEntry: function(event) { event.preventDefault(); // We don't call updateModel here since it's bound to the // change event var dict = $.extend(true, {}, this.model.get('value')) || {}; dict[''] = ''; this.setValueInEditor(dict); this.$el.find('.create-setting').addClass('is-disabled').attr('aria-disabled', true); }, removeEntry: function(event) { event.preventDefault(); var entry = $(event.currentTarget).siblings('.input-key').val(); this.setValueInEditor(_.omit(this.model.get('value'), entry)); this.updateModel(); this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false); }, enableAdd: function() { this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false); }, clear: function() { AbstractEditor.prototype.clear.apply(this, arguments); if (_.isNull(this.model.getValue())) { this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false); } } }); /** * Provides convenient way to upload/download files in component edit. * The editor uploads files directly to course assets and stores link * to uploaded file. */ Metadata.FileUploader = AbstractEditor.extend({ events : { "click .upload-setting" : "upload", "click .setting-clear" : "clear" }, templateName: "metadata-file-uploader-entry", templateButtonsName: "metadata-file-uploader-item", initialize: function () { this.buttonTemplate = this.loadTemplate(this.templateButtonsName); AbstractEditor.prototype.initialize.apply(this); }, getValueFromEditor: function () { return this.$('#' + this.uniqueId).val(); }, setValueInEditor: function (value) { var html = this.buttonTemplate({ model: this.model, uniqueId: this.uniqueId }); this.$('#' + this.uniqueId).val(value); this.$('.wrapper-uploader-actions').html(html); }, upload: function (event) { var self = this, target = $(event.currentTarget), url = '/assets/' + this.options.courseKey + '/', model = new FileUpload({ title: gettext('Upload File'), }), view = new UploadDialog({ model: model, url: url, parentElement: target.closest('.xblock-editor'), onSuccess: function (response) { if (response['asset'] && response['asset']['url']) { self.model.setValue(response['asset']['url']); } } }).show(); event.preventDefault(); } }); Metadata.License = AbstractEditor.extend({ initialize: function(options) { this.licenseModel = new LicenseModel({"asString": this.model.getValue()}); this.licenseView = new LicenseView({model: this.licenseModel}); // Rerender when the license model changes this.listenTo(this.licenseModel, 'change', this.setLicense); this.render(); }, render: function() { this.licenseView.render().$el.css("display", "inline"); this.licenseView.undelegateEvents(); this.$el.empty().append(this.licenseView.el); // restore event bindings this.licenseView.delegateEvents(); return this; }, setLicense: function() { this.model.setValue(this.licenseModel.toString()); this.render() } }); return Metadata; });
MakeHer/edx-platform
cms/static/js/views/metadata.js
JavaScript
agpl-3.0
21,517
# Copyright (c) 2008-2013 Michael Dvorkin and contributors. # # Fat Free CRM is freely distributable under the terms of MIT license. # See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe CampaignsController do def get_data_for_sidebar @status = Setting.campaign_status.dup end before(:each) do require_user set_current_tab(:campaigns) end # GET /campaigns # GET /campaigns.xml #---------------------------------------------------------------------------- describe "responding to GET index" do before(:each) do get_data_for_sidebar end it "should expose all campaigns as @campaigns and render [index] template" do @campaigns = [FactoryGirl.create(:campaign, user: current_user)] get :index expect(assigns[:campaigns]).to eq(@campaigns) expect(response).to render_template("campaigns/index") end it "should collect the data for the opportunities sidebar" do @campaigns = [FactoryGirl.create(:campaign, user: current_user)] get :index expect(assigns[:campaign_status_total].keys.map(&:to_sym) - (@status << :all << :other)).to eq([]) end it "should filter out campaigns by status" do controller.session[:campaigns_filter] = "planned,started" @campaigns = [ FactoryGirl.create(:campaign, user: current_user, status: "started"), FactoryGirl.create(:campaign, user: current_user, status: "planned") ] # This one should be filtered out. FactoryGirl.create(:campaign, user: current_user, status: "completed") get :index # Note: can't compare campaigns directly because of BigDecimal objects. expect(assigns[:campaigns].size).to eq(2) expect(assigns[:campaigns].map(&:status).sort).to eq(%w(planned started)) end it "should perform lookup using query string" do @first = FactoryGirl.create(:campaign, user: current_user, name: "Hello, world!") @second = FactoryGirl.create(:campaign, user: current_user, name: "Hello again") get :index, query: "again" expect(assigns[:campaigns]).to eq([@second]) expect(assigns[:current_query]).to eq("again") expect(session[:campaigns_current_query]).to eq("again") end describe "AJAX pagination" do it "should pick up page number from params" do @campaigns = [FactoryGirl.create(:campaign, user: current_user)] xhr :get, :index, page: 42 expect(assigns[:current_page].to_i).to eq(42) expect(assigns[:campaigns]).to eq([]) # page #42 should be empty if there's only one campaign ;-) expect(session[:campaigns_current_page].to_i).to eq(42) expect(response).to render_template("campaigns/index") end it "should pick up saved page number from session" do session[:campaigns_current_page] = 42 @campaigns = [FactoryGirl.create(:campaign, user: current_user)] xhr :get, :index expect(assigns[:current_page]).to eq(42) expect(assigns[:campaigns]).to eq([]) expect(response).to render_template("campaigns/index") end it "should reset current_page when query is altered" do session[:campaigns_current_page] = 42 session[:campaigns_current_query] = "bill" @campaigns = [FactoryGirl.create(:campaign, user: current_user)] xhr :get, :index expect(assigns[:current_page]).to eq(1) expect(assigns[:campaigns]).to eq(@campaigns) expect(response).to render_template("campaigns/index") end end describe "with mime type of JSON" do it "should render all campaigns as JSON" do expect(@controller).to receive(:get_campaigns).and_return(@campaigns = []) expect(@campaigns).to receive(:to_json).and_return("generated JSON") request.env["HTTP_ACCEPT"] = "application/json" get :index expect(response.body).to eq("generated JSON") end end describe "with mime type of XML" do it "should render all campaigns as xml" do expect(@controller).to receive(:get_campaigns).and_return(@campaigns = []) expect(@campaigns).to receive(:to_xml).and_return("generated XML") request.env["HTTP_ACCEPT"] = "application/xml" get :index expect(response.body).to eq("generated XML") end end end # GET /campaigns/1 # GET /campaigns/1.xml HTML #---------------------------------------------------------------------------- describe "responding to GET show" do describe "with mime type of HTML" do before(:each) do @campaign = FactoryGirl.create(:campaign, id: 42, user: current_user) @stage = Setting.unroll(:opportunity_stage) @comment = Comment.new end it "should expose the requested campaign as @campaign and render [show] template" do get :show, id: 42 expect(assigns[:campaign]).to eq(@campaign) expect(assigns[:stage]).to eq(@stage) expect(assigns[:comment].attributes).to eq(@comment.attributes) expect(response).to render_template("campaigns/show") end it "should update an activity when viewing the campaign" do get :show, id: @campaign.id expect(@campaign.versions.last.event).to eq('view') end end describe "with mime type of JSON" do it "should render the requested campaign as JSON" do @campaign = FactoryGirl.create(:campaign, id: 42, user: current_user) expect(Campaign).to receive(:find).and_return(@campaign) expect(@campaign).to receive(:to_json).and_return("generated JSON") request.env["HTTP_ACCEPT"] = "application/json" get :show, id: 42 expect(response.body).to eq("generated JSON") end end describe "with mime type of XML" do it "should render the requested campaign as XML" do @campaign = FactoryGirl.create(:campaign, id: 42, user: current_user) expect(Campaign).to receive(:find).and_return(@campaign) expect(@campaign).to receive(:to_xml).and_return("generated XML") request.env["HTTP_ACCEPT"] = "application/xml" get :show, id: 42 expect(response.body).to eq("generated XML") end end describe "campaign got deleted or otherwise unavailable" do it "should redirect to campaign index if the campaign got deleted" do @campaign = FactoryGirl.create(:campaign, user: current_user) @campaign.destroy get :show, id: @campaign.id expect(flash[:warning]).not_to eq(nil) expect(response).to redirect_to(campaigns_path) end it "should redirect to campaign index if the campaign is protected" do @campaign = FactoryGirl.create(:campaign, user: FactoryGirl.create(:user), access: "Private") get :show, id: @campaign.id expect(flash[:warning]).not_to eq(nil) expect(response).to redirect_to(campaigns_path) end it "should return 404 (Not Found) JSON error" do @campaign = FactoryGirl.create(:campaign, user: current_user) @campaign.destroy request.env["HTTP_ACCEPT"] = "application/json" get :show, id: @campaign.id expect(response.code).to eq("404") # :not_found end it "should return 404 (Not Found) XML error" do @campaign = FactoryGirl.create(:campaign, user: current_user) @campaign.destroy request.env["HTTP_ACCEPT"] = "application/xml" get :show, id: @campaign.id expect(response.code).to eq("404") # :not_found end end end # GET /campaigns/new # GET /campaigns/new.xml AJAX #---------------------------------------------------------------------------- describe "responding to GET new" do it "should expose a new campaign as @campaign" do @campaign = Campaign.new(user: current_user, access: Setting.default_access) xhr :get, :new expect(assigns[:campaign].attributes).to eq(@campaign.attributes) expect(response).to render_template("campaigns/new") end it "should create related object when necessary" do @lead = FactoryGirl.create(:lead, id: 42) xhr :get, :new, related: "lead_42" expect(assigns[:lead]).to eq(@lead) end end # GET /campaigns/1/edit AJAX #---------------------------------------------------------------------------- describe "responding to GET edit" do it "should expose the requested campaign as @campaign and render [edit] template" do @campaign = FactoryGirl.create(:campaign, id: 42, user: current_user) xhr :get, :edit, id: 42 expect(assigns[:campaign]).to eq(@campaign) expect(response).to render_template("campaigns/edit") end it "should find previous campaign as necessary" do @campaign = FactoryGirl.create(:campaign, id: 42) @previous = FactoryGirl.create(:campaign, id: 99) xhr :get, :edit, id: 42, previous: 99 expect(assigns[:campaign]).to eq(@campaign) expect(assigns[:previous]).to eq(@previous) end describe "(campaign got deleted or is otherwise unavailable)" do it "should reload current page with the flash message if the campaign got deleted" do @campaign = FactoryGirl.create(:campaign, user: current_user) @campaign.destroy xhr :get, :edit, id: @campaign.id expect(flash[:warning]).not_to eq(nil) expect(response.body).to eq("window.location.reload();") end it "should reload current page with the flash message if the campaign is protected" do @private = FactoryGirl.create(:campaign, user: FactoryGirl.create(:user), access: "Private") xhr :get, :edit, id: @private.id expect(flash[:warning]).not_to eq(nil) expect(response.body).to eq("window.location.reload();") end end describe "(previous campaign got deleted or is otherwise unavailable)" do before(:each) do @campaign = FactoryGirl.create(:campaign, user: current_user) @previous = FactoryGirl.create(:campaign, user: FactoryGirl.create(:user)) end it "should notify the view if previous campaign got deleted" do @previous.destroy xhr :get, :edit, id: @campaign.id, previous: @previous.id expect(flash[:warning]).to eq(nil) # no warning, just silently remove the div expect(assigns[:previous]).to eq(@previous.id) expect(response).to render_template("campaigns/edit") end it "should notify the view if previous campaign got protected" do @previous.update_attribute(:access, "Private") xhr :get, :edit, id: @campaign.id, previous: @previous.id expect(flash[:warning]).to eq(nil) expect(assigns[:previous]).to eq(@previous.id) expect(response).to render_template("campaigns/edit") end end end # POST /campaigns # POST /campaigns.xml AJAX #---------------------------------------------------------------------------- describe "responding to POST create" do describe "with valid params" do it "should expose a newly created campaign as @campaign and render [create] template" do @campaign = FactoryGirl.build(:campaign, name: "Hello", user: current_user) allow(Campaign).to receive(:new).and_return(@campaign) xhr :post, :create, campaign: { name: "Hello" } expect(assigns(:campaign)).to eq(@campaign) expect(response).to render_template("campaigns/create") end it "should get data to update campaign sidebar" do @campaign = FactoryGirl.build(:campaign, name: "Hello", user: current_user) allow(Campaign).to receive(:new).and_return(@campaign) xhr :post, :create, campaign: { name: "Hello" } expect(assigns[:campaign_status_total]).to be_instance_of(HashWithIndifferentAccess) end it "should reload campaigns to update pagination" do @campaign = FactoryGirl.build(:campaign, user: current_user) allow(Campaign).to receive(:new).and_return(@campaign) xhr :post, :create, campaign: { name: "Hello" } expect(assigns[:campaigns]).to eq([@campaign]) end it "should add a new comment to the newly created campaign when specified" do @campaign = FactoryGirl.build(:campaign, name: "Hello world", user: current_user) allow(Campaign).to receive(:new).and_return(@campaign) xhr :post, :create, campaign: { name: "Hello world" }, comment_body: "Awesome comment is awesome" expect(@campaign.reload.comments.map(&:comment)).to include("Awesome comment is awesome") end end describe "with invalid params" do it "should expose a newly created but unsaved campaign as @campaign and still render [create] template" do @campaign = FactoryGirl.build(:campaign, id: nil, name: nil, user: current_user) allow(Campaign).to receive(:new).and_return(@campaign) xhr :post, :create, campaign: {} expect(assigns(:campaign)).to eq(@campaign) expect(response).to render_template("campaigns/create") end end end # PUT /campaigns/1 # PUT /campaigns/1.xml AJAX #---------------------------------------------------------------------------- describe "responding to PUT update" do describe "with valid params" do it "should update the requested campaign and render [update] template" do @campaign = FactoryGirl.create(:campaign, id: 42, name: "Bye") xhr :put, :update, id: 42, campaign: { name: "Hello" } expect(@campaign.reload.name).to eq("Hello") expect(assigns(:campaign)).to eq(@campaign) expect(response).to render_template("campaigns/update") end it "should get data for campaigns sidebar when called from Campaigns index" do @campaign = FactoryGirl.create(:campaign, id: 42) request.env["HTTP_REFERER"] = "http://localhost/campaigns" xhr :put, :update, id: 42, campaign: { name: "Hello" } expect(assigns(:campaign)).to eq(@campaign) expect(assigns[:campaign_status_total]).to be_instance_of(HashWithIndifferentAccess) end it "should update campaign permissions when sharing with specific users" do @campaign = FactoryGirl.create(:campaign, id: 42, access: "Public") he = FactoryGirl.create(:user, id: 7) she = FactoryGirl.create(:user, id: 8) xhr :put, :update, id: 42, campaign: { name: "Hello", access: "Shared", user_ids: %w(7 8) } expect(assigns[:campaign].access).to eq("Shared") expect(assigns[:campaign].user_ids.sort).to eq([7, 8]) end describe "campaign got deleted or otherwise unavailable" do it "should reload current page with the flash message if the campaign got deleted" do @campaign = FactoryGirl.create(:campaign, user: current_user) @campaign.destroy xhr :put, :update, id: @campaign.id expect(flash[:warning]).not_to eq(nil) expect(response.body).to eq("window.location.reload();") end it "should reload current page with the flash message if the campaign is protected" do @private = FactoryGirl.create(:campaign, user: FactoryGirl.create(:user), access: "Private") xhr :put, :update, id: @private.id expect(flash[:warning]).not_to eq(nil) expect(response.body).to eq("window.location.reload();") end end end describe "with invalid params" do it "should not update the requested campaign, but still expose it as @campaign and still render [update] template" do @campaign = FactoryGirl.create(:campaign, id: 42, name: "Hello", user: current_user) xhr :put, :update, id: 42, campaign: { name: nil } expect(@campaign.reload.name).to eq("Hello") expect(assigns(:campaign)).to eq(@campaign) expect(response).to render_template("campaigns/update") end end end # DELETE /campaigns/1 # DELETE /campaigns/1.xml AJAX #---------------------------------------------------------------------------- describe "responding to DELETE destroy" do before(:each) do @campaign = FactoryGirl.create(:campaign, user: current_user) end describe "AJAX request" do it "should destroy the requested campaign and render [destroy] template" do @another_campaign = FactoryGirl.create(:campaign, user: current_user) xhr :delete, :destroy, id: @campaign.id expect(assigns[:campaigns]).to eq([@another_campaign]) expect { Campaign.find(@campaign.id) }.to raise_error(ActiveRecord::RecordNotFound) expect(response).to render_template("campaigns/destroy") end it "should get data for campaigns sidebar" do xhr :delete, :destroy, id: @campaign.id expect(assigns[:campaign_status_total]).to be_instance_of(HashWithIndifferentAccess) end it "should try previous page and render index action if current page has no campaigns" do session[:campaigns_current_page] = 42 xhr :delete, :destroy, id: @campaign.id expect(session[:campaigns_current_page]).to eq(41) expect(response).to render_template("campaigns/index") end it "should render index action when deleting last campaign" do session[:campaigns_current_page] = 1 xhr :delete, :destroy, id: @campaign.id expect(session[:campaigns_current_page]).to eq(1) expect(response).to render_template("campaigns/index") end describe "campaign got deleted or otherwise unavailable" do it "should reload current page with the flash message if the campaign got deleted" do @campaign = FactoryGirl.create(:campaign, user: current_user) @campaign.destroy xhr :delete, :destroy, id: @campaign.id expect(flash[:warning]).not_to eq(nil) expect(response.body).to eq("window.location.reload();") end it "should reload current page with the flash message if the campaign is protected" do @private = FactoryGirl.create(:campaign, user: FactoryGirl.create(:user), access: "Private") xhr :delete, :destroy, id: @private.id expect(flash[:warning]).not_to eq(nil) expect(response.body).to eq("window.location.reload();") end end end describe "HTML request" do it "should redirect to Campaigns index when a campaign gets deleted from its landing page" do delete :destroy, id: @campaign.id expect(flash[:notice]).not_to eq(nil) expect(response).to redirect_to(campaigns_path) end it "should redirect to campaign index with the flash message is the campaign got deleted" do @campaign = FactoryGirl.create(:campaign, user: current_user) @campaign.destroy delete :destroy, id: @campaign.id expect(flash[:warning]).not_to eq(nil) expect(response).to redirect_to(campaigns_path) end it "should redirect to campaign index with the flash message if the campaign is protected" do @private = FactoryGirl.create(:campaign, user: FactoryGirl.create(:user), access: "Private") delete :destroy, id: @private.id expect(flash[:warning]).not_to eq(nil) expect(response).to redirect_to(campaigns_path) end end end # PUT /campaigns/1/attach # PUT /campaigns/1/attach.xml AJAX #---------------------------------------------------------------------------- describe "responding to PUT attach" do describe "tasks" do before do @model = FactoryGirl.create(:campaign) @attachment = FactoryGirl.create(:task, asset: nil) end it_should_behave_like("attach") end describe "leads" do before do @model = FactoryGirl.create(:campaign) @attachment = FactoryGirl.create(:lead, campaign: nil) end it_should_behave_like("attach") end describe "opportunities" do before do @model = FactoryGirl.create(:campaign) @attachment = FactoryGirl.create(:opportunity, campaign: nil) end it_should_behave_like("attach") end end # PUT /campaigns/1/attach # PUT /campaigns/1/attach.xml AJAX #---------------------------------------------------------------------------- describe "responding to PUT attach" do describe "tasks" do before do @model = FactoryGirl.create(:campaign) @attachment = FactoryGirl.create(:task, asset: nil) end it_should_behave_like("attach") end describe "leads" do before do @model = FactoryGirl.create(:campaign) @attachment = FactoryGirl.create(:lead, campaign: nil) end it_should_behave_like("attach") end describe "opportunities" do before do @model = FactoryGirl.create(:campaign) @attachment = FactoryGirl.create(:opportunity, campaign: nil) end it_should_behave_like("attach") end end # POST /campaigns/1/discard # POST /campaigns/1/discard.xml AJAX #---------------------------------------------------------------------------- describe "responding to POST discard" do describe "tasks" do before do @model = FactoryGirl.create(:campaign) @attachment = FactoryGirl.create(:task, asset: @model) end it_should_behave_like("discard") end describe "leads" do before do @attachment = FactoryGirl.create(:lead) @model = FactoryGirl.create(:campaign) @model.leads << @attachment end it_should_behave_like("discard") end describe "opportunities" do before do @attachment = FactoryGirl.create(:opportunity) @model = FactoryGirl.create(:campaign) @model.opportunities << @attachment end it_should_behave_like("discard") end end # POST /campaigns/auto_complete/query AJAX #---------------------------------------------------------------------------- describe "responding to POST auto_complete" do before(:each) do @auto_complete_matches = [FactoryGirl.create(:campaign, name: "Hello World", user: current_user)] end it_should_behave_like("auto complete") end # GET /campaigns/redraw AJAX #---------------------------------------------------------------------------- describe "responding to GET redraw" do it "should save user selected campaign preference" do xhr :get, :redraw, per_page: 42, view: "brief", sort_by: "name" expect(current_user.preference[:campaigns_per_page]).to eq("42") expect(current_user.preference[:campaigns_index_view]).to eq("brief") expect(current_user.preference[:campaigns_sort_by]).to eq("campaigns.name ASC") end it "should reset current page to 1" do xhr :get, :redraw, per_page: 42, view: "brief", sort_by: "name" expect(session[:campaigns_current_page]).to eq(1) end it "should select @campaigns and render [index] template" do @campaigns = [ FactoryGirl.create(:campaign, name: "A", user: current_user), FactoryGirl.create(:campaign, name: "B", user: current_user) ] xhr :get, :redraw, per_page: 1, sort_by: "name" expect(assigns(:campaigns)).to eq([@campaigns.first]) expect(response).to render_template("campaigns/index") end end # POST /campaigns/filter AJAX #---------------------------------------------------------------------------- describe "responding to POST filter" do it "should expose filtered campaigns as @campaigns and render [index] template" do session[:campaigns_filter] = "planned,started" @campaigns = [FactoryGirl.create(:campaign, status: "completed", user: current_user)] xhr :post, :filter, status: "completed" expect(assigns(:campaigns)).to eq(@campaigns) expect(response).to render_template("campaigns/index") end it "should reset current page to 1" do @campaigns = [] xhr :post, :filter, status: "completed" expect(session[:campaigns_current_page]).to eq(1) end end end
srinuvasuv/fat_free_crm
spec/controllers/entities/campaigns_controller_spec.rb
Ruby
mit
24,917
<?php /** * Unit test class for the MultiLineAssignment sniff. * * PHP version 5 * * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood <gsherwood@squiz.net> * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence * @link http://pear.php.net/package/PHP_CodeSniffer */ /** * Unit test class for the MultiLineAssignment sniff. * * A sniff unit test checks a .inc file for expected violations of a single * coding standard. Expected errors and warnings are stored in this class. * * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood <gsherwood@squiz.net> * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence * @version Release: @package_version@ * @link http://pear.php.net/package/PHP_CodeSniffer */ class PEAR_Tests_Formatting_MultiLineAssignmentUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * * The key of the array should represent the line number and the value * should represent the number of errors that should occur on that line. * * @return array<int, int> */ public function getErrorList() { return array( 3 => 1, 6 => 1, 8 => 1, ); }//end getErrorList() /** * Returns the lines where warnings should occur. * * The key of the array should represent the line number and the value * should represent the number of warnings that should occur on that line. * * @return array<int, int> */ public function getWarningList() { return array(); }//end getWarningList() }//end class ?>
danalec/dotfiles
sublime/.config/sublime-text-3/Packages/anaconda_php/plugin/handlers_php/linting/phpcs/CodeSniffer/Standards/PEAR/Tests/Formatting/MultiLineAssignmentUnitTest.php
PHP
mit
1,893
<?php global $wpdb, $wp_version, $yarpp; /* Enforce YARPP setup: */ $yarpp->enforce(); if(!$yarpp->enabled() && !$yarpp->activate()) { echo '<div class="updated">'.__('The YARPP database has an error which could not be fixed.','yarpp').'</div>'; } /* Check to see that templates are in the right place */ if (!$yarpp->diagnostic_custom_templates()) { $template_option = yarpp_get_option('template'); if ($template_option !== false && $template_option !== 'thumbnails') yarpp_set_option('template', false); $template_option = yarpp_get_option('rss_template'); if ($template_option !== false && $template_option !== 'thumbnails') yarpp_set_option('rss_template', false); } /** * @since 3.3 Move version checking here, in PHP. */ if (current_user_can('update_plugins')) { $yarpp_version_info = $yarpp->version_info(); /* * These strings are not localizable, as long as the plugin data on wordpress.org cannot be. */ $slug = 'yet-another-related-posts-plugin'; $plugin_name = 'Yet Another Related Posts Plugin'; $file = basename(YARPP_DIR).'/yarpp.php'; if ($yarpp_version_info['result'] === 'new') { /* Make sure the update system is aware of this version. */ $current = get_site_transient('update_plugins'); if (!isset($current->response[$file])) { delete_site_transient('update_plugins'); wp_update_plugins(); } echo '<div class="updated"><p>'; $details_url = self_admin_url('plugin-install.php?tab=plugin-information&plugin='.$slug.'&TB_iframe=true&width=600&height=800'); printf( __( 'There is a new version of %1$s available.'. '<a href="%2$s" class="thickbox" title="%3$s">View version %4$s details</a>'. 'or <a href="%5$s">update automatically</a>.', 'yarpp'), $plugin_name, esc_url($details_url), esc_attr($plugin_name), $yarpp_version_info['current']['version'], wp_nonce_url( self_admin_url('update.php?action=upgrade-plugin&plugin=').$file, 'upgrade-plugin_'.$file) ); echo '</p></div>'; } else if ($yarpp_version_info['result'] === 'newbeta') { echo '<div class="updated"><p>'; printf( __( "There is a new beta (%s) of Yet Another Related Posts Plugin. ". "You can <a href=\"%s\">download it here</a> at your own risk.", "yarpp"), $yarpp_version_info['beta']['version'], $yarpp_version_info['beta']['url'] ); echo '</p></div>'; } } /* MyISAM Check */ include 'yarpp_myisam_notice.php'; /* This is not a yarpp pluging update, it is an yarpp option update */ if (isset($_POST['update_yarpp'])) { $new_options = array(); foreach ($yarpp->default_options as $option => $default) { if ( is_bool($default) ) $new_options[$option] = isset($_POST[$option]); if ( (is_string($default) || is_int($default)) && isset($_POST[$option]) && is_string($_POST[$option]) ) $new_options[$option] = stripslashes($_POST[$option]); } if ( isset($_POST['weight']) ) { $new_options['weight'] = array(); $new_options['require_tax'] = array(); foreach ( (array) $_POST['weight'] as $key => $value) { if ( $value == 'consider' ) $new_options['weight'][$key] = 1; if ( $value == 'consider_extra' ) $new_options['weight'][$key] = YARPP_EXTRA_WEIGHT; } foreach ( (array) $_POST['weight']['tax'] as $tax => $value) { if ( $value == 'consider' ) $new_options['weight']['tax'][$tax] = 1; if ( $value == 'consider_extra' ) $new_options['weight']['tax'][$tax] = YARPP_EXTRA_WEIGHT; if ( $value == 'require_one' ) { $new_options['weight']['tax'][$tax] = 1; $new_options['require_tax'][$tax] = 1; } if ( $value == 'require_more' ) { $new_options['weight']['tax'][$tax] = 1; $new_options['require_tax'][$tax] = 2; } } } if ( isset( $_POST['auto_display_post_types'] ) ) { $new_options['auto_display_post_types'] = array_keys( $_POST['auto_display_post_types'] ); } else { $new_options['auto_display_post_types'] = array(); } $new_options['recent'] = isset($_POST['recent_only']) ? $_POST['recent_number'] . ' ' . $_POST['recent_units'] : false; if ( isset($_POST['exclude']) ) $new_options['exclude'] = implode(',',array_keys($_POST['exclude'])); else $new_options['exclude'] = ''; $new_options['template'] = $_POST['use_template'] == 'custom' ? $_POST['template_file'] : ( $_POST['use_template'] == 'thumbnails' ? 'thumbnails' : false ); $new_options['rss_template'] = $_POST['rss_use_template'] == 'custom' ? $_POST['rss_template_file'] : ( $_POST['rss_use_template'] == 'thumbnails' ? 'thumbnails' : false ); $new_options = apply_filters( 'yarpp_settings_save', $new_options ); yarpp_set_option($new_options); echo '<div class="updated fade"><p>'.__('Options saved!','yarpp').'</p></div>'; } wp_nonce_field('meta-box-order', 'meta-box-order-nonce', false); wp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false); wp_nonce_field('yarpp_display_demo', 'yarpp_display_demo-nonce', false); wp_nonce_field('yarpp_display_exclude_terms', 'yarpp_display_exclude_terms-nonce', false); wp_nonce_field('yarpp_optin_data', 'yarpp_optin_data-nonce', false); wp_nonce_field('yarpp_set_display_code', 'yarpp_set_display_code-nonce', false); if (!count($yarpp->admin->get_templates()) && $yarpp->admin->can_copy_templates()) { wp_nonce_field('yarpp_copy_templates', 'yarpp_copy_templates-nonce', false); } include(YARPP_DIR.'/includes/phtmls/yarpp_options.phtml');
sarahkpeck/it-starts-with
wp-content/plugins/yet-another-related-posts-plugin/includes/yarpp_options.php
PHP
gpl-2.0
5,985
""" report test results in JUnit-XML format, for use with Jenkins and build integration servers. Based on initial code from Ross Lawley. Output conforms to https://github.com/jenkinsci/xunit-plugin/blob/master/ src/main/resources/org/jenkinsci/plugins/xunit/types/model/xsd/junit-10.xsd """ from __future__ import absolute_import, division, print_function import functools import py import os import re import sys import time import pytest from _pytest import nodes from _pytest.config import filename_arg # Python 2.X and 3.X compatibility if sys.version_info[0] < 3: from codecs import open else: unichr = chr unicode = str long = int class Junit(py.xml.Namespace): pass # We need to get the subset of the invalid unicode ranges according to # XML 1.0 which are valid in this python build. Hence we calculate # this dynamically instead of hardcoding it. The spec range of valid # chars is: Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] # | [#x10000-#x10FFFF] _legal_chars = (0x09, 0x0A, 0x0d) _legal_ranges = ( (0x20, 0x7E), (0x80, 0xD7FF), (0xE000, 0xFFFD), (0x10000, 0x10FFFF), ) _legal_xml_re = [ unicode("%s-%s") % (unichr(low), unichr(high)) for (low, high) in _legal_ranges if low < sys.maxunicode ] _legal_xml_re = [unichr(x) for x in _legal_chars] + _legal_xml_re illegal_xml_re = re.compile(unicode('[^%s]') % unicode('').join(_legal_xml_re)) del _legal_chars del _legal_ranges del _legal_xml_re _py_ext_re = re.compile(r"\.py$") def bin_xml_escape(arg): def repl(matchobj): i = ord(matchobj.group()) if i <= 0xFF: return unicode('#x%02X') % i else: return unicode('#x%04X') % i return py.xml.raw(illegal_xml_re.sub(repl, py.xml.escape(arg))) class _NodeReporter(object): def __init__(self, nodeid, xml): self.id = nodeid self.xml = xml self.add_stats = self.xml.add_stats self.duration = 0 self.properties = [] self.nodes = [] self.testcase = None self.attrs = {} def append(self, node): self.xml.add_stats(type(node).__name__) self.nodes.append(node) def add_property(self, name, value): self.properties.append((str(name), bin_xml_escape(value))) def make_properties_node(self): """Return a Junit node containing custom properties, if any. """ if self.properties: return Junit.properties([ Junit.property(name=name, value=value) for name, value in self.properties ]) return '' def record_testreport(self, testreport): assert not self.testcase names = mangle_test_address(testreport.nodeid) classnames = names[:-1] if self.xml.prefix: classnames.insert(0, self.xml.prefix) attrs = { "classname": ".".join(classnames), "name": bin_xml_escape(names[-1]), "file": testreport.location[0], } if testreport.location[1] is not None: attrs["line"] = testreport.location[1] if hasattr(testreport, "url"): attrs["url"] = testreport.url self.attrs = attrs def to_xml(self): testcase = Junit.testcase(time=self.duration, **self.attrs) testcase.append(self.make_properties_node()) for node in self.nodes: testcase.append(node) return testcase def _add_simple(self, kind, message, data=None): data = bin_xml_escape(data) node = kind(data, message=message) self.append(node) def write_captured_output(self, report): for capname in ('out', 'err'): content = getattr(report, 'capstd' + capname) if content: tag = getattr(Junit, 'system-' + capname) self.append(tag(bin_xml_escape(content))) def append_pass(self, report): self.add_stats('passed') def append_failure(self, report): # msg = str(report.longrepr.reprtraceback.extraline) if hasattr(report, "wasxfail"): self._add_simple( Junit.skipped, "xfail-marked test passes unexpectedly") else: if hasattr(report.longrepr, "reprcrash"): message = report.longrepr.reprcrash.message elif isinstance(report.longrepr, (unicode, str)): message = report.longrepr else: message = str(report.longrepr) message = bin_xml_escape(message) fail = Junit.failure(message=message) fail.append(bin_xml_escape(report.longrepr)) self.append(fail) def append_collect_error(self, report): # msg = str(report.longrepr.reprtraceback.extraline) self.append(Junit.error(bin_xml_escape(report.longrepr), message="collection failure")) def append_collect_skipped(self, report): self._add_simple( Junit.skipped, "collection skipped", report.longrepr) def append_error(self, report): if getattr(report, 'when', None) == 'teardown': msg = "test teardown failure" else: msg = "test setup failure" self._add_simple( Junit.error, msg, report.longrepr) def append_skipped(self, report): if hasattr(report, "wasxfail"): self._add_simple( Junit.skipped, "expected test failure", report.wasxfail ) else: filename, lineno, skipreason = report.longrepr if skipreason.startswith("Skipped: "): skipreason = bin_xml_escape(skipreason[9:]) self.append( Junit.skipped("%s:%s: %s" % (filename, lineno, skipreason), type="pytest.skip", message=skipreason)) self.write_captured_output(report) def finalize(self): data = self.to_xml().unicode(indent=0) self.__dict__.clear() self.to_xml = lambda: py.xml.raw(data) @pytest.fixture def record_xml_property(request): """Add extra xml properties to the tag for the calling test. The fixture is callable with ``(name, value)``, with value being automatically xml-encoded. """ request.node.warn( code='C3', message='record_xml_property is an experimental feature', ) xml = getattr(request.config, "_xml", None) if xml is not None: node_reporter = xml.node_reporter(request.node.nodeid) return node_reporter.add_property else: def add_property_noop(name, value): pass return add_property_noop def pytest_addoption(parser): group = parser.getgroup("terminal reporting") group.addoption( '--junitxml', '--junit-xml', action="store", dest="xmlpath", metavar="path", type=functools.partial(filename_arg, optname="--junitxml"), default=None, help="create junit-xml style report file at given path.") group.addoption( '--junitprefix', '--junit-prefix', action="store", metavar="str", default=None, help="prepend prefix to classnames in junit-xml output") parser.addini("junit_suite_name", "Test suite name for JUnit report", default="pytest") def pytest_configure(config): xmlpath = config.option.xmlpath # prevent opening xmllog on slave nodes (xdist) if xmlpath and not hasattr(config, 'slaveinput'): config._xml = LogXML(xmlpath, config.option.junitprefix, config.getini("junit_suite_name")) config.pluginmanager.register(config._xml) def pytest_unconfigure(config): xml = getattr(config, '_xml', None) if xml: del config._xml config.pluginmanager.unregister(xml) def mangle_test_address(address): path, possible_open_bracket, params = address.partition('[') names = path.split("::") try: names.remove('()') except ValueError: pass # convert file path to dotted path names[0] = names[0].replace(nodes.SEP, '.') names[0] = _py_ext_re.sub("", names[0]) # put any params back names[-1] += possible_open_bracket + params return names class LogXML(object): def __init__(self, logfile, prefix, suite_name="pytest"): logfile = os.path.expanduser(os.path.expandvars(logfile)) self.logfile = os.path.normpath(os.path.abspath(logfile)) self.prefix = prefix self.suite_name = suite_name self.stats = dict.fromkeys([ 'error', 'passed', 'failure', 'skipped', ], 0) self.node_reporters = {} # nodeid -> _NodeReporter self.node_reporters_ordered = [] self.global_properties = [] # List of reports that failed on call but teardown is pending. self.open_reports = [] self.cnt_double_fail_tests = 0 def finalize(self, report): nodeid = getattr(report, 'nodeid', report) # local hack to handle xdist report order slavenode = getattr(report, 'node', None) reporter = self.node_reporters.pop((nodeid, slavenode)) if reporter is not None: reporter.finalize() def node_reporter(self, report): nodeid = getattr(report, 'nodeid', report) # local hack to handle xdist report order slavenode = getattr(report, 'node', None) key = nodeid, slavenode if key in self.node_reporters: # TODO: breasks for --dist=each return self.node_reporters[key] reporter = _NodeReporter(nodeid, self) self.node_reporters[key] = reporter self.node_reporters_ordered.append(reporter) return reporter def add_stats(self, key): if key in self.stats: self.stats[key] += 1 def _opentestcase(self, report): reporter = self.node_reporter(report) reporter.record_testreport(report) return reporter def pytest_runtest_logreport(self, report): """handle a setup/call/teardown report, generating the appropriate xml tags as necessary. note: due to plugins like xdist, this hook may be called in interlaced order with reports from other nodes. for example: usual call order: -> setup node1 -> call node1 -> teardown node1 -> setup node2 -> call node2 -> teardown node2 possible call order in xdist: -> setup node1 -> call node1 -> setup node2 -> call node2 -> teardown node2 -> teardown node1 """ close_report = None if report.passed: if report.when == "call": # ignore setup/teardown reporter = self._opentestcase(report) reporter.append_pass(report) elif report.failed: if report.when == "teardown": # The following vars are needed when xdist plugin is used report_wid = getattr(report, "worker_id", None) report_ii = getattr(report, "item_index", None) close_report = next( (rep for rep in self.open_reports if (rep.nodeid == report.nodeid and getattr(rep, "item_index", None) == report_ii and getattr(rep, "worker_id", None) == report_wid ) ), None) if close_report: # We need to open new testcase in case we have failure in # call and error in teardown in order to follow junit # schema self.finalize(close_report) self.cnt_double_fail_tests += 1 reporter = self._opentestcase(report) if report.when == "call": reporter.append_failure(report) self.open_reports.append(report) else: reporter.append_error(report) elif report.skipped: reporter = self._opentestcase(report) reporter.append_skipped(report) self.update_testcase_duration(report) if report.when == "teardown": reporter = self._opentestcase(report) reporter.write_captured_output(report) self.finalize(report) report_wid = getattr(report, "worker_id", None) report_ii = getattr(report, "item_index", None) close_report = next( (rep for rep in self.open_reports if (rep.nodeid == report.nodeid and getattr(rep, "item_index", None) == report_ii and getattr(rep, "worker_id", None) == report_wid ) ), None) if close_report: self.open_reports.remove(close_report) def update_testcase_duration(self, report): """accumulates total duration for nodeid from given report and updates the Junit.testcase with the new total if already created. """ reporter = self.node_reporter(report) reporter.duration += getattr(report, 'duration', 0.0) def pytest_collectreport(self, report): if not report.passed: reporter = self._opentestcase(report) if report.failed: reporter.append_collect_error(report) else: reporter.append_collect_skipped(report) def pytest_internalerror(self, excrepr): reporter = self.node_reporter('internal') reporter.attrs.update(classname="pytest", name='internal') reporter._add_simple(Junit.error, 'internal error', excrepr) def pytest_sessionstart(self): self.suite_start_time = time.time() def pytest_sessionfinish(self): dirname = os.path.dirname(os.path.abspath(self.logfile)) if not os.path.isdir(dirname): os.makedirs(dirname) logfile = open(self.logfile, 'w', encoding='utf-8') suite_stop_time = time.time() suite_time_delta = suite_stop_time - self.suite_start_time numtests = (self.stats['passed'] + self.stats['failure'] + self.stats['skipped'] + self.stats['error'] - self.cnt_double_fail_tests) logfile.write('<?xml version="1.0" encoding="utf-8"?>') logfile.write(Junit.testsuite( self._get_global_properties_node(), [x.to_xml() for x in self.node_reporters_ordered], name=self.suite_name, errors=self.stats['error'], failures=self.stats['failure'], skips=self.stats['skipped'], tests=numtests, time="%.3f" % suite_time_delta, ).unicode(indent=0)) logfile.close() def pytest_terminal_summary(self, terminalreporter): terminalreporter.write_sep("-", "generated xml file: %s" % (self.logfile)) def add_global_property(self, name, value): self.global_properties.append((str(name), bin_xml_escape(value))) def _get_global_properties_node(self): """Return a Junit node containing custom properties, if any. """ if self.global_properties: return Junit.properties( [ Junit.property(name=name, value=value) for name, value in self.global_properties ] ) return ''
anthgur/servo
tests/wpt/web-platform-tests/tools/third_party/pytest/_pytest/junitxml.py
Python
mpl-2.0
15,681
/** * Copyright (c) 2016 hustcc * License: MIT * https://github.com/hustcc/timeago.js **/ /* jshint expr: true */ !function (root, factory) { if (typeof module === 'object' && module.exports) module.exports = factory(root); else root.timeago = factory(root); }(typeof window !== 'undefined' ? window : this, function () { var cnt = 0, // the timer counter, for timer key indexMapEn = ['second', 'minute', 'hour', 'day', 'week', 'month', 'year'], indexMapZh = ['秒', '分钟', '小时', '天', '周', '月', '年'], // build-in locales: en & zh_CN locales = { 'en': function(number, index) { if (index === 0) return ['just now', 'a while']; else { var unit = indexMapEn[parseInt(index / 2)]; if (number > 1) unit += 's'; return [number + ' ' + unit + ' ago', 'in ' + number + ' ' + unit]; } }, 'zh_CN': function(number, index) { if (index === 0) return ['刚刚', '片刻后']; else { var unit = indexMapZh[parseInt(index / 2)]; return [number + unit + '前', number + unit + '后']; } } }, // second, minute, hour, day, week, month, year(365 days) SEC_ARRAY = [60, 60, 24, 7, 365/7/12, 12], SEC_ARRAY_LEN = 6, ATTR_DATETIME = 'datetime'; /** * timeago: the function to get `timeago` instance. * - nowDate: the relative date, default is new Date(). * - defaultLocale: the default locale, default is en. if your set it, then the `locale` parameter of format is not needed of you. * * How to use it? * var timeagoLib = require('timeago.js'); * var timeago = timeagoLib(); // all use default. * var timeago = timeagoLib('2016-09-10'); // the relative date is 2016-09-10, so the 2016-09-11 will be 1 day ago. * var timeago = timeagoLib(null, 'zh_CN'); // set default locale is `zh_CN`. * var timeago = timeagoLib('2016-09-10', 'zh_CN'); // the relative date is 2016-09-10, and locale is zh_CN, so the 2016-09-11 will be 1天前. **/ function timeago(nowDate, defaultLocale) { var timers = {}; // real-time render timers // if do not set the defaultLocale, set it with `en` if (! defaultLocale) defaultLocale = 'en'; // use default build-in locale // calculate the diff second between date to be formated an now date. function diffSec(date) { var now = new Date(); if (nowDate) now = toDate(nowDate); return (now - toDate(date)) / 1000; } // format the diff second to *** time ago, with setting locale function formatDiff(diff, locale) { if (! locales[locale]) locale = defaultLocale; var i = 0; agoin = diff < 0 ? 1 : 0, // timein or timeago diff = Math.abs(diff); for (; diff >= SEC_ARRAY[i] && i < SEC_ARRAY_LEN; i++) { diff /= SEC_ARRAY[i]; } diff = toInt(diff); i *= 2; if (diff > (i === 0 ? 9 : 1)) i += 1; return locales[locale](diff, i)[agoin].replace('%s', diff); } /** * format: format the date to *** time ago, with setting or default locale * - date: the date / string / timestamp to be formated * - locale: the formated string's locale name, e.g. en / zh_CN * * How to use it? * var timeago = require('timeago.js')(); * timeago.format(new Date(), 'pl'); // Date instance * timeago.format('2016-09-10', 'fr'); // formated date string * timeago.format(1473473400269); // timestamp with ms **/ this.format = function(date, locale) { return formatDiff(diffSec(date), locale); }; // format Date / string / timestamp to Date instance. function toDate(input) { if (input instanceof Date) { return input; } else if (!isNaN(input)) { return new Date(toInt(input)); } else if (/^\d+$/.test(input)) { return new Date(toInt(input, 10)); } else { var s = (input || '').trim(); s = s.replace(/\.\d+/, '') // remove milliseconds .replace(/-/, '/').replace(/-/, '/') .replace(/T/, ' ').replace(/Z/, ' UTC') .replace(/([\+\-]\d\d)\:?(\d\d)/, ' $1$2'); // -04:00 -> -0400 return new Date(s); } } // change f into int, remove Decimal. just for code compression function toInt(f) { return parseInt(f); } // function leftSec(diff, unit) { // diff = diff % unit; // diff = diff ? unit - diff : unit; // return Math.ceil(diff); // } /** * nextInterval: calculate the next interval time. * - diff: the diff sec between now and date to be formated. * * What's the meaning? * diff = 61 then return 59 * diff = 3601 (an hour + 1 second), then return 3599 * make the interval with high performace. **/ // this.nextInterval = function(diff) { // for dev test function nextInterval(diff) { var rst = 1, i = 0, d = diff; for (; diff >= SEC_ARRAY[i] && i < SEC_ARRAY_LEN; i++) { diff /= SEC_ARRAY[i]; rst *= SEC_ARRAY[i]; } // return leftSec(d, rst); d = d % rst; d = d ? rst - d : rst; return Math.ceil(d); // }; // for dev test } // what the timer will do function doRender(node, date, locale, cnt) { var diff = diffSec(date); node.innerHTML = formatDiff(diff, locale); // waiting %s seconds, do the next render timers['k' + cnt] = setTimeout(function() { doRender(node, date, locale, cnt); }, nextInterval(diff) * 1000); } // get the datetime attribute, jQuery and DOM function getDateAttr(node) { if (node.getAttribute) return node.getAttribute(ATTR_DATETIME); if(node.attr) return node.attr(ATTR_DATETIME); } /** * render: render the DOM real-time. * - nodes: which nodes will be rendered. * - locale: the locale name used to format date. * * How to use it? * var timeago = new require('timeago.js')(); * // 1. javascript selector * timeago.render(document.querySelectorAll('.need_to_be_rendered')); * // 2. use jQuery selector * timeago.render($('.need_to_be_rendered'), 'pl'); * * Notice: please be sure the dom has attribute `datetime`. **/ this.render = function(nodes, locale) { if (nodes.length === undefined) nodes = [nodes]; for (var i = 0; i < nodes.length; i++) { doRender(nodes[i], getDateAttr(nodes[i]), locale, ++ cnt); // render item } }; /** * cancel: cancel all the timers which are doing real-time render. * * How to use it? * var timeago = new require('timeago.js')(); * timeago.render(document.querySelectorAll('.need_to_be_rendered')); * timeago.cancel(); // will stop all the timer, stop render in real time. **/ this.cancel = function() { for (var key in timers) { clearTimeout(timers[key]); } timers = {}; }; /** * setLocale: set the default locale name. * * How to use it? * var timeago = require('timeago.js'); * timeago = new timeago(); * timeago.setLocale('fr'); **/ this.setLocale = function(locale) { defaultLocale = locale; }; return this; } /** * timeago: the function to get `timeago` instance. * - nowDate: the relative date, default is new Date(). * - defaultLocale: the default locale, default is en. if your set it, then the `locale` parameter of format is not needed of you. * * How to use it? * var timeagoLib = require('timeago.js'); * var timeago = timeagoLib(); // all use default. * var timeago = timeagoLib('2016-09-10'); // the relative date is 2016-09-10, so the 2016-09-11 will be 1 day ago. * var timeago = timeagoLib(null, 'zh_CN'); // set default locale is `zh_CN`. * var timeago = timeagoLib('2016-09-10', 'zh_CN'); // the relative date is 2016-09-10, and locale is zh_CN, so the 2016-09-11 will be 1天前. **/ function timeagoFactory(nowDate, defaultLocale) { return new timeago(nowDate, defaultLocale); } /** * register: register a new language locale * - locale: locale name, e.g. en / zh_CN, notice the standard. * - localeFunc: the locale process function * * How to use it? * var timeagoLib = require('timeago.js'); * * timeagoLib.register('the locale name', the_locale_func); * // or * timeagoLib.register('pl', require('timeago.js/locales/pl')); **/ timeagoFactory.register = function(locale, localeFunc) { locales[locale] = localeFunc; }; return timeagoFactory; });
froala/cdnjs
ajax/libs/timeago.js/2.0.0/timeago.js
JavaScript
mit
8,824
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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. */ package com.intellij.usages.impl; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.util.text.StringUtil; import com.intellij.pom.Navigatable; import com.intellij.usages.Usage; import com.intellij.usages.UsageGroup; import com.intellij.usages.UsageView; import com.intellij.usages.rules.MergeableUsage; import com.intellij.util.Consumer; import com.intellij.util.SmartList; import gnu.trove.THashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.MutableTreeNode; import javax.swing.tree.TreeNode; import java.util.*; /** * @author max */ public class GroupNode extends Node implements Navigatable, Comparable<GroupNode> { private static final NodeComparator COMPARATOR = new NodeComparator(); private final Object lock = new Object(); private final UsageGroup myGroup; private final int myRuleIndex; private final Map<UsageGroup, GroupNode> mySubgroupNodes = new THashMap<UsageGroup, GroupNode>(); private final List<UsageNode> myUsageNodes = new SmartList<UsageNode>(); @NotNull private final UsageViewTreeModelBuilder myUsageTreeModel; private volatile int myRecursiveUsageCount = 0; public GroupNode(@Nullable UsageGroup group, int ruleIndex, @NotNull UsageViewTreeModelBuilder treeModel) { super(treeModel); myUsageTreeModel = treeModel; setUserObject(group); myGroup = group; myRuleIndex = ruleIndex; } @Override protected void updateNotify() { if (myGroup != null) { myGroup.update(); } } public String toString() { String result = ""; if (myGroup != null) result = myGroup.getText(null); if (children == null) { return result; } return result + children.subList(0, Math.min(10, children.size())).toString(); } public GroupNode addGroup(@NotNull UsageGroup group, int ruleIndex, @NotNull Consumer<Runnable> edtQueue) { synchronized (lock) { GroupNode node = mySubgroupNodes.get(group); if (node == null) { final GroupNode node1 = node = new GroupNode(group, ruleIndex, getBuilder()); mySubgroupNodes.put(group, node); addNode(node1, edtQueue); } return node; } } void addNode(@NotNull final DefaultMutableTreeNode node, @NotNull Consumer<Runnable> edtQueue) { if (!getBuilder().isDetachedMode()) { edtQueue.consume(new Runnable() { @Override public void run() { myTreeModel.insertNodeInto(node, GroupNode.this, getNodeInsertionIndex(node)); } }); } } private UsageViewTreeModelBuilder getBuilder() { return (UsageViewTreeModelBuilder)myTreeModel; } @Override public void removeAllChildren() { synchronized (lock) { ApplicationManager.getApplication().assertIsDispatchThread(); super.removeAllChildren(); mySubgroupNodes.clear(); myRecursiveUsageCount = 0; myUsageNodes.clear(); } myTreeModel.reload(this); } @Nullable UsageNode tryMerge(@NotNull Usage usage) { if (!(usage instanceof MergeableUsage)) return null; MergeableUsage mergeableUsage = (MergeableUsage)usage; for (UsageNode node : myUsageNodes) { Usage original = node.getUsage(); if (original == mergeableUsage) { // search returned duplicate usage, ignore return node; } if (original instanceof MergeableUsage) { if (((MergeableUsage)original).merge(mergeableUsage)) return node; } } return null; } public boolean removeUsage(@NotNull UsageNode usage) { ApplicationManager.getApplication().assertIsDispatchThread(); final Collection<GroupNode> groupNodes = mySubgroupNodes.values(); for(Iterator<GroupNode> iterator = groupNodes.iterator();iterator.hasNext();) { final GroupNode groupNode = iterator.next(); if(groupNode.removeUsage(usage)) { doUpdate(); if (groupNode.getRecursiveUsageCount() == 0) { myTreeModel.removeNodeFromParent(groupNode); iterator.remove(); } return true; } } boolean removed; synchronized (lock) { removed = myUsageNodes.remove(usage); } if (removed) { doUpdate(); return true; } return false; } public boolean removeUsagesBulk(@NotNull Set<UsageNode> usages) { boolean removed; synchronized (lock) { removed = myUsageNodes.removeAll(usages); } Collection<GroupNode> groupNodes = mySubgroupNodes.values(); for (Iterator<GroupNode> iterator = groupNodes.iterator(); iterator.hasNext(); ) { GroupNode groupNode = iterator.next(); if (groupNode.removeUsagesBulk(usages)) { if (groupNode.getRecursiveUsageCount() == 0) { MutableTreeNode parent = (MutableTreeNode)groupNode.getParent(); int childIndex = parent.getIndex(groupNode); if (childIndex != -1) { parent.remove(childIndex); } iterator.remove(); } removed = true; } } if (removed) { --myRecursiveUsageCount; } return removed; } private void doUpdate() { ApplicationManager.getApplication().assertIsDispatchThread(); --myRecursiveUsageCount; myTreeModel.nodeChanged(this); } public UsageNode addUsage(@NotNull Usage usage, @NotNull Consumer<Runnable> edtQueue) { final UsageNode node; synchronized (lock) { if (myUsageTreeModel.isFilterDuplicatedLine()) { UsageNode mergedWith = tryMerge(usage); if (mergedWith != null) { return mergedWith; } } node = new UsageNode(usage, getBuilder()); myUsageNodes.add(node); } if (!getBuilder().isDetachedMode()) { edtQueue.consume(new Runnable() { @Override public void run() { myTreeModel.insertNodeInto(node, GroupNode.this, getNodeIndex(node)); incrementUsageCount(); } }); } return node; } private int getNodeIndex(@NotNull UsageNode node) { int index = indexedBinarySearch(node); return index >= 0 ? index : -index-1; } private int indexedBinarySearch(@NotNull UsageNode key) { int low = 0; int high = getChildCount() - 1; while (low <= high) { int mid = (low + high) / 2; TreeNode treeNode = getChildAt(mid); int cmp; if (treeNode instanceof UsageNode) { UsageNode midVal = (UsageNode)treeNode; cmp = midVal.compareTo(key); } else { cmp = -1; } if (cmp < 0) { low = mid + 1; } else if (cmp > 0) { high = mid - 1; } else { return mid; // key found } } return -(low + 1); // key not found } private void incrementUsageCount() { GroupNode groupNode = this; while (true) { groupNode.myRecursiveUsageCount++; final GroupNode node = groupNode; myTreeModel.nodeChanged(node); TreeNode parent = groupNode.getParent(); if (!(parent instanceof GroupNode)) return; groupNode = (GroupNode)parent; } } @Override public String tree2string(int indent, String lineSeparator) { StringBuffer result = new StringBuffer(); StringUtil.repeatSymbol(result, ' ', indent); if (myGroup != null) result.append(myGroup.toString()); result.append("["); result.append(lineSeparator); Enumeration enumeration = children(); while (enumeration.hasMoreElements()) { Node node = (Node)enumeration.nextElement(); result.append(node.tree2string(indent + 4, lineSeparator)); result.append(lineSeparator); } StringUtil.repeatSymbol(result, ' ', indent); result.append("]"); result.append(lineSeparator); return result.toString(); } @Override protected boolean isDataValid() { return myGroup == null || myGroup.isValid(); } @Override protected boolean isDataReadOnly() { Enumeration enumeration = children(); while (enumeration.hasMoreElements()) { Object element = enumeration.nextElement(); if (element instanceof Node && ((Node)element).isReadOnly()) return true; } return false; } private int getNodeInsertionIndex(@NotNull DefaultMutableTreeNode node) { Enumeration children = children(); int idx = 0; while (children.hasMoreElements()) { DefaultMutableTreeNode child = (DefaultMutableTreeNode)children.nextElement(); if (COMPARATOR.compare(child, node) >= 0) break; idx++; } return idx; } private static class NodeComparator implements Comparator<DefaultMutableTreeNode> { private static int getClassIndex(DefaultMutableTreeNode node) { if (node instanceof UsageNode) return 3; if (node instanceof GroupNode) return 2; if (node instanceof UsageTargetNode) return 1; return 0; } @Override public int compare(DefaultMutableTreeNode n1, DefaultMutableTreeNode n2) { int classIdx1 = getClassIndex(n1); int classIdx2 = getClassIndex(n2); if (classIdx1 != classIdx2) return classIdx1 - classIdx2; if (classIdx1 == 2) return ((GroupNode)n1).compareTo((GroupNode)n2); return 0; } } @Override public int compareTo(@NotNull GroupNode groupNode) { if (myRuleIndex == groupNode.myRuleIndex) { return myGroup.compareTo(groupNode.myGroup); } return myRuleIndex - groupNode.myRuleIndex; } public UsageGroup getGroup() { return myGroup; } public int getRecursiveUsageCount() { return myRecursiveUsageCount; } @Override public void navigate(boolean requestFocus) { if (myGroup != null) { myGroup.navigate(requestFocus); } } @Override public boolean canNavigate() { return myGroup != null && myGroup.canNavigate(); } @Override public boolean canNavigateToSource() { return myGroup != null && myGroup.canNavigateToSource(); } @Override protected boolean isDataExcluded() { Enumeration enumeration = children(); while (enumeration.hasMoreElements()) { Node node = (Node)enumeration.nextElement(); if (!node.isExcluded()) return false; } return true; } @Override protected String getText(@NotNull UsageView view) { return myGroup.getText(view); } @NotNull public Collection<GroupNode> getSubGroups() { return mySubgroupNodes.values(); } @NotNull public Collection<UsageNode> getUsageNodes() { return myUsageNodes; } }
akosyakov/intellij-community
platform/usageView/src/com/intellij/usages/impl/GroupNode.java
Java
apache-2.0
11,143
package testclient import ( ktestclient "k8s.io/kubernetes/pkg/client/testclient" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/watch" templateapi "github.com/openshift/origin/pkg/template/api" ) // FakeTemplates implements TemplateInterface. Meant to be embedded into a struct to get a default // implementation. This makes faking out just the methods you want to test easier. type FakeTemplates struct { Fake *Fake Namespace string } func (c *FakeTemplates) Get(name string) (*templateapi.Template, error) { obj, err := c.Fake.Invokes(ktestclient.NewGetAction("templates", c.Namespace, name), &templateapi.Template{}) if obj == nil { return nil, err } return obj.(*templateapi.Template), err } func (c *FakeTemplates) List(label labels.Selector, field fields.Selector) (*templateapi.TemplateList, error) { obj, err := c.Fake.Invokes(ktestclient.NewListAction("templates", c.Namespace, label, field), &templateapi.TemplateList{}) if obj == nil { return nil, err } return obj.(*templateapi.TemplateList), err } func (c *FakeTemplates) Create(inObj *templateapi.Template) (*templateapi.Template, error) { obj, err := c.Fake.Invokes(ktestclient.NewCreateAction("templates", c.Namespace, inObj), inObj) if obj == nil { return nil, err } return obj.(*templateapi.Template), err } func (c *FakeTemplates) Update(inObj *templateapi.Template) (*templateapi.Template, error) { obj, err := c.Fake.Invokes(ktestclient.NewUpdateAction("templates", c.Namespace, inObj), inObj) if obj == nil { return nil, err } return obj.(*templateapi.Template), err } func (c *FakeTemplates) Delete(name string) error { _, err := c.Fake.Invokes(ktestclient.NewDeleteAction("templates", c.Namespace, name), &templateapi.Template{}) return err } func (c *FakeTemplates) Watch(label labels.Selector, field fields.Selector, resourceVersion string) (watch.Interface, error) { c.Fake.Invokes(ktestclient.NewWatchAction("templates", c.Namespace, label, field, resourceVersion), nil) return c.Fake.Watch, nil }
domenicbove/origin
pkg/client/testclient/fake_templates.go
GO
apache-2.0
2,068
package im.actor.model.api.rpc; /* * Generated by the Actor API Scheme generator. DO NOT EDIT! */ import im.actor.model.droidkit.bser.Bser; import im.actor.model.droidkit.bser.BserParser; import im.actor.model.droidkit.bser.BserObject; import im.actor.model.droidkit.bser.BserValues; import im.actor.model.droidkit.bser.BserWriter; import im.actor.model.droidkit.bser.DataInput; import im.actor.model.droidkit.bser.DataOutput; import im.actor.model.droidkit.bser.util.SparseArray; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.NotNull; import com.google.j2objc.annotations.ObjectiveCName; import static im.actor.model.droidkit.bser.Utils.*; import java.io.IOException; import im.actor.model.network.parser.*; import java.util.List; import java.util.ArrayList; import im.actor.model.api.*; public class RequestSendMessage extends Request<ResponseSeqDate> { public static final int HEADER = 0x5c; public static RequestSendMessage fromBytes(byte[] data) throws IOException { return Bser.parse(new RequestSendMessage(), data); } private OutPeer peer; private long rid; private Message message; public RequestSendMessage(@NotNull OutPeer peer, long rid, @NotNull Message message) { this.peer = peer; this.rid = rid; this.message = message; } public RequestSendMessage() { } @NotNull public OutPeer getPeer() { return this.peer; } public long getRid() { return this.rid; } @NotNull public Message getMessage() { return this.message; } @Override public void parse(BserValues values) throws IOException { this.peer = values.getObj(1, new OutPeer()); this.rid = values.getLong(3); this.message = Message.fromBytes(values.getBytes(4)); } @Override public void serialize(BserWriter writer) throws IOException { if (this.peer == null) { throw new IOException(); } writer.writeObject(1, this.peer); writer.writeLong(3, this.rid); if (this.message == null) { throw new IOException(); } writer.writeBytes(4, this.message.buildContainer()); } @Override public String toString() { String res = "rpc SendMessage{"; res += "peer=" + this.peer; res += ", rid=" + this.rid; res += ", message=" + this.message; res += "}"; return res; } @Override public int getHeaderKey() { return HEADER; } }
Rogerlin2013/actor-platform
actor-apps/core/src/main/java/im/actor/model/api/rpc/RequestSendMessage.java
Java
mit
2,557
require "spec_helper" describe Mongoid::Relations::Referenced::In do let(:person) do Person.create end describe "#=" do context "when the relation is named target" do let(:target) do User.new end context "when the relation is referenced from an embeds many" do context "when setting via create" do let(:service) do person.services.create(target: target) end it "sets the target relation" do service.target.should eq(target) end end end end context "when the inverse relation has no reference defined" do let(:agent) do Agent.new(title: "007") end let(:game) do Game.new(name: "Donkey Kong") end before do agent.game = game end it "sets the relation" do agent.game.should eq(game) end it "sets the foreign_key" do agent.game_id.should eq(game.id) end end context "when referencing a document from an embedded document" do let(:person) do Person.create end let(:address) do person.addresses.create(street: "Wienerstr") end let(:account) do Account.create(name: "1", number: 1000000) end before do address.account = account end it "sets the relation" do address.account.should eq(account) end it "does not erase the metadata" do address.metadata.should_not be_nil end it "allows saving of the embedded document" do address.save.should be_true end end context "when the parent is a references one" do context "when the relation is not polymorphic" do context "when the child is a new record" do let(:person) do Person.new end let(:game) do Game.new end before do game.person = person end it "sets the target of the relation" do game.person.target.should eq(person) end it "sets the foreign key on the relation" do game.person_id.should eq(person.id) end it "sets the base on the inverse relation" do person.game.should eq(game) end it "sets the same instance on the inverse relation" do person.game.should eql(game) end it "does not save the target" do person.should_not be_persisted end end context "when the child is not a new record" do let(:person) do Person.new end let(:game) do Game.create end before do game.person = person end it "sets the target of the relation" do game.person.target.should eq(person) end it "sets the foreign key of the relation" do game.person_id.should eq(person.id) end it "sets the base on the inverse relation" do person.game.should eq(game) end it "sets the same instance on the inverse relation" do person.game.should eql(game) end it "does not saves the target" do person.should_not be_persisted end end end context "when the relation is not polymorphic" do context "when the child is a new record" do let(:bar) do Bar.new end let(:rating) do Rating.new end before do rating.ratable = bar end it "sets the target of the relation" do rating.ratable.target.should eq(bar) end it "sets the foreign key on the relation" do rating.ratable_id.should eq(bar.id) end it "sets the base on the inverse relation" do bar.rating.should eq(rating) end it "sets the same instance on the inverse relation" do bar.rating.should eql(rating) end it "does not save the target" do bar.should_not be_persisted end end context "when the child is not a new record" do let(:bar) do Bar.new end let(:rating) do Rating.create end before do rating.ratable = bar end it "sets the target of the relation" do rating.ratable.target.should eq(bar) end it "sets the foreign key of the relation" do rating.ratable_id.should eq(bar.id) end it "sets the base on the inverse relation" do bar.rating.should eq(rating) end it "sets the same instance on the inverse relation" do bar.rating.should eql(rating) end it "does not saves the target" do bar.should_not be_persisted end end end end context "when the parent is a references many" do context "when the relation is not polymorphic" do context "when the child is a new record" do let(:person) do Person.new end let(:post) do Post.new end before do post.person = person end it "sets the target of the relation" do post.person.target.should eq(person) end it "sets the foreign key on the relation" do post.person_id.should eq(person.id) end it "does not save the target" do person.should_not be_persisted end end context "when the child is not a new record" do let(:person) do Person.new end let(:post) do Post.create end before do post.person = person end it "sets the target of the relation" do post.person.target.should eq(person) end it "sets the foreign key of the relation" do post.person_id.should eq(person.id) end it "does not saves the target" do person.should_not be_persisted end end end context "when the relation is polymorphic" do context "when multiple relations against the same class exist" do let(:face) do Face.new end let(:eye) do Eye.new end it "raises an error" do expect { eye.eyeable = face }.to raise_error(Mongoid::Errors::InvalidSetPolymorphicRelation) end end context "when one relation against the same class exists" do context "when the child is a new record" do let(:movie) do Movie.new end let(:rating) do Rating.new end before do rating.ratable = movie end it "sets the target of the relation" do rating.ratable.target.should eq(movie) end it "sets the foreign key on the relation" do rating.ratable_id.should eq(movie.id) end it "does not save the target" do movie.should_not be_persisted end end context "when the child is not a new record" do let(:movie) do Movie.new end let(:rating) do Rating.create end before do rating.ratable = movie end it "sets the target of the relation" do rating.ratable.target.should eq(movie) end it "sets the foreign key of the relation" do rating.ratable_id.should eq(movie.id) end it "does not saves the target" do movie.should_not be_persisted end end end end end end describe "#= nil" do context "when dependent is destroy" do let(:account) do Account.create end let(:drug) do Drug.create end let(:person) do Person.create end context "when relation is has_one" do before do Account.belongs_to :person, dependent: :destroy Person.has_one :account person.account = account person.save end after :all do Account.belongs_to :person, dependent: :nullify Person.has_one :account, validate: false end context "when parent exists" do context "when child is destroyed" do before do account.delete end it "deletes child" do account.should be_destroyed end it "deletes parent" do person.should be_destroyed end end end end context "when relation is has_many" do before do Drug.belongs_to :person, dependent: :destroy Person.has_many :drugs person.drugs = [drug] person.save end after :all do Drug.belongs_to :person, dependent: :nullify Person.has_many :drugs, validate: false end context "when parent exists" do context "when child is destroyed" do before do drug.delete end it "deletes child" do drug.should be_destroyed end it "deletes parent" do person.should be_destroyed end end end end end context "when dependent is delete" do let(:account) do Account.create end let(:drug) do Drug.create end let(:person) do Person.create end context "when relation is has_one" do before do Account.belongs_to :person, dependent: :delete Person.has_one :account person.account = account person.save end after :all do Account.belongs_to :person, dependent: :nullify Person.has_one :account, validate: false end context "when parent is persisted" do context "when child is deleted" do before do account.delete end it "deletes child" do account.should be_destroyed end it "deletes parent" do person.should be_destroyed end end end end context "when relation is has_many" do before do Drug.belongs_to :person, dependent: :delete Person.has_many :drugs person.drugs = [drug] person.save end after :all do Drug.belongs_to :person, dependent: :nullify Person.has_many :drugs, validate: false end context "when parent exists" do context "when child is destroyed" do before do drug.delete end it "deletes child" do drug.should be_destroyed end it "deletes parent" do person.should be_destroyed end end end end end context "when dependent is nullify" do let(:account) do Account.create end let(:drug) do Drug.create end let(:person) do Person.create end context "when relation is has_one" do before do Account.belongs_to :person, dependent: :nullify Person.has_one :account person.account = account person.save end context "when parent is persisted" do context "when child is deleted" do before do account.delete end it "deletes child" do account.should be_destroyed end it "doesn't delete parent" do person.should_not be_destroyed end it "removes the link" do person.account.should be_nil end end end end context "when relation is has_many" do before do Drug.belongs_to :person, dependent: :nullify Person.has_many :drugs person.drugs = [drug] person.save end context "when parent exists" do context "when child is destroyed" do before do drug.delete end it "deletes child" do drug.should be_destroyed end it "doesn't deletes parent" do person.should_not be_destroyed end it "removes the link" do person.drugs.should eq([]) end end end end end context "when the inverse relation has no reference defined" do let(:agent) do Agent.new(title: "007") end let(:game) do Game.new(name: "Donkey Kong") end before do agent.game = game agent.game = nil end it "removes the relation" do agent.game.should be_nil end it "removes the foreign_key" do agent.game_id.should be_nil end end context "when the parent is a references one" do context "when the relation is not polymorphic" do context "when the parent is a new record" do let(:person) do Person.new end let(:game) do Game.new end before do game.person = person game.person = nil end it "sets the relation to nil" do game.person.should be_nil end it "removed the inverse relation" do person.game.should be_nil end it "removes the foreign key value" do game.person_id.should be_nil end end context "when the parent is not a new record" do let(:person) do Person.create end let(:game) do Game.create end before do game.person = person game.person = nil end it "sets the relation to nil" do game.person.should be_nil end it "removed the inverse relation" do person.game.should be_nil end it "removes the foreign key value" do game.person_id.should be_nil end it "does not delete the child" do game.should_not be_destroyed end end end context "when the relation is polymorphic" do context "when multiple relations against the same class exist" do context "when the parent is a new record" do let(:face) do Face.new end let(:eye) do Eye.new end before do face.left_eye = eye eye.eyeable = nil end it "sets the relation to nil" do eye.eyeable.should be_nil end it "removed the inverse relation" do face.left_eye.should be_nil end it "removes the foreign key value" do eye.eyeable_id.should be_nil end end context "when the parent is not a new record" do let(:face) do Face.new end let(:eye) do Eye.create end before do face.left_eye = eye eye.eyeable = nil end it "sets the relation to nil" do eye.eyeable.should be_nil end it "removed the inverse relation" do face.left_eye.should be_nil end it "removes the foreign key value" do eye.eyeable_id.should be_nil end end end context "when one relation against the same class exists" do context "when the parent is a new record" do let(:bar) do Bar.new end let(:rating) do Rating.new end before do rating.ratable = bar rating.ratable = nil end it "sets the relation to nil" do rating.ratable.should be_nil end it "removed the inverse relation" do bar.rating.should be_nil end it "removes the foreign key value" do rating.ratable_id.should be_nil end end context "when the parent is not a new record" do let(:bar) do Bar.new end let(:rating) do Rating.create end before do rating.ratable = bar rating.ratable = nil end it "sets the relation to nil" do rating.ratable.should be_nil end it "removed the inverse relation" do bar.rating.should be_nil end it "removes the foreign key value" do rating.ratable_id.should be_nil end end end end end context "when the parent is a references many" do context "when the relation is not polymorphic" do context "when the parent is a new record" do let(:person) do Person.new end let(:post) do Post.new end before do post.person = person post.person = nil end it "sets the relation to nil" do post.person.should be_nil end it "removed the inverse relation" do person.posts.should be_empty end it "removes the foreign key value" do post.person_id.should be_nil end end context "when the parent is not a new record" do let(:person) do Person.new end let(:post) do Post.create end before do post.person = person post.person = nil end it "sets the relation to nil" do post.person.should be_nil end it "removed the inverse relation" do person.posts.should be_empty end it "removes the foreign key value" do post.person_id.should be_nil end end end context "when the relation is polymorphic" do context "when the parent is a new record" do let(:movie) do Movie.new end let(:rating) do Rating.new end before do rating.ratable = movie rating.ratable = nil end it "sets the relation to nil" do rating.ratable.should be_nil end it "removed the inverse relation" do movie.ratings.should be_empty end it "removes the foreign key value" do rating.ratable_id.should be_nil end end context "when the parent is not a new record" do let(:movie) do Movie.new end let(:rating) do Rating.create end before do rating.ratable = movie rating.ratable = nil end it "sets the relation to nil" do rating.ratable.should be_nil end it "removed the inverse relation" do movie.ratings.should be_empty end it "removes the foreign key value" do rating.ratable_id.should be_nil end end end end end describe ".builder" do let(:builder_klass) do Mongoid::Relations::Builders::Referenced::In end let(:document) do stub end let(:metadata) do stub(extension?: false) end it "returns the embedded in builder" do described_class.builder(nil, metadata, document).should be_a_kind_of(builder_klass) end end describe ".eager_load" do before do Mongoid.identity_map_enabled = true end after do Mongoid.identity_map_enabled = false end context "when the relation is not polymorphic" do let!(:person) do Person.create end let!(:post) do person.posts.create(title: "testing") end let(:metadata) do Post.relations["person"] end let(:eager) do described_class.eager_load(metadata, Post.all) end let!(:map) do Mongoid::IdentityMap.get(Person, person.id) end it "puts the document in the identity map" do map.should eq(person) end end context "when the relation is polymorphic" do let(:metadata) do Rating.relations["ratable"] end it "raises an error" do expect { described_class.eager_load(metadata, Rating.all) }.to raise_error(Mongoid::Errors::EagerLoad) end end context "when the ids has been duplicated" do let!(:person) do Person.create end let!(:posts) do 2.times {|i| person.posts.create(title: "testing#{i}") } person.posts end let(:metadata) do Post.relations["person"] end let(:eager) do described_class.eager_load(metadata, posts.map(&:person_id)) end it "duplication should be removed" do eager.count.should eq(1) end end end describe ".embedded?" do it "returns false" do described_class.should_not be_embedded end end describe ".foreign_key_suffix" do it "returns _id" do described_class.foreign_key_suffix.should eq("_id") end end describe ".macro" do it "returns belongs_to" do described_class.macro.should eq(:belongs_to) end end describe "#respond_to?" do let(:person) do Person.new end let(:game) do person.build_game(name: "Tron") end let(:document) do game.person end Mongoid::Document.public_instance_methods(true).each do |method| context "when checking #{method}" do it "returns true" do document.respond_to?(method).should be_true end end end end describe ".stores_foreign_key?" do it "returns true" do described_class.stores_foreign_key?.should be_true end end describe ".valid_options" do it "returns the valid options" do described_class.valid_options.should eq( [ :autobuild, :autosave, :dependent, :foreign_key, :index, :polymorphic, :touch ] ) end end describe ".validation_default" do it "returns false" do described_class.validation_default.should be_false end end context "when the relation is self referencing" do let(:game_one) do Game.new(name: "Diablo") end let(:game_two) do Game.new(name: "Warcraft") end context "when setting the parent" do before do game_one.parent = game_two end it "sets the parent" do game_one.parent.should eq(game_two) end it "does not set the parent recursively" do game_two.parent.should be_nil end end end context "when the relation belongs to a has many and has one" do before(:all) do class A include Mongoid::Document has_many :bs, inverse_of: :a end class B include Mongoid::Document belongs_to :a, inverse_of: :bs belongs_to :c, inverse_of: :b end class C include Mongoid::Document has_one :b, inverse_of: :c end end after(:all) do Object.send(:remove_const, :A) Object.send(:remove_const, :B) Object.send(:remove_const, :C) end context "when setting the has one" do let(:a) do A.new end let(:b) do B.new end let(:c) do C.new end before do b.c = c end context "when subsequently setting the has many" do before do b.a = a end context "when setting the has one again" do before do b.c = c end it "allows the reset of the has one" do b.c.should eq(c) end end end end end context "when replacing the relation with another" do let!(:person) do Person.create end let!(:post) do Post.create(title: "test") end let!(:game) do person.create_game(name: "Tron") end before do post.person = game.person post.save end it "clones the relation" do post.person.should eq(person) end it "sets the foreign key" do post.person_id.should eq(person.id) end it "does not remove the previous relation" do game.person.should eq(person) end it "does not remove the previous foreign key" do game.person_id.should eq(person.id) end context "when reloading" do before do post.reload game.reload end it "persists the relation" do post.reload.person.should eq(person) end it "persists the foreign key" do post.reload.person_id.should eq(game.person_id) end it "does not remove the previous relation" do game.person.should eq(person) end it "does not remove the previous foreign key" do game.person_id.should eq(person.id) end end end context "when the document belongs to a has one and has many" do let(:movie) do Movie.create(name: "Infernal Affairs") end let(:account) do Account.create(name: "Leung") end context "when creating the document" do let(:comment) do Comment.create(movie: movie, account: account) end it "sets the correct has one" do comment.account.should eq(account) end it "sets the correct has many" do comment.movie.should eq(movie) end end end context "when reloading the relation" do let!(:person_one) do Person.create end let!(:person_two) do Person.create(title: "Sir") end let!(:game) do Game.create(name: "Starcraft 2") end before do game.person = person_one game.save end context "when the relation references the same document" do before do Person.collection.find({ _id: person_one.id }). update({ "$set" => { title: "Madam" }}) end let(:reloaded) do game.person(true) end it "reloads the document from the database" do reloaded.title.should eq("Madam") end it "sets a new document instance" do reloaded.should_not equal(person_one) end end context "when the relation references a different document" do before do game.person_id = person_two.id game.save end let(:reloaded) do game.person(true) end it "reloads the new document from the database" do reloaded.title.should eq("Sir") end it "sets a new document instance" do reloaded.should_not equal(person_one) end end end context "when the parent and child are persisted" do context "when the identity map is enabled" do before do Mongoid.identity_map_enabled = true end after do Mongoid.identity_map_enabled = false end let(:series) do Series.create end let!(:book_one) do series.books.create end let!(:book_two) do series.books.create end let(:id) do Book.first.id end context "when asking for the inverse multiple times" do before do Book.find(id).series.books.to_a end it "does not append and save duplicate docs" do Book.find(id).series.books.to_a.length.should eq(2) end it "returns the same documents from the map" do Book.find(id).should equal(Book.find(id)) end end end end context "when creating with a reference to an integer id parent" do let!(:jar) do Jar.create do |doc| doc._id = 1 end end let(:cookie) do Cookie.create(jar_id: "1") end it "allows strings to be passed as the id" do cookie.jar.should eq(jar) end it "persists the relation" do cookie.reload.jar.should eq(jar) end end context "when setting the relation via the foreign key" do context "when the relation exists" do let!(:person_one) do Person.create end let!(:person_two) do Person.create end let!(:game) do Game.create(person: person_one) end before do game.person_id = person_two.id end it "sets the new document on the relation" do game.person.should eq(person_two) end end end end
peterwillcn/mongoid
spec/mongoid/relations/referenced/in_spec.rb
Ruby
mit
30,037
// 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 Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Globalization; using System.Security.Cryptography.X509Certificates; namespace System.Net.Security { internal static class CertificateValidation { private static readonly IdnMapping s_idnMapping = new IdnMapping(); internal static SslPolicyErrors BuildChainAndVerifyProperties(X509Chain chain, X509Certificate2 remoteCertificate, bool checkCertName, string hostName) { SslPolicyErrors errors = chain.Build(remoteCertificate) ? SslPolicyErrors.None : SslPolicyErrors.RemoteCertificateChainErrors; if (!checkCertName) { return errors; } if (string.IsNullOrEmpty(hostName)) { return errors | SslPolicyErrors.RemoteCertificateNameMismatch; } int hostNameMatch; using (SafeX509Handle certHandle = Interop.Crypto.X509UpRef(remoteCertificate.Handle)) { IPAddress hostnameAsIp; if (IPAddress.TryParse(hostName, out hostnameAsIp)) { byte[] addressBytes = hostnameAsIp.GetAddressBytes(); hostNameMatch = Interop.Crypto.CheckX509IpAddress(certHandle, addressBytes, addressBytes.Length, hostName, hostName.Length); } else { // The IdnMapping converts Unicode input into the IDNA punycode sequence. // It also does host case normalization. The bypass logic would be something // like "all characters being within [a-z0-9.-]+" string matchName = s_idnMapping.GetAscii(hostName); hostNameMatch = Interop.Crypto.CheckX509Hostname(certHandle, matchName, matchName.Length); } } Debug.Assert(hostNameMatch == 0 || hostNameMatch == 1, $"Expected 0 or 1 from CheckX509Hostname, got {hostNameMatch}"); return hostNameMatch == 1 ? errors : errors | SslPolicyErrors.RemoteCertificateNameMismatch; } } }
ptoonen/corefx
src/Common/src/System/Net/Security/CertificateValidation.Unix.cs
C#
mit
2,411
/* ------------------------------------------------------------------ * Copyright (C) 1998-2009 PacketVideo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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. * ------------------------------------------------------------------- */ /**************************************************************************************** Portions of this file are derived from the following 3GPP standard: 3GPP TS 26.173 ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec Available from http://www.3gpp.org (C) 2007, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC) Permission to distribute, modify and use this file under the standard license terms listed above has been obtained from the copyright holder. ****************************************************************************************/ #include "qisf_ns.h" /* * Tables for function q_gain2() * * g_pitch(Q14), g_code(Q11) * * pitch gain are ordered in table to reduce complexity * during quantization of gains. */ const int16 t_qua_gain6b[NB_QUA_GAIN6B*2] = { 1566, 1332, 1577, 3557, 3071, 6490, 4193, 10163, 4496, 2534, 5019, 4488, 5586, 15614, 5725, 1422, 6453, 580, 6724, 6831, 7657, 3527, 8072, 2099, 8232, 5319, 8827, 8775, 9740, 2868, 9856, 1465, 10087, 12488, 10241, 4453, 10859, 6618, 11321, 3587, 11417, 1800, 11643, 2428, 11718, 988, 12312, 5093, 12523, 8413, 12574, 26214, 12601, 3396, 13172, 1623, 13285, 2423, 13418, 6087, 13459, 12810, 13656, 3607, 14111, 4521, 14144, 1229, 14425, 1871, 14431, 7234, 14445, 2834, 14628, 10036, 14860, 17496, 15161, 3629, 15209, 5819, 15299, 2256, 15518, 4722, 15663, 1060, 15759, 7972, 15939, 11964, 16020, 2996, 16086, 1707, 16521, 4254, 16576, 6224, 16894, 2380, 16906, 681, 17213, 8406, 17610, 3418, 17895, 5269, 18168, 11748, 18230, 1575, 18607, 32767, 18728, 21684, 19137, 2543, 19422, 6577, 19446, 4097, 19450, 9056, 20371, 14885 }; const int16 t_qua_gain7b[NB_QUA_GAIN7B*2] = { 204, 441, 464, 1977, 869, 1077, 1072, 3062, 1281, 4759, 1647, 1539, 1845, 7020, 1853, 634, 1995, 2336, 2351, 15400, 2661, 1165, 2702, 3900, 2710, 10133, 3195, 1752, 3498, 2624, 3663, 849, 3984, 5697, 4214, 3399, 4415, 1304, 4695, 2056, 5376, 4558, 5386, 676, 5518, 23554, 5567, 7794, 5644, 3061, 5672, 1513, 5957, 2338, 6533, 1060, 6804, 5998, 6820, 1767, 6937, 3837, 7277, 414, 7305, 2665, 7466, 11304, 7942, 794, 8007, 1982, 8007, 1366, 8326, 3105, 8336, 4810, 8708, 7954, 8989, 2279, 9031, 1055, 9247, 3568, 9283, 1631, 9654, 6311, 9811, 2605, 10120, 683, 10143, 4179, 10245, 1946, 10335, 1218, 10468, 9960, 10651, 3000, 10951, 1530, 10969, 5290, 11203, 2305, 11325, 3562, 11771, 6754, 11839, 1849, 11941, 4495, 11954, 1298, 11975, 15223, 11977, 883, 11986, 2842, 12438, 2141, 12593, 3665, 12636, 8367, 12658, 1594, 12886, 2628, 12984, 4942, 13146, 1115, 13224, 524, 13341, 3163, 13399, 1923, 13549, 5961, 13606, 1401, 13655, 2399, 13782, 3909, 13868, 10923, 14226, 1723, 14232, 2939, 14278, 7528, 14439, 4598, 14451, 984, 14458, 2265, 14792, 1403, 14818, 3445, 14899, 5709, 15017, 15362, 15048, 1946, 15069, 2655, 15405, 9591, 15405, 4079, 15570, 7183, 15687, 2286, 15691, 1624, 15699, 3068, 15772, 5149, 15868, 1205, 15970, 696, 16249, 3584, 16338, 1917, 16424, 2560, 16483, 4438, 16529, 6410, 16620, 11966, 16839, 8780, 17030, 3050, 17033, 18325, 17092, 1568, 17123, 5197, 17351, 2113, 17374, 980, 17566, 26214, 17609, 3912, 17639, 32767, 18151, 7871, 18197, 2516, 18202, 5649, 18679, 3283, 18930, 1370, 19271, 13757, 19317, 4120, 19460, 1973, 19654, 10018, 19764, 6792, 19912, 5135, 20040, 2841, 21234, 19833 };
raj-bhatia/grooveip-ios-public
submodules/externals/opencore-amr/opencore/codecs_v2/audio/gsm_amr/amr_wb/dec/src/q_gain2_tab.cpp
C++
gpl-2.0
5,030
require 'will_paginate/core_ext' module WillPaginate # A mixin for ActiveRecord::Base. Provides +per_page+ class method # and hooks things up to provide paginating finders. # # Find out more in WillPaginate::Finder::ClassMethods # module Finder def self.included(base) base.extend ClassMethods class << base alias_method_chain :method_missing, :paginate # alias_method_chain :find_every, :paginate define_method(:per_page) { 30 } unless respond_to?(:per_page) end end # = Paginating finders for ActiveRecord models # # WillPaginate adds +paginate+, +per_page+ and other methods to # ActiveRecord::Base class methods and associations. It also hooks into # +method_missing+ to intercept pagination calls to dynamic finders such as # +paginate_by_user_id+ and translate them to ordinary finders # (+find_all_by_user_id+ in this case). # # In short, paginating finders are equivalent to ActiveRecord finders; the # only difference is that we start with "paginate" instead of "find" and # that <tt>:page</tt> is required parameter: # # @posts = Post.paginate :all, :page => params[:page], :order => 'created_at DESC' # # In paginating finders, "all" is implicit. There is no sense in paginating # a single record, right? So, you can drop the <tt>:all</tt> argument: # # Post.paginate(...) => Post.find :all # Post.paginate_all_by_something => Post.find_all_by_something # Post.paginate_by_something => Post.find_all_by_something # # == The importance of the <tt>:order</tt> parameter # # In ActiveRecord finders, <tt>:order</tt> parameter specifies columns for # the <tt>ORDER BY</tt> clause in SQL. It is important to have it, since # pagination only makes sense with ordered sets. Without the <tt>ORDER # BY</tt> clause, databases aren't required to do consistent ordering when # performing <tt>SELECT</tt> queries; this is especially true for # PostgreSQL. # # Therefore, make sure you are doing ordering on a column that makes the # most sense in the current context. Make that obvious to the user, also. # For perfomance reasons you will also want to add an index to that column. module ClassMethods # This is the main paginating finder. # # == Special parameters for paginating finders # * <tt>:page</tt> -- REQUIRED, but defaults to 1 if false or nil # * <tt>:per_page</tt> -- defaults to <tt>CurrentModel.per_page</tt> (which is 30 if not overridden) # * <tt>:total_entries</tt> -- use only if you manually count total entries # * <tt>:count</tt> -- additional options that are passed on to +count+ # * <tt>:finder</tt> -- name of the ActiveRecord finder used (default: "find") # # All other options (+conditions+, +order+, ...) are forwarded to +find+ # and +count+ calls. def paginate(*args, &block) options = args.pop page, per_page, total_entries = wp_parse_options(options) finder = (options[:finder] || 'find').to_s if finder == 'find' # an array of IDs may have been given: total_entries ||= (Array === args.first and args.first.size) # :all is implicit args.unshift(:all) if args.empty? end WillPaginate::Collection.create(page, per_page, total_entries) do |pager| count_options = options.except :page, :per_page, :total_entries, :finder find_options = count_options.except(:count).update(:offset => pager.offset, :limit => pager.per_page) args << find_options # @options_from_last_find = nil pager.replace send(finder, *args, &block) # magic counting for user convenience: pager.total_entries = wp_count(count_options, args, finder) unless pager.total_entries end end # Iterates through all records by loading one page at a time. This is useful # for migrations or any other use case where you don't want to load all the # records in memory at once. # # It uses +paginate+ internally; therefore it accepts all of its options. # You can specify a starting page with <tt>:page</tt> (default is 1). Default # <tt>:order</tt> is <tt>"id"</tt>, override if necessary. # # See http://weblog.jamisbuck.org/2007/4/6/faking-cursors-in-activerecord where # Jamis Buck describes this and also uses a more efficient way for MySQL. def paginated_each(options = {}, &block) options = { :order => 'id', :page => 1 }.merge options options[:page] = options[:page].to_i options[:total_entries] = 0 # skip the individual count queries total = 0 begin collection = paginate(options) total += collection.each(&block).size options[:page] += 1 end until collection.size < collection.per_page total end # Wraps +find_by_sql+ by simply adding LIMIT and OFFSET to your SQL string # based on the params otherwise used by paginating finds: +page+ and # +per_page+. # # Example: # # @developers = Developer.paginate_by_sql ['select * from developers where salary > ?', 80000], # :page => params[:page], :per_page => 3 # # A query for counting rows will automatically be generated if you don't # supply <tt>:total_entries</tt>. If you experience problems with this # generated SQL, you might want to perform the count manually in your # application. # def paginate_by_sql(sql, options) WillPaginate::Collection.create(*wp_parse_options(options)) do |pager| query = sanitize_sql(sql) original_query = query.dup # add limit, offset add_limit! query, :offset => pager.offset, :limit => pager.per_page # perfom the find pager.replace find_by_sql(query) unless pager.total_entries count_query = original_query.sub /\bORDER\s+BY\s+[\w`,\s]+$/mi, '' count_query = "SELECT COUNT(*) FROM (#{count_query})" unless ['oracle', 'oci'].include?(self.connection.adapter_name.downcase) count_query << ' AS count_table' end # perform the count query pager.total_entries = count_by_sql(count_query) end end end def respond_to?(method, include_priv = false) #:nodoc: case method.to_sym when :paginate, :paginate_by_sql true else super(method.to_s.sub(/^paginate/, 'find'), include_priv) end end protected def method_missing_with_paginate(method, *args, &block) #:nodoc: # did somebody tried to paginate? if not, let them be unless method.to_s.index('paginate') == 0 return method_missing_without_paginate(method, *args, &block) end # paginate finders are really just find_* with limit and offset finder = method.to_s.sub('paginate', 'find') finder.sub!('find', 'find_all') if finder.index('find_by_') == 0 options = args.pop raise ArgumentError, 'parameter hash expected' unless options.respond_to? :symbolize_keys options = options.dup options[:finder] = finder args << options paginate(*args, &block) end # Does the not-so-trivial job of finding out the total number of entries # in the database. It relies on the ActiveRecord +count+ method. def wp_count(options, args, finder) excludees = [:count, :order, :limit, :offset, :readonly] unless options[:select] and options[:select] =~ /^\s*DISTINCT\b/i excludees << :select # only exclude the select param if it doesn't begin with DISTINCT end # count expects (almost) the same options as find count_options = options.except *excludees # merge the hash found in :count # this allows you to specify :select, :order, or anything else just for the count query count_options.update options[:count] if options[:count] # we may be in a model or an association proxy klass = (@owner and @reflection) ? @reflection.klass : self # forget about includes if they are irrelevant (Rails 2.1) if count_options[:include] and klass.private_methods.include?('references_eager_loaded_tables?') and !klass.send(:references_eager_loaded_tables?, count_options) count_options.delete :include end # we may have to scope ... counter = Proc.new { count(count_options) } count = if finder.index('find_') == 0 and klass.respond_to?(scoper = finder.sub('find', 'with')) # scope_out adds a 'with_finder' method which acts like with_scope, if it's present # then execute the count with the scoping provided by the with_finder send(scoper, &counter) elsif match = /^find_(all_by|by)_([_a-zA-Z]\w*)$/.match(finder) # extract conditions from calls like "paginate_by_foo_and_bar" attribute_names = extract_attribute_names_from_match(match) conditions = construct_attributes_from_arguments(attribute_names, args) with_scope(:find => { :conditions => conditions }, &counter) else counter.call end count.respond_to?(:length) ? count.length : count end def wp_parse_options(options) #:nodoc: raise ArgumentError, 'parameter hash expected' unless options.respond_to? :symbolize_keys options = options.symbolize_keys raise ArgumentError, ':page parameter required' unless options.key? :page if options[:count] and options[:total_entries] raise ArgumentError, ':count and :total_entries are mutually exclusive' end page = options[:page] || 1 per_page = options[:per_page] || self.per_page total = options[:total_entries] [page, per_page, total] end private # def find_every_with_paginate(options) # @options_from_last_find = options # find_every_without_paginate(options) # end end end end
gkneighb/insoshi
vendor/plugins/will_paginate/lib/will_paginate/finder.rb
Ruby
agpl-3.0
10,582
// // basic_serial_port.hpp // ~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) // Copyright (c) 2008 Rep Invariant Systems, Inc. (info@repinvariant.com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef ASIO_BASIC_SERIAL_PORT_HPP #define ASIO_BASIC_SERIAL_PORT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_SERIAL_PORT) \ || defined(GENERATING_DOCUMENTATION) #include <string> #include "asio/basic_io_object.hpp" #include "asio/detail/handler_type_requirements.hpp" #include "asio/detail/throw_error.hpp" #include "asio/error.hpp" #include "asio/serial_port_base.hpp" #include "asio/serial_port_service.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// Provides serial port functionality. /** * The basic_serial_port class template provides functionality that is common * to all serial ports. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. */ template <typename SerialPortService = serial_port_service> class basic_serial_port : public basic_io_object<SerialPortService>, public serial_port_base { public: /// (Deprecated: Use native_handle_type.) The native representation of a /// serial port. typedef typename SerialPortService::native_handle_type native_type; /// The native representation of a serial port. typedef typename SerialPortService::native_handle_type native_handle_type; /// A basic_serial_port is always the lowest layer. typedef basic_serial_port<SerialPortService> lowest_layer_type; /// Construct a basic_serial_port without opening it. /** * This constructor creates a serial port without opening it. * * @param io_service The io_service object that the serial port will use to * dispatch handlers for any asynchronous operations performed on the port. */ explicit basic_serial_port(asio::io_service& io_service) : basic_io_object<SerialPortService>(io_service) { } /// Construct and open a basic_serial_port. /** * This constructor creates and opens a serial port for the specified device * name. * * @param io_service The io_service object that the serial port will use to * dispatch handlers for any asynchronous operations performed on the port. * * @param device The platform-specific device name for this serial * port. */ explicit basic_serial_port(asio::io_service& io_service, const char* device) : basic_io_object<SerialPortService>(io_service) { asio::error_code ec; this->get_service().open(this->get_implementation(), device, ec); asio::detail::throw_error(ec, "open"); } /// Construct and open a basic_serial_port. /** * This constructor creates and opens a serial port for the specified device * name. * * @param io_service The io_service object that the serial port will use to * dispatch handlers for any asynchronous operations performed on the port. * * @param device The platform-specific device name for this serial * port. */ explicit basic_serial_port(asio::io_service& io_service, const std::string& device) : basic_io_object<SerialPortService>(io_service) { asio::error_code ec; this->get_service().open(this->get_implementation(), device, ec); asio::detail::throw_error(ec, "open"); } /// Construct a basic_serial_port on an existing native serial port. /** * This constructor creates a serial port object to hold an existing native * serial port. * * @param io_service The io_service object that the serial port will use to * dispatch handlers for any asynchronous operations performed on the port. * * @param native_serial_port A native serial port. * * @throws asio::system_error Thrown on failure. */ basic_serial_port(asio::io_service& io_service, const native_handle_type& native_serial_port) : basic_io_object<SerialPortService>(io_service) { asio::error_code ec; this->get_service().assign(this->get_implementation(), native_serial_port, ec); asio::detail::throw_error(ec, "assign"); } #if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) /// Move-construct a basic_serial_port from another. /** * This constructor moves a serial port from one object to another. * * @param other The other basic_serial_port object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_serial_port(io_service&) constructor. */ basic_serial_port(basic_serial_port&& other) : basic_io_object<SerialPortService>( ASIO_MOVE_CAST(basic_serial_port)(other)) { } /// Move-assign a basic_serial_port from another. /** * This assignment operator moves a serial port from one object to another. * * @param other The other basic_serial_port object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_serial_port(io_service&) constructor. */ basic_serial_port& operator=(basic_serial_port&& other) { basic_io_object<SerialPortService>::operator=( ASIO_MOVE_CAST(basic_serial_port)(other)); return *this; } #endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) /// Get a reference to the lowest layer. /** * This function returns a reference to the lowest layer in a stack of * layers. Since a basic_serial_port cannot contain any further layers, it * simply returns a reference to itself. * * @return A reference to the lowest layer in the stack of layers. Ownership * is not transferred to the caller. */ lowest_layer_type& lowest_layer() { return *this; } /// Get a const reference to the lowest layer. /** * This function returns a const reference to the lowest layer in a stack of * layers. Since a basic_serial_port cannot contain any further layers, it * simply returns a reference to itself. * * @return A const reference to the lowest layer in the stack of layers. * Ownership is not transferred to the caller. */ const lowest_layer_type& lowest_layer() const { return *this; } /// Open the serial port using the specified device name. /** * This function opens the serial port for the specified device name. * * @param device The platform-specific device name. * * @throws asio::system_error Thrown on failure. */ void open(const std::string& device) { asio::error_code ec; this->get_service().open(this->get_implementation(), device, ec); asio::detail::throw_error(ec, "open"); } /// Open the serial port using the specified device name. /** * This function opens the serial port using the given platform-specific * device name. * * @param device The platform-specific device name. * * @param ec Set the indicate what error occurred, if any. */ asio::error_code open(const std::string& device, asio::error_code& ec) { return this->get_service().open(this->get_implementation(), device, ec); } /// Assign an existing native serial port to the serial port. /* * This function opens the serial port to hold an existing native serial port. * * @param native_serial_port A native serial port. * * @throws asio::system_error Thrown on failure. */ void assign(const native_handle_type& native_serial_port) { asio::error_code ec; this->get_service().assign(this->get_implementation(), native_serial_port, ec); asio::detail::throw_error(ec, "assign"); } /// Assign an existing native serial port to the serial port. /* * This function opens the serial port to hold an existing native serial port. * * @param native_serial_port A native serial port. * * @param ec Set to indicate what error occurred, if any. */ asio::error_code assign(const native_handle_type& native_serial_port, asio::error_code& ec) { return this->get_service().assign(this->get_implementation(), native_serial_port, ec); } /// Determine whether the serial port is open. bool is_open() const { return this->get_service().is_open(this->get_implementation()); } /// Close the serial port. /** * This function is used to close the serial port. Any asynchronous read or * write operations will be cancelled immediately, and will complete with the * asio::error::operation_aborted error. * * @throws asio::system_error Thrown on failure. */ void close() { asio::error_code ec; this->get_service().close(this->get_implementation(), ec); asio::detail::throw_error(ec, "close"); } /// Close the serial port. /** * This function is used to close the serial port. Any asynchronous read or * write operations will be cancelled immediately, and will complete with the * asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. */ asio::error_code close(asio::error_code& ec) { return this->get_service().close(this->get_implementation(), ec); } /// (Deprecated: Use native_handle().) Get the native serial port /// representation. /** * This function may be used to obtain the underlying representation of the * serial port. This is intended to allow access to native serial port * functionality that is not otherwise provided. */ native_type native() { return this->get_service().native_handle(this->get_implementation()); } /// Get the native serial port representation. /** * This function may be used to obtain the underlying representation of the * serial port. This is intended to allow access to native serial port * functionality that is not otherwise provided. */ native_handle_type native_handle() { return this->get_service().native_handle(this->get_implementation()); } /// Cancel all asynchronous operations associated with the serial port. /** * This function causes all outstanding asynchronous read or write operations * to finish immediately, and the handlers for cancelled operations will be * passed the asio::error::operation_aborted error. * * @throws asio::system_error Thrown on failure. */ void cancel() { asio::error_code ec; this->get_service().cancel(this->get_implementation(), ec); asio::detail::throw_error(ec, "cancel"); } /// Cancel all asynchronous operations associated with the serial port. /** * This function causes all outstanding asynchronous read or write operations * to finish immediately, and the handlers for cancelled operations will be * passed the asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. */ asio::error_code cancel(asio::error_code& ec) { return this->get_service().cancel(this->get_implementation(), ec); } /// Send a break sequence to the serial port. /** * This function causes a break sequence of platform-specific duration to be * sent out the serial port. * * @throws asio::system_error Thrown on failure. */ void send_break() { asio::error_code ec; this->get_service().send_break(this->get_implementation(), ec); asio::detail::throw_error(ec, "send_break"); } /// Send a break sequence to the serial port. /** * This function causes a break sequence of platform-specific duration to be * sent out the serial port. * * @param ec Set to indicate what error occurred, if any. */ asio::error_code send_break(asio::error_code& ec) { return this->get_service().send_break(this->get_implementation(), ec); } /// Set an option on the serial port. /** * This function is used to set an option on the serial port. * * @param option The option value to be set on the serial port. * * @throws asio::system_error Thrown on failure. * * @sa SettableSerialPortOption @n * asio::serial_port_base::baud_rate @n * asio::serial_port_base::flow_control @n * asio::serial_port_base::parity @n * asio::serial_port_base::stop_bits @n * asio::serial_port_base::character_size */ template <typename SettableSerialPortOption> void set_option(const SettableSerialPortOption& option) { asio::error_code ec; this->get_service().set_option(this->get_implementation(), option, ec); asio::detail::throw_error(ec, "set_option"); } /// Set an option on the serial port. /** * This function is used to set an option on the serial port. * * @param option The option value to be set on the serial port. * * @param ec Set to indicate what error occurred, if any. * * @sa SettableSerialPortOption @n * asio::serial_port_base::baud_rate @n * asio::serial_port_base::flow_control @n * asio::serial_port_base::parity @n * asio::serial_port_base::stop_bits @n * asio::serial_port_base::character_size */ template <typename SettableSerialPortOption> asio::error_code set_option(const SettableSerialPortOption& option, asio::error_code& ec) { return this->get_service().set_option( this->get_implementation(), option, ec); } /// Get an option from the serial port. /** * This function is used to get the current value of an option on the serial * port. * * @param option The option value to be obtained from the serial port. * * @throws asio::system_error Thrown on failure. * * @sa GettableSerialPortOption @n * asio::serial_port_base::baud_rate @n * asio::serial_port_base::flow_control @n * asio::serial_port_base::parity @n * asio::serial_port_base::stop_bits @n * asio::serial_port_base::character_size */ template <typename GettableSerialPortOption> void get_option(GettableSerialPortOption& option) { asio::error_code ec; this->get_service().get_option(this->get_implementation(), option, ec); asio::detail::throw_error(ec, "get_option"); } /// Get an option from the serial port. /** * This function is used to get the current value of an option on the serial * port. * * @param option The option value to be obtained from the serial port. * * @param ec Set to indicate what error occured, if any. * * @sa GettableSerialPortOption @n * asio::serial_port_base::baud_rate @n * asio::serial_port_base::flow_control @n * asio::serial_port_base::parity @n * asio::serial_port_base::stop_bits @n * asio::serial_port_base::character_size */ template <typename GettableSerialPortOption> asio::error_code get_option(GettableSerialPortOption& option, asio::error_code& ec) { return this->get_service().get_option( this->get_implementation(), option, ec); } /// Write some data to the serial port. /** * This function is used to write data to the serial port. The function call * will block until one or more bytes of the data has been written * successfully, or until an error occurs. * * @param buffers One or more data buffers to be written to the serial port. * * @returns The number of bytes written. * * @throws asio::system_error Thrown on failure. An error code of * asio::error::eof indicates that the connection was closed by the * peer. * * @note The write_some operation may not transmit all of the data to the * peer. Consider using the @ref write function if you need to ensure that * all data is written before the blocking operation completes. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * serial_port.write_some(asio::buffer(data, size)); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers) { asio::error_code ec; std::size_t s = this->get_service().write_some( this->get_implementation(), buffers, ec); asio::detail::throw_error(ec, "write_some"); return s; } /// Write some data to the serial port. /** * This function is used to write data to the serial port. The function call * will block until one or more bytes of the data has been written * successfully, or until an error occurs. * * @param buffers One or more data buffers to be written to the serial port. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes written. Returns 0 if an error occurred. * * @note The write_some operation may not transmit all of the data to the * peer. Consider using the @ref write function if you need to ensure that * all data is written before the blocking operation completes. */ template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers, asio::error_code& ec) { return this->get_service().write_some( this->get_implementation(), buffers, ec); } /// Start an asynchronous write. /** * This function is used to asynchronously write data to the serial port. * The function call always returns immediately. * * @param buffers One or more data buffers to be written to the serial port. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the handler is called. * * @param handler The handler to be called when the write operation completes. * Copies will be made of the handler as required. The function signature of * the handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes written. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation * of the handler will be performed in a manner equivalent to using * asio::io_service::post(). * * @note The write operation may not transmit all of the data to the peer. * Consider using the @ref async_write function if you need to ensure that all * data is written before the asynchronous operation completes. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * serial_port.async_write_some(asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence, typename WriteHandler> ASIO_INITFN_RESULT_TYPE(WriteHandler, void (asio::error_code, std::size_t)) async_write_some(const ConstBufferSequence& buffers, ASIO_MOVE_ARG(WriteHandler) handler) { // If you get an error on the following line it means that your handler does // not meet the documented type requirements for a WriteHandler. ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; return this->get_service().async_write_some(this->get_implementation(), buffers, ASIO_MOVE_CAST(WriteHandler)(handler)); } /// Read some data from the serial port. /** * This function is used to read data from the serial port. The function * call will block until one or more bytes of data has been read successfully, * or until an error occurs. * * @param buffers One or more buffers into which the data will be read. * * @returns The number of bytes read. * * @throws asio::system_error Thrown on failure. An error code of * asio::error::eof indicates that the connection was closed by the * peer. * * @note The read_some operation may not read all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that * the requested amount of data is read before the blocking operation * completes. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * serial_port.read_some(asio::buffer(data, size)); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers) { asio::error_code ec; std::size_t s = this->get_service().read_some( this->get_implementation(), buffers, ec); asio::detail::throw_error(ec, "read_some"); return s; } /// Read some data from the serial port. /** * This function is used to read data from the serial port. The function * call will block until one or more bytes of data has been read successfully, * or until an error occurs. * * @param buffers One or more buffers into which the data will be read. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes read. Returns 0 if an error occurred. * * @note The read_some operation may not read all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that * the requested amount of data is read before the blocking operation * completes. */ template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers, asio::error_code& ec) { return this->get_service().read_some( this->get_implementation(), buffers, ec); } /// Start an asynchronous read. /** * This function is used to asynchronously read data from the serial port. * The function call always returns immediately. * * @param buffers One or more buffers into which the data will be read. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the handler is called. * * @param handler The handler to be called when the read operation completes. * Copies will be made of the handler as required. The function signature of * the handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes read. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation * of the handler will be performed in a manner equivalent to using * asio::io_service::post(). * * @note The read operation may not read all of the requested number of bytes. * Consider using the @ref async_read function if you need to ensure that the * requested amount of data is read before the asynchronous operation * completes. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * serial_port.async_read_some(asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence, typename ReadHandler> ASIO_INITFN_RESULT_TYPE(ReadHandler, void (asio::error_code, std::size_t)) async_read_some(const MutableBufferSequence& buffers, ASIO_MOVE_ARG(ReadHandler) handler) { // If you get an error on the following line it means that your handler does // not meet the documented type requirements for a ReadHandler. ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; return this->get_service().async_read_some(this->get_implementation(), buffers, ASIO_MOVE_CAST(ReadHandler)(handler)); } }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // defined(ASIO_HAS_SERIAL_PORT) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_BASIC_SERIAL_PORT_HPP
julien3/vertxbuspp
vertxbuspp/asio/include/asio/basic_serial_port.hpp
C++
apache-2.0
24,579
/** * 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. */ package org.apache.camel.test.spring; import org.apache.camel.management.JmxSystemPropertyKeys; import org.apache.camel.spring.SpringCamelContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigUtils; import org.springframework.test.context.MergedContextConfiguration; import org.springframework.test.context.support.DelegatingSmartContextLoader; /** * CamelSpringDelegatingTestContextLoader which fixes issues in Camel's JavaConfigContextLoader. (adds support for Camel's test annotations) * <br> * <em>This loader can handle either classes or locations for configuring the context.</em> * <br> * NOTE: This TestContextLoader doesn't support the annotation of ExcludeRoutes now. */ public class CamelSpringDelegatingTestContextLoader extends DelegatingSmartContextLoader { protected final Logger logger = LoggerFactory.getLogger(getClass()); @Override public ApplicationContext loadContext(MergedContextConfiguration mergedConfig) throws Exception { Class<?> testClass = getTestClass(); if (logger.isDebugEnabled()) { logger.debug("Loading ApplicationContext for merged context configuration [{}].", mergedConfig); } // Pre CamelContext(s) instantiation setup CamelAnnotationsHandler.handleDisableJmx(null, testClass); try { SpringCamelContext.setNoStart(true); System.setProperty("skipStartingCamelContext", "true"); ConfigurableApplicationContext context = (ConfigurableApplicationContext) super.loadContext(mergedConfig); SpringCamelContext.setNoStart(false); System.clearProperty("skipStartingCamelContext"); return loadContext(context, testClass); } finally { cleanup(testClass); } } /** * Performs the bulk of the Spring application context loading/customization. * * @param context the partially configured context. The context should have the bean definitions loaded, but nothing else. * @param testClass the test class being executed * @return the initialized (refreshed) Spring application context * * @throws Exception if there is an error during initialization/customization */ public ApplicationContext loadContext(ConfigurableApplicationContext context, Class<?> testClass) throws Exception { AnnotationConfigUtils.registerAnnotationConfigProcessors((BeanDefinitionRegistry) context); // Post CamelContext(s) instantiation but pre CamelContext(s) start setup CamelAnnotationsHandler.handleProvidesBreakpoint(context, testClass); CamelAnnotationsHandler.handleShutdownTimeout(context, testClass); CamelAnnotationsHandler.handleMockEndpoints(context, testClass); CamelAnnotationsHandler.handleMockEndpointsAndSkip(context, testClass); CamelAnnotationsHandler.handleUseOverridePropertiesWithPropertiesComponent(context, testClass); // CamelContext(s) startup CamelAnnotationsHandler.handleCamelContextStartup(context, testClass); return context; } /** * Cleanup/restore global state to defaults / pre-test values after the test setup * is complete. * * @param testClass the test class being executed */ protected void cleanup(Class<?> testClass) { SpringCamelContext.setNoStart(false); if (testClass.isAnnotationPresent(DisableJmx.class)) { if (CamelSpringTestHelper.getOriginalJmxDisabled() == null) { System.clearProperty(JmxSystemPropertyKeys.DISABLED); } else { System.setProperty(JmxSystemPropertyKeys.DISABLED, CamelSpringTestHelper.getOriginalJmxDisabled()); } } } /** * Returns the class under test in order to enable inspection of annotations while the * Spring context is being created. * * @return the test class that is being executed * @see CamelSpringTestHelper */ protected Class<?> getTestClass() { return CamelSpringTestHelper.getTestClass(); } }
jmandawg/camel
components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringDelegatingTestContextLoader.java
Java
apache-2.0
5,252
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See the LICENSE file in builder/azure for license information. package arm import ( "golang.org/x/crypto/ssh" "testing" ) func TestFart(t *testing.T) { } func TestAuthorizedKeyShouldParse(t *testing.T) { testSubject, err := NewOpenSshKeyPairWithSize(512) if err != nil { t.Fatalf("Failed to create a new OpenSSH key pair, err=%s.", err) } authorizedKey := testSubject.AuthorizedKey() _, _, _, _, err = ssh.ParseAuthorizedKey([]byte(authorizedKey)) if err != nil { t.Fatalf("Failed to parse the authorized key, err=%s", err) } } func TestPrivateKeyShouldParse(t *testing.T) { testSubject, err := NewOpenSshKeyPairWithSize(512) if err != nil { t.Fatalf("Failed to create a new OpenSSH key pair, err=%s.", err) } _, err = ssh.ParsePrivateKey([]byte(testSubject.PrivateKey())) if err != nil { t.Fatalf("Failed to parse the private key, err=%s\n", err) } }
stardog-union/stardog-graviton
vendor/github.com/mitchellh/packer/builder/azure/arm/openssh_key_pair_test.go
GO
apache-2.0
980
import {isPresent, RegExpWrapper, StringWrapper} from 'angular2/src/core/facade/lang'; import {MapWrapper} from 'angular2/src/core/facade/collection'; import {Parser} from 'angular2/src/core/change_detection/change_detection'; import {CompileStep} from './compile_step'; import {CompileElement} from './compile_element'; import {CompileControl} from './compile_control'; import {dashCaseToCamelCase} from '../util'; // Group 1 = "bind-" // Group 2 = "var-" or "#" // Group 3 = "on-" // Group 4 = "bindon-" // Group 5 = the identifier after "bind-", "var-/#", or "on-" // Group 6 = identifier inside [()] // Group 7 = identifier inside [] // Group 8 = identifier inside () var BIND_NAME_REGEXP = /^(?:(?:(?:(bind-)|(var-|#)|(on-)|(bindon-))(.+))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/g; /** * Parses the property bindings on a single element. */ export class PropertyBindingParser implements CompileStep { constructor(private _parser: Parser) {} processStyle(style: string): string { return style; } processElement(parent: CompileElement, current: CompileElement, control: CompileControl) { var attrs = current.attrs(); var newAttrs = new Map(); MapWrapper.forEach(attrs, (attrValue, attrName) => { attrName = this._normalizeAttributeName(attrName); var bindParts = RegExpWrapper.firstMatch(BIND_NAME_REGEXP, attrName); if (isPresent(bindParts)) { if (isPresent(bindParts[1])) { // match: bind-prop this._bindProperty(bindParts[5], attrValue, current, newAttrs); } else if (isPresent( bindParts[2])) { // match: var-name / var-name="iden" / #name / #name="iden" var identifier = bindParts[5]; var value = attrValue == '' ? '\$implicit' : attrValue; this._bindVariable(identifier, value, current, newAttrs); } else if (isPresent(bindParts[3])) { // match: on-event this._bindEvent(bindParts[5], attrValue, current, newAttrs); } else if (isPresent(bindParts[4])) { // match: bindon-prop this._bindProperty(bindParts[5], attrValue, current, newAttrs); this._bindAssignmentEvent(bindParts[5], attrValue, current, newAttrs); } else if (isPresent(bindParts[6])) { // match: [(expr)] this._bindProperty(bindParts[6], attrValue, current, newAttrs); this._bindAssignmentEvent(bindParts[6], attrValue, current, newAttrs); } else if (isPresent(bindParts[7])) { // match: [expr] this._bindProperty(bindParts[7], attrValue, current, newAttrs); } else if (isPresent(bindParts[8])) { // match: (event) this._bindEvent(bindParts[8], attrValue, current, newAttrs); } } else { var expr = this._parser.parseInterpolation(attrValue, current.elementDescription); if (isPresent(expr)) { this._bindPropertyAst(attrName, expr, current, newAttrs); } } }); MapWrapper.forEach(newAttrs, (attrValue, attrName) => { attrs.set(attrName, attrValue); }); } _normalizeAttributeName(attrName: string): string { return StringWrapper.startsWith(attrName, 'data-') ? StringWrapper.substring(attrName, 5) : attrName; } _bindVariable(identifier, value, current: CompileElement, newAttrs: Map<any, any>) { current.bindElement().bindVariable(dashCaseToCamelCase(identifier), value); newAttrs.set(identifier, value); } _bindProperty(name, expression, current: CompileElement, newAttrs) { this._bindPropertyAst(name, this._parser.parseBinding(expression, current.elementDescription), current, newAttrs); } _bindPropertyAst(name, ast, current: CompileElement, newAttrs: Map<any, any>) { var binder = current.bindElement(); binder.bindProperty(dashCaseToCamelCase(name), ast); newAttrs.set(name, ast.source); } _bindAssignmentEvent(name, expression, current: CompileElement, newAttrs) { this._bindEvent(name, `${expression}=$event`, current, newAttrs); } _bindEvent(name, expression, current: CompileElement, newAttrs) { current.bindElement().bindEvent( dashCaseToCamelCase(name), this._parser.parseAction(expression, current.elementDescription)); // Don't detect directives for event names for now, // so don't add the event name to the CompileElement.attrs } }
shahata/angular
modules/angular2/src/core/render/dom/compiler/property_binding_parser.ts
TypeScript
apache-2.0
4,415
public class Test { void fooBarGoo() { try {} finally {} fbg<caret> } }
smmribeiro/intellij-community
java/java-tests/testData/codeInsight/completion/normal/MethodCallAfterFinally.java
Java
apache-2.0
87
# rank 1 class CandidateTest def test4 end def test5 end end
phstc/sshp
vendor/ruby/1.9.1/gems/pry-0.9.12.2/spec/fixtures/candidate_helper2.rb
Ruby
mit
70
import frappe def execute(): duplicates = frappe.db.sql("""select email_group, email, count(name) from `tabEmail Group Member` group by email_group, email having count(name) > 1""") # delete all duplicates except 1 for email_group, email, count in duplicates: frappe.db.sql("""delete from `tabEmail Group Member` where email_group=%s and email=%s limit %s""", (email_group, email, count-1))
hassanibi/erpnext
erpnext/patches/v6_2/remove_newsletter_duplicates.py
Python
gpl-3.0
407
import { Subscriber } from '../Subscriber'; import { tryCatch } from '../util/tryCatch'; import { errorObject } from '../util/errorObject'; /** * Compares all values of two observables in sequence using an optional comparor function * and returns an observable of a single boolean value representing whether or not the two sequences * are equal. * * <span class="informal">Checks to see of all values emitted by both observables are equal, in order.</span> * * <img src="./img/sequenceEqual.png" width="100%"> * * `sequenceEqual` subscribes to two observables and buffers incoming values from each observable. Whenever either * observable emits a value, the value is buffered and the buffers are shifted and compared from the bottom * up; If any value pair doesn't match, the returned observable will emit `false` and complete. If one of the * observables completes, the operator will wait for the other observable to complete; If the other * observable emits before completing, the returned observable will emit `false` and complete. If one observable never * completes or emits after the other complets, the returned observable will never complete. * * @example <caption>figure out if the Konami code matches</caption> * var code = Rx.Observable.from([ * "ArrowUp", * "ArrowUp", * "ArrowDown", * "ArrowDown", * "ArrowLeft", * "ArrowRight", * "ArrowLeft", * "ArrowRight", * "KeyB", * "KeyA", * "Enter" // no start key, clearly. * ]); * * var keys = Rx.Observable.fromEvent(document, 'keyup') * .map(e => e.code); * var matches = keys.bufferCount(11, 1) * .mergeMap( * last11 => * Rx.Observable.from(last11) * .sequenceEqual(code) * ); * matches.subscribe(matched => console.log('Successful cheat at Contra? ', matched)); * * @see {@link combineLatest} * @see {@link zip} * @see {@link withLatestFrom} * * @param {Observable} compareTo The observable sequence to compare the source sequence to. * @param {function} [comparor] An optional function to compare each value pair * @return {Observable} An Observable of a single boolean value representing whether or not * the values emitted by both observables were equal in sequence. * @method sequenceEqual * @owner Observable */ export function sequenceEqual(compareTo, comparor) { return (source) => source.lift(new SequenceEqualOperator(compareTo, comparor)); } export class SequenceEqualOperator { constructor(compareTo, comparor) { this.compareTo = compareTo; this.comparor = comparor; } call(subscriber, source) { return source.subscribe(new SequenceEqualSubscriber(subscriber, this.compareTo, this.comparor)); } } /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ export class SequenceEqualSubscriber extends Subscriber { constructor(destination, compareTo, comparor) { super(destination); this.compareTo = compareTo; this.comparor = comparor; this._a = []; this._b = []; this._oneComplete = false; this.add(compareTo.subscribe(new SequenceEqualCompareToSubscriber(destination, this))); } _next(value) { if (this._oneComplete && this._b.length === 0) { this.emit(false); } else { this._a.push(value); this.checkValues(); } } _complete() { if (this._oneComplete) { this.emit(this._a.length === 0 && this._b.length === 0); } else { this._oneComplete = true; } } checkValues() { const { _a, _b, comparor } = this; while (_a.length > 0 && _b.length > 0) { let a = _a.shift(); let b = _b.shift(); let areEqual = false; if (comparor) { areEqual = tryCatch(comparor)(a, b); if (areEqual === errorObject) { this.destination.error(errorObject.e); } } else { areEqual = a === b; } if (!areEqual) { this.emit(false); } } } emit(value) { const { destination } = this; destination.next(value); destination.complete(); } nextB(value) { if (this._oneComplete && this._a.length === 0) { this.emit(false); } else { this._b.push(value); this.checkValues(); } } } class SequenceEqualCompareToSubscriber extends Subscriber { constructor(destination, parent) { super(destination); this.parent = parent; } _next(value) { this.parent.nextB(value); } _error(err) { this.parent.error(err); } _complete() { this.parent._complete(); } } //# sourceMappingURL=sequenceEqual.js.map
rospilot/rospilot
share/web_assets/nodejs_deps/node_modules/rxjs/_esm2015/operators/sequenceEqual.js
JavaScript
apache-2.0
4,896
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 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. */ package aws_ebs import ( "fmt" "path/filepath" "strconv" "strings" "github.com/golang/glog" "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/kubernetes/pkg/cloudprovider/providers/aws" "k8s.io/kubernetes/pkg/util/mount" kstrings "k8s.io/kubernetes/pkg/util/strings" "k8s.io/kubernetes/pkg/volume" "k8s.io/kubernetes/pkg/volume/util" "k8s.io/kubernetes/pkg/volume/util/volumepathhandler" ) var _ volume.VolumePlugin = &awsElasticBlockStorePlugin{} var _ volume.PersistentVolumePlugin = &awsElasticBlockStorePlugin{} var _ volume.BlockVolumePlugin = &awsElasticBlockStorePlugin{} var _ volume.DeletableVolumePlugin = &awsElasticBlockStorePlugin{} var _ volume.ProvisionableVolumePlugin = &awsElasticBlockStorePlugin{} func (plugin *awsElasticBlockStorePlugin) ConstructBlockVolumeSpec(podUID types.UID, volumeName, mapPath string) (*volume.Spec, error) { pluginDir := plugin.host.GetVolumeDevicePluginDir(awsElasticBlockStorePluginName) blkutil := volumepathhandler.NewBlockVolumePathHandler() globalMapPathUUID, err := blkutil.FindGlobalMapPathUUIDFromPod(pluginDir, mapPath, podUID) if err != nil { return nil, err } glog.V(5).Infof("globalMapPathUUID: %s", globalMapPathUUID) globalMapPath := filepath.Dir(globalMapPathUUID) if len(globalMapPath) <= 1 { return nil, fmt.Errorf("failed to get volume plugin information from globalMapPathUUID: %v", globalMapPathUUID) } return getVolumeSpecFromGlobalMapPath(globalMapPath) } func getVolumeSpecFromGlobalMapPath(globalMapPath string) (*volume.Spec, error) { // Get volume spec information from globalMapPath // globalMapPath example: // plugins/kubernetes.io/{PluginName}/{DefaultKubeletVolumeDevicesDirName}/{volumeID} // plugins/kubernetes.io/aws-ebs/volumeDevices/vol-XXXXXX vID := filepath.Base(globalMapPath) if len(vID) <= 1 { return nil, fmt.Errorf("failed to get volumeID from global path=%s", globalMapPath) } if !strings.Contains(vID, "vol-") { return nil, fmt.Errorf("failed to get volumeID from global path=%s, invalid volumeID format = %s", globalMapPath, vID) } block := v1.PersistentVolumeBlock awsVolume := &v1.PersistentVolume{ Spec: v1.PersistentVolumeSpec{ PersistentVolumeSource: v1.PersistentVolumeSource{ AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{ VolumeID: vID, }, }, VolumeMode: &block, }, } return volume.NewSpecFromPersistentVolume(awsVolume, true), nil } // NewBlockVolumeMapper creates a new volume.BlockVolumeMapper from an API specification. func (plugin *awsElasticBlockStorePlugin) NewBlockVolumeMapper(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.BlockVolumeMapper, error) { // If this is called via GenerateUnmapDeviceFunc(), pod is nil. // Pass empty string as dummy uid since uid isn't used in the case. var uid types.UID if pod != nil { uid = pod.UID } return plugin.newBlockVolumeMapperInternal(spec, uid, &AWSDiskUtil{}, plugin.host.GetMounter(plugin.GetPluginName())) } func (plugin *awsElasticBlockStorePlugin) newBlockVolumeMapperInternal(spec *volume.Spec, podUID types.UID, manager ebsManager, mounter mount.Interface) (volume.BlockVolumeMapper, error) { ebs, readOnly, err := getVolumeSource(spec) if err != nil { return nil, err } volumeID := aws.KubernetesVolumeID(ebs.VolumeID) partition := "" if ebs.Partition != 0 { partition = strconv.Itoa(int(ebs.Partition)) } return &awsElasticBlockStoreMapper{ awsElasticBlockStore: &awsElasticBlockStore{ podUID: podUID, volName: spec.Name(), volumeID: volumeID, partition: partition, manager: manager, mounter: mounter, plugin: plugin, }, readOnly: readOnly}, nil } func (plugin *awsElasticBlockStorePlugin) NewBlockVolumeUnmapper(volName string, podUID types.UID) (volume.BlockVolumeUnmapper, error) { return plugin.newUnmapperInternal(volName, podUID, &AWSDiskUtil{}, plugin.host.GetMounter(plugin.GetPluginName())) } func (plugin *awsElasticBlockStorePlugin) newUnmapperInternal(volName string, podUID types.UID, manager ebsManager, mounter mount.Interface) (volume.BlockVolumeUnmapper, error) { return &awsElasticBlockStoreUnmapper{ awsElasticBlockStore: &awsElasticBlockStore{ podUID: podUID, volName: volName, manager: manager, mounter: mounter, plugin: plugin, }}, nil } func (c *awsElasticBlockStoreUnmapper) TearDownDevice(mapPath, devicePath string) error { return nil } type awsElasticBlockStoreUnmapper struct { *awsElasticBlockStore } var _ volume.BlockVolumeUnmapper = &awsElasticBlockStoreUnmapper{} type awsElasticBlockStoreMapper struct { *awsElasticBlockStore readOnly bool } var _ volume.BlockVolumeMapper = &awsElasticBlockStoreMapper{} func (b *awsElasticBlockStoreMapper) SetUpDevice() (string, error) { return "", nil } func (b *awsElasticBlockStoreMapper) MapDevice(devicePath, globalMapPath, volumeMapPath, volumeMapName string, podUID types.UID) error { return util.MapBlockVolume(devicePath, globalMapPath, volumeMapPath, volumeMapName, podUID) } // GetGlobalMapPath returns global map path and error // path: plugins/kubernetes.io/{PluginName}/volumeDevices/volumeID // plugins/kubernetes.io/aws-ebs/volumeDevices/vol-XXXXXX func (ebs *awsElasticBlockStore) GetGlobalMapPath(spec *volume.Spec) (string, error) { volumeSource, _, err := getVolumeSource(spec) if err != nil { return "", err } return filepath.Join(ebs.plugin.host.GetVolumeDevicePluginDir(awsElasticBlockStorePluginName), string(volumeSource.VolumeID)), nil } // GetPodDeviceMapPath returns pod device map path and volume name // path: pods/{podUid}/volumeDevices/kubernetes.io~aws func (ebs *awsElasticBlockStore) GetPodDeviceMapPath() (string, string) { name := awsElasticBlockStorePluginName return ebs.plugin.host.GetPodVolumeDeviceDir(ebs.podUID, kstrings.EscapeQualifiedNameForDisk(name)), ebs.volName }
wjiangjay/origin
vendor/k8s.io/kubernetes/pkg/volume/aws_ebs/aws_ebs_block.go
GO
apache-2.0
6,460
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 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. ==============================================================================*/ #include "tensorflow/core/common_runtime/session_factory.h" #include <unordered_map> #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/mutex.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/protobuf/config.pb_text.h" #include "tensorflow/core/public/session_options.h" namespace tensorflow { namespace { static mutex* get_session_factory_lock() { static mutex session_factory_lock; return &session_factory_lock; } typedef std::unordered_map<string, SessionFactory*> SessionFactories; SessionFactories* session_factories() { static SessionFactories* factories = new SessionFactories; return factories; } } // namespace void SessionFactory::Register(const string& runtime_type, SessionFactory* factory) { mutex_lock l(*get_session_factory_lock()); if (!session_factories()->insert({runtime_type, factory}).second) { LOG(ERROR) << "Two session factories are being registered " << "under" << runtime_type; } } namespace { const string RegisteredFactoriesErrorMessageLocked() { std::vector<string> factory_types; for (const auto& session_factory : *session_factories()) { factory_types.push_back(session_factory.first); } return strings::StrCat("Registered factories are {", str_util::Join(factory_types, ", "), "}."); } string SessionOptionsToString(const SessionOptions& options) { return strings::StrCat("target: \"", options.target, "\" config: ", ProtoShortDebugString(options.config)); } } // namespace Status SessionFactory::GetFactory(const SessionOptions& options, SessionFactory** out_factory) { mutex_lock l(*get_session_factory_lock()); // could use reader lock std::vector<std::pair<string, SessionFactory*>> candidate_factories; for (const auto& session_factory : *session_factories()) { if (session_factory.second->AcceptsOptions(options)) { VLOG(2) << "SessionFactory type " << session_factory.first << " accepts target: " << options.target; candidate_factories.push_back(session_factory); } else { VLOG(2) << "SessionFactory type " << session_factory.first << " does not accept target: " << options.target; } } if (candidate_factories.size() == 1) { *out_factory = candidate_factories[0].second; return Status::OK(); } else if (candidate_factories.size() > 1) { // NOTE(mrry): This implementation assumes that the domains (in // terms of acceptable SessionOptions) of the registered // SessionFactory implementations do not overlap. This is fine for // now, but we may need an additional way of distinguishing // different runtimes (such as an additional session option) if // the number of sessions grows. // TODO(mrry): Consider providing a system-default fallback option // in this case. std::vector<string> factory_types; factory_types.reserve(candidate_factories.size()); for (const auto& candidate_factory : candidate_factories) { factory_types.push_back(candidate_factory.first); } return errors::Internal( "Multiple session factories registered for the given session " "options: {", SessionOptionsToString(options), "} Candidate factories are {", str_util::Join(factory_types, ", "), "}. ", RegisteredFactoriesErrorMessageLocked()); } else { return errors::NotFound( "No session factory registered for the given session options: {", SessionOptionsToString(options), "} ", RegisteredFactoriesErrorMessageLocked()); } } } // namespace tensorflow
npuichigo/ttsflow
third_party/tensorflow/tensorflow/core/common_runtime/session_factory.cc
C++
apache-2.0
4,469
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // 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. // var mocha = require('mocha'); var should = require('should'); var sinon = require('sinon'); var _ = require('underscore'); // Test includes var testutil = require('../util/util'); // Lib includes var util = testutil.libRequire('util/utils'); var GetCommand = require('./util-GetCommand.js'); describe('HDInsight list command (under unit test)', function() { after(function (done) { done(); }); // NOTE: To Do, we should actually create new accounts for our tests // So that we can work on any existing subscription. before (function (done) { done(); }); it('should call startProgress with the correct statement', function(done) { var command = new GetCommand(); command.hdinsight.listClustersCommand.should.not.equal(null); command.hdinsight.listClustersCommand({}, _); command.user.startProgress.firstCall.args[0].should.be.equal('Getting HDInsight servers'); done(); }); it('should call listClusters with the supplied subscriptionId (when none is supplied)', function(done) { var command = new GetCommand(); command.hdinsight.listClustersCommand.should.not.equal(null); command.hdinsight.listClustersCommand({}, _); command.processor.listClusters.firstCall.should.not.equal(null); (command.processor.listClusters.firstCall.args[0] === undefined).should.equal(true); done(); }); it('should call listClusters with the supplied subscriptionId (when one is supplied)', function(done) { var command = new GetCommand(); command.hdinsight.listClustersCommand.should.not.equal(null); command.hdinsight.listClustersCommand({ subscription: 'test1' }, _); command.processor.listClusters.firstCall.should.not.equal(null); command.processor.listClusters.firstCall.args[0].should.not.equal(null); command.processor.listClusters.firstCall.args[0].should.be.equal('test1'); done(); }); });
Nepomuceno/azure-xplat-cli
test/hdinsight/unit-list-command.js
JavaScript
apache-2.0
2,528
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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. */ package org.elasticsearch.search.aggregations.bucket.terms; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import org.elasticsearch.common.io.stream.Streamable; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.search.aggregations.AggregationExecutionException; import org.elasticsearch.search.aggregations.Aggregations; import org.elasticsearch.search.aggregations.InternalAggregation; import org.elasticsearch.search.aggregations.InternalAggregations; import org.elasticsearch.search.aggregations.InternalMultiBucketAggregation; import org.elasticsearch.search.aggregations.bucket.terms.support.BucketPriorityQueue; import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator; import org.elasticsearch.search.aggregations.support.format.ValueFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; /** * */ public abstract class InternalTerms<A extends InternalTerms, B extends InternalTerms.Bucket> extends InternalMultiBucketAggregation<A, B> implements Terms, ToXContent, Streamable { protected static final String DOC_COUNT_ERROR_UPPER_BOUND_FIELD_NAME = "doc_count_error_upper_bound"; protected static final String SUM_OF_OTHER_DOC_COUNTS = "sum_other_doc_count"; public static abstract class Bucket extends Terms.Bucket { long bucketOrd; protected long docCount; protected long docCountError; protected InternalAggregations aggregations; protected boolean showDocCountError; transient final ValueFormatter formatter; protected Bucket(ValueFormatter formatter, boolean showDocCountError) { // for serialization this.showDocCountError = showDocCountError; this.formatter = formatter; } protected Bucket(long docCount, InternalAggregations aggregations, boolean showDocCountError, long docCountError, ValueFormatter formatter) { this(formatter, showDocCountError); this.docCount = docCount; this.aggregations = aggregations; this.docCountError = docCountError; } @Override public long getDocCount() { return docCount; } @Override public long getDocCountError() { if (!showDocCountError) { throw new IllegalStateException("show_terms_doc_count_error is false"); } return docCountError; } @Override public Aggregations getAggregations() { return aggregations; } abstract Bucket newBucket(long docCount, InternalAggregations aggs, long docCountError); public Bucket reduce(List<? extends Bucket> buckets, ReduceContext context) { long docCount = 0; long docCountError = 0; List<InternalAggregations> aggregationsList = new ArrayList<>(buckets.size()); for (Bucket bucket : buckets) { docCount += bucket.docCount; if (docCountError != -1) { if (bucket.docCountError == -1) { docCountError = -1; } else { docCountError += bucket.docCountError; } } aggregationsList.add(bucket.aggregations); } InternalAggregations aggs = InternalAggregations.reduce(aggregationsList, context); return newBucket(docCount, aggs, docCountError); } } protected Terms.Order order; protected int requiredSize; protected int shardSize; protected long minDocCount; protected List<? extends Bucket> buckets; protected Map<String, Bucket> bucketMap; protected long docCountError; protected boolean showTermDocCountError; protected long otherDocCount; protected InternalTerms() {} // for serialization protected InternalTerms(String name, Terms.Order order, int requiredSize, int shardSize, long minDocCount, List<? extends Bucket> buckets, boolean showTermDocCountError, long docCountError, long otherDocCount, List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData) { super(name, pipelineAggregators, metaData); this.order = order; this.requiredSize = requiredSize; this.shardSize = shardSize; this.minDocCount = minDocCount; this.buckets = buckets; this.showTermDocCountError = showTermDocCountError; this.docCountError = docCountError; this.otherDocCount = otherDocCount; } @Override public List<Terms.Bucket> getBuckets() { Object o = buckets; return (List<Terms.Bucket>) o; } @Override public Terms.Bucket getBucketByKey(String term) { if (bucketMap == null) { bucketMap = Maps.newHashMapWithExpectedSize(buckets.size()); for (Bucket bucket : buckets) { bucketMap.put(bucket.getKeyAsString(), bucket); } } return bucketMap.get(term); } @Override public long getDocCountError() { return docCountError; } @Override public long getSumOfOtherDocCounts() { return otherDocCount; } @Override public InternalAggregation doReduce(List<InternalAggregation> aggregations, ReduceContext reduceContext) { Multimap<Object, InternalTerms.Bucket> buckets = ArrayListMultimap.create(); long sumDocCountError = 0; long otherDocCount = 0; InternalTerms<A, B> referenceTerms = null; for (InternalAggregation aggregation : aggregations) { InternalTerms<A, B> terms = (InternalTerms<A, B>) aggregation; if (referenceTerms == null && !terms.getClass().equals(UnmappedTerms.class)) { referenceTerms = (InternalTerms<A, B>) aggregation; } if (referenceTerms != null && !referenceTerms.getClass().equals(terms.getClass()) && !terms.getClass().equals(UnmappedTerms.class)) { // control gets into this loop when the same field name against which the query is executed // is of different types in different indices. throw new AggregationExecutionException("Merging/Reducing the aggregations failed " + "when computing the aggregation [ Name: " + referenceTerms.getName() + ", Type: " + referenceTerms.type() + " ]" + " because: " + "the field you gave in the aggregation query " + "existed as two different types " + "in two different indices"); } otherDocCount += terms.getSumOfOtherDocCounts(); final long thisAggDocCountError; if (terms.buckets.size() < this.shardSize || this.order == InternalOrder.TERM_ASC || this.order == InternalOrder.TERM_DESC) { thisAggDocCountError = 0; } else if (InternalOrder.isCountDesc(this.order)) { thisAggDocCountError = terms.buckets.get(terms.buckets.size() - 1).docCount; } else { thisAggDocCountError = -1; } if (sumDocCountError != -1) { if (thisAggDocCountError == -1) { sumDocCountError = -1; } else { sumDocCountError += thisAggDocCountError; } } terms.docCountError = thisAggDocCountError; for (Bucket bucket : terms.buckets) { bucket.docCountError = thisAggDocCountError; buckets.put(bucket.getKey(), bucket); } } final int size = Math.min(requiredSize, buckets.size()); BucketPriorityQueue ordered = new BucketPriorityQueue(size, order.comparator(null)); for (Collection<Bucket> l : buckets.asMap().values()) { List<Bucket> sameTermBuckets = (List<Bucket>) l; // cast is ok according to javadocs final Bucket b = sameTermBuckets.get(0).reduce(sameTermBuckets, reduceContext); if (b.docCountError != -1) { if (sumDocCountError == -1) { b.docCountError = -1; } else { b.docCountError = sumDocCountError - b.docCountError; } } if (b.docCount >= minDocCount) { Terms.Bucket removed = ordered.insertWithOverflow(b); if (removed != null) { otherDocCount += removed.getDocCount(); } } } Bucket[] list = new Bucket[ordered.size()]; for (int i = ordered.size() - 1; i >= 0; i--) { list[i] = (Bucket) ordered.pop(); } long docCountError; if (sumDocCountError == -1) { docCountError = -1; } else { docCountError = aggregations.size() == 1 ? 0 : sumDocCountError; } return create(name, Arrays.asList(list), docCountError, otherDocCount, this); } protected abstract A create(String name, List<InternalTerms.Bucket> buckets, long docCountError, long otherDocCount, InternalTerms prototype); }
queirozfcom/elasticsearch
core/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/InternalTerms.java
Java
apache-2.0
10,492
// Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // 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. package v2 import ( "fmt" "time" "github.com/golang/glog" "github.com/google/cadvisor/info/v1" ) func machineFsStatsFromV1(fsStats []v1.FsStats) []MachineFsStats { var result []MachineFsStats for _, stat := range fsStats { readDuration := time.Millisecond * time.Duration(stat.ReadTime) writeDuration := time.Millisecond * time.Duration(stat.WriteTime) ioDuration := time.Millisecond * time.Duration(stat.IoTime) weightedDuration := time.Millisecond * time.Duration(stat.WeightedIoTime) result = append(result, MachineFsStats{ Device: stat.Device, Type: stat.Type, Capacity: &stat.Limit, Usage: &stat.Usage, Available: &stat.Available, InodesFree: &stat.InodesFree, DiskStats: DiskStats{ ReadsCompleted: &stat.ReadsCompleted, ReadsMerged: &stat.ReadsMerged, SectorsRead: &stat.SectorsRead, ReadDuration: &readDuration, WritesCompleted: &stat.WritesCompleted, WritesMerged: &stat.WritesMerged, SectorsWritten: &stat.SectorsWritten, WriteDuration: &writeDuration, IoInProgress: &stat.IoInProgress, IoDuration: &ioDuration, WeightedIoDuration: &weightedDuration, }, }) } return result } func MachineStatsFromV1(cont *v1.ContainerInfo) []MachineStats { var stats []MachineStats var last *v1.ContainerStats for _, val := range cont.Stats { stat := MachineStats{ Timestamp: val.Timestamp, } if cont.Spec.HasCpu { stat.Cpu = &val.Cpu cpuInst, err := InstCpuStats(last, val) if err != nil { glog.Warningf("Could not get instant cpu stats: %v", err) } else { stat.CpuInst = cpuInst } last = val } if cont.Spec.HasMemory { stat.Memory = &val.Memory } if cont.Spec.HasNetwork { stat.Network = &NetworkStats{ // FIXME: Use reflection instead. Tcp: TcpStat(val.Network.Tcp), Tcp6: TcpStat(val.Network.Tcp6), Interfaces: val.Network.Interfaces, } } if cont.Spec.HasFilesystem { stat.Filesystem = machineFsStatsFromV1(val.Filesystem) } // TODO(rjnagal): Handle load stats. stats = append(stats, stat) } return stats } func ContainerStatsFromV1(spec *v1.ContainerSpec, stats []*v1.ContainerStats) []*ContainerStats { newStats := make([]*ContainerStats, 0, len(stats)) var last *v1.ContainerStats for _, val := range stats { stat := &ContainerStats{ Timestamp: val.Timestamp, } if spec.HasCpu { stat.Cpu = &val.Cpu cpuInst, err := InstCpuStats(last, val) if err != nil { glog.Warningf("Could not get instant cpu stats: %v", err) } else { stat.CpuInst = cpuInst } last = val } if spec.HasMemory { stat.Memory = &val.Memory } if spec.HasNetwork { // TODO: Handle TcpStats stat.Network = &NetworkStats{ Interfaces: val.Network.Interfaces, } } if spec.HasFilesystem { if len(val.Filesystem) == 1 { stat.Filesystem = &FilesystemStats{ TotalUsageBytes: &val.Filesystem[0].Usage, BaseUsageBytes: &val.Filesystem[0].BaseUsage, } } else if len(val.Filesystem) > 1 { // Cannot handle multiple devices per container. glog.V(2).Infof("failed to handle multiple devices for container. Skipping Filesystem stats") } } if spec.HasDiskIo { stat.DiskIo = &val.DiskIo } if spec.HasCustomMetrics { stat.CustomMetrics = val.CustomMetrics } // TODO(rjnagal): Handle load stats. newStats = append(newStats, stat) } return newStats } func DeprecatedStatsFromV1(cont *v1.ContainerInfo) []DeprecatedContainerStats { stats := make([]DeprecatedContainerStats, 0, len(cont.Stats)) var last *v1.ContainerStats for _, val := range cont.Stats { stat := DeprecatedContainerStats{ Timestamp: val.Timestamp, HasCpu: cont.Spec.HasCpu, HasMemory: cont.Spec.HasMemory, HasNetwork: cont.Spec.HasNetwork, HasFilesystem: cont.Spec.HasFilesystem, HasDiskIo: cont.Spec.HasDiskIo, HasCustomMetrics: cont.Spec.HasCustomMetrics, } if stat.HasCpu { stat.Cpu = val.Cpu cpuInst, err := InstCpuStats(last, val) if err != nil { glog.Warningf("Could not get instant cpu stats: %v", err) } else { stat.CpuInst = cpuInst } last = val } if stat.HasMemory { stat.Memory = val.Memory } if stat.HasNetwork { stat.Network.Interfaces = val.Network.Interfaces } if stat.HasFilesystem { stat.Filesystem = val.Filesystem } if stat.HasDiskIo { stat.DiskIo = val.DiskIo } if stat.HasCustomMetrics { stat.CustomMetrics = val.CustomMetrics } // TODO(rjnagal): Handle load stats. stats = append(stats, stat) } return stats } func InstCpuStats(last, cur *v1.ContainerStats) (*CpuInstStats, error) { if last == nil { return nil, nil } if !cur.Timestamp.After(last.Timestamp) { return nil, fmt.Errorf("container stats move backwards in time") } if len(last.Cpu.Usage.PerCpu) != len(cur.Cpu.Usage.PerCpu) { return nil, fmt.Errorf("different number of cpus") } timeDelta := cur.Timestamp.Sub(last.Timestamp) if timeDelta <= 100*time.Millisecond { return nil, fmt.Errorf("time delta unexpectedly small") } // Nanoseconds to gain precision and avoid having zero seconds if the // difference between the timestamps is just under a second timeDeltaNs := uint64(timeDelta.Nanoseconds()) convertToRate := func(lastValue, curValue uint64) (uint64, error) { if curValue < lastValue { return 0, fmt.Errorf("cumulative stats decrease") } valueDelta := curValue - lastValue // Use float64 to keep precision return uint64(float64(valueDelta) / float64(timeDeltaNs) * 1e9), nil } total, err := convertToRate(last.Cpu.Usage.Total, cur.Cpu.Usage.Total) if err != nil { return nil, err } percpu := make([]uint64, len(last.Cpu.Usage.PerCpu)) for i := range percpu { var err error percpu[i], err = convertToRate(last.Cpu.Usage.PerCpu[i], cur.Cpu.Usage.PerCpu[i]) if err != nil { return nil, err } } user, err := convertToRate(last.Cpu.Usage.User, cur.Cpu.Usage.User) if err != nil { return nil, err } system, err := convertToRate(last.Cpu.Usage.System, cur.Cpu.Usage.System) if err != nil { return nil, err } return &CpuInstStats{ Usage: CpuInstUsage{ Total: total, PerCpu: percpu, User: user, System: system, }, }, nil } // Get V2 container spec from v1 container info. func ContainerSpecFromV1(specV1 *v1.ContainerSpec, aliases []string, namespace string) ContainerSpec { specV2 := ContainerSpec{ CreationTime: specV1.CreationTime, HasCpu: specV1.HasCpu, HasMemory: specV1.HasMemory, HasFilesystem: specV1.HasFilesystem, HasNetwork: specV1.HasNetwork, HasDiskIo: specV1.HasDiskIo, HasCustomMetrics: specV1.HasCustomMetrics, Image: specV1.Image, Labels: specV1.Labels, } if specV1.HasCpu { specV2.Cpu.Limit = specV1.Cpu.Limit specV2.Cpu.MaxLimit = specV1.Cpu.MaxLimit specV2.Cpu.Mask = specV1.Cpu.Mask } if specV1.HasMemory { specV2.Memory.Limit = specV1.Memory.Limit specV2.Memory.Reservation = specV1.Memory.Reservation specV2.Memory.SwapLimit = specV1.Memory.SwapLimit } if specV1.HasCustomMetrics { specV2.CustomMetrics = specV1.CustomMetrics } specV2.Aliases = aliases specV2.Namespace = namespace return specV2 }
dmirubtsov/k8s-executor
vendor/k8s.io/kubernetes/vendor/github.com/google/cadvisor/info/v2/conversion.go
GO
apache-2.0
7,941
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/message_loop/message_loop.h" #include "content/renderer/media/mock_web_rtc_peer_connection_handler_client.h" #include "content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/public/platform/WebRTCPeerConnectionHandler.h" namespace content { class PeerConnectionDependencyFactoryTest : public ::testing::Test { public: void SetUp() override { dependency_factory_.reset(new MockPeerConnectionDependencyFactory()); } protected: base::MessageLoop message_loop_; scoped_ptr<MockPeerConnectionDependencyFactory> dependency_factory_; }; TEST_F(PeerConnectionDependencyFactoryTest, CreateRTCPeerConnectionHandler) { MockWebRTCPeerConnectionHandlerClient client_jsep; scoped_ptr<blink::WebRTCPeerConnectionHandler> pc_handler( dependency_factory_->CreateRTCPeerConnectionHandler(&client_jsep)); EXPECT_TRUE(pc_handler.get() != NULL); } } // namespace content
CTSRD-SOAAP/chromium-42.0.2311.135
content/renderer/media/webrtc/peer_connection_dependency_factory_unittest.cc
C++
bsd-3-clause
1,157
class GstPluginsUgly < Formula desc "GStreamer plugins (well-supported, possibly problematic for distributors)" homepage "https://gstreamer.freedesktop.org/" url "https://gstreamer.freedesktop.org/src/gst-plugins-ugly/gst-plugins-ugly-1.8.0.tar.xz" sha256 "53657ffb7d49ddc4ae40e3f52e56165db4c06eb016891debe2b6c0e9f134eb8c" bottle do sha256 "de81ae62cc34b67d54cb632dce97fb108e4dff3cf839cf99703c23415e64fa8b" => :el_capitan sha256 "5b471670878ccc08926394d973d3ddb5904921e7739ef11bb0f4fe3c67b77f09" => :yosemite sha256 "32c4fc7c2fa4a60390f4346f69b9f4d1bf3a260c94400319d122d2b4c634d5ad" => :mavericks end head do url "https://anongit.freedesktop.org/git/gstreamer/gst-plugins-ugly.git" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build end depends_on "pkg-config" => :build depends_on "gettext" depends_on "gst-plugins-base" # The set of optional dependencies is based on the intersection of # gst-plugins-ugly-0.10.17/REQUIREMENTS and Homebrew formulae depends_on "dirac" => :optional depends_on "mad" => :optional depends_on "jpeg" => :optional depends_on "libvorbis" => :optional depends_on "cdparanoia" => :optional depends_on "lame" => :optional depends_on "two-lame" => :optional depends_on "libshout" => :optional depends_on "aalib" => :optional depends_on "libcaca" => :optional depends_on "libdvdread" => :optional depends_on "libmpeg2" => :optional depends_on "a52dec" => :optional depends_on "liboil" => :optional depends_on "flac" => :optional depends_on "gtk+" => :optional depends_on "pango" => :optional depends_on "theora" => :optional depends_on "libmms" => :optional depends_on "x264" => :optional depends_on "opencore-amr" => :optional # Does not work with libcdio 0.9 def install args = %W[ --prefix=#{prefix} --mandir=#{man} --disable-debug --disable-dependency-tracking ] if build.head? ENV["NOCONFIGURE"] = "yes" system "./autogen.sh" end if build.with? "opencore-amr" # Fixes build error, missing includes. # https://github.com/Homebrew/homebrew/issues/14078 nbcflags = `pkg-config --cflags opencore-amrnb`.chomp wbcflags = `pkg-config --cflags opencore-amrwb`.chomp ENV["AMRNB_CFLAGS"] = nbcflags + "-I#{HOMEBREW_PREFIX}/include/opencore-amrnb" ENV["AMRWB_CFLAGS"] = wbcflags + "-I#{HOMEBREW_PREFIX}/include/opencore-amrwb" else args << "--disable-amrnb" << "--disable-amrwb" end system "./configure", *args system "make" system "make", "install" end end
gnubila-france/linuxbrew
Library/Formula/gst-plugins-ugly.rb
Ruby
bsd-2-clause
2,650
cask 'netbeans-java-se' do version '8.2' sha256 '91652f03d8abba0ae9d76a612ed909c9f82e4f138cbd510f5d3679280323011b' url "https://download.netbeans.org/netbeans/#{version}/final/bundles/netbeans-#{version}-javase-macosx.dmg" name 'NetBeans IDE for Java SE' homepage 'https://netbeans.org/' pkg "NetBeans #{version}.pkg" uninstall pkgutil: 'org.netbeans.ide.*', delete: '/Applications/NetBeans' end
wastrachan/homebrew-cask
Casks/netbeans-java-se.rb
Ruby
bsd-2-clause
426
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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. */ class Google_Service_Dataproc_DataprocEmpty extends Google_Model { }
drthomas21/WordPress_Tutorial
wordpress_htdocs/wp-content/plugins/swg-youtube-vids/vendor/google/apiclient-services/src/Google/Service/Dataproc/DataprocEmpty.php
PHP
apache-2.0
667
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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. */ class Google_Service_DoubleClickBidManager_QueryMetadata extends Google_Collection { protected $collection_key = 'shareEmailAddress'; public $dataRange; public $format; public $googleCloudStoragePathForLatestReport; public $googleDrivePathForLatestReport; public $latestReportRunTimeMs; public $locale; public $reportCount; public $running; public $sendNotification; public $shareEmailAddress; public $title; public function setDataRange($dataRange) { $this->dataRange = $dataRange; } public function getDataRange() { return $this->dataRange; } public function setFormat($format) { $this->format = $format; } public function getFormat() { return $this->format; } public function setGoogleCloudStoragePathForLatestReport($googleCloudStoragePathForLatestReport) { $this->googleCloudStoragePathForLatestReport = $googleCloudStoragePathForLatestReport; } public function getGoogleCloudStoragePathForLatestReport() { return $this->googleCloudStoragePathForLatestReport; } public function setGoogleDrivePathForLatestReport($googleDrivePathForLatestReport) { $this->googleDrivePathForLatestReport = $googleDrivePathForLatestReport; } public function getGoogleDrivePathForLatestReport() { return $this->googleDrivePathForLatestReport; } public function setLatestReportRunTimeMs($latestReportRunTimeMs) { $this->latestReportRunTimeMs = $latestReportRunTimeMs; } public function getLatestReportRunTimeMs() { return $this->latestReportRunTimeMs; } public function setLocale($locale) { $this->locale = $locale; } public function getLocale() { return $this->locale; } public function setReportCount($reportCount) { $this->reportCount = $reportCount; } public function getReportCount() { return $this->reportCount; } public function setRunning($running) { $this->running = $running; } public function getRunning() { return $this->running; } public function setSendNotification($sendNotification) { $this->sendNotification = $sendNotification; } public function getSendNotification() { return $this->sendNotification; } public function setShareEmailAddress($shareEmailAddress) { $this->shareEmailAddress = $shareEmailAddress; } public function getShareEmailAddress() { return $this->shareEmailAddress; } public function setTitle($title) { $this->title = $title; } public function getTitle() { return $this->title; } }
drthomas21/WordPress_Tutorial
wordpress_htdocs/wp-content/plugins/swg-youtube-vids/vendor/google/apiclient-services/src/Google/Service/DoubleClickBidManager/QueryMetadata.php
PHP
apache-2.0
3,146
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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. */ package com.intellij.openapi.vcs.changes.ui; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.extensions.PluginAware; import com.intellij.openapi.extensions.PluginDescriptor; import com.intellij.openapi.project.Project; import com.intellij.util.NotNullFunction; import com.intellij.util.pico.ConstructorInjectionComponentAdapter; import com.intellij.util.xmlb.annotations.Attribute; import org.jetbrains.annotations.Nullable; /** * @author yole */ public class ChangesViewContentEP implements PluginAware { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.changes.ui.ChangesViewContentEP"); public static final ExtensionPointName<ChangesViewContentEP> EP_NAME = new ExtensionPointName<ChangesViewContentEP>("com.intellij.changesViewContent"); @Attribute("tabName") public String tabName; @Attribute("className") public String className; @Attribute("predicateClassName") public String predicateClassName; private PluginDescriptor myPluginDescriptor; private ChangesViewContentProvider myInstance; public void setPluginDescriptor(PluginDescriptor pluginDescriptor) { myPluginDescriptor = pluginDescriptor; } public String getTabName() { return tabName; } public void setTabName(final String tabName) { this.tabName = tabName; } public String getClassName() { return className; } public void setClassName(final String className) { this.className = className; } public String getPredicateClassName() { return predicateClassName; } public void setPredicateClassName(final String predicateClassName) { this.predicateClassName = predicateClassName; } public ChangesViewContentProvider getInstance(Project project) { if (myInstance == null) { myInstance = (ChangesViewContentProvider) newClassInstance(project, className); } return myInstance; } @Nullable public NotNullFunction<Project, Boolean> newPredicateInstance(Project project) { //noinspection unchecked return predicateClassName != null ? (NotNullFunction<Project, Boolean>)newClassInstance(project, predicateClassName) : null; } private Object newClassInstance(final Project project, final String className) { try { final Class<?> aClass = Class.forName(className, true, myPluginDescriptor == null ? getClass().getClassLoader() : myPluginDescriptor.getPluginClassLoader()); return new ConstructorInjectionComponentAdapter(className, aClass).getComponentInstance(project.getPicoContainer()); } catch(Exception e) { LOG.error(e); return null; } } }
samthor/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesViewContentEP.java
Java
apache-2.0
3,337
package com.marshalchen.common.demoofui.showcaseview.legacy; import android.annotation.TargetApi; import android.app.Activity; import android.os.Build; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.marshalchen.common.demoofui.R; public class MultipleShowcaseSampleActivity extends Activity { private static final float SHOWCASE_KITTEN_SCALE = 1.2f; private static final float SHOWCASE_LIKE_SCALE = 0.5f; //ShowcaseViews mViews; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.showcase_activity_sample_legacy); findViewById(R.id.buttonLike).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(getApplicationContext(), "like_message", Toast.LENGTH_SHORT).show(); } }); //mOptions.block = false; // mViews = new ShowcaseViews(this, // new ShowcaseViews.OnShowcaseAcknowledged() { // @Override // public void onShowCaseAcknowledged(ShowcaseView showcaseView) { // Toast.makeText(MultipleShowcaseSampleActivity.this, R.string.dismissed_message, Toast.LENGTH_SHORT).show(); // } // }); // mViews.addView( new ShowcaseViews.ItemViewProperties(R.id.image, // R.string.showcase_image_title, // R.string.showcase_image_message, // SHOWCASE_KITTEN_SCALE)); // mViews.addView( new ShowcaseViews.ItemViewProperties(R.id.buttonLike, // R.string.showcase_like_title, // R.string.showcase_like_message, // SHOWCASE_LIKE_SCALE)); // mViews.show(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { enableUp(); } } @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void enableUp() { getActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); } return super.onOptionsItemSelected(item); } }
cymcsg/UltimateAndroid
deprecated/UltimateAndroidNormal/DemoOfUI/src/com/marshalchen/common/demoofui/showcaseview/legacy/MultipleShowcaseSampleActivity.java
Java
apache-2.0
2,332
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2014-Today OpenERP SA (<http://www.openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import osv, fields from itertools import groupby def grouplines(self, ordered_lines, sortkey): """Return lines from a specified invoice or sale order grouped by category""" grouped_lines = [] for key, valuesiter in groupby(ordered_lines, sortkey): group = {} group['category'] = key group['lines'] = list(v for v in valuesiter) if 'subtotal' in key and key.subtotal is True: group['subtotal'] = sum(line.price_subtotal for line in group['lines']) grouped_lines.append(group) return grouped_lines class SaleLayoutCategory(osv.Model): _name = 'sale_layout.category' _order = 'sequence' _columns = { 'name': fields.char('Name', required=True), 'sequence': fields.integer('Sequence', required=True), 'subtotal': fields.boolean('Add subtotal'), 'separator': fields.boolean('Add separator'), 'pagebreak': fields.boolean('Add pagebreak') } _defaults = { 'subtotal': True, 'separator': True, 'pagebreak': False, 'sequence': 10 } class AccountInvoice(osv.Model): _inherit = 'account.invoice' def sale_layout_lines(self, cr, uid, ids, invoice_id=None, context=None): """ Returns invoice lines from a specified invoice ordered by sale_layout_category sequence. Used in sale_layout module. :Parameters: -'invoice_id' (int): specify the concerned invoice. """ ordered_lines = self.browse(cr, uid, invoice_id, context=context).invoice_line # We chose to group first by category model and, if not present, by invoice name sortkey = lambda x: x.sale_layout_cat_id if x.sale_layout_cat_id else '' return grouplines(self, ordered_lines, sortkey) import openerp class AccountInvoiceLine(osv.Model): _inherit = 'account.invoice.line' _order = 'invoice_id, categ_sequence, sequence, id' sale_layout_cat_id = openerp.fields.Many2one('sale_layout.category', string='Section') categ_sequence = openerp.fields.Integer(related='sale_layout_cat_id.sequence', string='Layout Sequence', store=True) class SaleOrder(osv.Model): _inherit = 'sale.order' def sale_layout_lines(self, cr, uid, ids, order_id=None, context=None): """ Returns order lines from a specified sale ordered by sale_layout_category sequence. Used in sale_layout module. :Parameters: -'order_id' (int): specify the concerned sale order. """ ordered_lines = self.browse(cr, uid, order_id, context=context).order_line sortkey = lambda x: x.sale_layout_cat_id if x.sale_layout_cat_id else '' return grouplines(self, ordered_lines, sortkey) class SaleOrderLine(osv.Model): _inherit = 'sale.order.line' _columns = { 'sale_layout_cat_id': fields.many2one('sale_layout.category', string='Section'), 'categ_sequence': fields.related('sale_layout_cat_id', 'sequence', type='integer', string='Layout Sequence', store=True) # Store is intentionally set in order to keep the "historic" order. } _order = 'order_id, categ_sequence, sequence, id' def _prepare_order_line_invoice_line(self, cr, uid, line, account_id=False, context=None): """Save the layout when converting to an invoice line.""" invoice_vals = super(SaleOrderLine, self)._prepare_order_line_invoice_line(cr, uid, line, account_id=account_id, context=context) if line.sale_layout_cat_id: invoice_vals['sale_layout_cat_id'] = line.sale_layout_cat_id.id if line.categ_sequence: invoice_vals['categ_sequence'] = line.categ_sequence return invoice_vals
diogocs1/comps
web/addons/sale_layout/models/sale_layout.py
Python
apache-2.0
4,907
/* * Copyright 2012, Google Inc. * All rights reserved. * * 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 Google Inc. 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. */ package org.jf.dexlib2.dexbacked; import com.google.common.io.ByteStreams; import org.jf.dexlib2.Opcodes; import org.jf.dexlib2.dexbacked.raw.*; import org.jf.dexlib2.dexbacked.util.FixedSizeSet; import org.jf.dexlib2.iface.DexFile; import org.jf.util.ExceptionWithContext; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.util.Set; public class DexBackedDexFile extends BaseDexBuffer implements DexFile { private final Opcodes opcodes; private final int stringCount; private final int stringStartOffset; private final int typeCount; private final int typeStartOffset; private final int protoCount; private final int protoStartOffset; private final int fieldCount; private final int fieldStartOffset; private final int methodCount; private final int methodStartOffset; private final int classCount; private final int classStartOffset; private DexBackedDexFile(Opcodes opcodes, @Nonnull byte[] buf, int offset, boolean verifyMagic) { super(buf); this.opcodes = opcodes; if (verifyMagic) { verifyMagicAndByteOrder(buf, offset); } stringCount = readSmallUint(HeaderItem.STRING_COUNT_OFFSET); stringStartOffset = readSmallUint(HeaderItem.STRING_START_OFFSET); typeCount = readSmallUint(HeaderItem.TYPE_COUNT_OFFSET); typeStartOffset = readSmallUint(HeaderItem.TYPE_START_OFFSET); protoCount = readSmallUint(HeaderItem.PROTO_COUNT_OFFSET); protoStartOffset = readSmallUint(HeaderItem.PROTO_START_OFFSET); fieldCount = readSmallUint(HeaderItem.FIELD_COUNT_OFFSET); fieldStartOffset = readSmallUint(HeaderItem.FIELD_START_OFFSET); methodCount = readSmallUint(HeaderItem.METHOD_COUNT_OFFSET); methodStartOffset = readSmallUint(HeaderItem.METHOD_START_OFFSET); classCount = readSmallUint(HeaderItem.CLASS_COUNT_OFFSET); classStartOffset = readSmallUint(HeaderItem.CLASS_START_OFFSET); } public DexBackedDexFile(@Nonnull Opcodes opcodes, @Nonnull BaseDexBuffer buf) { this(opcodes, buf.buf); } public DexBackedDexFile(@Nonnull Opcodes opcodes, @Nonnull byte[] buf, int offset) { this(opcodes, buf, offset, false); } public DexBackedDexFile(@Nonnull Opcodes opcodes, @Nonnull byte[] buf) { this(opcodes, buf, 0, true); } public static DexBackedDexFile fromInputStream(@Nonnull Opcodes opcodes, @Nonnull InputStream is) throws IOException { if (!is.markSupported()) { throw new IllegalArgumentException("InputStream must support mark"); } is.mark(44); byte[] partialHeader = new byte[44]; try { ByteStreams.readFully(is, partialHeader); } catch (EOFException ex) { throw new NotADexFile("File is too short"); } finally { is.reset(); } verifyMagicAndByteOrder(partialHeader, 0); byte[] buf = ByteStreams.toByteArray(is); return new DexBackedDexFile(opcodes, buf, 0, false); } public Opcodes getOpcodes() { return opcodes; } public boolean isOdexFile() { return false; } @Nonnull @Override public Set<? extends DexBackedClassDef> getClasses() { return new FixedSizeSet<DexBackedClassDef>() { @Nonnull @Override public DexBackedClassDef readItem(int index) { return new DexBackedClassDef(DexBackedDexFile.this, getClassDefItemOffset(index)); } @Override public int size() { return classCount; } }; } private static void verifyMagicAndByteOrder(@Nonnull byte[] buf, int offset) { if (!HeaderItem.verifyMagic(buf, offset)) { StringBuilder sb = new StringBuilder("Invalid magic value:"); for (int i=0; i<8; i++) { sb.append(String.format(" %02x", buf[i])); } throw new NotADexFile(sb.toString()); } int endian = HeaderItem.getEndian(buf, offset); if (endian == HeaderItem.BIG_ENDIAN_TAG) { throw new ExceptionWithContext("Big endian dex files are not currently supported"); } if (endian != HeaderItem.LITTLE_ENDIAN_TAG) { throw new ExceptionWithContext("Invalid endian tag: 0x%x", endian); } } public int getStringIdItemOffset(int stringIndex) { if (stringIndex < 0 || stringIndex >= stringCount) { throw new InvalidItemIndex(stringIndex, "String index out of bounds: %d", stringIndex); } return stringStartOffset + stringIndex*StringIdItem.ITEM_SIZE; } public int getTypeIdItemOffset(int typeIndex) { if (typeIndex < 0 || typeIndex >= typeCount) { throw new InvalidItemIndex(typeIndex, "Type index out of bounds: %d", typeIndex); } return typeStartOffset + typeIndex*TypeIdItem.ITEM_SIZE; } public int getFieldIdItemOffset(int fieldIndex) { if (fieldIndex < 0 || fieldIndex >= fieldCount) { throw new InvalidItemIndex(fieldIndex, "Field index out of bounds: %d", fieldIndex); } return fieldStartOffset + fieldIndex*FieldIdItem.ITEM_SIZE; } public int getMethodIdItemOffset(int methodIndex) { if (methodIndex < 0 || methodIndex >= methodCount) { throw new InvalidItemIndex(methodIndex, "Method index out of bounds: %d", methodIndex); } return methodStartOffset + methodIndex*MethodIdItem.ITEM_SIZE; } public int getProtoIdItemOffset(int protoIndex) { if (protoIndex < 0 || protoIndex >= protoCount) { throw new InvalidItemIndex(protoIndex, "Proto index out of bounds: %d", protoIndex); } return protoStartOffset + protoIndex*ProtoIdItem.ITEM_SIZE; } public int getClassDefItemOffset(int classIndex) { if (classIndex < 0 || classIndex >= classCount) { throw new InvalidItemIndex(classIndex, "Class index out of bounds: %d", classIndex); } return classStartOffset + classIndex*ClassDefItem.ITEM_SIZE; } public int getClassCount() { return classCount; } public int getStringCount() { return stringCount; } public int getTypeCount() { return typeCount; } public int getProtoCount() { return protoCount; } public int getFieldCount() { return fieldCount; } public int getMethodCount() { return methodCount; } @Nonnull public String getString(int stringIndex) { int stringOffset = getStringIdItemOffset(stringIndex); int stringDataOffset = readSmallUint(stringOffset); DexReader reader = readerAt(stringDataOffset); int utf16Length = reader.readSmallUleb128(); return reader.readString(utf16Length); } @Nullable public String getOptionalString(int stringIndex) { if (stringIndex == -1) { return null; } return getString(stringIndex); } @Nonnull public String getType(int typeIndex) { int typeOffset = getTypeIdItemOffset(typeIndex); int stringIndex = readSmallUint(typeOffset); return getString(stringIndex); } @Nullable public String getOptionalType(int typeIndex) { if (typeIndex == -1) { return null; } return getType(typeIndex); } @Override @Nonnull public DexReader readerAt(int offset) { return new DexReader(this, offset); } public static class NotADexFile extends RuntimeException { public NotADexFile() { } public NotADexFile(Throwable cause) { super(cause); } public NotADexFile(String message) { super(message); } public NotADexFile(String message, Throwable cause) { super(message, cause); } } public static class InvalidItemIndex extends ExceptionWithContext { private final int itemIndex; public InvalidItemIndex(int itemIndex) { super(""); this.itemIndex = itemIndex; } public InvalidItemIndex(int itemIndex, String message, Object... formatArgs) { super(message, formatArgs); this.itemIndex = itemIndex; } public int getInvalidIndex() { return itemIndex; } } }
valery-barysok/Apktool
brut.apktool.smali/dexlib2/src/main/java/org/jf/dexlib2/dexbacked/DexBackedDexFile.java
Java
apache-2.0
10,213
/* Copyright 2012 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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. */ /* jshint globalstrict: false */ /* umdutils ignore */ (function (root, factory) { 'use strict'; if (typeof define === 'function' && define.amd) { define('pdfjs-dist/build/pdf', ['exports'], factory); } else if (typeof exports !== 'undefined') { factory(exports); } else { factory((root.pdfjsDistBuildPdf = {})); } }(this, function (exports) { // Use strict in our context only - users might not want it 'use strict'; var pdfjsVersion = '1.3.177'; var pdfjsBuild = '51b59bc'; var pdfjsFilePath = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : null; var pdfjsLibs = {}; (function pdfjsWrapper() { (function (root, factory) { { factory((root.pdfjsSharedGlobal = {})); } }(this, function (exports) { var globalScope = (typeof window !== 'undefined') ? window : (typeof global !== 'undefined') ? global : (typeof self !== 'undefined') ? self : this; var isWorker = (typeof window === 'undefined'); // The global PDFJS object exposes the API // In production, it will be declared outside a global wrapper // In development, it will be declared here if (!globalScope.PDFJS) { globalScope.PDFJS = {}; } if (typeof pdfjsVersion !== 'undefined') { globalScope.PDFJS.version = pdfjsVersion; } if (typeof pdfjsVersion !== 'undefined') { globalScope.PDFJS.build = pdfjsBuild; } globalScope.PDFJS.pdfBug = false; exports.globalScope = globalScope; exports.isWorker = isWorker; exports.PDFJS = globalScope.PDFJS; })); (function (root, factory) { { factory((root.pdfjsDisplayDOMUtils = {}), root.pdfjsSharedGlobal); } }(this, function (exports, sharedGlobal) { var PDFJS = sharedGlobal.PDFJS; /** * Optimised CSS custom property getter/setter. * @class */ var CustomStyle = (function CustomStyleClosure() { // As noted on: http://www.zachstronaut.com/posts/2009/02/17/ // animate-css-transforms-firefox-webkit.html // in some versions of IE9 it is critical that ms appear in this list // before Moz var prefixes = ['ms', 'Moz', 'Webkit', 'O']; var _cache = {}; function CustomStyle() {} CustomStyle.getProp = function get(propName, element) { // check cache only when no element is given if (arguments.length === 1 && typeof _cache[propName] === 'string') { return _cache[propName]; } element = element || document.documentElement; var style = element.style, prefixed, uPropName; // test standard property first if (typeof style[propName] === 'string') { return (_cache[propName] = propName); } // capitalize uPropName = propName.charAt(0).toUpperCase() + propName.slice(1); // test vendor specific properties for (var i = 0, l = prefixes.length; i < l; i++) { prefixed = prefixes[i] + uPropName; if (typeof style[prefixed] === 'string') { return (_cache[propName] = prefixed); } } //if all fails then set to undefined return (_cache[propName] = 'undefined'); }; CustomStyle.setProp = function set(propName, element, str) { var prop = this.getProp(propName); if (prop !== 'undefined') { element.style[prop] = str; } }; return CustomStyle; })(); PDFJS.CustomStyle = CustomStyle; exports.CustomStyle = CustomStyle; })); (function (root, factory) { { factory((root.pdfjsSharedUtil = {}), root.pdfjsSharedGlobal); } }(this, function (exports, sharedGlobal) { var PDFJS = sharedGlobal.PDFJS; var globalScope = sharedGlobal.globalScope; var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0]; var TextRenderingMode = { FILL: 0, STROKE: 1, FILL_STROKE: 2, INVISIBLE: 3, FILL_ADD_TO_PATH: 4, STROKE_ADD_TO_PATH: 5, FILL_STROKE_ADD_TO_PATH: 6, ADD_TO_PATH: 7, FILL_STROKE_MASK: 3, ADD_TO_PATH_FLAG: 4 }; var ImageKind = { GRAYSCALE_1BPP: 1, RGB_24BPP: 2, RGBA_32BPP: 3 }; var AnnotationType = { TEXT: 1, LINK: 2, FREETEXT: 3, LINE: 4, SQUARE: 5, CIRCLE: 6, POLYGON: 7, POLYLINE: 8, HIGHLIGHT: 9, UNDERLINE: 10, SQUIGGLY: 11, STRIKEOUT: 12, STAMP: 13, CARET: 14, INK: 15, POPUP: 16, FILEATTACHMENT: 17, SOUND: 18, MOVIE: 19, WIDGET: 20, SCREEN: 21, PRINTERMARK: 22, TRAPNET: 23, WATERMARK: 24, THREED: 25, REDACT: 26 }; var AnnotationFlag = { INVISIBLE: 0x01, HIDDEN: 0x02, PRINT: 0x04, NOZOOM: 0x08, NOROTATE: 0x10, NOVIEW: 0x20, READONLY: 0x40, LOCKED: 0x80, TOGGLENOVIEW: 0x100, LOCKEDCONTENTS: 0x200 }; var AnnotationBorderStyleType = { SOLID: 1, DASHED: 2, BEVELED: 3, INSET: 4, UNDERLINE: 5 }; var StreamType = { UNKNOWN: 0, FLATE: 1, LZW: 2, DCT: 3, JPX: 4, JBIG: 5, A85: 6, AHX: 7, CCF: 8, RL: 9 }; var FontType = { UNKNOWN: 0, TYPE1: 1, TYPE1C: 2, CIDFONTTYPE0: 3, CIDFONTTYPE0C: 4, TRUETYPE: 5, CIDFONTTYPE2: 6, TYPE3: 7, OPENTYPE: 8, TYPE0: 9, MMTYPE1: 10 }; PDFJS.VERBOSITY_LEVELS = { errors: 0, warnings: 1, infos: 5 }; // All the possible operations for an operator list. var OPS = PDFJS.OPS = { // Intentionally start from 1 so it is easy to spot bad operators that will be // 0's. dependency: 1, setLineWidth: 2, setLineCap: 3, setLineJoin: 4, setMiterLimit: 5, setDash: 6, setRenderingIntent: 7, setFlatness: 8, setGState: 9, save: 10, restore: 11, transform: 12, moveTo: 13, lineTo: 14, curveTo: 15, curveTo2: 16, curveTo3: 17, closePath: 18, rectangle: 19, stroke: 20, closeStroke: 21, fill: 22, eoFill: 23, fillStroke: 24, eoFillStroke: 25, closeFillStroke: 26, closeEOFillStroke: 27, endPath: 28, clip: 29, eoClip: 30, beginText: 31, endText: 32, setCharSpacing: 33, setWordSpacing: 34, setHScale: 35, setLeading: 36, setFont: 37, setTextRenderingMode: 38, setTextRise: 39, moveText: 40, setLeadingMoveText: 41, setTextMatrix: 42, nextLine: 43, showText: 44, showSpacedText: 45, nextLineShowText: 46, nextLineSetSpacingShowText: 47, setCharWidth: 48, setCharWidthAndBounds: 49, setStrokeColorSpace: 50, setFillColorSpace: 51, setStrokeColor: 52, setStrokeColorN: 53, setFillColor: 54, setFillColorN: 55, setStrokeGray: 56, setFillGray: 57, setStrokeRGBColor: 58, setFillRGBColor: 59, setStrokeCMYKColor: 60, setFillCMYKColor: 61, shadingFill: 62, beginInlineImage: 63, beginImageData: 64, endInlineImage: 65, paintXObject: 66, markPoint: 67, markPointProps: 68, beginMarkedContent: 69, beginMarkedContentProps: 70, endMarkedContent: 71, beginCompat: 72, endCompat: 73, paintFormXObjectBegin: 74, paintFormXObjectEnd: 75, beginGroup: 76, endGroup: 77, beginAnnotations: 78, endAnnotations: 79, beginAnnotation: 80, endAnnotation: 81, paintJpegXObject: 82, paintImageMaskXObject: 83, paintImageMaskXObjectGroup: 84, paintImageXObject: 85, paintInlineImageXObject: 86, paintInlineImageXObjectGroup: 87, paintImageXObjectRepeat: 88, paintImageMaskXObjectRepeat: 89, paintSolidColorImageMask: 90, constructPath: 91 }; // A notice for devs. These are good for things that are helpful to devs, such // as warning that Workers were disabled, which is important to devs but not // end users. function info(msg) { if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) { console.log('Info: ' + msg); } } // Non-fatal warnings. function warn(msg) { if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) { console.log('Warning: ' + msg); } } // Deprecated API function -- treated as warnings. function deprecated(details) { warn('Deprecated API usage: ' + details); } // Fatal errors that should trigger the fallback UI and halt execution by // throwing an exception. function error(msg) { if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.errors) { console.log('Error: ' + msg); console.log(backtrace()); } throw new Error(msg); } function backtrace() { try { throw new Error(); } catch (e) { return e.stack ? e.stack.split('\n').slice(2).join('\n') : ''; } } function assert(cond, msg) { if (!cond) { error(msg); } } var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = { unknown: 'unknown', forms: 'forms', javaScript: 'javaScript', smask: 'smask', shadingPattern: 'shadingPattern', font: 'font' }; // Combines two URLs. The baseUrl shall be absolute URL. If the url is an // absolute URL, it will be returned as is. function combineUrl(baseUrl, url) { if (!url) { return baseUrl; } if (/^[a-z][a-z0-9+\-.]*:/i.test(url)) { return url; } var i; if (url.charAt(0) === '/') { // absolute path i = baseUrl.indexOf('://'); if (url.charAt(1) === '/') { ++i; } else { i = baseUrl.indexOf('/', i + 3); } return baseUrl.substring(0, i) + url; } else { // relative path var pathLength = baseUrl.length; i = baseUrl.lastIndexOf('#'); pathLength = i >= 0 ? i : pathLength; i = baseUrl.lastIndexOf('?', pathLength); pathLength = i >= 0 ? i : pathLength; var prefixLength = baseUrl.lastIndexOf('/', pathLength); return baseUrl.substring(0, prefixLength + 1) + url; } } // Validates if URL is safe and allowed, e.g. to avoid XSS. function isValidUrl(url, allowRelative) { if (!url) { return false; } // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1) // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url); if (!protocol) { return allowRelative; } protocol = protocol[0].toLowerCase(); switch (protocol) { case 'http': case 'https': case 'ftp': case 'mailto': case 'tel': return true; default: return false; } } PDFJS.isValidUrl = isValidUrl; function shadow(obj, prop, value) { Object.defineProperty(obj, prop, { value: value, enumerable: true, configurable: true, writable: false }); return value; } PDFJS.shadow = shadow; var LinkTarget = PDFJS.LinkTarget = { NONE: 0, // Default value. SELF: 1, BLANK: 2, PARENT: 3, TOP: 4, }; var LinkTargetStringMap = [ '', '_self', '_blank', '_parent', '_top' ]; function isExternalLinkTargetSet() { if (PDFJS.openExternalLinksInNewWindow) { deprecated('PDFJS.openExternalLinksInNewWindow, please use ' + '"PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK" instead.'); if (PDFJS.externalLinkTarget === LinkTarget.NONE) { PDFJS.externalLinkTarget = LinkTarget.BLANK; } // Reset the deprecated parameter, to suppress further warnings. PDFJS.openExternalLinksInNewWindow = false; } switch (PDFJS.externalLinkTarget) { case LinkTarget.NONE: return false; case LinkTarget.SELF: case LinkTarget.BLANK: case LinkTarget.PARENT: case LinkTarget.TOP: return true; } warn('PDFJS.externalLinkTarget is invalid: ' + PDFJS.externalLinkTarget); // Reset the external link target, to suppress further warnings. PDFJS.externalLinkTarget = LinkTarget.NONE; return false; } PDFJS.isExternalLinkTargetSet = isExternalLinkTargetSet; var PasswordResponses = PDFJS.PasswordResponses = { NEED_PASSWORD: 1, INCORRECT_PASSWORD: 2 }; var PasswordException = (function PasswordExceptionClosure() { function PasswordException(msg, code) { this.name = 'PasswordException'; this.message = msg; this.code = code; } PasswordException.prototype = new Error(); PasswordException.constructor = PasswordException; return PasswordException; })(); PDFJS.PasswordException = PasswordException; var UnknownErrorException = (function UnknownErrorExceptionClosure() { function UnknownErrorException(msg, details) { this.name = 'UnknownErrorException'; this.message = msg; this.details = details; } UnknownErrorException.prototype = new Error(); UnknownErrorException.constructor = UnknownErrorException; return UnknownErrorException; })(); PDFJS.UnknownErrorException = UnknownErrorException; var InvalidPDFException = (function InvalidPDFExceptionClosure() { function InvalidPDFException(msg) { this.name = 'InvalidPDFException'; this.message = msg; } InvalidPDFException.prototype = new Error(); InvalidPDFException.constructor = InvalidPDFException; return InvalidPDFException; })(); PDFJS.InvalidPDFException = InvalidPDFException; var MissingPDFException = (function MissingPDFExceptionClosure() { function MissingPDFException(msg) { this.name = 'MissingPDFException'; this.message = msg; } MissingPDFException.prototype = new Error(); MissingPDFException.constructor = MissingPDFException; return MissingPDFException; })(); PDFJS.MissingPDFException = MissingPDFException; var UnexpectedResponseException = (function UnexpectedResponseExceptionClosure() { function UnexpectedResponseException(msg, status) { this.name = 'UnexpectedResponseException'; this.message = msg; this.status = status; } UnexpectedResponseException.prototype = new Error(); UnexpectedResponseException.constructor = UnexpectedResponseException; return UnexpectedResponseException; })(); PDFJS.UnexpectedResponseException = UnexpectedResponseException; var NotImplementedException = (function NotImplementedExceptionClosure() { function NotImplementedException(msg) { this.message = msg; } NotImplementedException.prototype = new Error(); NotImplementedException.prototype.name = 'NotImplementedException'; NotImplementedException.constructor = NotImplementedException; return NotImplementedException; })(); var MissingDataException = (function MissingDataExceptionClosure() { function MissingDataException(begin, end) { this.begin = begin; this.end = end; this.message = 'Missing data [' + begin + ', ' + end + ')'; } MissingDataException.prototype = new Error(); MissingDataException.prototype.name = 'MissingDataException'; MissingDataException.constructor = MissingDataException; return MissingDataException; })(); var XRefParseException = (function XRefParseExceptionClosure() { function XRefParseException(msg) { this.message = msg; } XRefParseException.prototype = new Error(); XRefParseException.prototype.name = 'XRefParseException'; XRefParseException.constructor = XRefParseException; return XRefParseException; })(); var NullCharactersRegExp = /\x00/g; function removeNullCharacters(str) { if (typeof str !== 'string') { warn('The argument for removeNullCharacters must be a string.'); return str; } return str.replace(NullCharactersRegExp, ''); } PDFJS.removeNullCharacters = removeNullCharacters; function bytesToString(bytes) { assert(bytes !== null && typeof bytes === 'object' && bytes.length !== undefined, 'Invalid argument for bytesToString'); var length = bytes.length; var MAX_ARGUMENT_COUNT = 8192; if (length < MAX_ARGUMENT_COUNT) { return String.fromCharCode.apply(null, bytes); } var strBuf = []; for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) { var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length); var chunk = bytes.subarray(i, chunkEnd); strBuf.push(String.fromCharCode.apply(null, chunk)); } return strBuf.join(''); } function stringToBytes(str) { assert(typeof str === 'string', 'Invalid argument for stringToBytes'); var length = str.length; var bytes = new Uint8Array(length); for (var i = 0; i < length; ++i) { bytes[i] = str.charCodeAt(i) & 0xFF; } return bytes; } function string32(value) { return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff); } function log2(x) { var n = 1, i = 0; while (x > n) { n <<= 1; i++; } return i; } function readInt8(data, start) { return (data[start] << 24) >> 24; } function readUint16(data, offset) { return (data[offset] << 8) | data[offset + 1]; } function readUint32(data, offset) { return ((data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]) >>> 0; } // Lazy test the endianness of the platform // NOTE: This will be 'true' for simulated TypedArrays function isLittleEndian() { var buffer8 = new Uint8Array(2); buffer8[0] = 1; var buffer16 = new Uint16Array(buffer8.buffer); return (buffer16[0] === 1); } Object.defineProperty(PDFJS, 'isLittleEndian', { configurable: true, get: function PDFJS_isLittleEndian() { return shadow(PDFJS, 'isLittleEndian', isLittleEndian()); } }); // Lazy test if the userAgent support CanvasTypedArrays function hasCanvasTypedArrays() { var canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; var ctx = canvas.getContext('2d'); var imageData = ctx.createImageData(1, 1); return (typeof imageData.data.buffer !== 'undefined'); } Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', { configurable: true, get: function PDFJS_hasCanvasTypedArrays() { return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays()); } }); var Uint32ArrayView = (function Uint32ArrayViewClosure() { function Uint32ArrayView(buffer, length) { this.buffer = buffer; this.byteLength = buffer.length; this.length = length === undefined ? (this.byteLength >> 2) : length; ensureUint32ArrayViewProps(this.length); } Uint32ArrayView.prototype = Object.create(null); var uint32ArrayViewSetters = 0; function createUint32ArrayProp(index) { return { get: function () { var buffer = this.buffer, offset = index << 2; return (buffer[offset] | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0; }, set: function (value) { var buffer = this.buffer, offset = index << 2; buffer[offset] = value & 255; buffer[offset + 1] = (value >> 8) & 255; buffer[offset + 2] = (value >> 16) & 255; buffer[offset + 3] = (value >>> 24) & 255; } }; } function ensureUint32ArrayViewProps(length) { while (uint32ArrayViewSetters < length) { Object.defineProperty(Uint32ArrayView.prototype, uint32ArrayViewSetters, createUint32ArrayProp(uint32ArrayViewSetters)); uint32ArrayViewSetters++; } } return Uint32ArrayView; })(); exports.Uint32ArrayView = Uint32ArrayView; var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0]; var Util = PDFJS.Util = (function UtilClosure() { function Util() {} var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')']; // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids // creating many intermediate strings. Util.makeCssRgb = function Util_makeCssRgb(r, g, b) { rgbBuf[1] = r; rgbBuf[3] = g; rgbBuf[5] = b; return rgbBuf.join(''); }; // Concatenates two transformation matrices together and returns the result. Util.transform = function Util_transform(m1, m2) { return [ m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5] ]; }; // For 2d affine transforms Util.applyTransform = function Util_applyTransform(p, m) { var xt = p[0] * m[0] + p[1] * m[2] + m[4]; var yt = p[0] * m[1] + p[1] * m[3] + m[5]; return [xt, yt]; }; Util.applyInverseTransform = function Util_applyInverseTransform(p, m) { var d = m[0] * m[3] - m[1] * m[2]; var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d; var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d; return [xt, yt]; }; // Applies the transform to the rectangle and finds the minimum axially // aligned bounding box. Util.getAxialAlignedBoundingBox = function Util_getAxialAlignedBoundingBox(r, m) { var p1 = Util.applyTransform(r, m); var p2 = Util.applyTransform(r.slice(2, 4), m); var p3 = Util.applyTransform([r[0], r[3]], m); var p4 = Util.applyTransform([r[2], r[1]], m); return [ Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1]) ]; }; Util.inverseTransform = function Util_inverseTransform(m) { var d = m[0] * m[3] - m[1] * m[2]; return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d]; }; // Apply a generic 3d matrix M on a 3-vector v: // | a b c | | X | // | d e f | x | Y | // | g h i | | Z | // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i], // with v as [X,Y,Z] Util.apply3dTransform = function Util_apply3dTransform(m, v) { return [ m[0] * v[0] + m[1] * v[1] + m[2] * v[2], m[3] * v[0] + m[4] * v[1] + m[5] * v[2], m[6] * v[0] + m[7] * v[1] + m[8] * v[2] ]; }; // This calculation uses Singular Value Decomposition. // The SVD can be represented with formula A = USV. We are interested in the // matrix S here because it represents the scale values. Util.singularValueDecompose2dScale = function Util_singularValueDecompose2dScale(m) { var transpose = [m[0], m[2], m[1], m[3]]; // Multiply matrix m with its transpose. var a = m[0] * transpose[0] + m[1] * transpose[2]; var b = m[0] * transpose[1] + m[1] * transpose[3]; var c = m[2] * transpose[0] + m[3] * transpose[2]; var d = m[2] * transpose[1] + m[3] * transpose[3]; // Solve the second degree polynomial to get roots. var first = (a + d) / 2; var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2; var sx = first + second || 1; var sy = first - second || 1; // Scale values are the square roots of the eigenvalues. return [Math.sqrt(sx), Math.sqrt(sy)]; }; // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2) // For coordinate systems whose origin lies in the bottom-left, this // means normalization to (BL,TR) ordering. For systems with origin in the // top-left, this means (TL,BR) ordering. Util.normalizeRect = function Util_normalizeRect(rect) { var r = rect.slice(0); // clone rect if (rect[0] > rect[2]) { r[0] = rect[2]; r[2] = rect[0]; } if (rect[1] > rect[3]) { r[1] = rect[3]; r[3] = rect[1]; } return r; }; // Returns a rectangle [x1, y1, x2, y2] corresponding to the // intersection of rect1 and rect2. If no intersection, returns 'false' // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2] Util.intersect = function Util_intersect(rect1, rect2) { function compare(a, b) { return a - b; } // Order points along the axes var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare), orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare), result = []; rect1 = Util.normalizeRect(rect1); rect2 = Util.normalizeRect(rect2); // X: first and second points belong to different rectangles? if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) || (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) { // Intersection must be between second and third points result[0] = orderedX[1]; result[2] = orderedX[2]; } else { return false; } // Y: first and second points belong to different rectangles? if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) || (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) { // Intersection must be between second and third points result[1] = orderedY[1]; result[3] = orderedY[2]; } else { return false; } return result; }; Util.sign = function Util_sign(num) { return num < 0 ? -1 : 1; }; Util.appendToArray = function Util_appendToArray(arr1, arr2) { Array.prototype.push.apply(arr1, arr2); }; Util.prependToArray = function Util_prependToArray(arr1, arr2) { Array.prototype.unshift.apply(arr1, arr2); }; Util.extendObj = function extendObj(obj1, obj2) { for (var key in obj2) { obj1[key] = obj2[key]; } }; Util.getInheritableProperty = function Util_getInheritableProperty(dict, name) { while (dict && !dict.has(name)) { dict = dict.get('Parent'); } if (!dict) { return null; } return dict.get(name); }; Util.inherit = function Util_inherit(sub, base, prototype) { sub.prototype = Object.create(base.prototype); sub.prototype.constructor = sub; for (var prop in prototype) { sub.prototype[prop] = prototype[prop]; } }; Util.loadScript = function Util_loadScript(src, callback) { var script = document.createElement('script'); var loaded = false; script.setAttribute('src', src); if (callback) { script.onload = function() { if (!loaded) { callback(); } loaded = true; }; } document.getElementsByTagName('head')[0].appendChild(script); }; return Util; })(); /** * PDF page viewport created based on scale, rotation and offset. * @class * @alias PDFJS.PageViewport */ var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() { /** * @constructor * @private * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates. * @param scale {number} scale of the viewport. * @param rotation {number} rotations of the viewport in degrees. * @param offsetX {number} offset X * @param offsetY {number} offset Y * @param dontFlip {boolean} if true, axis Y will not be flipped. */ function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) { this.viewBox = viewBox; this.scale = scale; this.rotation = rotation; this.offsetX = offsetX; this.offsetY = offsetY; // creating transform to convert pdf coordinate system to the normal // canvas like coordinates taking in account scale and rotation var centerX = (viewBox[2] + viewBox[0]) / 2; var centerY = (viewBox[3] + viewBox[1]) / 2; var rotateA, rotateB, rotateC, rotateD; rotation = rotation % 360; rotation = rotation < 0 ? rotation + 360 : rotation; switch (rotation) { case 180: rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1; break; case 90: rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0; break; case 270: rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0; break; //case 0: default: rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1; break; } if (dontFlip) { rotateC = -rotateC; rotateD = -rotateD; } var offsetCanvasX, offsetCanvasY; var width, height; if (rotateA === 0) { offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX; offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY; width = Math.abs(viewBox[3] - viewBox[1]) * scale; height = Math.abs(viewBox[2] - viewBox[0]) * scale; } else { offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX; offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY; width = Math.abs(viewBox[2] - viewBox[0]) * scale; height = Math.abs(viewBox[3] - viewBox[1]) * scale; } // creating transform for the following operations: // translate(-centerX, -centerY), rotate and flip vertically, // scale, and translate(offsetCanvasX, offsetCanvasY) this.transform = [ rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY ]; this.width = width; this.height = height; this.fontScale = scale; } PageViewport.prototype = /** @lends PDFJS.PageViewport.prototype */ { /** * Clones viewport with additional properties. * @param args {Object} (optional) If specified, may contain the 'scale' or * 'rotation' properties to override the corresponding properties in * the cloned viewport. * @returns {PDFJS.PageViewport} Cloned viewport. */ clone: function PageViewPort_clone(args) { args = args || {}; var scale = 'scale' in args ? args.scale : this.scale; var rotation = 'rotation' in args ? args.rotation : this.rotation; return new PageViewport(this.viewBox.slice(), scale, rotation, this.offsetX, this.offsetY, args.dontFlip); }, /** * Converts PDF point to the viewport coordinates. For examples, useful for * converting PDF location into canvas pixel coordinates. * @param x {number} X coordinate. * @param y {number} Y coordinate. * @returns {Object} Object that contains 'x' and 'y' properties of the * point in the viewport coordinate space. * @see {@link convertToPdfPoint} * @see {@link convertToViewportRectangle} */ convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) { return Util.applyTransform([x, y], this.transform); }, /** * Converts PDF rectangle to the viewport coordinates. * @param rect {Array} xMin, yMin, xMax and yMax coordinates. * @returns {Array} Contains corresponding coordinates of the rectangle * in the viewport coordinate space. * @see {@link convertToViewportPoint} */ convertToViewportRectangle: function PageViewport_convertToViewportRectangle(rect) { var tl = Util.applyTransform([rect[0], rect[1]], this.transform); var br = Util.applyTransform([rect[2], rect[3]], this.transform); return [tl[0], tl[1], br[0], br[1]]; }, /** * Converts viewport coordinates to the PDF location. For examples, useful * for converting canvas pixel location into PDF one. * @param x {number} X coordinate. * @param y {number} Y coordinate. * @returns {Object} Object that contains 'x' and 'y' properties of the * point in the PDF coordinate space. * @see {@link convertToViewportPoint} */ convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) { return Util.applyInverseTransform([x, y], this.transform); } }; return PageViewport; })(); var PDFStringTranslateTable = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C, 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160, 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC ]; function stringToPDFString(str) { var i, n = str.length, strBuf = []; if (str[0] === '\xFE' && str[1] === '\xFF') { // UTF16BE BOM for (i = 2; i < n; i += 2) { strBuf.push(String.fromCharCode( (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1))); } } else { for (i = 0; i < n; ++i) { var code = PDFStringTranslateTable[str.charCodeAt(i)]; strBuf.push(code ? String.fromCharCode(code) : str.charAt(i)); } } return strBuf.join(''); } function stringToUTF8String(str) { return decodeURIComponent(escape(str)); } function utf8StringToString(str) { return unescape(encodeURIComponent(str)); } function isEmptyObj(obj) { for (var key in obj) { return false; } return true; } function isBool(v) { return typeof v === 'boolean'; } function isInt(v) { return typeof v === 'number' && ((v | 0) === v); } function isNum(v) { return typeof v === 'number'; } function isString(v) { return typeof v === 'string'; } function isArray(v) { return v instanceof Array; } function isArrayBuffer(v) { return typeof v === 'object' && v !== null && v.byteLength !== undefined; } /** * Promise Capability object. * * @typedef {Object} PromiseCapability * @property {Promise} promise - A promise object. * @property {function} resolve - Fullfills the promise. * @property {function} reject - Rejects the promise. */ /** * Creates a promise capability object. * @alias PDFJS.createPromiseCapability * * @return {PromiseCapability} A capability object contains: * - a Promise, resolve and reject methods. */ function createPromiseCapability() { var capability = {}; capability.promise = new Promise(function (resolve, reject) { capability.resolve = resolve; capability.reject = reject; }); return capability; } PDFJS.createPromiseCapability = createPromiseCapability; /** * Polyfill for Promises: * The following promise implementation tries to generally implement the * Promise/A+ spec. Some notable differences from other promise libaries are: * - There currently isn't a seperate deferred and promise object. * - Unhandled rejections eventually show an error if they aren't handled. * * Based off of the work in: * https://bugzilla.mozilla.org/show_bug.cgi?id=810490 */ (function PromiseClosure() { if (globalScope.Promise) { // Promises existing in the DOM/Worker, checking presence of all/resolve if (typeof globalScope.Promise.all !== 'function') { globalScope.Promise.all = function (iterable) { var count = 0, results = [], resolve, reject; var promise = new globalScope.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); iterable.forEach(function (p, i) { count++; p.then(function (result) { results[i] = result; count--; if (count === 0) { resolve(results); } }, reject); }); if (count === 0) { resolve(results); } return promise; }; } if (typeof globalScope.Promise.resolve !== 'function') { globalScope.Promise.resolve = function (value) { return new globalScope.Promise(function (resolve) { resolve(value); }); }; } if (typeof globalScope.Promise.reject !== 'function') { globalScope.Promise.reject = function (reason) { return new globalScope.Promise(function (resolve, reject) { reject(reason); }); }; } if (typeof globalScope.Promise.prototype.catch !== 'function') { globalScope.Promise.prototype.catch = function (onReject) { return globalScope.Promise.prototype.then(undefined, onReject); }; } return; } var STATUS_PENDING = 0; var STATUS_RESOLVED = 1; var STATUS_REJECTED = 2; // In an attempt to avoid silent exceptions, unhandled rejections are // tracked and if they aren't handled in a certain amount of time an // error is logged. var REJECTION_TIMEOUT = 500; var HandlerManager = { handlers: [], running: false, unhandledRejections: [], pendingRejectionCheck: false, scheduleHandlers: function scheduleHandlers(promise) { if (promise._status === STATUS_PENDING) { return; } this.handlers = this.handlers.concat(promise._handlers); promise._handlers = []; if (this.running) { return; } this.running = true; setTimeout(this.runHandlers.bind(this), 0); }, runHandlers: function runHandlers() { var RUN_TIMEOUT = 1; // ms var timeoutAt = Date.now() + RUN_TIMEOUT; while (this.handlers.length > 0) { var handler = this.handlers.shift(); var nextStatus = handler.thisPromise._status; var nextValue = handler.thisPromise._value; try { if (nextStatus === STATUS_RESOLVED) { if (typeof handler.onResolve === 'function') { nextValue = handler.onResolve(nextValue); } } else if (typeof handler.onReject === 'function') { nextValue = handler.onReject(nextValue); nextStatus = STATUS_RESOLVED; if (handler.thisPromise._unhandledRejection) { this.removeUnhandeledRejection(handler.thisPromise); } } } catch (ex) { nextStatus = STATUS_REJECTED; nextValue = ex; } handler.nextPromise._updateStatus(nextStatus, nextValue); if (Date.now() >= timeoutAt) { break; } } if (this.handlers.length > 0) { setTimeout(this.runHandlers.bind(this), 0); return; } this.running = false; }, addUnhandledRejection: function addUnhandledRejection(promise) { this.unhandledRejections.push({ promise: promise, time: Date.now() }); this.scheduleRejectionCheck(); }, removeUnhandeledRejection: function removeUnhandeledRejection(promise) { promise._unhandledRejection = false; for (var i = 0; i < this.unhandledRejections.length; i++) { if (this.unhandledRejections[i].promise === promise) { this.unhandledRejections.splice(i); i--; } } }, scheduleRejectionCheck: function scheduleRejectionCheck() { if (this.pendingRejectionCheck) { return; } this.pendingRejectionCheck = true; setTimeout(function rejectionCheck() { this.pendingRejectionCheck = false; var now = Date.now(); for (var i = 0; i < this.unhandledRejections.length; i++) { if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) { var unhandled = this.unhandledRejections[i].promise._value; var msg = 'Unhandled rejection: ' + unhandled; if (unhandled.stack) { msg += '\n' + unhandled.stack; } warn(msg); this.unhandledRejections.splice(i); i--; } } if (this.unhandledRejections.length) { this.scheduleRejectionCheck(); } }.bind(this), REJECTION_TIMEOUT); } }; function Promise(resolver) { this._status = STATUS_PENDING; this._handlers = []; try { resolver.call(this, this._resolve.bind(this), this._reject.bind(this)); } catch (e) { this._reject(e); } } /** * Builds a promise that is resolved when all the passed in promises are * resolved. * @param {array} array of data and/or promises to wait for. * @return {Promise} New dependant promise. */ Promise.all = function Promise_all(promises) { var resolveAll, rejectAll; var deferred = new Promise(function (resolve, reject) { resolveAll = resolve; rejectAll = reject; }); var unresolved = promises.length; var results = []; if (unresolved === 0) { resolveAll(results); return deferred; } function reject(reason) { if (deferred._status === STATUS_REJECTED) { return; } results = []; rejectAll(reason); } for (var i = 0, ii = promises.length; i < ii; ++i) { var promise = promises[i]; var resolve = (function(i) { return function(value) { if (deferred._status === STATUS_REJECTED) { return; } results[i] = value; unresolved--; if (unresolved === 0) { resolveAll(results); } }; })(i); if (Promise.isPromise(promise)) { promise.then(resolve, reject); } else { resolve(promise); } } return deferred; }; /** * Checks if the value is likely a promise (has a 'then' function). * @return {boolean} true if value is thenable */ Promise.isPromise = function Promise_isPromise(value) { return value && typeof value.then === 'function'; }; /** * Creates resolved promise * @param value resolve value * @returns {Promise} */ Promise.resolve = function Promise_resolve(value) { return new Promise(function (resolve) { resolve(value); }); }; /** * Creates rejected promise * @param reason rejection value * @returns {Promise} */ Promise.reject = function Promise_reject(reason) { return new Promise(function (resolve, reject) { reject(reason); }); }; Promise.prototype = { _status: null, _value: null, _handlers: null, _unhandledRejection: null, _updateStatus: function Promise__updateStatus(status, value) { if (this._status === STATUS_RESOLVED || this._status === STATUS_REJECTED) { return; } if (status === STATUS_RESOLVED && Promise.isPromise(value)) { value.then(this._updateStatus.bind(this, STATUS_RESOLVED), this._updateStatus.bind(this, STATUS_REJECTED)); return; } this._status = status; this._value = value; if (status === STATUS_REJECTED && this._handlers.length === 0) { this._unhandledRejection = true; HandlerManager.addUnhandledRejection(this); } HandlerManager.scheduleHandlers(this); }, _resolve: function Promise_resolve(value) { this._updateStatus(STATUS_RESOLVED, value); }, _reject: function Promise_reject(reason) { this._updateStatus(STATUS_REJECTED, reason); }, then: function Promise_then(onResolve, onReject) { var nextPromise = new Promise(function (resolve, reject) { this.resolve = resolve; this.reject = reject; }); this._handlers.push({ thisPromise: this, onResolve: onResolve, onReject: onReject, nextPromise: nextPromise }); HandlerManager.scheduleHandlers(this); return nextPromise; }, catch: function Promise_catch(onReject) { return this.then(undefined, onReject); } }; globalScope.Promise = Promise; })(); var StatTimer = (function StatTimerClosure() { function rpad(str, pad, length) { while (str.length < length) { str += pad; } return str; } function StatTimer() { this.started = {}; this.times = []; this.enabled = true; } StatTimer.prototype = { time: function StatTimer_time(name) { if (!this.enabled) { return; } if (name in this.started) { warn('Timer is already running for ' + name); } this.started[name] = Date.now(); }, timeEnd: function StatTimer_timeEnd(name) { if (!this.enabled) { return; } if (!(name in this.started)) { warn('Timer has not been started for ' + name); } this.times.push({ 'name': name, 'start': this.started[name], 'end': Date.now() }); // Remove timer from started so it can be called again. delete this.started[name]; }, toString: function StatTimer_toString() { var i, ii; var times = this.times; var out = ''; // Find the longest name for padding purposes. var longest = 0; for (i = 0, ii = times.length; i < ii; ++i) { var name = times[i]['name']; if (name.length > longest) { longest = name.length; } } for (i = 0, ii = times.length; i < ii; ++i) { var span = times[i]; var duration = span.end - span.start; out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n'; } return out; } }; return StatTimer; })(); PDFJS.createBlob = function createBlob(data, contentType) { if (typeof Blob !== 'undefined') { return new Blob([data], { type: contentType }); } // Blob builder is deprecated in FF14 and removed in FF18. var bb = new MozBlobBuilder(); bb.append(data); return bb.getBlob(contentType); }; PDFJS.createObjectURL = (function createObjectURLClosure() { // Blob/createObjectURL is not available, falling back to data schema. var digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; return function createObjectURL(data, contentType) { if (!PDFJS.disableCreateObjectURL && typeof URL !== 'undefined' && URL.createObjectURL) { var blob = PDFJS.createBlob(data, contentType); return URL.createObjectURL(blob); } var buffer = 'data:' + contentType + ';base64,'; for (var i = 0, ii = data.length; i < ii; i += 3) { var b1 = data[i] & 0xFF; var b2 = data[i + 1] & 0xFF; var b3 = data[i + 2] & 0xFF; var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4); var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64; var d4 = i + 2 < ii ? (b3 & 0x3F) : 64; buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4]; } return buffer; }; })(); function MessageHandler(sourceName, targetName, comObj) { this.sourceName = sourceName; this.targetName = targetName; this.comObj = comObj; this.callbackIndex = 1; this.postMessageTransfers = true; var callbacksCapabilities = this.callbacksCapabilities = {}; var ah = this.actionHandler = {}; this._onComObjOnMessage = function messageHandlerComObjOnMessage(event) { var data = event.data; if (data.targetName !== this.sourceName) { return; } if (data.isReply) { var callbackId = data.callbackId; if (data.callbackId in callbacksCapabilities) { var callback = callbacksCapabilities[callbackId]; delete callbacksCapabilities[callbackId]; if ('error' in data) { callback.reject(data.error); } else { callback.resolve(data.data); } } else { error('Cannot resolve callback ' + callbackId); } } else if (data.action in ah) { var action = ah[data.action]; if (data.callbackId) { var sourceName = this.sourceName; var targetName = data.sourceName; Promise.resolve().then(function () { return action[0].call(action[1], data.data); }).then(function (result) { comObj.postMessage({ sourceName: sourceName, targetName: targetName, isReply: true, callbackId: data.callbackId, data: result }); }, function (reason) { if (reason instanceof Error) { // Serialize error to avoid "DataCloneError" reason = reason + ''; } comObj.postMessage({ sourceName: sourceName, targetName: targetName, isReply: true, callbackId: data.callbackId, error: reason }); }); } else { action[0].call(action[1], data.data); } } else { error('Unknown action from worker: ' + data.action); } }.bind(this); comObj.addEventListener('message', this._onComObjOnMessage); } MessageHandler.prototype = { on: function messageHandlerOn(actionName, handler, scope) { var ah = this.actionHandler; if (ah[actionName]) { error('There is already an actionName called "' + actionName + '"'); } ah[actionName] = [handler, scope]; }, /** * Sends a message to the comObj to invoke the action with the supplied data. * @param {String} actionName Action to call. * @param {JSON} data JSON data to send. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers */ send: function messageHandlerSend(actionName, data, transfers) { var message = { sourceName: this.sourceName, targetName: this.targetName, action: actionName, data: data }; this.postMessage(message, transfers); }, /** * Sends a message to the comObj to invoke the action with the supplied data. * Expects that other side will callback with the response. * @param {String} actionName Action to call. * @param {JSON} data JSON data to send. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers. * @returns {Promise} Promise to be resolved with response data. */ sendWithPromise: function messageHandlerSendWithPromise(actionName, data, transfers) { var callbackId = this.callbackIndex++; var message = { sourceName: this.sourceName, targetName: this.targetName, action: actionName, data: data, callbackId: callbackId }; var capability = createPromiseCapability(); this.callbacksCapabilities[callbackId] = capability; try { this.postMessage(message, transfers); } catch (e) { capability.reject(e); } return capability.promise; }, /** * Sends raw message to the comObj. * @private * @param message {Object} Raw message. * @param transfers List of transfers/ArrayBuffers, or undefined. */ postMessage: function (message, transfers) { if (transfers && this.postMessageTransfers) { this.comObj.postMessage(message, transfers); } else { this.comObj.postMessage(message); } }, destroy: function () { this.comObj.removeEventListener('message', this._onComObjOnMessage); } }; function loadJpegStream(id, imageUrl, objs) { var img = new Image(); img.onload = (function loadJpegStream_onloadClosure() { objs.resolve(id, img); }); img.onerror = (function loadJpegStream_onerrorClosure() { objs.resolve(id, null); warn('Error during JPEG image loading'); }); img.src = imageUrl; } exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX; exports.IDENTITY_MATRIX = IDENTITY_MATRIX; exports.OPS = OPS; exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES; exports.AnnotationBorderStyleType = AnnotationBorderStyleType; exports.AnnotationFlag = AnnotationFlag; exports.AnnotationType = AnnotationType; exports.FontType = FontType; exports.ImageKind = ImageKind; exports.InvalidPDFException = InvalidPDFException; exports.LinkTarget = LinkTarget; exports.LinkTargetStringMap = LinkTargetStringMap; exports.MessageHandler = MessageHandler; exports.MissingDataException = MissingDataException; exports.MissingPDFException = MissingPDFException; exports.NotImplementedException = NotImplementedException; exports.PasswordException = PasswordException; exports.PasswordResponses = PasswordResponses; exports.StatTimer = StatTimer; exports.StreamType = StreamType; exports.TextRenderingMode = TextRenderingMode; exports.UnexpectedResponseException = UnexpectedResponseException; exports.UnknownErrorException = UnknownErrorException; exports.Util = Util; exports.XRefParseException = XRefParseException; exports.assert = assert; exports.bytesToString = bytesToString; exports.combineUrl = combineUrl; exports.createPromiseCapability = createPromiseCapability; exports.deprecated = deprecated; exports.error = error; exports.info = info; exports.isArray = isArray; exports.isArrayBuffer = isArrayBuffer; exports.isBool = isBool; exports.isEmptyObj = isEmptyObj; exports.isExternalLinkTargetSet = isExternalLinkTargetSet; exports.isInt = isInt; exports.isNum = isNum; exports.isString = isString; exports.isValidUrl = isValidUrl; exports.loadJpegStream = loadJpegStream; exports.log2 = log2; exports.readInt8 = readInt8; exports.readUint16 = readUint16; exports.readUint32 = readUint32; exports.removeNullCharacters = removeNullCharacters; exports.shadow = shadow; exports.string32 = string32; exports.stringToBytes = stringToBytes; exports.stringToPDFString = stringToPDFString; exports.stringToUTF8String = stringToUTF8String; exports.utf8StringToString = utf8StringToString; exports.warn = warn; })); (function (root, factory) { { factory((root.pdfjsDisplayAnnotationLayer = {}), root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils); } }(this, function (exports, sharedUtil, displayDOMUtils) { var AnnotationBorderStyleType = sharedUtil.AnnotationBorderStyleType; var AnnotationType = sharedUtil.AnnotationType; var Util = sharedUtil.Util; var isExternalLinkTargetSet = sharedUtil.isExternalLinkTargetSet; var LinkTargetStringMap = sharedUtil.LinkTargetStringMap; var removeNullCharacters = sharedUtil.removeNullCharacters; var warn = sharedUtil.warn; var CustomStyle = displayDOMUtils.CustomStyle; /** * @typedef {Object} AnnotationElementParameters * @property {Object} data * @property {HTMLDivElement} layer * @property {PDFPage} page * @property {PageViewport} viewport * @property {IPDFLinkService} linkService */ /** * @class * @alias AnnotationElementFactory */ function AnnotationElementFactory() {} AnnotationElementFactory.prototype = /** @lends AnnotationElementFactory.prototype */ { /** * @param {AnnotationElementParameters} parameters * @returns {AnnotationElement} */ create: function AnnotationElementFactory_create(parameters) { var subtype = parameters.data.annotationType; switch (subtype) { case AnnotationType.LINK: return new LinkAnnotationElement(parameters); case AnnotationType.TEXT: return new TextAnnotationElement(parameters); case AnnotationType.WIDGET: return new WidgetAnnotationElement(parameters); case AnnotationType.POPUP: return new PopupAnnotationElement(parameters); case AnnotationType.HIGHLIGHT: return new HighlightAnnotationElement(parameters); case AnnotationType.UNDERLINE: return new UnderlineAnnotationElement(parameters); case AnnotationType.SQUIGGLY: return new SquigglyAnnotationElement(parameters); case AnnotationType.STRIKEOUT: return new StrikeOutAnnotationElement(parameters); default: throw new Error('Unimplemented annotation type "' + subtype + '"'); } } }; /** * @class * @alias AnnotationElement */ var AnnotationElement = (function AnnotationElementClosure() { function AnnotationElement(parameters) { this.data = parameters.data; this.layer = parameters.layer; this.page = parameters.page; this.viewport = parameters.viewport; this.linkService = parameters.linkService; this.container = this._createContainer(); } AnnotationElement.prototype = /** @lends AnnotationElement.prototype */ { /** * Create an empty container for the annotation's HTML element. * * @private * @memberof AnnotationElement * @returns {HTMLSectionElement} */ _createContainer: function AnnotationElement_createContainer() { var data = this.data, page = this.page, viewport = this.viewport; var container = document.createElement('section'); var width = data.rect[2] - data.rect[0]; var height = data.rect[3] - data.rect[1]; container.setAttribute('data-annotation-id', data.id); // Do *not* modify `data.rect`, since that will corrupt the annotation // position on subsequent calls to `_createContainer` (see issue 6804). var rect = Util.normalizeRect([ data.rect[0], page.view[3] - data.rect[1] + page.view[1], data.rect[2], page.view[3] - data.rect[3] + page.view[1] ]); CustomStyle.setProp('transform', container, 'matrix(' + viewport.transform.join(',') + ')'); CustomStyle.setProp('transformOrigin', container, -rect[0] + 'px ' + -rect[1] + 'px'); if (data.borderStyle.width > 0) { container.style.borderWidth = data.borderStyle.width + 'px'; if (data.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) { // Underline styles only have a bottom border, so we do not need // to adjust for all borders. This yields a similar result as // Adobe Acrobat/Reader. width = width - 2 * data.borderStyle.width; height = height - 2 * data.borderStyle.width; } var horizontalRadius = data.borderStyle.horizontalCornerRadius; var verticalRadius = data.borderStyle.verticalCornerRadius; if (horizontalRadius > 0 || verticalRadius > 0) { var radius = horizontalRadius + 'px / ' + verticalRadius + 'px'; CustomStyle.setProp('borderRadius', container, radius); } switch (data.borderStyle.style) { case AnnotationBorderStyleType.SOLID: container.style.borderStyle = 'solid'; break; case AnnotationBorderStyleType.DASHED: container.style.borderStyle = 'dashed'; break; case AnnotationBorderStyleType.BEVELED: warn('Unimplemented border style: beveled'); break; case AnnotationBorderStyleType.INSET: warn('Unimplemented border style: inset'); break; case AnnotationBorderStyleType.UNDERLINE: container.style.borderBottomStyle = 'solid'; break; default: break; } if (data.color) { container.style.borderColor = Util.makeCssRgb(data.color[0] | 0, data.color[1] | 0, data.color[2] | 0); } else { // Transparent (invisible) border, so do not draw it at all. container.style.borderWidth = 0; } } container.style.left = rect[0] + 'px'; container.style.top = rect[1] + 'px'; container.style.width = width + 'px'; container.style.height = height + 'px'; return container; }, /** * Render the annotation's HTML element in the empty container. * * @public * @memberof AnnotationElement */ render: function AnnotationElement_render() { throw new Error('Abstract method AnnotationElement.render called'); } }; return AnnotationElement; })(); /** * @class * @alias LinkAnnotationElement */ var LinkAnnotationElement = (function LinkAnnotationElementClosure() { function LinkAnnotationElement(parameters) { AnnotationElement.call(this, parameters); } Util.inherit(LinkAnnotationElement, AnnotationElement, { /** * Render the link annotation's HTML element in the empty container. * * @public * @memberof LinkAnnotationElement * @returns {HTMLSectionElement} */ render: function LinkAnnotationElement_render() { this.container.className = 'linkAnnotation'; var link = document.createElement('a'); link.href = link.title = (this.data.url ? removeNullCharacters(this.data.url) : ''); if (this.data.url && isExternalLinkTargetSet()) { link.target = LinkTargetStringMap[PDFJS.externalLinkTarget]; } // Strip referrer from the URL. if (this.data.url) { link.rel = PDFJS.externalLinkRel; } if (!this.data.url) { if (this.data.action) { this._bindNamedAction(link, this.data.action); } else { this._bindLink(link, ('dest' in this.data) ? this.data.dest : null); } } this.container.appendChild(link); return this.container; }, /** * Bind internal links to the link element. * * @private * @param {Object} link * @param {Object} destination * @memberof LinkAnnotationElement */ _bindLink: function LinkAnnotationElement_bindLink(link, destination) { var self = this; link.href = this.linkService.getDestinationHash(destination); link.onclick = function() { if (destination) { self.linkService.navigateTo(destination); } return false; }; if (destination) { link.className = 'internalLink'; } }, /** * Bind named actions to the link element. * * @private * @param {Object} link * @param {Object} action * @memberof LinkAnnotationElement */ _bindNamedAction: function LinkAnnotationElement_bindNamedAction(link, action) { var self = this; link.href = this.linkService.getAnchorUrl(''); link.onclick = function() { self.linkService.executeNamedAction(action); return false; }; link.className = 'internalLink'; } }); return LinkAnnotationElement; })(); /** * @class * @alias TextAnnotationElement */ var TextAnnotationElement = (function TextAnnotationElementClosure() { function TextAnnotationElement(parameters) { AnnotationElement.call(this, parameters); } Util.inherit(TextAnnotationElement, AnnotationElement, { /** * Render the text annotation's HTML element in the empty container. * * @public * @memberof TextAnnotationElement * @returns {HTMLSectionElement} */ render: function TextAnnotationElement_render() { this.container.className = 'textAnnotation'; var image = document.createElement('img'); image.style.height = this.container.style.height; image.style.width = this.container.style.width; image.src = PDFJS.imageResourcesPath + 'annotation-' + this.data.name.toLowerCase() + '.svg'; image.alt = '[{{type}} Annotation]'; image.dataset.l10nId = 'text_annotation_type'; image.dataset.l10nArgs = JSON.stringify({type: this.data.name}); if (!this.data.hasPopup) { var popupElement = new PopupElement({ container: this.container, trigger: image, color: this.data.color, title: this.data.title, contents: this.data.contents, hideWrapper: true }); var popup = popupElement.render(); // Position the popup next to the Text annotation's container. popup.style.left = image.style.width; this.container.appendChild(popup); } this.container.appendChild(image); return this.container; } }); return TextAnnotationElement; })(); /** * @class * @alias WidgetAnnotationElement */ var WidgetAnnotationElement = (function WidgetAnnotationElementClosure() { function WidgetAnnotationElement(parameters) { AnnotationElement.call(this, parameters); } Util.inherit(WidgetAnnotationElement, AnnotationElement, { /** * Render the widget annotation's HTML element in the empty container. * * @public * @memberof WidgetAnnotationElement * @returns {HTMLSectionElement} */ render: function WidgetAnnotationElement_render() { var content = document.createElement('div'); content.textContent = this.data.fieldValue; var textAlignment = this.data.textAlignment; content.style.textAlign = ['left', 'center', 'right'][textAlignment]; content.style.verticalAlign = 'middle'; content.style.display = 'table-cell'; var font = (this.data.fontRefName ? this.page.commonObjs.getData(this.data.fontRefName) : null); this._setTextStyle(content, font); this.container.appendChild(content); return this.container; }, /** * Apply text styles to the text in the element. * * @private * @param {HTMLDivElement} element * @param {Object} font * @memberof WidgetAnnotationElement */ _setTextStyle: function WidgetAnnotationElement_setTextStyle(element, font) { // TODO: This duplicates some of the logic in CanvasGraphics.setFont(). var style = element.style; style.fontSize = this.data.fontSize + 'px'; style.direction = (this.data.fontDirection < 0 ? 'rtl': 'ltr'); if (!font) { return; } style.fontWeight = (font.black ? (font.bold ? '900' : 'bold') : (font.bold ? 'bold' : 'normal')); style.fontStyle = (font.italic ? 'italic' : 'normal'); // Use a reasonable default font if the font doesn't specify a fallback. var fontFamily = font.loadedName ? '"' + font.loadedName + '", ' : ''; var fallbackName = font.fallbackName || 'Helvetica, sans-serif'; style.fontFamily = fontFamily + fallbackName; } }); return WidgetAnnotationElement; })(); /** * @class * @alias PopupAnnotationElement */ var PopupAnnotationElement = (function PopupAnnotationElementClosure() { function PopupAnnotationElement(parameters) { AnnotationElement.call(this, parameters); } Util.inherit(PopupAnnotationElement, AnnotationElement, { /** * Render the popup annotation's HTML element in the empty container. * * @public * @memberof PopupAnnotationElement * @returns {HTMLSectionElement} */ render: function PopupAnnotationElement_render() { this.container.className = 'popupAnnotation'; var selector = '[data-annotation-id="' + this.data.parentId + '"]'; var parentElement = this.layer.querySelector(selector); if (!parentElement) { return this.container; } var popup = new PopupElement({ container: this.container, trigger: parentElement, color: this.data.color, title: this.data.title, contents: this.data.contents }); // Position the popup next to the parent annotation's container. // PDF viewers ignore a popup annotation's rectangle. var parentLeft = parseFloat(parentElement.style.left); var parentWidth = parseFloat(parentElement.style.width); CustomStyle.setProp('transformOrigin', this.container, -(parentLeft + parentWidth) + 'px -' + parentElement.style.top); this.container.style.left = (parentLeft + parentWidth) + 'px'; this.container.appendChild(popup.render()); return this.container; } }); return PopupAnnotationElement; })(); /** * @class * @alias PopupElement */ var PopupElement = (function PopupElementClosure() { var BACKGROUND_ENLIGHT = 0.7; function PopupElement(parameters) { this.container = parameters.container; this.trigger = parameters.trigger; this.color = parameters.color; this.title = parameters.title; this.contents = parameters.contents; this.hideWrapper = parameters.hideWrapper || false; this.pinned = false; } PopupElement.prototype = /** @lends PopupElement.prototype */ { /** * Render the popup's HTML element. * * @public * @memberof PopupElement * @returns {HTMLSectionElement} */ render: function PopupElement_render() { var wrapper = document.createElement('div'); wrapper.className = 'popupWrapper'; // For Popup annotations we hide the entire section because it contains // only the popup. However, for Text annotations without a separate Popup // annotation, we cannot hide the entire container as the image would // disappear too. In that special case, hiding the wrapper suffices. this.hideElement = (this.hideWrapper ? wrapper : this.container); this.hideElement.setAttribute('hidden', true); var popup = document.createElement('div'); popup.className = 'popup'; var color = this.color; if (color) { // Enlighten the color. var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0]; var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1]; var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2]; popup.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0); } var contents = this._formatContents(this.contents); var title = document.createElement('h1'); title.textContent = this.title; // Attach the event listeners to the trigger element. this.trigger.addEventListener('click', this._toggle.bind(this)); this.trigger.addEventListener('mouseover', this._show.bind(this, false)); this.trigger.addEventListener('mouseout', this._hide.bind(this, false)); popup.addEventListener('click', this._hide.bind(this, true)); popup.appendChild(title); popup.appendChild(contents); wrapper.appendChild(popup); return wrapper; }, /** * Format the contents of the popup by adding newlines where necessary. * * @private * @param {string} contents * @memberof PopupElement * @returns {HTMLParagraphElement} */ _formatContents: function PopupElement_formatContents(contents) { var p = document.createElement('p'); var lines = contents.split(/(?:\r\n?|\n)/); for (var i = 0, ii = lines.length; i < ii; ++i) { var line = lines[i]; p.appendChild(document.createTextNode(line)); if (i < (ii - 1)) { p.appendChild(document.createElement('br')); } } return p; }, /** * Toggle the visibility of the popup. * * @private * @memberof PopupElement */ _toggle: function PopupElement_toggle() { if (this.pinned) { this._hide(true); } else { this._show(true); } }, /** * Show the popup. * * @private * @param {boolean} pin * @memberof PopupElement */ _show: function PopupElement_show(pin) { if (pin) { this.pinned = true; } if (this.hideElement.hasAttribute('hidden')) { this.hideElement.removeAttribute('hidden'); this.container.style.zIndex += 1; } }, /** * Hide the popup. * * @private * @param {boolean} unpin * @memberof PopupElement */ _hide: function PopupElement_hide(unpin) { if (unpin) { this.pinned = false; } if (!this.hideElement.hasAttribute('hidden') && !this.pinned) { this.hideElement.setAttribute('hidden', true); this.container.style.zIndex -= 1; } } }; return PopupElement; })(); /** * @class * @alias HighlightAnnotationElement */ var HighlightAnnotationElement = ( function HighlightAnnotationElementClosure() { function HighlightAnnotationElement(parameters) { AnnotationElement.call(this, parameters); } Util.inherit(HighlightAnnotationElement, AnnotationElement, { /** * Render the highlight annotation's HTML element in the empty container. * * @public * @memberof HighlightAnnotationElement * @returns {HTMLSectionElement} */ render: function HighlightAnnotationElement_render() { this.container.className = 'highlightAnnotation'; return this.container; } }); return HighlightAnnotationElement; })(); /** * @class * @alias UnderlineAnnotationElement */ var UnderlineAnnotationElement = ( function UnderlineAnnotationElementClosure() { function UnderlineAnnotationElement(parameters) { AnnotationElement.call(this, parameters); } Util.inherit(UnderlineAnnotationElement, AnnotationElement, { /** * Render the underline annotation's HTML element in the empty container. * * @public * @memberof UnderlineAnnotationElement * @returns {HTMLSectionElement} */ render: function UnderlineAnnotationElement_render() { this.container.className = 'underlineAnnotation'; return this.container; } }); return UnderlineAnnotationElement; })(); /** * @class * @alias SquigglyAnnotationElement */ var SquigglyAnnotationElement = (function SquigglyAnnotationElementClosure() { function SquigglyAnnotationElement(parameters) { AnnotationElement.call(this, parameters); } Util.inherit(SquigglyAnnotationElement, AnnotationElement, { /** * Render the squiggly annotation's HTML element in the empty container. * * @public * @memberof SquigglyAnnotationElement * @returns {HTMLSectionElement} */ render: function SquigglyAnnotationElement_render() { this.container.className = 'squigglyAnnotation'; return this.container; } }); return SquigglyAnnotationElement; })(); /** * @class * @alias StrikeOutAnnotationElement */ var StrikeOutAnnotationElement = ( function StrikeOutAnnotationElementClosure() { function StrikeOutAnnotationElement(parameters) { AnnotationElement.call(this, parameters); } Util.inherit(StrikeOutAnnotationElement, AnnotationElement, { /** * Render the strikeout annotation's HTML element in the empty container. * * @public * @memberof StrikeOutAnnotationElement * @returns {HTMLSectionElement} */ render: function StrikeOutAnnotationElement_render() { this.container.className = 'strikeoutAnnotation'; return this.container; } }); return StrikeOutAnnotationElement; })(); /** * @typedef {Object} AnnotationLayerParameters * @property {PageViewport} viewport * @property {HTMLDivElement} div * @property {Array} annotations * @property {PDFPage} page * @property {IPDFLinkService} linkService */ /** * @class * @alias AnnotationLayer */ var AnnotationLayer = (function AnnotationLayerClosure() { return { /** * Render a new annotation layer with all annotation elements. * * @public * @param {AnnotationLayerParameters} parameters * @memberof AnnotationLayer */ render: function AnnotationLayer_render(parameters) { var annotationElementFactory = new AnnotationElementFactory(); for (var i = 0, ii = parameters.annotations.length; i < ii; i++) { var data = parameters.annotations[i]; if (!data || !data.hasHtml) { continue; } var properties = { data: data, layer: parameters.div, page: parameters.page, viewport: parameters.viewport, linkService: parameters.linkService }; var element = annotationElementFactory.create(properties); parameters.div.appendChild(element.render()); } }, /** * Update the annotation elements on existing annotation layer. * * @public * @param {AnnotationLayerParameters} parameters * @memberof AnnotationLayer */ update: function AnnotationLayer_update(parameters) { for (var i = 0, ii = parameters.annotations.length; i < ii; i++) { var data = parameters.annotations[i]; var element = parameters.div.querySelector( '[data-annotation-id="' + data.id + '"]'); if (element) { CustomStyle.setProp('transform', element, 'matrix(' + parameters.viewport.transform.join(',') + ')'); } } parameters.div.removeAttribute('hidden'); } }; })(); PDFJS.AnnotationLayer = AnnotationLayer; exports.AnnotationLayer = AnnotationLayer; })); (function (root, factory) { { factory((root.pdfjsDisplayFontLoader = {}), root.pdfjsSharedUtil, root.pdfjsSharedGlobal); } }(this, function (exports, sharedUtil, sharedGlobal) { var assert = sharedUtil.assert; var bytesToString = sharedUtil.bytesToString; var string32 = sharedUtil.string32; var shadow = sharedUtil.shadow; var warn = sharedUtil.warn; var PDFJS = sharedGlobal.PDFJS; var globalScope = sharedGlobal.globalScope; var isWorker = sharedGlobal.isWorker; function FontLoader(docId) { this.docId = docId; this.styleElement = null; this.nativeFontFaces = []; this.loadTestFontId = 0; this.loadingContext = { requests: [], nextRequestId: 0 }; } FontLoader.prototype = { insertRule: function fontLoaderInsertRule(rule) { var styleElement = this.styleElement; if (!styleElement) { styleElement = this.styleElement = document.createElement('style'); styleElement.id = 'PDFJS_FONT_STYLE_TAG_' + this.docId; document.documentElement.getElementsByTagName('head')[0].appendChild( styleElement); } var styleSheet = styleElement.sheet; styleSheet.insertRule(rule, styleSheet.cssRules.length); }, clear: function fontLoaderClear() { var styleElement = this.styleElement; if (styleElement) { styleElement.parentNode.removeChild(styleElement); styleElement = this.styleElement = null; } this.nativeFontFaces.forEach(function(nativeFontFace) { document.fonts.delete(nativeFontFace); }); this.nativeFontFaces.length = 0; }, get loadTestFont() { // This is a CFF font with 1 glyph for '.' that fills its entire width and // height. return shadow(this, 'loadTestFont', atob( 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' + 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' + 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' + 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' + 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' + 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' + 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' + 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' + 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' + 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' + 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' + 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' + 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' + 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' + 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' + 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' + 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' + 'ABAAAAAAAAAAAD6AAAAAAAAA==' )); }, addNativeFontFace: function fontLoader_addNativeFontFace(nativeFontFace) { this.nativeFontFaces.push(nativeFontFace); document.fonts.add(nativeFontFace); }, bind: function fontLoaderBind(fonts, callback) { assert(!isWorker, 'bind() shall be called from main thread'); var rules = []; var fontsToLoad = []; var fontLoadPromises = []; var getNativeFontPromise = function(nativeFontFace) { // Return a promise that is always fulfilled, even when the font fails to // load. return nativeFontFace.loaded.catch(function(e) { warn('Failed to load font "' + nativeFontFace.family + '": ' + e); }); }; for (var i = 0, ii = fonts.length; i < ii; i++) { var font = fonts[i]; // Add the font to the DOM only once or skip if the font // is already loaded. if (font.attached || font.loading === false) { continue; } font.attached = true; if (FontLoader.isFontLoadingAPISupported) { var nativeFontFace = font.createNativeFontFace(); if (nativeFontFace) { this.addNativeFontFace(nativeFontFace); fontLoadPromises.push(getNativeFontPromise(nativeFontFace)); } } else { var rule = font.createFontFaceRule(); if (rule) { this.insertRule(rule); rules.push(rule); fontsToLoad.push(font); } } } var request = this.queueLoadingCallback(callback); if (FontLoader.isFontLoadingAPISupported) { Promise.all(fontLoadPromises).then(function() { request.complete(); }); } else if (rules.length > 0 && !FontLoader.isSyncFontLoadingSupported) { this.prepareFontLoadEvent(rules, fontsToLoad, request); } else { request.complete(); } }, queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) { function LoadLoader_completeRequest() { assert(!request.end, 'completeRequest() cannot be called twice'); request.end = Date.now(); // sending all completed requests in order how they were queued while (context.requests.length > 0 && context.requests[0].end) { var otherRequest = context.requests.shift(); setTimeout(otherRequest.callback, 0); } } var context = this.loadingContext; var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++); var request = { id: requestId, complete: LoadLoader_completeRequest, callback: callback, started: Date.now() }; context.requests.push(request); return request; }, prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules, fonts, request) { /** Hack begin */ // There's currently no event when a font has finished downloading so the // following code is a dirty hack to 'guess' when a font is // ready. It's assumed fonts are loaded in order, so add a known test // font after the desired fonts and then test for the loading of that // test font. function int32(data, offset) { return (data.charCodeAt(offset) << 24) | (data.charCodeAt(offset + 1) << 16) | (data.charCodeAt(offset + 2) << 8) | (data.charCodeAt(offset + 3) & 0xff); } function spliceString(s, offset, remove, insert) { var chunk1 = s.substr(0, offset); var chunk2 = s.substr(offset + remove); return chunk1 + insert + chunk2; } var i, ii; var canvas = document.createElement('canvas'); canvas.width = 1; canvas.height = 1; var ctx = canvas.getContext('2d'); var called = 0; function isFontReady(name, callback) { called++; // With setTimeout clamping this gives the font ~100ms to load. if(called > 30) { warn('Load test font never loaded.'); callback(); return; } ctx.font = '30px ' + name; ctx.fillText('.', 0, 20); var imageData = ctx.getImageData(0, 0, 1, 1); if (imageData.data[3] > 0) { callback(); return; } setTimeout(isFontReady.bind(null, name, callback)); } var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++; // Chromium seems to cache fonts based on a hash of the actual font data, // so the font must be modified for each load test else it will appear to // be loaded already. // TODO: This could maybe be made faster by avoiding the btoa of the full // font by splitting it in chunks before hand and padding the font id. var data = this.loadTestFont; var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum) data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId); // CFF checksum is important for IE, adjusting it var CFF_CHECKSUM_OFFSET = 16; var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X' var checksum = int32(data, CFF_CHECKSUM_OFFSET); for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) { checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0; } if (i < loadTestFontId.length) { // align to 4 bytes boundary checksum = (checksum - XXXX_VALUE + int32(loadTestFontId + 'XXX', i)) | 0; } data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum)); var url = 'url(data:font/opentype;base64,' + btoa(data) + ');'; var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' + url + '}'; this.insertRule(rule); var names = []; for (i = 0, ii = fonts.length; i < ii; i++) { names.push(fonts[i].loadedName); } names.push(loadTestFontId); var div = document.createElement('div'); div.setAttribute('style', 'visibility: hidden;' + 'width: 10px; height: 10px;' + 'position: absolute; top: 0px; left: 0px;'); for (i = 0, ii = names.length; i < ii; ++i) { var span = document.createElement('span'); span.textContent = 'Hi'; span.style.fontFamily = names[i]; div.appendChild(span); } document.body.appendChild(div); isFontReady(loadTestFontId, function() { document.body.removeChild(div); request.complete(); }); /** Hack end */ } }; FontLoader.isFontLoadingAPISupported = (!isWorker && typeof document !== 'undefined' && !!document.fonts); Object.defineProperty(FontLoader, 'isSyncFontLoadingSupported', { get: function () { var supported = false; // User agent string sniffing is bad, but there is no reliable way to tell // if font is fully loaded and ready to be used with canvas. var userAgent = window.navigator.userAgent; var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(userAgent); if (m && m[1] >= 14) { supported = true; } // TODO other browsers if (userAgent === 'node') { supported = true; } return shadow(FontLoader, 'isSyncFontLoadingSupported', supported); }, enumerable: true, configurable: true }); var FontFaceObject = (function FontFaceObjectClosure() { function FontFaceObject(translatedData) { this.compiledGlyphs = {}; // importing translated data for (var i in translatedData) { this[i] = translatedData[i]; } } Object.defineProperty(FontFaceObject, 'isEvalSupported', { get: function () { var evalSupport = false; if (PDFJS.isEvalSupported) { try { /* jshint evil: true */ new Function(''); evalSupport = true; } catch (e) {} } return shadow(this, 'isEvalSupported', evalSupport); }, enumerable: true, configurable: true }); FontFaceObject.prototype = { createNativeFontFace: function FontFaceObject_createNativeFontFace() { if (!this.data) { return null; } if (PDFJS.disableFontFace) { this.disableFontFace = true; return null; } var nativeFontFace = new FontFace(this.loadedName, this.data, {}); if (PDFJS.pdfBug && 'FontInspector' in globalScope && globalScope['FontInspector'].enabled) { globalScope['FontInspector'].fontAdded(this); } return nativeFontFace; }, createFontFaceRule: function FontFaceObject_createFontFaceRule() { if (!this.data) { return null; } if (PDFJS.disableFontFace) { this.disableFontFace = true; return null; } var data = bytesToString(new Uint8Array(this.data)); var fontName = this.loadedName; // Add the font-face rule to the document var url = ('url(data:' + this.mimetype + ';base64,' + window.btoa(data) + ');'); var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}'; if (PDFJS.pdfBug && 'FontInspector' in globalScope && globalScope['FontInspector'].enabled) { globalScope['FontInspector'].fontAdded(this, url); } return rule; }, getPathGenerator: function FontFaceObject_getPathGenerator(objs, character) { if (!(character in this.compiledGlyphs)) { var cmds = objs.get(this.loadedName + '_path_' + character); var current, i, len; // If we can, compile cmds into JS for MAXIMUM SPEED if (FontFaceObject.isEvalSupported) { var args, js = ''; for (i = 0, len = cmds.length; i < len; i++) { current = cmds[i]; if (current.args !== undefined) { args = current.args.join(','); } else { args = ''; } js += 'c.' + current.cmd + '(' + args + ');\n'; } /* jshint -W054 */ this.compiledGlyphs[character] = new Function('c', 'size', js); } else { // But fall back on using Function.prototype.apply() if we're // blocked from using eval() for whatever reason (like CSP policies) this.compiledGlyphs[character] = function(c, size) { for (i = 0, len = cmds.length; i < len; i++) { current = cmds[i]; if (current.cmd === 'scale') { current.args = [size, -size]; } c[current.cmd].apply(c, current.args); } }; } } return this.compiledGlyphs[character]; } }; return FontFaceObject; })(); exports.FontFaceObject = FontFaceObject; exports.FontLoader = FontLoader; })); (function (root, factory) { { factory((root.pdfjsDisplayMetadata = {}), root.pdfjsSharedUtil); } }(this, function (exports, sharedUtil) { var error = sharedUtil.error; var Metadata = PDFJS.Metadata = (function MetadataClosure() { function fixMetadata(meta) { return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) { var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g, function(code, d1, d2, d3) { return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1); }); var chars = ''; for (var i = 0; i < bytes.length; i += 2) { var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1); chars += code >= 32 && code < 127 && code !== 60 && code !== 62 && code !== 38 && false ? String.fromCharCode(code) : '&#x' + (0x10000 + code).toString(16).substring(1) + ';'; } return '>' + chars; }); } function Metadata(meta) { if (typeof meta === 'string') { // Ghostscript produces invalid metadata meta = fixMetadata(meta); var parser = new DOMParser(); meta = parser.parseFromString(meta, 'application/xml'); } else if (!(meta instanceof Document)) { error('Metadata: Invalid metadata object'); } this.metaDocument = meta; this.metadata = {}; this.parse(); } Metadata.prototype = { parse: function Metadata_parse() { var doc = this.metaDocument; var rdf = doc.documentElement; if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta> rdf = rdf.firstChild; while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') { rdf = rdf.nextSibling; } } var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null; if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) { return; } var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength; for (i = 0, length = children.length; i < length; i++) { desc = children[i]; if (desc.nodeName.toLowerCase() !== 'rdf:description') { continue; } for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) { if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') { entry = desc.childNodes[ii]; name = entry.nodeName.toLowerCase(); this.metadata[name] = entry.textContent.trim(); } } } }, get: function Metadata_get(name) { return this.metadata[name] || null; }, has: function Metadata_has(name) { return typeof this.metadata[name] !== 'undefined'; } }; return Metadata; })(); exports.Metadata = Metadata; })); (function (root, factory) { { factory((root.pdfjsDisplaySVG = {}), root.pdfjsSharedUtil); } }(this, function (exports, sharedUtil) { var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX; var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX; var ImageKind = sharedUtil.ImageKind; var OPS = sharedUtil.OPS; var Util = sharedUtil.Util; var isNum = sharedUtil.isNum; var isArray = sharedUtil.isArray; var warn = sharedUtil.warn; var SVG_DEFAULTS = { fontStyle: 'normal', fontWeight: 'normal', fillColor: '#000000' }; var convertImgDataToPng = (function convertImgDataToPngClosure() { var PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); var CHUNK_WRAPPER_SIZE = 12; var crcTable = new Int32Array(256); for (var i = 0; i < 256; i++) { var c = i; for (var h = 0; h < 8; h++) { if (c & 1) { c = 0xedB88320 ^ ((c >> 1) & 0x7fffffff); } else { c = (c >> 1) & 0x7fffffff; } } crcTable[i] = c; } function crc32(data, start, end) { var crc = -1; for (var i = start; i < end; i++) { var a = (crc ^ data[i]) & 0xff; var b = crcTable[a]; crc = (crc >>> 8) ^ b; } return crc ^ -1; } function writePngChunk(type, body, data, offset) { var p = offset; var len = body.length; data[p] = len >> 24 & 0xff; data[p + 1] = len >> 16 & 0xff; data[p + 2] = len >> 8 & 0xff; data[p + 3] = len & 0xff; p += 4; data[p] = type.charCodeAt(0) & 0xff; data[p + 1] = type.charCodeAt(1) & 0xff; data[p + 2] = type.charCodeAt(2) & 0xff; data[p + 3] = type.charCodeAt(3) & 0xff; p += 4; data.set(body, p); p += body.length; var crc = crc32(data, offset + 4, p); data[p] = crc >> 24 & 0xff; data[p + 1] = crc >> 16 & 0xff; data[p + 2] = crc >> 8 & 0xff; data[p + 3] = crc & 0xff; } function adler32(data, start, end) { var a = 1; var b = 0; for (var i = start; i < end; ++i) { a = (a + (data[i] & 0xff)) % 65521; b = (b + a) % 65521; } return (b << 16) | a; } function encode(imgData, kind) { var width = imgData.width; var height = imgData.height; var bitDepth, colorType, lineSize; var bytes = imgData.data; switch (kind) { case ImageKind.GRAYSCALE_1BPP: colorType = 0; bitDepth = 1; lineSize = (width + 7) >> 3; break; case ImageKind.RGB_24BPP: colorType = 2; bitDepth = 8; lineSize = width * 3; break; case ImageKind.RGBA_32BPP: colorType = 6; bitDepth = 8; lineSize = width * 4; break; default: throw new Error('invalid format'); } // prefix every row with predictor 0 var literals = new Uint8Array((1 + lineSize) * height); var offsetLiterals = 0, offsetBytes = 0; var y, i; for (y = 0; y < height; ++y) { literals[offsetLiterals++] = 0; // no prediction literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals); offsetBytes += lineSize; offsetLiterals += lineSize; } if (kind === ImageKind.GRAYSCALE_1BPP) { // inverting for B/W offsetLiterals = 0; for (y = 0; y < height; y++) { offsetLiterals++; // skipping predictor for (i = 0; i < lineSize; i++) { literals[offsetLiterals++] ^= 0xFF; } } } var ihdr = new Uint8Array([ width >> 24 & 0xff, width >> 16 & 0xff, width >> 8 & 0xff, width & 0xff, height >> 24 & 0xff, height >> 16 & 0xff, height >> 8 & 0xff, height & 0xff, bitDepth, // bit depth colorType, // color type 0x00, // compression method 0x00, // filter method 0x00 // interlace method ]); var len = literals.length; var maxBlockLength = 0xFFFF; var deflateBlocks = Math.ceil(len / maxBlockLength); var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4); var pi = 0; idat[pi++] = 0x78; // compression method and flags idat[pi++] = 0x9c; // flags var pos = 0; while (len > maxBlockLength) { // writing non-final DEFLATE blocks type 0 and length of 65535 idat[pi++] = 0x00; idat[pi++] = 0xff; idat[pi++] = 0xff; idat[pi++] = 0x00; idat[pi++] = 0x00; idat.set(literals.subarray(pos, pos + maxBlockLength), pi); pi += maxBlockLength; pos += maxBlockLength; len -= maxBlockLength; } // writing non-final DEFLATE blocks type 0 idat[pi++] = 0x01; idat[pi++] = len & 0xff; idat[pi++] = len >> 8 & 0xff; idat[pi++] = (~len & 0xffff) & 0xff; idat[pi++] = (~len & 0xffff) >> 8 & 0xff; idat.set(literals.subarray(pos), pi); pi += literals.length - pos; var adler = adler32(literals, 0, literals.length); // checksum idat[pi++] = adler >> 24 & 0xff; idat[pi++] = adler >> 16 & 0xff; idat[pi++] = adler >> 8 & 0xff; idat[pi++] = adler & 0xff; // PNG will consists: header, IHDR+data, IDAT+data, and IEND. var pngLength = PNG_HEADER.length + (CHUNK_WRAPPER_SIZE * 3) + ihdr.length + idat.length; var data = new Uint8Array(pngLength); var offset = 0; data.set(PNG_HEADER, offset); offset += PNG_HEADER.length; writePngChunk('IHDR', ihdr, data, offset); offset += CHUNK_WRAPPER_SIZE + ihdr.length; writePngChunk('IDATA', idat, data, offset); offset += CHUNK_WRAPPER_SIZE + idat.length; writePngChunk('IEND', new Uint8Array(0), data, offset); return PDFJS.createObjectURL(data, 'image/png'); } return function convertImgDataToPng(imgData) { var kind = (imgData.kind === undefined ? ImageKind.GRAYSCALE_1BPP : imgData.kind); return encode(imgData, kind); }; })(); var SVGExtraState = (function SVGExtraStateClosure() { function SVGExtraState() { this.fontSizeScale = 1; this.fontWeight = SVG_DEFAULTS.fontWeight; this.fontSize = 0; this.textMatrix = IDENTITY_MATRIX; this.fontMatrix = FONT_IDENTITY_MATRIX; this.leading = 0; // Current point (in user coordinates) this.x = 0; this.y = 0; // Start of text line (in text coordinates) this.lineX = 0; this.lineY = 0; // Character and word spacing this.charSpacing = 0; this.wordSpacing = 0; this.textHScale = 1; this.textRise = 0; // Default foreground and background colors this.fillColor = SVG_DEFAULTS.fillColor; this.strokeColor = '#000000'; this.fillAlpha = 1; this.strokeAlpha = 1; this.lineWidth = 1; this.lineJoin = ''; this.lineCap = ''; this.miterLimit = 0; this.dashArray = []; this.dashPhase = 0; this.dependencies = []; // Clipping this.clipId = ''; this.pendingClip = false; this.maskId = ''; } SVGExtraState.prototype = { clone: function SVGExtraState_clone() { return Object.create(this); }, setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) { this.x = x; this.y = y; } }; return SVGExtraState; })(); var SVGGraphics = (function SVGGraphicsClosure() { function createScratchSVG(width, height) { var NS = 'http://www.w3.org/2000/svg'; var svg = document.createElementNS(NS, 'svg:svg'); svg.setAttributeNS(null, 'version', '1.1'); svg.setAttributeNS(null, 'width', width + 'px'); svg.setAttributeNS(null, 'height', height + 'px'); svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height); return svg; } function opListToTree(opList) { var opTree = []; var tmp = []; var opListLen = opList.length; for (var x = 0; x < opListLen; x++) { if (opList[x].fn === 'save') { opTree.push({'fnId': 92, 'fn': 'group', 'items': []}); tmp.push(opTree); opTree = opTree[opTree.length - 1].items; continue; } if(opList[x].fn === 'restore') { opTree = tmp.pop(); } else { opTree.push(opList[x]); } } return opTree; } /** * Formats float number. * @param value {number} number to format. * @returns {string} */ function pf(value) { if (value === (value | 0)) { // integer number return value.toString(); } var s = value.toFixed(10); var i = s.length - 1; if (s[i] !== '0') { return s; } // removing trailing zeros do { i--; } while (s[i] === '0'); return s.substr(0, s[i] === '.' ? i : i + 1); } /** * Formats transform matrix. The standard rotation, scale and translate * matrices are replaced by their shorter forms, and for identity matrix * returns empty string to save the memory. * @param m {Array} matrix to format. * @returns {string} */ function pm(m) { if (m[4] === 0 && m[5] === 0) { if (m[1] === 0 && m[2] === 0) { if (m[0] === 1 && m[3] === 1) { return ''; } return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')'; } if (m[0] === m[3] && m[1] === -m[2]) { var a = Math.acos(m[0]) * 180 / Math.PI; return 'rotate(' + pf(a) + ')'; } } else { if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) { return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')'; } } return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' + pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')'; } function SVGGraphics(commonObjs, objs) { this.current = new SVGExtraState(); this.transformMatrix = IDENTITY_MATRIX; // Graphics state matrix this.transformStack = []; this.extraStack = []; this.commonObjs = commonObjs; this.objs = objs; this.pendingEOFill = false; this.embedFonts = false; this.embeddedFonts = {}; this.cssStyle = null; } var NS = 'http://www.w3.org/2000/svg'; var XML_NS = 'http://www.w3.org/XML/1998/namespace'; var XLINK_NS = 'http://www.w3.org/1999/xlink'; var LINE_CAP_STYLES = ['butt', 'round', 'square']; var LINE_JOIN_STYLES = ['miter', 'round', 'bevel']; var clipCount = 0; var maskCount = 0; SVGGraphics.prototype = { save: function SVGGraphics_save() { this.transformStack.push(this.transformMatrix); var old = this.current; this.extraStack.push(old); this.current = old.clone(); }, restore: function SVGGraphics_restore() { this.transformMatrix = this.transformStack.pop(); this.current = this.extraStack.pop(); this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); this.pgrp.appendChild(this.tgrp); }, group: function SVGGraphics_group(items) { this.save(); this.executeOpTree(items); this.restore(); }, loadDependencies: function SVGGraphics_loadDependencies(operatorList) { var fnArray = operatorList.fnArray; var fnArrayLen = fnArray.length; var argsArray = operatorList.argsArray; var self = this; for (var i = 0; i < fnArrayLen; i++) { if (OPS.dependency === fnArray[i]) { var deps = argsArray[i]; for (var n = 0, nn = deps.length; n < nn; n++) { var obj = deps[n]; var common = obj.substring(0, 2) === 'g_'; var promise; if (common) { promise = new Promise(function(resolve) { self.commonObjs.get(obj, resolve); }); } else { promise = new Promise(function(resolve) { self.objs.get(obj, resolve); }); } this.current.dependencies.push(promise); } } } return Promise.all(this.current.dependencies); }, transform: function SVGGraphics_transform(a, b, c, d, e, f) { var transformMatrix = [a, b, c, d, e, f]; this.transformMatrix = PDFJS.Util.transform(this.transformMatrix, transformMatrix); this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); }, getSVG: function SVGGraphics_getSVG(operatorList, viewport) { this.svg = createScratchSVG(viewport.width, viewport.height); this.viewport = viewport; return this.loadDependencies(operatorList).then(function () { this.transformMatrix = IDENTITY_MATRIX; this.pgrp = document.createElementNS(NS, 'svg:g'); // Parent group this.pgrp.setAttributeNS(null, 'transform', pm(viewport.transform)); this.tgrp = document.createElementNS(NS, 'svg:g'); // Transform group this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); this.defs = document.createElementNS(NS, 'svg:defs'); this.pgrp.appendChild(this.defs); this.pgrp.appendChild(this.tgrp); this.svg.appendChild(this.pgrp); var opTree = this.convertOpList(operatorList); this.executeOpTree(opTree); return this.svg; }.bind(this)); }, convertOpList: function SVGGraphics_convertOpList(operatorList) { var argsArray = operatorList.argsArray; var fnArray = operatorList.fnArray; var fnArrayLen = fnArray.length; var REVOPS = []; var opList = []; for (var op in OPS) { REVOPS[OPS[op]] = op; } for (var x = 0; x < fnArrayLen; x++) { var fnId = fnArray[x]; opList.push({'fnId' : fnId, 'fn': REVOPS[fnId], 'args': argsArray[x]}); } return opListToTree(opList); }, executeOpTree: function SVGGraphics_executeOpTree(opTree) { var opTreeLen = opTree.length; for(var x = 0; x < opTreeLen; x++) { var fn = opTree[x].fn; var fnId = opTree[x].fnId; var args = opTree[x].args; switch (fnId | 0) { case OPS.beginText: this.beginText(); break; case OPS.setLeading: this.setLeading(args); break; case OPS.setLeadingMoveText: this.setLeadingMoveText(args[0], args[1]); break; case OPS.setFont: this.setFont(args); break; case OPS.showText: this.showText(args[0]); break; case OPS.showSpacedText: this.showText(args[0]); break; case OPS.endText: this.endText(); break; case OPS.moveText: this.moveText(args[0], args[1]); break; case OPS.setCharSpacing: this.setCharSpacing(args[0]); break; case OPS.setWordSpacing: this.setWordSpacing(args[0]); break; case OPS.setHScale: this.setHScale(args[0]); break; case OPS.setTextMatrix: this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]); break; case OPS.setLineWidth: this.setLineWidth(args[0]); break; case OPS.setLineJoin: this.setLineJoin(args[0]); break; case OPS.setLineCap: this.setLineCap(args[0]); break; case OPS.setMiterLimit: this.setMiterLimit(args[0]); break; case OPS.setFillRGBColor: this.setFillRGBColor(args[0], args[1], args[2]); break; case OPS.setStrokeRGBColor: this.setStrokeRGBColor(args[0], args[1], args[2]); break; case OPS.setDash: this.setDash(args[0], args[1]); break; case OPS.setGState: this.setGState(args[0]); break; case OPS.fill: this.fill(); break; case OPS.eoFill: this.eoFill(); break; case OPS.stroke: this.stroke(); break; case OPS.fillStroke: this.fillStroke(); break; case OPS.eoFillStroke: this.eoFillStroke(); break; case OPS.clip: this.clip('nonzero'); break; case OPS.eoClip: this.clip('evenodd'); break; case OPS.paintSolidColorImageMask: this.paintSolidColorImageMask(); break; case OPS.paintJpegXObject: this.paintJpegXObject(args[0], args[1], args[2]); break; case OPS.paintImageXObject: this.paintImageXObject(args[0]); break; case OPS.paintInlineImageXObject: this.paintInlineImageXObject(args[0]); break; case OPS.paintImageMaskXObject: this.paintImageMaskXObject(args[0]); break; case OPS.paintFormXObjectBegin: this.paintFormXObjectBegin(args[0], args[1]); break; case OPS.paintFormXObjectEnd: this.paintFormXObjectEnd(); break; case OPS.closePath: this.closePath(); break; case OPS.closeStroke: this.closeStroke(); break; case OPS.closeFillStroke: this.closeFillStroke(); break; case OPS.nextLine: this.nextLine(); break; case OPS.transform: this.transform(args[0], args[1], args[2], args[3], args[4], args[5]); break; case OPS.constructPath: this.constructPath(args[0], args[1]); break; case OPS.endPath: this.endPath(); break; case 92: this.group(opTree[x].items); break; default: warn('Unimplemented method '+ fn); break; } } }, setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) { this.current.wordSpacing = wordSpacing; }, setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) { this.current.charSpacing = charSpacing; }, nextLine: function SVGGraphics_nextLine() { this.moveText(0, this.current.leading); }, setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) { var current = this.current; this.current.textMatrix = this.current.lineMatrix = [a, b, c, d, e, f]; this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; current.xcoords = []; current.tspan = document.createElementNS(NS, 'svg:tspan'); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.txtElement = document.createElementNS(NS, 'svg:text'); current.txtElement.appendChild(current.tspan); }, beginText: function SVGGraphics_beginText() { this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; this.current.textMatrix = IDENTITY_MATRIX; this.current.lineMatrix = IDENTITY_MATRIX; this.current.tspan = document.createElementNS(NS, 'svg:tspan'); this.current.txtElement = document.createElementNS(NS, 'svg:text'); this.current.txtgrp = document.createElementNS(NS, 'svg:g'); this.current.xcoords = []; }, moveText: function SVGGraphics_moveText(x, y) { var current = this.current; this.current.x = this.current.lineX += x; this.current.y = this.current.lineY += y; current.xcoords = []; current.tspan = document.createElementNS(NS, 'svg:tspan'); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); }, showText: function SVGGraphics_showText(glyphs) { var current = this.current; var font = current.font; var fontSize = current.fontSize; if (fontSize === 0) { return; } var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var fontDirection = current.fontDirection; var textHScale = current.textHScale * fontDirection; var glyphsLength = glyphs.length; var vertical = font.vertical; var widthAdvanceScale = fontSize * current.fontMatrix[0]; var x = 0, i; for (i = 0; i < glyphsLength; ++i) { var glyph = glyphs[i]; if (glyph === null) { // word break x += fontDirection * wordSpacing; continue; } else if (isNum(glyph)) { x += -glyph * fontSize * 0.001; continue; } current.xcoords.push(current.x + x * textHScale); var width = glyph.width; var character = glyph.fontChar; var charWidth = width * widthAdvanceScale + charSpacing * fontDirection; x += charWidth; current.tspan.textContent += character; } if (vertical) { current.y -= x * textHScale; } else { current.x += x * textHScale; } current.tspan.setAttributeNS(null, 'x', current.xcoords.map(pf).join(' ')); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); if (current.fontStyle !== SVG_DEFAULTS.fontStyle) { current.tspan.setAttributeNS(null, 'font-style', current.fontStyle); } if (current.fontWeight !== SVG_DEFAULTS.fontWeight) { current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight); } if (current.fillColor !== SVG_DEFAULTS.fillColor) { current.tspan.setAttributeNS(null, 'fill', current.fillColor); } current.txtElement.setAttributeNS(null, 'transform', pm(current.textMatrix) + ' scale(1, -1)' ); current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve'); current.txtElement.appendChild(current.tspan); current.txtgrp.appendChild(current.txtElement); this.tgrp.appendChild(current.txtElement); }, setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) { this.setLeading(-y); this.moveText(x, y); }, addFontStyle: function SVGGraphics_addFontStyle(fontObj) { if (!this.cssStyle) { this.cssStyle = document.createElementNS(NS, 'svg:style'); this.cssStyle.setAttributeNS(null, 'type', 'text/css'); this.defs.appendChild(this.cssStyle); } var url = PDFJS.createObjectURL(fontObj.data, fontObj.mimetype); this.cssStyle.textContent += '@font-face { font-family: "' + fontObj.loadedName + '";' + ' src: url(' + url + '); }\n'; }, setFont: function SVGGraphics_setFont(details) { var current = this.current; var fontObj = this.commonObjs.get(details[0]); var size = details[1]; this.current.font = fontObj; if (this.embedFonts && fontObj.data && !this.embeddedFonts[fontObj.loadedName]) { this.addFontStyle(fontObj); this.embeddedFonts[fontObj.loadedName] = fontObj; } current.fontMatrix = (fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX); var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') : (fontObj.bold ? 'bold' : 'normal'); var italic = fontObj.italic ? 'italic' : 'normal'; if (size < 0) { size = -size; current.fontDirection = -1; } else { current.fontDirection = 1; } current.fontSize = size; current.fontFamily = fontObj.loadedName; current.fontWeight = bold; current.fontStyle = italic; current.tspan = document.createElementNS(NS, 'svg:tspan'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.xcoords = []; }, endText: function SVGGraphics_endText() { if (this.current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); }, // Path properties setLineWidth: function SVGGraphics_setLineWidth(width) { this.current.lineWidth = width; }, setLineCap: function SVGGraphics_setLineCap(style) { this.current.lineCap = LINE_CAP_STYLES[style]; }, setLineJoin: function SVGGraphics_setLineJoin(style) { this.current.lineJoin = LINE_JOIN_STYLES[style]; }, setMiterLimit: function SVGGraphics_setMiterLimit(limit) { this.current.miterLimit = limit; }, setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.current.strokeColor = color; }, setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.current.fillColor = color; this.current.tspan = document.createElementNS(NS, 'svg:tspan'); this.current.xcoords = []; }, setDash: function SVGGraphics_setDash(dashArray, dashPhase) { this.current.dashArray = dashArray; this.current.dashPhase = dashPhase; }, constructPath: function SVGGraphics_constructPath(ops, args) { var current = this.current; var x = current.x, y = current.y; current.path = document.createElementNS(NS, 'svg:path'); var d = []; var opLength = ops.length; for (var i = 0, j = 0; i < opLength; i++) { switch (ops[i] | 0) { case OPS.rectangle: x = args[j++]; y = args[j++]; var width = args[j++]; var height = args[j++]; var xw = x + width; var yh = y + height; d.push('M', pf(x), pf(y), 'L', pf(xw) , pf(y), 'L', pf(xw), pf(yh), 'L', pf(x), pf(yh), 'Z'); break; case OPS.moveTo: x = args[j++]; y = args[j++]; d.push('M', pf(x), pf(y)); break; case OPS.lineTo: x = args[j++]; y = args[j++]; d.push('L', pf(x) , pf(y)); break; case OPS.curveTo: x = args[j + 4]; y = args[j + 5]; d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y)); j += 6; break; case OPS.curveTo2: x = args[j + 2]; y = args[j + 3]; d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3])); j += 4; break; case OPS.curveTo3: x = args[j + 2]; y = args[j + 3]; d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y)); j += 4; break; case OPS.closePath: d.push('Z'); break; } } current.path.setAttributeNS(null, 'd', d.join(' ')); current.path.setAttributeNS(null, 'stroke-miterlimit', pf(current.miterLimit)); current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap); current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin); current.path.setAttributeNS(null, 'stroke-width', pf(current.lineWidth) + 'px'); current.path.setAttributeNS(null, 'stroke-dasharray', current.dashArray.map(pf).join(' ')); current.path.setAttributeNS(null, 'stroke-dashoffset', pf(current.dashPhase) + 'px'); current.path.setAttributeNS(null, 'fill', 'none'); this.tgrp.appendChild(current.path); if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } // Saving a reference in current.element so that it can be addressed // in 'fill' and 'stroke' current.element = current.path; current.setCurrentPoint(x, y); }, endPath: function SVGGraphics_endPath() { var current = this.current; if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); }, clip: function SVGGraphics_clip(type) { var current = this.current; // Add current path to clipping path current.clipId = 'clippath' + clipCount; clipCount++; this.clippath = document.createElementNS(NS, 'svg:clipPath'); this.clippath.setAttributeNS(null, 'id', current.clipId); var clipElement = current.element.cloneNode(); if (type === 'evenodd') { clipElement.setAttributeNS(null, 'clip-rule', 'evenodd'); } else { clipElement.setAttributeNS(null, 'clip-rule', 'nonzero'); } this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix)); this.clippath.appendChild(clipElement); this.defs.appendChild(this.clippath); // Create a new group with that attribute current.pendingClip = true; this.cgrp = document.createElementNS(NS, 'svg:g'); this.cgrp.setAttributeNS(null, 'clip-path', 'url(#' + current.clipId + ')'); this.pgrp.appendChild(this.cgrp); }, closePath: function SVGGraphics_closePath() { var current = this.current; var d = current.path.getAttributeNS(null, 'd'); d += 'Z'; current.path.setAttributeNS(null, 'd', d); }, setLeading: function SVGGraphics_setLeading(leading) { this.current.leading = -leading; }, setTextRise: function SVGGraphics_setTextRise(textRise) { this.current.textRise = textRise; }, setHScale: function SVGGraphics_setHScale(scale) { this.current.textHScale = scale / 100; }, setGState: function SVGGraphics_setGState(states) { for (var i = 0, ii = states.length; i < ii; i++) { var state = states[i]; var key = state[0]; var value = state[1]; switch (key) { case 'LW': this.setLineWidth(value); break; case 'LC': this.setLineCap(value); break; case 'LJ': this.setLineJoin(value); break; case 'ML': this.setMiterLimit(value); break; case 'D': this.setDash(value[0], value[1]); break; case 'RI': break; case 'FL': break; case 'Font': this.setFont(value); break; case 'CA': break; case 'ca': break; case 'BM': break; case 'SMask': break; } } }, fill: function SVGGraphics_fill() { var current = this.current; current.element.setAttributeNS(null, 'fill', current.fillColor); }, stroke: function SVGGraphics_stroke() { var current = this.current; current.element.setAttributeNS(null, 'stroke', current.strokeColor); current.element.setAttributeNS(null, 'fill', 'none'); }, eoFill: function SVGGraphics_eoFill() { var current = this.current; current.element.setAttributeNS(null, 'fill', current.fillColor); current.element.setAttributeNS(null, 'fill-rule', 'evenodd'); }, fillStroke: function SVGGraphics_fillStroke() { // Order is important since stroke wants fill to be none. // First stroke, then if fill needed, it will be overwritten. this.stroke(); this.fill(); }, eoFillStroke: function SVGGraphics_eoFillStroke() { this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd'); this.fillStroke(); }, closeStroke: function SVGGraphics_closeStroke() { this.closePath(); this.stroke(); }, closeFillStroke: function SVGGraphics_closeFillStroke() { this.closePath(); this.fillStroke(); }, paintSolidColorImageMask: function SVGGraphics_paintSolidColorImageMask() { var current = this.current; var rect = document.createElementNS(NS, 'svg:rect'); rect.setAttributeNS(null, 'x', '0'); rect.setAttributeNS(null, 'y', '0'); rect.setAttributeNS(null, 'width', '1px'); rect.setAttributeNS(null, 'height', '1px'); rect.setAttributeNS(null, 'fill', current.fillColor); this.tgrp.appendChild(rect); }, paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) { var current = this.current; var imgObj = this.objs.get(objId); var imgEl = document.createElementNS(NS, 'svg:image'); imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src); imgEl.setAttributeNS(null, 'width', imgObj.width + 'px'); imgEl.setAttributeNS(null, 'height', imgObj.height + 'px'); imgEl.setAttributeNS(null, 'x', '0'); imgEl.setAttributeNS(null, 'y', pf(-h)); imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')'); this.tgrp.appendChild(imgEl); if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } }, paintImageXObject: function SVGGraphics_paintImageXObject(objId) { var imgData = this.objs.get(objId); if (!imgData) { warn('Dependent image isn\'t ready yet'); return; } this.paintInlineImageXObject(imgData); }, paintInlineImageXObject: function SVGGraphics_paintInlineImageXObject(imgData, mask) { var current = this.current; var width = imgData.width; var height = imgData.height; var imgSrc = convertImgDataToPng(imgData); var cliprect = document.createElementNS(NS, 'svg:rect'); cliprect.setAttributeNS(null, 'x', '0'); cliprect.setAttributeNS(null, 'y', '0'); cliprect.setAttributeNS(null, 'width', pf(width)); cliprect.setAttributeNS(null, 'height', pf(height)); current.element = cliprect; this.clip('nonzero'); var imgEl = document.createElementNS(NS, 'svg:image'); imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc); imgEl.setAttributeNS(null, 'x', '0'); imgEl.setAttributeNS(null, 'y', pf(-height)); imgEl.setAttributeNS(null, 'width', pf(width) + 'px'); imgEl.setAttributeNS(null, 'height', pf(height) + 'px'); imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / width) + ' ' + pf(-1 / height) + ')'); if (mask) { mask.appendChild(imgEl); } else { this.tgrp.appendChild(imgEl); } if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } }, paintImageMaskXObject: function SVGGraphics_paintImageMaskXObject(imgData) { var current = this.current; var width = imgData.width; var height = imgData.height; var fillColor = current.fillColor; current.maskId = 'mask' + maskCount++; var mask = document.createElementNS(NS, 'svg:mask'); mask.setAttributeNS(null, 'id', current.maskId); var rect = document.createElementNS(NS, 'svg:rect'); rect.setAttributeNS(null, 'x', '0'); rect.setAttributeNS(null, 'y', '0'); rect.setAttributeNS(null, 'width', pf(width)); rect.setAttributeNS(null, 'height', pf(height)); rect.setAttributeNS(null, 'fill', fillColor); rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId +')'); this.defs.appendChild(mask); this.tgrp.appendChild(rect); this.paintInlineImageXObject(imgData, mask); }, paintFormXObjectBegin: function SVGGraphics_paintFormXObjectBegin(matrix, bbox) { this.save(); if (isArray(matrix) && matrix.length === 6) { this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); } if (isArray(bbox) && bbox.length === 4) { var width = bbox[2] - bbox[0]; var height = bbox[3] - bbox[1]; var cliprect = document.createElementNS(NS, 'svg:rect'); cliprect.setAttributeNS(null, 'x', bbox[0]); cliprect.setAttributeNS(null, 'y', bbox[1]); cliprect.setAttributeNS(null, 'width', pf(width)); cliprect.setAttributeNS(null, 'height', pf(height)); this.current.element = cliprect; this.clip('nonzero'); this.endPath(); } }, paintFormXObjectEnd: function SVGGraphics_paintFormXObjectEnd() { this.restore(); } }; return SVGGraphics; })(); PDFJS.SVGGraphics = SVGGraphics; exports.SVGGraphics = SVGGraphics; })); (function (root, factory) { { factory((root.pdfjsDisplayTextLayer = {}), root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils, root.pdfjsSharedGlobal); } }(this, function (exports, sharedUtil, displayDOMUtils, sharedGlobal) { var Util = sharedUtil.Util; var createPromiseCapability = sharedUtil.createPromiseCapability; var CustomStyle = displayDOMUtils.CustomStyle; var PDFJS = sharedGlobal.PDFJS; /** * Text layer render parameters. * * @typedef {Object} TextLayerRenderParameters * @property {TextContent} textContent - Text content to render (the object is * returned by the page's getTextContent() method). * @property {HTMLElement} container - HTML element that will contain text runs. * @property {PDFJS.PageViewport} viewport - The target viewport to properly * layout the text runs. * @property {Array} textDivs - (optional) HTML elements that are correspond * the text items of the textContent input. This is output and shall be * initially be set to empty array. * @property {number} timeout - (optional) Delay in milliseconds before * rendering of the text runs occurs. */ var renderTextLayer = (function renderTextLayerClosure() { var MAX_TEXT_DIVS_TO_RENDER = 100000; var NonWhitespaceRegexp = /\S/; function isAllWhitespace(str) { return !NonWhitespaceRegexp.test(str); } function appendText(textDivs, viewport, geom, styles) { var style = styles[geom.fontName]; var textDiv = document.createElement('div'); textDivs.push(textDiv); if (isAllWhitespace(geom.str)) { textDiv.dataset.isWhitespace = true; return; } var tx = Util.transform(viewport.transform, geom.transform); var angle = Math.atan2(tx[1], tx[0]); if (style.vertical) { angle += Math.PI / 2; } var fontHeight = Math.sqrt((tx[2] * tx[2]) + (tx[3] * tx[3])); var fontAscent = fontHeight; if (style.ascent) { fontAscent = style.ascent * fontAscent; } else if (style.descent) { fontAscent = (1 + style.descent) * fontAscent; } var left; var top; if (angle === 0) { left = tx[4]; top = tx[5] - fontAscent; } else { left = tx[4] + (fontAscent * Math.sin(angle)); top = tx[5] - (fontAscent * Math.cos(angle)); } textDiv.style.left = left + 'px'; textDiv.style.top = top + 'px'; textDiv.style.fontSize = fontHeight + 'px'; textDiv.style.fontFamily = style.fontFamily; textDiv.textContent = geom.str; // |fontName| is only used by the Font Inspector. This test will succeed // when e.g. the Font Inspector is off but the Stepper is on, but it's // not worth the effort to do a more accurate test. if (PDFJS.pdfBug) { textDiv.dataset.fontName = geom.fontName; } // Storing into dataset will convert number into string. if (angle !== 0) { textDiv.dataset.angle = angle * (180 / Math.PI); } // We don't bother scaling single-char text divs, because it has very // little effect on text highlighting. This makes scrolling on docs with // lots of such divs a lot faster. if (geom.str.length > 1) { if (style.vertical) { textDiv.dataset.canvasWidth = geom.height * viewport.scale; } else { textDiv.dataset.canvasWidth = geom.width * viewport.scale; } } } function render(task) { if (task._canceled) { return; } var textLayerFrag = task._container; var textDivs = task._textDivs; var capability = task._capability; var textDivsLength = textDivs.length; // No point in rendering many divs as it would make the browser // unusable even after the divs are rendered. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) { capability.resolve(); return; } var canvas = document.createElement('canvas'); canvas.mozOpaque = true; var ctx = canvas.getContext('2d', {alpha: false}); var lastFontSize; var lastFontFamily; for (var i = 0; i < textDivsLength; i++) { var textDiv = textDivs[i]; if (textDiv.dataset.isWhitespace !== undefined) { continue; } var fontSize = textDiv.style.fontSize; var fontFamily = textDiv.style.fontFamily; // Only build font string and set to context if different from last. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) { ctx.font = fontSize + ' ' + fontFamily; lastFontSize = fontSize; lastFontFamily = fontFamily; } var width = ctx.measureText(textDiv.textContent).width; if (width > 0) { textLayerFrag.appendChild(textDiv); var transform; if (textDiv.dataset.canvasWidth !== undefined) { // Dataset values come of type string. var textScale = textDiv.dataset.canvasWidth / width; transform = 'scaleX(' + textScale + ')'; } else { transform = ''; } var rotation = textDiv.dataset.angle; if (rotation) { transform = 'rotate(' + rotation + 'deg) ' + transform; } if (transform) { CustomStyle.setProp('transform' , textDiv, transform); } } } capability.resolve(); } /** * Text layer rendering task. * * @param {TextContent} textContent * @param {HTMLElement} container * @param {PDFJS.PageViewport} viewport * @param {Array} textDivs * @private */ function TextLayerRenderTask(textContent, container, viewport, textDivs) { this._textContent = textContent; this._container = container; this._viewport = viewport; textDivs = textDivs || []; this._textDivs = textDivs; this._canceled = false; this._capability = createPromiseCapability(); this._renderTimer = null; } TextLayerRenderTask.prototype = { get promise() { return this._capability.promise; }, cancel: function TextLayer_cancel() { this._canceled = true; if (this._renderTimer !== null) { clearTimeout(this._renderTimer); this._renderTimer = null; } this._capability.reject('canceled'); }, _render: function TextLayer_render(timeout) { var textItems = this._textContent.items; var styles = this._textContent.styles; var textDivs = this._textDivs; var viewport = this._viewport; for (var i = 0, len = textItems.length; i < len; i++) { appendText(textDivs, viewport, textItems[i], styles); } if (!timeout) { // Render right away render(this); } else { // Schedule var self = this; this._renderTimer = setTimeout(function() { render(self); self._renderTimer = null; }, timeout); } } }; /** * Starts rendering of the text layer. * * @param {TextLayerRenderParameters} renderParameters * @returns {TextLayerRenderTask} */ function renderTextLayer(renderParameters) { var task = new TextLayerRenderTask(renderParameters.textContent, renderParameters.container, renderParameters.viewport, renderParameters.textDivs); task._render(renderParameters.timeout); return task; } return renderTextLayer; })(); PDFJS.renderTextLayer = renderTextLayer; exports.renderTextLayer = renderTextLayer; })); (function (root, factory) { { factory((root.pdfjsDisplayWebGL = {}), root.pdfjsSharedUtil); } }(this, function (exports, sharedUtil) { var shadow = sharedUtil.shadow; var WebGLUtils = (function WebGLUtilsClosure() { function loadShader(gl, code, shaderType) { var shader = gl.createShader(shaderType); gl.shaderSource(shader, code); gl.compileShader(shader); var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS); if (!compiled) { var errorMsg = gl.getShaderInfoLog(shader); throw new Error('Error during shader compilation: ' + errorMsg); } return shader; } function createVertexShader(gl, code) { return loadShader(gl, code, gl.VERTEX_SHADER); } function createFragmentShader(gl, code) { return loadShader(gl, code, gl.FRAGMENT_SHADER); } function createProgram(gl, shaders) { var program = gl.createProgram(); for (var i = 0, ii = shaders.length; i < ii; ++i) { gl.attachShader(program, shaders[i]); } gl.linkProgram(program); var linked = gl.getProgramParameter(program, gl.LINK_STATUS); if (!linked) { var errorMsg = gl.getProgramInfoLog(program); throw new Error('Error during program linking: ' + errorMsg); } return program; } function createTexture(gl, image, textureId) { gl.activeTexture(textureId); var texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); // Set the parameters so we can render any size image. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); // Upload the image into the texture. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); return texture; } var currentGL, currentCanvas; function generateGL() { if (currentGL) { return; } currentCanvas = document.createElement('canvas'); currentGL = currentCanvas.getContext('webgl', { premultipliedalpha: false }); } var smaskVertexShaderCode = '\ attribute vec2 a_position; \ attribute vec2 a_texCoord; \ \ uniform vec2 u_resolution; \ \ varying vec2 v_texCoord; \ \ void main() { \ vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \ gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \ \ v_texCoord = a_texCoord; \ } '; var smaskFragmentShaderCode = '\ precision mediump float; \ \ uniform vec4 u_backdrop; \ uniform int u_subtype; \ uniform sampler2D u_image; \ uniform sampler2D u_mask; \ \ varying vec2 v_texCoord; \ \ void main() { \ vec4 imageColor = texture2D(u_image, v_texCoord); \ vec4 maskColor = texture2D(u_mask, v_texCoord); \ if (u_backdrop.a > 0.0) { \ maskColor.rgb = maskColor.rgb * maskColor.a + \ u_backdrop.rgb * (1.0 - maskColor.a); \ } \ float lum; \ if (u_subtype == 0) { \ lum = maskColor.a; \ } else { \ lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \ maskColor.b * 0.11; \ } \ imageColor.a *= lum; \ imageColor.rgb *= imageColor.a; \ gl_FragColor = imageColor; \ } '; var smaskCache = null; function initSmaskGL() { var canvas, gl; generateGL(); canvas = currentCanvas; currentCanvas = null; gl = currentGL; currentGL = null; // setup a GLSL program var vertexShader = createVertexShader(gl, smaskVertexShaderCode); var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode); var program = createProgram(gl, [vertexShader, fragmentShader]); gl.useProgram(program); var cache = {}; cache.gl = gl; cache.canvas = canvas; cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution'); cache.positionLocation = gl.getAttribLocation(program, 'a_position'); cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop'); cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype'); var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord'); var texLayerLocation = gl.getUniformLocation(program, 'u_image'); var texMaskLocation = gl.getUniformLocation(program, 'u_mask'); // provide texture coordinates for the rectangle. var texCoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0]), gl.STATIC_DRAW); gl.enableVertexAttribArray(texCoordLocation); gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0); gl.uniform1i(texLayerLocation, 0); gl.uniform1i(texMaskLocation, 1); smaskCache = cache; } function composeSMask(layer, mask, properties) { var width = layer.width, height = layer.height; if (!smaskCache) { initSmaskGL(); } var cache = smaskCache,canvas = cache.canvas, gl = cache.gl; canvas.width = width; canvas.height = height; gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); gl.uniform2f(cache.resolutionLocation, width, height); if (properties.backdrop) { gl.uniform4f(cache.resolutionLocation, properties.backdrop[0], properties.backdrop[1], properties.backdrop[2], 1); } else { gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0); } gl.uniform1i(cache.subtypeLocation, properties.subtype === 'Luminosity' ? 1 : 0); // Create a textures var texture = createTexture(gl, layer, gl.TEXTURE0); var maskTexture = createTexture(gl, mask, gl.TEXTURE1); // Create a buffer and put a single clipspace rectangle in // it (2 triangles) var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 0, 0, width, 0, 0, height, 0, height, width, 0, width, height]), gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.positionLocation); gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0); // draw gl.clearColor(0, 0, 0, 0); gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.TRIANGLES, 0, 6); gl.flush(); gl.deleteTexture(texture); gl.deleteTexture(maskTexture); gl.deleteBuffer(buffer); return canvas; } var figuresVertexShaderCode = '\ attribute vec2 a_position; \ attribute vec3 a_color; \ \ uniform vec2 u_resolution; \ uniform vec2 u_scale; \ uniform vec2 u_offset; \ \ varying vec4 v_color; \ \ void main() { \ vec2 position = (a_position + u_offset) * u_scale; \ vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \ gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \ \ v_color = vec4(a_color / 255.0, 1.0); \ } '; var figuresFragmentShaderCode = '\ precision mediump float; \ \ varying vec4 v_color; \ \ void main() { \ gl_FragColor = v_color; \ } '; var figuresCache = null; function initFiguresGL() { var canvas, gl; generateGL(); canvas = currentCanvas; currentCanvas = null; gl = currentGL; currentGL = null; // setup a GLSL program var vertexShader = createVertexShader(gl, figuresVertexShaderCode); var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode); var program = createProgram(gl, [vertexShader, fragmentShader]); gl.useProgram(program); var cache = {}; cache.gl = gl; cache.canvas = canvas; cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution'); cache.scaleLocation = gl.getUniformLocation(program, 'u_scale'); cache.offsetLocation = gl.getUniformLocation(program, 'u_offset'); cache.positionLocation = gl.getAttribLocation(program, 'a_position'); cache.colorLocation = gl.getAttribLocation(program, 'a_color'); figuresCache = cache; } function drawFigures(width, height, backgroundColor, figures, context) { if (!figuresCache) { initFiguresGL(); } var cache = figuresCache, canvas = cache.canvas, gl = cache.gl; canvas.width = width; canvas.height = height; gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); gl.uniform2f(cache.resolutionLocation, width, height); // count triangle points var count = 0; var i, ii, rows; for (i = 0, ii = figures.length; i < ii; i++) { switch (figures[i].type) { case 'lattice': rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0; count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6; break; case 'triangles': count += figures[i].coords.length; break; } } // transfer data var coords = new Float32Array(count * 2); var colors = new Uint8Array(count * 3); var coordsMap = context.coords, colorsMap = context.colors; var pIndex = 0, cIndex = 0; for (i = 0, ii = figures.length; i < ii; i++) { var figure = figures[i], ps = figure.coords, cs = figure.colors; switch (figure.type) { case 'lattice': var cols = figure.verticesPerRow; rows = (ps.length / cols) | 0; for (var row = 1; row < rows; row++) { var offset = row * cols + 1; for (var col = 1; col < cols; col++, offset++) { coords[pIndex] = coordsMap[ps[offset - cols - 1]]; coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1]; coords[pIndex + 2] = coordsMap[ps[offset - cols]]; coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1]; coords[pIndex + 4] = coordsMap[ps[offset - 1]]; coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1]; colors[cIndex] = colorsMap[cs[offset - cols - 1]]; colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1]; colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2]; colors[cIndex + 3] = colorsMap[cs[offset - cols]]; colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1]; colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2]; colors[cIndex + 6] = colorsMap[cs[offset - 1]]; colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1]; colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2]; coords[pIndex + 6] = coords[pIndex + 2]; coords[pIndex + 7] = coords[pIndex + 3]; coords[pIndex + 8] = coords[pIndex + 4]; coords[pIndex + 9] = coords[pIndex + 5]; coords[pIndex + 10] = coordsMap[ps[offset]]; coords[pIndex + 11] = coordsMap[ps[offset] + 1]; colors[cIndex + 9] = colors[cIndex + 3]; colors[cIndex + 10] = colors[cIndex + 4]; colors[cIndex + 11] = colors[cIndex + 5]; colors[cIndex + 12] = colors[cIndex + 6]; colors[cIndex + 13] = colors[cIndex + 7]; colors[cIndex + 14] = colors[cIndex + 8]; colors[cIndex + 15] = colorsMap[cs[offset]]; colors[cIndex + 16] = colorsMap[cs[offset] + 1]; colors[cIndex + 17] = colorsMap[cs[offset] + 2]; pIndex += 12; cIndex += 18; } } break; case 'triangles': for (var j = 0, jj = ps.length; j < jj; j++) { coords[pIndex] = coordsMap[ps[j]]; coords[pIndex + 1] = coordsMap[ps[j] + 1]; colors[cIndex] = colorsMap[cs[j]]; colors[cIndex + 1] = colorsMap[cs[j] + 1]; colors[cIndex + 2] = colorsMap[cs[j] + 2]; pIndex += 2; cIndex += 3; } break; } } // draw if (backgroundColor) { gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255, backgroundColor[2] / 255, 1.0); } else { gl.clearColor(0, 0, 0, 0); } gl.clear(gl.COLOR_BUFFER_BIT); var coordsBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer); gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.positionLocation); gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0); var colorsBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer); gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.colorLocation); gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false, 0, 0); gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY); gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY); gl.drawArrays(gl.TRIANGLES, 0, count); gl.flush(); gl.deleteBuffer(coordsBuffer); gl.deleteBuffer(colorsBuffer); return canvas; } function cleanup() { if (smaskCache && smaskCache.canvas) { smaskCache.canvas.width = 0; smaskCache.canvas.height = 0; } if (figuresCache && figuresCache.canvas) { figuresCache.canvas.width = 0; figuresCache.canvas.height = 0; } smaskCache = null; figuresCache = null; } return { get isEnabled() { if (PDFJS.disableWebGL) { return false; } var enabled = false; try { generateGL(); enabled = !!currentGL; } catch (e) { } return shadow(this, 'isEnabled', enabled); }, composeSMask: composeSMask, drawFigures: drawFigures, clear: cleanup }; })(); exports.WebGLUtils = WebGLUtils; })); (function (root, factory) { { factory((root.pdfjsDisplayPatternHelper = {}), root.pdfjsSharedUtil, root.pdfjsDisplayWebGL); } }(this, function (exports, sharedUtil, displayWebGL) { var Util = sharedUtil.Util; var info = sharedUtil.info; var isArray = sharedUtil.isArray; var error = sharedUtil.error; var WebGLUtils = displayWebGL.WebGLUtils; var ShadingIRs = {}; ShadingIRs.RadialAxial = { fromIR: function RadialAxial_fromIR(raw) { var type = raw[1]; var colorStops = raw[2]; var p0 = raw[3]; var p1 = raw[4]; var r0 = raw[5]; var r1 = raw[6]; return { type: 'Pattern', getPattern: function RadialAxial_getPattern(ctx) { var grad; if (type === 'axial') { grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]); } else if (type === 'radial') { grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1); } for (var i = 0, ii = colorStops.length; i < ii; ++i) { var c = colorStops[i]; grad.addColorStop(c[0], c[1]); } return grad; } }; } }; var createMeshCanvas = (function createMeshCanvasClosure() { function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) { // Very basic Gouraud-shaded triangle rasterization algorithm. var coords = context.coords, colors = context.colors; var bytes = data.data, rowSize = data.width * 4; var tmp; if (coords[p1 + 1] > coords[p2 + 1]) { tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp; } if (coords[p2 + 1] > coords[p3 + 1]) { tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp; } if (coords[p1 + 1] > coords[p2 + 1]) { tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp; } var x1 = (coords[p1] + context.offsetX) * context.scaleX; var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY; var x2 = (coords[p2] + context.offsetX) * context.scaleX; var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY; var x3 = (coords[p3] + context.offsetX) * context.scaleX; var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY; if (y1 >= y3) { return; } var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2]; var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2]; var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2]; var minY = Math.round(y1), maxY = Math.round(y3); var xa, car, cag, cab; var xb, cbr, cbg, cbb; var k; for (var y = minY; y <= maxY; y++) { if (y < y2) { k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2); xa = x1 - (x1 - x2) * k; car = c1r - (c1r - c2r) * k; cag = c1g - (c1g - c2g) * k; cab = c1b - (c1b - c2b) * k; } else { k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3); xa = x2 - (x2 - x3) * k; car = c2r - (c2r - c3r) * k; cag = c2g - (c2g - c3g) * k; cab = c2b - (c2b - c3b) * k; } k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3); xb = x1 - (x1 - x3) * k; cbr = c1r - (c1r - c3r) * k; cbg = c1g - (c1g - c3g) * k; cbb = c1b - (c1b - c3b) * k; var x1_ = Math.round(Math.min(xa, xb)); var x2_ = Math.round(Math.max(xa, xb)); var j = rowSize * y + x1_ * 4; for (var x = x1_; x <= x2_; x++) { k = (xa - x) / (xa - xb); k = k < 0 ? 0 : k > 1 ? 1 : k; bytes[j++] = (car - (car - cbr) * k) | 0; bytes[j++] = (cag - (cag - cbg) * k) | 0; bytes[j++] = (cab - (cab - cbb) * k) | 0; bytes[j++] = 255; } } } function drawFigure(data, figure, context) { var ps = figure.coords; var cs = figure.colors; var i, ii; switch (figure.type) { case 'lattice': var verticesPerRow = figure.verticesPerRow; var rows = Math.floor(ps.length / verticesPerRow) - 1; var cols = verticesPerRow - 1; for (i = 0; i < rows; i++) { var q = i * verticesPerRow; for (var j = 0; j < cols; j++, q++) { drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]); drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]); } } break; case 'triangles': for (i = 0, ii = ps.length; i < ii; i += 3) { drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]); } break; default: error('illigal figure'); break; } } function createMeshCanvas(bounds, combinesScale, coords, colors, figures, backgroundColor, cachedCanvases) { // we will increase scale on some weird factor to let antialiasing take // care of "rough" edges var EXPECTED_SCALE = 1.1; // MAX_PATTERN_SIZE is used to avoid OOM situation. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough var offsetX = Math.floor(bounds[0]); var offsetY = Math.floor(bounds[1]); var boundsWidth = Math.ceil(bounds[2]) - offsetX; var boundsHeight = Math.ceil(bounds[3]) - offsetY; var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); var scaleX = boundsWidth / width; var scaleY = boundsHeight / height; var context = { coords: coords, colors: colors, offsetX: -offsetX, offsetY: -offsetY, scaleX: 1 / scaleX, scaleY: 1 / scaleY }; var canvas, tmpCanvas, i, ii; if (WebGLUtils.isEnabled) { canvas = WebGLUtils.drawFigures(width, height, backgroundColor, figures, context); // https://bugzilla.mozilla.org/show_bug.cgi?id=972126 tmpCanvas = cachedCanvases.getCanvas('mesh', width, height, false); tmpCanvas.context.drawImage(canvas, 0, 0); canvas = tmpCanvas.canvas; } else { tmpCanvas = cachedCanvases.getCanvas('mesh', width, height, false); var tmpCtx = tmpCanvas.context; var data = tmpCtx.createImageData(width, height); if (backgroundColor) { var bytes = data.data; for (i = 0, ii = bytes.length; i < ii; i += 4) { bytes[i] = backgroundColor[0]; bytes[i + 1] = backgroundColor[1]; bytes[i + 2] = backgroundColor[2]; bytes[i + 3] = 255; } } for (i = 0; i < figures.length; i++) { drawFigure(data, figures[i], context); } tmpCtx.putImageData(data, 0, 0); canvas = tmpCanvas.canvas; } return {canvas: canvas, offsetX: offsetX, offsetY: offsetY, scaleX: scaleX, scaleY: scaleY}; } return createMeshCanvas; })(); ShadingIRs.Mesh = { fromIR: function Mesh_fromIR(raw) { //var type = raw[1]; var coords = raw[2]; var colors = raw[3]; var figures = raw[4]; var bounds = raw[5]; var matrix = raw[6]; //var bbox = raw[7]; var background = raw[8]; return { type: 'Pattern', getPattern: function Mesh_getPattern(ctx, owner, shadingFill) { var scale; if (shadingFill) { scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform); } else { // Obtain scale from matrix and current transformation matrix. scale = Util.singularValueDecompose2dScale(owner.baseTransform); if (matrix) { var matrixScale = Util.singularValueDecompose2dScale(matrix); scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]]; } } // Rasterizing on the main thread since sending/queue large canvases // might cause OOM. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords, colors, figures, shadingFill ? null : background, owner.cachedCanvases); if (!shadingFill) { ctx.setTransform.apply(ctx, owner.baseTransform); if (matrix) { ctx.transform.apply(ctx, matrix); } } ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY); ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY); return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat'); } }; } }; ShadingIRs.Dummy = { fromIR: function Dummy_fromIR() { return { type: 'Pattern', getPattern: function Dummy_fromIR_getPattern() { return 'hotpink'; } }; } }; function getShadingPatternFromIR(raw) { var shadingIR = ShadingIRs[raw[0]]; if (!shadingIR) { error('Unknown IR type: ' + raw[0]); } return shadingIR.fromIR(raw); } var TilingPattern = (function TilingPatternClosure() { var PaintType = { COLORED: 1, UNCOLORED: 2 }; var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough function TilingPattern(IR, color, ctx, canvasGraphicsFactory, baseTransform) { this.operatorList = IR[2]; this.matrix = IR[3] || [1, 0, 0, 1, 0, 0]; this.bbox = IR[4]; this.xstep = IR[5]; this.ystep = IR[6]; this.paintType = IR[7]; this.tilingType = IR[8]; this.color = color; this.canvasGraphicsFactory = canvasGraphicsFactory; this.baseTransform = baseTransform; this.type = 'Pattern'; this.ctx = ctx; } TilingPattern.prototype = { createPatternCanvas: function TilinPattern_createPatternCanvas(owner) { var operatorList = this.operatorList; var bbox = this.bbox; var xstep = this.xstep; var ystep = this.ystep; var paintType = this.paintType; var tilingType = this.tilingType; var color = this.color; var canvasGraphicsFactory = this.canvasGraphicsFactory; info('TilingType: ' + tilingType); var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3]; var topLeft = [x0, y0]; // we want the canvas to be as large as the step size var botRight = [x0 + xstep, y0 + ystep]; var width = botRight[0] - topLeft[0]; var height = botRight[1] - topLeft[1]; // Obtain scale from matrix and current transformation matrix. var matrixScale = Util.singularValueDecompose2dScale(this.matrix); var curMatrixScale = Util.singularValueDecompose2dScale( this.baseTransform); var combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]]; // MAX_PATTERN_SIZE is used to avoid OOM situation. // Use width and height values that are as close as possible to the end // result when the pattern is used. Too low value makes the pattern look // blurry. Too large value makes it look too crispy. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])), MAX_PATTERN_SIZE); height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])), MAX_PATTERN_SIZE); var tmpCanvas = owner.cachedCanvases.getCanvas('pattern', width, height, true); var tmpCtx = tmpCanvas.context; var graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx); graphics.groupLevel = owner.groupLevel; this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color); this.setScale(width, height, xstep, ystep); this.transformToScale(graphics); // transform coordinates to pattern space var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]]; graphics.transform.apply(graphics, tmpTranslate); this.clipBbox(graphics, bbox, x0, y0, x1, y1); graphics.executeOperatorList(operatorList); return tmpCanvas.canvas; }, setScale: function TilingPattern_setScale(width, height, xstep, ystep) { this.scale = [width / xstep, height / ystep]; }, transformToScale: function TilingPattern_transformToScale(graphics) { var scale = this.scale; var tmpScale = [scale[0], 0, 0, scale[1], 0, 0]; graphics.transform.apply(graphics, tmpScale); }, scaleToContext: function TilingPattern_scaleToContext() { var scale = this.scale; this.ctx.scale(1 / scale[0], 1 / scale[1]); }, clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) { if (bbox && isArray(bbox) && bbox.length === 4) { var bboxWidth = x1 - x0; var bboxHeight = y1 - y0; graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight); graphics.clip(); graphics.endPath(); } }, setFillAndStrokeStyleToContext: function setFillAndStrokeStyleToContext(context, paintType, color) { switch (paintType) { case PaintType.COLORED: var ctx = this.ctx; context.fillStyle = ctx.fillStyle; context.strokeStyle = ctx.strokeStyle; break; case PaintType.UNCOLORED: var cssColor = Util.makeCssRgb(color[0], color[1], color[2]); context.fillStyle = cssColor; context.strokeStyle = cssColor; break; default: error('Unsupported paint type: ' + paintType); } }, getPattern: function TilingPattern_getPattern(ctx, owner) { var temporaryPatternCanvas = this.createPatternCanvas(owner); ctx = this.ctx; ctx.setTransform.apply(ctx, this.baseTransform); ctx.transform.apply(ctx, this.matrix); this.scaleToContext(); return ctx.createPattern(temporaryPatternCanvas, 'repeat'); } }; return TilingPattern; })(); exports.getShadingPatternFromIR = getShadingPatternFromIR; exports.TilingPattern = TilingPattern; })); (function (root, factory) { { factory((root.pdfjsDisplayCanvas = {}), root.pdfjsSharedUtil, root.pdfjsDisplayPatternHelper, root.pdfjsDisplayWebGL); } }(this, function (exports, sharedUtil, displayPatternHelper, displayWebGL) { var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX; var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX; var ImageKind = sharedUtil.ImageKind; var OPS = sharedUtil.OPS; var TextRenderingMode = sharedUtil.TextRenderingMode; var Uint32ArrayView = sharedUtil.Uint32ArrayView; var Util = sharedUtil.Util; var assert = sharedUtil.assert; var info = sharedUtil.info; var isNum = sharedUtil.isNum; var isArray = sharedUtil.isArray; var error = sharedUtil.error; var shadow = sharedUtil.shadow; var warn = sharedUtil.warn; var TilingPattern = displayPatternHelper.TilingPattern; var getShadingPatternFromIR = displayPatternHelper.getShadingPatternFromIR; var WebGLUtils = displayWebGL.WebGLUtils; // <canvas> contexts store most of the state we need natively. // However, PDF needs a bit more state, which we store here. // Minimal font size that would be used during canvas fillText operations. var MIN_FONT_SIZE = 16; // Maximum font size that would be used during canvas fillText operations. var MAX_FONT_SIZE = 100; var MAX_GROUP_SIZE = 4096; // Heuristic value used when enforcing minimum line widths. var MIN_WIDTH_FACTOR = 0.65; var COMPILE_TYPE3_GLYPHS = true; var MAX_SIZE_TO_COMPILE = 1000; var FULL_CHUNK_HEIGHT = 16; function createScratchCanvas(width, height) { var canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; return canvas; } function addContextCurrentTransform(ctx) { // If the context doesn't expose a `mozCurrentTransform`, add a JS based one. if (!ctx.mozCurrentTransform) { ctx._originalSave = ctx.save; ctx._originalRestore = ctx.restore; ctx._originalRotate = ctx.rotate; ctx._originalScale = ctx.scale; ctx._originalTranslate = ctx.translate; ctx._originalTransform = ctx.transform; ctx._originalSetTransform = ctx.setTransform; ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0]; ctx._transformStack = []; Object.defineProperty(ctx, 'mozCurrentTransform', { get: function getCurrentTransform() { return this._transformMatrix; } }); Object.defineProperty(ctx, 'mozCurrentTransformInverse', { get: function getCurrentTransformInverse() { // Calculation done using WolframAlpha: // http://www.wolframalpha.com/input/? // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}} var m = this._transformMatrix; var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5]; var ad_bc = a * d - b * c; var bc_ad = b * c - a * d; return [ d / ad_bc, b / bc_ad, c / bc_ad, a / ad_bc, (d * e - c * f) / bc_ad, (b * e - a * f) / ad_bc ]; } }); ctx.save = function ctxSave() { var old = this._transformMatrix; this._transformStack.push(old); this._transformMatrix = old.slice(0, 6); this._originalSave(); }; ctx.restore = function ctxRestore() { var prev = this._transformStack.pop(); if (prev) { this._transformMatrix = prev; this._originalRestore(); } }; ctx.translate = function ctxTranslate(x, y) { var m = this._transformMatrix; m[4] = m[0] * x + m[2] * y + m[4]; m[5] = m[1] * x + m[3] * y + m[5]; this._originalTranslate(x, y); }; ctx.scale = function ctxScale(x, y) { var m = this._transformMatrix; m[0] = m[0] * x; m[1] = m[1] * x; m[2] = m[2] * y; m[3] = m[3] * y; this._originalScale(x, y); }; ctx.transform = function ctxTransform(a, b, c, d, e, f) { var m = this._transformMatrix; this._transformMatrix = [ m[0] * a + m[2] * b, m[1] * a + m[3] * b, m[0] * c + m[2] * d, m[1] * c + m[3] * d, m[0] * e + m[2] * f + m[4], m[1] * e + m[3] * f + m[5] ]; ctx._originalTransform(a, b, c, d, e, f); }; ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) { this._transformMatrix = [a, b, c, d, e, f]; ctx._originalSetTransform(a, b, c, d, e, f); }; ctx.rotate = function ctxRotate(angle) { var cosValue = Math.cos(angle); var sinValue = Math.sin(angle); var m = this._transformMatrix; this._transformMatrix = [ m[0] * cosValue + m[2] * sinValue, m[1] * cosValue + m[3] * sinValue, m[0] * (-sinValue) + m[2] * cosValue, m[1] * (-sinValue) + m[3] * cosValue, m[4], m[5] ]; this._originalRotate(angle); }; } } var CachedCanvases = (function CachedCanvasesClosure() { function CachedCanvases() { this.cache = Object.create(null); } CachedCanvases.prototype = { getCanvas: function CachedCanvases_getCanvas(id, width, height, trackTransform) { var canvasEntry; if (this.cache[id] !== undefined) { canvasEntry = this.cache[id]; canvasEntry.canvas.width = width; canvasEntry.canvas.height = height; // reset canvas transform for emulated mozCurrentTransform, if needed canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0); } else { var canvas = createScratchCanvas(width, height); var ctx = canvas.getContext('2d'); if (trackTransform) { addContextCurrentTransform(ctx); } this.cache[id] = canvasEntry = {canvas: canvas, context: ctx}; } return canvasEntry; }, clear: function () { for (var id in this.cache) { var canvasEntry = this.cache[id]; // Zeroing the width and height causes Firefox to release graphics // resources immediately, which can greatly reduce memory consumption. canvasEntry.canvas.width = 0; canvasEntry.canvas.height = 0; delete this.cache[id]; } } }; return CachedCanvases; })(); function compileType3Glyph(imgData) { var POINT_TO_PROCESS_LIMIT = 1000; var width = imgData.width, height = imgData.height; var i, j, j0, width1 = width + 1; var points = new Uint8Array(width1 * (height + 1)); var POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]); // decodes bit-packed mask data var lineSize = (width + 7) & ~7, data0 = imgData.data; var data = new Uint8Array(lineSize * height), pos = 0, ii; for (i = 0, ii = data0.length; i < ii; i++) { var mask = 128, elem = data0[i]; while (mask > 0) { data[pos++] = (elem & mask) ? 0 : 255; mask >>= 1; } } // finding iteresting points: every point is located between mask pixels, // so there will be points of the (width + 1)x(height + 1) grid. Every point // will have flags assigned based on neighboring mask pixels: // 4 | 8 // --P-- // 2 | 1 // We are interested only in points with the flags: // - outside corners: 1, 2, 4, 8; // - inside corners: 7, 11, 13, 14; // - and, intersections: 5, 10. var count = 0; pos = 0; if (data[pos] !== 0) { points[0] = 1; ++count; } for (j = 1; j < width; j++) { if (data[pos] !== data[pos + 1]) { points[j] = data[pos] ? 2 : 1; ++count; } pos++; } if (data[pos] !== 0) { points[j] = 2; ++count; } for (i = 1; i < height; i++) { pos = i * lineSize; j0 = i * width1; if (data[pos - lineSize] !== data[pos]) { points[j0] = data[pos] ? 1 : 8; ++count; } // 'sum' is the position of the current pixel configuration in the 'TYPES' // array (in order 8-1-2-4, so we can use '>>2' to shift the column). var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0); for (j = 1; j < width; j++) { sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0); if (POINT_TYPES[sum]) { points[j0 + j] = POINT_TYPES[sum]; ++count; } pos++; } if (data[pos - lineSize] !== data[pos]) { points[j0 + j] = data[pos] ? 2 : 4; ++count; } if (count > POINT_TO_PROCESS_LIMIT) { return null; } } pos = lineSize * (height - 1); j0 = i * width1; if (data[pos] !== 0) { points[j0] = 8; ++count; } for (j = 1; j < width; j++) { if (data[pos] !== data[pos + 1]) { points[j0 + j] = data[pos] ? 4 : 8; ++count; } pos++; } if (data[pos] !== 0) { points[j0 + j] = 4; ++count; } if (count > POINT_TO_PROCESS_LIMIT) { return null; } // building outlines var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]); var outlines = []; for (i = 0; count && i <= height; i++) { var p = i * width1; var end = p + width; while (p < end && !points[p]) { p++; } if (p === end) { continue; } var coords = [p % width1, i]; var type = points[p], p0 = p, pp; do { var step = steps[type]; do { p += step; } while (!points[p]); pp = points[p]; if (pp !== 5 && pp !== 10) { // set new direction type = pp; // delete mark points[p] = 0; } else { // type is 5 or 10, ie, a crossing // set new direction type = pp & ((0x33 * type) >> 4); // set new type for "future hit" points[p] &= (type >> 2 | type << 2); } coords.push(p % width1); coords.push((p / width1) | 0); --count; } while (p0 !== p); outlines.push(coords); --i; } var drawOutline = function(c) { c.save(); // the path shall be painted in [0..1]x[0..1] space c.scale(1 / width, -1 / height); c.translate(0, -height); c.beginPath(); for (var i = 0, ii = outlines.length; i < ii; i++) { var o = outlines[i]; c.moveTo(o[0], o[1]); for (var j = 2, jj = o.length; j < jj; j += 2) { c.lineTo(o[j], o[j+1]); } } c.fill(); c.beginPath(); c.restore(); }; return drawOutline; } var CanvasExtraState = (function CanvasExtraStateClosure() { function CanvasExtraState(old) { // Are soft masks and alpha values shapes or opacities? this.alphaIsShape = false; this.fontSize = 0; this.fontSizeScale = 1; this.textMatrix = IDENTITY_MATRIX; this.textMatrixScale = 1; this.fontMatrix = FONT_IDENTITY_MATRIX; this.leading = 0; // Current point (in user coordinates) this.x = 0; this.y = 0; // Start of text line (in text coordinates) this.lineX = 0; this.lineY = 0; // Character and word spacing this.charSpacing = 0; this.wordSpacing = 0; this.textHScale = 1; this.textRenderingMode = TextRenderingMode.FILL; this.textRise = 0; // Default fore and background colors this.fillColor = '#000000'; this.strokeColor = '#000000'; this.patternFill = false; // Note: fill alpha applies to all non-stroking operations this.fillAlpha = 1; this.strokeAlpha = 1; this.lineWidth = 1; this.activeSMask = null; // nonclonable field (see the save method below) this.old = old; } CanvasExtraState.prototype = { clone: function CanvasExtraState_clone() { return Object.create(this); }, setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) { this.x = x; this.y = y; } }; return CanvasExtraState; })(); var CanvasGraphics = (function CanvasGraphicsClosure() { // Defines the time the executeOperatorList is going to be executing // before it stops and shedules a continue of execution. var EXECUTION_TIME = 15; // Defines the number of steps before checking the execution time var EXECUTION_STEPS = 10; function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) { this.ctx = canvasCtx; this.current = new CanvasExtraState(); this.stateStack = []; this.pendingClip = null; this.pendingEOFill = false; this.res = null; this.xobjs = null; this.commonObjs = commonObjs; this.objs = objs; this.imageLayer = imageLayer; this.groupStack = []; this.processingType3 = null; // Patterns are painted relative to the initial page/form transform, see pdf // spec 8.7.2 NOTE 1. this.baseTransform = null; this.baseTransformStack = []; this.groupLevel = 0; this.smaskStack = []; this.smaskCounter = 0; this.tempSMask = null; this.cachedCanvases = new CachedCanvases(); if (canvasCtx) { // NOTE: if mozCurrentTransform is polyfilled, then the current state of // the transformation must already be set in canvasCtx._transformMatrix. addContextCurrentTransform(canvasCtx); } this.cachedGetSinglePixelWidth = null; } function putBinaryImageData(ctx, imgData) { if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) { ctx.putImageData(imgData, 0, 0); return; } // Put the image data to the canvas in chunks, rather than putting the // whole image at once. This saves JS memory, because the ImageData object // is smaller. It also possibly saves C++ memory within the implementation // of putImageData(). (E.g. in Firefox we make two short-lived copies of // the data passed to putImageData()). |n| shouldn't be too small, however, // because too many putImageData() calls will slow things down. // // Note: as written, if the last chunk is partial, the putImageData() call // will (conceptually) put pixels past the bounds of the canvas. But // that's ok; any such pixels are ignored. var height = imgData.height, width = imgData.width; var partialChunkHeight = height % FULL_CHUNK_HEIGHT; var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); var srcPos = 0, destPos; var src = imgData.data; var dest = chunkImgData.data; var i, j, thisChunkHeight, elemsInThisChunk; // There are multiple forms in which the pixel data can be passed, and // imgData.kind tells us which one this is. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) { // Grayscale, 1 bit per pixel (i.e. black-and-white). var srcLength = src.byteLength; var dest32 = PDFJS.hasCanvasTypedArrays ? new Uint32Array(dest.buffer) : new Uint32ArrayView(dest); var dest32DataLength = dest32.length; var fullSrcDiff = (width + 7) >> 3; var white = 0xFFFFFFFF; var black = (PDFJS.isLittleEndian || !PDFJS.hasCanvasTypedArrays) ? 0xFF000000 : 0x000000FF; for (i = 0; i < totalChunks; i++) { thisChunkHeight = (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight; destPos = 0; for (j = 0; j < thisChunkHeight; j++) { var srcDiff = srcLength - srcPos; var k = 0; var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7; var kEndUnrolled = kEnd & ~7; var mask = 0; var srcByte = 0; for (; k < kEndUnrolled; k += 8) { srcByte = src[srcPos++]; dest32[destPos++] = (srcByte & 128) ? white : black; dest32[destPos++] = (srcByte & 64) ? white : black; dest32[destPos++] = (srcByte & 32) ? white : black; dest32[destPos++] = (srcByte & 16) ? white : black; dest32[destPos++] = (srcByte & 8) ? white : black; dest32[destPos++] = (srcByte & 4) ? white : black; dest32[destPos++] = (srcByte & 2) ? white : black; dest32[destPos++] = (srcByte & 1) ? white : black; } for (; k < kEnd; k++) { if (mask === 0) { srcByte = src[srcPos++]; mask = 128; } dest32[destPos++] = (srcByte & mask) ? white : black; mask >>= 1; } } // We ran out of input. Make all remaining pixels transparent. while (destPos < dest32DataLength) { dest32[destPos++] = 0; } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } else if (imgData.kind === ImageKind.RGBA_32BPP) { // RGBA, 32-bits per pixel. j = 0; elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4; for (i = 0; i < fullChunks; i++) { dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); srcPos += elemsInThisChunk; ctx.putImageData(chunkImgData, 0, j); j += FULL_CHUNK_HEIGHT; } if (i < totalChunks) { elemsInThisChunk = width * partialChunkHeight * 4; dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); ctx.putImageData(chunkImgData, 0, j); } } else if (imgData.kind === ImageKind.RGB_24BPP) { // RGB, 24-bits per pixel. thisChunkHeight = FULL_CHUNK_HEIGHT; elemsInThisChunk = width * thisChunkHeight; for (i = 0; i < totalChunks; i++) { if (i >= fullChunks) { thisChunkHeight = partialChunkHeight; elemsInThisChunk = width * thisChunkHeight; } destPos = 0; for (j = elemsInThisChunk; j--;) { dest[destPos++] = src[srcPos++]; dest[destPos++] = src[srcPos++]; dest[destPos++] = src[srcPos++]; dest[destPos++] = 255; } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } else { error('bad image kind: ' + imgData.kind); } } function putBinaryImageMask(ctx, imgData) { var height = imgData.height, width = imgData.width; var partialChunkHeight = height % FULL_CHUNK_HEIGHT; var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); var srcPos = 0; var src = imgData.data; var dest = chunkImgData.data; for (var i = 0; i < totalChunks; i++) { var thisChunkHeight = (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight; // Expand the mask so it can be used by the canvas. Any required // inversion has already been handled. var destPos = 3; // alpha component offset for (var j = 0; j < thisChunkHeight; j++) { var mask = 0; for (var k = 0; k < width; k++) { if (!mask) { var elem = src[srcPos++]; mask = 128; } dest[destPos] = (elem & mask) ? 0 : 255; destPos += 4; mask >>= 1; } } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } function copyCtxState(sourceCtx, destCtx) { var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha', 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit', 'globalCompositeOperation', 'font']; for (var i = 0, ii = properties.length; i < ii; i++) { var property = properties[i]; if (sourceCtx[property] !== undefined) { destCtx[property] = sourceCtx[property]; } } if (sourceCtx.setLineDash !== undefined) { destCtx.setLineDash(sourceCtx.getLineDash()); destCtx.lineDashOffset = sourceCtx.lineDashOffset; } else if (sourceCtx.mozDashOffset !== undefined) { destCtx.mozDash = sourceCtx.mozDash; destCtx.mozDashOffset = sourceCtx.mozDashOffset; } } function composeSMaskBackdrop(bytes, r0, g0, b0) { var length = bytes.length; for (var i = 3; i < length; i += 4) { var alpha = bytes[i]; if (alpha === 0) { bytes[i - 3] = r0; bytes[i - 2] = g0; bytes[i - 1] = b0; } else if (alpha < 255) { var alpha_ = 255 - alpha; bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8; bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8; bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8; } } } function composeSMaskAlpha(maskData, layerData, transferMap) { var length = maskData.length; var scale = 1 / 255; for (var i = 3; i < length; i += 4) { var alpha = transferMap ? transferMap[maskData[i]] : maskData[i]; layerData[i] = (layerData[i] * alpha * scale) | 0; } } function composeSMaskLuminosity(maskData, layerData, transferMap) { var length = maskData.length; for (var i = 3; i < length; i += 4) { var y = (maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000 (maskData[i - 2] * 152) + // * 0.59 .... (maskData[i - 1] * 28); // * 0.11 .... layerData[i] = transferMap ? (layerData[i] * transferMap[y >> 8]) >> 8 : (layerData[i] * y) >> 16; } } function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap) { var hasBackdrop = !!backdrop; var r0 = hasBackdrop ? backdrop[0] : 0; var g0 = hasBackdrop ? backdrop[1] : 0; var b0 = hasBackdrop ? backdrop[2] : 0; var composeFn; if (subtype === 'Luminosity') { composeFn = composeSMaskLuminosity; } else { composeFn = composeSMaskAlpha; } // processing image in chunks to save memory var PIXELS_TO_PROCESS = 1048576; var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width)); for (var row = 0; row < height; row += chunkSize) { var chunkHeight = Math.min(chunkSize, height - row); var maskData = maskCtx.getImageData(0, row, width, chunkHeight); var layerData = layerCtx.getImageData(0, row, width, chunkHeight); if (hasBackdrop) { composeSMaskBackdrop(maskData.data, r0, g0, b0); } composeFn(maskData.data, layerData.data, transferMap); maskCtx.putImageData(layerData, 0, row); } } function composeSMask(ctx, smask, layerCtx) { var mask = smask.canvas; var maskCtx = smask.context; ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY, smask.offsetX, smask.offsetY); var backdrop = smask.backdrop || null; if (!smask.transferMap && WebGLUtils.isEnabled) { var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask, {subtype: smask.subtype, backdrop: backdrop}); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(composed, smask.offsetX, smask.offsetY); return; } genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height, smask.subtype, backdrop, smask.transferMap); ctx.drawImage(mask, 0, 0); } var LINE_CAP_STYLES = ['butt', 'round', 'square']; var LINE_JOIN_STYLES = ['miter', 'round', 'bevel']; var NORMAL_CLIP = {}; var EO_CLIP = {}; CanvasGraphics.prototype = { beginDrawing: function CanvasGraphics_beginDrawing(transform, viewport, transparency) { // For pdfs that use blend modes we have to clear the canvas else certain // blend modes can look wrong since we'd be blending with a white // backdrop. The problem with a transparent backdrop though is we then // don't get sub pixel anti aliasing on text, creating temporary // transparent canvas when we have blend modes. var width = this.ctx.canvas.width; var height = this.ctx.canvas.height; this.ctx.save(); this.ctx.fillStyle = 'rgb(255, 255, 255)'; this.ctx.fillRect(0, 0, width, height); this.ctx.restore(); if (transparency) { var transparentCanvas = this.cachedCanvases.getCanvas( 'transparent', width, height, true); this.compositeCtx = this.ctx; this.transparentCanvas = transparentCanvas.canvas; this.ctx = transparentCanvas.context; this.ctx.save(); // The transform can be applied before rendering, transferring it to // the new canvas. this.ctx.transform.apply(this.ctx, this.compositeCtx.mozCurrentTransform); } this.ctx.save(); if (transform) { this.ctx.transform.apply(this.ctx, transform); } this.ctx.transform.apply(this.ctx, viewport.transform); this.baseTransform = this.ctx.mozCurrentTransform.slice(); if (this.imageLayer) { this.imageLayer.beginLayout(); } }, executeOperatorList: function CanvasGraphics_executeOperatorList( operatorList, executionStartIdx, continueCallback, stepper) { var argsArray = operatorList.argsArray; var fnArray = operatorList.fnArray; var i = executionStartIdx || 0; var argsArrayLen = argsArray.length; // Sometimes the OperatorList to execute is empty. if (argsArrayLen === i) { return i; } var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === 'function'); var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0; var steps = 0; var commonObjs = this.commonObjs; var objs = this.objs; var fnId; while (true) { if (stepper !== undefined && i === stepper.nextBreakPoint) { stepper.breakIt(i, continueCallback); return i; } fnId = fnArray[i]; if (fnId !== OPS.dependency) { this[fnId].apply(this, argsArray[i]); } else { var deps = argsArray[i]; for (var n = 0, nn = deps.length; n < nn; n++) { var depObjId = deps[n]; var common = depObjId[0] === 'g' && depObjId[1] === '_'; var objsPool = common ? commonObjs : objs; // If the promise isn't resolved yet, add the continueCallback // to the promise and bail out. if (!objsPool.isResolved(depObjId)) { objsPool.get(depObjId, continueCallback); return i; } } } i++; // If the entire operatorList was executed, stop as were done. if (i === argsArrayLen) { return i; } // If the execution took longer then a certain amount of time and // `continueCallback` is specified, interrupt the execution. if (chunkOperations && ++steps > EXECUTION_STEPS) { if (Date.now() > endTime) { continueCallback(); return i; } steps = 0; } // If the operatorList isn't executed completely yet OR the execution // time was short enough, do another execution round. } }, endDrawing: function CanvasGraphics_endDrawing() { this.ctx.restore(); if (this.transparentCanvas) { this.ctx = this.compositeCtx; this.ctx.drawImage(this.transparentCanvas, 0, 0); this.transparentCanvas = null; } this.cachedCanvases.clear(); WebGLUtils.clear(); if (this.imageLayer) { this.imageLayer.endLayout(); } }, // Graphics state setLineWidth: function CanvasGraphics_setLineWidth(width) { this.current.lineWidth = width; this.ctx.lineWidth = width; }, setLineCap: function CanvasGraphics_setLineCap(style) { this.ctx.lineCap = LINE_CAP_STYLES[style]; }, setLineJoin: function CanvasGraphics_setLineJoin(style) { this.ctx.lineJoin = LINE_JOIN_STYLES[style]; }, setMiterLimit: function CanvasGraphics_setMiterLimit(limit) { this.ctx.miterLimit = limit; }, setDash: function CanvasGraphics_setDash(dashArray, dashPhase) { var ctx = this.ctx; if (ctx.setLineDash !== undefined) { ctx.setLineDash(dashArray); ctx.lineDashOffset = dashPhase; } else { ctx.mozDash = dashArray; ctx.mozDashOffset = dashPhase; } }, setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) { // Maybe if we one day fully support color spaces this will be important // for now we can ignore. // TODO set rendering intent? }, setFlatness: function CanvasGraphics_setFlatness(flatness) { // There's no way to control this with canvas, but we can safely ignore. // TODO set flatness? }, setGState: function CanvasGraphics_setGState(states) { for (var i = 0, ii = states.length; i < ii; i++) { var state = states[i]; var key = state[0]; var value = state[1]; switch (key) { case 'LW': this.setLineWidth(value); break; case 'LC': this.setLineCap(value); break; case 'LJ': this.setLineJoin(value); break; case 'ML': this.setMiterLimit(value); break; case 'D': this.setDash(value[0], value[1]); break; case 'RI': this.setRenderingIntent(value); break; case 'FL': this.setFlatness(value); break; case 'Font': this.setFont(value[0], value[1]); break; case 'CA': this.current.strokeAlpha = state[1]; break; case 'ca': this.current.fillAlpha = state[1]; this.ctx.globalAlpha = state[1]; break; case 'BM': if (value && value.name && (value.name !== 'Normal')) { var mode = value.name.replace(/([A-Z])/g, function(c) { return '-' + c.toLowerCase(); } ).substring(1); this.ctx.globalCompositeOperation = mode; if (this.ctx.globalCompositeOperation !== mode) { warn('globalCompositeOperation "' + mode + '" is not supported'); } } else { this.ctx.globalCompositeOperation = 'source-over'; } break; case 'SMask': if (this.current.activeSMask) { this.endSMaskGroup(); } this.current.activeSMask = value ? this.tempSMask : null; if (this.current.activeSMask) { this.beginSMaskGroup(); } this.tempSMask = null; break; } } }, beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() { var activeSMask = this.current.activeSMask; var drawnWidth = activeSMask.canvas.width; var drawnHeight = activeSMask.canvas.height; var cacheId = 'smaskGroupAt' + this.groupLevel; var scratchCanvas = this.cachedCanvases.getCanvas( cacheId, drawnWidth, drawnHeight, true); var currentCtx = this.ctx; var currentTransform = currentCtx.mozCurrentTransform; this.ctx.save(); var groupCtx = scratchCanvas.context; groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY); groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY); groupCtx.transform.apply(groupCtx, currentTransform); copyCtxState(currentCtx, groupCtx); this.ctx = groupCtx; this.setGState([ ['BM', 'Normal'], ['ca', 1], ['CA', 1] ]); this.groupStack.push(currentCtx); this.groupLevel++; }, endSMaskGroup: function CanvasGraphics_endSMaskGroup() { var groupCtx = this.ctx; this.groupLevel--; this.ctx = this.groupStack.pop(); composeSMask(this.ctx, this.current.activeSMask, groupCtx); this.ctx.restore(); copyCtxState(groupCtx, this.ctx); }, save: function CanvasGraphics_save() { this.ctx.save(); var old = this.current; this.stateStack.push(old); this.current = old.clone(); this.current.activeSMask = null; }, restore: function CanvasGraphics_restore() { if (this.stateStack.length !== 0) { if (this.current.activeSMask !== null) { this.endSMaskGroup(); } this.current = this.stateStack.pop(); this.ctx.restore(); // Ensure that the clipping path is reset (fixes issue6413.pdf). this.pendingClip = null; this.cachedGetSinglePixelWidth = null; } }, transform: function CanvasGraphics_transform(a, b, c, d, e, f) { this.ctx.transform(a, b, c, d, e, f); this.cachedGetSinglePixelWidth = null; }, // Path constructPath: function CanvasGraphics_constructPath(ops, args) { var ctx = this.ctx; var current = this.current; var x = current.x, y = current.y; for (var i = 0, j = 0, ii = ops.length; i < ii; i++) { switch (ops[i] | 0) { case OPS.rectangle: x = args[j++]; y = args[j++]; var width = args[j++]; var height = args[j++]; if (width === 0) { width = this.getSinglePixelWidth(); } if (height === 0) { height = this.getSinglePixelWidth(); } var xw = x + width; var yh = y + height; this.ctx.moveTo(x, y); this.ctx.lineTo(xw, y); this.ctx.lineTo(xw, yh); this.ctx.lineTo(x, yh); this.ctx.lineTo(x, y); this.ctx.closePath(); break; case OPS.moveTo: x = args[j++]; y = args[j++]; ctx.moveTo(x, y); break; case OPS.lineTo: x = args[j++]; y = args[j++]; ctx.lineTo(x, y); break; case OPS.curveTo: x = args[j + 4]; y = args[j + 5]; ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y); j += 6; break; case OPS.curveTo2: ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]); x = args[j + 2]; y = args[j + 3]; j += 4; break; case OPS.curveTo3: x = args[j + 2]; y = args[j + 3]; ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y); j += 4; break; case OPS.closePath: ctx.closePath(); break; } } current.setCurrentPoint(x, y); }, closePath: function CanvasGraphics_closePath() { this.ctx.closePath(); }, stroke: function CanvasGraphics_stroke(consumePath) { consumePath = typeof consumePath !== 'undefined' ? consumePath : true; var ctx = this.ctx; var strokeColor = this.current.strokeColor; // Prevent drawing too thin lines by enforcing a minimum line width. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR, this.current.lineWidth); // For stroke we want to temporarily change the global alpha to the // stroking alpha. ctx.globalAlpha = this.current.strokeAlpha; if (strokeColor && strokeColor.hasOwnProperty('type') && strokeColor.type === 'Pattern') { // for patterns, we transform to pattern space, calculate // the pattern, call stroke, and restore to user space ctx.save(); ctx.strokeStyle = strokeColor.getPattern(ctx, this); ctx.stroke(); ctx.restore(); } else { ctx.stroke(); } if (consumePath) { this.consumePath(); } // Restore the global alpha to the fill alpha ctx.globalAlpha = this.current.fillAlpha; }, closeStroke: function CanvasGraphics_closeStroke() { this.closePath(); this.stroke(); }, fill: function CanvasGraphics_fill(consumePath) { consumePath = typeof consumePath !== 'undefined' ? consumePath : true; var ctx = this.ctx; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var needRestore = false; if (isPatternFill) { ctx.save(); if (this.baseTransform) { ctx.setTransform.apply(ctx, this.baseTransform); } ctx.fillStyle = fillColor.getPattern(ctx, this); needRestore = true; } if (this.pendingEOFill) { if (ctx.mozFillRule !== undefined) { ctx.mozFillRule = 'evenodd'; ctx.fill(); ctx.mozFillRule = 'nonzero'; } else { ctx.fill('evenodd'); } this.pendingEOFill = false; } else { ctx.fill(); } if (needRestore) { ctx.restore(); } if (consumePath) { this.consumePath(); } }, eoFill: function CanvasGraphics_eoFill() { this.pendingEOFill = true; this.fill(); }, fillStroke: function CanvasGraphics_fillStroke() { this.fill(false); this.stroke(false); this.consumePath(); }, eoFillStroke: function CanvasGraphics_eoFillStroke() { this.pendingEOFill = true; this.fillStroke(); }, closeFillStroke: function CanvasGraphics_closeFillStroke() { this.closePath(); this.fillStroke(); }, closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() { this.pendingEOFill = true; this.closePath(); this.fillStroke(); }, endPath: function CanvasGraphics_endPath() { this.consumePath(); }, // Clipping clip: function CanvasGraphics_clip() { this.pendingClip = NORMAL_CLIP; }, eoClip: function CanvasGraphics_eoClip() { this.pendingClip = EO_CLIP; }, // Text beginText: function CanvasGraphics_beginText() { this.current.textMatrix = IDENTITY_MATRIX; this.current.textMatrixScale = 1; this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; }, endText: function CanvasGraphics_endText() { var paths = this.pendingTextPaths; var ctx = this.ctx; if (paths === undefined) { ctx.beginPath(); return; } ctx.save(); ctx.beginPath(); for (var i = 0; i < paths.length; i++) { var path = paths[i]; ctx.setTransform.apply(ctx, path.transform); ctx.translate(path.x, path.y); path.addToPath(ctx, path.fontSize); } ctx.restore(); ctx.clip(); ctx.beginPath(); delete this.pendingTextPaths; }, setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) { this.current.charSpacing = spacing; }, setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) { this.current.wordSpacing = spacing; }, setHScale: function CanvasGraphics_setHScale(scale) { this.current.textHScale = scale / 100; }, setLeading: function CanvasGraphics_setLeading(leading) { this.current.leading = -leading; }, setFont: function CanvasGraphics_setFont(fontRefName, size) { var fontObj = this.commonObjs.get(fontRefName); var current = this.current; if (!fontObj) { error('Can\'t find font for ' + fontRefName); } current.fontMatrix = (fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX); // A valid matrix needs all main diagonal elements to be non-zero // This also ensures we bypass FF bugzilla bug #719844. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) { warn('Invalid font matrix for font ' + fontRefName); } // The spec for Tf (setFont) says that 'size' specifies the font 'scale', // and in some docs this can be negative (inverted x-y axes). if (size < 0) { size = -size; current.fontDirection = -1; } else { current.fontDirection = 1; } this.current.font = fontObj; this.current.fontSize = size; if (fontObj.isType3Font) { return; // we don't need ctx.font for Type3 fonts } var name = fontObj.loadedName || 'sans-serif'; var bold = fontObj.black ? (fontObj.bold ? '900' : 'bold') : (fontObj.bold ? 'bold' : 'normal'); var italic = fontObj.italic ? 'italic' : 'normal'; var typeface = '"' + name + '", ' + fontObj.fallbackName; // Some font backends cannot handle fonts below certain size. // Keeping the font at minimal size and using the fontSizeScale to change // the current transformation matrix before the fillText/strokeText. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227 var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE : size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size; this.current.fontSizeScale = size / browserFontSize; var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface; this.ctx.font = rule; }, setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) { this.current.textRenderingMode = mode; }, setTextRise: function CanvasGraphics_setTextRise(rise) { this.current.textRise = rise; }, moveText: function CanvasGraphics_moveText(x, y) { this.current.x = this.current.lineX += x; this.current.y = this.current.lineY += y; }, setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) { this.setLeading(-y); this.moveText(x, y); }, setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) { this.current.textMatrix = [a, b, c, d, e, f]; this.current.textMatrixScale = Math.sqrt(a * a + b * b); this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; }, nextLine: function CanvasGraphics_nextLine() { this.moveText(0, this.current.leading); }, paintChar: function CanvasGraphics_paintChar(character, x, y) { var ctx = this.ctx; var current = this.current; var font = current.font; var textRenderingMode = current.textRenderingMode; var fontSize = current.fontSize / current.fontSizeScale; var fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; var isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG); var addToPath; if (font.disableFontFace || isAddToPathSet) { addToPath = font.getPathGenerator(this.commonObjs, character); } if (font.disableFontFace) { ctx.save(); ctx.translate(x, y); ctx.beginPath(); addToPath(ctx, fontSize); if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.fill(); } if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.stroke(); } ctx.restore(); } else { if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.fillText(character, x, y); } if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.strokeText(character, x, y); } } if (isAddToPathSet) { var paths = this.pendingTextPaths || (this.pendingTextPaths = []); paths.push({ transform: ctx.mozCurrentTransform, x: x, y: y, fontSize: fontSize, addToPath: addToPath }); } }, get isFontSubpixelAAEnabled() { // Checks if anti-aliasing is enabled when scaled text is painted. // On Windows GDI scaled fonts looks bad. var ctx = document.createElement('canvas').getContext('2d'); ctx.scale(1.5, 1); ctx.fillText('I', 0, 10); var data = ctx.getImageData(0, 0, 10, 10).data; var enabled = false; for (var i = 3; i < data.length; i += 4) { if (data[i] > 0 && data[i] < 255) { enabled = true; break; } } return shadow(this, 'isFontSubpixelAAEnabled', enabled); }, showText: function CanvasGraphics_showText(glyphs) { var current = this.current; var font = current.font; if (font.isType3Font) { return this.showType3Text(glyphs); } var fontSize = current.fontSize; if (fontSize === 0) { return; } var ctx = this.ctx; var fontSizeScale = current.fontSizeScale; var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var fontDirection = current.fontDirection; var textHScale = current.textHScale * fontDirection; var glyphsLength = glyphs.length; var vertical = font.vertical; var spacingDir = vertical ? 1 : -1; var defaultVMetrics = font.defaultVMetrics; var widthAdvanceScale = fontSize * current.fontMatrix[0]; var simpleFillText = current.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace; ctx.save(); ctx.transform.apply(ctx, current.textMatrix); ctx.translate(current.x, current.y + current.textRise); if (current.patternFill) { // TODO: Some shading patterns are not applied correctly to text, // e.g. issues 3988 and 5432, and ShowText-ShadingPattern.pdf. ctx.fillStyle = current.fillColor.getPattern(ctx, this); } if (fontDirection > 0) { ctx.scale(textHScale, -1); } else { ctx.scale(textHScale, 1); } var lineWidth = current.lineWidth; var scale = current.textMatrixScale; if (scale === 0 || lineWidth === 0) { var fillStrokeMode = current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { this.cachedGetSinglePixelWidth = null; lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR; } } else { lineWidth /= scale; } if (fontSizeScale !== 1.0) { ctx.scale(fontSizeScale, fontSizeScale); lineWidth /= fontSizeScale; } ctx.lineWidth = lineWidth; var x = 0, i; for (i = 0; i < glyphsLength; ++i) { var glyph = glyphs[i]; if (isNum(glyph)) { x += spacingDir * glyph * fontSize / 1000; continue; } var restoreNeeded = false; var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; var character = glyph.fontChar; var accent = glyph.accent; var scaledX, scaledY, scaledAccentX, scaledAccentY; var width = glyph.width; if (vertical) { var vmetric, vx, vy; vmetric = glyph.vmetric || defaultVMetrics; vx = glyph.vmetric ? vmetric[1] : width * 0.5; vx = -vx * widthAdvanceScale; vy = vmetric[2] * widthAdvanceScale; width = vmetric ? -vmetric[0] : width; scaledX = vx / fontSizeScale; scaledY = (x + vy) / fontSizeScale; } else { scaledX = x / fontSizeScale; scaledY = 0; } if (font.remeasure && width > 0) { // Some standard fonts may not have the exact width: rescale per // character if measured width is greater than expected glyph width // and subpixel-aa is enabled, otherwise just center the glyph. var measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale; if (width < measuredWidth && this.isFontSubpixelAAEnabled) { var characterScaleX = width / measuredWidth; restoreNeeded = true; ctx.save(); ctx.scale(characterScaleX, 1); scaledX /= characterScaleX; } else if (width !== measuredWidth) { scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale; } } if (simpleFillText && !accent) { // common case ctx.fillText(character, scaledX, scaledY); } else { this.paintChar(character, scaledX, scaledY); if (accent) { scaledAccentX = scaledX + accent.offset.x / fontSizeScale; scaledAccentY = scaledY - accent.offset.y / fontSizeScale; this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY); } } var charWidth = width * widthAdvanceScale + spacing * fontDirection; x += charWidth; if (restoreNeeded) { ctx.restore(); } } if (vertical) { current.y -= x * textHScale; } else { current.x += x * textHScale; } ctx.restore(); }, showType3Text: function CanvasGraphics_showType3Text(glyphs) { // Type3 fonts - each glyph is a "mini-PDF" var ctx = this.ctx; var current = this.current; var font = current.font; var fontSize = current.fontSize; var fontDirection = current.fontDirection; var spacingDir = font.vertical ? 1 : -1; var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var textHScale = current.textHScale * fontDirection; var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX; var glyphsLength = glyphs.length; var isTextInvisible = current.textRenderingMode === TextRenderingMode.INVISIBLE; var i, glyph, width, spacingLength; if (isTextInvisible || fontSize === 0) { return; } this.cachedGetSinglePixelWidth = null; ctx.save(); ctx.transform.apply(ctx, current.textMatrix); ctx.translate(current.x, current.y); ctx.scale(textHScale, fontDirection); for (i = 0; i < glyphsLength; ++i) { glyph = glyphs[i]; if (isNum(glyph)) { spacingLength = spacingDir * glyph * fontSize / 1000; this.ctx.translate(spacingLength, 0); current.x += spacingLength * textHScale; continue; } var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; var operatorList = font.charProcOperatorList[glyph.operatorListId]; if (!operatorList) { warn('Type3 character \"' + glyph.operatorListId + '\" is not available'); continue; } this.processingType3 = glyph; this.save(); ctx.scale(fontSize, fontSize); ctx.transform.apply(ctx, fontMatrix); this.executeOperatorList(operatorList); this.restore(); var transformed = Util.applyTransform([glyph.width, 0], fontMatrix); width = transformed[0] * fontSize + spacing; ctx.translate(width, 0); current.x += width * textHScale; } ctx.restore(); this.processingType3 = null; }, // Type3 fonts setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) { // We can safely ignore this since the width should be the same // as the width in the Widths array. }, setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) { // TODO According to the spec we're also suppose to ignore any operators // that set color or include images while processing this type3 font. this.ctx.rect(llx, lly, urx - llx, ury - lly); this.clip(); this.endPath(); }, // Color getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) { var pattern; if (IR[0] === 'TilingPattern') { var color = IR[1]; var baseTransform = this.baseTransform || this.ctx.mozCurrentTransform.slice(); var self = this; var canvasGraphicsFactory = { createCanvasGraphics: function (ctx) { return new CanvasGraphics(ctx, self.commonObjs, self.objs); } }; pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform); } else { pattern = getShadingPatternFromIR(IR); } return pattern; }, setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) { this.current.strokeColor = this.getColorN_Pattern(arguments); }, setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) { this.current.fillColor = this.getColorN_Pattern(arguments); this.current.patternFill = true; }, setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.ctx.strokeStyle = color; this.current.strokeColor = color; }, setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.ctx.fillStyle = color; this.current.fillColor = color; this.current.patternFill = false; }, shadingFill: function CanvasGraphics_shadingFill(patternIR) { var ctx = this.ctx; this.save(); var pattern = getShadingPatternFromIR(patternIR); ctx.fillStyle = pattern.getPattern(ctx, this, true); var inv = ctx.mozCurrentTransformInverse; if (inv) { var canvas = ctx.canvas; var width = canvas.width; var height = canvas.height; var bl = Util.applyTransform([0, 0], inv); var br = Util.applyTransform([0, height], inv); var ul = Util.applyTransform([width, 0], inv); var ur = Util.applyTransform([width, height], inv); var x0 = Math.min(bl[0], br[0], ul[0], ur[0]); var y0 = Math.min(bl[1], br[1], ul[1], ur[1]); var x1 = Math.max(bl[0], br[0], ul[0], ur[0]); var y1 = Math.max(bl[1], br[1], ul[1], ur[1]); this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0); } else { // HACK to draw the gradient onto an infinite rectangle. // PDF gradients are drawn across the entire image while // Canvas only allows gradients to be drawn in a rectangle // The following bug should allow us to remove this. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884 this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10); } this.restore(); }, // Images beginInlineImage: function CanvasGraphics_beginInlineImage() { error('Should not call beginInlineImage'); }, beginImageData: function CanvasGraphics_beginImageData() { error('Should not call beginImageData'); }, paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix, bbox) { this.save(); this.baseTransformStack.push(this.baseTransform); if (isArray(matrix) && 6 === matrix.length) { this.transform.apply(this, matrix); } this.baseTransform = this.ctx.mozCurrentTransform; if (isArray(bbox) && 4 === bbox.length) { var width = bbox[2] - bbox[0]; var height = bbox[3] - bbox[1]; this.ctx.rect(bbox[0], bbox[1], width, height); this.clip(); this.endPath(); } }, paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() { this.restore(); this.baseTransform = this.baseTransformStack.pop(); }, beginGroup: function CanvasGraphics_beginGroup(group) { this.save(); var currentCtx = this.ctx; // TODO non-isolated groups - according to Rik at adobe non-isolated // group results aren't usually that different and they even have tools // that ignore this setting. Notes from Rik on implmenting: // - When you encounter an transparency group, create a new canvas with // the dimensions of the bbox // - copy the content from the previous canvas to the new canvas // - draw as usual // - remove the backdrop alpha: // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha // value of your transparency group and 'alphaBackdrop' the alpha of the // backdrop // - remove background color: // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew) if (!group.isolated) { info('TODO: Support non-isolated groups.'); } // TODO knockout - supposedly possible with the clever use of compositing // modes. if (group.knockout) { warn('Knockout groups not supported.'); } var currentTransform = currentCtx.mozCurrentTransform; if (group.matrix) { currentCtx.transform.apply(currentCtx, group.matrix); } assert(group.bbox, 'Bounding box is required.'); // Based on the current transform figure out how big the bounding box // will actually be. var bounds = Util.getAxialAlignedBoundingBox( group.bbox, currentCtx.mozCurrentTransform); // Clip the bounding box to the current canvas. var canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height]; bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0]; // Use ceil in case we're between sizes so we don't create canvas that is // too small and make the canvas at least 1x1 pixels. var offsetX = Math.floor(bounds[0]); var offsetY = Math.floor(bounds[1]); var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1); var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1); var scaleX = 1, scaleY = 1; if (drawnWidth > MAX_GROUP_SIZE) { scaleX = drawnWidth / MAX_GROUP_SIZE; drawnWidth = MAX_GROUP_SIZE; } if (drawnHeight > MAX_GROUP_SIZE) { scaleY = drawnHeight / MAX_GROUP_SIZE; drawnHeight = MAX_GROUP_SIZE; } var cacheId = 'groupAt' + this.groupLevel; if (group.smask) { // Using two cache entries is case if masks are used one after another. cacheId += '_smask_' + ((this.smaskCounter++) % 2); } var scratchCanvas = this.cachedCanvases.getCanvas( cacheId, drawnWidth, drawnHeight, true); var groupCtx = scratchCanvas.context; // Since we created a new canvas that is just the size of the bounding box // we have to translate the group ctx. groupCtx.scale(1 / scaleX, 1 / scaleY); groupCtx.translate(-offsetX, -offsetY); groupCtx.transform.apply(groupCtx, currentTransform); if (group.smask) { // Saving state and cached mask to be used in setGState. this.smaskStack.push({ canvas: scratchCanvas.canvas, context: groupCtx, offsetX: offsetX, offsetY: offsetY, scaleX: scaleX, scaleY: scaleY, subtype: group.smask.subtype, backdrop: group.smask.backdrop, transferMap: group.smask.transferMap || null }); } else { // Setup the current ctx so when the group is popped we draw it at the // right location. currentCtx.setTransform(1, 0, 0, 1, 0, 0); currentCtx.translate(offsetX, offsetY); currentCtx.scale(scaleX, scaleY); } // The transparency group inherits all off the current graphics state // except the blend mode, soft mask, and alpha constants. copyCtxState(currentCtx, groupCtx); this.ctx = groupCtx; this.setGState([ ['BM', 'Normal'], ['ca', 1], ['CA', 1] ]); this.groupStack.push(currentCtx); this.groupLevel++; }, endGroup: function CanvasGraphics_endGroup(group) { this.groupLevel--; var groupCtx = this.ctx; this.ctx = this.groupStack.pop(); // Turn off image smoothing to avoid sub pixel interpolation which can // look kind of blurry for some pdfs. if (this.ctx.imageSmoothingEnabled !== undefined) { this.ctx.imageSmoothingEnabled = false; } else { this.ctx.mozImageSmoothingEnabled = false; } if (group.smask) { this.tempSMask = this.smaskStack.pop(); } else { this.ctx.drawImage(groupCtx.canvas, 0, 0); } this.restore(); }, beginAnnotations: function CanvasGraphics_beginAnnotations() { this.save(); this.current = new CanvasExtraState(); if (this.baseTransform) { this.ctx.setTransform.apply(this.ctx, this.baseTransform); } }, endAnnotations: function CanvasGraphics_endAnnotations() { this.restore(); }, beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform, matrix) { this.save(); if (isArray(rect) && 4 === rect.length) { var width = rect[2] - rect[0]; var height = rect[3] - rect[1]; this.ctx.rect(rect[0], rect[1], width, height); this.clip(); this.endPath(); } this.transform.apply(this, transform); this.transform.apply(this, matrix); }, endAnnotation: function CanvasGraphics_endAnnotation() { this.restore(); }, paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) { var domImage = this.objs.get(objId); if (!domImage) { warn('Dependent image isn\'t ready yet'); return; } this.save(); var ctx = this.ctx; // scale the image to the unit square ctx.scale(1 / w, -1 / h); ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height, 0, -h, w, h); if (this.imageLayer) { var currentTransform = ctx.mozCurrentTransformInverse; var position = this.getCanvasPosition(0, 0); this.imageLayer.appendImage({ objId: objId, left: position[0], top: position[1], width: w / currentTransform[0], height: h / currentTransform[3] }); } this.restore(); }, paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) { var ctx = this.ctx; var width = img.width, height = img.height; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var glyph = this.processingType3; if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) { if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) { glyph.compiled = compileType3Glyph({data: img.data, width: width, height: height}); } else { glyph.compiled = null; } } if (glyph && glyph.compiled) { glyph.compiled(ctx); return; } var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, img); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); this.paintInlineImageXObject(maskCanvas.canvas); }, paintImageMaskXObjectRepeat: function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX, scaleY, positions) { var width = imgData.width; var height = imgData.height; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, imgData); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); var ctx = this.ctx; for (var i = 0, ii = positions.length; i < ii; i += 2) { ctx.save(); ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]); ctx.scale(1, -1); ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); ctx.restore(); } }, paintImageMaskXObjectGroup: function CanvasGraphics_paintImageMaskXObjectGroup(images) { var ctx = this.ctx; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; for (var i = 0, ii = images.length; i < ii; i++) { var image = images[i]; var width = image.width, height = image.height; var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, image); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); ctx.save(); ctx.transform.apply(ctx, image.transform); ctx.scale(1, -1); ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); ctx.restore(); } }, paintImageXObject: function CanvasGraphics_paintImageXObject(objId) { var imgData = this.objs.get(objId); if (!imgData) { warn('Dependent image isn\'t ready yet'); return; } this.paintInlineImageXObject(imgData); }, paintImageXObjectRepeat: function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY, positions) { var imgData = this.objs.get(objId); if (!imgData) { warn('Dependent image isn\'t ready yet'); return; } var width = imgData.width; var height = imgData.height; var map = []; for (var i = 0, ii = positions.length; i < ii; i += 2) { map.push({transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]], x: 0, y: 0, w: width, h: height}); } this.paintInlineImageXObjectGroup(imgData, map); }, paintInlineImageXObject: function CanvasGraphics_paintInlineImageXObject(imgData) { var width = imgData.width; var height = imgData.height; var ctx = this.ctx; this.save(); // scale the image to the unit square ctx.scale(1 / width, -1 / height); var currentTransform = ctx.mozCurrentTransformInverse; var a = currentTransform[0], b = currentTransform[1]; var widthScale = Math.max(Math.sqrt(a * a + b * b), 1); var c = currentTransform[2], d = currentTransform[3]; var heightScale = Math.max(Math.sqrt(c * c + d * d), 1); var imgToPaint, tmpCanvas; // instanceof HTMLElement does not work in jsdom node.js module if (imgData instanceof HTMLElement || !imgData.data) { imgToPaint = imgData; } else { tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', width, height); var tmpCtx = tmpCanvas.context; putBinaryImageData(tmpCtx, imgData); imgToPaint = tmpCanvas.canvas; } var paintWidth = width, paintHeight = height; var tmpCanvasId = 'prescale1'; // Vertial or horizontal scaling shall not be more than 2 to not loose the // pixels during drawImage operation, painting on the temporary canvas(es) // that are twice smaller in size while ((widthScale > 2 && paintWidth > 1) || (heightScale > 2 && paintHeight > 1)) { var newWidth = paintWidth, newHeight = paintHeight; if (widthScale > 2 && paintWidth > 1) { newWidth = Math.ceil(paintWidth / 2); widthScale /= paintWidth / newWidth; } if (heightScale > 2 && paintHeight > 1) { newHeight = Math.ceil(paintHeight / 2); heightScale /= paintHeight / newHeight; } tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight); tmpCtx = tmpCanvas.context; tmpCtx.clearRect(0, 0, newWidth, newHeight); tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight); imgToPaint = tmpCanvas.canvas; paintWidth = newWidth; paintHeight = newHeight; tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1'; } ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, -height, width, height); if (this.imageLayer) { var position = this.getCanvasPosition(0, -height); this.imageLayer.appendImage({ imgData: imgData, left: position[0], top: position[1], width: width / currentTransform[0], height: height / currentTransform[3] }); } this.restore(); }, paintInlineImageXObjectGroup: function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) { var ctx = this.ctx; var w = imgData.width; var h = imgData.height; var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h); var tmpCtx = tmpCanvas.context; putBinaryImageData(tmpCtx, imgData); for (var i = 0, ii = map.length; i < ii; i++) { var entry = map[i]; ctx.save(); ctx.transform.apply(ctx, entry.transform); ctx.scale(1, -1); ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1); if (this.imageLayer) { var position = this.getCanvasPosition(entry.x, entry.y); this.imageLayer.appendImage({ imgData: imgData, left: position[0], top: position[1], width: w, height: h }); } ctx.restore(); } }, paintSolidColorImageMask: function CanvasGraphics_paintSolidColorImageMask() { this.ctx.fillRect(0, 0, 1, 1); }, paintXObject: function CanvasGraphics_paintXObject() { warn('Unsupported \'paintXObject\' command.'); }, // Marked content markPoint: function CanvasGraphics_markPoint(tag) { // TODO Marked content. }, markPointProps: function CanvasGraphics_markPointProps(tag, properties) { // TODO Marked content. }, beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) { // TODO Marked content. }, beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps( tag, properties) { // TODO Marked content. }, endMarkedContent: function CanvasGraphics_endMarkedContent() { // TODO Marked content. }, // Compatibility beginCompat: function CanvasGraphics_beginCompat() { // TODO ignore undefined operators (should we do that anyway?) }, endCompat: function CanvasGraphics_endCompat() { // TODO stop ignoring undefined operators }, // Helper functions consumePath: function CanvasGraphics_consumePath() { var ctx = this.ctx; if (this.pendingClip) { if (this.pendingClip === EO_CLIP) { if (ctx.mozFillRule !== undefined) { ctx.mozFillRule = 'evenodd'; ctx.clip(); ctx.mozFillRule = 'nonzero'; } else { ctx.clip('evenodd'); } } else { ctx.clip(); } this.pendingClip = null; } ctx.beginPath(); }, getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) { if (this.cachedGetSinglePixelWidth === null) { var inverse = this.ctx.mozCurrentTransformInverse; // max of the current horizontal and vertical scale this.cachedGetSinglePixelWidth = Math.sqrt(Math.max( (inverse[0] * inverse[0] + inverse[1] * inverse[1]), (inverse[2] * inverse[2] + inverse[3] * inverse[3]))); } return this.cachedGetSinglePixelWidth; }, getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) { var transform = this.ctx.mozCurrentTransform; return [ transform[0] * x + transform[2] * y + transform[4], transform[1] * x + transform[3] * y + transform[5] ]; } }; for (var op in OPS) { CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op]; } return CanvasGraphics; })(); exports.CanvasGraphics = CanvasGraphics; exports.createScratchCanvas = createScratchCanvas; })); (function (root, factory) { { factory((root.pdfjsDisplayAPI = {}), root.pdfjsSharedUtil, root.pdfjsDisplayFontLoader, root.pdfjsDisplayCanvas, root.pdfjsDisplayMetadata, root.pdfjsSharedGlobal); } }(this, function (exports, sharedUtil, displayFontLoader, displayCanvas, displayMetadata, sharedGlobal, amdRequire) { var InvalidPDFException = sharedUtil.InvalidPDFException; var MessageHandler = sharedUtil.MessageHandler; var MissingPDFException = sharedUtil.MissingPDFException; var PasswordResponses = sharedUtil.PasswordResponses; var PasswordException = sharedUtil.PasswordException; var StatTimer = sharedUtil.StatTimer; var UnexpectedResponseException = sharedUtil.UnexpectedResponseException; var UnknownErrorException = sharedUtil.UnknownErrorException; var Util = sharedUtil.Util; var createPromiseCapability = sharedUtil.createPromiseCapability; var combineUrl = sharedUtil.combineUrl; var error = sharedUtil.error; var deprecated = sharedUtil.deprecated; var info = sharedUtil.info; var isArrayBuffer = sharedUtil.isArrayBuffer; var loadJpegStream = sharedUtil.loadJpegStream; var stringToBytes = sharedUtil.stringToBytes; var warn = sharedUtil.warn; var FontFaceObject = displayFontLoader.FontFaceObject; var FontLoader = displayFontLoader.FontLoader; var CanvasGraphics = displayCanvas.CanvasGraphics; var createScratchCanvas = displayCanvas.createScratchCanvas; var Metadata = displayMetadata.Metadata; var PDFJS = sharedGlobal.PDFJS; var globalScope = sharedGlobal.globalScope; var DEFAULT_RANGE_CHUNK_SIZE = 65536; // 2^16 = 65536 var useRequireEnsure = false; if (typeof module !== 'undefined' && module.require) { // node.js - disable worker and set require.ensure. PDFJS.disableWorker = true; if (typeof require.ensure === 'undefined') { require.ensure = require('node-ensure'); } useRequireEnsure = true; } if (typeof __webpack_require__ !== 'undefined') { // Webpack - get/bundle pdf.worker.js as additional file. PDFJS.workerSrc = require('entry?name=[hash]-worker.js!./pdf.worker.js'); useRequireEnsure = true; } if (typeof requirejs !== 'undefined' && requirejs.toUrl) { PDFJS.workerSrc = requirejs.toUrl('pdfjs-dist/build/pdf.worker.js'); } var fakeWorkerFilesLoader = useRequireEnsure ? (function (callback) { require.ensure([], function () { require('./pdf.worker.js'); callback(); }); }) : (typeof requirejs !== 'undefined') ? (function (callback) { requirejs(['pdfjs-dist/build/pdf.worker'], function (worker) { callback(); }); }) : null; /** * The maximum allowed image size in total pixels e.g. width * height. Images * above this value will not be drawn. Use -1 for no limit. * @var {number} */ PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ? -1 : PDFJS.maxImageSize); /** * The url of where the predefined Adobe CMaps are located. Include trailing * slash. * @var {string} */ PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl); /** * Specifies if CMaps are binary packed. * @var {boolean} */ PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked; /** * By default fonts are converted to OpenType fonts and loaded via font face * rules. If disabled, the font will be rendered using a built in font renderer * that constructs the glyphs with primitive path commands. * @var {boolean} */ PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ? false : PDFJS.disableFontFace); /** * Path for image resources, mainly for annotation icons. Include trailing * slash. * @var {string} */ PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ? '' : PDFJS.imageResourcesPath); /** * Disable the web worker and run all code on the main thread. This will happen * automatically if the browser doesn't support workers or sending typed arrays * to workers. * @var {boolean} */ PDFJS.disableWorker = (PDFJS.disableWorker === undefined ? false : PDFJS.disableWorker); /** * Path and filename of the worker file. Required when the worker is enabled in * development mode. If unspecified in the production build, the worker will be * loaded based on the location of the pdf.js file. It is recommended that * the workerSrc is set in a custom application to prevent issues caused by * third-party frameworks and libraries. * @var {string} */ PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc); /** * Disable range request loading of PDF files. When enabled and if the server * supports partial content requests then the PDF will be fetched in chunks. * Enabled (false) by default. * @var {boolean} */ PDFJS.disableRange = (PDFJS.disableRange === undefined ? false : PDFJS.disableRange); /** * Disable streaming of PDF file data. By default PDF.js attempts to load PDF * in chunks. This default behavior can be disabled. * @var {boolean} */ PDFJS.disableStream = (PDFJS.disableStream === undefined ? false : PDFJS.disableStream); /** * Disable pre-fetching of PDF file data. When range requests are enabled PDF.js * will automatically keep fetching more data even if it isn't needed to display * the current page. This default behavior can be disabled. * * NOTE: It is also necessary to disable streaming, see above, * in order for disabling of pre-fetching to work correctly. * @var {boolean} */ PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ? false : PDFJS.disableAutoFetch); /** * Enables special hooks for debugging PDF.js. * @var {boolean} */ PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug); /** * Enables transfer usage in postMessage for ArrayBuffers. * @var {boolean} */ PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ? true : PDFJS.postMessageTransfers); /** * Disables URL.createObjectURL usage. * @var {boolean} */ PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ? false : PDFJS.disableCreateObjectURL); /** * Disables WebGL usage. * @var {boolean} */ PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ? true : PDFJS.disableWebGL); /** * Disables fullscreen support, and by extension Presentation Mode, * in browsers which support the fullscreen API. * @var {boolean} */ PDFJS.disableFullscreen = (PDFJS.disableFullscreen === undefined ? false : PDFJS.disableFullscreen); /** * Enables CSS only zooming. * @var {boolean} */ PDFJS.useOnlyCssZoom = (PDFJS.useOnlyCssZoom === undefined ? false : PDFJS.useOnlyCssZoom); /** * Controls the logging level. * The constants from PDFJS.VERBOSITY_LEVELS should be used: * - errors * - warnings [default] * - infos * @var {number} */ PDFJS.verbosity = (PDFJS.verbosity === undefined ? PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity); /** * The maximum supported canvas size in total pixels e.g. width * height. * The default value is 4096 * 4096. Use -1 for no limit. * @var {number} */ PDFJS.maxCanvasPixels = (PDFJS.maxCanvasPixels === undefined ? 16777216 : PDFJS.maxCanvasPixels); /** * (Deprecated) Opens external links in a new window if enabled. * The default behavior opens external links in the PDF.js window. * * NOTE: This property has been deprecated, please use * `PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK` instead. * @var {boolean} */ PDFJS.openExternalLinksInNewWindow = ( PDFJS.openExternalLinksInNewWindow === undefined ? false : PDFJS.openExternalLinksInNewWindow); /** * Specifies the |target| attribute for external links. * The constants from PDFJS.LinkTarget should be used: * - NONE [default] * - SELF * - BLANK * - PARENT * - TOP * @var {number} */ PDFJS.externalLinkTarget = (PDFJS.externalLinkTarget === undefined ? PDFJS.LinkTarget.NONE : PDFJS.externalLinkTarget); /** * Specifies the |rel| attribute for external links. Defaults to stripping * the referrer. * @var {string} */ PDFJS.externalLinkRel = (PDFJS.externalLinkRel === undefined ? 'noreferrer' : PDFJS.externalLinkRel); /** * Determines if we can eval strings as JS. Primarily used to improve * performance for font rendering. * @var {boolean} */ PDFJS.isEvalSupported = (PDFJS.isEvalSupported === undefined ? true : PDFJS.isEvalSupported); /** * Document initialization / loading parameters object. * * @typedef {Object} DocumentInitParameters * @property {string} url - The URL of the PDF. * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded, * use atob() to convert it to a binary string first. * @property {Object} httpHeaders - Basic authentication headers. * @property {boolean} withCredentials - Indicates whether or not cross-site * Access-Control requests should be made using credentials such as cookies * or authorization headers. The default is false. * @property {string} password - For decrypting password-protected PDFs. * @property {TypedArray} initialData - A typed array with the first portion or * all of the pdf data. Used by the extension since some data is already * loaded before the switch to range requests. * @property {number} length - The PDF file length. It's used for progress * reports and range requests operations. * @property {PDFDataRangeTransport} range * @property {number} rangeChunkSize - Optional parameter to specify * maximum number of bytes fetched per range request. The default value is * 2^16 = 65536. * @property {PDFWorker} worker - The worker that will be used for the loading * and parsing of the PDF data. */ /** * @typedef {Object} PDFDocumentStats * @property {Array} streamTypes - Used stream types in the document (an item * is set to true if specific stream ID was used in the document). * @property {Array} fontTypes - Used font type in the document (an item is set * to true if specific font ID was used in the document). */ /** * This is the main entry point for loading a PDF and interacting with it. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR) * is used, which means it must follow the same origin rules that any XHR does * e.g. No cross domain requests without CORS. * * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src * Can be a url to where a PDF is located, a typed array (Uint8Array) * already populated with data or parameter object. * * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used * if you want to manually serve range requests for data in the PDF. * * @param {function} passwordCallback (deprecated) It is used to request a * password if wrong or no password was provided. The callback receives two * parameters: function that needs to be called with new password and reason * (see {PasswordResponses}). * * @param {function} progressCallback (deprecated) It is used to be able to * monitor the loading progress of the PDF file (necessary to implement e.g. * a loading bar). The callback receives an {Object} with the properties: * {number} loaded and {number} total. * * @return {PDFDocumentLoadingTask} */ PDFJS.getDocument = function getDocument(src, pdfDataRangeTransport, passwordCallback, progressCallback) { var task = new PDFDocumentLoadingTask(); // Support of the obsolete arguments (for compatibility with API v1.0) if (arguments.length > 1) { deprecated('getDocument is called with pdfDataRangeTransport, ' + 'passwordCallback or progressCallback argument'); } if (pdfDataRangeTransport) { if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) { // Not a PDFDataRangeTransport instance, trying to add missing properties. pdfDataRangeTransport = Object.create(pdfDataRangeTransport); pdfDataRangeTransport.length = src.length; pdfDataRangeTransport.initialData = src.initialData; if (!pdfDataRangeTransport.abort) { pdfDataRangeTransport.abort = function () {}; } } src = Object.create(src); src.range = pdfDataRangeTransport; } task.onPassword = passwordCallback || null; task.onProgress = progressCallback || null; var source; if (typeof src === 'string') { source = { url: src }; } else if (isArrayBuffer(src)) { source = { data: src }; } else if (src instanceof PDFDataRangeTransport) { source = { range: src }; } else { if (typeof src !== 'object') { error('Invalid parameter in getDocument, need either Uint8Array, ' + 'string or a parameter object'); } if (!src.url && !src.data && !src.range) { error('Invalid parameter object: need either .data, .range or .url'); } source = src; } var params = {}; var rangeTransport = null; var worker = null; for (var key in source) { if (key === 'url' && typeof window !== 'undefined') { // The full path is required in the 'url' field. params[key] = combineUrl(window.location.href, source[key]); continue; } else if (key === 'range') { rangeTransport = source[key]; continue; } else if (key === 'worker') { worker = source[key]; continue; } else if (key === 'data' && !(source[key] instanceof Uint8Array)) { // Converting string or array-like data to Uint8Array. var pdfBytes = source[key]; if (typeof pdfBytes === 'string') { params[key] = stringToBytes(pdfBytes); } else if (typeof pdfBytes === 'object' && pdfBytes !== null && !isNaN(pdfBytes.length)) { params[key] = new Uint8Array(pdfBytes); } else if (isArrayBuffer(pdfBytes)) { params[key] = new Uint8Array(pdfBytes); } else { error('Invalid PDF binary data: either typed array, string or ' + 'array-like object is expected in the data property.'); } continue; } params[key] = source[key]; } params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE; if (!worker) { // Worker was not provided -- creating and owning our own. worker = new PDFWorker(); task._worker = worker; } var docId = task.docId; worker.promise.then(function () { if (task.destroyed) { throw new Error('Loading aborted'); } return _fetchDocument(worker, params, rangeTransport, docId).then( function (workerId) { if (task.destroyed) { throw new Error('Loading aborted'); } var messageHandler = new MessageHandler(docId, workerId, worker.port); messageHandler.send('Ready', null); var transport = new WorkerTransport(messageHandler, task, rangeTransport); task._transport = transport; }); }).catch(task._capability.reject); return task; }; /** * Starts fetching of specified PDF document/data. * @param {PDFWorker} worker * @param {Object} source * @param {PDFDataRangeTransport} pdfDataRangeTransport * @param {string} docId Unique document id, used as MessageHandler id. * @returns {Promise} The promise, which is resolved when worker id of * MessageHandler is known. * @private */ function _fetchDocument(worker, source, pdfDataRangeTransport, docId) { if (worker.destroyed) { return Promise.reject(new Error('Worker was destroyed')); } source.disableAutoFetch = PDFJS.disableAutoFetch; source.disableStream = PDFJS.disableStream; source.chunkedViewerLoading = !!pdfDataRangeTransport; if (pdfDataRangeTransport) { source.length = pdfDataRangeTransport.length; source.initialData = pdfDataRangeTransport.initialData; } return worker.messageHandler.sendWithPromise('GetDocRequest', { docId: docId, source: source, disableRange: PDFJS.disableRange, maxImageSize: PDFJS.maxImageSize, cMapUrl: PDFJS.cMapUrl, cMapPacked: PDFJS.cMapPacked, disableFontFace: PDFJS.disableFontFace, disableCreateObjectURL: PDFJS.disableCreateObjectURL, verbosity: PDFJS.verbosity }).then(function (workerId) { if (worker.destroyed) { throw new Error('Worker was destroyed'); } return workerId; }); } /** * PDF document loading operation. * @class * @alias PDFDocumentLoadingTask */ var PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() { var nextDocumentId = 0; /** @constructs PDFDocumentLoadingTask */ function PDFDocumentLoadingTask() { this._capability = createPromiseCapability(); this._transport = null; this._worker = null; /** * Unique document loading task id -- used in MessageHandlers. * @type {string} */ this.docId = 'd' + (nextDocumentId++); /** * Shows if loading task is destroyed. * @type {boolean} */ this.destroyed = false; /** * Callback to request a password if wrong or no password was provided. * The callback receives two parameters: function that needs to be called * with new password and reason (see {PasswordResponses}). */ this.onPassword = null; /** * Callback to be able to monitor the loading progress of the PDF file * (necessary to implement e.g. a loading bar). The callback receives * an {Object} with the properties: {number} loaded and {number} total. */ this.onProgress = null; /** * Callback to when unsupported feature is used. The callback receives * an {PDFJS.UNSUPPORTED_FEATURES} argument. */ this.onUnsupportedFeature = null; } PDFDocumentLoadingTask.prototype = /** @lends PDFDocumentLoadingTask.prototype */ { /** * @return {Promise} */ get promise() { return this._capability.promise; }, /** * Aborts all network requests and destroys worker. * @return {Promise} A promise that is resolved after destruction activity * is completed. */ destroy: function () { this.destroyed = true; var transportDestroyed = !this._transport ? Promise.resolve() : this._transport.destroy(); return transportDestroyed.then(function () { this._transport = null; if (this._worker) { this._worker.destroy(); this._worker = null; } }.bind(this)); }, /** * Registers callbacks to indicate the document loading completion. * * @param {function} onFulfilled The callback for the loading completion. * @param {function} onRejected The callback for the loading failure. * @return {Promise} A promise that is resolved after the onFulfilled or * onRejected callback. */ then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) { return this.promise.then.apply(this.promise, arguments); } }; return PDFDocumentLoadingTask; })(); /** * Abstract class to support range requests file loading. * @class * @alias PDFJS.PDFDataRangeTransport * @param {number} length * @param {Uint8Array} initialData */ var PDFDataRangeTransport = (function pdfDataRangeTransportClosure() { function PDFDataRangeTransport(length, initialData) { this.length = length; this.initialData = initialData; this._rangeListeners = []; this._progressListeners = []; this._progressiveReadListeners = []; this._readyCapability = createPromiseCapability(); } PDFDataRangeTransport.prototype = /** @lends PDFDataRangeTransport.prototype */ { addRangeListener: function PDFDataRangeTransport_addRangeListener(listener) { this._rangeListeners.push(listener); }, addProgressListener: function PDFDataRangeTransport_addProgressListener(listener) { this._progressListeners.push(listener); }, addProgressiveReadListener: function PDFDataRangeTransport_addProgressiveReadListener(listener) { this._progressiveReadListeners.push(listener); }, onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) { var listeners = this._rangeListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](begin, chunk); } }, onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) { this._readyCapability.promise.then(function () { var listeners = this._progressListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](loaded); } }.bind(this)); }, onDataProgressiveRead: function PDFDataRangeTransport_onDataProgress(chunk) { this._readyCapability.promise.then(function () { var listeners = this._progressiveReadListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](chunk); } }.bind(this)); }, transportReady: function PDFDataRangeTransport_transportReady() { this._readyCapability.resolve(); }, requestDataRange: function PDFDataRangeTransport_requestDataRange(begin, end) { throw new Error('Abstract method PDFDataRangeTransport.requestDataRange'); }, abort: function PDFDataRangeTransport_abort() { } }; return PDFDataRangeTransport; })(); PDFJS.PDFDataRangeTransport = PDFDataRangeTransport; /** * Proxy to a PDFDocument in the worker thread. Also, contains commonly used * properties that can be read synchronously. * @class * @alias PDFDocumentProxy */ var PDFDocumentProxy = (function PDFDocumentProxyClosure() { function PDFDocumentProxy(pdfInfo, transport, loadingTask) { this.pdfInfo = pdfInfo; this.transport = transport; this.loadingTask = loadingTask; } PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ { /** * @return {number} Total number of pages the PDF contains. */ get numPages() { return this.pdfInfo.numPages; }, /** * @return {string} A unique ID to identify a PDF. Not guaranteed to be * unique. */ get fingerprint() { return this.pdfInfo.fingerprint; }, /** * @param {number} pageNumber The page number to get. The first page is 1. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy} * object. */ getPage: function PDFDocumentProxy_getPage(pageNumber) { return this.transport.getPage(pageNumber); }, /** * @param {{num: number, gen: number}} ref The page reference. Must have * the 'num' and 'gen' properties. * @return {Promise} A promise that is resolved with the page index that is * associated with the reference. */ getPageIndex: function PDFDocumentProxy_getPageIndex(ref) { return this.transport.getPageIndex(ref); }, /** * @return {Promise} A promise that is resolved with a lookup table for * mapping named destinations to reference numbers. * * This can be slow for large documents: use getDestination instead */ getDestinations: function PDFDocumentProxy_getDestinations() { return this.transport.getDestinations(); }, /** * @param {string} id The named destination to get. * @return {Promise} A promise that is resolved with all information * of the given named destination. */ getDestination: function PDFDocumentProxy_getDestination(id) { return this.transport.getDestination(id); }, /** * @return {Promise} A promise that is resolved with a lookup table for * mapping named attachments to their content. */ getAttachments: function PDFDocumentProxy_getAttachments() { return this.transport.getAttachments(); }, /** * @return {Promise} A promise that is resolved with an array of all the * JavaScript strings in the name tree. */ getJavaScript: function PDFDocumentProxy_getJavaScript() { return this.transport.getJavaScript(); }, /** * @return {Promise} A promise that is resolved with an {Array} that is a * tree outline (if it has one) of the PDF. The tree is in the format of: * [ * { * title: string, * bold: boolean, * italic: boolean, * color: rgb array, * dest: dest obj, * items: array of more items like this * }, * ... * ]. */ getOutline: function PDFDocumentProxy_getOutline() { return this.transport.getOutline(); }, /** * @return {Promise} A promise that is resolved with an {Object} that has * info and metadata properties. Info is an {Object} filled with anything * available in the information dictionary and similarly metadata is a * {Metadata} object with information from the metadata section of the PDF. */ getMetadata: function PDFDocumentProxy_getMetadata() { return this.transport.getMetadata(); }, /** * @return {Promise} A promise that is resolved with a TypedArray that has * the raw data from the PDF. */ getData: function PDFDocumentProxy_getData() { return this.transport.getData(); }, /** * @return {Promise} A promise that is resolved when the document's data * is loaded. It is resolved with an {Object} that contains the length * property that indicates size of the PDF data in bytes. */ getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() { return this.transport.downloadInfoCapability.promise; }, /** * @return {Promise} A promise this is resolved with current stats about * document structures (see {@link PDFDocumentStats}). */ getStats: function PDFDocumentProxy_getStats() { return this.transport.getStats(); }, /** * Cleans up resources allocated by the document, e.g. created @font-face. */ cleanup: function PDFDocumentProxy_cleanup() { this.transport.startCleanup(); }, /** * Destroys current document instance and terminates worker. */ destroy: function PDFDocumentProxy_destroy() { return this.loadingTask.destroy(); } }; return PDFDocumentProxy; })(); /** * Page getTextContent parameters. * * @typedef {Object} getTextContentParameters * @param {boolean} normalizeWhitespace - replaces all occurrences of * whitespace with standard spaces (0x20). The default value is `false`. */ /** * Page text content. * * @typedef {Object} TextContent * @property {array} items - array of {@link TextItem} * @property {Object} styles - {@link TextStyles} objects, indexed by font * name. */ /** * Page text content part. * * @typedef {Object} TextItem * @property {string} str - text content. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'. * @property {array} transform - transformation matrix. * @property {number} width - width in device space. * @property {number} height - height in device space. * @property {string} fontName - font name used by pdf.js for converted font. */ /** * Text style. * * @typedef {Object} TextStyle * @property {number} ascent - font ascent. * @property {number} descent - font descent. * @property {boolean} vertical - text is in vertical mode. * @property {string} fontFamily - possible font family */ /** * Page annotation parameters. * * @typedef {Object} GetAnnotationsParameters * @param {string} intent - Determines the annotations that will be fetched, * can be either 'display' (viewable annotations) or 'print' * (printable annotations). * If the parameter is omitted, all annotations are fetched. */ /** * Page render parameters. * * @typedef {Object} RenderParameters * @property {Object} canvasContext - A 2D context of a DOM Canvas object. * @property {PDFJS.PageViewport} viewport - Rendering viewport obtained by * calling of PDFPage.getViewport method. * @property {string} intent - Rendering intent, can be 'display' or 'print' * (default value is 'display'). * @property {Array} transform - (optional) Additional transform, applied * just before viewport transform. * @property {Object} imageLayer - (optional) An object that has beginLayout, * endLayout and appendImage functions. * @property {function} continueCallback - (deprecated) A function that will be * called each time the rendering is paused. To continue * rendering call the function that is the first argument * to the callback. */ /** * PDF page operator list. * * @typedef {Object} PDFOperatorList * @property {Array} fnArray - Array containing the operator functions. * @property {Array} argsArray - Array containing the arguments of the * functions. */ /** * Proxy to a PDFPage in the worker thread. * @class * @alias PDFPageProxy */ var PDFPageProxy = (function PDFPageProxyClosure() { function PDFPageProxy(pageIndex, pageInfo, transport) { this.pageIndex = pageIndex; this.pageInfo = pageInfo; this.transport = transport; this.stats = new StatTimer(); this.stats.enabled = !!globalScope.PDFJS.enableStats; this.commonObjs = transport.commonObjs; this.objs = new PDFObjects(); this.cleanupAfterRender = false; this.pendingCleanup = false; this.intentStates = {}; this.destroyed = false; } PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ { /** * @return {number} Page number of the page. First page is 1. */ get pageNumber() { return this.pageIndex + 1; }, /** * @return {number} The number of degrees the page is rotated clockwise. */ get rotate() { return this.pageInfo.rotate; }, /** * @return {Object} The reference that points to this page. It has 'num' and * 'gen' properties. */ get ref() { return this.pageInfo.ref; }, /** * @return {Array} An array of the visible portion of the PDF page in the * user space units - [x1, y1, x2, y2]. */ get view() { return this.pageInfo.view; }, /** * @param {number} scale The desired scale of the viewport. * @param {number} rotate Degrees to rotate the viewport. If omitted this * defaults to the page rotation. * @return {PDFJS.PageViewport} Contains 'width' and 'height' properties * along with transforms required for rendering. */ getViewport: function PDFPageProxy_getViewport(scale, rotate) { if (arguments.length < 2) { rotate = this.rotate; } return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0); }, /** * @param {GetAnnotationsParameters} params - Annotation parameters. * @return {Promise} A promise that is resolved with an {Array} of the * annotation objects. */ getAnnotations: function PDFPageProxy_getAnnotations(params) { var intent = (params && params.intent) || null; if (!this.annotationsPromise || this.annotationsIntent !== intent) { this.annotationsPromise = this.transport.getAnnotations(this.pageIndex, intent); this.annotationsIntent = intent; } return this.annotationsPromise; }, /** * Begins the process of rendering a page to the desired context. * @param {RenderParameters} params Page render parameters. * @return {RenderTask} An object that contains the promise, which * is resolved when the page finishes rendering. */ render: function PDFPageProxy_render(params) { var stats = this.stats; stats.time('Overall'); // If there was a pending destroy cancel it so no cleanup happens during // this call to render. this.pendingCleanup = false; var renderingIntent = (params.intent === 'print' ? 'print' : 'display'); if (!this.intentStates[renderingIntent]) { this.intentStates[renderingIntent] = {}; } var intentState = this.intentStates[renderingIntent]; // If there's no displayReadyCapability yet, then the operatorList // was never requested before. Make the request and create the promise. if (!intentState.displayReadyCapability) { intentState.receivingOperatorList = true; intentState.displayReadyCapability = createPromiseCapability(); intentState.operatorList = { fnArray: [], argsArray: [], lastChunk: false }; this.stats.time('Page Request'); this.transport.messageHandler.send('RenderPageRequest', { pageIndex: this.pageNumber - 1, intent: renderingIntent }); } var internalRenderTask = new InternalRenderTask(complete, params, this.objs, this.commonObjs, intentState.operatorList, this.pageNumber); internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print'; if (!intentState.renderTasks) { intentState.renderTasks = []; } intentState.renderTasks.push(internalRenderTask); var renderTask = internalRenderTask.task; // Obsolete parameter support if (params.continueCallback) { deprecated('render is used with continueCallback parameter'); renderTask.onContinue = params.continueCallback; } var self = this; intentState.displayReadyCapability.promise.then( function pageDisplayReadyPromise(transparency) { if (self.pendingCleanup) { complete(); return; } stats.time('Rendering'); internalRenderTask.initalizeGraphics(transparency); internalRenderTask.operatorListChanged(); }, function pageDisplayReadPromiseError(reason) { complete(reason); } ); function complete(error) { var i = intentState.renderTasks.indexOf(internalRenderTask); if (i >= 0) { intentState.renderTasks.splice(i, 1); } if (self.cleanupAfterRender) { self.pendingCleanup = true; } self._tryCleanup(); if (error) { internalRenderTask.capability.reject(error); } else { internalRenderTask.capability.resolve(); } stats.timeEnd('Rendering'); stats.timeEnd('Overall'); } return renderTask; }, /** * @return {Promise} A promise resolved with an {@link PDFOperatorList} * object that represents page's operator list. */ getOperatorList: function PDFPageProxy_getOperatorList() { function operatorListChanged() { if (intentState.operatorList.lastChunk) { intentState.opListReadCapability.resolve(intentState.operatorList); } } var renderingIntent = 'oplist'; if (!this.intentStates[renderingIntent]) { this.intentStates[renderingIntent] = {}; } var intentState = this.intentStates[renderingIntent]; if (!intentState.opListReadCapability) { var opListTask = {}; opListTask.operatorListChanged = operatorListChanged; intentState.receivingOperatorList = true; intentState.opListReadCapability = createPromiseCapability(); intentState.renderTasks = []; intentState.renderTasks.push(opListTask); intentState.operatorList = { fnArray: [], argsArray: [], lastChunk: false }; this.transport.messageHandler.send('RenderPageRequest', { pageIndex: this.pageIndex, intent: renderingIntent }); } return intentState.opListReadCapability.promise; }, /** * @param {getTextContentParameters} params - getTextContent parameters. * @return {Promise} That is resolved a {@link TextContent} * object that represent the page text content. */ getTextContent: function PDFPageProxy_getTextContent(params) { var normalizeWhitespace = (params && params.normalizeWhitespace) || false; return this.transport.messageHandler.sendWithPromise('GetTextContent', { pageIndex: this.pageNumber - 1, normalizeWhitespace: normalizeWhitespace, }); }, /** * Destroys page object. */ _destroy: function PDFPageProxy_destroy() { this.destroyed = true; this.transport.pageCache[this.pageIndex] = null; var waitOn = []; Object.keys(this.intentStates).forEach(function(intent) { var intentState = this.intentStates[intent]; intentState.renderTasks.forEach(function(renderTask) { var renderCompleted = renderTask.capability.promise. catch(function () {}); // ignoring failures waitOn.push(renderCompleted); renderTask.cancel(); }); }, this); this.objs.clear(); this.annotationsPromise = null; this.pendingCleanup = false; return Promise.all(waitOn); }, /** * Cleans up resources allocated by the page. (deprecated) */ destroy: function() { deprecated('page destroy method, use cleanup() instead'); this.cleanup(); }, /** * Cleans up resources allocated by the page. */ cleanup: function PDFPageProxy_cleanup() { this.pendingCleanup = true; this._tryCleanup(); }, /** * For internal use only. Attempts to clean up if rendering is in a state * where that's possible. * @ignore */ _tryCleanup: function PDFPageProxy_tryCleanup() { if (!this.pendingCleanup || Object.keys(this.intentStates).some(function(intent) { var intentState = this.intentStates[intent]; return (intentState.renderTasks.length !== 0 || intentState.receivingOperatorList); }, this)) { return; } Object.keys(this.intentStates).forEach(function(intent) { delete this.intentStates[intent]; }, this); this.objs.clear(); this.annotationsPromise = null; this.pendingCleanup = false; }, /** * For internal use only. * @ignore */ _startRenderPage: function PDFPageProxy_startRenderPage(transparency, intent) { var intentState = this.intentStates[intent]; // TODO Refactor RenderPageRequest to separate rendering // and operator list logic if (intentState.displayReadyCapability) { intentState.displayReadyCapability.resolve(transparency); } }, /** * For internal use only. * @ignore */ _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk, intent) { var intentState = this.intentStates[intent]; var i, ii; // Add the new chunk to the current operator list. for (i = 0, ii = operatorListChunk.length; i < ii; i++) { intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]); intentState.operatorList.argsArray.push( operatorListChunk.argsArray[i]); } intentState.operatorList.lastChunk = operatorListChunk.lastChunk; // Notify all the rendering tasks there are more operators to be consumed. for (i = 0; i < intentState.renderTasks.length; i++) { intentState.renderTasks[i].operatorListChanged(); } if (operatorListChunk.lastChunk) { intentState.receivingOperatorList = false; this._tryCleanup(); } } }; return PDFPageProxy; })(); /** * PDF.js web worker abstraction, it controls instantiation of PDF documents and * WorkerTransport for them. If creation of a web worker is not possible, * a "fake" worker will be used instead. * @class */ var PDFWorker = (function PDFWorkerClosure() { var nextFakeWorkerId = 0; function getWorkerSrc() { if (PDFJS.workerSrc) { return PDFJS.workerSrc; } if (pdfjsFilePath) { return pdfjsFilePath.replace(/\.js$/i, '.worker.js'); } error('No PDFJS.workerSrc specified'); } // Loads worker code into main thread. function setupFakeWorkerGlobal() { if (!PDFJS.fakeWorkerFilesLoadedCapability) { PDFJS.fakeWorkerFilesLoadedCapability = createPromiseCapability(); // In the developer build load worker_loader which in turn loads all the // other files and resolves the promise. In production only the // pdf.worker.js file is needed. var loader = fakeWorkerFilesLoader || function (callback) { Util.loadScript(getWorkerSrc(), callback); }; loader(function () { PDFJS.fakeWorkerFilesLoadedCapability.resolve(); }); } return PDFJS.fakeWorkerFilesLoadedCapability.promise; } function PDFWorker(name) { this.name = name; this.destroyed = false; this._readyCapability = createPromiseCapability(); this._port = null; this._webWorker = null; this._messageHandler = null; this._initialize(); } PDFWorker.prototype = /** @lends PDFWorker.prototype */ { get promise() { return this._readyCapability.promise; }, get port() { return this._port; }, get messageHandler() { return this._messageHandler; }, _initialize: function PDFWorker_initialize() { // If worker support isn't disabled explicit and the browser has worker // support, create a new web worker and test if it/the browser fullfills // all requirements to run parts of pdf.js in a web worker. // Right now, the requirement is, that an Uint8Array is still an // Uint8Array as it arrives on the worker. (Chrome added this with v.15.) if (!globalScope.PDFJS.disableWorker && typeof Worker !== 'undefined') { var workerSrc = getWorkerSrc(); try { // Some versions of FF can't create a worker on localhost, see: // https://bugzilla.mozilla.org/show_bug.cgi?id=683280 var worker = new Worker(workerSrc); var messageHandler = new MessageHandler('main', 'worker', worker); messageHandler.on('test', function PDFWorker_test(data) { if (this.destroyed) { this._readyCapability.reject(new Error('Worker was destroyed')); messageHandler.destroy(); worker.terminate(); return; // worker was destroyed } var supportTypedArray = data && data.supportTypedArray; if (supportTypedArray) { this._messageHandler = messageHandler; this._port = worker; this._webWorker = worker; if (!data.supportTransfers) { PDFJS.postMessageTransfers = false; } this._readyCapability.resolve(); } else { this._setupFakeWorker(); messageHandler.destroy(); worker.terminate(); } }.bind(this)); messageHandler.on('console_log', function (data) { console.log.apply(console, data); }); messageHandler.on('console_error', function (data) { console.error.apply(console, data); }); messageHandler.on('ready', function (data) { if (this.destroyed) { this._readyCapability.reject(new Error('Worker was destroyed')); messageHandler.destroy(); worker.terminate(); return; // worker was destroyed } try { sendTest(); } catch (e) { // We need fallback to a faked worker. this._setupFakeWorker(); } }.bind(this)); var sendTest = function () { var testObj = new Uint8Array( [PDFJS.postMessageTransfers ? 255 : 0]); // Some versions of Opera throw a DATA_CLONE_ERR on serializing the // typed array. Also, checking if we can use transfers. try { messageHandler.send('test', testObj, [testObj.buffer]); } catch (ex) { info('Cannot use postMessage transfers'); testObj[0] = 0; messageHandler.send('test', testObj); } }; // It might take time for worker to initialize (especially when AMD // loader is used). We will try to send test immediately, and then // when 'ready' message will arrive. The worker shall process only // first received 'test'. sendTest(); return; } catch (e) { info('The worker has been disabled.'); } } // Either workers are disabled, not supported or have thrown an exception. // Thus, we fallback to a faked worker. this._setupFakeWorker(); }, _setupFakeWorker: function PDFWorker_setupFakeWorker() { if (!globalScope.PDFJS.disableWorker) { warn('Setting up fake worker.'); globalScope.PDFJS.disableWorker = true; } setupFakeWorkerGlobal().then(function () { if (this.destroyed) { this._readyCapability.reject(new Error('Worker was destroyed')); return; } // If we don't use a worker, just post/sendMessage to the main thread. var port = { _listeners: [], postMessage: function (obj) { var e = {data: obj}; this._listeners.forEach(function (listener) { listener.call(this, e); }, this); }, addEventListener: function (name, listener) { this._listeners.push(listener); }, removeEventListener: function (name, listener) { var i = this._listeners.indexOf(listener); this._listeners.splice(i, 1); }, terminate: function () {} }; this._port = port; // All fake workers use the same port, making id unique. var id = 'fake' + (nextFakeWorkerId++); // If the main thread is our worker, setup the handling for the // messages -- the main thread sends to it self. var workerHandler = new MessageHandler(id + '_worker', id, port); PDFJS.WorkerMessageHandler.setup(workerHandler, port); var messageHandler = new MessageHandler(id, id + '_worker', port); this._messageHandler = messageHandler; this._readyCapability.resolve(); }.bind(this)); }, /** * Destroys the worker instance. */ destroy: function PDFWorker_destroy() { this.destroyed = true; if (this._webWorker) { // We need to terminate only web worker created resource. this._webWorker.terminate(); this._webWorker = null; } this._port = null; if (this._messageHandler) { this._messageHandler.destroy(); this._messageHandler = null; } } }; return PDFWorker; })(); PDFJS.PDFWorker = PDFWorker; /** * For internal use only. * @ignore */ var WorkerTransport = (function WorkerTransportClosure() { function WorkerTransport(messageHandler, loadingTask, pdfDataRangeTransport) { this.messageHandler = messageHandler; this.loadingTask = loadingTask; this.pdfDataRangeTransport = pdfDataRangeTransport; this.commonObjs = new PDFObjects(); this.fontLoader = new FontLoader(loadingTask.docId); this.destroyed = false; this.destroyCapability = null; this.pageCache = []; this.pagePromises = []; this.downloadInfoCapability = createPromiseCapability(); this.setupMessageHandler(); } WorkerTransport.prototype = { destroy: function WorkerTransport_destroy() { if (this.destroyCapability) { return this.destroyCapability.promise; } this.destroyed = true; this.destroyCapability = createPromiseCapability(); var waitOn = []; // We need to wait for all renderings to be completed, e.g. // timeout/rAF can take a long time. this.pageCache.forEach(function (page) { if (page) { waitOn.push(page._destroy()); } }); this.pageCache = []; this.pagePromises = []; var self = this; // We also need to wait for the worker to finish its long running tasks. var terminated = this.messageHandler.sendWithPromise('Terminate', null); waitOn.push(terminated); Promise.all(waitOn).then(function () { self.fontLoader.clear(); if (self.pdfDataRangeTransport) { self.pdfDataRangeTransport.abort(); self.pdfDataRangeTransport = null; } if (self.messageHandler) { self.messageHandler.destroy(); self.messageHandler = null; } self.destroyCapability.resolve(); }, this.destroyCapability.reject); return this.destroyCapability.promise; }, setupMessageHandler: function WorkerTransport_setupMessageHandler() { var messageHandler = this.messageHandler; function updatePassword(password) { messageHandler.send('UpdatePassword', password); } var pdfDataRangeTransport = this.pdfDataRangeTransport; if (pdfDataRangeTransport) { pdfDataRangeTransport.addRangeListener(function(begin, chunk) { messageHandler.send('OnDataRange', { begin: begin, chunk: chunk }); }); pdfDataRangeTransport.addProgressListener(function(loaded) { messageHandler.send('OnDataProgress', { loaded: loaded }); }); pdfDataRangeTransport.addProgressiveReadListener(function(chunk) { messageHandler.send('OnDataRange', { chunk: chunk }); }); messageHandler.on('RequestDataRange', function transportDataRange(data) { pdfDataRangeTransport.requestDataRange(data.begin, data.end); }, this); } messageHandler.on('GetDoc', function transportDoc(data) { var pdfInfo = data.pdfInfo; this.numPages = data.pdfInfo.numPages; var loadingTask = this.loadingTask; var pdfDocument = new PDFDocumentProxy(pdfInfo, this, loadingTask); this.pdfDocument = pdfDocument; loadingTask._capability.resolve(pdfDocument); }, this); messageHandler.on('NeedPassword', function transportNeedPassword(exception) { var loadingTask = this.loadingTask; if (loadingTask.onPassword) { return loadingTask.onPassword(updatePassword, PasswordResponses.NEED_PASSWORD); } loadingTask._capability.reject( new PasswordException(exception.message, exception.code)); }, this); messageHandler.on('IncorrectPassword', function transportIncorrectPassword(exception) { var loadingTask = this.loadingTask; if (loadingTask.onPassword) { return loadingTask.onPassword(updatePassword, PasswordResponses.INCORRECT_PASSWORD); } loadingTask._capability.reject( new PasswordException(exception.message, exception.code)); }, this); messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) { this.loadingTask._capability.reject( new InvalidPDFException(exception.message)); }, this); messageHandler.on('MissingPDF', function transportMissingPDF(exception) { this.loadingTask._capability.reject( new MissingPDFException(exception.message)); }, this); messageHandler.on('UnexpectedResponse', function transportUnexpectedResponse(exception) { this.loadingTask._capability.reject( new UnexpectedResponseException(exception.message, exception.status)); }, this); messageHandler.on('UnknownError', function transportUnknownError(exception) { this.loadingTask._capability.reject( new UnknownErrorException(exception.message, exception.details)); }, this); messageHandler.on('DataLoaded', function transportPage(data) { this.downloadInfoCapability.resolve(data); }, this); messageHandler.on('PDFManagerReady', function transportPage(data) { if (this.pdfDataRangeTransport) { this.pdfDataRangeTransport.transportReady(); } }, this); messageHandler.on('StartRenderPage', function transportRender(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var page = this.pageCache[data.pageIndex]; page.stats.timeEnd('Page Request'); page._startRenderPage(data.transparency, data.intent); }, this); messageHandler.on('RenderPageChunk', function transportRender(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var page = this.pageCache[data.pageIndex]; page._renderPageChunk(data.operatorList, data.intent); }, this); messageHandler.on('commonobj', function transportObj(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var id = data[0]; var type = data[1]; if (this.commonObjs.hasData(id)) { return; } switch (type) { case 'Font': var exportedData = data[2]; var font; if ('error' in exportedData) { var error = exportedData.error; warn('Error during font loading: ' + error); this.commonObjs.resolve(id, error); break; } else { font = new FontFaceObject(exportedData); } this.fontLoader.bind( [font], function fontReady(fontObjs) { this.commonObjs.resolve(id, font); }.bind(this) ); break; case 'FontPath': this.commonObjs.resolve(id, data[2]); break; default: error('Got unknown common object type ' + type); } }, this); messageHandler.on('obj', function transportObj(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var id = data[0]; var pageIndex = data[1]; var type = data[2]; var pageProxy = this.pageCache[pageIndex]; var imageData; if (pageProxy.objs.hasData(id)) { return; } switch (type) { case 'JpegStream': imageData = data[3]; loadJpegStream(id, imageData, pageProxy.objs); break; case 'Image': imageData = data[3]; pageProxy.objs.resolve(id, imageData); // heuristics that will allow not to store large data var MAX_IMAGE_SIZE_TO_STORE = 8000000; if (imageData && 'data' in imageData && imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) { pageProxy.cleanupAfterRender = true; } break; default: error('Got unknown object type ' + type); } }, this); messageHandler.on('DocProgress', function transportDocProgress(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var loadingTask = this.loadingTask; if (loadingTask.onProgress) { loadingTask.onProgress({ loaded: data.loaded, total: data.total }); } }, this); messageHandler.on('PageError', function transportError(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var page = this.pageCache[data.pageNum - 1]; var intentState = page.intentStates[data.intent]; if (intentState.displayReadyCapability) { intentState.displayReadyCapability.reject(data.error); } else { error(data.error); } }, this); messageHandler.on('UnsupportedFeature', function transportUnsupportedFeature(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var featureId = data.featureId; var loadingTask = this.loadingTask; if (loadingTask.onUnsupportedFeature) { loadingTask.onUnsupportedFeature(featureId); } PDFJS.UnsupportedManager.notify(featureId); }, this); messageHandler.on('JpegDecode', function(data) { if (this.destroyed) { return Promise.reject('Worker was terminated'); } var imageUrl = data[0]; var components = data[1]; if (components !== 3 && components !== 1) { return Promise.reject( new Error('Only 3 components or 1 component can be returned')); } return new Promise(function (resolve, reject) { var img = new Image(); img.onload = function () { var width = img.width; var height = img.height; var size = width * height; var rgbaLength = size * 4; var buf = new Uint8Array(size * components); var tmpCanvas = createScratchCanvas(width, height); var tmpCtx = tmpCanvas.getContext('2d'); tmpCtx.drawImage(img, 0, 0); var data = tmpCtx.getImageData(0, 0, width, height).data; var i, j; if (components === 3) { for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) { buf[j] = data[i]; buf[j + 1] = data[i + 1]; buf[j + 2] = data[i + 2]; } } else if (components === 1) { for (i = 0, j = 0; i < rgbaLength; i += 4, j++) { buf[j] = data[i]; } } resolve({ data: buf, width: width, height: height}); }; img.onerror = function () { reject(new Error('JpegDecode failed to load image')); }; img.src = imageUrl; }); }, this); }, getData: function WorkerTransport_getData() { return this.messageHandler.sendWithPromise('GetData', null); }, getPage: function WorkerTransport_getPage(pageNumber, capability) { if (pageNumber <= 0 || pageNumber > this.numPages || (pageNumber|0) !== pageNumber) { return Promise.reject(new Error('Invalid page request')); } var pageIndex = pageNumber - 1; if (pageIndex in this.pagePromises) { return this.pagePromises[pageIndex]; } var promise = this.messageHandler.sendWithPromise('GetPage', { pageIndex: pageIndex }).then(function (pageInfo) { if (this.destroyed) { throw new Error('Transport destroyed'); } var page = new PDFPageProxy(pageIndex, pageInfo, this); this.pageCache[pageIndex] = page; return page; }.bind(this)); this.pagePromises[pageIndex] = promise; return promise; }, getPageIndex: function WorkerTransport_getPageIndexByRef(ref) { return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref }); }, getAnnotations: function WorkerTransport_getAnnotations(pageIndex, intent) { return this.messageHandler.sendWithPromise('GetAnnotations', { pageIndex: pageIndex, intent: intent, }); }, getDestinations: function WorkerTransport_getDestinations() { return this.messageHandler.sendWithPromise('GetDestinations', null); }, getDestination: function WorkerTransport_getDestination(id) { return this.messageHandler.sendWithPromise('GetDestination', { id: id }); }, getAttachments: function WorkerTransport_getAttachments() { return this.messageHandler.sendWithPromise('GetAttachments', null); }, getJavaScript: function WorkerTransport_getJavaScript() { return this.messageHandler.sendWithPromise('GetJavaScript', null); }, getOutline: function WorkerTransport_getOutline() { return this.messageHandler.sendWithPromise('GetOutline', null); }, getMetadata: function WorkerTransport_getMetadata() { return this.messageHandler.sendWithPromise('GetMetadata', null). then(function transportMetadata(results) { return { info: results[0], metadata: (results[1] ? new Metadata(results[1]) : null) }; }); }, getStats: function WorkerTransport_getStats() { return this.messageHandler.sendWithPromise('GetStats', null); }, startCleanup: function WorkerTransport_startCleanup() { this.messageHandler.sendWithPromise('Cleanup', null). then(function endCleanup() { for (var i = 0, ii = this.pageCache.length; i < ii; i++) { var page = this.pageCache[i]; if (page) { page.cleanup(); } } this.commonObjs.clear(); this.fontLoader.clear(); }.bind(this)); } }; return WorkerTransport; })(); /** * A PDF document and page is built of many objects. E.g. there are objects * for fonts, images, rendering code and such. These objects might get processed * inside of a worker. The `PDFObjects` implements some basic functions to * manage these objects. * @ignore */ var PDFObjects = (function PDFObjectsClosure() { function PDFObjects() { this.objs = {}; } PDFObjects.prototype = { /** * Internal function. * Ensures there is an object defined for `objId`. */ ensureObj: function PDFObjects_ensureObj(objId) { if (this.objs[objId]) { return this.objs[objId]; } var obj = { capability: createPromiseCapability(), data: null, resolved: false }; this.objs[objId] = obj; return obj; }, /** * If called *without* callback, this returns the data of `objId` but the * object needs to be resolved. If it isn't, this function throws. * * If called *with* a callback, the callback is called with the data of the * object once the object is resolved. That means, if you call this * function and the object is already resolved, the callback gets called * right away. */ get: function PDFObjects_get(objId, callback) { // If there is a callback, then the get can be async and the object is // not required to be resolved right now if (callback) { this.ensureObj(objId).capability.promise.then(callback); return null; } // If there isn't a callback, the user expects to get the resolved data // directly. var obj = this.objs[objId]; // If there isn't an object yet or the object isn't resolved, then the // data isn't ready yet! if (!obj || !obj.resolved) { error('Requesting object that isn\'t resolved yet ' + objId); } return obj.data; }, /** * Resolves the object `objId` with optional `data`. */ resolve: function PDFObjects_resolve(objId, data) { var obj = this.ensureObj(objId); obj.resolved = true; obj.data = data; obj.capability.resolve(data); }, isResolved: function PDFObjects_isResolved(objId) { var objs = this.objs; if (!objs[objId]) { return false; } else { return objs[objId].resolved; } }, hasData: function PDFObjects_hasData(objId) { return this.isResolved(objId); }, /** * Returns the data of `objId` if object exists, null otherwise. */ getData: function PDFObjects_getData(objId) { var objs = this.objs; if (!objs[objId] || !objs[objId].resolved) { return null; } else { return objs[objId].data; } }, clear: function PDFObjects_clear() { this.objs = {}; } }; return PDFObjects; })(); /** * Allows controlling of the rendering tasks. * @class * @alias RenderTask */ var RenderTask = (function RenderTaskClosure() { function RenderTask(internalRenderTask) { this._internalRenderTask = internalRenderTask; /** * Callback for incremental rendering -- a function that will be called * each time the rendering is paused. To continue rendering call the * function that is the first argument to the callback. * @type {function} */ this.onContinue = null; } RenderTask.prototype = /** @lends RenderTask.prototype */ { /** * Promise for rendering task completion. * @return {Promise} */ get promise() { return this._internalRenderTask.capability.promise; }, /** * Cancels the rendering task. If the task is currently rendering it will * not be cancelled until graphics pauses with a timeout. The promise that * this object extends will resolved when cancelled. */ cancel: function RenderTask_cancel() { this._internalRenderTask.cancel(); }, /** * Registers callbacks to indicate the rendering task completion. * * @param {function} onFulfilled The callback for the rendering completion. * @param {function} onRejected The callback for the rendering failure. * @return {Promise} A promise that is resolved after the onFulfilled or * onRejected callback. */ then: function RenderTask_then(onFulfilled, onRejected) { return this.promise.then.apply(this.promise, arguments); } }; return RenderTask; })(); /** * For internal use only. * @ignore */ var InternalRenderTask = (function InternalRenderTaskClosure() { function InternalRenderTask(callback, params, objs, commonObjs, operatorList, pageNumber) { this.callback = callback; this.params = params; this.objs = objs; this.commonObjs = commonObjs; this.operatorListIdx = null; this.operatorList = operatorList; this.pageNumber = pageNumber; this.running = false; this.graphicsReadyCallback = null; this.graphicsReady = false; this.useRequestAnimationFrame = false; this.cancelled = false; this.capability = createPromiseCapability(); this.task = new RenderTask(this); // caching this-bound methods this._continueBound = this._continue.bind(this); this._scheduleNextBound = this._scheduleNext.bind(this); this._nextBound = this._next.bind(this); } InternalRenderTask.prototype = { initalizeGraphics: function InternalRenderTask_initalizeGraphics(transparency) { if (this.cancelled) { return; } if (PDFJS.pdfBug && 'StepperManager' in globalScope && globalScope.StepperManager.enabled) { this.stepper = globalScope.StepperManager.create(this.pageNumber - 1); this.stepper.init(this.operatorList); this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint(); } var params = this.params; this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs, this.objs, params.imageLayer); this.gfx.beginDrawing(params.transform, params.viewport, transparency); this.operatorListIdx = 0; this.graphicsReady = true; if (this.graphicsReadyCallback) { this.graphicsReadyCallback(); } }, cancel: function InternalRenderTask_cancel() { this.running = false; this.cancelled = true; this.callback('cancelled'); }, operatorListChanged: function InternalRenderTask_operatorListChanged() { if (!this.graphicsReady) { if (!this.graphicsReadyCallback) { this.graphicsReadyCallback = this._continueBound; } return; } if (this.stepper) { this.stepper.updateOperatorList(this.operatorList); } if (this.running) { return; } this._continue(); }, _continue: function InternalRenderTask__continue() { this.running = true; if (this.cancelled) { return; } if (this.task.onContinue) { this.task.onContinue.call(this.task, this._scheduleNextBound); } else { this._scheduleNext(); } }, _scheduleNext: function InternalRenderTask__scheduleNext() { if (this.useRequestAnimationFrame) { window.requestAnimationFrame(this._nextBound); } else { Promise.resolve(undefined).then(this._nextBound); } }, _next: function InternalRenderTask__next() { if (this.cancelled) { return; } this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper); if (this.operatorListIdx === this.operatorList.argsArray.length) { this.running = false; if (this.operatorList.lastChunk) { this.gfx.endDrawing(); this.callback(); } } } }; return InternalRenderTask; })(); /** * (Deprecated) Global observer of unsupported feature usages. Use * onUnsupportedFeature callback of the {PDFDocumentLoadingTask} instance. */ PDFJS.UnsupportedManager = (function UnsupportedManagerClosure() { var listeners = []; return { listen: function (cb) { deprecated('Global UnsupportedManager.listen is used: ' + ' use PDFDocumentLoadingTask.onUnsupportedFeature instead'); listeners.push(cb); }, notify: function (featureId) { for (var i = 0, ii = listeners.length; i < ii; i++) { listeners[i](featureId); } } }; })(); exports.getDocument = PDFJS.getDocument; exports.PDFDataRangeTransport = PDFDataRangeTransport; exports.PDFDocumentProxy = PDFDocumentProxy; exports.PDFPageProxy = PDFPageProxy; })); }).call(pdfjsLibs); exports.PDFJS = pdfjsLibs.pdfjsSharedGlobal.PDFJS; exports.getDocument = pdfjsLibs.pdfjsDisplayAPI.getDocument; exports.PDFDataRangeTransport = pdfjsLibs.pdfjsDisplayAPI.PDFDataRangeTransport; exports.renderTextLayer = pdfjsLibs.pdfjsDisplayTextLayer.renderTextLayer; exports.AnnotationLayer = pdfjsLibs.pdfjsDisplayAnnotationLayer.AnnotationLayer; exports.CustomStyle = pdfjsLibs.pdfjsDisplayDOMUtils.CustomStyle; exports.PasswordResponses = pdfjsLibs.pdfjsSharedUtil.PasswordResponses; exports.InvalidPDFException = pdfjsLibs.pdfjsSharedUtil.InvalidPDFException; exports.MissingPDFException = pdfjsLibs.pdfjsSharedUtil.MissingPDFException; exports.UnexpectedResponseException = pdfjsLibs.pdfjsSharedUtil.UnexpectedResponseException; }));
sreym/cdnjs
ajax/libs/pdf.js/1.3.177/pdf.js
JavaScript
mit
313,996
""" Integration tests for third_party_auth LTI auth providers """ import unittest from django.conf import settings from django.contrib.auth.models import User from django.core.urlresolvers import reverse from oauthlib.oauth1.rfc5849 import Client, SIGNATURE_TYPE_BODY from third_party_auth.tests import testutil FORM_ENCODED = 'application/x-www-form-urlencoded' LTI_CONSUMER_KEY = 'consumer' LTI_CONSUMER_SECRET = 'secret' LTI_TPA_LOGIN_URL = 'http://testserver/auth/login/lti/' LTI_TPA_COMPLETE_URL = 'http://testserver/auth/complete/lti/' OTHER_LTI_CONSUMER_KEY = 'settings-consumer' OTHER_LTI_CONSUMER_SECRET = 'secret2' LTI_USER_ID = 'lti_user_id' EDX_USER_ID = 'test_user' EMAIL = 'lti_user@example.com' @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms') class IntegrationTestLTI(testutil.TestCase): """ Integration tests for third_party_auth LTI auth providers """ def setUp(self): super(IntegrationTestLTI, self).setUp() self.client.defaults['SERVER_NAME'] = 'testserver' self.url_prefix = 'http://testserver' self.configure_lti_provider( name='Other Tool Consumer 1', enabled=True, lti_consumer_key='other1', lti_consumer_secret='secret1', lti_max_timestamp_age=10, ) self.configure_lti_provider( name='LTI Test Tool Consumer', enabled=True, lti_consumer_key=LTI_CONSUMER_KEY, lti_consumer_secret=LTI_CONSUMER_SECRET, lti_max_timestamp_age=10, ) self.configure_lti_provider( name='Tool Consumer with Secret in Settings', enabled=True, lti_consumer_key=OTHER_LTI_CONSUMER_KEY, lti_consumer_secret='', lti_max_timestamp_age=10, ) self.lti = Client( client_key=LTI_CONSUMER_KEY, client_secret=LTI_CONSUMER_SECRET, signature_type=SIGNATURE_TYPE_BODY, ) def test_lti_login(self): # The user initiates a login from an external site (uri, _headers, body) = self.lti.sign( uri=LTI_TPA_LOGIN_URL, http_method='POST', headers={'Content-Type': FORM_ENCODED}, body={ 'user_id': LTI_USER_ID, 'custom_tpa_next': '/account/finish_auth/?course_id=my_course_id&enrollment_action=enroll', } ) login_response = self.client.post(path=uri, content_type=FORM_ENCODED, data=body) # The user should be redirected to the registration form self.assertEqual(login_response.status_code, 302) self.assertTrue(login_response['Location'].endswith(reverse('signin_user'))) register_response = self.client.get(login_response['Location']) self.assertEqual(register_response.status_code, 200) self.assertIn('"currentProvider": "LTI Test Tool Consumer"', register_response.content) self.assertIn('"errorMessage": null', register_response.content) # Now complete the form: ajax_register_response = self.client.post( reverse('user_api_registration'), { 'email': EMAIL, 'name': 'Myself', 'username': EDX_USER_ID, 'honor_code': True, } ) self.assertEqual(ajax_register_response.status_code, 200) continue_response = self.client.get(LTI_TPA_COMPLETE_URL) # The user should be redirected to the finish_auth view which will enroll them. # FinishAuthView.js reads the URL parameters directly from $.url self.assertEqual(continue_response.status_code, 302) self.assertEqual( continue_response['Location'], 'http://testserver/account/finish_auth/?course_id=my_course_id&enrollment_action=enroll' ) # Now check that we can login again self.client.logout() self.verify_user_email(EMAIL) (uri, _headers, body) = self.lti.sign( uri=LTI_TPA_LOGIN_URL, http_method='POST', headers={'Content-Type': FORM_ENCODED}, body={'user_id': LTI_USER_ID} ) login_2_response = self.client.post(path=uri, content_type=FORM_ENCODED, data=body) # The user should be redirected to the dashboard self.assertEqual(login_2_response.status_code, 302) self.assertEqual(login_2_response['Location'], LTI_TPA_COMPLETE_URL) continue_2_response = self.client.get(login_2_response['Location']) self.assertEqual(continue_2_response.status_code, 302) self.assertTrue(continue_2_response['Location'].endswith(reverse('dashboard'))) # Check that the user was created correctly user = User.objects.get(email=EMAIL) self.assertEqual(user.username, EDX_USER_ID) def test_reject_initiating_login(self): response = self.client.get(LTI_TPA_LOGIN_URL) self.assertEqual(response.status_code, 405) # Not Allowed def test_reject_bad_login(self): login_response = self.client.post( path=LTI_TPA_LOGIN_URL, content_type=FORM_ENCODED, data="invalid=login" ) # The user should be redirected to the login page with an error message # (auth_entry defaults to login for this provider) self.assertEqual(login_response.status_code, 302) self.assertTrue(login_response['Location'].endswith(reverse('signin_user'))) error_response = self.client.get(login_response['Location']) self.assertIn( 'Authentication failed: LTI parameters could not be validated.', error_response.content ) def test_can_load_consumer_secret_from_settings(self): lti = Client( client_key=OTHER_LTI_CONSUMER_KEY, client_secret=OTHER_LTI_CONSUMER_SECRET, signature_type=SIGNATURE_TYPE_BODY, ) (uri, _headers, body) = lti.sign( uri=LTI_TPA_LOGIN_URL, http_method='POST', headers={'Content-Type': FORM_ENCODED}, body={ 'user_id': LTI_USER_ID, 'custom_tpa_next': '/account/finish_auth/?course_id=my_course_id&enrollment_action=enroll', } ) with self.settings(SOCIAL_AUTH_LTI_CONSUMER_SECRETS={OTHER_LTI_CONSUMER_KEY: OTHER_LTI_CONSUMER_SECRET}): login_response = self.client.post(path=uri, content_type=FORM_ENCODED, data=body) # The user should be redirected to the registration form self.assertEqual(login_response.status_code, 302) self.assertTrue(login_response['Location'].endswith(reverse('signin_user'))) register_response = self.client.get(login_response['Location']) self.assertEqual(register_response.status_code, 200) self.assertIn( '"currentProvider": "Tool Consumer with Secret in Settings"', register_response.content ) self.assertIn('"errorMessage": null', register_response.content)
solashirai/edx-platform
common/djangoapps/third_party_auth/tests/specs/test_lti.py
Python
agpl-3.0
7,079
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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. */ package com.facebook.presto.sql.planner.sanity; import com.facebook.presto.Session; import com.facebook.presto.metadata.Metadata; import com.facebook.presto.spi.type.Type; import com.facebook.presto.sql.parser.SqlParser; import com.facebook.presto.sql.planner.ExpressionExtractor; import com.facebook.presto.sql.planner.Symbol; import com.facebook.presto.sql.planner.plan.PlanNode; import com.facebook.presto.sql.tree.DefaultTraversalVisitor; import com.facebook.presto.sql.tree.Expression; import com.facebook.presto.sql.tree.SubqueryExpression; import java.util.Map; import static java.lang.String.format; public final class NoSubqueryExpressionLeftChecker implements PlanSanityChecker.Checker { @Override public void validate(PlanNode plan, Session session, Metadata metadata, SqlParser sqlParser, Map<Symbol, Type> types) { for (Expression expression : ExpressionExtractor.extractExpressions(plan)) { new DefaultTraversalVisitor<Void, Void>() { @Override protected Void visitSubqueryExpression(SubqueryExpression node, Void context) { throw new IllegalStateException(format("Unexpected subquery expression in logical plan: %s", node)); } }.process(expression, null); } } }
marsorp/blog
presto166/presto-main/src/main/java/com/facebook/presto/sql/planner/sanity/NoSubqueryExpressionLeftChecker.java
Java
apache-2.0
1,903
var FormData = require('form-data'); function form(obj) { var form = new FormData(); if (obj) { Object.keys(obj).forEach(function (name) { form.append(name, obj[name]); }); } return form; } Object.defineProperty(exports, "__esModule", { value: true }); exports.default = form; //# sourceMappingURL=form.js.map
carmine/northshore
ui/node_modules/popsicle/dist/form.js
JavaScript
apache-2.0
353
if (!self.GLOBAL || self.GLOBAL.isWindow()) { test(() => { assert_equals(document.title, "foo"); }, '<title> exists'); test(() => { assert_equals(document.querySelectorAll("meta[name=timeout][content=long]").length, 1); }, '<meta name=timeout> exists'); } scripts.push('expect-title-meta.js');
scheib/chromium
third_party/blink/web_tests/external/wpt/infrastructure/server/resources/expect-title-meta.js
JavaScript
bsd-3-clause
312
""" By specifying the 'proxy' Meta attribute, model subclasses can specify that they will take data directly from the table of their base class table rather than using a new table of their own. This allows them to act as simple proxies, providing a modified interface to the data from the base class. """ from django.db import models from django.utils.encoding import python_2_unicode_compatible # A couple of managers for testing managing overriding in proxy model cases. class PersonManager(models.Manager): def get_queryset(self): return super(PersonManager, self).get_queryset().exclude(name="fred") class SubManager(models.Manager): def get_queryset(self): return super(SubManager, self).get_queryset().exclude(name="wilma") @python_2_unicode_compatible class Person(models.Model): """ A simple concrete base class. """ name = models.CharField(max_length=50) objects = PersonManager() def __str__(self): return self.name class Abstract(models.Model): """ A simple abstract base class, to be used for error checking. """ data = models.CharField(max_length=10) class Meta: abstract = True class MyPerson(Person): """ A proxy subclass, this should not get a new table. Overrides the default manager. """ class Meta: proxy = True ordering = ["name"] permissions = ( ("display_users", "May display users information"), ) objects = SubManager() other = PersonManager() def has_special_name(self): return self.name.lower() == "special" class ManagerMixin(models.Model): excluder = SubManager() class Meta: abstract = True class OtherPerson(Person, ManagerMixin): """ A class with the default manager from Person, plus an secondary manager. """ class Meta: proxy = True ordering = ["name"] class StatusPerson(MyPerson): """ A non-proxy subclass of a proxy, it should get a new table. """ status = models.CharField(max_length=80) # We can even have proxies of proxies (and subclass of those). class MyPersonProxy(MyPerson): class Meta: proxy = True class LowerStatusPerson(MyPersonProxy): status = models.CharField(max_length=80) @python_2_unicode_compatible class User(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class UserProxy(User): class Meta: proxy = True class UserProxyProxy(UserProxy): class Meta: proxy = True # We can still use `select_related()` to include related models in our querysets. class Country(models.Model): name = models.CharField(max_length=50) @python_2_unicode_compatible class State(models.Model): name = models.CharField(max_length=50) country = models.ForeignKey(Country, models.CASCADE) def __str__(self): return self.name class StateProxy(State): class Meta: proxy = True # Proxy models still works with filters (on related fields) # and select_related, even when mixed with model inheritance @python_2_unicode_compatible class BaseUser(models.Model): name = models.CharField(max_length=255) def __str__(self): return ':'.join((self.__class__.__name__, self.name,)) class TrackerUser(BaseUser): status = models.CharField(max_length=50) class ProxyTrackerUser(TrackerUser): class Meta: proxy = True @python_2_unicode_compatible class Issue(models.Model): summary = models.CharField(max_length=255) assignee = models.ForeignKey(ProxyTrackerUser, models.CASCADE, related_name='issues') def __str__(self): return ':'.join((self.__class__.__name__, self.summary,)) class Bug(Issue): version = models.CharField(max_length=50) reporter = models.ForeignKey(BaseUser, models.CASCADE) class ProxyBug(Bug): """ Proxy of an inherited class """ class Meta: proxy = True class ProxyProxyBug(ProxyBug): """ A proxy of proxy model with related field """ class Meta: proxy = True class Improvement(Issue): """ A model that has relation to a proxy model or to a proxy of proxy model """ version = models.CharField(max_length=50) reporter = models.ForeignKey(ProxyTrackerUser, models.CASCADE) associated_bug = models.ForeignKey(ProxyProxyBug, models.CASCADE) class ProxyImprovement(Improvement): class Meta: proxy = True
benjaminjkraft/django
tests/proxy_models/models.py
Python
bsd-3-clause
4,514
// 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.Diagnostics; using System.Threading.Tasks; using Xunit; namespace System.Threading.Tests { /// <summary> /// SemaphoreSlim unit tests /// </summary> public class SemaphoreSlimTests { /// <summary> /// SemaphoreSlim public methods and properties to be tested /// </summary> private enum SemaphoreSlimActions { Constructor, Wait, WaitAsync, Release, Dispose, CurrentCount, AvailableWaitHandle } [Fact] public static void RunSemaphoreSlimTest0_Ctor() { RunSemaphoreSlimTest0_Ctor(0, 10, null); RunSemaphoreSlimTest0_Ctor(5, 10, null); RunSemaphoreSlimTest0_Ctor(10, 10, null); } [Fact] public static void RunSemaphoreSlimTest0_Ctor_Negative() { RunSemaphoreSlimTest0_Ctor(10, 0, typeof(ArgumentOutOfRangeException)); RunSemaphoreSlimTest0_Ctor(10, -1, typeof(ArgumentOutOfRangeException)); RunSemaphoreSlimTest0_Ctor(-1, 10, typeof(ArgumentOutOfRangeException)); } [Fact] public static void RunSemaphoreSlimTest1_Wait() { // Infinite timeout RunSemaphoreSlimTest1_Wait(10, 10, -1, true, null); RunSemaphoreSlimTest1_Wait(1, 10, -1, true, null); // Zero timeout RunSemaphoreSlimTest1_Wait(10, 10, 0, true, null); RunSemaphoreSlimTest1_Wait(1, 10, 0, true, null); RunSemaphoreSlimTest1_Wait(0, 10, 0, false, null); // Positive timeout RunSemaphoreSlimTest1_Wait(10, 10, 10, true, null); RunSemaphoreSlimTest1_Wait(1, 10, 10, true, null); RunSemaphoreSlimTest1_Wait(0, 10, 10, false, null); } [Fact] public static void RunSemaphoreSlimTest1_Wait_NegativeCases() { // Invalid timeout RunSemaphoreSlimTest1_Wait(10, 10, -10, true, typeof(ArgumentOutOfRangeException)); RunSemaphoreSlimTest1_Wait (10, 10, new TimeSpan(0, 0, int.MaxValue), true, typeof(ArgumentOutOfRangeException)); } [Fact] public static void RunSemaphoreSlimTest1_WaitAsync() { // Infinite timeout RunSemaphoreSlimTest1_WaitAsync(10, 10, -1, true, null); RunSemaphoreSlimTest1_WaitAsync(1, 10, -1, true, null); // Zero timeout RunSemaphoreSlimTest1_WaitAsync(10, 10, 0, true, null); RunSemaphoreSlimTest1_WaitAsync(1, 10, 0, true, null); RunSemaphoreSlimTest1_WaitAsync(0, 10, 0, false, null); // Positive timeout RunSemaphoreSlimTest1_WaitAsync(10, 10, 10, true, null); RunSemaphoreSlimTest1_WaitAsync(1, 10, 10, true, null); RunSemaphoreSlimTest1_WaitAsync(0, 10, 10, false, null); } [Fact] public static void RunSemaphoreSlimTest1_WaitAsync_NegativeCases() { // Invalid timeout RunSemaphoreSlimTest1_WaitAsync(10, 10, -10, true, typeof(ArgumentOutOfRangeException)); RunSemaphoreSlimTest1_WaitAsync (10, 10, new TimeSpan(0, 0, int.MaxValue), true, typeof(ArgumentOutOfRangeException)); RunSemaphoreSlimTest1_WaitAsync2(); } [Fact] public static void RunSemaphoreSlimTest2_Release() { // Valid release count RunSemaphoreSlimTest2_Release(5, 10, 1, null); RunSemaphoreSlimTest2_Release(0, 10, 1, null); RunSemaphoreSlimTest2_Release(5, 10, 5, null); } [Fact] public static void RunSemaphoreSlimTest2_Release_NegativeCases() { // Invalid release count RunSemaphoreSlimTest2_Release(5, 10, 0, typeof(ArgumentOutOfRangeException)); RunSemaphoreSlimTest2_Release(5, 10, -1, typeof(ArgumentOutOfRangeException)); // Semaphore Full RunSemaphoreSlimTest2_Release(10, 10, 1, typeof(SemaphoreFullException)); RunSemaphoreSlimTest2_Release(5, 10, 6, typeof(SemaphoreFullException)); RunSemaphoreSlimTest2_Release(int.MaxValue - 1, int.MaxValue, 10, typeof(SemaphoreFullException)); } [Fact] public static void RunSemaphoreSlimTest4_Dispose() { RunSemaphoreSlimTest4_Dispose(5, 10, null, null); RunSemaphoreSlimTest4_Dispose(5, 10, SemaphoreSlimActions.CurrentCount, null); RunSemaphoreSlimTest4_Dispose (5, 10, SemaphoreSlimActions.Wait, typeof(ObjectDisposedException)); RunSemaphoreSlimTest4_Dispose (5, 10, SemaphoreSlimActions.WaitAsync, typeof(ObjectDisposedException)); RunSemaphoreSlimTest4_Dispose (5, 10, SemaphoreSlimActions.Release, typeof(ObjectDisposedException)); RunSemaphoreSlimTest4_Dispose (5, 10, SemaphoreSlimActions.AvailableWaitHandle, typeof(ObjectDisposedException)); } [Fact] public static void RunSemaphoreSlimTest5_CurrentCount() { RunSemaphoreSlimTest5_CurrentCount(5, 10, null); RunSemaphoreSlimTest5_CurrentCount(5, 10, SemaphoreSlimActions.Wait); RunSemaphoreSlimTest5_CurrentCount(5, 10, SemaphoreSlimActions.WaitAsync); RunSemaphoreSlimTest5_CurrentCount(5, 10, SemaphoreSlimActions.Release); } [Fact] public static void RunSemaphoreSlimTest7_AvailableWaitHandle() { RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, null, true); RunSemaphoreSlimTest7_AvailableWaitHandle(0, 10, null, false); RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, SemaphoreSlimActions.Wait, true); RunSemaphoreSlimTest7_AvailableWaitHandle(1, 10, SemaphoreSlimActions.Wait, false); RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, SemaphoreSlimActions.Wait, true); RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, SemaphoreSlimActions.WaitAsync, true); RunSemaphoreSlimTest7_AvailableWaitHandle(1, 10, SemaphoreSlimActions.WaitAsync, false); RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, SemaphoreSlimActions.WaitAsync, true); RunSemaphoreSlimTest7_AvailableWaitHandle(0, 10, SemaphoreSlimActions.Release, true); } /// <summary> /// Test SemaphoreSlim constructor /// </summary> /// <param name="initial">The initial semaphore count</param> /// <param name="maximum">The maximum semaphore count</param> /// <param name="exceptionType">The type of the thrown exception in case of invalid cases, /// null for valid cases</param> /// <returns>True if the test succeeded, false otherwise</returns> private static void RunSemaphoreSlimTest0_Ctor(int initial, int maximum, Type exceptionType) { string methodFailed = "RunSemaphoreSlimTest0_Ctor(" + initial + "," + maximum + "): FAILED. "; Exception exception = null; try { SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum); Assert.Equal(initial, semaphore.CurrentCount); } catch (Exception ex) { Assert.NotNull(exceptionType); Assert.IsType(exceptionType, ex); exception = ex; } } /// <summary> /// Test SemaphoreSlim Wait /// </summary> /// <param name="initial">The initial semaphore count</param> /// <param name="maximum">The maximum semaphore count</param> /// <param name="timeout">The timeout parameter for the wait method, it must be either int or TimeSpan</param> /// <param name="returnValue">The expected wait return value</param> /// <param name="exceptionType">The type of the thrown exception in case of invalid cases, /// null for valid cases</param> /// <returns>True if the test succeeded, false otherwise</returns> private static void RunSemaphoreSlimTest1_Wait (int initial, int maximum, object timeout, bool returnValue, Type exceptionType) { SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum); try { bool result = false; if (timeout is TimeSpan) { result = semaphore.Wait((TimeSpan)timeout); } else { result = semaphore.Wait((int)timeout); } Assert.Equal(returnValue, result); if (result) { Assert.Equal(initial - 1, semaphore.CurrentCount); } } catch (Exception ex) { Assert.NotNull(exceptionType); Assert.IsType(exceptionType, ex); } } /// <summary> /// Test SemaphoreSlim WaitAsync /// </summary> /// <param name="initial">The initial semaphore count</param> /// <param name="maximum">The maximum semaphore count</param> /// <param name="timeout">The timeout parameter for the wait method, it must be either int or TimeSpan</param> /// <param name="returnValue">The expected wait return value</param> /// <param name="exceptionType">The type of the thrown exception in case of invalid cases, /// null for valid cases</param> /// <returns>True if the test succeeded, false otherwise</returns> private static void RunSemaphoreSlimTest1_WaitAsync (int initial, int maximum, object timeout, bool returnValue, Type exceptionType) { SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum); try { bool result = false; if (timeout is TimeSpan) { result = semaphore.WaitAsync((TimeSpan)timeout).Result; } else { result = semaphore.WaitAsync((int)timeout).Result; } Assert.Equal(returnValue, result); if (result) { Assert.Equal(initial - 1, semaphore.CurrentCount); } } catch (Exception ex) { Assert.NotNull(exceptionType); Assert.IsType(exceptionType, ex); } } /// <summary> /// Test SemaphoreSlim WaitAsync /// The test verifies that SemaphoreSlim.Release() does not execute any user code synchronously. /// </summary> private static void RunSemaphoreSlimTest1_WaitAsync2() { SemaphoreSlim semaphore = new SemaphoreSlim(1); ThreadLocal<int> counter = new ThreadLocal<int>(() => 0); bool nonZeroObserved = false; const int asyncActions = 20; int remAsyncActions = asyncActions; ManualResetEvent mre = new ManualResetEvent(false); Action<int> doWorkAsync = async delegate (int i) { await semaphore.WaitAsync(); if (counter.Value > 0) { nonZeroObserved = true; } counter.Value = counter.Value + 1; semaphore.Release(); counter.Value = counter.Value - 1; if (Interlocked.Decrement(ref remAsyncActions) == 0) mre.Set(); }; semaphore.Wait(); for (int i = 0; i < asyncActions; i++) doWorkAsync(i); semaphore.Release(); mre.WaitOne(); Assert.False(nonZeroObserved, "RunSemaphoreSlimTest1_WaitAsync2: FAILED. SemaphoreSlim.Release() seems to have synchronously invoked a continuation."); } /// <summary> /// Test SemaphoreSlim Release /// </summary> /// <param name="initial">The initial semaphore count</param> /// <param name="maximum">The maximum semaphore count</param> /// <param name="releaseCount">The release count for the release method</param> /// <param name="exceptionType">The type of the thrown exception in case of invalid cases, /// null for valid cases</param> /// <returns>True if the test succeeded, false otherwise</returns> private static void RunSemaphoreSlimTest2_Release (int initial, int maximum, int releaseCount, Type exceptionType) { SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum); try { int oldCount = semaphore.Release(releaseCount); Assert.Equal(initial, oldCount); Assert.Equal(initial + releaseCount, semaphore.CurrentCount); } catch (Exception ex) { Assert.NotNull(exceptionType); Assert.IsType(exceptionType, ex); } } /// <summary> /// Call specific SemaphoreSlim method or property /// </summary> /// <param name="semaphore">The SemaphoreSlim instance</param> /// <param name="action">The action name</param> /// <param name="param">The action parameter, null if it takes no parameters</param> /// <returns>The action return value, null if the action returns void</returns> private static object CallSemaphoreAction (SemaphoreSlim semaphore, SemaphoreSlimActions? action, object param) { if (action == SemaphoreSlimActions.Wait) { if (param is TimeSpan) { return semaphore.Wait((TimeSpan)param); } else if (param is int) { return semaphore.Wait((int)param); } semaphore.Wait(); return null; } else if (action == SemaphoreSlimActions.WaitAsync) { if (param is TimeSpan) { return semaphore.WaitAsync((TimeSpan)param).Result; } else if (param is int) { return semaphore.WaitAsync((int)param).Result; } semaphore.WaitAsync().Wait(); return null; } else if (action == SemaphoreSlimActions.Release) { if (param != null) { return semaphore.Release((int)param); } return semaphore.Release(); } else if (action == SemaphoreSlimActions.Dispose) { semaphore.Dispose(); return null; } else if (action == SemaphoreSlimActions.CurrentCount) { return semaphore.CurrentCount; } else if (action == SemaphoreSlimActions.AvailableWaitHandle) { return semaphore.AvailableWaitHandle; } return null; } /// <summary> /// Test SemaphoreSlim Dispose /// </summary> /// <param name="initial">The initial semaphore count</param> /// <param name="maximum">The maximum semaphore count</param> /// <param name="action">SemaphoreSlim action to be called after Dispose</param> /// <param name="exceptionType">The type of the thrown exception in case of invalid cases, /// null for valid cases</param> /// <returns>True if the test succeeded, false otherwise</returns> private static void RunSemaphoreSlimTest4_Dispose(int initial, int maximum, SemaphoreSlimActions? action, Type exceptionType) { SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum); try { semaphore.Dispose(); CallSemaphoreAction(semaphore, action, null); } catch (Exception ex) { Assert.NotNull(exceptionType); Assert.IsType(exceptionType, ex); } } /// <summary> /// Test SemaphoreSlim CurrentCount property /// </summary> /// <param name="initial">The initial semaphore count</param> /// <param name="maximum">The maximum semaphore count</param> /// <param name="action">SemaphoreSlim action to be called before CurrentCount</param> /// <returns>True if the test succeeded, false otherwise</returns> private static void RunSemaphoreSlimTest5_CurrentCount(int initial, int maximum, SemaphoreSlimActions? action) { SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum); CallSemaphoreAction(semaphore, action, null); if (action == null) { Assert.Equal(initial, semaphore.CurrentCount); } else { Assert.Equal(initial + (action == SemaphoreSlimActions.Release ? 1 : -1), semaphore.CurrentCount); } } /// <summary> /// Test SemaphoreSlim AvailableWaitHandle property /// </summary> /// <param name="initial">The initial semaphore count</param> /// <param name="maximum">The maximum semaphore count</param> /// <param name="action">SemaphoreSlim action to be called before WaitHandle</param> /// <param name="state">The expected wait handle state</param> /// <returns>True if the test succeeded, false otherwise</returns> private static void RunSemaphoreSlimTest7_AvailableWaitHandle(int initial, int maximum, SemaphoreSlimActions? action, bool state) { SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum); CallSemaphoreAction(semaphore, action, null); Assert.NotNull(semaphore.AvailableWaitHandle); Assert.Equal(state, semaphore.AvailableWaitHandle.WaitOne(0)); } /// <summary> /// Test SemaphoreSlim Wait and Release methods concurrently /// </summary> /// <param name="initial">The initial semaphore count</param> /// <param name="maximum">The maximum semaphore count</param> /// <param name="waitThreads">Number of the threads that call Wait method</param> /// <param name="releaseThreads">Number of the threads that call Release method</param> /// <param name="succeededWait">Number of succeeded wait threads</param> /// <param name="failedWait">Number of failed wait threads</param> /// <param name="finalCount">The final semaphore count</param> /// <returns>True if the test succeeded, false otherwise</returns> [Theory] [InlineData(5, 1000, 50, 50, 50, 0, 5, 1000)] [InlineData(0, 1000, 50, 25, 25, 25, 0, 500)] [InlineData(0, 1000, 50, 0, 0, 50, 0, 100)] public static void RunSemaphoreSlimTest8_ConcWaitAndRelease(int initial, int maximum, int waitThreads, int releaseThreads, int succeededWait, int failedWait, int finalCount, int timeout) { SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum); Task[] threads = new Task[waitThreads + releaseThreads]; int succeeded = 0; int failed = 0; ManualResetEvent mre = new ManualResetEvent(false); // launch threads for (int i = 0; i < threads.Length; i++) { if (i < waitThreads) { // We are creating the Task using TaskCreationOptions.LongRunning to // force usage of another thread (which will be the case on the default scheduler // with its current implementation). Without this, the release tasks will likely get // queued behind the wait tasks in the pool, making it very likely that the wait tasks // will starve the very tasks that when run would unblock them. threads[i] = new Task(delegate () { mre.WaitOne(); if (semaphore.Wait(timeout)) { Interlocked.Increment(ref succeeded); } else { Interlocked.Increment(ref failed); } }, TaskCreationOptions.LongRunning); } else { threads[i] = new Task(delegate () { mre.WaitOne(); semaphore.Release(); }); } threads[i].Start(TaskScheduler.Default); } mre.Set(); //wait work to be done; Task.WaitAll(threads); //check the number of succeeded and failed wait Assert.Equal(succeededWait, succeeded); Assert.Equal(failedWait, failed); Assert.Equal(finalCount, semaphore.CurrentCount); } /// <summary> /// Test SemaphoreSlim WaitAsync and Release methods concurrently /// </summary> /// <param name="initial">The initial semaphore count</param> /// <param name="maximum">The maximum semaphore count</param> /// <param name="waitThreads">Number of the threads that call Wait method</param> /// <param name="releaseThreads">Number of the threads that call Release method</param> /// <param name="succeededWait">Number of succeeded wait threads</param> /// <param name="failedWait">Number of failed wait threads</param> /// <param name="finalCount">The final semaphore count</param> /// <returns>True if the test succeeded, false otherwise</returns> [Theory] [InlineData(5, 1000, 50, 50, 50, 0, 5, 500)] [InlineData(0, 1000, 50, 25, 25, 25, 0, 500)] [InlineData(0, 1000, 50, 0, 0, 50, 0, 100)] public static void RunSemaphoreSlimTest8_ConcWaitAsyncAndRelease(int initial, int maximum, int waitThreads, int releaseThreads, int succeededWait, int failedWait, int finalCount, int timeout) { SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum); Task[] tasks = new Task[waitThreads + releaseThreads]; int succeeded = 0; int failed = 0; ManualResetEvent mre = new ManualResetEvent(false); // launch threads for (int i = 0; i < tasks.Length; i++) { if (i < waitThreads) { tasks[i] = Task.Run(async delegate { mre.WaitOne(); if (await semaphore.WaitAsync(timeout)) { Interlocked.Increment(ref succeeded); } else { Interlocked.Increment(ref failed); } }); } else { tasks[i] = Task.Run(delegate { mre.WaitOne(); semaphore.Release(); }); } } mre.Set(); //wait work to be done; Task.WaitAll(tasks); Assert.Equal(succeededWait, succeeded); Assert.Equal(failedWait, failed); Assert.Equal(finalCount, semaphore.CurrentCount); } [Theory] [InlineData(10, 10)] [InlineData(1, 10)] [InlineData(10, 1)] public static void TestConcurrentWaitAndWaitAsync(int syncWaiters, int asyncWaiters) { int totalWaiters = syncWaiters + asyncWaiters; var semaphore = new SemaphoreSlim(0); Task[] tasks = new Task[totalWaiters]; const int ITERS = 10; int randSeed = unchecked((int)DateTime.Now.Ticks); for (int i = 0; i < syncWaiters; i++) { tasks[i] = Task.Run(delegate { //Random rand = new Random(Interlocked.Increment(ref randSeed)); for (int iter = 0; iter < ITERS; iter++) { semaphore.Wait(); semaphore.Release(); } }); } for (int i = syncWaiters; i < totalWaiters; i++) { tasks[i] = Task.Run(async delegate { //Random rand = new Random(Interlocked.Increment(ref randSeed)); for (int iter = 0; iter < ITERS; iter++) { await semaphore.WaitAsync(); semaphore.Release(); } }); } semaphore.Release(totalWaiters / 2); Task.WaitAll(tasks); } } }
shimingsg/corefx
src/System.Threading/tests/SemaphoreSlimTests.cs
C#
mit
25,845
import SignaturePad from 'signature_pad'; /* TEST 1 - Basic structure and usage */ function BasicTest() { const canvas = document.querySelector('canvas'); const signaturePad = new SignaturePad(canvas); // Returns signature image as data URL signaturePad.toDataURL(); // Returns signature image as data URL using the given media type signaturePad.toDataURL('image/jpeg'); // Returns an array of point groups that define the signature signaturePad.toData(); // Draws signature image from data URL signaturePad.fromDataURL('data:image/png;base64,iVBORw0K...'); // Clears the canvas signaturePad.clear(); // Returns true if canvas is empty, otherwise returns false signaturePad.isEmpty(); } /* TEST 2 - You can set options during initialization: */ function SetDuringInit() { const canvas = document.querySelector('canvas'); const signaturePad = new SignaturePad(canvas, { minWidth: 5, maxWidth: 10, penColor: 'rgb(66, 133, 244)' }); } /* TEST 3 - or during runtime: */ function RuntimeChange() { const canvas = document.querySelector('canvas'); const signaturePad = new SignaturePad(canvas); signaturePad.minWidth = 5; signaturePad.maxWidth = 10; signaturePad.penColor = 'rgb(66, 133, 244)'; }
aaronryden/DefinitelyTyped
types/signature_pad/signature_pad-tests.ts
TypeScript
mit
1,313
/* * * 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. * */ /* Network API overview: http://dvcs.w3.org/hg/dap/raw-file/tip/network-api/Overview.html */ var cordova = require('cordova'); module.exports = { var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection; getConnectionInfo: function (win, fail, args) { /* bandwidth of type double, readonly The user agent must set the value of the bandwidth attribute to: 0 if the user is currently offline; Infinity if the bandwidth is unknown; an estimation of the current bandwidth in MB/s (Megabytes per seconds) available for communication with the browsing context active document's domain. */ win(connection.bandwidth); }, isMetered: function (win, fail, args) { /* readonly attribute boolean metered A connection is metered when the user's connection is subject to a limitation from his Internet Service Provider strong enough to request web applications to be careful with the bandwidth usage. What is a metered connection is voluntarily left to the user agent to judge. It would not be possible to give an exhaustive list of limitations considered strong enough to flag the connection as metered and even if doable, some limitations can be considered strong or weak depending on the context. Examples of metered connections are mobile connections with a small bandwidth quota or connections with a pay-per use plan. The user agent MUST set the value of the metered attribute to true if the connection with the browsing context active document's domain is metered and false otherwise. If the implementation is not able to know the status of the connection or if the user is offline, the value MUST be set to false. If unable to know if a connection is metered, a user agent could ask the user about the status of his current connection. */ win(connection.metered); } }; require("cordova/firefoxos/commandProxy").add("Network", module.exports);
alejo8591/cyav
unidad-4/testappavantel3/plugins/org.apache.cordova.network-information/src/firefoxos/NetworkProxy.js
JavaScript
mit
2,982
<?php /** * Part of the Fuel framework. * * @package Fuel * @version 1.7 * @author Fuel Development Team * @license MIT License * @copyright 2010 - 2015 Fuel Development Team * @link http://fuelphp.com */ namespace Fuel\Core; /** * Testcase class tests * * @group Core * @group Testcase */ class Test_Testcase extends TestCase { public function test_foo() {} }
vano00/todo
fuel/core/tests/testcase.php
PHP
mit
399
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "chrome/browser/ui/panels/panel_mouse_watcher.h" #include "chrome/browser/ui/panels/panel_mouse_watcher_observer.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/point.h" class TestMouseObserver : public PanelMouseWatcherObserver { public: TestMouseObserver() : mouse_movements_(0) {} // Overridden from PanelMouseWatcherObserver: virtual void OnMouseMove(const gfx::Point& mouse_position) OVERRIDE { ++mouse_movements_; } int mouse_movements_; }; class PanelMouseWatcherTest : public testing::Test { }; TEST_F(PanelMouseWatcherTest, StartStopWatching) { base::MessageLoopForUI loop; scoped_ptr<PanelMouseWatcher> watcher(PanelMouseWatcher::Create()); EXPECT_FALSE(watcher->IsActive()); scoped_ptr<TestMouseObserver> user1(new TestMouseObserver()); scoped_ptr<TestMouseObserver> user2(new TestMouseObserver()); // No observers. watcher->NotifyMouseMovement(gfx::Point(42, 101)); EXPECT_EQ(0, user1->mouse_movements_); EXPECT_EQ(0, user2->mouse_movements_); // Only one mouse observer. watcher->AddObserver(user1.get()); EXPECT_TRUE(watcher->IsActive()); watcher->NotifyMouseMovement(gfx::Point(42, 101)); EXPECT_GE(user1->mouse_movements_, 1); EXPECT_EQ(0, user2->mouse_movements_); watcher->RemoveObserver(user1.get()); EXPECT_FALSE(watcher->IsActive()); // More than one mouse observer. watcher->AddObserver(user1.get()); EXPECT_TRUE(watcher->IsActive()); watcher->AddObserver(user2.get()); watcher->NotifyMouseMovement(gfx::Point(101, 42)); EXPECT_GE(user1->mouse_movements_, 2); EXPECT_GE(user2->mouse_movements_, 1); // Back to one observer. watcher->RemoveObserver(user1.get()); EXPECT_TRUE(watcher->IsActive()); int saved_count = user1->mouse_movements_; watcher->NotifyMouseMovement(gfx::Point(1, 2)); EXPECT_EQ(saved_count, user1->mouse_movements_); EXPECT_GE(user2->mouse_movements_, 2); watcher->RemoveObserver(user2.get()); EXPECT_FALSE(watcher->IsActive()); }
s20121035/rk3288_android5.1_repo
external/chromium_org/chrome/browser/ui/panels/panel_mouse_watcher_unittest.cc
C++
gpl-3.0
2,240
/* * bag.js - js/css/other loader + kv storage * * Copyright 2013-2014 Vitaly Puzrin * https://github.com/nodeca/bag.js * * License MIT */ /*global define*/ (function (root, factory) { 'use strict'; if (typeof define === 'function' && define.amd) { define(factory); } else if (typeof module === 'object' && typeof module.exports === 'object') { module.exports = factory(); } else { root.Bag = factory(); } } (this, function () { 'use strict'; var head = document.head || document.getElementsByTagName('head')[0]; ////////////////////////////////////////////////////////////////////////////// // helpers function _nope() { return; } function _isString(obj) { return Object.prototype.toString.call(obj) === '[object String]'; } var _isArray = Array.isArray || function isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; }; function _isFunction(obj) { return Object.prototype.toString.call(obj) === '[object Function]'; } function _each(obj, iterator) { if (_isArray(obj)) { if (obj.forEach) { return obj.forEach(iterator); } for (var i = 0; i < obj.length; i++) { iterator(obj[i], i, obj); } } else { for (var k in obj) { if (Object.prototype.hasOwnProperty.call(obj, k)) { iterator(obj[k], k); } } } } function _default(obj, src) { // extend obj with src properties if not exists; _each(src, function (val, key) { if (!obj[key]) { obj[key] = src[key]; } }); } function _asyncEach(arr, iterator, callback) { callback = callback || _nope; if (!arr.length) { return callback(); } var completed = 0; _each(arr, function (x) { iterator(x, function (err) { if (err) { callback(err); callback = _nope; } else { completed += 1; if (completed >= arr.length) { callback(); } } }); }); } ////////////////////////////////////////////////////////////////////////////// // Adapters for Store class function DomStorage(namespace) { var self = this; var _ns = namespace + '__'; var _storage = localStorage; this.init = function (callback) { callback(); }; this.remove = function (key, callback) { callback = callback || _nope; _storage.removeItem(_ns + key); callback(); }; this.set = function (key, value, expire, callback) { var obj = { value: value, expire: expire }; var err; try { _storage.setItem(_ns + key, JSON.stringify(obj)); } catch (e) { // On quota error try to reset storage & try again. // Just remove all keys, without conditions, no optimizations needed. if (e.name.toUpperCase().indexOf('QUOTA') >= 0) { try { _each(_storage, function (val, name) { var k = name.split(_ns)[1]; if (k) { self.remove(k); } }); _storage.setItem(_ns + key, JSON.stringify(obj)); } catch (e2) { err = e2; } } else { err = e; } } callback(err); }; this.get = function (key, raw, callback) { if (_isFunction(raw)) { callback = raw; raw = false; } var err, data; try { data = JSON.parse(_storage.getItem(_ns + key)); data = raw ? data : data.value; } catch (e) { err = new Error('Can\'t read key: ' + key); } callback(err, data); }; this.clear = function (expiredOnly, callback) { var now = +new Date(); _each(_storage, function (val, name) { var key = name.split(_ns)[1]; if (!key) { return; } if (!expiredOnly) { self.remove(key); return; } var raw; self.get(key, true, function (__, data) { raw = data; // can use this hack, because get is sync; }); if (raw && (raw.expire > 0) && ((raw.expire - now) < 0)) { self.remove(key); } }); callback(); }; } DomStorage.prototype.exists = function () { try { localStorage.setItem('__ls_test__', '__ls_test__'); localStorage.removeItem('__ls_test__'); return true; } catch (e) { return false; } }; function WebSql(namespace) { var db; this.init = function (callback) { db = window.openDatabase(namespace, '1.0', 'bag.js db', 2e5); if (!db) { return callback('Can\'t open webdql database'); } db.transaction(function (tx) { tx.executeSql( 'CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT, expire INTEGER KEY)', [], function () { return callback(); }, function (tx, err) { return callback(err); } ); }); }; this.remove = function (key, callback) { callback = callback || _nope; db.transaction(function (tx) { tx.executeSql( 'DELETE FROM kv WHERE key = ?', [ key ], function () { return callback(); }, function (tx, err) { return callback(err); } ); }); }; this.set = function (key, value, expire, callback) { db.transaction(function (tx) { tx.executeSql( 'INSERT OR REPLACE INTO kv (key, value, expire) VALUES (?, ?, ?)', [ key, JSON.stringify(value), expire ], function () { return callback(); }, function (tx, err) { return callback(err); } ); }); }; this.get = function (key, callback) { db.readTransaction(function (tx) { tx.executeSql( 'SELECT value FROM kv WHERE key = ?', [ key ], function (tx, result) { if (result.rows.length === 0) { return callback(new Error('key not found: ' + key)); } var value = result.rows.item(0).value; var err, data; try { data = JSON.parse(value); } catch (e) { err = new Error('Can\'t unserialise data: ' + value); } callback(err, data); }, function (tx, err) { return callback(err); } ); }); }; this.clear = function (expiredOnly, callback) { db.transaction(function (tx) { if (expiredOnly) { tx.executeSql( 'DELETE FROM kv WHERE expire > 0 AND expire < ?', [ +new Date() ], function () { return callback(); }, function (tx, err) { return callback(err); } ); } else { db.transaction(function (tx) { tx.executeSql( 'DELETE FROM kv', [], function () { return callback(); }, function (tx, err) { return callback(err); } ); }); } }); }; } WebSql.prototype.exists = function () { return (!!window.openDatabase); }; function Idb(namespace) { var db; this.init = function (callback) { var idb = this.idb = window.indexedDB; /* || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;*/ var req = idb.open(namespace, 2 /*version*/); req.onsuccess = function (e) { db = e.target.result; callback(); }; req.onblocked = function (e) { callback(new Error('IndexedDB blocked. ' + e.target.errorCode)); }; req.onerror = function (e) { callback(new Error('IndexedDB opening error. ' + e.target.errorCode)); }; req.onupgradeneeded = function (e) { db = e.target.result; if (db.objectStoreNames.contains('kv')) { db.deleteObjectStore('kv'); } var store = db.createObjectStore('kv', { keyPath: 'key' }); store.createIndex('expire', 'expire', { unique: false }); }; }; this.remove = function (key, callback) { var tx = db.transaction('kv', 'readwrite'); tx.oncomplete = function () { callback(); }; tx.onerror = tx.onabort = function (e) { callback(new Error('Key remove error: ', e.target)); }; // IE 8 not allow to use reserved keywords as functions. More info: // http://tiffanybbrown.com/2013/09/10/expected-identifier-bug-in-internet-explorer-8/ tx.objectStore('kv')['delete'](key).onerror = function () { tx.abort(); }; }; this.set = function (key, value, expire, callback) { var tx = db.transaction('kv', 'readwrite'); tx.oncomplete = function () { callback(); }; tx.onerror = tx.onabort = function (e) { callback(new Error('Key set error: ', e.target)); }; tx.objectStore('kv').put({ key: key, value: value, expire: expire }).onerror = function () { tx.abort(); }; }; this.get = function (key, callback) { var err, result; var tx = db.transaction('kv'); tx.oncomplete = function () { callback(err, result); }; tx.onerror = tx.onabort = function (e) { callback(new Error('Key get error: ', e.target)); }; tx.objectStore('kv').get(key).onsuccess = function (e) { if (e.target.result) { result = e.target.result.value; } else { err = new Error('key not found: ' + key); } }; }; this.clear = function (expiredOnly, callback) { var keyrange = window.IDBKeyRange; /* || window.webkitIDBKeyRange || window.msIDBKeyRange;*/ var tx, store; tx = db.transaction('kv', 'readwrite'); store = tx.objectStore('kv'); tx.oncomplete = function () { callback(); }; tx.onerror = tx.onabort = function (e) { callback(new Error('Clear error: ', e.target)); }; if (expiredOnly) { var cursor = store.index('expire').openCursor(keyrange.bound(1, +new Date())); cursor.onsuccess = function (e) { var _cursor = e.target.result; if (_cursor) { // IE 8 not allow to use reserved keywords as functions (`delete` and `continue`). More info: // http://tiffanybbrown.com/2013/09/10/expected-identifier-bug-in-internet-explorer-8/ store['delete'](_cursor.primaryKey).onerror = function () { tx.abort(); }; _cursor['continue'](); } }; } else { // Just clear everything tx.objectStore('kv').clear().onerror = function () { tx.abort(); }; } }; } Idb.prototype.exists = function () { var db = window.indexedDB /*|| window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB*/; if (!db) { return false; } // Check outdated idb implementations, where `onupgradeneede` event doesn't work, // see https://github.com/pouchdb/pouchdb/issues/1207 for more details var dbName = '__idb_test__'; var result = db.open(dbName, 1).onupgradeneeded === null; if (db.deleteDatabase) { db.deleteDatabase(dbName); } return result; }; ///////////////////////////////////////////////////////////////////////////// // key/value storage with expiration var storeAdapters = { indexeddb: Idb, websql: WebSql, localstorage: DomStorage }; // namespace - db name or similar // storesList - array of allowed adapter names to use // function Storage(namespace, storesList) { var self = this; var db = null; // States of db init singletone process // 'done' / 'progress' / 'failed' / undefined var initState; var initStack = []; _each(storesList, function (name) { // do storage names case insensitive name = name.toLowerCase(); if (!storeAdapters[name]) { throw new Error('Wrong storage adapter name: ' + name, storesList); } if (storeAdapters[name].prototype.exists() && !db) { db = new storeAdapters[name](namespace); return false; // terminate search on first success } }); if (!db) { /* eslint-disable no-console */ // If no adaprets - don't make error for correct fallback. // Just log that we continue work without storing results. if (typeof console !== 'undefined' && console.log) { console.log('None of requested storages available: ' + storesList); } /* eslint-enable no-console */ } this.init = function (callback) { if (!db) { callback(new Error('No available db')); return; } if (initState === 'done') { callback(); return; } if (initState === 'progress') { initStack.push(callback); return; } initStack.push(callback); initState = 'progress'; db.init(function (err) { initState = !err ? 'done' : 'failed'; _each(initStack, function (cb) { cb(err); }); initStack = []; // Clear expired. A bit dirty without callback, // but we don't care until clear compleete if (!err) { self.clear(true); } }); }; this.set = function (key, value, expire, callback) { if (_isFunction(expire)) { callback = expire; expire = null; } callback = callback || _nope; expire = expire ? +(new Date()) + (expire * 1000) : 0; this.init(function (err) { if (err) { return callback(err); } db.set(key, value, expire, callback); }); }; this.get = function (key, callback) { this.init(function (err) { if (err) { return callback(err); } db.get(key, callback); }); }; this.remove = function (key, callback) { callback = callback || _nope; this.init(function (err) { if (err) { return callback(err); } db.remove(key, callback); }); }; this.clear = function (expiredOnly, callback) { if (_isFunction(expiredOnly)) { callback = expiredOnly; expiredOnly = false; } callback = callback || _nope; this.init(function (err) { if (err) { return callback(err); } db.clear(expiredOnly, callback); }); }; } ////////////////////////////////////////////////////////////////////////////// // Bag class implementation function Bag(options) { if (!(this instanceof Bag)) { return new Bag(options); } var self = this; options = options || {}; this.prefix = options.prefix || 'bag'; this.timeout = options.timeout || 20; // 20 seconds this.expire = options.expire || 30 * 24; // 30 days this.isValidItem = options.isValidItem || null; this.stores = _isArray(options.stores) ? options.stores : [ 'indexeddb', 'websql', 'localstorage' ]; var storage = null; this._queue = []; this._chained = false; this._createStorage = function () { if (!storage) { storage = new Storage(self.prefix, self.stores); } }; function getUrl(url, callback) { var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { callback(null, { content: xhr.responseText, type: xhr.getResponseHeader('content-type') }); callback = _nope; } else { callback(new Error('Can\'t open url ' + url + (xhr.status ? xhr.statusText + ' (' + xhr.status + ')' : ''))); callback = _nope; } } }; setTimeout(function () { if (xhr.readyState < 4) { xhr.abort(); callback(new Error('Timeout')); callback = _nope; } }, self.timeout * 1000); xhr.send(); } function createCacheObj(obj, response) { var cacheObj = {}; _each([ 'url', 'key', 'unique' ], function (key) { if (obj[key]) { cacheObj[key] = obj[key]; } }); var now = +new Date(); cacheObj.data = response.content; cacheObj.originalType = response.type; cacheObj.type = obj.type || response.type; cacheObj.stamp = now; return cacheObj; } function saveUrl(obj, callback) { getUrl(obj.url_real, function (err, result) { if (err) { return callback(err); } var delay = (obj.expire || self.expire) * 60 * 60; // in seconds var cached = createCacheObj(obj, result); self.set(obj.key, cached, delay, function () { // Don't check error - have to return data anyway _default(obj, cached); callback(null, obj); }); }); } function isCacheValid(cached, obj) { return !cached || cached.expire - +new Date() < 0 || obj.unique !== cached.unique || obj.url !== cached.url || (self.isValidItem && !self.isValidItem(cached, obj)); } function fetch(obj, callback) { if (!obj.url) { return callback(); } obj.key = (obj.key || obj.url); self.get(obj.key, function (err_cache, cached) { // Check error only on forced fetch from cache if (err_cache && obj.cached) { callback(err_cache); return; } // if can't get object from store, then just load it from web. obj.execute = (obj.execute !== false); var shouldFetch = !!err_cache || isCacheValid(cached, obj); // If don't have to load new date - return one from cache if (!obj.live && !shouldFetch) { obj.type = obj.type || cached.originalType; _default(obj, cached); callback(null, obj); return; } // calculate loading url obj.url_real = obj.url; if (obj.unique) { // set parameter to prevent browser cache obj.url_real = obj.url + ((obj.url.indexOf('?') > 0) ? '&' : '?') + 'bag-unique=' + obj.unique; } saveUrl(obj, function (err_load) { if (err_cache && err_load) { callback(err_load); return; } if (err_load) { obj.type = obj.type || cached.originalType; _default(obj, cached); callback(null, obj); return; } callback(null, obj); }); }); } //////////////////////////////////////////////////////////////////////////// // helpers to set absolute sourcemap url /* eslint-disable max-len */ var sourceMappingRe = /(?:^([ \t]*\/\/[@|#][ \t]+sourceMappingURL=)(.+?)([ \t]*)$)|(?:^([ \t]*\/\*[@#][ \t]+sourceMappingURL=)(.+?)([ \t]*\*\/[ \t])*$)/mg; /* eslint-enable max-len */ function parse_url(url) { var pattern = new RegExp('^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?'); var matches = url.match(pattern); return { scheme: matches[2], authority: matches[4], path: matches[5], query: matches[7], fragment: matches[9] }; } function patchMappingUrl(obj) { var refUrl = parse_url(obj.url); var done = false; var res = obj.data.replace(sourceMappingRe, function (match, p1, p2, p3, p4, p5, p6) { if (!match) { return null; } done = true; // select matched group of params if (!p1) { p1 = p4; p2 = p5; p3 = p6; } var mapUrl = parse_url(p2); var scheme = (mapUrl.scheme ? mapUrl.scheme : refUrl.scheme) || window.location.protocol.slice(0, -1); var authority = (mapUrl.authority ? mapUrl.authority : refUrl.authority) || window.location.host; /* eslint-disable max-len */ var path = mapUrl.path[0] === '/' ? mapUrl.path : refUrl.path.split('/').slice(0, -1).join('/') + '/' + mapUrl.path; /* eslint-enable max-len */ return p1 + (scheme + '://' + authority + path) + p3; }); return done ? res : ''; } //////////////////////////////////////////////////////////////////////////// var handlers = { 'application/javascript': function injectScript(obj) { var script = document.createElement('script'), txt; // try to change sourcemap address to absolute txt = patchMappingUrl(obj); if (!txt) { // or add script name for dev tools txt = obj.data + '\n//# sourceURL=' + obj.url; } // Have to use .text, since we support IE8, // which won't allow appending to a script script.text = txt; head.appendChild(script); return; }, 'text/css': function injectStyle(obj) { var style = document.createElement('style'), txt; // try to change sourcemap address to absolute txt = patchMappingUrl(obj); if (!txt) { // or add stylesheet script name for dev tools txt = obj.data + '\n/*# sourceURL=' + obj.url + ' */'; } // Needed to enable `style.styleSheet` in IE style.setAttribute('type', 'text/css'); if (style.styleSheet) { // We should append style element to DOM before assign css text to // workaround IE bugs with `@import` and `@font-face`. // https://github.com/andrewwakeling/ie-css-bugs head.appendChild(style); style.styleSheet.cssText = txt; // IE method } else { style.appendChild(document.createTextNode(txt)); // others head.appendChild(style); } return; } }; function execute(obj) { if (!obj.type) { return; } // Cut off encoding if exists: // application/javascript; charset=UTF-8 var handlerName = obj.type.split(';')[0]; // Fix outdated mime types if needed, to use single handler if (handlerName === 'application/x-javascript' || handlerName === 'text/javascript') { handlerName = 'application/javascript'; } if (handlers[handlerName]) { handlers[handlerName](obj); } return; } //////////////////////////////////////////////////////////////////////////// // // Public methods // this.require = function (resources, callback) { var queue = self._queue; if (_isFunction(resources)) { callback = resources; resources = null; } if (resources) { var res = _isArray(resources) ? resources : [ resources ]; // convert string urls to structures // and push to queue _each(res, function (r, i) { if (_isString(r)) { res[i] = { url: r }; } queue.push(res[i]); }); } self._createStorage(); if (!callback) { self._chained = true; return self; } _asyncEach(queue, fetch, function (err) { if (err) { // cleanup self._chained = false; self._queue = []; callback(err); return; } _each(queue, function (obj) { if (obj.execute) { execute(obj); } }); // return content only, if one need fuul info - // check input object, that will be extended. var replies = []; _each(queue, function (r) { replies.push(r.data); }); var result = (_isArray(resources) || self._chained) ? replies : replies[0]; // cleanup self._chained = false; self._queue = []; callback(null, result); }); }; // Create proxy methods (init store then subcall) _each([ 'remove', 'get', 'set', 'clear' ], function (method) { self[method] = function () { self._createStorage(); storage[method].apply(storage, arguments); }; }); this.addHandler = function (types, handler) { types = _isArray(types) ? types : [ types ]; _each(types, function (type) { handlers[type] = handler; }); }; this.removeHandler = function (types) { self.addHandler(types/*, undefined*/); }; } return Bag; }));
kiwi89/cdnjs
ajax/libs/bagjs/1.0.0/bag.js
JavaScript
mit
24,235
// Copyright (C) 2012-2015 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // // { dg-require-debug-mode "" } // { dg-options "-std=gnu++11" } // { dg-do run { xfail *-*-* } } #include <unordered_map> void test01() { std::unordered_map<int, int> um1; auto it1 = um1.begin(); it1 = std::move(it1); } int main() { test01(); return 0; }
zjh171/gcc
libstdc++-v3/testsuite/23_containers/unordered_map/debug/iterator_self_move_assign_neg.cc
C++
gpl-2.0
1,039
// { dg-options "-std=gnu++11" } // 2007-10-26 Paolo Carlini <pcarlini@suse.de> // Copyright (C) 2007-2015 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // { dg-require-time "" } #include <ext/throw_allocator.h> #include <utility> #include <testsuite_hooks.h> void test01() { bool test __attribute__((unused)) = true; typedef std::pair<int, char> pair_type; __gnu_cxx::throw_allocator_random<pair_type> alloc1; pair_type* ptp1 = alloc1.allocate(1); alloc1.construct(ptp1, 3, 'a'); VERIFY( ptp1->first == 3 ); VERIFY( ptp1->second == 'a' ); alloc1.deallocate(ptp1, 1); } int main() { test01(); return 0; }
puppeh/gcc-6502
libstdc++-v3/testsuite/ext/throw_allocator/variadic_construct.cc
C++
gpl-2.0
1,330
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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. */ package org.jetbrains.idea.svn; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.util.RequestsMerger; import com.intellij.util.Consumer; import com.intellij.util.concurrency.Semaphore; public class SvnCopiesRefreshManager { private final RequestsMerger myRequestsMerger; private final Semaphore mySemaphore; private Runnable myMappingCallback; public SvnCopiesRefreshManager(final SvnFileUrlMappingImpl mapping) { mySemaphore = new Semaphore(); // svn mappings refresh inside also uses asynchronous pass -> we need to pass callback that will ping our "single-threaded" executor here myMappingCallback = new Runnable() { @Override public void run() { mySemaphore.up(); } }; myRequestsMerger = new RequestsMerger(new Runnable() { @Override public void run() { mySemaphore.down(); mapping.realRefresh(myMappingCallback); mySemaphore.waitFor(); } }, new Consumer<Runnable>() { public void consume(final Runnable runnable) { ApplicationManager.getApplication().executeOnPooledThread(runnable); } }); } public void asynchRequest() { myRequestsMerger.request(); } public void waitRefresh(final Runnable runnable) { myRequestsMerger.waitRefresh(runnable); } }
consulo/consulo-apache-subversion
src/main/java/org/jetbrains/idea/svn/SvnCopiesRefreshManager.java
Java
apache-2.0
1,939
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2013 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ ///b3DynamicBvh implementation by Nathanael Presson #include "b3DynamicBvh.h" // typedef b3AlignedObjectArray<b3DbvtNode*> b3NodeArray; typedef b3AlignedObjectArray<const b3DbvtNode*> b3ConstNodeArray; // struct b3DbvtNodeEnumerator : b3DynamicBvh::ICollide { b3ConstNodeArray nodes; void Process(const b3DbvtNode* n) { nodes.push_back(n); } }; // static B3_DBVT_INLINE int b3IndexOf(const b3DbvtNode* node) { return(node->parent->childs[1]==node); } // static B3_DBVT_INLINE b3DbvtVolume b3Merge( const b3DbvtVolume& a, const b3DbvtVolume& b) { #if (B3_DBVT_MERGE_IMPL==B3_DBVT_IMPL_SSE) B3_ATTRIBUTE_ALIGNED16(char locals[sizeof(b3DbvtAabbMm)]); b3DbvtVolume& res=*(b3DbvtVolume*)locals; #else b3DbvtVolume res; #endif b3Merge(a,b,res); return(res); } // volume+edge lengths static B3_DBVT_INLINE b3Scalar b3Size(const b3DbvtVolume& a) { const b3Vector3 edges=a.Lengths(); return( edges.x*edges.y*edges.z+ edges.x+edges.y+edges.z); } // static void b3GetMaxDepth(const b3DbvtNode* node,int depth,int& maxdepth) { if(node->isinternal()) { b3GetMaxDepth(node->childs[0],depth+1,maxdepth); b3GetMaxDepth(node->childs[1],depth+1,maxdepth); } else maxdepth=b3Max(maxdepth,depth); } // static B3_DBVT_INLINE void b3DeleteNode( b3DynamicBvh* pdbvt, b3DbvtNode* node) { b3AlignedFree(pdbvt->m_free); pdbvt->m_free=node; } // static void b3RecurseDeleteNode( b3DynamicBvh* pdbvt, b3DbvtNode* node) { if(!node->isleaf()) { b3RecurseDeleteNode(pdbvt,node->childs[0]); b3RecurseDeleteNode(pdbvt,node->childs[1]); } if(node==pdbvt->m_root) pdbvt->m_root=0; b3DeleteNode(pdbvt,node); } // static B3_DBVT_INLINE b3DbvtNode* b3CreateNode( b3DynamicBvh* pdbvt, b3DbvtNode* parent, void* data) { b3DbvtNode* node; if(pdbvt->m_free) { node=pdbvt->m_free;pdbvt->m_free=0; } else { node=new(b3AlignedAlloc(sizeof(b3DbvtNode),16)) b3DbvtNode(); } node->parent = parent; node->data = data; node->childs[1] = 0; return(node); } // static B3_DBVT_INLINE b3DbvtNode* b3CreateNode( b3DynamicBvh* pdbvt, b3DbvtNode* parent, const b3DbvtVolume& volume, void* data) { b3DbvtNode* node=b3CreateNode(pdbvt,parent,data); node->volume=volume; return(node); } // static B3_DBVT_INLINE b3DbvtNode* b3CreateNode( b3DynamicBvh* pdbvt, b3DbvtNode* parent, const b3DbvtVolume& volume0, const b3DbvtVolume& volume1, void* data) { b3DbvtNode* node=b3CreateNode(pdbvt,parent,data); b3Merge(volume0,volume1,node->volume); return(node); } // static void b3InsertLeaf( b3DynamicBvh* pdbvt, b3DbvtNode* root, b3DbvtNode* leaf) { if(!pdbvt->m_root) { pdbvt->m_root = leaf; leaf->parent = 0; } else { if(!root->isleaf()) { do { root=root->childs[b3Select( leaf->volume, root->childs[0]->volume, root->childs[1]->volume)]; } while(!root->isleaf()); } b3DbvtNode* prev=root->parent; b3DbvtNode* node=b3CreateNode(pdbvt,prev,leaf->volume,root->volume,0); if(prev) { prev->childs[b3IndexOf(root)] = node; node->childs[0] = root;root->parent=node; node->childs[1] = leaf;leaf->parent=node; do { if(!prev->volume.Contain(node->volume)) b3Merge(prev->childs[0]->volume,prev->childs[1]->volume,prev->volume); else break; node=prev; } while(0!=(prev=node->parent)); } else { node->childs[0] = root;root->parent=node; node->childs[1] = leaf;leaf->parent=node; pdbvt->m_root = node; } } } // static b3DbvtNode* b3RemoveLeaf( b3DynamicBvh* pdbvt, b3DbvtNode* leaf) { if(leaf==pdbvt->m_root) { pdbvt->m_root=0; return(0); } else { b3DbvtNode* parent=leaf->parent; b3DbvtNode* prev=parent->parent; b3DbvtNode* sibling=parent->childs[1-b3IndexOf(leaf)]; if(prev) { prev->childs[b3IndexOf(parent)]=sibling; sibling->parent=prev; b3DeleteNode(pdbvt,parent); while(prev) { const b3DbvtVolume pb=prev->volume; b3Merge(prev->childs[0]->volume,prev->childs[1]->volume,prev->volume); if(b3NotEqual(pb,prev->volume)) { prev=prev->parent; } else break; } return(prev?prev:pdbvt->m_root); } else { pdbvt->m_root=sibling; sibling->parent=0; b3DeleteNode(pdbvt,parent); return(pdbvt->m_root); } } } // static void b3FetchLeaves(b3DynamicBvh* pdbvt, b3DbvtNode* root, b3NodeArray& leaves, int depth=-1) { if(root->isinternal()&&depth) { b3FetchLeaves(pdbvt,root->childs[0],leaves,depth-1); b3FetchLeaves(pdbvt,root->childs[1],leaves,depth-1); b3DeleteNode(pdbvt,root); } else { leaves.push_back(root); } } // static void b3Split( const b3NodeArray& leaves, b3NodeArray& left, b3NodeArray& right, const b3Vector3& org, const b3Vector3& axis) { left.resize(0); right.resize(0); for(int i=0,ni=leaves.size();i<ni;++i) { if(b3Dot(axis,leaves[i]->volume.Center()-org)<0) left.push_back(leaves[i]); else right.push_back(leaves[i]); } } // static b3DbvtVolume b3Bounds( const b3NodeArray& leaves) { #if B3_DBVT_MERGE_IMPL==B3_DBVT_IMPL_SSE B3_ATTRIBUTE_ALIGNED16(char locals[sizeof(b3DbvtVolume)]); b3DbvtVolume& volume=*(b3DbvtVolume*)locals; volume=leaves[0]->volume; #else b3DbvtVolume volume=leaves[0]->volume; #endif for(int i=1,ni=leaves.size();i<ni;++i) { b3Merge(volume,leaves[i]->volume,volume); } return(volume); } // static void b3BottomUp( b3DynamicBvh* pdbvt, b3NodeArray& leaves) { while(leaves.size()>1) { b3Scalar minsize=B3_INFINITY; int minidx[2]={-1,-1}; for(int i=0;i<leaves.size();++i) { for(int j=i+1;j<leaves.size();++j) { const b3Scalar sz=b3Size(b3Merge(leaves[i]->volume,leaves[j]->volume)); if(sz<minsize) { minsize = sz; minidx[0] = i; minidx[1] = j; } } } b3DbvtNode* n[] = {leaves[minidx[0]],leaves[minidx[1]]}; b3DbvtNode* p = b3CreateNode(pdbvt,0,n[0]->volume,n[1]->volume,0); p->childs[0] = n[0]; p->childs[1] = n[1]; n[0]->parent = p; n[1]->parent = p; leaves[minidx[0]] = p; leaves.swap(minidx[1],leaves.size()-1); leaves.pop_back(); } } // static b3DbvtNode* b3TopDown(b3DynamicBvh* pdbvt, b3NodeArray& leaves, int bu_treshold) { static const b3Vector3 axis[]={b3MakeVector3(1,0,0), b3MakeVector3(0,1,0), b3MakeVector3(0,0,1)}; if(leaves.size()>1) { if(leaves.size()>bu_treshold) { const b3DbvtVolume vol=b3Bounds(leaves); const b3Vector3 org=vol.Center(); b3NodeArray sets[2]; int bestaxis=-1; int bestmidp=leaves.size(); int splitcount[3][2]={{0,0},{0,0},{0,0}}; int i; for( i=0;i<leaves.size();++i) { const b3Vector3 x=leaves[i]->volume.Center()-org; for(int j=0;j<3;++j) { ++splitcount[j][b3Dot(x,axis[j])>0?1:0]; } } for( i=0;i<3;++i) { if((splitcount[i][0]>0)&&(splitcount[i][1]>0)) { const int midp=(int)b3Fabs(b3Scalar(splitcount[i][0]-splitcount[i][1])); if(midp<bestmidp) { bestaxis=i; bestmidp=midp; } } } if(bestaxis>=0) { sets[0].reserve(splitcount[bestaxis][0]); sets[1].reserve(splitcount[bestaxis][1]); b3Split(leaves,sets[0],sets[1],org,axis[bestaxis]); } else { sets[0].reserve(leaves.size()/2+1); sets[1].reserve(leaves.size()/2); for(int i=0,ni=leaves.size();i<ni;++i) { sets[i&1].push_back(leaves[i]); } } b3DbvtNode* node=b3CreateNode(pdbvt,0,vol,0); node->childs[0]=b3TopDown(pdbvt,sets[0],bu_treshold); node->childs[1]=b3TopDown(pdbvt,sets[1],bu_treshold); node->childs[0]->parent=node; node->childs[1]->parent=node; return(node); } else { b3BottomUp(pdbvt,leaves); return(leaves[0]); } } return(leaves[0]); } // static B3_DBVT_INLINE b3DbvtNode* b3Sort(b3DbvtNode* n,b3DbvtNode*& r) { b3DbvtNode* p=n->parent; b3Assert(n->isinternal()); if(p>n) { const int i=b3IndexOf(n); const int j=1-i; b3DbvtNode* s=p->childs[j]; b3DbvtNode* q=p->parent; b3Assert(n==p->childs[i]); if(q) q->childs[b3IndexOf(p)]=n; else r=n; s->parent=n; p->parent=n; n->parent=q; p->childs[0]=n->childs[0]; p->childs[1]=n->childs[1]; n->childs[0]->parent=p; n->childs[1]->parent=p; n->childs[i]=p; n->childs[j]=s; b3Swap(p->volume,n->volume); return(p); } return(n); } #if 0 static B3_DBVT_INLINE b3DbvtNode* walkup(b3DbvtNode* n,int count) { while(n&&(count--)) n=n->parent; return(n); } #endif // // Api // // b3DynamicBvh::b3DynamicBvh() { m_root = 0; m_free = 0; m_lkhd = -1; m_leaves = 0; m_opath = 0; } // b3DynamicBvh::~b3DynamicBvh() { clear(); } // void b3DynamicBvh::clear() { if(m_root) b3RecurseDeleteNode(this,m_root); b3AlignedFree(m_free); m_free=0; m_lkhd = -1; m_stkStack.clear(); m_opath = 0; } // void b3DynamicBvh::optimizeBottomUp() { if(m_root) { b3NodeArray leaves; leaves.reserve(m_leaves); b3FetchLeaves(this,m_root,leaves); b3BottomUp(this,leaves); m_root=leaves[0]; } } // void b3DynamicBvh::optimizeTopDown(int bu_treshold) { if(m_root) { b3NodeArray leaves; leaves.reserve(m_leaves); b3FetchLeaves(this,m_root,leaves); m_root=b3TopDown(this,leaves,bu_treshold); } } // void b3DynamicBvh::optimizeIncremental(int passes) { if(passes<0) passes=m_leaves; if(m_root&&(passes>0)) { do { b3DbvtNode* node=m_root; unsigned bit=0; while(node->isinternal()) { node=b3Sort(node,m_root)->childs[(m_opath>>bit)&1]; bit=(bit+1)&(sizeof(unsigned)*8-1); } update(node); ++m_opath; } while(--passes); } } // b3DbvtNode* b3DynamicBvh::insert(const b3DbvtVolume& volume,void* data) { b3DbvtNode* leaf=b3CreateNode(this,0,volume,data); b3InsertLeaf(this,m_root,leaf); ++m_leaves; return(leaf); } // void b3DynamicBvh::update(b3DbvtNode* leaf,int lookahead) { b3DbvtNode* root=b3RemoveLeaf(this,leaf); if(root) { if(lookahead>=0) { for(int i=0;(i<lookahead)&&root->parent;++i) { root=root->parent; } } else root=m_root; } b3InsertLeaf(this,root,leaf); } // void b3DynamicBvh::update(b3DbvtNode* leaf,b3DbvtVolume& volume) { b3DbvtNode* root=b3RemoveLeaf(this,leaf); if(root) { if(m_lkhd>=0) { for(int i=0;(i<m_lkhd)&&root->parent;++i) { root=root->parent; } } else root=m_root; } leaf->volume=volume; b3InsertLeaf(this,root,leaf); } // bool b3DynamicBvh::update(b3DbvtNode* leaf,b3DbvtVolume& volume,const b3Vector3& velocity,b3Scalar margin) { if(leaf->volume.Contain(volume)) return(false); volume.Expand(b3MakeVector3(margin,margin,margin)); volume.SignedExpand(velocity); update(leaf,volume); return(true); } // bool b3DynamicBvh::update(b3DbvtNode* leaf,b3DbvtVolume& volume,const b3Vector3& velocity) { if(leaf->volume.Contain(volume)) return(false); volume.SignedExpand(velocity); update(leaf,volume); return(true); } // bool b3DynamicBvh::update(b3DbvtNode* leaf,b3DbvtVolume& volume,b3Scalar margin) { if(leaf->volume.Contain(volume)) return(false); volume.Expand(b3MakeVector3(margin,margin,margin)); update(leaf,volume); return(true); } // void b3DynamicBvh::remove(b3DbvtNode* leaf) { b3RemoveLeaf(this,leaf); b3DeleteNode(this,leaf); --m_leaves; } // void b3DynamicBvh::write(IWriter* iwriter) const { b3DbvtNodeEnumerator nodes; nodes.nodes.reserve(m_leaves*2); enumNodes(m_root,nodes); iwriter->Prepare(m_root,nodes.nodes.size()); for(int i=0;i<nodes.nodes.size();++i) { const b3DbvtNode* n=nodes.nodes[i]; int p=-1; if(n->parent) p=nodes.nodes.findLinearSearch(n->parent); if(n->isinternal()) { const int c0=nodes.nodes.findLinearSearch(n->childs[0]); const int c1=nodes.nodes.findLinearSearch(n->childs[1]); iwriter->WriteNode(n,i,p,c0,c1); } else { iwriter->WriteLeaf(n,i,p); } } } // void b3DynamicBvh::clone(b3DynamicBvh& dest,IClone* iclone) const { dest.clear(); if(m_root!=0) { b3AlignedObjectArray<sStkCLN> stack; stack.reserve(m_leaves); stack.push_back(sStkCLN(m_root,0)); do { const int i=stack.size()-1; const sStkCLN e=stack[i]; b3DbvtNode* n=b3CreateNode(&dest,e.parent,e.node->volume,e.node->data); stack.pop_back(); if(e.parent!=0) e.parent->childs[i&1]=n; else dest.m_root=n; if(e.node->isinternal()) { stack.push_back(sStkCLN(e.node->childs[0],n)); stack.push_back(sStkCLN(e.node->childs[1],n)); } else { iclone->CloneLeaf(n); } } while(stack.size()>0); } } // int b3DynamicBvh::maxdepth(const b3DbvtNode* node) { int depth=0; if(node) b3GetMaxDepth(node,1,depth); return(depth); } // int b3DynamicBvh::countLeaves(const b3DbvtNode* node) { if(node->isinternal()) return(countLeaves(node->childs[0])+countLeaves(node->childs[1])); else return(1); } // void b3DynamicBvh::extractLeaves(const b3DbvtNode* node,b3AlignedObjectArray<const b3DbvtNode*>& leaves) { if(node->isinternal()) { extractLeaves(node->childs[0],leaves); extractLeaves(node->childs[1],leaves); } else { leaves.push_back(node); } } // #if B3_DBVT_ENABLE_BENCHMARK #include <stdio.h> #include <stdlib.h> /* q6600,2.4ghz /Ox /Ob2 /Oi /Ot /I "." /I "..\.." /I "..\..\src" /D "NDEBUG" /D "_LIB" /D "_WINDOWS" /D "_CRT_SECURE_NO_DEPRECATE" /D "_CRT_NONSTDC_NO_DEPRECATE" /D "WIN32" /GF /FD /MT /GS- /Gy /arch:SSE2 /Zc:wchar_t- /Fp"..\..\out\release8\build\libbulletcollision\libbulletcollision.pch" /Fo"..\..\out\release8\build\libbulletcollision\\" /Fd"..\..\out\release8\build\libbulletcollision\bulletcollision.pdb" /W3 /nologo /c /Wp64 /Zi /errorReport:prompt Benchmarking dbvt... World scale: 100.000000 Extents base: 1.000000 Extents range: 4.000000 Leaves: 8192 sizeof(b3DbvtVolume): 32 bytes sizeof(b3DbvtNode): 44 bytes [1] b3DbvtVolume intersections: 3499 ms (-1%) [2] b3DbvtVolume merges: 1934 ms (0%) [3] b3DynamicBvh::collideTT: 5485 ms (-21%) [4] b3DynamicBvh::collideTT self: 2814 ms (-20%) [5] b3DynamicBvh::collideTT xform: 7379 ms (-1%) [6] b3DynamicBvh::collideTT xform,self: 7270 ms (-2%) [7] b3DynamicBvh::rayTest: 6314 ms (0%),(332143 r/s) [8] insert/remove: 2093 ms (0%),(1001983 ir/s) [9] updates (teleport): 1879 ms (-3%),(1116100 u/s) [10] updates (jitter): 1244 ms (-4%),(1685813 u/s) [11] optimize (incremental): 2514 ms (0%),(1668000 o/s) [12] b3DbvtVolume notequal: 3659 ms (0%) [13] culling(OCL+fullsort): 2218 ms (0%),(461 t/s) [14] culling(OCL+qsort): 3688 ms (5%),(2221 t/s) [15] culling(KDOP+qsort): 1139 ms (-1%),(7192 t/s) [16] insert/remove batch(256): 5092 ms (0%),(823704 bir/s) [17] b3DbvtVolume select: 3419 ms (0%) */ struct b3DbvtBenchmark { struct NilPolicy : b3DynamicBvh::ICollide { NilPolicy() : m_pcount(0),m_depth(-B3_INFINITY),m_checksort(true) {} void Process(const b3DbvtNode*,const b3DbvtNode*) { ++m_pcount; } void Process(const b3DbvtNode*) { ++m_pcount; } void Process(const b3DbvtNode*,b3Scalar depth) { ++m_pcount; if(m_checksort) { if(depth>=m_depth) m_depth=depth; else printf("wrong depth: %f (should be >= %f)\r\n",depth,m_depth); } } int m_pcount; b3Scalar m_depth; bool m_checksort; }; struct P14 : b3DynamicBvh::ICollide { struct Node { const b3DbvtNode* leaf; b3Scalar depth; }; void Process(const b3DbvtNode* leaf,b3Scalar depth) { Node n; n.leaf = leaf; n.depth = depth; } static int sortfnc(const Node& a,const Node& b) { if(a.depth<b.depth) return(+1); if(a.depth>b.depth) return(-1); return(0); } b3AlignedObjectArray<Node> m_nodes; }; struct P15 : b3DynamicBvh::ICollide { struct Node { const b3DbvtNode* leaf; b3Scalar depth; }; void Process(const b3DbvtNode* leaf) { Node n; n.leaf = leaf; n.depth = dot(leaf->volume.Center(),m_axis); } static int sortfnc(const Node& a,const Node& b) { if(a.depth<b.depth) return(+1); if(a.depth>b.depth) return(-1); return(0); } b3AlignedObjectArray<Node> m_nodes; b3Vector3 m_axis; }; static b3Scalar RandUnit() { return(rand()/(b3Scalar)RAND_MAX); } static b3Vector3 RandVector3() { return(b3Vector3(RandUnit(),RandUnit(),RandUnit())); } static b3Vector3 RandVector3(b3Scalar cs) { return(RandVector3()*cs-b3Vector3(cs,cs,cs)/2); } static b3DbvtVolume RandVolume(b3Scalar cs,b3Scalar eb,b3Scalar es) { return(b3DbvtVolume::FromCE(RandVector3(cs),b3Vector3(eb,eb,eb)+RandVector3()*es)); } static b3Transform RandTransform(b3Scalar cs) { b3Transform t; t.setOrigin(RandVector3(cs)); t.setRotation(b3Quaternion(RandUnit()*B3_PI*2,RandUnit()*B3_PI*2,RandUnit()*B3_PI*2).normalized()); return(t); } static void RandTree(b3Scalar cs,b3Scalar eb,b3Scalar es,int leaves,b3DynamicBvh& dbvt) { dbvt.clear(); for(int i=0;i<leaves;++i) { dbvt.insert(RandVolume(cs,eb,es),0); } } }; void b3DynamicBvh::benchmark() { static const b3Scalar cfgVolumeCenterScale = 100; static const b3Scalar cfgVolumeExentsBase = 1; static const b3Scalar cfgVolumeExentsScale = 4; static const int cfgLeaves = 8192; static const bool cfgEnable = true; //[1] b3DbvtVolume intersections bool cfgBenchmark1_Enable = cfgEnable; static const int cfgBenchmark1_Iterations = 8; static const int cfgBenchmark1_Reference = 3499; //[2] b3DbvtVolume merges bool cfgBenchmark2_Enable = cfgEnable; static const int cfgBenchmark2_Iterations = 4; static const int cfgBenchmark2_Reference = 1945; //[3] b3DynamicBvh::collideTT bool cfgBenchmark3_Enable = cfgEnable; static const int cfgBenchmark3_Iterations = 512; static const int cfgBenchmark3_Reference = 5485; //[4] b3DynamicBvh::collideTT self bool cfgBenchmark4_Enable = cfgEnable; static const int cfgBenchmark4_Iterations = 512; static const int cfgBenchmark4_Reference = 2814; //[5] b3DynamicBvh::collideTT xform bool cfgBenchmark5_Enable = cfgEnable; static const int cfgBenchmark5_Iterations = 512; static const b3Scalar cfgBenchmark5_OffsetScale = 2; static const int cfgBenchmark5_Reference = 7379; //[6] b3DynamicBvh::collideTT xform,self bool cfgBenchmark6_Enable = cfgEnable; static const int cfgBenchmark6_Iterations = 512; static const b3Scalar cfgBenchmark6_OffsetScale = 2; static const int cfgBenchmark6_Reference = 7270; //[7] b3DynamicBvh::rayTest bool cfgBenchmark7_Enable = cfgEnable; static const int cfgBenchmark7_Passes = 32; static const int cfgBenchmark7_Iterations = 65536; static const int cfgBenchmark7_Reference = 6307; //[8] insert/remove bool cfgBenchmark8_Enable = cfgEnable; static const int cfgBenchmark8_Passes = 32; static const int cfgBenchmark8_Iterations = 65536; static const int cfgBenchmark8_Reference = 2105; //[9] updates (teleport) bool cfgBenchmark9_Enable = cfgEnable; static const int cfgBenchmark9_Passes = 32; static const int cfgBenchmark9_Iterations = 65536; static const int cfgBenchmark9_Reference = 1879; //[10] updates (jitter) bool cfgBenchmark10_Enable = cfgEnable; static const b3Scalar cfgBenchmark10_Scale = cfgVolumeCenterScale/10000; static const int cfgBenchmark10_Passes = 32; static const int cfgBenchmark10_Iterations = 65536; static const int cfgBenchmark10_Reference = 1244; //[11] optimize (incremental) bool cfgBenchmark11_Enable = cfgEnable; static const int cfgBenchmark11_Passes = 64; static const int cfgBenchmark11_Iterations = 65536; static const int cfgBenchmark11_Reference = 2510; //[12] b3DbvtVolume notequal bool cfgBenchmark12_Enable = cfgEnable; static const int cfgBenchmark12_Iterations = 32; static const int cfgBenchmark12_Reference = 3677; //[13] culling(OCL+fullsort) bool cfgBenchmark13_Enable = cfgEnable; static const int cfgBenchmark13_Iterations = 1024; static const int cfgBenchmark13_Reference = 2231; //[14] culling(OCL+qsort) bool cfgBenchmark14_Enable = cfgEnable; static const int cfgBenchmark14_Iterations = 8192; static const int cfgBenchmark14_Reference = 3500; //[15] culling(KDOP+qsort) bool cfgBenchmark15_Enable = cfgEnable; static const int cfgBenchmark15_Iterations = 8192; static const int cfgBenchmark15_Reference = 1151; //[16] insert/remove batch bool cfgBenchmark16_Enable = cfgEnable; static const int cfgBenchmark16_BatchCount = 256; static const int cfgBenchmark16_Passes = 16384; static const int cfgBenchmark16_Reference = 5138; //[17] select bool cfgBenchmark17_Enable = cfgEnable; static const int cfgBenchmark17_Iterations = 4; static const int cfgBenchmark17_Reference = 3390; b3Clock wallclock; printf("Benchmarking dbvt...\r\n"); printf("\tWorld scale: %f\r\n",cfgVolumeCenterScale); printf("\tExtents base: %f\r\n",cfgVolumeExentsBase); printf("\tExtents range: %f\r\n",cfgVolumeExentsScale); printf("\tLeaves: %u\r\n",cfgLeaves); printf("\tsizeof(b3DbvtVolume): %u bytes\r\n",sizeof(b3DbvtVolume)); printf("\tsizeof(b3DbvtNode): %u bytes\r\n",sizeof(b3DbvtNode)); if(cfgBenchmark1_Enable) {// Benchmark 1 srand(380843); b3AlignedObjectArray<b3DbvtVolume> volumes; b3AlignedObjectArray<bool> results; volumes.resize(cfgLeaves); results.resize(cfgLeaves); for(int i=0;i<cfgLeaves;++i) { volumes[i]=b3DbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale); } printf("[1] b3DbvtVolume intersections: "); wallclock.reset(); for(int i=0;i<cfgBenchmark1_Iterations;++i) { for(int j=0;j<cfgLeaves;++j) { for(int k=0;k<cfgLeaves;++k) { results[k]=Intersect(volumes[j],volumes[k]); } } } const int time=(int)wallclock.getTimeMilliseconds(); printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark1_Reference)*100/time); } if(cfgBenchmark2_Enable) {// Benchmark 2 srand(380843); b3AlignedObjectArray<b3DbvtVolume> volumes; b3AlignedObjectArray<b3DbvtVolume> results; volumes.resize(cfgLeaves); results.resize(cfgLeaves); for(int i=0;i<cfgLeaves;++i) { volumes[i]=b3DbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale); } printf("[2] b3DbvtVolume merges: "); wallclock.reset(); for(int i=0;i<cfgBenchmark2_Iterations;++i) { for(int j=0;j<cfgLeaves;++j) { for(int k=0;k<cfgLeaves;++k) { Merge(volumes[j],volumes[k],results[k]); } } } const int time=(int)wallclock.getTimeMilliseconds(); printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark2_Reference)*100/time); } if(cfgBenchmark3_Enable) {// Benchmark 3 srand(380843); b3DynamicBvh dbvt[2]; b3DbvtBenchmark::NilPolicy policy; b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt[0]); b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt[1]); dbvt[0].optimizeTopDown(); dbvt[1].optimizeTopDown(); printf("[3] b3DynamicBvh::collideTT: "); wallclock.reset(); for(int i=0;i<cfgBenchmark3_Iterations;++i) { b3DynamicBvh::collideTT(dbvt[0].m_root,dbvt[1].m_root,policy); } const int time=(int)wallclock.getTimeMilliseconds(); printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark3_Reference)*100/time); } if(cfgBenchmark4_Enable) {// Benchmark 4 srand(380843); b3DynamicBvh dbvt; b3DbvtBenchmark::NilPolicy policy; b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt); dbvt.optimizeTopDown(); printf("[4] b3DynamicBvh::collideTT self: "); wallclock.reset(); for(int i=0;i<cfgBenchmark4_Iterations;++i) { b3DynamicBvh::collideTT(dbvt.m_root,dbvt.m_root,policy); } const int time=(int)wallclock.getTimeMilliseconds(); printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark4_Reference)*100/time); } if(cfgBenchmark5_Enable) {// Benchmark 5 srand(380843); b3DynamicBvh dbvt[2]; b3AlignedObjectArray<b3Transform> transforms; b3DbvtBenchmark::NilPolicy policy; transforms.resize(cfgBenchmark5_Iterations); for(int i=0;i<transforms.size();++i) { transforms[i]=b3DbvtBenchmark::RandTransform(cfgVolumeCenterScale*cfgBenchmark5_OffsetScale); } b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt[0]); b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt[1]); dbvt[0].optimizeTopDown(); dbvt[1].optimizeTopDown(); printf("[5] b3DynamicBvh::collideTT xform: "); wallclock.reset(); for(int i=0;i<cfgBenchmark5_Iterations;++i) { b3DynamicBvh::collideTT(dbvt[0].m_root,dbvt[1].m_root,transforms[i],policy); } const int time=(int)wallclock.getTimeMilliseconds(); printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark5_Reference)*100/time); } if(cfgBenchmark6_Enable) {// Benchmark 6 srand(380843); b3DynamicBvh dbvt; b3AlignedObjectArray<b3Transform> transforms; b3DbvtBenchmark::NilPolicy policy; transforms.resize(cfgBenchmark6_Iterations); for(int i=0;i<transforms.size();++i) { transforms[i]=b3DbvtBenchmark::RandTransform(cfgVolumeCenterScale*cfgBenchmark6_OffsetScale); } b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt); dbvt.optimizeTopDown(); printf("[6] b3DynamicBvh::collideTT xform,self: "); wallclock.reset(); for(int i=0;i<cfgBenchmark6_Iterations;++i) { b3DynamicBvh::collideTT(dbvt.m_root,dbvt.m_root,transforms[i],policy); } const int time=(int)wallclock.getTimeMilliseconds(); printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark6_Reference)*100/time); } if(cfgBenchmark7_Enable) {// Benchmark 7 srand(380843); b3DynamicBvh dbvt; b3AlignedObjectArray<b3Vector3> rayorg; b3AlignedObjectArray<b3Vector3> raydir; b3DbvtBenchmark::NilPolicy policy; rayorg.resize(cfgBenchmark7_Iterations); raydir.resize(cfgBenchmark7_Iterations); for(int i=0;i<rayorg.size();++i) { rayorg[i]=b3DbvtBenchmark::RandVector3(cfgVolumeCenterScale*2); raydir[i]=b3DbvtBenchmark::RandVector3(cfgVolumeCenterScale*2); } b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt); dbvt.optimizeTopDown(); printf("[7] b3DynamicBvh::rayTest: "); wallclock.reset(); for(int i=0;i<cfgBenchmark7_Passes;++i) { for(int j=0;j<cfgBenchmark7_Iterations;++j) { b3DynamicBvh::rayTest(dbvt.m_root,rayorg[j],rayorg[j]+raydir[j],policy); } } const int time=(int)wallclock.getTimeMilliseconds(); unsigned rays=cfgBenchmark7_Passes*cfgBenchmark7_Iterations; printf("%u ms (%i%%),(%u r/s)\r\n",time,(time-cfgBenchmark7_Reference)*100/time,(rays*1000)/time); } if(cfgBenchmark8_Enable) {// Benchmark 8 srand(380843); b3DynamicBvh dbvt; b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt); dbvt.optimizeTopDown(); printf("[8] insert/remove: "); wallclock.reset(); for(int i=0;i<cfgBenchmark8_Passes;++i) { for(int j=0;j<cfgBenchmark8_Iterations;++j) { dbvt.remove(dbvt.insert(b3DbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale),0)); } } const int time=(int)wallclock.getTimeMilliseconds(); const int ir=cfgBenchmark8_Passes*cfgBenchmark8_Iterations; printf("%u ms (%i%%),(%u ir/s)\r\n",time,(time-cfgBenchmark8_Reference)*100/time,ir*1000/time); } if(cfgBenchmark9_Enable) {// Benchmark 9 srand(380843); b3DynamicBvh dbvt; b3AlignedObjectArray<const b3DbvtNode*> leaves; b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt); dbvt.optimizeTopDown(); dbvt.extractLeaves(dbvt.m_root,leaves); printf("[9] updates (teleport): "); wallclock.reset(); for(int i=0;i<cfgBenchmark9_Passes;++i) { for(int j=0;j<cfgBenchmark9_Iterations;++j) { dbvt.update(const_cast<b3DbvtNode*>(leaves[rand()%cfgLeaves]), b3DbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale)); } } const int time=(int)wallclock.getTimeMilliseconds(); const int up=cfgBenchmark9_Passes*cfgBenchmark9_Iterations; printf("%u ms (%i%%),(%u u/s)\r\n",time,(time-cfgBenchmark9_Reference)*100/time,up*1000/time); } if(cfgBenchmark10_Enable) {// Benchmark 10 srand(380843); b3DynamicBvh dbvt; b3AlignedObjectArray<const b3DbvtNode*> leaves; b3AlignedObjectArray<b3Vector3> vectors; vectors.resize(cfgBenchmark10_Iterations); for(int i=0;i<vectors.size();++i) { vectors[i]=(b3DbvtBenchmark::RandVector3()*2-b3Vector3(1,1,1))*cfgBenchmark10_Scale; } b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt); dbvt.optimizeTopDown(); dbvt.extractLeaves(dbvt.m_root,leaves); printf("[10] updates (jitter): "); wallclock.reset(); for(int i=0;i<cfgBenchmark10_Passes;++i) { for(int j=0;j<cfgBenchmark10_Iterations;++j) { const b3Vector3& d=vectors[j]; b3DbvtNode* l=const_cast<b3DbvtNode*>(leaves[rand()%cfgLeaves]); b3DbvtVolume v=b3DbvtVolume::FromMM(l->volume.Mins()+d,l->volume.Maxs()+d); dbvt.update(l,v); } } const int time=(int)wallclock.getTimeMilliseconds(); const int up=cfgBenchmark10_Passes*cfgBenchmark10_Iterations; printf("%u ms (%i%%),(%u u/s)\r\n",time,(time-cfgBenchmark10_Reference)*100/time,up*1000/time); } if(cfgBenchmark11_Enable) {// Benchmark 11 srand(380843); b3DynamicBvh dbvt; b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt); dbvt.optimizeTopDown(); printf("[11] optimize (incremental): "); wallclock.reset(); for(int i=0;i<cfgBenchmark11_Passes;++i) { dbvt.optimizeIncremental(cfgBenchmark11_Iterations); } const int time=(int)wallclock.getTimeMilliseconds(); const int op=cfgBenchmark11_Passes*cfgBenchmark11_Iterations; printf("%u ms (%i%%),(%u o/s)\r\n",time,(time-cfgBenchmark11_Reference)*100/time,op/time*1000); } if(cfgBenchmark12_Enable) {// Benchmark 12 srand(380843); b3AlignedObjectArray<b3DbvtVolume> volumes; b3AlignedObjectArray<bool> results; volumes.resize(cfgLeaves); results.resize(cfgLeaves); for(int i=0;i<cfgLeaves;++i) { volumes[i]=b3DbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale); } printf("[12] b3DbvtVolume notequal: "); wallclock.reset(); for(int i=0;i<cfgBenchmark12_Iterations;++i) { for(int j=0;j<cfgLeaves;++j) { for(int k=0;k<cfgLeaves;++k) { results[k]=NotEqual(volumes[j],volumes[k]); } } } const int time=(int)wallclock.getTimeMilliseconds(); printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark12_Reference)*100/time); } if(cfgBenchmark13_Enable) {// Benchmark 13 srand(380843); b3DynamicBvh dbvt; b3AlignedObjectArray<b3Vector3> vectors; b3DbvtBenchmark::NilPolicy policy; vectors.resize(cfgBenchmark13_Iterations); for(int i=0;i<vectors.size();++i) { vectors[i]=(b3DbvtBenchmark::RandVector3()*2-b3Vector3(1,1,1)).normalized(); } b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt); dbvt.optimizeTopDown(); printf("[13] culling(OCL+fullsort): "); wallclock.reset(); for(int i=0;i<cfgBenchmark13_Iterations;++i) { static const b3Scalar offset=0; policy.m_depth=-B3_INFINITY; dbvt.collideOCL(dbvt.m_root,&vectors[i],&offset,vectors[i],1,policy); } const int time=(int)wallclock.getTimeMilliseconds(); const int t=cfgBenchmark13_Iterations; printf("%u ms (%i%%),(%u t/s)\r\n",time,(time-cfgBenchmark13_Reference)*100/time,(t*1000)/time); } if(cfgBenchmark14_Enable) {// Benchmark 14 srand(380843); b3DynamicBvh dbvt; b3AlignedObjectArray<b3Vector3> vectors; b3DbvtBenchmark::P14 policy; vectors.resize(cfgBenchmark14_Iterations); for(int i=0;i<vectors.size();++i) { vectors[i]=(b3DbvtBenchmark::RandVector3()*2-b3Vector3(1,1,1)).normalized(); } b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt); dbvt.optimizeTopDown(); policy.m_nodes.reserve(cfgLeaves); printf("[14] culling(OCL+qsort): "); wallclock.reset(); for(int i=0;i<cfgBenchmark14_Iterations;++i) { static const b3Scalar offset=0; policy.m_nodes.resize(0); dbvt.collideOCL(dbvt.m_root,&vectors[i],&offset,vectors[i],1,policy,false); policy.m_nodes.quickSort(b3DbvtBenchmark::P14::sortfnc); } const int time=(int)wallclock.getTimeMilliseconds(); const int t=cfgBenchmark14_Iterations; printf("%u ms (%i%%),(%u t/s)\r\n",time,(time-cfgBenchmark14_Reference)*100/time,(t*1000)/time); } if(cfgBenchmark15_Enable) {// Benchmark 15 srand(380843); b3DynamicBvh dbvt; b3AlignedObjectArray<b3Vector3> vectors; b3DbvtBenchmark::P15 policy; vectors.resize(cfgBenchmark15_Iterations); for(int i=0;i<vectors.size();++i) { vectors[i]=(b3DbvtBenchmark::RandVector3()*2-b3Vector3(1,1,1)).normalized(); } b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt); dbvt.optimizeTopDown(); policy.m_nodes.reserve(cfgLeaves); printf("[15] culling(KDOP+qsort): "); wallclock.reset(); for(int i=0;i<cfgBenchmark15_Iterations;++i) { static const b3Scalar offset=0; policy.m_nodes.resize(0); policy.m_axis=vectors[i]; dbvt.collideKDOP(dbvt.m_root,&vectors[i],&offset,1,policy); policy.m_nodes.quickSort(b3DbvtBenchmark::P15::sortfnc); } const int time=(int)wallclock.getTimeMilliseconds(); const int t=cfgBenchmark15_Iterations; printf("%u ms (%i%%),(%u t/s)\r\n",time,(time-cfgBenchmark15_Reference)*100/time,(t*1000)/time); } if(cfgBenchmark16_Enable) {// Benchmark 16 srand(380843); b3DynamicBvh dbvt; b3AlignedObjectArray<b3DbvtNode*> batch; b3DbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt); dbvt.optimizeTopDown(); batch.reserve(cfgBenchmark16_BatchCount); printf("[16] insert/remove batch(%u): ",cfgBenchmark16_BatchCount); wallclock.reset(); for(int i=0;i<cfgBenchmark16_Passes;++i) { for(int j=0;j<cfgBenchmark16_BatchCount;++j) { batch.push_back(dbvt.insert(b3DbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale),0)); } for(int j=0;j<cfgBenchmark16_BatchCount;++j) { dbvt.remove(batch[j]); } batch.resize(0); } const int time=(int)wallclock.getTimeMilliseconds(); const int ir=cfgBenchmark16_Passes*cfgBenchmark16_BatchCount; printf("%u ms (%i%%),(%u bir/s)\r\n",time,(time-cfgBenchmark16_Reference)*100/time,int(ir*1000.0/time)); } if(cfgBenchmark17_Enable) {// Benchmark 17 srand(380843); b3AlignedObjectArray<b3DbvtVolume> volumes; b3AlignedObjectArray<int> results; b3AlignedObjectArray<int> indices; volumes.resize(cfgLeaves); results.resize(cfgLeaves); indices.resize(cfgLeaves); for(int i=0;i<cfgLeaves;++i) { indices[i]=i; volumes[i]=b3DbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale); } for(int i=0;i<cfgLeaves;++i) { b3Swap(indices[i],indices[rand()%cfgLeaves]); } printf("[17] b3DbvtVolume select: "); wallclock.reset(); for(int i=0;i<cfgBenchmark17_Iterations;++i) { for(int j=0;j<cfgLeaves;++j) { for(int k=0;k<cfgLeaves;++k) { const int idx=indices[k]; results[idx]=Select(volumes[idx],volumes[j],volumes[k]); } } } const int time=(int)wallclock.getTimeMilliseconds(); printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark17_Reference)*100/time); } printf("\r\n\r\n"); } #endif
LauriM/PropellerEngine
thirdparty/Bullet/src/Bullet3Collision/BroadPhaseCollision/b3DynamicBvh.cpp
C++
bsd-2-clause
36,826
/*! * Cropper v0.4.0 * https://github.com/fengyuanchen/cropperjs * * Copyright (c) 2015 Fengyuan Chen * Released under the MIT license * * Date: 2015-12-02T06:35:32.008Z */ (function (global, factory) { if (typeof module === 'object' && typeof module.exports === 'object') { module.exports = global.document ? factory(global, true) : function (w) { if (!w.document) { throw new Error('Cropper requires a window with a document'); } return factory(w); }; } else { factory(global); } })(typeof window !== 'undefined' ? window : this, function (window, noGlobal) { 'use strict'; // Globals var document = window.document; var location = window.location; // Constants var NAMESPACE = 'cropper'; // Classes var CLASS_MODAL = 'cropper-modal'; var CLASS_HIDE = 'cropper-hide'; var CLASS_HIDDEN = 'cropper-hidden'; var CLASS_INVISIBLE = 'cropper-invisible'; var CLASS_MOVE = 'cropper-move'; var CLASS_CROP = 'cropper-crop'; var CLASS_DISABLED = 'cropper-disabled'; var CLASS_BG = 'cropper-bg'; // Events var EVENT_MOUSE_DOWN = 'mousedown touchstart pointerdown MSPointerDown'; var EVENT_MOUSE_MOVE = 'mousemove touchmove pointermove MSPointerMove'; var EVENT_MOUSE_UP = 'mouseup touchend touchcancel pointerup pointercancel MSPointerUp MSPointerCancel'; var EVENT_WHEEL = 'wheel mousewheel DOMMouseScroll'; var EVENT_DBLCLICK = 'dblclick'; var EVENT_RESIZE = 'resize'; var EVENT_ERROR = 'error'; var EVENT_LOAD = 'load'; // RegExps var REGEXP_ACTIONS = /^(e|w|s|n|se|sw|ne|nw|all|crop|move|zoom)$/; var REGEXP_SPACES = /\s+/; var REGEXP_TRIM = /^\s+(.*)\s+^/; // Data var DATA_PREVIEW = 'preview'; var DATA_ACTION = 'action'; // Actions var ACTION_EAST = 'e'; var ACTION_WEST = 'w'; var ACTION_SOUTH = 's'; var ACTION_NORTH = 'n'; var ACTION_SOUTH_EAST = 'se'; var ACTION_SOUTH_WEST = 'sw'; var ACTION_NORTH_EAST = 'ne'; var ACTION_NORTH_WEST = 'nw'; var ACTION_ALL = 'all'; var ACTION_CROP = 'crop'; var ACTION_MOVE = 'move'; var ACTION_ZOOM = 'zoom'; var ACTION_NONE = 'none'; // Supports var SUPPORT_CANVAS = !!document.createElement('canvas').getContext; // Maths var num = Number; var min = Math.min; var max = Math.max; var abs = Math.abs; var sin = Math.sin; var cos = Math.cos; var sqrt = Math.sqrt; var round = Math.round; var floor = Math.floor; // Prototype var prototype = { version: '0.4.0' }; // Utilities var EMPTY_OBJECT = {}; var toString = EMPTY_OBJECT.toString; var hasOwnProperty = EMPTY_OBJECT.hasOwnProperty; function typeOf(obj) { return toString.call(obj).slice(8, -1).toLowerCase(); } function isString(str) { return typeof str === 'string'; } function isNumber(num) { return typeof num === 'number' && !isNaN(num); } function isUndefined(obj) { return typeof obj === 'undefined'; } function isObject(obj) { return typeof obj === 'object' && obj !== null; } function isPlainObject(obj) { var constructor; var prototype; if (!isObject(obj)) { return false; } try { constructor = obj.constructor; prototype = constructor.prototype; return constructor && prototype && hasOwnProperty.call(prototype, 'isPrototypeOf'); } catch (e) { return false; } } function isFunction(fn) { return typeOf(fn) === 'function'; } function isArray(arr) { return Array.isArray ? Array.isArray(arr) : typeOf(arr) === 'array'; } function toArray(obj, offset) { var args = []; // This is necessary for IE8 if (isNumber(offset)) { args.push(offset); } return args.slice.apply(obj, args); } function inArray(value, arr) { var index = -1; each(arr, function (n, i) { if (n === value) { index = i; return false; } }); return index; } function trim(str) { if (!isString(str)) { str = String(str); } if (str.trim) { str = str.trim(); } else { str = str.replace(REGEXP_TRIM, '$1'); } return str; } function each(obj, callback) { var length; var i; if (obj && isFunction(callback)) { if (isArray(obj) || isNumber(obj.length)/* array-like */) { for (i = 0, length = obj.length; i < length; i++) { if (callback.call(obj, obj[i], i, obj) === false) { break; } } } else if (isObject(obj)) { for (i in obj) { if (hasOwnProperty.call(obj, i)) { if (callback.call(obj, obj[i], i, obj) === false) { break; } } } } } return obj; } function extend(obj) { var args = toArray(arguments); if (args.length > 1) { args.shift(); } each(args, function (arg) { each(arg, function (prop, i) { obj[i] = prop; }); }); return obj; } function proxy(fn, context) { var args = toArray(arguments, 2); return function () { return fn.apply(context, args.concat(toArray(arguments))); }; } function parseClass(className) { return trim(className).split(REGEXP_SPACES); } function hasClass(element, value) { return element.className.indexOf(value) > -1; } function addClass(element, value) { var classes; if (isNumber(element.length)) { return each(element, function (elem) { addClass(elem, value); }); } classes = parseClass(element.className); each(parseClass(value), function (n) { if (inArray(n, classes) < 0) { classes.push(n); } }); element.className = classes.join(' '); } function removeClass(element, value) { var classes; if (isNumber(element.length)) { return each(element, function (elem) { removeClass(elem, value); }); } classes = parseClass(element.className); each(parseClass(value), function (n, i) { if ((i = inArray(n, classes)) > -1) { classes.splice(i, 1); } }); element.className = classes.join(' '); } function toggleClass(element, value, added) { return added ? addClass(element, value) : removeClass(element, value); } function getData(element, name) { if (isObject(element[name])) { return element[name]; } else if (element.dataset) { return element.dataset[name]; } else { return element.getAttribute('data-' + name); } } function setData(element, name, data) { if (isObject(data) && isUndefined(element[name])) { element[name] = data; } else if (element.dataset) { element.dataset[name] = data; } else { element.setAttribute('data-' + name, data); } } function removeData(element, name) { if (isObject(element[name])) { delete element[name]; } else if (element.dataset) { delete element.dataset[name]; } else { element.removeAttribute('data-' + name); } } function addListener(element, type, handler) { var types; if (!isFunction(handler)) { return; } types = trim(type).split(REGEXP_SPACES); if (types.length > 1) { return each(types, function (type) { addListener(element, type, handler); }); } if (element.addEventListener) { element.addEventListener(type, handler, false); } else if (element.attachEvent) { element.attachEvent('on' + type, handler); } } function removeListener(element, type, handler) { var types; if (!isFunction(handler)) { return; } types = trim(type).split(REGEXP_SPACES); if (types.length > 1) { return each(types, function (type) { removeListener(element, type, handler); }); } if (element.removeEventListener) { element.removeEventListener(type, handler, false); } else if (element.detachEvent) { element.detachEvent('on' + type, handler); } } function preventDefault(e) { if (e) { if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } } } function getEvent(event) { var e = event || window.event; var doc; // Fix target property (IE8) if (!e.target) { e.target = e.srcElement || document; } if (!isNumber(e.pageX)) { doc = document.documentElement; e.pageX = e.clientX + (window.scrollX || doc && doc.scrollLeft || 0) - (doc && doc.clientLeft || 0); e.pageY = e.clientY + (window.scrollY || doc && doc.scrollTop || 0) - (doc && doc.clientTop || 0); } return e; } function getOffset(element) { var doc = document.documentElement; var box = element.getBoundingClientRect(); return { left: box.left + (window.scrollX || doc && doc.scrollLeft || 0) - (doc && doc.clientLeft || 0), top: box.top + (window.scrollY || doc && doc.scrollTop || 0) - (doc && doc.clientTop || 0) }; } function querySelector(element, selector) { return element.querySelector(selector); } function querySelectorAll(element, selector) { return element.querySelectorAll(selector); } function insertBefore(element, elem) { element.parentNode.insertBefore(elem, element); } function appendChild(element, elem) { element.appendChild(elem); } function removeChild(element) { element.parentNode.removeChild(element); } function empty(element) { while (element.firstChild) { element.removeChild(element.firstChild); } } function isCrossOriginURL(url) { var parts = url.match(/^(https?:)\/\/([^\:\/\?#]+):?(\d*)/i); return parts && ( parts[1] !== location.protocol || parts[2] !== location.hostname || parts[3] !== location.port ); } function setCrossOrigin(image, crossOrigin) { if (crossOrigin) { image.crossOrigin = crossOrigin; } } function addTimestamp(url) { var timestamp = 'timestamp=' + (new Date()).getTime(); return (url + (url.indexOf('?') === -1 ? '?' : '&') + timestamp); } function getImageSize(image, callback) { var newImage; // Modern browsers if (image.naturalWidth) { return callback(image.naturalWidth, image.naturalHeight); } // IE8: Don't use `new Image()` here newImage = document.createElement('img'); newImage.onload = function () { callback(this.width, this.height); }; newImage.src = image.src; } function getTransform(options) { var transforms = []; var rotate = options.rotate; var scaleX = options.scaleX; var scaleY = options.scaleY; if (isNumber(rotate)) { transforms.push('rotate(' + rotate + 'deg)'); } if (isNumber(scaleX) && isNumber(scaleY)) { transforms.push('scale(' + scaleX + ',' + scaleY + ')'); } return transforms.length ? transforms.join(' ') : 'none'; } function getRotatedSizes(data, isReversed) { var deg = abs(data.degree) % 180; var arc = (deg > 90 ? (180 - deg) : deg) * Math.PI / 180; var sinArc = sin(arc); var cosArc = cos(arc); var width = data.width; var height = data.height; var aspectRatio = data.aspectRatio; var newWidth; var newHeight; if (!isReversed) { newWidth = width * cosArc + height * sinArc; newHeight = width * sinArc + height * cosArc; } else { newWidth = width / (cosArc + sinArc / aspectRatio); newHeight = newWidth / aspectRatio; } return { width: newWidth, height: newHeight }; } function getSourceCanvas(image, data) { var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); var x = 0; var y = 0; var width = data.naturalWidth; var height = data.naturalHeight; var rotate = data.rotate; var scaleX = data.scaleX; var scaleY = data.scaleY; var scalable = isNumber(scaleX) && isNumber(scaleY) && (scaleX !== 1 || scaleY !== 1); var rotatable = isNumber(rotate) && rotate !== 0; var advanced = rotatable || scalable; var canvasWidth = width; var canvasHeight = height; var translateX; var translateY; var rotated; if (scalable) { translateX = width / 2; translateY = height / 2; } if (rotatable) { rotated = getRotatedSizes({ width: width, height: height, degree: rotate }); canvasWidth = rotated.width; canvasHeight = rotated.height; translateX = rotated.width / 2; translateY = rotated.height / 2; } canvas.width = canvasWidth; canvas.height = canvasHeight; if (advanced) { x = -width / 2; y = -height / 2; context.save(); context.translate(translateX, translateY); } if (rotatable) { context.rotate(rotate * Math.PI / 180); } // Should call `scale` after rotated if (scalable) { context.scale(scaleX, scaleY); } context.drawImage(image, floor(x), floor(y), floor(width), floor(height)); if (advanced) { context.restore(); } return canvas; } function Cropper(element, options) { this.element = element; this.options = extend({}, Cropper.DEFAULTS, isPlainObject(options) && options); this.isLoaded = false; this.isBuilt = false; this.isCompleted = false; this.isRotated = false; this.isCropped = false; this.isDisabled = false; this.isReplaced = false; this.isLimited = false; this.isImg = false; this.originalUrl = ''; this.crossOrigin = ''; this.canvasData = null; this.cropBoxData = null; this.previews = null; this.init(); } extend(prototype, { init: function () { var element = this.element; var tagName = element.tagName.toLowerCase(); var url; if (getData(element, NAMESPACE)) { return; } setData(element, NAMESPACE, this); if (tagName === 'img') { this.isImg = true; // e.g.: "img/picture.jpg" this.originalUrl = url = element.getAttribute('src'); // Stop when it's a blank image if (!url) { return; } // e.g.: "http://example.com/img/picture.jpg" url = element.src; } else if (tagName === 'canvas' && SUPPORT_CANVAS) { url = element.toDataURL(); } this.load(url); }, load: function (url) { var options = this.options; var element = this.element; var crossOrigin; var bustCacheUrl; var image; var start; var stop; if (!url) { return; } this.url = url; if (isFunction(options.build) && options.build.call(element) === false) { return; } if (options.checkCrossOrigin && isCrossOriginURL(url)) { crossOrigin = element.crossOrigin; if (!crossOrigin) { crossOrigin = 'anonymous'; bustCacheUrl = addTimestamp(url); } } this.crossOrigin = crossOrigin; image = document.createElement('img'); setCrossOrigin(image, crossOrigin); image.src = bustCacheUrl || url; this.image = image; this._start = start = proxy(this.start, this); this._stop = stop = proxy(this.stop, this); if (this.isImg) { if (element.complete) { this.start(); } else { addListener(element, EVENT_LOAD, start); } } else { addListener(image, EVENT_LOAD, start); addListener(image, EVENT_ERROR, stop); addClass(image, CLASS_HIDE); insertBefore(element, image); } }, start: function (event) { var image = this.isImg ? this.element : this.image; if (event) { removeListener(image, EVENT_LOAD, this._start); removeListener(image, EVENT_ERROR, this._stop); } getImageSize(image, proxy(function (naturalWidth, naturalHeight) { this.imageData = { naturalWidth: naturalWidth, naturalHeight: naturalHeight, aspectRatio: naturalWidth / naturalHeight }; this.isLoaded = true; this.build(); }, this)); }, stop: function () { var image = this.image; removeListener(image, EVENT_LOAD, this._start); removeListener(image, EVENT_ERROR, this._stop); removeChild(image); this.image = null; } }); extend(prototype, { build: function () { var options = this.options; var element = this.element; var image = this.image; var template; var cropper; var canvas; var dragBox; var cropBox; var face; if (!this.isLoaded) { return; } // Unbuild first when replace if (this.isBuilt) { this.unbuild(); } template = document.createElement('div'); template.innerHTML = Cropper.TEMPLATE; // Create cropper elements this.container = element.parentNode; this.cropper = cropper = querySelector(template, '.cropper-container'); this.canvas = canvas = querySelector(cropper, '.cropper-canvas'); this.dragBox = dragBox = querySelector(cropper, '.cropper-drag-box'); this.cropBox = cropBox = querySelector(cropper, '.cropper-crop-box'); this.viewBox = querySelector(cropper, '.cropper-view-box'); this.face = face = querySelector(cropBox, '.cropper-face'); appendChild(canvas, image); // Hide the original image addClass(element, CLASS_HIDDEN); insertBefore(element, cropper); // Show the image if is hidden if (!this.isImg) { removeClass(image, CLASS_HIDE); } this.initPreview(); this.bind(); options.aspectRatio = max(0, options.aspectRatio) || NaN; options.viewMode = max(0, min(3, round(options.viewMode))) || 0; if (options.autoCrop) { this.isCropped = true; if (options.modal) { addClass(dragBox, CLASS_MODAL); } } else { addClass(cropBox, CLASS_HIDDEN); } if (!options.guides) { addClass(querySelectorAll(cropBox, '.cropper-dashed'), CLASS_HIDDEN); } if (!options.center) { addClass(querySelector(cropBox, '.cropper-center'), CLASS_HIDDEN); } if (options.background) { addClass(cropper, CLASS_BG); } if (!options.highlight) { addClass(face, CLASS_INVISIBLE); } if (options.cropBoxMovable) { addClass(face, CLASS_MOVE); setData(face, DATA_ACTION, ACTION_ALL); } if (!options.cropBoxResizable) { addClass(querySelectorAll(cropBox, '.cropper-line'), CLASS_HIDDEN); addClass(querySelectorAll(cropBox, '.cropper-point'), CLASS_HIDDEN); } this.setDragMode(options.dragMode); this.render(); this.isBuilt = true; this.setData(options.data); // Call the built asynchronously to keep "image.cropper" is defined setTimeout(proxy(function () { if (isFunction(options.built)) { options.built.call(element); } if (isFunction(options.crop)) { options.crop.call(element, this.getData()); } this.isCompleted = true; }, this), 0); }, unbuild: function () { if (!this.isBuilt) { return; } this.isBuilt = false; this.initialImageData = null; // Clear `initialCanvasData` is necessary when replace this.initialCanvasData = null; this.initialCropBoxData = null; this.containerData = null; this.canvasData = null; // Clear `cropBoxData` is necessary when replace this.cropBoxData = null; this.unbind(); this.resetPreview(); this.previews = null; this.viewBox = null; this.cropBox = null; this.dragBox = null; this.canvas = null; this.container = null; removeChild(this.cropper); this.cropper = null; } }); extend(prototype, { render: function () { this.initContainer(); this.initCanvas(); this.initCropBox(); this.renderCanvas(); if (this.isCropped) { this.renderCropBox(); } }, initContainer: function () { var options = this.options; var element = this.element; var container = this.container; var cropper = this.cropper; var containerData; addClass(cropper, CLASS_HIDDEN); removeClass(element, CLASS_HIDDEN); this.containerData = containerData = { width: max(container.offsetWidth, num(options.minContainerWidth) || 200), height: max(container.offsetHeight, num(options.minContainerHeight) || 100) }; cropper.style.cssText = ( 'width:' + containerData.width + 'px;' + 'height:' + containerData.height + 'px;' ); addClass(element, CLASS_HIDDEN); removeClass(cropper, CLASS_HIDDEN); }, // Canvas (image wrapper) initCanvas: function () { var viewMode = this.options.viewMode; var containerData = this.containerData; var containerWidth = containerData.width; var containerHeight = containerData.height; var imageData = this.imageData; var aspectRatio = imageData.aspectRatio; var canvasData = { naturalWidth: imageData.naturalWidth, naturalHeight: imageData.naturalHeight, aspectRatio: aspectRatio, width: containerWidth, height: containerHeight }; if (containerHeight * aspectRatio > containerWidth) { if (viewMode === 3) { canvasData.width = containerHeight * aspectRatio; } else { canvasData.height = containerWidth / aspectRatio; } } else { if (viewMode === 3) { canvasData.height = containerWidth / aspectRatio; } else { canvasData.width = containerHeight * aspectRatio; } } canvasData.oldLeft = canvasData.left = (containerWidth - canvasData.width) / 2; canvasData.oldTop = canvasData.top = (containerHeight - canvasData.height) / 2; this.canvasData = canvasData; this.isLimited = (viewMode === 1 || viewMode === 2); this.limitCanvas(true, true); this.initialImageData = extend({}, imageData); this.initialCanvasData = extend({}, canvasData); }, limitCanvas: function (isSizeLimited, isPositionLimited) { var options = this.options; var viewMode = options.viewMode; var containerData = this.containerData; var containerWidth = containerData.width; var containerHeight = containerData.height; var canvasData = this.canvasData; var aspectRatio = canvasData.aspectRatio; var cropBoxData = this.cropBoxData; var isCropped = this.isCropped && cropBoxData; var minCanvasWidth; var minCanvasHeight; var newCanvasLeft; var newCanvasTop; if (isSizeLimited) { minCanvasWidth = num(options.minCanvasWidth) || 0; minCanvasHeight = num(options.minCanvasHeight) || 0; if (viewMode) { if (viewMode > 1) { minCanvasWidth = max(minCanvasWidth, containerWidth); minCanvasHeight = max(minCanvasHeight, containerHeight); if (viewMode === 3) { if (minCanvasHeight * aspectRatio > minCanvasWidth) { minCanvasWidth = minCanvasHeight * aspectRatio; } else { minCanvasHeight = minCanvasWidth / aspectRatio; } } } else { if (minCanvasWidth) { minCanvasWidth = max(minCanvasWidth, isCropped ? cropBoxData.width : 0); } else if (minCanvasHeight) { minCanvasHeight = max(minCanvasHeight, isCropped ? cropBoxData.height : 0); } else if (isCropped) { minCanvasWidth = cropBoxData.width; minCanvasHeight = cropBoxData.height; if (minCanvasHeight * aspectRatio > minCanvasWidth) { minCanvasWidth = minCanvasHeight * aspectRatio; } else { minCanvasHeight = minCanvasWidth / aspectRatio; } } } } if (minCanvasWidth && minCanvasHeight) { if (minCanvasHeight * aspectRatio > minCanvasWidth) { minCanvasHeight = minCanvasWidth / aspectRatio; } else { minCanvasWidth = minCanvasHeight * aspectRatio; } } else if (minCanvasWidth) { minCanvasHeight = minCanvasWidth / aspectRatio; } else if (minCanvasHeight) { minCanvasWidth = minCanvasHeight * aspectRatio; } canvasData.minWidth = minCanvasWidth; canvasData.minHeight = minCanvasHeight; canvasData.maxWidth = Infinity; canvasData.maxHeight = Infinity; } if (isPositionLimited) { if (viewMode) { newCanvasLeft = containerWidth - canvasData.width; newCanvasTop = containerHeight - canvasData.height; canvasData.minLeft = min(0, newCanvasLeft); canvasData.minTop = min(0, newCanvasTop); canvasData.maxLeft = max(0, newCanvasLeft); canvasData.maxTop = max(0, newCanvasTop); if (isCropped && this.isLimited) { canvasData.minLeft = min( cropBoxData.left, cropBoxData.left + cropBoxData.width - canvasData.width ); canvasData.minTop = min( cropBoxData.top, cropBoxData.top + cropBoxData.height - canvasData.height ); canvasData.maxLeft = cropBoxData.left; canvasData.maxTop = cropBoxData.top; if (viewMode === 2) { if (canvasData.width >= containerWidth) { canvasData.minLeft = min(0, newCanvasLeft); canvasData.maxLeft = max(0, newCanvasLeft); } if (canvasData.height >= containerHeight) { canvasData.minTop = min(0, newCanvasTop); canvasData.maxTop = max(0, newCanvasTop); } } } } else { canvasData.minLeft = -canvasData.width; canvasData.minTop = -canvasData.height; canvasData.maxLeft = containerWidth; canvasData.maxTop = containerHeight; } } }, renderCanvas: function (isChanged) { var canvasData = this.canvasData; var imageData = this.imageData; var rotate = imageData.rotate; var naturalWidth = imageData.naturalWidth; var naturalHeight = imageData.naturalHeight; var aspectRatio; var rotatedData; if (this.isRotated) { this.isRotated = false; // Computes rotated sizes with image sizes rotatedData = getRotatedSizes({ width: imageData.width, height: imageData.height, degree: rotate }); aspectRatio = rotatedData.width / rotatedData.height; if (aspectRatio !== canvasData.aspectRatio) { canvasData.left -= (rotatedData.width - canvasData.width) / 2; canvasData.top -= (rotatedData.height - canvasData.height) / 2; canvasData.width = rotatedData.width; canvasData.height = rotatedData.height; canvasData.aspectRatio = aspectRatio; canvasData.naturalWidth = naturalWidth; canvasData.naturalHeight = naturalHeight; // Computes rotated sizes with natural image sizes if (rotate % 180) { rotatedData = getRotatedSizes({ width: naturalWidth, height: naturalHeight, degree: rotate }); canvasData.naturalWidth = rotatedData.width; canvasData.naturalHeight = rotatedData.height; } this.limitCanvas(true, false); } } if (canvasData.width > canvasData.maxWidth || canvasData.width < canvasData.minWidth) { canvasData.left = canvasData.oldLeft; } if (canvasData.height > canvasData.maxHeight || canvasData.height < canvasData.minHeight) { canvasData.top = canvasData.oldTop; } canvasData.width = min( max(canvasData.width, canvasData.minWidth), canvasData.maxWidth ); canvasData.height = min( max(canvasData.height, canvasData.minHeight), canvasData.maxHeight ); this.limitCanvas(false, true); canvasData.oldLeft = canvasData.left = min( max(canvasData.left, canvasData.minLeft), canvasData.maxLeft ); canvasData.oldTop = canvasData.top = min( max(canvasData.top, canvasData.minTop), canvasData.maxTop ); this.canvas.style.cssText = ( 'width:' + canvasData.width + 'px;' + 'height:' + canvasData.height + 'px;' + 'left:' + canvasData.left + 'px;' + 'top:' + canvasData.top + 'px;' ); this.renderImage(); if (this.isCropped && this.isLimited) { this.limitCropBox(true, true); } if (isChanged) { this.output(); } }, renderImage: function (isChanged) { var canvasData = this.canvasData; var imageData = this.imageData; var reversedData; var transform; if (imageData.rotate) { reversedData = getRotatedSizes({ width: canvasData.width, height: canvasData.height, degree: imageData.rotate, aspectRatio: imageData.aspectRatio }, true); } extend(imageData, reversedData ? { width: reversedData.width, height: reversedData.height, left: (canvasData.width - reversedData.width) / 2, top: (canvasData.height - reversedData.height) / 2 } : { width: canvasData.width, height: canvasData.height, left: 0, top: 0 }); transform = getTransform(imageData); this.image.style.cssText = ( 'width:' + imageData.width + 'px;' + 'height:' + imageData.height + 'px;' + 'margin-left:' + imageData.left + 'px;' + 'margin-top:' + imageData.top + 'px;' + '-webkit-transform:' + transform + ';' + '-ms-transform:' + transform + ';' + 'transform:' + transform + ';' ); if (isChanged) { this.output(); } }, initCropBox: function () { var options = this.options; var aspectRatio = options.aspectRatio; var autoCropArea = num(options.autoCropArea) || 0.8; var canvasData = this.canvasData; var cropBoxData = { width: canvasData.width, height: canvasData.height }; if (aspectRatio) { if (canvasData.height * aspectRatio > canvasData.width) { cropBoxData.height = cropBoxData.width / aspectRatio; } else { cropBoxData.width = cropBoxData.height * aspectRatio; } } this.cropBoxData = cropBoxData; this.limitCropBox(true, true); // Initialize auto crop area cropBoxData.width = min( max(cropBoxData.width, cropBoxData.minWidth), cropBoxData.maxWidth ); cropBoxData.height = min( max(cropBoxData.height, cropBoxData.minHeight), cropBoxData.maxHeight ); // The width/height of auto crop area must large than "minWidth/Height" cropBoxData.width = max( cropBoxData.minWidth, cropBoxData.width * autoCropArea ); cropBoxData.height = max( cropBoxData.minHeight, cropBoxData.height * autoCropArea ); cropBoxData.oldLeft = cropBoxData.left = canvasData.left + (canvasData.width - cropBoxData.width) / 2; cropBoxData.oldTop = cropBoxData.top = canvasData.top + (canvasData.height - cropBoxData.height) / 2; this.initialCropBoxData = extend({}, cropBoxData); }, limitCropBox: function (isSizeLimited, isPositionLimited) { var options = this.options; var aspectRatio = options.aspectRatio; var containerData = this.containerData; var containerWidth = containerData.width; var containerHeight = containerData.height; var canvasData = this.canvasData; var cropBoxData = this.cropBoxData; var isLimited = this.isLimited; var minCropBoxWidth; var minCropBoxHeight; var maxCropBoxWidth; var maxCropBoxHeight; if (isSizeLimited) { minCropBoxWidth = num(options.minCropBoxWidth) || 0; minCropBoxHeight = num(options.minCropBoxHeight) || 0; // The min/maxCropBoxWidth/Height must be less than containerWidth/Height minCropBoxWidth = min(minCropBoxWidth, containerWidth); minCropBoxHeight = min(minCropBoxHeight, containerHeight); maxCropBoxWidth = min(containerWidth, isLimited ? canvasData.width : containerWidth); maxCropBoxHeight = min(containerHeight, isLimited ? canvasData.height : containerHeight); if (aspectRatio) { if (minCropBoxWidth && minCropBoxHeight) { if (minCropBoxHeight * aspectRatio > minCropBoxWidth) { minCropBoxHeight = minCropBoxWidth / aspectRatio; } else { minCropBoxWidth = minCropBoxHeight * aspectRatio; } } else if (minCropBoxWidth) { minCropBoxHeight = minCropBoxWidth / aspectRatio; } else if (minCropBoxHeight) { minCropBoxWidth = minCropBoxHeight * aspectRatio; } if (maxCropBoxHeight * aspectRatio > maxCropBoxWidth) { maxCropBoxHeight = maxCropBoxWidth / aspectRatio; } else { maxCropBoxWidth = maxCropBoxHeight * aspectRatio; } } // The minWidth/Height must be less than maxWidth/Height cropBoxData.minWidth = min(minCropBoxWidth, maxCropBoxWidth); cropBoxData.minHeight = min(minCropBoxHeight, maxCropBoxHeight); cropBoxData.maxWidth = maxCropBoxWidth; cropBoxData.maxHeight = maxCropBoxHeight; } if (isPositionLimited) { if (isLimited) { cropBoxData.minLeft = max(0, canvasData.left); cropBoxData.minTop = max(0, canvasData.top); cropBoxData.maxLeft = min(containerWidth, canvasData.left + canvasData.width) - cropBoxData.width; cropBoxData.maxTop = min(containerHeight, canvasData.top + canvasData.height) - cropBoxData.height; } else { cropBoxData.minLeft = 0; cropBoxData.minTop = 0; cropBoxData.maxLeft = containerWidth - cropBoxData.width; cropBoxData.maxTop = containerHeight - cropBoxData.height; } } }, renderCropBox: function () { var options = this.options; var containerData = this.containerData; var containerWidth = containerData.width; var containerHeight = containerData.height; var cropBoxData = this.cropBoxData; if (cropBoxData.width > cropBoxData.maxWidth || cropBoxData.width < cropBoxData.minWidth) { cropBoxData.left = cropBoxData.oldLeft; } if (cropBoxData.height > cropBoxData.maxHeight || cropBoxData.height < cropBoxData.minHeight) { cropBoxData.top = cropBoxData.oldTop; } cropBoxData.width = min( max(cropBoxData.width, cropBoxData.minWidth), cropBoxData.maxWidth ); cropBoxData.height = min( max(cropBoxData.height, cropBoxData.minHeight), cropBoxData.maxHeight ); this.limitCropBox(false, true); cropBoxData.oldLeft = cropBoxData.left = min( max(cropBoxData.left, cropBoxData.minLeft), cropBoxData.maxLeft ); cropBoxData.oldTop = cropBoxData.top = min( max(cropBoxData.top, cropBoxData.minTop), cropBoxData.maxTop ); if (options.movable && options.cropBoxDataMovable) { // Turn to move the canvas when the crop box is equal to the container setData(this.face, DATA_ACTION, (cropBoxData.width === containerWidth && cropBoxData.height === containerHeight) ? ACTION_MOVE : ACTION_ALL); } this.cropBox.style.cssText = ( 'width:' + cropBoxData.width + 'px;' + 'height:' + cropBoxData.height + 'px;' + 'left:' + cropBoxData.left + 'px;' + 'top:' + cropBoxData.top + 'px;' ); if (this.isCropped && this.isLimited) { this.limitCanvas(true, true); } if (!this.isDisabled) { this.output(); } }, output: function () { var options = this.options; this.preview(); if (this.isCompleted && isFunction(options.crop)) { options.crop.call(this.element, this.getData()); } } }); extend(prototype, { initPreview: function () { var preview = this.options.preview; var image = document.createElement('img'); var crossOrigin = this.crossOrigin; var url = this.url; var previews; setCrossOrigin(image, crossOrigin); image.src = url; appendChild(this.viewBox, image); if (!preview) { return; } this.previews = previews = querySelectorAll(document, preview); each(previews, function (element) { var image = document.createElement('img'); // Save the original size for recover setData(element, DATA_PREVIEW, { width: element.offsetWidth, height: element.offsetHeight, html: element.innerHTML }); setCrossOrigin(image, crossOrigin); image.src = url; /** * Override img element styles * Add `display:block` to avoid margin top issue * Add `height:auto` to override `height` attribute on IE8 * (Occur only when margin-top <= -height) */ image.style.cssText = ( 'display:block;width:100%;height:auto;' + 'min-width:0!important;min-height:0!important;' + 'max-width:none!important;max-height:none!important;' + 'image-orientation:0deg!important;"' ); empty(element); appendChild(element, image); }); }, resetPreview: function () { each(this.previews, function (element) { var data = getData(element, DATA_PREVIEW); element.style.width = data.width + 'px'; element.style.height = data.height + 'px'; element.innerHTML = data.html; removeData(element, DATA_PREVIEW); }); }, preview: function () { var imageData = this.imageData; var canvasData = this.canvasData; var cropBoxData = this.cropBoxData; var cropBoxWidth = cropBoxData.width; var cropBoxHeight = cropBoxData.height; var width = imageData.width; var height = imageData.height; var left = cropBoxData.left - canvasData.left - imageData.left; var top = cropBoxData.top - canvasData.top - imageData.top; var transform = getTransform(imageData); if (!this.isCropped || this.isDisabled) { return; } querySelector(this.viewBox, 'img').style.cssText = ( 'width:' + width + 'px;' + 'height:' + height + 'px;' + 'margin-left:' + -left + 'px;' + 'margin-top:' + -top + 'px;' + '-webkit-transform:' + transform + ';' + '-ms-transform:' + transform + ';' + 'transform:' + transform + ';' ); each(this.previews, function (element) { var imageStyle = querySelector(element, 'img').style; var data = getData(element, DATA_PREVIEW); var originalWidth = data.width; var originalHeight = data.height; var newWidth = originalWidth; var newHeight = originalHeight; var ratio = 1; if (cropBoxWidth) { ratio = originalWidth / cropBoxWidth; newHeight = cropBoxHeight * ratio; } if (cropBoxHeight && newHeight > originalHeight) { ratio = originalHeight / cropBoxHeight; newWidth = cropBoxWidth * ratio; newHeight = originalHeight; } element.style.width = newWidth + 'px'; element.style.height = newHeight + 'px'; imageStyle.width = width * ratio + 'px'; imageStyle.height = height * ratio + 'px'; imageStyle.marginLeft = -left * ratio + 'px'; imageStyle.marginTop = -top * ratio + 'px'; imageStyle.WebkitTransform = transform; imageStyle.msTransform = transform; imageStyle.transform = transform; }); } }); extend(prototype, { bind: function () { var options = this.options; var cropper = this.cropper; addListener(cropper, EVENT_MOUSE_DOWN, proxy(this.cropStart, this)); if (options.zoomable && options.zoomOnWheel) { addListener(cropper, EVENT_WHEEL, proxy(this.wheel, this)); } if (options.toggleDragModeOnDblclick) { addListener(cropper, EVENT_DBLCLICK, proxy(this.dblclick, this)); } addListener(document, EVENT_MOUSE_MOVE, (this._cropMove = proxy(this.cropMove, this))); addListener(document, EVENT_MOUSE_UP, (this._cropEnd = proxy(this.cropEnd, this))); if (options.responsive) { addListener(window, EVENT_RESIZE, (this._resize = proxy(this.resize, this))); } }, unbind: function () { var options = this.options; var cropper = this.cropper; removeListener(cropper, EVENT_MOUSE_DOWN, this.cropStart); if (options.zoomable && options.zoomOnWheel) { removeListener(cropper, EVENT_WHEEL, this.wheel); } if (options.toggleDragModeOnDblclick) { removeListener(cropper, EVENT_DBLCLICK, this.dblclick); } removeListener(document, EVENT_MOUSE_MOVE, this._cropMove); removeListener(document, EVENT_MOUSE_UP, this._cropEnd); if (options.responsive) { removeListener(window, EVENT_RESIZE, this._resize); } } }); extend(prototype, { resize: function () { var restore = this.options.restore; var container = this.container; var containerData = this.containerData; var canvasData; var cropBoxData; var ratio; // Check `container` is necessary for IE8 if (this.isDisabled || !containerData) { return; } ratio = container.offsetWidth / containerData.width; // Resize when width changed or height changed if (ratio !== 1 || container.offsetHeight !== containerData.height) { if (restore) { canvasData = this.getCanvasData(); cropBoxData = this.getCropBoxData(); } this.render(); if (restore) { this.setCanvasData(each(canvasData, function (n, i) { canvasData[i] = n * ratio; })); this.setCropBoxData(each(cropBoxData, function (n, i) { cropBoxData[i] = n * ratio; })); } } }, dblclick: function () { if (this.isDisabled) { return; } this.setDragMode(hasClass(this.dragBox, CLASS_CROP) ? ACTION_MOVE : ACTION_CROP); }, wheel: function (event) { var e = getEvent(event); var ratio = num(this.options.wheelZoomRatio) || 0.1; var delta = 1; if (this.isDisabled) { return; } preventDefault(e); if (e.deltaY) { delta = e.deltaY > 0 ? 1 : -1; } else if (e.wheelDelta) { delta = -e.wheelDelta / 120; } else if (e.detail) { delta = e.detail > 0 ? 1 : -1; } this.zoom(-delta * ratio, e); }, cropStart: function (event) { var options = this.options; var e = getEvent(event); var touches = e.touches; var touchesLength; var touch; var action; if (this.isDisabled) { return; } if (touches) { touchesLength = touches.length; if (touchesLength > 1) { if (options.zoomable && options.zoomOnTouch && touchesLength === 2) { touch = touches[1]; this.startX2 = touch.pageX; this.startY2 = touch.pageY; action = ACTION_ZOOM; } else { return; } } touch = touches[0]; } action = action || getData(e.target, DATA_ACTION); if (REGEXP_ACTIONS.test(action)) { if (isFunction(options.cropstart) && options.cropstart.call(this.element, { originalEvent: e, action: action }) === false) { return; } preventDefault(e); this.action = action; this.cropping = false; this.startX = touch ? touch.pageX : e.pageX; this.startY = touch ? touch.pageY : e.pageY; if (action === ACTION_CROP) { this.cropping = true; addClass(this.dragBox, CLASS_MODAL); } } }, cropMove: function (event) { var options = this.options; var e = getEvent(event); var touches = e.touches; var action = this.action; var touchesLength; var touch; if (this.isDisabled) { return; } if (touches) { touchesLength = touches.length; if (touchesLength > 1) { if (options.zoomable && options.zoomOnTouch && touchesLength === 2) { touch = touches[1]; this.endX2 = touch.pageX; this.endY2 = touch.pageY; } else { return; } } touch = touches[0]; } if (action) { if (isFunction(options.cropmove) && options.cropmove.call(this.element, { originalEvent: e, action: action }) === false) { return; } preventDefault(e); this.endX = touch ? touch.pageX : e.pageX; this.endY = touch ? touch.pageY : e.pageY; this.change(e.shiftKey, action === ACTION_ZOOM ? e : null); } }, cropEnd: function (event) { var options = this.options; var e = getEvent(event); var action = this.action; if (this.isDisabled) { return; } if (action) { preventDefault(e); if (this.cropping) { this.cropping = false; toggleClass(this.dragBox, CLASS_MODAL, this.isCropped && options.modal); } this.action = ''; if (isFunction(options.cropend)) { options.cropend.call(this.element, { originalEvent: e, action: action }); } } } }); extend(prototype, { change: function (shiftKey, originalEvent) { var options = this.options; var aspectRatio = options.aspectRatio; var action = this.action; var containerData = this.containerData; var canvasData = this.canvasData; var cropBoxData = this.cropBoxData; var width = cropBoxData.width; var height = cropBoxData.height; var left = cropBoxData.left; var top = cropBoxData.top; var right = left + width; var bottom = top + height; var minLeft = 0; var minTop = 0; var maxWidth = containerData.width; var maxHeight = containerData.height; var renderable = true; var offset; var range; // Locking aspect ratio in "free mode" by holding shift key if (!aspectRatio && shiftKey) { aspectRatio = width && height ? width / height : 1; } if (this.isLimited) { minLeft = cropBoxData.minLeft; minTop = cropBoxData.minTop; maxWidth = minLeft + min(containerData.width, canvasData.width); maxHeight = minTop + min(containerData.height, canvasData.height); } range = { x: this.endX - this.startX, y: this.endY - this.startY }; if (aspectRatio) { range.X = range.y * aspectRatio; range.Y = range.x / aspectRatio; } switch (action) { // Move crop box case ACTION_ALL: left += range.x; top += range.y; break; // Resize crop box case ACTION_EAST: if (range.x >= 0 && (right >= maxWidth || aspectRatio && (top <= minTop || bottom >= maxHeight))) { renderable = false; break; } width += range.x; if (aspectRatio) { height = width / aspectRatio; top -= range.Y / 2; } if (width < 0) { action = ACTION_WEST; width = 0; } break; case ACTION_NORTH: if (range.y <= 0 && (top <= minTop || aspectRatio && (left <= minLeft || right >= maxWidth))) { renderable = false; break; } height -= range.y; top += range.y; if (aspectRatio) { width = height * aspectRatio; left += range.X / 2; } if (height < 0) { action = ACTION_SOUTH; height = 0; } break; case ACTION_WEST: if (range.x <= 0 && (left <= minLeft || aspectRatio && (top <= minTop || bottom >= maxHeight))) { renderable = false; break; } width -= range.x; left += range.x; if (aspectRatio) { height = width / aspectRatio; top += range.Y / 2; } if (width < 0) { action = ACTION_EAST; width = 0; } break; case ACTION_SOUTH: if (range.y >= 0 && (bottom >= maxHeight || aspectRatio && (left <= minLeft || right >= maxWidth))) { renderable = false; break; } height += range.y; if (aspectRatio) { width = height * aspectRatio; left -= range.X / 2; } if (height < 0) { action = ACTION_NORTH; height = 0; } break; case ACTION_NORTH_EAST: if (aspectRatio) { if (range.y <= 0 && (top <= minTop || right >= maxWidth)) { renderable = false; break; } height -= range.y; top += range.y; width = height * aspectRatio; } else { if (range.x >= 0) { if (right < maxWidth) { width += range.x; } else if (range.y <= 0 && top <= minTop) { renderable = false; } } else { width += range.x; } if (range.y <= 0) { if (top > minTop) { height -= range.y; top += range.y; } } else { height -= range.y; top += range.y; } } if (width < 0 && height < 0) { action = ACTION_SOUTH_WEST; height = 0; width = 0; } else if (width < 0) { action = ACTION_NORTH_WEST; width = 0; } else if (height < 0) { action = ACTION_SOUTH_EAST; height = 0; } break; case ACTION_NORTH_WEST: if (aspectRatio) { if (range.y <= 0 && (top <= minTop || left <= minLeft)) { renderable = false; break; } height -= range.y; top += range.y; width = height * aspectRatio; left += range.X; } else { if (range.x <= 0) { if (left > minLeft) { width -= range.x; left += range.x; } else if (range.y <= 0 && top <= minTop) { renderable = false; } } else { width -= range.x; left += range.x; } if (range.y <= 0) { if (top > minTop) { height -= range.y; top += range.y; } } else { height -= range.y; top += range.y; } } if (width < 0 && height < 0) { action = ACTION_SOUTH_EAST; height = 0; width = 0; } else if (width < 0) { action = ACTION_NORTH_EAST; width = 0; } else if (height < 0) { action = ACTION_SOUTH_WEST; height = 0; } break; case ACTION_SOUTH_WEST: if (aspectRatio) { if (range.x <= 0 && (left <= minLeft || bottom >= maxHeight)) { renderable = false; break; } width -= range.x; left += range.x; height = width / aspectRatio; } else { if (range.x <= 0) { if (left > minLeft) { width -= range.x; left += range.x; } else if (range.y >= 0 && bottom >= maxHeight) { renderable = false; } } else { width -= range.x; left += range.x; } if (range.y >= 0) { if (bottom < maxHeight) { height += range.y; } } else { height += range.y; } } if (width < 0 && height < 0) { action = ACTION_NORTH_EAST; height = 0; width = 0; } else if (width < 0) { action = ACTION_SOUTH_EAST; width = 0; } else if (height < 0) { action = ACTION_NORTH_WEST; height = 0; } break; case ACTION_SOUTH_EAST: if (aspectRatio) { if (range.x >= 0 && (right >= maxWidth || bottom >= maxHeight)) { renderable = false; break; } width += range.x; height = width / aspectRatio; } else { if (range.x >= 0) { if (right < maxWidth) { width += range.x; } else if (range.y >= 0 && bottom >= maxHeight) { renderable = false; } } else { width += range.x; } if (range.y >= 0) { if (bottom < maxHeight) { height += range.y; } } else { height += range.y; } } if (width < 0 && height < 0) { action = ACTION_NORTH_WEST; height = 0; width = 0; } else if (width < 0) { action = ACTION_SOUTH_WEST; width = 0; } else if (height < 0) { action = ACTION_NORTH_EAST; height = 0; } break; // Move canvas case ACTION_MOVE: this.move(range.x, range.y); renderable = false; break; // Zoom canvas case ACTION_ZOOM: this.zoom((function (x1, y1, x2, y2) { var z1 = sqrt(x1 * x1 + y1 * y1); var z2 = sqrt(x2 * x2 + y2 * y2); return (z2 - z1) / z1; })( abs(this.startX - this.startX2), abs(this.startY - this.startY2), abs(this.endX - this.endX2), abs(this.endY - this.endY2) ), originalEvent); this.startX2 = this.endX2; this.startY2 = this.endY2; renderable = false; break; // Create crop box case ACTION_CROP: if (!range.x || !range.y) { renderable = false; break; } offset = getOffset(this.cropper); left = this.startX - offset.left; top = this.startY - offset.top; width = cropBoxData.minWidth; height = cropBoxData.minHeight; if (range.x > 0) { action = range.y > 0 ? ACTION_SOUTH_EAST : ACTION_NORTH_EAST; } else if (range.x < 0) { left -= width; action = range.y > 0 ? ACTION_SOUTH_WEST : ACTION_NORTH_WEST; } if (range.y < 0) { top -= height; } // Show the crop box if is hidden if (!this.isCropped) { removeClass(this.cropBox, CLASS_HIDDEN); this.isCropped = true; if (this.isLimited) { this.limitCropBox(true, true); } } break; // No default } if (renderable) { cropBoxData.width = width; cropBoxData.height = height; cropBoxData.left = left; cropBoxData.top = top; this.action = action; this.renderCropBox(); } // Override this.startX = this.endX; this.startY = this.endY; } }); extend(prototype, { // Show the crop box manually crop: function () { if (this.isBuilt && !this.isDisabled) { if (!this.isCropped) { this.isCropped = true; this.limitCropBox(true, true); if (this.options.modal) { addClass(this.dragBox, CLASS_MODAL); } removeClass(this.cropBox, CLASS_HIDDEN); } this.setCropBoxData(this.initialCropBoxData); } return this; }, // Reset the image and crop box to their initial states reset: function () { if (this.isBuilt && !this.isDisabled) { this.imageData = extend({}, this.initialImageData); this.canvasData = extend({}, this.initialCanvasData); this.cropBoxData = extend({}, this.initialCropBoxData); this.renderCanvas(); if (this.isCropped) { this.renderCropBox(); } } return this; }, // Clear the crop box clear: function () { if (this.isCropped && !this.isDisabled) { extend(this.cropBoxData, { left: 0, top: 0, width: 0, height: 0 }); this.isCropped = false; this.renderCropBox(); this.limitCanvas(); // Render canvas after crop box rendered this.renderCanvas(); removeClass(this.dragBox, CLASS_MODAL); addClass(this.cropBox, CLASS_HIDDEN); } return this; }, /** * Replace the image's src and rebuild the cropper * * @param {String} url */ replace: function (url) { if (!this.isDisabled && url) { if (this.isImg) { this.isReplaced = true; this.element.src = url; } // Clear previous data this.options.data = null; this.load(url); } return this; }, // Enable (unfreeze) the cropper enable: function () { if (this.isBuilt) { this.isDisabled = false; removeClass(this.cropper, CLASS_DISABLED); } return this; }, // Disable (freeze) the cropper disable: function () { if (this.isBuilt) { this.isDisabled = true; addClass(this.cropper, CLASS_DISABLED); } return this; }, // Destroy the cropper and remove the instance from the image destroy: function () { var element = this.element; var image = this.image; if (this.isLoaded) { if (this.isImg && this.isReplaced) { element.src = this.originalUrl; } this.unbuild(); removeClass(element, CLASS_HIDDEN); } else { if (this.isImg) { element.off(EVENT_LOAD, this.start); } else if (image) { removeChild(image); } } removeData(element, NAMESPACE); return this; }, /** * Move the canvas with relative offsets * * @param {Number} offsetX * @param {Number} offsetY (optional) */ move: function (offsetX, offsetY) { var canvasData = this.canvasData; return this.moveTo( isUndefined(offsetX) ? offsetX : canvasData.left + num(offsetX), isUndefined(offsetY) ? offsetY : canvasData.top + num(offsetY) ); }, /** * Move the canvas to an absolute point * * @param {Number} x * @param {Number} y (optional) */ moveTo: function (x, y) { var canvasData = this.canvasData; var isChanged = false; // If "y" is not present, its default value is "x" if (isUndefined(y)) { y = x; } x = num(x); y = num(y); if (this.isBuilt && !this.isDisabled && this.options.movable) { if (isNumber(x)) { canvasData.left = x; isChanged = true; } if (isNumber(y)) { canvasData.top = y; isChanged = true; } if (isChanged) { this.renderCanvas(true); } } return this; }, /** * Zoom the canvas with a relative ratio * * @param {Number} ratio * @param {Event} _originalEvent (private) */ zoom: function (ratio, _originalEvent) { var canvasData = this.canvasData; ratio = num(ratio); if (ratio < 0) { ratio = 1 / (1 - ratio); } else { ratio = 1 + ratio; } return this.zoomTo(canvasData.width * ratio / canvasData.naturalWidth, _originalEvent); }, /** * Zoom the canvas to an absolute ratio * * @param {Number} ratio * @param {Event} _originalEvent (private) */ zoomTo: function (ratio, _originalEvent) { var options = this.options; var canvasData = this.canvasData; var width = canvasData.width; var height = canvasData.height; var naturalWidth = canvasData.naturalWidth; var naturalHeight = canvasData.naturalHeight; var newWidth; var newHeight; ratio = num(ratio); if (ratio >= 0 && this.isBuilt && !this.isDisabled && options.zoomable) { newWidth = naturalWidth * ratio; newHeight = naturalHeight * ratio; if (isFunction(options.zoom) && options.zoom.call(this.element, { originalEvent: _originalEvent, oldRatio: width / naturalWidth, ratio: newWidth / naturalWidth }) === false) { return this; } canvasData.left -= (newWidth - width) / 2; canvasData.top -= (newHeight - height) / 2; canvasData.width = newWidth; canvasData.height = newHeight; this.renderCanvas(true); } return this; }, /** * Rotate the canvas with a relative degree * * @param {Number} degree */ rotate: function (degree) { return this.rotateTo((this.imageData.rotate || 0) + num(degree)); }, /** * Rotate the canvas to an absolute degree * https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function#rotate() * * @param {Number} degree */ rotateTo: function (degree) { degree = num(degree); if (isNumber(degree) && this.isBuilt && !this.isDisabled && this.options.rotatable) { this.imageData.rotate = degree % 360; this.isRotated = true; this.renderCanvas(true); } return this; }, /** * Scale the image * https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function#scale() * * @param {Number} scaleX * @param {Number} scaleY (optional) */ scale: function (scaleX, scaleY) { var imageData = this.imageData; var isChanged = false; // If "scaleY" is not present, its default value is "scaleX" if (isUndefined(scaleY)) { scaleY = scaleX; } scaleX = num(scaleX); scaleY = num(scaleY); if (this.isBuilt && !this.isDisabled && this.options.scalable) { if (isNumber(scaleX)) { imageData.scaleX = scaleX; isChanged = true; } if (isNumber(scaleY)) { imageData.scaleY = scaleY; isChanged = true; } if (isChanged) { this.renderImage(true); } } return this; }, /** * Scale the abscissa of the image * * @param {Number} scaleX */ scaleX: function (scaleX) { var scaleY = this.imageData.scaleY; return this.scale(scaleX, isNumber(scaleY) ? scaleY : 1); }, /** * Scale the ordinate of the image * * @param {Number} scaleY */ scaleY: function (scaleY) { var scaleX = this.imageData.scaleX; return this.scale(isNumber(scaleX) ? scaleX : 1, scaleY); }, /** * Get the cropped area position and size data (base on the original image) * * @param {Boolean} isRounded (optional) * @return {Object} data */ getData: function (isRounded) { var options = this.options; var imageData = this.imageData; var canvasData = this.canvasData; var cropBoxData = this.cropBoxData; var ratio; var data; if (this.isBuilt && this.isCropped) { data = { x: cropBoxData.left - canvasData.left, y: cropBoxData.top - canvasData.top, width: cropBoxData.width, height: cropBoxData.height }; ratio = imageData.width / imageData.naturalWidth; each(data, function (n, i) { n = n / ratio; data[i] = isRounded ? round(n) : n; }); } else { data = { x: 0, y: 0, width: 0, height: 0 }; } if (options.rotatable) { data.rotate = imageData.rotate || 0; } if (options.scalable) { data.scaleX = imageData.scaleX || 1; data.scaleY = imageData.scaleY || 1; } return data; }, /** * Set the cropped area position and size with new data * * @param {Object} data */ setData: function (data) { var options = this.options; var imageData = this.imageData; var canvasData = this.canvasData; var cropBoxData = {}; var isRotated; var isScaled; var ratio; if (isFunction(data)) { data = data.call(this.element); } if (this.isBuilt && !this.isDisabled && isPlainObject(data)) { if (options.rotatable) { if (isNumber(data.rotate) && data.rotate !== imageData.rotate) { imageData.rotate = data.rotate; this.isRotated = isRotated = true; } } if (options.scalable) { if (isNumber(data.scaleX) && data.scaleX !== imageData.scaleX) { imageData.scaleX = data.scaleX; isScaled = true; } if (isNumber(data.scaleY) && data.scaleY !== imageData.scaleY) { imageData.scaleY = data.scaleY; isScaled = true; } } if (isRotated) { this.renderCanvas(); } else if (isScaled) { this.renderImage(); } ratio = imageData.width / imageData.naturalWidth; if (isNumber(data.x)) { cropBoxData.left = data.x * ratio + canvasData.left; } if (isNumber(data.y)) { cropBoxData.top = data.y * ratio + canvasData.top; } if (isNumber(data.width)) { cropBoxData.width = data.width * ratio; } if (isNumber(data.height)) { cropBoxData.height = data.height * ratio; } this.setCropBoxData(cropBoxData); } return this; }, /** * Get the container size data * * @return {Object} data */ getContainerData: function () { return this.isBuilt ? this.containerData : {}; }, /** * Get the image position and size data * * @return {Object} data */ getImageData: function () { return this.isLoaded ? this.imageData : {}; }, /** * Get the canvas position and size data * * @return {Object} data */ getCanvasData: function () { var canvasData = this.canvasData; var data = {}; if (this.isBuilt) { each([ 'left', 'top', 'width', 'height', 'naturalWidth', 'naturalHeight' ], function (n) { data[n] = canvasData[n]; }); } return data; }, /** * Set the canvas position and size with new data * * @param {Object} data */ setCanvasData: function (data) { var canvasData = this.canvasData; var aspectRatio = canvasData.aspectRatio; if (isFunction(data)) { data = data.call(this.element); } if (this.isBuilt && !this.isDisabled && isPlainObject(data)) { if (isNumber(data.left)) { canvasData.left = data.left; } if (isNumber(data.top)) { canvasData.top = data.top; } if (isNumber(data.width)) { canvasData.width = data.width; canvasData.height = data.width / aspectRatio; } else if (isNumber(data.height)) { canvasData.height = data.height; canvasData.width = data.height * aspectRatio; } this.renderCanvas(true); } return this; }, /** * Get the crop box position and size data * * @return {Object} data */ getCropBoxData: function () { var cropBoxData = this.cropBoxData; var data; if (this.isBuilt && this.isCropped) { data = { left: cropBoxData.left, top: cropBoxData.top, width: cropBoxData.width, height: cropBoxData.height }; } return data || {}; }, /** * Set the crop box position and size with new data * * @param {Object} data */ setCropBoxData: function (data) { var cropBoxData = this.cropBoxData; var aspectRatio = this.options.aspectRatio; var isWidthChanged; var isHeightChanged; if (isFunction(data)) { data = data.call(this.element); } if (this.isBuilt && this.isCropped && !this.isDisabled && isPlainObject(data)) { if (isNumber(data.left)) { cropBoxData.left = data.left; } if (isNumber(data.top)) { cropBoxData.top = data.top; } if (isNumber(data.width) && data.width !== cropBoxData.width) { isWidthChanged = true; cropBoxData.width = data.width; } if (isNumber(data.height) && data.height !== cropBoxData.height) { isHeightChanged = true; cropBoxData.height = data.height; } if (aspectRatio) { if (isWidthChanged) { cropBoxData.height = cropBoxData.width / aspectRatio; } else if (isHeightChanged) { cropBoxData.width = cropBoxData.height * aspectRatio; } } this.renderCropBox(); } return this; }, /** * Get a canvas drawn the cropped image * * @param {Object} options (optional) * @return {HTMLCanvasElement} canvas */ getCroppedCanvas: function (options) { var originalWidth; var originalHeight; var canvasWidth; var canvasHeight; var scaledWidth; var scaledHeight; var scaledRatio; var aspectRatio; var canvas; var context; var data; if (!this.isBuilt || !this.isCropped || !SUPPORT_CANVAS) { return; } if (!isPlainObject(options)) { options = {}; } data = this.getData(); originalWidth = data.width; originalHeight = data.height; aspectRatio = originalWidth / originalHeight; if (isPlainObject(options)) { scaledWidth = options.width; scaledHeight = options.height; if (scaledWidth) { scaledHeight = scaledWidth / aspectRatio; scaledRatio = scaledWidth / originalWidth; } else if (scaledHeight) { scaledWidth = scaledHeight * aspectRatio; scaledRatio = scaledHeight / originalHeight; } } // The canvas element will use `Math.floor` on a float number, so round first canvasWidth = round(scaledWidth || originalWidth); canvasHeight = round(scaledHeight || originalHeight); canvas = document.createElement('canvas'); canvas.width = canvasWidth; canvas.height = canvasHeight; context = canvas.getContext('2d'); if (options.fillColor) { context.fillStyle = options.fillColor; context.fillRect(0, 0, canvasWidth, canvasHeight); } // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D.drawImage context.drawImage.apply(context, (function () { var source = getSourceCanvas(this.image, this.imageData); var sourceWidth = source.width; var sourceHeight = source.height; var args = [source]; // Source canvas var srcX = data.x; var srcY = data.y; var srcWidth; var srcHeight; // Destination canvas var dstX; var dstY; var dstWidth; var dstHeight; if (srcX <= -originalWidth || srcX > sourceWidth) { srcX = srcWidth = dstX = dstWidth = 0; } else if (srcX <= 0) { dstX = -srcX; srcX = 0; srcWidth = dstWidth = min(sourceWidth, originalWidth + srcX); } else if (srcX <= sourceWidth) { dstX = 0; srcWidth = dstWidth = min(originalWidth, sourceWidth - srcX); } if (srcWidth <= 0 || srcY <= -originalHeight || srcY > sourceHeight) { srcY = srcHeight = dstY = dstHeight = 0; } else if (srcY <= 0) { dstY = -srcY; srcY = 0; srcHeight = dstHeight = min(sourceHeight, originalHeight + srcY); } else if (srcY <= sourceHeight) { dstY = 0; srcHeight = dstHeight = min(originalHeight, sourceHeight - srcY); } args.push(floor(srcX), floor(srcY), floor(srcWidth), floor(srcHeight)); // Scale destination sizes if (scaledRatio) { dstX *= scaledRatio; dstY *= scaledRatio; dstWidth *= scaledRatio; dstHeight *= scaledRatio; } // Avoid "IndexSizeError" in IE and Firefox if (dstWidth > 0 && dstHeight > 0) { args.push(floor(dstX), floor(dstY), floor(dstWidth), floor(dstHeight)); } return args; }).call(this)); return canvas; }, /** * Change the aspect ratio of the crop box * * @param {Number} aspectRatio */ setAspectRatio: function (aspectRatio) { var options = this.options; if (!this.isDisabled && !isUndefined(aspectRatio)) { // 0 -> NaN options.aspectRatio = max(0, aspectRatio) || NaN; if (this.isBuilt) { this.initCropBox(); if (this.isCropped) { this.renderCropBox(); } } } return this; }, /** * Change the drag mode * * @param {String} mode (optional) */ setDragMode: function (mode) { var options = this.options; var dragBox = this.dragBox; var face = this.face; var croppable; var movable; if (this.isLoaded && !this.isDisabled) { croppable = mode === ACTION_CROP; movable = options.movable && mode === ACTION_MOVE; mode = (croppable || movable) ? mode : ACTION_NONE; setData(dragBox, DATA_ACTION, mode); toggleClass(dragBox, CLASS_CROP, croppable); toggleClass(dragBox, CLASS_MOVE, movable); if (!options.cropBoxMovable) { // Sync drag mode to crop box when it is not movable setData(face, DATA_ACTION, mode); toggleClass(face, CLASS_CROP, croppable); toggleClass(face, CLASS_MOVE, movable); } } return this; } }); extend(Cropper.prototype, prototype); Cropper.DEFAULTS = { // Define the view mode of the cropper viewMode: 0, // 0, 1, 2, 3 // Define the dragging mode of the cropper dragMode: 'crop', // 'crop', 'move' or 'none' // Define the aspect ratio of the crop box aspectRatio: NaN, // An object with the previous cropping result data data: null, // A selector for adding extra containers to preview preview: '', // Re-render the cropper when resize the window responsive: true, // Restore the cropped area after resize the window restore: true, // Check if the target image is cross origin checkCrossOrigin: true, // Show the black modal modal: true, // Show the dashed lines for guiding guides: true, // Show the center indicator for guiding center: true, // Show the white modal to highlight the crop box highlight: true, // Show the grid background background: true, // Enable to crop the image automatically when initialize autoCrop: true, // Define the percentage of automatic cropping area when initializes autoCropArea: 0.8, // Enable to move the image movable: true, // Enable to rotate the image rotatable: true, // Enable to scale the image scalable: true, // Enable to zoom the image zoomable: true, // Enable to zoom the image by dragging touch zoomOnTouch: true, // Enable to zoom the image by wheeling mouse zoomOnWheel: true, // Define zoom ratio when zoom the image by wheeling mouse wheelZoomRatio: 0.1, // Enable to move the crop box cropBoxMovable: true, // Enable to resize the crop box cropBoxResizable: true, // Toggle drag mode between "crop" and "move" when click twice on the cropper toggleDragModeOnDblclick: true, // Size limitation minCanvasWidth: 0, minCanvasHeight: 0, minCropBoxWidth: 0, minCropBoxHeight: 0, minContainerWidth: 200, minContainerHeight: 100, // Shortcuts of events build: null, built: null, cropstart: null, cropmove: null, cropend: null, crop: null, zoom: null }; Cropper.TEMPLATE = ( '<div class="cropper-container">' + '<div class="cropper-wrap-box">' + '<div class="cropper-canvas"></div>' + '</div>' + '<div class="cropper-drag-box"></div>' + '<div class="cropper-crop-box">' + '<span class="cropper-view-box"></span>' + '<span class="cropper-dashed dashed-h"></span>' + '<span class="cropper-dashed dashed-v"></span>' + '<span class="cropper-center"></span>' + '<span class="cropper-face"></span>' + '<span class="cropper-line line-e" data-action="e"></span>' + '<span class="cropper-line line-n" data-action="n"></span>' + '<span class="cropper-line line-w" data-action="w"></span>' + '<span class="cropper-line line-s" data-action="s"></span>' + '<span class="cropper-point point-e" data-action="e"></span>' + '<span class="cropper-point point-n" data-action="n"></span>' + '<span class="cropper-point point-w" data-action="w"></span>' + '<span class="cropper-point point-s" data-action="s"></span>' + '<span class="cropper-point point-ne" data-action="ne"></span>' + '<span class="cropper-point point-nw" data-action="nw"></span>' + '<span class="cropper-point point-sw" data-action="sw"></span>' + '<span class="cropper-point point-se" data-action="se"></span>' + '</div>' + '</div>' ); var _Cropper = window.Cropper; Cropper.noConflict = function () { window.Cropper = _Cropper; return Cropper; }; Cropper.setDefaults = function (options) { extend(Cropper.DEFAULTS, options); }; if (typeof define === 'function' && define.amd) { define('cropper', [], function () { return Cropper; }); } if (typeof noGlobal === 'undefined') { window.Cropper = Cropper; } return Cropper; });
redmunds/cdnjs
ajax/libs/cropperjs/0.4.0/cropper.js
JavaScript
mit
83,381
var isIterateeCall = require('./isIterateeCall'), rest = require('../rest'); /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return rest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = typeof customizer == 'function' ? (length--, customizer) : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, customizer); } } return object; }); } module.exports = createAssigner;
zverevalexei/bierman-topology
web/node_modules/bower/node_modules/lodash/internal/createAssigner.js
JavaScript
mit
984
/* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 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. */ // Code generated by client-gen. DO NOT EDIT. package fake import ( v1 "k8s.io/apimachinery/pkg/apis/meta/v1" labels "k8s.io/apimachinery/pkg/labels" schema "k8s.io/apimachinery/pkg/runtime/schema" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" testing "k8s.io/client-go/testing" batch "k8s.io/kubernetes/pkg/apis/batch" ) // FakeJobs implements JobInterface type FakeJobs struct { Fake *FakeBatch ns string } var jobsResource = schema.GroupVersionResource{Group: "batch", Version: "", Resource: "jobs"} var jobsKind = schema.GroupVersionKind{Group: "batch", Version: "", Kind: "Job"} // Get takes name of the job, and returns the corresponding job object, and an error if there is any. func (c *FakeJobs) Get(name string, options v1.GetOptions) (result *batch.Job, err error) { obj, err := c.Fake. Invokes(testing.NewGetAction(jobsResource, c.ns, name), &batch.Job{}) if obj == nil { return nil, err } return obj.(*batch.Job), err } // List takes label and field selectors, and returns the list of Jobs that match those selectors. func (c *FakeJobs) List(opts v1.ListOptions) (result *batch.JobList, err error) { obj, err := c.Fake. Invokes(testing.NewListAction(jobsResource, jobsKind, c.ns, opts), &batch.JobList{}) if obj == nil { return nil, err } label, _, _ := testing.ExtractFromListOptions(opts) if label == nil { label = labels.Everything() } list := &batch.JobList{ListMeta: obj.(*batch.JobList).ListMeta} for _, item := range obj.(*batch.JobList).Items { if label.Matches(labels.Set(item.Labels)) { list.Items = append(list.Items, item) } } return list, err } // Watch returns a watch.Interface that watches the requested jobs. func (c *FakeJobs) Watch(opts v1.ListOptions) (watch.Interface, error) { return c.Fake. InvokesWatch(testing.NewWatchAction(jobsResource, c.ns, opts)) } // Create takes the representation of a job and creates it. Returns the server's representation of the job, and an error, if there is any. func (c *FakeJobs) Create(job *batch.Job) (result *batch.Job, err error) { obj, err := c.Fake. Invokes(testing.NewCreateAction(jobsResource, c.ns, job), &batch.Job{}) if obj == nil { return nil, err } return obj.(*batch.Job), err } // Update takes the representation of a job and updates it. Returns the server's representation of the job, and an error, if there is any. func (c *FakeJobs) Update(job *batch.Job) (result *batch.Job, err error) { obj, err := c.Fake. Invokes(testing.NewUpdateAction(jobsResource, c.ns, job), &batch.Job{}) if obj == nil { return nil, err } return obj.(*batch.Job), err } // UpdateStatus was generated because the type contains a Status member. // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). func (c *FakeJobs) UpdateStatus(job *batch.Job) (*batch.Job, error) { obj, err := c.Fake. Invokes(testing.NewUpdateSubresourceAction(jobsResource, "status", c.ns, job), &batch.Job{}) if obj == nil { return nil, err } return obj.(*batch.Job), err } // Delete takes name of the job and deletes it. Returns an error if one occurs. func (c *FakeJobs) Delete(name string, options *v1.DeleteOptions) error { _, err := c.Fake. Invokes(testing.NewDeleteAction(jobsResource, c.ns, name), &batch.Job{}) return err } // DeleteCollection deletes a collection of objects. func (c *FakeJobs) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { action := testing.NewDeleteCollectionAction(jobsResource, c.ns, listOptions) _, err := c.Fake.Invokes(action, &batch.JobList{}) return err } // Patch applies the patch and returns the patched job. func (c *FakeJobs) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *batch.Job, err error) { obj, err := c.Fake. Invokes(testing.NewPatchSubresourceAction(jobsResource, c.ns, name, pt, data, subresources...), &batch.Job{}) if obj == nil { return nil, err } return obj.(*batch.Job), err }
Stackdriver/heapster
vendor/k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/batch/internalversion/fake/fake_job.go
GO
apache-2.0
4,578
cask 'gqrx' do version '2.11.5' sha256 '896cefcb2825840178b6dbfb894b01543b1c8225539e6969052133223a59ffee' # github.com/csete/gqrx was verified as official when first introduced to the cask url "https://github.com/csete/gqrx/releases/download/v#{version.major_minor_patch}/Gqrx-#{version}.dmg" appcast 'https://github.com/csete/gqrx/releases.atom' name 'Gqrx' homepage 'http://gqrx.dk/' app 'Gqrx.app' binary "#{appdir}/Gqrx.app/Contents/MacOS/airspy_info" binary "#{appdir}/Gqrx.app/Contents/MacOS/airspy_rx" binary "#{appdir}/Gqrx.app/Contents/MacOS/airspy_spiflash" binary "#{appdir}/Gqrx.app/Contents/MacOS/hackrf_cpldjtag" binary "#{appdir}/Gqrx.app/Contents/MacOS/hackrf_debug" binary "#{appdir}/Gqrx.app/Contents/MacOS/hackrf_info" binary "#{appdir}/Gqrx.app/Contents/MacOS/hackrf_spiflash" binary "#{appdir}/Gqrx.app/Contents/MacOS/hackrf_transfer" binary "#{appdir}/Gqrx.app/Contents/MacOS/rtl_adsb" binary "#{appdir}/Gqrx.app/Contents/MacOS/rtl_eeprom" binary "#{appdir}/Gqrx.app/Contents/MacOS/rtl_fm" binary "#{appdir}/Gqrx.app/Contents/MacOS/rtl_power" binary "#{appdir}/Gqrx.app/Contents/MacOS/rtl_sdr" binary "#{appdir}/Gqrx.app/Contents/MacOS/rtl_tcp" binary "#{appdir}/Gqrx.app/Contents/MacOS/rtl_test" binary "#{appdir}/Gqrx.app/Contents/MacOS/SoapySDRUtil", target: 'soapysdrutil' binary "#{appdir}/Gqrx.app/Contents/MacOS/volk_profile" # shim script (https://github.com/Homebrew/homebrew-cask/issues/18809) shimscript = "#{staged_path}/gqrx.wrapper.sh" binary shimscript, target: 'gqrx' preflight do IO.write shimscript, <<~EOS #!/bin/sh '#{appdir}/Gqrx.app/Contents/MacOS/gqrx' "$@" EOS end end
reelsense/homebrew-cask
Casks/gqrx.rb
Ruby
bsd-2-clause
1,698
// 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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GetAndWithElementSingle0() { var test = new VectorGetAndWithElement__GetAndWithElementSingle0(); // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); // Validates that invalid indices throws ArgumentOutOfRangeException test.RunArgumentOutOfRangeScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorGetAndWithElement__GetAndWithElementSingle0 { private static readonly int LargestVectorSize = 16; private static readonly int ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); public bool Succeeded { get; set; } = true; public void RunBasicScenario(int imm = 0, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Single[] values = new Single[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetSingle(); } Vector128<Single> value = Vector128.Create(values[0], values[1], values[2], values[3]); bool succeeded = !expectedOutOfRangeException; try { Single result = value.GetElement(imm); ValidateGetResult(result, values); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<Single.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Single insertedValue = TestLibrary.Generator.GetSingle(); try { Vector128<Single> result2 = value.WithElement(imm, insertedValue); ValidateWithResult(result2, values, insertedValue); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<Single.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunReflectionScenario(int imm = 0, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Single[] values = new Single[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetSingle(); } Vector128<Single> value = Vector128.Create(values[0], values[1], values[2], values[3]); bool succeeded = !expectedOutOfRangeException; try { object result = typeof(Vector128) .GetMethod(nameof(Vector128.GetElement)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value, imm }); ValidateGetResult((Single)(result), values); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<Single.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Single insertedValue = TestLibrary.Generator.GetSingle(); try { object result2 = typeof(Vector128) .GetMethod(nameof(Vector128.WithElement)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value, imm, insertedValue }); ValidateWithResult((Vector128<Single>)(result2), values, insertedValue); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<Single.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunArgumentOutOfRangeScenario() { RunBasicScenario(0 - ElementCount, expectedOutOfRangeException: true); RunBasicScenario(0 + ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(0 - ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(0 + ElementCount, expectedOutOfRangeException: true); } private void ValidateGetResult(Single result, Single[] values, [CallerMemberName] string method = "") { if (result != values[0]) { Succeeded = false; TestLibrary.TestFramework.LogInformation($"Vector128<Single.GetElement(0): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } private void ValidateWithResult(Vector128<Single> result, Single[] values, Single insertedValue, [CallerMemberName] string method = "") { Single[] resultElements = new Single[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, insertedValue, method); } private void ValidateWithResult(Single[] result, Single[] values, Single insertedValue, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount; i++) { if ((i != 0) && (result[i] != values[i])) { succeeded = false; break; } } if (result[0] != insertedValue) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<Single.WithElement(0): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" insert: insertedValue"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
krk/coreclr
tests/src/JIT/HardwareIntrinsics/General/Vector128_1/GetAndWithElement.Single.0.cs
C#
mit
8,967
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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. */ package org.jetbrains.idea.svn.svnkit.lowLevel; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.util.text.StringUtil; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * Created with IntelliJ IDEA. * User: Irina.Chernushina * Date: 7/30/12 * Time: 6:23 PM * * SVNLogInputStream is not used, since it does not check available() * */ public class SVNStoppableInputStream extends InputStream { private final static Logger LOG = Logger.getInstance(SVNStoppableInputStream.class); private final static String ourCheckAvalilable = "svn.check.available"; private final InputStream myOriginalIs; private final InputStream myIn; private boolean myAvailableChecked; private final boolean myCheckAvailable; public SVNStoppableInputStream(InputStream original, InputStream in) { final String property = System.getProperty(ourCheckAvalilable); myCheckAvailable = ! StringUtil.isEmptyOrSpaces(property) && Boolean.parseBoolean(property); //myCheckAvailable = Boolean.parseBoolean(property); myOriginalIs = myCheckAvailable ? digOriginal(original) : original; myIn = in; myAvailableChecked = false; } private InputStream digOriginal(InputStream original) { // because of many delegates in the chain possible InputStream current = original; try { while (true) { final String name = current.getClass().getName(); if ("org.tmatesoft.svn.core.internal.io.dav.http.SpoolFile.SpoolInputStream".equals(name)) { current = byName(current, "myCurrentInput"); } else if ("org.tmatesoft.svn.core.internal.util.ChunkedInputStream".equals(name)) { current = byName(current, "myInputStream"); } else if ("org.tmatesoft.svn.core.internal.util.FixedSizeInputStream".equals(name)) { current = byName(current, "mySource"); } else if (current instanceof BufferedInputStream) { return createReadingProxy(current); } else { // maybe ok class, maybe some unknown proxy Method[] methods = current.getClass().getDeclaredMethods(); for (Method method : methods) { if ("available".equals(method.getName())) { return current; } } return createReadingProxy(current); } } } catch (NoSuchFieldException e) { LOG.info(e); return createReadingProxy(current); } catch (IllegalAccessException e) { LOG.info(e); return createReadingProxy(current); } } private InputStream createReadingProxy(final InputStream current) { return new InputStream() { @Override public int read() throws IOException { return current.read(); } public int read(byte[] b) throws IOException { return current.read(b); } public int read(byte[] b, int off, int len) throws IOException { return current.read(b, off, len); } public long skip(long n) throws IOException { return current.skip(n); } public void close() throws IOException { current.close(); } public void mark(int readlimit) { current.mark(readlimit); } public void reset() throws IOException { current.reset(); } public boolean markSupported() { return current.markSupported(); } @Override public int available() throws IOException { return 1; } }; } private InputStream byName(InputStream current, final String name) throws NoSuchFieldException, IllegalAccessException { final Field input = current.getClass().getDeclaredField(name); input.setAccessible(true); current = (InputStream) input.get(current); return current; } @Override public int read() throws IOException { waitForAvailable(); return myIn.read(); } @Override public int read(byte[] b, int off, int len) throws IOException { waitForAvailable(); return myIn.read(b, off, len); } @Override public long skip(long n) throws IOException { if (n <= 0) return 0; check(); if (available() <= 0) return 0; return myIn.skip(n); } @Override public int available() throws IOException { check(); if (! myAvailableChecked) { int available = myOriginalIs.available(); if (available > 0) { myAvailableChecked = true; } return available; } return 1; } @Override public void close() throws IOException { check(); myIn.close(); } @Override public synchronized void mark(int readlimit) { myIn.mark(readlimit); } @Override public synchronized void reset() throws IOException { check(); myIn.reset(); } @Override public boolean markSupported() { return myIn.markSupported(); } private void check() throws IOException { ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); if (indicator != null && indicator.isCanceled()) { throw new IOException("Read request to canceled by user"); } } private void waitForAvailable() throws IOException { if (! myCheckAvailable) return; final Object lock = new Object(); synchronized (lock) { while (available() <= 0) { check(); try { lock.wait(100); } catch (InterruptedException e) { // } } } } }
ivan-fedorov/intellij-community
plugins/svn4idea/src/org/jetbrains/idea/svn/svnkit/lowLevel/SVNStoppableInputStream.java
Java
apache-2.0
6,260
/** * 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. */ package org.apache.camel.component.kura; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.Map; import org.apache.camel.CamelContext; import org.apache.camel.ConsumerTemplate; import org.apache.camel.ProducerTemplate; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.core.osgi.OsgiDefaultCamelContext; import org.apache.camel.model.RoutesDefinition; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; import org.osgi.service.component.ComponentContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class KuraRouter extends RouteBuilder implements BundleActivator { // Member collaborators protected final Logger log = LoggerFactory.getLogger(getClass()); protected BundleContext bundleContext; protected CamelContext camelContext; protected ProducerTemplate producerTemplate; protected ConsumerTemplate consumerTemplate; // Lifecycle @Override public void start(BundleContext bundleContext) throws Exception { try { this.bundleContext = bundleContext; log.debug("Initializing bundle {}.", bundleContext.getBundle().getBundleId()); camelContext = createCamelContext(); camelContext.addRoutes(this); ConfigurationAdmin configurationAdmin = requiredService(ConfigurationAdmin.class); Configuration camelKuraConfig = configurationAdmin.getConfiguration(camelXmlRoutesPid()); if (camelKuraConfig != null && camelKuraConfig.getProperties() != null) { Object routePropertyValue = camelKuraConfig.getProperties().get(camelXmlRoutesProperty()); if (routePropertyValue != null) { InputStream routesXml = new ByteArrayInputStream(routePropertyValue.toString().getBytes()); RoutesDefinition loadedRoutes = camelContext.loadRoutesDefinition(routesXml); camelContext.addRouteDefinitions(loadedRoutes.getRoutes()); } } beforeStart(camelContext); log.debug("About to start Camel Kura router: {}", getClass().getName()); camelContext.start(); producerTemplate = camelContext.createProducerTemplate(); consumerTemplate = camelContext.createConsumerTemplate(); log.debug("Bundle {} started.", bundleContext.getBundle().getBundleId()); } catch (Throwable e) { String errorMessage = "Problem when starting Kura module " + getClass().getName() + ":"; log.warn(errorMessage, e); // Print error to the Kura console. System.err.println(errorMessage); e.printStackTrace(); throw e; } } @Override public void stop(BundleContext bundleContext) throws Exception { log.debug("Stopping bundle {}.", bundleContext.getBundle().getBundleId()); camelContext.stop(); log.debug("Bundle {} stopped.", bundleContext.getBundle().getBundleId()); } protected void activate(ComponentContext componentContext, Map<String, Object> properties) throws Exception { start(componentContext.getBundleContext()); } protected void deactivate(ComponentContext componentContext) throws Exception { stop(componentContext.getBundleContext()); } // Callbacks @Override public void configure() throws Exception { log.debug("No programmatic routes configuration found."); } protected CamelContext createCamelContext() { return new OsgiDefaultCamelContext(bundleContext); } protected void beforeStart(CamelContext camelContext) { log.debug("Empty KuraRouter CamelContext before start configuration - skipping."); } // API Helpers protected <T> T service(Class<T> serviceType) { ServiceReference reference = bundleContext.getServiceReference(serviceType); return reference == null ? null : (T) bundleContext.getService(reference); } protected <T> T requiredService(Class<T> serviceType) { ServiceReference reference = bundleContext.getServiceReference(serviceType); if (reference == null) { throw new IllegalStateException("Cannot find service: " + serviceType.getName()); } return (T) bundleContext.getService(reference); } // Private helpers protected String camelXmlRoutesPid() { return "kura.camel"; } protected String camelXmlRoutesProperty() { return "kura.camel." + bundleContext.getBundle().getSymbolicName() + ".route"; } }
jmandawg/camel
components/camel-kura/src/main/java/org/apache/camel/component/kura/KuraRouter.java
Java
apache-2.0
5,602
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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. */ package com.intellij.ide; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * This class is initialized in two classloaders: the bootstrap classloader and the main IDEA classloader. The bootstrap instance * has ourMirrorClass initialized by the Bootstrap class; it calls the main instance of itself via reflection. * * @author yole */ @SuppressWarnings("UnusedDeclaration") public class WindowsCommandLineProcessor { // The WindowsCommandLineProcessor class which is loaded in the main IDEA (non-bootstrap) classloader. public static Class ourMirrorClass = null; public static WindowsCommandLineListener LISTENER = null; /** * NOTE: This method is called through JNI by the Windows launcher. Please do not delete or rename it. */ public static void processWindowsLauncherCommandLine(final String currentDirectory, final String commandLine) { if (ourMirrorClass != null) { try { Method method = ourMirrorClass.getMethod("processWindowsLauncherCommandLine", String.class, String.class); method.invoke(null, currentDirectory, commandLine); } catch (NoSuchMethodException e) { } catch (InvocationTargetException e) { } catch (IllegalAccessException e) { } } else { if (LISTENER != null) { LISTENER.processWindowsLauncherCommandLine(currentDirectory, commandLine); } } } }
caot/intellij-community
platform/bootstrap/src/com/intellij/ide/WindowsCommandLineProcessor.java
Java
apache-2.0
2,035
/// <reference path="../../typings/_custom.d.ts" /> /* * TODO: ES5 for now until I make a webpack plugin for protractor */ describe('App', function() { var subject; var result; beforeEach(function() { browser.get('/'); }); afterEach(function() { expect(subject).toEqual(result); }); it('should have a title', function() { subject = browser.getTitle(); result = 'Angular2 Webpack Starter by @gdi2990 from @AngularClass'; }); it('should have <header>', function() { subject = element(by.deepCss('app /deep/ header')).isPresent(); result = true; }); it('should have <main>', function() { subject = element(by.deepCss('app /deep/ main')).isPresent(); result = true; }); it('should have <footer>', function() { subject = element(by.deepCss('app /deep/ footer')).getText(); result = 'WebPack Angular 2 Starter by @AngularClass'; }); });
yanivefraim/angular2-webpack-starter
test/app/app.e2e.js
JavaScript
mit
916
#pragma once #define WIN32_MEAN_AND_LEAN #include <Windows.h> #undef WIN32_MEAN_AND_LEAN #include <mfapi.h> #include <mfidl.h> #include <stdint.h> #include <vector> #include <util/windows/ComPtr.hpp> #define MF_LOG(level, format, ...) \ blog(level, "[Media Foundation encoder]: " format, ##__VA_ARGS__) #define MF_LOG_ENCODER(format_name, encoder, level, format, ...) \ blog(level, "[Media Foundation %s: '%s']: " format, \ format_name, obs_encoder_get_name(encoder), \ ##__VA_ARGS__) namespace MFAAC { enum Status { FAILURE, SUCCESS, NOT_ACCEPTING, NEED_MORE_INPUT }; class Encoder { public: Encoder(const obs_encoder_t *encoder, UINT32 bitrate, UINT32 channels, UINT32 sampleRate, UINT32 bitsPerSample) : encoder(encoder), bitrate(bitrate), channels(channels), sampleRate(sampleRate), bitsPerSample(bitsPerSample) {} Encoder& operator=(Encoder const&) = delete; bool Initialize(); bool ProcessInput(UINT8 *data, UINT32 dataLength, UINT64 pts, MFAAC::Status *status); bool ProcessOutput(UINT8 **data, UINT32 *dataLength, UINT64 *pts, MFAAC::Status *status); bool ExtraData(UINT8 **extraData, UINT32 *extraDataLength); const obs_encoder_t *ObsEncoder() { return encoder; } UINT32 Bitrate() { return bitrate; } UINT32 Channels() { return channels; } UINT32 SampleRate() { return sampleRate; } UINT32 BitsPerSample() { return bitsPerSample; } static const UINT32 FrameSize = 1024; private: void InitializeExtraData(); HRESULT CreateMediaTypes(ComPtr<IMFMediaType> &inputType, ComPtr<IMFMediaType> &outputType); HRESULT EnsureCapacity(ComPtr<IMFSample> &sample, DWORD length); HRESULT CreateEmptySample(ComPtr<IMFSample> &sample, ComPtr<IMFMediaBuffer> &buffer, DWORD length); private: const obs_encoder_t *encoder; const UINT32 bitrate; const UINT32 channels; const UINT32 sampleRate; const UINT32 bitsPerSample; ComPtr<IMFTransform> transform; ComPtr<IMFSample> outputSample; std::vector<BYTE> packetBuffer; UINT8 extraData[3]; }; static const UINT32 FrameSize = 1024; UINT32 FindBestBitrateMatch(UINT32 value); UINT32 FindBestChannelsMatch(UINT32 value); UINT32 FindBestBitsPerSampleMatch(UINT32 value); UINT32 FindBestSamplerateMatch(UINT32 value); bool BitrateValid(UINT32 value); bool ChannelsValid(UINT32 value); bool BitsPerSampleValid(UINT32 value); bool SamplerateValid(UINT32 value); }
Palakis/obs-studio
plugins/win-mf/mf-aac-encoder.hpp
C++
gpl-2.0
2,383
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Version info * * @package report * @subpackage courseoverview * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die; $plugin->version = 2013050100; // The current plugin version (Date: YYYYMMDDXX) $plugin->requires = 2013050100; // Requires this Moodle version $plugin->component = 'report_courseoverview'; // Full name of the plugin (used for diagnostics)
sorted2323/msi
testauthorize/report/courseoverview/version.php
PHP
gpl-3.0
1,219
using System; using NLog; using NLog.Targets; using NLog.Targets.Wrappers; class Example { static void Main(string[] args) { try { NLog.Internal.InternalLogger.LogToConsole = true; NLog.Internal.InternalLogger.LogLevel = LogLevel.Trace; Console.WriteLine("Setting up the target..."); MailTarget target = new MailTarget(); target.SmtpServer = "192.168.0.15"; target.From = "jaak@jkowalski.net"; target.To = "jaak@jkowalski.net"; target.Subject = "sample subject"; target.Body = "${message}${newline}"; BufferingTargetWrapper buffer = new BufferingTargetWrapper(target, 5); NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(buffer, LogLevel.Debug); Console.WriteLine("Sending..."); Logger logger = LogManager.GetLogger("Example"); logger.Debug("log message 1"); logger.Debug("log message 2"); logger.Debug("log message 3"); logger.Debug("log message 4"); logger.Debug("log message 5"); logger.Debug("log message 6"); logger.Debug("log message 7"); logger.Debug("log message 8"); // this should send 2 mails - one with messages 1..5, the other with messages 6..8 Console.WriteLine("Sent."); } catch (Exception ex) { Console.WriteLine("EX: {0}", ex); } } }
reasyrf/XBeeMultiTerminal
src/NLog/examples/targets/Configuration API/Mail/Buffered/Example.cs
C#
gpl-3.0
1,532
""" SCGI-->WSGI application proxy, "SWAP". (Originally written by Titus Brown.) This lets an SCGI front-end like mod_scgi be used to execute WSGI application objects. To use it, subclass the SWAP class like so:: class TestAppHandler(swap.SWAP): def __init__(self, *args, **kwargs): self.prefix = '/canal' self.app_obj = TestAppClass swap.SWAP.__init__(self, *args, **kwargs) where 'TestAppClass' is the application object from WSGI and '/canal' is the prefix for what is served by the SCGI Web-server-side process. Then execute the SCGI handler "as usual" by doing something like this:: scgi_server.SCGIServer(TestAppHandler, port=4000).serve() and point mod_scgi (or whatever your SCGI front end is) at port 4000. Kudos to the WSGI folk for writing a nice PEP & the Quixote folk for writing a nice extensible SCGI server for Python! """ import six import sys import time from scgi import scgi_server def debug(msg): timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) sys.stderr.write("[%s] %s\n" % (timestamp, msg)) class SWAP(scgi_server.SCGIHandler): """ SCGI->WSGI application proxy: let an SCGI server execute WSGI application objects. """ app_obj = None prefix = None def __init__(self, *args, **kwargs): assert self.app_obj, "must set app_obj" assert self.prefix is not None, "must set prefix" args = (self,) + args scgi_server.SCGIHandler.__init__(*args, **kwargs) def handle_connection(self, conn): """ Handle an individual connection. """ input = conn.makefile("r") output = conn.makefile("w") environ = self.read_env(input) environ['wsgi.input'] = input environ['wsgi.errors'] = sys.stderr environ['wsgi.version'] = (1, 0) environ['wsgi.multithread'] = False environ['wsgi.multiprocess'] = True environ['wsgi.run_once'] = False # dunno how SCGI does HTTPS signalling; can't test it myself... @CTB if environ.get('HTTPS','off') in ('on','1'): environ['wsgi.url_scheme'] = 'https' else: environ['wsgi.url_scheme'] = 'http' ## SCGI does some weird environ manglement. We need to set ## SCRIPT_NAME from 'prefix' and then set PATH_INFO from ## REQUEST_URI. prefix = self.prefix path = environ['REQUEST_URI'][len(prefix):].split('?', 1)[0] environ['SCRIPT_NAME'] = prefix environ['PATH_INFO'] = path headers_set = [] headers_sent = [] chunks = [] def write(data): chunks.append(data) def start_response(status, response_headers, exc_info=None): if exc_info: try: if headers_sent: # Re-raise original exception if headers sent six.reraise(exc_info[0], exc_info[1], exc_info[2]) finally: exc_info = None # avoid dangling circular ref elif headers_set: raise AssertionError("Headers already set!") headers_set[:] = [status, response_headers] return write ### result = self.app_obj(environ, start_response) try: for data in result: chunks.append(data) # Before the first output, send the stored headers if not headers_set: # Error -- the app never called start_response status = '500 Server Error' response_headers = [('Content-type', 'text/html')] chunks = ["XXX start_response never called"] else: status, response_headers = headers_sent[:] = headers_set output.write('Status: %s\r\n' % status) for header in response_headers: output.write('%s: %s\r\n' % header) output.write('\r\n') for data in chunks: output.write(data) finally: if hasattr(result,'close'): result.close() # SCGI backends use connection closing to signal 'fini'. try: input.close() output.close() conn.close() except IOError as err: debug("IOError while closing connection ignored: %s" % err) def serve_application(application, prefix, port=None, host=None, max_children=None): """ Serve the specified WSGI application via SCGI proxy. ``application`` The WSGI application to serve. ``prefix`` The prefix for what is served by the SCGI Web-server-side process. ``port`` Optional port to bind the SCGI proxy to. Defaults to SCGIServer's default port value. ``host`` Optional host to bind the SCGI proxy to. Defaults to SCGIServer's default host value. ``host`` Optional maximum number of child processes the SCGIServer will spawn. Defaults to SCGIServer's default max_children value. """ class SCGIAppHandler(SWAP): def __init__ (self, *args, **kwargs): self.prefix = prefix self.app_obj = application SWAP.__init__(self, *args, **kwargs) kwargs = dict(handler_class=SCGIAppHandler) for kwarg in ('host', 'port', 'max_children'): if locals()[kwarg] is not None: kwargs[kwarg] = locals()[kwarg] scgi_server.SCGIServer(**kwargs).serve()
endlessm/chromium-browser
third_party/catapult/third_party/Paste/paste/util/scgiserver.py
Python
bsd-3-clause
5,612
<?php /** * CodeIgniter * * An open source application development framework for PHP * * This content is released under the MIT License (MIT) * * Copyright (c) 2014 - 2016, British Columbia Institute of Technology * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @package CodeIgniter * @author EllisLab Dev Team * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) * @copyright Copyright (c) 2014 - 2016, British Columbia Institute of Technology (http://bcit.ca/) * @license http://opensource.org/licenses/MIT MIT License * @link https://codeigniter.com * @since Version 2.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); /** * Utf8 Class * * Provides support for UTF-8 environments * * @package CodeIgniter * @subpackage Libraries * @category UTF-8 * @author EllisLab Dev Team * @link https://codeigniter.com/user_guide/libraries/utf8.html */ class CI_Utf8 { /** * Class constructor * * Determines if UTF-8 support is to be enabled. * * @return void */ public function __construct() { if ( defined('PREG_BAD_UTF8_ERROR') // PCRE must support UTF-8 && (ICONV_ENABLED === TRUE OR MB_ENABLED === TRUE) // iconv or mbstring must be installed && strtoupper(config_item('charset')) === 'UTF-8' // Application charset must be UTF-8 ) { define('UTF8_ENABLED', TRUE); log_message('info', 'UTF-8 Support Enabled'); } else { define('UTF8_ENABLED', FALSE); log_message('info', 'UTF-8 Support Disabled'); } log_message('info', 'Utf8 Class Initialized'); } // -------------------------------------------------------------------- /** * Clean UTF-8 strings * * Ensures strings contain only valid UTF-8 characters. * * @param string $str String to clean * @return string */ public function clean_string($str) { if ($this->is_ascii($str) === FALSE) { if (MB_ENABLED) { $str = mb_convert_encoding($str, 'UTF-8', 'UTF-8'); } elseif (ICONV_ENABLED) { $str = @iconv('UTF-8', 'UTF-8//IGNORE', $str); } } return $str; } // -------------------------------------------------------------------- /** * Remove ASCII control characters * * Removes all ASCII control characters except horizontal tabs, * line feeds, and carriage returns, as all others can cause * problems in XML. * * @param string $str String to clean * @return string */ public function safe_ascii_for_xml($str) { return remove_invisible_characters($str, FALSE); } // -------------------------------------------------------------------- /** * Convert to UTF-8 * * Attempts to convert a string to UTF-8. * * @param string $str Input string * @param string $encoding Input encoding * @return string $str encoded in UTF-8 or FALSE on failure */ public function convert_to_utf8($str, $encoding) { if (MB_ENABLED) { return mb_convert_encoding($str, 'UTF-8', $encoding); } elseif (ICONV_ENABLED) { return @iconv($encoding, 'UTF-8', $str); } return FALSE; } // -------------------------------------------------------------------- /** * Is ASCII? * * Tests if a string is standard 7-bit ASCII or not. * * @param string $str String to check * @return bool */ public function is_ascii($str) { return (preg_match('/[^\x00-\x7F]/S', $str) === 0); } }
emelyan1987/FoodDelivery
tests/system/core/Utf8.php
PHP
mit
4,412
/** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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. */ /*jshint evil:true*/ require('mock-modules').autoMockOff(); describe('static type function syntax', function() { var flowSyntaxVisitors; var jstransform; beforeEach(function() { require('mock-modules').dumpCache(); flowSyntaxVisitors = require('../type-syntax.js').visitorList; jstransform = require('jstransform'); }); function transform(code, visitors) { code = code.join('\n'); // We run the flow transform first code = jstransform.transform( flowSyntaxVisitors, code ).code; if (visitors) { code = jstransform.transform( visitors, code ).code; } return code; } describe('param type annotations', () => { it('strips single param annotation', () => { var code = transform([ 'function foo(param1: bool) {', ' return param1;', '}', '', 'var bar = function(param1: bool) {', ' return param1;', '}' ]); eval(code); expect(foo(42)).toBe(42); expect(bar(42)).toBe(42); }); it('strips multiple param annotations', () => { var code = transform([ 'function foo(param1: bool, param2: number) {', ' return [param1, param2];', '}', '', 'var bar = function(param1: bool, param2: number) {', ' return [param1, param2];', '}' ]); eval(code); expect(foo(true, 42)).toEqual([true, 42]); expect(bar(true, 42)).toEqual([true, 42]); }); it('strips higher-order param annotations', () => { var code = transform([ 'function foo(param1: (_:bool) => number) {', ' return param1;', '}', '', 'var bar = function(param1: (_:bool) => number) {', ' return param1;', '}' ]); eval(code); var callback = function(param) { return param ? 42 : 0; }; expect(foo(callback)).toBe(callback); expect(bar(callback)).toBe(callback); }); it('strips annotated params next to non-annotated params', () => { var code = transform([ 'function foo(param1, param2: number) {', ' return [param1, param2];', '}', '', 'var bar = function(param1, param2: number) {', ' return [param1, param2];', '}' ]); eval(code); expect(foo('p1', 42)).toEqual(['p1', 42]); expect(bar('p1', 42)).toEqual(['p1', 42]); }); it('strips annotated params before a rest parameter', () => { var restParamVisitors = require('../es6-rest-param-visitors').visitorList; var code = transform([ 'function foo(param1: number, ...args) {', ' return [param1, args];', '}', '', 'var bar = function(param1: number, ...args) {', ' return [param1, args];', '}' ], restParamVisitors); eval(code); expect(foo(42, 43, 44)).toEqual([42, [43, 44]]); expect(bar(42, 43, 44)).toEqual([42, [43, 44]]); }); it('strips annotated rest parameter', () => { var restParamVisitors = require('../es6-rest-param-visitors').visitorList; var code = transform([ 'function foo(param1: number, ...args: Array<number>) {', ' return [param1, args];', '}', '', 'var bar = function(param1: number, ...args: Array<number>) {', ' return [param1, args];', '}' ], restParamVisitors); eval(code); expect(foo(42, 43, 44)).toEqual([42, [43, 44]]); expect(bar(42, 43, 44)).toEqual([42, [43, 44]]); }); it('strips optional param marker without type annotation', () => { var code = transform([ 'function foo(param1?, param2 ?) {', ' return 42;', '}' ]); eval(code); expect(foo()).toBe(42); }); it('strips optional param marker with type annotation', () => { var code = transform([ 'function foo(param1?:number, param2 ?: string, param3 ? : bool) {', ' return 42;', '}' ]); eval(code); expect(foo()).toBe(42); }); }); describe('return type annotations', () => { it('strips function return types', () => { var code = transform([ 'function foo(param1:number): () => number {', ' return function() { return param1; };', '}', '', 'var bar = function(param1:number): () => number {', ' return function() { return param1; };', '}' ]); eval(code); expect(foo(42)()).toBe(42); expect(bar(42)()).toBe(42); }); it('strips void return types', () => { var code = transform([ 'function foo(param1): void {', ' param1();', '}', '', 'var bar = function(param1): void {', ' param1();', '}' ]); eval(code); var counter = 0; function testFn() { counter++; } foo(testFn); expect(counter).toBe(1); bar(testFn); expect(counter).toBe(2); }); it('strips void return types with rest params', () => { var code = transform( [ 'function foo(param1, ...rest): void {', ' param1();', '}', '', 'var bar = function(param1, ...rest): void {', ' param1();', '}' ], require('../es6-rest-param-visitors').visitorList ); eval(code); var counter = 0; function testFn() { counter++; } foo(testFn); expect(counter).toBe(1); bar(testFn); expect(counter).toBe(2); }); it('strips object return types', () => { var code = transform([ 'function foo(param1:number): {num: number} {', ' return {num: param1};', '}', '', 'var bar = function(param1:number): {num: number} {', ' return {num: param1};', '}' ]); eval(code); expect(foo(42)).toEqual({num: 42}); expect(bar(42)).toEqual({num: 42}); }); }); describe('parametric type annotation', () => { it('strips parametric type annotations', () => { var code = transform([ 'function foo<T>(param1) {', ' return param1;', '}', '', 'var bar = function<T>(param1) {', ' return param1;', '}', ]); eval(code); expect(foo(42)).toBe(42); expect(bar(42)).toBe(42); }); it('strips multi-parameter type annotations', () => { var restParamVisitors = require('../es6-rest-param-visitors').visitorList; var code = transform([ 'function foo<T, S>(param1) {', ' return param1;', '}', '', 'var bar = function<T,S>(param1) {', ' return param1;', '}' ], restParamVisitors); eval(code); expect(foo(42)).toBe(42); expect(bar(42)).toBe(42); }); }); describe('arrow functions', () => { // TODO: We don't currently support arrow functions, but we should // soon! The only reason we don't now is because we don't // need it at this very moment and I'm in a rush to get the // basics in. }); });
demns/todomvc-perf-comparison
todomvc/react/node_modules/reactify/node_modules/react-tools/node_modules/jstransform/visitors/__tests__/type-function-syntax-test.js
JavaScript
mit
7,860
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Service * @subpackage DeveloperGarden * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** * @see Zend_Service_DeveloperGarden_Response_ConferenceCall_ConferenceCallAbstract */ require_once 'Zend/Service/DeveloperGarden/Response/ConferenceCall/ConferenceCallAbstract.php'; /** * @category Zend * @package Zend_Service * @subpackage DeveloperGarden * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @author Marco Kaiser * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Service_DeveloperGarden_Response_ConferenceCall_GetRunningConferenceResponse extends Zend_Service_DeveloperGarden_Response_ConferenceCall_ConferenceCallAbstract { /** * response data * * @var Zend_Service_DeveloperGarden_Response_ConferenceCall_GetRunningConferenceResponseType */ public $getRunningConferenceResponse = null; }
angusty/symfony-study
vendor/Zend/Service/DeveloperGarden/Response/ConferenceCall/GetRunningConferenceResponse.php
PHP
mit
1,572
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="it_IT"> <context> <name>VTranslateMeasurements</name> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="190"/> <source>height</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>altezza</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="192"/> <source>Height: Total</source> <comment>Full measurement name.</comment> <translation>Altezza: Total</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="193"/> <source>Vertical distance from crown of head to floor.</source> <comment>Full measurement description.</comment> <translation>Distanza verticale dalla parte superiore della testa al pavimento.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="197"/> <source>height_neck_back</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>altezza_collo_dietro</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="199"/> <source>Height: Neck Back</source> <comment>Full measurement name.</comment> <translation>Altezza: Collo Dietro</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="200"/> <source>Vertical distance from the Neck Back (cervicale vertebra) to the floor.</source> <comment>Full measurement description.</comment> <translation>Distanza verticale da Collo Dietro (vertebra cervicale) al pavimento.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="204"/> <source>height_scapula</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>altezza_scapola</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="206"/> <source>Height: Scapula</source> <comment>Full measurement name.</comment> <translation>Altezza: Scapola</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="207"/> <source>Vertical distance from the Scapula (Blade point) to the floor.</source> <comment>Full measurement description.</comment> <translation>Distanza verticale dalla Scapola (punto più esterno della scapola) al pavimento.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="211"/> <source>height_armpit</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>altezza_ascella</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="213"/> <source>Height: Armpit</source> <comment>Full measurement name.</comment> <translation>Altezza: Ascella</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="214"/> <source>Vertical distance from the Armpit to the floor.</source> <comment>Full measurement description.</comment> <translation>Distanza verticale dall&apos;Ascella al pavimento.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="218"/> <source>height_waist_side</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>altezza_vita_fianco</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="220"/> <source>Height: Waist Side</source> <comment>Full measurement name.</comment> <translation>Altezza: Vita Fianco</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="221"/> <source>Vertical distance from the Waist Side to the floor.</source> <comment>Full measurement description.</comment> <translation>Distanza verticale dal Fianco Vita al pavimento.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="225"/> <source>height_hip</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>altezza_anca</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="227"/> <source>Height: Hip</source> <comment>Full measurement name.</comment> <translation>Altezza: Anca</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="228"/> <source>Vertical distance from the Hip level to the floor.</source> <comment>Full measurement description.</comment> <translation>Distanza verticale dal livello Anca al pavimento.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="232"/> <source>height_gluteal_fold</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>altezza_piega_gluteo</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="234"/> <source>Height: Gluteal Fold</source> <comment>Full measurement name.</comment> <translation>Altezza: Piega Gluteo</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="235"/> <source>Vertical distance from the Gluteal fold, where the Gluteal muscle meets the top of the back thigh, to the floor.</source> <comment>Full measurement description.</comment> <translation>Distanza verticale dalla piega del Gluteo, dove il muscolo del Gluteo incontra la parte superiore della coscia dietro, al pavimento.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="239"/> <source>height_knee</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>altezza_ginocchio</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="241"/> <source>Height: Knee</source> <comment>Full measurement name.</comment> <translation>Altezza: Ginocchio</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="242"/> <source>Vertical distance from the fold at the back of the Knee to the floor.</source> <comment>Full measurement description.</comment> <translation>Distanza verticale dalla piega dietro il ginocchio al pavimento.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="246"/> <source>height_calf</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>altezza_polpaccio</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="248"/> <source>Height: Calf</source> <comment>Full measurement name.</comment> <translation>Altezza: Polpaccio</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="249"/> <source>Vertical distance from the widest point of the calf to the floor.</source> <comment>Full measurement description.</comment> <translation>Distanza verticale dal punto più ampio del polpaccio al pavimento.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="253"/> <source>height_ankle_high</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>altezza_caviglia_alto</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="255"/> <source>Height: Ankle High</source> <comment>Full measurement name.</comment> <translation>Altezza: Caviglia Alta</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="256"/> <source>Vertical distance from the deepest indentation of the back of the ankle to the floor.</source> <comment>Full measurement description.</comment> <translation>Distanza verticale dal rientro più profondo della parte posteriore della caviglia al pavimento .</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="260"/> <source>height_ankle</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>altezza_caviglia</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="262"/> <source>Height: Ankle</source> <comment>Full measurement name.</comment> <translation>Altezza: Caviglia</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="263"/> <source>Vertical distance from point where the front leg meets the foot to the floor.</source> <comment>Full measurement description.</comment> <translation>Distanza verticale dal punto dove la gamba di fronte incontra il piede al pavimento.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="267"/> <source>height_highhip</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>altezza_ancasuperiore</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="269"/> <source>Height: Highhip</source> <comment>Full measurement name.</comment> <translation>Altezza: Anca superiore</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="270"/> <source>Vertical distance from the Highhip level, where front abdomen is most prominent, to the floor.</source> <comment>Full measurement description.</comment> <translation>Distanza verticale dal livello superiore Anca, dove l&apos;addome anteriore è più sporgente, al pavimento.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="274"/> <source>height_waist_front</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>altezza_vita_davanti</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="276"/> <source>Height: Waist Front</source> <comment>Full measurement name.</comment> <translation>Altezza: Vita Davanti</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="277"/> <source>Vertical distance from the Waist Front to the floor.</source> <comment>Full measurement description.</comment> <translation>Distanza verticale dalla Vita Davanti al pavimento.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="281"/> <source>height_bustpoint</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>altezza_seno</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="283"/> <source>Height: Bustpoint</source> <comment>Full measurement name.</comment> <translation>Altezza: Seno</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="284"/> <source>Vertical distance from Bustpoint to the floor.</source> <comment>Full measurement description.</comment> <translation>Distanza verticale dal Seno al pavimento.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="288"/> <source>height_shoulder_tip</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>altezza_spalla_punta</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="290"/> <source>Height: Shoulder Tip</source> <comment>Full measurement name.</comment> <translation>Altezza: Punta Spalla</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="291"/> <source>Vertical distance from the Shoulder Tip to the floor.</source> <comment>Full measurement description.</comment> <translation>Distanza verticale dalla Punta della Spalla al pavimento.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="295"/> <source>height_neck_front</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>altezza_collo_fronte</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="297"/> <source>Height: Neck Front</source> <comment>Full measurement name.</comment> <translation>Altezza: Collo Fronte</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="298"/> <source>Vertical distance from the Neck Front to the floor.</source> <comment>Full measurement description.</comment> <translation>Distanza verticale dal Collo Davanti al pavimento.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="302"/> <source>height_neck_side</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>altezza_lato_collo</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="304"/> <source>Height: Neck Side</source> <comment>Full measurement name.</comment> <translation>Altezza: Lato Collo</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="305"/> <source>Vertical distance from the Neck Side to the floor.</source> <comment>Full measurement description.</comment> <translation>Distanza verticale dal Lato Collo al pavimento.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="309"/> <source>height_neck_back_to_knee</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>altezza_collo_dietro_al_ginocchio</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="311"/> <source>Height: Neck Back to Knee</source> <comment>Full measurement name.</comment> <translation>Altezza: Collo Dietro al Ginocchio</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="312"/> <source>Vertical distance from the Neck Back (cervicale vertebra) to the fold at the back of the knee.</source> <comment>Full measurement description.</comment> <translation>Distanza verticale dal Collo Dietro (vertebra cervicale) alla piega dietro del ginocchio.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="316"/> <source>height_waist_side_to_knee</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>altezza_lato_vita_al_ginocchio</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="318"/> <source>Height: Waist Side to Knee</source> <comment>Full measurement name.</comment> <translation>Altezza: Lato Vita al Ginocchio</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="319"/> <source>Vertical distance from the Waist Side to the fold at the back of the knee.</source> <comment>Full measurement description.</comment> <translation>Distanza verticale dal Lato Vita alla piega dietro al ginocchio.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="324"/> <source>height_waist_side_to_hip</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>altezza_lato_vita_al_fianco</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="326"/> <source>Height: Waist Side to Hip</source> <comment>Full measurement name.</comment> <translation>Altezza: Lato Vita al Fianco</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="327"/> <source>Vertical distance from the Waist Side to the Hip level.</source> <comment>Full measurement description.</comment> <translation>Distanza verticale dal Lato Vita al Livello Fianco.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="331"/> <source>height_knee_to_ankle</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>altezza_ginocchio_ad_anca</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="333"/> <source>Height: Knee to Ankle</source> <comment>Full measurement name.</comment> <translation>Altezza: Ginocchio all&apos;Anca</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="334"/> <source>Vertical distance from the fold at the back of the knee to the point where the front leg meets the top of the foot.</source> <comment>Full measurement description.</comment> <translation>Distanza verticale dalla piega dietro del ginocchio al punto dove la parte frontale della gamba incontra la parte superiore del piede.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="338"/> <source>height_neck_back_to_waist_side</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>altezza_collo_dietro_al_lato_vita</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="340"/> <source>Height: Neck Back to Waist Side</source> <comment>Full measurement name.</comment> <translation>Altezza: Collo Dietro al Lato Vita</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="341"/> <source>Vertical distance from Neck Back to Waist Side. (&apos;Height: Neck Back&apos; - &apos;Height: Waist Side&apos;).</source> <comment>Full measurement description.</comment> <translation>Distanza verticale dal Collo Dietro al Lato Vita. (&apos;Altezza:Collo Dietro&apos;-&apos;Altezza:Lato Vita&apos;).</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="364"/> <source>width_shoulder</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>larghezza_spalla</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="366"/> <source>Width: Shoulder</source> <comment>Full measurement name.</comment> <translation>Larghezza: Spalla</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="367"/> <source>Horizontal distance from Shoulder Tip to Shoulder Tip.</source> <comment>Full measurement description.</comment> <translation>Distanza orizzontale da una Punta della Spalla all&apos;altra Punta della Spalla.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="371"/> <source>width_bust</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>larghezza_busto</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="373"/> <source>Width: Bust</source> <comment>Full measurement name.</comment> <translation>Larghezza: Busto</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="374"/> <source>Horizontal distance from Bust Side to Bust Side.</source> <comment>Full measurement description.</comment> <translation>Distanza orizzontale da Fianco a Fianco del Busto. </translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="378"/> <source>width_waist</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>larghezza_vita</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="380"/> <source>Width: Waist</source> <comment>Full measurement name.</comment> <translation>Larghezza: Vita</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="381"/> <source>Horizontal distance from Waist Side to Waist Side.</source> <comment>Full measurement description.</comment> <translation>Distanza orizzontale da Fianco a Fianco della Vita.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="385"/> <source>width_hip</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>larghezza_anca</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="387"/> <source>Width: Hip</source> <comment>Full measurement name.</comment> <translation>Larghezza: Anca</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="388"/> <source>Horizontal distance from Hip Side to Hip Side.</source> <comment>Full measurement description.</comment> <translation>Distanza orizzontale dal Fianco a Fianco dell&apos;Anca.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="392"/> <source>width_abdomen_to_hip</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>larghezza_ventre_a_anca</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="394"/> <source>Width: Abdomen to Hip</source> <comment>Full measurement name.</comment> <translation>Larghezza:Ventre ad Anca</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="395"/> <source>Horizontal distance from the greatest abdomen prominence to the greatest hip prominence.</source> <comment>Full measurement description.</comment> <translation>Distanza orizzontale dal punto più esterno dell&apos;addome fino al punto più prominente dei fianchi.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="411"/> <source>indent_neck_back</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>tacca_collo_dietro</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="413"/> <source>Indent: Neck Back</source> <comment>Full measurement name.</comment> <translation>Tacca: Collo Dietro</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="414"/> <source>Horizontal distance from Scapula (Blade point) to the Neck Back.</source> <comment>Full measurement description.</comment> <translation>Distanza orizzontale tra Scapola (punto più esterno) al Collo Dietro.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="418"/> <source>indent_waist_back</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>tacca_vita_dietro</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="420"/> <source>Indent: Waist Back</source> <comment>Full measurement name.</comment> <translation>Tacca: Vita Dietro</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="421"/> <source>Horizontal distance between a flat stick, placed to touch Hip and Scapula, and Waist Back.</source> <comment>Full measurement description.</comment> <translation>Distanza orizzontale tra un bastoncino piatto, posto a toccare anca e scapola, e vita posteriore.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="425"/> <source>indent_ankle_high</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>tacca_caviglia_alta</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="427"/> <source>Indent: Ankle High</source> <comment>Full measurement name.</comment> <translation>Tacca: Caviglia Alta</translation> </message> <message> <source>Horizontal Distance betwee a flat stick, placed perpendicular to Heel, and the greatest indentation of Ankle.</source> <comment>Full measurement description.</comment> <translation type="vanished">Distanza orizzontale tra un bastoncino piatto, posto perpendicolare al tallone e la rientranza più profonda della caviglia.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="444"/> <source>hand_palm_length</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>lunghezza_palmo_mano</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="446"/> <source>Hand: Palm length</source> <comment>Full measurement name.</comment> <translation>Mano: lunghezza palmo</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="447"/> <source>Length from Wrist line to base of middle finger.</source> <comment>Full measurement description.</comment> <translation>Lunghezza dalla linea del polso alla base del dito medio.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="451"/> <source>hand_length</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>lunghezza_mano</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="453"/> <source>Hand: Length</source> <comment>Full measurement name.</comment> <translation>Mano: Lunghezza</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="454"/> <source>Length from Wrist line to end of middle finger.</source> <comment>Full measurement description.</comment> <translation>Lunghezza dalla linea del Polso alla fine del dito medio.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="458"/> <source>hand_palm_width</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>larghezza_palmo_mano</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="460"/> <source>Hand: Palm width</source> <comment>Full measurement name.</comment> <translation>Mano: larghezza Palmo</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="461"/> <source>Measure where Palm is widest.</source> <comment>Full measurement description.</comment> <translation>Misura dove il palmo è più largo.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="464"/> <source>hand_palm_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>circonferenza_palmo_mano</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="466"/> <source>Hand: Palm circumference</source> <comment>Full measurement name.</comment> <translation>Mano: circonferenza Palmo</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="467"/> <source>Circumference where Palm is widest.</source> <comment>Full measurement description.</comment> <translation>Circonferenza dove il palmo è più largo.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="470"/> <source>hand_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>circ_mano</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="472"/> <source>Hand: Circumference</source> <comment>Full measurement name.</comment> <translation>Mano: Circonferenza</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="473"/> <source>Tuck thumb toward smallest finger, bring fingers close together. Measure circumference around widest part of hand.</source> <comment>Full measurement description.</comment> <translation>Piega il pollice verso il dito più piccolo, avvicina le dita. Misura la circonferenza attorno alla parte più larga della mano.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="489"/> <source>foot_width</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>larghezza_piede</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="491"/> <source>Foot: Width</source> <comment>Full measurement name.</comment> <translation>Piede: Larghezza</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="492"/> <source>Measure at widest part of foot.</source> <comment>Full measurement description.</comment> <translation>Misura della parte più larga del piede.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="495"/> <source>foot_length</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>lunghezza_piede</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="497"/> <source>Foot: Length</source> <comment>Full measurement name.</comment> <translation>Piede: Lunghezza</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="498"/> <source>Measure from back of heel to end of longest toe.</source> <comment>Full measurement description.</comment> <translation>Misura dal retro del tallone alla fine del dito del piede più lungo.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="502"/> <source>foot_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>circ_piede</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="504"/> <source>Foot: Circumference</source> <comment>Full measurement name.</comment> <translation>Piede: Circonferenza</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="505"/> <source>Measure circumference around widest part of foot.</source> <comment>Full measurement description.</comment> <translation>Misura circonferenza attorno alla parte del piede più larga.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="509"/> <source>foot_instep_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>collodel_piede_circ</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="511"/> <source>Foot: Instep circumference</source> <comment>Full measurement name.</comment> <translation>Piede: collo del piede circonferenza</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="512"/> <source>Measure circumference at tallest part of instep.</source> <comment>Full measurement description.</comment> <translation>Misura circonferenza alla parte più alta del collo del piede.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="528"/> <source>head_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>testa_circ</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="530"/> <source>Head: Circumference</source> <comment>Full measurement name.</comment> <translation>Testa: Circonferenza</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="531"/> <source>Measure circumference at largest level of head.</source> <comment>Full measurement description.</comment> <translation>Misura circonferenza al punto più largo della testa.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="535"/> <source>head_length</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>lunghezza_testa</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="537"/> <source>Head: Length</source> <comment>Full measurement name.</comment> <translation>Testa: Lunghezza</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="538"/> <source>Vertical distance from Head Crown to bottom of jaw.</source> <comment>Full measurement description.</comment> <translation>Distanza verticale dalla parte più alta della testa al fondo della mascella.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="542"/> <source>head_depth</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>testa_profondità</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="544"/> <source>Head: Depth</source> <comment>Full measurement name.</comment> <translation>Testa: Profondità</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="545"/> <source>Horizontal distance from front of forehead to back of head.</source> <comment>Full measurement description.</comment> <translation>Distanza orizzontale dalla fronte al retro della testa.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="549"/> <source>head_width</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>altezza_larghezza</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="551"/> <source>Head: Width</source> <comment>Full measurement name.</comment> <translation>Testa: Larghezza</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="552"/> <source>Horizontal distance from Head Side to Head Side, where Head is widest.</source> <comment>Full measurement description.</comment> <translation>Distanza orizzontale da lato a lato della testa, dove è più larga.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="556"/> <source>head_crown_to_neck_back</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>sommità_testa_al_collo_dietro</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="558"/> <source>Head: Crown to Neck Back</source> <comment>Full measurement name.</comment> <translation>Testa: Sommità al Collo Dietro</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="559"/> <source>Vertical distance from Crown to Neck Back. (&apos;Height: Total&apos; - &apos;Height: Neck Back&apos;).</source> <comment>Full measurement description.</comment> <translation>Distanza verticale dalla Sommità della testa al Collo Dietro. (&apos;Altezza: Totale&apos; - &apos;Altezza: Collo Dietro&apos;).</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="563"/> <source>head_chin_to_neck_back</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>testa_mento_al_collo_dietro</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="565"/> <source>Head: Chin to Neck Back</source> <comment>Full measurement name.</comment> <translation>Testa: Mento al Collo Dietro</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="566"/> <source>Vertical distance from Chin to Neck Back. (&apos;Height&apos; - &apos;Height: Neck Back&apos; - &apos;Head: Length&apos;)</source> <comment>Full measurement description.</comment> <translation>Distanza verticale dal Mento al Collo Dietro. (&apos;Altezza&apos; - &apos;Altezza: Collo Dietro&apos; - &apos;Testa: Lunghezza&apos;)</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="583"/> <source>neck_mid_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>collo_medio_circ</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="585"/> <source>Neck circumference, midsection</source> <comment>Full measurement name.</comment> <translation>Circonferenza Collo, sezione di mezzo</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="586"/> <source>Circumference of Neck midsection, about halfway between jaw and torso.</source> <comment>Full measurement description.</comment> <translation>Circonferenza della parte media del collo, circa a metà strada tra la mascella e il tronco.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="590"/> <source>neck_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>collo_circ</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="592"/> <source>Neck circumference</source> <comment>Full measurement name.</comment> <translation>Circonferenza collo</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="593"/> <source>Neck circumference at base of Neck, touching Neck Back, Neck Sides, and Neck Front.</source> <comment>Full measurement description.</comment> <translation>Circonferenza collo alla base del Collo, toccando Dietro il Collo, i Lati del Collo e Parte Anteriore del Collo.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="598"/> <source>highbust_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>torace_circ</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="600"/> <source>Highbust circumference</source> <comment>Full measurement name.</comment> <translation>Circonferenza torace</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="601"/> <source>Circumference at Highbust, following shortest distance between Armfolds across chest, high under armpits.</source> <comment>Full measurement description.</comment> <translation>Circonferenza del torace, seguendo la distanza più corta tra le braccia incrociate sul petto, la parte superiore sotto le ascelle.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="605"/> <source>bust_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>busto_circ</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="607"/> <source>Bust circumference</source> <comment>Full measurement name.</comment> <translation>Circonferenza busto</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="608"/> <source>Circumference around Bust, parallel to floor.</source> <comment>Full measurement description.</comment> <translation>Circonferenza attorno al busto, parallelo al pavimento.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="612"/> <source>lowbust_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>basso_torace_circ</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="614"/> <source>Lowbust circumference</source> <comment>Full measurement name.</comment> <translation>Circonferenza basso torace</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="615"/> <source>Circumference around LowBust under the breasts, parallel to floor.</source> <comment>Full measurement description.</comment> <translation>Circonferenza del basso torace sotto il seno, parallela al pavimento</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="619"/> <source>rib_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>costola_circ</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="621"/> <source>Rib circumference</source> <comment>Full measurement name.</comment> <translation>Circonferenza costola</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="622"/> <source>Circumference around Ribs at level of the lowest rib at the side, parallel to floor.</source> <comment>Full measurement description.</comment> <translation>Circonferenza attorno alle costole, all&apos;altezza della costola più bassa laterale, parallelo al pavimento.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="627"/> <source>waist_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>vita_circ</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="629"/> <source>Waist circumference</source> <comment>Full measurement name.</comment> <translation>Circonferenza vita</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="635"/> <source>highhip_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>fiancoalto_circ</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="637"/> <source>Highhip circumference</source> <comment>Full measurement name.</comment> <translation>Circonferenza parte alta delle anche</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="630"/> <source>Circumference around Waist, following natural contours. Waists are typically higher in back.</source> <comment>Full measurement description.</comment> <translation>Circonferenza attorno alle anche, seguendo il contorno naturale. Le anche di solito sono più alte dietro.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="345"/> <source>height_waist_back</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>altezza_vita_dietro</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="347"/> <source>Height: Waist Back</source> <comment>Full measurement name.</comment> <translation>Altezza: Anca Posteriore</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="348"/> <source>Vertical height from Waist Back to floor. (&apos;Height: Waist Front&apos;&apos; - &apos;Leg: Crotch to floor&apos;&apos;).</source> <comment>Full measurement description.</comment> <translation>Altezza verticale dalla vita dietro al pavimento. (&apos;Altezza: Vita Davanti&quot; - &apos;Gamba: Cavallo al pavimento&quot;).</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="428"/> <source>Horizontal Distance between a flat stick, placed perpendicular to Heel, and the greatest indentation of Ankle.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="638"/> <source>Circumference around Highhip, where Abdomen protrusion is greatest, parallel to floor.</source> <comment>Full measurement description.</comment> <translation>Circonferenza attorno alle Anche, dove l&apos;Addome sporge maggiormente, parallelo al pavimento.</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="643"/> <source>hip_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation>anche_circ</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="645"/> <source>Hip circumference</source> <comment>Full measurement name.</comment> <translation>Circonferenza anche</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="646"/> <source>Circumference around Hip where Hip protrusion is greatest, parallel to floor.</source> <comment>Full measurement description.</comment> <translation>Circonferenza fianchi nel punto dove i fianchi sono più larghi, parallela al pavimento</translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="651"/> <source>neck_arc_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="653"/> <source>Neck arc, front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="654"/> <source>From Neck Side to Neck Side through Neck Front.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="658"/> <source>highbust_arc_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="660"/> <source>Highbust arc, front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="661"/> <source>From Highbust Side (Armpit) to HIghbust Side (Armpit) across chest.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="665"/> <source>bust_arc_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="667"/> <source>Bust arc, front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="668"/> <source>From Bust Side to Bust Side across chest.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="672"/> <source>size</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="674"/> <source>Size</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="675"/> <source>Same as bust_arc_f.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="679"/> <source>lowbust_arc_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="681"/> <source>Lowbust arc, front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="682"/> <source>From Lowbust Side to Lowbust Side across front.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="686"/> <source>rib_arc_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="688"/> <source>Rib arc, front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="689"/> <source>From Rib Side to Rib Side, across front.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="693"/> <source>waist_arc_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="695"/> <source>Waist arc, front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="696"/> <source>From Waist Side to Waist Side across front.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="700"/> <source>highhip_arc_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="702"/> <source>Highhip arc, front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="703"/> <source>From Highhip Side to Highhip Side across front.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="707"/> <source>hip_arc_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="709"/> <source>Hip arc, front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="710"/> <source>From Hip Side to Hip Side across Front.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="714"/> <source>neck_arc_half_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="716"/> <source>Neck arc, front, half</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="717"/> <source>Half of &apos;Neck arc, front&apos;. (&apos;Neck arc, front&apos; / 2).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="721"/> <source>highbust_arc_half_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="723"/> <source>Highbust arc, front, half</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="724"/> <source>Half of &apos;Highbust arc, front&apos;. From Highbust Front to Highbust Side. (&apos;Highbust arc, front&apos; / 2).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="729"/> <source>bust_arc_half_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="731"/> <source>Bust arc, front, half</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="732"/> <source>Half of &apos;Bust arc, front&apos;. (&apos;Bust arc, front&apos;/2).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="736"/> <source>lowbust_arc_half_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="738"/> <source>Lowbust arc, front, half</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="739"/> <source>Half of &apos;Lowbust arc, front&apos;. (&apos;Lowbust Arc, front&apos; / 2).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="743"/> <source>rib_arc_half_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="745"/> <source>Rib arc, front, half</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="746"/> <source>Half of &apos;Rib arc, front&apos;. (&apos;Rib Arc, front&apos; / 2).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="750"/> <source>waist_arc_half_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="752"/> <source>Waist arc, front, half</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="753"/> <source>Half of &apos;Waist arc, front&apos;. (&apos;Waist arc, front&apos; / 2).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="757"/> <source>highhip_arc_half_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="759"/> <source>Highhip arc, front, half</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="760"/> <source>Half of &apos;Highhip arc, front&apos;. (&apos;Highhip arc, front&apos; / 2).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="764"/> <source>hip_arc_half_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="766"/> <source>Hip arc, front, half</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="767"/> <source>Half of &apos;Hip arc, front&apos;. (&apos;Hip arc, front&apos; / 2).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="771"/> <source>neck_arc_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="773"/> <source>Neck arc, back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="774"/> <source>From Neck Side to Neck Side across back. (&apos;Neck circumference&apos; - &apos;Neck arc, front&apos;).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="779"/> <source>highbust_arc_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="781"/> <source>Highbust arc, back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="782"/> <source>From Highbust Side to Highbust Side across back. (&apos;Highbust circumference&apos; - &apos;Highbust arc, front&apos;).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="786"/> <source>bust_arc_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="788"/> <source>Bust arc, back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="789"/> <source>From Bust Side to Bust Side across back. (&apos;Bust circumference&apos; - &apos;Bust arc, front&apos;).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="794"/> <source>lowbust_arc_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="796"/> <source>Lowbust arc, back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="797"/> <source>From Lowbust Side to Lowbust Side across back. (&apos;Lowbust circumference&apos; - &apos;Lowbust arc, front&apos;).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="802"/> <source>rib_arc_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="804"/> <source>Rib arc, back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="805"/> <source>From Rib Side to Rib side across back. (&apos;Rib circumference&apos; - &apos;Rib arc, front&apos;).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="810"/> <source>waist_arc_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="812"/> <source>Waist arc, back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="813"/> <source>From Waist Side to Waist Side across back. (&apos;Waist circumference&apos; - &apos;Waist arc, front&apos;).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="818"/> <source>highhip_arc_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="820"/> <source>Highhip arc, back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="821"/> <source>From Highhip Side to Highhip Side across back. (&apos;Highhip circumference&apos; - &apos;Highhip arc, front&apos;).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="826"/> <source>hip_arc_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="828"/> <source>Hip arc, back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="829"/> <source>From Hip Side to Hip Side across back. (&apos;Hip circumference&apos; - &apos;Hip arc, front&apos;).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="834"/> <source>neck_arc_half_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="836"/> <source>Neck arc, back, half</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="837"/> <source>Half of &apos;Neck arc, back&apos;. (&apos;Neck arc, back&apos; / 2).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="841"/> <source>highbust_arc_half_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="843"/> <source>Highbust arc, back, half</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="844"/> <source>Half of &apos;Highbust arc, back&apos;. From Highbust Back to Highbust Side. (&apos;Highbust arc, back&apos; / 2).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="849"/> <source>bust_arc_half_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="851"/> <source>Bust arc, back, half</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="852"/> <source>Half of &apos;Bust arc, back&apos;. (&apos;Bust arc, back&apos; / 2).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="856"/> <source>lowbust_arc_half_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="858"/> <source>Lowbust arc, back, half</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="859"/> <source>Half of &apos;Lowbust Arc, back&apos;. (&apos;Lowbust arc, back&apos; / 2).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="863"/> <source>rib_arc_half_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="865"/> <source>Rib arc, back, half</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="866"/> <source>Half of &apos;Rib arc, back&apos;. (&apos;Rib arc, back&apos; / 2).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="870"/> <source>waist_arc_half_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="872"/> <source>Waist arc, back, half</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="873"/> <source>Half of &apos;Waist arc, back&apos;. (&apos;Waist arc, back&apos; / 2).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="877"/> <source>highhip_arc_half_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="879"/> <source>Highhip arc, back, half</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="880"/> <source>Half of &apos;Highhip arc, back&apos;. From Highhip Back to Highbust Side. (&apos;Highhip arc, back&apos;/ 2).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="885"/> <source>hip_arc_half_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="887"/> <source>Hip arc, back, half</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="888"/> <source>Half of &apos;Hip arc, back&apos;. (&apos;Hip arc, back&apos; / 2).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="892"/> <source>hip_with_abdomen_arc_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="894"/> <source>Hip arc with Abdomen, front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="895"/> <source>Curve stiff paper around front of abdomen, tape_ at sides. Measure from Hip Side to Hip Side over paper across front.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="900"/> <source>body_armfold_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="902"/> <source>Body circumference at Armfold level</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="903"/> <source>Measure around arms and torso at Armfold level.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="907"/> <source>body_bust_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="909"/> <source>Body circumference at Bust level</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="910"/> <source>Measure around arms and torso at Bust level.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="914"/> <source>body_torso_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="916"/> <source>Body circumference of full torso</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="917"/> <source>Circumference around torso from mid-shoulder around crotch back up to mid-shoulder.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="922"/> <source>hip_circ_with_abdomen</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="924"/> <source>Hip circumference, including Abdomen</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="925"/> <source>Measurement at Hip level, including the depth of the Abdomen. (Hip arc, back + Hip arc with abdomen, front).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="942"/> <source>neck_front_to_waist_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="944"/> <source>Neck Front to Waist Front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="945"/> <source>From Neck Front, over tape_ between Breastpoints, down to Waist Front.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="949"/> <source>neck_front_to_waist_flat_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="951"/> <source>Neck Front to Waist Front flat</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="952"/> <source>From Neck Front down between breasts to Waist Front.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="956"/> <source>armpit_to_waist_side</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="958"/> <source>Armpit to Waist Side</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="959"/> <source>From Armpit down to Waist Side.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="962"/> <source>shoulder_tip_to_waist_side_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="964"/> <source>Shoulder Tip to Waist Side, front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="965"/> <source>From Shoulder Tip, curving around Armscye Front, then down to Waist Side.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="969"/> <source>neck_side_to_waist_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="971"/> <source>Neck Side to Waist level, front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="972"/> <source>From Neck Side straight down front to Waist level.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="976"/> <source>neck_side_to_waist_bustpoint_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="978"/> <source>Neck Side to Waist level, through Bustpoint</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="979"/> <source>From Neck Side over Bustpoint to Waist level, forming a straight line.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="983"/> <source>neck_front_to_highbust_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="985"/> <source>Neck Front to Highbust Front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="986"/> <source>Neck Front down to Highbust Front.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="989"/> <source>highbust_to_waist_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="991"/> <source>Highbust Front to Waist Front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="992"/> <source>From Highbust Front to Waist Front. Use tape_ to bridge gap between Bustpoints. (&apos;Neck Front to Waist Front&apos; - &apos;Neck Front to Highbust Front&apos;).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="997"/> <source>neck_front_to_bust_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="999"/> <source>Neck Front to Bust Front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1000"/> <source>From Neck Front down to Bust Front. Requires tape_ to cover gap between Bustpoints.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1005"/> <source>bust_to_waist_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1007"/> <source>Bust Front to Waist Front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1008"/> <source>From Bust Front down to Waist level. (&apos;Neck Front to Waist Front&apos; - &apos;Neck Front to Bust Front&apos;).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1013"/> <source>lowbust_to_waist_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1015"/> <source>Lowbust Front to Waist Front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1016"/> <source>From Lowbust Front down to Waist Front.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1019"/> <source>rib_to_waist_side</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1021"/> <source>Rib Side to Waist Side</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1022"/> <source>From lowest rib at side down to Waist Side.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1026"/> <source>shoulder_tip_to_armfold_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1028"/> <source>Shoulder Tip to Armfold Front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1029"/> <source>From Shoulder Tip around Armscye down to Armfold Front.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1033"/> <source>neck_side_to_bust_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1035"/> <source>Neck Side to Bust level, front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1036"/> <source>From Neck Side straight down front to Bust level.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1040"/> <source>neck_side_to_highbust_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1042"/> <source>Neck Side to Highbust level, front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1043"/> <source>From Neck Side straight down front to Highbust level.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1047"/> <source>shoulder_center_to_highbust_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1049"/> <source>Shoulder center to Highbust level, front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1050"/> <source>From mid-Shoulder down front to Highbust level, aimed at Bustpoint.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1054"/> <source>shoulder_tip_to_waist_side_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1056"/> <source>Shoulder Tip to Waist Side, back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1057"/> <source>From Shoulder Tip, curving around Armscye Back, then down to Waist Side.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1061"/> <source>neck_side_to_waist_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1063"/> <source>Neck Side to Waist level, back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1064"/> <source>From Neck Side straight down back to Waist level.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1068"/> <source>neck_back_to_waist_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1070"/> <source>Neck Back to Waist Back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1071"/> <source>From Neck Back down to Waist Back.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1074"/> <source>neck_side_to_waist_scapula_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1076"/> <source>Neck Side to Waist level, through Scapula</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1077"/> <source>From Neck Side across Scapula down to Waist level, forming a straight line.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1082"/> <source>neck_back_to_highbust_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1084"/> <source>Neck Back to Highbust Back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1085"/> <source>From Neck Back down to Highbust Back.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1088"/> <source>highbust_to_waist_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1090"/> <source>Highbust Back to Waist Back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1091"/> <source>From Highbust Back down to Waist Back. (&apos;Neck Back to Waist Back&apos; - &apos;Neck Back to Highbust Back&apos;).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1096"/> <source>neck_back_to_bust_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1098"/> <source>Neck Back to Bust Back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1099"/> <source>From Neck Back down to Bust Back.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1102"/> <source>bust_to_waist_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1104"/> <source>Bust Back to Waist Back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1105"/> <source>From Bust Back down to Waist level. (&apos;Neck Back to Waist Back&apos; - &apos;Neck Back to Bust Back&apos;).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1110"/> <source>lowbust_to_waist_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1112"/> <source>Lowbust Back to Waist Back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1113"/> <source>From Lowbust Back down to Waist Back.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1116"/> <source>shoulder_tip_to_armfold_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1118"/> <source>Shoulder Tip to Armfold Back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1119"/> <source>From Shoulder Tip around Armscye down to Armfold Back.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1123"/> <source>neck_side_to_bust_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1125"/> <source>Neck Side to Bust level, back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1126"/> <source>From Neck Side straight down back to Bust level.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1130"/> <source>neck_side_to_highbust_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1132"/> <source>Neck Side to Highbust level, back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1133"/> <source>From Neck Side straight down back to Highbust level.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1137"/> <source>shoulder_center_to_highbust_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1139"/> <source>Shoulder center to Highbust level, back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1140"/> <source>From mid-Shoulder down back to Highbust level, aimed through Scapula.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1144"/> <source>waist_to_highhip_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1146"/> <source>Waist Front to Highhip Front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1147"/> <source>From Waist Front to Highhip Front.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1150"/> <source>waist_to_hip_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1152"/> <source>Waist Front to Hip Front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1153"/> <source>From Waist Front to Hip Front.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1156"/> <source>waist_to_highhip_side</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1158"/> <source>Waist Side to Highhip Side</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1159"/> <source>From Waist Side to Highhip Side.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1162"/> <source>waist_to_highhip_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1164"/> <source>Waist Back to Highhip Back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1165"/> <source>From Waist Back down to Highhip Back.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1168"/> <source>waist_to_hip_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1170"/> <source>Waist Back to Hip Back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1171"/> <source>From Waist Back down to Hip Back. Requires tape_ to cover the gap between buttocks.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1176"/> <source>waist_to_hip_side</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1178"/> <source>Waist Side to Hip Side</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1179"/> <source>From Waist Side to Hip Side.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1182"/> <source>shoulder_slope_neck_side_angle</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1184"/> <source>Shoulder Slope Angle from Neck Side</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1185"/> <source>Angle formed by line from Neck Side to Shoulder Tip and line from Neck Side parallel to floor.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1190"/> <source>shoulder_slope_neck_side_length</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1192"/> <source>Shoulder Slope length from Neck Side</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1193"/> <source>Vertical distance between Neck Side and Shoulder Tip.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1197"/> <source>shoulder_slope_neck_back_angle</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1199"/> <source>Shoulder Slope Angle from Neck Back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1200"/> <source>Angle formed by line from Neck Back to Shoulder Tip and line from Neck Back parallel to floor.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1205"/> <source>shoulder_slope_neck_back_height</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1207"/> <source>Shoulder Slope length from Neck Back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1208"/> <source>Vertical distance between Neck Back and Shoulder Tip.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1212"/> <source>shoulder_slope_shoulder_tip_angle</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1214"/> <source>Shoulder Slope Angle from Shoulder Tip</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1216"/> <source>Angle formed by line from Neck Side to Shoulder Tip and vertical line at Shoulder Tip.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1221"/> <source>neck_back_to_across_back</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1223"/> <source>Neck Back to Across Back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1224"/> <source>From neck back, down to level of Across Back measurement.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1228"/> <source>across_back_to_waist_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1230"/> <source>Across Back to Waist back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1231"/> <source>From middle of Across Back down to Waist back.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1247"/> <source>shoulder_length</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1249"/> <source>Shoulder length</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1250"/> <source>From Neck Side to Shoulder Tip.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1253"/> <source>shoulder_tip_to_shoulder_tip_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1255"/> <source>Shoulder Tip to Shoulder Tip, front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1256"/> <source>From Shoulder Tip to Shoulder Tip, across front.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1260"/> <source>across_chest_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1262"/> <source>Across Chest</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1263"/> <source>From Armscye to Armscye at narrowest width across chest.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1267"/> <source>armfold_to_armfold_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1269"/> <source>Armfold to Armfold, front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1270"/> <source>From Armfold to Armfold, shortest distance between Armfolds, not parallel to floor.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1275"/> <source>shoulder_tip_to_shoulder_tip_half_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1277"/> <source>Shoulder Tip to Shoulder Tip, front, half</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1278"/> <source>Half of&apos; Shoulder Tip to Shoulder tip, front&apos;. (&apos;Shoulder Tip to Shoulder Tip, front&apos; / 2).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1283"/> <source>across_chest_half_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1285"/> <source>Across Chest, half</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1286"/> <source>Half of &apos;Across Chest&apos;. (&apos;Across Chest&apos; / 2).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1290"/> <source>shoulder_tip_to_shoulder_tip_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1292"/> <source>Shoulder Tip to Shoulder Tip, back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1293"/> <source>From Shoulder Tip to Shoulder Tip, across the back.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1297"/> <source>across_back_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1299"/> <source>Across Back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1300"/> <source>From Armscye to Armscye at the narrowest width of the back.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1304"/> <source>armfold_to_armfold_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1306"/> <source>Armfold to Armfold, back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1307"/> <source>From Armfold to Armfold across the back.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1311"/> <source>shoulder_tip_to_shoulder_tip_half_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1313"/> <source>Shoulder Tip to Shoulder Tip, back, half</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1314"/> <source>Half of &apos;Shoulder Tip to Shoulder Tip, back&apos;. (&apos;Shoulder Tip to Shoulder Tip, back&apos; / 2).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1319"/> <source>across_back_half_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1321"/> <source>Across Back, half</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1322"/> <source>Half of &apos;Across Back&apos;. (&apos;Across Back&apos; / 2).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1326"/> <source>neck_front_to_shoulder_tip_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1328"/> <source>Neck Front to Shoulder Tip</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1329"/> <source>From Neck Front to Shoulder Tip.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1332"/> <source>neck_back_to_shoulder_tip_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1334"/> <source>Neck Back to Shoulder Tip</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1335"/> <source>From Neck Back to Shoulder Tip.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1338"/> <source>neck_width</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1340"/> <source>Neck Width</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1341"/> <source>Measure between the &apos;legs&apos; of an unclosed necklace or chain draped around the neck.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1358"/> <source>bustpoint_to_bustpoint</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1360"/> <source>Bustpoint to Bustpoint</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1361"/> <source>From Bustpoint to Bustpoint.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1364"/> <source>bustpoint_to_neck_side</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1366"/> <source>Bustpoint to Neck Side</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1367"/> <source>From Neck Side to Bustpoint.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1370"/> <source>bustpoint_to_lowbust</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1372"/> <source>Bustpoint to Lowbust</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1373"/> <source>From Bustpoint down to Lowbust level, following curve of bust or chest.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1377"/> <source>bustpoint_to_waist</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1379"/> <source>Bustpoint to Waist level</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1380"/> <source>From Bustpoint to straight down to Waist level, forming a straight line (not curving along the body).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1385"/> <source>bustpoint_to_bustpoint_half</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1387"/> <source>Bustpoint to Bustpoint, half</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1388"/> <source>Half of &apos;Bustpoint to Bustpoint&apos;. (&apos;Bustpoint to Bustpoint&apos; / 2).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1392"/> <source>bustpoint_neck_side_to_waist</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1394"/> <source>Bustpoint, Neck Side to Waist level</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1395"/> <source>From Neck Side to Bustpoint, then straight down to Waist level. (&apos;Neck Side to Bustpoint&apos; + &apos;Bustpoint to Waist level&apos;).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1400"/> <source>bustpoint_to_shoulder_tip</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1402"/> <source>Bustpoint to Shoulder Tip</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1403"/> <source>From Bustpoint to Shoulder tip.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1406"/> <source>bustpoint_to_waist_front</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1408"/> <source>Bustpoint to Waist Front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1409"/> <source>From Bustpoint to Waist Front, in a straight line, not following the curves of the body.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1414"/> <source>bustpoint_to_bustpoint_halter</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1416"/> <source>Bustpoint to Bustpoint Halter</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1417"/> <source>From Bustpoint around Neck Back down to other Bustpoint.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1421"/> <source>bustpoint_to_shoulder_center</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1423"/> <source>Bustpoint to Shoulder Center</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1424"/> <source>From center of Shoulder to Bustpoint.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1439"/> <source>shoulder_tip_to_waist_front</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1441"/> <source>Shoulder Tip to Waist Front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1442"/> <source>From Shoulder Tip diagonal to Waist Front.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1446"/> <source>neck_front_to_waist_side</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1448"/> <source>Neck Front to Waist Side</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1449"/> <source>From Neck Front diagonal to Waist Side.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1453"/> <source>neck_side_to_waist_side_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1455"/> <source>Neck Side to Waist Side, front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1456"/> <source>From Neck Side diagonal across front to Waist Side.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1460"/> <source>shoulder_tip_to_waist_back</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1462"/> <source>Shoulder Tip to Waist Back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1463"/> <source>From Shoulder Tip diagonal to Waist Back.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1467"/> <source>shoulder_tip_to_waist_b_1in_offset</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1469"/> <source>Shoulder Tip to Waist Back, with 1in (2.54cm) offset</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1471"/> <source>Mark 1in (2.54cm) outward from Waist Back along Waist level. Measure from Shoulder Tip diagonal to mark.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1475"/> <source>neck_back_to_waist_side</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1477"/> <source>Neck Back to Waist Side</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1478"/> <source>From Neck Back diagonal across back to Waist Side.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1482"/> <source>neck_side_to_waist_side_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1484"/> <source>Neck Side to Waist Side, back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1485"/> <source>From Neck Side diagonal across back to Waist Side.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1489"/> <source>neck_side_to_armfold_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1491"/> <source>Neck Side to Armfold Front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1492"/> <source>From Neck Side diagonal to Armfold Front.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1496"/> <source>neck_side_to_armpit_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1498"/> <source>Neck Side to Highbust Side, front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1499"/> <source>From Neck Side diagonal across front to Highbust Side (Armpit).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1503"/> <source>neck_side_to_bust_side_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1505"/> <source>Neck Side to Bust Side, front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1506"/> <source>Neck Side diagonal across front to Bust Side.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1510"/> <source>neck_side_to_armfold_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1512"/> <source>Neck Side to Armfold Back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1513"/> <source>From Neck Side diagonal to Armfold Back.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1517"/> <source>neck_side_to_armpit_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1519"/> <source>Neck Side to Highbust Side, back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1520"/> <source>From Neck Side diagonal across back to Highbust Side (Armpit).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1524"/> <source>neck_side_to_bust_side_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1526"/> <source>Neck Side to Bust Side, back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1527"/> <source>Neck Side diagonal across back to Bust Side.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1543"/> <source>arm_shoulder_tip_to_wrist_bent</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1545"/> <source>Arm: Shoulder Tip to Wrist, bent</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1546"/> <source>Bend Arm, measure from Shoulder Tip around Elbow to radial Wrist bone.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1550"/> <source>arm_shoulder_tip_to_elbow_bent</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1552"/> <source>Arm: Shoulder Tip to Elbow, bent</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1553"/> <source>Bend Arm, measure from Shoulder Tip to Elbow Tip.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1557"/> <source>arm_elbow_to_wrist_bent</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1559"/> <source>Arm: Elbow to Wrist, bent</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1560"/> <source>Elbow tip to wrist. (&apos;Arm: Shoulder Tip to Wrist, bent&apos; - &apos;Arm: Shoulder Tip to Elbow, bent&apos;).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1566"/> <source>arm_elbow_circ_bent</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1568"/> <source>Arm: Elbow circumference, bent</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1569"/> <source>Elbow circumference, arm is bent.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1572"/> <source>arm_shoulder_tip_to_wrist</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1574"/> <source>Arm: Shoulder Tip to Wrist</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1575"/> <source>From Shoulder Tip to Wrist bone, arm straight.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1579"/> <source>arm_shoulder_tip_to_elbow</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1581"/> <source>Arm: Shoulder Tip to Elbow</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1582"/> <source>From Shoulder tip to Elbow Tip, arm straight.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1586"/> <source>arm_elbow_to_wrist</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1588"/> <source>Arm: Elbow to Wrist</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1589"/> <source>From Elbow to Wrist, arm straight. (&apos;Arm: Shoulder Tip to Wrist&apos; - &apos;Arm: Shoulder Tip to Elbow&apos;).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1594"/> <source>arm_armpit_to_wrist</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1596"/> <source>Arm: Armpit to Wrist, inside</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1597"/> <source>From Armpit to ulna Wrist bone, arm straight.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1601"/> <source>arm_armpit_to_elbow</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1603"/> <source>Arm: Armpit to Elbow, inside</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1604"/> <source>From Armpit to inner Elbow, arm straight.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1608"/> <source>arm_elbow_to_wrist_inside</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1610"/> <source>Arm: Elbow to Wrist, inside</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1611"/> <source>From inside Elbow to Wrist. (&apos;Arm: Armpit to Wrist, inside&apos; - &apos;Arm: Armpit to Elbow, inside&apos;).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1616"/> <source>arm_upper_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1618"/> <source>Arm: Upper Arm circumference</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1619"/> <source>Arm circumference at Armpit level.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1622"/> <source>arm_above_elbow_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1624"/> <source>Arm: Above Elbow circumference</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1625"/> <source>Arm circumference at Bicep level.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1628"/> <source>arm_elbow_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1630"/> <source>Arm: Elbow circumference</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1631"/> <source>Elbow circumference, arm straight.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1634"/> <source>arm_lower_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1636"/> <source>Arm: Lower Arm circumference</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1637"/> <source>Arm circumference where lower arm is widest.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1641"/> <source>arm_wrist_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1643"/> <source>Arm: Wrist circumference</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1644"/> <source>Wrist circumference.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1647"/> <source>arm_shoulder_tip_to_armfold_line</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1649"/> <source>Arm: Shoulder Tip to Armfold line</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1650"/> <source>From Shoulder Tip down to Armpit level.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1653"/> <source>arm_neck_side_to_wrist</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1655"/> <source>Arm: Neck Side to Wrist</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1656"/> <source>From Neck Side to Wrist. (&apos;Shoulder Length&apos; + &apos;Arm: Shoulder Tip to Wrist&apos;).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1661"/> <source>arm_neck_side_to_finger_tip</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1663"/> <source>Arm: Neck Side to Finger Tip</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1664"/> <source>From Neck Side down arm to tip of middle finger. (&apos;Shoulder Length&apos; + &apos;Arm: Shoulder Tip to Wrist&apos; + &apos;Hand: Length&apos;).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1670"/> <source>armscye_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1672"/> <source>Armscye: Circumference</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1673"/> <source>Let arm hang at side. Measure Armscye circumference through Shoulder Tip and Armpit.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1678"/> <source>armscye_length</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1680"/> <source>Armscye: Length</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1681"/> <source>Vertical distance from Shoulder Tip to Armpit.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1685"/> <source>armscye_width</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1687"/> <source>Armscye: Width</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1688"/> <source>Horizontal distance between Armscye Front and Armscye Back.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1692"/> <source>arm_neck_side_to_outer_elbow</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1694"/> <source>Arm: Neck side to Elbow</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1695"/> <source>From Neck Side over Shoulder Tip down to Elbow. (Shoulder length + Arm: Shoulder Tip to Elbow).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1711"/> <source>leg_crotch_to_floor</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1713"/> <source>Leg: Crotch to floor</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1714"/> <source>Stand feet close together. Measure from crotch level (touching body, no extra space) down to floor.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1805"/> <source>From Waist Side along curve to Hip level then straight down to Knee level. (&apos;Leg: Waist Side to Floor&apos; - &apos;Height Knee&apos;).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1845"/> <source>rise_length_side_sitting</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1878"/> <source>Vertical distance from Waist side down to Crotch level. Use formula (Height: Waist side - Leg: Crotch to floor).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2131"/> <source>This information is pulled from pattern charts in some patternmaking systems, e.g. Winifred P. Aldrich&apos;s &quot;Metric Pattern Cutting&quot;.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1719"/> <source>leg_waist_side_to_floor</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1721"/> <source>Leg: Waist Side to floor</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1722"/> <source>From Waist Side along curve to Hip level then straight down to floor.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1726"/> <source>leg_thigh_upper_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1728"/> <source>Leg: Thigh Upper circumference</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1729"/> <source>Thigh circumference at the fullest part of the upper Thigh near the Crotch.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1734"/> <source>leg_thigh_mid_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1736"/> <source>Leg: Thigh Middle circumference</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1737"/> <source>Thigh circumference about halfway between Crotch and Knee.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1741"/> <source>leg_knee_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1743"/> <source>Leg: Knee circumference</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1744"/> <source>Knee circumference with straight leg.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1747"/> <source>leg_knee_small_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1749"/> <source>Leg: Knee Small circumference</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1750"/> <source>Leg circumference just below the knee.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1753"/> <source>leg_calf_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1755"/> <source>Leg: Calf circumference</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1756"/> <source>Calf circumference at the largest part of lower leg.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1760"/> <source>leg_ankle_high_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1762"/> <source>Leg: Ankle High circumference</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1763"/> <source>Ankle circumference where the indentation at the back of the ankle is the deepest.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1768"/> <source>leg_ankle_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1770"/> <source>Leg: Ankle circumference</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1771"/> <source>Ankle circumference where front of leg meets the top of the foot.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1775"/> <source>leg_knee_circ_bent</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1777"/> <source>Leg: Knee circumference, bent</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1778"/> <source>Knee circumference with leg bent.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1781"/> <source>leg_ankle_diag_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1783"/> <source>Leg: Ankle diagonal circumference</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1784"/> <source>Ankle circumference diagonal from top of foot to bottom of heel.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1788"/> <source>leg_crotch_to_ankle</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1790"/> <source>Leg: Crotch to Ankle</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1791"/> <source>From Crotch to Ankle. (&apos;Leg: Crotch to Floor&apos; - &apos;Height: Ankle&apos;).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1795"/> <source>leg_waist_side_to_ankle</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1797"/> <source>Leg: Waist Side to Ankle</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1798"/> <source>From Waist Side to Ankle. (&apos;Leg: Waist Side to Floor&apos; - &apos;Height: Ankle&apos;).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1802"/> <source>leg_waist_side_to_knee</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1804"/> <source>Leg: Waist Side to Knee</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1822"/> <source>crotch_length</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1824"/> <source>Crotch length</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1825"/> <source>Put tape_ across gap between buttocks at Hip level. Measure from Waist Front down between legs and up to Waist Back.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1829"/> <source>crotch_length_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1831"/> <source>Crotch length, back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1832"/> <source>Put tape_ across gap between buttocks at Hip level. Measure from Waist Back to mid-Crotch, either at the vagina or between testicles and anus).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1837"/> <source>crotch_length_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1839"/> <source>Crotch length, front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1840"/> <source>From Waist Front to start of vagina or end of testicles. (&apos;Crotch length&apos; - &apos;Crotch length, back&apos;).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1847"/> <source>Rise length, side, sitting</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1849"/> <source>From Waist Side around hip curve down to surface, while seated on hard surface.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1864"/> <source>Vertical distance from Waist Back to Crotch level. (&apos;Height: Waist Back&apos; - &apos;Leg: Crotch to Floor&apos;)</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1871"/> <source>Vertical Distance from Waist Front to Crotch level. (&apos;Height: Waist Front&apos; - &apos;Leg: Crotch to Floor&apos;)</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1875"/> <source>rise_length_side</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1877"/> <source>Rise length, side</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1854"/> <source>rise_length_diag</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1856"/> <source>Rise length, diagonal</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1857"/> <source>Measure from Waist Side diagonally to a string tied at the top of the leg, seated on a hard surface.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1861"/> <source>rise_length_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1863"/> <source>Rise length, back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1868"/> <source>rise_length_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1870"/> <source>Rise length, front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1894"/> <source>neck_back_to_waist_front</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1896"/> <source>Neck Back to Waist Front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1897"/> <source>From Neck Back around Neck Side down to Waist Front.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1901"/> <source>waist_to_waist_halter</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1903"/> <source>Waist to Waist Halter, around Neck Back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1904"/> <source>From Waist level around Neck Back to Waist level.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1908"/> <source>waist_natural_circ</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1910"/> <source>Natural Waist circumference</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1911"/> <source>Torso circumference at men&apos;s natural side Abdominal Obliques indentation, if Oblique indentation isn&apos;t found then just below the Navel level.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1916"/> <source>waist_natural_arc_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1918"/> <source>Natural Waist arc, front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1919"/> <source>From Side to Side at the Natural Waist level, across the front.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1923"/> <source>waist_natural_arc_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1925"/> <source>Natural Waist arc, back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1926"/> <source>From Side to Side at Natural Waist level, across the back. Calculate as ( Natural Waist circumference - Natural Waist arc (front) ).</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1930"/> <source>waist_to_natural_waist_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1932"/> <source>Waist Front to Natural Waist Front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1933"/> <source>Length from Waist Front to Natural Waist Front.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1937"/> <source>waist_to_natural_waist_b</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1939"/> <source>Waist Back to Natural Waist Back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1940"/> <source>Length from Waist Back to Natural Waist Back.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1944"/> <source>arm_neck_back_to_elbow_bent</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1946"/> <source>Arm: Neck Back to Elbow, high bend</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1947"/> <source>Bend Arm with Elbow out, hand in front. Measure from Neck Back to Elbow Tip.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1952"/> <source>arm_neck_back_to_wrist_bent</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1954"/> <source>Arm: Neck Back to Wrist, high bend</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1955"/> <source>Bend Arm with Elbow out, hand in front. Measure from Neck Back to Elbow Tip to Wrist bone.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1959"/> <source>arm_neck_side_to_elbow_bent</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1961"/> <source>Arm: Neck Side to Elbow, high bend</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1962"/> <source>Bend Arm with Elbow out, hand in front. Measure from Neck Side to Elbow Tip.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1966"/> <source>arm_neck_side_to_wrist_bent</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1968"/> <source>Arm: Neck Side to Wrist, high bend</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1969"/> <source>Bend Arm with Elbow out, hand in front. Measure from Neck Side to Elbow Tip to Wrist bone.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1974"/> <source>arm_across_back_center_to_elbow_bent</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1976"/> <source>Arm: Across Back Center to Elbow, high bend</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1977"/> <source>Bend Arm with Elbow out, hand in front. Measure from Middle of Back to Elbow Tip.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1982"/> <source>arm_across_back_center_to_wrist_bent</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1984"/> <source>Arm: Across Back Center to Wrist, high bend</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1985"/> <source>Bend Arm with Elbow out, hand in front. Measure from Middle of Back to Elbow Tip to Wrist bone.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1990"/> <source>arm_armscye_back_center_to_wrist_bent</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1992"/> <source>Arm: Armscye Back Center to Wrist, high bend</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="1993"/> <source>Bend Arm with Elbow out, hand in front. Measure from Armscye Back to Elbow Tip.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2010"/> <source>neck_back_to_bust_front</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2012"/> <source>Neck Back to Bust Front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2013"/> <source>From Neck Back, over Shoulder, to Bust Front.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2017"/> <source>neck_back_to_armfold_front</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2019"/> <source>Neck Back to Armfold Front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2020"/> <source>From Neck Back over Shoulder to Armfold Front.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2024"/> <source>neck_back_to_armfold_front_to_waist_side</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2026"/> <source>Neck Back, over Shoulder, to Waist Side</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2027"/> <source>From Neck Back, over Shoulder, down chest to Waist Side.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2031"/> <source>highbust_back_over_shoulder_to_armfold_front</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2033"/> <source>Highbust Back, over Shoulder, to Armfold Front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2034"/> <source>From Highbust Back over Shoulder to Armfold Front.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2038"/> <source>highbust_back_over_shoulder_to_waist_front</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2040"/> <source>Highbust Back, over Shoulder, to Waist Front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2041"/> <source>From Highbust Back, over Shoulder touching Neck Side, to Waist Front.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2045"/> <source>neck_back_to_armfold_front_to_neck_back</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2047"/> <source>Neck Back, to Armfold Front, to Neck Back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2048"/> <source>From Neck Back, over Shoulder to Armfold Front, under arm and return to start.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2053"/> <source>across_back_center_to_armfold_front_to_across_back_center</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2055"/> <source>Across Back Center, circled around Shoulder</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2056"/> <source>From center of Across Back, over Shoulder, under Arm, and return to start.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2061"/> <source>neck_back_to_armfold_front_to_highbust_back</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2063"/> <source>Neck Back, to Armfold Front, to Highbust Back</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2064"/> <source>From Neck Back over Shoulder to Armfold Front, under arm to Highbust Back.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2069"/> <source>armfold_to_armfold_bust</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2071"/> <source>Armfold to Armfold, front, curved through Bust Front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2073"/> <source>Measure in a curve from Armfold Left Front through Bust Front curved back up to Armfold Right Front.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2077"/> <source>armfold_to_bust_front</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2079"/> <source>Armfold to Bust Front</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2080"/> <source>Measure from Armfold Front to Bust Front, shortest distance between the two, as straight as possible.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2084"/> <source>highbust_b_over_shoulder_to_highbust_f</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2086"/> <source>Highbust Back, over Shoulder, to Highbust level</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2088"/> <source>From Highbust Back, over Shoulder, then aim at Bustpoint, stopping measurement at Highbust level.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2093"/> <source>armscye_arc</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2095"/> <source>Armscye: Arc</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2096"/> <source>From Armscye at Across Chest over ShoulderTip to Armscye at Across Back.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2112"/> <source>dart_width_shoulder</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2114"/> <source>Dart Width: Shoulder</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2115"/> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2123"/> <source>This information is pulled from pattern charts in some patternmaking systems, e.g. Winifred P. Aldrich&apos;s &quot;Metric Pattern Cutting&quot;.</source> <comment>Full measurement description.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2120"/> <source>dart_width_bust</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2122"/> <source>Dart Width: Bust</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2128"/> <source>dart_width_waist</source> <comment>Name in a formula. Don&apos;t use math symbols and space in name!!!!</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../../src/libs/vpatterndb/vtranslatemeasurements.cpp" line="2130"/> <source>Dart Width: Waist</source> <comment>Full measurement name.</comment> <translation type="unfinished"></translation> </message> </context> </TS>
FashionFreedom/Seamly2D
share/translations/measurements_p8_it_IT.ts
TypeScript
gpl-3.0
231,740
package compute // SecurityApplicationsClient is a client for the Security Application functions of the Compute API. type SecurityApplicationsClient struct { ResourceClient } // SecurityApplications obtains a SecurityApplicationsClient which can be used to access to the // Security Application functions of the Compute API func (c *Client) SecurityApplications() *SecurityApplicationsClient { return &SecurityApplicationsClient{ ResourceClient: ResourceClient{ Client: c, ResourceDescription: "security application", ContainerPath: "/secapplication/", ResourceRootPath: "/secapplication", }} } // SecurityApplicationInfo describes an existing security application. type SecurityApplicationInfo struct { // A description of the security application. Description string `json:"description"` // The TCP or UDP destination port number. This can be a port range, such as 5900-5999 for TCP. DPort string `json:"dport"` // The ICMP code. ICMPCode SecurityApplicationICMPCode `json:"icmpcode"` // The ICMP type. ICMPType SecurityApplicationICMPType `json:"icmptype"` // The three-part name of the Security Application (/Compute-identity_domain/user/object). Name string `json:"name"` // The protocol to use. Protocol SecurityApplicationProtocol `json:"protocol"` // The Uniform Resource Identifier URI string `json:"uri"` } type SecurityApplicationProtocol string const ( All SecurityApplicationProtocol = "all" AH SecurityApplicationProtocol = "ah" ESP SecurityApplicationProtocol = "esp" ICMP SecurityApplicationProtocol = "icmp" ICMPV6 SecurityApplicationProtocol = "icmpv6" IGMP SecurityApplicationProtocol = "igmp" IPIP SecurityApplicationProtocol = "ipip" GRE SecurityApplicationProtocol = "gre" MPLSIP SecurityApplicationProtocol = "mplsip" OSPF SecurityApplicationProtocol = "ospf" PIM SecurityApplicationProtocol = "pim" RDP SecurityApplicationProtocol = "rdp" SCTP SecurityApplicationProtocol = "sctp" TCP SecurityApplicationProtocol = "tcp" UDP SecurityApplicationProtocol = "udp" ) type SecurityApplicationICMPCode string const ( Admin SecurityApplicationICMPCode = "admin" Df SecurityApplicationICMPCode = "df" Host SecurityApplicationICMPCode = "host" Network SecurityApplicationICMPCode = "network" Port SecurityApplicationICMPCode = "port" Protocol SecurityApplicationICMPCode = "protocol" ) type SecurityApplicationICMPType string const ( Echo SecurityApplicationICMPType = "echo" Reply SecurityApplicationICMPType = "reply" TTL SecurityApplicationICMPType = "ttl" TraceRoute SecurityApplicationICMPType = "traceroute" Unreachable SecurityApplicationICMPType = "unreachable" ) func (c *SecurityApplicationsClient) success(result *SecurityApplicationInfo) (*SecurityApplicationInfo, error) { c.unqualify(&result.Name) return result, nil } // CreateSecurityApplicationInput describes the Security Application to create type CreateSecurityApplicationInput struct { // A description of the security application. // Optional Description string `json:"description"` // The TCP or UDP destination port number. // You can also specify a port range, such as 5900-5999 for TCP. // This parameter isn't relevant to the icmp protocol. // Required if the Protocol is TCP or UDP DPort string `json:"dport"` // The ICMP code. This parameter is relevant only if you specify ICMP as the protocol. // If you specify icmp as the protocol and don't specify icmptype or icmpcode, then all ICMP packets are matched. // Optional ICMPCode SecurityApplicationICMPCode `json:"icmpcode,omitempty"` // This parameter is relevant only if you specify ICMP as the protocol. // If you specify icmp as the protocol and don't specify icmptype or icmpcode, then all ICMP packets are matched. // Optional ICMPType SecurityApplicationICMPType `json:"icmptype,omitempty"` // The three-part name of the Security Application (/Compute-identity_domain/user/object). // Object names can contain only alphanumeric characters, hyphens, underscores, and periods. Object names are case-sensitive. // Required Name string `json:"name"` // The protocol to use. // Required Protocol SecurityApplicationProtocol `json:"protocol"` } // CreateSecurityApplication creates a new security application. func (c *SecurityApplicationsClient) CreateSecurityApplication(input *CreateSecurityApplicationInput) (*SecurityApplicationInfo, error) { input.Name = c.getQualifiedName(input.Name) var appInfo SecurityApplicationInfo if err := c.createResource(&input, &appInfo); err != nil { return nil, err } return c.success(&appInfo) } // GetSecurityApplicationInput describes the Security Application to obtain type GetSecurityApplicationInput struct { // The three-part name of the Security Application (/Compute-identity_domain/user/object). // Required Name string `json:"name"` } // GetSecurityApplication retrieves the security application with the given name. func (c *SecurityApplicationsClient) GetSecurityApplication(input *GetSecurityApplicationInput) (*SecurityApplicationInfo, error) { var appInfo SecurityApplicationInfo if err := c.getResource(input.Name, &appInfo); err != nil { return nil, err } return c.success(&appInfo) } // DeleteSecurityApplicationInput describes the Security Application to delete type DeleteSecurityApplicationInput struct { // The three-part name of the Security Application (/Compute-identity_domain/user/object). // Required Name string `json:"name"` } // DeleteSecurityApplication deletes the security application with the given name. func (c *SecurityApplicationsClient) DeleteSecurityApplication(input *DeleteSecurityApplicationInput) error { return c.deleteResource(input.Name) }
TheWeatherCompany/terraform
vendor/github.com/hashicorp/go-oracle-terraform/compute/security_applications.go
GO
mpl-2.0
5,793
package matchers import ( "fmt" "reflect" "strings" "github.com/onsi/gomega/format" "gopkg.in/yaml.v2" ) type MatchYAMLMatcher struct { YAMLToMatch interface{} } func (matcher *MatchYAMLMatcher) Match(actual interface{}) (success bool, err error) { actualString, expectedString, err := matcher.toStrings(actual) if err != nil { return false, err } var aval interface{} var eval interface{} if err := yaml.Unmarshal([]byte(actualString), &aval); err != nil { return false, fmt.Errorf("Actual '%s' should be valid YAML, but it is not.\nUnderlying error:%s", actualString, err) } if err := yaml.Unmarshal([]byte(expectedString), &eval); err != nil { return false, fmt.Errorf("Expected '%s' should be valid YAML, but it is not.\nUnderlying error:%s", expectedString, err) } return reflect.DeepEqual(aval, eval), nil } func (matcher *MatchYAMLMatcher) FailureMessage(actual interface{}) (message string) { actualString, expectedString, _ := matcher.toNormalisedStrings(actual) return format.Message(actualString, "to match YAML of", expectedString) } func (matcher *MatchYAMLMatcher) NegatedFailureMessage(actual interface{}) (message string) { actualString, expectedString, _ := matcher.toNormalisedStrings(actual) return format.Message(actualString, "not to match YAML of", expectedString) } func (matcher *MatchYAMLMatcher) toNormalisedStrings(actual interface{}) (actualFormatted, expectedFormatted string, err error) { actualString, expectedString, err := matcher.toStrings(actual) return normalise(actualString), normalise(expectedString), err } func normalise(input string) string { var val interface{} err := yaml.Unmarshal([]byte(input), &val) if err != nil { panic(err) // guarded by Match } output, err := yaml.Marshal(val) if err != nil { panic(err) // guarded by Unmarshal } return strings.TrimSpace(string(output)) } func (matcher *MatchYAMLMatcher) toStrings(actual interface{}) (actualFormatted, expectedFormatted string, err error) { actualString, ok := toString(actual) if !ok { return "", "", fmt.Errorf("MatchYAMLMatcher matcher requires a string, stringer, or []byte. Got actual:\n%s", format.Object(actual, 1)) } expectedString, ok := toString(matcher.YAMLToMatch) if !ok { return "", "", fmt.Errorf("MatchYAMLMatcher matcher requires a string, stringer, or []byte. Got expected:\n%s", format.Object(matcher.YAMLToMatch, 1)) } return actualString, expectedString, nil }
KarolKraskiewicz/autoscaler
vertical-pod-autoscaler/vendor/github.com/onsi/gomega/matchers/match_yaml_matcher.go
GO
apache-2.0
2,453
# # Author:: Joe Williams (<joe@joetify.com>) # Author:: Tyler Cloke (<tyler@opscode.com>) # Copyright:: Copyright (c) 2009 Joe Williams # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. # require 'chef/resource' class Chef class Resource class Mdadm < Chef::Resource identity_attr :raid_device state_attrs :devices, :level, :chunk default_action :create allowed_actions :create, :assemble, :stop def initialize(name, run_context=nil) super @chunk = 16 @devices = [] @exists = false @level = 1 @metadata = "0.90" @bitmap = nil @raid_device = name end def chunk(arg=nil) set_or_return( :chunk, arg, :kind_of => [ Integer ] ) end def devices(arg=nil) set_or_return( :devices, arg, :kind_of => [ Array ] ) end def exists(arg=nil) set_or_return( :exists, arg, :kind_of => [ TrueClass, FalseClass ] ) end def level(arg=nil) set_or_return( :level, arg, :kind_of => [ Integer ] ) end def metadata(arg=nil) set_or_return( :metadata, arg, :kind_of => [ String ] ) end def bitmap(arg=nil) set_or_return( :bitmap, arg, :kind_of => [ String ] ) end def raid_device(arg=nil) set_or_return( :raid_device, arg, :kind_of => [ String ] ) end end end end
ckaushik/chef
lib/chef/resource/mdadm.rb
Ruby
apache-2.0
2,207
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), View = _dereq_('../lib/View'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Core":5,"../lib/View":26}],2:[function(_dereq_,module,exports){ "use strict"; /** * Creates an always-sorted multi-key bucket that allows ForerunnerDB to * know the index that a document will occupy in an array with minimal * processing, speeding up things like sorted views. */ var Shared = _dereq_('./Shared'); /** * The active bucket class. * @param {object} orderBy An order object. * @constructor */ var ActiveBucket = function (orderBy) { var sortKey; this._primaryKey = '_id'; this._keyArr = []; this._data = []; this._objLookup = {}; this._count = 0; for (sortKey in orderBy) { if (orderBy.hasOwnProperty(sortKey)) { this._keyArr.push({ key: sortKey, dir: orderBy[sortKey] }); } } }; Shared.addModule('ActiveBucket', ActiveBucket); Shared.synthesize(ActiveBucket.prototype, 'primaryKey'); Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting'); /** * Quicksorts a single document into the passed array and * returns the index that the document should occupy. * @param {object} obj The document to calculate index for. * @param {array} arr The array the document index will be * calculated for. * @param {string} item The string key representation of the * document whose index is being calculated. * @param {function} fn The comparison function that is used * to determine if a document is sorted below or above the * document we are calculating the index for. * @returns {number} The index the document should occupy. */ ActiveBucket.prototype.qs = function (obj, arr, item, fn) { // If the array is empty then return index zero if (!arr.length) { return 0; } var lastMidwayIndex = -1, midwayIndex, lookupItem, result, start = 0, end = arr.length - 1; // Loop the data until our range overlaps while (end >= start) { // Calculate the midway point (divide and conquer) midwayIndex = Math.floor((start + end) / 2); if (lastMidwayIndex === midwayIndex) { // No more items to scan break; } // Get the item to compare against lookupItem = arr[midwayIndex]; if (lookupItem !== undefined) { // Compare items result = fn(this, obj, item, lookupItem); if (result > 0) { start = midwayIndex + 1; } if (result < 0) { end = midwayIndex - 1; } } lastMidwayIndex = midwayIndex; } if (result > 0) { return midwayIndex + 1; } else { return midwayIndex; } }; /** * Calculates the sort position of an item against another item. * @param {object} sorter An object or instance that contains * sortAsc and sortDesc methods. * @param {object} obj The document to compare. * @param {string} a The first key to compare. * @param {string} b The second key to compare. * @returns {number} Either 1 for sort a after b or -1 to sort * a before b. * @private */ ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) { var aVals = a.split('.:.'), bVals = b.split('.:.'), arr = sorter._keyArr, count = arr.length, index, sortType, castType; for (index = 0; index < count; index++) { sortType = arr[index]; castType = typeof obj[sortType.key]; if (castType === 'number') { aVals[index] = Number(aVals[index]); bVals[index] = Number(bVals[index]); } // Check for non-equal items if (aVals[index] !== bVals[index]) { // Return the sorted items if (sortType.dir === 1) { return sorter.sortAsc(aVals[index], bVals[index]); } if (sortType.dir === -1) { return sorter.sortDesc(aVals[index], bVals[index]); } } } }; /** * Inserts a document into the active bucket. * @param {object} obj The document to insert. * @returns {number} The index the document now occupies. */ ActiveBucket.prototype.insert = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Insert key keyIndex = this.qs(obj, this._data, key, this._sortFunc); this._data.splice(keyIndex, 0, key); } else { this._data.splice(keyIndex, 0, key); } this._objLookup[obj[this._primaryKey]] = key; this._count++; return keyIndex; }; /** * Removes a document from the active bucket. * @param {object} obj The document to remove. * @returns {boolean} True if the document was removed * successfully or false if it wasn't found in the active * bucket. */ ActiveBucket.prototype.remove = function (obj) { var key, keyIndex; key = this._objLookup[obj[this._primaryKey]]; if (key) { keyIndex = this._data.indexOf(key); if (keyIndex > -1) { this._data.splice(keyIndex, 1); delete this._objLookup[obj[this._primaryKey]]; this._count--; return true; } else { return false; } } return false; }; /** * Get the index that the passed document currently occupies * or the index it will occupy if added to the active bucket. * @param {object} obj The document to get the index for. * @returns {number} The index. */ ActiveBucket.prototype.index = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Get key index keyIndex = this.qs(obj, this._data, key, this._sortFunc); } return keyIndex; }; /** * The key that represents the passed document. * @param {object} obj The document to get the key for. * @returns {string} The document key. */ ActiveBucket.prototype.documentKey = function (obj) { var key = '', arr = this._keyArr, count = arr.length, index, sortType; for (index = 0; index < count; index++) { sortType = arr[index]; if (key) { key += '.:.'; } key += obj[sortType.key]; } // Add the unique identifier on the end of the key key += '.:.' + obj[this._primaryKey]; return key; }; /** * Get the number of documents currently indexed in the active * bucket instance. * @returns {number} The number of documents. */ ActiveBucket.prototype.count = function () { return this._count; }; Shared.finishModule('ActiveBucket'); module.exports = ActiveBucket; },{"./Shared":25}],3:[function(_dereq_,module,exports){ "use strict"; /** * The main collection class. Collections store multiple documents and * can operate on them using the query language to insert, read, update * and delete. */ var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Crc, Overload, ReactorIO; Shared = _dereq_('./Shared'); /** * Collection object used to store data. * @constructor */ var Collection = function (name) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name) { this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._deferQueue = { insert: [], update: [], remove: [], upsert: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; // Set the subset to itself since it is the root collection this._subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Shared.mixin(Collection.prototype, 'Mixin.Updating'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Crc = _dereq_('./Crc'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Collection.prototype.crc = Crc; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Get the internal data * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (this._state !== 'dropped') { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log('Dropping collection ' + this._name); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._name; delete this._data; delete this._metrics; if (callback) { callback(false, true); } return true; } } else { if (callback) { callback(false, true); } return true; } if (callback) { callback(false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); } } return this.$super.apply(this, arguments); }); /** * Sets the collection's data to the array of documents passed. * @param data * @param options Optional options object. * @param callback Optional callback function. */ Collection.prototype.setData = function (data, options, callback) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } if (data) { var op = this._metrics.create('setData'); op.start(); options = this.options(options); this.preSetData(data, options, callback); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } op.time('transformIn'); data = this.transformIn(data); op.time('transformIn'); var oldData = [].concat(this._data); this._dataReplace(data); // Update the primary key index op.time('Rebuild Primary Key Index'); this.rebuildPrimaryKeyIndex(options); op.time('Rebuild Primary Key Index'); // Rebuild all other indexes op.time('Rebuild All Other Indexes'); this._rebuildIndexes(); op.time('Rebuild All Other Indexes'); op.time('Resolve chains'); this.chainSend('setData', data, {oldData: oldData}); op.time('Resolve chains'); op.stop(); this.emit('setData', this._data, oldData); } if (callback) { callback(false); } return this; }; /** * Drops and rebuilds the primary key index for all documents in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw('ForerunnerDB.Collection "' + this.name() + '": Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a CRC string jString = JSON.stringify(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} obj The document object to upsert or an array containing * documents to upsert. * * If the document contains a primary key field (based on the collections's primary * key) then the database will search for an existing document with a matching id. * If a matching document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with new data. Any keys * that do not currently exist on the document will be added to the document. * * If the document does not contain an id or the id passed does not match an existing * document, an insert is performed instead. If no id is present a new primary key * id is provided for the item. * * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains either "insert" or * "update" depending on the type of operation that was performed and "result" * contains the return data from the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert; var returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback(); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj); break; case 'update': returnData.result = this.update(query, obj); break; default: break; } return returnData; } else { if (callback) { callback(); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } // Decouple the update data update = this.decouple(update); // Handle transform update = this.transformIn(update); if (this.debug()) { console.log('Updating some collection data for collection "' + this.name() + '"'); } var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (originalDoc) { var newDoc = self.decouple(originalDoc), triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, originalDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(originalDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, originalDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(originalDoc, update, query, options, ''); } return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { op.time('Resolve chains'); this.chainSend('update', { query: query, update: update, dataSet: dataSet }, options); op.time('Resolve chains'); this._onUpdate(updated); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw('ForerunnerDB.Collection "' + this.name() + '": Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return true; }; /** * Helper method to update a document from it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to update to. * @returns {Array} The items that were updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update); }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, pathInstance, sourceIsArray, updateIsArray, i; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': case '$data': // Ignore some operators operation = true; break; case '$each': operation = true; // Loop over the array of updates and run each one tmpCount = update.$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path); if (recurseUpdated) { updated = true; } } updated = updated || recurseUpdated; break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': this._updateIncrement(doc, i, update[i]); updated = true; break; case '$cast': // Casts a property to the type specified if it is not already // that type. If the cast is an array or an object and the property // is not already that type a new array or object is created and // set to the property, overwriting the previous value switch (update[i]) { case 'array': if (!(doc[i] instanceof Array)) { // Cast to an array this._updateProperty(doc, i, update.$data || []); updated = true; } break; case 'object': if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) { // Cast to an object this._updateProperty(doc, i, update.$data || {}); updated = true; } break; case 'number': if (typeof doc[i] !== 'number') { // Cast to a number this._updateProperty(doc, i, Number(doc[i])); updated = true; } break; case 'string': if (typeof doc[i] !== 'string') { // Cast to a string this._updateProperty(doc, i, String(doc[i])); updated = true; } break; default: throw('ForerunnerDB.Collection "' + this.name() + '": Cannot update cast to unknown type: ' + update[i]); } break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = JSON.stringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (JSON.stringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot splicePush without a $index integer value!'); } } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot move without a $index integer value!'); } break; } } } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot pop from a key that is not an array! (' + i + ')'); } break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search query * key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback(false, returnArr); } return returnArr; } else { dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } //op.time('Resolve chains'); this.chainSend('remove', { query: query, dataSet: dataSet }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(dataSet); } this.deferEmit('change', {type: 'remove', data: dataSet}); } if (callback) { callback(false, dataSet); } return dataSet; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Array} An array of documents that were removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj); }; /** * Queues an event to be fired. This has automatic de-bouncing so that any * events of the same type that occur within 100 milliseconds of a previous * one will all be wrapped into a single emit rather than emitting tons of * events for lots of chained inserts etc. * @private */ Collection.prototype.deferEmit = function () { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout if (this._changeTimeout) { clearTimeout(this._changeTimeout); } // Set a timeout this._changeTimeout = setTimeout(function () { if (self.debug()) { console.log('ForerunnerDB.Collection: Emitting ' + args[0]); } self.emit.apply(self, args); }, 1); } else { this.emit.apply(this, arguments); } }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. */ Collection.prototype.processQueue = function (type, callback) { var queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type]; if (queue.length) { var self = this, dataArr; // Process items up to the threshold if (queue.length) { if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } this[type](dataArr); } // Queue another process setTimeout(function () { self.processQueue(type, callback); }, deferTime); } else { if (callback) { callback(); } } }; /** * Inserts a document or array of documents into the collection. * @param {Object||Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype.insert = function (data, index, callback) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * Inserts a document or array of documents into the collection. * @param {Object||Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } //op.time('Resolve chains'); this.chainSend('insert', data, {index: index}); //op.time('Resolve chains'); this._onInsert(inserted, failed); if (callback) { callback(); } this.deferEmit('change', {type: 'insert', data: inserted}); return { inserted: inserted, failed: failed }; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc; this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return false; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, jString = JSON.stringify(doc); // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc); this._primaryCrc.uniqueSet(doc[this._primaryKey], jString); this._crcLookup.uniqueSet(jString, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, jString = JSON.stringify(doc); // Remove from primary key index this._primaryIndex.unSet(doc[this._primaryKey]); this._primaryCrc.unSet(doc[this._primaryKey]); this._crcLookup.unSet(jString); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Returns the index of the document identified by the passed item's primary key. * @param {Object} item The item whose primary key should be used to lookup. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (item) { return this._data.indexOf( this._primaryIndex.get( item[this._primaryKey] ) ); }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() ._subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Gets the collection that this collection is a subset of. * @returns {Collection} */ Collection.prototype.subsetOf = function () { return this.__subsetOf; }; /** * Sets the collection that this collection is a subset of. * @param {Collection} collection The collection to set as the parent of this subset. * @returns {*} This object for chaining. * @private */ Collection.prototype._subsetOf = function (collection) { this.__subsetOf = collection; return this; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param search The string to search for. Case sensitive. * @param options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = JSON.stringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; options = this.options(options); var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, //finalQuery, scanLength, requiresTableScan = true, resultArr, joinCollectionIndex, joinIndex, joinCollection = {}, joinQuery, joinPath, joinCollectionName, joinCollectionInstance, joinMatch, joinMatchIndex, joinSearch, joinMulti, joinRequire, joinFindResults, resultCollectionName, resultIndex, resultRemove = [], index, i, j, k, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, matcher = function (doc) { return self._match(doc, query, 'and', matcherTmpOptions); }; op.start(); if (query) { // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(query, options, op); op.time('analyseQuery'); op.data('analysis', analysis); if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get an instance reference to the join collections op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinCollectionName = analysis.joinsOn[joinIndex]; joinPath = new Path(analysis.joinQueries[joinCollectionName]); joinQuery = joinPath.value(query)[0]; joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery); } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } op.time('tableScan: ' + scanLength); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { // Set the key to store the join result in to the collection name by default resultCollectionName = joinCollectionName; // Get the join collection instance from the DB joinCollectionInstance = this._db.collection(joinCollectionName); // Get the match data for the join joinMatch = options.$join[joinCollectionIndex][joinCollectionName]; // Loop our result data array for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearch = {}; joinMulti = false; joinRequire = false; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$as': // Rename the collection when stored in the result document resultCollectionName = joinMatch[joinMatchIndex]; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatch[joinMatchIndex]; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatch[joinMatchIndex]; break; /*default: // Check for a double-dollar which is a back-reference to the root collection item if (joinMatchIndex.substr(0, 3) === '$$.') { // Back reference // TODO: Support complex joins } break;*/ } } else { // TODO: Could optimise this by caching path objects // Get the data to match against and store in the search object joinSearch[joinMatchIndex] = new Path(joinMatch[joinMatchIndex]).value(resultArr[resultIndex])[0]; } } } // Do a find on the target collection against the match data joinFindResults = joinCollectionInstance.find(joinSearch); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultArr[resultIndex]); } } } } } op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); for (i = 0; i < resultRemove.length; i++) { index = resultArr.indexOf(resultRemove[i]); if (index > -1) { resultArr.splice(index, 1); } } op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @returns {Number} */ Collection.prototype.indexOf = function (query) { var item = this.find(query, {$decouple: false})[0]; if (item) { return this._data.indexOf(item); } }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformIn(data[i]); } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformOut(data[i]); } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = sortKey; sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } }; /** * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets buckets = this.bucket(keyObj.___fdbKey, arr); // Loop buckets and sort contents for (i in buckets) { if (buckets.hasOwnProperty(i)) { arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[i])); } } return finalArr; } else { return this._sort(keyObj, arr); } }; /** * Sorts array by individual sort path. * @param key * @param arr * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw('ForerunnerDB.Collection "' + this.name() + '": $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ Collection.prototype.bucket = function (key, arr) { var i, buckets = {}; for (i = 0; i < arr.length; i++) { buckets[arr[i][key]] = buckets[arr[i][key]] || []; buckets[arr[i][key]].push(arr[i]); } return buckets; }; /** * Internal method that takes a search query and options and returns an object * containing details about the query which can be used to optimise the search. * * @param query * @param options * @param op * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [this._name], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinCollectionIndex, joinCollectionName, joinCollections = [], joinCollectionReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.countKeys(query); if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); analysis.indexMatch.push({ lookup: this._primaryIndex.lookup(query, options), keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { // Loop the join collections and keep a reference to them for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { joinCollections.push(joinCollectionName); // Check if the join uses an $as operator if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) { joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as); } else { joinCollectionReferences.push(joinCollectionName); } } } } // Loop the join collection references and determine if the query references // any of the collections that are used in the join. If there no queries against // joined collections the find method can use a code path optimised for this. // Queries against joined collections requires the joined collections to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinCollectionReferences.length; index++) { // Check if the query references any collection data that the join will create queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], ''); if (queryPath) { analysis.joinQueries[joinCollections[index]] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinCollections; analysis.queriesOn = analysis.queriesOn.concat(joinCollections); } return analysis; }; /** * Checks if the passed query references this collection. * @param query * @param collection * @param path * @returns {*} * @private */ Collection.prototype._queryReferencesCollection = function (query, collection, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === collection) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesCollection(query[i], collection, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param match * @param path * @param subDocQuery * @param subDocOptions * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docArr = this.find(match), docCount = docArr.length, docIndex, subDocArr, subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } resultObj.subDocs.push(subDocResults); resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.noStats) { return resultObj.subDocs; } if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } return resultObj; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { switch (options.type) { case 'hashed': index = new IndexHashMap(keys, options, this); break; case 'btree': index = new IndexBinaryTree(keys, options, this); break; default: // Default index = new IndexHashMap(keys, options, this); break; } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; } // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pm = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pm !== collection.primaryKey()) { throw('ForerunnerDB.Collection "' + this.name() + '": Collection diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pm])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pm]) !== collection._primaryCrc.get(arrItem[pm])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pm])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload({ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data); self.update({}, obj1); break; case 'update': obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); break; case 'remove': obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); break; default: } }); }, 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; Db.prototype.collection = new Overload({ /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @param {Object} options An options object. * @returns {Collection} */ 'object': function (options) { return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, /** * The main handler method. This get's called by all the other variants and * handles the actual logic of the overloaded method. * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var name = options.name; if (name) { if (!this._collection[name]) { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw('ForerunnerDB.Db "' + this.name() + '": Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } } if (this.debug()) { console.log('Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name).db(this); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw('ForerunnerDB.Db "' + this.name() + '": Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each collection * the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { if (search) { if (search.exec(i)) { arr.push({ name: i, count: this._collection[i].count() }); } } else { arr.push({ name: i, count: this._collection[i].count() }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Crc":6,"./IndexBinaryTree":8,"./IndexHashMap":9,"./KeyValueStore":10,"./Metrics":11,"./Overload":22,"./Path":23,"./ReactorIO":24,"./Shared":25}],4:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, DbInit, Collection; Shared = _dereq_('./Shared'); var CollectionGroup = function () { this.init.apply(this, arguments); }; CollectionGroup.prototype.init = function (name) { var self = this; self._name = name; self._data = new Collection('__FDB__cg_data_' + self._name); self._collections = []; self._view = []; }; Shared.addModule('CollectionGroup', CollectionGroup); Shared.mixin(CollectionGroup.prototype, 'Mixin.Common'); Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; DbInit = Shared.modules.Db.prototype.init; CollectionGroup.prototype.on = function () { this._data.on.apply(this._data, arguments); }; CollectionGroup.prototype.off = function () { this._data.off.apply(this._data, arguments); }; CollectionGroup.prototype.emit = function () { this._data.emit.apply(this._data, arguments); }; /** * Gets / sets the primary key for this collection group. * @param {String=} keyName The name of the primary key. * @returns {*} */ CollectionGroup.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { this._primaryKey = keyName; return this; } return this._primaryKey; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'state'); /** * Gets / sets the db instance the collection group belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'db'); CollectionGroup.prototype.addCollection = function (collection) { if (collection) { if (this._collections.indexOf(collection) === -1) { //var self = this; // Check for compatible primary keys if (this._collections.length) { if (this._primaryKey !== collection.primaryKey()) { throw('ForerunnerDB.CollectionGroup "' + this.name() + '": All collections in a collection group must have the same primary key!'); } } else { // Set the primary key to the first collection added this.primaryKey(collection.primaryKey()); } // Add the collection this._collections.push(collection); collection._groups = collection._groups || []; collection._groups.push(this); collection.chain(this); // Hook the collection's drop event to destroy group data collection.on('drop', function () { // Remove collection from any group associations if (collection._groups && collection._groups.length) { var groupArr = [], i; // Copy the group array because if we call removeCollection on a group // it will alter the groups array of this collection mid-loop! for (i = 0; i < collection._groups.length; i++) { groupArr.push(collection._groups[i]); } // Loop any groups we are part of and remove ourselves from them for (i = 0; i < groupArr.length; i++) { collection._groups[i].removeCollection(collection); } } delete collection._groups; }); // Add collection's data this._data.insert(collection.find()); } } return this; }; CollectionGroup.prototype.removeCollection = function (collection) { if (collection) { var collectionIndex = this._collections.indexOf(collection), groupIndex; if (collectionIndex !== -1) { collection.unChain(this); this._collections.splice(collectionIndex, 1); collection._groups = collection._groups || []; groupIndex = collection._groups.indexOf(this); if (groupIndex !== -1) { collection._groups.splice(groupIndex, 1); } collection.off('drop'); } if (this._collections.length === 0) { // Wipe the primary key delete this._primaryKey; } } return this; }; CollectionGroup.prototype._chainHandler = function (chainPacket) { //sender = chainPacket.sender; switch (chainPacket.type) { case 'setData': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Remove old data this._data.remove(chainPacket.options.oldData); // Add new data this._data.insert(chainPacket.data); break; case 'insert': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Add new data this._data.insert(chainPacket.data); break; case 'update': // Update data this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options); break; case 'remove': this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; CollectionGroup.prototype.insert = function () { this._collectionsRun('insert', arguments); }; CollectionGroup.prototype.update = function () { this._collectionsRun('update', arguments); }; CollectionGroup.prototype.updateById = function () { this._collectionsRun('updateById', arguments); }; CollectionGroup.prototype.remove = function () { this._collectionsRun('remove', arguments); }; CollectionGroup.prototype._collectionsRun = function (type, args) { for (var i = 0; i < this._collections.length; i++) { this._collections[i][type].apply(this._collections[i], args); } }; CollectionGroup.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. */ CollectionGroup.prototype.removeById = function (id) { // Loop the collections in this group and apply the remove for (var i = 0; i < this._collections.length; i++) { this._collections[i].removeById(id); } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ CollectionGroup.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() ._subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Drops a collection group from the database. * @returns {boolean} True on success, false on failure. */ CollectionGroup.prototype.drop = function () { if (this._state !== 'dropped') { var i, collArr, viewArr; if (this._debug) { console.log('Dropping collection group ' + this._name); } this._state = 'dropped'; if (this._collections && this._collections.length) { collArr = [].concat(this._collections); for (i = 0; i < collArr.length; i++) { this.removeCollection(collArr[i]); } } if (this._view && this._view.length) { viewArr = [].concat(this._view); for (i = 0; i < viewArr.length; i++) { this._removeView(viewArr[i]); } } this.emit('drop', this); } return true; }; // Extend DB to include collection groups Db.prototype.init = function () { this._collectionGroup = {}; DbInit.apply(this, arguments); }; Db.prototype.collectionGroup = function (collectionGroupName) { if (collectionGroupName) { this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this); return this._collectionGroup[collectionGroupName]; } else { // Return an object of collection data return this._collectionGroup; } }; /** * Returns an array of collection groups the DB currently has. * @returns {Array} An array of objects containing details of each collection group * the database is currently managing. */ Db.prototype.collectionGroups = function () { var arr = [], i; for (i in this._collectionGroup) { if (this._collectionGroup.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; module.exports = CollectionGroup; },{"./Collection":3,"./Shared":25}],5:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Db, Metrics, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * The main ForerunnerDB core object. * @constructor */ var Core = function (name) { this.init.apply(this, arguments); }; Core.prototype.init = function () { this._db = {}; this._debug = {}; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Core.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Core.moduleLoaded = Core.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Core.version = Core.prototype.version; // Provide public access to the Shared object Core.shared = Shared; Core.prototype.shared = Shared; Shared.addModule('Core', Core); Shared.mixin(Core.prototype, 'Mixin.Common'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Db = _dereq_('./Db.js'); Metrics = _dereq_('./Metrics.js'); Core.prototype._isServer = false; /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Core.prototype.isServer = function () { return this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Added to provide an error message for users who have not seen * the new instantiation breaking change warning and try to get * a collection directly from the core instance. */ Core.prototype.collection = function () { throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"); }; module.exports = Core; },{"./Db.js":7,"./Metrics.js":11,"./Overload":22,"./Shared":25}],6:[function(_dereq_,module,exports){ "use strict"; var crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); module.exports = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; },{}],7:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Core, Collection, Metrics, Crc, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * The main ForerunnerDB db object. * @constructor */ var Db = function (name) { this.init.apply(this, arguments); }; Db.prototype.init = function (name) { this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Db.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Db.moduleLoaded = Db.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Db.version = Db.prototype.version; // Provide public access to the Shared object Db.shared = Shared; Db.prototype.shared = Shared; Shared.addModule('Db', Db); Shared.mixin(Db.prototype, 'Mixin.Common'); Shared.mixin(Db.prototype, 'Mixin.ChainReactor'); Shared.mixin(Db.prototype, 'Mixin.Constants'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Crc = _dereq_('./Crc.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.crc = Crc; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Db.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; Db.prototype.drop = new Overload({ /** * Drops the database. */ '': function () { if (this._state !== 'dropped') { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; }, /** * Drops the database. * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (this._state !== 'dropped') { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; }, /** * Drops the database. * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (this._state !== 'dropped') { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; }, /** * Drops the database. * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (this._state !== 'dropped') { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist, afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name).core(this); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing. */ Core.prototype.databases = function (search) { var arr = [], i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { if (search) { if (search.exec(i)) { arr.push({ name: i, collectionCount: this._db[i].collections().length }); } } else { arr.push({ name: i, collectionCount: this._db[i].collections().length }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; module.exports = Db; },{"./Collection.js":3,"./Crc.js":6,"./Metrics.js":11,"./Overload":22,"./Shared":25}],8:[function(_dereq_,module,exports){ "use strict"; /* name id rebuild state match lookup */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), btree = function () {}; /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexBinaryTree = function () { this.init.apply(this, arguments); }; IndexBinaryTree.prototype.init = function (keys, options, collection) { this._btree = new (btree.create(2, this.sortAsc))(); this._size = 0; this._id = this._itemKeyHash(keys, keys); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexBinaryTree', IndexBinaryTree); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting'); IndexBinaryTree.prototype.id = function () { return this._id; }; IndexBinaryTree.prototype.state = function () { return this._state; }; IndexBinaryTree.prototype.size = function () { return this._size; }; Shared.synthesize(IndexBinaryTree.prototype, 'data'); Shared.synthesize(IndexBinaryTree.prototype, 'name'); Shared.synthesize(IndexBinaryTree.prototype, 'collection'); Shared.synthesize(IndexBinaryTree.prototype, 'type'); Shared.synthesize(IndexBinaryTree.prototype, 'unique'); IndexBinaryTree.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexBinaryTree.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree = new (btree.create(2, this.sortAsc))(); if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexBinaryTree.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // We store multiple items that match a key inside an array // that is then stored against that key in the tree... // Check if item exists for this key already keyArr = this._btree.get(dataItemHash); // Check if the array exists if (keyArr === undefined) { // Generate an array for this key first keyArr = []; // Put the new array into the tree under the key this._btree.put(dataItemHash, keyArr); } // Push the item into the array keyArr.push(dataItem); this._size++; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr, itemIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Try and get the array for the item hash key keyArr = this._btree.get(dataItemHash); if (keyArr !== undefined) { // The key array exits, remove the item from the key array itemIndex = keyArr.indexOf(dataItem); if (itemIndex > -1) { // Check the length of the array if (keyArr.length === 1) { // This item is the last in the array, just kill the tree entry this._btree.del(dataItemHash); } else { // Remove the item keyArr.splice(itemIndex, 1); } this._size--; } } }; IndexBinaryTree.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexBinaryTree.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./Path":23,"./Shared":25}],9:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":23,"./Shared":25}],10:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @constructor */ var KeyValueStore = function (name) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name) { this._name = name; this._data = {}; this._primaryKey = '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} obj A lookup query, can be a string key, an array of string keys, * an object with further query clauses or a regular expression that should be * run against all keys. * @returns {*} */ KeyValueStore.prototype.lookup = function (obj) { var pKeyVal = obj[this._primaryKey], arrIndex, arrCount, lookupItem, result; if (pKeyVal instanceof Array) { // An array of primary keys, find all matches arrCount = pKeyVal.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this._data[pKeyVal[arrIndex]]; if (lookupItem) { result.push(lookupItem); } } return result; } else if (pKeyVal instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.test(arrIndex)) { result.push(this._data[arrIndex]); } } } return result; } else if (typeof pKeyVal === 'object') { // The primary key clause is an object, now we have to do some // more extensive searching if (pKeyVal.$ne) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (arrIndex !== pKeyVal.$ne) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$in.indexOf(arrIndex) > -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$nin.indexOf(arrIndex) === -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) { result = result.concat(this.lookup(pKeyVal.$or[arrIndex])); } return result; } } else { // Key is a basic lookup from string lookupItem = this._data[pKeyVal]; if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } }; /** * Removes data for the given key from the store. * @param {String} key The key to un-set. * @returns {*} */ KeyValueStore.prototype.unSet = function (key) { delete this._data[key]; return this; }; /** * Sets data for the give key in the store only where the given key * does not already have a value in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {Boolean} True if data was set or false if data already * exists for the key. */ KeyValueStore.prototype.uniqueSet = function (key, value) { if (this._data[key] === undefined) { this._data[key] = value; return true; } return false; }; Shared.finishModule('KeyValueStore'); module.exports = KeyValueStore; },{"./Shared":25}],11:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Operation = _dereq_('./Operation'); /** * The metrics class used to store details about operations. * @constructor */ var Metrics = function () { this.init.apply(this, arguments); }; Metrics.prototype.init = function () { this._data = []; }; Shared.addModule('Metrics', Metrics); Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor'); /** * Creates an operation within the metrics instance and if metrics * are currently enabled (by calling the start() method) the operation * is also stored in the metrics log. * @param {String} name The name of the operation. * @returns {Operation} */ Metrics.prototype.create = function (name) { var op = new Operation(name); if (this._enabled) { this._data.push(op); } return op; }; /** * Starts logging operations. * @returns {Metrics} */ Metrics.prototype.start = function () { this._enabled = true; return this; }; /** * Stops logging operations. * @returns {Metrics} */ Metrics.prototype.stop = function () { this._enabled = false; return this; }; /** * Clears all logged operations. * @returns {Metrics} */ Metrics.prototype.clear = function () { this._data = []; return this; }; /** * Returns an array of all logged operations. * @returns {Array} */ Metrics.prototype.list = function () { return this._data; }; Shared.finishModule('Metrics'); module.exports = Metrics; },{"./Operation":21,"./Shared":25}],12:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],13:[function(_dereq_,module,exports){ "use strict"; // TODO: Document the methods in this mixin var ChainReactor = { chain: function (obj) { this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, unChain: function (obj) { if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, chainSend: function (type, data, options) { if (this._chain) { var arr = this._chain, count = arr.length, index; for (index = 0; index < count; index++) { arr[index].chainReceive(this, type, data, options); } } }, chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }; // Fire our internal handler if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],14:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Common; Common = { /** * Gets / sets data in the item store. The store can be used to set and * retrieve data against a key. Useful for adding arbitrary key/value data * to a collection / view etc and retrieving it later. * @param {String|*} key The key under which to store the passed value or * retrieve the existing stored value. * @param {*=} val Optional value. If passed will overwrite the existing value * stored against the specified key if one currently exists. * @returns {*} */ store: function (key, val) { if (key !== undefined) { if (val !== undefined) { // Store the data this._store = this._store || {}; this._store[key] = val; return this; } if (this._store) { return this._store[key]; } } return undefined; }, /** * Removes a previously stored key/value pair from the item store, set previously * by using the store() method. * @param {String|*} key The key of the key/value pair to remove; * @returns {Common} Returns this for chaining. */ unStore: function (key) { if (key !== undefined) { delete this._store[key]; } return this; }, /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined) { if (!copies) { return JSON.parse(JSON.stringify(data)); } else { var i, json = JSON.stringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(JSON.parse(json)); } return copyArr; } } return undefined; }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]) }; module.exports = Common; },{"./Overload":22}],15:[function(_dereq_,module,exports){ "use strict"; var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],16:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); var Events = { on: new Overload({ /** * Attach an event listener to the passed event. * @param {String} event The name of the event to listen for. * @param {Function} listener The method to call when the event is fired. */ 'string, function': function (event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event]['*'] = this._listeners[event]['*'] || []; this._listeners[event]['*'].push(listener); return this; }, /** * Attach an event listener to the passed event only if the passed * id matches the document id for the event being fired. * @param {String} event The name of the event to listen for. * @param {*} id The document id to match against. * @param {Function} listener The method to call when the event is fired. */ 'string, *, function': function (event, id, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event][id] = this._listeners[event][id] || []; this._listeners[event][id].push(listener); return this; } }), off: new Overload({ 'string': function (event) { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } return this; }, 'string, function': function (event, listener) { var arr, index; if (typeof(listener) === 'string') { if (this._listeners && this._listeners[event] && this._listeners[event][listener]) { delete this._listeners[event][listener]; } } else { if (this._listeners && event in this._listeners) { arr = this._listeners[event]['*']; index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } return this; }, 'string, *, function': function (event, id, listener) { if (this._listeners && event in this._listeners && id in this.listeners[event]) { var arr = this._listeners[event][id], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } }, 'string, *': function (event, id) { if (this._listeners && event in this._listeners && id in this._listeners[event]) { // Kill all listeners for this event id delete this._listeners[event][id]; } } }), emit: function (event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arrIndex, arrCount; // Handle global emit if (this._listeners[event]['*']) { var arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } // Handle individual emit if (data instanceof Array) { // Check if the array is an array of objects in the collection if (data[0] && data[0][this._primaryKey]) { // Loop the array and check for listeners against the primary key var listenerIdArr = this._listeners[event], listenerIdCount, listenerIdIndex; arrCount = data.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { if (listenerIdArr[data[arrIndex][this._primaryKey]]) { // Emit for this id listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length; for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } return this; } }; module.exports = Events; },{"./Overload":22}],17:[function(_dereq_,module,exports){ "use strict"; var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; options = options || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number') { // Number comparison if (source !== test) { matchedAll = false; } } else { // String comparison if (source.localeCompare(test)) { matchedAll = false; } } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Reset operation flag operation = false; substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (typeof(source) === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (inArr[inArrIndex] === source) { return true; } } return false; } else { throw('ForerunnerDB.Mixin.Matching "' + this.name() + '": Cannot use an $in operator on a non-array key: ' + key); } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (notInArr[notInArrIndex] === source) { return false; } } return true; } else { throw('ForerunnerDB.Mixin.Matching "' + this.name() + '": Cannot use a $nin operator on a non-array key: ' + key); } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootQuery['//distinctLookup'] = options.$rootQuery['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootQuery['//distinctLookup'][distinctProp] = options.$rootQuery['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootQuery['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootQuery['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; } return -1; } }; module.exports = Matching; },{}],18:[function(_dereq_,module,exports){ "use strict"; var Sorting = { /** * Sorts the passed value a against the passed value b ascending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAsc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } return 0; }, /** * Sorts the passed value a against the passed value b descending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDesc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } return 0; } }; module.exports = Sorting; },{}],19:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); var Triggers = { /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Number} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {Function} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (this.debug()) { var typeName, phaseName; switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } //console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Check the response for a non-expected result (anything other than // undefined, true or false is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":22}],20:[function(_dereq_,module,exports){ "use strict"; var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log('ForerunnerDB.Mixin.Updating: Setting non-data-bound document property "' + prop + '" for "' + this.name() + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log('ForerunnerDB.Mixin.Updating: Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '" for "' + this.name() + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @param {*} val The new property value. * @private */ _updateOverwrite: function (doc, prop, val) { doc[prop] = val; }, /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ _updateUnset: function (doc, prop) { delete doc[prop]; }, /** * Removes all properties from an object without destroying * the object instance, thereby maintaining data-bound linking. * @param {Object} doc The parent object to modify. * @param {String} prop The name of the child object to clear. * @private */ _updateClear: function (doc, prop) { var obj = doc[prop], i; if (obj && typeof obj === 'object') { for (i in obj) { if (obj.hasOwnProperty(i)) { this._updateUnset(obj, i); } } } }, /** * Pops an item from the array stack. * @param {Object} doc The document to modify. * @param {Number=} val Optional, if set to 1 will pop, if set to -1 will shift. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false; if (doc.length > 0) { if (val === 1) { doc.pop(); updated = true; } else if (val === -1) { doc.shift(); updated = true; } } return updated; } }; module.exports = Updating; },{}],21:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The operation class, used to store details about an operation being * performed by the database. * @param {String} name The name of the operation. * @constructor */ var Operation = function (name) { this.pathSolver = new Path(); this.counter = 0; this.init.apply(this, arguments); }; Operation.prototype.init = function (name) { this._data = { operation: name, // The name of the operation executed such as "find", "update" etc index: { potential: [], // Indexes that could have potentially been used used: false // The index that was picked to use }, steps: [], // The steps taken to generate the query results, time: { startMs: 0, stopMs: 0, totalMs: 0, process: {} }, flag: {}, // An object with flags that denote certain execution paths log: [] // Any extra data that might be useful such as warnings or helpful hints }; }; Shared.addModule('Operation', Operation); Shared.mixin(Operation.prototype, 'Mixin.ChainReactor'); /** * Starts the operation timer. */ Operation.prototype.start = function () { this._data.time.startMs = new Date().getTime(); }; /** * Adds an item to the operation log. * @param {String} event The item to log. * @returns {*} */ Operation.prototype.log = function (event) { if (event) { var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0, logObj = { event: event, time: new Date().getTime(), delta: 0 }; this._data.log.push(logObj); if (lastLogTime) { logObj.delta = logObj.time - lastLogTime; } return this; } return this._data.log; }; /** * Called when starting and ending a timed operation, used to time * internal calls within an operation's execution. * @param {String} section An operation name. * @returns {*} */ Operation.prototype.time = function (section) { if (section !== undefined) { var process = this._data.time.process, processObj = process[section] = process[section] || {}; if (!processObj.startMs) { // Timer started processObj.startMs = new Date().getTime(); processObj.stepObj = { name: section }; this._data.steps.push(processObj.stepObj); } else { processObj.stopMs = new Date().getTime(); processObj.totalMs = processObj.stopMs - processObj.startMs; processObj.stepObj.totalMs = processObj.totalMs; delete processObj.stepObj; } return this; } return this._data.time; }; /** * Used to set key/value flags during operation execution. * @param {String} key * @param {String} val * @returns {*} */ Operation.prototype.flag = function (key, val) { if (key !== undefined && val !== undefined) { this._data.flag[key] = val; } else if (key !== undefined) { return this._data.flag[key]; } else { return this._data.flag; } }; Operation.prototype.data = function (path, val, noTime) { if (val !== undefined) { // Assign value to object path this.pathSolver.set(this._data, path, val); return this; } return this.pathSolver.get(this._data, path); }; Operation.prototype.pushData = function (path, val, noTime) { // Assign value to object path this.pathSolver.push(this._data, path, val); }; /** * Stops the operation timer. */ Operation.prototype.stop = function () { this._data.time.stopMs = new Date().getTime(); this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs; }; Shared.finishModule('Operation'); module.exports = Operation; },{"./Path":23,"./Shared":25}],22:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {Object} def * @returns {Function} * @constructor */ var Overload = function (def) { if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } throw('ForerunnerDB.Overload "' + this.name() + '": Overloaded method does not have a matching signature for the passed arguments: ' + JSON.stringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],23:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Path object used to resolve object paths and retrieve data from * objects by using paths. * @param {String=} path The path to assign. * @constructor */ var Path = function (path) { this.init.apply(this, arguments); }; Path.prototype.init = function (path) { if (path) { this.path(path); } }; Shared.addModule('Path', Path); Shared.mixin(Path.prototype, 'Mixin.ChainReactor'); /** * Gets / sets the given path for the Path instance. * @param {String=} path The path to assign. */ Path.prototype.path = function (path) { if (path !== undefined) { this._path = this.clean(path); this._pathParts = this._path.split('.'); return this; } return this._path; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Boolean} True if the object paths exist. */ Path.prototype.hasObjectPaths = function (testKeys, testObj) { var result = true, i; for (i in testKeys) { if (testKeys.hasOwnProperty(i)) { if (testObj[i] === undefined) { return false; } if (typeof testKeys[i] === 'object') { // Recurse object result = this.hasObjectPaths(testKeys[i], testObj[i]); // Should we exit early? if (!result) { return false; } } } } return result; }; /** * Counts the total number of key endpoints in the passed object. * @param {Object} testObj The object to count key endpoints for. * @returns {Number} The number of endpoints. */ Path.prototype.countKeys = function (testObj) { var totalKeys = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (testObj[i] !== undefined) { if (typeof testObj[i] !== 'object') { totalKeys++; } else { totalKeys += this.countKeys(testObj[i]); } } } } return totalKeys; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths and if so returns the number matched. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Object} Stats on the matched keys */ Path.prototype.countObjectPaths = function (testKeys, testObj) { var matchData, matchedKeys = {}, matchedKeyCount = 0, totalKeyCount = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (typeof testObj[i] === 'object') { // The test / query object key is an object, recurse matchData = this.countObjectPaths(testKeys[i], testObj[i]); matchedKeys[i] = matchData.matchedKeys; totalKeyCount += matchData.totalKeyCount; matchedKeyCount += matchData.matchedKeyCount; } else { // The test / query object has a property that is not an object so add it as a key totalKeyCount++; // Check if the test keys also have this key and it is also not an object if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') { matchedKeys[i] = true; matchedKeyCount++; } else { matchedKeys[i] = false; } } } } return { matchedKeys: matchedKeys, matchedKeyCount: matchedKeyCount, totalKeyCount: totalKeyCount }; }; /** * Takes a non-recursive object and converts the object hierarchy into * a path string. * @param {Object} obj The object to parse. * @param {Boolean=} withValue If true will include a 'value' key in the returned * object that represents the value the object path points to. * @returns {Object} */ Path.prototype.parse = function (obj, withValue) { var paths = [], path = '', resultData, i, k; for (i in obj) { if (obj.hasOwnProperty(i)) { // Set the path to the key path = i; if (typeof(obj[i]) === 'object') { if (withValue) { resultData = this.parse(obj[i], withValue); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path, value: resultData[k].value }); } } else { resultData = this.parse(obj[i]); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path }); } } } else { if (withValue) { paths.push({ path: path, value: obj[i] }); } else { paths.push({ path: path }); } } } } return paths; }; /** * Takes a non-recursive object and converts the object hierarchy into * an array of path strings that allow you to target all possible paths * in an object. * * @returns {Array} */ Path.prototype.parseArr = function (obj, options) { options = options || {}; return this._parseArr(obj, '', [], options); }; Path.prototype._parseArr = function (obj, path, paths, options) { var i, newPath = ''; path = path || ''; paths = paths || []; for (i in obj) { if (obj.hasOwnProperty(i)) { if (!options.ignore || (options.ignore && !options.ignore.test(i))) { if (path) { newPath = path + '.' + i; } else { newPath = i; } if (typeof(obj[i]) === 'object') { this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; /** * Gets the value(s) that the object contains for the currently assigned path string. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path) { if (obj !== undefined && typeof obj === 'object') { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr = [], i, k; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (objPartParent instanceof Array) { // Search inside the array for the next key for (k = 0; k < objPartParent.length; k++) { valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i])); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * Push a value to an array on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to the array to push to. * @param {*} val The value to push to the array at the object path. * @returns {*} */ Path.prototype.push = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = obj[part] || []; if (obj[part] instanceof Array) { obj[part].push(val); } else { throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!'); } } } return obj; }; /** * Gets the value(s) that the object contains for the currently assigned path string * with their associated keys. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path with the associated key. */ Path.prototype.keyValue = function (obj, path) { var pathParts, arr, arrCount, objPart, objPartParent, objPartHash, i; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (!objPart || typeof(objPart) !== 'object') { objPartHash = arr[i] + ':' + objPart; break; } objPartParent = objPart; } return objPartHash; }; /** * Removes leading period (.) from string and returns it. * @param {String} str The string to clean. * @returns {*} */ Path.prototype.clean = function (str) { if (str.substr(0, 1) === '.') { str = str.substr(1, str.length -1); } return str; }; Shared.finishModule('Path'); module.exports = Path; },{"./Shared":25}],24:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); var ReactorIO = function (reactorIn, reactorOut, reactorProcess) { if (reactorIn && reactorOut && reactorProcess) { this._reactorIn = reactorIn; this._reactorOut = reactorOut; this._chainHandler = reactorProcess; if (!reactorIn.chain || !reactorOut.chainReceive) { throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!'); } // Register the reactorIO with the input reactorIn.chain(this); // Register the output with the reactorIO this.chain(reactorOut); } else { throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!'); } }; Shared.addModule('ReactorIO', ReactorIO); ReactorIO.prototype.drop = function () { if (this._state !== 'dropped') { this._state = 'dropped'; // Remove links if (this._reactorIn) { this._reactorIn.unChain(this); } if (this._reactorOut) { this.unChain(this._reactorOut); } delete this._reactorIn; delete this._reactorOut; delete this._chainHandler; this.emit('drop', this); } return true; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(ReactorIO.prototype, 'state'); Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":25}],25:[function(_dereq_,module,exports){ "use strict"; var Shared = { version: '1.3.50', modules: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { this.modules[name] = module; this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { this.modules[name]._fdbFinished = true; this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { if (callback) { callback(name, this.modules[name]); } } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, /** * Adds the properties and methods defined in the mixin to the passed object. * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ mixin: function (obj, mixinName) { var system = this.mixins[mixinName]; if (system) { for (var i in system) { if (system.hasOwnProperty(i)) { obj[i] = system[i]; } } } else { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } }, /** * Generates a generic getter/setter method for the passed method name. * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @param arr * @returns {Function} * @constructor */ overload: _dereq_('./Overload'), /** * Define the mixins that other modules can use as required. */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":12,"./Mixin.ChainReactor":13,"./Mixin.Common":14,"./Mixin.Constants":15,"./Mixin.Events":16,"./Mixin.Matching":17,"./Mixin.Sorting":18,"./Mixin.Triggers":19,"./Mixin.Updating":20,"./Overload":22}],26:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, CollectionInit, DbInit, ReactorIO, ActiveBucket; Shared = _dereq_('./Shared'); /** * The view constructor. * @param name * @param query * @param options * @constructor */ var View = function (name, query, options) { this.init.apply(this, arguments); }; View.prototype.init = function (name, query, options) { var self = this; this._name = name; this._listeners = {}; this._querySettings = {}; this._debug = {}; this.query(query, false); this.queryOptions(options, false); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; this._privateData = new Collection('__FDB__view_privateData_' + this._name); }; Shared.addModule('View', View); Shared.mixin(View.prototype, 'Mixin.Common'); Shared.mixin(View.prototype, 'Mixin.ChainReactor'); Shared.mixin(View.prototype, 'Mixin.Constants'); Shared.mixin(View.prototype, 'Mixin.Triggers'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); ActiveBucket = _dereq_('./ActiveBucket'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(View.prototype, 'state'); Shared.synthesize(View.prototype, 'name'); Shared.synthesize(View.prototype, 'cursor'); /** * Executes an insert against the view's underlying data-source. */ View.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the view's underlying data-source. */ View.prototype.update = function () { this._from.update.apply(this._from, arguments); }; /** * Executes an updateById against the view's underlying data-source. */ View.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the view's underlying data-source. */ View.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Queries the view data. See Collection.find() for more information. * @returns {*} */ View.prototype.find = function (query, options) { return this.publicData().find(query, options); }; /** * Gets the module's internal data collection. * @returns {Collection} */ View.prototype.data = function () { return this._privateData; }; /** * Sets the collection from which the view will assemble its data. * @param {Collection} collection The collection to use to assemble view data. * @returns {View} */ View.prototype.from = function (collection) { var self = this; if (collection !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); delete this._from; } if (typeof(collection) === 'string') { collection = this._db.collection(collection); } this._from = collection; this._from.on('drop', this._collectionDroppedWrap); // Create a new reactor IO graph node that intercepts chain packets from the // view's "from" collection and determines how they should be interpreted by // this view. If the view does not have a query then this reactor IO will // simply pass along the chain packet without modifying it. this._io = new ReactorIO(collection, this, function (chainPacket) { var data, diff, query, filteredData, doSend, pk, i; // Check if we have a constraining query if (self._querySettings.query) { if (chainPacket.type === 'insert') { data = chainPacket.data; // Check if the data matches our query if (data instanceof Array) { filteredData = []; for (i = 0; i < data.length; i++) { if (self._privateData._match(data[i], self._querySettings.query, 'and', {})) { filteredData.push(data[i]); doSend = true; } } } else { if (self._privateData._match(data, self._querySettings.query, 'and', {})) { filteredData = data; doSend = true; } } if (doSend) { this.chainSend('insert', filteredData); } return true; } if (chainPacket.type === 'update') { // Do a DB diff between this view's data and the underlying collection it reads from // to see if something has changed diff = self._privateData.diff(self._from.subset(self._querySettings.query, self._querySettings.options)); if (diff.insert.length || diff.remove.length) { // Now send out new chain packets for each operation if (diff.insert.length) { this.chainSend('insert', diff.insert); } if (diff.update.length) { pk = self._privateData.primaryKey(); for (i = 0; i < diff.update.length; i++) { query = {}; query[pk] = diff.update[i][pk]; this.chainSend('update', { query: query, update: diff.update[i] }); } } if (diff.remove.length) { pk = self._privateData.primaryKey(); var $or = [], removeQuery = { query: { $or: $or } }; for (i = 0; i < diff.remove.length; i++) { $or.push({_id: diff.remove[i][pk]}); } this.chainSend('remove', removeQuery); } // Return true to stop further propagation of the chain packet return true; } else { // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } } } // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; }); var collData = collection.find(this._querySettings.query, this._querySettings.options); this._transformPrimaryKey(collection.primaryKey()); this._transformSetData(collData); this._privateData.primaryKey(collection.primaryKey()); this._privateData.setData(collData); if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } } return this; }; View.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from view delete this._from; } }; View.prototype.ensureIndex = function () { return this._privateData.ensureIndex.apply(this._privateData, arguments); }; View.prototype._chainHandler = function (chainPacket) { var //self = this, arr, count, index, insertIndex, //tempData, //dataIsArray, updates, //finalUpdates, primaryKey, tQuery, item, currentIndex, i; switch (chainPacket.type) { case 'setData': if (this.debug()) { console.log('ForerunnerDB.View: Setting data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"'); } // Get the new data from our underlying data source sorted as we want var collData = this._from.find(this._querySettings.query, this._querySettings.options); // Modify transform data this._transformSetData(collData); this._privateData.setData(collData); break; case 'insert': if (this.debug()) { console.log('ForerunnerDB.View: Inserting some data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"'); } // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Make sure we are working with an array if (!(chainPacket.data instanceof Array)) { chainPacket.data = [chainPacket.data]; } if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the insert data and find each item's index arr = chainPacket.data; count = arr.length; for (index = 0; index < count; index++) { insertIndex = this._activeBucket.insert(arr[index]); // Modify transform data this._transformInsert(chainPacket.data, insertIndex); this._privateData._insertHandle(chainPacket.data, insertIndex); } } else { // Set the insert index to the passed index, or if none, the end of the view data array insertIndex = this._privateData._data.length; // Modify transform data this._transformInsert(chainPacket.data, insertIndex); this._privateData._insertHandle(chainPacket.data, insertIndex); } break; case 'update': if (this.debug()) { console.log('ForerunnerDB.View: Updating some data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"'); } primaryKey = this._privateData.primaryKey(); // Do the update updates = this._privateData.update( chainPacket.data.query, chainPacket.data.update, chainPacket.data.options ); if (this._querySettings.options && this._querySettings.options.$orderBy) { // TODO: This would be a good place to improve performance by somehow // TODO: inspecting the change that occurred when update was performed // TODO: above and determining if it affected the order clause keys // TODO: and if not, skipping the active bucket updates here // Loop the updated items and work out their new sort locations count = updates.length; for (index = 0; index < count; index++) { item = updates[index]; // Remove the item from the active bucket (via it's id) this._activeBucket.remove(item); // Get the current location of the item currentIndex = this._privateData._data.indexOf(item); // Add the item back in to the active bucket insertIndex = this._activeBucket.insert(item); if (currentIndex !== insertIndex) { // Move the updated item to the new index this._privateData._updateSpliceMove(this._privateData._data, currentIndex, insertIndex); } } } if (this._transformEnabled && this._transformIn) { primaryKey = this._publicData.primaryKey(); for (i = 0; i < updates.length; i++) { tQuery = {}; item = updates[i]; tQuery[primaryKey] = item[primaryKey]; this._transformUpdate(tQuery, item); } } break; case 'remove': if (this.debug()) { console.log('ForerunnerDB.View: Removing some data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"'); } // Modify transform data this._transformRemove(chainPacket.data.query, chainPacket.options); this._privateData.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; View.prototype.on = function () { this._privateData.on.apply(this._privateData, arguments); }; View.prototype.off = function () { this._privateData.off.apply(this._privateData, arguments); }; View.prototype.emit = function () { this._privateData.emit.apply(this._privateData, arguments); }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ View.prototype.distinct = function (key, query, options) { return this._privateData.distinct.apply(this._privateData, arguments); }; /** * Gets the primary key for this view from the assigned collection. * @returns {String} */ View.prototype.primaryKey = function () { return this._privateData.primaryKey(); }; /** * Drops a view and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ View.prototype.drop = function () { if (this._state !== 'dropped') { if (this._from) { this._from.off('drop', this._collectionDroppedWrap); this._from._removeView(this); if (this.debug() || (this._db && this._db.debug())) { console.log('ForerunnerDB.View: Dropping view ' + this._name); } this._state = 'dropped'; // Clear io and chains if (this._io) { this._io.drop(); } // Drop the view's internal collection if (this._privateData) { this._privateData.drop(); } if (this._db && this._name) { delete this._db._view[this._name]; } this.emit('drop', this); delete this._chain; delete this._from; delete this._privateData; delete this._io; delete this._listeners; delete this._querySettings; delete this._db; return true; } } else { return true; } return false; }; /** * Gets / sets the DB the view is bound against. Automatically set * when the db.oldView(viewName) method is called. * @param db * @returns {*} */ View.prototype.db = function (db) { if (db !== undefined) { this._db = db; this.privateData().db(db); this.publicData().db(db); return this; } return this._db; }; /** * Gets / sets the query that the view uses to build it's data set. * @param {Object=} query * @param {Boolean=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryData = function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings; }; /** * Add data to the existing query. * @param {Object} obj The data whose keys will be added to the existing * query object. * @param {Boolean} overwrite Whether or not to overwrite data that already * exists in the query object. Defaults to true. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryAdd = function (obj, overwrite, refresh) { this._querySettings.query = this._querySettings.query || {}; var query = this._querySettings.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) { query[i] = obj[i]; } } } } if (refresh === undefined || refresh === true) { this.refresh(); } }; /** * Remove data from the existing query. * @param {Object} obj The data whose keys will be removed from the existing * query object. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryRemove = function (obj, refresh) { var query = this._querySettings.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { delete query[i]; } } } if (refresh === undefined || refresh === true) { this.refresh(); } }; /** * Gets / sets the query being used to generate the view data. * @param {Object=} query The query to set. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.query = function (query, refresh) { if (query !== undefined) { this._querySettings.query = query; if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings.query; }; /** * Gets / sets the orderBy clause in the query options for the view. * @param {Object=} val The order object. * @returns {*} */ View.prototype.orderBy = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; queryOptions.$orderBy = val; this.queryOptions(queryOptions); return this; } return (this.queryOptions() || {}).$orderBy; }; /** * Gets / sets the page clause in the query options for the view. * @param {Number=} val The page number to change to (zero index). * @returns {*} */ View.prototype.page = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; // Only execute a query options update if page has changed if (val !== queryOptions.$page) { queryOptions.$page = val; this.queryOptions(queryOptions); } return this; } return (this.queryOptions() || {}).$page; }; /** * Jump to the first page in the data set. * @returns {*} */ View.prototype.pageFirst = function () { return this.page(0); }; /** * Jump to the last page in the data set. * @returns {*} */ View.prototype.pageLast = function () { var pages = this.cursor().pages, lastPage = pages !== undefined ? pages : 0; return this.page(lastPage - 1); }; /** * Move forward or backwards in the data set pages by passing a positive * or negative integer of the number of pages to move. * @param {Number} val The number of pages to move. * @returns {*} */ View.prototype.pageScan = function (val) { if (val !== undefined) { var pages = this.cursor().pages, queryOptions = this.queryOptions() || {}, currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0; currentPage += val; if (currentPage < 0) { currentPage = 0; } if (currentPage >= pages) { currentPage = pages - 1; } return this.page(currentPage); } }; /** * Gets / sets the query options used when applying sorting etc to the * view data set. * @param {Object=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryOptions = function (options, refresh) { if (options !== undefined) { this._querySettings.options = options; if (options.$decouple === undefined) { options.$decouple = true; } if (refresh === undefined || refresh === true) { this.refresh(); } else { this.rebuildActiveBucket(options.$orderBy); } return this; } return this._querySettings.options; }; View.prototype.rebuildActiveBucket = function (orderBy) { if (orderBy) { var arr = this._privateData._data, arrCount = arr.length; // Build a new active bucket this._activeBucket = new ActiveBucket(orderBy); this._activeBucket.primaryKey(this._privateData.primaryKey()); // Loop the current view data and add each item for (var i = 0; i < arrCount; i++) { this._activeBucket.insert(arr[i]); } } else { // Remove any existing active bucket delete this._activeBucket; } }; /** * Refreshes the view data such as ordering etc. */ View.prototype.refresh = function () { if (this._from) { var pubData = this.publicData(), refreshResults; // Re-grab all the data for the view from the collection this._privateData.remove(); pubData.remove(); refreshResults = this._from.find(this._querySettings.query, this._querySettings.options); this.cursor(refreshResults.$cursor); this._privateData.insert(refreshResults); this._privateData._data.$cursor = refreshResults.$cursor; pubData._data.$cursor = refreshResults.$cursor; /*if (pubData._linked) { // Update data and observers //var transformedData = this._privateData.find(); // TODO: Shouldn't this data get passed into a transformIn first? // TODO: This breaks linking because its passing decoupled data and overwriting non-decoupled data // TODO: Is this even required anymore? After commenting it all seems to work // TODO: Might be worth setting up a test to check transforms and linking then remove this if working? //jQuery.observable(pubData._data).refresh(transformedData); }*/ } if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; }; /** * Returns the number of documents currently in the view. * @returns {Number} */ View.prototype.count = function () { return this._privateData && this._privateData._data ? this._privateData._data.length : 0; }; // Call underlying View.prototype.subset = function () { return this.publicData().subset.apply(this._privateData, arguments); }; /** * Takes the passed data and uses it to set transform methods and globally * enable or disable the transform system for the view. * @param {Object} obj The new transform system settings "enabled", "dataIn" and "dataOut": * { * "enabled": true, * "dataIn": function (data) { return data; }, * "dataOut": function (data) { return data; } * } * @returns {*} */ View.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } // Update the transformed data object this._transformPrimaryKey(this.privateData().primaryKey()); this._transformSetData(this.privateData().find()); return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ View.prototype.filter = function (query, func, options) { return (this.publicData()).filter(query, func, options); }; /** * Returns the non-transformed data the view holds as a collection * reference. * @return {Collection} The non-transformed collection reference. */ View.prototype.privateData = function () { return this._privateData; }; /** * Returns a data object representing the public data this view * contains. This can change depending on if transforms are being * applied to the view or not. * * If no transforms are applied then the public data will be the * same as the private data the view holds. If transforms are * applied then the public data will contain the transformed version * of the private data. * * The public data collection is also used by data binding to only * changes to the publicData will show in a data-bound element. */ View.prototype.publicData = function () { if (this._transformEnabled) { return this._publicData; } else { return this._privateData; } }; /** * Updates the public data object to match data from the private data object * by running private data through the dataIn method provided in * the transform() call. * @private */ View.prototype._transformSetData = function (data) { if (this._transformEnabled) { // Clear existing data this._publicData = new Collection('__FDB__view_publicData_' + this._name); this._publicData.db(this._privateData._db); this._publicData.transform({ enabled: true, dataIn: this._transformIn, dataOut: this._transformOut }); this._publicData.setData(data); } }; View.prototype._transformInsert = function (data, index) { if (this._transformEnabled && this._publicData) { this._publicData.insert(data, index); } }; View.prototype._transformUpdate = function (query, update, options) { if (this._transformEnabled && this._publicData) { this._publicData.update(query, update, options); } }; View.prototype._transformRemove = function (query, options) { if (this._transformEnabled && this._publicData) { this._publicData.remove(query, options); } }; View.prototype._transformPrimaryKey = function (key) { if (this._transformEnabled && this._publicData) { this._publicData.primaryKey(key); } }; // Extend collection with view init Collection.prototype.init = function () { this._view = []; CollectionInit.apply(this, arguments); }; /** * Creates a view and assigns the collection as its data source. * @param {String} name The name of the new view. * @param {Object} query The query to apply to the new view. * @param {Object} options The options object to apply to the view. * @returns {*} */ Collection.prototype.view = function (name, query, options) { if (this._db && this._db._view ) { if (!this._db._view[name]) { var view = new View(name, query, options) .db(this._db) .from(this); this._view = this._view || []; this._view.push(view); return view; } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot create a view using this collection because a view with this name already exists: ' + name); } } }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) { if (view !== undefined) { this._view.push(view); } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) { if (view !== undefined) { var index = this._view.indexOf(view); if (index > -1) { this._view.splice(index, 1); } } return this; }; // Extend DB with views init Db.prototype.init = function () { this._view = {}; DbInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} viewName The name of the view to retrieve. * @returns {*} */ Db.prototype.view = function (viewName) { if (!this._view[viewName]) { if (this.debug() || (this._db && this._db.debug())) { console.log('Db.View: Creating view ' + viewName); } } this._view[viewName] = this._view[viewName] || new View(viewName).db(this); return this._view[viewName]; }; /** * Determine if a view with the passed name already exists. * @param {String} viewName The name of the view to check for. * @returns {boolean} */ Db.prototype.viewExists = function (viewName) { return Boolean(this._view[viewName]); }; /** * Returns an array of views the DB currently has. * @returns {Array} An array of objects containing details of each view * the database is currently managing. */ Db.prototype.views = function () { var arr = [], i; for (i in this._view) { if (this._view.hasOwnProperty(i)) { arr.push({ name: i, count: this._view[i].count() }); } } return arr; }; Shared.finishModule('View'); module.exports = View; },{"./ActiveBucket":2,"./Collection":3,"./CollectionGroup":4,"./ReactorIO":24,"./Shared":25}]},{},[1]);
Piicksarn/cdnjs
ajax/libs/forerunnerdb/1.3.50/fdb-core+views.js
JavaScript
mit
223,891
/* * Copyright 2015 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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. */ #include <folly/io/async/EventHandler.h> #include <sys/eventfd.h> #include <thread> #include <folly/MPMCQueue.h> #include <folly/ScopeGuard.h> #include <folly/io/async/EventBase.h> #include <gtest/gtest.h> #include <gmock/gmock.h> using namespace std; using namespace folly; using namespace testing; void runInThreadsAndWait( size_t nthreads, function<void(size_t)> cb) { vector<thread> threads(nthreads); for (size_t i = 0; i < nthreads; ++i) { threads[i] = thread(cb, i); } for (size_t i = 0; i < nthreads; ++i) { threads[i].join(); } } void runInThreadsAndWait(vector<function<void()>> cbs) { runInThreadsAndWait(cbs.size(), [&](size_t k) { cbs[k](); }); } class EventHandlerMock : public EventHandler { public: EventHandlerMock(EventBase* eb, int fd) : EventHandler(eb, fd) {} // gmock can't mock noexcept methods, so we need an intermediary MOCK_METHOD1(_handlerReady, void(uint16_t)); void handlerReady(uint16_t events) noexcept override { _handlerReady(events); } }; class EventHandlerTest : public Test { public: int efd = 0; void SetUp() override { efd = eventfd(0, EFD_SEMAPHORE); ASSERT_THAT(efd, Gt(0)); } void TearDown() override { if (efd > 0) { close(efd); } efd = 0; } void efd_write(uint64_t val) { write(efd, &val, sizeof(val)); } uint64_t efd_read() { uint64_t val = 0; read(efd, &val, sizeof(val)); return val; } }; TEST_F(EventHandlerTest, simple) { const size_t writes = 4; size_t readsRemaining = writes; EventBase eb; EventHandlerMock eh(&eb, efd); eh.registerHandler(EventHandler::READ | EventHandler::PERSIST); EXPECT_CALL(eh, _handlerReady(_)) .Times(writes) .WillRepeatedly(Invoke([&](uint16_t events) { efd_read(); if (--readsRemaining == 0) { eh.unregisterHandler(); } })); efd_write(writes); eb.loop(); EXPECT_EQ(0, readsRemaining); } TEST_F(EventHandlerTest, many_concurrent_producers) { const size_t writes = 200; const size_t nproducers = 20; size_t readsRemaining = writes; runInThreadsAndWait({ [&] { EventBase eb; EventHandlerMock eh(&eb, efd); eh.registerHandler(EventHandler::READ | EventHandler::PERSIST); EXPECT_CALL(eh, _handlerReady(_)) .Times(writes) .WillRepeatedly(Invoke([&](uint16_t events) { efd_read(); if (--readsRemaining == 0) { eh.unregisterHandler(); } })); eb.loop(); }, [&] { runInThreadsAndWait(nproducers, [&](size_t k) { for (size_t i = 0; i < writes / nproducers; ++i) { this_thread::sleep_for(chrono::milliseconds(1)); efd_write(1); } }); }, }); EXPECT_EQ(0, readsRemaining); } TEST_F(EventHandlerTest, many_concurrent_consumers) { const size_t writes = 200; const size_t nproducers = 8; const size_t nconsumers = 20; atomic<size_t> writesRemaining(writes); atomic<size_t> readsRemaining(writes); MPMCQueue<nullptr_t> queue(writes / 10); runInThreadsAndWait({ [&] { runInThreadsAndWait(nconsumers, [&](size_t k) { size_t thReadsRemaining = writes / nconsumers; EventBase eb; EventHandlerMock eh(&eb, efd); eh.registerHandler(EventHandler::READ | EventHandler::PERSIST); EXPECT_CALL(eh, _handlerReady(_)) .WillRepeatedly(Invoke([&](uint16_t events) { nullptr_t val; if (!queue.readIfNotEmpty(val)) { return; } efd_read(); --readsRemaining; if (--thReadsRemaining == 0) { eh.unregisterHandler(); } })); eb.loop(); }); }, [&] { runInThreadsAndWait(nproducers, [&](size_t k) { for (size_t i = 0; i < writes / nproducers; ++i) { this_thread::sleep_for(chrono::milliseconds(1)); queue.blockingWrite(nullptr); efd_write(1); --writesRemaining; } }); }, }); EXPECT_EQ(0, writesRemaining); EXPECT_EQ(0, readsRemaining); }
respu/coral-folly
folly/io/async/test/EventHandlerTest.cpp
C++
apache-2.0
4,714
// 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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void TrailingZeroCountUInt64() { var test = new ScalarUnaryOpTest__TrailingZeroCountUInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.ReadUnaligned test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.ReadUnaligned test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.ReadUnaligned test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ScalarUnaryOpTest__TrailingZeroCountUInt64 { private struct TestStruct { public UInt64 _fld; public static TestStruct Create() { var testStruct = new TestStruct(); testStruct._fld = TestLibrary.Generator.GetUInt64(); return testStruct; } public void RunStructFldScenario(ScalarUnaryOpTest__TrailingZeroCountUInt64 testClass) { var result = Bmi1.X64.TrailingZeroCount(_fld); testClass.ValidateResult(_fld, result); } } private static UInt64 _data; private static UInt64 _clsVar; private UInt64 _fld; static ScalarUnaryOpTest__TrailingZeroCountUInt64() { _clsVar = TestLibrary.Generator.GetUInt64(); } public ScalarUnaryOpTest__TrailingZeroCountUInt64() { Succeeded = true; _fld = TestLibrary.Generator.GetUInt64(); _data = TestLibrary.Generator.GetUInt64(); } public bool IsSupported => Bmi1.X64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Bmi1.X64.TrailingZeroCount( Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data)) ); ValidateResult(_data, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Bmi1.X64).GetMethod(nameof(Bmi1.X64.TrailingZeroCount), new Type[] { typeof(UInt64) }) .Invoke(null, new object[] { Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data)) }); ValidateResult(_data, (UInt64)result); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Bmi1.X64.TrailingZeroCount( _clsVar ); ValidateResult(_clsVar, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var data = Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data)); var result = Bmi1.X64.TrailingZeroCount(data); ValidateResult(data, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ScalarUnaryOpTest__TrailingZeroCountUInt64(); var result = Bmi1.X64.TrailingZeroCount(test._fld); ValidateResult(test._fld, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Bmi1.X64.TrailingZeroCount(_fld); ValidateResult(_fld, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Bmi1.X64.TrailingZeroCount(test._fld); ValidateResult(test._fld, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(UInt64 data, UInt64 result, [CallerMemberName] string method = "") { var isUnexpectedResult = false; ulong expectedResult = 0; for (int index = 0; ((data >> index) & 1) == 0; index++) { expectedResult++; } isUnexpectedResult = (expectedResult != result); if (isUnexpectedResult) { TestLibrary.TestFramework.LogInformation($"{nameof(Bmi1.X64)}.{nameof(Bmi1.X64.TrailingZeroCount)}<UInt64>(UInt64): TrailingZeroCount failed:"); TestLibrary.TestFramework.LogInformation($" data: {data}"); TestLibrary.TestFramework.LogInformation($" result: {result}"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
krk/coreclr
tests/src/JIT/HardwareIntrinsics/X86/Bmi1.X64/TrailingZeroCount.UInt64.cs
C#
mit
7,684
<?php /** * @file * Contains \Drupal\toolbar\Controller\ToolbarController. */ namespace Drupal\toolbar\Controller; use Drupal\Core\Access\AccessResult; use Drupal\Core\Ajax\AjaxResponse; use Drupal\Core\Controller\ControllerBase; use Drupal\toolbar\Ajax\SetSubtreesCommand; /** * Defines a controller for the toolbar module. */ class ToolbarController extends ControllerBase { /** * Returns an AJAX response to render the toolbar subtrees. * * @return \Drupal\Core\Ajax\AjaxResponse */ public function subtreesAjax() { list($subtrees, $cacheability) = toolbar_get_rendered_subtrees(); $response = new AjaxResponse(); $response->addCommand(new SetSubtreesCommand($subtrees)); // The Expires HTTP header is the heart of the client-side HTTP caching. The // additional server-side page cache only takes effect when the client // accesses the callback URL again (e.g., after clearing the browser cache // or when force-reloading a Drupal page). $max_age = 365 * 24 * 60 * 60; $response->setPrivate(); $response->setMaxAge($max_age); $expires = new \DateTime(); $expires->setTimestamp(REQUEST_TIME + $max_age); $response->setExpires($expires); return $response; } /** * Checks access for the subtree controller. * * @param string $hash * The hash of the toolbar subtrees. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. */ public function checkSubTreeAccess($hash) { return AccessResult::allowedIf($this->currentUser()->hasPermission('access toolbar') && $hash == _toolbar_get_subtrees_hash()[0])->cachePerPermissions(); } }
komejo/article-test
web/core/modules/toolbar/src/Controller/ToolbarController.php
PHP
gpl-2.0
1,674
# orm/exc.py # Copyright (C) 2005-2016 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """SQLAlchemy ORM exceptions.""" from .. import exc as sa_exc, util NO_STATE = (AttributeError, KeyError) """Exception types that may be raised by instrumentation implementations.""" class StaleDataError(sa_exc.SQLAlchemyError): """An operation encountered database state that is unaccounted for. Conditions which cause this to happen include: * A flush may have attempted to update or delete rows and an unexpected number of rows were matched during the UPDATE or DELETE statement. Note that when version_id_col is used, rows in UPDATE or DELETE statements are also matched against the current known version identifier. * A mapped object with version_id_col was refreshed, and the version number coming back from the database does not match that of the object itself. * A object is detached from its parent object, however the object was previously attached to a different parent identity which was garbage collected, and a decision cannot be made if the new parent was really the most recent "parent". .. versionadded:: 0.7.4 """ ConcurrentModificationError = StaleDataError class FlushError(sa_exc.SQLAlchemyError): """A invalid condition was detected during flush().""" class UnmappedError(sa_exc.InvalidRequestError): """Base for exceptions that involve expected mappings not present.""" class ObjectDereferencedError(sa_exc.SQLAlchemyError): """An operation cannot complete due to an object being garbage collected. """ class DetachedInstanceError(sa_exc.SQLAlchemyError): """An attempt to access unloaded attributes on a mapped instance that is detached.""" class UnmappedInstanceError(UnmappedError): """An mapping operation was requested for an unknown instance.""" @util.dependencies("sqlalchemy.orm.base") def __init__(self, base, obj, msg=None): if not msg: try: base.class_mapper(type(obj)) name = _safe_cls_name(type(obj)) msg = ("Class %r is mapped, but this instance lacks " "instrumentation. This occurs when the instance" "is created before sqlalchemy.orm.mapper(%s) " "was called." % (name, name)) except UnmappedClassError: msg = _default_unmapped(type(obj)) if isinstance(obj, type): msg += ( '; was a class (%s) supplied where an instance was ' 'required?' % _safe_cls_name(obj)) UnmappedError.__init__(self, msg) def __reduce__(self): return self.__class__, (None, self.args[0]) class UnmappedClassError(UnmappedError): """An mapping operation was requested for an unknown class.""" def __init__(self, cls, msg=None): if not msg: msg = _default_unmapped(cls) UnmappedError.__init__(self, msg) def __reduce__(self): return self.__class__, (None, self.args[0]) class ObjectDeletedError(sa_exc.InvalidRequestError): """A refresh operation failed to retrieve the database row corresponding to an object's known primary key identity. A refresh operation proceeds when an expired attribute is accessed on an object, or when :meth:`.Query.get` is used to retrieve an object which is, upon retrieval, detected as expired. A SELECT is emitted for the target row based on primary key; if no row is returned, this exception is raised. The true meaning of this exception is simply that no row exists for the primary key identifier associated with a persistent object. The row may have been deleted, or in some cases the primary key updated to a new value, outside of the ORM's management of the target object. """ @util.dependencies("sqlalchemy.orm.base") def __init__(self, base, state, msg=None): if not msg: msg = "Instance '%s' has been deleted, or its "\ "row is otherwise not present." % base.state_str(state) sa_exc.InvalidRequestError.__init__(self, msg) def __reduce__(self): return self.__class__, (None, self.args[0]) class UnmappedColumnError(sa_exc.InvalidRequestError): """Mapping operation was requested on an unknown column.""" class NoResultFound(sa_exc.InvalidRequestError): """A database result was required but none was found.""" class MultipleResultsFound(sa_exc.InvalidRequestError): """A single database result was required but more than one were found.""" def _safe_cls_name(cls): try: cls_name = '.'.join((cls.__module__, cls.__name__)) except AttributeError: cls_name = getattr(cls, '__name__', None) if cls_name is None: cls_name = repr(cls) return cls_name @util.dependencies("sqlalchemy.orm.base") def _default_unmapped(base, cls): try: mappers = base.manager_of_class(cls).mappers except NO_STATE: mappers = {} except TypeError: mappers = {} name = _safe_cls_name(cls) if not mappers: return "Class '%s' is not mapped" % name
pcu4dros/pandora-core
workspace/lib/python3.5/site-packages/sqlalchemy/orm/exc.py
Python
mit
5,439
package network // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // 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. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "net/http" ) // ExpressRouteCircuitPeeringsClient is the network Client type ExpressRouteCircuitPeeringsClient struct { ManagementClient } // NewExpressRouteCircuitPeeringsClient creates an instance of the ExpressRouteCircuitPeeringsClient client. func NewExpressRouteCircuitPeeringsClient(subscriptionID string) ExpressRouteCircuitPeeringsClient { return NewExpressRouteCircuitPeeringsClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewExpressRouteCircuitPeeringsClientWithBaseURI creates an instance of the ExpressRouteCircuitPeeringsClient client. func NewExpressRouteCircuitPeeringsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteCircuitPeeringsClient { return ExpressRouteCircuitPeeringsClient{NewWithBaseURI(baseURI, subscriptionID)} } // CreateOrUpdate creates or updates a peering in the specified express route circuits. This method may poll for // completion. Polling can be canceled by passing the cancel channel argument. The channel will be used to cancel // polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. circuitName is the name of the express route circuit. // peeringName is the name of the peering. peeringParameters is parameters supplied to the create or update express // route circuit peering operation. func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdate(resourceGroupName string, circuitName string, peeringName string, peeringParameters ExpressRouteCircuitPeering, cancel <-chan struct{}) (<-chan ExpressRouteCircuitPeering, <-chan error) { resultChan := make(chan ExpressRouteCircuitPeering, 1) errChan := make(chan error, 1) go func() { var err error var result ExpressRouteCircuitPeering defer func() { if err != nil { errChan <- err } resultChan <- result close(resultChan) close(errChan) }() req, err := client.CreateOrUpdatePreparer(resourceGroupName, circuitName, peeringName, peeringParameters, cancel) if err != nil { err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", nil, "Failure preparing request") return } resp, err := client.CreateOrUpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", resp, "Failure sending request") return } result, err = client.CreateOrUpdateResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", resp, "Failure responding to request") } }() return resultChan, errChan } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdatePreparer(resourceGroupName string, circuitName string, peeringName string, peeringParameters ExpressRouteCircuitPeering, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "circuitName": autorest.Encode("path", circuitName), "peeringName": autorest.Encode("path", peeringName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2017-09-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}", pathParameters), autorest.WithJSON(peeringParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare(&http.Request{Cancel: cancel}) } // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client), azure.DoPollForAsynchronous(client.PollingDelay)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteCircuitPeering, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Delete deletes the specified peering from the specified express route circuit. This method may poll for completion. // Polling can be canceled by passing the cancel channel argument. The channel will be used to cancel polling and any // outstanding HTTP requests. // // resourceGroupName is the name of the resource group. circuitName is the name of the express route circuit. // peeringName is the name of the peering. func (client ExpressRouteCircuitPeeringsClient) Delete(resourceGroupName string, circuitName string, peeringName string, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { resultChan := make(chan autorest.Response, 1) errChan := make(chan error, 1) go func() { var err error var result autorest.Response defer func() { if err != nil { errChan <- err } resultChan <- result close(resultChan) close(errChan) }() req, err := client.DeletePreparer(resourceGroupName, circuitName, peeringName, cancel) if err != nil { err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Delete", nil, "Failure preparing request") return } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Delete", resp, "Failure sending request") return } result, err = client.DeleteResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Delete", resp, "Failure responding to request") } }() return resultChan, errChan } // DeletePreparer prepares the Delete request. func (client ExpressRouteCircuitPeeringsClient) DeletePreparer(resourceGroupName string, circuitName string, peeringName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "circuitName": autorest.Encode("path", circuitName), "peeringName": autorest.Encode("path", peeringName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2017-09-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare(&http.Request{Cancel: cancel}) } // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client ExpressRouteCircuitPeeringsClient) DeleteSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client), azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteResponder handles the response to the Delete request. The method always // closes the http.Response Body. func (client ExpressRouteCircuitPeeringsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return } // Get gets the specified authorization from the specified express route circuit. // // resourceGroupName is the name of the resource group. circuitName is the name of the express route circuit. // peeringName is the name of the peering. func (client ExpressRouteCircuitPeeringsClient) Get(resourceGroupName string, circuitName string, peeringName string) (result ExpressRouteCircuitPeering, err error) { req, err := client.GetPreparer(resourceGroupName, circuitName, peeringName) if err != nil { err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Get", resp, "Failure responding to request") } return } // GetPreparer prepares the Get request. func (client ExpressRouteCircuitPeeringsClient) GetPreparer(resourceGroupName string, circuitName string, peeringName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "circuitName": autorest.Encode("path", circuitName), "peeringName": autorest.Encode("path", peeringName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2017-09-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings/{peeringName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare(&http.Request{}) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client ExpressRouteCircuitPeeringsClient) GetSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client ExpressRouteCircuitPeeringsClient) GetResponder(resp *http.Response) (result ExpressRouteCircuitPeering, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // List gets all peerings in a specified express route circuit. // // resourceGroupName is the name of the resource group. circuitName is the name of the express route circuit. func (client ExpressRouteCircuitPeeringsClient) List(resourceGroupName string, circuitName string) (result ExpressRouteCircuitPeeringListResult, err error) { req, err := client.ListPreparer(resourceGroupName, circuitName) if err != nil { err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", nil, "Failure preparing request") return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", resp, "Failure sending request") return } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", resp, "Failure responding to request") } return } // ListPreparer prepares the List request. func (client ExpressRouteCircuitPeeringsClient) ListPreparer(resourceGroupName string, circuitName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "circuitName": autorest.Encode("path", circuitName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2017-09-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerings", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare(&http.Request{}) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client ExpressRouteCircuitPeeringsClient) ListSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client ExpressRouteCircuitPeeringsClient) ListResponder(resp *http.Response) (result ExpressRouteCircuitPeeringListResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // ListNextResults retrieves the next set of results, if any. func (client ExpressRouteCircuitPeeringsClient) ListNextResults(lastResults ExpressRouteCircuitPeeringListResult) (result ExpressRouteCircuitPeeringListResult, err error) { req, err := lastResults.ExpressRouteCircuitPeeringListResultPreparer() if err != nil { return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", resp, "Failure sending next results request") } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", resp, "Failure responding to next results request") } return } // ListComplete gets all elements from the list without paging. func (client ExpressRouteCircuitPeeringsClient) ListComplete(resourceGroupName string, circuitName string, cancel <-chan struct{}) (<-chan ExpressRouteCircuitPeering, <-chan error) { resultChan := make(chan ExpressRouteCircuitPeering) errChan := make(chan error, 1) go func() { defer func() { close(resultChan) close(errChan) }() list, err := client.List(resourceGroupName, circuitName) if err != nil { errChan <- err return } if list.Value != nil { for _, item := range *list.Value { select { case <-cancel: return case resultChan <- item: // Intentionally left blank } } } for list.NextLink != nil { list, err = client.ListNextResults(list) if err != nil { errChan <- err return } if list.Value != nil { for _, item := range *list.Value { select { case <-cancel: return case resultChan <- item: // Intentionally left blank } } } } }() return resultChan, errChan }
kgrygiel/autoscaler
vertical-pod-autoscaler/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressroutecircuitpeerings.go
GO
apache-2.0
16,778
# # Author:: Mukta Aphale (<mukta.aphale@clogeny.com>) # Copyright:: Copyright (c) 2013 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. # require 'spec_helper' if Chef::Platform.windows? require 'chef/application/windows_service' end describe "Chef::Application::WindowsService", :windows_only do let (:instance) {Chef::Application::WindowsService.new} let (:shell_out_result) {Object.new} let (:tempfile) {Tempfile.new "log_file"} before do allow(instance).to receive(:parse_options) allow(shell_out_result).to receive(:stdout) allow(shell_out_result).to receive(:stderr) end it "runs chef-client in new process" do expect(instance).to receive(:configure_chef).twice instance.service_init expect(instance).to receive(:run_chef_client).and_call_original expect(instance).to receive(:shell_out).and_return(shell_out_result) allow(instance).to receive(:running?).and_return(true, false) allow(instance.instance_variable_get(:@service_signal)).to receive(:wait) allow(instance).to receive(:state).and_return(4) instance.service_main end context 'when running chef-client' do it "passes config params to new process with a default timeout of 2 hours (7200 seconds)" do Chef::Config.merge!({:log_location => tempfile.path, :config_file => "test_config_file", :log_level => :info}) expect(instance).to receive(:configure_chef).twice instance.service_init allow(instance).to receive(:running?).and_return(true, false) allow(instance.instance_variable_get(:@service_signal)).to receive(:wait) allow(instance).to receive(:state).and_return(4) expect(instance).to receive(:run_chef_client).and_call_original expect(instance).to receive(:shell_out).with("chef-client --no-fork -c test_config_file -L #{tempfile.path}", {:timeout => 7200}).and_return(shell_out_result) instance.service_main tempfile.unlink end it "passes config params to new process with a the timeout specified in the config" do Chef::Config.merge!({:log_location => tempfile.path, :config_file => "test_config_file", :log_level => :info}) Chef::Config[:windows_service][:watchdog_timeout] = 10 expect(instance).to receive(:configure_chef).twice instance.service_init allow(instance).to receive(:running?).and_return(true, false) allow(instance.instance_variable_get(:@service_signal)).to receive(:wait) allow(instance).to receive(:state).and_return(4) expect(instance).to receive(:run_chef_client).and_call_original expect(instance).to receive(:shell_out).with("chef-client --no-fork -c test_config_file -L #{tempfile.path}", {:timeout => 10}).and_return(shell_out_result) instance.service_main tempfile.unlink end end end
cgvarela/chef
spec/unit/windows_service_spec.rb
Ruby
apache-2.0
3,344
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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. */ package com.intellij.util.xml; /** * Specifies how method names are converted into XML element names * * @author peter * @see NameStrategy * @see NameStrategyForAttributes */ public abstract class DomNameStrategy { /** * @param propertyName property name, i.e. method name without first 'get', 'set' or 'is' * @return XML element name */ public abstract String convertName(String propertyName); /** * Is used to get presentable DOM elements in UI * @param xmlElementName XML element name * @return Presentable DOM element name */ public abstract String splitIntoWords(final String xmlElementName); /** * This strategy splits property name into words, decapitalizes them and joins using hyphen as separator, * e.g. getXmlElementName() will correspond to xml-element-name */ public static final DomNameStrategy HYPHEN_STRATEGY = new HyphenNameStrategy(); /** * This strategy decapitalizes property name, e.g. getXmlElementName() will correspond to xmlElementName */ public static final DomNameStrategy JAVA_STRATEGY = new JavaNameStrategy(); }
asedunov/intellij-community
xml/dom-openapi/src/com/intellij/util/xml/DomNameStrategy.java
Java
apache-2.0
1,707
--TEST-- phpunit --configuration tests/_files/phpunit-example-extension --FILE-- <?php $_SERVER['argv'][1] = '--configuration'; $_SERVER['argv'][2] = __DIR__ . '/../_files/phpunit-example-extension'; require __DIR__ . '/../bootstrap.php'; PHPUnit\TextUI\Command::main(); --EXPECTF-- PHPUnit %s by Sebastian Bergmann and contributors. Runtime: %s Configuration: %s%ephpunit-example-extension%ephpunit.xml Extension: phpunit/phpunit-example-extension 1.0.1 . 1 / 1 (100%) Time: %s, Memory: %s OK (1 test, 1 assertion)
nusendra/nusendra-blog
vendor/phpunit/phpunit/tests/end-to-end/phar-extension.phpt
PHP
mit
597
package storage import ( "fmt" "path" "strings" "github.com/docker/distribution/digest" ) const storagePathVersion = "v2" // pathMapper maps paths based on "object names" and their ids. The "object // names" mapped by pathMapper are internal to the storage system. // // The path layout in the storage backend is roughly as follows: // // <root>/v2 // -> repositories/ // -><name>/ // -> _manifests/ // revisions // -> <manifest digest path> // -> link // -> signatures // <algorithm>/<digest>/link // tags/<tag> // -> current/link // -> index // -> <algorithm>/<hex digest>/link // -> _layers/ // <layer links to blob store> // -> _uploads/<id> // data // startedat // hashstates/<algorithm>/<offset> // -> blob/<algorithm> // <split directory content addressable storage> // // The storage backend layout is broken up into a content- addressable blob // store and repositories. The content-addressable blob store holds most data // throughout the backend, keyed by algorithm and digests of the underlying // content. Access to the blob store is controled through links from the // repository to blobstore. // // A repository is made up of layers, manifests and tags. The layers component // is just a directory of layers which are "linked" into a repository. A layer // can only be accessed through a qualified repository name if it is linked in // the repository. Uploads of layers are managed in the uploads directory, // which is key by upload id. When all data for an upload is received, the // data is moved into the blob store and the upload directory is deleted. // Abandoned uploads can be garbage collected by reading the startedat file // and removing uploads that have been active for longer than a certain time. // // The third component of the repository directory is the manifests store, // which is made up of a revision store and tag store. Manifests are stored in // the blob store and linked into the revision store. Signatures are separated // from the manifest payload data and linked into the blob store, as well. // While the registry can save all revisions of a manifest, no relationship is // implied as to the ordering of changes to a manifest. The tag store provides // support for name, tag lookups of manifests, using "current/link" under a // named tag directory. An index is maintained to support deletions of all // revisions of a given manifest tag. // // We cover the path formats implemented by this path mapper below. // // Manifests: // // manifestRevisionPathSpec: <root>/v2/repositories/<name>/_manifests/revisions/<algorithm>/<hex digest>/ // manifestRevisionLinkPathSpec: <root>/v2/repositories/<name>/_manifests/revisions/<algorithm>/<hex digest>/link // manifestSignaturesPathSpec: <root>/v2/repositories/<name>/_manifests/revisions/<algorithm>/<hex digest>/signatures/ // manifestSignatureLinkPathSpec: <root>/v2/repositories/<name>/_manifests/revisions/<algorithm>/<hex digest>/signatures/<algorithm>/<hex digest>/link // // Tags: // // manifestTagsPathSpec: <root>/v2/repositories/<name>/_manifests/tags/ // manifestTagPathSpec: <root>/v2/repositories/<name>/_manifests/tags/<tag>/ // manifestTagCurrentPathSpec: <root>/v2/repositories/<name>/_manifests/tags/<tag>/current/link // manifestTagIndexPathSpec: <root>/v2/repositories/<name>/_manifests/tags/<tag>/index/ // manifestTagIndexEntryPathSpec: <root>/v2/repositories/<name>/_manifests/tags/<tag>/index/<algorithm>/<hex digest>/ // manifestTagIndexEntryLinkPathSpec: <root>/v2/repositories/<name>/_manifests/tags/<tag>/index/<algorithm>/<hex digest>/link // // Blobs: // // layerLinkPathSpec: <root>/v2/repositories/<name>/_layers/<algorithm>/<hex digest>/link // // Uploads: // // uploadDataPathSpec: <root>/v2/repositories/<name>/_uploads/<id>/data // uploadStartedAtPathSpec: <root>/v2/repositories/<name>/_uploads/<id>/startedat // uploadHashStatePathSpec: <root>/v2/repositories/<name>/_uploads/<id>/hashstates/<algorithm>/<offset> // // Blob Store: // // blobPathSpec: <root>/v2/blobs/<algorithm>/<first two hex bytes of digest>/<hex digest> // blobDataPathSpec: <root>/v2/blobs/<algorithm>/<first two hex bytes of digest>/<hex digest>/data // blobMediaTypePathSpec: <root>/v2/blobs/<algorithm>/<first two hex bytes of digest>/<hex digest>/data // // For more information on the semantic meaning of each path and their // contents, please see the path spec documentation. type pathMapper struct { root string version string // should be a constant? } var defaultPathMapper = &pathMapper{ root: "/docker/registry/", version: storagePathVersion, } // path returns the path identified by spec. func (pm *pathMapper) path(spec pathSpec) (string, error) { // Switch on the path object type and return the appropriate path. At // first glance, one may wonder why we don't use an interface to // accomplish this. By keep the formatting separate from the pathSpec, we // keep separate the path generation componentized. These specs could be // passed to a completely different mapper implementation and generate a // different set of paths. // // For example, imagine migrating from one backend to the other: one could // build a filesystem walker that converts a string path in one version, // to an intermediate path object, than can be consumed and mapped by the // other version. rootPrefix := []string{pm.root, pm.version} repoPrefix := append(rootPrefix, "repositories") switch v := spec.(type) { case manifestRevisionPathSpec: components, err := digestPathComponents(v.revision, false) if err != nil { return "", err } return path.Join(append(append(repoPrefix, v.name, "_manifests", "revisions"), components...)...), nil case manifestRevisionLinkPathSpec: root, err := pm.path(manifestRevisionPathSpec{ name: v.name, revision: v.revision, }) if err != nil { return "", err } return path.Join(root, "link"), nil case manifestSignaturesPathSpec: root, err := pm.path(manifestRevisionPathSpec{ name: v.name, revision: v.revision, }) if err != nil { return "", err } return path.Join(root, "signatures"), nil case manifestSignatureLinkPathSpec: root, err := pm.path(manifestSignaturesPathSpec{ name: v.name, revision: v.revision, }) if err != nil { return "", err } signatureComponents, err := digestPathComponents(v.signature, false) if err != nil { return "", err } return path.Join(root, path.Join(append(signatureComponents, "link")...)), nil case manifestTagsPathSpec: return path.Join(append(repoPrefix, v.name, "_manifests", "tags")...), nil case manifestTagPathSpec: root, err := pm.path(manifestTagsPathSpec{ name: v.name, }) if err != nil { return "", err } return path.Join(root, v.tag), nil case manifestTagCurrentPathSpec: root, err := pm.path(manifestTagPathSpec{ name: v.name, tag: v.tag, }) if err != nil { return "", err } return path.Join(root, "current", "link"), nil case manifestTagIndexPathSpec: root, err := pm.path(manifestTagPathSpec{ name: v.name, tag: v.tag, }) if err != nil { return "", err } return path.Join(root, "index"), nil case manifestTagIndexEntryLinkPathSpec: root, err := pm.path(manifestTagIndexEntryPathSpec{ name: v.name, tag: v.tag, revision: v.revision, }) if err != nil { return "", err } return path.Join(root, "link"), nil case manifestTagIndexEntryPathSpec: root, err := pm.path(manifestTagIndexPathSpec{ name: v.name, tag: v.tag, }) if err != nil { return "", err } components, err := digestPathComponents(v.revision, false) if err != nil { return "", err } return path.Join(root, path.Join(components...)), nil case layerLinkPathSpec: components, err := digestPathComponents(v.digest, false) if err != nil { return "", err } // TODO(stevvooe): Right now, all blobs are linked under "_layers". If // we have future migrations, we may want to rename this to "_blobs". // A migration strategy would simply leave existing items in place and // write the new paths, commit a file then delete the old files. blobLinkPathComponents := append(repoPrefix, v.name, "_layers") return path.Join(path.Join(append(blobLinkPathComponents, components...)...), "link"), nil case blobDataPathSpec: components, err := digestPathComponents(v.digest, true) if err != nil { return "", err } components = append(components, "data") blobPathPrefix := append(rootPrefix, "blobs") return path.Join(append(blobPathPrefix, components...)...), nil case uploadDataPathSpec: return path.Join(append(repoPrefix, v.name, "_uploads", v.id, "data")...), nil case uploadStartedAtPathSpec: return path.Join(append(repoPrefix, v.name, "_uploads", v.id, "startedat")...), nil case uploadHashStatePathSpec: offset := fmt.Sprintf("%d", v.offset) if v.list { offset = "" // Limit to the prefix for listing offsets. } return path.Join(append(repoPrefix, v.name, "_uploads", v.id, "hashstates", string(v.alg), offset)...), nil case repositoriesRootPathSpec: return path.Join(repoPrefix...), nil default: // TODO(sday): This is an internal error. Ensure it doesn't escape (panic?). return "", fmt.Errorf("unknown path spec: %#v", v) } } // pathSpec is a type to mark structs as path specs. There is no // implementation because we'd like to keep the specs and the mappers // decoupled. type pathSpec interface { pathSpec() } // manifestRevisionPathSpec describes the components of the directory path for // a manifest revision. type manifestRevisionPathSpec struct { name string revision digest.Digest } func (manifestRevisionPathSpec) pathSpec() {} // manifestRevisionLinkPathSpec describes the path components required to look // up the data link for a revision of a manifest. If this file is not present, // the manifest blob is not available in the given repo. The contents of this // file should just be the digest. type manifestRevisionLinkPathSpec struct { name string revision digest.Digest } func (manifestRevisionLinkPathSpec) pathSpec() {} // manifestSignaturesPathSpec decribes the path components for the directory // containing all the signatures for the target blob. Entries are named with // the underlying key id. type manifestSignaturesPathSpec struct { name string revision digest.Digest } func (manifestSignaturesPathSpec) pathSpec() {} // manifestSignatureLinkPathSpec decribes the path components used to look up // a signature file by the hash of its blob. type manifestSignatureLinkPathSpec struct { name string revision digest.Digest signature digest.Digest } func (manifestSignatureLinkPathSpec) pathSpec() {} // manifestTagsPathSpec describes the path elements required to point to the // manifest tags directory. type manifestTagsPathSpec struct { name string } func (manifestTagsPathSpec) pathSpec() {} // manifestTagPathSpec describes the path elements required to point to the // manifest tag links files under a repository. These contain a blob id that // can be used to look up the data and signatures. type manifestTagPathSpec struct { name string tag string } func (manifestTagPathSpec) pathSpec() {} // manifestTagCurrentPathSpec describes the link to the current revision for a // given tag. type manifestTagCurrentPathSpec struct { name string tag string } func (manifestTagCurrentPathSpec) pathSpec() {} // manifestTagCurrentPathSpec describes the link to the index of revisions // with the given tag. type manifestTagIndexPathSpec struct { name string tag string } func (manifestTagIndexPathSpec) pathSpec() {} // manifestTagIndexEntryPathSpec contains the entries of the index by revision. type manifestTagIndexEntryPathSpec struct { name string tag string revision digest.Digest } func (manifestTagIndexEntryPathSpec) pathSpec() {} // manifestTagIndexEntryLinkPathSpec describes the link to a revisions of a // manifest with given tag within the index. type manifestTagIndexEntryLinkPathSpec struct { name string tag string revision digest.Digest } func (manifestTagIndexEntryLinkPathSpec) pathSpec() {} // blobLinkPathSpec specifies a path for a blob link, which is a file with a // blob id. The blob link will contain a content addressable blob id reference // into the blob store. The format of the contents is as follows: // // <algorithm>:<hex digest of layer data> // // The following example of the file contents is more illustrative: // // sha256:96443a84ce518ac22acb2e985eda402b58ac19ce6f91980bde63726a79d80b36 // // This indicates that there is a blob with the id/digest, calculated via // sha256 that can be fetched from the blob store. type layerLinkPathSpec struct { name string digest digest.Digest } func (layerLinkPathSpec) pathSpec() {} // blobAlgorithmReplacer does some very simple path sanitization for user // input. Mostly, this is to provide some hierarchy for tarsum digests. Paths // should be "safe" before getting this far due to strict digest requirements // but we can add further path conversion here, if needed. var blobAlgorithmReplacer = strings.NewReplacer( "+", "/", ".", "/", ";", "/", ) // // blobPathSpec contains the path for the registry global blob store. // type blobPathSpec struct { // digest digest.Digest // } // func (blobPathSpec) pathSpec() {} // blobDataPathSpec contains the path for the registry global blob store. For // now, this contains layer data, exclusively. type blobDataPathSpec struct { digest digest.Digest } func (blobDataPathSpec) pathSpec() {} // uploadDataPathSpec defines the path parameters of the data file for // uploads. type uploadDataPathSpec struct { name string id string } func (uploadDataPathSpec) pathSpec() {} // uploadDataPathSpec defines the path parameters for the file that stores the // start time of an uploads. If it is missing, the upload is considered // unknown. Admittedly, the presence of this file is an ugly hack to make sure // we have a way to cleanup old or stalled uploads that doesn't rely on driver // FileInfo behavior. If we come up with a more clever way to do this, we // should remove this file immediately and rely on the startetAt field from // the client to enforce time out policies. type uploadStartedAtPathSpec struct { name string id string } func (uploadStartedAtPathSpec) pathSpec() {} // uploadHashStatePathSpec defines the path parameters for the file that stores // the hash function state of an upload at a specific byte offset. If `list` is // set, then the path mapper will generate a list prefix for all hash state // offsets for the upload identified by the name, id, and alg. type uploadHashStatePathSpec struct { name string id string alg digest.Algorithm offset int64 list bool } func (uploadHashStatePathSpec) pathSpec() {} // repositoriesRootPathSpec returns the root of repositories type repositoriesRootPathSpec struct { } func (repositoriesRootPathSpec) pathSpec() {} // digestPathComponents provides a consistent path breakdown for a given // digest. For a generic digest, it will be as follows: // // <algorithm>/<hex digest> // // Most importantly, for tarsum, the layout looks like this: // // tarsum/<version>/<digest algorithm>/<full digest> // // If multilevel is true, the first two bytes of the digest will separate // groups of digest folder. It will be as follows: // // <algorithm>/<first two bytes of digest>/<full digest> // func digestPathComponents(dgst digest.Digest, multilevel bool) ([]string, error) { if err := dgst.Validate(); err != nil { return nil, err } algorithm := blobAlgorithmReplacer.Replace(string(dgst.Algorithm())) hex := dgst.Hex() prefix := []string{algorithm} var suffix []string if multilevel { suffix = append(suffix, hex[:2]) } suffix = append(suffix, hex) if tsi, err := digest.ParseTarSum(dgst.String()); err == nil { // We have a tarsum! version := tsi.Version if version == "" { version = "v0" } prefix = []string{ "tarsum", version, tsi.Algorithm, } } return append(prefix, suffix...), nil }
philiplb/flynn
vendor/github.com/docker/distribution/registry/storage/paths.go
GO
bsd-3-clause
16,435
import {Credentials} from '../credentials'; import {AWSError} from '../error'; import STS = require('../../clients/sts'); export class TemporaryCredentials extends Credentials { /** * Creates a new temporary credentials object. * @param {Object} options - a map of options that are passed to the AWS.STS.assumeRole() or AWS.STS.getSessionToken() operations. If a RoleArn parameter is passed in, credentials will be based on the IAM role. * @param {Object} masterCredentials - The master (non-temporary) credentials used to get and refresh credentials from AWS STS. */ constructor(options: TemporaryCredentials.TemporaryCredentialsOptions, masterCredentials?: Credentials); /** * Creates a new temporary credentials object. * @param {Object} options - a map of options that are passed to the AWS.STS.assumeRole() or AWS.STS.getSessionToken() operations. If a RoleArn parameter is passed in, credentials will be based on the IAM role. */ constructor(options?: TemporaryCredentials.TemporaryCredentialsOptions); /** * Refreshes credentials using AWS.STS.assumeRole() or AWS.STS.getSessionToken(), depending on whether an IAM role ARN was passed to the credentials constructor(). */ refresh(callback: (err: AWSError) => void): void; /** * The master (non-temporary) credentials used to get and refresh temporary credentials from AWS STS. */ masterCredentials: Credentials } // Needed to expose interfaces on the class declare namespace TemporaryCredentials { export type TemporaryCredentialsOptions = STS.Types.AssumeRoleRequest|STS.Types.GetSessionTokenRequest; }
ChaseGHMU/AlexaSymptomChecker
src/node_modules/aws-sdk/lib/credentials/temporary_credentials.d.ts
TypeScript
mit
1,654
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_View * @subpackage Helper * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @version $Id$ * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * Helper for alternating between set of values * * @package Zend_View * @subpackage Helper * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_View_Helper_Cycle implements Iterator { /** * Default name * @var string */ const DEFAULT_NAME = 'default'; /** * Pointers * * @var array */ protected $_pointers = array(self::DEFAULT_NAME =>-1) ; /** * Array of values * * @var array */ protected $_data = array(self::DEFAULT_NAME=>array()); /** * Actual name of cycle * * @var string */ protected $_name = self::DEFAULT_NAME; /** * Add elements to alternate * * @param array $data * @param string $name * @return Zend_View_Helper_Cycle */ public function cycle(array $data = array(), $name = self::DEFAULT_NAME) { if(!empty($data)) $this->_data[$name] = $data; $this->setName($name); return $this; } /** * Add elements to alternate * * @param array $data * @param string $name * @return Zend_View_Helper_Cycle */ public function assign(Array $data , $name = self::DEFAULT_NAME) { $this->setName($name); $this->_data[$name] = $data; $this->rewind(); return $this; } /** * Sets actual name of cycle * * @param string $name * @return Zend_View_Helper_Cycle */ public function setName($name = self::DEFAULT_NAME) { $this->_name = $name; if(!isset($this->_data[$this->_name])) $this->_data[$this->_name] = array(); if(!isset($this->_pointers[$this->_name])) $this->rewind(); return $this; } /** * Gets actual name of cycle * * @return string */ public function getName() { return $this->_name; } /** * Return all elements * * @return array */ public function getAll() { return $this->_data[$this->_name]; } /** * Turn helper into string * * @return string */ public function toString() { return (string) $this->_data[$this->_name][$this->key()]; } /** * Cast to string * * @return string */ public function __toString() { return $this->toString(); } /** * Move to next value * * @return Zend_View_Helper_Cycle */ public function next() { $count = count($this->_data[$this->_name]); if ($this->_pointers[$this->_name] == ($count - 1)) $this->_pointers[$this->_name] = 0; else $this->_pointers[$this->_name] = ++$this->_pointers[$this->_name]; return $this; } /** * Move to previous value * * @return Zend_View_Helper_Cycle */ public function prev() { $count = count($this->_data[$this->_name]); if ($this->_pointers[$this->_name] <= 0) $this->_pointers[$this->_name] = $count - 1; else $this->_pointers[$this->_name] = --$this->_pointers[$this->_name]; return $this; } /** * Return iteration number * * @return int */ public function key() { if ($this->_pointers[$this->_name] < 0) return 0; else return $this->_pointers[$this->_name]; } /** * Rewind pointer * * @return Zend_View_Helper_Cycle */ public function rewind() { $this->_pointers[$this->_name] = -1; return $this; } /** * Check if element is valid * * @return bool */ public function valid() { return isset($this->_data[$this->_name][$this->key()]); } /** * Return current element * * @return mixed */ public function current() { return $this->_data[$this->_name][$this->key()]; } }
T0MM0R/magento
web/lib/Zend/View/Helper/Cycle.php
PHP
gpl-2.0
4,843
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Security\Guard\Firewall; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\GetResponseEvent; use Symfony\Component\Security\Guard\GuardAuthenticatorHandler; use Symfony\Component\Security\Guard\Token\PreAuthenticationGuardToken; use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface; use Symfony\Component\Security\Guard\GuardAuthenticatorInterface; use Psr\Log\LoggerInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Http\Firewall\ListenerInterface; use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface; /** * Authentication listener for the "guard" system. * * @author Ryan Weaver <ryan@knpuniversity.com> */ class GuardAuthenticationListener implements ListenerInterface { private $guardHandler; private $authenticationManager; private $providerKey; private $guardAuthenticators; private $logger; private $rememberMeServices; /** * @param GuardAuthenticatorHandler $guardHandler The Guard handler * @param AuthenticationManagerInterface $authenticationManager An AuthenticationManagerInterface instance * @param string $providerKey The provider (i.e. firewall) key * @param iterable|GuardAuthenticatorInterface[] $guardAuthenticators The authenticators, with keys that match what's passed to GuardAuthenticationProvider * @param LoggerInterface $logger A LoggerInterface instance */ public function __construct(GuardAuthenticatorHandler $guardHandler, AuthenticationManagerInterface $authenticationManager, $providerKey, $guardAuthenticators, LoggerInterface $logger = null) { if (empty($providerKey)) { throw new \InvalidArgumentException('$providerKey must not be empty.'); } $this->guardHandler = $guardHandler; $this->authenticationManager = $authenticationManager; $this->providerKey = $providerKey; $this->guardAuthenticators = $guardAuthenticators; $this->logger = $logger; } /** * Iterates over each authenticator to see if each wants to authenticate the request. * * @param GetResponseEvent $event */ public function handle(GetResponseEvent $event) { if (null !== $this->logger) { $context = array('firewall_key' => $this->providerKey); if ($this->guardAuthenticators instanceof \Countable || is_array($this->guardAuthenticators)) { $context['authenticators'] = count($this->guardAuthenticators); } $this->logger->debug('Checking for guard authentication credentials.', $context); } foreach ($this->guardAuthenticators as $key => $guardAuthenticator) { // get a key that's unique to *this* guard authenticator // this MUST be the same as GuardAuthenticationProvider $uniqueGuardKey = $this->providerKey.'_'.$key; $this->executeGuardAuthenticator($uniqueGuardKey, $guardAuthenticator, $event); if ($event->hasResponse()) { if (null !== $this->logger) { $this->logger->debug('The "{authenticator}" authenticator set the response. Any later authenticator will not be called', array('authenticator' => get_class($guardAuthenticator))); } break; } } } private function executeGuardAuthenticator($uniqueGuardKey, GuardAuthenticatorInterface $guardAuthenticator, GetResponseEvent $event) { $request = $event->getRequest(); try { if (null !== $this->logger) { $this->logger->debug('Calling getCredentials() on guard configurator.', array('firewall_key' => $this->providerKey, 'authenticator' => get_class($guardAuthenticator))); } // allow the authenticator to fetch authentication info from the request $credentials = $guardAuthenticator->getCredentials($request); // allow null to be returned to skip authentication if (null === $credentials) { return; } // create a token with the unique key, so that the provider knows which authenticator to use $token = new PreAuthenticationGuardToken($credentials, $uniqueGuardKey); if (null !== $this->logger) { $this->logger->debug('Passing guard token information to the GuardAuthenticationProvider', array('firewall_key' => $this->providerKey, 'authenticator' => get_class($guardAuthenticator))); } // pass the token into the AuthenticationManager system // this indirectly calls GuardAuthenticationProvider::authenticate() $token = $this->authenticationManager->authenticate($token); if (null !== $this->logger) { $this->logger->info('Guard authentication successful!', array('token' => $token, 'authenticator' => get_class($guardAuthenticator))); } // sets the token on the token storage, etc $this->guardHandler->authenticateWithToken($token, $request); } catch (AuthenticationException $e) { // oh no! Authentication failed! if (null !== $this->logger) { $this->logger->info('Guard authentication failed.', array('exception' => $e, 'authenticator' => get_class($guardAuthenticator))); } $response = $this->guardHandler->handleAuthenticationFailure($e, $request, $guardAuthenticator, $this->providerKey); if ($response instanceof Response) { $event->setResponse($response); } return; } // success! $response = $this->guardHandler->handleAuthenticationSuccess($token, $request, $guardAuthenticator, $this->providerKey); if ($response instanceof Response) { if (null !== $this->logger) { $this->logger->debug('Guard authenticator set success response.', array('response' => $response, 'authenticator' => get_class($guardAuthenticator))); } $event->setResponse($response); } else { if (null !== $this->logger) { $this->logger->debug('Guard authenticator set no success response: request continues.', array('authenticator' => get_class($guardAuthenticator))); } } // attempt to trigger the remember me functionality $this->triggerRememberMe($guardAuthenticator, $request, $token, $response); } /** * Should be called if this listener will support remember me. * * @param RememberMeServicesInterface $rememberMeServices */ public function setRememberMeServices(RememberMeServicesInterface $rememberMeServices) { $this->rememberMeServices = $rememberMeServices; } /** * Checks to see if remember me is supported in the authenticator and * on the firewall. If it is, the RememberMeServicesInterface is notified. * * @param GuardAuthenticatorInterface $guardAuthenticator * @param Request $request * @param TokenInterface $token * @param Response $response */ private function triggerRememberMe(GuardAuthenticatorInterface $guardAuthenticator, Request $request, TokenInterface $token, Response $response = null) { if (null === $this->rememberMeServices) { if (null !== $this->logger) { $this->logger->debug('Remember me skipped: it is not configured for the firewall.', array('authenticator' => get_class($guardAuthenticator))); } return; } if (!$guardAuthenticator->supportsRememberMe()) { if (null !== $this->logger) { $this->logger->debug('Remember me skipped: your authenticator does not support it.', array('authenticator' => get_class($guardAuthenticator))); } return; } if (!$response instanceof Response) { throw new \LogicException(sprintf( '%s::onAuthenticationSuccess *must* return a Response if you want to use the remember me functionality. Return a Response, or set remember_me to false under the guard configuration.', get_class($guardAuthenticator) )); } $this->rememberMeServices->loginSuccess($request, $response, $token); } }
toncatalansuazo/SymfonyDashboard
vendor/symfony/symfony/src/Symfony/Component/Security/Guard/Firewall/GuardAuthenticationListener.php
PHP
mit
9,036
/** * @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ /** * Unobtrusive Form Validation library * * Inspired by: Chris Campbell <www.particletree.com> * * @package Joomla.Framework * @subpackage Forms * @since 1.5 */ var JFormValidator = function($) { var handlers, custom, inputEmail; var setHandler = function(name, fn, en) { en = (en === '') ? true : en; handlers[name] = { enabled : en, exec : fn }; }; var handleResponse = function(state, $el) { // Find the label object for the given field if it exists if (!$el.get(0).labelref) { $('label').each(function() { var $label = $(this); if ($label.attr('for') === $el.attr('id')) { $el.get(0).labelref = this; } }); } var labelref = $el.get(0).labelref; // Set the element and its label (if exists) invalid state if (state === false) { $el.addClass('invalid').attr('aria-invalid', 'true'); if (labelref) { $(labelref).addClass('invalid').attr('aria-invalid', 'true'); } } else { $el.removeClass('invalid').attr('aria-invalid', 'false'); if (labelref) { $(labelref).removeClass('invalid').attr('aria-invalid', 'false'); } } }; var validate = function(el) { var $el = $(el); // Ignore the element if its currently disabled, because are not submitted for the http-request. For those case return always true. if ($el.attr('disabled')) { handleResponse(true, $el); return true; } // If the field is required make sure it has a value if ($el.hasClass('required')) { var tagName = $el.prop("tagName").toLowerCase(), i = 0, selector; if (tagName === 'fieldset' && ($el.hasClass('radio') || $el.hasClass('checkboxes'))) { while (true) { selector = "#" + $el.attr('id') + i; if ($(selector).get(0)) { if ($(selector).is(':checked')) { break; } } else { handleResponse(false, $el); return false; } i++; } //If element has class placeholder that means it is empty. } else if (!$el.val() || $el.hasClass('placeholder') || ($el.attr('type') === 'checkbox' && !$el.is(':checked'))) { handleResponse(false, $el); return false; } } // Only validate the field if the validate class is set var handler = ($el.attr('class') && $el.attr('class').match(/validate-([a-zA-Z0-9\_\-]+)/)) ? $el.attr('class').match(/validate-([a-zA-Z0-9\_\-]+)/)[1] : ""; if (handler === '') { handleResponse(true, $el); return true; } // Check the additional validation types if ((handler) && (handler !== 'none') && (handlers[handler]) && $el.val()) { // Execute the validation handler and return result if (handlers[handler].exec($el.val()) !== true) { handleResponse(false, $el); return false; } } // Return validation state handleResponse(true, $el); return true; }; var isValid = function(form) { var valid = true, $form = $(form), i; // Validate form fields $form.find('input, textarea, select, button, fieldset').each(function(index, el){ if (validate(el) === false) { valid = false; } }); // Run custom form validators if present new Hash(custom).each(function(validator) { if (validator.exec() !== true) { valid = false; } }); if (!valid) { var message, errors, error; message = Joomla.JText._('JLIB_FORM_FIELD_INVALID'); errors = $("label.invalid"); error = {}; error.error = []; for ( i = 0; i < errors.length; i++) { var label = $(errors[i]).text(); if (label !== 'undefined') { error.error[i] = message + label.replace("*", ""); } } Joomla.renderMessages(error); } return valid; }; var attachToForm = function(form) { // Iterate through the form object and attach the validate method to all input fields. $(form).find('input,textarea,select,button').each(function() { var $el = $(this), tagName = $el.prop("tagName").toLowerCase(); if ($el.attr('required') === 'required') { $el.attr('aria-required', 'true'); } if ((tagName === 'input' && $el.attr('type') === 'submit') || (tagName === 'button' && $el.attr('type') === undefined)) { if ($el.hasClass('validate')) { $el.on('click', function() { return isValid(form); }); } } else { $el.on('blur', function() { return validate(this); }); if ($el.hasClass('validate-email') && inputEmail) { $el.get(0).type = 'email'; } } }); }; var initialize = function() { handlers = {}; custom = {}; inputEmail = (function() { var input = document.createElement("input"); input.setAttribute("type", "email"); return input.type !== "text"; })(); // Default handlers setHandler('username', function(value) { regex = new RegExp("[\<|\>|\"|\'|\%|\;|\(|\)|\&]", "i"); return !regex.test(value); }); setHandler('password', function(value) { regex = /^\S[\S ]{2,98}\S$/; return regex.test(value); }); setHandler('numeric', function(value) { regex = /^(\d|-)?(\d|,)*\.?\d*$/; return regex.test(value); }); setHandler('email', function(value) { regex = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/; return regex.test(value); }); // Attach to forms with class 'form-validate' $('form.form-validate').each(function() { attachToForm(this); }); }; return { initialize : initialize, isValid : isValid, validate : validate }; }; document.formvalidator = null; window.addEvent('domready', function() { document.formvalidator = new JFormValidator(jQuery.noConflict()); document.formvalidator.initialize(); });
google-code/asianspecialroad
plugins/media/system/js/validate-jquery-uncompressed.js
JavaScript
gpl-2.0
5,696
/* * Copyright (C) Research In Motion Limited 2010. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #if ENABLE(SVG) #include "SVGTextChunkBuilder.h" #include "RenderSVGInlineText.h" #include "SVGElement.h" #include "SVGInlineTextBox.h" namespace WebCore { SVGTextChunkBuilder::SVGTextChunkBuilder() { } void SVGTextChunkBuilder::transformationForTextBox(SVGInlineTextBox* textBox, AffineTransform& transform) const { DEFINE_STATIC_LOCAL(const AffineTransform, s_identityTransform, ()); if (!m_textBoxTransformations.contains(textBox)) { transform = s_identityTransform; return; } transform = m_textBoxTransformations.get(textBox); } void SVGTextChunkBuilder::buildTextChunks(Vector<SVGInlineTextBox*>& lineLayoutBoxes) { if (lineLayoutBoxes.isEmpty()) return; bool foundStart = false; unsigned lastChunkStartPosition = 0; unsigned boxPosition = 0; unsigned boxCount = lineLayoutBoxes.size(); for (; boxPosition < boxCount; ++boxPosition) { SVGInlineTextBox* textBox = lineLayoutBoxes[boxPosition]; if (!textBox->startsNewTextChunk()) continue; if (!foundStart) { lastChunkStartPosition = boxPosition; foundStart = true; } else { ASSERT(boxPosition > lastChunkStartPosition); addTextChunk(lineLayoutBoxes, lastChunkStartPosition, boxPosition - lastChunkStartPosition); lastChunkStartPosition = boxPosition; } } if (!foundStart) return; if (boxPosition - lastChunkStartPosition > 0) addTextChunk(lineLayoutBoxes, lastChunkStartPosition, boxPosition - lastChunkStartPosition); } void SVGTextChunkBuilder::layoutTextChunks(Vector<SVGInlineTextBox*>& lineLayoutBoxes) { buildTextChunks(lineLayoutBoxes); if (m_textChunks.isEmpty()) return; unsigned chunkCount = m_textChunks.size(); for (unsigned i = 0; i < chunkCount; ++i) processTextChunk(m_textChunks[i]); m_textChunks.clear(); } void SVGTextChunkBuilder::addTextChunk(Vector<SVGInlineTextBox*>& lineLayoutBoxes, unsigned boxStart, unsigned boxCount) { SVGInlineTextBox* textBox = lineLayoutBoxes[boxStart]; ASSERT(textBox); RenderSVGInlineText* textRenderer = toRenderSVGInlineText(textBox->textRenderer()); ASSERT(textRenderer); const RenderStyle* style = textRenderer->style(); ASSERT(style); const SVGRenderStyle* svgStyle = style->svgStyle(); ASSERT(svgStyle); // Build chunk style flags. unsigned chunkStyle = SVGTextChunk::DefaultStyle; // Handle 'direction' property. if (!style->isLeftToRightDirection()) chunkStyle |= SVGTextChunk::RightToLeftText; // Handle 'writing-mode' property. if (svgStyle->isVerticalWritingMode()) chunkStyle |= SVGTextChunk::VerticalText; // Handle 'text-anchor' property. switch (svgStyle->textAnchor()) { case TA_START: break; case TA_MIDDLE: chunkStyle |= SVGTextChunk::MiddleAnchor; break; case TA_END: chunkStyle |= SVGTextChunk::EndAnchor; break; }; // Handle 'lengthAdjust' property. float desiredTextLength = 0; if (SVGTextContentElement* textContentElement = SVGTextContentElement::elementFromRenderer(textRenderer->parent())) { desiredTextLength = textContentElement->specifiedTextLength().value(textContentElement); switch (static_cast<SVGTextContentElement::SVGLengthAdjustType>(textContentElement->lengthAdjust())) { case SVGTextContentElement::LENGTHADJUST_UNKNOWN: break; case SVGTextContentElement::LENGTHADJUST_SPACING: chunkStyle |= SVGTextChunk::LengthAdjustSpacing; break; case SVGTextContentElement::LENGTHADJUST_SPACINGANDGLYPHS: chunkStyle |= SVGTextChunk::LengthAdjustSpacingAndGlyphs; break; }; } SVGTextChunk chunk(chunkStyle, desiredTextLength); Vector<SVGInlineTextBox*>& boxes = chunk.boxes(); for (unsigned i = boxStart; i < boxStart + boxCount; ++i) boxes.append(lineLayoutBoxes[i]); m_textChunks.append(chunk); } void SVGTextChunkBuilder::processTextChunk(const SVGTextChunk& chunk) { bool processTextLength = chunk.hasDesiredTextLength(); bool processTextAnchor = chunk.hasTextAnchor(); if (!processTextAnchor && !processTextLength) return; const Vector<SVGInlineTextBox*>& boxes = chunk.boxes(); unsigned boxCount = boxes.size(); if (!boxCount) return; // Calculate absolute length of whole text chunk (starting from text box 'start', spanning 'length' text boxes). float chunkLength = 0; unsigned chunkCharacters = 0; chunk.calculateLength(chunkLength, chunkCharacters); bool isVerticalText = chunk.isVerticalText(); if (processTextLength) { if (chunk.hasLengthAdjustSpacing()) { float textLengthShift = (chunk.desiredTextLength() - chunkLength) / chunkCharacters; unsigned atCharacter = 0; for (unsigned boxPosition = 0; boxPosition < boxCount; ++boxPosition) { Vector<SVGTextFragment>& fragments = boxes[boxPosition]->textFragments(); if (fragments.isEmpty()) continue; processTextLengthSpacingCorrection(isVerticalText, textLengthShift, fragments, atCharacter); } } else { ASSERT(chunk.hasLengthAdjustSpacingAndGlyphs()); float textLengthScale = chunk.desiredTextLength() / chunkLength; AffineTransform spacingAndGlyphsTransform; bool foundFirstFragment = false; for (unsigned boxPosition = 0; boxPosition < boxCount; ++boxPosition) { SVGInlineTextBox* textBox = boxes[boxPosition]; Vector<SVGTextFragment>& fragments = textBox->textFragments(); if (fragments.isEmpty()) continue; if (!foundFirstFragment) { foundFirstFragment = true; buildSpacingAndGlyphsTransform(isVerticalText, textLengthScale, fragments.first(), spacingAndGlyphsTransform); } m_textBoxTransformations.set(textBox, spacingAndGlyphsTransform); } } } if (!processTextAnchor) return; // If we previously applied a lengthAdjust="spacing" correction, we have to recalculate the chunk length, to be able to apply the text-anchor shift. if (processTextLength && chunk.hasLengthAdjustSpacing()) { chunkLength = 0; chunkCharacters = 0; chunk.calculateLength(chunkLength, chunkCharacters); } float textAnchorShift = chunk.calculateTextAnchorShift(chunkLength); for (unsigned boxPosition = 0; boxPosition < boxCount; ++boxPosition) { Vector<SVGTextFragment>& fragments = boxes[boxPosition]->textFragments(); if (fragments.isEmpty()) continue; processTextAnchorCorrection(isVerticalText, textAnchorShift, fragments); } } void SVGTextChunkBuilder::processTextLengthSpacingCorrection(bool isVerticalText, float textLengthShift, Vector<SVGTextFragment>& fragments, unsigned& atCharacter) { unsigned fragmentCount = fragments.size(); for (unsigned i = 0; i < fragmentCount; ++i) { SVGTextFragment& fragment = fragments[i]; if (isVerticalText) fragment.y += textLengthShift * atCharacter; else fragment.x += textLengthShift * atCharacter; atCharacter += fragment.length; } } void SVGTextChunkBuilder::processTextAnchorCorrection(bool isVerticalText, float textAnchorShift, Vector<SVGTextFragment>& fragments) { unsigned fragmentCount = fragments.size(); for (unsigned i = 0; i < fragmentCount; ++i) { SVGTextFragment& fragment = fragments[i]; if (isVerticalText) fragment.y += textAnchorShift; else fragment.x += textAnchorShift; } } void SVGTextChunkBuilder::buildSpacingAndGlyphsTransform(bool isVerticalText, float scale, const SVGTextFragment& fragment, AffineTransform& spacingAndGlyphsTransform) { spacingAndGlyphsTransform.translate(fragment.x, fragment.y); if (isVerticalText) spacingAndGlyphsTransform.scaleNonUniform(1, scale); else spacingAndGlyphsTransform.scaleNonUniform(scale, 1); spacingAndGlyphsTransform.translate(-fragment.x, -fragment.y); } } #endif // ENABLE(SVG)
mogoweb/webkit_for_android5.1
webkit/Source/WebCore/rendering/svg/SVGTextChunkBuilder.cpp
C++
apache-2.0
9,299
<?php /* vim: set expandtab sw=4 ts=4 sts=4: */ /** * * @package PhpMyAdmin */ // Run common work require_once './libraries/common.inc.php'; define('TABLE_MAY_BE_ABSENT', true); require './libraries/tbl_common.php'; $url_query .= '&amp;goto=tbl_tracking.php&amp;back=tbl_tracking.php'; $url_params['goto'] = 'tbl_tracking.php';; $url_params['back'] = 'tbl_tracking.php'; // Init vars for tracking report if (isset($_REQUEST['report']) || isset($_REQUEST['report_export'])) { $data = PMA_Tracker::getTrackedData($_REQUEST['db'], $_REQUEST['table'], $_REQUEST['version']); $selection_schema = false; $selection_data = false; $selection_both = false; if (! isset($_REQUEST['logtype'])) { $_REQUEST['logtype'] = 'schema_and_data'; } if ($_REQUEST['logtype'] == 'schema') { $selection_schema = true; } elseif ($_REQUEST['logtype'] == 'data') { $selection_data = true; } else { $selection_both = true; } if (! isset($_REQUEST['date_from'])) { $_REQUEST['date_from'] = $data['date_from']; } if (! isset($_REQUEST['date_to'])) { $_REQUEST['date_to'] = $data['date_to']; } if (! isset($_REQUEST['users'])) { $_REQUEST['users'] = '*'; } $filter_ts_from = strtotime($_REQUEST['date_from']); $filter_ts_to = strtotime($_REQUEST['date_to']); $filter_users = array_map('trim', explode(',', $_REQUEST['users'])); } // Prepare export if (isset($_REQUEST['report_export'])) { /** * Filters tracking entries * * @param array the entries to filter * @param string "from" date * @param string "to" date * @param string users * * @return array filtered entries * */ function PMA_filter_tracking($data, $filter_ts_from, $filter_ts_to, $filter_users) { $tmp_entries = array(); $id = 0; foreach ( $data as $entry ) { $timestamp = strtotime($entry['date']); if ($timestamp >= $filter_ts_from && $timestamp <= $filter_ts_to && ( in_array('*', $filter_users) || in_array($entry['username'], $filter_users) ) ) { $tmp_entries[] = array( 'id' => $id, 'timestamp' => $timestamp, 'username' => $entry['username'], 'statement' => $entry['statement'] ); } $id++; } return($tmp_entries); } $entries = array(); // Filtering data definition statements if ($_REQUEST['logtype'] == 'schema' || $_REQUEST['logtype'] == 'schema_and_data') { $entries = array_merge($entries, PMA_filter_tracking($data['ddlog'], $filter_ts_from, $filter_ts_to, $filter_users)); } // Filtering data manipulation statements if ($_REQUEST['logtype'] == 'data' || $_REQUEST['logtype'] == 'schema_and_data') { $entries = array_merge($entries, PMA_filter_tracking($data['dmlog'], $filter_ts_from, $filter_ts_to, $filter_users)); } // Sort it foreach ($entries as $key => $row) { $ids[$key] = $row['id']; $timestamps[$key] = $row['timestamp']; $usernames[$key] = $row['username']; $statements[$key] = $row['statement']; } array_multisort($timestamps, SORT_ASC, $ids, SORT_ASC, $usernames, SORT_ASC, $statements, SORT_ASC, $entries); } // Export as file download if (isset($_REQUEST['report_export']) && $_REQUEST['export_type'] == 'sqldumpfile') { @ini_set('url_rewriter.tags', ''); $dump = "# " . sprintf(__('Tracking report for table `%s`'), htmlspecialchars($_REQUEST['table'])) . "\n" . "# " . date('Y-m-d H:i:s') . "\n"; foreach ($entries as $entry) { $dump .= $entry['statement']; } $filename = 'log_' . htmlspecialchars($_REQUEST['table']) . '.sql'; PMA_download_header($filename, 'text/x-sql', strlen($dump)); echo $dump; exit(); } /** * Gets tables informations */ /** * Displays top menu links */ require_once './libraries/tbl_links.inc.php'; echo '<br />'; /** * Actions */ // Create tracking version if (isset($_REQUEST['submit_create_version'])) { $tracking_set = ''; if ($_REQUEST['alter_table'] == true) { $tracking_set .= 'ALTER TABLE,'; } if ($_REQUEST['rename_table'] == true) { $tracking_set .= 'RENAME TABLE,'; } if ($_REQUEST['create_table'] == true) { $tracking_set .= 'CREATE TABLE,'; } if ($_REQUEST['drop_table'] == true) { $tracking_set .= 'DROP TABLE,'; } if ($_REQUEST['create_index'] == true) { $tracking_set .= 'CREATE INDEX,'; } if ($_REQUEST['drop_index'] == true) { $tracking_set .= 'DROP INDEX,'; } if ($_REQUEST['insert'] == true) { $tracking_set .= 'INSERT,'; } if ($_REQUEST['update'] == true) { $tracking_set .= 'UPDATE,'; } if ($_REQUEST['delete'] == true) { $tracking_set .= 'DELETE,'; } if ($_REQUEST['truncate'] == true) { $tracking_set .= 'TRUNCATE,'; } $tracking_set = rtrim($tracking_set, ','); if (PMA_Tracker::createVersion($GLOBALS['db'], $GLOBALS['table'], $_REQUEST['version'], $tracking_set )) { $msg = PMA_Message::success(sprintf(__('Version %s is created, tracking for %s.%s is activated.'), htmlspecialchars($_REQUEST['version']), htmlspecialchars($GLOBALS['db']), htmlspecialchars($GLOBALS['table']))); $msg->display(); } } // Deactivate tracking if (isset($_REQUEST['submit_deactivate_now'])) { if (PMA_Tracker::deactivateTracking($GLOBALS['db'], $GLOBALS['table'], $_REQUEST['version'])) { $msg = PMA_Message::success(sprintf(__('Tracking for %s.%s , version %s is deactivated.'), htmlspecialchars($GLOBALS['db']), htmlspecialchars($GLOBALS['table']), htmlspecialchars($_REQUEST['version']))); $msg->display(); } } // Activate tracking if (isset($_REQUEST['submit_activate_now'])) { if (PMA_Tracker::activateTracking($GLOBALS['db'], $GLOBALS['table'], $_REQUEST['version'])) { $msg = PMA_Message::success(sprintf(__('Tracking for %s.%s , version %s is activated.'), htmlspecialchars($GLOBALS['db']), htmlspecialchars($GLOBALS['table']), htmlspecialchars($_REQUEST['version']))); $msg->display(); } } // Export as SQL execution if (isset($_REQUEST['report_export']) && $_REQUEST['export_type'] == 'execution') { foreach ($entries as $entry) { $sql_result = PMA_DBI_query( "/*NOTRACK*/\n" . $entry['statement'] ); } $msg = PMA_Message::success(__('SQL statements executed.')); $msg->display(); } // Export as SQL dump if (isset($_REQUEST['report_export']) && $_REQUEST['export_type'] == 'sqldump') { $new_query = "# " . __('You can execute the dump by creating and using a temporary database. Please ensure that you have the privileges to do so.') . "\n" . "# " . __('Comment out these two lines if you do not need them.') . "\n" . "\n" . "CREATE database IF NOT EXISTS pma_temp_db; \n" . "USE pma_temp_db; \n" . "\n"; foreach ($entries as $entry) { $new_query .= $entry['statement']; } $msg = PMA_Message::success(__('SQL statements exported. Please copy the dump or execute it.')); $msg->display(); $db_temp = $db; $table_temp = $table; $db = $table = ''; include_once './libraries/sql_query_form.lib.php'; PMA_sqlQueryForm($new_query, 'sql'); $db = $db_temp; $table = $table_temp; } /* * Schema snapshot */ if (isset($_REQUEST['snapshot'])) { ?> <h3><?php echo __('Structure snapshot');?> [<a href="tbl_tracking.php?<?php echo $url_query;?>"><?php echo __('Close');?></a>]</h3> <?php $data = PMA_Tracker::getTrackedData($_REQUEST['db'], $_REQUEST['table'], $_REQUEST['version']); // Get first DROP TABLE and CREATE TABLE statements $drop_create_statements = $data['ddlog'][0]['statement']; if (strstr($data['ddlog'][0]['statement'], 'DROP TABLE')) { $drop_create_statements .= $data['ddlog'][1]['statement']; } // Print SQL code PMA_showMessage(sprintf(__('Version %s snapshot (SQL code)'), htmlspecialchars($_REQUEST['version'])), $drop_create_statements); // Unserialize snapshot $temp = unserialize($data['schema_snapshot']); $columns = $temp['COLUMNS']; $indexes = $temp['INDEXES']; ?> <h3><?php echo __('Structure');?></h3> <table id="tablestructure" class="data"> <thead> <tr> <th><?php echo __('Column'); ?></th> <th><?php echo __('Type'); ?></th> <th><?php echo __('Collation'); ?></th> <th><?php echo __('Null'); ?></th> <th><?php echo __('Default'); ?></th> <th><?php echo __('Extra'); ?></th> <th><?php echo __('Comment'); ?></th> </tr> </thead> <tbody> <?php $style = 'odd'; foreach ($columns as $field_index => $field) { ?> <tr class="noclick <?php echo $style; ?>"> <?php if ($field['Key'] == 'PRI') { echo '<td><b><u>' . htmlspecialchars($field['Field']) . '</u></b></td>' . "\n"; } else { echo '<td><b>' . htmlspecialchars($field['Field']) . '</b></td>' . "\n"; } ?> <td><?php echo htmlspecialchars($field['Type']);?></td> <td><?php echo htmlspecialchars($field['Collation']);?></td> <td><?php echo (($field['Null'] == 'YES') ? __('Yes') : __('No')); ?></td> <td><?php if (isset($field['Default'])) { $extracted_fieldspec = PMA_extractFieldSpec($field['Type']); if ($extracted_fieldspec['type'] == 'bit') { // here, $field['Default'] contains something like b'010' echo PMA_convert_bit_default_value($field['Default']); } else { echo htmlspecialchars($field['Default']); } } else { if ($field['Null'] == 'YES') { echo '<i>NULL</i>'; } else { echo '<i>' . _pgettext('None for default', 'None') . '</i>'; } } ?></td> <td><?php echo htmlspecialchars($field['Extra']);?></td> <td><?php echo htmlspecialchars($field['Comment']);?></td> </tr> <?php if ($style == 'even') { $style = 'odd'; } else { $style = 'even'; } } ?> </tbody> </table> <?php if (count($indexes) > 0) { ?> <h3><?php echo __('Indexes');?></h3> <table id="tablestructure_indexes" class="data"> <thead> <tr> <th><?php echo __('Keyname');?></th> <th><?php echo __('Type');?></th> <th><?php echo __('Unique');?></th> <th><?php echo __('Packed');?></th> <th><?php echo __('Column');?></th> <th><?php echo __('Cardinality');?></th> <th><?php echo __('Collation');?></th> <th><?php echo __('Null');?></th> <th><?php echo __('Comment');?></th> </tr> <tbody> <?php $style = 'odd'; foreach ($indexes as $indexes_index => $index) { if ($index['Non_unique'] == 0) { $str_unique = __('Yes'); } else { $str_unique = __('No'); } if ($index['Packed'] != '') { $str_packed = __('Yes'); } else { $str_packed = __('No'); } ?> <tr class="noclick <?php echo $style; ?>"> <td><b><?php echo htmlspecialchars($index['Key_name']);?></b></td> <td><?php echo htmlspecialchars($index['Index_type']);?></td> <td><?php echo $str_unique;?></td> <td><?php echo $str_packed;?></td> <td><?php echo htmlspecialchars($index['Column_name']);?></td> <td><?php echo htmlspecialchars($index['Cardinality']);?></td> <td><?php echo htmlspecialchars($index['Collation']);?></td> <td><?php echo htmlspecialchars($index['Null']);?></td> <td><?php echo htmlspecialchars($index['Comment']);?></td> </tr> <?php if ($style == 'even') { $style = 'odd'; } else { $style = 'even'; } } ?> </tbody> </table> <?php } // endif ?> <br /><hr /><br /> <?php } // end of snapshot report /* * Tracking report */ if (isset($_REQUEST['report']) && (isset($_REQUEST['delete_ddlog']) || isset($_REQUEST['delete_dmlog']))) { if (isset($_REQUEST['delete_ddlog'])) { // Delete ddlog row data $delete_id = $_REQUEST['delete_ddlog']; // Only in case of valable id if ($delete_id == (int)$delete_id) { unset($data['ddlog'][$delete_id]); if (PMA_Tracker::changeTrackingData($_REQUEST['db'], $_REQUEST['table'], $_REQUEST['version'], 'DDL', $data['ddlog'])) $msg = PMA_Message::success(__('Tracking data definition successfully deleted')); else $msg = PMA_Message::rawError(__('Query error')); $msg->display(); } } if (isset($_REQUEST['delete_dmlog'])) { // Delete dmlog row data $delete_id = $_REQUEST['delete_dmlog']; // Only in case of valable id if ($delete_id == (int)$delete_id) { unset($data['dmlog'][$delete_id]); if (PMA_Tracker::changeTrackingData($_REQUEST['db'], $_REQUEST['table'], $_REQUEST['version'], 'DML', $data['dmlog'])) $msg = PMA_Message::success(__('Tracking data manipulation successfully deleted')); else $msg = PMA_Message::rawError(__('Query error')); $msg->display(); } } } if (isset($_REQUEST['report']) || isset($_REQUEST['report_export'])) { ?> <h3><?php echo __('Tracking report');?> [<a href="tbl_tracking.php?<?php echo $url_query;?>"><?php echo __('Close');?></a>]</h3> <small><?php echo __('Tracking statements') . ' ' . htmlspecialchars($data['tracking']); ?></small><br/> <br/> <form method="post" action="tbl_tracking.php<?php echo PMA_generate_common_url($url_params + array('report' => 'true', 'version' => $_REQUEST['version'])); ?>"> <?php $str1 = '<select name="logtype">' . '<option value="schema"' . ($selection_schema ? ' selected="selected"' : '') . '>' . __('Structure only') . '</option>' . '<option value="data"' . ($selection_data ? ' selected="selected"' : ''). '>' . __('Data only') . '</option>' . '<option value="schema_and_data"' . ($selection_both ? ' selected="selected"' : '') . '>' . __('Structure and data') . '</option>' . '</select>'; $str2 = '<input type="text" name="date_from" value="' . htmlspecialchars($_REQUEST['date_from']) . '" size="19" />'; $str3 = '<input type="text" name="date_to" value="' . htmlspecialchars($_REQUEST['date_to']) . '" size="19" />'; $str4 = '<input type="text" name="users" value="' . htmlspecialchars($_REQUEST['users']) . '" />'; $str5 = '<input type="submit" name="list_report" value="' . __('Go') . '" />'; printf(__('Show %s with dates from %s to %s by user %s %s'), $str1, $str2, $str3, $str4, $str5); // Prepare delete link content here $drop_image_or_text = ''; if (true == $GLOBALS['cfg']['PropertiesIconic']) { $drop_image_or_text .= PMA_getImage('b_drop.png', __('Delete tracking data row from report')); } if ('both' === $GLOBALS['cfg']['PropertiesIconic'] || false === $GLOBALS['cfg']['PropertiesIconic']) { $drop_image_or_text .= __('Delete'); } /* * First, list tracked data definition statements */ $i = 1; if (count($data['ddlog']) == 0 && count($data['dmlog']) == 0) { $msg = PMA_Message::notice(__('No data')); $msg->display(); } if ($selection_schema || $selection_both && count($data['ddlog']) > 0) { ?> <table id="ddl_versions" class="data" width="100%"> <thead> <tr> <th width="18">#</th> <th width="100"><?php echo __('Date');?></th> <th width="60"><?php echo __('Username');?></th> <th><?php echo __('Data definition statement');?></th> <th><?php echo __('Delete');?></th> </tr> </thead> <tbody> <?php $style = 'odd'; foreach ($data['ddlog'] as $entry) { if (strlen($entry['statement']) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) { $statement = substr($entry['statement'], 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) . '[...]'; } else { $statement = PMA_formatSql(PMA_SQP_parse($entry['statement'])); } $timestamp = strtotime($entry['date']); if ($timestamp >= $filter_ts_from && $timestamp <= $filter_ts_to && ( in_array('*', $filter_users) || in_array($entry['username'], $filter_users) ) ) { ?> <tr class="noclick <?php echo $style; ?>"> <td><small><?php echo $i;?></small></td> <td><small><?php echo htmlspecialchars($entry['date']);?></small></td> <td><small><?php echo htmlspecialchars($entry['username']); ?></small></td> <td><?php echo $statement; ?></td> <td nowrap="nowrap"><a href="tbl_tracking.php?<?php echo $url_query;?>&amp;report=true&amp;version=<?php echo $version['version'];?>&amp;delete_ddlog=<?php echo $i-1; ?>"><?php echo $drop_image_or_text; ?></a></td> </tr> <?php if ($style == 'even') { $style = 'odd'; } else { $style = 'even'; } $i++; } } ?> </tbody> </table> <?php } //endif // Memorize data definition amount $ddlog_count = $i; /* * Secondly, list tracked data manipulation statements */ if (($selection_data || $selection_both) && count($data['dmlog']) > 0) { ?> <table id="dml_versions" class="data" width="100%"> <thead> <tr> <th width="18">#</th> <th width="100"><?php echo __('Date');?></th> <th width="60"><?php echo __('Username');?></th> <th><?php echo __('Data manipulation statement');?></th> <th><?php echo __('Delete');?></th> </tr> </thead> <tbody> <?php $style = 'odd'; foreach ($data['dmlog'] as $entry) { if (strlen($entry['statement']) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) { $statement = substr($entry['statement'], 0, $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) . '[...]'; } else { $statement = PMA_formatSql(PMA_SQP_parse($entry['statement'])); } $timestamp = strtotime($entry['date']); if ($timestamp >= $filter_ts_from && $timestamp <= $filter_ts_to && ( in_array('*', $filter_users) || in_array($entry['username'], $filter_users) ) ) { ?> <tr class="noclick <?php echo $style; ?>"> <td><small><?php echo $i; ?></small></td> <td><small><?php echo htmlspecialchars($entry['date']); ?></small></td> <td><small><?php echo htmlspecialchars($entry['username']); ?></small></td> <td><?php echo $statement; ?></td> <td nowrap="nowrap"><a href="tbl_tracking.php?<?php echo $url_query;?>&amp;report=true&amp;version=<?php echo $version['version'];?>&amp;delete_dmlog=<?php echo $i-$ddlog_count; ?>"><?php echo $drop_image_or_text; ?></a></td> </tr> <?php if ($style == 'even') { $style = 'odd'; } else { $style = 'even'; } $i++; } } ?> </tbody> </table> <?php } ?> </form> <form method="post" action="tbl_tracking.php<?php echo PMA_generate_common_url($url_params + array('report' => 'true', 'version' => $_REQUEST['version'])); ?>"> <?php printf(__('Show %s with dates from %s to %s by user %s %s'), $str1, $str2, $str3, $str4, $str5); $str_export1 = '<select name="export_type">' . '<option value="sqldumpfile">' . __('SQL dump (file download)') . '</option>' . '<option value="sqldump">' . __('SQL dump') . '</option>' . '<option value="execution" onclick="alert(\'' . PMA_escapeJsString(__('This option will replace your table and contained data.')) .'\')">' . __('SQL execution') . '</option>' . '</select>'; $str_export2 = '<input type="submit" name="report_export" value="' . __('Go') .'" />'; ?> </form> <form method="post" action="tbl_tracking.php<?php echo PMA_generate_common_url($url_params + array('report' => 'true', 'version' => $_REQUEST['version'])); ?>"> <input type="hidden" name="logtype" value="<?php echo htmlspecialchars($_REQUEST['logtype']);?>" /> <input type="hidden" name="date_from" value="<?php echo htmlspecialchars($_REQUEST['date_from']);?>" /> <input type="hidden" name="date_to" value="<?php echo htmlspecialchars($_REQUEST['date_to']);?>" /> <input type="hidden" name="users" value="<?php echo htmlspecialchars($_REQUEST['users']);?>" /> <?php echo "<br/>" . sprintf(__('Export as %s'), $str_export1) . $str_export2 . "<br/>"; ?> </form> <?php echo "<br/><br/><hr/><br/>\n"; } // end of report /* * List selectable tables */ $sql_query = " SELECT DISTINCT db_name, table_name FROM " . PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) . "." . PMA_backquote($GLOBALS['cfg']['Server']['tracking']) . " WHERE db_name = '" . PMA_sqlAddSlashes($GLOBALS['db']) . "' " . " ORDER BY db_name, table_name"; $sql_result = PMA_query_as_controluser($sql_query); if (PMA_DBI_num_rows($sql_result) > 0) { ?> <form method="post" action="tbl_tracking.php?<?php echo $url_query;?>"> <select name="table"> <?php while ($entries = PMA_DBI_fetch_array($sql_result)) { if (PMA_Tracker::isTracked($entries['db_name'], $entries['table_name'])) { $status = ' (' . __('active') . ')'; } else { $status = ' (' . __('not active') . ')'; } if ($entries['table_name'] == $_REQUEST['table']) { $s = ' selected="selected"'; } else { $s = ''; } echo '<option value="' . htmlspecialchars($entries['table_name']) . '"' . $s . '>' . htmlspecialchars($entries['db_name']) . ' . ' . htmlspecialchars($entries['table_name']) . $status . '</option>' . "\n"; } ?> </select> <input type="submit" name="show_versions_submit" value="<?php echo __('Show versions');?>" /> </form> <?php } ?> <br /> <?php /* * List versions of current table */ $sql_query = " SELECT * FROM " . PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) . "." . PMA_backquote($GLOBALS['cfg']['Server']['tracking']) . " WHERE db_name = '" . PMA_sqlAddSlashes($_REQUEST['db']) . "' ". " AND table_name = '" . PMA_sqlAddSlashes($_REQUEST['table']) ."' ". " ORDER BY version DESC "; $sql_result = PMA_query_as_controluser($sql_query); $last_version = 0; $maxversion = PMA_DBI_fetch_array($sql_result); $last_version = $maxversion['version']; if ($last_version > 0) { ?> <table id="versions" class="data"> <thead> <tr> <th><?php echo __('Database');?></th> <th><?php echo __('Table');?></th> <th><?php echo __('Version');?></th> <th><?php echo __('Created');?></th> <th><?php echo __('Updated');?></th> <th><?php echo __('Status');?></th> <th><?php echo __('Show');?></th> </tr> </thead> <tbody> <?php $style = 'odd'; PMA_DBI_data_seek($sql_result, 0); while ($version = PMA_DBI_fetch_array($sql_result)) { if ($version['tracking_active'] == 1) { $version_status = __('active'); } else { $version_status = __('not active'); } if ($version['version'] == $last_version) { if ($version['tracking_active'] == 1) { $tracking_active = true; } else { $tracking_active = false; } } ?> <tr class="noclick <?php echo $style;?>"> <td><?php echo htmlspecialchars($version['db_name']);?></td> <td><?php echo htmlspecialchars($version['table_name']);?></td> <td><?php echo htmlspecialchars($version['version']);?></td> <td><?php echo htmlspecialchars($version['date_created']);?></td> <td><?php echo htmlspecialchars($version['date_updated']);?></td> <td><?php echo $version_status;?></td> <td> <a href="tbl_tracking.php<?php echo PMA_generate_common_url($url_params + array('report' => 'true', 'version' => $version['version']) );?>"><?php echo __('Tracking report');?></a> | <a href="tbl_tracking.php<?php echo PMA_generate_common_url($url_params + array('snapshot' => 'true', 'version' => $version['version']) );?>"><?php echo __('Structure snapshot');?></a> </td> </tr> <?php if ($style == 'even') { $style = 'odd'; } else { $style = 'even'; } } ?> </tbody> </table> <?php if ($tracking_active == true) {?> <div id="div_deactivate_tracking"> <form method="post" action="tbl_tracking.php?<?php echo $url_query; ?>"> <fieldset> <legend><?php printf(__('Deactivate tracking for %s.%s'), htmlspecialchars($GLOBALS['db']), htmlspecialchars($GLOBALS['table'])); ?></legend> <input type="hidden" name="version" value="<?php echo $last_version; ?>" /> <input type="submit" name="submit_deactivate_now" value="<?php echo __('Deactivate now'); ?>" /> </fieldset> </form> </div> <?php } ?> <?php if ($tracking_active == false) {?> <div id="div_activate_tracking"> <form method="post" action="tbl_tracking.php?<?php echo $url_query; ?>"> <fieldset> <legend><?php printf(__('Activate tracking for %s.%s'), htmlspecialchars($GLOBALS['db']), htmlspecialchars($GLOBALS['table'])); ?></legend> <input type="hidden" name="version" value="<?php echo $last_version; ?>" /> <input type="submit" name="submit_activate_now" value="<?php echo __('Activate now'); ?>" /> </fieldset> </form> </div> <?php } } ?> <div id="div_create_version"> <form method="post" action="tbl_tracking.php?<?php echo $url_query; ?>"> <?php echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']); ?> <fieldset> <legend><?php printf(__('Create version %s of %s.%s'), ($last_version + 1), htmlspecialchars($GLOBALS['db']), htmlspecialchars($GLOBALS['table'])); ?></legend> <input type="hidden" name="version" value="<?php echo ($last_version + 1); ?>" /> <p><?php echo __('Track these data definition statements:');?></p> <input type="checkbox" name="alter_table" value="true" checked="checked" /> ALTER TABLE<br/> <input type="checkbox" name="rename_table" value="true" checked="checked" /> RENAME TABLE<br/> <input type="checkbox" name="create_table" value="true" checked="checked" /> CREATE TABLE<br/> <input type="checkbox" name="drop_table" value="true" checked="checked" /> DROP TABLE<br/> <br/> <input type="checkbox" name="create_index" value="true" checked="checked" /> CREATE INDEX<br/> <input type="checkbox" name="drop_index" value="true" checked="checked" /> DROP INDEX<br/> <p><?php echo __('Track these data manipulation statements:');?></p> <input type="checkbox" name="insert" value="true" checked="checked" /> INSERT<br/> <input type="checkbox" name="update" value="true" checked="checked" /> UPDATE<br/> <input type="checkbox" name="delete" value="true" checked="checked" /> DELETE<br/> <input type="checkbox" name="truncate" value="true" checked="checked" /> TRUNCATE<br/> </fieldset> <fieldset class="tblFooters"> <input type="submit" name="submit_create_version" value="<?php echo __('Create version'); ?>" /> </fieldset> </form> </div> <br class="clearfloat"/> <?php /** * Displays the footer */ require './libraries/footer.inc.php'; ?>
teiath/lms
web/dbadmin/tbl_tracking.php
PHP
mit
29,065
package terraform //go:generate stringer -type=walkOperation graph_walk_operation.go // walkOperation is an enum which tells the walkContext what to do. type walkOperation byte const ( walkInvalid walkOperation = iota walkInput walkApply walkPlan walkPlanDestroy walkRefresh walkValidate walkDestroy )
kzittritsch/terraform-provider-bigip
vendor/github.com/hashicorp/terraform/terraform/graph_walk_operation.go
GO
mpl-2.0
313
(function (env) { "use strict"; env.ddg_spice_bacon_ipsum = function(api_result){ if (!api_result || api_result.error) { return Spice.failed('bacon_ipsum'); } var pageContent = ''; for (var i in api_result) { pageContent += "<p>" + api_result[i] + "</p>"; } Spice.add({ id: 'bacon_ipsum', name: 'Bacon Ipsum', data: { content: pageContent, title: "Bacon Ipsum", subtitle: "Randomly generated text" }, meta: { sourceName: 'Bacon Ipsum', sourceUrl: 'http://baconipsum.com/' }, templates: { group: 'text', options: { content: Spice.bacon_ipsum.content } } }); }; }(this));
hshackathons/zeroclickinfo-spice
share/spice/bacon_ipsum/bacon_ipsum.js
JavaScript
apache-2.0
910
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //////////////////////////////////////////////////////////////////////////// // // // Purpose: This class implements a set of methods for retrieving // sort key information. // // //////////////////////////////////////////////////////////////////////////// namespace System.Globalization { using System; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] [Serializable] public class SortKey { //--------------------------------------------------------------------// // Internal Information // //--------------------------------------------------------------------// // // Variables. // [OptionalField(VersionAdded = 3)] internal String localeName; // locale identifier [OptionalField(VersionAdded = 1)] // LCID field so serialization is Whidbey compatible though we don't officially support it internal int win32LCID; // Whidbey serialization internal CompareOptions options; // options internal String m_String; // original string internal byte[] m_KeyData; // sortkey data // // The following constructor is designed to be called from CompareInfo to get the // the sort key of specific string for synthetic culture // internal SortKey(String localeName, String str, CompareOptions options, byte[] keyData) { this.m_KeyData = keyData; this.localeName = localeName; this.options = options; this.m_String = str; } #if FEATURE_USE_LCID [OnSerializing] private void OnSerializing(StreamingContext context) { //set LCID to proper value for Whidbey serialization (no other use) if (win32LCID == 0) { win32LCID = CultureInfo.GetCultureInfo(localeName).LCID; } } [OnDeserialized] private void OnDeserialized(StreamingContext context) { //set locale name to proper value after Whidbey deserialization if (String.IsNullOrEmpty(localeName) && win32LCID != 0) { localeName = CultureInfo.GetCultureInfo(win32LCID).Name; } } #endif //FEATURE_USE_LCID //////////////////////////////////////////////////////////////////////// // // GetOriginalString // // Returns the original string used to create the current instance // of SortKey. // //////////////////////////////////////////////////////////////////////// public virtual String OriginalString { get { return (m_String); } } //////////////////////////////////////////////////////////////////////// // // GetKeyData // // Returns a byte array representing the current instance of the // sort key. // //////////////////////////////////////////////////////////////////////// public virtual byte[] KeyData { get { return (byte[])(m_KeyData.Clone()); } } //////////////////////////////////////////////////////////////////////// // // Compare // // Compares the two sort keys. Returns 0 if the two sort keys are // equal, a number less than 0 if sortkey1 is less than sortkey2, // and a number greater than 0 if sortkey1 is greater than sortkey2. // //////////////////////////////////////////////////////////////////////// public static int Compare(SortKey sortkey1, SortKey sortkey2) { if (sortkey1==null || sortkey2==null) { throw new ArgumentNullException((sortkey1==null ? "sortkey1": "sortkey2")); } Contract.EndContractBlock(); byte[] key1Data = sortkey1.m_KeyData; byte[] key2Data = sortkey2.m_KeyData; Contract.Assert(key1Data!=null, "key1Data!=null"); Contract.Assert(key2Data!=null, "key2Data!=null"); if (key1Data.Length == 0) { if (key2Data.Length == 0) { return (0); } return (-1); } if (key2Data.Length == 0) { return (1); } int compLen = (key1Data.Length<key2Data.Length)?key1Data.Length:key2Data.Length; for (int i=0; i<compLen; i++) { if (key1Data[i]>key2Data[i]) { return (1); } if (key1Data[i]<key2Data[i]) { return (-1); } } return 0; } //////////////////////////////////////////////////////////////////////// // // Equals // // Implements Object.Equals(). Returns a boolean indicating whether // or not object refers to the same SortKey as the current instance. // //////////////////////////////////////////////////////////////////////// public override bool Equals(Object value) { SortKey that = value as SortKey; if (that != null) { return Compare(this, that) == 0; } return (false); } //////////////////////////////////////////////////////////////////////// // // GetHashCode // // Implements Object.GetHashCode(). Returns the hash code for the // SortKey. The hash code is guaranteed to be the same for // SortKey A and B where A.Equals(B) is true. // //////////////////////////////////////////////////////////////////////// public override int GetHashCode() { return (CompareInfo.GetCompareInfo( this.localeName).GetHashCodeOfString(this.m_String, this.options)); } //////////////////////////////////////////////////////////////////////// // // ToString // // Implements Object.ToString(). Returns a string describing the // SortKey. // //////////////////////////////////////////////////////////////////////// public override String ToString() { return ("SortKey - " + localeName + ", " + options + ", " + m_String); } } }
Priya91/coreclr
src/mscorlib/src/System/Globalization/SortKey.cs
C#
mit
6,975
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.Contracts; //using System.Globalization; using System.Runtime.CompilerServices; namespace System.Collections.Generic { [Serializable] [TypeDependencyAttribute("System.Collections.Generic.ObjectComparer`1")] public abstract class Comparer<T> : IComparer, IComparer<T> { static volatile Comparer<T> defaultComparer; public static Comparer<T> Default { get { Contract.Ensures(Contract.Result<Comparer<T>>() != null); Comparer<T> comparer = defaultComparer; if (comparer == null) { comparer = CreateComparer(); defaultComparer = comparer; } return comparer; } } public static Comparer<T> Create(Comparison<T> comparison) { Contract.Ensures(Contract.Result<Comparer<T>>() != null); if (comparison == null) throw new ArgumentNullException("comparison"); return new ComparisonComparer<T>(comparison); } // // Note that logic in this method is replicated in vm\compile.cpp to ensure that NGen // saves the right instantiations // [System.Security.SecuritySafeCritical] // auto-generated private static Comparer<T> CreateComparer() { RuntimeType t = (RuntimeType)typeof(T); // If T implements IComparable<T> return a GenericComparer<T> #if FEATURE_LEGACYNETCF // Pre-Apollo Windows Phone call the overload that sorts the keys, not values this achieves the same result if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { if (t.ImplementInterface(typeof(IComparable<T>))) { return (Comparer<T>)RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(GenericComparer<int>), t); } } else #endif if (typeof(IComparable<T>).IsAssignableFrom(t)) { return (Comparer<T>)RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(GenericComparer<int>), t); } // If T is a Nullable<U> where U implements IComparable<U> return a NullableComparer<U> if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) { RuntimeType u = (RuntimeType)t.GetGenericArguments()[0]; if (typeof(IComparable<>).MakeGenericType(u).IsAssignableFrom(u)) { return (Comparer<T>)RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(NullableComparer<int>), u); } } // Otherwise return an ObjectComparer<T> return new ObjectComparer<T>(); } public abstract int Compare(T x, T y); int IComparer.Compare(object x, object y) { if (x == null) return y == null ? 0 : -1; if (y == null) return 1; if (x is T && y is T) return Compare((T)x, (T)y); ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArgumentForComparison); return 0; } } [Serializable] internal class GenericComparer<T> : Comparer<T> where T: IComparable<T> { public override int Compare(T x, T y) { if (x != null) { if (y != null) return x.CompareTo(y); return 1; } if (y != null) return -1; return 0; } // Equals method for the comparer itself. public override bool Equals(Object obj){ GenericComparer<T> comparer = obj as GenericComparer<T>; return comparer != null; } public override int GetHashCode() { return this.GetType().Name.GetHashCode(); } } [Serializable] internal class NullableComparer<T> : Comparer<Nullable<T>> where T : struct, IComparable<T> { public override int Compare(Nullable<T> x, Nullable<T> y) { if (x.HasValue) { if (y.HasValue) return x.value.CompareTo(y.value); return 1; } if (y.HasValue) return -1; return 0; } // Equals method for the comparer itself. public override bool Equals(Object obj){ NullableComparer<T> comparer = obj as NullableComparer<T>; return comparer != null; } public override int GetHashCode() { return this.GetType().Name.GetHashCode(); } } [Serializable] internal class ObjectComparer<T> : Comparer<T> { public override int Compare(T x, T y) { return System.Collections.Comparer.Default.Compare(x, y); } // Equals method for the comparer itself. public override bool Equals(Object obj){ ObjectComparer<T> comparer = obj as ObjectComparer<T>; return comparer != null; } public override int GetHashCode() { return this.GetType().Name.GetHashCode(); } } [Serializable] internal class ComparisonComparer<T> : Comparer<T> { private readonly Comparison<T> _comparison; public ComparisonComparer(Comparison<T> comparison) { _comparison = comparison; } public override int Compare(T x, T y) { return _comparison(x, y); } } }
Priya91/coreclr
src/mscorlib/src/System/Collections/Generic/Comparer.cs
C#
mit
5,796
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CSharp; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public static class DiagnosticFixerTestsExtensions { internal static Document Apply(this Document document, CodeAction action) { var operations = action.GetOperationsAsync(CancellationToken.None).Result; var solution = operations.OfType<ApplyChangesOperation>().Single().ChangedSolution; return solution.GetDocument(document.Id); } } }
mavasani/roslyn-analyzers
tools/AnalyzerCodeGenerator/template/src/Test/Utilities/CodeFixTests.Extensions.cs
C#
apache-2.0
826
package consul import ( "fmt" "strings" "time" "github.com/xordataexchange/crypt/backend" "github.com/armon/consul-api" ) type Client struct { client *consulapi.KV waitIndex uint64 } func New(machines []string) (*Client, error) { conf := consulapi.DefaultConfig() if len(machines) > 0 { conf.Address = machines[0] } client, err := consulapi.NewClient(conf) if err != nil { return nil, err } return &Client{client.KV(), 0}, nil } func (c *Client) Get(key string) ([]byte, error) { kv, _, err := c.client.Get(key, nil) if err != nil { return nil, err } if kv == nil { return nil, fmt.Errorf("Key ( %s ) was not found.", key) } return kv.Value, nil } func (c *Client) List(key string) (backend.KVPairs, error) { pairs, _, err := c.client.List(key, nil) if err != nil { return nil, err } if err != nil { return nil, err } ret := make(backend.KVPairs, len(pairs), len(pairs)) for i, kv := range pairs { ret[i] = &backend.KVPair{Key: kv.Key, Value: kv.Value} } return ret, nil } func (c *Client) Set(key string, value []byte) error { key = strings.TrimPrefix(key, "/") kv := &consulapi.KVPair{ Key: key, Value: value, } _, err := c.client.Put(kv, nil) return err } func (c *Client) Watch(key string, stop chan bool) <-chan *backend.Response { respChan := make(chan *backend.Response, 0) go func() { for { opts := consulapi.QueryOptions{ WaitIndex: c.waitIndex, } keypair, meta, err := c.client.Get(key, &opts) if keypair == nil && err == nil { err = fmt.Errorf("Key ( %s ) was not found.", key) } if err != nil { respChan <- &backend.Response{nil, err} time.Sleep(time.Second * 5) continue } c.waitIndex = meta.LastIndex respChan <- &backend.Response{keypair.Value, nil} } }() return respChan }
tcotav/etcdhooks
vendor/src/github.com/xordataexchange/crypt/backend/consul/consul.go
GO
mit
1,810
require('../lib/node_loader'); var AWS = require('../lib/core'); var Service = require('../lib/service'); var apiLoader = require('../lib/api_loader'); apiLoader.services['cloudsearchdomain'] = {}; AWS.CloudSearchDomain = Service.defineService('cloudsearchdomain', ['2013-01-01']); require('../lib/services/cloudsearchdomain'); Object.defineProperty(apiLoader.services['cloudsearchdomain'], '2013-01-01', { get: function get() { var model = require('../apis/cloudsearchdomain-2013-01-01.min.json'); return model; }, enumerable: true, configurable: true }); module.exports = AWS.CloudSearchDomain;
edeati/alexa-translink-skill-js
test/node_modules/aws-sdk/clients/cloudsearchdomain.js
JavaScript
apache-2.0
615
#!/usr/bin/env python """ exec_command Implements exec_command function that is (almost) equivalent to commands.getstatusoutput function but on NT, DOS systems the returned status is actually correct (though, the returned status values may be different by a factor). In addition, exec_command takes keyword arguments for (re-)defining environment variables. Provides functions: exec_command --- execute command in a specified directory and in the modified environment. find_executable --- locate a command using info from environment variable PATH. Equivalent to posix `which` command. Author: Pearu Peterson <pearu@cens.ioc.ee> Created: 11 January 2003 Requires: Python 2.x Succesfully tested on: ======== ============ ================================================= os.name sys.platform comments ======== ============ ================================================= posix linux2 Debian (sid) Linux, Python 2.1.3+, 2.2.3+, 2.3.3 PyCrust 0.9.3, Idle 1.0.2 posix linux2 Red Hat 9 Linux, Python 2.1.3, 2.2.2, 2.3.2 posix sunos5 SunOS 5.9, Python 2.2, 2.3.2 posix darwin Darwin 7.2.0, Python 2.3 nt win32 Windows Me Python 2.3(EE), Idle 1.0, PyCrust 0.7.2 Python 2.1.1 Idle 0.8 nt win32 Windows 98, Python 2.1.1. Idle 0.8 nt win32 Cygwin 98-4.10, Python 2.1.1(MSC) - echo tests fail i.e. redefining environment variables may not work. FIXED: don't use cygwin echo! Comment: also `cmd /c echo` will not work but redefining environment variables do work. posix cygwin Cygwin 98-4.10, Python 2.3.3(cygming special) nt win32 Windows XP, Python 2.3.3 ======== ============ ================================================= Known bugs: * Tests, that send messages to stderr, fail when executed from MSYS prompt because the messages are lost at some point. """ from __future__ import division, absolute_import, print_function __all__ = ['exec_command', 'find_executable'] import os import sys import shlex from numpy.distutils.misc_util import is_sequence, make_temp_file from numpy.distutils import log from numpy.distutils.compat import get_exception from numpy.compat import open_latin1 def temp_file_name(): fo, name = make_temp_file() fo.close() return name def get_pythonexe(): pythonexe = sys.executable if os.name in ['nt', 'dos']: fdir, fn = os.path.split(pythonexe) fn = fn.upper().replace('PYTHONW', 'PYTHON') pythonexe = os.path.join(fdir, fn) assert os.path.isfile(pythonexe), '%r is not a file' % (pythonexe,) return pythonexe def find_executable(exe, path=None, _cache={}): """Return full path of a executable or None. Symbolic links are not followed. """ key = exe, path try: return _cache[key] except KeyError: pass log.debug('find_executable(%r)' % exe) orig_exe = exe if path is None: path = os.environ.get('PATH', os.defpath) if os.name=='posix': realpath = os.path.realpath else: realpath = lambda a:a if exe.startswith('"'): exe = exe[1:-1] suffixes = [''] if os.name in ['nt', 'dos', 'os2']: fn, ext = os.path.splitext(exe) extra_suffixes = ['.exe', '.com', '.bat'] if ext.lower() not in extra_suffixes: suffixes = extra_suffixes if os.path.isabs(exe): paths = [''] else: paths = [ os.path.abspath(p) for p in path.split(os.pathsep) ] for path in paths: fn = os.path.join(path, exe) for s in suffixes: f_ext = fn+s if not os.path.islink(f_ext): f_ext = realpath(f_ext) if os.path.isfile(f_ext) and os.access(f_ext, os.X_OK): log.info('Found executable %s' % f_ext) _cache[key] = f_ext return f_ext log.warn('Could not locate executable %s' % orig_exe) return None ############################################################ def _preserve_environment( names ): log.debug('_preserve_environment(%r)' % (names)) env = {} for name in names: env[name] = os.environ.get(name) return env def _update_environment( **env ): log.debug('_update_environment(...)') for name, value in env.items(): os.environ[name] = value or '' def _supports_fileno(stream): """ Returns True if 'stream' supports the file descriptor and allows fileno(). """ if hasattr(stream, 'fileno'): try: r = stream.fileno() return True except IOError: return False else: return False def exec_command(command, execute_in='', use_shell=None, use_tee=None, _with_python = 1, **env ): """ Return (status,output) of executed command. Parameters ---------- command : str A concatenated string of executable and arguments. execute_in : str Before running command ``cd execute_in`` and after ``cd -``. use_shell : {bool, None}, optional If True, execute ``sh -c command``. Default None (True) use_tee : {bool, None}, optional If True use tee. Default None (True) Returns ------- res : str Both stdout and stderr messages. Notes ----- On NT, DOS systems the returned status is correct for external commands. Wild cards will not work for non-posix systems or when use_shell=0. """ log.debug('exec_command(%r,%s)' % (command,\ ','.join(['%s=%r'%kv for kv in env.items()]))) if use_tee is None: use_tee = os.name=='posix' if use_shell is None: use_shell = os.name=='posix' execute_in = os.path.abspath(execute_in) oldcwd = os.path.abspath(os.getcwd()) if __name__[-12:] == 'exec_command': exec_dir = os.path.dirname(os.path.abspath(__file__)) elif os.path.isfile('exec_command.py'): exec_dir = os.path.abspath('.') else: exec_dir = os.path.abspath(sys.argv[0]) if os.path.isfile(exec_dir): exec_dir = os.path.dirname(exec_dir) if oldcwd!=execute_in: os.chdir(execute_in) log.debug('New cwd: %s' % execute_in) else: log.debug('Retaining cwd: %s' % oldcwd) oldenv = _preserve_environment( list(env.keys()) ) _update_environment( **env ) try: # _exec_command is robust but slow, it relies on # usable sys.std*.fileno() descriptors. If they # are bad (like in win32 Idle, PyCrust environments) # then _exec_command_python (even slower) # will be used as a last resort. # # _exec_command_posix uses os.system and is faster # but not on all platforms os.system will return # a correct status. if (_with_python and _supports_fileno(sys.stdout) and sys.stdout.fileno() == -1): st = _exec_command_python(command, exec_command_dir = exec_dir, **env) elif os.name=='posix': st = _exec_command_posix(command, use_shell=use_shell, use_tee=use_tee, **env) else: st = _exec_command(command, use_shell=use_shell, use_tee=use_tee,**env) finally: if oldcwd!=execute_in: os.chdir(oldcwd) log.debug('Restored cwd to %s' % oldcwd) _update_environment(**oldenv) return st def _exec_command_posix( command, use_shell = None, use_tee = None, **env ): log.debug('_exec_command_posix(...)') if is_sequence(command): command_str = ' '.join(list(command)) else: command_str = command tmpfile = temp_file_name() stsfile = None if use_tee: stsfile = temp_file_name() filter = '' if use_tee == 2: filter = r'| tr -cd "\n" | tr "\n" "."; echo' command_posix = '( %s ; echo $? > %s ) 2>&1 | tee %s %s'\ % (command_str, stsfile, tmpfile, filter) else: stsfile = temp_file_name() command_posix = '( %s ; echo $? > %s ) > %s 2>&1'\ % (command_str, stsfile, tmpfile) #command_posix = '( %s ) > %s 2>&1' % (command_str,tmpfile) log.debug('Running os.system(%r)' % (command_posix)) status = os.system(command_posix) if use_tee: if status: # if command_tee fails then fall back to robust exec_command log.warn('_exec_command_posix failed (status=%s)' % status) return _exec_command(command, use_shell=use_shell, **env) if stsfile is not None: f = open_latin1(stsfile, 'r') status_text = f.read() status = int(status_text) f.close() os.remove(stsfile) f = open_latin1(tmpfile, 'r') text = f.read() f.close() os.remove(tmpfile) if text[-1:]=='\n': text = text[:-1] return status, text def _exec_command_python(command, exec_command_dir='', **env): log.debug('_exec_command_python(...)') python_exe = get_pythonexe() cmdfile = temp_file_name() stsfile = temp_file_name() outfile = temp_file_name() f = open(cmdfile, 'w') f.write('import os\n') f.write('import sys\n') f.write('sys.path.insert(0,%r)\n' % (exec_command_dir)) f.write('from exec_command import exec_command\n') f.write('del sys.path[0]\n') f.write('cmd = %r\n' % command) f.write('os.environ = %r\n' % (os.environ)) f.write('s,o = exec_command(cmd, _with_python=0, **%r)\n' % (env)) f.write('f=open(%r,"w")\nf.write(str(s))\nf.close()\n' % (stsfile)) f.write('f=open(%r,"w")\nf.write(o)\nf.close()\n' % (outfile)) f.close() cmd = '%s %s' % (python_exe, cmdfile) status = os.system(cmd) if status: raise RuntimeError("%r failed" % (cmd,)) os.remove(cmdfile) f = open_latin1(stsfile, 'r') status = int(f.read()) f.close() os.remove(stsfile) f = open_latin1(outfile, 'r') text = f.read() f.close() os.remove(outfile) return status, text def quote_arg(arg): if arg[0]!='"' and ' ' in arg: return '"%s"' % arg return arg def _exec_command( command, use_shell=None, use_tee = None, **env ): log.debug('_exec_command(...)') if use_shell is None: use_shell = os.name=='posix' if use_tee is None: use_tee = os.name=='posix' using_command = 0 if use_shell: # We use shell (unless use_shell==0) so that wildcards can be # used. sh = os.environ.get('SHELL', '/bin/sh') if is_sequence(command): argv = [sh, '-c', ' '.join(list(command))] else: argv = [sh, '-c', command] else: # On NT, DOS we avoid using command.com as it's exit status is # not related to the exit status of a command. if is_sequence(command): argv = command[:] else: argv = shlex.split(command) if hasattr(os, 'spawnvpe'): spawn_command = os.spawnvpe else: spawn_command = os.spawnve argv[0] = find_executable(argv[0]) or argv[0] if not os.path.isfile(argv[0]): log.warn('Executable %s does not exist' % (argv[0])) if os.name in ['nt', 'dos']: # argv[0] might be internal command argv = [os.environ['COMSPEC'], '/C'] + argv using_command = 1 _so_has_fileno = _supports_fileno(sys.stdout) _se_has_fileno = _supports_fileno(sys.stderr) so_flush = sys.stdout.flush se_flush = sys.stderr.flush if _so_has_fileno: so_fileno = sys.stdout.fileno() so_dup = os.dup(so_fileno) if _se_has_fileno: se_fileno = sys.stderr.fileno() se_dup = os.dup(se_fileno) outfile = temp_file_name() fout = open(outfile, 'w') if using_command: errfile = temp_file_name() ferr = open(errfile, 'w') log.debug('Running %s(%s,%r,%r,os.environ)' \ % (spawn_command.__name__, os.P_WAIT, argv[0], argv)) if sys.version_info[0] >= 3 and os.name == 'nt': # Pre-encode os.environ, discarding un-encodable entries, # to avoid it failing during encoding as part of spawn. Failure # is possible if the environment contains entries that are not # encoded using the system codepage as windows expects. # # This is not necessary on unix, where os.environ is encoded # using the surrogateescape error handler and decoded using # it as part of spawn. encoded_environ = {} for k, v in os.environ.items(): try: encoded_environ[k.encode(sys.getfilesystemencoding())] = v.encode( sys.getfilesystemencoding()) except UnicodeEncodeError: log.debug("ignoring un-encodable env entry %s", k) else: encoded_environ = os.environ argv0 = argv[0] if not using_command: argv[0] = quote_arg(argv0) so_flush() se_flush() if _so_has_fileno: os.dup2(fout.fileno(), so_fileno) if _se_has_fileno: if using_command: #XXX: disabled for now as it does not work from cmd under win32. # Tests fail on msys os.dup2(ferr.fileno(), se_fileno) else: os.dup2(fout.fileno(), se_fileno) try: status = spawn_command(os.P_WAIT, argv0, argv, encoded_environ) except Exception: errmess = str(get_exception()) status = 999 sys.stderr.write('%s: %s'%(errmess, argv[0])) so_flush() se_flush() if _so_has_fileno: os.dup2(so_dup, so_fileno) os.close(so_dup) if _se_has_fileno: os.dup2(se_dup, se_fileno) os.close(se_dup) fout.close() fout = open_latin1(outfile, 'r') text = fout.read() fout.close() os.remove(outfile) if using_command: ferr.close() ferr = open_latin1(errfile, 'r') errmess = ferr.read() ferr.close() os.remove(errfile) if errmess and not status: # Not sure how to handle the case where errmess # contains only warning messages and that should # not be treated as errors. #status = 998 if text: text = text + '\n' #text = '%sCOMMAND %r FAILED: %s' %(text,command,errmess) text = text + errmess print (errmess) if text[-1:]=='\n': text = text[:-1] if status is None: status = 0 if use_tee: print (text) return status, text def test_nt(**kws): pythonexe = get_pythonexe() echo = find_executable('echo') using_cygwin_echo = echo != 'echo' if using_cygwin_echo: log.warn('Using cygwin echo in win32 environment is not supported') s, o=exec_command(pythonexe\ +' -c "import os;print os.environ.get(\'AAA\',\'\')"') assert s==0 and o=='', (s, o) s, o=exec_command(pythonexe\ +' -c "import os;print os.environ.get(\'AAA\')"', AAA='Tere') assert s==0 and o=='Tere', (s, o) os.environ['BBB'] = 'Hi' s, o=exec_command(pythonexe\ +' -c "import os;print os.environ.get(\'BBB\',\'\')"') assert s==0 and o=='Hi', (s, o) s, o=exec_command(pythonexe\ +' -c "import os;print os.environ.get(\'BBB\',\'\')"', BBB='Hey') assert s==0 and o=='Hey', (s, o) s, o=exec_command(pythonexe\ +' -c "import os;print os.environ.get(\'BBB\',\'\')"') assert s==0 and o=='Hi', (s, o) elif 0: s, o=exec_command('echo Hello') assert s==0 and o=='Hello', (s, o) s, o=exec_command('echo a%AAA%') assert s==0 and o=='a', (s, o) s, o=exec_command('echo a%AAA%', AAA='Tere') assert s==0 and o=='aTere', (s, o) os.environ['BBB'] = 'Hi' s, o=exec_command('echo a%BBB%') assert s==0 and o=='aHi', (s, o) s, o=exec_command('echo a%BBB%', BBB='Hey') assert s==0 and o=='aHey', (s, o) s, o=exec_command('echo a%BBB%') assert s==0 and o=='aHi', (s, o) s, o=exec_command('this_is_not_a_command') assert s and o!='', (s, o) s, o=exec_command('type not_existing_file') assert s and o!='', (s, o) s, o=exec_command('echo path=%path%') assert s==0 and o!='', (s, o) s, o=exec_command('%s -c "import sys;sys.stderr.write(sys.platform)"' \ % pythonexe) assert s==0 and o=='win32', (s, o) s, o=exec_command('%s -c "raise \'Ignore me.\'"' % pythonexe) assert s==1 and o, (s, o) s, o=exec_command('%s -c "import sys;sys.stderr.write(\'0\');sys.stderr.write(\'1\');sys.stderr.write(\'2\')"'\ % pythonexe) assert s==0 and o=='012', (s, o) s, o=exec_command('%s -c "import sys;sys.exit(15)"' % pythonexe) assert s==15 and o=='', (s, o) s, o=exec_command('%s -c "print \'Heipa\'"' % pythonexe) assert s==0 and o=='Heipa', (s, o) print ('ok') def test_posix(**kws): s, o=exec_command("echo Hello",**kws) assert s==0 and o=='Hello', (s, o) s, o=exec_command('echo $AAA',**kws) assert s==0 and o=='', (s, o) s, o=exec_command('echo "$AAA"',AAA='Tere',**kws) assert s==0 and o=='Tere', (s, o) s, o=exec_command('echo "$AAA"',**kws) assert s==0 and o=='', (s, o) os.environ['BBB'] = 'Hi' s, o=exec_command('echo "$BBB"',**kws) assert s==0 and o=='Hi', (s, o) s, o=exec_command('echo "$BBB"',BBB='Hey',**kws) assert s==0 and o=='Hey', (s, o) s, o=exec_command('echo "$BBB"',**kws) assert s==0 and o=='Hi', (s, o) s, o=exec_command('this_is_not_a_command',**kws) assert s!=0 and o!='', (s, o) s, o=exec_command('echo path=$PATH',**kws) assert s==0 and o!='', (s, o) s, o=exec_command('python -c "import sys,os;sys.stderr.write(os.name)"',**kws) assert s==0 and o=='posix', (s, o) s, o=exec_command('python -c "raise \'Ignore me.\'"',**kws) assert s==1 and o, (s, o) s, o=exec_command('python -c "import sys;sys.stderr.write(\'0\');sys.stderr.write(\'1\');sys.stderr.write(\'2\')"',**kws) assert s==0 and o=='012', (s, o) s, o=exec_command('python -c "import sys;sys.exit(15)"',**kws) assert s==15 and o=='', (s, o) s, o=exec_command('python -c "print \'Heipa\'"',**kws) assert s==0 and o=='Heipa', (s, o) print ('ok') def test_execute_in(**kws): pythonexe = get_pythonexe() tmpfile = temp_file_name() fn = os.path.basename(tmpfile) tmpdir = os.path.dirname(tmpfile) f = open(tmpfile, 'w') f.write('Hello') f.close() s, o = exec_command('%s -c "print \'Ignore the following IOError:\','\ 'open(%r,\'r\')"' % (pythonexe, fn),**kws) assert s and o!='', (s, o) s, o = exec_command('%s -c "print open(%r,\'r\').read()"' % (pythonexe, fn), execute_in = tmpdir,**kws) assert s==0 and o=='Hello', (s, o) os.remove(tmpfile) print ('ok') def test_svn(**kws): s, o = exec_command(['svn', 'status'],**kws) assert s, (s, o) print ('svn ok') def test_cl(**kws): if os.name=='nt': s, o = exec_command(['cl', '/V'],**kws) assert s, (s, o) print ('cl ok') if os.name=='posix': test = test_posix elif os.name in ['nt', 'dos']: test = test_nt else: raise NotImplementedError('exec_command tests for ', os.name) ############################################################ if __name__ == "__main__": test(use_tee=0) test(use_tee=1) test_execute_in(use_tee=0) test_execute_in(use_tee=1) test_svn(use_tee=1) test_cl(use_tee=1)
LumPenPacK/NetworkExtractionFromImages
win_build/nefi2_win_amd64_msvc_2015/site-packages/numpy/distutils/exec_command.py
Python
bsd-2-clause
20,462
<?php namespace Drupal\file\Plugin\Field\FieldFormatter; /** * Defines getter methods for FileMediaFormatterBase. * * This interface is used on the FileMediaFormatterBase class to ensure that * each file media formatter will be based on a media type. * * Abstract classes are not able to implement abstract static methods, * this interface will work around that. * * @see \Drupal\file\Plugin\Field\FieldFormatter\FileMediaFormatterBase */ interface FileMediaFormatterInterface { /** * Gets the applicable media type for a formatter. * * @return string * The media type of this formatter. */ public static function getMediaType(); }
tobiasbuhrer/tobiasb
web/core/modules/file/src/Plugin/Field/FieldFormatter/FileMediaFormatterInterface.php
PHP
gpl-2.0
667
#include <gtest/gtest.h> #include "codec_def.h" #include "codec_api.h" #include "utils/BufferedData.h" #include "utils/FileInputStream.h" #include "BaseEncoderTest.h" class EncInterfaceCallTest : public ::testing::Test, public BaseEncoderTest { public: virtual void SetUp() { BaseEncoderTest::SetUp(); }; virtual void TearDown() { BaseEncoderTest::TearDown(); }; virtual void onEncodeFrame (const SFrameBSInfo& frameInfo) { //nothing } //testing case }; TEST_F (EncInterfaceCallTest, BaseParameterVerify) { int uiTraceLevel = WELS_LOG_QUIET; encoder_->SetOption (ENCODER_OPTION_TRACE_LEVEL, &uiTraceLevel); int ret = cmResultSuccess; SEncParamBase baseparam; memset (&baseparam, 0, sizeof (SEncParamBase)); baseparam.iPicWidth = 0; baseparam.iPicHeight = 7896; ret = encoder_->Initialize (&baseparam); EXPECT_EQ (ret, static_cast<int> (cmInitParaError)); uiTraceLevel = WELS_LOG_ERROR; encoder_->SetOption (ENCODER_OPTION_TRACE_LEVEL, &uiTraceLevel); } void outputData() { } TEST_F (EncInterfaceCallTest, SetOptionLTR) { int iTotalFrameNum = 100; int iFrameNum = 0; int frameSize = 0; int ret = cmResultSuccess; int width = 320; int height = 192; SEncParamBase baseparam; memset (&baseparam, 0, sizeof (SEncParamBase)); baseparam.iUsageType = CAMERA_VIDEO_REAL_TIME; baseparam.fMaxFrameRate = 12; baseparam.iPicWidth = width; baseparam.iPicHeight = height; baseparam.iTargetBitrate = 5000000; encoder_->Initialize (&baseparam); frameSize = width * height * 3 / 2; BufferedData buf; buf.SetLength (frameSize); ASSERT_TRUE (buf.Length() == (size_t)frameSize); SFrameBSInfo info; memset (&info, 0, sizeof (SFrameBSInfo)); SSourcePicture pic; memset (&pic, 0, sizeof (SSourcePicture)); pic.iPicWidth = width; pic.iPicHeight = height; pic.iColorFormat = videoFormatI420; pic.iStride[0] = pic.iPicWidth; pic.iStride[1] = pic.iStride[2] = pic.iPicWidth >> 1; pic.pData[0] = buf.data(); pic.pData[1] = pic.pData[0] + width * height; pic.pData[2] = pic.pData[1] + (width * height >> 2); SLTRConfig config; config.bEnableLongTermReference = true; config.iLTRRefNum = rand() % 4; encoder_->SetOption (ENCODER_OPTION_LTR, &config); do { FileInputStream fileStream; ASSERT_TRUE (fileStream.Open ("res/CiscoVT2people_320x192_12fps.yuv")); while (fileStream.read (buf.data(), frameSize) == frameSize) { ret = encoder_->EncodeFrame (&pic, &info); ASSERT_TRUE (ret == cmResultSuccess); if (info.eFrameType != videoFrameTypeSkip) { this->onEncodeFrame (info); iFrameNum++; } } } while (iFrameNum < iTotalFrameNum); }
AnyRTC/AnyRTC-RTMP
third_party/openh264/src/test/encoder/EncUT_InterfaceTest.cpp
C++
gpl-3.0
2,699